Files
dtf-system/app/migrate.py
Cauê Faleiros 6b7ef1c4c8 fix: a rollback never stops the database from starting; schema changes are migration files
schema.sql dropped and re-added three CHECK constraints on every start, so
an older image narrowed the lists and failed on rows written by a newer one
(an Expedição user, for example). They are now created only when missing,
and app/migrate.py applies timestamped files from app/migrations/ once each,
recording them in dtf_local.migrations; an older image skips names it does
not know. The first migration sets today's full lists. A CI step rehearses
the rollback on the real database inside a rolled-back transaction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 16:11:30 -03:00

35 lines
1.4 KiB
Python

"""Timestamped schema migrations, applied once by the database initializer.
schema.sql is the frozen baseline and runs on every start; a change after it is
a file in app/migrations/, named YYYYMMDDHHMM_slug.sql. The name is the
migration's identity and is recorded in dtf_local.migrations, so a deploy never
applies one twice and an older image skips names it does not know.
"""
import re
from pathlib import Path
MIGRATIONS = Path(__file__).resolve().with_name('migrations')
LOCK = 804209
NAME = re.compile(r'\d{12}_[a-z0-9-]+\.sql')
def apply(c, directory=MIGRATIONS) -> list[str]:
"""Run, in name order, every migration file not yet recorded in
dtf_local.migrations, each recorded in the same transaction. A name in
the table that has no file (written by a newer image) is ignored, so an
older image still starts."""
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
files = {}
for path in Path(directory).iterdir():
if not path.is_file() or not NAME.fullmatch(path.name):
raise ValueError(f'Unexpected file in {directory}: {path.name}')
files[path.name] = path
applied = []
for name in sorted(files):
if c.execute('SELECT 1 FROM dtf_local.migrations WHERE name=%s', (name,)).fetchone():
continue
c.execute(files[name].read_text())
c.execute('INSERT INTO dtf_local.migrations(name) VALUES(%s)', (name,))
applied.append(name)
return applied