77 lines
2.2 KiB
Python
77 lines
2.2 KiB
Python
|
|
"""Alembic environment.
|
||
|
|
|
||
|
|
We bypass `alembic.ini`'s `sqlalchemy.url` and pull the URL from the project's
|
||
|
|
Pydantic settings so a single .env governs both runtime and migrations.
|
||
|
|
|
||
|
|
Importing `app.models` registers every model on `Base.metadata`.
|
||
|
|
"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from logging.config import fileConfig
|
||
|
|
|
||
|
|
from alembic import context
|
||
|
|
from sqlalchemy import engine_from_config, pool
|
||
|
|
|
||
|
|
# noqa: F401 — registers models on Base.metadata
|
||
|
|
from app import models as _models # noqa: F401
|
||
|
|
from app.core.config import settings
|
||
|
|
from app.db.base import Base
|
||
|
|
|
||
|
|
config = context.config
|
||
|
|
|
||
|
|
if config.config_file_name is not None:
|
||
|
|
fileConfig(config.config_file_name)
|
||
|
|
|
||
|
|
# Inject the DB URL at runtime.
|
||
|
|
config.set_main_option("sqlalchemy.url", settings.database_url)
|
||
|
|
|
||
|
|
target_metadata = Base.metadata
|
||
|
|
|
||
|
|
|
||
|
|
def include_object(_object, _name, type_, _reflected, _compare_to): # type: ignore[no-untyped-def]
|
||
|
|
"""Skip alembic's internal version table from autogenerate diffs."""
|
||
|
|
if type_ == "table" and _name == "alembic_version":
|
||
|
|
return False
|
||
|
|
return True
|
||
|
|
|
||
|
|
|
||
|
|
def run_migrations_offline() -> None:
|
||
|
|
"""Generate SQL without an engine — useful for review."""
|
||
|
|
context.configure(
|
||
|
|
url=config.get_main_option("sqlalchemy.url"),
|
||
|
|
target_metadata=target_metadata,
|
||
|
|
literal_binds=True,
|
||
|
|
dialect_opts={"paramstyle": "named"},
|
||
|
|
include_object=include_object,
|
||
|
|
compare_type=True,
|
||
|
|
compare_server_default=True,
|
||
|
|
)
|
||
|
|
with context.begin_transaction():
|
||
|
|
context.run_migrations()
|
||
|
|
|
||
|
|
|
||
|
|
def run_migrations_online() -> None:
|
||
|
|
"""Apply migrations against a live DB."""
|
||
|
|
connectable = engine_from_config(
|
||
|
|
config.get_section(config.config_ini_section, {}),
|
||
|
|
prefix="sqlalchemy.",
|
||
|
|
poolclass=pool.NullPool,
|
||
|
|
)
|
||
|
|
with connectable.connect() as connection:
|
||
|
|
context.configure(
|
||
|
|
connection=connection,
|
||
|
|
target_metadata=target_metadata,
|
||
|
|
include_object=include_object,
|
||
|
|
compare_type=True,
|
||
|
|
compare_server_default=True,
|
||
|
|
)
|
||
|
|
with context.begin_transaction():
|
||
|
|
context.run_migrations()
|
||
|
|
|
||
|
|
|
||
|
|
if context.is_offline_mode():
|
||
|
|
run_migrations_offline()
|
||
|
|
else:
|
||
|
|
run_migrations_online()
|