114 lines
7.5 KiB
Python
114 lines
7.5 KiB
Python
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"
|
|
|
|
|
|
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()))
|
|
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()
|