|
| 1 | +/** |
| 2 | + * Real-Postgres gate for #258 — "adopting a database whose PRIMARY KEY differs |
| 3 | + * from the metadata identity." |
| 4 | + * |
| 5 | + * Root cause: the diff/emit has no primary-key change kind, so a table whose live |
| 6 | + * PK moved (e.g. live `PRIMARY KEY (user_id)`, metadata identity `id`) degrades |
| 7 | + * silently into an add-column `id` + drop-column `user_id`: the old PK column (and |
| 8 | + * its constraint) is dropped, the new column is never made PK, and the table is left |
| 9 | + * with NO primary key — so every foreign key that references it is rejected at apply |
| 10 | + * ("there is no unique constraint matching given keys for referenced table …"). |
| 11 | + * |
| 12 | + * The fix is DETECT-AND-REFUSE: migration generation compares the introspected PK to |
| 13 | + * the metadata identity and throws PrimaryKeyChangeError instead of emitting the |
| 14 | + * un-appliable SQL. This test proves the refusal fires against the REAL introspected |
| 15 | + * schema (a unit assertion on hand-built snapshots is not sufficient evidence that |
| 16 | + * introspection reads the live PK correctly) — and that WITHOUT the guard the diff |
| 17 | + * still produces the silent add/drop pair, so the guard is what closes the gap. |
| 18 | + * |
| 19 | + * Gated on MIGRATE_TS_PG_URL like every other pg integration test here; skips cleanly |
| 20 | + * when unset. |
| 21 | + */ |
| 22 | + |
| 23 | +import { test, expect, beforeAll, afterAll, describe } from "bun:test"; |
| 24 | +import { Pool } from "pg"; |
| 25 | +import { Kysely, PostgresDialect, sql } from "kysely"; |
| 26 | +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; |
| 27 | +import { buildExpectedSchema } from "../../src/expected-schema.js"; |
| 28 | +import { introspectPostgres } from "../../src/introspect/postgres.js"; |
| 29 | +import { diff } from "../../src/diff/index.js"; |
| 30 | +import { PrimaryKeyChangeError } from "../../src/errors.js"; |
| 31 | + |
| 32 | +const PG_URL = process.env["MIGRATE_TS_PG_URL"]; |
| 33 | +const realDescribe = PG_URL ? describe : describe.skip; |
| 34 | + |
| 35 | +// Metadata: user_profiles keyed on `id` (uuid). The LIVE table (raw SQL below) is |
| 36 | +// instead keyed on `user_id` — the PK MOVE the bug is about. |
| 37 | +const META = JSON.stringify({ |
| 38 | + "metadata.root": { |
| 39 | + package: "acme", |
| 40 | + children: [ |
| 41 | + { |
| 42 | + "object.entity": { |
| 43 | + name: "UserProfile", |
| 44 | + children: [ |
| 45 | + { "source.rdb": { "@table": "user_profiles" } }, |
| 46 | + { "field.uuid": { name: "id" } }, |
| 47 | + { "field.string": { name: "authUserId", "@required": true } }, |
| 48 | + { "identity.primary": { name: "pk", "@fields": ["id"] } }, |
| 49 | + ], |
| 50 | + }, |
| 51 | + }, |
| 52 | + ], |
| 53 | + }, |
| 54 | +}); |
| 55 | + |
| 56 | +let k: Kysely<Record<string, unknown>>; |
| 57 | +let pool: Pool; |
| 58 | + |
| 59 | +if (PG_URL) { |
| 60 | + beforeAll(() => { |
| 61 | + pool = new Pool({ connectionString: PG_URL }); |
| 62 | + k = new Kysely<Record<string, unknown>>({ dialect: new PostgresDialect({ pool }) }); |
| 63 | + }); |
| 64 | + afterAll(async () => { |
| 65 | + await cleanup(); |
| 66 | + await k.destroy(); |
| 67 | + }); |
| 68 | +} |
| 69 | + |
| 70 | +async function cleanup(): Promise<void> { |
| 71 | + await sql.raw(`DROP TABLE IF EXISTS "agent_configs" CASCADE`).execute(k); |
| 72 | + await sql.raw(`DROP TABLE IF EXISTS "user_profiles" CASCADE`).execute(k); |
| 73 | +} |
| 74 | + |
| 75 | +async function loadRoot(json: string) { |
| 76 | + return (await new MetaDataLoader().load([new InMemoryStringSource(json)])).root; |
| 77 | +} |
| 78 | + |
| 79 | +realDescribe("PG #258 — a live primary-key move is refused, not silently dropped", () => { |
| 80 | + test("adopting a DB whose PRIMARY KEY differs from the metadata identity refuses instead of losing the PK", async () => { |
| 81 | + await cleanup(); |
| 82 | + |
| 83 | + // LIVE schema: user_profiles keyed on user_id, with a second table whose FK |
| 84 | + // references it — the exact shape where a silent PK drop breaks the FK at apply. |
| 85 | + await sql |
| 86 | + .raw(`CREATE TABLE "user_profiles" ("user_id" bigint PRIMARY KEY, "auth_user_id" text NOT NULL)`) |
| 87 | + .execute(k); |
| 88 | + await sql |
| 89 | + .raw( |
| 90 | + `CREATE TABLE "agent_configs" ("id" bigint PRIMARY KEY, ` + |
| 91 | + `"created_by" bigint NOT NULL REFERENCES "user_profiles" ("user_id"))`, |
| 92 | + ) |
| 93 | + .execute(k); |
| 94 | + |
| 95 | + const root = await loadRoot(META); |
| 96 | + const expected = buildExpectedSchema(root, { dialect: "postgres" }); |
| 97 | + const actual = await introspectPostgres(k); |
| 98 | + |
| 99 | + // Introspection read the live PK as user_id (the premise of the whole bug). |
| 100 | + const liveUP = actual.tables.find((t) => t.name === "user_profiles"); |
| 101 | + expect(liveUP?.primaryKey).toEqual(["user_id"]); |
| 102 | + |
| 103 | + // WITHOUT the guard: the diff silently degrades into add-column id + drop-column |
| 104 | + // user_id — the PK is dropped and never re-added (the un-appliable migration). |
| 105 | + const unsafe = await diff({ expected, actual, dialect: "postgres", allow: { dropColumn: true } }); |
| 106 | + expect(unsafe.changes.some((c) => c.kind === "add-column" && c.column.name === "id")).toBe(true); |
| 107 | + expect(unsafe.changes.some((c) => c.kind === "drop-column" && c.column === "user_id")).toBe(true); |
| 108 | + |
| 109 | + // WITH the guard (migration generation): refuse loudly, so no bad SQL is emitted. |
| 110 | + let refused: unknown; |
| 111 | + try { |
| 112 | + await diff({ expected, actual, dialect: "postgres", refusePrimaryKeyChange: true, allow: { dropColumn: true } }); |
| 113 | + } catch (e) { |
| 114 | + refused = e; |
| 115 | + } |
| 116 | + expect(refused).toBeInstanceOf(PrimaryKeyChangeError); |
| 117 | + const err = refused as PrimaryKeyChangeError; |
| 118 | + expect(err.table).toBe("user_profiles"); |
| 119 | + expect(err.livePrimaryKey).toEqual(["user_id"]); |
| 120 | + expect(err.expectedPrimaryKey).toEqual(["id"]); |
| 121 | + }); |
| 122 | +}); |
0 commit comments