59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
"""Alembic environment — runs raw SQL migrations against SQLite or Postgres.
|
|
|
|
No SQLAlchemy ORM is used. Migrations are plain SQL scripts so the migration
|
|
layer stays independent of any Python model objects.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from logging.config import fileConfig
|
|
from typing import Any
|
|
|
|
from alembic import context
|
|
|
|
# Load the alembic.ini logging config without disabling existing loggers —
|
|
# when running inside the FastAPI app the app's own loggers must not be reset.
|
|
if context.config.config_file_name is not None:
|
|
fileConfig(context.config.config_file_name, disable_existing_loggers=False)
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
"""Emit SQL to stdout (used by `alembic upgrade --sql`)."""
|
|
url = context.config.get_main_option("sqlalchemy.url")
|
|
context.configure(
|
|
url=url,
|
|
target_metadata=None,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def do_run_migrations(connection: Any) -> None:
|
|
context.configure(connection=connection, target_metadata=None)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def run_migrations_online() -> None:
|
|
"""Run migrations against a live DB connection."""
|
|
from sqlalchemy.ext.asyncio import create_async_engine
|
|
|
|
url = context.config.get_main_option("sqlalchemy.url")
|
|
# Coerce sqlite:// → sqlite+aiosqlite:// for async support.
|
|
if url and url.startswith("sqlite:///"):
|
|
url = url.replace("sqlite:///", "sqlite+aiosqlite:///", 1)
|
|
|
|
connectable = create_async_engine(url)
|
|
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())
|