From a09860dc61d5e263764d438f34b47a6fdbbe623e Mon Sep 17 00:00:00 2001 From: archeious Date: Fri, 17 Apr 2026 11:51:49 -0600 Subject: [PATCH] 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) --- alembic/env.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/alembic/env.py b/alembic/env.py index 920a806..4522785 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -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)