viborm 1.3.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
- package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
- package/dist/{adapter-namespace-B8XWzCev.mjs → adapter-namespace-BLejG8FA.mjs} +2 -2
- package/dist/{adapter-namespace-B8XWzCev.mjs.map → adapter-namespace-BLejG8FA.mjs.map} +1 -1
- package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
- package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/{batch-refs-DoWlPD2h.mjs → batch-refs-BYCu1JnQ.mjs} +2 -2
- package/dist/{batch-refs-DoWlPD2h.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
- package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
- package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
- package/dist/builder-BS8EW4BQ.mjs +2 -0
- package/dist/builder-BS8EW4BQ.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
- package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
- package/dist/chain-D5J9hIw-.mjs +2 -0
- package/dist/chain-D5J9hIw-.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/client-Bhl2mWam.mjs +2 -0
- package/dist/client-Bhl2mWam.mjs.map +1 -0
- package/dist/{client-Df81J4oB.d.mts → client-BzgBm_86.d.mts} +4 -2
- package/dist/{client-q6ccRgdO.mjs → client-aU3YhZ6G.mjs} +16 -16
- package/dist/client-aU3YhZ6G.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
- package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/datetime-physical-codec-lX7IJBlz.mjs +2 -0
- package/dist/datetime-physical-codec-lX7IJBlz.mjs.map +1 -0
- package/dist/driver-CQQbCQh9.mjs +2 -0
- package/dist/{driver-Ddt147dK.mjs.map → driver-CQQbCQh9.mjs.map} +1 -1
- package/dist/{driver-D6_Ik58x.mjs → driver-u2qJicrE.mjs} +2 -2
- package/dist/{driver-D6_Ik58x.mjs.map → driver-u2qJicrE.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/{error-mapping-C9WgitPi.mjs → error-mapping-6op318w6.mjs} +2 -2
- package/dist/error-mapping-6op318w6.mjs.map +1 -0
- package/dist/every-CzF00eDV.mjs +2 -0
- package/dist/{every-dpzVDwzu.mjs.map → every-CzF00eDV.mjs.map} +1 -1
- package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
- package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.mjs.map} +1 -1
- package/dist/{geo-area-codec-CbkmFArQ.mjs → geo-area-codec-BmMmWgU_.mjs} +2 -2
- package/dist/{geo-area-codec-CbkmFArQ.mjs.map → geo-area-codec-BmMmWgU_.mjs.map} +1 -1
- package/dist/{geo-point-codec-DyEHMdJg.mjs → geo-point-codec-D95uXgDF.mjs} +2 -2
- package/dist/{geo-point-codec-DyEHMdJg.mjs.map → geo-point-codec-D95uXgDF.mjs.map} +1 -1
- package/dist/{hydration-C2uXmJy6.mjs → hydration-BflrXEIQ.mjs} +2 -2
- package/dist/{hydration-C2uXmJy6.mjs.map → hydration-BflrXEIQ.mjs.map} +1 -1
- package/dist/{identifier-conversion-C2pwwFOS.mjs → identifier-conversion-Dc0Rf4Gi.mjs} +2 -2
- package/dist/{identifier-conversion-C2pwwFOS.mjs.map → identifier-conversion-Dc0Rf4Gi.mjs.map} +1 -1
- package/dist/identity-CmRos0Yf.mjs +2 -0
- package/dist/identity-CmRos0Yf.mjs.map +1 -0
- package/dist/{index-D4O0Twvs.d.mts → index-B4IWFJfv.d.mts} +1304 -1056
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
- package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
- package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/{key-B7vuAYPG.mjs → key-B89Z4vxn.mjs} +2 -2
- package/dist/{key-B7vuAYPG.mjs.map → key-B89Z4vxn.mjs.map} +1 -1
- package/dist/{libsql-DUO6vHad.mjs → libsql-CrDXsfpL.mjs} +2 -2
- package/dist/{libsql-DUO6vHad.mjs.map → libsql-CrDXsfpL.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/{memory-BApsTkt1.mjs → memory-TXO4KgBy.mjs} +2 -2
- package/dist/{memory-BApsTkt1.mjs.map → memory-TXO4KgBy.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-D1GlcktG.mjs → mysql-C2vOPcuA.mjs} +2 -2
- package/dist/{mysql-D1GlcktG.mjs.map → mysql-C2vOPcuA.mjs.map} +1 -1
- package/dist/mysql-adapter-C5CMIYRS.mjs +2 -0
- package/dist/mysql-adapter-C5CMIYRS.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-BF7gr4_b.mjs +2 -0
- package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
- package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
- package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
- package/dist/{object-store-BN64q8Zn.d.mts → object-store-uRqi0URP.d.mts} +3 -3
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +26 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-CAOaNM4R.mjs → physical-uJfmo4-Z.mjs} +2 -2
- package/dist/{physical-CAOaNM4R.mjs.map → physical-uJfmo4-Z.mjs.map} +1 -1
- package/dist/{pinned-session-CjvR0Ge2.mjs → pinned-session-FYOFV_gB.mjs} +2 -2
- package/dist/{pinned-session-CjvR0Ge2.mjs.map → pinned-session-FYOFV_gB.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-8smxUOt9.d.mts → planner-SzkGh-3T.d.mts} +1 -1
- package/dist/{postgres-Be0jMJWI.mjs → postgres-BSmy1PYR.mjs} +2 -2
- package/dist/{postgres-Be0jMJWI.mjs.map → postgres-BSmy1PYR.mjs.map} +1 -1
- package/dist/postgres-adapter-B1RyJlWL.mjs +2 -0
- package/dist/postgres-adapter-B1RyJlWL.mjs.map +1 -0
- package/dist/postgres-adapter-BAqRfWl1.mjs +2 -0
- package/dist/postgres-adapter-BAqRfWl1.mjs.map +1 -0
- package/dist/postgres-result-BCUQf8b_.mjs +2 -0
- package/dist/{postgres-result-CYu1dyI_.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-Da00ilvv.mjs → provider-limits-V09frtmK.mjs} +2 -2
- package/dist/{provider-limits-Da00ilvv.mjs.map → provider-limits-V09frtmK.mjs.map} +1 -1
- package/dist/relation-bound-BrZLsSke.mjs +2 -0
- package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
- package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
- package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
- package/dist/result-shape-Fi1-Fvri.mjs +2 -0
- package/dist/result-shape-Fi1-Fvri.mjs.map +1 -0
- package/dist/{rows-JXjhWwyb.mjs → rows-BiaiswSV.mjs} +2 -2
- package/dist/{rows-JXjhWwyb.mjs.map → rows-BiaiswSV.mjs.map} +1 -1
- package/dist/{scalar-CqqZ6jWd.mjs → scalar-Cm7nMFmO.mjs} +2 -2
- package/dist/{scalar-CqqZ6jWd.mjs.map → scalar-Cm7nMFmO.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-introspection-B2Rvqgut.mjs → schema-introspection-C1-XrQP4.mjs} +2 -2
- package/dist/{schema-introspection-B2Rvqgut.mjs.map → schema-introspection-C1-XrQP4.mjs.map} +1 -1
- package/dist/{schema-Cv-hhpl5.mjs → schema-tGtziyCJ.mjs} +2 -2
- package/dist/{schema-Cv-hhpl5.mjs.map → schema-tGtziyCJ.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-BjT_fDbu.mjs +2 -0
- package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
- package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
- package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
- package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
- package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +3 -3
- package/dist/sql-BvHwL73I.mjs +2 -0
- package/dist/sql-BvHwL73I.mjs.map +1 -0
- package/dist/{sql-EsoN_7Et.d.mts → sql-Q_twK-wW.d.mts} +5 -0
- package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
- package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CoDeF2h2.mjs +2 -0
- package/dist/sqlite-adapter-CoDeF2h2.mjs.map +1 -0
- package/dist/{sqlite-utils-DIOll4P7.mjs → sqlite-utils-C0TyzOys.mjs} +2 -2
- package/dist/{sqlite-utils-DIOll4P7.mjs.map → sqlite-utils-C0TyzOys.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-mJt0RHHE.mjs → standard-sql-DmKF8msN.mjs} +2 -2
- package/dist/standard-sql-DmKF8msN.mjs.map +1 -0
- package/dist/{to-many-BSipkSbK.mjs → to-many-Btc9X5Ga.mjs} +2 -2
- package/dist/{to-many-BSipkSbK.mjs.map → to-many-Btc9X5Ga.mjs.map} +1 -1
- package/dist/transaction-operation-CU1zlxiG.mjs.map +1 -1
- package/dist/{utils-DjXObbUK.mjs → utils-DkAxKcDD.mjs} +2 -2
- package/dist/{utils-DjXObbUK.mjs.map → utils-DkAxKcDD.mjs.map} +1 -1
- package/dist/{v-CrJYqdzu.mjs → v-514RME2X.mjs} +2 -2
- package/dist/{v-CrJYqdzu.mjs.map → v-514RME2X.mjs.map} +1 -1
- package/dist/{validation-BQtO6srU.mjs → validation-C7Z6wTJa.mjs} +2 -2
- package/dist/{validation-BQtO6srU.mjs.map → validation-C7Z6wTJa.mjs.map} +1 -1
- package/dist/validation-gwZYm3Yn.mjs +2 -0
- package/dist/validation-gwZYm3Yn.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-BqzpyNmt.mjs → validator-CQOw7G3q.mjs} +2 -2
- package/dist/{validator-BqzpyNmt.mjs.map → validator-CQOw7G3q.mjs.map} +1 -1
- package/dist/version-n393hhwM.mjs +2 -0
- package/dist/{version-Dus3if78.mjs.map → version-n393hhwM.mjs.map} +1 -1
- package/package.json +14 -14
- package/dist/bind-parameter-capacity-qfEejeOX.mjs +0 -2
- package/dist/bind-parameter-capacity-qfEejeOX.mjs.map +0 -1
- package/dist/builder-DhxaVYP2.mjs +0 -2
- package/dist/builder-DhxaVYP2.mjs.map +0 -1
- package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
- package/dist/chain-BjJ_M7EE.mjs +0 -2
- package/dist/chain-BjJ_M7EE.mjs.map +0 -1
- package/dist/client-BCgMXn6N.mjs +0 -2
- package/dist/client-BCgMXn6N.mjs.map +0 -1
- package/dist/client-q6ccRgdO.mjs.map +0 -1
- package/dist/datetime-physical-codec-BEqQbIP_.mjs +0 -2
- package/dist/datetime-physical-codec-BEqQbIP_.mjs.map +0 -1
- package/dist/driver-Ddt147dK.mjs +0 -2
- package/dist/error-mapping-C9WgitPi.mjs.map +0 -1
- package/dist/every-dpzVDwzu.mjs +0 -2
- package/dist/identity-Bj2EN6Ss.mjs +0 -2
- package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
- package/dist/mysql-adapter-ClOoHKpn.mjs +0 -2
- package/dist/mysql-adapter-ClOoHKpn.mjs.map +0 -1
- package/dist/postgres-adapter-BoQ4RRwr.mjs +0 -2
- package/dist/postgres-adapter-BoQ4RRwr.mjs.map +0 -1
- package/dist/postgres-adapter-C_Mt8lVC.mjs +0 -2
- package/dist/postgres-adapter-C_Mt8lVC.mjs.map +0 -1
- package/dist/postgres-result-CYu1dyI_.mjs +0 -2
- package/dist/result-shape-DQc-tDJ5.mjs +0 -2
- package/dist/result-shape-DQc-tDJ5.mjs.map +0 -1
- package/dist/select-assembly-BxtETbG9.mjs +0 -2
- package/dist/select-assembly-BxtETbG9.mjs.map +0 -1
- package/dist/sql-Bhxq9arK.mjs +0 -2
- package/dist/sql-Bhxq9arK.mjs.map +0 -1
- package/dist/sqlite-adapter-B_LNxPA0.mjs +0 -2
- package/dist/sqlite-adapter-B_LNxPA0.mjs.map +0 -1
- package/dist/standard-sql-mJt0RHHE.mjs.map +0 -1
- package/dist/validation-BamBwne9.mjs +0 -2
- package/dist/validation-BamBwne9.mjs.map +0 -1
- package/dist/version-Dus3if78.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-Be0jMJWI.mjs","names":["elementType","quoted","column"],"sources":["../src/migrations/drivers/postgres/canonicalize-index-predicate.ts","../src/migrations/drivers/postgres/introspect.ts","../src/migrations/drivers/postgres/catalog-digest.ts","../src/migrations/drivers/postgres/index.ts"],"sourcesContent":["/**\n * Decision 7.4 — the declared partial-index predicate, canonicalized by the\n * database that will store it.\n *\n * PostgreSQL's catalog does not keep the statement it was given. `CREATE INDEX\n * … WHERE published = true` is parsed into a node tree, and\n * `pg_get_expr(indpred, indrelid)` deparses that tree back out as\n * `(published = true)`. The introspection reads the deparsed form; the\n * serializer holds the declared form; they never compare equal, so **every push\n * dropped and re-created every partial index**. SQLite has no such gap — it\n * stores the CREATE INDEX text verbatim — which is why only this dialect\n * implements the hook.\n *\n * The fix asks PostgreSQL itself. A predicate is put through the same parse and\n * deparse the catalog performs, and the differ compares the two answers. If\n * both texts deparse to one text they are one predicate; if either cannot be\n * deparsed, nothing is claimed and the drop/create stands. No client-side text\n * normalization can do this and stay fail-closed: flattening whitespace and\n * parentheses makes `a AND (b OR c)` read equal to `(a AND b) OR c`, and a real\n * predicate change would stop being seen.\n *\n * The vehicle is a scratch view: `SELECT 1 AS c FROM <table> WHERE <p>`, read\n * back with `pg_get_viewdef`. A view is the cheapest parse-and-store\n * PostgreSQL offers — no table scan, no data touched, only an ACCESS SHARE lock\n * on the table. A CHECK constraint or a real index would each parse the same\n * expression, but one locks the table against writers and the other builds\n * the index this is trying to avoid building.\n *\n * The view is a regular one, in the estate's own schema, created, read and\n * dropped in one transaction, so no other session ever sees it and nothing\n * outlives the transaction. PlanetScale's Neki has no temporary relations\n * (`NK013`), and its router resolves neither a `regclass` literal nor a\n * relation name for a relation created earlier in the transaction, so the\n * read finds the view through `pg_class`, by oid. Its name carries a random\n * part: two sessions canonicalizing one table at once never wait on each\n * other's uncommitted catalog row.\n *\n * Both sides of the comparison go through this same transform, so the answer\n * does not depend on `pg_get_viewdef` and `pg_get_expr` agreeing on\n * parenthesization — only on each being a function of the parsed tree.\n *\n * The predicate is interpolated, not bound: it is an expression, and no\n * parameter placeholder can carry one. It reaches here from the schema's own\n * `.index({ where })`, the same text the emitter already interpolates into\n * `CREATE INDEX`, so this widens nothing.\n */\n\nconst SCRATCH_VIEW_PREFIX = \"viborm_index_predicate_\";\nconst TRAILING_SEMICOLON = /;\\s*$/;\nconst UUID_DASHES = /-/g;\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/** Sends statements as ONE request, in one transaction, answering each. */\nexport type BatchExecutor = <T>(\n statements: readonly string[]\n) => Promise<ReadonlyArray<{ rows: T[] }>>;\n\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction quoteLiteral(text: string): string {\n return `'${text.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Deparses each predicate through PostgreSQL and returns the answers\n * positionally.\n *\n * `table` arrives ALREADY QUALIFIED and quoted by the bound migration driver,\n * and `namespace` is that estate's schema, where the scratch views live. A bare\n * table name would canonicalize this estate's predicate against a same-named\n * table in another schema on the session's `search_path` — and then hand that\n * answer to the differ as if it described the estate's own index.\n *\n * Throws rather than reporting a failure per predicate. The caller runs this\n * inside one transaction: a statement that fails aborts it, every later\n * statement in it fails too, and the rollback is what removes the scratch views\n * — which must go, because a view referencing a table blocks dropping that\n * table later in the same push.\n *\n * Each pass creates, reads and drops its views. `executeBatch`, on a transport\n * with no session (Neon HTTP, plan D7), sends each pass as one request: its\n * statements in one transaction, so on one backend, where separate requests\n * may each land on another.\n */\nexport async function canonicalizeIndexPredicates(\n namespace: string,\n table: string,\n predicates: readonly string[],\n executeRaw: RawExecutor,\n executeBatch?: BatchExecutor\n): Promise<ReadonlyArray<string | undefined>> {\n if (predicates.length === 0) return [];\n const run: BatchExecutor =\n executeBatch ??\n (async <T>(statements: readonly string[]) => {\n const results: { rows: T[] }[] = [];\n for (const sql of statements) results.push(await executeRaw<T>(sql));\n return results;\n });\n const deparse = async (queries: readonly (string | undefined)[]) => {\n // A position with no query has no answer, and no view.\n const live = [...queries.keys()].filter(\n (position) => queries[position] !== undefined\n );\n if (live.length === 0) return queries.map(() => undefined);\n const scratch = `${SCRATCH_VIEW_PREFIX}${crypto.randomUUID().replace(UUID_DASHES, \"\")}_`;\n const names = live.map((position) => `${scratch}${position}`);\n const views = names.map(\n (name) => `${quoteIdentifier(namespace)}.${quoteIdentifier(name)}`\n );\n const results = await run<{ name: string; definition: string | null }>([\n ...live.map(\n (position, index) =>\n `CREATE VIEW ${views[index]} AS ${queries[position]}`\n ),\n `SELECT c.relname AS name, pg_catalog.pg_get_viewdef(c.oid) AS definition FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${quoteLiteral(namespace)} AND c.relname IN (${names.map(quoteLiteral).join(\", \")})`,\n `DROP VIEW ${views.join(\", \")}`,\n ]);\n const answers = new Map(\n results[live.length]?.rows.map((row) => [row.name, row.definition])\n );\n return queries.map((query, position) =>\n query === undefined\n ? undefined\n : (answers.get(`${scratch}${position}`) ?? undefined)\n );\n };\n\n // Two passes: one parse and deparse is not a fixed point. PostgreSQL\n // expands BETWEEN after its grammar has flattened AND, so a declared\n // `a BETWEEN x AND y AND b` parses to a nested AND, which its own deparse\n // (the catalog's text) reparses flat. Parsing each answer once more gives\n // the declared and the catalog spelling the same tree.\n const once = await deparse(\n predicates.map(\n (predicate) => `SELECT 1 AS c FROM ${table} WHERE ${predicate}`\n )\n );\n return deparse(once.map((query) => query?.replace(TRAILING_SEMICOLON, \"\")));\n}\n","/**\n * PostgreSQL Schema Introspection\n *\n * Reads the current database schema from PostgreSQL's information_schema\n * and system catalogs, returning a normalized SchemaSnapshot.\n *\n * Every catalog query is NAMESPACE-RELATIVE: the selected schema arrives as a\n * bound parameter (`$1`), never as a literal in a predicate and never as a\n * `public` fallback. The snapshot it produces stays namespace-RELATIVE in the\n * other direction — table, enum and type names are bare, exactly as the\n * serializer spells them — so one estate's snapshot never carries the schema\n * its DDL renderer qualifies with.\n */\n\nimport {\n canonicalizeDecimal,\n type DecimalDescriptor,\n decimalDefaultText,\n} from \"@validation/primitives/decimal-codec\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { readStoredDecimalDescriptor } from \"../../decimal\";\nimport type {\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport { groupBy, groupByNested, mapReferentialAction } from \"../utils\";\nimport { throwIfCatalogRefusal } from \"./catalog-refusal\";\n\nimport type {\n PgColumn,\n PgCrossSchemaForeignKey,\n PgEnum,\n PgForeignKey,\n PgIndex,\n PgPrimaryKey,\n PgTable,\n PgUniqueConstraint,\n} from \"./types\";\n\n// Regex for cleaning up PostgreSQL type casting (e.g., 'value'::text -> 'value')\nconst TYPE_CAST_REGEX =\n /::(?:\"(?:[^\"]|\"\")+\"|[a-zA-Z_][\\w$]*)(?:\\.(?:\"(?:[^\"]|\"\")+\"|[a-zA-Z_][\\w$]*))?(?:\\s+(?:varying|precision|with time zone|without time zone))?(?:\\(\\d+(?:,\\s*\\d+)?\\))?(?:\\[\\])?$/;\n\n/** The schemas PostgreSQL's own types live in; never estate-owned. */\nconst BUILT_IN_TYPE_SCHEMAS = new Set([\"pg_catalog\", \"information_schema\"]);\n\n/**\n * What one introspection run is bound to.\n *\n * `namespace` is the estate's schema, and `admittedExtensionTypes` is the set\n * of extension-owned base type names the CONCRETE adapter declares typmods\n * for (pgvector's `vector`, PostGIS's `geometry`/`geography`). An extension\n * type outside that set is still read — through `udt_name`, the way every\n * snapshot written before `format_type` was consulted holds it.\n */\nexport interface PostgresIntrospectionScope {\n readonly namespace: string;\n readonly tables?: readonly string[];\n readonly admittedExtensionTypes: ReadonlySet<string>;\n}\n\n/**\n * Extension-owned base types whose SERVER-FORMATTED spelling introspection\n * reads, keyed by the adapter capability that declares them.\n *\n * These are the types whose modifiers a snapshot cannot be written without\n * (`vector(3)`, `geometry(Point,4326)`), so introspection reads\n * `format_type` for them instead of `udt_name`. The set admits a SPELLING,\n * never a type: an extension type outside it — `citext`, and anything else a\n * database has installed — reads back through `udt_name` like every built-in,\n * which is the spelling this driver's own renderer emits for it.\n */\nconst EXTENSION_TYPES_BY_CAPABILITY = {\n supportsVector: [\"vector\", \"halfvec\", \"sparsevec\"],\n geoPoint: [\"geometry\", \"geography\"],\n} as const;\n\n/**\n * The extension-owned base types the bound execution driver's adapter\n * declares, and whose `format_type` spelling introspection therefore reads.\n */\nexport function admittedExtensionTypes(\n executionDriver: AnyDriver | undefined\n): ReadonlySet<string> {\n const adapter = executionDriver?.adapter;\n return new Set([\n ...(adapter?.capabilities.supportsVector\n ? EXTENSION_TYPES_BY_CAPABILITY.supportsVector\n : []),\n ...(adapter?.geoPoint ? EXTENSION_TYPES_BY_CAPABILITY.geoPoint : []),\n ]);\n}\n\n/** An index row, with the validity an interrupted CONCURRENTLY build clears. */\ntype PgIndexRow = PgIndex & { readonly is_valid: boolean };\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n// =============================================================================\n// SQL QUERIES\n// =============================================================================\n\nexport const POSTGRES_MANAGED_TABLE_NAMES_SOURCE = `\nSELECT tables.table_name, tables.table_name AS name, relation.relkind AS relation_kind, relation.relispartition AS is_partition\nFROM information_schema.tables tables\nJOIN pg_catalog.pg_class relation\n ON relation.relname = tables.table_name\nJOIN pg_catalog.pg_namespace relation_namespace\n ON relation_namespace.oid = relation.relnamespace\n AND relation_namespace.nspname = tables.table_schema\nWHERE tables.table_schema = $1\n AND tables.table_type = 'BASE TABLE'\n AND NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend dependency\n JOIN pg_catalog.pg_extension extension\n ON extension.oid = dependency.refobjid\n WHERE dependency.classid = 'pg_catalog.pg_class'::pg_catalog.regclass\n AND dependency.objid = relation.oid\n AND dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND dependency.deptype = 'e'\n )\n`;\nexport const POSTGRES_MANAGED_TABLE_NAMES_QUERY = `${POSTGRES_MANAGED_TABLE_NAMES_SOURCE}ORDER BY tables.table_name;\n`;\n\n/**\n * Columns, with the type identity the snapshot cannot be built without.\n *\n * The catalog join beside `information_schema.columns` exists for two facts\n * that view cannot give: the server's formatted type (modifiers and array\n * structure) and the extension provenance that proves a non-estate type is a\n * provider object rather than an unknown external one. For an ARRAY column the\n * dependency is looked up on the ELEMENT type (`typcategory = 'A'`), because\n * the array type's own dependency is on its element, not on the extension.\n */\nexport const COLUMNS_SOURCE = `\nSELECT\n c.table_name,\n c.column_name,\n c.data_type,\n c.udt_schema,\n c.udt_name,\n c.is_nullable,\n c.column_default,\n a.attgenerated AS generated_kind,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n pg_catalog.format_type(a.atttypid, a.atttypmod) AS formatted_type,\n ext.extname AS type_extension,\n ext_ns.nspname AS type_extension_schema\nFROM information_schema.columns c\nJOIN information_schema.tables t\n ON c.table_name = t.table_name\n AND c.table_schema = t.table_schema\nJOIN pg_catalog.pg_class cls\n ON cls.relname = c.table_name\nJOIN pg_catalog.pg_namespace cls_ns\n ON cls_ns.oid = cls.relnamespace\n AND cls_ns.nspname = c.table_schema\nJOIN pg_catalog.pg_attribute a\n ON a.attrelid = cls.oid\n AND a.attname = c.column_name\nJOIN pg_catalog.pg_type col_type\n ON col_type.oid = a.atttypid\nLEFT JOIN pg_catalog.pg_depend dep\n ON dep.classid = 'pg_catalog.pg_type'::regclass\n AND dep.objid = CASE\n WHEN col_type.typcategory = 'A' THEN col_type.typelem\n ELSE col_type.oid\n END\n AND dep.deptype = 'e'\nLEFT JOIN pg_catalog.pg_extension ext\n ON ext.oid = dep.refobjid\nLEFT JOIN pg_catalog.pg_namespace ext_ns\n ON ext_ns.oid = ext.extnamespace\nWHERE c.table_schema = $1\n AND t.table_type = 'BASE TABLE'\n AND NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend relation_dependency\n JOIN pg_catalog.pg_extension relation_extension\n ON relation_extension.oid = relation_dependency.refobjid\n WHERE relation_dependency.classid = 'pg_catalog.pg_class'::pg_catalog.regclass\n AND relation_dependency.objid = cls.oid\n AND relation_dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND relation_dependency.deptype = 'e'\n )\n`;\nconst COLUMNS_QUERY = `${COLUMNS_SOURCE}ORDER BY c.table_name, c.ordinal_position;\n`;\n\nexport const PRIMARY_KEYS_SOURCE = `\nSELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\nWHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\n`;\nconst PRIMARY_KEYS_QUERY = `${PRIMARY_KEYS_SOURCE}ORDER BY tc.table_name, kcu.ordinal_position;\n`;\n\n/**\n * Standalone indexes. `conindid` names the index a UNIQUE or PRIMARY KEY\n * constraint owns — those stay in `uniqueConstraints` / `primaryKey`. A\n * foreign key also points `conindid` at the unique index it targets, so the\n * join must not treat that as ownership or a unique-index FK target vanishes\n * from both lists.\n *\n * `nullsNotDistinct` is the SQL that says whether a unique index takes NULLs\n * as equal, which no snapshot models: `ix.indnullsnotdistinct` where the\n * column exists ({@link NULLS_NOT_DISTINCT_QUERY}), `false` before PostgreSQL\n * 15. Never a whole-row read such as `to_jsonb(ix)`: PlanetScale's Neki\n * refuses a catalog relation's row type (0A000).\n */\nexport const indexesSource = (nullsNotDistinct: string): string => `\nSELECT\n t.relname AS table_name,\n i.relname AS index_name,\n a.attname AS column_name,\n ix.indisunique AS is_unique,\n ix.indisvalid AND ix.indisready AS is_valid,\n (ix.indexprs IS NOT NULL OR ix.indnkeyatts <> ix.indnatts OR ${nullsNotDistinct}\n OR EXISTS (SELECT 1 FROM unnest(ix.indoption) AS flags(value) WHERE flags.value <> 0)\n OR EXISTS (SELECT 1 FROM unnest(ix.indclass) AS classes(oid) JOIN pg_opclass AS opc ON opc.oid=classes.oid WHERE NOT opc.opcdefault)\n OR EXISTS (SELECT 1 FROM generate_series(0,ix.indnkeyatts-1) AS key(position) LEFT JOIN pg_attribute AS attr ON attr.attrelid=t.oid AND attr.attnum=ix.indkey[key.position] WHERE ix.indcollation[key.position] <> COALESCE(attr.attcollation,0))) AS unsupported_structure,\n am.amname AS index_type,\n pg_get_expr(ix.indpred, ix.indrelid) AS filter_condition,\n array_position(ix.indkey, a.attnum) AS ordinal_position\nFROM pg_index ix\nJOIN pg_class t ON t.oid = ix.indrelid\nJOIN pg_class i ON i.oid = ix.indexrelid\nJOIN pg_am am ON am.oid = i.relam\nJOIN pg_namespace n ON n.oid = t.relnamespace\nLEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)\nLEFT JOIN pg_constraint c\n ON c.conindid = ix.indexrelid\n AND c.contype IN ('u', 'p')\nWHERE n.nspname = $1\n AND NOT ix.indisprimary\n AND c.oid IS NULL\n AND t.relkind = 'r'\n`;\nconst INDEXES_ORDER = `ORDER BY t.relname, i.relname, array_position(ix.indkey, a.attnum);\n`;\n\n/** Whether this server's `pg_index` has `indnullsnotdistinct` (PostgreSQL 15+). */\nexport const NULLS_NOT_DISTINCT_QUERY = `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = 'pg_catalog.pg_index'::pg_catalog.regclass AND attname = 'indnullsnotdistinct' AND NOT attisdropped) AS present`;\n\n/**\n * Foreign keys OWNED by the selected schema.\n *\n * Read from `pg_constraint`, not `information_schema.referential_constraints`.\n * A foreign key may target a unique INDEX rather than a unique constraint;\n * that catalog view then leaves `unique_constraint_name` null and the join\n * drops the constraint. `pg_constraint.confrelid`/`confkey` still name the\n * referenced columns. Both sides stay in this schema so `referencedTable` is\n * a bare estate-relative name. A constraint that leaves the schema is not\n * silently dropped — `CROSS_SCHEMA_FOREIGN_KEYS_QUERY` inventories both\n * directions and refuses the whole run before this snapshot is published.\n */\nexport const FOREIGN_KEYS_SOURCE = `\nSELECT\n owner.relname AS table_name,\n con.conname AS constraint_name,\n local_att.attname AS column_name,\n referenced.relname AS foreign_table_name,\n referenced_att.attname AS foreign_column_name,\n CASE con.confdeltype\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'd' THEN 'SET DEFAULT'\n ELSE 'NO ACTION'\n END AS delete_rule,\n CASE con.confupdtype\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'd' THEN 'SET DEFAULT'\n ELSE 'NO ACTION'\n END AS update_rule,\n local.ordinality AS ordinal_position\nFROM pg_catalog.pg_constraint con\nJOIN pg_catalog.pg_class owner ON owner.oid = con.conrelid\nJOIN pg_catalog.pg_namespace owner_ns ON owner_ns.oid = owner.relnamespace\nJOIN pg_catalog.pg_class referenced ON referenced.oid = con.confrelid\nJOIN pg_catalog.pg_namespace referenced_ns ON referenced_ns.oid = referenced.relnamespace\nJOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS local(attnum, ordinality) ON TRUE\nJOIN LATERAL unnest(con.confkey) WITH ORDINALITY AS referenced_col(attnum, ordinality)\n ON referenced_col.ordinality = local.ordinality\nJOIN pg_catalog.pg_attribute local_att\n ON local_att.attrelid = owner.oid AND local_att.attnum = local.attnum\nJOIN pg_catalog.pg_attribute referenced_att\n ON referenced_att.attrelid = referenced.oid\n AND referenced_att.attnum = referenced_col.attnum\nWHERE con.contype = 'f'\n AND owner_ns.nspname = $1\n AND referenced_ns.nspname = $1\n`;\nconst FOREIGN_KEYS_QUERY = `${FOREIGN_KEYS_SOURCE}ORDER BY owner.relname, con.conname, local.ordinality;\n`;\n\n/**\n * Every foreign key with exactly ONE side in the selected schema.\n *\n * `pg_constraint` is joined to its owning and referenced relations through both\n * `pg_class`/`pg_namespace` pairs, so an INBOUND key — owned by a foreign\n * schema, pointing at an estate table — is found as readily as an outbound one.\n * The exclusive-or in the predicate is the whole test: a key with both sides in\n * the schema is ordinary, a key with neither belongs to somebody else.\n */\nexport const CROSS_SCHEMA_FOREIGN_KEYS_SOURCE = `\nSELECT\n con.conname AS constraint_name,\n owner_ns.nspname AS owning_schema,\n owner.relname AS owning_table,\n referenced_ns.nspname AS referenced_schema,\n referenced.relname AS referenced_table\nFROM pg_catalog.pg_constraint con\nJOIN pg_catalog.pg_class owner ON owner.oid = con.conrelid\nJOIN pg_catalog.pg_namespace owner_ns ON owner_ns.oid = owner.relnamespace\nJOIN pg_catalog.pg_class referenced ON referenced.oid = con.confrelid\nJOIN pg_catalog.pg_namespace referenced_ns ON referenced_ns.oid = referenced.relnamespace\nWHERE con.contype = 'f'\n AND (owner_ns.nspname = $1) <> (referenced_ns.nspname = $1)\n`;\nconst CROSS_SCHEMA_FOREIGN_KEYS_QUERY = `${CROSS_SCHEMA_FOREIGN_KEYS_SOURCE}ORDER BY owner_ns.nspname, owner.relname, con.conname;\n`;\n\nexport const UNIQUE_CONSTRAINTS_SOURCE = `\nSELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\nWHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\n`;\nconst UNIQUE_CONSTRAINTS_QUERY = `${UNIQUE_CONSTRAINTS_SOURCE}ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position;\n`;\n\nexport const ENUMS_SOURCE = `\nSELECT\n t.typname AS enum_name,\n e.enumlabel AS enum_value,\n e.enumsortorder AS sort_order\nFROM pg_type t\nJOIN pg_enum e ON t.oid = e.enumtypid\nJOIN pg_namespace n ON n.oid = t.typnamespace\nWHERE n.nspname = $1\n`;\nconst ENUMS_QUERY = `${ENUMS_SOURCE}ORDER BY t.typname, e.enumsortorder;\n`;\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\n/** The element type's name for an array type, else the name itself. */\nfunction baseTypeName(udtName: string): string {\n return udtName.startsWith(\"_\") ? udtName.slice(1) : udtName;\n}\n\n/**\n * The extension-owned type spelled the way this estate's DDL spells it.\n *\n * `format_type` qualifies the type when the extension's schema is not on the\n * session's `search_path` and leaves it bare when it is, so the same column\n * reads back two ways on two sessions. Removing exactly the PROVEN extension\n * schema — never a general prefix strip — makes the answer one, and keeps every\n * modifier and the array suffix the catalog supplied.\n */\nfunction stripExtensionSchema(formattedType: string, schema: string): string {\n for (const prefix of [`${schema}.`, `\"${schema.replaceAll('\"', '\"\"')}\".`]) {\n if (formattedType.startsWith(prefix)) {\n return formattedType.slice(prefix.length);\n }\n }\n return formattedType;\n}\n\n/**\n * The one unrepresentable class: a type of another schema that no installed\n * extension owns (§4.2's external enum, domain, composite or UDT).\n *\n * The refusal names both schemas in its MESSAGE. `meta` carries only keys the\n * error metadata allowlist admits (`src/errors/diagnostics.ts`), which has no\n * namespace key today, so the schema travels in the message rather than being\n * silently dropped from a metadata object that claims to carry it.\n */\nfunction refuseUnrepresentableType(\n col: PgColumn,\n scope: PostgresIntrospectionScope\n): never {\n throw new MigrationError(\n `Column \"${col.table_name}\".\"${col.column_name}\" has type \"${col.udt_schema}\".\"${baseTypeName(col.udt_name)}\", which lives in another schema and no installed extension owns it. ` +\n `VibORM manages one schema (\"${scope.namespace}\") and cannot represent that type in a snapshot or regenerate it as DDL.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: col.table_name,\n column: col.column_name,\n type: baseTypeName(col.udt_name),\n feature: \"external-type\",\n },\n }\n );\n}\n\n/**\n * The snapshot spelling of one column's type.\n *\n * Two readings, and a refusal for what neither can spell:\n *\n * 1. A provider object owned by an extension this adapter DECLARES keeps the\n * server's own formatted spelling, so its modifiers and array structure\n * survive the round trip (`vector(3)`, `geometry(Point,4326)`).\n * 2. Everything else keeps the `udt_name` reading every existing snapshot was\n * written with — built-ins, estate-owned types, AND an extension type\n * outside the two admitted capabilities. The capability decides which\n * SPELLING is read, never whether a type is representable: `citext` is a\n * shipped VibORM native type (`src/schema/scalars/native-types.ts`) that no\n * capability can admit, and `udt_name` spells it exactly as the desired\n * side does, so it round-trips. Refusing it would brick `introspect` and\n * `push` for an estate that used it.\n * 3. A type of ANOTHER schema that no extension owns is refused, because\n * nothing here can spell it: a snapshot carries bare names relative to the\n * estate, and re-rendering that name would create a same-named object in\n * the estate rather than reach the one the column actually has.\n */\nfunction formatColumnType(\n col: PgColumn,\n scope: PostgresIntrospectionScope\n): string {\n const extensionType = baseTypeName(col.udt_name);\n if (\n col.type_extension === \"postgis\" &&\n (extensionType === \"geometry\" || extensionType === \"geography\") &&\n !scope.admittedExtensionTypes.has(extensionType)\n ) {\n throw new MigrationError(\n `Column \"${col.table_name}\".\"${col.column_name}\" uses PostGIS ${extensionType}, but this PostgreSQL adapter has no GeoPoint protocol. ` +\n \"Migration introspection refuses to erase its subtype and SRID into a bare extension type; construct the driver with `postgis: true` or use a client that does not manage this estate.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"postgresql\",\n table: col.table_name,\n column: col.column_name,\n type: extensionType,\n feature: \"GeoPoint\",\n },\n }\n );\n }\n if (\n col.type_extension !== null &&\n col.type_extension_schema !== null &&\n scope.admittedExtensionTypes.has(extensionType)\n ) {\n return stripExtensionSchema(col.formatted_type, col.type_extension_schema);\n }\n\n // `type_extension === null` is what keeps an extension type installed\n // OUTSIDE the estate (the ordinary `CREATE EXTENSION citext` into `public`)\n // out of this refusal: the extension owns it, PostgreSQL resolves it for the\n // unqualified type token the renderer emits, and `udt_name` spells it.\n if (\n col.type_extension === null &&\n col.udt_schema !== scope.namespace &&\n !BUILT_IN_TYPE_SCHEMAS.has(col.udt_schema)\n ) {\n refuseUnrepresentableType(col, scope);\n }\n\n const elementType = baseTypeName(col.udt_name);\n const snapshotType = col.udt_name.startsWith(\"_\")\n ? `${elementType}[]`\n : elementType;\n\n // The server's formatted built-in type retains every typmod, including\n // precision on timestamp/time, bit widths and array element modifiers.\n if (BUILT_IN_TYPE_SCHEMAS.has(col.udt_schema)) {\n return col.formatted_type;\n }\n\n return snapshotType;\n}\n\n/** `numeric[]`'s `udt_name`; PostgreSQL prefixes an array type with `_`. */\nconst NUMERIC_ARRAY_UDT = \"_numeric\";\n\n/**\n * The declared decimal domain of a PostgreSQL column, or `undefined`.\n *\n * PostgreSQL is the one dialect that needs no reserved carrier: the typmod IS\n * the descriptor, so it is read from the catalog rather than from anything\n * VibORM wrote. A scalar reports it through `information_schema`; an array\n * reports it only inside `format_type`, so the two are recovered from the two\n * places the server keeps them.\n *\n * An unconstrained `numeric` has no typmod and therefore no domain — which is\n * correct, and is what makes the differ plan the conversion to a declared one.\n */\nfunction readDecimalDomain(col: PgColumn): DecimalDescriptor | undefined {\n if (col.data_type === \"numeric\" && col.numeric_precision !== null) {\n return requireDecimalDomain(\n col,\n col.numeric_precision,\n col.numeric_scale ?? 0\n );\n }\n if (col.udt_name !== NUMERIC_ARRAY_UDT) return undefined;\n const match = NUMERIC_ARRAY_TYPMOD.exec(col.formatted_type);\n if (!match) return undefined;\n return requireDecimalDomain(col, match[1], match[2]);\n}\n\nconst NUMERIC_ARRAY_TYPMOD = /^numeric\\((-?\\d+),(-?\\d+)\\)\\[\\]$/;\n\nfunction requireDecimalDomain(\n col: PgColumn,\n precision: unknown,\n scale: unknown\n): DecimalDescriptor {\n const descriptor = readStoredDecimalDescriptor(precision, scale, \"pg\");\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n `PostgreSQL reported column \"${col.table_name}\".\"${col.column_name}\" as NUMERIC(${String(precision)},${String(scale)}), outside VibORM's fixed-decimal domain. Migration introspection is refused rather than publishing an invalid descriptor.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"postgresql\",\n table: col.table_name,\n column: col.column_name,\n type: \"invalid-catalog-decimal-domain\",\n },\n }\n );\n}\n\nfunction isAutoIncrement(columnDefault: string | null): boolean {\n if (!columnDefault) return false;\n return (\n columnDefault.includes(\"nextval(\") ||\n columnDefault.includes(\"_seq'::regclass)\")\n );\n}\n\n/**\n * Every spelling PostgreSQL can give the terminal cast onto ONE named type.\n *\n * The server renders a default expression through `pg_get_expr`, which\n * qualifies the type only when the type's schema is off the session's\n * `search_path` and quotes an identifier only when the identifier needs it.\n * Both facts are session state, so the same column reads back as\n * `'active'::billing.state` on one connection and `'active'::state` on another,\n * and either half may be quoted. The set is enumerated rather than matched by\n * pattern because it must name THIS column's type exactly: a regex loose enough\n * to cover the spellings is also loose enough to eat an unrelated cast.\n */\nfunction terminalCastSpellings(schema: string, typeName: string): string[] {\n const quoted = (name: string) => `\"${name.replaceAll('\"', '\"\"')}\"`;\n const qualifiers = [\"\", `${schema}.`, `${quoted(schema)}.`];\n const names = [typeName, quoted(typeName)];\n const spellings: string[] = [];\n for (const qualifier of qualifiers) {\n for (const name of names) {\n for (const array of [\"\", \"[]\"]) {\n spellings.push(`::${qualifier}${name}${array}`);\n }\n }\n }\n // Longest first: `::billing.state[]` must not be half-stripped by `::state`.\n return spellings.sort((left, right) => right.length - left.length);\n}\n\n/**\n * Removes the cast that names this column's own managed enum type, if the\n * default ends with one.\n *\n * §4.3: the strip is keyed on the column's catalog-proven `udt_schema` /\n * `udt_name` and on that name being an enum this estate manages — never on the\n * text alone. A default casting to a built-in, an extension type, a domain or a\n * composite therefore reaches the generic strip below unchanged, which is what\n * keeps every already-converged column byte-identical.\n */\nfunction stripManagedEnumCast(\n columnDefault: string,\n col: PgColumn,\n scope: PostgresIntrospectionScope,\n managedEnums: ReadonlySet<string>\n): string {\n const enumName = baseTypeName(col.udt_name);\n if (col.udt_schema !== scope.namespace || !managedEnums.has(enumName)) {\n return columnDefault;\n }\n for (const cast of terminalCastSpellings(col.udt_schema, enumName)) {\n if (columnDefault.endsWith(cast)) {\n return columnDefault.slice(0, -cast.length);\n }\n }\n return columnDefault;\n}\n\nfunction cleanDefault(\n col: PgColumn,\n scope: PostgresIntrospectionScope,\n managedEnums: ReadonlySet<string>\n): string | undefined {\n const columnDefault = col.column_default;\n if (!columnDefault) return undefined;\n\n // Skip auto-increment defaults\n if (isAutoIncrement(columnDefault)) return undefined;\n\n // Clean up type casting (e.g., 'value'::text -> 'value')\n const withoutEnumCast = stripManagedEnumCast(\n columnDefault,\n col,\n scope,\n managedEnums\n );\n const cleaned = withoutEnumCast.replace(TYPE_CAST_REGEX, \"\").trim();\n return renderDecimalDefault(cleaned, readDecimalDomain(col));\n}\n\n/**\n * Re-renders a decimal column's default through the codec, so both snapshot\n * sides hold the SAME of the two renderings.\n *\n * PostgreSQL deparses a decimal default in two spellings and the difference is\n * the sign: `DEFAULT 12.34000` comes back as the bare literal, while\n * `DEFAULT -12.34000` comes back as `'-12.34000'::numeric`, because the minus\n * is a unary operator over a constant and the folded result is spelled as a\n * cast literal. (Measured on PGlite 0.3.) Stripping the cast leaves the quotes\n * behind, so the negative default would never equal the one the serializer\n * emits and the estate would churn forever.\n *\n * Sending it back through `decimalDefaultText` settles both spellings at once:\n * the quotes are dropped by the grammar and the fraction is padded to the\n * scale, which is exactly what the serializer emitted. Anything that is not a\n * decimal literal — a function call, `NULL`, an array literal — is not a value\n * this rendering describes and passes through untouched.\n */\nfunction renderDecimalDefault(\n cleaned: string,\n descriptor: DecimalDescriptor | undefined\n): string {\n if (descriptor === undefined) return cleaned;\n const unquoted =\n cleaned.startsWith(\"'\") && cleaned.endsWith(\"'\") && cleaned.length > 1\n ? cleaned.slice(1, -1)\n : cleaned;\n const canonical = canonicalizeDecimal(unquoted);\n if (canonical === undefined) return cleaned;\n return decimalDefaultText(\"pg\", canonical, descriptor);\n}\n\n/**\n * Refuses a foreign key that crosses the estate boundary, in either direction.\n *\n * This runs BEFORE the snapshot is returned, so push, public introspection and\n * every reset path that inventories objects refuse before planning a single\n * operation — an outbound reference would otherwise be silently dropped from\n * the snapshot (the owned-key query only sees same-schema pairs) and an inbound\n * one would turn a later table drop into somebody else's broken constraint.\n */\nfunction assertNoCrossSchemaForeignKeys(\n crossing: readonly PgCrossSchemaForeignKey[],\n scope: PostgresIntrospectionScope\n): void {\n const first = crossing.find(\n (fk) =>\n scope.tables === undefined ||\n (fk.owning_schema === scope.namespace &&\n scope.tables.includes(fk.owning_table)) ||\n (fk.referenced_schema === scope.namespace &&\n scope.tables.includes(fk.referenced_table))\n );\n if (!first) return;\n\n const direction = first.owning_schema === scope.namespace ? \"out of\" : \"into\";\n throw new MigrationError(\n `Foreign key \"${first.constraint_name}\" points ${direction} the migration estate: ` +\n `\"${first.owning_schema}\".\"${first.owning_table}\" references \"${first.referenced_schema}\".\"${first.referenced_table}\". ` +\n `VibORM manages one schema (\"${scope.namespace}\") per estate, so a constraint with one side outside it is an unsupported migration topology` +\n (crossing.length > 1 ? ` (${crossing.length} such constraints).` : \".\"),\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n // Both schemas are in the message: the metadata allowlist admits no\n // namespace key, and a refusal that cannot say which boundary was\n // crossed is not actionable.\n meta: {\n constraint: first.constraint_name,\n table: first.owning_table,\n relation: first.referenced_table,\n feature: \"cross-schema-foreign-key\",\n },\n }\n );\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspectPostgresSchema(\n executeRaw: RawExecutor,\n scope: PostgresIntrospectionScope\n): Promise<SchemaSnapshot> {\n const namespace = [scope.namespace];\n\n // One after another: `push` runs these on its ONE pinned session, and a\n // connection runs one statement at a time. Overlapping them only queued\n // them inside the provider, which node-postgres warns it will refuse in\n // pg@9. Each is a short catalog read, named when the provider refuses it.\n const read = async <T>(\n query: string,\n sql: string,\n parameters: unknown[] = namespace\n ) => {\n try {\n return await executeRaw<T>(sql, parameters);\n } catch (error) {\n throwIfCatalogRefusal(query, error);\n throw error;\n }\n };\n const tablesResult = await read<PgTable>(\n \"tables\",\n POSTGRES_MANAGED_TABLE_NAMES_QUERY\n );\n const columnsResult = await read<PgColumn>(\"columns\", COLUMNS_QUERY);\n const primaryKeysResult = await read<PgPrimaryKey>(\n \"primary keys\",\n PRIMARY_KEYS_QUERY\n );\n const columnProbe = await read<{ present: boolean }>(\n \"nulls not distinct\",\n NULLS_NOT_DISTINCT_QUERY,\n []\n );\n const nullsNotDistinct =\n columnProbe.rows[0]?.present === true ? \"ix.indnullsnotdistinct\" : \"false\";\n const indexesResult = await read<PgIndexRow>(\n \"indexes\",\n `${indexesSource(nullsNotDistinct)}${INDEXES_ORDER}`\n );\n const foreignKeysResult = await read<PgForeignKey>(\n \"foreign keys\",\n FOREIGN_KEYS_QUERY\n );\n const crossSchemaForeignKeysResult = await read<PgCrossSchemaForeignKey>(\n \"cross-schema foreign keys\",\n CROSS_SCHEMA_FOREIGN_KEYS_QUERY\n );\n const uniqueConstraintsResult = await read<PgUniqueConstraint>(\n \"unique constraints\",\n UNIQUE_CONSTRAINTS_QUERY\n );\n const enumsResult = await read<PgEnum>(\"enums\", ENUMS_QUERY);\n\n assertNoCrossSchemaForeignKeys(crossSchemaForeignKeysResult.rows, scope);\n\n // Group results using helper functions\n const columnsByTable = groupBy(columnsResult.rows, (col) => col.table_name);\n const pkByTable = groupBy(primaryKeysResult.rows, (pk) => pk.table_name);\n const indexesByTable = groupByNested(\n indexesResult.rows,\n (idx) => idx.table_name,\n (idx) => idx.index_name\n );\n const fkByTable = groupByNested(\n foreignKeysResult.rows,\n (fk) => fk.table_name,\n (fk) => fk.constraint_name\n );\n const uniqueByTable = groupByNested(\n uniqueConstraintsResult.rows,\n (uq) => uq.table_name,\n (uq) => uq.constraint_name\n );\n const enumsByName = groupBy(enumsResult.rows, (e) => e.enum_name);\n const managedEnums = new Set(enumsByName.keys());\n\n // Build tables\n const tables: TableDef[] = [];\n\n for (const table of tablesResult.rows) {\n const tableName = table.table_name;\n\n const selected =\n scope.tables === undefined || scope.tables.includes(tableName);\n if (\n selected &&\n (table.relation_kind === \"p\" || table.is_partition === true)\n )\n throw new MigrationError(\n `PostgreSQL table \"${tableName}\" is partitioned or a partition. Synchronization refuses before effects because its physical definition cannot be represented.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"partitioned table\" } }\n );\n const generated = (columnsByTable.get(tableName) ?? []).find(\n (column) =>\n column.generated_kind !== undefined && column.generated_kind !== \"\"\n );\n if (selected && generated)\n throw new MigrationError(\n `PostgreSQL column \"${tableName}.${generated.column_name}\" is generated. Synchronization refuses before effects because its expression cannot be represented.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: tableName,\n column: generated.column_name,\n feature: \"generated column\",\n },\n }\n );\n\n // Build columns\n const columns = (columnsByTable.get(tableName) || []).map((col) => ({\n name: col.column_name,\n type:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? col.udt_name.startsWith(\"_\")\n ? `${baseTypeName(col.udt_name)}[]`\n : col.udt_name\n : formatColumnType(col, scope),\n nullable: col.is_nullable === \"YES\",\n default:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? undefined\n : cleanDefault(col, scope, managedEnums),\n autoIncrement: isAutoIncrement(col.column_default),\n decimal:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? undefined\n : readDecimalDomain(col),\n }));\n\n // Build primary key\n let primaryKey: PrimaryKeyDef | undefined;\n const pkCols = pkByTable.get(tableName);\n if (pkCols && pkCols.length > 0) {\n pkCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstPk = pkCols[0];\n if (firstPk) {\n primaryKey = {\n columns: pkCols.map((pk) => pk.column_name),\n name: firstPk.constraint_name,\n };\n }\n }\n\n // Build indexes\n const indexes: IndexDef[] = [];\n const tableIndexes = indexesByTable.get(tableName);\n if (tableIndexes) {\n for (const [indexName, indexCols] of tableIndexes) {\n indexCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstCol = indexCols[0];\n if (firstCol) {\n const method = firstCol.index_type;\n const managed =\n scope.tables === undefined || scope.tables.includes(tableName);\n // `=== false` is not fail-open: is_valid is a NOT NULL boolean, and\n // a transport returning non-booleans fails unsupported_structure.\n if (managed && firstCol.is_valid === false) {\n throw new MigrationError(\n `PostgreSQL index \"${tableName}.${indexName}\" is INVALID: a CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY build of it was interrupted or is still running, and PostgreSQL never reads through it. status() lists it; resolve() repairs it when the unfinished migration attempt's own CONCURRENTLY statement named it, otherwise drop it with DROP INDEX CONCURRENTLY or rebuild it with REINDEX INDEX CONCURRENTLY.`,\n VibORMErrorCode.MIGRATION_INVALID_INDEX,\n { meta: { table: tableName, indexName } }\n );\n }\n if (\n managed &&\n (firstCol.unsupported_structure !== false ||\n (method !== \"btree\" &&\n method !== \"hash\" &&\n method !== \"gin\" &&\n method !== \"gist\"))\n ) {\n throw new MigrationError(\n `PostgreSQL index \"${tableName}.${indexName}\" has physical method/order/expression/include/opclass/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves the index. Manage its table outside this synchronization scope until a faithful declaration is available.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: tableName, indexName } }\n );\n }\n if (\n method !== \"btree\" &&\n method !== \"hash\" &&\n method !== \"gin\" &&\n method !== \"gist\"\n )\n continue;\n if (indexCols.some((column) => column.column_name === null)) continue;\n indexes.push({\n name: indexName,\n columns: indexCols.flatMap((idx) =>\n idx.column_name === null ? [] : [idx.column_name]\n ),\n unique: firstCol.is_unique,\n type: method,\n where: firstCol.filter_condition || undefined,\n });\n }\n }\n }\n\n // Build foreign keys\n const foreignKeys: ForeignKeyDef[] = [];\n const tableFks = fkByTable.get(tableName);\n if (tableFks) {\n for (const [constraintName, fkCols] of tableFks) {\n fkCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstFk = fkCols[0];\n if (firstFk) {\n foreignKeys.push({\n name: constraintName,\n columns: fkCols.map((fk) => fk.column_name),\n referencedTable: firstFk.foreign_table_name,\n referencedColumns: fkCols.map((fk) => fk.foreign_column_name),\n onDelete: mapReferentialAction(firstFk.delete_rule),\n onUpdate: mapReferentialAction(firstFk.update_rule),\n });\n }\n }\n }\n\n // Build unique constraints\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const tableUniques = uniqueByTable.get(tableName);\n if (tableUniques) {\n for (const [constraintName, uqCols] of tableUniques) {\n uqCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n uniqueConstraints.push({\n name: constraintName,\n columns: uqCols.map((uq) => uq.column_name),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // Build enums\n const enums: EnumDef[] = [];\n for (const [enumName, enumVals] of enumsByName) {\n enumVals.sort((a, b) => a.sort_order - b.sort_order);\n enums.push({\n name: enumName,\n values: enumVals.map((e) => e.enum_value),\n });\n }\n\n return {\n tables,\n enums: enums.length > 0 ? enums : undefined,\n };\n}\n","/**\n * Plan D5 (decision 7): the live managed schema's fingerprint, computed by\n * PostgreSQL in ONE statement instead of the namespace proof and the eight\n * catalog reads a full introspection sends.\n *\n * The digest is `fingerprintLive(introspectManaged(…))` reproduced, not\n * approximated. It reads the introspection's own catalog sources (their text\n * is shared with `introspect.ts`, never copied) and hashes the projection\n * `fingerprintSnapshot` hashes: `formatColumnType`, `cleanDefault` and\n * `normalizeDefault`, `normalizeType`, `canonicalUniqueEntities`, the\n * managed-table list `selectManagedSnapshot` applies (its tables and the\n * enums they use), the control tables left out, RFC 8785 bytes, the\n * snapshot hash domain.\n *\n * Where reproducing a fact exactly would need more than SQL can say, the\n * statement answers NULL instead of a digest, and the caller introspects as\n * before. That is every case the introspection or the managed-table list\n * refuses (its refusal is then raised with its own message), and:\n * - a partial index, whose predicate `fingerprintLive` canonicalizes through\n * a scratch view, which one SELECT cannot create — unless the caller asks\n * for predicates as deparsed (`$6`): the digest is then\n * `fingerprintSnapshot` of the introspection itself, each predicate as\n * `pg_get_expr` spells it, which the no-op compares with the spelling the\n * apply that wrote the marker recorded from its introspection;\n * - a default that is a temporal literal, a JSON literal other than `{}`,\n * `[]`, `null`, `true` or `false`, an array literal other than `{}`, a\n * `date_trunc(…)` clock, an exponent or more than 15 significant digits in\n * a floating-point literal, or more than two layers of parentheses;\n * - a type spelled with quotes or non-ASCII characters;\n * - a projection holding a character at or above U+E000, where PostgreSQL's\n * code-point order and JavaScript's UTF-16 order can disagree;\n * - a database whose encoding is not UTF-8;\n * - an index whose deparsed definition mentions NULLS NOT DISTINCT: one\n * statement cannot name `indnullsnotdistinct`, absent before PostgreSQL 15,\n * but through a whole-row read, which PlanetScale's Neki refuses.\n *\n * JavaScript's regular expressions are spelled for PostgreSQL's ARE in E''\n * strings, which mean the same thing whatever `standard_conforming_strings`\n * says. No expression here can raise: the statement runs inside the locked\n * migration transaction, where an error would abort it.\n */\n\nimport { arrayLiteralText } from \"../../../adapters/databases/postgres/array-literal\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { boundNamespace } from \"../../catalog-probes\";\nimport { HASH_DOMAIN, isSha256, type Sha256 } from \"../../identity\";\nimport type { BoundMigrationDriver } from \"..\";\nimport type { ControlTableNames } from \"../base\";\nimport {\n admittedExtensionTypes,\n COLUMNS_SOURCE,\n CROSS_SCHEMA_FOREIGN_KEYS_SOURCE,\n ENUMS_SOURCE,\n FOREIGN_KEYS_SOURCE,\n indexesSource,\n POSTGRES_MANAGED_TABLE_NAMES_SOURCE,\n PRIMARY_KEYS_SOURCE,\n UNIQUE_CONSTRAINTS_SOURCE,\n} from \"./introspect\";\n\n/** A regular expression or replacement as an E'' literal. */\nconst re = (text: string): string =>\n `E'${text.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"''\")}'`;\n\n/** JavaScript's `\\s`, which is also what `String#trim` removes. */\nconst WS =\n \"[\\\\t\\\\n\\\\v\\\\f\\\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]\";\n\nconst trim = (value: string): string =>\n `regexp_replace(${value}, ${re(`^${WS}+|${WS}+$`)}, '', 'g')`;\n\n/** `normalizeType`'s rewrites, in its order. */\nconst TYPE_REWRITES: readonly (readonly [string, string])[] = [\n [`${WS}+`, \" \"],\n [`${WS}*,${WS}*`, \",\"],\n [String.raw`${WS}+\\[\\]`, \"[]\"],\n [String.raw`\\ycharacter varying\\y`, \"varchar\"],\n [String.raw`\\ycharacter\\y`, \"char\"],\n [String.raw`\\ybit varying\\y`, \"varbit\"],\n [\n String.raw`\\ytimestamptz(\\([0-9]+\\))?`,\n String.raw`timestamp\\1 with time zone`,\n ],\n [String.raw`\\ytimetz(\\([0-9]+\\))?`, String.raw`time\\1 with time zone`],\n [\n String.raw`\\y(timestamp|time)(\\([0-9]+\\))? without time zone`,\n String.raw`\\1\\2`,\n ],\n [String.raw`\\yint4\\y`, \"integer\"],\n [String.raw`\\yint8\\y`, \"bigint\"],\n [String.raw`\\yint2\\y`, \"smallint\"],\n [String.raw`\\yfloat4\\y`, \"real\"],\n [String.raw`\\yfloat8\\y`, \"double precision\"],\n [String.raw`\\ybool\\y`, \"boolean\"],\n];\n\n/** `normalizeType` of a quote-free ASCII type. */\nconst normalizeType = (type: string): string =>\n TYPE_REWRITES.reduce(\n (text, [pattern, replacement]) =>\n `regexp_replace(${text}, ${re(pattern)}, ${re(replacement)}, 'g')`,\n `lower(${trim(type)} COLLATE \"C\")`\n );\n\nconst IDENTIFIER = `(?:\"(?:[^\"]|\"\")+\"|[a-zA-Z_][a-zA-Z0-9_$]*)`;\n/** `TYPE_CAST_REGEX` of `introspect.ts`. */\nconst TERMINAL_CAST = String.raw`::${IDENTIFIER}(?:\\.${IDENTIFIER})?(?:${WS}+(?:varying|precision|with time zone|without time zone))?(?:\\([0-9]+(?:,${WS}*[0-9]+)?\\))?(?:\\[\\])?$`;\n/** Quoted literals, blanked before parentheses are counted. */\nconst LITERALS = `'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"`;\nconst UTC_NOW = String.raw`^(?:now\\(\\) at time zone 'utc'|timezone\\(${WS}*'utc'${WS}*,${WS}*now\\(\\)${WS}*\\))$`;\nconst UTC_CURRENT_TIME = String.raw`^timezone\\(${WS}*'utc'${WS}*,${WS}*current_time(?:\\(3\\))?${WS}*\\)$`;\nconst NUMBER_LITERAL = String.raw`^[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:e[+-]?[0-9]+)?$`;\n/** Characters whose order differs between code points and UTF-16 units. */\nconst BEYOND_ORDER = \"[\\ue000-\\\\U0010FFFF]\";\n\nconst quoted = (value: string): string =>\n `(left(${value}, 1) = '''' AND right(${value}, 1) = '''')`;\n/** `value.slice(1, -1)`, never a negative length. */\nconst inner = (value: string): string =>\n `CASE WHEN length(${value}) >= 2 THEN substr(${value}, 2, length(${value}) - 2) ELSE '' END`;\n\n/**\n * One turn of `stripDefaultParentheses`: the outer pair goes when it encloses\n * the whole value outside quoted literals. Its parentheses are reduced pair by\n * pair; eight passes settle any nesting up to eight deep, and a deeper one is\n * NULL rather than guessed.\n */\nfunction stripParentheses(value: string): string {\n let pairs = `regexp_replace(${inner(`regexp_replace(${value}, ${re(LITERALS)}, 'q', 'g')`)}, '[^()]', '', 'g')`;\n for (let pass = 0; pass < 8; pass += 1) {\n pairs = `replace(${pairs}, '()', '')`;\n }\n return `(SELECT CASE WHEN ${value} IS NULL OR NOT (left(${value}, 1) = '(' AND right(${value}, 1) = ')') THEN ${value} WHEN reduced = '' THEN ${trim(inner(value))} WHEN reduced ~ ${re(String.raw`^\\)*\\(*$`)} THEN ${value} END FROM (SELECT ${pairs} AS reduced OFFSET 0) parentheses)`;\n}\n\n/** `String(Number(literal))` for a decimal literal JavaScript prints in full. */\nconst FLOAT_TEXT = `(SELECT CASE\n WHEN digits IS NULL THEN NULL\n WHEN whole = '' AND fraction = '' THEN '0'\n WHEN length(whole) <= 21 AND length(rtrim(ltrim(whole || fraction, '0'), '0')) <= 15 AND (whole <> '' OR length(fraction) - length(ltrim(fraction, '0')) <= 5)\n THEN CASE WHEN digits[1] = '-' THEN '-' ELSE '' END || coalesce(nullif(whole, ''), '0') || CASE WHEN fraction = '' THEN '' ELSE '.' || fraction END\nEND FROM (SELECT digits, ltrim(digits[2], '0') AS whole, rtrim(coalesce(digits[3], ''), '0') AS fraction FROM (SELECT regexp_match(unquoted, ${re(String.raw`^([+-]?)([0-9]*)(?:\\.([0-9]*))?$`)}) AS digits) parsed) parts)`;\n\n/** `BigInt(literal).toString()`. */\nconst INTEGER_TEXT = `(SELECT CASE WHEN digits[1] = '-' AND digits[2] <> '0' THEN '-' || digits[2] ELSE digits[2] END FROM (SELECT regexp_match(unquoted, '^([-+]?)0*([0-9]+)$') AS digits) parsed)`;\n\n/** `normalizeDefault`, as the JSON text of its answer; NULL where it abstains. */\nconst DEFAULT_JSON = `CASE\n WHEN spelling IS NULL OR strpos(spelling, chr(8490)) > 0 THEN NULL\n WHEN normalized = 'null' THEN 'null'\n WHEN clock ~ ${re(UTC_NOW)} THEN to_json('now() at time zone ''utc'''::text)::text\n WHEN clock ~ '^date_trunc[(]' THEN NULL\n WHEN clock ~ ${re(UTC_CURRENT_TIME)} THEN to_json(CASE WHEN strpos(clock, 'current_time(3)') > 0 THEN 'timezone(''utc'',current_time(3))' ELSE 'timezone(''utc'',current_time)' END)::text\n WHEN normalized IN ('current_timestamp', 'now()') THEN '\"now()\"'\n WHEN ntype = 'boolean' AND normalized IN ('true', '''t''', '1') THEN '\"true\"'\n WHEN ntype = 'boolean' AND normalized IN ('false', '''f''', '0') THEN '\"false\"'\n WHEN normalized ~ ${re(String.raw`^[a-z_][a-z0-9_]*\\(\\)$`)} THEN to_json(normalized)::text\n WHEN ${quoted(\"spelling\")} AND right(ntype, 2) = '[]' THEN CASE WHEN literal = '{}' THEN '\"[]\"' END\n WHEN ${quoted(\"spelling\")} AND ntype IN ('json', 'jsonb') THEN CASE WHEN literal IN ('{}', '[]', 'null', 'true', 'false') THEN to_json(literal)::text END\n WHEN ntype ~ '^(integer|bigint|smallint|real|double precision|float|int|tinyint)' AND unquoted ~ ${re(NUMBER_LITERAL)}\n THEN to_json(CASE WHEN ntype ~ '^(integer|bigint|smallint|int|tinyint)' AND unquoted ~ '^[-+]?[0-9]+$' THEN ${INTEGER_TEXT} ELSE ${FLOAT_TEXT} END)::text\n WHEN ntype ~ '^(timestamp|time|date)' AND ${quoted(\"spelling\")} THEN NULL\n ELSE to_json(spelling)::text\nEND`;\n\nconst SQL = `WITH\ntbl AS (${POSTGRES_MANAGED_TABLE_NAMES_SOURCE}),\ncol AS (${COLUMNS_SOURCE}),\npk AS (${PRIMARY_KEYS_SOURCE}),\nidx AS (${indexesSource(\"strpos(pg_catalog.pg_get_indexdef(ix.indexrelid), ' NULLS NOT DISTINCT') > 0\")}),\nfk AS (${FOREIGN_KEYS_SOURCE}),\nxfk AS (${CROSS_SCHEMA_FOREIGN_KEYS_SOURCE}),\nuq AS (${UNIQUE_CONSTRAINTS_SOURCE}),\nen AS (${ENUMS_SOURCE}),\nscope AS (\n SELECT table_name::text AS table_name,\n ($4::text[] IS NULL OR table_name::text = ANY ($4::text[])) AS selected,\n table_name::text NOT IN ($2::text, $3::text) AS kept,\n (relation_kind = 'p' OR is_partition) AS partitioned\n FROM tbl\n),\ncolumns AS (\n SELECT s.table_name, s.selected, s.kept, c.column_name::text AS name,\n coalesce(c.generated_kind::text, '') <> '' AS generated,\n t.type, nt.ntype, dd.valid AS decimal_valid,\n '{\"autoIncrement\":' || (coalesce(c.column_default, '') <> '' AND (strpos(c.column_default, 'nextval(') > 0 OR strpos(c.column_default, '_seq''::regclass)') > 0))::text\n || ',\"default\":' || CASE WHEN NOT s.selected OR coalesce(c.column_default, '') = '' OR strpos(c.column_default, 'nextval(') > 0 OR strpos(c.column_default, '_seq''::regclass)') > 0 THEN 'null' ELSE f.json END\n || ',\"name\":' || to_json(c.column_name::text)::text\n || ',\"nullable\":' || (c.is_nullable = 'YES')::text\n || ',\"type\":' || to_json(nt.ntype)::text || '}' AS json\n FROM col c\n JOIN scope s ON s.table_name = c.table_name::text\n CROSS JOIN LATERAL (SELECT c.udt_name::text AS udt, CASE WHEN left(c.udt_name::text, 1) = '_' THEN substr(c.udt_name::text, 2) ELSE c.udt_name::text END AS base OFFSET 0) b\n CROSS JOIN LATERAL (SELECT CASE\n WHEN NOT s.selected THEN CASE WHEN left(b.udt, 1) = '_' THEN b.base || '[]' ELSE b.udt END\n WHEN c.type_extension = 'postgis' AND b.base IN ('geometry', 'geography') AND NOT b.base = ANY ($5::text[]) THEN NULL\n WHEN c.type_extension IS NOT NULL AND c.type_extension_schema IS NOT NULL AND b.base = ANY ($5::text[]) THEN CASE\n WHEN starts_with(c.formatted_type, c.type_extension_schema::text || '.') THEN substr(c.formatted_type, length(c.type_extension_schema::text) + 2)\n WHEN starts_with(c.formatted_type, '\"' || replace(c.type_extension_schema::text, '\"', '\"\"') || '\".') THEN substr(c.formatted_type, length(replace(c.type_extension_schema::text, '\"', '\"\"')) + 4)\n ELSE c.formatted_type END\n WHEN c.type_extension IS NULL AND c.udt_schema::text <> $1::text AND c.udt_schema::text NOT IN ('pg_catalog', 'information_schema') THEN NULL\n WHEN c.udt_schema::text IN ('pg_catalog', 'information_schema') THEN c.formatted_type\n ELSE CASE WHEN left(b.udt, 1) = '_' THEN b.base || '[]' ELSE b.base END\n END AS type OFFSET 0) t\n CROSS JOIN LATERAL (SELECT CASE WHEN t.type ~ '[''\"]' OR octet_length(t.type) <> length(t.type) THEN NULL ELSE ${normalizeType(\"t.type\")} END AS ntype OFFSET 0) nt\n CROSS JOIN LATERAL (SELECT precision, scale, precision IS NULL OR (precision > 0 AND scale >= 0 AND scale <= precision AND precision <= 1000 AND scale <= 1000) AS valid FROM (SELECT\n CASE WHEN c.data_type = 'numeric' AND c.numeric_precision IS NOT NULL THEN c.numeric_precision::numeric WHEN b.udt = '_numeric' THEN m[1]::numeric END AS precision,\n CASE WHEN c.data_type = 'numeric' AND c.numeric_precision IS NOT NULL THEN coalesce(c.numeric_scale, 0)::numeric WHEN b.udt = '_numeric' THEN m[2]::numeric END AS scale\n FROM (SELECT regexp_match(c.formatted_type, ${re(String.raw`^numeric\\((-?[0-9]+),(-?[0-9]+)\\)\\[\\]$`)}) AS m) typmod) domain OFFSET 0) dd\n LEFT JOIN LATERAL (\n SELECT left(c.column_default, length(c.column_default) - length(cast_text)) AS stripped\n FROM (SELECT '::' || q || n || a AS cast_text\n FROM (VALUES (''), ($1::text || '.'), ('\"' || replace($1::text, '\"', '\"\"') || '\".')) qualifiers(q),\n (VALUES (b.base), ('\"' || replace(b.base, '\"', '\"\"') || '\"')) names(n),\n (VALUES (''), ('[]')) arrays(a)) spellings\n WHERE c.udt_schema::text = $1::text AND b.base IN (SELECT enum_name::text FROM en) AND right(c.column_default, length(cast_text)) = cast_text\n ORDER BY length(cast_text) DESC LIMIT 1\n ) e ON true\n CROSS JOIN LATERAL (SELECT ${trim(`regexp_replace(coalesce(e.stripped, c.column_default), ${re(TERMINAL_CAST)}, '')`)} AS cleaned OFFSET 0) d\n CROSS JOIN LATERAL (SELECT CASE WHEN dd.precision IS NULL OR NOT dd.valid OR NOT u ~ '^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$' THEN d.cleaned ELSE (\n SELECT CASE WHEN dd.scale = 0 THEN CASE WHEN strpos(canonical, '.') = 0 THEN canonical ELSE left(canonical, strpos(canonical, '.') - 1) END\n WHEN strpos(canonical, '.') = 0 THEN canonical || '.' || repeat('0', dd.scale::int)\n WHEN length(canonical) >= strpos(canonical, '.') + dd.scale THEN canonical\n ELSE rpad(canonical, strpos(canonical, '.') + dd.scale::int, '0') END\n FROM (SELECT CASE WHEN whole = '0' AND fraction = '' THEN '0' ELSE CASE WHEN left(u, 1) = '-' THEN '-' ELSE '' END || whole || CASE WHEN fraction = '' THEN '' ELSE '.' || fraction END END AS canonical\n FROM (SELECT coalesce(nullif(ltrim(split_part(regexp_replace(u, '^[+-]', ''), '.', 1), '0'), ''), '0') AS whole, rtrim(split_part(regexp_replace(u, '^[+-]', ''), '.', 2), '0') AS fraction) parts) decimal_text\n ) END AS rendered FROM (SELECT CASE WHEN length(d.cleaned) > 1 AND ${quoted(\"d.cleaned\")} THEN ${inner(\"d.cleaned\")} ELSE d.cleaned END AS u) unquoted_decimal OFFSET 0) r\n CROSS JOIN LATERAL (SELECT ${trim(\"r.rendered\")} AS layer0 OFFSET 0) p0\n CROSS JOIN LATERAL (SELECT ${stripParentheses(\"p0.layer0\")} AS layer1 OFFSET 0) p1\n CROSS JOIN LATERAL (SELECT ${stripParentheses(\"p1.layer1\")} AS layer2 OFFSET 0) p2\n CROSS JOIN LATERAL (SELECT CASE WHEN ${stripParentheses(\"p2.layer2\")} IS NOT DISTINCT FROM p2.layer2 THEN p2.layer2 END AS spelling OFFSET 0) sp\n CROSS JOIN LATERAL (SELECT lower(spelling COLLATE \"C\") AS normalized,\n replace(replace(lower(spelling COLLATE \"C\"), '::text', ''), 'current_timestamp', 'now()') AS clock,\n replace(${inner(\"spelling\")}, '''''', '''') AS literal,\n CASE WHEN ${quoted('lower(spelling COLLATE \"C\")')} THEN ${inner('lower(spelling COLLATE \"C\")')} ELSE lower(spelling COLLATE \"C\") END AS unquoted OFFSET 0) v\n CROSS JOIN LATERAL (SELECT ${DEFAULT_JSON} AS json OFFSET 0) f\n),\nindexes AS (\n SELECT s.table_name, s.selected, s.kept, i.index_name::text AS name,\n bool_and(i.is_valid) AS valid,\n bool_or(i.unsupported_structure IS DISTINCT FROM false) AS unsupported,\n min(i.index_type::text) AS method,\n bool_and(i.is_unique) AS is_unique,\n min(coalesce(i.filter_condition, '')) AS predicate,\n bool_or(i.column_name IS NULL) AS expression,\n '[' || string_agg(to_json(i.column_name::text)::text, ',' ORDER BY i.ordinal_position) || ']' AS columns\n FROM idx i JOIN scope s ON s.table_name = i.table_name::text\n GROUP BY s.table_name, s.selected, s.kept, i.index_name\n),\nkept_indexes AS (\n SELECT table_name, name, columns,\n is_unique AND predicate = '' AND method = 'btree' AS total_unique,\n '{\"columns\":' || columns || ',\"name\":' || to_json(name)::text || ',\"type\":' || to_json(method)::text || ',\"unique\":' || is_unique::text\n || ',\"where\":' || coalesce(to_json(nullif(${trim(\"predicate\")}, ''))::text, 'null') || '}' AS json\n FROM indexes\n WHERE kept AND method IN ('btree', 'hash', 'gin', 'gist') AND NOT expression\n),\npks AS (\n SELECT s.table_name, '{\"columns\":[' || string_agg(to_json(p.column_name::text)::text, ',' ORDER BY p.ordinal_position) || '],\"name\":' || to_json(min(p.constraint_name::text))::text || '}' AS json\n FROM pk p JOIN scope s ON s.table_name = p.table_name::text\n WHERE s.kept\n GROUP BY s.table_name\n),\nfks AS (\n SELECT s.table_name, '{\"columns\":[' || string_agg(to_json(f.column_name::text)::text, ',' ORDER BY f.ordinal_position)\n || '],\"name\":' || to_json(f.constraint_name::text)::text\n || ',\"onDelete\":\"' || ${referentialAction(\"min(f.delete_rule::text)\")}\n || '\",\"onUpdate\":\"' || ${referentialAction(\"min(f.update_rule::text)\")}\n || '\",\"referencedColumns\":[' || string_agg(to_json(f.foreign_column_name::text)::text, ',' ORDER BY f.ordinal_position)\n || '],\"referencedTable\":' || to_json(min(f.foreign_table_name::text))::text || '}' AS json\n FROM fk f JOIN scope s ON s.table_name = f.table_name::text\n WHERE s.kept\n GROUP BY s.table_name, f.constraint_name\n),\nuqs AS (\n SELECT s.table_name, '{\"columns\":[' || string_agg(to_json(u.column_name::text)::text, ',' ORDER BY u.ordinal_position) || '],\"name\":' || to_json(u.constraint_name::text)::text || '}' AS json\n FROM uq u JOIN scope s ON s.table_name = u.table_name::text\n WHERE s.kept\n GROUP BY s.table_name, u.constraint_name\n UNION ALL\n SELECT table_name, '{\"columns\":' || columns || ',\"name\":' || to_json(name)::text || '}'\n FROM kept_indexes WHERE total_unique\n),\ntables AS (\n SELECT s.table_name,\n '{\"columns\":[' || coalesce((SELECT string_agg(c.json, ',' ORDER BY c.name COLLATE \"C\") FROM columns c WHERE c.table_name = s.table_name), '')\n || '],\"foreignKeys\":[' || coalesce((SELECT string_agg(f.json, ',' ORDER BY f.json COLLATE \"C\") FROM fks f WHERE f.table_name = s.table_name), '')\n || '],\"indexes\":[' || coalesce((SELECT string_agg(i.json, ',' ORDER BY i.name COLLATE \"C\") FROM kept_indexes i WHERE i.table_name = s.table_name AND NOT i.total_unique), '')\n || '],\"name\":' || to_json(s.table_name)::text\n || ',\"primaryKey\":' || coalesce((SELECT p.json FROM pks p WHERE p.table_name = s.table_name), 'null')\n || ',\"uniqueConstraints\":[' || coalesce((SELECT string_agg(u.json, ',' ORDER BY u.json COLLATE \"C\") FROM uqs u WHERE u.table_name = s.table_name), '')\n || ']}' AS json\n FROM scope s\n WHERE s.kept AND s.selected\n),\nenums AS (\n SELECT enum_name::text AS name, '{\"name\":' || to_json(enum_name::text)::text || ',\"values\":[' || string_agg(to_json(enum_value::text)::text, ',' ORDER BY sort_order) || ']}' AS json\n FROM en\n WHERE $4::text[] IS NULL OR enum_name::text IN (SELECT ${elementType(\"c.type\")} FROM columns c WHERE c.selected OR NOT c.kept)\n GROUP BY enum_name\n),\nprojection AS (\n SELECT '{\"enums\":[' || coalesce((SELECT string_agg(json, ',' ORDER BY name COLLATE \"C\") FROM enums), '')\n || '],\"tables\":[' || coalesce((SELECT string_agg(json, ',' ORDER BY table_name COLLATE \"C\") FROM tables), '') || ']}' AS json\n)\nSELECT CASE WHEN\n EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = $1::text)\n AND pg_catalog.getdatabaseencoding() = 'UTF8'\n AND NOT EXISTS (SELECT 1 FROM scope WHERE selected AND partitioned)\n AND NOT EXISTS (SELECT 1 FROM columns WHERE selected AND (generated OR type IS NULL OR NOT decimal_valid OR (kept AND json IS NULL)))\n AND NOT EXISTS (SELECT 1 FROM indexes WHERE selected AND (NOT valid OR unsupported OR method NOT IN ('btree', 'hash', 'gin', 'gist') OR (kept AND NOT expression AND predicate <> '' AND NOT $6::boolean)))\n AND NOT EXISTS (SELECT 1 FROM fk WHERE $4::text[] IS NOT NULL AND ${managedOrControl(\"fk.table_name\")} <> ${managedOrControl(\"fk.foreign_table_name\")})\n AND NOT EXISTS (SELECT 1 FROM columns c WHERE NOT c.selected AND c.kept AND ${elementType(\"c.type\")} IN (SELECT name FROM enums))\n AND NOT EXISTS (SELECT 1 FROM xfk WHERE $4::text[] IS NULL OR (owning_schema::text = $1::text AND owning_table::text = ANY ($4::text[])) OR (referenced_schema::text = $1::text AND referenced_table::text = ANY ($4::text[])))\n AND NOT projection.json ~ ${re(BEYOND_ORDER)}\nTHEN encode(sha256(convert_to('${HASH_DOMAIN.snapshot}', 'UTF8') || decode('00', 'hex') || convert_to(projection.json, 'UTF8')), 'hex') END AS digest\nFROM projection`;\n\n/** A column type without its `[]`, as the managed-table selection reads it. */\nfunction elementType(type: string): string {\n return `regexp_replace(${type}, ${re(String.raw`\\[\\]$`)}, '')`;\n}\n\n/** Whether a table is selected by the managed-table list, or a control table. */\nfunction managedOrControl(table: string): string {\n return `(${table}::text = ANY ($4::text[]) OR ${table}::text IN ($2::text, $3::text))`;\n}\n\nfunction referentialAction(rule: string): string {\n return `CASE ${rule} WHEN 'CASCADE' THEN 'cascade' WHEN 'SET NULL' THEN 'setNull' WHEN 'RESTRICT' THEN 'restrict' WHEN 'SET DEFAULT' THEN 'setDefault' ELSE 'noAction' END`;\n}\n\n/**\n * The statement and its parameters, for a caller that embeds it in a\n * statement of its own: `$1` is the namespace and `$2`, `$3` the state and log\n * control tables, as in the control catalog read; `$4` to `$6` are its own.\n * `deparsedPredicates` hashes each partial-index predicate as the server\n * deparses it instead of abstaining (see the header).\n */\nexport function postgresCatalogDigestQuery(\n driver: BoundMigrationDriver,\n control: ControlTableNames,\n deparsedPredicates = false\n): {\n readonly sql: string;\n readonly parameters: unknown[];\n} {\n const tables = driver.target.tables;\n return {\n sql: SQL,\n parameters: [\n boundNamespace(driver),\n control.state,\n control.log,\n tables === undefined ? null : arrayLiteralText(tables),\n arrayLiteralText([...admittedExtensionTypes(driver.executionDriver)]),\n deparsedPredicates,\n ],\n };\n}\n\n/**\n * The live managed schema's fingerprint, read in one statement; `undefined`\n * where the digest abstains and the caller must introspect.\n */\nexport async function postgresCatalogDigest(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n control: ControlTableNames\n): Promise<Sha256 | undefined> {\n const { sql, parameters } = postgresCatalogDigestQuery(driver, control);\n const result = await producer._executeRaw<{ digest: unknown }>(\n sql,\n parameters\n );\n return readDigest(result.rows[0]?.digest);\n}\n\n/** A digest the statement answered, or `undefined` for an abstention. */\nfunction readDigest(value: unknown): Sha256 | undefined {\n return isSha256(value) ? value : undefined;\n}\n","import { isGeneratorDefault } from \"@schema/scalars/common\";\nimport { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idDomainOfState, idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport {\n arrayLiteralText,\n readArrayLiteralText,\n} from \"../../../adapters/databases/postgres/array-literal\";\n/**\n * PostgreSQL Migration Driver\n *\n * Implements the MigrationDriver interface for PostgreSQL databases.\n * Supports all DDL operations natively.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport { hasIdPrefix } from \"@validation/primitives/id-formats\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { errorCause } from \"../../../errors/diagnostic-safety\";\nimport { renderQualifiedIdentifier } from \"../../../sql/identifiers\";\nimport { type LowLockContext, tableRewrites } from \"../../compile\";\nimport {\n decimalConversionConstraintName,\n decimalConversionRequired,\n postgresDecimalFitsCheck,\n} from \"../../decimal\";\nimport { providerFacts } from \"../../execute-dispatch\";\nimport {\n isPostgresTextToUuid,\n postgresTextToUuidGuard,\n} from \"../../identifier-conversion\";\nimport type { Sha256 } from \"../../identity\";\nimport { DEFAULT_MIGRATION_LIMITS } from \"../../limits\";\nimport {\n type CatalogHazard,\n catalogCommitBoundaries,\n} from \"../../statement-safety\";\nimport type {\n ColumnDef,\n DiffOperation,\n IndexDef,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\nimport { derivedMigrationName } from \"../../utils\";\nimport type { BoundMigrationDriver } from \"..\";\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type ControlTableNames,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DerivedRename,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\nimport { getPostgresType, PG_TYPE_DEFAULTS } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport {\n type BatchExecutor,\n canonicalizeIndexPredicates,\n} from \"./canonicalize-index-predicate\";\nimport {\n postgresCatalogDigest,\n postgresCatalogDigestQuery,\n} from \"./catalog-digest\";\nimport {\n admittedExtensionTypes,\n introspectPostgresSchema,\n POSTGRES_MANAGED_TABLE_NAMES_QUERY,\n} from \"./introspect\";\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * One catalog existence proof for the estate's schema.\n *\n * Bound, never interpolated, and asking `pg_namespace` exactly one question:\n * does this schema exist. Privilege failures are deliberately NOT folded in —\n * a schema this role cannot use is a different fact with a different fix, and\n * it surfaces as the provider's own error from the statement that needed the\n * privilege.\n */\nconst VECTOR_TYPE_TOKEN = /^(vector|halfvec|sparsevec)(?:\\(\\d+\\))?(?:\\[\\])?$/i;\nconst TEMPORAL_PRECISION_TOKEN = /\\((\\d+)\\)/;\n/** The planner's row estimate in the first line of an EXPLAIN. */\nconst PLAN_ROWS = /\\brows=(\\d+)/;\n\nconst NAMESPACE_EXISTS_QUERY =\n \"SELECT 1 AS present FROM pg_catalog.pg_namespace WHERE nspname = $1\";\n\nconst POSTGIS_PREFLIGHT_QUERY = `\nWITH postgis AS (\n SELECT oid\n FROM pg_catalog.pg_extension\n WHERE extname = 'postgis'\n), required_objects(classid, objid) AS (\n VALUES\n ('pg_catalog.pg_type'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regtype('geometry')::pg_catalog.oid),\n ('pg_catalog.pg_type'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regtype('geography')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_makepoint(double precision,double precision)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_setsrid(geometry,integer)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_x(geometry)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_y(geometry)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_geomfromgeojson(text)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_intersects(geography,geography)')::pg_catalog.oid),\n ('pg_catalog.pg_operator'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regoperator('&&(geography,geography)')::pg_catalog.oid)\n)\nSELECT (\n EXISTS (SELECT 1 FROM postgis)\n AND NOT EXISTS (\n SELECT 1\n FROM required_objects required\n WHERE required.objid IS NULL\n OR NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend dependency\n CROSS JOIN postgis\n WHERE dependency.classid = required.classid\n AND dependency.objid = required.objid\n AND dependency.objsubid = 0\n AND dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND dependency.refobjid = postgis.oid\n AND dependency.deptype = 'e'\n )\n )\n) AS ready\n`;\n\n/** The Neki fact a bound migration driver's lock protocol already read. */\nconst NEKI = new WeakMap<object, boolean>();\n\n/**\n * Whether the server is PlanetScale's Neki (its `version()` names it): the\n * one read of that fact, asked once per command by the lock protocol\n * ({@link PostgresMigrationDriver.holdsSessionLock}), whose answer the\n * preflight of a program that would need a commit there reuses; a command\n * outside the lock protocol asks it there.\n */\nasync function serverIsNeki(\n driver: object,\n executeRaw: RawExecutor\n): Promise<boolean> {\n const known = NEKI.get(driver);\n if (known !== undefined) return known;\n const { rows } = await executeRaw<{ neki: boolean }>(\n \"SELECT pg_catalog.version() LIKE '%(Neki)%' AS neki\"\n );\n const neki = rows[0]?.neki === true;\n NEKI.set(driver, neki);\n return neki;\n}\n\n/**\n * The refusal of a program PlanetScale's Neki cannot run (V11021), before any\n * effect: one entry whose own statements need a commit between them\n * (`inside`), where no commit can be placed, or, for a command that runs its\n * program in one transaction, the first statement that needs one.\n */\nfunction nekiRefusal(\n dialect: string,\n { kind, change, statement }: CatalogHazard,\n inside: boolean\n): MigrationError {\n const reason =\n kind === \"rows\"\n ? \"a statement does not see a schema change made earlier in its own transaction\"\n : \"a statement cannot retype, rename or drop a column of a table created or renamed earlier in its own transaction (NK316)\";\n const where = inside\n ? `statement ${statement.position + 1} of this migration runs ${statement.words} after ${change.words} in one dispatch, which no commit can divide. Nothing ran. Put them in separate statements of the migration (one sql fragment each), or in states of their own.`\n : `this migration runs statement ${statement.position + 1} (${statement.words}) after statement ${change.position + 1} (${change.words}). Nothing ran. apply() commits between them; this command runs them in one transaction. Put the later statement in a state of its own after the earlier one, and apply up to the earlier one first (apply({ to })).`;\n return new MigrationError(\n `On PlanetScale's Neki, ${reason}, and ${where}`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n {\n meta: {\n dialect,\n feature: inside\n ? \"dependent statements in one dispatch\"\n : kind === \"rows\"\n ? \"data after schema change in one transaction\"\n : \"column change of a new relation in one transaction\",\n },\n }\n );\n}\n\nfunction snapshotUsesGeoPoint(snapshot: SchemaSnapshot): boolean {\n const physicalType = PG_TYPE_DEFAULTS.point.toLowerCase().replace(/\\s+/g, \"\");\n return snapshot.tables.some((table) =>\n table.columns.some(\n (column) => column.type.toLowerCase().replace(/\\s+/g, \"\") === physicalType\n )\n );\n}\n\nconst QUOTED_LITERAL = /^'(.*)'$/s;\n\nconst storesEnum = (column: ColumnDef, enumName: string) =>\n column.type === enumName || column.type === `${enumName}[]`;\n\n/** The labels a default of `enumName`, or of its array, spells. */\nfunction enumDefaultLabels(\n column: ColumnDef,\n enumName: string\n): readonly (string | null)[] {\n if (!storesEnum(column, enumName)) return [];\n const literal = column.default\n ?.match(QUOTED_LITERAL)?.[1]\n ?.replaceAll(\"''\", \"'\");\n if (literal === undefined) return [];\n return column.type === enumName\n ? [literal]\n : (readArrayLiteralText(literal) ?? []);\n}\n\nconst IDENTIFIER_PART = /[\\w$]/;\n\n/**\n * Whether SQL text may name `identifier`: bare in any case, or double-quoted.\n * Matches inside literals and comments count too; they only cost a type\n * recreation that was not needed.\n */\nfunction mayName(sql: string, identifier: string): boolean {\n const text = sql.toLowerCase();\n const name = identifier.replaceAll('\"', '\"\"').toLowerCase();\n for (let at = text.indexOf(name); at >= 0; at = text.indexOf(name, at + 1))\n if (\n !(\n IDENTIFIER_PART.test(text[at - 1] ?? \"\") ||\n IDENTIFIER_PART.test(text[at + name.length] ?? \"\")\n )\n )\n return true;\n return false;\n}\n\n/**\n * Whether an operation after `ALTER TYPE … ADD VALUE` in the same transaction\n * may read an added label, which PostgreSQL refuses until commit (55P04): a\n * default naming one, a cast of stored data into the enum, or a partial-index\n * predicate naming the type or a column of it. No literal spelling is\n * trusted: `$$archived$$`, `E'archived'` and a function result compare the\n * same.\n */\nfunction readsAddedValue(\n enumName: string,\n added: readonly string[],\n tables: readonly TableDef[],\n following: readonly DiffOperation[]\n): boolean {\n const defaultNamesAdded = (column: ColumnDef) => {\n const labels = enumDefaultLabels(column, enumName);\n return added.some((value) => labels.includes(value));\n };\n // The type and every name the batch gives a column of it, on any table.\n const names = new Set([enumName]);\n const addEnumColumns = (columns: readonly ColumnDef[]) => {\n for (const column of columns)\n if (storesEnum(column, enumName)) names.add(column.name);\n };\n for (const table of tables) addEnumColumns(table.columns);\n const predicateNamesEnum = ({ where }: IndexDef) =>\n where !== undefined && [...names].some((name) => mayName(where, name));\n for (const operation of following) {\n switch (operation.type) {\n case \"createTable\":\n addEnumColumns(operation.table.columns);\n if (\n operation.table.columns.some(defaultNamesAdded) ||\n operation.table.indexes.some(predicateNamesEnum)\n )\n return true;\n break;\n case \"addColumn\":\n if (defaultNamesAdded(operation.column)) return true;\n addEnumColumns([operation.column]);\n break;\n // A column already of the enum is known; one cast into it may hold a label.\n case \"alterColumn\":\n if (\n defaultNamesAdded(operation.to) ||\n (storesEnum(operation.to, enumName) &&\n !storesEnum(operation.from, enumName))\n )\n return true;\n break;\n case \"renameColumn\":\n if (names.has(operation.from)) names.add(operation.to);\n break;\n case \"createIndex\":\n if (predicateNamesEnum(operation.index)) return true;\n break;\n default:\n break;\n }\n }\n return false;\n}\n\nexport class PostgresMigrationDriver extends MigrationDriver {\n readonly dialect = \"postgresql\" as const;\n readonly driverName = \"postgresql\";\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: true,\n supportsAddEnumValueInTransaction: true,\n supportsIndexTypes: [\"btree\", \"hash\", \"gin\", \"gist\"],\n supportsNativeArrays: true,\n supportsAddForeignKeyViaAlter: true,\n // `pg_constraint.conname` is the name the DDL gave the constraint.\n introspectionReadsConstraintNames: true,\n };\n\n // ===========================================================================\n // ESTATE QUALIFICATION\n // ===========================================================================\n\n /**\n * The schema this estate's persistent objects are named with, or undefined\n * on the REGISTERED singleton, which is bound to no estate.\n *\n * ONE source: the estate target. `this.namespace` holds the same string for\n * a PostgreSQL estate — `getMigrationDriver` reads both from the same\n * adapter, and the estate gate refuses a schema that is not this\n * one — so reading exactly one of them is what keeps the two from ever being\n * asked to disagree.\n *\n * `DDLContext.destination` does not enter: §3.4 binds GENERATED PostgreSQL\n * SQL to the configured schema for the same reason live SQL is bound, so an\n * artifact and a live statement in one estate name one schema. That is the\n * dialect difference from MySQL, whose artifacts stay database-relative.\n *\n * The dialect comparison is the union narrowing `MigrationTarget` requires\n * before `namespace` is readable at all, not a second check on top of the\n * registry's: a PostgreSQL implementation is only ever bound to a PostgreSQL\n * target.\n */\n private estateNamespace(): string | undefined {\n const target = this.target;\n return target?.dialect === \"postgresql\" ? target.namespace : undefined;\n }\n\n /**\n * The estate schema where a statement cannot be written without one.\n *\n * A catalog predicate and a schema-scoped inventory have no unqualified\n * reading: with no schema operand they answer for every schema in the\n * database, and any default answers for a schema nothing proved. DDL text is\n * the opposite case and renders unqualified off an unbound singleton (see\n * {@link qualify}).\n */\n private requireEstateNamespace(): string {\n const namespace = this.estateNamespace();\n if (namespace === undefined) {\n throw new MigrationError(\n \"This PostgreSQL migration driver is not bound to an estate, so it has no schema to read the catalog for. \" +\n \"Reach the driver through `getMigrationDriver(driver)`, which binds the adapter's namespace, instead of the registered singleton.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect } }\n );\n }\n return namespace;\n }\n\n /**\n * `\"schema\".\"object\"` — the one qualified spelling, through the one shared\n * primitive, with this driver's own quoter (§2.2, N11).\n *\n * An unbound singleton renders `\"object\"`: it is the dialect's renderer with\n * no estate behind it, and every shipped path reaches a bound view because\n * `getMigrationDriver` refuses a PostgreSQL adapter that declares no\n * namespace. Qualification is never composed by hand anywhere in this file.\n */\n private qualify(objectName: string): string {\n return renderQualifiedIdentifier(\n (name) => this.escapeIdentifier(name),\n this.estateNamespace(),\n objectName\n );\n }\n\n /** A table position is qualified like any object, whatever the destination. */\n protected override tableRef(tableName: string): string {\n return this.qualify(tableName);\n }\n\n /**\n * The enum types this DDL batch may name as a column type.\n *\n * Membership is the ONLY thing that qualifies a column's type token, which is\n * what replaced the `_enum` suffix guess: an explicitly named enum such as\n * `state` is no less managed, and an arbitrary type token cannot prove enum\n * ownership. The set is the introspected schema's enums plus the enums the\n * operations already emitted in this batch have created — a table created\n * beside its own new enum must qualify that enum's name.\n *\n * A `dropEnum` earlier in the batch is deliberately not subtracted: a column\n * type naming a type this batch already dropped is a broken batch either way,\n * and the subtraction would silently UNqualify the very statements that run\n * before the drop.\n *\n * A createEnum introduces a name; alterEnum keeps an existing name from the\n * snapshot. Enum replacement runs before dependent columns, so its full\n * ordered value set and defaults are ready for those subsequent changes.\n */\n private managedEnumNames(context: DDLContext): ReadonlySet<string> {\n const names = new Set<string>();\n for (const enumDef of context.currentSchema?.enums ?? []) {\n names.add(enumDef.name);\n }\n for (const operation of context.precedingOperations ?? []) {\n if (operation.type === \"createEnum\") {\n names.add(operation.enumDef.name);\n }\n }\n return names;\n }\n\n /**\n * A column type token, qualified when it names a managed enum.\n *\n * Built-in types and the adapter-supported extension spellings (`vector(3)`,\n * `geometry(Point,4326)`) pass through untouched: they are provider objects\n * resolved through `search_path`, not estate objects, and prefixing every\n * type token would break them.\n */\n private renderTypeToken(type: string, context: DDLContext): string {\n const isArray = type.endsWith(\"[]\");\n const baseType = isArray ? type.slice(0, -2) : type;\n if (!this.managedEnumNames(context).has(baseType)) {\n return type;\n }\n const qualified = this.qualify(baseType);\n return isArray ? `${qualified}[]` : qualified;\n }\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Reads the estate's schema, and nothing else's.\n *\n * The namespace proof runs FIRST and here rather than at every caller: this\n * is the one inventory every catalog-driven path goes through (public\n * `introspect`, push including dry-run, and force-reset), and a configured\n * but absent schema must not be published as an empty database.\n */\n async introspect(executeRaw: RawExecutor): Promise<SchemaSnapshot> {\n await this.proveNamespaceExists(executeRaw);\n return await introspectPostgresSchema(executeRaw, {\n namespace: this.requireEstateNamespace(),\n tables: this.target?.tables,\n admittedExtensionTypes: admittedExtensionTypes(this.executionDriver),\n });\n }\n\n override catalogDigestQuery(\n this: BoundMigrationDriver,\n control: ControlTableNames,\n deparsedPredicates = false\n ) {\n return postgresCatalogDigestQuery(this, control, deparsedPredicates);\n }\n\n override catalogDigest(\n this: BoundMigrationDriver,\n producer: AnyDriver,\n control: ControlTableNames\n ): Promise<Sha256 | undefined> {\n return postgresCatalogDigest(producer, this, control);\n }\n\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: RawExecutor,\n program: readonly string[],\n splits = false\n ): Promise<boolean> {\n try {\n // PlanetScale's Neki plans a statement against the schema committed\n // before its transaction (`catalogCommitBoundaries`). Asked of the\n // server only for a program that would need a commit there.\n const { boundaries, first, inside } = catalogCommitBoundaries(program);\n const neki =\n boundaries.length > 0 && (await serverIsNeki(this, executeRaw));\n const refused = neki\n ? (inside ?? (splits ? undefined : first))\n : undefined;\n if (refused) throw nekiRefusal(this.dialect, refused, refused === inside);\n // T5a: a statement that rewrites or scans a table holds a lock that\n // blocks it for as long as that takes, so above `largeTableRows` (the\n // planner's estimate, as EXPLAIN reports it) it is refused here, before\n // any effect. A table the program creates is not there yet: it is empty.\n const { largeTableRows } = this.limits ?? DEFAULT_MIGRATION_LIMITS;\n const rewrites = largeTableRows > 0 ? tableRewrites(program) : [];\n const tables = [...new Set(rewrites.map(({ table }) => table))];\n const relations =\n tables.length === 0\n ? []\n : (\n await executeRaw<{ relation: string | null }>(\n \"SELECT pg_catalog.to_regclass(name)::text AS relation FROM unnest($1::text[]) WITH ORDINALITY AS input(name, position) ORDER BY position\",\n [arrayLiteralText(tables)]\n )\n ).rows;\n for (const [index, { relation }] of relations.entries()) {\n if (relation === null) continue;\n const explain = `EXPLAIN SELECT 1 FROM ${relation}`;\n const plan = await executeRaw<Record<string, string>>(explain);\n const line = Object.values(plan.rows[0] ?? {})[0] ?? \"\";\n const estimate = PLAN_ROWS.exec(line)?.[1];\n // A plan without an estimate is not admitted: it was not measured.\n if (estimate !== undefined && Number(estimate) <= largeTableRows) {\n continue;\n }\n const table = tables[index]!;\n const operations = [\n ...new Set(\n rewrites.flatMap((item) =>\n item.table === table ? [item.operation] : []\n )\n ),\n ];\n const operation = operations.join(\" and \");\n // T5b: a validation alone has a step form that blocks no write.\n const steps = operations.every((name) => name.endsWith(\" validation\"))\n ? \" Or add the constraint NOT VALID and validate it (VALIDATE CONSTRAINT) in a later migration: neither step blocks writes. generate({ lowLock: true }) does this for foreign keys.\"\n : \"\";\n const size =\n estimate === undefined\n ? `whose row estimate ${explain} did not report (${JSON.stringify(line)}), so limits.largeTableRows (${largeTableRows}) cannot admit it`\n : `which the planner estimates at ${estimate} rows, above limits.largeTableRows (${largeTableRows})`;\n throw new MigrationError(\n `This migration runs a ${operation} on ${table}, ${size}. It rewrites or scans the whole table while holding a lock that blocks it, longer than a request should wait. Nothing ran: the schema and data are unchanged. Run it outside the request with a client whose largeTableRows is higher, or 0 for no limit.${steps}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: { table, operation, feature: \"large table rewrite\" },\n }\n );\n }\n const vectors = new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.flatMap((table) =>\n table.columns.flatMap(\n (column) =>\n VECTOR_TYPE_TOKEN.exec(column.type)?.[1]?.toLowerCase() ?? []\n )\n )\n )\n );\n if (\n vectors.size > 0 &&\n !this.executionDriver?.adapter.capabilities.supportsVector\n )\n throw new MigrationError(\n \"This migration requires pgvector support. Construct the PostgreSQL driver with pgvector: true and install the vector extension before applying it. VibORM never installs it.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { dialect: this.dialect, feature: \"vector\" } }\n );\n if (\n snapshots.some(snapshotUsesGeoPoint) &&\n !this.executionDriver?.adapter.geoPoint\n ) {\n throw new MigrationError(\n \"This migration requires PostGIS GeoPoint support, but the bound PostgreSQL adapter has no GeoPoint protocol. Construct the driver with `postgis: true` and ensure PostGIS is installed before applying it.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { dialect: this.dialect, feature: \"GeoPoint\" } }\n );\n }\n const desiredNames = [\n ...new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n ),\n ];\n if (desiredNames.length > 0) {\n const views = await executeRaw<{ name: string }>(\n `SELECT relation.relname AS name FROM pg_catalog.pg_class relation JOIN pg_catalog.pg_namespace namespace ON namespace.oid=relation.relnamespace WHERE namespace.nspname=$1 AND relation.relkind IN ('v','m') AND relation.relname=ANY($2::text[])`,\n [this.requireEstateNamespace(), arrayLiteralText(desiredNames)]\n );\n const collision = views.rows.find((row) =>\n desiredNames.includes(row.name)\n );\n if (collision)\n throw new MigrationError(\n `PostgreSQL relation \"${collision.name}\" is a view or materialized view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: collision.name, feature: \"view\" } }\n );\n }\n if (vectors.size > 0) {\n const proof = await executeRaw<{ ready: boolean }>(\n `SELECT NOT EXISTS (SELECT 1 FROM unnest($1::text[]) AS required(name) WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.pg_extension AS e JOIN pg_catalog.pg_depend AS d ON d.refobjid=e.oid AND d.refclassid='pg_catalog.pg_extension'::regclass AND d.deptype='e' JOIN pg_catalog.pg_type AS t ON t.oid=d.objid AND d.classid='pg_catalog.pg_type'::regclass WHERE e.extname='vector' AND t.typname=required.name AND pg_catalog.pg_type_is_visible(t.oid))) AS ready`,\n [arrayLiteralText([...vectors])]\n );\n if (proof.rows.length !== 1 || proof.rows[0]?.ready !== true)\n throw new MigrationError(\n \"pgvector preflight did not prove every required visible extension-owned vector type. Install the vector extension before migration effects; VibORM never installs it.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, feature: \"vector\" } }\n );\n }\n if (snapshots.some((snapshot) => (snapshot.enums?.length ?? 0) > 0)) {\n const version = await executeRaw<{ version: string }>(\n \"SELECT current_setting('server_version_num') AS version\"\n );\n const number = Number(version.rows[0]?.version);\n if (!Number.isInteger(number) || number < 120_000)\n throw new MigrationError(\n \"PostgreSQL enum migrations require server_version_num >= 120000 for transactional enum safety\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n if (!snapshots.some(snapshotUsesGeoPoint)) return neki;\n let rows: readonly { ready?: unknown }[];\n try {\n rows = (await executeRaw<{ ready?: unknown }>(POSTGIS_PREFLIGHT_QUERY))\n .rows;\n } catch (failure) {\n throw new MigrationError(\n \"PostGIS GeoPoint preflight could not prove the required extension, types, and functions before migration effects.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause: errorCause(failure),\n meta: {\n dialect: this.dialect,\n feature: \"GeoPoint\",\n ...providerFacts(failure),\n },\n }\n );\n }\n if (rows.length !== 1 || rows[0]?.ready !== true) {\n throw new MigrationError(\n \"PostGIS GeoPoint preflight did not prove the required extension, visible types, and exact function signatures. VibORM never installs PostGIS.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, feature: \"GeoPoint\" } }\n );\n }\n return neki;\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw new MigrationError(\n \"PostgreSQL schema preflight could not prove the required catalog facts before migration effects.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause: errorCause(failure),\n meta: {\n dialect: this.dialect,\n feature: \"schema catalog\",\n ...providerFacts(failure),\n },\n }\n );\n }\n }\n\n /**\n * PostgreSQL reports a missing schema as SQLSTATE `3F000` only where the\n * statement names one; a catalog read filtered on a schema name that does not\n * exist just returns nothing. This proof is what makes that silence\n * impossible, and it runs before any missing-tracking-table translation can\n * be consulted, because PostgreSQL reports a missing schema and a missing\n * relation alike as `42P01`.\n */\n override async proveNamespaceExists(executeRaw: RawExecutor): Promise<void> {\n const namespace = this.requireEstateNamespace();\n const { rows } = await executeRaw<{ present: number }>(\n NAMESPACE_EXISTS_QUERY,\n [namespace]\n );\n if (rows.length === 0) {\n // The schema is named in the message AND on the allowlist's `namespace`\n // key (`src/errors/diagnostics.ts`), so a caller can read which estate\n // was missing without parsing prose.\n throw new MigrationError(\n `The configured PostgreSQL schema \"${namespace}\" does not exist. ` +\n \"VibORM never creates or drops a schema: create it (or fix the configured `namespace`) before running migrations.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, driver: this.driverName, namespace } }\n );\n }\n }\n\n // PostgreSQL deparses an index predicate rather than storing the statement,\n // so the declared spelling and the introspected one never match on their own\n // (Decision 7.4). The other dialects have no such gap and leave this unset.\n override canonicalizeIndexPredicates(\n tableName: string,\n predicates: readonly string[],\n executeRaw: RawExecutor,\n executeBatch?: BatchExecutor\n ): Promise<ReadonlyArray<string | undefined>> {\n return canonicalizeIndexPredicates(\n this.requireEstateNamespace(),\n this.qualify(tableName),\n predicates,\n executeRaw,\n executeBatch\n );\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string {\n const declaration = scalar[\"~\"].nativeType;\n\n // An identifier column's type is the ONE storage owner's answer, override\n // included — which is also why the override is not read separately here: a\n // spelling this domain cannot live in was refused at the schema boundary,\n // and a text-family one keeps text storage with the domain still admitted.\n const idStorage =\n idDomain === undefined\n ? undefined\n : idStorageOf(idDomain, declaration, \"pg\");\n if (idStorage) return idStorage.columnType;\n\n // The declaration's PostgreSQL choice, if it makes one\n const nativeType = nativeTypeFor(declaration, \"pg\");\n if (nativeType) {\n return scalarState.array ? `${nativeType.type}[]` : nativeType.type;\n }\n\n // Use centralized type mapping\n return getPostgresType({\n type: scalarState.type,\n array: scalarState.array,\n withTimezone: scalarState.withTimezone,\n dimension: scalarState.dimension,\n decimal: scalarState.decimal,\n });\n }\n\n override finalizeTable(table: TableDef): TableDef {\n return {\n ...table,\n ...(table.primaryKey?.name\n ? {\n primaryKey: {\n ...table.primaryKey,\n name: derivedMigrationName(table.primaryKey.name),\n },\n }\n : {}),\n uniqueConstraints: table.uniqueConstraints.map((item) => ({\n ...item,\n name: derivedMigrationName(item.name),\n })),\n foreignKeys: table.foreignKeys.map((item) => ({\n ...item,\n name: derivedMigrationName(item.name),\n })),\n indexes: table.indexes.map((index) => ({\n ...index,\n name: derivedMigrationName(index.name),\n ...(index.type === \"spatial\" ? { type: \"gist\" as const } : {}),\n })),\n };\n }\n\n /**\n * The only generator PostgreSQL can run itself.\n *\n * `gen_random_uuid()` (PostgreSQL 13+) produces exactly what `.uuid()`\n * produces — but ONLY when no prefix is declared: a prefixed field's public\n * value is `prefix-payload`, and a column default that wrote the bare payload\n * would disagree with every row the application inserts. No other format has\n * a server-side equivalent: `uuidv7()` arrives in PostgreSQL 18, and ULID,\n * KSUID, NanoID and CUID2 have none at all, so those fields carry no DDL\n * default and the application's own generator remains their single owner.\n */\n override getDefaultExpression(\n scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n const literal =\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n !scalarState.decimal &&\n (scalarState.array ||\n scalarState.type === \"datetime\" ||\n scalarState.type === \"date\")\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n scalarState.array &&\n Array.isArray(literal)\n ) {\n if (scalarState.decimal)\n return super.getDefaultExpression(scalar, scalarState);\n // A JSON field has no list form: members are scalars or temporals.\n const members = literal.map((value) =>\n (scalarState.type === \"datetime\" || scalarState.type === \"date\") &&\n typeof value === \"string\"\n ? encodePostgresTemporal(value)\n : value\n );\n return this.escapeValue(arrayLiteralText(members));\n }\n // `gen_random_uuid()` produces a `uuid`, so a column that does not hold one\n // cannot take it as a default. A `.uuid()` field whose native type override\n // makes it `bytea` is exactly that column: the value would be a type error\n // at DDL time, and the application generator is already its single owner.\n if (scalarState.hasDefault && scalarState.default === null)\n return undefined;\n if (\n scalarState.type === \"datetime\" &&\n scalarState.autoGenerate?.kind === \"now\"\n ) {\n const physical = this.mapScalarType(scalar, scalarState).toLowerCase();\n const clock =\n physical.includes(\"timestamptz\") || physical.includes(\"with time zone\")\n ? \"CURRENT_TIMESTAMP\"\n : \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n // PostgreSQL's omitted precision is six. Our generated logical DateTime\n // must remain a millisecond value even when native storage is wider.\n const precision = Number(\n TEMPORAL_PRECISION_TOKEN.exec(physical)?.[1] ?? 6\n );\n return precision > 3 ? `date_trunc('milliseconds', ${clock})` : clock;\n }\n if (\n (scalarState.type === \"datetime\" || scalarState.type === \"date\") &&\n scalarState.autoGenerate === undefined &&\n scalarState.hasDefault &&\n typeof literal === \"string\"\n )\n return this.escapeValue(encodePostgresTemporal(literal));\n if (scalarState.autoGenerate?.kind === \"now\") {\n if (scalarState.type === \"date\")\n return \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n if (scalarState.type === \"time\") {\n const physical = this.mapScalarType(scalar, scalarState).toLowerCase();\n if (Number(TEMPORAL_PRECISION_TOKEN.exec(physical)?.[1] ?? 6) > 3)\n return \"timezone('UTC', CURRENT_TIME(3))\";\n return physical.includes(\"timetz\") ||\n physical.includes(\"with time zone\")\n ? \"timezone('UTC', CURRENT_TIME)\"\n : \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n }\n }\n const idDomain = idDomainOfState(scalarState);\n if (\n idDomain !== undefined &&\n idStorageOf(idDomain, scalar[\"~\"].nativeType, \"pg\")?.representation ===\n \"bytes\"\n ) {\n return undefined;\n }\n // DDL follows the scalar's own generator rule (string/scalar.ts\n // `withIdentifier`): only a uuid generator the scalar INSTALLED becomes\n // `gen_random_uuid()`. A non-key `.uuid()` and a `generate: false` key are\n // caller-supplied, and a later `.default(...)` replaces the generator.\n if (\n scalarState.autoGenerate?.kind === \"uuid\" &&\n !isGeneratorDefault(scalarState.default)\n )\n return undefined;\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n protected override getAutoGenerateExpression(\n autoGenerate: import(\"@schema/scalars\").ScalarState[\"autoGenerate\"]\n ): string | undefined {\n switch (autoGenerate?.kind) {\n case \"uuid\":\n // `.id()`'s implicit ULID never reaches here (its kind is `ulid`), and\n // a NAMED `.uuid()` gets the database default only unprefixed.\n return hasIdPrefix(autoGenerate.prefix)\n ? undefined\n : \"gen_random_uuid()\";\n case \"now\":\n // Use database-level NOW() for consistent timestamps\n return \"NOW()\";\n default:\n return undefined;\n }\n }\n\n getEnumColumnType(\n tableName: string,\n columnName: string,\n _values: string[]\n ): string {\n return derivedMigrationName(`${tableName}_${columnName}_enum`);\n }\n\n // ===========================================================================\n // OVERRIDES: Column Definition Helpers\n // ===========================================================================\n\n /**\n * PostgreSQL integer types that support SERIAL auto-increment.\n */\n private static readonly SERIAL_TYPE_MAP: Record<string, string> = {\n integer: \"SERIAL\",\n int4: \"SERIAL\",\n int: \"SERIAL\",\n bigint: \"BIGSERIAL\",\n int8: \"BIGSERIAL\",\n smallint: \"SMALLSERIAL\",\n int2: \"SMALLSERIAL\",\n };\n\n /**\n * Formats the column type for PostgreSQL.\n * Handles SERIAL types for auto-increment and managed-enum qualification.\n */\n protected override formatColumnType(\n column: ColumnDef,\n context: DDLContext\n ): string {\n // Handle auto-increment with SERIAL types\n if (column.autoIncrement) {\n const normalizedType = column.type.toLowerCase();\n const serialType =\n PostgresMigrationDriver.SERIAL_TYPE_MAP[normalizedType];\n\n if (!serialType) {\n throw new MigrationError(\n \"PostgreSQL auto-increment (SERIAL) requires an integer type (INTEGER, BIGINT, SMALLINT). \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment.`,\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n column: column.name,\n type: column.type,\n autoIncrement: true,\n },\n }\n );\n }\n\n return serialType;\n }\n\n // A managed enum is a persistent object of this estate and is qualified\n // exactly like a table; its array form takes the same prefix. Everything\n // else — built-ins and the adapter-supported extension spellings — is a\n // provider object and passes through.\n return this.renderTypeToken(column.type, context);\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n const { table } = op;\n const columnDefs = table.columns.map((col) =>\n this.generateColumnDef(col, context)\n );\n\n if (table.primaryKey) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const pkName = `CONSTRAINT ${this.escapeIdentifier(this.generatedPrimaryKeyName(table.name, table.primaryKey.name))} `;\n columnDefs.push(`${pkName}PRIMARY KEY (${pkCols})`);\n }\n\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n columnDefs.push(\n `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n const sql = `CREATE TABLE ${this.qualify(table.name)} (\\n ${columnDefs.join(\",\\n \")}\\n)`;\n\n const statements = [sql];\n\n for (const idx of table.indexes) {\n statements.push(\n this.generateCreateIndex(\n {\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n },\n context\n )\n );\n }\n\n for (const fk of table.foreignKeys) {\n statements.push(\n this.generateAddForeignKey(\n {\n type: \"addForeignKey\",\n tableName: table.name,\n fk,\n },\n context\n )\n );\n }\n\n return statements;\n }\n\n /**\n * No `CASCADE` (§6.1). It dropped views, foreign keys and dependants in OTHER\n * schemas even though the enumeration behind this operation only ever\n * selected one, which made the namespace a filter instead of a boundary. The\n * foreign keys inside the program are materialized as explicit\n * `dropForeignKey` operations that sort ahead of every table drop\n * (`materializeDroppedTableForeignKeys`), and anything left is a dependency\n * this estate does not own: PostgreSQL's default `RESTRICT` then aborts the\n * transaction instead of deleting it.\n */\n generateDropTable(op: DropTableOperation, _context: DDLContext): string {\n return `DROP TABLE ${this.qualify(op.tableName)}`;\n }\n\n // `RENAME TO` takes ONE unqualified identifier: PostgreSQL renames the table\n // inside its own schema, and a qualified new name is a syntax error, not a\n // move (§4.1).\n generateRenameTable(op: RenameTableOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.qualify(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\n }\n\n protected override renameDerivedNames(\n owner: string,\n renames: ReadonlyMap<string, DerivedRename>\n ): string[] {\n return [...renames].map(([from, { kind, to }]) =>\n kind === \"constraint\"\n ? `ALTER TABLE ${this.qualify(owner)} RENAME CONSTRAINT ${this.escapeIdentifier(from)} TO ${this.escapeIdentifier(to)}`\n : `ALTER ${kind === \"type\" ? \"TYPE\" : \"INDEX\"} ${this.qualify(from)} RENAME TO ${this.escapeIdentifier(to)}`\n );\n }\n\n /** Generated keys have an explicit bounded name; catalog omissions stay unknown. */\n override generatedPrimaryKeyName(tableName: string, name?: string): string {\n return name || derivedMigrationName(`${tableName}_pkey`);\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(op: AddColumnOperation, context: DDLContext): string {\n const colDef = this.generateColumnDef(op.column, context);\n return `ALTER TABLE ${this.qualify(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n generateRenameColumn(\n op: RenameColumnOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n const { tableName, columnName, from, to } = op;\n const statements: string[] = [];\n const table = this.qualify(tableName);\n const col = this.escapeIdentifier(columnName);\n\n // A decimal descriptor change is VALIDATED BEFORE the type moves, and the\n // proof stays live across it. `ALTER TYPE numeric(p,s) USING c::numeric(p,s)`\n // on its own ROUNDS a value with too many fractional digits — silently\n // rewriting stored data, which §7.3 forbids outright (\"No descriptor change\n // rounds existing data\"). The constraint refuses those rows instead, before\n // any DDL runs, and because it is only dropped afterwards no concurrent\n // write can land an unrepresentable value while the conversion is in\n // flight. The whole sequence is one transaction on PostgreSQL, so a\n // refusal takes the validation, the DDL and the metadata back together.\n //\n // The TARGET domain alone is the whole predicate — `c = c::numeric(p,s)`\n // says \"this value survives the conversion unchanged\" without consulting\n // where it came from. So an unconstrained `numeric` adopted by a declared\n // descriptor is validated exactly like a descriptor-to-descriptor change;\n // skipping it there was the one path on which the `USING` cast still\n // rounded.\n const conversion = decimalConversionRequired(from, to);\n if (conversion && to.decimal) {\n const targetType = this.renderTypeToken(to.type, context);\n const constraint = this.escapeIdentifier(\n decimalConversionConstraintName(\n targetType.endsWith(\"[]\") ? \"list\" : \"scalar\",\n to.decimal\n )\n );\n // The migration owner's table lock, taken inside the transaction the\n // executor already opened (§7.4): it makes the validation and the type\n // change one lock acquisition rather than two, so nothing interleaves\n // between the row the constraint proved and the row the cast reads.\n statements.push(`LOCK TABLE ${table} IN ACCESS EXCLUSIVE MODE`);\n statements.push(\n `ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${postgresDecimalFitsCheck(col, targetType)})`\n );\n }\n\n if (from.type !== to.type) {\n if (from.default !== undefined) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP DEFAULT`\n );\n }\n // The new type is a column type token like any other, so a managed enum\n // is qualified here too — in BOTH positions, since the `USING` cast names\n // the same type the column is being changed to.\n const newType = this.renderTypeToken(to.type, context);\n // text → uuid is the ONE identifier conversion a dialect performs on its\n // own, and the only one whose failure is per-row rather than structural.\n // The guard changes no outcome — the cast below refuses the same estate —\n // it replaces \"invalid input syntax for type uuid\" with the count and the\n // two routes, before the transaction is spent.\n if (isPostgresTextToUuid(from.type, newType)) {\n statements.push(postgresTextToUuidGuard(table, col));\n }\n const fromBase = from.type.endsWith(\"[]\")\n ? from.type.slice(0, -2)\n : from.type;\n const throughText = this.managedEnumNames(context).has(fromBase)\n ? `::text${from.type.endsWith(\"[]\") ? \"[]\" : \"\"}`\n : \"\";\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} TYPE ${newType} USING ${col}${throughText}::${newType}`\n );\n }\n\n if (from.nullable !== to.nullable) {\n if (to.nullable) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP NOT NULL`\n );\n } else {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} SET NOT NULL`\n );\n }\n }\n\n if (\n from.default !== to.default ||\n (from.type !== to.type && from.default !== undefined)\n ) {\n if (to.default === undefined) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP DEFAULT`\n );\n } else {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} SET DEFAULT ${to.default}`\n );\n }\n }\n\n if (conversion && to.decimal) {\n const targetType = this.renderTypeToken(to.type, context);\n statements.push(\n `ALTER TABLE ${table} DROP CONSTRAINT ${this.escapeIdentifier(decimalConversionConstraintName(targetType.endsWith(\"[]\") ? \"list\" : \"scalar\", to.decimal))}`\n );\n }\n\n return statements;\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n // A low-lock build (T5b) runs CONCURRENTLY: writes keep flowing while it\n // reads the table, and an interrupted one leaves the index INVALID for\n // `resolve` to repair.\n generateCreateIndex(\n op: CreateIndexOperation,\n context: LowLockContext\n ): string {\n const { tableName, index } = op;\n const physicalType = index.type === \"spatial\" ? \"gist\" : index.type;\n\n // Validate index type against capabilities\n this.validateIndexType(physicalType, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const indexType = physicalType ? `USING ${physicalType} ` : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const where = index.where ? ` WHERE ${index.where}` : \"\";\n // PostgreSQL does not allow a schema on the index name in CREATE INDEX —\n // the index is created in the target table's schema, which is why the\n // TABLE carries the qualification and the index name is one identifier.\n const concurrently = context.lowLock === \"add\" ? \" CONCURRENTLY\" : \"\";\n return `CREATE ${unique}INDEX${concurrently} ${this.escapeIdentifier(index.name)} ON ${this.qualify(tableName)} ${indexType}(${cols})${where}`;\n }\n\n // DROP INDEX names the index itself, which lives in a schema and takes one\n // (§4.1) — the mirror of CREATE INDEX above.\n generateDropIndex(op: DropIndexOperation, _context: DDLContext): string {\n return `DROP INDEX ${this.qualify(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n // A low-lock key (T5b) is added NOT VALID, which checks new rows only and\n // scans nothing, and validated by a later commit, whose scan blocks no write.\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: LowLockContext\n ): string {\n const { tableName, fk } = op;\n if (context.lowLock === \"validate\") {\n return `ALTER TABLE ${this.qualify(tableName)} VALIDATE CONSTRAINT ${this.escapeIdentifier(fk.name)}`;\n }\n const cols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const onDelete = fk.onDelete\n ? ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`\n : \"\";\n const onUpdate = fk.onUpdate\n ? ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`\n : \"\";\n // Both TABLE positions are qualified — the owner and the reference target.\n // A bare `REFERENCES` target resolves through `search_path` and would let\n // one estate's constraint point at another schema's table.\n const notValid = context.lowLock === \"add\" ? \" NOT VALID\" : \"\";\n return `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(fk.name)} FOREIGN KEY (${cols}) REFERENCES ${this.qualify(fk.referencedTable)} (${refCols})${onDelete}${onUpdate}${notValid}`;\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.fkName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n _context: DDLContext\n ): string {\n const { tableName, constraint } = op;\n const cols = constraint.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(constraint.name)} UNIQUE (${cols})`;\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n _context: DDLContext\n ): string {\n const { tableName, primaryKey } = op;\n const cols = primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const name = this.escapeIdentifier(\n this.generatedPrimaryKeyName(tableName, primaryKey.name)\n );\n return `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${name} PRIMARY KEY (${cols})`;\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n // An enum OPERATION names an ORM-managed enum by construction, so its type\n // name is qualified unconditionally — the managed-enum SET exists only to\n // decide whether a COLUMN's type token happens to name one.\n generateCreateEnum(op: CreateEnumOperation, _context: DDLContext): string {\n const { enumDef } = op;\n const values = enumDef.values.map((v) => this.escapeValue(v)).join(\", \");\n return `CREATE TYPE ${this.qualify(enumDef.name)} AS ENUM (${values})`;\n }\n\n generateDropEnum(op: DropEnumOperation, _context: DDLContext): string {\n return `DROP TYPE ${this.qualify(op.enumName)}`;\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * The TRANSACTION lock a batch request takes after its limits (plans D1,\n * D7): it ends with the transaction, so nothing outlives the request. One\n * request cannot loop across requests, so it retries on the server until\n * the command's `lockWait` (default 10 s) passes, holding its snapshot that\n * long; the transaction's `statement_timeout` is longer by construction\n * (`resolveMigrationLimits`), so the loop is never cut short. A session\n * waits instead with one {@link generateLockFree} try per transaction,\n * holding no snapshot between them (`pinned-session.ts`). Stepwise work\n * adds the session lock on top ({@link generateSessionLock}), and releases\n * that one with {@link generateReleaseLock}.\n */\n generateAcquireLock(lockId: number): string | null {\n const { lockWait } = this.limits ?? DEFAULT_MIGRATION_LIMITS;\n return `WITH RECURSIVE lock_attempt AS (\n SELECT pg_try_advisory_xact_lock(${lockId}) AS acquired, clock_timestamp() + interval '${lockWait / 1000} seconds' AS deadline\n UNION ALL\n SELECT pg_try_advisory_xact_lock(${lockId}), previous.deadline\n FROM lock_attempt previous\n CROSS JOIN LATERAL (SELECT pg_sleep(CASE WHEN previous.acquired THEN 0 ELSE 0.05 END)) waiting\n WHERE NOT previous.acquired AND clock_timestamp() < previous.deadline\n ) SELECT acquired FROM lock_attempt ORDER BY acquired DESC LIMIT 1`;\n }\n\n generateReleaseLock(lockId: number): string | null {\n return `SELECT pg_advisory_unlock(${lockId}) AS released`;\n }\n\n /**\n * PlanetScale's Neki refuses a session advisory lock and a transaction one\n * in the same session (`NK013`, \"Mixing session and transaction advisory\n * locks is unavailable\"), so a command there holds only the session lock.\n */\n override holdsSessionLock(read: RawExecutor): Promise<boolean> {\n // Read afresh for each command: its answer is then the command's.\n NEKI.delete(this);\n return serverIsNeki(this, read);\n }\n\n override generateSessionLock(lockId: number): string {\n return `SELECT pg_try_advisory_lock(${lockId}) AS acquired`;\n }\n\n /**\n * Takes the transaction lock: outside a transaction, it releases with the\n * statement that asks; inside one, it is that transaction's lock try.\n */\n override generateLockFree(lockId: number): string {\n return `pg_try_advisory_xact_lock(${lockId})`;\n }\n\n /** A lock try, or the batch's loop: only boolean true proves ownership. */\n override provesLockAcquired(rows: readonly unknown[]): boolean {\n const row = rows[0];\n return (\n rows.length === 1 &&\n typeof row === \"object\" &&\n row !== null &&\n Reflect.get(row, \"acquired\") === true\n );\n }\n\n /**\n * `pg_advisory_unlock` returns a real boolean: `true` when this session held\n * the lock and released it, `false` when it never held it. Only one boolean\n * `true` proves the release; `false`, a missing row, extra rows, or anything\n * that is not a boolean leaves the session holding a lock nobody will free.\n */\n override provesLockReleased(rows: readonly unknown[]): boolean {\n if (rows.length !== 1) {\n return false;\n }\n const row = rows[0];\n if (typeof row !== \"object\" || row === null) {\n return false;\n }\n return Reflect.get(row, \"released\") === true;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n // Both inventories BIND the schema: they are the reads that decide what a\n // reset drops, and §4.2 admits no interpolated catalog operand.\n generateInventoryTables(): { sql: string; params: unknown[] } {\n return {\n sql: POSTGRES_MANAGED_TABLE_NAMES_QUERY,\n params: [this.requireEstateNamespace()],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n return {\n sql: `SELECT t.typname AS name\n FROM pg_type t\n JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n WHERE t.typtype = 'e' AND n.nspname = $1\n ORDER BY t.typname`,\n params: [this.requireEstateNamespace()],\n };\n }\n\n // No CASCADE here or on the inherited table drop (§6.1). PostgreSQL's\n // default RESTRICT is the containment boundary: a dependant this estate does\n // not own aborts the operation instead of being deleted with it.\n override generateDropEnumSQL(enumName: string): string | null {\n return `DROP TYPE IF EXISTS ${this.qualify(enumName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): readonly string[] {\n const physicalContext = {\n ...context,\n currentSchema: this.schemaAtOperation(context),\n };\n const {\n enumName,\n addValues = [],\n removeValues,\n newValues,\n dependentColumns,\n } = op;\n const statements: string[] = [];\n const enumType = this.qualify(enumName);\n const before =\n physicalContext.currentSchema?.enums?.find(\n (item) => item.name === enumName\n )?.values ?? [];\n const reordered =\n newValues !== undefined &&\n before.filter((value) => newValues.includes(value)).join(\"\\0\") !==\n newValues.filter((value) => before.includes(value)).join(\"\\0\");\n // ADD VALUE only touches the catalog; a recreated type admits a later\n // read of an added value in the same transaction.\n const usesAddedValue = readsAddedValue(\n enumName,\n addValues,\n physicalContext.currentSchema?.tables ?? [],\n context.followingOperations ?? []\n );\n if (!(removeValues?.length || reordered || usesAddedValue)) {\n const available = new Set(before);\n for (const value of addValues) {\n const following = newValues\n ?.slice(newValues.indexOf(value) + 1)\n .find((candidate) => available.has(candidate));\n statements.push(\n `ALTER TYPE ${enumType} ADD VALUE ${this.escapeValue(value)}${following === undefined ? \"\" : ` BEFORE ${this.escapeValue(following)}`}`\n );\n available.add(value);\n }\n return statements;\n }\n if (!newValues?.length)\n throw new MigrationError(\n `Cannot alter enum \"${enumName}\" without its full destination values`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n for (const { tableName, columnName } of dependentColumns ?? []) {\n const column = physicalContext.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((item) => item.name === columnName);\n const reference = `${this.qualify(tableName)} ALTER COLUMN ${this.escapeIdentifier(columnName)}`;\n if (column?.default !== undefined)\n statements.push(`ALTER TABLE ${reference} DROP DEFAULT`);\n const carrier = column?.type.endsWith(\"[]\") ? \"text[]\" : \"text\";\n statements.push(\n `ALTER TABLE ${reference} TYPE ${carrier} USING ${this.escapeIdentifier(columnName)}::${carrier}`\n );\n }\n statements.push(...this.buildEnumReplacementUpdates(op, physicalContext));\n statements.push(`DROP TYPE ${enumType}`);\n statements.push(\n `CREATE TYPE ${enumType} AS ENUM (${newValues.map((value) => this.escapeValue(value)).join(\", \")})`\n );\n for (const { tableName, columnName } of dependentColumns ?? []) {\n const column = physicalContext.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((item) => item.name === columnName);\n const reference = `${this.qualify(tableName)} ALTER COLUMN ${this.escapeIdentifier(columnName)}`;\n const target = column?.type.endsWith(\"[]\") ? `${enumType}[]` : enumType;\n statements.push(\n `ALTER TABLE ${reference} TYPE ${target} USING ${this.escapeIdentifier(columnName)}::${target}`\n );\n if (\n column?.default !== undefined &&\n !enumDefaultLabels(column, enumName).some(\n (label) => label !== null && removeValues?.includes(label)\n )\n )\n statements.push(\n `ALTER TABLE ${reference} SET DEFAULT ${column.default}`\n );\n }\n return statements;\n }\n\n /**\n * An array column's members move in one UPDATE that keeps their order; a\n * scalar column takes the shared per-value UPDATEs.\n */\n protected override enumColumnReplacementUpdates(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string,\n context: DDLContext\n ): string[] {\n const columnType = context.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((column) => column.name === columnName)?.type;\n if (!columnType?.endsWith(\"[]\")) {\n return super.enumColumnReplacementUpdates(\n op,\n tableName,\n columnName,\n context\n );\n }\n const cases = this.enumReplacementCases(op, tableName, columnName);\n if (cases.length === 0) return [];\n const column = this.escapeIdentifier(columnName);\n return [\n `UPDATE ${this.qualify(tableName)} SET ${column} = ARRAY(SELECT CASE value ${cases.join(\" \")} ELSE value END FROM unnest(${column}) WITH ORDINALITY AS member(value, position) ORDER BY position) WHERE ${column} IS NOT NULL`,\n ];\n }\n}\n\n// Export singleton instance\nexport const postgresMigrationDriver = new PostgresMigrationDriver();\n"],"mappings":"qwBA+CA,MACM,EAAqB,QACrB,EAAc,KAYpB,SAAS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U,EAAM,OAAS,EAAU,EACxC,QAAQ,KAAM,GAAS,EAAK,OAAS,EAAW,CAC9C,EAAY,GAAG,KAAK,QAAQ,EAAU,CAAC,gBAAgB,KAAK,iBAAiB,EAAW,GACxF,EAAS,GAAQ,KAAK,SAAS,KAAK,CAAG,GAAG,EAAS,IAAM,EAC/D,EAAW,KACT,eAAe,EAAU,QAAQ,EAAO,SAAS,KAAK,iBAAiB,EAAW,CAAC,IAAI,IACxF,CAEC,GAAQ,UAAY,IAAA,IACpB,CAAC,kBAAkB,EAAQ,EAAS,CAAC,KAClC,GAAU,IAAU,MAAQ,GAAc,SAAS,EAAM,CAC3D,EAED,EAAW,KACT,eAAe,EAAU,eAAe,EAAO,UAChD,CAEL,OAAO,EAOT,6BACE,EACA,EACA,EACA,EACU,CAIV,GAAI,EAHe,EAAQ,eAAe,OACvC,KAAM,GAAU,EAAM,OAAS,EAAU,EACxC,QAAQ,KAAM,GAAWC,EAAO,OAAS,EAAW,EAAE,OACzC,SAAS,KAAK,CAC7B,OAAO,MAAM,6BACX,EACA,EACA,EACA,EACD,CAEH,IAAM,EAAQ,KAAK,qBAAqB,EAAI,EAAW,EAAW,CAClE,GAAI,EAAM,SAAW,EAAG,MAAO,EAAE,CACjC,IAAM,EAAS,KAAK,iBAAiB,EAAW,CAChD,MAAO,CACL,UAAU,KAAK,QAAQ,EAAU,CAAC,OAAO,EAAO,6BAA6B,EAAM,KAAK,IAAI,CAAC,8BAA8B,EAAO,wEAAwE,EAAO,cAClN"}
|
|
1
|
+
{"version":3,"file":"postgres-BSmy1PYR.mjs","names":["elementType","quoted","column"],"sources":["../src/migrations/drivers/postgres/canonicalize-index-predicate.ts","../src/migrations/drivers/postgres/introspect.ts","../src/migrations/drivers/postgres/catalog-digest.ts","../src/migrations/drivers/postgres/index.ts"],"sourcesContent":["/**\n * Decision 7.4 — the declared partial-index predicate, canonicalized by the\n * database that will store it.\n *\n * PostgreSQL's catalog does not keep the statement it was given. `CREATE INDEX\n * … WHERE published = true` is parsed into a node tree, and\n * `pg_get_expr(indpred, indrelid)` deparses that tree back out as\n * `(published = true)`. The introspection reads the deparsed form; the\n * serializer holds the declared form; they never compare equal, so **every push\n * dropped and re-created every partial index**. SQLite has no such gap — it\n * stores the CREATE INDEX text verbatim — which is why only this dialect\n * implements the hook.\n *\n * The fix asks PostgreSQL itself. A predicate is put through the same parse and\n * deparse the catalog performs, and the differ compares the two answers. If\n * both texts deparse to one text they are one predicate; if either cannot be\n * deparsed, nothing is claimed and the drop/create stands. No client-side text\n * normalization can do this and stay fail-closed: flattening whitespace and\n * parentheses makes `a AND (b OR c)` read equal to `(a AND b) OR c`, and a real\n * predicate change would stop being seen.\n *\n * The vehicle is a scratch view: `SELECT 1 AS c FROM <table> WHERE <p>`, read\n * back with `pg_get_viewdef`. A view is the cheapest parse-and-store\n * PostgreSQL offers — no table scan, no data touched, only an ACCESS SHARE lock\n * on the table. A CHECK constraint or a real index would each parse the same\n * expression, but one locks the table against writers and the other builds\n * the index this is trying to avoid building.\n *\n * The view is a regular one, in the estate's own schema, created, read and\n * dropped in one transaction, so no other session ever sees it and nothing\n * outlives the transaction. PlanetScale's Neki has no temporary relations\n * (`NK013`), and its router resolves neither a `regclass` literal nor a\n * relation name for a relation created earlier in the transaction, so the\n * read finds the view through `pg_class`, by oid. Its name carries a random\n * part: two sessions canonicalizing one table at once never wait on each\n * other's uncommitted catalog row.\n *\n * Both sides of the comparison go through this same transform, so the answer\n * does not depend on `pg_get_viewdef` and `pg_get_expr` agreeing on\n * parenthesization — only on each being a function of the parsed tree.\n *\n * The predicate is interpolated, not bound: it is an expression, and no\n * parameter placeholder can carry one. It reaches here from the schema's own\n * `.index({ where })`, the same text the emitter already interpolates into\n * `CREATE INDEX`, so this widens nothing.\n */\n\nconst SCRATCH_VIEW_PREFIX = \"viborm_index_predicate_\";\nconst TRAILING_SEMICOLON = /;\\s*$/;\nconst UUID_DASHES = /-/g;\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/** Sends statements as ONE request, in one transaction, answering each. */\nexport type BatchExecutor = <T>(\n statements: readonly string[]\n) => Promise<ReadonlyArray<{ rows: T[] }>>;\n\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction quoteLiteral(text: string): string {\n return `'${text.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Deparses each predicate through PostgreSQL and returns the answers\n * positionally.\n *\n * `table` arrives ALREADY QUALIFIED and quoted by the bound migration driver,\n * and `namespace` is that estate's schema, where the scratch views live. A bare\n * table name would canonicalize this estate's predicate against a same-named\n * table in another schema on the session's `search_path` — and then hand that\n * answer to the differ as if it described the estate's own index.\n *\n * Throws rather than reporting a failure per predicate. The caller runs this\n * inside one transaction: a statement that fails aborts it, every later\n * statement in it fails too, and the rollback is what removes the scratch views\n * — which must go, because a view referencing a table blocks dropping that\n * table later in the same push.\n *\n * Each pass creates, reads and drops its views. `executeBatch`, on a transport\n * with no session (Neon HTTP, plan D7), sends each pass as one request: its\n * statements in one transaction, so on one backend, where separate requests\n * may each land on another.\n */\nexport async function canonicalizeIndexPredicates(\n namespace: string,\n table: string,\n predicates: readonly string[],\n executeRaw: RawExecutor,\n executeBatch?: BatchExecutor\n): Promise<ReadonlyArray<string | undefined>> {\n if (predicates.length === 0) return [];\n const run: BatchExecutor =\n executeBatch ??\n (async <T>(statements: readonly string[]) => {\n const results: { rows: T[] }[] = [];\n for (const sql of statements) results.push(await executeRaw<T>(sql));\n return results;\n });\n const deparse = async (queries: readonly (string | undefined)[]) => {\n // A position with no query has no answer, and no view.\n const live = [...queries.keys()].filter(\n (position) => queries[position] !== undefined\n );\n if (live.length === 0) return queries.map(() => undefined);\n const scratch = `${SCRATCH_VIEW_PREFIX}${crypto.randomUUID().replace(UUID_DASHES, \"\")}_`;\n const names = live.map((position) => `${scratch}${position}`);\n const views = names.map(\n (name) => `${quoteIdentifier(namespace)}.${quoteIdentifier(name)}`\n );\n const results = await run<{ name: string; definition: string | null }>([\n ...live.map(\n (position, index) =>\n `CREATE VIEW ${views[index]} AS ${queries[position]}`\n ),\n `SELECT c.relname AS name, pg_catalog.pg_get_viewdef(c.oid) AS definition FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${quoteLiteral(namespace)} AND c.relname IN (${names.map(quoteLiteral).join(\", \")})`,\n `DROP VIEW ${views.join(\", \")}`,\n ]);\n const answers = new Map(\n results[live.length]?.rows.map((row) => [row.name, row.definition])\n );\n return queries.map((query, position) =>\n query === undefined\n ? undefined\n : (answers.get(`${scratch}${position}`) ?? undefined)\n );\n };\n\n // Two passes: one parse and deparse is not a fixed point. PostgreSQL\n // expands BETWEEN after its grammar has flattened AND, so a declared\n // `a BETWEEN x AND y AND b` parses to a nested AND, which its own deparse\n // (the catalog's text) reparses flat. Parsing each answer once more gives\n // the declared and the catalog spelling the same tree.\n const once = await deparse(\n predicates.map(\n (predicate) => `SELECT 1 AS c FROM ${table} WHERE ${predicate}`\n )\n );\n return deparse(once.map((query) => query?.replace(TRAILING_SEMICOLON, \"\")));\n}\n","/**\n * PostgreSQL Schema Introspection\n *\n * Reads the current database schema from PostgreSQL's information_schema\n * and system catalogs, returning a normalized SchemaSnapshot.\n *\n * Every catalog query is NAMESPACE-RELATIVE: the selected schema arrives as a\n * bound parameter (`$1`), never as a literal in a predicate and never as a\n * `public` fallback. The snapshot it produces stays namespace-RELATIVE in the\n * other direction — table, enum and type names are bare, exactly as the\n * serializer spells them — so one estate's snapshot never carries the schema\n * its DDL renderer qualifies with.\n */\n\nimport {\n canonicalizeDecimal,\n type DecimalDescriptor,\n decimalDefaultText,\n} from \"@validation/primitives/decimal-codec\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { readStoredDecimalDescriptor } from \"../../decimal\";\nimport type {\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport { groupBy, groupByNested, mapReferentialAction } from \"../utils\";\nimport { throwIfCatalogRefusal } from \"./catalog-refusal\";\n\nimport type {\n PgColumn,\n PgCrossSchemaForeignKey,\n PgEnum,\n PgForeignKey,\n PgIndex,\n PgPrimaryKey,\n PgTable,\n PgUniqueConstraint,\n} from \"./types\";\n\n// Regex for cleaning up PostgreSQL type casting (e.g., 'value'::text -> 'value')\nconst TYPE_CAST_REGEX =\n /::(?:\"(?:[^\"]|\"\")+\"|[a-zA-Z_][\\w$]*)(?:\\.(?:\"(?:[^\"]|\"\")+\"|[a-zA-Z_][\\w$]*))?(?:\\s+(?:varying|precision|with time zone|without time zone))?(?:\\(\\d+(?:,\\s*\\d+)?\\))?(?:\\[\\])?$/;\n\n/** The schemas PostgreSQL's own types live in; never estate-owned. */\nconst BUILT_IN_TYPE_SCHEMAS = new Set([\"pg_catalog\", \"information_schema\"]);\n\n/**\n * What one introspection run is bound to.\n *\n * `namespace` is the estate's schema, and `admittedExtensionTypes` is the set\n * of extension-owned base type names the CONCRETE adapter declares typmods\n * for (pgvector's `vector`, PostGIS's `geometry`/`geography`). An extension\n * type outside that set is still read — through `udt_name`, the way every\n * snapshot written before `format_type` was consulted holds it.\n */\nexport interface PostgresIntrospectionScope {\n readonly namespace: string;\n readonly tables?: readonly string[];\n readonly admittedExtensionTypes: ReadonlySet<string>;\n}\n\n/**\n * Extension-owned base types whose SERVER-FORMATTED spelling introspection\n * reads, keyed by the adapter capability that declares them.\n *\n * These are the types whose modifiers a snapshot cannot be written without\n * (`vector(3)`, `geometry(Point,4326)`), so introspection reads\n * `format_type` for them instead of `udt_name`. The set admits a SPELLING,\n * never a type: an extension type outside it — `citext`, and anything else a\n * database has installed — reads back through `udt_name` like every built-in,\n * which is the spelling this driver's own renderer emits for it.\n */\nconst EXTENSION_TYPES_BY_CAPABILITY = {\n supportsVector: [\"vector\", \"halfvec\", \"sparsevec\"],\n geoPoint: [\"geometry\", \"geography\"],\n} as const;\n\n/**\n * The extension-owned base types the bound execution driver's adapter\n * declares, and whose `format_type` spelling introspection therefore reads.\n */\nexport function admittedExtensionTypes(\n executionDriver: AnyDriver | undefined\n): ReadonlySet<string> {\n const adapter = executionDriver?.adapter;\n return new Set([\n ...(adapter?.capabilities.supportsVector\n ? EXTENSION_TYPES_BY_CAPABILITY.supportsVector\n : []),\n ...(adapter?.geoPoint ? EXTENSION_TYPES_BY_CAPABILITY.geoPoint : []),\n ]);\n}\n\n/** An index row, with the validity an interrupted CONCURRENTLY build clears. */\ntype PgIndexRow = PgIndex & { readonly is_valid: boolean };\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n// =============================================================================\n// SQL QUERIES\n// =============================================================================\n\nexport const POSTGRES_MANAGED_TABLE_NAMES_SOURCE = `\nSELECT tables.table_name, tables.table_name AS name, relation.relkind AS relation_kind, relation.relispartition AS is_partition\nFROM information_schema.tables tables\nJOIN pg_catalog.pg_class relation\n ON relation.relname = tables.table_name\nJOIN pg_catalog.pg_namespace relation_namespace\n ON relation_namespace.oid = relation.relnamespace\n AND relation_namespace.nspname = tables.table_schema\nWHERE tables.table_schema = $1\n AND tables.table_type = 'BASE TABLE'\n AND NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend dependency\n JOIN pg_catalog.pg_extension extension\n ON extension.oid = dependency.refobjid\n WHERE dependency.classid = 'pg_catalog.pg_class'::pg_catalog.regclass\n AND dependency.objid = relation.oid\n AND dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND dependency.deptype = 'e'\n )\n`;\nexport const POSTGRES_MANAGED_TABLE_NAMES_QUERY = `${POSTGRES_MANAGED_TABLE_NAMES_SOURCE}ORDER BY tables.table_name;\n`;\n\n/**\n * Columns, with the type identity the snapshot cannot be built without.\n *\n * The catalog join beside `information_schema.columns` exists for two facts\n * that view cannot give: the server's formatted type (modifiers and array\n * structure) and the extension provenance that proves a non-estate type is a\n * provider object rather than an unknown external one. For an ARRAY column the\n * dependency is looked up on the ELEMENT type (`typcategory = 'A'`), because\n * the array type's own dependency is on its element, not on the extension.\n */\nexport const COLUMNS_SOURCE = `\nSELECT\n c.table_name,\n c.column_name,\n c.data_type,\n c.udt_schema,\n c.udt_name,\n c.is_nullable,\n c.column_default,\n a.attgenerated AS generated_kind,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n pg_catalog.format_type(a.atttypid, a.atttypmod) AS formatted_type,\n ext.extname AS type_extension,\n ext_ns.nspname AS type_extension_schema\nFROM information_schema.columns c\nJOIN information_schema.tables t\n ON c.table_name = t.table_name\n AND c.table_schema = t.table_schema\nJOIN pg_catalog.pg_class cls\n ON cls.relname = c.table_name\nJOIN pg_catalog.pg_namespace cls_ns\n ON cls_ns.oid = cls.relnamespace\n AND cls_ns.nspname = c.table_schema\nJOIN pg_catalog.pg_attribute a\n ON a.attrelid = cls.oid\n AND a.attname = c.column_name\nJOIN pg_catalog.pg_type col_type\n ON col_type.oid = a.atttypid\nLEFT JOIN pg_catalog.pg_depend dep\n ON dep.classid = 'pg_catalog.pg_type'::regclass\n AND dep.objid = CASE\n WHEN col_type.typcategory = 'A' THEN col_type.typelem\n ELSE col_type.oid\n END\n AND dep.deptype = 'e'\nLEFT JOIN pg_catalog.pg_extension ext\n ON ext.oid = dep.refobjid\nLEFT JOIN pg_catalog.pg_namespace ext_ns\n ON ext_ns.oid = ext.extnamespace\nWHERE c.table_schema = $1\n AND t.table_type = 'BASE TABLE'\n AND NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend relation_dependency\n JOIN pg_catalog.pg_extension relation_extension\n ON relation_extension.oid = relation_dependency.refobjid\n WHERE relation_dependency.classid = 'pg_catalog.pg_class'::pg_catalog.regclass\n AND relation_dependency.objid = cls.oid\n AND relation_dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND relation_dependency.deptype = 'e'\n )\n`;\nconst COLUMNS_QUERY = `${COLUMNS_SOURCE}ORDER BY c.table_name, c.ordinal_position;\n`;\n\nexport const PRIMARY_KEYS_SOURCE = `\nSELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\nWHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\n`;\nconst PRIMARY_KEYS_QUERY = `${PRIMARY_KEYS_SOURCE}ORDER BY tc.table_name, kcu.ordinal_position;\n`;\n\n/**\n * Standalone indexes. `conindid` names the index a UNIQUE or PRIMARY KEY\n * constraint owns — those stay in `uniqueConstraints` / `primaryKey`. A\n * foreign key also points `conindid` at the unique index it targets, so the\n * join must not treat that as ownership or a unique-index FK target vanishes\n * from both lists.\n *\n * `nullsNotDistinct` is the SQL that says whether a unique index takes NULLs\n * as equal, which no snapshot models: `ix.indnullsnotdistinct` where the\n * column exists ({@link NULLS_NOT_DISTINCT_QUERY}), `false` before PostgreSQL\n * 15. Never a whole-row read such as `to_jsonb(ix)`: PlanetScale's Neki\n * refuses a catalog relation's row type (0A000).\n */\nexport const indexesSource = (nullsNotDistinct: string): string => `\nSELECT\n t.relname AS table_name,\n i.relname AS index_name,\n a.attname AS column_name,\n ix.indisunique AS is_unique,\n ix.indisvalid AND ix.indisready AS is_valid,\n (ix.indexprs IS NOT NULL OR ix.indnkeyatts <> ix.indnatts OR ${nullsNotDistinct}\n OR EXISTS (SELECT 1 FROM unnest(ix.indoption) AS flags(value) WHERE flags.value <> 0)\n OR EXISTS (SELECT 1 FROM unnest(ix.indclass) AS classes(oid) JOIN pg_opclass AS opc ON opc.oid=classes.oid WHERE NOT opc.opcdefault)\n OR EXISTS (SELECT 1 FROM generate_series(0,ix.indnkeyatts-1) AS key(position) LEFT JOIN pg_attribute AS attr ON attr.attrelid=t.oid AND attr.attnum=ix.indkey[key.position] WHERE ix.indcollation[key.position] <> COALESCE(attr.attcollation,0))) AS unsupported_structure,\n am.amname AS index_type,\n pg_get_expr(ix.indpred, ix.indrelid) AS filter_condition,\n array_position(ix.indkey, a.attnum) AS ordinal_position\nFROM pg_index ix\nJOIN pg_class t ON t.oid = ix.indrelid\nJOIN pg_class i ON i.oid = ix.indexrelid\nJOIN pg_am am ON am.oid = i.relam\nJOIN pg_namespace n ON n.oid = t.relnamespace\nLEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)\nLEFT JOIN pg_constraint c\n ON c.conindid = ix.indexrelid\n AND c.contype IN ('u', 'p')\nWHERE n.nspname = $1\n AND NOT ix.indisprimary\n AND c.oid IS NULL\n AND t.relkind = 'r'\n`;\nconst INDEXES_ORDER = `ORDER BY t.relname, i.relname, array_position(ix.indkey, a.attnum);\n`;\n\n/** Whether this server's `pg_index` has `indnullsnotdistinct` (PostgreSQL 15+). */\nexport const NULLS_NOT_DISTINCT_QUERY = `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = 'pg_catalog.pg_index'::pg_catalog.regclass AND attname = 'indnullsnotdistinct' AND NOT attisdropped) AS present`;\n\n/**\n * Foreign keys OWNED by the selected schema.\n *\n * Read from `pg_constraint`, not `information_schema.referential_constraints`.\n * A foreign key may target a unique INDEX rather than a unique constraint;\n * that catalog view then leaves `unique_constraint_name` null and the join\n * drops the constraint. `pg_constraint.confrelid`/`confkey` still name the\n * referenced columns. Both sides stay in this schema so `referencedTable` is\n * a bare estate-relative name. A constraint that leaves the schema is not\n * silently dropped — `CROSS_SCHEMA_FOREIGN_KEYS_QUERY` inventories both\n * directions and refuses the whole run before this snapshot is published.\n */\nexport const FOREIGN_KEYS_SOURCE = `\nSELECT\n owner.relname AS table_name,\n con.conname AS constraint_name,\n local_att.attname AS column_name,\n referenced.relname AS foreign_table_name,\n referenced_att.attname AS foreign_column_name,\n CASE con.confdeltype\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'd' THEN 'SET DEFAULT'\n ELSE 'NO ACTION'\n END AS delete_rule,\n CASE con.confupdtype\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'd' THEN 'SET DEFAULT'\n ELSE 'NO ACTION'\n END AS update_rule,\n local.ordinality AS ordinal_position\nFROM pg_catalog.pg_constraint con\nJOIN pg_catalog.pg_class owner ON owner.oid = con.conrelid\nJOIN pg_catalog.pg_namespace owner_ns ON owner_ns.oid = owner.relnamespace\nJOIN pg_catalog.pg_class referenced ON referenced.oid = con.confrelid\nJOIN pg_catalog.pg_namespace referenced_ns ON referenced_ns.oid = referenced.relnamespace\nJOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS local(attnum, ordinality) ON TRUE\nJOIN LATERAL unnest(con.confkey) WITH ORDINALITY AS referenced_col(attnum, ordinality)\n ON referenced_col.ordinality = local.ordinality\nJOIN pg_catalog.pg_attribute local_att\n ON local_att.attrelid = owner.oid AND local_att.attnum = local.attnum\nJOIN pg_catalog.pg_attribute referenced_att\n ON referenced_att.attrelid = referenced.oid\n AND referenced_att.attnum = referenced_col.attnum\nWHERE con.contype = 'f'\n AND owner_ns.nspname = $1\n AND referenced_ns.nspname = $1\n`;\nconst FOREIGN_KEYS_QUERY = `${FOREIGN_KEYS_SOURCE}ORDER BY owner.relname, con.conname, local.ordinality;\n`;\n\n/**\n * Every foreign key with exactly ONE side in the selected schema.\n *\n * `pg_constraint` is joined to its owning and referenced relations through both\n * `pg_class`/`pg_namespace` pairs, so an INBOUND key — owned by a foreign\n * schema, pointing at an estate table — is found as readily as an outbound one.\n * The exclusive-or in the predicate is the whole test: a key with both sides in\n * the schema is ordinary, a key with neither belongs to somebody else.\n */\nexport const CROSS_SCHEMA_FOREIGN_KEYS_SOURCE = `\nSELECT\n con.conname AS constraint_name,\n owner_ns.nspname AS owning_schema,\n owner.relname AS owning_table,\n referenced_ns.nspname AS referenced_schema,\n referenced.relname AS referenced_table\nFROM pg_catalog.pg_constraint con\nJOIN pg_catalog.pg_class owner ON owner.oid = con.conrelid\nJOIN pg_catalog.pg_namespace owner_ns ON owner_ns.oid = owner.relnamespace\nJOIN pg_catalog.pg_class referenced ON referenced.oid = con.confrelid\nJOIN pg_catalog.pg_namespace referenced_ns ON referenced_ns.oid = referenced.relnamespace\nWHERE con.contype = 'f'\n AND (owner_ns.nspname = $1) <> (referenced_ns.nspname = $1)\n`;\nconst CROSS_SCHEMA_FOREIGN_KEYS_QUERY = `${CROSS_SCHEMA_FOREIGN_KEYS_SOURCE}ORDER BY owner_ns.nspname, owner.relname, con.conname;\n`;\n\nexport const UNIQUE_CONSTRAINTS_SOURCE = `\nSELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\nWHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\n`;\nconst UNIQUE_CONSTRAINTS_QUERY = `${UNIQUE_CONSTRAINTS_SOURCE}ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position;\n`;\n\nexport const ENUMS_SOURCE = `\nSELECT\n t.typname AS enum_name,\n e.enumlabel AS enum_value,\n e.enumsortorder AS sort_order\nFROM pg_type t\nJOIN pg_enum e ON t.oid = e.enumtypid\nJOIN pg_namespace n ON n.oid = t.typnamespace\nWHERE n.nspname = $1\n`;\nconst ENUMS_QUERY = `${ENUMS_SOURCE}ORDER BY t.typname, e.enumsortorder;\n`;\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\n/** The element type's name for an array type, else the name itself. */\nfunction baseTypeName(udtName: string): string {\n return udtName.startsWith(\"_\") ? udtName.slice(1) : udtName;\n}\n\n/**\n * The extension-owned type spelled the way this estate's DDL spells it.\n *\n * `format_type` qualifies the type when the extension's schema is not on the\n * session's `search_path` and leaves it bare when it is, so the same column\n * reads back two ways on two sessions. Removing exactly the PROVEN extension\n * schema — never a general prefix strip — makes the answer one, and keeps every\n * modifier and the array suffix the catalog supplied.\n */\nfunction stripExtensionSchema(formattedType: string, schema: string): string {\n for (const prefix of [`${schema}.`, `\"${schema.replaceAll('\"', '\"\"')}\".`]) {\n if (formattedType.startsWith(prefix)) {\n return formattedType.slice(prefix.length);\n }\n }\n return formattedType;\n}\n\n/**\n * The one unrepresentable class: a type of another schema that no installed\n * extension owns (§4.2's external enum, domain, composite or UDT).\n *\n * The refusal names both schemas in its MESSAGE. `meta` carries only keys the\n * error metadata allowlist admits (`src/errors/diagnostics.ts`), which has no\n * namespace key today, so the schema travels in the message rather than being\n * silently dropped from a metadata object that claims to carry it.\n */\nfunction refuseUnrepresentableType(\n col: PgColumn,\n scope: PostgresIntrospectionScope\n): never {\n throw new MigrationError(\n `Column \"${col.table_name}\".\"${col.column_name}\" has type \"${col.udt_schema}\".\"${baseTypeName(col.udt_name)}\", which lives in another schema and no installed extension owns it. ` +\n `VibORM manages one schema (\"${scope.namespace}\") and cannot represent that type in a snapshot or regenerate it as DDL.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: col.table_name,\n column: col.column_name,\n type: baseTypeName(col.udt_name),\n feature: \"external-type\",\n },\n }\n );\n}\n\n/**\n * The snapshot spelling of one column's type.\n *\n * Two readings, and a refusal for what neither can spell:\n *\n * 1. A provider object owned by an extension this adapter DECLARES keeps the\n * server's own formatted spelling, so its modifiers and array structure\n * survive the round trip (`vector(3)`, `geometry(Point,4326)`).\n * 2. Everything else keeps the `udt_name` reading every existing snapshot was\n * written with — built-ins, estate-owned types, AND an extension type\n * outside the two admitted capabilities. The capability decides which\n * SPELLING is read, never whether a type is representable: `citext` is a\n * shipped VibORM native type (`src/schema/scalars/native-types.ts`) that no\n * capability can admit, and `udt_name` spells it exactly as the desired\n * side does, so it round-trips. Refusing it would brick `introspect` and\n * `push` for an estate that used it.\n * 3. A type of ANOTHER schema that no extension owns is refused, because\n * nothing here can spell it: a snapshot carries bare names relative to the\n * estate, and re-rendering that name would create a same-named object in\n * the estate rather than reach the one the column actually has.\n */\nfunction formatColumnType(\n col: PgColumn,\n scope: PostgresIntrospectionScope\n): string {\n const extensionType = baseTypeName(col.udt_name);\n if (\n col.type_extension === \"postgis\" &&\n (extensionType === \"geometry\" || extensionType === \"geography\") &&\n !scope.admittedExtensionTypes.has(extensionType)\n ) {\n throw new MigrationError(\n `Column \"${col.table_name}\".\"${col.column_name}\" uses PostGIS ${extensionType}, but this PostgreSQL adapter has no GeoPoint protocol. ` +\n \"Migration introspection refuses to erase its subtype and SRID into a bare extension type; construct the driver with `postgis: true` or use a client that does not manage this estate.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"postgresql\",\n table: col.table_name,\n column: col.column_name,\n type: extensionType,\n feature: \"GeoPoint\",\n },\n }\n );\n }\n if (\n col.type_extension !== null &&\n col.type_extension_schema !== null &&\n scope.admittedExtensionTypes.has(extensionType)\n ) {\n return stripExtensionSchema(col.formatted_type, col.type_extension_schema);\n }\n\n // `type_extension === null` is what keeps an extension type installed\n // OUTSIDE the estate (the ordinary `CREATE EXTENSION citext` into `public`)\n // out of this refusal: the extension owns it, PostgreSQL resolves it for the\n // unqualified type token the renderer emits, and `udt_name` spells it.\n if (\n col.type_extension === null &&\n col.udt_schema !== scope.namespace &&\n !BUILT_IN_TYPE_SCHEMAS.has(col.udt_schema)\n ) {\n refuseUnrepresentableType(col, scope);\n }\n\n const elementType = baseTypeName(col.udt_name);\n const snapshotType = col.udt_name.startsWith(\"_\")\n ? `${elementType}[]`\n : elementType;\n\n // The server's formatted built-in type retains every typmod, including\n // precision on timestamp/time, bit widths and array element modifiers.\n if (BUILT_IN_TYPE_SCHEMAS.has(col.udt_schema)) {\n return col.formatted_type;\n }\n\n return snapshotType;\n}\n\n/** `numeric[]`'s `udt_name`; PostgreSQL prefixes an array type with `_`. */\nconst NUMERIC_ARRAY_UDT = \"_numeric\";\n\n/**\n * The declared decimal domain of a PostgreSQL column, or `undefined`.\n *\n * PostgreSQL is the one dialect that needs no reserved carrier: the typmod IS\n * the descriptor, so it is read from the catalog rather than from anything\n * VibORM wrote. A scalar reports it through `information_schema`; an array\n * reports it only inside `format_type`, so the two are recovered from the two\n * places the server keeps them.\n *\n * An unconstrained `numeric` has no typmod and therefore no domain — which is\n * correct, and is what makes the differ plan the conversion to a declared one.\n */\nfunction readDecimalDomain(col: PgColumn): DecimalDescriptor | undefined {\n if (col.data_type === \"numeric\" && col.numeric_precision !== null) {\n return requireDecimalDomain(\n col,\n col.numeric_precision,\n col.numeric_scale ?? 0\n );\n }\n if (col.udt_name !== NUMERIC_ARRAY_UDT) return undefined;\n const match = NUMERIC_ARRAY_TYPMOD.exec(col.formatted_type);\n if (!match) return undefined;\n return requireDecimalDomain(col, match[1], match[2]);\n}\n\nconst NUMERIC_ARRAY_TYPMOD = /^numeric\\((-?\\d+),(-?\\d+)\\)\\[\\]$/;\n\nfunction requireDecimalDomain(\n col: PgColumn,\n precision: unknown,\n scale: unknown\n): DecimalDescriptor {\n const descriptor = readStoredDecimalDescriptor(precision, scale, \"pg\");\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n `PostgreSQL reported column \"${col.table_name}\".\"${col.column_name}\" as NUMERIC(${String(precision)},${String(scale)}), outside VibORM's fixed-decimal domain. Migration introspection is refused rather than publishing an invalid descriptor.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"postgresql\",\n table: col.table_name,\n column: col.column_name,\n type: \"invalid-catalog-decimal-domain\",\n },\n }\n );\n}\n\nfunction isAutoIncrement(columnDefault: string | null): boolean {\n if (!columnDefault) return false;\n return (\n columnDefault.includes(\"nextval(\") ||\n columnDefault.includes(\"_seq'::regclass)\")\n );\n}\n\n/**\n * Every spelling PostgreSQL can give the terminal cast onto ONE named type.\n *\n * The server renders a default expression through `pg_get_expr`, which\n * qualifies the type only when the type's schema is off the session's\n * `search_path` and quotes an identifier only when the identifier needs it.\n * Both facts are session state, so the same column reads back as\n * `'active'::billing.state` on one connection and `'active'::state` on another,\n * and either half may be quoted. The set is enumerated rather than matched by\n * pattern because it must name THIS column's type exactly: a regex loose enough\n * to cover the spellings is also loose enough to eat an unrelated cast.\n */\nfunction terminalCastSpellings(schema: string, typeName: string): string[] {\n const quoted = (name: string) => `\"${name.replaceAll('\"', '\"\"')}\"`;\n const qualifiers = [\"\", `${schema}.`, `${quoted(schema)}.`];\n const names = [typeName, quoted(typeName)];\n const spellings: string[] = [];\n for (const qualifier of qualifiers) {\n for (const name of names) {\n for (const array of [\"\", \"[]\"]) {\n spellings.push(`::${qualifier}${name}${array}`);\n }\n }\n }\n // Longest first: `::billing.state[]` must not be half-stripped by `::state`.\n return spellings.sort((left, right) => right.length - left.length);\n}\n\n/**\n * Removes the cast that names this column's own managed enum type, if the\n * default ends with one.\n *\n * §4.3: the strip is keyed on the column's catalog-proven `udt_schema` /\n * `udt_name` and on that name being an enum this estate manages — never on the\n * text alone. A default casting to a built-in, an extension type, a domain or a\n * composite therefore reaches the generic strip below unchanged, which is what\n * keeps every already-converged column byte-identical.\n */\nfunction stripManagedEnumCast(\n columnDefault: string,\n col: PgColumn,\n scope: PostgresIntrospectionScope,\n managedEnums: ReadonlySet<string>\n): string {\n const enumName = baseTypeName(col.udt_name);\n if (col.udt_schema !== scope.namespace || !managedEnums.has(enumName)) {\n return columnDefault;\n }\n for (const cast of terminalCastSpellings(col.udt_schema, enumName)) {\n if (columnDefault.endsWith(cast)) {\n return columnDefault.slice(0, -cast.length);\n }\n }\n return columnDefault;\n}\n\nfunction cleanDefault(\n col: PgColumn,\n scope: PostgresIntrospectionScope,\n managedEnums: ReadonlySet<string>\n): string | undefined {\n const columnDefault = col.column_default;\n if (!columnDefault) return undefined;\n\n // Skip auto-increment defaults\n if (isAutoIncrement(columnDefault)) return undefined;\n\n // Clean up type casting (e.g., 'value'::text -> 'value')\n const withoutEnumCast = stripManagedEnumCast(\n columnDefault,\n col,\n scope,\n managedEnums\n );\n const cleaned = withoutEnumCast.replace(TYPE_CAST_REGEX, \"\").trim();\n return renderDecimalDefault(cleaned, readDecimalDomain(col));\n}\n\n/**\n * Re-renders a decimal column's default through the codec, so both snapshot\n * sides hold the SAME of the two renderings.\n *\n * PostgreSQL deparses a decimal default in two spellings and the difference is\n * the sign: `DEFAULT 12.34000` comes back as the bare literal, while\n * `DEFAULT -12.34000` comes back as `'-12.34000'::numeric`, because the minus\n * is a unary operator over a constant and the folded result is spelled as a\n * cast literal. (Measured on PGlite 0.3.) Stripping the cast leaves the quotes\n * behind, so the negative default would never equal the one the serializer\n * emits and the estate would churn forever.\n *\n * Sending it back through `decimalDefaultText` settles both spellings at once:\n * the quotes are dropped by the grammar and the fraction is padded to the\n * scale, which is exactly what the serializer emitted. Anything that is not a\n * decimal literal — a function call, `NULL`, an array literal — is not a value\n * this rendering describes and passes through untouched.\n */\nfunction renderDecimalDefault(\n cleaned: string,\n descriptor: DecimalDescriptor | undefined\n): string {\n if (descriptor === undefined) return cleaned;\n const unquoted =\n cleaned.startsWith(\"'\") && cleaned.endsWith(\"'\") && cleaned.length > 1\n ? cleaned.slice(1, -1)\n : cleaned;\n const canonical = canonicalizeDecimal(unquoted);\n if (canonical === undefined) return cleaned;\n return decimalDefaultText(\"pg\", canonical, descriptor);\n}\n\n/**\n * Refuses a foreign key that crosses the estate boundary, in either direction.\n *\n * This runs BEFORE the snapshot is returned, so push, public introspection and\n * every reset path that inventories objects refuse before planning a single\n * operation — an outbound reference would otherwise be silently dropped from\n * the snapshot (the owned-key query only sees same-schema pairs) and an inbound\n * one would turn a later table drop into somebody else's broken constraint.\n */\nfunction assertNoCrossSchemaForeignKeys(\n crossing: readonly PgCrossSchemaForeignKey[],\n scope: PostgresIntrospectionScope\n): void {\n const first = crossing.find(\n (fk) =>\n scope.tables === undefined ||\n (fk.owning_schema === scope.namespace &&\n scope.tables.includes(fk.owning_table)) ||\n (fk.referenced_schema === scope.namespace &&\n scope.tables.includes(fk.referenced_table))\n );\n if (!first) return;\n\n const direction = first.owning_schema === scope.namespace ? \"out of\" : \"into\";\n throw new MigrationError(\n `Foreign key \"${first.constraint_name}\" points ${direction} the migration estate: ` +\n `\"${first.owning_schema}\".\"${first.owning_table}\" references \"${first.referenced_schema}\".\"${first.referenced_table}\". ` +\n `VibORM manages one schema (\"${scope.namespace}\") per estate, so a constraint with one side outside it is an unsupported migration topology` +\n (crossing.length > 1 ? ` (${crossing.length} such constraints).` : \".\"),\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n // Both schemas are in the message: the metadata allowlist admits no\n // namespace key, and a refusal that cannot say which boundary was\n // crossed is not actionable.\n meta: {\n constraint: first.constraint_name,\n table: first.owning_table,\n relation: first.referenced_table,\n feature: \"cross-schema-foreign-key\",\n },\n }\n );\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspectPostgresSchema(\n executeRaw: RawExecutor,\n scope: PostgresIntrospectionScope\n): Promise<SchemaSnapshot> {\n const namespace = [scope.namespace];\n\n // One after another: `push` runs these on its ONE pinned session, and a\n // connection runs one statement at a time. Overlapping them only queued\n // them inside the provider, which node-postgres warns it will refuse in\n // pg@9. Each is a short catalog read, named when the provider refuses it.\n const read = async <T>(\n query: string,\n sql: string,\n parameters: unknown[] = namespace\n ) => {\n try {\n return await executeRaw<T>(sql, parameters);\n } catch (error) {\n throwIfCatalogRefusal(query, error);\n throw error;\n }\n };\n const tablesResult = await read<PgTable>(\n \"tables\",\n POSTGRES_MANAGED_TABLE_NAMES_QUERY\n );\n const columnsResult = await read<PgColumn>(\"columns\", COLUMNS_QUERY);\n const primaryKeysResult = await read<PgPrimaryKey>(\n \"primary keys\",\n PRIMARY_KEYS_QUERY\n );\n const columnProbe = await read<{ present: boolean }>(\n \"nulls not distinct\",\n NULLS_NOT_DISTINCT_QUERY,\n []\n );\n const nullsNotDistinct =\n columnProbe.rows[0]?.present === true ? \"ix.indnullsnotdistinct\" : \"false\";\n const indexesResult = await read<PgIndexRow>(\n \"indexes\",\n `${indexesSource(nullsNotDistinct)}${INDEXES_ORDER}`\n );\n const foreignKeysResult = await read<PgForeignKey>(\n \"foreign keys\",\n FOREIGN_KEYS_QUERY\n );\n const crossSchemaForeignKeysResult = await read<PgCrossSchemaForeignKey>(\n \"cross-schema foreign keys\",\n CROSS_SCHEMA_FOREIGN_KEYS_QUERY\n );\n const uniqueConstraintsResult = await read<PgUniqueConstraint>(\n \"unique constraints\",\n UNIQUE_CONSTRAINTS_QUERY\n );\n const enumsResult = await read<PgEnum>(\"enums\", ENUMS_QUERY);\n\n assertNoCrossSchemaForeignKeys(crossSchemaForeignKeysResult.rows, scope);\n\n // Group results using helper functions\n const columnsByTable = groupBy(columnsResult.rows, (col) => col.table_name);\n const pkByTable = groupBy(primaryKeysResult.rows, (pk) => pk.table_name);\n const indexesByTable = groupByNested(\n indexesResult.rows,\n (idx) => idx.table_name,\n (idx) => idx.index_name\n );\n const fkByTable = groupByNested(\n foreignKeysResult.rows,\n (fk) => fk.table_name,\n (fk) => fk.constraint_name\n );\n const uniqueByTable = groupByNested(\n uniqueConstraintsResult.rows,\n (uq) => uq.table_name,\n (uq) => uq.constraint_name\n );\n const enumsByName = groupBy(enumsResult.rows, (e) => e.enum_name);\n const managedEnums = new Set(enumsByName.keys());\n\n // Build tables\n const tables: TableDef[] = [];\n\n for (const table of tablesResult.rows) {\n const tableName = table.table_name;\n\n const selected =\n scope.tables === undefined || scope.tables.includes(tableName);\n if (\n selected &&\n (table.relation_kind === \"p\" || table.is_partition === true)\n )\n throw new MigrationError(\n `PostgreSQL table \"${tableName}\" is partitioned or a partition. Synchronization refuses before effects because its physical definition cannot be represented.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"partitioned table\" } }\n );\n const generated = (columnsByTable.get(tableName) ?? []).find(\n (column) =>\n column.generated_kind !== undefined && column.generated_kind !== \"\"\n );\n if (selected && generated)\n throw new MigrationError(\n `PostgreSQL column \"${tableName}.${generated.column_name}\" is generated. Synchronization refuses before effects because its expression cannot be represented.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: tableName,\n column: generated.column_name,\n feature: \"generated column\",\n },\n }\n );\n\n // Build columns\n const columns = (columnsByTable.get(tableName) || []).map((col) => ({\n name: col.column_name,\n type:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? col.udt_name.startsWith(\"_\")\n ? `${baseTypeName(col.udt_name)}[]`\n : col.udt_name\n : formatColumnType(col, scope),\n nullable: col.is_nullable === \"YES\",\n default:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? undefined\n : cleanDefault(col, scope, managedEnums),\n autoIncrement: isAutoIncrement(col.column_default),\n decimal:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? undefined\n : readDecimalDomain(col),\n }));\n\n // Build primary key\n let primaryKey: PrimaryKeyDef | undefined;\n const pkCols = pkByTable.get(tableName);\n if (pkCols && pkCols.length > 0) {\n pkCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstPk = pkCols[0];\n if (firstPk) {\n primaryKey = {\n columns: pkCols.map((pk) => pk.column_name),\n name: firstPk.constraint_name,\n };\n }\n }\n\n // Build indexes\n const indexes: IndexDef[] = [];\n const tableIndexes = indexesByTable.get(tableName);\n if (tableIndexes) {\n for (const [indexName, indexCols] of tableIndexes) {\n indexCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstCol = indexCols[0];\n if (firstCol) {\n const method = firstCol.index_type;\n const managed =\n scope.tables === undefined || scope.tables.includes(tableName);\n // `=== false` is not fail-open: is_valid is a NOT NULL boolean, and\n // a transport returning non-booleans fails unsupported_structure.\n if (managed && firstCol.is_valid === false) {\n throw new MigrationError(\n `PostgreSQL index \"${tableName}.${indexName}\" is INVALID: a CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY build of it was interrupted or is still running, and PostgreSQL never reads through it. status() lists it; resolve() repairs it when the unfinished migration attempt's own CONCURRENTLY statement named it, otherwise drop it with DROP INDEX CONCURRENTLY or rebuild it with REINDEX INDEX CONCURRENTLY.`,\n VibORMErrorCode.MIGRATION_INVALID_INDEX,\n { meta: { table: tableName, indexName } }\n );\n }\n if (\n managed &&\n (firstCol.unsupported_structure !== false ||\n (method !== \"btree\" &&\n method !== \"hash\" &&\n method !== \"gin\" &&\n method !== \"gist\"))\n ) {\n throw new MigrationError(\n `PostgreSQL index \"${tableName}.${indexName}\" has physical method/order/expression/include/opclass/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves the index. Manage its table outside this synchronization scope until a faithful declaration is available.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: tableName, indexName } }\n );\n }\n if (\n method !== \"btree\" &&\n method !== \"hash\" &&\n method !== \"gin\" &&\n method !== \"gist\"\n )\n continue;\n if (indexCols.some((column) => column.column_name === null)) continue;\n indexes.push({\n name: indexName,\n columns: indexCols.flatMap((idx) =>\n idx.column_name === null ? [] : [idx.column_name]\n ),\n unique: firstCol.is_unique,\n type: method,\n where: firstCol.filter_condition || undefined,\n });\n }\n }\n }\n\n // Build foreign keys\n const foreignKeys: ForeignKeyDef[] = [];\n const tableFks = fkByTable.get(tableName);\n if (tableFks) {\n for (const [constraintName, fkCols] of tableFks) {\n fkCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstFk = fkCols[0];\n if (firstFk) {\n foreignKeys.push({\n name: constraintName,\n columns: fkCols.map((fk) => fk.column_name),\n referencedTable: firstFk.foreign_table_name,\n referencedColumns: fkCols.map((fk) => fk.foreign_column_name),\n onDelete: mapReferentialAction(firstFk.delete_rule),\n onUpdate: mapReferentialAction(firstFk.update_rule),\n });\n }\n }\n }\n\n // Build unique constraints\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const tableUniques = uniqueByTable.get(tableName);\n if (tableUniques) {\n for (const [constraintName, uqCols] of tableUniques) {\n uqCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n uniqueConstraints.push({\n name: constraintName,\n columns: uqCols.map((uq) => uq.column_name),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // Build enums\n const enums: EnumDef[] = [];\n for (const [enumName, enumVals] of enumsByName) {\n enumVals.sort((a, b) => a.sort_order - b.sort_order);\n enums.push({\n name: enumName,\n values: enumVals.map((e) => e.enum_value),\n });\n }\n\n return {\n tables,\n enums: enums.length > 0 ? enums : undefined,\n };\n}\n","/**\n * Plan D5 (decision 7): the live managed schema's fingerprint, computed by\n * PostgreSQL in ONE statement instead of the namespace proof and the eight\n * catalog reads a full introspection sends.\n *\n * The digest is `fingerprintLive(introspectManaged(…))` reproduced, not\n * approximated. It reads the introspection's own catalog sources (their text\n * is shared with `introspect.ts`, never copied) and hashes the projection\n * `fingerprintSnapshot` hashes: `formatColumnType`, `cleanDefault` and\n * `normalizeDefault`, `normalizeType`, `canonicalUniqueEntities`, the\n * managed-table list `selectManagedSnapshot` applies (its tables and the\n * enums they use), the control tables left out, RFC 8785 bytes, the\n * snapshot hash domain.\n *\n * Where reproducing a fact exactly would need more than SQL can say, the\n * statement answers NULL instead of a digest, and the caller introspects as\n * before. That is every case the introspection or the managed-table list\n * refuses (its refusal is then raised with its own message), and:\n * - a partial index, whose predicate `fingerprintLive` canonicalizes through\n * a scratch view, which one SELECT cannot create — unless the caller asks\n * for predicates as deparsed (`$6`): the digest is then\n * `fingerprintSnapshot` of the introspection itself, each predicate as\n * `pg_get_expr` spells it, which the no-op compares with the spelling the\n * apply that wrote the marker recorded from its introspection;\n * - a default that is a temporal literal, a JSON literal other than `{}`,\n * `[]`, `null`, `true` or `false`, an array literal other than `{}`, a\n * `date_trunc(…)` clock, an exponent or more than 15 significant digits in\n * a floating-point literal, or more than two layers of parentheses;\n * - a type spelled with quotes or non-ASCII characters;\n * - a projection holding a character at or above U+E000, where PostgreSQL's\n * code-point order and JavaScript's UTF-16 order can disagree;\n * - a database whose encoding is not UTF-8;\n * - an index whose deparsed definition mentions NULLS NOT DISTINCT: one\n * statement cannot name `indnullsnotdistinct`, absent before PostgreSQL 15,\n * but through a whole-row read, which PlanetScale's Neki refuses.\n *\n * JavaScript's regular expressions are spelled for PostgreSQL's ARE in E''\n * strings, which mean the same thing whatever `standard_conforming_strings`\n * says. No expression here can raise: the statement runs inside the locked\n * migration transaction, where an error would abort it.\n */\n\nimport { arrayLiteralText } from \"../../../adapters/databases/postgres/array-literal\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { boundNamespace } from \"../../catalog-probes\";\nimport { HASH_DOMAIN, isSha256, type Sha256 } from \"../../identity\";\nimport type { BoundMigrationDriver } from \"..\";\nimport type { ControlTableNames } from \"../base\";\nimport {\n admittedExtensionTypes,\n COLUMNS_SOURCE,\n CROSS_SCHEMA_FOREIGN_KEYS_SOURCE,\n ENUMS_SOURCE,\n FOREIGN_KEYS_SOURCE,\n indexesSource,\n POSTGRES_MANAGED_TABLE_NAMES_SOURCE,\n PRIMARY_KEYS_SOURCE,\n UNIQUE_CONSTRAINTS_SOURCE,\n} from \"./introspect\";\n\n/** A regular expression or replacement as an E'' literal. */\nconst re = (text: string): string =>\n `E'${text.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"''\")}'`;\n\n/** JavaScript's `\\s`, which is also what `String#trim` removes. */\nconst WS =\n \"[\\\\t\\\\n\\\\v\\\\f\\\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]\";\n\nconst trim = (value: string): string =>\n `regexp_replace(${value}, ${re(`^${WS}+|${WS}+$`)}, '', 'g')`;\n\n/** `normalizeType`'s rewrites, in its order. */\nconst TYPE_REWRITES: readonly (readonly [string, string])[] = [\n [`${WS}+`, \" \"],\n [`${WS}*,${WS}*`, \",\"],\n [String.raw`${WS}+\\[\\]`, \"[]\"],\n [String.raw`\\ycharacter varying\\y`, \"varchar\"],\n [String.raw`\\ycharacter\\y`, \"char\"],\n [String.raw`\\ybit varying\\y`, \"varbit\"],\n [\n String.raw`\\ytimestamptz(\\([0-9]+\\))?`,\n String.raw`timestamp\\1 with time zone`,\n ],\n [String.raw`\\ytimetz(\\([0-9]+\\))?`, String.raw`time\\1 with time zone`],\n [\n String.raw`\\y(timestamp|time)(\\([0-9]+\\))? without time zone`,\n String.raw`\\1\\2`,\n ],\n [String.raw`\\yint4\\y`, \"integer\"],\n [String.raw`\\yint8\\y`, \"bigint\"],\n [String.raw`\\yint2\\y`, \"smallint\"],\n [String.raw`\\yfloat4\\y`, \"real\"],\n [String.raw`\\yfloat8\\y`, \"double precision\"],\n [String.raw`\\ybool\\y`, \"boolean\"],\n];\n\n/** `normalizeType` of a quote-free ASCII type. */\nconst normalizeType = (type: string): string =>\n TYPE_REWRITES.reduce(\n (text, [pattern, replacement]) =>\n `regexp_replace(${text}, ${re(pattern)}, ${re(replacement)}, 'g')`,\n `lower(${trim(type)} COLLATE \"C\")`\n );\n\nconst IDENTIFIER = `(?:\"(?:[^\"]|\"\")+\"|[a-zA-Z_][a-zA-Z0-9_$]*)`;\n/** `TYPE_CAST_REGEX` of `introspect.ts`. */\nconst TERMINAL_CAST = String.raw`::${IDENTIFIER}(?:\\.${IDENTIFIER})?(?:${WS}+(?:varying|precision|with time zone|without time zone))?(?:\\([0-9]+(?:,${WS}*[0-9]+)?\\))?(?:\\[\\])?$`;\n/** Quoted literals, blanked before parentheses are counted. */\nconst LITERALS = `'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"`;\nconst UTC_NOW = String.raw`^(?:now\\(\\) at time zone 'utc'|timezone\\(${WS}*'utc'${WS}*,${WS}*now\\(\\)${WS}*\\))$`;\nconst UTC_CURRENT_TIME = String.raw`^timezone\\(${WS}*'utc'${WS}*,${WS}*current_time(?:\\(3\\))?${WS}*\\)$`;\nconst NUMBER_LITERAL = String.raw`^[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:e[+-]?[0-9]+)?$`;\n/** Characters whose order differs between code points and UTF-16 units. */\nconst BEYOND_ORDER = \"[\\ue000-\\\\U0010FFFF]\";\n\nconst quoted = (value: string): string =>\n `(left(${value}, 1) = '''' AND right(${value}, 1) = '''')`;\n/** `value.slice(1, -1)`, never a negative length. */\nconst inner = (value: string): string =>\n `CASE WHEN length(${value}) >= 2 THEN substr(${value}, 2, length(${value}) - 2) ELSE '' END`;\n\n/**\n * One turn of `stripDefaultParentheses`: the outer pair goes when it encloses\n * the whole value outside quoted literals. Its parentheses are reduced pair by\n * pair; eight passes settle any nesting up to eight deep, and a deeper one is\n * NULL rather than guessed.\n */\nfunction stripParentheses(value: string): string {\n let pairs = `regexp_replace(${inner(`regexp_replace(${value}, ${re(LITERALS)}, 'q', 'g')`)}, '[^()]', '', 'g')`;\n for (let pass = 0; pass < 8; pass += 1) {\n pairs = `replace(${pairs}, '()', '')`;\n }\n return `(SELECT CASE WHEN ${value} IS NULL OR NOT (left(${value}, 1) = '(' AND right(${value}, 1) = ')') THEN ${value} WHEN reduced = '' THEN ${trim(inner(value))} WHEN reduced ~ ${re(String.raw`^\\)*\\(*$`)} THEN ${value} END FROM (SELECT ${pairs} AS reduced OFFSET 0) parentheses)`;\n}\n\n/** `String(Number(literal))` for a decimal literal JavaScript prints in full. */\nconst FLOAT_TEXT = `(SELECT CASE\n WHEN digits IS NULL THEN NULL\n WHEN whole = '' AND fraction = '' THEN '0'\n WHEN length(whole) <= 21 AND length(rtrim(ltrim(whole || fraction, '0'), '0')) <= 15 AND (whole <> '' OR length(fraction) - length(ltrim(fraction, '0')) <= 5)\n THEN CASE WHEN digits[1] = '-' THEN '-' ELSE '' END || coalesce(nullif(whole, ''), '0') || CASE WHEN fraction = '' THEN '' ELSE '.' || fraction END\nEND FROM (SELECT digits, ltrim(digits[2], '0') AS whole, rtrim(coalesce(digits[3], ''), '0') AS fraction FROM (SELECT regexp_match(unquoted, ${re(String.raw`^([+-]?)([0-9]*)(?:\\.([0-9]*))?$`)}) AS digits) parsed) parts)`;\n\n/** `BigInt(literal).toString()`. */\nconst INTEGER_TEXT = `(SELECT CASE WHEN digits[1] = '-' AND digits[2] <> '0' THEN '-' || digits[2] ELSE digits[2] END FROM (SELECT regexp_match(unquoted, '^([-+]?)0*([0-9]+)$') AS digits) parsed)`;\n\n/** `normalizeDefault`, as the JSON text of its answer; NULL where it abstains. */\nconst DEFAULT_JSON = `CASE\n WHEN spelling IS NULL OR strpos(spelling, chr(8490)) > 0 THEN NULL\n WHEN normalized = 'null' THEN 'null'\n WHEN clock ~ ${re(UTC_NOW)} THEN to_json('now() at time zone ''utc'''::text)::text\n WHEN clock ~ '^date_trunc[(]' THEN NULL\n WHEN clock ~ ${re(UTC_CURRENT_TIME)} THEN to_json(CASE WHEN strpos(clock, 'current_time(3)') > 0 THEN 'timezone(''utc'',current_time(3))' ELSE 'timezone(''utc'',current_time)' END)::text\n WHEN normalized IN ('current_timestamp', 'now()') THEN '\"now()\"'\n WHEN ntype = 'boolean' AND normalized IN ('true', '''t''', '1') THEN '\"true\"'\n WHEN ntype = 'boolean' AND normalized IN ('false', '''f''', '0') THEN '\"false\"'\n WHEN normalized ~ ${re(String.raw`^[a-z_][a-z0-9_]*\\(\\)$`)} THEN to_json(normalized)::text\n WHEN ${quoted(\"spelling\")} AND right(ntype, 2) = '[]' THEN CASE WHEN literal = '{}' THEN '\"[]\"' END\n WHEN ${quoted(\"spelling\")} AND ntype IN ('json', 'jsonb') THEN CASE WHEN literal IN ('{}', '[]', 'null', 'true', 'false') THEN to_json(literal)::text END\n WHEN ntype ~ '^(integer|bigint|smallint|real|double precision|float|int|tinyint)' AND unquoted ~ ${re(NUMBER_LITERAL)}\n THEN to_json(CASE WHEN ntype ~ '^(integer|bigint|smallint|int|tinyint)' AND unquoted ~ '^[-+]?[0-9]+$' THEN ${INTEGER_TEXT} ELSE ${FLOAT_TEXT} END)::text\n WHEN ntype ~ '^(timestamp|time|date)' AND ${quoted(\"spelling\")} THEN NULL\n ELSE to_json(spelling)::text\nEND`;\n\nconst SQL = `WITH\ntbl AS (${POSTGRES_MANAGED_TABLE_NAMES_SOURCE}),\ncol AS (${COLUMNS_SOURCE}),\npk AS (${PRIMARY_KEYS_SOURCE}),\nidx AS (${indexesSource(\"strpos(pg_catalog.pg_get_indexdef(ix.indexrelid), ' NULLS NOT DISTINCT') > 0\")}),\nfk AS (${FOREIGN_KEYS_SOURCE}),\nxfk AS (${CROSS_SCHEMA_FOREIGN_KEYS_SOURCE}),\nuq AS (${UNIQUE_CONSTRAINTS_SOURCE}),\nen AS (${ENUMS_SOURCE}),\nscope AS (\n SELECT table_name::text AS table_name,\n ($4::text[] IS NULL OR table_name::text = ANY ($4::text[])) AS selected,\n table_name::text NOT IN ($2::text, $3::text) AS kept,\n (relation_kind = 'p' OR is_partition) AS partitioned\n FROM tbl\n),\ncolumns AS (\n SELECT s.table_name, s.selected, s.kept, c.column_name::text AS name,\n coalesce(c.generated_kind::text, '') <> '' AS generated,\n t.type, nt.ntype, dd.valid AS decimal_valid,\n '{\"autoIncrement\":' || (coalesce(c.column_default, '') <> '' AND (strpos(c.column_default, 'nextval(') > 0 OR strpos(c.column_default, '_seq''::regclass)') > 0))::text\n || ',\"default\":' || CASE WHEN NOT s.selected OR coalesce(c.column_default, '') = '' OR strpos(c.column_default, 'nextval(') > 0 OR strpos(c.column_default, '_seq''::regclass)') > 0 THEN 'null' ELSE f.json END\n || ',\"name\":' || to_json(c.column_name::text)::text\n || ',\"nullable\":' || (c.is_nullable = 'YES')::text\n || ',\"type\":' || to_json(nt.ntype)::text || '}' AS json\n FROM col c\n JOIN scope s ON s.table_name = c.table_name::text\n CROSS JOIN LATERAL (SELECT c.udt_name::text AS udt, CASE WHEN left(c.udt_name::text, 1) = '_' THEN substr(c.udt_name::text, 2) ELSE c.udt_name::text END AS base OFFSET 0) b\n CROSS JOIN LATERAL (SELECT CASE\n WHEN NOT s.selected THEN CASE WHEN left(b.udt, 1) = '_' THEN b.base || '[]' ELSE b.udt END\n WHEN c.type_extension = 'postgis' AND b.base IN ('geometry', 'geography') AND NOT b.base = ANY ($5::text[]) THEN NULL\n WHEN c.type_extension IS NOT NULL AND c.type_extension_schema IS NOT NULL AND b.base = ANY ($5::text[]) THEN CASE\n WHEN starts_with(c.formatted_type, c.type_extension_schema::text || '.') THEN substr(c.formatted_type, length(c.type_extension_schema::text) + 2)\n WHEN starts_with(c.formatted_type, '\"' || replace(c.type_extension_schema::text, '\"', '\"\"') || '\".') THEN substr(c.formatted_type, length(replace(c.type_extension_schema::text, '\"', '\"\"')) + 4)\n ELSE c.formatted_type END\n WHEN c.type_extension IS NULL AND c.udt_schema::text <> $1::text AND c.udt_schema::text NOT IN ('pg_catalog', 'information_schema') THEN NULL\n WHEN c.udt_schema::text IN ('pg_catalog', 'information_schema') THEN c.formatted_type\n ELSE CASE WHEN left(b.udt, 1) = '_' THEN b.base || '[]' ELSE b.base END\n END AS type OFFSET 0) t\n CROSS JOIN LATERAL (SELECT CASE WHEN t.type ~ '[''\"]' OR octet_length(t.type) <> length(t.type) THEN NULL ELSE ${normalizeType(\"t.type\")} END AS ntype OFFSET 0) nt\n CROSS JOIN LATERAL (SELECT precision, scale, precision IS NULL OR (precision > 0 AND scale >= 0 AND scale <= precision AND precision <= 1000 AND scale <= 1000) AS valid FROM (SELECT\n CASE WHEN c.data_type = 'numeric' AND c.numeric_precision IS NOT NULL THEN c.numeric_precision::numeric WHEN b.udt = '_numeric' THEN m[1]::numeric END AS precision,\n CASE WHEN c.data_type = 'numeric' AND c.numeric_precision IS NOT NULL THEN coalesce(c.numeric_scale, 0)::numeric WHEN b.udt = '_numeric' THEN m[2]::numeric END AS scale\n FROM (SELECT regexp_match(c.formatted_type, ${re(String.raw`^numeric\\((-?[0-9]+),(-?[0-9]+)\\)\\[\\]$`)}) AS m) typmod) domain OFFSET 0) dd\n LEFT JOIN LATERAL (\n SELECT left(c.column_default, length(c.column_default) - length(cast_text)) AS stripped\n FROM (SELECT '::' || q || n || a AS cast_text\n FROM (VALUES (''), ($1::text || '.'), ('\"' || replace($1::text, '\"', '\"\"') || '\".')) qualifiers(q),\n (VALUES (b.base), ('\"' || replace(b.base, '\"', '\"\"') || '\"')) names(n),\n (VALUES (''), ('[]')) arrays(a)) spellings\n WHERE c.udt_schema::text = $1::text AND b.base IN (SELECT enum_name::text FROM en) AND right(c.column_default, length(cast_text)) = cast_text\n ORDER BY length(cast_text) DESC LIMIT 1\n ) e ON true\n CROSS JOIN LATERAL (SELECT ${trim(`regexp_replace(coalesce(e.stripped, c.column_default), ${re(TERMINAL_CAST)}, '')`)} AS cleaned OFFSET 0) d\n CROSS JOIN LATERAL (SELECT CASE WHEN dd.precision IS NULL OR NOT dd.valid OR NOT u ~ '^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$' THEN d.cleaned ELSE (\n SELECT CASE WHEN dd.scale = 0 THEN CASE WHEN strpos(canonical, '.') = 0 THEN canonical ELSE left(canonical, strpos(canonical, '.') - 1) END\n WHEN strpos(canonical, '.') = 0 THEN canonical || '.' || repeat('0', dd.scale::int)\n WHEN length(canonical) >= strpos(canonical, '.') + dd.scale THEN canonical\n ELSE rpad(canonical, strpos(canonical, '.') + dd.scale::int, '0') END\n FROM (SELECT CASE WHEN whole = '0' AND fraction = '' THEN '0' ELSE CASE WHEN left(u, 1) = '-' THEN '-' ELSE '' END || whole || CASE WHEN fraction = '' THEN '' ELSE '.' || fraction END END AS canonical\n FROM (SELECT coalesce(nullif(ltrim(split_part(regexp_replace(u, '^[+-]', ''), '.', 1), '0'), ''), '0') AS whole, rtrim(split_part(regexp_replace(u, '^[+-]', ''), '.', 2), '0') AS fraction) parts) decimal_text\n ) END AS rendered FROM (SELECT CASE WHEN length(d.cleaned) > 1 AND ${quoted(\"d.cleaned\")} THEN ${inner(\"d.cleaned\")} ELSE d.cleaned END AS u) unquoted_decimal OFFSET 0) r\n CROSS JOIN LATERAL (SELECT ${trim(\"r.rendered\")} AS layer0 OFFSET 0) p0\n CROSS JOIN LATERAL (SELECT ${stripParentheses(\"p0.layer0\")} AS layer1 OFFSET 0) p1\n CROSS JOIN LATERAL (SELECT ${stripParentheses(\"p1.layer1\")} AS layer2 OFFSET 0) p2\n CROSS JOIN LATERAL (SELECT CASE WHEN ${stripParentheses(\"p2.layer2\")} IS NOT DISTINCT FROM p2.layer2 THEN p2.layer2 END AS spelling OFFSET 0) sp\n CROSS JOIN LATERAL (SELECT lower(spelling COLLATE \"C\") AS normalized,\n replace(replace(lower(spelling COLLATE \"C\"), '::text', ''), 'current_timestamp', 'now()') AS clock,\n replace(${inner(\"spelling\")}, '''''', '''') AS literal,\n CASE WHEN ${quoted('lower(spelling COLLATE \"C\")')} THEN ${inner('lower(spelling COLLATE \"C\")')} ELSE lower(spelling COLLATE \"C\") END AS unquoted OFFSET 0) v\n CROSS JOIN LATERAL (SELECT ${DEFAULT_JSON} AS json OFFSET 0) f\n),\nindexes AS (\n SELECT s.table_name, s.selected, s.kept, i.index_name::text AS name,\n bool_and(i.is_valid) AS valid,\n bool_or(i.unsupported_structure IS DISTINCT FROM false) AS unsupported,\n min(i.index_type::text) AS method,\n bool_and(i.is_unique) AS is_unique,\n min(coalesce(i.filter_condition, '')) AS predicate,\n bool_or(i.column_name IS NULL) AS expression,\n '[' || string_agg(to_json(i.column_name::text)::text, ',' ORDER BY i.ordinal_position) || ']' AS columns\n FROM idx i JOIN scope s ON s.table_name = i.table_name::text\n GROUP BY s.table_name, s.selected, s.kept, i.index_name\n),\nkept_indexes AS (\n SELECT table_name, name, columns,\n is_unique AND predicate = '' AND method = 'btree' AS total_unique,\n '{\"columns\":' || columns || ',\"name\":' || to_json(name)::text || ',\"type\":' || to_json(method)::text || ',\"unique\":' || is_unique::text\n || ',\"where\":' || coalesce(to_json(nullif(${trim(\"predicate\")}, ''))::text, 'null') || '}' AS json\n FROM indexes\n WHERE kept AND method IN ('btree', 'hash', 'gin', 'gist') AND NOT expression\n),\npks AS (\n SELECT s.table_name, '{\"columns\":[' || string_agg(to_json(p.column_name::text)::text, ',' ORDER BY p.ordinal_position) || '],\"name\":' || to_json(min(p.constraint_name::text))::text || '}' AS json\n FROM pk p JOIN scope s ON s.table_name = p.table_name::text\n WHERE s.kept\n GROUP BY s.table_name\n),\nfks AS (\n SELECT s.table_name, '{\"columns\":[' || string_agg(to_json(f.column_name::text)::text, ',' ORDER BY f.ordinal_position)\n || '],\"name\":' || to_json(f.constraint_name::text)::text\n || ',\"onDelete\":\"' || ${referentialAction(\"min(f.delete_rule::text)\")}\n || '\",\"onUpdate\":\"' || ${referentialAction(\"min(f.update_rule::text)\")}\n || '\",\"referencedColumns\":[' || string_agg(to_json(f.foreign_column_name::text)::text, ',' ORDER BY f.ordinal_position)\n || '],\"referencedTable\":' || to_json(min(f.foreign_table_name::text))::text || '}' AS json\n FROM fk f JOIN scope s ON s.table_name = f.table_name::text\n WHERE s.kept\n GROUP BY s.table_name, f.constraint_name\n),\nuqs AS (\n SELECT s.table_name, '{\"columns\":[' || string_agg(to_json(u.column_name::text)::text, ',' ORDER BY u.ordinal_position) || '],\"name\":' || to_json(u.constraint_name::text)::text || '}' AS json\n FROM uq u JOIN scope s ON s.table_name = u.table_name::text\n WHERE s.kept\n GROUP BY s.table_name, u.constraint_name\n UNION ALL\n SELECT table_name, '{\"columns\":' || columns || ',\"name\":' || to_json(name)::text || '}'\n FROM kept_indexes WHERE total_unique\n),\ntables AS (\n SELECT s.table_name,\n '{\"columns\":[' || coalesce((SELECT string_agg(c.json, ',' ORDER BY c.name COLLATE \"C\") FROM columns c WHERE c.table_name = s.table_name), '')\n || '],\"foreignKeys\":[' || coalesce((SELECT string_agg(f.json, ',' ORDER BY f.json COLLATE \"C\") FROM fks f WHERE f.table_name = s.table_name), '')\n || '],\"indexes\":[' || coalesce((SELECT string_agg(i.json, ',' ORDER BY i.name COLLATE \"C\") FROM kept_indexes i WHERE i.table_name = s.table_name AND NOT i.total_unique), '')\n || '],\"name\":' || to_json(s.table_name)::text\n || ',\"primaryKey\":' || coalesce((SELECT p.json FROM pks p WHERE p.table_name = s.table_name), 'null')\n || ',\"uniqueConstraints\":[' || coalesce((SELECT string_agg(u.json, ',' ORDER BY u.json COLLATE \"C\") FROM uqs u WHERE u.table_name = s.table_name), '')\n || ']}' AS json\n FROM scope s\n WHERE s.kept AND s.selected\n),\nenums AS (\n SELECT enum_name::text AS name, '{\"name\":' || to_json(enum_name::text)::text || ',\"values\":[' || string_agg(to_json(enum_value::text)::text, ',' ORDER BY sort_order) || ']}' AS json\n FROM en\n WHERE $4::text[] IS NULL OR enum_name::text IN (SELECT ${elementType(\"c.type\")} FROM columns c WHERE c.selected OR NOT c.kept)\n GROUP BY enum_name\n),\nprojection AS (\n SELECT '{\"enums\":[' || coalesce((SELECT string_agg(json, ',' ORDER BY name COLLATE \"C\") FROM enums), '')\n || '],\"tables\":[' || coalesce((SELECT string_agg(json, ',' ORDER BY table_name COLLATE \"C\") FROM tables), '') || ']}' AS json\n)\nSELECT CASE WHEN\n EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = $1::text)\n AND pg_catalog.getdatabaseencoding() = 'UTF8'\n AND NOT EXISTS (SELECT 1 FROM scope WHERE selected AND partitioned)\n AND NOT EXISTS (SELECT 1 FROM columns WHERE selected AND (generated OR type IS NULL OR NOT decimal_valid OR (kept AND json IS NULL)))\n AND NOT EXISTS (SELECT 1 FROM indexes WHERE selected AND (NOT valid OR unsupported OR method NOT IN ('btree', 'hash', 'gin', 'gist') OR (kept AND NOT expression AND predicate <> '' AND NOT $6::boolean)))\n AND NOT EXISTS (SELECT 1 FROM fk WHERE $4::text[] IS NOT NULL AND ${managedOrControl(\"fk.table_name\")} <> ${managedOrControl(\"fk.foreign_table_name\")})\n AND NOT EXISTS (SELECT 1 FROM columns c WHERE NOT c.selected AND c.kept AND ${elementType(\"c.type\")} IN (SELECT name FROM enums))\n AND NOT EXISTS (SELECT 1 FROM xfk WHERE $4::text[] IS NULL OR (owning_schema::text = $1::text AND owning_table::text = ANY ($4::text[])) OR (referenced_schema::text = $1::text AND referenced_table::text = ANY ($4::text[])))\n AND NOT projection.json ~ ${re(BEYOND_ORDER)}\nTHEN encode(sha256(convert_to('${HASH_DOMAIN.snapshot}', 'UTF8') || decode('00', 'hex') || convert_to(projection.json, 'UTF8')), 'hex') END AS digest\nFROM projection`;\n\n/** A column type without its `[]`, as the managed-table selection reads it. */\nfunction elementType(type: string): string {\n return `regexp_replace(${type}, ${re(String.raw`\\[\\]$`)}, '')`;\n}\n\n/** Whether a table is selected by the managed-table list, or a control table. */\nfunction managedOrControl(table: string): string {\n return `(${table}::text = ANY ($4::text[]) OR ${table}::text IN ($2::text, $3::text))`;\n}\n\nfunction referentialAction(rule: string): string {\n return `CASE ${rule} WHEN 'CASCADE' THEN 'cascade' WHEN 'SET NULL' THEN 'setNull' WHEN 'RESTRICT' THEN 'restrict' WHEN 'SET DEFAULT' THEN 'setDefault' ELSE 'noAction' END`;\n}\n\n/**\n * The statement and its parameters, for a caller that embeds it in a\n * statement of its own: `$1` is the namespace and `$2`, `$3` the state and log\n * control tables, as in the control catalog read; `$4` to `$6` are its own.\n * `deparsedPredicates` hashes each partial-index predicate as the server\n * deparses it instead of abstaining (see the header).\n */\nexport function postgresCatalogDigestQuery(\n driver: BoundMigrationDriver,\n control: ControlTableNames,\n deparsedPredicates = false\n): {\n readonly sql: string;\n readonly parameters: unknown[];\n} {\n const tables = driver.target.tables;\n return {\n sql: SQL,\n parameters: [\n boundNamespace(driver),\n control.state,\n control.log,\n tables === undefined ? null : arrayLiteralText(tables),\n arrayLiteralText([...admittedExtensionTypes(driver.executionDriver)]),\n deparsedPredicates,\n ],\n };\n}\n\n/**\n * The live managed schema's fingerprint, read in one statement; `undefined`\n * where the digest abstains and the caller must introspect.\n */\nexport async function postgresCatalogDigest(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n control: ControlTableNames\n): Promise<Sha256 | undefined> {\n const { sql, parameters } = postgresCatalogDigestQuery(driver, control);\n const result = await producer._executeRaw<{ digest: unknown }>(\n sql,\n parameters\n );\n return readDigest(result.rows[0]?.digest);\n}\n\n/** A digest the statement answered, or `undefined` for an abstention. */\nfunction readDigest(value: unknown): Sha256 | undefined {\n return isSha256(value) ? value : undefined;\n}\n","import { isGeneratorDefault } from \"@schema/scalars/common\";\nimport { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idDomainOfState, idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport {\n arrayLiteralText,\n readArrayLiteralText,\n} from \"../../../adapters/databases/postgres/array-literal\";\n/**\n * PostgreSQL Migration Driver\n *\n * Implements the MigrationDriver interface for PostgreSQL databases.\n * Supports all DDL operations natively.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport { hasIdPrefix } from \"@validation/primitives/id-formats\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { errorCause } from \"../../../errors/diagnostic-safety\";\nimport { renderQualifiedIdentifier } from \"../../../sql/identifiers\";\nimport { type LowLockContext, tableRewrites } from \"../../compile\";\nimport {\n decimalConversionConstraintName,\n decimalConversionRequired,\n postgresDecimalFitsCheck,\n} from \"../../decimal\";\nimport { providerFacts } from \"../../execute-dispatch\";\nimport {\n isPostgresTextToUuid,\n postgresTextToUuidGuard,\n} from \"../../identifier-conversion\";\nimport type { Sha256 } from \"../../identity\";\nimport { DEFAULT_MIGRATION_LIMITS } from \"../../limits\";\nimport {\n type CatalogHazard,\n catalogCommitBoundaries,\n} from \"../../statement-safety\";\nimport type {\n ColumnDef,\n DiffOperation,\n IndexDef,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\nimport { derivedMigrationName } from \"../../utils\";\nimport type { BoundMigrationDriver } from \"..\";\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type ControlTableNames,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DerivedRename,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\nimport { getPostgresType, PG_TYPE_DEFAULTS } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport {\n type BatchExecutor,\n canonicalizeIndexPredicates,\n} from \"./canonicalize-index-predicate\";\nimport {\n postgresCatalogDigest,\n postgresCatalogDigestQuery,\n} from \"./catalog-digest\";\nimport {\n admittedExtensionTypes,\n introspectPostgresSchema,\n POSTGRES_MANAGED_TABLE_NAMES_QUERY,\n} from \"./introspect\";\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * One catalog existence proof for the estate's schema.\n *\n * Bound, never interpolated, and asking `pg_namespace` exactly one question:\n * does this schema exist. Privilege failures are deliberately NOT folded in —\n * a schema this role cannot use is a different fact with a different fix, and\n * it surfaces as the provider's own error from the statement that needed the\n * privilege.\n */\nconst VECTOR_TYPE_TOKEN = /^(vector|halfvec|sparsevec)(?:\\(\\d+\\))?(?:\\[\\])?$/i;\nconst TEMPORAL_PRECISION_TOKEN = /\\((\\d+)\\)/;\n/** The planner's row estimate in the first line of an EXPLAIN. */\nconst PLAN_ROWS = /\\brows=(\\d+)/;\n\nconst NAMESPACE_EXISTS_QUERY =\n \"SELECT 1 AS present FROM pg_catalog.pg_namespace WHERE nspname = $1\";\n\nconst POSTGIS_PREFLIGHT_QUERY = `\nWITH postgis AS (\n SELECT oid\n FROM pg_catalog.pg_extension\n WHERE extname = 'postgis'\n), required_objects(classid, objid) AS (\n VALUES\n ('pg_catalog.pg_type'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regtype('geometry')::pg_catalog.oid),\n ('pg_catalog.pg_type'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regtype('geography')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_makepoint(double precision,double precision)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_setsrid(geometry,integer)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_x(geometry)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_y(geometry)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_geomfromgeojson(text)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_intersects(geography,geography)')::pg_catalog.oid),\n ('pg_catalog.pg_operator'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regoperator('&&(geography,geography)')::pg_catalog.oid)\n)\nSELECT (\n EXISTS (SELECT 1 FROM postgis)\n AND NOT EXISTS (\n SELECT 1\n FROM required_objects required\n WHERE required.objid IS NULL\n OR NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend dependency\n CROSS JOIN postgis\n WHERE dependency.classid = required.classid\n AND dependency.objid = required.objid\n AND dependency.objsubid = 0\n AND dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND dependency.refobjid = postgis.oid\n AND dependency.deptype = 'e'\n )\n )\n) AS ready\n`;\n\n/** The Neki fact a bound migration driver's lock protocol already read. */\nconst NEKI = new WeakMap<object, boolean>();\n\n/**\n * Whether the server is PlanetScale's Neki (its `version()` names it): the\n * one read of that fact, asked once per command by the lock protocol\n * ({@link PostgresMigrationDriver.holdsSessionLock}), whose answer the\n * preflight of a program that would need a commit there reuses; a command\n * outside the lock protocol asks it there.\n */\nasync function serverIsNeki(\n driver: object,\n executeRaw: RawExecutor\n): Promise<boolean> {\n const known = NEKI.get(driver);\n if (known !== undefined) return known;\n const { rows } = await executeRaw<{ neki: boolean }>(\n \"SELECT pg_catalog.version() LIKE '%(Neki)%' AS neki\"\n );\n const neki = rows[0]?.neki === true;\n NEKI.set(driver, neki);\n return neki;\n}\n\n/**\n * The refusal of a program PlanetScale's Neki cannot run (V11021), before any\n * effect: one entry whose own statements need a commit between them\n * (`inside`), where no commit can be placed, or, for a command that runs its\n * program in one transaction, the first statement that needs one.\n */\nfunction nekiRefusal(\n dialect: string,\n { kind, change, statement }: CatalogHazard,\n inside: boolean\n): MigrationError {\n const reason =\n kind === \"rows\"\n ? \"a statement does not see a schema change made earlier in its own transaction\"\n : \"a statement cannot retype, rename or drop a column of a table created or renamed earlier in its own transaction (NK316)\";\n const where = inside\n ? `statement ${statement.position + 1} of this migration runs ${statement.words} after ${change.words} in one dispatch, which no commit can divide. Nothing ran. Put them in separate statements of the migration (one sql fragment each), or in states of their own.`\n : `this migration runs statement ${statement.position + 1} (${statement.words}) after statement ${change.position + 1} (${change.words}). Nothing ran. apply() commits between them; this command runs them in one transaction. Put the later statement in a state of its own after the earlier one, and apply up to the earlier one first (apply({ to })).`;\n return new MigrationError(\n `On PlanetScale's Neki, ${reason}, and ${where}`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n {\n meta: {\n dialect,\n feature: inside\n ? \"dependent statements in one dispatch\"\n : kind === \"rows\"\n ? \"data after schema change in one transaction\"\n : \"column change of a new relation in one transaction\",\n },\n }\n );\n}\n\nfunction snapshotUsesGeoPoint(snapshot: SchemaSnapshot): boolean {\n const physicalType = PG_TYPE_DEFAULTS.point.toLowerCase().replace(/\\s+/g, \"\");\n return snapshot.tables.some((table) =>\n table.columns.some(\n (column) => column.type.toLowerCase().replace(/\\s+/g, \"\") === physicalType\n )\n );\n}\n\nconst QUOTED_LITERAL = /^'(.*)'$/s;\n\nconst storesEnum = (column: ColumnDef, enumName: string) =>\n column.type === enumName || column.type === `${enumName}[]`;\n\n/** The labels a default of `enumName`, or of its array, spells. */\nfunction enumDefaultLabels(\n column: ColumnDef,\n enumName: string\n): readonly (string | null)[] {\n if (!storesEnum(column, enumName)) return [];\n const literal = column.default\n ?.match(QUOTED_LITERAL)?.[1]\n ?.replaceAll(\"''\", \"'\");\n if (literal === undefined) return [];\n return column.type === enumName\n ? [literal]\n : (readArrayLiteralText(literal) ?? []);\n}\n\nconst IDENTIFIER_PART = /[\\w$]/;\n\n/**\n * Whether SQL text may name `identifier`: bare in any case, or double-quoted.\n * Matches inside literals and comments count too; they only cost a type\n * recreation that was not needed.\n */\nfunction mayName(sql: string, identifier: string): boolean {\n const text = sql.toLowerCase();\n const name = identifier.replaceAll('\"', '\"\"').toLowerCase();\n for (let at = text.indexOf(name); at >= 0; at = text.indexOf(name, at + 1))\n if (\n !(\n IDENTIFIER_PART.test(text[at - 1] ?? \"\") ||\n IDENTIFIER_PART.test(text[at + name.length] ?? \"\")\n )\n )\n return true;\n return false;\n}\n\n/**\n * Whether an operation after `ALTER TYPE … ADD VALUE` in the same transaction\n * may read an added label, which PostgreSQL refuses until commit (55P04): a\n * default naming one, a cast of stored data into the enum, or a partial-index\n * predicate naming the type or a column of it. No literal spelling is\n * trusted: `$$archived$$`, `E'archived'` and a function result compare the\n * same.\n */\nfunction readsAddedValue(\n enumName: string,\n added: readonly string[],\n tables: readonly TableDef[],\n following: readonly DiffOperation[]\n): boolean {\n const defaultNamesAdded = (column: ColumnDef) => {\n const labels = enumDefaultLabels(column, enumName);\n return added.some((value) => labels.includes(value));\n };\n // The type and every name the batch gives a column of it, on any table.\n const names = new Set([enumName]);\n const addEnumColumns = (columns: readonly ColumnDef[]) => {\n for (const column of columns)\n if (storesEnum(column, enumName)) names.add(column.name);\n };\n for (const table of tables) addEnumColumns(table.columns);\n const predicateNamesEnum = ({ where }: IndexDef) =>\n where !== undefined && [...names].some((name) => mayName(where, name));\n for (const operation of following) {\n switch (operation.type) {\n case \"createTable\":\n addEnumColumns(operation.table.columns);\n if (\n operation.table.columns.some(defaultNamesAdded) ||\n operation.table.indexes.some(predicateNamesEnum)\n )\n return true;\n break;\n case \"addColumn\":\n if (defaultNamesAdded(operation.column)) return true;\n addEnumColumns([operation.column]);\n break;\n // A column already of the enum is known; one cast into it may hold a label.\n case \"alterColumn\":\n if (\n defaultNamesAdded(operation.to) ||\n (storesEnum(operation.to, enumName) &&\n !storesEnum(operation.from, enumName))\n )\n return true;\n break;\n case \"renameColumn\":\n if (names.has(operation.from)) names.add(operation.to);\n break;\n case \"createIndex\":\n if (predicateNamesEnum(operation.index)) return true;\n break;\n default:\n break;\n }\n }\n return false;\n}\n\nexport class PostgresMigrationDriver extends MigrationDriver {\n readonly dialect = \"postgresql\" as const;\n readonly driverName = \"postgresql\";\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: true,\n supportsAddEnumValueInTransaction: true,\n supportsIndexTypes: [\"btree\", \"hash\", \"gin\", \"gist\"],\n supportsNativeArrays: true,\n supportsAddForeignKeyViaAlter: true,\n // `pg_constraint.conname` is the name the DDL gave the constraint.\n introspectionReadsConstraintNames: true,\n };\n\n // ===========================================================================\n // ESTATE QUALIFICATION\n // ===========================================================================\n\n /**\n * The schema this estate's persistent objects are named with, or undefined\n * on the REGISTERED singleton, which is bound to no estate.\n *\n * ONE source: the estate target. `this.namespace` holds the same string for\n * a PostgreSQL estate — `getMigrationDriver` reads both from the same\n * adapter, and the estate gate refuses a schema that is not this\n * one — so reading exactly one of them is what keeps the two from ever being\n * asked to disagree.\n *\n * `DDLContext.destination` does not enter: §3.4 binds GENERATED PostgreSQL\n * SQL to the configured schema for the same reason live SQL is bound, so an\n * artifact and a live statement in one estate name one schema. That is the\n * dialect difference from MySQL, whose artifacts stay database-relative.\n *\n * The dialect comparison is the union narrowing `MigrationTarget` requires\n * before `namespace` is readable at all, not a second check on top of the\n * registry's: a PostgreSQL implementation is only ever bound to a PostgreSQL\n * target.\n */\n private estateNamespace(): string | undefined {\n const target = this.target;\n return target?.dialect === \"postgresql\" ? target.namespace : undefined;\n }\n\n /**\n * The estate schema where a statement cannot be written without one.\n *\n * A catalog predicate and a schema-scoped inventory have no unqualified\n * reading: with no schema operand they answer for every schema in the\n * database, and any default answers for a schema nothing proved. DDL text is\n * the opposite case and renders unqualified off an unbound singleton (see\n * {@link qualify}).\n */\n private requireEstateNamespace(): string {\n const namespace = this.estateNamespace();\n if (namespace === undefined) {\n throw new MigrationError(\n \"This PostgreSQL migration driver is not bound to an estate, so it has no schema to read the catalog for. \" +\n \"Reach the driver through `getMigrationDriver(driver)`, which binds the adapter's namespace, instead of the registered singleton.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect } }\n );\n }\n return namespace;\n }\n\n /**\n * `\"schema\".\"object\"` — the one qualified spelling, through the one shared\n * primitive, with this driver's own quoter (§2.2, N11).\n *\n * An unbound singleton renders `\"object\"`: it is the dialect's renderer with\n * no estate behind it, and every shipped path reaches a bound view because\n * `getMigrationDriver` refuses a PostgreSQL adapter that declares no\n * namespace. Qualification is never composed by hand anywhere in this file.\n */\n private qualify(objectName: string): string {\n return renderQualifiedIdentifier(\n (name) => this.escapeIdentifier(name),\n this.estateNamespace(),\n objectName\n );\n }\n\n /** A table position is qualified like any object, whatever the destination. */\n protected override tableRef(tableName: string): string {\n return this.qualify(tableName);\n }\n\n /**\n * The enum types this DDL batch may name as a column type.\n *\n * Membership is the ONLY thing that qualifies a column's type token, which is\n * what replaced the `_enum` suffix guess: an explicitly named enum such as\n * `state` is no less managed, and an arbitrary type token cannot prove enum\n * ownership. The set is the introspected schema's enums plus the enums the\n * operations already emitted in this batch have created — a table created\n * beside its own new enum must qualify that enum's name.\n *\n * A `dropEnum` earlier in the batch is deliberately not subtracted: a column\n * type naming a type this batch already dropped is a broken batch either way,\n * and the subtraction would silently UNqualify the very statements that run\n * before the drop.\n *\n * A createEnum introduces a name; alterEnum keeps an existing name from the\n * snapshot. Enum replacement runs before dependent columns, so its full\n * ordered value set and defaults are ready for those subsequent changes.\n */\n private managedEnumNames(context: DDLContext): ReadonlySet<string> {\n const names = new Set<string>();\n for (const enumDef of context.currentSchema?.enums ?? []) {\n names.add(enumDef.name);\n }\n for (const operation of context.precedingOperations ?? []) {\n if (operation.type === \"createEnum\") {\n names.add(operation.enumDef.name);\n }\n }\n return names;\n }\n\n /**\n * A column type token, qualified when it names a managed enum.\n *\n * Built-in types and the adapter-supported extension spellings (`vector(3)`,\n * `geometry(Point,4326)`) pass through untouched: they are provider objects\n * resolved through `search_path`, not estate objects, and prefixing every\n * type token would break them.\n */\n private renderTypeToken(type: string, context: DDLContext): string {\n const isArray = type.endsWith(\"[]\");\n const baseType = isArray ? type.slice(0, -2) : type;\n if (!this.managedEnumNames(context).has(baseType)) {\n return type;\n }\n const qualified = this.qualify(baseType);\n return isArray ? `${qualified}[]` : qualified;\n }\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Reads the estate's schema, and nothing else's.\n *\n * The namespace proof runs FIRST and here rather than at every caller: this\n * is the one inventory every catalog-driven path goes through (public\n * `introspect`, push including dry-run, and force-reset), and a configured\n * but absent schema must not be published as an empty database.\n */\n async introspect(executeRaw: RawExecutor): Promise<SchemaSnapshot> {\n await this.proveNamespaceExists(executeRaw);\n return await introspectPostgresSchema(executeRaw, {\n namespace: this.requireEstateNamespace(),\n tables: this.target?.tables,\n admittedExtensionTypes: admittedExtensionTypes(this.executionDriver),\n });\n }\n\n override catalogDigestQuery(\n this: BoundMigrationDriver,\n control: ControlTableNames,\n deparsedPredicates = false\n ) {\n return postgresCatalogDigestQuery(this, control, deparsedPredicates);\n }\n\n override catalogDigest(\n this: BoundMigrationDriver,\n producer: AnyDriver,\n control: ControlTableNames\n ): Promise<Sha256 | undefined> {\n return postgresCatalogDigest(producer, this, control);\n }\n\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: RawExecutor,\n program: readonly string[],\n splits = false\n ): Promise<boolean> {\n try {\n // PlanetScale's Neki plans a statement against the schema committed\n // before its transaction (`catalogCommitBoundaries`). Asked of the\n // server only for a program that would need a commit there.\n const { boundaries, first, inside } = catalogCommitBoundaries(program);\n const neki =\n boundaries.length > 0 && (await serverIsNeki(this, executeRaw));\n const refused = neki\n ? (inside ?? (splits ? undefined : first))\n : undefined;\n if (refused) throw nekiRefusal(this.dialect, refused, refused === inside);\n // T5a: a statement that rewrites or scans a table holds a lock that\n // blocks it for as long as that takes, so above `largeTableRows` (the\n // planner's estimate, as EXPLAIN reports it) it is refused here, before\n // any effect. A table the program creates is not there yet: it is empty.\n const { largeTableRows } = this.limits ?? DEFAULT_MIGRATION_LIMITS;\n const rewrites = largeTableRows > 0 ? tableRewrites(program) : [];\n const tables = [...new Set(rewrites.map(({ table }) => table))];\n const relations =\n tables.length === 0\n ? []\n : (\n await executeRaw<{ relation: string | null }>(\n \"SELECT pg_catalog.to_regclass(name)::text AS relation FROM unnest($1::text[]) WITH ORDINALITY AS input(name, position) ORDER BY position\",\n [arrayLiteralText(tables)]\n )\n ).rows;\n for (const [index, { relation }] of relations.entries()) {\n if (relation === null) continue;\n const explain = `EXPLAIN SELECT 1 FROM ${relation}`;\n const plan = await executeRaw<Record<string, string>>(explain);\n const line = Object.values(plan.rows[0] ?? {})[0] ?? \"\";\n const estimate = PLAN_ROWS.exec(line)?.[1];\n // A plan without an estimate is not admitted: it was not measured.\n if (estimate !== undefined && Number(estimate) <= largeTableRows) {\n continue;\n }\n const table = tables[index]!;\n const operations = [\n ...new Set(\n rewrites.flatMap((item) =>\n item.table === table ? [item.operation] : []\n )\n ),\n ];\n const operation = operations.join(\" and \");\n // T5b: a validation alone has a step form that blocks no write.\n const steps = operations.every((name) => name.endsWith(\" validation\"))\n ? \" Or add the constraint NOT VALID and validate it (VALIDATE CONSTRAINT) in a later migration: neither step blocks writes. generate({ lowLock: true }) does this for foreign keys.\"\n : \"\";\n const size =\n estimate === undefined\n ? `whose row estimate ${explain} did not report (${JSON.stringify(line)}), so limits.largeTableRows (${largeTableRows}) cannot admit it`\n : `which the planner estimates at ${estimate} rows, above limits.largeTableRows (${largeTableRows})`;\n throw new MigrationError(\n `This migration runs a ${operation} on ${table}, ${size}. It rewrites or scans the whole table while holding a lock that blocks it, longer than a request should wait. Nothing ran: the schema and data are unchanged. Run it outside the request with a client whose largeTableRows is higher, or 0 for no limit.${steps}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: { table, operation, feature: \"large table rewrite\" },\n }\n );\n }\n const vectors = new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.flatMap((table) =>\n table.columns.flatMap(\n (column) =>\n VECTOR_TYPE_TOKEN.exec(column.type)?.[1]?.toLowerCase() ?? []\n )\n )\n )\n );\n if (\n vectors.size > 0 &&\n !this.executionDriver?.adapter.capabilities.supportsVector\n )\n throw new MigrationError(\n \"This migration requires pgvector support. Construct the PostgreSQL driver with pgvector: true and install the vector extension before applying it. VibORM never installs it.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { dialect: this.dialect, feature: \"vector\" } }\n );\n if (\n snapshots.some(snapshotUsesGeoPoint) &&\n !this.executionDriver?.adapter.geoPoint\n ) {\n throw new MigrationError(\n \"This migration requires PostGIS GeoPoint support, but the bound PostgreSQL adapter has no GeoPoint protocol. Construct the driver with `postgis: true` and ensure PostGIS is installed before applying it.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { dialect: this.dialect, feature: \"GeoPoint\" } }\n );\n }\n const desiredNames = [\n ...new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n ),\n ];\n if (desiredNames.length > 0) {\n const views = await executeRaw<{ name: string }>(\n `SELECT relation.relname AS name FROM pg_catalog.pg_class relation JOIN pg_catalog.pg_namespace namespace ON namespace.oid=relation.relnamespace WHERE namespace.nspname=$1 AND relation.relkind IN ('v','m') AND relation.relname=ANY($2::text[])`,\n [this.requireEstateNamespace(), arrayLiteralText(desiredNames)]\n );\n const collision = views.rows.find((row) =>\n desiredNames.includes(row.name)\n );\n if (collision)\n throw new MigrationError(\n `PostgreSQL relation \"${collision.name}\" is a view or materialized view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: collision.name, feature: \"view\" } }\n );\n }\n if (vectors.size > 0) {\n const proof = await executeRaw<{ ready: boolean }>(\n `SELECT NOT EXISTS (SELECT 1 FROM unnest($1::text[]) AS required(name) WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.pg_extension AS e JOIN pg_catalog.pg_depend AS d ON d.refobjid=e.oid AND d.refclassid='pg_catalog.pg_extension'::regclass AND d.deptype='e' JOIN pg_catalog.pg_type AS t ON t.oid=d.objid AND d.classid='pg_catalog.pg_type'::regclass WHERE e.extname='vector' AND t.typname=required.name AND pg_catalog.pg_type_is_visible(t.oid))) AS ready`,\n [arrayLiteralText([...vectors])]\n );\n if (proof.rows.length !== 1 || proof.rows[0]?.ready !== true)\n throw new MigrationError(\n \"pgvector preflight did not prove every required visible extension-owned vector type. Install the vector extension before migration effects; VibORM never installs it.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, feature: \"vector\" } }\n );\n }\n if (snapshots.some((snapshot) => (snapshot.enums?.length ?? 0) > 0)) {\n const version = await executeRaw<{ version: string }>(\n \"SELECT current_setting('server_version_num') AS version\"\n );\n const number = Number(version.rows[0]?.version);\n if (!Number.isInteger(number) || number < 120_000)\n throw new MigrationError(\n \"PostgreSQL enum migrations require server_version_num >= 120000 for transactional enum safety\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n if (!snapshots.some(snapshotUsesGeoPoint)) return neki;\n let rows: readonly { ready?: unknown }[];\n try {\n rows = (await executeRaw<{ ready?: unknown }>(POSTGIS_PREFLIGHT_QUERY))\n .rows;\n } catch (failure) {\n throw new MigrationError(\n \"PostGIS GeoPoint preflight could not prove the required extension, types, and functions before migration effects.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause: errorCause(failure),\n meta: {\n dialect: this.dialect,\n feature: \"GeoPoint\",\n ...providerFacts(failure),\n },\n }\n );\n }\n if (rows.length !== 1 || rows[0]?.ready !== true) {\n throw new MigrationError(\n \"PostGIS GeoPoint preflight did not prove the required extension, visible types, and exact function signatures. VibORM never installs PostGIS.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, feature: \"GeoPoint\" } }\n );\n }\n return neki;\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw new MigrationError(\n \"PostgreSQL schema preflight could not prove the required catalog facts before migration effects.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause: errorCause(failure),\n meta: {\n dialect: this.dialect,\n feature: \"schema catalog\",\n ...providerFacts(failure),\n },\n }\n );\n }\n }\n\n /**\n * PostgreSQL reports a missing schema as SQLSTATE `3F000` only where the\n * statement names one; a catalog read filtered on a schema name that does not\n * exist just returns nothing. This proof is what makes that silence\n * impossible, and it runs before any missing-tracking-table translation can\n * be consulted, because PostgreSQL reports a missing schema and a missing\n * relation alike as `42P01`.\n */\n override async proveNamespaceExists(executeRaw: RawExecutor): Promise<void> {\n const namespace = this.requireEstateNamespace();\n const { rows } = await executeRaw<{ present: number }>(\n NAMESPACE_EXISTS_QUERY,\n [namespace]\n );\n if (rows.length === 0) {\n // The schema is named in the message AND on the allowlist's `namespace`\n // key (`src/errors/diagnostics.ts`), so a caller can read which estate\n // was missing without parsing prose.\n throw new MigrationError(\n `The configured PostgreSQL schema \"${namespace}\" does not exist. ` +\n \"VibORM never creates or drops a schema: create it (or fix the configured `namespace`) before running migrations.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, driver: this.driverName, namespace } }\n );\n }\n }\n\n // PostgreSQL deparses an index predicate rather than storing the statement,\n // so the declared spelling and the introspected one never match on their own\n // (Decision 7.4). The other dialects have no such gap and leave this unset.\n override canonicalizeIndexPredicates(\n tableName: string,\n predicates: readonly string[],\n executeRaw: RawExecutor,\n executeBatch?: BatchExecutor\n ): Promise<ReadonlyArray<string | undefined>> {\n return canonicalizeIndexPredicates(\n this.requireEstateNamespace(),\n this.qualify(tableName),\n predicates,\n executeRaw,\n executeBatch\n );\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string {\n const declaration = scalar[\"~\"].nativeType;\n\n // An identifier column's type is the ONE storage owner's answer, override\n // included — which is also why the override is not read separately here: a\n // spelling this domain cannot live in was refused at the schema boundary,\n // and a text-family one keeps text storage with the domain still admitted.\n const idStorage =\n idDomain === undefined\n ? undefined\n : idStorageOf(idDomain, declaration, \"pg\");\n if (idStorage) return idStorage.columnType;\n\n // The declaration's PostgreSQL choice, if it makes one\n const nativeType = nativeTypeFor(declaration, \"pg\");\n if (nativeType) {\n return scalarState.array ? `${nativeType.type}[]` : nativeType.type;\n }\n\n // Use centralized type mapping\n return getPostgresType({\n type: scalarState.type,\n array: scalarState.array,\n withTimezone: scalarState.withTimezone,\n dimension: scalarState.dimension,\n decimal: scalarState.decimal,\n });\n }\n\n override finalizeTable(table: TableDef): TableDef {\n return {\n ...table,\n ...(table.primaryKey?.name\n ? {\n primaryKey: {\n ...table.primaryKey,\n name: derivedMigrationName(table.primaryKey.name),\n },\n }\n : {}),\n uniqueConstraints: table.uniqueConstraints.map((item) => ({\n ...item,\n name: derivedMigrationName(item.name),\n })),\n foreignKeys: table.foreignKeys.map((item) => ({\n ...item,\n name: derivedMigrationName(item.name),\n })),\n indexes: table.indexes.map((index) => ({\n ...index,\n name: derivedMigrationName(index.name),\n ...(index.type === \"spatial\" ? { type: \"gist\" as const } : {}),\n })),\n };\n }\n\n /**\n * The only generator PostgreSQL can run itself.\n *\n * `gen_random_uuid()` (PostgreSQL 13+) produces exactly what `.uuid()`\n * produces — but ONLY when no prefix is declared: a prefixed field's public\n * value is `prefix-payload`, and a column default that wrote the bare payload\n * would disagree with every row the application inserts. No other format has\n * a server-side equivalent: `uuidv7()` arrives in PostgreSQL 18, and ULID,\n * KSUID, NanoID and CUID2 have none at all, so those fields carry no DDL\n * default and the application's own generator remains their single owner.\n */\n override getDefaultExpression(\n scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n const literal =\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n !scalarState.decimal &&\n (scalarState.array ||\n scalarState.type === \"datetime\" ||\n scalarState.type === \"date\")\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n scalarState.array &&\n Array.isArray(literal)\n ) {\n if (scalarState.decimal)\n return super.getDefaultExpression(scalar, scalarState);\n // A JSON field has no list form: members are scalars or temporals.\n const members = literal.map((value) =>\n (scalarState.type === \"datetime\" || scalarState.type === \"date\") &&\n typeof value === \"string\"\n ? encodePostgresTemporal(value)\n : value\n );\n return this.escapeValue(arrayLiteralText(members));\n }\n // `gen_random_uuid()` produces a `uuid`, so a column that does not hold one\n // cannot take it as a default. A `.uuid()` field whose native type override\n // makes it `bytea` is exactly that column: the value would be a type error\n // at DDL time, and the application generator is already its single owner.\n if (scalarState.hasDefault && scalarState.default === null)\n return undefined;\n if (\n scalarState.type === \"datetime\" &&\n scalarState.autoGenerate?.kind === \"now\"\n ) {\n const physical = this.mapScalarType(scalar, scalarState).toLowerCase();\n const clock =\n physical.includes(\"timestamptz\") || physical.includes(\"with time zone\")\n ? \"CURRENT_TIMESTAMP\"\n : \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n // PostgreSQL's omitted precision is six. Our generated logical DateTime\n // must remain a millisecond value even when native storage is wider.\n const precision = Number(\n TEMPORAL_PRECISION_TOKEN.exec(physical)?.[1] ?? 6\n );\n return precision > 3 ? `date_trunc('milliseconds', ${clock})` : clock;\n }\n if (\n (scalarState.type === \"datetime\" || scalarState.type === \"date\") &&\n scalarState.autoGenerate === undefined &&\n scalarState.hasDefault &&\n typeof literal === \"string\"\n )\n return this.escapeValue(encodePostgresTemporal(literal));\n if (scalarState.autoGenerate?.kind === \"now\") {\n if (scalarState.type === \"date\")\n return \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n if (scalarState.type === \"time\") {\n const physical = this.mapScalarType(scalar, scalarState).toLowerCase();\n if (Number(TEMPORAL_PRECISION_TOKEN.exec(physical)?.[1] ?? 6) > 3)\n return \"timezone('UTC', CURRENT_TIME(3))\";\n return physical.includes(\"timetz\") ||\n physical.includes(\"with time zone\")\n ? \"timezone('UTC', CURRENT_TIME)\"\n : \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n }\n }\n const idDomain = idDomainOfState(scalarState);\n if (\n idDomain !== undefined &&\n idStorageOf(idDomain, scalar[\"~\"].nativeType, \"pg\")?.representation ===\n \"bytes\"\n ) {\n return undefined;\n }\n // DDL follows the scalar's own generator rule (string/scalar.ts\n // `withIdentifier`): only a uuid generator the scalar INSTALLED becomes\n // `gen_random_uuid()`. A non-key `.uuid()` and a `generate: false` key are\n // caller-supplied, and a later `.default(...)` replaces the generator.\n if (\n scalarState.autoGenerate?.kind === \"uuid\" &&\n !isGeneratorDefault(scalarState.default)\n )\n return undefined;\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n protected override getAutoGenerateExpression(\n autoGenerate: import(\"@schema/scalars\").ScalarState[\"autoGenerate\"]\n ): string | undefined {\n switch (autoGenerate?.kind) {\n case \"uuid\":\n // `.id()`'s implicit ULID never reaches here (its kind is `ulid`), and\n // a NAMED `.uuid()` gets the database default only unprefixed.\n return hasIdPrefix(autoGenerate.prefix)\n ? undefined\n : \"gen_random_uuid()\";\n case \"now\":\n // Use database-level NOW() for consistent timestamps\n return \"NOW()\";\n default:\n return undefined;\n }\n }\n\n getEnumColumnType(\n tableName: string,\n columnName: string,\n _values: string[]\n ): string {\n return derivedMigrationName(`${tableName}_${columnName}_enum`);\n }\n\n // ===========================================================================\n // OVERRIDES: Column Definition Helpers\n // ===========================================================================\n\n /**\n * PostgreSQL integer types that support SERIAL auto-increment.\n */\n private static readonly SERIAL_TYPE_MAP: Record<string, string> = {\n integer: \"SERIAL\",\n int4: \"SERIAL\",\n int: \"SERIAL\",\n bigint: \"BIGSERIAL\",\n int8: \"BIGSERIAL\",\n smallint: \"SMALLSERIAL\",\n int2: \"SMALLSERIAL\",\n };\n\n /**\n * Formats the column type for PostgreSQL.\n * Handles SERIAL types for auto-increment and managed-enum qualification.\n */\n protected override formatColumnType(\n column: ColumnDef,\n context: DDLContext\n ): string {\n // Handle auto-increment with SERIAL types\n if (column.autoIncrement) {\n const normalizedType = column.type.toLowerCase();\n const serialType =\n PostgresMigrationDriver.SERIAL_TYPE_MAP[normalizedType];\n\n if (!serialType) {\n throw new MigrationError(\n \"PostgreSQL auto-increment (SERIAL) requires an integer type (INTEGER, BIGINT, SMALLINT). \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment.`,\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n column: column.name,\n type: column.type,\n autoIncrement: true,\n },\n }\n );\n }\n\n return serialType;\n }\n\n // A managed enum is a persistent object of this estate and is qualified\n // exactly like a table; its array form takes the same prefix. Everything\n // else — built-ins and the adapter-supported extension spellings — is a\n // provider object and passes through.\n return this.renderTypeToken(column.type, context);\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n const { table } = op;\n const columnDefs = table.columns.map((col) =>\n this.generateColumnDef(col, context)\n );\n\n if (table.primaryKey) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const pkName = `CONSTRAINT ${this.escapeIdentifier(this.generatedPrimaryKeyName(table.name, table.primaryKey.name))} `;\n columnDefs.push(`${pkName}PRIMARY KEY (${pkCols})`);\n }\n\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n columnDefs.push(\n `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n const sql = `CREATE TABLE ${this.qualify(table.name)} (\\n ${columnDefs.join(\",\\n \")}\\n)`;\n\n const statements = [sql];\n\n for (const idx of table.indexes) {\n statements.push(\n this.generateCreateIndex(\n {\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n },\n context\n )\n );\n }\n\n for (const fk of table.foreignKeys) {\n statements.push(\n this.generateAddForeignKey(\n {\n type: \"addForeignKey\",\n tableName: table.name,\n fk,\n },\n context\n )\n );\n }\n\n return statements;\n }\n\n /**\n * No `CASCADE` (§6.1). It dropped views, foreign keys and dependants in OTHER\n * schemas even though the enumeration behind this operation only ever\n * selected one, which made the namespace a filter instead of a boundary. The\n * foreign keys inside the program are materialized as explicit\n * `dropForeignKey` operations that sort ahead of every table drop\n * (`materializeDroppedTableForeignKeys`), and anything left is a dependency\n * this estate does not own: PostgreSQL's default `RESTRICT` then aborts the\n * transaction instead of deleting it.\n */\n generateDropTable(op: DropTableOperation, _context: DDLContext): string {\n return `DROP TABLE ${this.qualify(op.tableName)}`;\n }\n\n // `RENAME TO` takes ONE unqualified identifier: PostgreSQL renames the table\n // inside its own schema, and a qualified new name is a syntax error, not a\n // move (§4.1).\n generateRenameTable(op: RenameTableOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.qualify(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\n }\n\n protected override renameDerivedNames(\n owner: string,\n renames: ReadonlyMap<string, DerivedRename>\n ): string[] {\n return [...renames].map(([from, { kind, to }]) =>\n kind === \"constraint\"\n ? `ALTER TABLE ${this.qualify(owner)} RENAME CONSTRAINT ${this.escapeIdentifier(from)} TO ${this.escapeIdentifier(to)}`\n : `ALTER ${kind === \"type\" ? \"TYPE\" : \"INDEX\"} ${this.qualify(from)} RENAME TO ${this.escapeIdentifier(to)}`\n );\n }\n\n /** Generated keys have an explicit bounded name; catalog omissions stay unknown. */\n override generatedPrimaryKeyName(tableName: string, name?: string): string {\n return name || derivedMigrationName(`${tableName}_pkey`);\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(op: AddColumnOperation, context: DDLContext): string {\n const colDef = this.generateColumnDef(op.column, context);\n return `ALTER TABLE ${this.qualify(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n generateRenameColumn(\n op: RenameColumnOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n const { tableName, columnName, from, to } = op;\n const statements: string[] = [];\n const table = this.qualify(tableName);\n const col = this.escapeIdentifier(columnName);\n\n // A decimal descriptor change is VALIDATED BEFORE the type moves, and the\n // proof stays live across it. `ALTER TYPE numeric(p,s) USING c::numeric(p,s)`\n // on its own ROUNDS a value with too many fractional digits — silently\n // rewriting stored data, which §7.3 forbids outright (\"No descriptor change\n // rounds existing data\"). The constraint refuses those rows instead, before\n // any DDL runs, and because it is only dropped afterwards no concurrent\n // write can land an unrepresentable value while the conversion is in\n // flight. The whole sequence is one transaction on PostgreSQL, so a\n // refusal takes the validation, the DDL and the metadata back together.\n //\n // The TARGET domain alone is the whole predicate — `c = c::numeric(p,s)`\n // says \"this value survives the conversion unchanged\" without consulting\n // where it came from. So an unconstrained `numeric` adopted by a declared\n // descriptor is validated exactly like a descriptor-to-descriptor change;\n // skipping it there was the one path on which the `USING` cast still\n // rounded.\n const conversion = decimalConversionRequired(from, to);\n if (conversion && to.decimal) {\n const targetType = this.renderTypeToken(to.type, context);\n const constraint = this.escapeIdentifier(\n decimalConversionConstraintName(\n targetType.endsWith(\"[]\") ? \"list\" : \"scalar\",\n to.decimal\n )\n );\n // The migration owner's table lock, taken inside the transaction the\n // executor already opened (§7.4): it makes the validation and the type\n // change one lock acquisition rather than two, so nothing interleaves\n // between the row the constraint proved and the row the cast reads.\n statements.push(`LOCK TABLE ${table} IN ACCESS EXCLUSIVE MODE`);\n statements.push(\n `ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${postgresDecimalFitsCheck(col, targetType)})`\n );\n }\n\n if (from.type !== to.type) {\n if (from.default !== undefined) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP DEFAULT`\n );\n }\n // The new type is a column type token like any other, so a managed enum\n // is qualified here too — in BOTH positions, since the `USING` cast names\n // the same type the column is being changed to.\n const newType = this.renderTypeToken(to.type, context);\n // text → uuid is the ONE identifier conversion a dialect performs on its\n // own, and the only one whose failure is per-row rather than structural.\n // The guard changes no outcome — the cast below refuses the same estate —\n // it replaces \"invalid input syntax for type uuid\" with the count and the\n // two routes, before the transaction is spent.\n if (isPostgresTextToUuid(from.type, newType)) {\n statements.push(postgresTextToUuidGuard(table, col));\n }\n const fromBase = from.type.endsWith(\"[]\")\n ? from.type.slice(0, -2)\n : from.type;\n const throughText = this.managedEnumNames(context).has(fromBase)\n ? `::text${from.type.endsWith(\"[]\") ? \"[]\" : \"\"}`\n : \"\";\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} TYPE ${newType} USING ${col}${throughText}::${newType}`\n );\n }\n\n if (from.nullable !== to.nullable) {\n if (to.nullable) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP NOT NULL`\n );\n } else {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} SET NOT NULL`\n );\n }\n }\n\n if (\n from.default !== to.default ||\n (from.type !== to.type && from.default !== undefined)\n ) {\n if (to.default === undefined) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP DEFAULT`\n );\n } else {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} SET DEFAULT ${to.default}`\n );\n }\n }\n\n if (conversion && to.decimal) {\n const targetType = this.renderTypeToken(to.type, context);\n statements.push(\n `ALTER TABLE ${table} DROP CONSTRAINT ${this.escapeIdentifier(decimalConversionConstraintName(targetType.endsWith(\"[]\") ? \"list\" : \"scalar\", to.decimal))}`\n );\n }\n\n return statements;\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n // A low-lock build (T5b) runs CONCURRENTLY: writes keep flowing while it\n // reads the table, and an interrupted one leaves the index INVALID for\n // `resolve` to repair.\n generateCreateIndex(\n op: CreateIndexOperation,\n context: LowLockContext\n ): string {\n const { tableName, index } = op;\n const physicalType = index.type === \"spatial\" ? \"gist\" : index.type;\n\n // Validate index type against capabilities\n this.validateIndexType(physicalType, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const indexType = physicalType ? `USING ${physicalType} ` : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const where = index.where ? ` WHERE ${index.where}` : \"\";\n // PostgreSQL does not allow a schema on the index name in CREATE INDEX —\n // the index is created in the target table's schema, which is why the\n // TABLE carries the qualification and the index name is one identifier.\n const concurrently = context.lowLock === \"add\" ? \" CONCURRENTLY\" : \"\";\n return `CREATE ${unique}INDEX${concurrently} ${this.escapeIdentifier(index.name)} ON ${this.qualify(tableName)} ${indexType}(${cols})${where}`;\n }\n\n // DROP INDEX names the index itself, which lives in a schema and takes one\n // (§4.1) — the mirror of CREATE INDEX above.\n generateDropIndex(op: DropIndexOperation, _context: DDLContext): string {\n return `DROP INDEX ${this.qualify(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n // A low-lock key (T5b) is added NOT VALID, which checks new rows only and\n // scans nothing, and validated by a later commit, whose scan blocks no write.\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: LowLockContext\n ): string {\n const { tableName, fk } = op;\n if (context.lowLock === \"validate\") {\n return `ALTER TABLE ${this.qualify(tableName)} VALIDATE CONSTRAINT ${this.escapeIdentifier(fk.name)}`;\n }\n const cols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const onDelete = fk.onDelete\n ? ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`\n : \"\";\n const onUpdate = fk.onUpdate\n ? ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`\n : \"\";\n // Both TABLE positions are qualified — the owner and the reference target.\n // A bare `REFERENCES` target resolves through `search_path` and would let\n // one estate's constraint point at another schema's table.\n const notValid = context.lowLock === \"add\" ? \" NOT VALID\" : \"\";\n return `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(fk.name)} FOREIGN KEY (${cols}) REFERENCES ${this.qualify(fk.referencedTable)} (${refCols})${onDelete}${onUpdate}${notValid}`;\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.fkName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n _context: DDLContext\n ): string {\n const { tableName, constraint } = op;\n const cols = constraint.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(constraint.name)} UNIQUE (${cols})`;\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n _context: DDLContext\n ): string {\n const { tableName, primaryKey } = op;\n const cols = primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const name = this.escapeIdentifier(\n this.generatedPrimaryKeyName(tableName, primaryKey.name)\n );\n return `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${name} PRIMARY KEY (${cols})`;\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n // An enum OPERATION names an ORM-managed enum by construction, so its type\n // name is qualified unconditionally — the managed-enum SET exists only to\n // decide whether a COLUMN's type token happens to name one.\n generateCreateEnum(op: CreateEnumOperation, _context: DDLContext): string {\n const { enumDef } = op;\n const values = enumDef.values.map((v) => this.escapeValue(v)).join(\", \");\n return `CREATE TYPE ${this.qualify(enumDef.name)} AS ENUM (${values})`;\n }\n\n generateDropEnum(op: DropEnumOperation, _context: DDLContext): string {\n return `DROP TYPE ${this.qualify(op.enumName)}`;\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * The TRANSACTION lock a batch request takes after its limits (plans D1,\n * D7): it ends with the transaction, so nothing outlives the request. One\n * request cannot loop across requests, so it retries on the server until\n * the command's `lockWait` (default 10 s) passes, holding its snapshot that\n * long; the transaction's `statement_timeout` is longer by construction\n * (`resolveMigrationLimits`), so the loop is never cut short. A session\n * waits instead with one {@link generateLockFree} try per transaction,\n * holding no snapshot between them (`pinned-session.ts`). Stepwise work\n * adds the session lock on top ({@link generateSessionLock}), and releases\n * that one with {@link generateReleaseLock}.\n */\n generateAcquireLock(lockId: number): string | null {\n const { lockWait } = this.limits ?? DEFAULT_MIGRATION_LIMITS;\n return `WITH RECURSIVE lock_attempt AS (\n SELECT pg_try_advisory_xact_lock(${lockId}) AS acquired, clock_timestamp() + interval '${lockWait / 1000} seconds' AS deadline\n UNION ALL\n SELECT pg_try_advisory_xact_lock(${lockId}), previous.deadline\n FROM lock_attempt previous\n CROSS JOIN LATERAL (SELECT pg_sleep(CASE WHEN previous.acquired THEN 0 ELSE 0.05 END)) waiting\n WHERE NOT previous.acquired AND clock_timestamp() < previous.deadline\n ) SELECT acquired FROM lock_attempt ORDER BY acquired DESC LIMIT 1`;\n }\n\n generateReleaseLock(lockId: number): string | null {\n return `SELECT pg_advisory_unlock(${lockId}) AS released`;\n }\n\n /**\n * PlanetScale's Neki refuses a session advisory lock and a transaction one\n * in the same session (`NK013`, \"Mixing session and transaction advisory\n * locks is unavailable\"), so a command there holds only the session lock.\n */\n override holdsSessionLock(read: RawExecutor): Promise<boolean> {\n // Read afresh for each command: its answer is then the command's.\n NEKI.delete(this);\n return serverIsNeki(this, read);\n }\n\n override generateSessionLock(lockId: number): string {\n return `SELECT pg_try_advisory_lock(${lockId}) AS acquired`;\n }\n\n /**\n * Takes the transaction lock: outside a transaction, it releases with the\n * statement that asks; inside one, it is that transaction's lock try.\n */\n override generateLockFree(lockId: number): string {\n return `pg_try_advisory_xact_lock(${lockId})`;\n }\n\n /** A lock try, or the batch's loop: only boolean true proves ownership. */\n override provesLockAcquired(rows: readonly unknown[]): boolean {\n const row = rows[0];\n return (\n rows.length === 1 &&\n typeof row === \"object\" &&\n row !== null &&\n Reflect.get(row, \"acquired\") === true\n );\n }\n\n /**\n * `pg_advisory_unlock` returns a real boolean: `true` when this session held\n * the lock and released it, `false` when it never held it. Only one boolean\n * `true` proves the release; `false`, a missing row, extra rows, or anything\n * that is not a boolean leaves the session holding a lock nobody will free.\n */\n override provesLockReleased(rows: readonly unknown[]): boolean {\n if (rows.length !== 1) {\n return false;\n }\n const row = rows[0];\n if (typeof row !== \"object\" || row === null) {\n return false;\n }\n return Reflect.get(row, \"released\") === true;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n // Both inventories BIND the schema: they are the reads that decide what a\n // reset drops, and §4.2 admits no interpolated catalog operand.\n generateInventoryTables(): { sql: string; params: unknown[] } {\n return {\n sql: POSTGRES_MANAGED_TABLE_NAMES_QUERY,\n params: [this.requireEstateNamespace()],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n return {\n sql: `SELECT t.typname AS name\n FROM pg_type t\n JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n WHERE t.typtype = 'e' AND n.nspname = $1\n ORDER BY t.typname`,\n params: [this.requireEstateNamespace()],\n };\n }\n\n // No CASCADE here or on the inherited table drop (§6.1). PostgreSQL's\n // default RESTRICT is the containment boundary: a dependant this estate does\n // not own aborts the operation instead of being deleted with it.\n override generateDropEnumSQL(enumName: string): string | null {\n return `DROP TYPE IF EXISTS ${this.qualify(enumName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): readonly string[] {\n const physicalContext = {\n ...context,\n currentSchema: this.schemaAtOperation(context),\n };\n const {\n enumName,\n addValues = [],\n removeValues,\n newValues,\n dependentColumns,\n } = op;\n const statements: string[] = [];\n const enumType = this.qualify(enumName);\n const before =\n physicalContext.currentSchema?.enums?.find(\n (item) => item.name === enumName\n )?.values ?? [];\n const reordered =\n newValues !== undefined &&\n before.filter((value) => newValues.includes(value)).join(\"\\0\") !==\n newValues.filter((value) => before.includes(value)).join(\"\\0\");\n // ADD VALUE only touches the catalog; a recreated type admits a later\n // read of an added value in the same transaction.\n const usesAddedValue = readsAddedValue(\n enumName,\n addValues,\n physicalContext.currentSchema?.tables ?? [],\n context.followingOperations ?? []\n );\n if (!(removeValues?.length || reordered || usesAddedValue)) {\n const available = new Set(before);\n for (const value of addValues) {\n const following = newValues\n ?.slice(newValues.indexOf(value) + 1)\n .find((candidate) => available.has(candidate));\n statements.push(\n `ALTER TYPE ${enumType} ADD VALUE ${this.escapeValue(value)}${following === undefined ? \"\" : ` BEFORE ${this.escapeValue(following)}`}`\n );\n available.add(value);\n }\n return statements;\n }\n if (!newValues?.length)\n throw new MigrationError(\n `Cannot alter enum \"${enumName}\" without its full destination values`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n for (const { tableName, columnName } of dependentColumns ?? []) {\n const column = physicalContext.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((item) => item.name === columnName);\n const reference = `${this.qualify(tableName)} ALTER COLUMN ${this.escapeIdentifier(columnName)}`;\n if (column?.default !== undefined)\n statements.push(`ALTER TABLE ${reference} DROP DEFAULT`);\n const carrier = column?.type.endsWith(\"[]\") ? \"text[]\" : \"text\";\n statements.push(\n `ALTER TABLE ${reference} TYPE ${carrier} USING ${this.escapeIdentifier(columnName)}::${carrier}`\n );\n }\n statements.push(...this.buildEnumReplacementUpdates(op, physicalContext));\n statements.push(`DROP TYPE ${enumType}`);\n statements.push(\n `CREATE TYPE ${enumType} AS ENUM (${newValues.map((value) => this.escapeValue(value)).join(\", \")})`\n );\n for (const { tableName, columnName } of dependentColumns ?? []) {\n const column = physicalContext.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((item) => item.name === columnName);\n const reference = `${this.qualify(tableName)} ALTER COLUMN ${this.escapeIdentifier(columnName)}`;\n const target = column?.type.endsWith(\"[]\") ? `${enumType}[]` : enumType;\n statements.push(\n `ALTER TABLE ${reference} TYPE ${target} USING ${this.escapeIdentifier(columnName)}::${target}`\n );\n if (\n column?.default !== undefined &&\n !enumDefaultLabels(column, enumName).some(\n (label) => label !== null && removeValues?.includes(label)\n )\n )\n statements.push(\n `ALTER TABLE ${reference} SET DEFAULT ${column.default}`\n );\n }\n return statements;\n }\n\n /**\n * An array column's members move in one UPDATE that keeps their order; a\n * scalar column takes the shared per-value UPDATEs.\n */\n protected override enumColumnReplacementUpdates(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string,\n context: DDLContext\n ): string[] {\n const columnType = context.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((column) => column.name === columnName)?.type;\n if (!columnType?.endsWith(\"[]\")) {\n return super.enumColumnReplacementUpdates(\n op,\n tableName,\n columnName,\n context\n );\n }\n const cases = this.enumReplacementCases(op, tableName, columnName);\n if (cases.length === 0) return [];\n const column = this.escapeIdentifier(columnName);\n return [\n `UPDATE ${this.qualify(tableName)} SET ${column} = ARRAY(SELECT CASE value ${cases.join(\" \")} ELSE value END FROM unnest(${column}) WITH ORDINALITY AS member(value, position) ORDER BY position) WHERE ${column} IS NOT NULL`,\n ];\n }\n}\n\n// Export singleton instance\nexport const postgresMigrationDriver = new PostgresMigrationDriver();\n"],"mappings":"qwBA+CA,MACM,EAAqB,QACrB,EAAc,KAYpB,SAAS,gBAAgB,EAAsB,CAC7C,MAAO,IAAI,EAAK,QAAQ,KAAM,KAAK,CAAC,GAGtC,SAAS,aAAa,EAAsB,CAC1C,MAAO,IAAI,EAAK,QAAQ,KAAM,KAAK,CAAC,GAwBtC,eAAsB,4BACpB,EACA,EACA,EACA,EACA,EAC4C,CAC5C,GAAI,EAAW,SAAW,EAAG,MAAO,EAAE,CACtC,IAAM,EACJ,IACC,KAAU,IAAkC,CAC3C,IAAM,EAA2B,EAAE,CACnC,IAAK,IAAM,KAAO,EAAY,EAAQ,KAAK,MAAM,EAAc,EAAI,CAAC,CACpE,OAAO,IAEL,QAAU,KAAO,IAA6C,CAElE,IAAM,EAAO,CAAC,GAAG,EAAQ,MAAM,CAAC,CAAC,OAC9B,GAAa,EAA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