Skip to content

Commit 3b645ab

Browse files
nanotaboadaclaude
andcommitted
feat(migrations): implement Alembic for database migrations (#2)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 9151eee commit 3b645ab

File tree

17 files changed

+654
-119
lines changed

17 files changed

+654
-119
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ cover/
6161
local_settings.py
6262
db.sqlite3
6363
db.sqlite3-journal
64+
*.db
6465
*.db-shm
6566
*.db-wal
6667
*.db.bak.*

CHANGELOG.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ This project uses famous football coaches as release codenames, following an A-Z
4444

4545
### Added
4646

47+
- `alembic/`: Alembic migration support for async SQLAlchemy — `env.py`
48+
configured for async execution with `render_as_batch=True` (SQLite/PostgreSQL
49+
compatible); three migrations: `001` creates the `players` table, `002` seeds
50+
11 Starting XI players, `003` seeds 15 Substitute players (all with
51+
deterministic UUID v5 values); `alembic upgrade head` runs automatically on
52+
app startup via the lifespan handler (#2)
53+
- `alembic==1.18.4`, `asyncpg==0.31.0` added to dependencies (#2)
4754
- `.sonarcloud.properties`: SonarCloud Automatic Analysis configuration —
4855
sources, tests, coverage exclusions aligned with `codecov.yml` (#554)
4956
- `.dockerignore`: added `.claude/`, `CLAUDE.md`, `.coderabbit.yaml`,
@@ -53,6 +60,19 @@ This project uses famous football coaches as release codenames, following an A-Z
5360

5461
### Changed
5562

63+
- `databases/player_database.py`: engine URL now reads `DATABASE_URL`
64+
environment variable (SQLite default, PostgreSQL compatible); `connect_args`
65+
made conditional on SQLite dialect (#2)
66+
- `main.py`: lifespan handler now applies Alembic migrations on startup via
67+
thread executor (#2)
68+
- `Dockerfile`: removed `COPY storage/ ./hold/` and its associated comment;
69+
added `COPY alembic.ini` and `COPY alembic/` (#2)
70+
- `scripts/entrypoint.sh`: removed hold→volume copy and seed script logic,
71+
now replaced by Alembic migrations applied at app startup (#2)
72+
- `compose.yaml`: replaced `STORAGE_PATH` with `DATABASE_URL` pointing to the
73+
SQLite volume path (#2)
74+
- `.gitignore`: added `*.db`; `storage/players-sqlite3.db` removed from git
75+
tracking; `storage/` directory deleted (#2)
5676
- `tests/player_stub.py` renamed to `tests/player_fake.py`; class docstring
5777
updated to reflect fake (not stub) role; module-level docstring added
5878
documenting the three-term data-state vocabulary (`existing`, `nonexistent`,

Dockerfile

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ RUN pip install --no-cache-dir --no-index --find-links /app/wheelhouse /app/whee
5151

5252
# Copy application source code
5353
COPY main.py ./
54+
COPY alembic.ini ./
55+
COPY alembic/ ./alembic/
5456
COPY databases/ ./databases/
5557
COPY models/ ./models/
5658
COPY routes/ ./routes/
@@ -61,10 +63,6 @@ COPY tools/ ./tools/
6163
# Copy entrypoint and healthcheck scripts
6264
COPY --chmod=755 scripts/entrypoint.sh ./entrypoint.sh
6365
COPY --chmod=755 scripts/healthcheck.sh ./healthcheck.sh
64-
# The 'hold' is our storage compartment within the image. Here, we copy a
65-
# pre-seeded SQLite database file, which Compose will mount as a persistent
66-
# 'storage' volume when the container starts up.
67-
COPY --chmod=755 storage/ ./hold/
6866

6967
# Add non-root user and make volume mount point writable
7068
# Avoids running the container as root (see: https://rules.sonarsource.com/docker/RSPEC-6504/)

alembic.ini

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
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 via pip install.[tz]
19+
# timezone =
20+
21+
# max length of characters to apply to the "slug" field
22+
# truncate_slug_length = 40
23+
24+
# set to 'true' to run the environment during
25+
# the 'revision' command, regardless of autogenerate
26+
# revision_environment = false
27+
28+
# set to 'true' to allow .pyc and .pyo files without
29+
# a source .py file to be detected as revisions in the
30+
# versions/ directory
31+
# sourceless = false
32+
33+
# version location specification; This defaults
34+
# to alembic/versions. When using multiple version
35+
# directories, initial revisions must be specified with --version-path.
36+
# The path separator used here should be the separator specified by "version_path_separator" below.
37+
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
38+
39+
# version path separator; As mentioned above, this is the character used to split
40+
# version_locations. The default within new alembic.ini files is "os", which uses
41+
# os.pathsep. Note that this character also holds a place in the string formatting,
42+
# so if you use a character that is a % placeholder, you need to escape it (%%):
43+
# version_path_separator = :
44+
# version_path_separator = ;
45+
version_path_separator = os
46+
path_separator = os
47+
48+
# set to 'true' to search source files recursively
49+
# in each "version_locations" directory
50+
# new in Alembic version 1.10
51+
# recursive_version_locations = false
52+
53+
# the output encoding used when revision files
54+
# are written from script.py.mako
55+
# output_encoding = utf-8
56+
57+
# sqlalchemy.url is set dynamically in env.py from the DATABASE_URL environment
58+
# variable, so this placeholder is intentionally left empty.
59+
sqlalchemy.url =
60+
61+
62+
[post_write_hooks]
63+
# post_write_hooks defines scripts or Python functions that are run
64+
# on newly generated revision scripts. See the documentation for further
65+
# detail and examples
66+
67+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
68+
# hooks = black
69+
# black.type = console_scripts
70+
# black.entrypoint = black
71+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
72+
73+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
74+
# hooks = ruff
75+
# ruff.type = exec
76+
# ruff.executable = %(here)s/.venv/bin/ruff
77+
# ruff.options = --fix REVISION_SCRIPT_FILENAME
78+
79+
# Logging configuration
80+
[loggers]
81+
keys = root,sqlalchemy,alembic
82+
83+
[handlers]
84+
keys = console
85+
86+
[formatters]
87+
keys = generic
88+
89+
[logger_root]
90+
level = WARN
91+
handlers = console
92+
qualname =
93+
94+
[logger_sqlalchemy]
95+
level = WARN
96+
handlers =
97+
qualname = sqlalchemy.engine
98+
99+
[logger_alembic]
100+
level = INFO
101+
handlers =
102+
qualname = alembic
103+
104+
[handler_console]
105+
class = StreamHandler
106+
args = (sys.stderr,)
107+
level = NOTSET
108+
formatter = generic
109+
110+
[formatter_generic]
111+
format = %(levelname)-5.5s [%(name)s] %(message)s
112+
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 SQLAlchemy backend.

alembic/env.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""
2+
Alembic environment configuration for async SQLAlchemy.
3+
4+
Reads DATABASE_URL from the environment to support both SQLite (local dev/test)
5+
and PostgreSQL (Docker/production). Uses render_as_batch=True for SQLite ALTER
6+
TABLE compatibility (harmless on PostgreSQL).
7+
"""
8+
9+
import asyncio
10+
import os
11+
from logging.config import fileConfig
12+
13+
from sqlalchemy import pool
14+
from sqlalchemy.engine import Connection
15+
from sqlalchemy.ext.asyncio import async_engine_from_config
16+
17+
from alembic import context
18+
19+
from databases.player_database import Base
20+
from schemas.player_schema import Player # noqa: F401 — registers ORM model with Base
21+
22+
# Supports both SQLite (local) and PostgreSQL (Docker, see #542):
23+
# sqlite+aiosqlite:///./storage/players-sqlite3.db
24+
# postgresql+asyncpg://postgres:password@postgres:5432/playersdb
25+
_storage_path = os.getenv("STORAGE_PATH", "./players-sqlite3.db")
26+
_default_url = f"sqlite+aiosqlite:///{_storage_path}"
27+
database_url = os.getenv("DATABASE_URL", _default_url)
28+
29+
config = context.config
30+
config.set_main_option("sqlalchemy.url", database_url)
31+
32+
if config.config_file_name is not None:
33+
fileConfig(config.config_file_name)
34+
35+
target_metadata = Base.metadata
36+
37+
38+
def run_migrations_offline() -> None:
39+
"""Run migrations in 'offline' mode (no DB connection, generates SQL)."""
40+
url = config.get_main_option("sqlalchemy.url")
41+
context.configure(
42+
url=url,
43+
target_metadata=target_metadata,
44+
literal_binds=True,
45+
dialect_opts={"paramstyle": "named"},
46+
render_as_batch=True,
47+
)
48+
with context.begin_transaction():
49+
context.run_migrations()
50+
51+
52+
def do_run_migrations(connection: Connection) -> None:
53+
context.configure(
54+
connection=connection,
55+
target_metadata=target_metadata,
56+
render_as_batch=True,
57+
)
58+
with context.begin_transaction():
59+
context.run_migrations()
60+
61+
62+
async def run_async_migrations() -> None:
63+
connectable = async_engine_from_config(
64+
config.get_section(config.config_ini_section, {}),
65+
prefix="sqlalchemy.",
66+
poolclass=pool.NullPool,
67+
)
68+
async with connectable.connect() as connection:
69+
await connection.run_sync(do_run_migrations)
70+
await connectable.dispose()
71+
72+
73+
def run_migrations_online() -> None:
74+
"""Run migrations in 'online' mode (against a live DB connection)."""
75+
asyncio.run(run_async_migrations())
76+
77+
78+
if context.is_offline_mode():
79+
run_migrations_offline()
80+
else:
81+
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, Sequence[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: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""Create players table
2+
3+
Revision ID: 001
4+
Revises:
5+
Create Date: 2026-04-09
6+
7+
"""
8+
9+
from typing import Sequence, Union
10+
11+
import sqlalchemy as sa
12+
from alembic import op
13+
14+
revision: str = "001"
15+
down_revision: Union[str, Sequence[str], None] = None
16+
branch_labels: Union[str, Sequence[str], None] = None
17+
depends_on: Union[str, Sequence[str], None] = None
18+
19+
20+
def upgrade() -> None:
21+
op.create_table(
22+
"players",
23+
sa.Column("id", sa.String(length=36), nullable=False),
24+
sa.Column("firstName", sa.String(), nullable=False),
25+
sa.Column("middleName", sa.String(), nullable=True),
26+
sa.Column("lastName", sa.String(), nullable=False),
27+
sa.Column("dateOfBirth", sa.String(), nullable=True),
28+
sa.Column("squadNumber", sa.Integer(), nullable=False),
29+
sa.Column("position", sa.String(), nullable=False),
30+
sa.Column("abbrPosition", sa.String(), nullable=True),
31+
sa.Column("team", sa.String(), nullable=True),
32+
sa.Column("league", sa.String(), nullable=True),
33+
sa.Column("starting11", sa.Boolean(), nullable=True),
34+
sa.PrimaryKeyConstraint("id"),
35+
sa.UniqueConstraint("squadNumber"),
36+
)
37+
38+
39+
def downgrade() -> None:
40+
op.drop_table("players")

0 commit comments

Comments
 (0)