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

View File

@@ -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.')

View File

@@ -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)

34
app/migrate.py Normal file
View File

@@ -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

View File

@@ -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'));

View File

@@ -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