51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
|
|
from sqlalchemy import pool
|
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
|
|
|
from alembic import context
|
|
from app.db import Base, postgres_ssl_context
|
|
from app.settings import _secret
|
|
|
|
config = context.config
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def offline() -> None:
|
|
context.configure(
|
|
url=_secret("MESSAGE_SAFETY_CONFIG_ADMIN_DATABASE_URL"),
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def online() -> None:
|
|
section = config.get_section(config.config_ini_section) or {}
|
|
section["sqlalchemy.url"] = _secret("MESSAGE_SAFETY_CONFIG_ADMIN_DATABASE_URL")
|
|
engine = async_engine_from_config(
|
|
section,
|
|
prefix="sqlalchemy.",
|
|
poolclass=pool.NullPool,
|
|
connect_args={"ssl": postgres_ssl_context()},
|
|
)
|
|
async with engine.connect() as connection:
|
|
|
|
def migrate(conn) -> None:
|
|
context.configure(connection=conn, target_metadata=target_metadata)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
await connection.run_sync(migrate)
|
|
await engine.dispose()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
offline()
|
|
else:
|
|
asyncio.run(online())
|