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>
This commit is contained in:
Cauê Faleiros
2026-11-09 16:11:30 -03:00
parent 63af984e83
commit 6b7ef1c4c8
11 changed files with 278 additions and 12 deletions

59
tests/migrations_test.py Normal file
View File

@@ -0,0 +1,59 @@
"""Rollback safety on the real database: an image at or after the timestamped
migrations starts on data written under a newer, wider CHECK list.
Uses the database administrator's connection, so it runs in the db-init
container: docker compose -f compose.local.yaml run --rm --no-deps db-init \
python -m tests.migrations_test
Everything happens in one transaction that is rolled back at the end, so the
widening, its migration record and the test operator never remain.
"""
import tempfile
from pathlib import Path
from uuid import uuid4
from app import migrate
from app.bootstrap import admin_connect
SCHEMA = Path(__file__).resolve().parent.parent.joinpath('app', 'schema.sql')
WIDEN = """ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao','tester'));
"""
def check(condition, message):
if not condition:
raise AssertionError(message)
print('PASS:', message)
def main():
c = admin_connect()
try:
c.execute(SCHEMA.read_text())
migrated = migrate.apply(c)
check(True, f'the real schema and migrations run ({", ".join(migrated) or "none pending"})')
with tempfile.TemporaryDirectory() as folder:
name = '209901010000_widen-operators-role.sql'
Path(folder, name).write_text(WIDEN)
applied = migrate.apply(c, folder)
check(applied == [name], 'a temporary migration widens operators_role')
email = f'tester-{uuid4().hex[:8]}@example.test'
c.execute("INSERT INTO dtf_local.operators(id,email,password_hash,role) VALUES(%s,%s,'test','tester')",
(uuid4(), email))
check(True, 'an operator with the newer role is accepted')
# The rollback rehearsal: an older image at or after the migrations
# change runs its schema.sql and its own folder, with no later file,
# and must start on the current data without narrowing the list.
c.execute(SCHEMA.read_text())
migrate.apply(c)
check(True, 'the older image starts and leaves the widened list alone')
finally:
c.rollback()
c.close()
print('migrations_test OK')
if __name__ == '__main__':
main()

76
tests/test_migrate.py Normal file
View File

@@ -0,0 +1,76 @@
"""The migration runner: file names, order and recorded names.
Run from the repository root: python3 -m unittest tests.test_migrate
"""
import tempfile
import unittest
from pathlib import Path
from app import migrate
class Cursor:
def __init__(self, row=None):
self.row = row
def fetchone(self):
return self.row
class FakeConnection:
"""Records the SQL it is asked to run and the names already recorded."""
def __init__(self, recorded=()):
self.recorded = set(recorded)
self.calls = []
def execute(self, query, params=()):
self.calls.append((query, params))
if query.startswith('SELECT 1 FROM dtf_local.migrations'):
return Cursor((1,) if params[0] in self.recorded else None)
if query.startswith('INSERT INTO dtf_local.migrations'):
self.recorded.add(params[0])
return Cursor()
@property
def queries(self):
return [query for query, _ in self.calls]
class MigrateTest(unittest.TestCase):
def folder(self, names):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
for name in names:
Path(temp.name, name).write_text(f'-- {name}\n')
return temp.name
def test_runs_new_files_in_name_order(self):
directory = self.folder(['202611091202_b.sql', '202611091201_a.sql'])
c = FakeConnection()
self.assertEqual(migrate.apply(c, directory), ['202611091201_a.sql', '202611091202_b.sql'])
self.assertEqual(c.queries[0], 'SELECT pg_advisory_xact_lock(%s)')
ran = [query for query in c.queries if query.startswith('-- ')]
self.assertEqual(ran, ['-- 202611091201_a.sql\n', '-- 202611091202_b.sql\n'])
def test_recorded_files_are_skipped(self):
directory = self.folder(['202611091201_a.sql', '202611091202_b.sql'])
c = FakeConnection({'202611091201_a.sql'})
self.assertEqual(migrate.apply(c, directory), ['202611091202_b.sql'])
self.assertNotIn('-- 202611091201_a.sql\n', c.queries)
def test_a_recorded_name_without_a_file_is_ignored(self):
directory = self.folder(['202611091201_a.sql'])
c = FakeConnection({'209901010000_from-a-newer-image.sql'})
self.assertEqual(migrate.apply(c, directory), ['202611091201_a.sql'])
def test_an_unexpected_file_raises(self):
# A typo must stop the start, never be skipped as if it were applied.
for name in ('notes.txt', '20261109120_short.sql', '202611091201_Two-words.sql'):
with self.subTest(name=name):
with self.assertRaises(ValueError):
migrate.apply(FakeConnection(), self.folder([name]))
if __name__ == '__main__':
unittest.main()

View File

@@ -8,13 +8,44 @@ import unittest
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CONSTRAINTS = ('operators_role', 'mail_queue_kind_check', 'orders_origin_check')
def check_lists(text):
"""Each constraint's CHECK (column IN (...)) values, by constraint name."""
found = {}
for name in CONSTRAINTS:
match = re.search(r'ADD CONSTRAINT\s+' + name + r'\s+CHECK\s*\([^()]*\bIN\s*\(([^)]*)\)',
text, re.I | re.S)
if match:
found[name] = tuple(value.strip().strip("'") for value in match.group(1).split(','))
return found
class SchemaTest(unittest.TestCase):
def test_each_constraint_is_added_once(self):
schema = Path(__file__).resolve().parent.parent.joinpath('app', 'schema.sql').read_text()
schema = ROOT.joinpath('app', 'schema.sql').read_text()
added = Counter(re.findall(r'ADD CONSTRAINT\s+(\w+)', schema, re.I))
self.assertEqual([name for name, count in added.items() if count > 1], [])
def test_only_the_foreign_key_loop_drops_a_constraint(self):
# An image never lowers a CHECK on start. The FK loop rebuilds a
# foreign key only to add ON DELETE CASCADE, so it never narrows one.
schema = ROOT.joinpath('app', 'schema.sql').read_text()
loop = re.search(r'DO \$\$\nDECLARE r record;.*?\nEND \$\$;', schema, re.S)
self.assertIsNotNone(loop)
rest = schema[:loop.start()] + schema[loop.end():]
self.assertNotIn('DROP CONSTRAINT', rest)
def test_the_first_migration_has_the_current_lists(self):
schema = ROOT.joinpath('app', 'schema.sql').read_text()
files = list(ROOT.joinpath('app', 'migrations').glob('*_checks-current-lists.sql'))
self.assertEqual(len(files), 1)
migration = files[0].read_text()
self.assertEqual(check_lists(schema), check_lists(migration))
self.assertEqual(set(check_lists(schema)), set(CONSTRAINTS))
if __name__ == '__main__':
unittest.main()