66 lines
1.7 KiB
Python
66 lines
1.7 KiB
Python
"""Alembic 迁移环境。"""
|
|
|
|
from sqlalchemy import pool
|
|
from sqlalchemy.engine import Connection, make_url
|
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
|
|
|
from alembic import context
|
|
from app.core.config import settings
|
|
from app.db.base import Base
|
|
|
|
config = context.config
|
|
config.set_main_option("sqlalchemy.url", settings.resolved_database_url)
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def ensure_sqlite_parent_dir() -> None:
|
|
url = make_url(settings.resolved_database_url)
|
|
if url.drivername.startswith("sqlite") and url.database:
|
|
settings.resolve_from_backend(url.database).parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
ensure_sqlite_parent_dir()
|
|
context.configure(
|
|
url=settings.resolved_database_url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def do_run_migrations(connection: Connection) -> None:
|
|
context.configure(connection=connection, target_metadata=target_metadata)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def run_async_migrations() -> None:
|
|
ensure_sqlite_parent_dir()
|
|
section = config.get_section(config.config_ini_section, {})
|
|
connectable = async_engine_from_config(
|
|
section,
|
|
prefix="sqlalchemy.",
|
|
poolclass=pool.NullPool,
|
|
)
|
|
|
|
async with connectable.connect() as connection:
|
|
await connection.run_sync(do_run_migrations)
|
|
|
|
await connectable.dispose()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
import asyncio
|
|
|
|
asyncio.run(run_async_migrations())
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|