From 6b7ef1c4c84659faaf1979c0aa0df42d9cf3859e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 9 Nov 2026 16:11:30 -0300 Subject: [PATCH] fix: a rollback never stops the database from starting; schema changes are migration files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .gitea/workflows/deploy.yml | 7 ++ app/bootstrap.py | 4 + app/core/db.py | 3 + app/migrate.py | 34 +++++++++ .../202611091607_checks-current-lists.sql | 14 ++++ app/schema.sql | 37 ++++++--- docs/LOCAL_SETUP.md | 18 +++++ docs/PORTAINER.md | 5 +- tests/migrations_test.py | 59 ++++++++++++++ tests/test_migrate.py | 76 +++++++++++++++++++ tests/test_schema.py | 33 +++++++- 11 files changed, 278 insertions(+), 12 deletions(-) create mode 100644 app/migrate.py create mode 100644 app/migrations/202611091607_checks-current-lists.sql create mode 100644 tests/migrations_test.py create mode 100644 tests/test_migrate.py diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index f45d15e..75db134 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -23,6 +23,7 @@ jobs: deploy.test_production_preflight \ tests.test_pricing \ tests.test_coupons \ + tests.test_migrate \ tests.test_secrets -v sh -n infra/lock_dependencies.sh @@ -67,6 +68,12 @@ jobs: $COMPOSE up --build -d --wait --wait-timeout 600 $COMPOSE ps + # The database never blocks a rollback. Runs in db-init, the only job + # with the administrator connection; the whole test is rolled back, so + # nothing it inserts or alters remains. + - name: Rollback and migrations + run: $COMPOSE run --rm --no-deps db-init python -m tests.migrations_test + # Run inside the stack's own network. The runner is itself a container, so # ports published on the host's loopback are in a different namespace and # unreachable from here. SITE_HOST_HEADER keeps the Host the gateway and diff --git a/app/bootstrap.py b/app/bootstrap.py index 4150df2..f353be7 100644 --- a/app/bootstrap.py +++ b/app/bootstrap.py @@ -4,6 +4,7 @@ from pathlib import Path from urllib.parse import urlparse import psycopg from psycopg import sql +from . import migrate from .core.secrets import load as load_secret_files from .operators import seed_from_environment @@ -41,6 +42,7 @@ def main(): c.execute(sql.SQL('ALTER ROLE {} NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD {}').format( sql.Identifier(role), sql.Literal(password))) c.execute(Path(__file__).with_name('schema.sql').read_text()) + applied = migrate.apply(c) c.execute(sql.SQL('REVOKE CREATE ON SCHEMA public FROM PUBLIC')) c.execute(sql.SQL('GRANT CONNECT ON DATABASE {} TO {}').format(sql.Identifier(database),sql.Identifier(role))) c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role))) @@ -54,6 +56,8 @@ def main(): # reverted by a stale environment variable on the next deploy. seeded = seed_from_environment(c) print('Local schema migrated; runtime role has DML only.') + if applied: + print(f'Schema migrations applied: {", ".join(applied)}') if seeded: print(f'Seeded operator account {seeded} from OPERATOR_EMAIL.') diff --git a/app/core/db.py b/app/core/db.py index 46ff4b7..ce049e0 100644 --- a/app/core/db.py +++ b/app/core/db.py @@ -3,6 +3,8 @@ from pathlib import Path import psycopg from psycopg.rows import dict_row +from .. import migrate + def connect(): # Production passes credentials as discrete libpq fields. This avoids # treating characters in a generated password as URL syntax. Local and @@ -21,3 +23,4 @@ def initialize(): with connect() as c: # The schema lives at the package root, one level up from core/. c.execute((Path(__file__).resolve().parent.parent / 'schema.sql').read_text()) + migrate.apply(c) diff --git a/app/migrate.py b/app/migrate.py new file mode 100644 index 0000000..f537acf --- /dev/null +++ b/app/migrate.py @@ -0,0 +1,34 @@ +"""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 diff --git a/app/migrations/202611091607_checks-current-lists.sql b/app/migrations/202611091607_checks-current-lists.sql new file mode 100644 index 0000000..463169b --- /dev/null +++ b/app/migrations/202611091607_checks-current-lists.sql @@ -0,0 +1,14 @@ +-- The current lists of the three CHECK constraints whose values have grown +-- over time, applied once to every database, including one whose copy is older +-- (an image before front 7a lacks 'expedicao', for example). From now on, +-- widening a list is a new migration that drops and adds that one constraint. +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')); + +ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check; +ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check + CHECK(kind IN ('reset','code','account','notice','order','alert','test')); + +ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check; +ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento')); diff --git a/app/schema.sql b/app/schema.sql index faa663a..b4b4cd7 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -286,9 +286,16 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names ( -- the printed sheet and are the only ones to release it to Finalizado; -- vendedores only read; expedição assembles sheets in the Kanban's montador. ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin'; -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')); +-- Created once, and widened only by a migration: re-adding it on every start +-- would let an older image narrow the list and refuse rows written under a +-- later one, and the database would not finish starting. +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='operators_role' + AND conrelid='dtf_local.operators'::regclass) THEN + ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role + CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao')); + END IF; +END $$; -- Print machines and which products each prints. An order gets its machine -- when someone pulls it into Imprimindo; no machine is assigned at payment. -- limit_metres remains the load shown for a machine. @@ -410,11 +417,16 @@ UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified A -- E-mail kinds: a password-recovery link, a code, the notice that an account -- already exists, the notice of a changed e-mail, a customer's paid order, -- the team's alerts and a test. --- Defined once, here: the schema runs on every start, and an earlier, narrower --- copy would refuse the rows of the kinds added after it. -ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check; -ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check - CHECK(kind IN ('reset','code','account','notice','order','alert','test')); +-- Created once, and widened only by a migration: the schema runs on every +-- start, and re-adding an earlier, narrower copy would refuse the rows of the +-- kinds added after it. +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='mail_queue_kind_check' + AND conrelid='dtf_local.mail_queue'::regclass) THEN + ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check + CHECK(kind IN ('reset','code','account','notice','order','alert','test')); + END IF; +END $$; -- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose -- customer asked for a proof at checkout, prints 20 cm first; the room marks @@ -452,8 +464,13 @@ WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contac ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text; UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL; ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL; -ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check; -ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento')); +-- Created once, and widened only by a migration; never re-added on start. +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='orders_origin_check' + AND conrelid='dtf_local.orders'::regclass) THEN + ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento')); + END IF; +END $$; -- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of -- 2026-10-27). Gestão opens it with its cause, and the cause never changes diff --git a/docs/LOCAL_SETUP.md b/docs/LOCAL_SETUP.md index bb88ce1..d1194c2 100644 --- a/docs/LOCAL_SETUP.md +++ b/docs/LOCAL_SETUP.md @@ -238,6 +238,24 @@ storage permits; otherwise reselect them. Saved quote IDs also survive reloads. Clearing cookies loses a guest session, while registered customers can sign in again. The operator can still inspect order records. +## Schema changes + +`app/schema.sql` is the frozen baseline: every start runs it, and nothing new +is added to it. A schema change is a new file in `app/migrations/`, named with +a timestamp and a short slug, `YYYYMMDDHHMM_description.sql` (for example +`202611091607_checks-current-lists.sql`). `app/migrate.py` runs every file not +yet recorded in `dtf_local.migrations`, in name order, each recorded in the +same transaction and under an advisory lock; `app/bootstrap.py` and +`app/core/db.py` call it right after the schema and before the grants, so a +table a migration creates is granted to the runtime role. Never edit an applied +migration: add a new one instead. Any file in that folder whose name does not +match `^\d{12}_[a-z0-9-]+\.sql$` stops the start, so a typo is never skipped. + +Widening a CHECK constraint is a DROP + ADD in a migration, with the full list; +`app/schema.sql` only creates the three initial ones when missing. A rollback +to an image at or after this change is safe: an older image ignores migration +names it does not know. + ## Print files Every paid order queues one print-file job per item. The worker renders a PDF diff --git a/docs/PORTAINER.md b/docs/PORTAINER.md index 893fe4a..97c91d6 100644 --- a/docs/PORTAINER.md +++ b/docs/PORTAINER.md @@ -173,7 +173,10 @@ affect stored data or retention. In the Portainer stack variables, change `IMAGE_TAG` from `latest` to the full SHA of the last known-good Gitea commit and redeploy. This rolls back Site, API, Kanban, and worker code; it does not undo database migrations or restore data. -After recovery and a corrected release, return `IMAGE_TAG` to `latest`. +Rolling back to an image from before the timestamped migrations can still fail +if the data uses newer values; images from that change on ignore migration +names they do not know, so a rollback is safe. After recovery and a corrected +release, return `IMAGE_TAG` to `latest`. ## 6. Before opening to customers diff --git a/tests/migrations_test.py b/tests/migrations_test.py new file mode 100644 index 0000000..8a3af12 --- /dev/null +++ b/tests/migrations_test.py @@ -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() diff --git a/tests/test_migrate.py b/tests/test_migrate.py new file mode 100644 index 0000000..63f60cc --- /dev/null +++ b/tests/test_migrate.py @@ -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() diff --git a/tests/test_schema.py b/tests/test_schema.py index 04a6893..051530f 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -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()