viborm 1.12.0 → 1.13.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.
Files changed (222) hide show
  1. package/README.md +1 -1
  2. package/dist/{adapter-internals-DNY4JWFC.mjs → adapter-internals-DZO1WI67.mjs} +2 -2
  3. package/dist/adapter-internals-DZO1WI67.mjs.map +1 -0
  4. package/dist/{adapter-namespace-VikEzb7o.mjs → adapter-namespace-C9RM19_J.mjs} +1 -1
  5. package/dist/{adapter-namespace-VikEzb7o.mjs.map → adapter-namespace-C9RM19_J.mjs.map} +1 -1
  6. package/dist/adapters.d.mts +1 -1
  7. package/dist/adapters.mjs +1 -1
  8. package/dist/{batch-refs-ZHBzfoBC.mjs → batch-refs-DShoaHb7.mjs} +1 -1
  9. package/dist/{batch-refs-ZHBzfoBC.mjs.map → batch-refs-DShoaHb7.mjs.map} +1 -1
  10. package/dist/builder-yLL4r6JS.mjs +2 -0
  11. package/dist/builder-yLL4r6JS.mjs.map +1 -0
  12. package/dist/bun-sql.d.mts +1 -1
  13. package/dist/bun-sql.mjs +1 -1
  14. package/dist/bun-sql.mjs.map +1 -1
  15. package/dist/bun-sqlite.d.mts +1 -1
  16. package/dist/bun-sqlite.mjs +1 -1
  17. package/dist/bun-sqlite.mjs.map +1 -1
  18. package/dist/cache/cloudflare-kv.d.mts +1 -1
  19. package/dist/cache/cloudflare-kv.mjs +1 -1
  20. package/dist/cache/memory.d.mts +1 -1
  21. package/dist/cache/memory.mjs +1 -1
  22. package/dist/cache.d.mts +1 -1
  23. package/dist/cache.mjs +1 -1
  24. package/dist/{chain-CoOL8l4W.mjs → chain-3bgO2RX3.mjs} +2 -2
  25. package/dist/{chain-CoOL8l4W.mjs.map → chain-3bgO2RX3.mjs.map} +1 -1
  26. package/dist/cli.mjs +1 -1
  27. package/dist/client-Bbke7iRo.mjs +50 -0
  28. package/dist/client-Bbke7iRo.mjs.map +1 -0
  29. package/dist/{client-DMbHPHC_.d.mts → client-Dx-6NncH.d.mts} +6 -3
  30. package/dist/client-nkU6M5bV.mjs +2 -0
  31. package/dist/client-nkU6M5bV.mjs.map +1 -0
  32. package/dist/client.d.mts +1 -1
  33. package/dist/client.mjs +1 -1
  34. package/dist/config.d.mts +2 -2
  35. package/dist/config.mjs +1 -1
  36. package/dist/d1.d.mts +1 -1
  37. package/dist/d1.mjs +1 -1
  38. package/dist/{datetime-physical-codec-Cdgq6sGs.mjs → datetime-physical-codec-kE6fh5zZ.mjs} +1 -1
  39. package/dist/{datetime-physical-codec-Cdgq6sGs.mjs.map → datetime-physical-codec-kE6fh5zZ.mjs.map} +1 -1
  40. package/dist/driver-BRYL6K0W.mjs +2 -0
  41. package/dist/driver-BRYL6K0W.mjs.map +1 -0
  42. package/dist/{driver-DX8GWgGf.mjs → driver-CcEhJcsE.mjs} +1 -1
  43. package/dist/{driver-DX8GWgGf.mjs.map → driver-CcEhJcsE.mjs.map} +1 -1
  44. package/dist/driver.d.mts +1 -1
  45. package/dist/driver.mjs +1 -1
  46. package/dist/{error-mapping-D--MVRCY.mjs → error-mapping-DW7TYOyA.mjs} +2 -2
  47. package/dist/{error-mapping-D--MVRCY.mjs.map → error-mapping-DW7TYOyA.mjs.map} +1 -1
  48. package/dist/every-hDecAr5k.mjs +2 -0
  49. package/dist/every-hDecAr5k.mjs.map +1 -0
  50. package/dist/{fs-estate-CfvH8Fxa.mjs → fs-estate-Bfy9RFvT.mjs} +2 -2
  51. package/dist/{fs-estate-CfvH8Fxa.mjs.map → fs-estate-Bfy9RFvT.mjs.map} +1 -1
  52. package/dist/identifier-conversion-771tvRzd.mjs +2 -0
  53. package/dist/identifier-conversion-771tvRzd.mjs.map +1 -0
  54. package/dist/identifiers-DLcLFNim.mjs +2 -0
  55. package/dist/identifiers-DLcLFNim.mjs.map +1 -0
  56. package/dist/identity-b2N94bh1.mjs +2 -0
  57. package/dist/identity-b2N94bh1.mjs.map +1 -0
  58. package/dist/{index-B4Bo2kEi.d.mts → index-B8MMx5Al.d.mts} +104 -16
  59. package/dist/index.d.mts +2 -2
  60. package/dist/index.mjs +1 -1
  61. package/dist/instrumentation.d.mts +1 -1
  62. package/dist/instrumentation.mjs +1 -1
  63. package/dist/{invariant-Dw9UB49x.mjs → invariant-CKZrz_S2.mjs} +1 -1
  64. package/dist/{invariant-Dw9UB49x.mjs.map → invariant-CKZrz_S2.mjs.map} +1 -1
  65. package/dist/{keys-CyfjT6uC.mjs → keys-BcQgRjMB.mjs} +2 -2
  66. package/dist/{keys-CyfjT6uC.mjs.map → keys-BcQgRjMB.mjs.map} +1 -1
  67. package/dist/keys-M0pWraMM.mjs +2 -0
  68. package/dist/keys-M0pWraMM.mjs.map +1 -0
  69. package/dist/libsql-lOqKLyZA.mjs +11 -0
  70. package/dist/libsql-lOqKLyZA.mjs.map +1 -0
  71. package/dist/libsql.d.mts +1 -1
  72. package/dist/libsql.mjs +1 -1
  73. package/dist/libsql.mjs.map +1 -1
  74. package/dist/{memory-BXOh0pq2.mjs → memory-CsRVfZdT.mjs} +2 -2
  75. package/dist/{memory-BXOh0pq2.mjs.map → memory-CsRVfZdT.mjs.map} +1 -1
  76. package/dist/migrations/mysql.d.mts +5 -5
  77. package/dist/migrations/mysql.mjs +1 -1
  78. package/dist/migrations/postgres.d.mts +5 -5
  79. package/dist/migrations/postgres.mjs +1 -1
  80. package/dist/migrations/sqlite.d.mts +5 -5
  81. package/dist/migrations/sqlite.mjs +1 -1
  82. package/dist/migrations/storage/durable-object.d.mts +1 -1
  83. package/dist/migrations/storage/durable-object.mjs +1 -1
  84. package/dist/migrations/storage/fs.d.mts +1 -1
  85. package/dist/migrations/storage/fs.mjs +1 -1
  86. package/dist/migrations/storage/r2.d.mts +1 -1
  87. package/dist/migrations/storage/r2.mjs +1 -1
  88. package/dist/migrations/surrealdb.d.mts +6 -0
  89. package/dist/migrations/surrealdb.mjs +2 -0
  90. package/dist/migrations/surrealdb.mjs.map +1 -0
  91. package/dist/migrations/tenant.d.mts +3 -3
  92. package/dist/migrations/tenant.mjs +1 -1
  93. package/dist/migrations.d.mts +5 -5
  94. package/dist/migrations.mjs +1 -1
  95. package/dist/migrations.mjs.map +1 -1
  96. package/dist/{model-u8Ug971J.mjs → model-DK9BhhNF.mjs} +2 -2
  97. package/dist/{model-u8Ug971J.mjs.map → model-DK9BhhNF.mjs.map} +1 -1
  98. package/dist/mysql-CIdv4h7j.mjs +100 -0
  99. package/dist/mysql-CIdv4h7j.mjs.map +1 -0
  100. package/dist/mysql-adapter-C3d-TdaO.mjs +2 -0
  101. package/dist/{mysql-adapter-BZtZrWeX.mjs.map → mysql-adapter-C3d-TdaO.mjs.map} +1 -1
  102. package/dist/mysql2.d.mts +1 -1
  103. package/dist/mysql2.mjs +1 -1
  104. package/dist/neon-http.d.mts +1 -1
  105. package/dist/neon-http.mjs +1 -1
  106. package/dist/{object-store-DdgcT8d9.mjs → object-store-DdKoB-lN.mjs} +2 -2
  107. package/dist/{object-store-DdgcT8d9.mjs.map → object-store-DdKoB-lN.mjs.map} +1 -1
  108. package/dist/{object-store-BI1YgcZ9.d.mts → object-store-DlGfGCb4.d.mts} +4 -4
  109. package/dist/on.d.mts +1 -1
  110. package/dist/on.mjs +1 -1
  111. package/dist/ordering.d.mts +1 -1
  112. package/dist/ordering.mjs +3 -3
  113. package/dist/ordering.mjs.map +1 -1
  114. package/dist/permissions.d.mts +1 -1
  115. package/dist/pg.d.mts +1 -1
  116. package/dist/pg.mjs +1 -1
  117. package/dist/pg.mjs.map +1 -1
  118. package/dist/pglite.d.mts +1 -1
  119. package/dist/pglite.mjs +1 -1
  120. package/dist/pglite.mjs.map +1 -1
  121. package/dist/planetscale.d.mts +1 -1
  122. package/dist/planetscale.mjs +1 -1
  123. package/dist/planetscale.mjs.map +1 -1
  124. package/dist/{planner-rsXqQbJR.d.mts → planner-DUjM5jQk.d.mts} +26 -1
  125. package/dist/{postgres-CrjBX4Yj.mjs → postgres-V7noUFbG.mjs} +45 -40
  126. package/dist/postgres-V7noUFbG.mjs.map +1 -0
  127. package/dist/{postgres-adapter--PJvhRSM.mjs → postgres-adapter-CvLB764t.mjs} +2 -2
  128. package/dist/{postgres-adapter--PJvhRSM.mjs.map → postgres-adapter-CvLB764t.mjs.map} +1 -1
  129. package/dist/postgres-adapter-D53hxZM4.mjs +2 -0
  130. package/dist/postgres-adapter-D53hxZM4.mjs.map +1 -0
  131. package/dist/{postgres-result-ehQiy2H-.mjs → postgres-result-CJ8C5cck.mjs} +1 -1
  132. package/dist/{postgres-result-ehQiy2H-.mjs.map → postgres-result-CJ8C5cck.mjs.map} +1 -1
  133. package/dist/postgres.d.mts +1 -1
  134. package/dist/postgres.mjs +1 -1
  135. package/dist/{relation-bound-5hindjxU.mjs → relation-bound-C02WchLT.mjs} +1 -1
  136. package/dist/{relation-bound-5hindjxU.mjs.map → relation-bound-C02WchLT.mjs.map} +1 -1
  137. package/dist/{result-parsing-Dkgy-xcy.mjs → result-parsing-Bj0gVF-R.mjs} +1 -1
  138. package/dist/{result-parsing-Dkgy-xcy.mjs.map → result-parsing-Bj0gVF-R.mjs.map} +1 -1
  139. package/dist/{result-shape-BPdZ1rUk.mjs → result-shape-D5gZFVps.mjs} +2 -2
  140. package/dist/{result-shape-BPdZ1rUk.mjs.map → result-shape-D5gZFVps.mjs.map} +1 -1
  141. package/dist/{rows-C4hPsLfi.mjs → rows-B1SG8qg9.mjs} +2 -2
  142. package/dist/{rows-C4hPsLfi.mjs.map → rows-B1SG8qg9.mjs.map} +1 -1
  143. package/dist/rows-of-qH0_KyL6.mjs.map +1 -1
  144. package/dist/schema/json.d.mts +1 -1
  145. package/dist/schema/json.mjs +1 -1
  146. package/dist/schema/json.mjs.map +1 -1
  147. package/dist/{schema-C8_nS6Ub.mjs → schema-DKL7GSu7.mjs} +2 -2
  148. package/dist/{schema-C8_nS6Ub.mjs.map → schema-DKL7GSu7.mjs.map} +1 -1
  149. package/dist/{schema-introspection-BiG5153d.mjs → schema-introspection-BogU9kCO.mjs} +2 -2
  150. package/dist/{schema-introspection-BiG5153d.mjs.map → schema-introspection-BogU9kCO.mjs.map} +1 -1
  151. package/dist/schema.d.mts +1 -1
  152. package/dist/schema.mjs +1 -1
  153. package/dist/{select-assembly-Dcaqm09G.mjs → select-assembly-BL9BG6oR.mjs} +1 -1
  154. package/dist/select-assembly-BL9BG6oR.mjs.map +1 -0
  155. package/dist/soft-delete.d.mts +1 -1
  156. package/dist/{sql-statement-tokens-CV2qkIKN.mjs → sql-statement-tokens-ugBPr6SM.mjs} +1 -1
  157. package/dist/{sql-statement-tokens-CV2qkIKN.mjs.map → sql-statement-tokens-ugBPr6SM.mjs.map} +1 -1
  158. package/dist/sql.d.mts +1 -1
  159. package/dist/sqlite-adapter-CVKv1u4i.mjs +2 -0
  160. package/dist/{sqlite-adapter-CMRvEsOv.mjs.map → sqlite-adapter-CVKv1u4i.mjs.map} +1 -1
  161. package/dist/{sqlite-utils-DztTzv08.mjs → sqlite-utils-B-Y47_Uz.mjs} +2 -2
  162. package/dist/{sqlite-utils-DztTzv08.mjs.map → sqlite-utils-B-Y47_Uz.mjs.map} +1 -1
  163. package/dist/sqlite3.d.mts +1 -1
  164. package/dist/sqlite3.mjs +1 -1
  165. package/dist/sqlite3.mjs.map +1 -1
  166. package/dist/standard-sql-BHpLmLeM.mjs +6 -0
  167. package/dist/standard-sql-BHpLmLeM.mjs.map +1 -0
  168. package/dist/surrealdb.d.mts +86 -0
  169. package/dist/surrealdb.mjs +2 -0
  170. package/dist/surrealdb.mjs.map +1 -0
  171. package/dist/surrealql-Bnu3BzHE.mjs +2 -0
  172. package/dist/surrealql-Bnu3BzHE.mjs.map +1 -0
  173. package/dist/{to-many-CMK2Ys4N.mjs → to-many-Dd1m0XqX.mjs} +2 -2
  174. package/dist/{to-many-CMK2Ys4N.mjs.map → to-many-Dd1m0XqX.mjs.map} +1 -1
  175. package/dist/{utils-BLIPe1Cb.mjs → utils-CuQHO2NF.mjs} +2 -2
  176. package/dist/{utils-BLIPe1Cb.mjs.map → utils-CuQHO2NF.mjs.map} +1 -1
  177. package/dist/utils-QZGdBir8.mjs +2 -0
  178. package/dist/utils-QZGdBir8.mjs.map +1 -0
  179. package/dist/{validation-CMvAxrIo.mjs → validation-mTttU3Fk.mjs} +1 -1
  180. package/dist/{validation-CMvAxrIo.mjs.map → validation-mTttU3Fk.mjs.map} +1 -1
  181. package/dist/validation.d.mts +1 -1
  182. package/dist/validation.mjs +1 -1
  183. package/dist/validator-BjNxS3uX.mjs +2 -0
  184. package/dist/validator-BjNxS3uX.mjs.map +1 -0
  185. package/dist/version-Ce4zn8qc.mjs +2 -0
  186. package/dist/{version-BPr1CKHw.mjs.map → version-Ce4zn8qc.mjs.map} +1 -1
  187. package/dist/write-sinks-Bean5xf5.mjs +2 -0
  188. package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bean5xf5.mjs.map} +1 -1
  189. package/package.json +33 -18
  190. package/dist/adapter-internals-DNY4JWFC.mjs.map +0 -1
  191. package/dist/builder-CUyS5pxN.mjs +0 -2
  192. package/dist/builder-CUyS5pxN.mjs.map +0 -1
  193. package/dist/client-Db-sVg93.mjs +0 -2
  194. package/dist/client-Db-sVg93.mjs.map +0 -1
  195. package/dist/client-Dpgesimv.mjs +0 -49
  196. package/dist/client-Dpgesimv.mjs.map +0 -1
  197. package/dist/driver-XlmOJFRH.mjs +0 -2
  198. package/dist/driver-XlmOJFRH.mjs.map +0 -1
  199. package/dist/every-B1gLSYOW.mjs +0 -2
  200. package/dist/every-B1gLSYOW.mjs.map +0 -1
  201. package/dist/identifier-conversion-D3oCaSia.mjs +0 -2
  202. package/dist/identifier-conversion-D3oCaSia.mjs.map +0 -1
  203. package/dist/identity-BtuwgqhS.mjs +0 -2
  204. package/dist/identity-BtuwgqhS.mjs.map +0 -1
  205. package/dist/libsql-C4sm2U20.mjs +0 -11
  206. package/dist/libsql-C4sm2U20.mjs.map +0 -1
  207. package/dist/mysql-BR0XTumr.mjs +0 -99
  208. package/dist/mysql-BR0XTumr.mjs.map +0 -1
  209. package/dist/mysql-adapter-BZtZrWeX.mjs +0 -2
  210. package/dist/postgres-CrjBX4Yj.mjs.map +0 -1
  211. package/dist/postgres-adapter-BJcelBCx.mjs +0 -2
  212. package/dist/postgres-adapter-BJcelBCx.mjs.map +0 -1
  213. package/dist/select-assembly-Dcaqm09G.mjs.map +0 -1
  214. package/dist/sqlite-adapter-CMRvEsOv.mjs +0 -2
  215. package/dist/standard-sql-BtzSzrof.mjs +0 -6
  216. package/dist/standard-sql-BtzSzrof.mjs.map +0 -1
  217. package/dist/validator-CtSM_qvW.mjs +0 -2
  218. package/dist/validator-CtSM_qvW.mjs.map +0 -1
  219. package/dist/version-BPr1CKHw.mjs +0 -2
  220. package/dist/write-sinks-3IKCDF-S.mjs +0 -2
  221. /package/dist/{contract-CYl0OzhZ.d.mts → contract-BOwMGvl2.d.mts} +0 -0
  222. /package/dist/{sql-D7JnXgUh.d.mts → sql-BbLhTqDH.d.mts} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-CrjBX4Yj.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 EnumDependentCheck,\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\n/**\n * The CHECK constraints of the estate's tables on a column of each named enum\n * or of its array, one row per enum and constraint. `type` is the enum as this\n * session's deparse spells it, read beside the definition so the two agree.\n */\nconst ENUM_DEPENDENT_CHECKS_QUERY = `SELECT t.typname AS \"enumName\", c.relname AS \"tableName\", con.conname AS name, pg_catalog.pg_get_constraintdef(con.oid) AS definition, pg_catalog.format_type(t.oid, NULL) AS type\nFROM pg_catalog.pg_type t\nJOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\nJOIN pg_catalog.pg_class c ON c.relnamespace = n.oid\nJOIN pg_catalog.pg_constraint con ON con.conrelid = c.oid AND con.contype = 'c'\nWHERE n.nspname = $1 AND t.typtype = 'e' AND t.typname = ANY($2::text[])\n AND EXISTS (SELECT 1 FROM pg_catalog.pg_attribute a WHERE a.attrelid = con.conrelid AND a.attnum = ANY(con.conkey) AND a.atttypid IN (t.oid, t.typarray))\nORDER BY t.typname, c.relname, con.conname`;\n\n/**\n * The values of an enum a deparsed definition names as constants: PostgreSQL\n * writes each as `'label'::type`, or `'{…}'::type[]` for an array, with `'`\n * doubled and `type` spelled as `format_type` does in the same session. A\n * double-quoted identifier is skipped whole, so a quote inside one starts no\n * literal. An array literal this reader cannot read names nothing here; its\n * re-addition then fails inside the recreation's transaction.\n */\nfunction enumValuesNamed(definition: string, type: string): string[] {\n const cast = `::${type}`;\n const values = new Set<string>();\n let cursor = 0;\n while (cursor < definition.length) {\n const quote = definition[cursor];\n if (quote !== \"'\" && quote !== '\"') {\n cursor++;\n continue;\n }\n let body = \"\";\n for (cursor++; cursor < definition.length; cursor++) {\n if (definition[cursor] !== quote) body += definition[cursor];\n else if (definition[cursor + 1] === quote) body += definition[++cursor];\n else break;\n }\n cursor++;\n if (quote === '\"' || !definition.startsWith(cast, cursor)) continue;\n const array = definition.startsWith(\"[]\", cursor + cast.length);\n const end = cursor + cast.length + (array ? 2 : 0);\n if (IDENTIFIER_PART.test(definition[end] ?? \"\")) continue;\n for (const value of array ? (readArrayLiteralText(body) ?? []) : [body])\n if (value !== null) values.add(value);\n cursor = end;\n }\n return [...values];\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 /**\n * Neki's router plans every statement against the schema committed before\n * its transaction, and on some of its cells refuses any relation once the\n * transaction changed the schema: the answer the lock protocol read for\n * this command (or the command it views).\n */\n override commitsSchemaChangesAlone(): boolean {\n for (\n let owner: object | null = this;\n owner !== null;\n owner = Object.getPrototypeOf(owner)\n ) {\n const neki = NEKI.get(owner);\n if (neki !== undefined) return neki;\n }\n return false;\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 override async readEnumDependentChecks(\n enumNames: readonly string[],\n executeRaw: RawExecutor\n ): Promise<\n ReadonlyArray<EnumDependentCheck & { readonly enumName: string }>\n > {\n const result = await executeRaw<{\n enumName: string;\n tableName: string;\n name: string;\n definition: string;\n type: string;\n }>(ENUM_DEPENDENT_CHECKS_QUERY, [\n this.requireEstateNamespace(),\n arrayLiteralText(enumNames),\n ]);\n return result.rows.map(({ type, ...check }) => ({\n ...check,\n values: enumValuesNamed(check.definition, type),\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 // `TYPE text` re-parses every CHECK on the column, and one comparing it to\n // a label then has no operator (42883): each is dropped first and added\n // back, same name and definition, once the columns are the enum again.\n const checks = this.recreatedEnumChecks(op, context);\n for (const { tableName, name } of checks)\n statements.push(\n `ALTER TABLE ${this.qualify(tableName)} DROP CONSTRAINT ${this.escapeIdentifier(name)}`\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 for (const { tableName, name, definition } of checks)\n statements.push(\n `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(name)} ${definition}`\n );\n return statements;\n }\n\n /**\n * The live CHECKs a recreation drops and adds back, refused before any\n * effect where the addition cannot be the constraint that was dropped: its\n * definition names a value the new type no longer has, or an earlier rename\n * in this batch moved the table or a column its definition, read before the\n * rename, still names.\n */\n private recreatedEnumChecks(\n op: AlterEnumOperation,\n context: DDLContext\n ): readonly EnumDependentCheck[] {\n const checks = op.dependentChecks ?? [];\n for (const check of checks) {\n const removed = check.values.find((value) =>\n op.removeValues?.includes(value)\n );\n if (removed !== undefined)\n throw new MigrationError(\n `CHECK constraint \"${check.name}\" on \"${check.tableName}\" names the value '${removed}', which this change removes from enum \"${op.enumName}\", so it cannot be added back once the type is recreated. Drop the constraint or rewrite it without '${removed}', then push again. No migration effects were executed.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: check.tableName,\n constraint: check.name,\n enum: op.enumName,\n value: removed,\n },\n }\n );\n const renamed = context.precedingOperations?.some(\n (preceding) =>\n (preceding.type === \"renameTable\" &&\n preceding.from === check.tableName) ||\n (preceding.type === \"renameColumn\" &&\n preceding.tableName === check.tableName)\n );\n if (renamed)\n throw new MigrationError(\n `CHECK constraint \"${check.name}\" on \"${check.tableName}\" must be dropped and added back around the recreation of enum \"${op.enumName}\", but this push renames \"${check.tableName}\" or one of its columns first, and the definition was read before that rename. Push the rename on its own, then the enum change. No migration effects were executed.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: check.tableName,\n constraint: check.name,\n enum: op.enumName,\n },\n }\n );\n }\n return checks;\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":"owBA+CA,MACM,GAAqB,QACrB,GAAc,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,4B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O,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,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{d as n,f as r}from"./query-CTna5P9o.mjs";import{O as i,v as a}from"./geo-point-codec-Ggv29hSH.mjs";import{o,t as s}from"./sql-BsBoKwaf.mjs";import{o as c}from"./native-types-CQH05hcr.mjs";import{a as ee}from"./physical-CjG29tya.mjs";import{t as te}from"./geo-area-codec-B3QtKij8.mjs";import{t as l}from"./adapter-result-parser-Bz3WtMBa.mjs";import{r as u}from"./adapter-internals-DNY4JWFC.mjs";import{a as d}from"./datetime-physical-codec-Cdgq6sGs.mjs";import{t as f}from"./array-literal-DfgmVxKI.mjs";import{A as p,C as m,D as h,E as g,N as _,S as v,T as y,_ as b,a as x,b as S,c as C,d as w,f as T,h as E,i as D,j as O,l as k,m as A,n as j,o as M,p as N,r as ne,s as P,v as F,w as I,x as L,y as R}from"./standard-sql-BtzSzrof.mjs";import{r as z}from"./batch-refs-ZHBzfoBC.mjs";import{t as B}from"./adapter-namespace-VikEzb7o.mjs";import{a as V,c as H,i as U,l as W,m as G,n as K,p as q,r as J,s as Y,t as X}from"./select-assembly-Dcaqm09G.mjs";var Z=class JsonParameter{json;constructor(e){this.json=e,Object.freeze(this)}static from(e){let t=JSON.stringify(e);return t===void 0?void 0:new JsonParameter(t)}toString(){return this.json}toJSON(){return JSON.parse(this.json)}};const Q=_(`"`);function postgresLikePattern(e,t){let n=e===`startsWith`?``:`%`,r=e===`endsWith`?``:`%`,[i,a]=t.values;return t.strings.join(``)===``&&typeof i==`string`&&a===void 0?o`${n+p(i)+r}`:o`(${o.raw(n&&`'%' || `)}REPLACE(REPLACE(REPLACE(CAST(${t} AS TEXT), CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')${o.raw(r&&` || '%'`)})`}function postgresJsonObject(e){if(e.length===0)return o.raw`'{}'::json`;let t=[],n=o.raw(e.length>50?`jsonb_build_object`:`json_build_object`);for(let r=0;r<e.length;r+=50){let i=e.slice(r,r+50).flatMap(([e,t])=>[o`${e}::text`,t]);t.push(o`${n}(${o.join(i,`, `)})`)}return t.length===1?t[0]:o`(${o.join(t,` || `)})::json`}const re=G(e=>`${e}_pkey`);var CastParameter=class extends s{type;constructor(e,t){super([`CAST(`,` AS ${t})`],[e]),this.type=t}},ArrayParameter=class extends s{};const ie=g().list;function arrayParameter(e){let t=e[0];if(t===void 0)return;let n=t instanceof CastParameter?t.type:void 0,r=[];for(let t of e){let e=t instanceof CastParameter?t:void 0,[i,a,o]=t.strings;if(e?.type!==n||!e&&(i!==``||a!==``||o!==void 0))return;let s=t.values[0];if(s instanceof Uint8Array)r.push(`\\x${Array.from(s,e=>e.toString(16).padStart(2,`0`)).join(``)}`);else if(typeof s==`string`||typeof s==`number`||typeof s==`bigint`||typeof s==`boolean`)r.push(String(s));else return}let i=f(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>o`div(${e}, ${t})`,remainder:(e,t)=>o`mod(${e}, ${t})`},ae=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){B(this,e,`postgresql`),this.identifiers=T(Q,this.namespace,!0),q(this,t?this.#r():void 0),u(this,{batchRefs:this.#n,constraints:re,select:this.#e.select})}raw=v();identifiers;literals={...g(),dateTime:e=>o`${d(e)}`,true:()=>o.raw`TRUE`,false:()=>o.raw`FALSE`,json:e=>o`${Z.from(e)}`,decimal:(e,t)=>new CastParameter(i(e,t,`text`),a(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):o`${e}`,list:e=>arrayParameter(e)??ie(e)};operators={...x(),containsText:(e,t)=>o`${e} LIKE ${postgresLikePattern(`contains`,t)} ESCAPE '\\'`,startsWithText:(e,t)=>o`${e} LIKE ${postgresLikePattern(`startsWith`,t)} ESCAPE '\\'`,endsWithText:(e,t)=>o`${e} LIKE ${postgresLikePattern(`endsWith`,t)} ESCAPE '\\'`,insensitiveText:(e,t,n,r)=>o`${this.expressions.caseSensitiveText(t,r,!0)} ILIKE ${postgresLikePattern(e,n)} ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>o`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${p(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>o`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>this.operators.in(this.expressions.caseSensitiveText(e,n,!1),t),in:(e,t)=>t instanceof ArrayParameter?o`${e} = ANY(${t})`:o`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?o`${e} <> ALL(${t})`:o`${e} NOT IN ${t}`,...F(),...L(),...E(this.literals.true,this.literals.false),...w()};expressions={...D(),caseSensitiveText:(e,t,n=!1)=>{let i=c(t,`pg`)?.type;if(!n&&i?.toLowerCase()===`xml`)throw new r(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return n&&i&&ae.test(i)?o`CAST(${e} AS TEXT)`:e},caseFold:(e,t)=>o`LOWER(${this.expressions.caseSensitiveText(e,t,!0)})`,concat:(...e)=>e.length===0?o.raw`''`:e.length===1?e[0]:o`(${o.join(e,` || `)})`,greatest:(...e)=>o`GREATEST(${o.join(e,`, `)})`,least:(...e)=>o`LEAST(${o.join(e,`, `)})`,integerDivide:(e,t)=>o`(${e} / ${t})`,decimalCast:(e,t)=>o`CAST(${e} AS ${o.raw(a(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?o`decode(${e}, 'hex')`:o`CAST(${e} AS ${o.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:ne({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>o`encode(${e}, 'hex')`};aggregates={...j(`'Infinity'::float8`),min:(e,t=!1)=>t?o`BOOL_AND(${e})`:o`MIN(${e})`,max:(e,t=!1)=>t?o`BOOL_OR(${e})`:o`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:C(1e3)};json={equals:(e,t)=>o`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?o.raw`'[]'::json`:o`json_build_array(${o.join(e,`, `)})`,emptyArray:()=>o.raw`'[]'::json`,agg:e=>o`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>o`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>o`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>o`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>o`(${this.json.foldableStringAtPath(e,t)} COLLATE "C")`,foldableStringAtPath:(e,t)=>o`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END)`,contains:(e,t)=>o`(${e})::jsonb @> ${t}`,lastElement:e=>o`(${e})::jsonb -> -1`,value:e=>o`${Z.from(e)}`};arrays={literal:e=>e.length===0?o.raw`'{}'`:o`ARRAY[${o.join(e,`, `)}]`,value:(e,t)=>o`${t?e.map(e=>typeof e==`string`?d(e):e):e}`,enumValue:e=>o`${f(e)}`,ofRows:e=>o`ARRAY(${e})`,has:(e,t)=>o`${t} = ANY(${e})`,hasEvery:(e,t)=>o`${e} @> ${t}`,hasSome:(e,t)=>o`${e} && ${t}`,isEmpty:e=>o`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>o`CAST(${e} AS TEXT[])`,length:e=>o`cardinality(${e})`,get:(e,t)=>o`${e}[${t}]`,push:(e,t)=>o`array_append(${e}, ${t})`,set:(e,t,n)=>o`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...k(),nullsFirst:(e,t)=>t===`desc`?o`${e} DESC NULLS FIRST`:o`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?o`${e} DESC NULLS LAST`:o`${e} ASC NULLS LAST`};clauses=y();set={...R(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):o`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?H($,e,t,n.decimal):o`${e} = ${e} / ${t}`,push:(e,t)=>o`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>o`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=m();subqueries=h(Q);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e.distinct?o`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:o`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=P(Q,{inlining:o.raw(`NOT MATERIALIZED`)});mutations={skipDuplicatesStrategy:`sql`,insert:N(Q),insertDefault:e=>o`INSERT INTO ${e} DEFAULT VALUES`,...b(),returning:e=>o`RETURNING ${e}`,upserted:o.raw(`(xmax = 0)`),...S()};assertions={exists:e=>o`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>o`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,holds:(e,t)=>o`SELECT CASE WHEN ${e} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS "__viborm_judged__"${t?o` FROM ${t}`:o``}`};joins={...M(),full:(e,t)=>o`FULL OUTER JOIN ${e} ON ${t}`,...A(Q)};setOperations=I(Q,(e,t,n)=>{let r=o.raw(Q(e.alias)),column=e=>o.raw(Q(e)),[i,...a]=t,s=i.map((t,n)=>o`COALESCE(${t}, (${r}."row").${column(e.columns[n])})`);return o`(SELECT NULL::${e.table} AS "row") AS ${r} CROSS JOIN LATERAL (VALUES ${o.join([s,...a].map(O),`, `)}) AS ${o.raw(Q(n))}(${o.join(e.columns.map(column),`, `)})`});capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0,joinsJunctionFilters:`unbounded`,readsNodesByKey:!0};lastInsertId=()=>o.raw`lastval()`;#t=z({table:o.raw`"__viborm_batch_refs"`,batchIdColumn:o.raw`"batch_id"`,keyColumn:o.raw`"ref_key"`,valueColumn:o.raw`"ref_value"`,createTable:o.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>o`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>o`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new n(`PostgreSQL vector components must fit a finite float32 value.`,{code:t.INVALID_INPUT});return o`${`[${e.join(`,`)}]`}::vector`},l2:(e,t)=>o`${e} <-> ${t}`,cosine:(e,t)=>o`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>o`ST_X(${e}::geometry)`,latitude=e=>o`ST_Y(${e}::geometry)`;return{value:(e,t)=>o`ST_SetSRID(ST_MakePoint(${e}, ${t}), 4326)::geography`,longitude,latitude,...J(longitude,latitude,this.operators,(e,t)=>{let n=U(t);if(n.length!==0)return this.operators.or(...n.map(t=>o`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>o`ST_Intersects(${o`ST_SetSRID(ST_GeomFromGeoJSON(${V(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=o`RADIANS(ST_X(${e}::geometry))`,r=o`RADIANS(ST_Y(${e}::geometry))`,i=o`RADIANS(ST_X(${t}::geometry))`,a=o`RADIANS(ST_Y(${t}::geometry))`;return o`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${te} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${o`POWER(SIN((${a} - ${r}) / 2), 2) + COS(${r}) * COS(${a}) * POWER(SIN((${i} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>ee(e,t,`pg`)?.representation??`text`,parseResult:l,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
2
- //# sourceMappingURL=postgres-adapter-BJcelBCx.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-adapter-BJcelBCx.mjs","names":["sql","#createGeoPointSql","#batchRefs","#assemble","#cteBatchRefs"],"sources":["../src/sql/json-parameter.ts","../src/adapters/databases/postgres/postgres-adapter.ts"],"sourcesContent":["/**\n * One JSON document, bound as one statement parameter.\n *\n * PostgreSQL's JSON literals bind CANONICAL JSON TEXT and let the server cast\n * that text from the parameter's column context. Nothing at the driver can\n * tell that text apart from an ordinary string, so every transport that\n * re-serializes a `json`/`jsonb` parameter has to be told not to, and only some\n * of them offer a place to say it: postgres.js takes a `json` type override\n * (`src/drivers/postgres/index.ts`), PGlite's own JSON serializer already\n * passes strings through, and node-postgres/Neon never touch a string. Bun SQL\n * offers no such hook and JSON-ENCODES a string bound to a `json`/`jsonb`\n * parameter, storing the physical document `\"[1,2,3]\"` — a JSON string — where\n * `[1,2,3]` was meant (upstream Drizzle #5287).\n *\n * This carrier is the missing distinction, and it needs no per-transport hook:\n * a PostgreSQL transport can only reach a bound value through string coercion\n * or through JSON serialization, and this renders as its canonical text under\n * BOTH. The text captured at construction is the ONE stored fact: `toJSON`\n * answers it parsed back, and `JSON.stringify` of its own output re-serializes\n * to those exact bytes, so both protocols agree even if the caller mutates the\n * original value after binding.\n * Bun, which serializes an object parameter for a `json`/`jsonb` column with\n * `JSON.stringify`, therefore stores the exact document for every JSON type,\n * including the number, boolean and null primitives that no bare JavaScript\n * value can express to it (a JS number is bound as `integer`, `null` as SQL\n * NULL).\n *\n * `json` is an own property rather than a private field because it is what a\n * parameter snapshot shows: diagnostics read own properties, so an opted-in\n * `includeParams` disclosure keeps the document instead of reporting `{}`.\n */\nexport class JsonParameter {\n /** The canonical JSON text — `JSON.stringify(value)`. */\n readonly json: string;\n\n private constructor(json: string) {\n this.json = json;\n Object.freeze(this);\n }\n\n /**\n * The carrier for `value`, or `undefined` when `JSON.stringify` has no text\n * for it (`undefined`, a function, a symbol). Those bound `undefined`\n * directly before this carrier existed, which providers send as SQL NULL;\n * carrying them would bind the text `\"undefined\"` instead.\n */\n static from(value: unknown): JsonParameter | undefined {\n // The lib signature says `string`, which is only true for the values it can\n // represent.\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? undefined : new JsonParameter(json);\n }\n\n toString(): string {\n return this.json;\n }\n\n toJSON(): unknown {\n return JSON.parse(this.json);\n }\n}\n","import {\n QueryError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport { JsonParameter } from \"../../../sql/json-parameter\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport { passThroughParseResult } from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n type TextMatch,\n} from \"../../database-adapter\";\nimport { createOnConflictBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n rowValues,\n} from \"../../shared/standard-sql\";\nimport { arrayLiteralText } from \"./array-literal\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n/**\n * The `LIKE` pattern matching `value` literally where `kind` says. A plain\n * string (a bare bound parameter) is escaped here and bound as the finished\n * pattern; any other operand (a column, a JSON path) is escaped by the server.\n */\nfunction postgresLikePattern(kind: TextMatch, value: Sql): Sql {\n const head = kind === \"startsWith\" ? \"\" : \"%\";\n const tail = kind === \"endsWith\" ? \"\" : \"%\";\n const [literal, other] = value.values;\n if (\n value.strings.join(\"\") === \"\" &&\n typeof literal === \"string\" &&\n other === undefined\n )\n return sql`${head + escapeLikeLiteral(literal) + tail}`;\n return sql`(${sql.raw(head && \"'%' || \")}REPLACE(REPLACE(REPLACE(CAST(${value} AS TEXT), CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')${sql.raw(tail && \" || '%'\")})`;\n}\nfunction postgresJsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw`'{}'::json`;\n const chunks: Sql[] = [];\n const buildObject = sql.raw(\n pairs.length > 50 ? \"jsonb_build_object\" : \"json_build_object\"\n );\n // PostgreSQL limits a function call to 100 arguments. Chunking preserves\n // the surrounding aggregate scope, unlike moving values into a subquery.\n for (let start = 0; start < pairs.length; start += 50) {\n const args = pairs\n .slice(start, start + 50)\n .flatMap(([key, value]) => [sql`${key}::text`, value]);\n chunks.push(sql`${buildObject}(${sql.join(args, \", \")})`);\n }\n return chunks.length === 1\n ? chunks[0]!\n : sql`(${sql.join(chunks, \" || \")})::json`;\n}\nconst POSTGRES_CONSTRAINTS = createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n);\n\n/** An operand cast to the type its column holds: `uuid`, `NUMERIC(p,s)`. */\nclass CastParameter extends Sql {\n readonly type: string;\n constructor(value: unknown, type: string) {\n super([\"CAST(\", ` AS ${type})`], [value]);\n this.type = type;\n }\n}\n\n/** A value list bound as ONE array parameter: `= ANY(…)`, `<> ALL(…)`. */\nclass ArrayParameter extends Sql {}\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n\n/**\n * engine-09: a list whose members are each one parameter — bare, or all cast\n * to one type — as one array parameter: PostgreSQL's own array text, typed by\n * the members' cast or, bare, by the compared column, as a list column's\n * parameter is. Any other list keeps a parameter per member.\n */\nfunction arrayParameter(members: readonly Sql[]): ArrayParameter | undefined {\n const first = members[0];\n if (first === undefined) return;\n const type = first instanceof CastParameter ? first.type : undefined;\n const elements: string[] = [];\n for (const member of members) {\n const cast = member instanceof CastParameter ? member : undefined;\n const [head, tail, extra] = member.strings;\n if (\n cast?.type !== type ||\n (!cast && (head !== \"\" || tail !== \"\" || extra !== undefined))\n )\n return;\n const value = member.values[0];\n if (value instanceof Uint8Array)\n elements.push(\n `\\\\x${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`\n );\n else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n )\n elements.push(String(value));\n else return;\n }\n const text = arrayLiteralText(elements);\n return type === undefined\n ? new ArrayParameter([\"\", \"\"], [text])\n : new ArrayParameter([\"CAST(\", ` AS ${type}[])`], [text]);\n}\n\n/**\n * `div`/`mod` rather than `/` and a hand-rolled remainder: both are exact on\n * `numeric` for any operand, including a fractional divisor, and `div`\n * truncates toward zero — which is what the half-even rule's quotient means.\n * `/` on numerics picks its own result scale and would round the last digit.\n */\nconst POSTGRES_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`div(${n}, ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`mod(${n}, ${d})`,\n};\n\n/** The two characters PostgreSQL reads structurally inside a quoted member. */\n\n/**\n * PostgreSQL's own text spelling of one list, for a column whose element type\n * the driver cannot serialize.\n *\n * Every member is quoted, so a member that is empty, spells `NULL`, or holds a\n * brace, comma, quote or backslash is still exactly one member: those are the\n * only characters the server reads structurally, and quoting makes the reading\n * unambiguous without a per-member decision.\n */\n\nconst NON_TEXT_STRING_TYPE =\n /^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\\(|$)/i;\n\nexport class PostgresAdapter implements DatabaseAdapter {\n /**\n * The bound schema. PostgreSQL always qualifies, so this adapter has no\n * unbound mode: an omitted or explicitly `undefined` argument means the\n * `public` schema, whatever a connection's `search_path` says.\n */\n declare readonly namespace: string;\n readonly geoPoint: GeoPointSql | undefined;\n\n constructor(namespace = \"public\", postgis = false) {\n installAdapterNamespace(this, namespace, \"postgresql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace, true);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n containsText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"contains\", value)} ESCAPE '\\\\'`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"startsWith\", value)} ESCAPE '\\\\'`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"endsWith\", value)} ESCAPE '\\\\'`,\n // `ILIKE` folds case as the column's collation does: every letter on a\n // libc or ICU locale, ASCII only on a `C` one. On the bare column, so a\n // trigram index on it serves the filter.\n insensitiveText: (\n kind: TextMatch,\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} ILIKE ${postgresLikePattern(kind, value)} ESCAPE '\\\\'`,\n // PostgreSQL is the one dialect where the escaped LIKE spelling is both\n // exact and index-usable, so it stands alone here: `LIKE` is case- and\n // accent-sensitive natively, which is the contract `startsWithText` holds,\n // and `match_pattern_prefix` extracts `name >= 'x' AND name < 'y'` from the\n // constant-folded pattern even though it arrives as a bound parameter.\n //\n // THE INDEX RANGE HAS A COLLATION PRECONDITION, and the common case does\n // not meet it. Measured, 20k rows, plain btree index:\n // - C-collated database (PGlite, `datcollate = 'C'`): Bitmap Index Scan\n // over 111 rows, where `LEFT(col, LENGTH($1)) = $1` is a Seq Scan over\n // all 20000.\n // - `en_US.utf8` (postgres:16 — the project's own test container, and\n // what a default `initdb` produces): BOTH spellings Seq Scan. Only a\n // `(col text_pattern_ops)` index ranges, and `generateCreateIndex`\n // (src/migrations/drivers/postgres/index.ts) emits no opclass, so\n // viborm cannot create one.\n // What survives on a default-locale cluster — and the reason this spelling\n // still stands there — is the row estimate: `LIKE` tracks the data\n // (202/1010/11111/19998 against truths 111/1111/11111/20000) while\n // `LEFT(...)` is an opaque function estimated at a flat 100 for every\n // prefix width, a 111x error at `name1%` that propagates into the row\n // estimate of any join above it. It is never worse than the spelling it\n // replaced on any measured leg. Full record: Decision 7.3 in\n // docs/architecture/query-performance-plan.md.\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\'`,\n\n // Preserve native equality and indexes; the shared text boundary refuses\n // native types such as XML that cannot express an exact comparison.\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} = ${value}`,\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n this.operators.in(\n this.expressions.caseSensitiveText(column, nativeType, false),\n values\n ),\n\n // Set membership: a bound list (`literals.list`) is an array, read by\n // ANY/ALL; a parenthesized list or a subquery is read by IN.\n in: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} = ANY(${values})`\n : sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} <> ALL(${values})`\n : sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation = false\n ): Sql => {\n const type = nativeTypeFor(nativeType, \"pg\")?.type;\n if (!textOperation && type?.toLowerCase() === \"xml\")\n throw new UnsupportedOperationError(\n \"PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.\",\n { meta: { dialect: \"pg\", scalarType: \"string\" } }\n );\n return textOperation && type && NON_TEXT_STRING_TYPE.test(type)\n ? sql`CAST(${expr} AS TEXT)`\n : expr;\n },\n caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration): Sql =>\n sql`LOWER(${this.expressions.caseSensitiveText(expr, nativeType, true)})`,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // PostgreSQL integer division already truncates toward zero, which is why\n // `set.divide` ignores `target.integer` here as well. Casting either side\n // would narrow a `bigint` operand to `int4`.\n integerDivide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`decode(${expr}, 'hex')`\n : sql`CAST(${expr} AS ${sql.raw(\n representation === \"uuid\" ? \"UUID\" : \"TEXT\"\n )})`,\n\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"BIGINT\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`encode(${expr}, 'hex')`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'Infinity'::float8\"),\n\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_AND(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_OR(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(POSTGRES_INTEGERS, column, descriptor),\n\n // `sum(numeric)` is itself unbounded on PostgreSQL; 1000 is the widest\n // `NUMERIC(p,s)` an operand can be CAST into to meet it, which is the\n // domain a comparison against that sum is actually limited by.\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(1000),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql =>\n sql`(${left})::jsonb = (${right})::jsonb`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n number: (expression: Sql): Sql => expression,\n\n object: postgresJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'[]'::json`;\n return sql`json_build_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`'[]'::json`,\n\n agg: (expr: Sql): Sql => sql`COALESCE(json_agg(${expr}), '[]'::json)`,\n\n objectFromColumns: postgresJsonObject,\n\n // #>/#>> with a text[] param handles every path shape uniformly:\n // '{}' returns the document root, and integer segments address array\n // elements (a single-segment `-> '0'` would only match an object key)\n extract: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>${path}::text[]`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>>${path}::text[]`,\n\n // jsonb_typeof gates the cast: a non-number (or an absent path, where\n // jsonb_typeof is NULL) short-circuits to NULL instead of raising\n // \"invalid input syntax for type double precision\"\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'number' THEN ((${column})::jsonb#>>${path}::text[])::double precision END)`,\n\n // COLLATE \"C\" pins byte (= code point) ordering; the database's default\n // collation (en_US.UTF-8 and friends) orders 'a' before 'B', which would\n // make < / > disagree with MySQL and SQLite\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`(${this.json.foldableStringAtPath(column, path)} COLLATE \"C\")`,\n foldableStringAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'string' THEN (${column})::jsonb#>>${path}::text[] END)`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(${target})::jsonb @> ${value}`,\n\n lastElement: (target: Sql): Sql => sql`(${target})::jsonb -> -1`,\n\n // Serialized JSON text, same format literals.json writes — PG casts the\n // param to jsonb from the comparison context\n value: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'{}'`;\n return sql`ARRAY[${sql.join(items, \", \")}]`;\n },\n\n // Native array parameter; drivers serialize JS arrays to PG array format\n value: (values: unknown[], temporal?: \"date\" | \"datetime\"): Sql =>\n sql`${temporal ? values.map((value) => (typeof value === \"string\" ? encodePostgresTemporal(value) : value)) : values}`,\n\n // One untyped parameter holding PostgreSQL's own array literal. A managed\n // enum's array OID is created by the estate, so no driver has a serializer\n // for it and the native parameter above arrives malformed; an unknown\n // parameter instead takes its type from the column or operand it meets,\n // which is how the enum type is reached without naming it here.\n enumValue: (values: unknown[]): Sql => sql`${arrayLiteralText(values)}`,\n\n ofRows: (query: Sql): Sql => sql`ARRAY(${query})`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n const selectClause = parts.distinct\n ? sql`SELECT DISTINCT ON (${parts.distinct}) ${parts.columns}`\n : sql`SELECT ${parts.columns}`;\n\n return assembleSelectQuery(selectClause, parts, { forUpdate: \"append\" });\n },\n };\n\n cte = createCteBuilders(quoteIdent, {\n inlining: sql.raw(\"NOT MATERIALIZED\"),\n });\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n // An inserted row version has no deleting transaction yet; the row an\n // ON CONFLICT update rewrote carries the updating one.\n upserted: sql.raw(\"(xmax = 0)\"),\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n // The refusal names its sentinel (22P02, `invalid input syntax for type\n // integer: \"__viborm_refused__\"`), which no caller's division by zero\n // does; the text is a sublink, which PostgreSQL does not fold while\n // planning, so it is evaluated only where it is reached.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS \"__viborm_judged__\"${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n /**\n * The produced rows as a `VALUES` list: PostgreSQL parses each `UNION ALL`\n * arm one recursion deeper (`54001`, stack depth, at 8,000 rows on 16.14),\n * and a list is no deeper for its length. A `VALUES` column is typed by its\n * own rows, an unknown parameter as `text`, so the first row takes each\n * column's type from a NULL of the table's row type (`COALESCE`, the rule\n * a `UNION` arm met), beside the list, as a one-row FROM item. The NULL is\n * cast to the table's type, never read as `SELECT \"qN\" FROM table AS \"qN\"`:\n * there a column named `qN` would win over the whole-row reference (42809),\n * and the cast reads no relation at all.\n */\n setOperations = createSetOperations(quoteIdent, (typed, rows, alias) => {\n const name = sql.raw(quoteIdent(typed.alias));\n const column = (field: string) => sql.raw(quoteIdent(field));\n const [first, ...rest] = rows;\n const typedFirst = first!.map(\n (value, index) =>\n sql`COALESCE(${value}, (${name}.\"row\").${column(typed.columns[index]!)})`\n );\n return sql`(SELECT NULL::${typed.table} AS \"row\") AS ${name} CROSS JOIN LATERAL (VALUES ${sql.join(\n [typedFirst, ...rest].map(rowValues),\n \", \"\n )}) AS ${sql.raw(quoteIdent(alias))}(${sql.join(typed.columns.map(column), \", \")})`;\n });\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n joinsJunctionFilters: \"unbounded\",\n readsNodesByKey: true,\n };\n\n lastInsertId = (): Sql => sql.raw`lastval()`;\n\n readonly #cteBatchRefs = createOnConflictBatchRefs({\n table: sql.raw`\"__viborm_batch_refs\"`,\n batchIdColumn: sql.raw`\"batch_id\"`,\n keyColumn: sql.raw`\"ref_key\"`,\n valueColumn: sql.raw`\"ref_value\"`,\n // The table is not ON COMMIT DROP, so it survives the native batch that\n // created it (D-50); the scratch itself belongs to the dispatched batch —\n // each batch stores its own reference rows, reads back what it stored at\n // its own end and deletes them there (D-58), so a later batch never names\n // a reference an earlier one stored. The table lingers on the session like\n // the SQLite and MySQL scratch tables do.\n createTable: sql.raw`CREATE TEMP TABLE IF NOT EXISTS \"__viborm_batch_refs\" (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n // The exact identity of an INSERT, carried by the statement that runs it:\n // the INSERT is the data-modifying CTE, its RETURNING feeds the reference\n // row, and nothing session-global (lastval) is read.\n storeReturning: (batchId, key, insert, column) =>\n sql`WITH \"__viborm_inserted\" AS (${insert} RETURNING ${column}) INSERT INTO \"__viborm_batch_refs\" (\"batch_id\", \"ref_key\", \"ref_value\") SELECT ${batchId}, ${key}, CAST(${column} AS TEXT) FROM \"__viborm_inserted\"`,\n });\n\n // Whether this provider can mutate inside a CTE is the capability's fact,\n // read live: the CTE store and the key store it derives are offered only\n // while `capabilities.supportsCteWithMutations` holds, and a PostgreSQL\n // without it offers no exact key store at all (lastval() is not exact).\n readonly #batchRefs: BatchReferenceSqlAdapter = (() => {\n const withCte = this.#cteBatchRefs;\n const capabilities = this.capabilities;\n return {\n setup: withCte.setup,\n cleanup: withCte.cleanup,\n store: withCte.store,\n read: withCte.read,\n get storeReturning() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeReturning\n : undefined;\n },\n get storeInsertedKey() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeInsertedKey\n : undefined;\n },\n };\n })();\n\n vector = {\n literal: (values: number[]): Sql => {\n if (values.some((value) => !Number.isFinite(Math.fround(value))))\n throw new QueryError(\n \"PostgreSQL vector components must fit a finite float32 value.\",\n { code: VibORMErrorCode.INVALID_INPUT }\n );\n return sql`${`[${values.join(\",\")}]`}::vector`;\n },\n\n l2: (column: Sql, vector: Sql): Sql => sql`${column} <-> ${vector}`,\n\n cosine: (column: Sql, vector: Sql): Sql =>\n sql`NULLIF(${column} <=> ${vector}, 'NaN'::double precision)`,\n };\n\n #createGeoPointSql(): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point}::geometry)`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point}::geometry)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_SetSRID(ST_MakePoint(${pointLongitude}, ${pointLatitude}), 4326)::geography`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`${point} && ST_SetSRID(ST_GeomFromGeoJSON(${polygon}), 4326)::geography`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_SetSRID(ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}), 4326)::geography`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}::geometry))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}::geometry))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}::geometry))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}::geometry))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // PostgreSQL's LEAST/GREATEST ignore NULL operands. The explicit arm is\n // what keeps a nullable source point's distance NULL rather than zero.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n }\n\n result: DatabaseAdapter[\"result\"] = {\n // PostgreSQL returns native JS scalars and parseField below is a pure\n // passthrough, so the result parser may take the identity fast path for\n // plain string/int/number/boolean columns (byte-identical, guarded).\n nativeScalarPassthrough: true,\n\n // A managed enum's array OID is in no driver's result-type table, so an\n // enum LIST comes back as the array's own text rather than a JS array.\n enumListRepresentation: \"arrayText\",\n\n // The one physical promise an identifier column makes, derived from the\n // ONE storage owner so the column the migration creates, the parameter the\n // write binds and the value this reads back cannot be three decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"pg\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing. This leg used to offer\n // `convertBigIntToNumber(raw)`, but `Queries.decodeResult` hands it the\n // operation's ROW ARRAY, which is never a bigint, and an integer's width\n // is a VALUE's fact that the engine's `int` codec owns - it turns a bigint\n // or an integer text into a number and refuses one outside the safe range\n // (`raptor3/shared/query.ts`). Measured on live PostgreSQL over seven\n // operations and both routes, on `pg` and on `postgres.js`: 40 asks, 40\n // `undefined` (Arnaud's D-40, `g4/rulings/o2/receipts/leg-probe-pg.log`\n // and `leg-probe-postgresjs-2.log`), with `COUNT(*)` arriving as the text\n // `\"2\"` on both transports.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL returns native JSON objects - passthrough\n return next();\n },\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL has native types - passthrough\n return next();\n },\n };\n}\n"],"mappings":"0gCA+BA,IAAa,EAAb,MAAa,aAAc,CAEzB,KAEA,YAAoB,EAAc,CAChC,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CASrB,OAAO,KAAK,EAA2C,CAGrD,IAAM,EAA2B,KAAK,UAAU,EAAM,CACtD,OAAO,IAAS,IAAA,GAAY,IAAA,GAAY,IAAI,cAAc,EAAK,CAGjE,UAAmB,CACjB,OAAO,KAAK,KAGd,QAAkB,CAChB,OAAO,KAAK,MAAM,KAAK,KAAK,GCwBhC,MAAM,EAAa,EAAuB,IAAI,CAM9C,SAAS,oBAAoB,EAAiB,EAAiB,CAC7D,IAAM,EAAO,IAAS,aAAe,GAAK,IACpC,EAAO,IAAS,WAAa,GAAK,IAClC,CAAC,EAAS,GAAS,EAAM,OAO/B,OALE,EAAM,QAAQ,KAAK,GAAG,GAAK,IAC3B,OAAO,GAAY,UACnB,IAAU,IAAA,GAEH,CAAG,GAAG,EAAO,EAAkB,EAAQ,CAAG,IAC5C,CAAG,IAAIA,EAAI,IAAI,GAAQ,UAAU,CAAC,+BAA+B,EAAM,qFAAqFA,EAAI,IAAI,GAAQ,UAAU,CAAC,GAEhM,SAAS,mBAAmB,EAA6B,CACvD,GAAI,EAAM,SAAW,EAAG,MAAO,GAAI,GAAG,aACtC,IAAM,EAAgB,EAAE,CAClB,EAAcA,EAAI,IACtB,EAAM,OAAS,GAAK,qBAAuB,oBAC5C,CAGD,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,GAAI,CACrD,IAAM,EAAO,EACV,MAAM,EAAO,EAAQ,GAAG,CACxB,SAAS,CAAC,EAAK,KAAW,CAAC,CAAG,GAAG,EAAI,QAAS,EAAM,CAAC,CACxD,EAAO,KAAK,CAAG,G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