import sqlite3 from datetime import datetime, timezone MIGRATION = "20260925_agreement_boq_fk" BASE_LINK_MIGRATION = "20260925_agreement_base_boq" SCOPE_MIGRATION = "20260925_agreement_scope_boq" ITEM_WORK_ITEM_MIGRATION = "20260925_agreement_item_work_item_required" WORK_ITEM_OPTIONAL_BOQ_MIGRATION = "20260925_work_item_optional_boq" DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION = "20260925_daily_report_optional_system" KS2_REPORTING_PERIOD_MIGRATION = "20260925_ks2_reporting_period" PAYMENT_STATUS_MIGRATION = "20260926_payment_status" def run_migrations(engine): if engine.dialect.name != "sqlite": return path = engine.url.database connection = sqlite3.connect(path, isolation_level=None) try: connection.execute("PRAGMA foreign_keys=OFF") connection.execute("BEGIN IMMEDIATE") connection.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TEXT NOT NULL)") applied = {row[0] for row in connection.execute("SELECT version FROM schema_migrations")} if MIGRATION not in applied: cols = [row[1] for row in connection.execute("PRAGMA table_info(boq_documents)")] if "agreement_id" not in cols: raise RuntimeError("boq_documents.agreement_id is missing; refusing an unsafe migration") connection.execute("""CREATE TABLE boq_documents_new ( id INTEGER NOT NULL PRIMARY KEY, project_id INTEGER NOT NULL REFERENCES projects(id), agreement_id INTEGER REFERENCES agreements(id), name VARCHAR NOT NULL, version VARCHAR, source_file VARCHAR, created_at DATETIME )""") connection.execute("""INSERT INTO boq_documents_new (id, project_id, agreement_id, name, version, source_file, created_at) SELECT id, project_id, agreement_id, name, version, source_file, created_at FROM boq_documents""") connection.execute("DROP TABLE boq_documents") connection.execute("ALTER TABLE boq_documents_new RENAME TO boq_documents") connection.execute("CREATE INDEX IF NOT EXISTS ix_boq_documents_id ON boq_documents (id)") connection.execute("CREATE INDEX IF NOT EXISTS ix_boq_documents_agreement_id ON boq_documents (agreement_id)") connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (MIGRATION, datetime.now(timezone.utc).isoformat())) if BASE_LINK_MIGRATION not in applied: agreement_cols = [row[1] for row in connection.execute("PRAGMA table_info(agreements)")] if "base_boq_document_id" not in agreement_cols and "boq_document_id" not in agreement_cols: connection.execute("ALTER TABLE agreements ADD COLUMN boq_document_id INTEGER REFERENCES boq_documents(id)") connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_boq_document_id ON agreements (boq_document_id)") connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (BASE_LINK_MIGRATION, datetime.now(timezone.utc).isoformat())) if SCOPE_MIGRATION not in applied: agreement_cols = [row[1] for row in connection.execute("PRAGMA table_info(agreements)")] if "base_boq_document_id" in agreement_cols and "boq_document_id" not in agreement_cols: connection.execute("ALTER TABLE agreements RENAME COLUMN base_boq_document_id TO boq_document_id") elif "boq_document_id" not in agreement_cols: connection.execute("ALTER TABLE agreements ADD COLUMN boq_document_id INTEGER REFERENCES boq_documents(id)") connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_boq_document_id ON agreements (boq_document_id)") connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (SCOPE_MIGRATION, datetime.now(timezone.utc).isoformat())) if ITEM_WORK_ITEM_MIGRATION not in applied: item_cols = {row[1]: row[3] for row in connection.execute("PRAGMA table_info(agreement_items)")} if not item_cols.get("work_item_id", 0): null_items = connection.execute("SELECT COUNT(*) FROM agreement_items WHERE work_item_id IS NULL").fetchone()[0] if null_items: raise RuntimeError(f"Cannot require AgreementItem.work_item_id: {null_items} rows have no canonical WorkItem") connection.execute("""CREATE TABLE agreement_items_new ( id INTEGER NOT NULL PRIMARY KEY, agreement_id INTEGER NOT NULL REFERENCES agreements(id), work_item_id INTEGER NOT NULL REFERENCES work_items(id), change_type VARCHAR NOT NULL CHECK (change_type IN ('increase','decrease','new_position')), quantity_delta NUMERIC(15,4) NOT NULL, amount_delta NUMERIC(18,12) NOT NULL, source_row INTEGER, source_number VARCHAR, source_name VARCHAR, source_model VARCHAR, source_manufacturer VARCHAR, source_unit VARCHAR, source_unit_price NUMERIC(18,12), source_system_id INTEGER REFERENCES systems(id), source_section_id INTEGER REFERENCES sections(id), created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT ck_agreement_items_quantity_sign CHECK ( (change_type = 'increase' AND quantity_delta > 0) OR (change_type = 'decrease' AND quantity_delta < 0) OR (change_type = 'new_position' AND quantity_delta > 0) ) )""") connection.execute("""INSERT INTO agreement_items_new ( id, agreement_id, work_item_id, change_type, quantity_delta, amount_delta, source_row, source_number, source_name, source_model, source_manufacturer, source_unit, source_unit_price, source_system_id, source_section_id, created_at, updated_at ) SELECT id, agreement_id, work_item_id, change_type, quantity_delta, amount_delta, source_row, source_number, source_name, source_model, source_manufacturer, source_unit, source_unit_price, source_system_id, source_section_id, created_at, updated_at FROM agreement_items""") connection.execute("DROP TABLE agreement_items") connection.execute("ALTER TABLE agreement_items_new RENAME TO agreement_items") connection.execute("CREATE INDEX IF NOT EXISTS ix_agreement_items_id ON agreement_items (id)") connection.execute("CREATE INDEX IF NOT EXISTS ix_agreement_items_agreement_id ON agreement_items (agreement_id)") connection.execute("CREATE INDEX IF NOT EXISTS ix_agreement_items_work_item_id ON agreement_items (work_item_id)") connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (ITEM_WORK_ITEM_MIGRATION, datetime.now(timezone.utc).isoformat())) if WORK_ITEM_OPTIONAL_BOQ_MIGRATION not in applied: work_item_cols = {row[1]: row[3] for row in connection.execute("PRAGMA table_info(work_items)")} if work_item_cols.get("boq_document_id", 0): connection.execute("""CREATE TABLE work_items_new ( id INTEGER NOT NULL PRIMARY KEY, project_id INTEGER NOT NULL REFERENCES projects(id), boq_document_id INTEGER REFERENCES boq_documents(id), system_id INTEGER REFERENCES systems(id), section_id INTEGER REFERENCES sections(id), source_number VARCHAR, name VARCHAR NOT NULL, model VARCHAR, manufacturer VARCHAR, unit VARCHAR, quantity NUMERIC(15, 4), unit_price NUMERIC(18, 12), amount NUMERIC(18, 12), created_at DATETIME, updated_at DATETIME )""") connection.execute("""INSERT INTO work_items_new ( id, project_id, boq_document_id, system_id, section_id, source_number, name, model, manufacturer, unit, quantity, unit_price, amount, created_at, updated_at ) SELECT id, project_id, boq_document_id, system_id, section_id, source_number, name, model, manufacturer, unit, quantity, unit_price, amount, created_at, updated_at FROM work_items""") connection.execute("DROP TABLE work_items") connection.execute("ALTER TABLE work_items_new RENAME TO work_items") connection.execute("CREATE INDEX IF NOT EXISTS ix_work_items_id ON work_items (id)") agreement_item_cols = {row[1] for row in connection.execute("PRAGMA table_info(agreement_items)")} if "source_boq_document_id" not in agreement_item_cols: connection.execute("ALTER TABLE agreement_items ADD COLUMN source_boq_document_id INTEGER REFERENCES boq_documents(id)") # Older agreement-created positions live in an agreement document. Keep their # source BOQ scope where one was explicitly selected on the Agreement. connection.execute("""UPDATE agreement_items SET source_boq_document_id = ( SELECT agreements.boq_document_id FROM agreements WHERE agreements.id = agreement_items.agreement_id ) WHERE change_type = 'new_position' AND source_boq_document_id IS NULL""") connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (WORK_ITEM_OPTIONAL_BOQ_MIGRATION, datetime.now(timezone.utc).isoformat())) if DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION not in applied: report_cols = {row[1]: row[3] for row in connection.execute("PRAGMA table_info(daily_reports)")} if report_cols.get("system_id", 0): connection.execute("""CREATE TABLE daily_reports_new ( id INTEGER NOT NULL PRIMARY KEY, project_id INTEGER NOT NULL REFERENCES projects(id), system_id INTEGER REFERENCES systems(id), report_date DATE NOT NULL, notes TEXT, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP )""") connection.execute("""INSERT INTO daily_reports_new ( id, project_id, system_id, report_date, notes, created_at, updated_at ) SELECT id, project_id, system_id, report_date, notes, created_at, updated_at FROM daily_reports""") connection.execute("DROP TABLE daily_reports") connection.execute("ALTER TABLE daily_reports_new RENAME TO daily_reports") connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_id ON daily_reports (id)") connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_project_id ON daily_reports (project_id)") connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_system_id ON daily_reports (system_id)") connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_report_date ON daily_reports (report_date)") connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION, datetime.now(timezone.utc).isoformat())) if KS2_REPORTING_PERIOD_MIGRATION not in applied: ks2_cols = {row[1] for row in connection.execute("PRAGMA table_info(ks2_documents)")} if "reporting_period_from" not in ks2_cols: connection.execute("ALTER TABLE ks2_documents ADD COLUMN reporting_period_from DATE") if "reporting_period_to" not in ks2_cols: connection.execute("ALTER TABLE ks2_documents ADD COLUMN reporting_period_to DATE") connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (KS2_REPORTING_PERIOD_MIGRATION, datetime.now(timezone.utc).isoformat())) if PAYMENT_STATUS_MIGRATION not in applied: payment_cols = {row[1] for row in connection.execute("PRAGMA table_info(payments)")} if "status" not in payment_cols: connection.execute("ALTER TABLE payments ADD COLUMN status VARCHAR NOT NULL DEFAULT 'active'") connection.execute("CREATE INDEX IF NOT EXISTS ix_payments_status ON payments (status)") connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (PAYMENT_STATUS_MIGRATION, datetime.now(timezone.utc).isoformat())) violations = connection.execute("PRAGMA foreign_key_check").fetchall() if violations: raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}") connection.commit() except Exception: connection.rollback() raise finally: connection.execute("PRAGMA foreign_keys=ON") connection.close()