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:
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user