53 lines
1.4 KiB
Python
53 lines
1.4 KiB
Python
from logging.config import fileConfig
|
|
|
|
from alembic import context
|
|
from sqlalchemy import create_engine, pool, text
|
|
|
|
from core.config import settings
|
|
from core.db import build_url
|
|
from models import Base
|
|
|
|
config = context.config
|
|
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
# Ключ advisory lock: параллельные запуски миграций выполнятся по очереди.
|
|
MIGRATION_LOCK_KEY = 2_026_002
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
context.configure(
|
|
url=build_url(),
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
engine = create_engine(
|
|
build_url(),
|
|
poolclass=pool.NullPool,
|
|
connect_args={"connect_timeout": settings.db.connect_timeout},
|
|
)
|
|
with engine.connect() as connection:
|
|
context.configure(
|
|
connection=connection,
|
|
target_metadata=target_metadata,
|
|
compare_server_default=True,
|
|
)
|
|
with context.begin_transaction():
|
|
connection.execute(text("SELECT pg_advisory_xact_lock(:key)"), {"key": MIGRATION_LOCK_KEY})
|
|
context.run_migrations()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|