51 lines
1.8 KiB
Python
51 lines
1.8 KiB
Python
import os
|
||
from logging.config import fileConfig
|
||
|
||
from alembic import context
|
||
from sqlalchemy import engine_from_config, pool
|
||
|
||
from app.db import Base
|
||
from app import models # noqa: F401
|
||
|
||
config = context.config
|
||
if config.config_file_name is not None:
|
||
fileConfig(config.config_file_name)
|
||
|
||
config.set_main_option("sqlalchemy.url", os.environ["DATABASE_URL"])
|
||
target_metadata = Base.metadata
|
||
|
||
|
||
def run_migrations_offline() -> None:
|
||
context.configure(url=os.environ["DATABASE_URL"], target_metadata=target_metadata, literal_binds=True)
|
||
with context.begin_transaction():
|
||
context.run_migrations()
|
||
|
||
|
||
def run_migrations_online() -> None:
|
||
connectable = engine_from_config(
|
||
config.get_section(config.config_ini_section, {}),
|
||
prefix="sqlalchemy.",
|
||
poolclass=pool.NullPool,
|
||
)
|
||
with connectable.connect() as connection:
|
||
# Advisory lock сериализует параллельные запуски alembic upgrade
|
||
# (например, при старте нескольких реплик одновременно).
|
||
# В SQLAlchemy 2.0 engine.connect() открывает неявную транзакцию,
|
||
# поэтому после run_migrations() её нужно явно закоммитить —
|
||
# иначе DDL откатится при закрытии соединения.
|
||
connection.exec_driver_sql("SELECT pg_advisory_lock(727274)")
|
||
try:
|
||
context.configure(connection=connection, target_metadata=target_metadata)
|
||
with context.begin_transaction():
|
||
context.run_migrations()
|
||
connection.commit()
|
||
finally:
|
||
connection.exec_driver_sql("SELECT pg_advisory_unlock(727274)")
|
||
connection.commit()
|
||
|
||
|
||
if context.is_offline_mode():
|
||
run_migrations_offline()
|
||
else:
|
||
run_migrations_online()
|