61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
import asyncio
|
|
import os
|
|
from logging.config import fileConfig
|
|
|
|
from sqlalchemy.engine import Connection
|
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
|
|
|
from alembic import context
|
|
from fire_planner.db import SCHEMA_NAME, Base
|
|
|
|
config = context.config
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
db_url = os.environ.get("DB_CONNECTION_STRING")
|
|
if db_url:
|
|
config.set_main_option("sqlalchemy.url", db_url)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def do_run_migrations(connection: Connection) -> None:
|
|
# Alembic's version_table lives inside SCHEMA_NAME, so the schema must
|
|
# exist before context.configure() tries to create alembic_version.
|
|
connection.exec_driver_sql(f'CREATE SCHEMA IF NOT EXISTS "{SCHEMA_NAME}"')
|
|
context.configure(
|
|
connection=connection,
|
|
target_metadata=target_metadata,
|
|
version_table_schema=SCHEMA_NAME,
|
|
include_schemas=True,
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def run_migrations_online() -> None:
|
|
configuration = config.get_section(config.config_ini_section, {})
|
|
connectable = async_engine_from_config(configuration, prefix="sqlalchemy.")
|
|
async with connectable.connect() as connection:
|
|
await connection.run_sync(do_run_migrations)
|
|
await connection.commit()
|
|
await connectable.dispose()
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
context.configure(
|
|
url=config.get_main_option("sqlalchemy.url"),
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
version_table_schema=SCHEMA_NAME,
|
|
include_schemas=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
asyncio.run(run_migrations_online())
|