60 lines
1.7 KiB
Python
60 lines
1.7 KiB
Python
"""Alembic environment — uses sync psycopg2 driver for migrations."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from logging.config import fileConfig
|
|
|
|
from alembic import context
|
|
from sqlalchemy import create_engine
|
|
|
|
# this is the Alembic Config object
|
|
config = context.config
|
|
|
|
# Interpret the config file for Python logging.
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
# Read DATABASE_URL from environment (preferred) or alembic.ini
|
|
database_url = os.environ.get("DATABASE_URL") or config.get_main_option("sqlalchemy.url")
|
|
if not database_url:
|
|
raise RuntimeError(
|
|
"mals/alembic: DATABASE_URL is required. "
|
|
"Set it as an environment variable or in alembic.ini."
|
|
)
|
|
|
|
# Convert asyncpg URL to psycopg2 (sync) for Alembic
|
|
sync_url = (
|
|
database_url.replace("postgresql+asyncpg://", "postgresql://")
|
|
.replace("asyncpg://", "postgresql://")
|
|
)
|
|
|
|
target_metadata = None
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
"""Run migrations in 'offline' mode (generate SQL only)."""
|
|
context.configure(
|
|
url=sync_url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
"""Run migrations against a live database."""
|
|
connectable = create_engine(sync_url)
|
|
with connectable.connect() as connection:
|
|
context.configure(connection=connection, target_metadata=target_metadata)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|