Skip to content

Commit cb926cc

Browse files
committed
Add Alembic
1 parent f0e6345 commit cb926cc

11 files changed

+754
-6
lines changed

Pipfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ sentry-sdk = {extras = ["fastapi"], version = "*"}
1414
uvicorn = {extras = ["standard"] }
1515
ruff = "*"
1616
ssort = "*"
17+
alembic = "*"
1718

1819
[requires]
1920
python_version = "3.12"

Pipfile.lock

Lines changed: 214 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

alembic.ini

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

alembic/env.py

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

0 commit comments

Comments
 (0)