Add database schema with SQLAlchemy async + Alembic migrations

Set up PostgreSQL database layer with async SQLAlchemy 2.0 and asyncpg driver.
Implements 6 core tables (games, routes, pokemon, route_encounters, nuzlocke_runs,
encounters) with foreign keys, indexes, and an initial Alembic migration.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Julian Tabel
2026-02-05 13:29:34 +01:00
parent a87d2ef523
commit d94364d6ce
19 changed files with 649 additions and 19 deletions

View File

@@ -0,0 +1 @@
Generic single-database configuration.

View File

@@ -0,0 +1,61 @@
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
from app.core.config import settings
from app.core.database import Base, _get_async_url
# Import all models so Base.metadata is populated
import app.models # noqa: F401
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option("sqlalchemy.url", _get_async_url(settings.database_url))
target_metadata = Base.metadata
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection):
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
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()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())

View File

@@ -0,0 +1,28 @@
"""${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:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,155 @@
"""initial schema
Revision ID: 03e5f186a9d5
Revises:
Create Date: 2026-02-05 13:27:47.649534
"""
from typing import Sequence, Union
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "03e5f186a9d5"
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:
op.create_table(
"games",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("name", sa.String(100), nullable=False),
sa.Column("slug", sa.String(100), nullable=False, unique=True),
sa.Column("generation", sa.SmallInteger(), nullable=False),
sa.Column("region", sa.String(50), nullable=False),
sa.Column("box_art_url", sa.String(500), nullable=True),
sa.Column("release_year", sa.SmallInteger(), nullable=True),
)
op.create_table(
"routes",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("name", sa.String(100), nullable=False),
sa.Column(
"game_id", sa.Integer(), sa.ForeignKey("games.id"), nullable=False
),
sa.Column("order", sa.SmallInteger(), nullable=False),
)
op.create_index("ix_routes_game_id", "routes", ["game_id"])
op.create_table(
"pokemon",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"national_dex", sa.SmallInteger(), nullable=False, unique=True
),
sa.Column("name", sa.String(50), nullable=False),
sa.Column(
"types", postgresql.ARRAY(sa.String(20)), nullable=False
),
sa.Column("sprite_url", sa.String(500), nullable=True),
)
op.create_table(
"route_encounters",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"route_id", sa.Integer(), sa.ForeignKey("routes.id"), nullable=False
),
sa.Column(
"pokemon_id",
sa.Integer(),
sa.ForeignKey("pokemon.id"),
nullable=False,
),
sa.Column("encounter_method", sa.String(30), nullable=False),
sa.Column("encounter_rate", sa.SmallInteger(), nullable=False),
sa.UniqueConstraint(
"route_id",
"pokemon_id",
"encounter_method",
name="uq_route_pokemon_method",
),
)
op.create_index(
"ix_route_encounters_route_id", "route_encounters", ["route_id"]
)
op.create_index(
"ix_route_encounters_pokemon_id", "route_encounters", ["pokemon_id"]
)
op.create_table(
"nuzlocke_runs",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"game_id", sa.Integer(), sa.ForeignKey("games.id"), nullable=False
),
sa.Column("name", sa.String(100), nullable=False),
sa.Column("status", sa.String(20), nullable=False),
sa.Column(
"rules", postgresql.JSONB(), nullable=False, server_default="{}"
),
sa.Column(
"started_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.func.now(),
),
sa.Column(
"completed_at", sa.DateTime(timezone=True), nullable=True
),
)
op.create_index(
"ix_nuzlocke_runs_game_id", "nuzlocke_runs", ["game_id"]
)
op.create_index(
"ix_nuzlocke_runs_status", "nuzlocke_runs", ["status"]
)
op.create_table(
"encounters",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"run_id",
sa.Integer(),
sa.ForeignKey("nuzlocke_runs.id"),
nullable=False,
),
sa.Column(
"route_id", sa.Integer(), sa.ForeignKey("routes.id"), nullable=False
),
sa.Column(
"pokemon_id",
sa.Integer(),
sa.ForeignKey("pokemon.id"),
nullable=False,
),
sa.Column("nickname", sa.String(50), nullable=True),
sa.Column("status", sa.String(20), nullable=False),
sa.Column("catch_level", sa.SmallInteger(), nullable=True),
sa.Column("faint_level", sa.SmallInteger(), nullable=True),
sa.Column(
"caught_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.func.now(),
),
)
op.create_index("ix_encounters_run_id", "encounters", ["run_id"])
op.create_index("ix_encounters_route_id", "encounters", ["route_id"])
op.create_index("ix_encounters_pokemon_id", "encounters", ["pokemon_id"])
def downgrade() -> None:
op.drop_table("encounters")
op.drop_table("nuzlocke_runs")
op.drop_table("route_encounters")
op.drop_table("pokemon")
op.drop_table("routes")
op.drop_table("games")