viborm 1.3.3 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/dist/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
  2. package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
  3. package/dist/{adapter-namespace-CWLEmon2.mjs → adapter-namespace-BLejG8FA.mjs} +1 -1
  4. package/dist/{adapter-namespace-CWLEmon2.mjs.map → adapter-namespace-BLejG8FA.mjs.map} +1 -1
  5. package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
  6. package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
  7. package/dist/adapters.d.mts +1 -1
  8. package/dist/adapters.mjs +1 -1
  9. package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  10. package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  11. package/dist/{batch-refs-DGJPz8-G.mjs → batch-refs-BYCu1JnQ.mjs} +1 -1
  12. package/dist/{batch-refs-DGJPz8-G.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
  13. package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
  14. package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
  15. package/dist/builder-BS8EW4BQ.mjs +2 -0
  16. package/dist/builder-BS8EW4BQ.mjs.map +1 -0
  17. package/dist/bun-sql.d.mts +3 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sql.mjs.map +1 -1
  20. package/dist/bun-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/cache/cloudflare-kv.d.mts +1 -1
  23. package/dist/cache/cloudflare-kv.mjs +1 -1
  24. package/dist/cache/memory.d.mts +1 -1
  25. package/dist/cache/memory.mjs +1 -1
  26. package/dist/cache.d.mts +1 -1
  27. package/dist/cache.mjs +1 -1
  28. package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
  29. package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
  30. package/dist/chain-D5J9hIw-.mjs +2 -0
  31. package/dist/chain-D5J9hIw-.mjs.map +1 -0
  32. package/dist/cli.mjs +1 -1
  33. package/dist/client-Bhl2mWam.mjs +2 -0
  34. package/dist/client-Bhl2mWam.mjs.map +1 -0
  35. package/dist/{client-DR0vYetv.d.mts → client-BzgBm_86.d.mts} +3 -1
  36. package/dist/{client-DjtWangN.mjs → client-aU3YhZ6G.mjs} +16 -16
  37. package/dist/client-aU3YhZ6G.mjs.map +1 -0
  38. package/dist/client.d.mts +1 -1
  39. package/dist/client.mjs +1 -1
  40. package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
  41. package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
  42. package/dist/config.d.mts +1 -1
  43. package/dist/config.mjs +1 -1
  44. package/dist/d1.d.mts +1 -1
  45. package/dist/d1.mjs +1 -1
  46. package/dist/d1.mjs.map +1 -1
  47. package/dist/{datetime-physical-codec-qKxFtI3B.mjs → datetime-physical-codec-lX7IJBlz.mjs} +1 -1
  48. package/dist/{datetime-physical-codec-qKxFtI3B.mjs.map → datetime-physical-codec-lX7IJBlz.mjs.map} +1 -1
  49. package/dist/driver-CQQbCQh9.mjs +2 -0
  50. package/dist/{driver-Bzc0GCQ4.mjs.map → driver-CQQbCQh9.mjs.map} +1 -1
  51. package/dist/{driver-BvP7eW0A.mjs → driver-u2qJicrE.mjs} +2 -2
  52. package/dist/{driver-BvP7eW0A.mjs.map → driver-u2qJicrE.mjs.map} +1 -1
  53. package/dist/driver.d.mts +1 -1
  54. package/dist/driver.mjs +1 -1
  55. package/dist/error-mapping-6op318w6.mjs.map +1 -1
  56. package/dist/every-CzF00eDV.mjs +2 -0
  57. package/dist/{every-WUr3mlvg.mjs.map → every-CzF00eDV.mjs.map} +1 -1
  58. package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
  59. package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.mjs.map} +1 -1
  60. package/dist/{identifier-conversion-Bs7A2GGU.mjs → identifier-conversion-Dc0Rf4Gi.mjs} +2 -2
  61. package/dist/{identifier-conversion-Bs7A2GGU.mjs.map → identifier-conversion-Dc0Rf4Gi.mjs.map} +1 -1
  62. package/dist/identity-CmRos0Yf.mjs +2 -0
  63. package/dist/identity-CmRos0Yf.mjs.map +1 -0
  64. package/dist/{index-B_jh2oaQ.d.mts → index-B4IWFJfv.d.mts} +1282 -1053
  65. package/dist/index.d.mts +1 -1
  66. package/dist/index.mjs +1 -1
  67. package/dist/instrumentation.d.mts +1 -1
  68. package/dist/instrumentation.mjs +1 -1
  69. package/dist/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
  70. package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
  71. package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
  72. package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  73. package/dist/{libsql-C8dn4id0.mjs → libsql-CrDXsfpL.mjs} +2 -2
  74. package/dist/{libsql-C8dn4id0.mjs.map → libsql-CrDXsfpL.mjs.map} +1 -1
  75. package/dist/libsql.d.mts +1 -1
  76. package/dist/libsql.mjs +1 -1
  77. package/dist/libsql.mjs.map +1 -1
  78. package/dist/{memory-B7CcHS6I.mjs → memory-TXO4KgBy.mjs} +2 -2
  79. package/dist/{memory-B7CcHS6I.mjs.map → memory-TXO4KgBy.mjs.map} +1 -1
  80. package/dist/migrations/mysql.d.mts +4 -4
  81. package/dist/migrations/mysql.mjs +1 -1
  82. package/dist/migrations/postgres.d.mts +4 -4
  83. package/dist/migrations/postgres.mjs +1 -1
  84. package/dist/migrations/sqlite.d.mts +4 -4
  85. package/dist/migrations/sqlite.mjs +1 -1
  86. package/dist/migrations/storage/durable-object.mjs +1 -1
  87. package/dist/migrations/storage/fs.mjs +1 -1
  88. package/dist/migrations/storage/r2.mjs +1 -1
  89. package/dist/migrations/tenant.d.mts +2 -2
  90. package/dist/migrations/tenant.mjs +1 -1
  91. package/dist/migrations.d.mts +4 -4
  92. package/dist/migrations.mjs +1 -1
  93. package/dist/{mysql-mUmhH9Cf.mjs → mysql-C2vOPcuA.mjs} +2 -2
  94. package/dist/{mysql-mUmhH9Cf.mjs.map → mysql-C2vOPcuA.mjs.map} +1 -1
  95. package/dist/mysql-adapter-C5CMIYRS.mjs +2 -0
  96. package/dist/{mysql-adapter-ABpgFB2N.mjs.map → mysql-adapter-C5CMIYRS.mjs.map} +1 -1
  97. package/dist/mysql2.d.mts +1 -1
  98. package/dist/mysql2.mjs +1 -1
  99. package/dist/mysql2.mjs.map +1 -1
  100. package/dist/neon-http.d.mts +3 -1
  101. package/dist/neon-http.mjs +1 -1
  102. package/dist/neon-http.mjs.map +1 -1
  103. package/dist/normalized-result-BF7gr4_b.mjs +2 -0
  104. package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
  105. package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
  106. package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
  107. package/dist/{object-store-Ds9NKRU6.d.mts → object-store-uRqi0URP.d.mts} +3 -3
  108. package/dist/permissions.d.mts +1 -1
  109. package/dist/pg.d.mts +26 -1
  110. package/dist/pg.mjs +1 -1
  111. package/dist/pg.mjs.map +1 -1
  112. package/dist/pglite.d.mts +3 -1
  113. package/dist/pglite.mjs +1 -1
  114. package/dist/pglite.mjs.map +1 -1
  115. package/dist/{pinned-session-C79aDzOg.mjs → pinned-session-FYOFV_gB.mjs} +2 -2
  116. package/dist/{pinned-session-C79aDzOg.mjs.map → pinned-session-FYOFV_gB.mjs.map} +1 -1
  117. package/dist/planetscale.d.mts +1 -1
  118. package/dist/planetscale.mjs +1 -1
  119. package/dist/planetscale.mjs.map +1 -1
  120. package/dist/{planner-DHZG9Vy7.d.mts → planner-SzkGh-3T.d.mts} +1 -1
  121. package/dist/{postgres-BACQ_wqF.mjs → postgres-BSmy1PYR.mjs} +2 -2
  122. package/dist/{postgres-BACQ_wqF.mjs.map → postgres-BSmy1PYR.mjs.map} +1 -1
  123. package/dist/postgres-adapter-B1RyJlWL.mjs +2 -0
  124. package/dist/{postgres-adapter-DaMvNOkx.mjs.map → postgres-adapter-B1RyJlWL.mjs.map} +1 -1
  125. package/dist/postgres-adapter-BAqRfWl1.mjs +2 -0
  126. package/dist/postgres-adapter-BAqRfWl1.mjs.map +1 -0
  127. package/dist/postgres-result-BCUQf8b_.mjs +2 -0
  128. package/dist/{postgres-result-D403cLyA.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
  129. package/dist/postgres.d.mts +3 -1
  130. package/dist/postgres.mjs +1 -1
  131. package/dist/postgres.mjs.map +1 -1
  132. package/dist/{provider-limits-DSv2tYFr.mjs → provider-limits-V09frtmK.mjs} +1 -1
  133. package/dist/{provider-limits-DSv2tYFr.mjs.map → provider-limits-V09frtmK.mjs.map} +1 -1
  134. package/dist/relation-bound-BrZLsSke.mjs +2 -0
  135. package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
  136. package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
  137. package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
  138. package/dist/result-shape-Fi1-Fvri.mjs +2 -0
  139. package/dist/result-shape-Fi1-Fvri.mjs.map +1 -0
  140. package/dist/{rows-v1VuwOTa.mjs → rows-BiaiswSV.mjs} +2 -2
  141. package/dist/{rows-v1VuwOTa.mjs.map → rows-BiaiswSV.mjs.map} +1 -1
  142. package/dist/schema/json.d.mts +1 -1
  143. package/dist/{schema-introspection-TdJrSaKd.mjs → schema-introspection-C1-XrQP4.mjs} +2 -2
  144. package/dist/{schema-introspection-TdJrSaKd.mjs.map → schema-introspection-C1-XrQP4.mjs.map} +1 -1
  145. package/dist/{schema-D3-ScVH6.mjs → schema-tGtziyCJ.mjs} +1 -1
  146. package/dist/{schema-D3-ScVH6.mjs.map → schema-tGtziyCJ.mjs.map} +1 -1
  147. package/dist/schema.d.mts +1 -1
  148. package/dist/schema.mjs +1 -1
  149. package/dist/select-assembly-BjT_fDbu.mjs +2 -0
  150. package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
  151. package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
  152. package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
  153. package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
  154. package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
  155. package/dist/soft-delete.d.mts +3 -3
  156. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
  157. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
  158. package/dist/sqlite-adapter-CoDeF2h2.mjs +2 -0
  159. package/dist/sqlite-adapter-CoDeF2h2.mjs.map +1 -0
  160. package/dist/{sqlite-utils-BvSlEs5W.mjs → sqlite-utils-C0TyzOys.mjs} +2 -2
  161. package/dist/{sqlite-utils-BvSlEs5W.mjs.map → sqlite-utils-C0TyzOys.mjs.map} +1 -1
  162. package/dist/sqlite3.d.mts +1 -1
  163. package/dist/sqlite3.mjs +1 -1
  164. package/dist/sqlite3.mjs.map +1 -1
  165. package/dist/{standard-sql-CYdZ_KXH.mjs → standard-sql-DmKF8msN.mjs} +2 -2
  166. package/dist/{standard-sql-CYdZ_KXH.mjs.map → standard-sql-DmKF8msN.mjs.map} +1 -1
  167. package/dist/transaction-operation-CU1zlxiG.mjs.map +1 -1
  168. package/dist/{utils-Qr8ug94X.mjs → utils-DkAxKcDD.mjs} +1 -1
  169. package/dist/{utils-Qr8ug94X.mjs.map → utils-DkAxKcDD.mjs.map} +1 -1
  170. package/dist/{validation-CPnrLcjW.mjs → validation-C7Z6wTJa.mjs} +1 -1
  171. package/dist/{validation-CPnrLcjW.mjs.map → validation-C7Z6wTJa.mjs.map} +1 -1
  172. package/dist/validation.d.mts +1 -1
  173. package/dist/validation.mjs +1 -1
  174. package/dist/version-n393hhwM.mjs +2 -0
  175. package/dist/{version-0RVYpih5.mjs.map → version-n393hhwM.mjs.map} +1 -1
  176. package/package.json +14 -14
  177. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs +0 -2
  178. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs.map +0 -1
  179. package/dist/builder-D6Ug-zjM.mjs +0 -2
  180. package/dist/builder-D6Ug-zjM.mjs.map +0 -1
  181. package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
  182. package/dist/chain-B5IbqLGi.mjs +0 -2
  183. package/dist/chain-B5IbqLGi.mjs.map +0 -1
  184. package/dist/client-BmcHzDBa.mjs +0 -2
  185. package/dist/client-BmcHzDBa.mjs.map +0 -1
  186. package/dist/client-DjtWangN.mjs.map +0 -1
  187. package/dist/driver-Bzc0GCQ4.mjs +0 -2
  188. package/dist/every-WUr3mlvg.mjs +0 -2
  189. package/dist/identity-Bj2EN6Ss.mjs +0 -2
  190. package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
  191. package/dist/mysql-adapter-ABpgFB2N.mjs +0 -2
  192. package/dist/postgres-adapter-Ci07rgh_.mjs +0 -2
  193. package/dist/postgres-adapter-Ci07rgh_.mjs.map +0 -1
  194. package/dist/postgres-adapter-DaMvNOkx.mjs +0 -2
  195. package/dist/postgres-result-D403cLyA.mjs +0 -2
  196. package/dist/result-shape-BKydBCsR.mjs +0 -2
  197. package/dist/result-shape-BKydBCsR.mjs.map +0 -1
  198. package/dist/select-assembly-uZfvbYjz.mjs +0 -2
  199. package/dist/select-assembly-uZfvbYjz.mjs.map +0 -1
  200. package/dist/sqlite-adapter-DPc9T6Lh.mjs +0 -2
  201. package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +0 -1
  202. package/dist/version-0RVYpih5.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"neon-http.mjs","names":[],"sources":["../src/drivers/neon-http/index.ts"],"sourcesContent":["/**\n * Neon HTTP Driver\n *\n * Driver implementation for @neondatabase/serverless - Neon's HTTP-based PostgreSQL driver.\n *\n * Note: Neon's HTTP API uses non-interactive transactions. This means:\n * - Batch transactions ($transaction([...])) work via executeBatch\n * - Callback transactions ($transaction(async (tx) => {...})) are NOT supported\n * because Neon HTTP requires all queries to be submitted at once\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, QueryError } from \"@errors\";\nimport type {\n CustomTypesConfig,\n NeonQueryFunction,\n} from \"@neondatabase/serverless\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { isNormalizedResultRow } from \"../normalized-result\";\nimport {\n type BatchTransactionOptions,\n normalizePostgresRowCount,\n resolveNamespaceOption,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface NeonHTTPDriverOptions {\n databaseUrl?: string;\n options?: {\n fetchOptions?: RequestInit;\n authToken?: string | (() => Promise<string> | string);\n };\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\nconst NEON_HTTP_CONFIG_KEYS: Record<keyof NeonHTTPDriverOptions, true> = {\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n namespace: true,\n};\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n installPostgresAdapter(this, namespace, options);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"neon-http\", NEON_HTTP_CONFIG_KEYS);\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"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ACF,CAGD,GAFA,MAAM,KAAa,CAEf,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAQ,OAAQ,CAChE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,oBACJ,EACA,YAAY,EAAQ,OAAO,kCAAkC,IAC9D,CAGH,OAAO,EAAQ,KAAK,EAAQ,IAC1B,KAAK,YAAe,EAAQ,EAAQ,IAAQ,SAAW,EAAa,CACrE,CAMH,YACE,EACA,EACgB,CAChB,IAAM,EAAY,EAAQ,WAAa,UAEvC,OADA,qBAAwB,EAAQ,EAAQ,CACjC,CACL,KAAM,EAAO,KACb,SAAU,EACR,EAAO,SACP,EAAO,QACP,EAAO,KACP,CACE,SAAU,YACV,YACA,MAAO,EAAQ,MACf,cAAe,EAAQ,cACxB,CACF,CACF,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,YAAa,EAAsB,CACzE,GAAM,CAAE,cAAa,UAAS,WAAU,WAAY,EAC9C,EAAY,EAAuB,EAAO,CAWhD,OAAO,EAAmD,EAT3C,IAAI,eAAe,CAChC,cACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,YACD,CAAC,CAEuE"}
1
+ {"version":3,"file":"neon-http.mjs","names":[],"sources":["../src/drivers/neon-http/index.ts"],"sourcesContent":["/**\n * Neon HTTP Driver\n *\n * Driver implementation for @neondatabase/serverless - Neon's HTTP-based PostgreSQL driver.\n *\n * Note: Neon's HTTP API uses non-interactive transactions. This means:\n * - Batch transactions ($transaction([...])) work via executeBatch\n * - Callback transactions ($transaction(async (tx) => {...})) are NOT supported\n * because Neon HTTP requires all queries to be submitted at once\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, QueryError } from \"@errors\";\nimport type {\n CustomTypesConfig,\n NeonQueryFunction,\n} from \"@neondatabase/serverless\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { isNormalizedResultRow } from \"../normalized-result\";\nimport {\n type BatchTransactionOptions,\n normalizePostgresRowCount,\n resolveNamespaceOption,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface NeonHTTPDriverOptions {\n databaseUrl?: string;\n options?: {\n fetchOptions?: RequestInit;\n authToken?: string | (() => Promise<string> | string);\n };\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\nconst NEON_HTTP_CONFIG_KEYS: Record<keyof NeonHTTPDriverOptions, true> = {\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n namespace: true,\n};\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n installPostgresAdapter(this, namespace, options);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"neon-http\", NEON_HTTP_CONFIG_KEYS);\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"6YAiEA,MAAM,EAAmE,CACvE,YAAa,GACb,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,UAAW,GACZ,CAoBD,SAAS,oBACP,EACA,EACY,CACZ,IAAM,EAAY,EAAQ,WAAa,UACvC,OAAO,IAAI,EACT,yEAAyE,EAAU,KAAK,EAAO,GAC/F,CAAE,KAAM,CAAE,OAAQ,YAAa,GAAG,EAAS,YAAW,CAAE,CACzD,CAGH,SAAS,qBACP,EACA,EACqC,CACrC,GACE,EAAE,EAAsB,EAAO,EAAI,MAAM,QAAQ,EAAO,OAAO,GAC/D,OAAO,EAAO,SAAY,UAC1B,CAAC,OAAO,OAAO,EAAQ,WAAW,EACjC,EAAO,WAAa,OAClB,OAAO,EAAO,UAAa,UAC1B,CAAC,OAAO,SAAS,EAAO,SAAS,EACjC,CAAC,OAAO,cAAc,EAAO,SAAS,EACt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AOC,CACD,EAA8B,EAAQ,YAAa,EAAsB,CACzE,GAAM,CAAE,cAAa,UAAS,WAAU,WAAY,EAC9C,EAAY,EAAuB,EAAO,CAYhD,OAAO,EAAmD,EAV3C,IAAI,eAAe,CAChC,cACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACD,CAAC,CAEuE"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./value-guards-CK9guf2Z.mjs";import{n}from"./base-D3m1S7Uc.mjs";import{p as r}from"./validation-gwZYm3Yn.mjs";import{t as i}from"./sql-BvHwL73I.mjs";const a=typeof Symbol.asyncDispose==`symbol`?Symbol.asyncDispose:void 0,o=Symbol(`viborm.verbatimBatchQuery`);function markVerbatimBatchQuery(e){return Object.defineProperty(e,o,{configurable:!1,enumerable:!1,value:!0,writable:!1}),e}function isVerbatimBatchQuery(e){return Reflect.get(e,o)===!0}const s=new WeakMap;function registerPreparedStatement(e,t){s.set(e,t)}function transferPreparedStatement(e,t){let n=s.get(e);return n!==void 0&&s.set(t,n),t}function snapshotPreparedStatement(e,t,n){let r=s.get(e);return r!==void 0&&s.set(t,new i([...r.strings],[...n])),t}function readPreparedStatement(e){return s.get(e)}const c=/^(?:0|[1-9]\d*)$/;function captureBuiltinPrototype(e){let t=[];for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&t.push({descriptor:r,key:n})}return Object.freeze(t)}const l=captureBuiltinPrototype(Object.prototype),u=captureBuiltinPrototype(Array.prototype);function isArrayIndex(e){if(typeof e!=`string`||!c.test(e))return!1;let t=Number(e);return t<=4294967294&&String(t)===e}function functionSource(e){if(typeof e==`function`)try{return Function.prototype.toString.call(e)}catch{return}}function sameInertRecord(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return Object.is(e,t);try{if(Object.getPrototypeOf(e)!==null||Object.getPrototypeOf(t)!==null)return!1;let n=Reflect.ownKeys(e),r=Reflect.ownKeys(t);if(n.length!==r.length)return!1;for(let i=0;i<r.length;i+=1){let a=n[i],o=r[i];if(a!==o||o===void 0)return!1;let s=Object.getOwnPropertyDescriptor(e,o),c=Object.getOwnPropertyDescriptor(t,o);if(s===void 0||c===void 0||!(`value`in s)||!(`value`in c)||s.configurable!==c.configurable||s.enumerable!==c.enumerable||s.writable!==c.writable||!Object.is(s.value,c.value))return!1}return!0}catch{return!1}}function sameBuiltinDescriptor(e,t){if(e.configurable!==t.configurable||e.enumerable!==t.enumerable||`value`in e!=`value`in t)return!1;if(`value`in e&&`value`in t){if(e.writable!==t.writable)return!1;let n=functionSource(t.value);return n===void 0?sameInertRecord(e.value,t.value):functionSource(e.value)===n}return functionSource(e.get)===functionSource(t.get)&&functionSource(e.set)===functionSource(t.set)}function hasBuiltinPrototypeShape(e,t){try{let n=Reflect.ownKeys(e);if(n.length!==t.length)return!1;for(let r=0;r<t.length;r+=1){let i=t[r];if(i===void 0||n[r]!==i.key)return!1;let a=Object.getOwnPropertyDescriptor(e,i.key);if(a===void 0||!sameBuiltinDescriptor(a,i.descriptor))return!1}return!0}catch{return!1}}function isObjectPrototype(e){try{return Object.getPrototypeOf(e)===null&&hasBuiltinPrototypeShape(e,l)}catch{return!1}}function isArrayPrototype(e){try{let t=Object.getPrototypeOf(e);return t!==null&&isObjectPrototype(t)&&hasBuiltinPrototypeShape(e,u)}catch{return!1}}function rawParameterNodeShape(e){let t=!1;try{t=Array.isArray(e);let n=Object.getPrototypeOf(e);if(t&&n!==null&&!isArrayPrototype(n)||!t&&n!==null&&!isObjectPrototype(n))return{kind:t?`unsupported-array`:`opaque`};let r=[],i=[];for(let n of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,n);if(a!==void 0&&(i.push({descriptor:a,key:n}),t?isArrayIndex(n):a.enumerable&&typeof n==`string`)){if(!(`value`in a))return{kind:t?`unsupported-array`:`opaque`};r.push({descriptor:a,key:n,value:a.value})}}let a=i.find(e=>e.key===`toJSON`);return a&&(!(`value`in a.descriptor)||typeof a.descriptor.value==`function`)?{kind:t?`unsupported-array`:`opaque`}:{kind:`node`,shape:{edges:r,isArray:t,properties:i,prototype:n}}}catch{return{kind:t?`unsupported-array`:`opaque`}}}function rawDateTime(e,n,r){if(!t(e))return;let i=Date.prototype.getTime.call(e);if(Number.isNaN(i))throw r(n);return i}function analyzeRawParameterGraph(e,t){let n=new WeakMap,r=new WeakMap,i=[],a=Array(e.length),discover=(e,a)=>{let o=rawDateTime(e,a,t.invalidDate);if(o!==void 0&&typeof e==`object`&&e){r.set(e,o);return}if(typeof e!=`object`||!e)return;let s=n.get(e);if(s)return s;let c=rawParameterNodeShape(e);if(c.kind===`unsupported-array`)throw t.unsupportedArray(a);if(c.kind===`opaque`)return;let l={...c.shape,source:e};return n.set(e,l),i.push(l),l};for(let n=0;n<e.length;n++){if(!Object.hasOwn(e,n))continue;let o=e[n];a[n]=o;let s=rawDateTime(o,n,t.invalidDate);if(s!==void 0&&typeof o==`object`&&o){r.set(o,s);continue}let c=discover(o,n);if(!c)continue;let l=[c],u=0;for(;u<l.length;){let e=l[u];if(u+=1,e)for(let t of e.edges){let e=i.length,r=discover(t.value,n);r&&i.length>e&&l.push(r)}}}return{dateTimes:r,nodes:i,roots:a}}function validateRawParameters(e,t){analyzeRawParameterGraph(e,t)}function snapshotRawParameterGraph(e,t){let n=analyzeRawParameterGraph(e,t),r=new WeakMap,i=new WeakMap;for(let e of n.nodes){let t=e.isArray?[]:{};e.prototype===null&&Object.setPrototypeOf(t,null),r.set(e.source,t)}let copiedValue=e=>{if(typeof e!=`object`||!e)return e;let t=n.dateTimes.get(e);if(t!==void 0){let n=i.get(e);if(n)return n;let r=new Date(t);return i.set(e,r),r}return r.get(e)??e};for(let e of n.nodes){let t=r.get(e.source);if(t){for(let n of e.properties){if(e.isArray&&n.key===`length`)continue;let r=n.descriptor;Object.defineProperty(t,n.key,`value`in r&&(e.isArray?isArrayIndex(n.key):r.enumerable&&typeof n.key==`string`)?{...r,value:copiedValue(r.value)}:r)}if(e.isArray){let n=e.properties.find(e=>e.key===`length`);n&&Object.defineProperty(t,`length`,n.descriptor)}}}let a=Array(n.roots.length);for(let e=0;e<n.roots.length;e++)Object.hasOwn(n.roots,e)&&(a[e]=copiedValue(n.roots[e]));return a}function invalidProviderDateError(e,t){return new r(`Operation "${e.operation??`statement`}" received an invalid Date as bound parameter ${t}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,{code:n.INVALID_INPUT,meta:{parameterIndex:t,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function unsupportedProviderArrayError(e,t){return new r(`Operation "${e.operation??`statement`}" received raw array parameter ${t} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,{code:n.INVALID_INPUT,meta:{parameterIndex:t,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function snapshotProviderParameters(e,t){return t.model===`$raw`?snapshotRawParameterGraph(e,{invalidDate:e=>invalidProviderDateError(t,e),unsupportedArray:e=>unsupportedProviderArrayError(t,e)}):[...e]}function createNormalizedResultMeta(e){return{driver:e.provider,operation:e.operation,...e.model?{model:e.model}:{},...e.correlationId?{correlationId:e.correlationId}:{}}}const d=/^(?:0|[1-9]\d*)$/;function normalizeProviderRowCount(e,t,n){let i=e===null?n?.nullValue:e;if(n?.allowDecimalString===!0&&typeof i==`string`&&d.test(i)&&(i=Number(i)),typeof i!=`number`||!Number.isSafeInteger(i)||i<0)throw new r(`Driver "${t.provider}" returned a malformed row count for operation "${t.operation}".`,{meta:createNormalizedResultMeta(t)});return i}function normalizeProviderInsertId(e,t,n){if(typeof e==`string`){if(!d.test(e))throw malformedInsertId(t);return e===`0`?void 0:BigInt(e)}if(n?.allowNumber===!0&&typeof e==`number`){if(!Number.isSafeInteger(e)||e<0)throw malformedInsertId(t);return e===0?void 0:e}throw malformedInsertId(t)}function malformedInsertId(e){return new r(`Driver "${e.provider}" returned a malformed insert id for operation "${e.operation}".`,{meta:createNormalizedResultMeta(e)})}function malformedNormalizedResult(e,t){let n=t===void 0?``:` at batch result index ${t}`;return new r(`Driver "${e.provider}" returned a malformed normalized result for operation "${e.operation}"${n}; expected { rows: object[], rowCount: safe non-negative integer }.`,{meta:{...createNormalizedResultMeta(e),...t===void 0?{}:{resultIndex:t}}})}function isNormalizedResultRow(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function hasNormalizedRows(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!(Object.hasOwn(e,t)&&isNormalizedResultRow(e[t])))return!1;return!0}function assertNormalizedQueryResult(e,t,n){let r=e?.insertId===void 0||typeof e.insertId==`bigint`&&e.insertId>=0n||typeof e.insertId==`number`&&Number.isFinite(e.insertId)&&Number.isSafeInteger(e.insertId)&&e.insertId>=0;if(!(isNormalizedResultRow(e)&&hasNormalizedRows(e.rows))||typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0||!r)throw malformedNormalizedResult(t,n)}function assertNormalizedBatchResults(e,t,n){if(!Array.isArray(e)||e.length!==t){let i=Array.isArray(e)?e.length:0;throw new r(`Driver "${n.provider}" returned ${i} results for operation "${n.operation}"; expected ${t}, one per statement.`,{meta:{...createNormalizedResultMeta(n),expectedStatementCount:t,actualResultCount:i}})}for(let t=0;t<e.length;t+=1)assertNormalizedQueryResult(e[t],n,t)}export{normalizeProviderInsertId as a,validateRawParameters as c,snapshotPreparedStatement as d,transferPreparedStatement as f,a as h,isNormalizedResultRow as i,readPreparedStatement as l,markVerbatimBatchQuery as m,assertNormalizedQueryResult as n,normalizeProviderRowCount as o,isVerbatimBatchQuery as p,createNormalizedResultMeta as r,snapshotProviderParameters as s,assertNormalizedBatchResults as t,registerPreparedStatement as u};
2
+ //# sourceMappingURL=normalized-result-BF7gr4_b.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalized-result-BF7gr4_b.mjs","names":[],"sources":["../src/drivers/async-dispose.ts","../src/drivers/driver-batch-query-kind.ts","../src/drivers/prepared-statement-provenance.ts","../src/drivers/provider-parameter-snapshot.ts","../src/drivers/normalized-result.ts"],"sourcesContent":["/**\n * The platform's async-disposal protocol — as much of it as the runtime and the\n * consumer's type declarations actually provide.\n *\n * `Symbol.asyncDispose` (explicit resource management, TypeScript 5.2+) can be\n * missing in two independent ways, and each one is handled here so that no\n * caller has to think about it:\n *\n * 1. **The runtime symbol** is absent on engines that predate the proposal.\n * {@link ASYNC_DISPOSE} resolves it once; every definition site guards on it\n * rather than writing a bare `[Symbol.asyncDispose]` computed key, which\n * would otherwise install a method under the string key `\"undefined\"`.\n *\n * 2. **The type declaration** is absent from a consumer's `lib` / `@types`.\n * That is why the disposal member is carried by {@link AsyncDisposeMember}\n * instead of being written literally: a consumer who never writes\n * `await using` must not be forced to widen `lib` just to compile the\n * published `.d.mts`. See `docs/architecture/typed-kernel-without-effect-plan.md`\n * (Phase T6) and the consumer-floor probe in\n * `scripts/consumer-type-floor.mjs` for the measured floor.\n */\n\n/**\n * The runtime's async-disposal key, or `undefined` on engines that predate\n * explicit resource management.\n */\nexport const ASYNC_DISPOSE: typeof Symbol.asyncDispose | undefined =\n typeof Symbol.asyncDispose === \"symbol\" ? Symbol.asyncDispose : undefined;\n\n/**\n * `Symbol.asyncDispose`'s type where the ambient declarations define it, and\n * `never` where they do not.\n *\n * `never` is the load-bearing half: it turns {@link AsyncDisposeMember} into the\n * empty object, so the member simply is not there for a consumer whose `lib`\n * and `@types` never declared the symbol in the first place.\n */\nexport type AsyncDisposeKey = SymbolConstructor extends {\n readonly asyncDispose: infer Key extends symbol;\n}\n ? Key\n : never;\n\n/**\n * `{ [Symbol.asyncDispose](): Promise<void> }` where the symbol is typed, and\n * `{}` where it is not — the graceful-degradation carrier for every viborm type\n * that participates in `await using`.\n */\nexport type AsyncDisposeMember = {\n [Key in AsyncDisposeKey]: () => Promise<void>;\n};\n","/** Internal execution-kind metadata for prepared batch queries. */\n\nconst VERBATIM_BATCH_QUERY = Symbol(\"viborm.verbatimBatchQuery\");\n\n/** Mark a prepared raw statement that must retain verbatim driver semantics. */\nexport function markVerbatimBatchQuery<T extends object>(query: T): T {\n Object.defineProperty(query, VERBATIM_BATCH_QUERY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return query;\n}\n\n/** Whether a prepared statement came from an unsafe or legacy raw call. */\nexport function isVerbatimBatchQuery(query: object): boolean {\n return Reflect.get(query, VERBATIM_BATCH_QUERY) === true;\n}\n","import { Sql } from \"@sql\";\n\nconst preparedStatements = new WeakMap<object, Sql>();\n\n/** Retain the typed Sql behind a rendered batch query without publishing it. */\nexport function registerPreparedStatement(query: object, statement: Sql): void {\n preparedStatements.set(query, statement);\n}\n\n/** Preserve private provenance when an internal owner snapshots a batch query. */\nexport function transferPreparedStatement<Output extends object>(\n source: object,\n output: Output\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) preparedStatements.set(output, statement);\n return output;\n}\n\n/** Preserve provenance with the exact detached values a batch will execute. */\nexport function snapshotPreparedStatement<Output extends object>(\n source: object,\n output: Output,\n values: readonly unknown[]\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) {\n preparedStatements.set(\n output,\n new Sql([...statement.strings], [...values])\n );\n }\n return output;\n}\n\n/** Read provenance only at the trusted typed-statement execution boundary. */\nexport function readPreparedStatement(query: object): Sql | undefined {\n return preparedStatements.get(query);\n}\n","import { QueryError, VibORMErrorCode } from \"@errors\";\nimport { isDate } from \"@validation/value-guards\";\nimport type { QueryExecutionContext } from \"./types\";\n\ntype InvalidRawDateError = (parameterIndex: number) => Error;\ntype UnsupportedRawArrayError = (parameterIndex: number) => Error;\n\ninterface RawParameterErrors {\n readonly invalidDate: InvalidRawDateError;\n readonly unsupportedArray: UnsupportedRawArrayError;\n}\n\ninterface RawParameterEdge {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n readonly value: unknown;\n}\n\ninterface RawParameterNode {\n readonly edges: readonly RawParameterEdge[];\n readonly isArray: boolean;\n readonly properties: readonly RawParameterProperty[];\n readonly prototype: object | null;\n readonly source: object;\n}\n\ninterface RawParameterProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\ninterface RawParameterGraph {\n readonly dateTimes: WeakMap<object, number>;\n readonly nodes: readonly RawParameterNode[];\n readonly roots: readonly unknown[];\n}\n\ntype RawParameterNodeAnalysis =\n | { readonly kind: \"node\"; readonly shape: Omit<RawParameterNode, \"source\"> }\n | { readonly kind: \"opaque\" }\n | { readonly kind: \"unsupported-array\" };\n\nconst arrayIndex = /^(?:0|[1-9]\\d*)$/;\nconst maximumArrayIndex = 4_294_967_294;\n\ninterface BuiltinPrototypeProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\nfunction captureBuiltinPrototype(\n prototype: object\n): readonly BuiltinPrototypeProperty[] {\n const properties: BuiltinPrototypeProperty[] = [];\n for (const key of Reflect.ownKeys(prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, key);\n if (descriptor) properties.push({ descriptor, key });\n }\n return Object.freeze(properties);\n}\n\nconst objectPrototypeShape = captureBuiltinPrototype(Object.prototype);\nconst arrayPrototypeShape = captureBuiltinPrototype(Array.prototype);\n\nfunction isArrayIndex(key: PropertyKey): boolean {\n if (typeof key !== \"string\" || !arrayIndex.test(key)) return false;\n const index = Number(key);\n return index <= maximumArrayIndex && String(index) === key;\n}\n\nfunction functionSource(value: unknown): string | undefined {\n if (typeof value !== \"function\") return;\n try {\n return Function.prototype.toString.call(value);\n } catch {\n return;\n }\n}\n\nfunction sameInertRecord(left: unknown, right: unknown): boolean {\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\"\n ) {\n return Object.is(left, right);\n }\n try {\n if (\n Object.getPrototypeOf(left) !== null ||\n Object.getPrototypeOf(right) !== null\n ) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n for (let index = 0; index < rightKeys.length; index += 1) {\n const leftKey = leftKeys[index];\n const rightKey = rightKeys[index];\n if (leftKey !== rightKey || rightKey === undefined) return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, rightKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, rightKey);\n if (\n leftDescriptor === undefined ||\n rightDescriptor === undefined ||\n !(\"value\" in leftDescriptor) ||\n !(\"value\" in rightDescriptor) ||\n leftDescriptor.configurable !== rightDescriptor.configurable ||\n leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.writable !== rightDescriptor.writable ||\n !Object.is(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction sameBuiltinDescriptor(\n actual: PropertyDescriptor,\n expected: PropertyDescriptor\n): boolean {\n if (\n actual.configurable !== expected.configurable ||\n actual.enumerable !== expected.enumerable ||\n \"value\" in actual !== \"value\" in expected\n ) {\n return false;\n }\n if (\"value\" in actual && \"value\" in expected) {\n if (actual.writable !== expected.writable) return false;\n const expectedSource = functionSource(expected.value);\n if (expectedSource !== undefined) {\n return functionSource(actual.value) === expectedSource;\n }\n return sameInertRecord(actual.value, expected.value);\n }\n return (\n functionSource(actual.get) === functionSource(expected.get) &&\n functionSource(actual.set) === functionSource(expected.set)\n );\n}\n\nfunction hasBuiltinPrototypeShape(\n prototype: object,\n shape: readonly BuiltinPrototypeProperty[]\n): boolean {\n try {\n const keys = Reflect.ownKeys(prototype);\n if (keys.length !== shape.length) return false;\n for (let index = 0; index < shape.length; index += 1) {\n const expected = shape[index];\n if (expected === undefined || keys[index] !== expected.key) return false;\n const actual = Object.getOwnPropertyDescriptor(prototype, expected.key);\n if (\n actual === undefined ||\n !sameBuiltinDescriptor(actual, expected.descriptor)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isObjectPrototype(prototype: object): boolean {\n try {\n return (\n Object.getPrototypeOf(prototype) === null &&\n hasBuiltinPrototypeShape(prototype, objectPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\nfunction isArrayPrototype(prototype: object): boolean {\n try {\n const parent = Object.getPrototypeOf(prototype);\n return (\n parent !== null &&\n isObjectPrototype(parent) &&\n hasBuiltinPrototypeShape(prototype, arrayPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\n/** Only arrays and records with inert inherited behavior are interpreted. */\nfunction rawParameterNodeShape(value: object): RawParameterNodeAnalysis {\n let isArray = false;\n try {\n isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (\n (isArray && prototype !== null && !isArrayPrototype(prototype)) ||\n (!isArray && prototype !== null && !isObjectPrototype(prototype))\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n\n const edges: RawParameterEdge[] = [];\n const properties: RawParameterProperty[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n properties.push({ descriptor, key });\n const isProviderVisible = isArray\n ? isArrayIndex(key)\n : descriptor.enumerable && typeof key === \"string\";\n if (!isProviderVisible) continue;\n if (!(\"value\" in descriptor)) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n edges.push({ descriptor, key, value: descriptor.value });\n }\n const toJSON = properties.find((property) => property.key === \"toJSON\");\n if (\n toJSON &&\n (!(\"value\" in toJSON.descriptor) ||\n typeof toJSON.descriptor.value === \"function\")\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n return {\n kind: \"node\",\n shape: { edges, isArray, properties, prototype },\n };\n } catch {\n // An exotic record owns its traversal semantics. If reflection refuses an\n // array shape, it cannot safely reach provider array semantics.\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n}\n\nfunction rawDateTime(\n value: unknown,\n parameterIndex: number,\n invalidDateError: InvalidRawDateError\n): number | undefined {\n if (!isDate(value)) return;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) throw invalidDateError(parameterIndex);\n return time;\n}\n\nfunction analyzeRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): RawParameterGraph {\n const nodesBySource = new WeakMap<object, RawParameterNode>();\n const dateTimes = new WeakMap<object, number>();\n const nodes: RawParameterNode[] = [];\n const roots = new Array<unknown>(params.length);\n\n const discover = (\n value: unknown,\n parameterIndex: number\n ): RawParameterNode | undefined => {\n const time = rawDateTime(value, parameterIndex, errors.invalidDate);\n if (time !== undefined && typeof value === \"object\" && value !== null) {\n dateTimes.set(value, time);\n return;\n }\n if (typeof value !== \"object\" || value === null) return;\n\n const known = nodesBySource.get(value);\n if (known) return known;\n const analysis = rawParameterNodeShape(value);\n if (analysis.kind === \"unsupported-array\") {\n throw errors.unsupportedArray(parameterIndex);\n }\n if (analysis.kind === \"opaque\") return;\n const node: RawParameterNode = {\n ...analysis.shape,\n source: value,\n };\n nodesBySource.set(value, node);\n nodes.push(node);\n return node;\n };\n\n for (\n let parameterIndex = 0;\n parameterIndex < params.length;\n parameterIndex++\n ) {\n if (!Object.hasOwn(params, parameterIndex)) continue;\n const root = params[parameterIndex];\n roots[parameterIndex] = root;\n const rootTime = rawDateTime(root, parameterIndex, errors.invalidDate);\n if (rootTime !== undefined && typeof root === \"object\" && root !== null) {\n dateTimes.set(root, rootTime);\n continue;\n }\n const rootNode = discover(root, parameterIndex);\n if (!rootNode) continue;\n\n const pending = [rootNode];\n let cursor = 0;\n while (cursor < pending.length) {\n const node = pending[cursor];\n cursor += 1;\n if (!node) continue;\n for (const edge of node.edges) {\n const before = nodes.length;\n const child = discover(edge.value, parameterIndex);\n if (child && nodes.length > before) pending.push(child);\n }\n }\n }\n\n return { dateTimes, nodes, roots };\n}\n\n/** Validate every interpreted raw parameter before query interception. */\nexport function validateRawParameters(\n params: readonly unknown[],\n errors: RawParameterErrors\n): void {\n analyzeRawParameterGraph(params, errors);\n}\n\n/**\n * Snapshot every admitted data-descriptor JSON container, preserving aliases,\n * cycles, and property descriptors. Foreign built-in containers normalize to\n * local prototypes. Custom record carriers and provider-native objects remain\n * opaque; arrays with custom provider-visible behavior are refused. A Proxy\n * can run reflection traps while presenting an admitted container shape; the\n * captured descriptor view, never the later mutable Proxy, reaches dispatch.\n */\nfunction snapshotRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): unknown[] {\n const graph = analyzeRawParameterGraph(params, errors);\n const copies = new WeakMap<object, object>();\n const copiedDates = new WeakMap<object, Date>();\n\n for (const node of graph.nodes) {\n const copy: object = node.isArray ? [] : {};\n if (node.prototype === null) Object.setPrototypeOf(copy, null);\n copies.set(node.source, copy);\n }\n\n const copiedValue = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) return value;\n const time = graph.dateTimes.get(value);\n if (time !== undefined) {\n const known = copiedDates.get(value);\n if (known) return known;\n const copy = new Date(time);\n copiedDates.set(value, copy);\n return copy;\n }\n return copies.get(value) ?? value;\n };\n\n for (const node of graph.nodes) {\n const copy = copies.get(node.source);\n if (!copy) continue;\n for (const property of node.properties) {\n if (node.isArray && property.key === \"length\") continue;\n const descriptor = property.descriptor;\n Object.defineProperty(\n copy,\n property.key,\n \"value\" in descriptor &&\n (node.isArray\n ? isArrayIndex(property.key)\n : descriptor.enumerable && typeof property.key === \"string\")\n ? { ...descriptor, value: copiedValue(descriptor.value) }\n : descriptor\n );\n }\n if (node.isArray) {\n const length = node.properties.find(\n (property) => property.key === \"length\"\n );\n if (length) Object.defineProperty(copy, \"length\", length.descriptor);\n }\n }\n\n const snapshot = new Array<unknown>(graph.roots.length);\n for (let index = 0; index < graph.roots.length; index++) {\n if (!Object.hasOwn(graph.roots, index)) continue;\n snapshot[index] = copiedValue(graph.roots[index]);\n }\n return snapshot;\n}\n\nfunction invalidProviderDateError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\nfunction unsupportedProviderArrayError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\n/**\n * Preserve the raw Date admission invariant after the last trusted statement\n * transform. Non-raw statements keep the old shallow-copy path: their typed\n * inputs were validated upstream, and statement transforms are trusted. Raw\n * Date leaves are revalidated and every admitted data-descriptor array or\n * ordinary JSON record is detached. Reflection does not invoke accessors,\n * iterators, or `toJSON`; a Proxy may run its reflection traps, so its captured\n * descriptor view is the stable provider value. Arrays with custom inherited\n * or accessor behavior are refused. Custom record and provider-native carriers\n * remain opaque and are not traversed.\n */\nexport function snapshotProviderParameters(\n params: readonly unknown[],\n context: QueryExecutionContext\n): unknown[] {\n if (context.model !== \"$raw\") return [...params];\n return snapshotRawParameterGraph(params, {\n invalidDate: (parameterIndex) =>\n invalidProviderDateError(context, parameterIndex),\n unsupportedArray: (parameterIndex) =>\n unsupportedProviderArrayError(context, parameterIndex),\n });\n}\n","import { QueryError } from \"@errors\";\nimport type { QueryResult } from \"./types\";\n\nexport interface NormalizedResultContext {\n provider: string;\n operation: string;\n model?: string;\n correlationId?: string;\n}\n\nexport function createNormalizedResultMeta(\n context: NormalizedResultContext\n): Record<string, unknown> {\n return {\n driver: context.provider,\n operation: context.operation,\n ...(context.model ? { model: context.model } : {}),\n ...(context.correlationId ? { correlationId: context.correlationId } : {}),\n };\n}\n\nconst NON_NEGATIVE_DECIMAL_REGEX = /^(?:0|[1-9]\\d*)$/;\n\nexport function normalizeProviderRowCount(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowDecimalString?: boolean; nullValue?: number }\n): number {\n let normalized = value === null ? options?.nullValue : value;\n if (\n options?.allowDecimalString === true &&\n typeof normalized === \"string\" &&\n NON_NEGATIVE_DECIMAL_REGEX.test(normalized)\n ) {\n normalized = Number(normalized);\n }\n if (\n typeof normalized !== \"number\" ||\n !Number.isSafeInteger(normalized) ||\n normalized < 0\n ) {\n throw new QueryError(\n `Driver \"${context.provider}\" returned a malformed row count for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n }\n return normalized;\n}\n\nexport function normalizeProviderInsertId(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowNumber?: boolean }\n): number | bigint | undefined {\n if (typeof value === \"string\") {\n if (!NON_NEGATIVE_DECIMAL_REGEX.test(value)) {\n throw malformedInsertId(context);\n }\n return value === \"0\" ? undefined : BigInt(value);\n }\n if (options?.allowNumber === true && typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw malformedInsertId(context);\n }\n return value === 0 ? undefined : value;\n }\n throw malformedInsertId(context);\n}\n\nfunction malformedInsertId(context: NormalizedResultContext): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed insert id for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n}\n\nfunction malformedNormalizedResult(\n context: NormalizedResultContext,\n resultIndex?: number\n): QueryError {\n const position =\n resultIndex === undefined ? \"\" : ` at batch result index ${resultIndex}`;\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed normalized result for operation \"${context.operation}\"${position}; expected { rows: object[], rowCount: safe non-negative integer }.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n ...(resultIndex === undefined ? {} : { resultIndex }),\n },\n }\n );\n}\n\nexport function isNormalizedResultRow(\n value: unknown\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasNormalizedRows(value: unknown): value is Record<string, unknown>[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!(Object.hasOwn(value, index) && isNormalizedResultRow(value[index]))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Assert the single cross-driver success contract. Empty row arrays and a\n * rowCount of zero are valid; missing fields, non-record rows, and invented\n * counts are not.\n */\nexport function assertNormalizedQueryResult(\n result: QueryResult<unknown> | undefined,\n context: NormalizedResultContext,\n resultIndex?: number\n): void {\n const hasValidInsertId =\n result?.insertId === undefined ||\n (typeof result.insertId === \"bigint\" && result.insertId >= 0n) ||\n (typeof result.insertId === \"number\" &&\n Number.isFinite(result.insertId) &&\n Number.isSafeInteger(result.insertId) &&\n result.insertId >= 0);\n if (\n !(isNormalizedResultRow(result) && hasNormalizedRows(result.rows)) ||\n typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0 ||\n !hasValidInsertId\n ) {\n throw malformedNormalizedResult(context, resultIndex);\n }\n}\n\n/**\n * Native and planned batches must return one normalized result for each\n * submitted statement, in the same order.\n */\nexport function assertNormalizedBatchResults(\n results: readonly QueryResult<unknown>[],\n expectedStatementCount: number,\n context: NormalizedResultContext\n): void {\n if (!Array.isArray(results) || results.length !== expectedStatementCount) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw new QueryError(\n `Driver \"${context.provider}\" returned ${actualResultCount} results for operation \"${context.operation}\"; expected ${expectedStatementCount}, one per statement.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n expectedStatementCount,\n actualResultCount,\n },\n }\n );\n }\n\n for (let resultIndex = 0; resultIndex < results.length; resultIndex += 1) {\n assertNormalizedQueryResult(results[resultIndex], context, resultIndex);\n }\n}\n"],"mappings":"iNA0BA,MAAa,EACX,OAAO,OAAO,cAAiB,SAAW,OAAO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Q,EAAI,EAAQ,SAAW,EAAwB,CACxE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,IAAI,EACR,WAAW,EAAQ,SAAS,aAAa,EAAkB,0BAA0B,EAAQ,UAAU,cAAc,EAAuB,sBAC5I,CACE,KAAM,CACJ,GAAG,2BAA2B,EAAQ,CACtC,yBACA,oBACD,CACF,CACF,CAGH,IAAK,IAAI,EAAc,EAAG,EAAc,EAAQ,OAAQ,GAAe,EACrE,4BAA4B,EAAQ,GAAc,EAAS,EAAY"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";import{n as r}from"./canonical-json-BReb5nFO.mjs";import{a as i}from"./identity-Bj2EN6Ss.mjs";function refuseWorkersKvWritable(){throw new n(`Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional`,t.MIGRATION_UNSUPPORTED_PROVIDER)}var ObjectStoreEstateStorage=class{store;constructor(e){this.store=e}async readEstate(){return this.store.get(`estate.json`)}async listStates(){return this.listHex(`states/`,`.json`)}async listSnapshots(){return this.listHex(`snapshots/`,`.json`)}async listSql(){return this.listHex(`sql/`,`.sql`)}async readState(e){return this.store.get(`states/${e}.json`)}async readSnapshot(e){return this.store.get(`snapshots/${e}.json`)}async readSql(e){return this.store.get(`sql/${e}.sql`)}async publishEstate(e){return this.publish(`estate.json`,e)}async publishSnapshot(e,t){return this.publish(`snapshots/${e}.json`,t)}async publishSql(e,t){return this.publish(`sql/${e}.sql`,t)}async publishState(e,r){if(!i(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return this.publish(`states/${e}.json`,r)}async publish(e,i){if(await this.store.putIfAbsent(e,i)===`created`)return{outcome:`created`};let a=await this.store.get(e);if(!(a&&r(a,i)))throw new n(`Object-store key ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}async listHex(e,t){let n=await this.store.list(e),r=[];for(let a of n){let n=a.slice(e.length);if(!n.endsWith(t))continue;let o=n.slice(0,-t.length);i(o)&&r.push(o)}return r.sort()}},MemoryConditionalObjectStore=class{objects=new Map;async putIfAbsent(e,t){return this.objects.has(e)?`exists`:(this.objects.set(e,t.slice()),`created`)}async get(e){let t=this.objects.get(e);return t?t.slice():null}async list(e){return[...this.objects.keys()].filter(t=>t.startsWith(e)).sort()}};export{ObjectStoreEstateStorage as n,refuseWorkersKvWritable as r,MemoryConditionalObjectStore as t};
2
- //# sourceMappingURL=object-store-CZADAv4c.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";import{n as r}from"./canonical-json-acY4dQNQ.mjs";import{a as i}from"./identity-CmRos0Yf.mjs";function refuseWorkersKvWritable(){throw new n(`Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional`,t.MIGRATION_UNSUPPORTED_PROVIDER)}var ObjectStoreEstateStorage=class{store;constructor(e){this.store=e}async readEstate(){return this.store.get(`estate.json`)}async listStates(){return this.listHex(`states/`,`.json`)}async listSnapshots(){return this.listHex(`snapshots/`,`.json`)}async listSql(){return this.listHex(`sql/`,`.sql`)}async readState(e){return this.store.get(`states/${e}.json`)}async readSnapshot(e){return this.store.get(`snapshots/${e}.json`)}async readSql(e){return this.store.get(`sql/${e}.sql`)}async publishEstate(e){return this.publish(`estate.json`,e)}async publishSnapshot(e,t){return this.publish(`snapshots/${e}.json`,t)}async publishSql(e,t){return this.publish(`sql/${e}.sql`,t)}async publishState(e,r){if(!i(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return this.publish(`states/${e}.json`,r)}async publish(e,i){if(await this.store.putIfAbsent(e,i)===`created`)return{outcome:`created`};let a=await this.store.get(e);if(!(a&&r(a,i)))throw new n(`Object-store key ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}async listHex(e,t){let n=await this.store.list(e),r=[];for(let a of n){let n=a.slice(e.length);if(!n.endsWith(t))continue;let o=n.slice(0,-t.length);i(o)&&r.push(o)}return r.sort()}},MemoryConditionalObjectStore=class{objects=new Map;async putIfAbsent(e,t){return this.objects.has(e)?`exists`:(this.objects.set(e,t.slice()),`created`)}async get(e){let t=this.objects.get(e);return t?t.slice():null}async list(e){return[...this.objects.keys()].filter(t=>t.startsWith(e)).sort()}};export{ObjectStoreEstateStorage as n,refuseWorkersKvWritable as r,MemoryConditionalObjectStore as t};
2
+ //# sourceMappingURL=object-store-WjVilDvN.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"object-store-CZADAv4c.mjs","names":[],"sources":["../src/migrations/storage/object-store.ts"],"sourcesContent":["/**\n * Strong object-store publication contract.\n * A writable driver that cannot do conditional create is not a V1 estate owner.\n * Workers KV is refused here: it has no compare-and-swap publication.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport function refuseWorkersKvWritable(): never {\n throw new MigrationError(\n \"Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n}\n\nexport interface ObjectStoreConditionalPut {\n putIfAbsent(key: string, bytes: Uint8Array): Promise<\"created\" | \"exists\">;\n get(key: string): Promise<Uint8Array | null>;\n list(prefix: string): Promise<readonly string[]>;\n}\n\n/**\n * Estate writer over a strongly consistent object store with if-none-match\n * publication. Manifests become visible only after referenced bytes exist.\n */\nexport class ObjectStoreEstateStorage implements MigrationStorageWriter {\n private readonly store: ObjectStoreConditionalPut;\n\n constructor(store: ObjectStoreConditionalPut) {\n this.store = store;\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.store.get(\"estate.json\");\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return this.listHex(\"states/\", \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return this.listHex(\"snapshots/\", \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return this.listHex(\"sql/\", \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`states/${id}.json`);\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`snapshots/${hash}.json`);\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`sql/${hash}.sql`);\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(\"estate.json\", bytes);\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return this.publish(`snapshots/${hash}.json`, bytes);\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(`sql/${hash}.sql`, bytes);\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return this.publish(`states/${id}.json`, bytes);\n }\n\n private async publish(\n key: string,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n const result = await this.store.putIfAbsent(key, bytes);\n if (result === \"created\") return { outcome: \"created\" };\n const existing = await this.store.get(key);\n if (!(existing && bytesEqual(existing, bytes))) {\n throw new MigrationError(\n `Object-store key ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n\n private async listHex(prefix: string, suffix: string): Promise<Sha256[]> {\n const keys = await this.store.list(prefix);\n const hashes: Sha256[] = [];\n for (const key of keys) {\n const name = key.slice(prefix.length);\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (isSha256(hex)) hashes.push(hex);\n }\n return hashes.sort();\n }\n}\n\n/** In-memory strong object store for the conformance fixture. */\nexport class MemoryConditionalObjectStore implements ObjectStoreConditionalPut {\n private readonly objects = new Map<string, Uint8Array>();\n\n async putIfAbsent(\n key: string,\n bytes: Uint8Array\n ): Promise<\"created\" | \"exists\"> {\n if (this.objects.has(key)) return \"exists\";\n this.objects.set(key, bytes.slice());\n return \"created\";\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const bytes = this.objects.get(key);\n return bytes ? bytes.slice() : null;\n }\n\n async list(prefix: string): Promise<readonly string[]> {\n return [...this.objects.keys()]\n .filter((key) => key.startsWith(prefix))\n .sort();\n }\n}\n"],"mappings":"6NAWA,SAAgB,yBAAiC,CAC/C,MAAM,IAAI,EACR,yGACA,EAAgB,+BACjB,CAaH,IAAa,yBAAb,KAAwE,CACtE,MAEA,YAAY,EAAkC,CAC5C,KAAK,MAAQ,EAGf,MAAM,YAAyC,CAC7C,OAAO,KAAK,MAAM,IAAI,cAAc,CAGtC,MAAM,YAAyC,CAC7C,OAAO,KAAK,QAAQ,UAAW,QAAQ,CAGzC,MAAM,eAA4C,CAChD,OAAO,KAAK,QAAQ,aAAc,QAAQ,CAG5C,MAAM,SAAsC,CAC1C,OAAO,KAAK,QAAQ,OAAQ,OAAO,CAGrC,MAAM,UAAU,EAAwC,CACtD,OAAO,KAAK,MAAM,IAAI,UAAU,EAAG,OAAO,CAG5C,MAAM,aAAa,EAA0C,CAC3D,OAAO,KAAK,MAAM,IAAI,aAAa,EAAK,OAAO,CAGjD,MAAM,QAAQ,EAA0C,CACtD,OAAO,KAAK,MAAM,IAAI,OAAO,EAAK,MAAM,CAG1C,MAAM,cAAc,EAA2C,CAC7D,OAAO,KAAK,QAAQ,cAAe,EAAM,CAG3C,MAAM,gBACJ,EACA,EACwB,CACxB,OAAO,KAAK,QAAQ,aAAa,EAAK,OAAQ,EAAM,CAGtD,MAAM,WAAW,EAAc,EAA2C,CACxE,OAAO,KAAK,QAAQ,OAAO,EAAK,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":"object-store-WjVilDvN.mjs","names":[],"sources":["../src/migrations/storage/object-store.ts"],"sourcesContent":["/**\n * Strong object-store publication contract.\n * A writable driver that cannot do conditional create is not a V1 estate owner.\n * Workers KV is refused here: it has no compare-and-swap publication.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport function refuseWorkersKvWritable(): never {\n throw new MigrationError(\n \"Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n}\n\nexport interface ObjectStoreConditionalPut {\n putIfAbsent(key: string, bytes: Uint8Array): Promise<\"created\" | \"exists\">;\n get(key: string): Promise<Uint8Array | null>;\n list(prefix: string): Promise<readonly string[]>;\n}\n\n/**\n * Estate writer over a strongly consistent object store with if-none-match\n * publication. Manifests become visible only after referenced bytes exist.\n */\nexport class ObjectStoreEstateStorage implements MigrationStorageWriter {\n private readonly store: ObjectStoreConditionalPut;\n\n constructor(store: ObjectStoreConditionalPut) {\n this.store = store;\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.store.get(\"estate.json\");\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return this.listHex(\"states/\", \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return this.listHex(\"snapshots/\", \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return this.listHex(\"sql/\", \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`states/${id}.json`);\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`snapshots/${hash}.json`);\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`sql/${hash}.sql`);\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(\"estate.json\", bytes);\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return this.publish(`snapshots/${hash}.json`, bytes);\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(`sql/${hash}.sql`, bytes);\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return this.publish(`states/${id}.json`, bytes);\n }\n\n private async publish(\n key: string,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n const result = await this.store.putIfAbsent(key, bytes);\n if (result === \"created\") return { outcome: \"created\" };\n const existing = await this.store.get(key);\n if (!(existing && bytesEqual(existing, bytes))) {\n throw new MigrationError(\n `Object-store key ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n\n private async listHex(prefix: string, suffix: string): Promise<Sha256[]> {\n const keys = await this.store.list(prefix);\n const hashes: Sha256[] = [];\n for (const key of keys) {\n const name = key.slice(prefix.length);\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (isSha256(hex)) hashes.push(hex);\n }\n return hashes.sort();\n }\n}\n\n/** In-memory strong object store for the conformance fixture. */\nexport class MemoryConditionalObjectStore implements ObjectStoreConditionalPut {\n private readonly objects = new Map<string, Uint8Array>();\n\n async putIfAbsent(\n key: string,\n bytes: Uint8Array\n ): Promise<\"created\" | \"exists\"> {\n if (this.objects.has(key)) return \"exists\";\n this.objects.set(key, bytes.slice());\n return \"created\";\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const bytes = this.objects.get(key);\n return bytes ? bytes.slice() : null;\n }\n\n async list(prefix: string): Promise<readonly string[]> {\n return [...this.objects.keys()]\n .filter((key) => key.startsWith(prefix))\n .sort();\n }\n}\n"],"mappings":"6NAWA,SAAgB,yBA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CAEH,MAAO,CAAE,QAAS,YAAa,CAGjC,MAAc,QAAQ,EAAgB,EAAmC,CACvE,IAAM,EAAO,MAAM,KAAK,MAAM,KAAK,EAAO,CACpC,EAAmB,EAAE,CAC3B,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAO,EAAI,MAAM,EAAO,OAAO,CACrC,GAAI,CAAC,EAAK,SAAS,EAAO,CAAE,SAC5B,IAAM,EAAM,EAAK,MAAM,EAAG,CAAC,EAAO,OAAO,CACrC,EAAS,EAAI,EAAE,EAAO,KAAK,EAAI,CAErC,OAAO,EAAO,MAAM,GAKX,6BAAb,KAA+E,CAC7E,QAA2B,IAAI,IAE/B,MAAM,YACJ,EACA,EAC+B,CAG/B,OAFI,KAAK,QAAQ,IAAI,EAAI,CAAS,UAClC,KAAK,QAAQ,IAAI,EAAK,EAAM,OAAO,CAAC,CAC7B,WAGT,MAAM,IAAI,EAAyC,CACjD,IAAM,EAAQ,KAAK,QAAQ,IAAI,EAAI,CACnC,OAAO,EAAQ,EAAM,OAAO,CAAG,KAGjC,MAAM,KAAK,EAA4C,CACrD,MAAO,CAAC,GAAG,KAAK,QAAQ,MAAM,CAAC,CAC5B,OAAQ,GAAQ,EAAI,WAAW,EAAO,CAAC,CACvC,MAAM"}
@@ -1,7 +1,7 @@
1
- import { Mn as Dialect, Un as AnyModel } from "./index-B_jh2oaQ.mjs";
2
- import { i as ResolveCallback, t as MigrationClient } from "./planner-DHZG9Vy7.mjs";
1
+ import { Mn as Dialect, Un as AnyModel } from "./index-B4IWFJfv.mjs";
2
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-SzkGh-3T.mjs";
3
3
  import { i as Sha256, n as MigrationStorageWriter, r as PublishResult } from "./contract-Dw0FR78e.mjs";
4
- import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-DR0vYetv.mjs";
4
+ import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-BzgBm_86.mjs";
5
5
 
6
6
  //#region src/adapters/databases/sqlite/storage/datetime.d.ts
7
7
 
@@ -1,4 +1,4 @@
1
- import { E as OperationPayload, Ft as VibORMClient, It as VibORMConfig, Jt as RowsVerbs, M as ClientSchema, Nt as ExtensionState, W as InferOutput, an as MergeExtensionState, jt as ExtendedClient, kt as ClientTypeState } from "./index-B_jh2oaQ.mjs";
1
+ import { E as OperationPayload, Ft as VibORMClient, It as VibORMConfig, M as ClientSchema, Nt as ExtensionState, Ut as RowsVerbs, W as InferOutput, en as MergeExtensionState, jt as ExtendedClient, kt as ClientTypeState } from "./index-B4IWFJfv.mjs";
2
2
  import "./client.mjs";
3
3
  import { StandardSchemaV1 } from "@standard-schema/spec";
4
4
 
package/dist/pg.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-B_jh2oaQ.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-B4IWFJfv.mjs";
2
2
  import { Pool, PoolClient, PoolConfig, PoolConfig as PgOptions } from "pg";
3
3
 
4
4
  //#region src/drivers/pg/index.d.ts
@@ -35,6 +35,17 @@ interface PgDriverOptions {
35
35
  * `false` keeps every body inline.
36
36
  */
37
37
  sharedRelationBodies?: boolean;
38
+ /**
39
+ * The most relations (`FROM` items) one statement may reference. Past it, a
40
+ * statement states the recursive filters it repeats as key sets, and then
41
+ * joins the key sets a row tests, as far as it needs to fit: the answers are
42
+ * the same, some plans slower. PlanetScale Neki refuses a statement over
43
+ * 256: absent, a pool this driver makes reads each connection's startup,
44
+ * 256 on Neki and before the first connection, none on plain PostgreSQL (a
45
+ * supplied pool learns from Neki's first refusal). A stated bound always
46
+ * wins. Only where relation bodies are shared.
47
+ */
48
+ relationsPerStatement?: number;
38
49
  /**
39
50
  * Your claim, at your risk, that every connection this pool opens is one
40
51
  * server session for its whole life. It lifts migrations' refusal of
@@ -73,6 +84,13 @@ declare class PgDriver extends Driver<PgPool, PgPoolClient> {
73
84
  * transport until a proven successful end.
74
85
  */
75
86
  private readonly ownedPoolErrors;
87
+ /**
88
+ * The `server_version` the last connection this driver's own pool opened
89
+ * received at startup, read for the relation bound (`boundByServer`); a
90
+ * pool given its own `Client` class, or supplied, is not read.
91
+ */
92
+ private serverVersion;
93
+ private readonly readsServer;
76
94
  constructor(options?: PgDriverOptions);
77
95
  /** Every host or URL this driver's pool connects through, for migration admission. */
78
96
  protected migrationSessionEndpoints(): readonly unknown[];
@@ -92,6 +110,13 @@ declare class PgDriver extends Driver<PgPool, PgPoolClient> {
92
110
  * two estates share. This driver listens only on the pool it made.
93
111
  */
94
112
  protected initClient(): Promise<PgPool>;
113
+ /**
114
+ * node-postgres's `Client`, reading each connection's startup: it keeps no
115
+ * parameter status, so the `server_version` that names Neki is read as it
116
+ * arrives, before the connection is handed out (to a statement, or to a
117
+ * transaction before its callback builds any).
118
+ */
119
+ private readingClient;
95
120
  private readBackgroundPoolFailure;
96
121
  /** Clear exactly the failure observed before an operation started. */
97
122
  private clearBackgroundPoolFailure;
package/dist/pg.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t,n,p as r,r as i}from"./error-mapping-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./transaction-4dfqals6.mjs";import{n as s}from"./suppressed-failure-Bdo2aK81.mjs";import{s as c}from"./execution-context-rJXTRVrJ.mjs";import{n as l}from"./client-BmcHzDBa.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-Bzc0GCQ4.mjs";import{t as v}from"./postgres-result-D403cLyA.mjs";import{t as y}from"./postgres-adapter-Ci07rgh_.mjs";import{Pool as b,types as x}from"pg";const identityParser=e=>e,S={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:x.getTypeParser(e,t)};function createOwnedPoolErrorState(){let e=0,t={retain(n){e+=1,t.backgroundFailure={error:n,generation:e,isAvailable:!0}}};return t}function holdClientErrors(e){let t,retain=e=>{t??=e};return e.on(`error`,retain),{failure:()=>t,stop:()=>{e.off(`error`,retain)}}}const C=new Set([`user`,`password`,`host`,`port`]),w=[`sslmode`,`sslcert`,`sslkey`,`sslrootcert`];function connectionRecord(e,t){let n=e.connectionString??t;if(!n)return e;if(typeof e.password==`function`)throw new a('Driver "pg" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',{meta:{driver:`pg`,operation:`configuration`}});let r=f(n),i;try{i=new URL(r)}catch{i=void 0}let o=Object.entries(e).filter(([e,t])=>t!==void 0&&(C.has(e)||e===`database`||e===`ssl`||e!==`connectionString`&&i?.searchParams.has(e)));if(o.length===0)return{...e,connectionString:r};if(i===void 0)throw new a(`Driver "pg" could not read its connection URL to apply the connection options beside it.`,{meta:{driver:`pg`,operation:`configuration`}});for(let[e,t]of o)if(i.searchParams.delete(e),e===`ssl`)for(let e of w)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:C.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const T={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;constructor(e={}){super(`postgresql`,`pg`);let t=d(e);this.suppliedPool=e.pool;let n={...e.options};h(`pg`,e,!!(this.suppliedPool||n.host||n.connectionString)),this.connectionOptions=connectionRecord(n,e.databaseUrl),this.suppliedPool&&(this.client=this.suppliedPool),y(this,t,e),m(this,`migrationSessionAttestation`,_(e))}migrationSessionEndpoints(){let e=this.suppliedPool?Reflect.get(this.suppliedPool,`options`):void 0,t=typeof e==`object`&&e?e:{};return[this.connectionOptions.host,this.connectionOptions.connectionString,Reflect.get(t,`host`),Reflect.get(t,`connectionString`)]}initClient(){if(this.suppliedPool!==void 0)return Promise.resolve(this.suppliedPool);let e=new b({types:S,...this.connectionOptions}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readBackgroundPoolFailure(e){return this.ownedPoolErrors.get(e)?.backgroundFailure}clearBackgroundPoolFailure(e,t){if(t===void 0||!t.isAvailable)return!1;t.isAvailable=!1;let n=this.ownedPoolErrors.get(e);return n?.backgroundFailure?.generation===t.generation&&(n.backgroundFailure=void 0),!0}consumeBackgroundPoolFailure(e,t){if(this.clearBackgroundPoolFailure(e,t))return t?.error}throwPoolQueryFailure(e,t,n,r,a,o){let c=this.consumeBackgroundPoolFailure(e,t);throw c===void 0?n:s(i(n,{driverName:this.driverName,dialect:this.dialect,model:o?.model,operation:o?.operation,correlationId:o?.correlationId,query:r,params:this.getDiagnosticParameters(a??[],o),diagnostics:this.getErrorDisclosure(o),forceContext:!0}),c)}async acquirePooledClient(e,t={},r){let i=this.readBackgroundPoolFailure(e),a=!1;try{return await p(async()=>{try{let t=await e.connect();return this.clearBackgroundPoolFailure(e,i),t}finally{a=!0}},e=>e.release(),r,{driverName:this.driverName,form:`callback`})}catch(r){if(!a)throw r;let o=this.consumeBackgroundPoolFailure(e,i);throw o===void 0?r:s(n(r,{driverName:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId,diagnostics:this.getErrorDisclosure(t)},`Database connection failed after the pool reported a background failure`),o)}}async closeClient(e){if(e===this.suppliedPool)return;let t=this.ownedPoolErrors.get(e);try{await e.end()}catch(r){let i=this.consumeBackgroundPoolFailure(e,t?.backgroundFailure);throw i===void 0?r:s(n(r,{driverName:this.driverName},`Database disconnection failed`),i)}t!==void 0&&(e.off(`error`,t.retain),t.backgroundFailure=void 0,this.ownedPoolErrors.delete(e))}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=this.readBackgroundPoolFailure(e),s=await e.query({text:t,values:n,types:S}).catch(i=>this.throwPoolQueryFailure(e,o,i,t,n,r));return this.clearBackgroundPoolFailure(e,o),{rows:s.rows,rowCount:v(s.rowCount,s.command,s.rows,{provider:`pg`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,n,i,a){if(`release`in e)throw t(this.driverName);let l=await this.acquirePooledClient(e,i,a?.maxWaitMs),u=holdClientErrors(l),withClientFailure=e=>{let t=u.failure();return t===void 0||t===e?e:s(e,t)},d,queryOrDiscard=async e=>{try{await l.query(e)}catch(e){throw d??=e instanceof Error?e:!0,withClientFailure(e)}};return r({begin:()=>queryOrDiscard(`BEGIN`),callback:async()=>{try{return await n(l)}catch(e){throw withClientFailure(e)}},commit:()=>{let e=u.failure();if(e!==void 0)throw e;return queryOrDiscard(`COMMIT`)},rollback:()=>u.failure()===void 0?queryOrDiscard(`ROLLBACK`):void 0,phases:c(i),close:()=>{try{let e=d??u.failure();if(e){l.release(e);return}l.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "pg" could not release an unsafe transaction connection.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{u.stop()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw t(this.driverName);let n=await this.acquirePooledClient(e,{operation:`pinnedSession`}),r=holdClientErrors(n);return{session:n,lost:r.failure,release:e=>{try{n.release(r.failure()??(e?!0:void 0))}finally{r.stop()}return Promise.resolve()}}}};function createClient(e){u(e,`pg`,T);let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e;return l(e,new PgDriver({namespace:d(e),migrationSessionAttestation:_(e),pool:t||void 0,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies}))}export{PgDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t,n,p as r,r as i}from"./error-mapping-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./transaction-4dfqals6.mjs";import{n as s}from"./suppressed-failure-Bdo2aK81.mjs";import{s as c}from"./execution-context-rJXTRVrJ.mjs";import{n as l}from"./client-Bhl2mWam.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-CQQbCQh9.mjs";import{t as v}from"./postgres-result-BCUQf8b_.mjs";import{t as y}from"./postgres-adapter-BAqRfWl1.mjs";import{n as b,t as x}from"./relation-bound-BrZLsSke.mjs";import{Client as S,Pool as C,types as w}from"pg";const identityParser=e=>e,T={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:w.getTypeParser(e,t)};function createOwnedPoolErrorState(){let e=0,t={retain(n){e+=1,t.backgroundFailure={error:n,generation:e,isAvailable:!0}}};return t}function holdClientErrors(e){let t,retain=e=>{t??=e};return e.on(`error`,retain),{failure:()=>t,stop:()=>{e.off(`error`,retain)}}}const E=new Set([`user`,`password`,`host`,`port`]),D=[`sslmode`,`sslcert`,`sslkey`,`sslrootcert`];function connectionRecord(e,t){let n=e.connectionString??t;if(!n)return e;if(typeof e.password==`function`)throw new a('Driver "pg" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',{meta:{driver:`pg`,operation:`configuration`}});let r=f(n),i;try{i=new URL(r)}catch{i=void 0}let o=Object.entries(e).filter(([e,t])=>t!==void 0&&(E.has(e)||e===`database`||e===`ssl`||e!==`connectionString`&&i?.searchParams.has(e)));if(o.length===0)return{...e,connectionString:r};if(i===void 0)throw new a(`Driver "pg" could not read its connection URL to apply the connection options beside it.`,{meta:{driver:`pg`,operation:`configuration`}});for(let[e,t]of o)if(i.searchParams.delete(e),e===`ssl`)for(let e of D)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:E.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const O={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,relationsPerStatement:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;serverVersion;readsServer;constructor(e={}){super(`postgresql`,`pg`);let t=d(e);this.suppliedPool=e.pool;let n={...e.options};h(`pg`,e,!!(this.suppliedPool||n.host||n.connectionString)),this.connectionOptions=connectionRecord(n,e.databaseUrl),this.suppliedPool&&(this.client=this.suppliedPool),y(this,t,e),this.readsServer=this.suppliedPool===void 0&&n.Client===void 0&&x(this.adapter,()=>this.serverVersion),m(this,`migrationSessionAttestation`,_(e))}migrationSessionEndpoints(){let e=this.suppliedPool?Reflect.get(this.suppliedPool,`options`):void 0,t=typeof e==`object`&&e?e:{};return[this.connectionOptions.host,this.connectionOptions.connectionString,Reflect.get(t,`host`),Reflect.get(t,`connectionString`)]}initClient(){if(this.suppliedPool!==void 0)return Promise.resolve(this.suppliedPool);let e=new C({types:T,...this.connectionOptions,...this.readsServer?{Client:this.readingClient()}:{}}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readingClient(){let read=e=>{this.serverVersion=e};return class extends S{constructor(e){super(e),this.connection.on(`parameterStatus`,e=>{e.parameterName===`server_version`&&read(e.parameterValue)})}}}readBackgroundPoolFailure(e){return this.ownedPoolErrors.get(e)?.backgroundFailure}clearBackgroundPoolFailure(e,t){if(t===void 0||!t.isAvailable)return!1;t.isAvailable=!1;let n=this.ownedPoolErrors.get(e);return n?.backgroundFailure?.generation===t.generation&&(n.backgroundFailure=void 0),!0}consumeBackgroundPoolFailure(e,t){if(this.clearBackgroundPoolFailure(e,t))return t?.error}throwPoolQueryFailure(e,t,n,r,a,o){let c=this.consumeBackgroundPoolFailure(e,t);throw c===void 0?n:s(i(n,{driverName:this.driverName,dialect:this.dialect,model:o?.model,operation:o?.operation,correlationId:o?.correlationId,query:r,params:this.getDiagnosticParameters(a??[],o),diagnostics:this.getErrorDisclosure(o),forceContext:!0}),c)}async acquirePooledClient(e,t={},r){let i=this.readBackgroundPoolFailure(e),a=!1;try{return await p(async()=>{try{let t=await e.connect();return this.clearBackgroundPoolFailure(e,i),t}finally{a=!0}},e=>e.release(),r,{driverName:this.driverName,form:`callback`})}catch(r){if(!a)throw r;let o=this.consumeBackgroundPoolFailure(e,i);throw o===void 0?r:s(n(r,{driverName:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId,diagnostics:this.getErrorDisclosure(t)},`Database connection failed after the pool reported a background failure`),o)}}async closeClient(e){if(e===this.suppliedPool)return;let t=this.ownedPoolErrors.get(e);try{await e.end()}catch(r){let i=this.consumeBackgroundPoolFailure(e,t?.backgroundFailure);throw i===void 0?r:s(n(r,{driverName:this.driverName},`Database disconnection failed`),i)}t!==void 0&&(e.off(`error`,t.retain),t.backgroundFailure=void 0,this.ownedPoolErrors.delete(e))}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=this.readBackgroundPoolFailure(e),s=await e.query({text:t,values:n,types:T}).catch(i=>(b(this.adapter,i),this.throwPoolQueryFailure(e,o,i,t,n,r)));return this.clearBackgroundPoolFailure(e,o),{rows:s.rows,rowCount:v(s.rowCount,s.command,s.rows,{provider:`pg`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,n,i,a){if(`release`in e)throw t(this.driverName);let l=await this.acquirePooledClient(e,i,a?.maxWaitMs),u=holdClientErrors(l),withClientFailure=e=>{let t=u.failure();return t===void 0||t===e?e:s(e,t)},d,queryOrDiscard=async e=>{try{await l.query(e)}catch(e){throw d??=e instanceof Error?e:!0,withClientFailure(e)}};return r({begin:()=>queryOrDiscard(`BEGIN`),callback:async()=>{try{return await n(l)}catch(e){throw withClientFailure(e)}},commit:()=>{let e=u.failure();if(e!==void 0)throw e;return queryOrDiscard(`COMMIT`)},rollback:()=>u.failure()===void 0?queryOrDiscard(`ROLLBACK`):void 0,phases:c(i),close:()=>{try{let e=d??u.failure();if(e){l.release(e);return}l.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "pg" could not release an unsafe transaction connection.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{u.stop()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw t(this.driverName);let n=await this.acquirePooledClient(e,{operation:`pinnedSession`}),r=holdClientErrors(n);return{session:n,lost:r.failure,release:e=>{try{n.release(r.failure()??(e?!0:void 0))}finally{r.stop()}return Promise.resolve()}}}};function createClient(e){u(e,`pg`,O);let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e;return l(e,new PgDriver({namespace:d(e),migrationSessionAttestation:_(e),pool:t||void 0,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement}))}export{PgDriver,createClient};
2
2
  //# sourceMappingURL=pg.mjs.map
package/dist/pg.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, TransactionError } from \"@errors\";\nimport { Pool, type PoolClient, type PoolConfig, types as pgTypes } from \"pg\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PgPoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n/** The keys node-postgres's URL parser reads from the query before the authority. */\nconst URL_QUERY_KEYS = new Set([\"user\", \"password\", \"host\", \"port\"]);\n/** The query parameters node-postgres derives `ssl` from. */\nconst URL_SSL_KEYS = [\"sslmode\", \"sslcert\", \"sslkey\", \"sslrootcert\"];\n\n/**\n * The pool's connection record: the caller's options, with `databaseUrl` as\n * the connection string unless `options.connectionString` names one, and each\n * connection option they set written into that URL so that it wins.\n *\n * node-postgres parses the connection string over the options beside it and\n * fills the connection keys the URL lacks with empty values, so a per-tenant\n * URL without a password lost `options.password` from a secret, and the URL's\n * port replaced `options.port`. Its parser prefers `user`, `password`, `host`\n * and `port` from the query and reads the database from the path, so an\n * explicit key is written there; any other option the query also names is\n * dropped from it, and an explicit `ssl` drops the parameters that derive one.\n * A password callback cannot be written into a URL, and node-postgres would\n * replace it with the URL's password, so one beside a URL is refused.\n */\nfunction connectionRecord(\n options: PoolConfig,\n databaseUrl: string | undefined\n): PoolConfig {\n const given = options.connectionString ?? databaseUrl;\n if (!given) return options;\n if (typeof options.password === \"function\") {\n throw new ClientInitializationError(\n 'Driver \"pg\" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n const connectionString = systemRootAsVerifyFull(given);\n let url: URL | undefined;\n try {\n url = new URL(connectionString);\n } catch {\n url = undefined;\n }\n const entries: [string, unknown][] = Object.entries(options);\n const overrides = entries.filter(\n ([key, value]) =>\n value !== undefined &&\n (URL_QUERY_KEYS.has(key) ||\n key === \"database\" ||\n key === \"ssl\" ||\n (key !== \"connectionString\" && url?.searchParams.has(key)))\n );\n if (overrides.length === 0) return { ...options, connectionString };\n if (url === undefined) {\n throw new ClientInitializationError(\n 'Driver \"pg\" could not read its connection URL to apply the connection options beside it.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Each relation filter body a statement repeats is stated once, in a\n * `WITH`, as the key set its arms test: the answers are the same, the\n * statement smaller, and a server that bounds the relations one statement\n * references (PlanetScale's Neki: 256) accepts it. Defaults to `true`;\n * `false` keeps every body inline.\n */\n sharedRelationBodies?: boolean;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n sharedRelationBodies: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: PgPool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here,\n * with the caller's `databaseUrl` merged in (see `connectionRecord`).\n */\n private readonly connectionOptions: PoolConfig;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(\n this.suppliedPool || connection.host || connection.connectionString\n )\n );\n this.connectionOptions = connectionRecord(connection, options.databaseUrl);\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's pool connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const supplied: unknown = this.suppliedPool\n ? Reflect.get(this.suppliedPool, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n this.connectionOptions.host,\n this.connectionOptions.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<PgPool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const pool = new Pool({ types: utcSafeTypes, ...this.connectionOptions });\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n private readBackgroundPoolFailure(\n pool: PgPool | PgPoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PgPoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: PgPool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // AFTER a proven end, not before it: `end()` disposes idle clients whose\n // own listeners can still re-emit on the pool. If end rejects, the still\n // live pool keeps containment; its pre-start evidence travels on the public\n // disconnect failure, exactly once.\n if (errorState !== undefined) {\n pool.off(\"error\", errorState.retain);\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) =>\n this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n )\n );\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: PgPool | PgPoolClient,\n fn: (tx: PgPoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const poolClient = await this.acquirePooledClient(\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PgPool | PgPoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n // The client's own `error` event is how pg reports a socket that died\n // between or under statements; the pinned session then sends nothing\n // more on it (plan S2). Release destroys it either way.\n lost: clientErrors.failure,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"yjBA4DA,MAEM,eAAkB,GAAkB,EACpC,EAAoC,CACxC,eAAgB,EAAa,IAEzB,CAAC,KAAU,KAAe,KAAM,KAAM,KAAM,KAAK,CAAC,SAAS,EAAI,EAC/D,IAAW,SAEJ,eAEFA,EAAQ,cAAc,EAAc,EAAgB,CAE9D,CAaD,SAAS,2BAAiD,CACxD,IAAI,EAAa,EACX,EAA6B,CACjC,OAAO,EAAO,CACZ,GAAc,EACd,EAAM,kBAAoB,CAAE,QAAO,aAAY,YAAa,GAAM,EAErE,CACD,OAAO,EAqBT,SAAS,iBAAiB,EAAwC,CAChE,IAAI,EACE,OAAU,GAAiB,CAC/B,IAAY,GAGd,OADA,EAAO,GAAG,QAAS,OAAO,CACnB,CACL,YAAe,EACf,SAAY,CACV,EAAO,IAAI,QAAS,OAAO,EAE9B,CAIH,MAAM,EAAiB,IAAI,IAAI,CAAC,OAAQ,WAAY,OAAQ,OAAO,CAAC,CAE9D,EAAe,CAAC,UAAW,UAAW,SAAU,cAAc,CAiBpE,SAAS,iBACP,EACA,EACY,CACZ,IAAM,EAAQ,EAAQ,kBAAoB,EAC1C,GAAI,CAAC,EAAO,OAAO,EACnB,GAAI,OAAO,EAAQ,UAAa,WAC9B,MAAM,IAAI,EACR,+KACA,CAAE,KAAM,CAAE,OAAQ,KAAM,UAAW,gBAAiB,CAAE,CACvD,CAEH,IAAM,EAAmB,EAAuB,EAAM,CAClD,EACJ,GAAI,CACF,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 {"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, TransactionError } from \"@errors\";\nimport {\n Client,\n type ClientConfig,\n Pool,\n type PoolClient,\n type PoolConfig,\n types as pgTypes,\n} from \"pg\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PgPoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n/** The keys node-postgres's URL parser reads from the query before the authority. */\nconst URL_QUERY_KEYS = new Set([\"user\", \"password\", \"host\", \"port\"]);\n/** The query parameters node-postgres derives `ssl` from. */\nconst URL_SSL_KEYS = [\"sslmode\", \"sslcert\", \"sslkey\", \"sslrootcert\"];\n\n/**\n * The pool's connection record: the caller's options, with `databaseUrl` as\n * the connection string unless `options.connectionString` names one, and each\n * connection option they set written into that URL so that it wins.\n *\n * node-postgres parses the connection string over the options beside it and\n * fills the connection keys the URL lacks with empty values, so a per-tenant\n * URL without a password lost `options.password` from a secret, and the URL's\n * port replaced `options.port`. Its parser prefers `user`, `password`, `host`\n * and `port` from the query and reads the database from the path, so an\n * explicit key is written there; any other option the query also names is\n * dropped from it, and an explicit `ssl` drops the parameters that derive one.\n * A password callback cannot be written into a URL, and node-postgres would\n * replace it with the URL's password, so one beside a URL is refused.\n */\nfunction connectionRecord(\n options: PoolConfig,\n databaseUrl: string | undefined\n): PoolConfig {\n const given = options.connectionString ?? databaseUrl;\n if (!given) return options;\n if (typeof options.password === \"function\") {\n throw new ClientInitializationError(\n 'Driver \"pg\" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n const connectionString = systemRootAsVerifyFull(given);\n let url: URL | undefined;\n try {\n url = new URL(connectionString);\n } catch {\n url = undefined;\n }\n const entries: [string, unknown][] = Object.entries(options);\n const overrides = entries.filter(\n ([key, value]) =>\n value !== undefined &&\n (URL_QUERY_KEYS.has(key) ||\n key === \"database\" ||\n key === \"ssl\" ||\n (key !== \"connectionString\" && url?.searchParams.has(key)))\n );\n if (overrides.length === 0) return { ...options, connectionString };\n if (url === undefined) {\n throw new ClientInitializationError(\n 'Driver \"pg\" could not read its connection URL to apply the connection options beside it.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Each relation filter body a statement repeats is stated once, in a\n * `WITH`, as the key set its arms test: the answers are the same, the\n * statement smaller, and a server that bounds the relations one statement\n * references (PlanetScale's Neki: 256) accepts it. Defaults to `true`;\n * `false` keeps every body inline.\n */\n sharedRelationBodies?: boolean;\n /**\n * The most relations (`FROM` items) one statement may reference. Past it, a\n * statement states the recursive filters it repeats as key sets, and then\n * joins the key sets a row tests, as far as it needs to fit: the answers are\n * the same, some plans slower. PlanetScale Neki refuses a statement over\n * 256: absent, a pool this driver makes reads each connection's startup,\n * 256 on Neki and before the first connection, none on plain PostgreSQL (a\n * supplied pool learns from Neki's first refusal). A stated bound always\n * wins. Only where relation bodies are shared.\n */\n relationsPerStatement?: number;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: PgPool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here,\n * with the caller's `databaseUrl` merged in (see `connectionRecord`).\n */\n private readonly connectionOptions: PoolConfig;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n /**\n * The `server_version` the last connection this driver's own pool opened\n * received at startup, read for the relation bound (`boundByServer`); a\n * pool given its own `Client` class, or supplied, is not read.\n */\n private serverVersion: string | undefined;\n private readonly readsServer: boolean;\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(\n this.suppliedPool || connection.host || connection.connectionString\n )\n );\n this.connectionOptions = connectionRecord(connection, options.databaseUrl);\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n this.readsServer =\n this.suppliedPool === undefined &&\n connection.Client === undefined &&\n boundByServer(this.adapter, () => this.serverVersion);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's pool connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const supplied: unknown = this.suppliedPool\n ? Reflect.get(this.suppliedPool, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n this.connectionOptions.host,\n this.connectionOptions.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<PgPool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const pool = new Pool({\n types: utcSafeTypes,\n ...this.connectionOptions,\n ...(this.readsServer ? { Client: this.readingClient() } : {}),\n });\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n /**\n * node-postgres's `Client`, reading each connection's startup: it keeps no\n * parameter status, so the `server_version` that names Neki is read as it\n * arrives, before the connection is handed out (to a statement, or to a\n * transaction before its callback builds any).\n */\n private readingClient(): typeof Client {\n const read = (version: string) => {\n this.serverVersion = version;\n };\n return class extends Client {\n constructor(config?: string | ClientConfig) {\n super(config);\n this.connection.on(\n \"parameterStatus\",\n (status: { parameterName: string; parameterValue: string }) => {\n if (status.parameterName === \"server_version\")\n read(status.parameterValue);\n }\n );\n }\n };\n }\n\n private readBackgroundPoolFailure(\n pool: PgPool | PgPoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PgPoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: PgPool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // AFTER a proven end, not before it: `end()` disposes idle clients whose\n // own listeners can still re-emit on the pool. If end rejects, the still\n // live pool keeps containment; its pre-start evidence travels on the public\n // disconnect failure, exactly once.\n if (errorState !== undefined) {\n pool.off(\"error\", errorState.retain);\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n return this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n );\n });\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: PgPool | PgPoolClient,\n fn: (tx: PgPoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const poolClient = await this.acquirePooledClient(\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PgPool | PgPoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n // The client's own `error` event is how pg reports a socket that died\n // between or under statements; the pinned session then sends nothing\n // more on it (plan S2). Release destroys it either way.\n lost: clientErrors.failure,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"8nBAoEA,MAEM,eAAkB,GAAkB,EACpC,EAAoC,CACxC,eAAgB,EAAa,IAEzB,CAAC,KAAU,KAAe,KAAM,KAAM,KAAM,KAAK,CAAC,SAAS,EAAI,EAC/D,IAAW,SAEJ,eAEFA,EAAQ,cAAc,EAAc,EAAgB,CAE9D,CAaD,SAAS,2BAAiD,CACxD,IAAI,EAAa,EACX,EAA6B,CACjC,OAAO,EAAO,CACZ,GAAc,EACd,EAAM,kBAAoB,CAAE,QAAO,aAAY,YAAa,GAAM,EAErE,CACD,OAAO,EAqBT,SAAS,iBAAiB,EAAwC,CAChE,IAAI,EACE,OAAU,GAAiB,CAC/B,IAAY,GAGd,OADA,EAAO,GAAG,QAAS,OAAO,CACnB,CACL,YAAe,EACf,SAAY,CACV,EAAO,IAAI,QAAS,OAAO,EAE9B,CAIH,MAAM,EAAiB,IAAI,IAAI,CAAC,OAAQ,WAAY,OAAQ,OAAO,CAAC,CAE9D,EAAe,CAAC,UAAW,UAAW,SAAU,cAAc,CAiBpE,SAAS,iBACP,EACA,EACY,CACZ,IAAM,EAAQ,EAAQ,kBAAoB,EAC1C,GAAI,CAAC,EAAO,OAAO,EACnB,GAAI,OAAO,EAAQ,UAAa,WAC9B,MAAM,IAAI,EACR,+KACA,CAAE,KAAM,CAAE,OAAQ,KAAM,UAAW,gBAAiB,CAAE,CACvD,CAEH,IAAM,EAAmB,EAAuB,EAAM,CAClD,EACJ,GAAI,CACF,EAAM,IAAI,IAAI,EAAiB,MACzB,CACN,EAAM,IAAA,GAGR,IAAM,EAD+B,OAAO,QAAQ,EAAQ,CAClC,QACvB,CAAC,EAAK,KACL,IAAU,IAAA,KACT,EAAe,IA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M,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EAiB/D,OAAO,EAA6C,EAhBrC,IAAI,SAAS,CAE1B,UAAW,EAAuB,EAAO,CACzC,4BACE,EAAyC,EAAO,CAElD,KAAM,GAAQ,IAAA,GACd,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC/B,CAAC,CAEiE"}
package/dist/pglite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-B_jh2oaQ.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-B4IWFJfv.mjs";
2
2
  import { PGlite, PGliteOptions, PGliteOptions as PGliteOptions$1, Transaction } from "@electric-sql/pglite";
3
3
 
4
4
  //#region src/drivers/pglite/index.d.ts
@@ -11,6 +11,8 @@ interface PGliteDriverOptions {
11
11
  postgis?: boolean;
12
12
  /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */
13
13
  sharedRelationBodies?: boolean;
14
+ /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */
15
+ relationsPerStatement?: number;
14
16
  /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */
15
17
  namespace?: string;
16
18
  }
package/dist/pglite.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t}from"./bind-parameter-capacity-DiwRmZ1h.mjs";import{d as n,l as r}from"./error-mapping-6op318w6.mjs";import{s as i}from"./execution-context-rJXTRVrJ.mjs";import{n as a}from"./client-BmcHzDBa.mjs";import{a as o,n as s}from"./pinned-session-C79aDzOg.mjs";import{c,d as l,r as u,t as d}from"./driver-Bzc0GCQ4.mjs";import{t as f}from"./postgres-adapter-Ci07rgh_.mjs";import{PGlite as p}from"@electric-sql/pglite";const m=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e])),h={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,namespace:!0};function isPGliteDatabase(e){return`transaction`in e}var PGliteDriver=class extends d{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)})),f(this,t,e)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await p.create(e,n):await p.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,n,r,i,a){let o=i?.operation??a,s=await e.query(n,r,{parsers:m}),c=t(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,a){if(!isPGliteDatabase(e))throw r(this.driverName);return n({run:t=>e.transaction(t),callback:t,phases:i(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!isPGliteDatabase(e))throw r(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw s(e),o(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){c(e,`pglite`,h);let{client:t,dataDir:n,options:r,pgvector:i,postgis:o}=e,s=l(e);return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,sharedRelationBodies:e.sharedRelationBodies,namespace:s}))}export{PGliteDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-BF7gr4_b.mjs";import{d as n,l as r}from"./error-mapping-6op318w6.mjs";import{s as i}from"./execution-context-rJXTRVrJ.mjs";import{n as a}from"./client-Bhl2mWam.mjs";import{a as o,n as s}from"./pinned-session-FYOFV_gB.mjs";import{c,d as l,r as u,t as d}from"./driver-CQQbCQh9.mjs";import{t as f}from"./postgres-adapter-BAqRfWl1.mjs";import{PGlite as p}from"@electric-sql/pglite";const m=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e])),h={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function isPGliteDatabase(e){return`transaction`in e}var PGliteDriver=class extends d{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)})),f(this,t,e)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await p.create(e,n):await p.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,n,r,i,a){let o=i?.operation??a,s=await e.query(n,r,{parsers:m}),c=t(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,a){if(!isPGliteDatabase(e))throw r(this.driverName);return n({run:t=>e.transaction(t),callback:t,phases:i(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!isPGliteDatabase(e))throw r(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw s(e),o(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){c(e,`pglite`,h);let{client:t,dataDir:n,options:r,pgvector:i,postgis:o}=e,s=l(e);return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:s}))}export{PGliteDriver,createClient};
2
2
  //# sourceMappingURL=pglite.mjs.map