62 lines
1.7 KiB
Python
62 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
import importlib
|
|
import os
|
|
from logging.config import fileConfig
|
|
|
|
from alembic import context
|
|
from sqlalchemy import create_engine, pool
|
|
from sqlalchemy.engine import URL, make_url
|
|
|
|
Base = importlib.import_module("backup_tool.db.models").Base
|
|
|
|
config = context.config
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def configured_url() -> str:
|
|
raw_url = os.environ.get("BACKUP_TOOL_DATABASE_URL") or config.get_main_option("sqlalchemy.url")
|
|
if raw_url is None:
|
|
raise RuntimeError("sqlalchemy.url is required")
|
|
return raw_url
|
|
|
|
|
|
def synchronous_url(raw_url: str) -> URL:
|
|
url = make_url(raw_url)
|
|
if url.drivername != "sqlite+aiosqlite":
|
|
raise RuntimeError("v2 migrations require sqlite+aiosqlite")
|
|
return url.set(drivername="sqlite")
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
url = synchronous_url(configured_url())
|
|
context.configure(
|
|
url=url.render_as_string(hide_password=False),
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
compare_type=True,
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
engine = create_engine(
|
|
synchronous_url(configured_url()),
|
|
poolclass=pool.NullPool,
|
|
)
|
|
with engine.connect() as connection:
|
|
context.configure(connection=connection, target_metadata=target_metadata, compare_type=True)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
engine.dispose()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|