Skip to content

Commit 1ce54fd

Browse files
committed
feat(backend): add alembic
1 parent 86c6d3e commit 1ce54fd

File tree

5 files changed

+235
-0
lines changed

5 files changed

+235
-0
lines changed

backend/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ uv.lock
22
sqlite.db
33
.venv
44
Pipfile.lock
5+
/app/migrations/versions/

backend/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+
# Use forward slashes (/) also on windows to provide an os agnostic path
6+
script_location = app/migrations
7+
8+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
9+
# Uncomment the line below if you want the files to be prepended with date and time
10+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
11+
# for all available tokens
12+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
13+
14+
# sys.path path, will be prepended to sys.path if present.
15+
# defaults to the current working directory.
16+
prepend_sys_path = .
17+
18+
# timezone to use when rendering the date within the migration file
19+
# as well as the filename.
20+
# If specified, requires the python>=3.9 or backports.zoneinfo library.
21+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
22+
# string value is passed to ZoneInfo()
23+
# leave blank for localtime
24+
# timezone =
25+
26+
# max length of characters to apply to the "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 migrations/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:migrations/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 = newline
53+
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
54+
55+
# set to 'true' to search source files recursively
56+
# in each "version_locations" directory
57+
# new in Alembic version 1.10
58+
# recursive_version_locations = false
59+
60+
# the output encoding used when revision files
61+
# are written from script.py.mako
62+
# output_encoding = utf-8
63+
64+
sqlalchemy.url = driver://user:pass@localhost/dbname
65+
66+
67+
[post_write_hooks]
68+
# post_write_hooks defines scripts or Python functions that are run
69+
# on newly generated revision scripts. See the documentation for further
70+
# detail and examples
71+
72+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
73+
# hooks = black
74+
# black.type = console_scripts
75+
# black.entrypoint = black
76+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
77+
78+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
79+
# hooks = ruff
80+
# ruff.type = exec
81+
# ruff.executable = %(here)s/.venv/bin/ruff
82+
# ruff.options = --fix 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 = WARNING
96+
handlers = console
97+
qualname =
98+
99+
[logger_sqlalchemy]
100+
level = WARNING
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

backend/app/migrations/README

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

backend/app/migrations/env.py

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

0 commit comments

Comments
 (0)