88 lines
2.2 KiB
Python
88 lines
2.2 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from logging.config import fileConfig
|
|
|
|
from alembic import context
|
|
from sqlalchemy import pool
|
|
from sqlalchemy.engine import Connection
|
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
|
|
|
from app.core.config import settings
|
|
from app.db.base import Base
|
|
import app.db.models
|
|
|
|
config = context.config
|
|
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
config.set_main_option(
|
|
"sqlalchemy.url",
|
|
settings.database_url.replace("%", "%%"),
|
|
)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def include_object(object_, name, type_, reflected, compare_to):
|
|
schemas = {"auth", "content", "commerce", "platform"}
|
|
schema = getattr(object_, "schema", None)
|
|
|
|
if type_ == "table":
|
|
return schema in schemas
|
|
|
|
table = getattr(object_, "table", None)
|
|
if table is not None:
|
|
return getattr(table, "schema", None) in schemas
|
|
|
|
return True
|
|
|
|
|
|
def configure(connection=None, url=None):
|
|
context.configure(
|
|
connection=connection,
|
|
url=url,
|
|
target_metadata=target_metadata,
|
|
include_schemas=True,
|
|
include_object=include_object,
|
|
compare_type=True,
|
|
compare_server_default=True,
|
|
literal_binds=connection is None,
|
|
dialect_opts={"paramstyle": "named"} if connection is None else None,
|
|
version_table="alembic_version",
|
|
version_table_schema="public",
|
|
)
|
|
|
|
|
|
def run_migrations_offline():
|
|
configure(url=config.get_main_option("sqlalchemy.url"))
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_sync(connection: Connection):
|
|
configure(connection=connection)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def run_migrations_async():
|
|
engine = async_engine_from_config(
|
|
config.get_section(config.config_ini_section, {}),
|
|
prefix="sqlalchemy.",
|
|
poolclass=pool.NullPool,
|
|
)
|
|
|
|
try:
|
|
async with engine.connect() as connection:
|
|
await connection.run_sync(run_migrations_sync)
|
|
finally:
|
|
await engine.dispose()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
asyncio.run(run_migrations_async())
|