Alembic Baseline

This commit is contained in:
Frank Agerholm 2025-12-11 16:54:45 +01:00
commit aaf5fd893d
8 changed files with 502 additions and 3 deletions

1
migrations/README Normal file
View file

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

104
migrations/env.py Normal file
View file

@ -0,0 +1,104 @@
# migrations/env.py
from __future__ import annotations
import asyncio
import os
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
# ----------------------------------------------------------------------
# Alembic Grund-Setup (Logging etc.)
# ----------------------------------------------------------------------
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# ----------------------------------------------------------------------
# Projekt-Root auf sys.path, damit "from app ..." klappt
# ----------------------------------------------------------------------
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
# ----------------------------------------------------------------------
# ORM-Base & Modelle importieren (wichtig: Modelle registrieren Tabellen)
# ----------------------------------------------------------------------
from app.db import Base
from app import models # noqa: F401
target_metadata = Base.metadata
# ----------------------------------------------------------------------
# Async-DB-URL (z. B. postgresql+asyncpg://...)
# ----------------------------------------------------------------------
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
raise RuntimeError(
"DATABASE_URL ist nicht gesetzt (z. B. postgresql+asyncpg://user:pass@host:5432/db)"
)
# ----------------------------------------------------------------------
# (Optional) Leere Autogenerate-Revisionen unterdrücken
# ----------------------------------------------------------------------
def process_revision_directives(context, revision, directives):
cmd_opts = getattr(config, "cmd_opts", None)
if cmd_opts and getattr(cmd_opts, "autogenerate", False):
script = directives[0]
if hasattr(script, "upgrade_ops") and script.upgrade_ops.is_empty():
directives[:] = [] # keine 'pass'-Revision erzeugen
# ----------------------------------------------------------------------
# Offline-Pfad (bewusst deaktiviert, damit Autogenerate immer online läuft)
# ----------------------------------------------------------------------
def run_migrations_offline() -> None:
raise RuntimeError("Offline-Modus deaktiviert bitte Online-Modus verwenden.")
# ----------------------------------------------------------------------
# Online-Pfad (AsyncEngine + run_sync)
# ----------------------------------------------------------------------
async def run_migrations_online() -> None:
connectable: AsyncEngine = create_async_engine(
DATABASE_URL,
poolclass=pool.NullPool,
future=True,
)
async with connectable.connect() as async_conn:
def do_run_migrations(connection: Connection) -> None:
# WICHTIG: connection + target_metadata -> nötige Voraussetzung
# damit Alembic den DB-Ist gegen ORM-Soll vergleicht (Autogenerate)
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
compare_server_default=True,
include_schemas=True,
process_revision_directives=process_revision_directives,
)
with context.begin_transaction():
context.run_migrations()
# run_sync ruft do_run_migrations(connection) auf
await async_conn.run_sync(do_run_migrations)
await connectable.dispose()
# ----------------------------------------------------------------------
# WICHTIG: beim Import starten KEIN __main__-Guard
# ----------------------------------------------------------------------
def run_migrations() -> None:
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())
run_migrations()

28
migrations/script.py.mako Normal file
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,81 @@
"""baseline
Revision ID: bb8e2c8e4b8f
Revises:
Create Date: 2025-12-11 16:51:50.423221
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'bb8e2c8e4b8f'
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:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('jobs',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('job_type', sa.String(length=64), nullable=False),
sa.Column('status', sa.Enum('PENDING', 'QUEUED', 'RUNNING', 'SUCCESS', 'FAILED', name='jobstatus'), nullable=False),
sa.Column('domain', sa.String(length=255), nullable=False),
sa.Column('payload', sa.JSON(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_jobs_domain'), 'jobs', ['domain'], unique=False)
op.create_index(op.f('ix_jobs_job_type'), 'jobs', ['job_type'], unique=False)
op.create_index(op.f('ix_jobs_status'), 'jobs', ['status'], unique=False)
op.create_table('tasks',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('job_id', sa.UUID(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=False),
sa.Column('status', sa.Enum('PENDING', 'QUEUED', 'RUNNING', 'SUCCESS', 'FAILED', name='taskstatus'), nullable=False),
sa.Column('routing_key', sa.String(length=128), nullable=False),
sa.Column('retries', sa.Integer(), nullable=False),
sa.Column('max_retries', sa.Integer(), nullable=False),
sa.Column('worker_id', sa.String(length=64), nullable=True),
sa.Column('result', sa.JSON(), nullable=True),
sa.Column('error', sa.String(length=1024), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('started_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('finished_at', sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(['job_id'], ['jobs.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_tasks_job_id'), 'tasks', ['job_id'], unique=False)
op.create_index(op.f('ix_tasks_name'), 'tasks', ['name'], unique=False)
op.create_index(op.f('ix_tasks_routing_key'), 'tasks', ['routing_key'], unique=False)
op.create_index(op.f('ix_tasks_status'), 'tasks', ['status'], unique=False)
op.create_table('task_dependencies',
sa.Column('task_id', sa.UUID(), nullable=False),
sa.Column('depends_on_task_id', sa.UUID(), nullable=False),
sa.ForeignKeyConstraint(['depends_on_task_id'], ['tasks.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['task_id'], ['tasks.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('task_id', 'depends_on_task_id')
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('task_dependencies')
op.drop_index(op.f('ix_tasks_status'), table_name='tasks')
op.drop_index(op.f('ix_tasks_routing_key'), table_name='tasks')
op.drop_index(op.f('ix_tasks_name'), table_name='tasks')
op.drop_index(op.f('ix_tasks_job_id'), table_name='tasks')
op.drop_table('tasks')
op.drop_index(op.f('ix_jobs_status'), table_name='jobs')
op.drop_index(op.f('ix_jobs_job_type'), table_name='jobs')
op.drop_index(op.f('ix_jobs_domain'), table_name='jobs')
op.drop_table('jobs')
# ### end Alembic commands ###