Files
activity-core/migrations/env.py
Bernd Worsch f55f497107 feat(db): init Alembic (async) + SQLAlchemy declarative base — T08
- alembic init -t async migrations
- alembic.ini: dev fallback URL postgresql+asyncpg://…:5433/actcore;
  ACTCORE_DB_URL env var overrides at runtime; src/ added to sys.path
- migrations/env.py: reads ACTCORE_DB_URL, wires target_metadata to Base.metadata
- src/activity_core/db.py: DeclarativeBase subclass + make_engine() helper

Tool choice: Alembic + SQLAlchemy[asyncio] (already declared in pyproject.toml).
Migrations run with: ACTCORE_DB_URL=... alembic upgrade head

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 21:45:40 +00:00

67 lines
1.8 KiB
Python

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 activity_core.db import Base # noqa: F401 — imports all ORM models via submodules
# Alembic Config object — access to values in alembic.ini
config = context.config
# Set up loggers from alembic.ini
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# ORM metadata for autogenerate
target_metadata = Base.metadata
# Override the DB URL from env var when running live migrations
_db_url = os.environ.get("ACTCORE_DB_URL")
if _db_url:
config.set_main_option("sqlalchemy.url", _db_url)
def run_migrations_offline() -> None:
"""Generate SQL without a live DB connection (alembic upgrade --sql)."""
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: Connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> 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()
def run_migrations_online() -> None:
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()