Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ cover/
local_settings.py
db.sqlite3
db.sqlite3-journal
*.db
*.db-shm
*.db-wal
*.db.bak.*
Expand Down
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ This project uses famous football coaches as release codenames, following an A-Z

### Added

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

### Changed

- `databases/player_database.py`: engine URL now reads `DATABASE_URL`
environment variable (SQLite default, PostgreSQL compatible); `connect_args`
made conditional on SQLite dialect (#2)
- `main.py`: lifespan handler now applies Alembic migrations on startup via
thread executor (#2)
- `Dockerfile`: removed `COPY storage/ ./hold/` and its associated comment;
added `COPY alembic.ini` and `COPY alembic/` (#2)
- `scripts/entrypoint.sh`: removed hold→volume copy and seed script logic,
now replaced by Alembic migrations applied at app startup (#2)
- `compose.yaml`: replaced `STORAGE_PATH` with `DATABASE_URL` pointing to the
SQLite volume path (#2)
- `.gitignore`: added `*.db`; `storage/players-sqlite3.db` removed from git
tracking; `storage/` directory deleted (#2)
- `tests/player_stub.py` renamed to `tests/player_fake.py`; class docstring
updated to reflect fake (not stub) role; module-level docstring added
documenting the three-term data-state vocabulary (`existing`, `nonexistent`,
Expand Down
6 changes: 2 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ RUN pip install --no-cache-dir --no-index --find-links /app/wheelhouse /app/whee

# Copy application source code
COPY main.py ./
COPY alembic.ini ./
COPY alembic/ ./alembic/
COPY databases/ ./databases/
COPY models/ ./models/
COPY routes/ ./routes/
Expand All @@ -61,10 +63,6 @@ COPY tools/ ./tools/
# Copy entrypoint and healthcheck scripts
COPY --chmod=755 scripts/entrypoint.sh ./entrypoint.sh
COPY --chmod=755 scripts/healthcheck.sh ./healthcheck.sh
# The 'hold' is our storage compartment within the image. Here, we copy a
# pre-seeded SQLite database file, which Compose will mount as a persistent
# 'storage' volume when the container starts up.
COPY --chmod=755 storage/ ./hold/

# Add non-root user and make volume mount point writable
# Avoids running the container as root (see: https://rules.sonarsource.com/docker/RSPEC-6504/)
Expand Down
112 changes: 112 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed via pip install.[tz]
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses
# os.pathsep. Note that this character also holds a place in the string formatting,
# so if you use a character that is a % placeholder, you need to escape it (%%):
# version_path_separator = :
# version_path_separator = ;
version_path_separator = os
path_separator = os

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

# sqlalchemy.url is set dynamically in env.py from the DATABASE_URL environment
# variable, so this placeholder is intentionally left empty.
sqlalchemy.url =


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
1 change: 1 addition & 0 deletions alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration with an async SQLAlchemy backend.
81 changes: 81 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""
Alembic environment configuration for async SQLAlchemy.

Reads DATABASE_URL from the environment to support both SQLite (local dev/test)
and PostgreSQL (Docker/production). Uses render_as_batch=True for SQLite ALTER
TABLE compatibility (harmless on PostgreSQL).
"""

import asyncio
import os
from logging.config import fileConfig

from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config

from alembic import context

from databases.player_database import Base
from schemas.player_schema import Player # noqa: F401 — registers ORM model with Base

Check notice on line 20 in alembic/env.py

View check run for this annotation

codefactor.io / CodeFactor

alembic/env.py#L20

Unused Player imported from schemas.player_schema (unused-import)

# Supports both SQLite (local) and PostgreSQL (Docker, see #542):
# sqlite+aiosqlite:///./storage/players-sqlite3.db
# postgresql+asyncpg://postgres:password@postgres:5432/playersdb
_storage_path = os.getenv("STORAGE_PATH", "./players-sqlite3.db")
_default_url = f"sqlite+aiosqlite:///{_storage_path}"

Check notice on line 26 in alembic/env.py

View check run for this annotation

codefactor.io / CodeFactor

alembic/env.py#L26

Constant name "_default_url" doesn't conform to UPPER_CASE naming style (invalid-name)
database_url = os.getenv("DATABASE_URL", _default_url)

config = context.config
config.set_main_option("sqlalchemy.url", database_url)

if config.config_file_name is not None:
fileConfig(config.config_file_name)

target_metadata = Base.metadata


def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode (no DB connection, generates SQL)."""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
render_as_batch=True,
)
with context.begin_transaction():
context.run_migrations()


def do_run_migrations(connection: Connection) -> None:

Check notice on line 52 in alembic/env.py

View check run for this annotation

codefactor.io / CodeFactor

alembic/env.py#L52

Missing function or method docstring (missing-function-docstring)
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=True,
)
with context.begin_transaction():
context.run_migrations()


async def run_async_migrations() -> None:

Check notice on line 62 in alembic/env.py

View check run for this annotation

codefactor.io / CodeFactor

alembic/env.py#L62

Missing function or method docstring (missing-function-docstring)
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()


def run_migrations_online() -> None:
"""Run migrations in 'online' mode (against a live DB connection)."""
asyncio.run(run_async_migrations())


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
26 changes: 26 additions & 0 deletions alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}


def upgrade() -> None:
${upgrades if upgrades else "pass"}


def downgrade() -> None:
${downgrades if downgrades else "pass"}
40 changes: 40 additions & 0 deletions alembic/versions/001_create_players_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Create players table

Check notice on line 1 in alembic/versions/001_create_players_table.py

View check run for this annotation

codefactor.io / CodeFactor

alembic/versions/001_create_players_table.py#L1

Module name "001_create_players_table" doesn't conform to snake_case naming style (invalid-name)

Revision ID: 001
Revises:
Create Date: 2026-04-09

"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "001"
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:

Check notice on line 20 in alembic/versions/001_create_players_table.py

View check run for this annotation

codefactor.io / CodeFactor

alembic/versions/001_create_players_table.py#L20

Missing function or method docstring (missing-function-docstring)
op.create_table(
"players",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("firstName", sa.String(), nullable=False),
sa.Column("middleName", sa.String(), nullable=True),
sa.Column("lastName", sa.String(), nullable=False),
sa.Column("dateOfBirth", sa.String(), nullable=True),
sa.Column("squadNumber", sa.Integer(), nullable=False),
sa.Column("position", sa.String(), nullable=False),
sa.Column("abbrPosition", sa.String(), nullable=True),
sa.Column("team", sa.String(), nullable=True),
sa.Column("league", sa.String(), nullable=True),
sa.Column("starting11", sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("squadNumber"),
)


def downgrade() -> None:

Check notice on line 39 in alembic/versions/001_create_players_table.py

View check run for this annotation

codefactor.io / CodeFactor

alembic/versions/001_create_players_table.py#L39

Missing function or method docstring (missing-function-docstring)
op.drop_table("players")
Loading
Loading