79 lines
2.0 KiB
Python
79 lines
2.0 KiB
Python
"""Alembic environment configuration for async SQLAlchemy engine."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from logging.config import fileConfig
|
|
|
|
from alembic import context
|
|
from sqlalchemy import Connection, pool
|
|
from sqlalchemy.ext.asyncio import AsyncEngine, async_engine_from_config
|
|
|
|
from app.core.config import settings
|
|
from app.models import Base
|
|
|
|
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)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
"""Run migrations without a database connection."""
|
|
context.configure(
|
|
url=settings.database_url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
compare_type=True,
|
|
compare_server_default=True,
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def do_run_migrations(connection: Connection) -> None:
|
|
"""Configure Alembic context and run migrations."""
|
|
context.configure(
|
|
connection=connection,
|
|
target_metadata=target_metadata,
|
|
compare_type=True,
|
|
compare_server_default=True,
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def run_migrations_online() -> None:
|
|
"""Run migrations inside an async engine context."""
|
|
configuration = config.get_section(config.config_ini_section) or {}
|
|
connectable = async_engine_from_config(
|
|
configuration,
|
|
prefix="sqlalchemy.",
|
|
poolclass=pool.NullPool,
|
|
future=True,
|
|
)
|
|
|
|
assert isinstance(connectable, AsyncEngine)
|
|
|
|
async with connectable.connect() as connection:
|
|
await connection.run_sync(do_run_migrations)
|
|
|
|
await connectable.dispose()
|
|
|
|
|
|
def main() -> None:
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
asyncio.run(run_migrations_online())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|