46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
from logging.config import fileConfig
|
|
|
|
from alembic import context
|
|
|
|
config = context.config
|
|
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
database_url = os.environ.get("DATABASE_URL")
|
|
if not database_url:
|
|
raise RuntimeError("DATABASE_URL environment variable is required for migrations")
|
|
|
|
target_metadata = None
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
"""Оффлайн-режим: печатает SQL, не подключаясь к БД."""
|
|
context.configure(
|
|
url=database_url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
"""Онлайн-режим: подключается к БД и применяет миграции."""
|
|
from sqlalchemy import create_engine
|
|
|
|
connectable = create_engine(database_url, pool_pre_ping=True)
|
|
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() |