Keep the message and idempotency receipt in one Core CTE statement with chat-first locking. Preserve rollback, bounded dependency failures, and domain ports. Replace the SQL runner with Alembic. Adopt legacy databases only after validating their journal and PostgreSQL schema, retain all data, and verify migrations on fresh and populated databases.
87 lines
3.9 KiB
Python
87 lines
3.9 KiB
Python
from uuid import uuid4
|
|
|
|
from alembic.migration import MigrationContext
|
|
from alembic.operations import Operations
|
|
from alembic.script import ScriptDirectory
|
|
from sqlalchemy import Connection, MetaData, Table, func, inspect, select, text
|
|
from sqlalchemy.schema import CreateSchema
|
|
|
|
LEGACY = {
|
|
"0001_init": "9a13618f078ae9056431391e2e5197a31b981ae1fff047a9b3421ac750d3fd0d",
|
|
"0002_idempotency_keys": "d9159a35553249a1e51af5f2e4e7c39b014e97593c49748e13f3799839063dd0",
|
|
}
|
|
SNAPSHOT = text("""
|
|
WITH relations AS (
|
|
SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
WHERE n.nspname = :schema AND c.relkind IN ('r', 'p')
|
|
AND c.relname NOT IN ('schema_migrations', 'alembic_version')
|
|
)
|
|
SELECT 'table' AS kind, c.relname AS name,
|
|
concat_ws('|', c.relkind, c.relrowsecurity, c.relforcerowsecurity) AS definition
|
|
FROM relations c
|
|
UNION ALL
|
|
SELECT 'column', c.relname || '.' || a.attname,
|
|
concat_ws('|', a.attnum, format_type(a.atttypid, a.atttypmod), a.attnotnull,
|
|
a.attidentity, a.attgenerated, pg_get_expr(d.adbin, d.adrelid))
|
|
FROM relations c JOIN pg_attribute a ON a.attrelid = c.oid
|
|
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
|
|
WHERE a.attnum > 0 AND NOT a.attisdropped
|
|
UNION ALL
|
|
SELECT 'constraint', c.relname || '.' || k.conname,
|
|
concat_ws('|', pg_get_constraintdef(k.oid), k.convalidated)
|
|
FROM relations c JOIN pg_constraint k ON k.conrelid = c.oid
|
|
UNION ALL
|
|
SELECT 'index', c.relname || '.' || x.relname,
|
|
concat_ws('|', pg_get_indexdef(i.indexrelid), i.indisvalid, i.indisready)
|
|
FROM relations c JOIN pg_index i ON i.indrelid = c.oid
|
|
JOIN pg_class x ON x.oid = i.indexrelid
|
|
UNION ALL
|
|
SELECT 'trigger', c.relname || '.' || t.tgname,
|
|
concat_ws('|', pg_get_triggerdef(t.oid), t.tgenabled)
|
|
FROM relations c JOIN pg_trigger t ON t.tgrelid = c.oid WHERE NOT t.tgisinternal
|
|
ORDER BY kind, name
|
|
""")
|
|
|
|
|
|
def snapshot(connection: Connection, schema: str) -> list[tuple[str, str, str]]:
|
|
return [
|
|
(kind, name, definition.replace(f"{schema}.", ""))
|
|
for kind, name, definition in connection.execute(SNAPSHOT, {"schema": schema})
|
|
]
|
|
|
|
|
|
def adopt_legacy(connection: Connection, scripts: ScriptDirectory) -> None:
|
|
migration = MigrationContext.configure(connection)
|
|
if migration.get_current_heads():
|
|
return
|
|
tables = set(inspect(connection).get_table_names(schema="public"))
|
|
if tables <= {"alembic_version"}:
|
|
return
|
|
if "schema_migrations" not in tables:
|
|
raise RuntimeError("Existing schema has no legacy migration journal")
|
|
journal = Table("schema_migrations", MetaData(), schema="public", autoload_with=connection)
|
|
applied = dict(connection.execute(select(journal.c.version, journal.c.checksum)).tuples().all())
|
|
expected = dict(list(LEGACY.items())[: len(applied)])
|
|
if applied != expected:
|
|
raise RuntimeError("Unknown or changed legacy migrations")
|
|
if not applied:
|
|
if tables - {"schema_migrations", "alembic_version"}:
|
|
raise RuntimeError("Existing schema has an empty migration journal")
|
|
return
|
|
revision = list(expected)[-1]
|
|
actual = snapshot(connection, "public")
|
|
reference = f"alembic_verify_{uuid4().hex}"
|
|
savepoint = connection.begin_nested()
|
|
try:
|
|
connection.execute(CreateSchema(reference))
|
|
connection.execute(select(func.set_config("search_path", reference, True)))
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
for script in reversed(list(scripts.walk_revisions(base="base", head=revision))):
|
|
script.module.upgrade()
|
|
wanted = snapshot(connection, reference)
|
|
finally:
|
|
savepoint.rollback()
|
|
if actual != wanted:
|
|
raise RuntimeError("Legacy schema differs from the recorded migrations")
|
|
migration.stamp(scripts, revision)
|