2026-09-23 11:52:08 +03:00

124 lines
3.6 KiB
Python

import asyncio
from logging.config import fileConfig
import os
import sys
from sqlalchemy import engine_from_config
from sqlalchemy import pool, text
from sqlalchemy.ext.asyncio import AsyncEngine
from alembic import context
from src.core.config import settings
from src.models import *
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option("sqlalchemy.url", settings.OPENBAO.DATABASE.DATABASE_URL)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
db_schema = settings.OPENBAO.DATABASE.DATABASE_SCHEMA
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
x_args = context.get_x_argument(as_dictionary=True)
env_name = x_args.get("env") or os.getenv("APP_ENV") or "dev"
if env_name == "prod":
answer = input(
"\n>>> You are about to run migrations against PROD.\n"
">>> Type 'yes' to continue: "
)
if answer.strip().lower() != "yes":
print("Aborted.")
sys.exit(1)
def include_object(obj, name, type_, reflected, compare_to):
"""Ignore anything outside the current schema during autogenerate."""
obj_schema = getattr(obj, "schema", None)
if obj_schema is not None and obj_schema != db_schema:
return False
return True
def do_run_migrations(connection) -> None:
connection.execute(text(f'CREATE SCHEMA IF NOT EXISTS "{db_schema}"'))
connection.execute(text(f'SET search_path TO "{db_schema}"'))
connection.commit()
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
compare_server_default=True,
version_table_schema=db_schema,
include_schemas=False,
include_object=include_object,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
version_table_schema="dkb",
include_schemas=True,
)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = AsyncEngine(
engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
future=True
)
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())