Skip to content

Commit d1c9088

Browse files
committed
initial commit
1 parent b24ea16 commit d1c9088

28 files changed

+1571
-1
lines changed

README.Docker.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
### Building and running your application
2+
3+
When you're ready, start your application by running:
4+
`docker compose up --build`.
5+
6+
Your application will be available at http://localhost:8000.
7+
8+
### Deploying your application to the cloud
9+
10+
First, build your image, e.g.: `docker build -t myapp .`.
11+
If your cloud uses a different CPU architecture than your development
12+
machine (e.g., you are on a Mac M1 and your cloud provider is amd64),
13+
you'll want to build the image for that platform, e.g.:
14+
`docker build --platform=linux/amd64 -t myapp .`.
15+
16+
Then, push it to your registry, e.g. `docker push myregistry.com/myapp`.
17+
18+
Consult Docker's [getting started](https://docs.docker.com/go/get-started-sharing/)
19+
docs for more detail on building and pushing.
20+
21+
### References
22+
* [Docker's Python guide](https://docs.docker.com/language/python/)

README.md

Lines changed: 0 additions & 1 deletion
This file was deleted.

alembic.ini

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
script_location = alembic
6+
7+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
8+
# Uncomment the line below if you want the files to be prepended with date and time
9+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
10+
# for all available tokens
11+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
12+
13+
# sys.path path, will be prepended to sys.path if present.
14+
# defaults to the current working directory.
15+
prepend_sys_path = .
16+
17+
# timezone to use when rendering the date within the migration file
18+
# as well as the filename.
19+
# If specified, requires the python>=3.9 or backports.zoneinfo library.
20+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
21+
# string value is passed to ZoneInfo()
22+
# leave blank for localtime
23+
# timezone =
24+
25+
# max length of characters to apply to the
26+
# "slug" field
27+
# truncate_slug_length = 40
28+
29+
# set to 'true' to run the environment during
30+
# the 'revision' command, regardless of autogenerate
31+
# revision_environment = false
32+
33+
# set to 'true' to allow .pyc and .pyo files without
34+
# a source .py file to be detected as revisions in the
35+
# versions/ directory
36+
# sourceless = false
37+
38+
# version location specification; This defaults
39+
# to alembic/versions. When using multiple version
40+
# directories, initial revisions must be specified with --version-path.
41+
# The path separator used here should be the separator specified by "version_path_separator" below.
42+
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
43+
44+
# version path separator; As mentioned above, this is the character used to split
45+
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
46+
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
47+
# Valid values for version_path_separator are:
48+
#
49+
# version_path_separator = :
50+
# version_path_separator = ;
51+
# version_path_separator = space
52+
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
53+
54+
# set to 'true' to search source files recursively
55+
# in each "version_locations" directory
56+
# new in Alembic version 1.10
57+
# recursive_version_locations = false
58+
59+
# the output encoding used when revision files
60+
# are written from script.py.mako
61+
# output_encoding = utf-8
62+
63+
sqlalchemy.url = driver://user:pass@localhost/dbname
64+
65+
66+
[post_write_hooks]
67+
# post_write_hooks defines scripts or Python functions that are run
68+
# on newly generated revision scripts. See the documentation for further
69+
# detail and examples
70+
71+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
72+
# hooks = black
73+
# black.type = console_scripts
74+
# black.entrypoint = black
75+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
76+
77+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
78+
# hooks = ruff
79+
# ruff.type = exec
80+
# ruff.executable = %(here)s/.venv/bin/ruff
81+
# ruff.options = --fix REVISION_SCRIPT_FILENAME
82+
83+
# Logging configuration
84+
[loggers]
85+
keys = root,sqlalchemy,alembic
86+
87+
[handlers]
88+
keys = console
89+
90+
[formatters]
91+
keys = generic
92+
93+
[logger_root]
94+
level = WARN
95+
handlers = console
96+
qualname =
97+
98+
[logger_sqlalchemy]
99+
level = WARN
100+
handlers =
101+
qualname = sqlalchemy.engine
102+
103+
[logger_alembic]
104+
level = INFO
105+
handlers =
106+
qualname = alembic
107+
108+
[handler_console]
109+
class = StreamHandler
110+
args = (sys.stderr,)
111+
level = NOTSET
112+
formatter = generic
113+
114+
[formatter_generic]
115+
format = %(levelname)-5.5s [%(name)s] %(message)s
116+
datefmt = %H:%M:%S

alembic/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

alembic/env.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import os
2+
from logging.config import fileConfig
3+
4+
from sqlalchemy import engine_from_config
5+
from sqlalchemy import pool
6+
7+
from alembic import context
8+
from dotenv import load_dotenv
9+
from sqlmodel import SQLModel
10+
11+
load_dotenv()
12+
# this is the Alembic Config object, which provides
13+
# access to the values within the .ini file in use.
14+
config = context.config
15+
16+
config.set_main_option(
17+
"sqlalchemy.url", f"postgresql://{os.environ["DATABASE_USERNAME"]}:{os.environ["DATABASE_PASSWORD"]}@{os.environ["DATABASE_HOST"]}/{os.environ["DATABASE_NAME"]}?sslmode=require"
18+
)
19+
20+
# Interpret the config file for Python logging.
21+
# This line sets up loggers basically.
22+
if config.config_file_name is not None:
23+
fileConfig(config.config_file_name)
24+
25+
# add your model's MetaData object here
26+
# for 'autogenerate' support
27+
# from myapp import mymodel
28+
# target_metadata = mymodel.Base.metadata
29+
target_metadata = SQLModel.metadata
30+
31+
# other values from the config, defined by the needs of env.py,
32+
# can be acquired:
33+
# my_important_option = config.get_main_option("my_important_option")
34+
# ... etc.
35+
36+
37+
def run_migrations_offline() -> None:
38+
"""Run migrations in 'offline' mode.
39+
40+
This configures the context with just a URL
41+
and not an Engine, though an Engine is acceptable
42+
here as well. By skipping the Engine creation
43+
we don't even need a DBAPI to be available.
44+
45+
Calls to context.execute() here emit the given string to the
46+
script output.
47+
48+
"""
49+
url = config.get_main_option("sqlalchemy.url")
50+
context.configure(
51+
url=url,
52+
target_metadata=target_metadata,
53+
literal_binds=True,
54+
dialect_opts={"paramstyle": "named"},
55+
)
56+
57+
with context.begin_transaction():
58+
context.run_migrations()
59+
60+
61+
def run_migrations_online() -> None:
62+
"""Run migrations in 'online' mode.
63+
64+
In this scenario we need to create an Engine
65+
and associate a connection with the context.
66+
67+
"""
68+
connectable = engine_from_config(
69+
config.get_section(config.config_ini_section, {}),
70+
prefix="sqlalchemy.",
71+
poolclass=pool.NullPool,
72+
)
73+
74+
with connectable.connect() as connection:
75+
context.configure(connection=connection, target_metadata=target_metadata)
76+
77+
with context.begin_transaction():
78+
context.run_migrations()
79+
80+
81+
if context.is_offline_mode():
82+
run_migrations_offline()
83+
else:
84+
run_migrations_online()

alembic/script.py.mako

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
${imports if imports else ""}
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = ${repr(up_revision)}
16+
down_revision: Union[str, None] = ${repr(down_revision)}
17+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19+
20+
21+
def upgrade() -> None:
22+
${upgrades if upgrades else "pass"}
23+
24+
25+
def downgrade() -> None:
26+
${downgrades if downgrades else "pass"}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""Updating User Model
2+
3+
Revision ID: 3e19c60f5721
4+
Revises:
5+
Create Date: 2024-01-31 10:34:41.848972
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
from sqlalchemy.dialects import postgresql
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = '3e19c60f5721'
16+
down_revision: Union[str, None] = None
17+
branch_labels: Union[str, Sequence[str], None] = None
18+
depends_on: Union[str, Sequence[str], None] = None
19+
20+
21+
def upgrade() -> None:
22+
# ### commands auto generated by Alembic - please adjust! ###
23+
op.drop_index('ix_url_short_url', table_name='url')
24+
op.drop_index('ix_url_url', table_name='url')
25+
op.drop_table('url')
26+
op.drop_index('ix_user_username', table_name='user')
27+
op.drop_table('user')
28+
# ### end Alembic commands ###
29+
30+
31+
def downgrade() -> None:
32+
# ### commands auto generated by Alembic - please adjust! ###
33+
op.create_table('user',
34+
sa.Column('id', sa.INTEGER(), server_default=sa.text("nextval('user_id_seq'::regclass)"), autoincrement=True, nullable=False),
35+
sa.Column('username', sa.VARCHAR(), autoincrement=False, nullable=False),
36+
sa.Column('hash_password', sa.VARCHAR(), autoincrement=False, nullable=False),
37+
sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
38+
sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
39+
sa.Column('deleted_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
40+
sa.PrimaryKeyConstraint('id', name='user_pkey'),
41+
postgresql_ignore_search_path=False
42+
)
43+
op.create_index('ix_user_username', 'user', ['username'], unique=True)
44+
op.create_table('url',
45+
sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),
46+
sa.Column('url', sa.VARCHAR(), autoincrement=False, nullable=False),
47+
sa.Column('short_url', sa.VARCHAR(), autoincrement=False, nullable=False),
48+
sa.Column('clicks', sa.INTEGER(), autoincrement=False, nullable=True),
49+
sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
50+
sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
51+
sa.Column('expires_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
52+
sa.Column('deleted_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
53+
sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),
54+
sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='url_user_id_fkey'),
55+
sa.PrimaryKeyConstraint('id', name='url_pkey')
56+
)
57+
op.create_index('ix_url_url', 'url', ['url'], unique=False)
58+
op.create_index('ix_url_short_url', 'url', ['short_url'], unique=True)
59+
# ### end Alembic commands ###
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""drop hash_password from User
2+
3+
Revision ID: 5264addfa836
4+
Revises: 607751276d64
5+
Create Date: 2024-01-31 21:16:31.864903
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = "5264addfa836"
16+
down_revision: Union[str, None] = "607751276d64"
17+
branch_labels: Union[str, Sequence[str], None] = None
18+
depends_on: Union[str, Sequence[str], None] = None
19+
20+
21+
def upgrade():
22+
op.drop_column("user", "hash_password")
23+
24+
25+
def downgrade():
26+
op.add_column("user", sa.Column("hash_password", sa.String(), nullable=False))
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""update User table
2+
3+
Revision ID: 607751276d64
4+
Revises: 6cef3610b0e2
5+
Create Date: 2024-01-31 20:16:46.226831
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
from sqlalchemy.dialects import postgresql
13+
from sqlalchemy import ForeignKeyConstraint
14+
15+
# revision identifiers, used by Alembic.
16+
revision: str = "607751276d64"
17+
down_revision: Union[str, None] = "6cef3610b0e2"
18+
branch_labels: Union[str, Sequence[str], None] = None
19+
depends_on: Union[str, Sequence[str], None] = None
20+
21+
22+
def upgrade() -> None:
23+
with op.batch_alter_table("url") as batch_op:
24+
batch_op.drop_constraint("url_user_id_fkey", type_="foreignkey")
25+
batch_op.alter_column("user_id", existing_type=sa.Integer(), type_=sa.String())
26+
27+
with op.batch_alter_table("user") as batch_op:
28+
batch_op.alter_column("id", existing_type=sa.Integer(), type_=sa.String())
29+
30+
with op.batch_alter_table("url") as batch_op:
31+
batch_op.create_foreign_key("url_user_id_fkey", "user", ["user_id"], ["id"])
32+
33+
34+
def downgrade() -> None:
35+
with op.batch_alter_table("url") as batch_op:
36+
batch_op.drop_constraint("url_user_id_fkey", type_="foreignkey")
37+
batch_op.alter_column("user_id", existing_type=sa.String(), type_=sa.Integer())
38+
39+
with op.batch_alter_table("user") as batch_op:
40+
batch_op.alter_column("id", existing_type=sa.String(), type_=sa.Integer())
41+
42+
with op.batch_alter_table("url") as batch_op:
43+
batch_op.create_foreign_key("url_user_id_fkey", "user", ["user_id"], ["id"])

0 commit comments

Comments
 (0)