84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
from __future__ import annotations
|
|
|
|
import importlib
|
|
import os
|
|
from logging.config import fileConfig
|
|
from typing import Any
|
|
|
|
from alembic import context
|
|
from sqlalchemy import create_engine, event, pool
|
|
from sqlalchemy.engine import URL, make_url
|
|
|
|
models = importlib.import_module("backup_tool.db.models")
|
|
sqlite_runtime = importlib.import_module("backup_tool.db.sqlite")
|
|
|
|
config = context.config
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
target_metadata = models.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 busy_timeout_ms() -> int:
|
|
raw_value = os.environ.get(
|
|
"BACKUP_TOOL_SQLITE_BUSY_TIMEOUT_MS", str(sqlite_runtime.DEFAULT_BUSY_TIMEOUT_MS)
|
|
)
|
|
try:
|
|
value = int(raw_value)
|
|
except ValueError as error:
|
|
raise RuntimeError("SQLite busy timeout must be an integer") from error
|
|
if value < 1_000 or value > 120_000:
|
|
raise RuntimeError("SQLite busy timeout must be between 1000 and 120000 ms")
|
|
return value
|
|
|
|
|
|
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:
|
|
timeout = busy_timeout_ms()
|
|
engine = create_engine(
|
|
synchronous_url(configured_url()),
|
|
poolclass=pool.NullPool,
|
|
connect_args=sqlite_runtime.sqlite_connect_args(timeout),
|
|
)
|
|
|
|
@event.listens_for(engine, "connect")
|
|
def configure_sqlite(dbapi_connection: Any, _connection_record: Any) -> None:
|
|
sqlite_runtime.configure_sqlite_connection(dbapi_connection)
|
|
|
|
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()
|