62 lines
1.6 KiB
Python
62 lines
1.6 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from logging.config import fileConfig
|
||
|
|
|
||
|
|
from alembic import context
|
||
|
|
from sqlalchemy import engine_from_config, pool
|
||
|
|
|
||
|
|
import app.models # noqa: F401
|
||
|
|
from app.config import Settings
|
||
|
|
from app.database import Base
|
||
|
|
|
||
|
|
config = context.config
|
||
|
|
|
||
|
|
if config.config_file_name is not None:
|
||
|
|
fileConfig(config.config_file_name)
|
||
|
|
|
||
|
|
# Always resolve runtime Settings() so DATABASE_URL env overrides take precedence
|
||
|
|
runtime_settings = Settings()
|
||
|
|
config.set_main_option("sqlalchemy.url", runtime_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"},
|
||
|
|
render_as_batch=url.startswith("sqlite") if url else False,
|
||
|
|
)
|
||
|
|
|
||
|
|
with context.begin_transaction():
|
||
|
|
context.run_migrations()
|
||
|
|
|
||
|
|
|
||
|
|
def run_migrations_online() -> None:
|
||
|
|
section = config.get_section(config.config_ini_section, {})
|
||
|
|
url = section.get("sqlalchemy.url", "")
|
||
|
|
connectable = engine_from_config(
|
||
|
|
section,
|
||
|
|
prefix="sqlalchemy.",
|
||
|
|
poolclass=pool.NullPool,
|
||
|
|
)
|
||
|
|
|
||
|
|
with connectable.connect() as connection:
|
||
|
|
context.configure(
|
||
|
|
connection=connection,
|
||
|
|
target_metadata=target_metadata,
|
||
|
|
render_as_batch=url.startswith("sqlite"),
|
||
|
|
)
|
||
|
|
|
||
|
|
with context.begin_transaction():
|
||
|
|
context.run_migrations()
|
||
|
|
|
||
|
|
|
||
|
|
if context.is_offline_mode():
|
||
|
|
run_migrations_offline()
|
||
|
|
else:
|
||
|
|
run_migrations_online()
|