feat(ops): alembic env hook invokes backup-db.sh before migrations

Runs at env module load so the backup fires ahead of offline and
online migration paths, as well as alembic current / revision. A
failing backup does not stop the migration: this is defense in depth,
not a hard prerequisite, and the common failure case is "DB does not
exist yet" on a fresh checkout.

Refs #5

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
archeious 2026-04-17 11:51:49 -06:00
parent a492294dd7
commit a09860dc61

View file

@ -1,4 +1,6 @@
import subprocess
from logging.config import fileConfig
from pathlib import Path
from sqlalchemy import engine_from_config, pool
@ -7,6 +9,28 @@ from alembic import context
from quartermaster.config import DB_URL
from quartermaster.models import Base
def _backup_before_migrations() -> None:
script = Path(__file__).resolve().parents[1] / "scripts" / "backup-db.sh"
if not script.is_file():
return
result = subprocess.run(
[str(script), "alembic"],
check=False,
capture_output=True,
text=True,
)
if result.stdout:
print(result.stdout, end="")
if result.returncode != 0 and result.stderr:
print(
f"alembic: backup-db.sh returned {result.returncode}; "
f"continuing without a fresh backup.\n{result.stderr}",
)
_backup_before_migrations()
config = context.config
config.set_main_option("sqlalchemy.url", DB_URL)