viborm 1.3.2 → 1.3.3

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 (180) hide show
  1. package/dist/{adapter-namespace-B8XWzCev.mjs → adapter-namespace-CWLEmon2.mjs} +2 -2
  2. package/dist/{adapter-namespace-B8XWzCev.mjs.map → adapter-namespace-CWLEmon2.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{batch-refs-DoWlPD2h.mjs → batch-refs-DGJPz8-G.mjs} +2 -2
  6. package/dist/{batch-refs-DoWlPD2h.mjs.map → batch-refs-DGJPz8-G.mjs.map} +1 -1
  7. package/dist/{bind-parameter-capacity-qfEejeOX.mjs → bind-parameter-capacity-DiwRmZ1h.mjs} +2 -2
  8. package/dist/{bind-parameter-capacity-qfEejeOX.mjs.map → bind-parameter-capacity-DiwRmZ1h.mjs.map} +1 -1
  9. package/dist/{builder-DhxaVYP2.mjs → builder-D6Ug-zjM.mjs} +2 -2
  10. package/dist/{builder-DhxaVYP2.mjs.map → builder-D6Ug-zjM.mjs.map} +1 -1
  11. package/dist/bun-sql.d.mts +1 -1
  12. package/dist/bun-sql.mjs +1 -1
  13. package/dist/bun-sqlite.d.mts +1 -1
  14. package/dist/bun-sqlite.mjs +1 -1
  15. package/dist/cache/cloudflare-kv.d.mts +1 -1
  16. package/dist/cache/cloudflare-kv.mjs +1 -1
  17. package/dist/cache/memory.d.mts +1 -1
  18. package/dist/cache/memory.mjs +1 -1
  19. package/dist/cache.d.mts +1 -1
  20. package/dist/cache.mjs +1 -1
  21. package/dist/{chain-BjJ_M7EE.mjs → chain-B5IbqLGi.mjs} +2 -2
  22. package/dist/{chain-BjJ_M7EE.mjs.map → chain-B5IbqLGi.mjs.map} +1 -1
  23. package/dist/cli.mjs +1 -1
  24. package/dist/client-BmcHzDBa.mjs +2 -0
  25. package/dist/client-BmcHzDBa.mjs.map +1 -0
  26. package/dist/{client-Df81J4oB.d.mts → client-DR0vYetv.d.mts} +2 -2
  27. package/dist/{client-q6ccRgdO.mjs → client-DjtWangN.mjs} +3 -3
  28. package/dist/{client-q6ccRgdO.mjs.map → client-DjtWangN.mjs.map} +1 -1
  29. package/dist/client.d.mts +1 -1
  30. package/dist/client.mjs +1 -1
  31. package/dist/config.d.mts +1 -1
  32. package/dist/config.mjs +1 -1
  33. package/dist/d1.d.mts +1 -1
  34. package/dist/d1.mjs +1 -1
  35. package/dist/datetime-physical-codec-qKxFtI3B.mjs +2 -0
  36. package/dist/datetime-physical-codec-qKxFtI3B.mjs.map +1 -0
  37. package/dist/{driver-D6_Ik58x.mjs → driver-BvP7eW0A.mjs} +2 -2
  38. package/dist/{driver-D6_Ik58x.mjs.map → driver-BvP7eW0A.mjs.map} +1 -1
  39. package/dist/{driver-Ddt147dK.mjs → driver-Bzc0GCQ4.mjs} +2 -2
  40. package/dist/{driver-Ddt147dK.mjs.map → driver-Bzc0GCQ4.mjs.map} +1 -1
  41. package/dist/driver.d.mts +1 -1
  42. package/dist/driver.mjs +1 -1
  43. package/dist/{error-mapping-C9WgitPi.mjs → error-mapping-6op318w6.mjs} +2 -2
  44. package/dist/error-mapping-6op318w6.mjs.map +1 -0
  45. package/dist/every-WUr3mlvg.mjs +2 -0
  46. package/dist/{every-dpzVDwzu.mjs.map → every-WUr3mlvg.mjs.map} +1 -1
  47. package/dist/{geo-area-codec-CbkmFArQ.mjs → geo-area-codec-BmMmWgU_.mjs} +2 -2
  48. package/dist/{geo-area-codec-CbkmFArQ.mjs.map → geo-area-codec-BmMmWgU_.mjs.map} +1 -1
  49. package/dist/{geo-point-codec-DyEHMdJg.mjs → geo-point-codec-D95uXgDF.mjs} +2 -2
  50. package/dist/{geo-point-codec-DyEHMdJg.mjs.map → geo-point-codec-D95uXgDF.mjs.map} +1 -1
  51. package/dist/{hydration-C2uXmJy6.mjs → hydration-BflrXEIQ.mjs} +2 -2
  52. package/dist/{hydration-C2uXmJy6.mjs.map → hydration-BflrXEIQ.mjs.map} +1 -1
  53. package/dist/{identifier-conversion-C2pwwFOS.mjs → identifier-conversion-Bs7A2GGU.mjs} +2 -2
  54. package/dist/{identifier-conversion-C2pwwFOS.mjs.map → identifier-conversion-Bs7A2GGU.mjs.map} +1 -1
  55. package/dist/{index-D4O0Twvs.d.mts → index-B_jh2oaQ.d.mts} +22 -3
  56. package/dist/index.d.mts +2 -2
  57. package/dist/index.mjs +1 -1
  58. package/dist/instrumentation.d.mts +1 -1
  59. package/dist/instrumentation.mjs +1 -1
  60. package/dist/{key-B7vuAYPG.mjs → key-B89Z4vxn.mjs} +2 -2
  61. package/dist/{key-B7vuAYPG.mjs.map → key-B89Z4vxn.mjs.map} +1 -1
  62. package/dist/{libsql-DUO6vHad.mjs → libsql-C8dn4id0.mjs} +2 -2
  63. package/dist/{libsql-DUO6vHad.mjs.map → libsql-C8dn4id0.mjs.map} +1 -1
  64. package/dist/libsql.d.mts +1 -1
  65. package/dist/libsql.mjs +1 -1
  66. package/dist/{memory-BApsTkt1.mjs → memory-B7CcHS6I.mjs} +2 -2
  67. package/dist/{memory-BApsTkt1.mjs.map → memory-B7CcHS6I.mjs.map} +1 -1
  68. package/dist/migrations/mysql.d.mts +4 -4
  69. package/dist/migrations/mysql.mjs +1 -1
  70. package/dist/migrations/postgres.d.mts +4 -4
  71. package/dist/migrations/postgres.mjs +1 -1
  72. package/dist/migrations/sqlite.d.mts +4 -4
  73. package/dist/migrations/sqlite.mjs +1 -1
  74. package/dist/migrations/tenant.d.mts +2 -2
  75. package/dist/migrations/tenant.mjs +1 -1
  76. package/dist/migrations.d.mts +4 -4
  77. package/dist/migrations.mjs +1 -1
  78. package/dist/mysql-adapter-ABpgFB2N.mjs +2 -0
  79. package/dist/mysql-adapter-ABpgFB2N.mjs.map +1 -0
  80. package/dist/{mysql-D1GlcktG.mjs → mysql-mUmhH9Cf.mjs} +2 -2
  81. package/dist/{mysql-D1GlcktG.mjs.map → mysql-mUmhH9Cf.mjs.map} +1 -1
  82. package/dist/mysql2.d.mts +1 -1
  83. package/dist/mysql2.mjs +1 -1
  84. package/dist/neon-http.d.mts +1 -1
  85. package/dist/neon-http.mjs +1 -1
  86. package/dist/{object-store-BN64q8Zn.d.mts → object-store-Ds9NKRU6.d.mts} +3 -3
  87. package/dist/permissions.d.mts +1 -1
  88. package/dist/permissions.mjs +1 -1
  89. package/dist/permissions.mjs.map +1 -1
  90. package/dist/pg.d.mts +1 -1
  91. package/dist/pg.mjs +1 -1
  92. package/dist/pglite.d.mts +1 -1
  93. package/dist/pglite.mjs +1 -1
  94. package/dist/{physical-CAOaNM4R.mjs → physical-uJfmo4-Z.mjs} +2 -2
  95. package/dist/{physical-CAOaNM4R.mjs.map → physical-uJfmo4-Z.mjs.map} +1 -1
  96. package/dist/{pinned-session-CjvR0Ge2.mjs → pinned-session-C79aDzOg.mjs} +2 -2
  97. package/dist/{pinned-session-CjvR0Ge2.mjs.map → pinned-session-C79aDzOg.mjs.map} +1 -1
  98. package/dist/planetscale.d.mts +1 -1
  99. package/dist/planetscale.mjs +1 -1
  100. package/dist/{planner-8smxUOt9.d.mts → planner-DHZG9Vy7.d.mts} +1 -1
  101. package/dist/{postgres-Be0jMJWI.mjs → postgres-BACQ_wqF.mjs} +2 -2
  102. package/dist/{postgres-Be0jMJWI.mjs.map → postgres-BACQ_wqF.mjs.map} +1 -1
  103. package/dist/{postgres-adapter-C_Mt8lVC.mjs → postgres-adapter-Ci07rgh_.mjs} +2 -2
  104. package/dist/{postgres-adapter-C_Mt8lVC.mjs.map → postgres-adapter-Ci07rgh_.mjs.map} +1 -1
  105. package/dist/postgres-adapter-DaMvNOkx.mjs +2 -0
  106. package/dist/postgres-adapter-DaMvNOkx.mjs.map +1 -0
  107. package/dist/{postgres-result-CYu1dyI_.mjs → postgres-result-D403cLyA.mjs} +2 -2
  108. package/dist/{postgres-result-CYu1dyI_.mjs.map → postgres-result-D403cLyA.mjs.map} +1 -1
  109. package/dist/postgres.d.mts +1 -1
  110. package/dist/postgres.mjs +1 -1
  111. package/dist/{provider-limits-Da00ilvv.mjs → provider-limits-DSv2tYFr.mjs} +2 -2
  112. package/dist/{provider-limits-Da00ilvv.mjs.map → provider-limits-DSv2tYFr.mjs.map} +1 -1
  113. package/dist/result-shape-BKydBCsR.mjs +2 -0
  114. package/dist/result-shape-BKydBCsR.mjs.map +1 -0
  115. package/dist/{rows-JXjhWwyb.mjs → rows-v1VuwOTa.mjs} +2 -2
  116. package/dist/{rows-JXjhWwyb.mjs.map → rows-v1VuwOTa.mjs.map} +1 -1
  117. package/dist/{scalar-CqqZ6jWd.mjs → scalar-Cm7nMFmO.mjs} +2 -2
  118. package/dist/{scalar-CqqZ6jWd.mjs.map → scalar-Cm7nMFmO.mjs.map} +1 -1
  119. package/dist/schema/json.d.mts +1 -1
  120. package/dist/schema/json.mjs +1 -1
  121. package/dist/{schema-Cv-hhpl5.mjs → schema-D3-ScVH6.mjs} +2 -2
  122. package/dist/{schema-Cv-hhpl5.mjs.map → schema-D3-ScVH6.mjs.map} +1 -1
  123. package/dist/{schema-introspection-B2Rvqgut.mjs → schema-introspection-TdJrSaKd.mjs} +2 -2
  124. package/dist/{schema-introspection-B2Rvqgut.mjs.map → schema-introspection-TdJrSaKd.mjs.map} +1 -1
  125. package/dist/schema.d.mts +1 -1
  126. package/dist/schema.mjs +1 -1
  127. package/dist/{select-assembly-BxtETbG9.mjs → select-assembly-uZfvbYjz.mjs} +2 -2
  128. package/dist/select-assembly-uZfvbYjz.mjs.map +1 -0
  129. package/dist/soft-delete.d.mts +1 -1
  130. package/dist/sql-BvHwL73I.mjs +2 -0
  131. package/dist/sql-BvHwL73I.mjs.map +1 -0
  132. package/dist/{sql-EsoN_7Et.d.mts → sql-Q_twK-wW.d.mts} +5 -0
  133. package/dist/sql.d.mts +1 -1
  134. package/dist/sql.mjs +1 -1
  135. package/dist/sqlite-adapter-DPc9T6Lh.mjs +2 -0
  136. package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +1 -0
  137. package/dist/{sqlite-utils-DIOll4P7.mjs → sqlite-utils-BvSlEs5W.mjs} +2 -2
  138. package/dist/{sqlite-utils-DIOll4P7.mjs.map → sqlite-utils-BvSlEs5W.mjs.map} +1 -1
  139. package/dist/sqlite3.d.mts +1 -1
  140. package/dist/sqlite3.mjs +1 -1
  141. package/dist/{standard-sql-mJt0RHHE.mjs → standard-sql-CYdZ_KXH.mjs} +2 -2
  142. package/dist/standard-sql-CYdZ_KXH.mjs.map +1 -0
  143. package/dist/{to-many-BSipkSbK.mjs → to-many-Btc9X5Ga.mjs} +2 -2
  144. package/dist/{to-many-BSipkSbK.mjs.map → to-many-Btc9X5Ga.mjs.map} +1 -1
  145. package/dist/{utils-DjXObbUK.mjs → utils-Qr8ug94X.mjs} +2 -2
  146. package/dist/{utils-DjXObbUK.mjs.map → utils-Qr8ug94X.mjs.map} +1 -1
  147. package/dist/{v-CrJYqdzu.mjs → v-514RME2X.mjs} +2 -2
  148. package/dist/{v-CrJYqdzu.mjs.map → v-514RME2X.mjs.map} +1 -1
  149. package/dist/{validation-BQtO6srU.mjs → validation-CPnrLcjW.mjs} +2 -2
  150. package/dist/{validation-BQtO6srU.mjs.map → validation-CPnrLcjW.mjs.map} +1 -1
  151. package/dist/validation-gwZYm3Yn.mjs +2 -0
  152. package/dist/validation-gwZYm3Yn.mjs.map +1 -0
  153. package/dist/validation.d.mts +1 -1
  154. package/dist/validation.mjs +1 -1
  155. package/dist/{validator-BqzpyNmt.mjs → validator-CQOw7G3q.mjs} +2 -2
  156. package/dist/{validator-BqzpyNmt.mjs.map → validator-CQOw7G3q.mjs.map} +1 -1
  157. package/dist/version-0RVYpih5.mjs +2 -0
  158. package/dist/{version-Dus3if78.mjs.map → version-0RVYpih5.mjs.map} +1 -1
  159. package/package.json +13 -13
  160. package/dist/client-BCgMXn6N.mjs +0 -2
  161. package/dist/client-BCgMXn6N.mjs.map +0 -1
  162. package/dist/datetime-physical-codec-BEqQbIP_.mjs +0 -2
  163. package/dist/datetime-physical-codec-BEqQbIP_.mjs.map +0 -1
  164. package/dist/error-mapping-C9WgitPi.mjs.map +0 -1
  165. package/dist/every-dpzVDwzu.mjs +0 -2
  166. package/dist/mysql-adapter-ClOoHKpn.mjs +0 -2
  167. package/dist/mysql-adapter-ClOoHKpn.mjs.map +0 -1
  168. package/dist/postgres-adapter-BoQ4RRwr.mjs +0 -2
  169. package/dist/postgres-adapter-BoQ4RRwr.mjs.map +0 -1
  170. package/dist/result-shape-DQc-tDJ5.mjs +0 -2
  171. package/dist/result-shape-DQc-tDJ5.mjs.map +0 -1
  172. package/dist/select-assembly-BxtETbG9.mjs.map +0 -1
  173. package/dist/sql-Bhxq9arK.mjs +0 -2
  174. package/dist/sql-Bhxq9arK.mjs.map +0 -1
  175. package/dist/sqlite-adapter-B_LNxPA0.mjs +0 -2
  176. package/dist/sqlite-adapter-B_LNxPA0.mjs.map +0 -1
  177. package/dist/standard-sql-mJt0RHHE.mjs.map +0 -1
  178. package/dist/validation-BamBwne9.mjs +0 -2
  179. package/dist/validation-BamBwne9.mjs.map +0 -1
  180. package/dist/version-Dus3if78.mjs +0 -2
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CK9guf2Z.mjs";import{d as r,f as i,p as a}from"./geo-point-codec-DyEHMdJg.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let r=t===`epochMillis`?n:Math.round((n-s)*o);if(i(r))return new Date(r)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function decodeProviderTimestamp(e){let t=c.exec(e);if(!t)return;let n=t[13]?1-Number(t[1]):Number(t[1]),o=Number(t[2]),s=Number(t[3]),l=Number(t[4]),u=Number(t[5]),d=Number(t[6]),f=Number(t[10]??0),p=Number(t[11]??0),m=Number(t[12]??0);if(!(a(n,o,s)&&r(l,u,d))||f>23||p>59||m>59)return;let h=new Date(0);h.setUTCFullYear(n,o-1,s),h.setUTCHours(l,u,d,Number((t[7]??``).padEnd(3,`0`).slice(0,3)));let g=(f*3600+p*60+m)*1e3,_=h.getTime()-(t[9]===`-`?-g:g);return i(_)?new Date(_):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
2
- //# sourceMappingURL=datetime-physical-codec-BEqQbIP_.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"datetime-physical-codec-BEqQbIP_.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"iKA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OAAO,SAAS,EAAM,CAAG,EAAQ,IAAA,GAC7D,GAAI,EAAS,EAAM,CAAE,CAInB,IAAM,EAAW,OAAO,EAAM,CAC9B,OAAO,OAAO,cAAc,EAAS,CAAG,EAAW,IAAA,IAcvD,SAAgB,uBACd,EACA,EACiB,CACjB,GAAI,IAAS,OAAQ,OAAO,EAC5B,IAAM,EAAoB,KAAK,MAAM,EAAI,CACzC,OAAO,IAAS,cACZ,EACA,EAAoB,EAAuB,EAcjD,SAAgB,uBACd,EACA,EACkB,CAClB,IAAM,EAAW,eAAe,EAAM,CACtC,GAAI,IAAa,IAAA,GAAW,OAC5B,IAAM,EACJ,IAAS,cACL,EACA,KAAK,OAAO,EAAW,GAAyB,EAAqB,CACtE,KAAkB,EAAkB,CACzC,OAAO,IAAI,KAAK,EAAkB,CAGpC,MAAM,EACJ,mIAGF,SAAgB,wBAAwB,EAAiC,CACvE,IAAM,EAAQ,EAAe,KAAK,EAAM,CACxC,GAAI,CAAC,EAAO,OACZ,IAAM,EAAO,EAAM,IAAM,EAAI,OAAO,EAAM,GAAG,CAAG,OAAO,EAAM,GAAG,CAC1D,EAAQ,OAAO,EAAM,GAAG,CACxB,EAAM,OAAO,EAAM,GAAG,CACtB,EAAO,OAAO,EAAM,GAAG,CACvB,EAAS,OAAO,EAAM,GAAG,CACzB,EAAS,OAAO,EAAM,GAAG,CACzB,EAAa,OAAO,EAAM,KAAO,EAAE,CACnC,EAAe,OAAO,EAAM,KAAO,EAAE,CACrC,EAAe,OAAO,EAAM,KAAO,EAAE,CAC3C,GACE,EACE,EAAwB,EAAM,EAAO,EAAI,EACzC,EAAgB,EAAM,EAAQ,EAAO,GAEvC,EAAa,IACb,EAAe,IACf,EAAe,GAEf,OACF,IAAM,EAAS,IAAI,KAAK,EAAE,CAE1B,EAAO,eAAe,EAAM,EAAQ,EAAG,EAAI,CAC3C,EAAO,YACL,EACA,EACA,EACA,QAAQ,EAAM,IAAM,IAAI,OAAO,EAAG,IAAI,CAAC,MAAM,EAAG,EAAE,CAAC,CACpD,CACD,IAAM,GAAU,EAAa,KAAO,EAAe,GAAK,GAAgB,IAClE,EAAQ,EAAO,SAAS,EAAI,EAAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,oBAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"error-mapping-C9WgitPi.mjs","names":["providerSettledBeforeCallback","settledOutcome"],"sources":["../src/errors/constraints.ts","../src/errors/record-series-progress.ts","../src/query-engine/types.ts","../src/errors/logged-errors.ts","../src/drivers/shared/transactions.ts","../src/drivers/driver-error-context.ts","../src/drivers/error-mapping.ts"],"sourcesContent":["import { VibORMError, VibORMErrorCode, type VibORMErrorOptions } from \"./base\";\n\n/**\n * Unique constraint violation\n */\nexport class UniqueConstraintError extends VibORMError {\n static override readonly diagnosticName = \"UniqueConstraintError\";\n\n /** Literal discriminant: this class always carries `UNIQUE_CONSTRAINT`. */\n declare readonly code: typeof VibORMErrorCode.UNIQUE_CONSTRAINT;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.UNIQUE_CONSTRAINT, options);\n }\n}\n\n/**\n * Foreign key constraint violation\n */\nexport class ForeignKeyError extends VibORMError {\n static override readonly diagnosticName = \"ForeignKeyError\";\n\n /** Literal discriminant: this class always carries `FOREIGN_KEY_CONSTRAINT`. */\n declare readonly code: typeof VibORMErrorCode.FOREIGN_KEY_CONSTRAINT;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.FOREIGN_KEY_CONSTRAINT, options);\n }\n}\n\n/**\n * Not-null constraint violation\n */\nexport class NotNullConstraintError extends VibORMError {\n static override readonly diagnosticName = \"NotNullConstraintError\";\n\n /** Literal discriminant: this class always carries `NOT_NULL_CONSTRAINT`. */\n declare readonly code: typeof VibORMErrorCode.NOT_NULL_CONSTRAINT;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.NOT_NULL_CONSTRAINT, options);\n }\n}\n\n/**\n * Check constraint violation\n */\nexport class CheckConstraintError extends VibORMError {\n static override readonly diagnosticName = \"CheckConstraintError\";\n\n /** Literal discriminant: this class always carries `CHECK_CONSTRAINT`. */\n declare readonly code: typeof VibORMErrorCode.CHECK_CONSTRAINT;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.CHECK_CONSTRAINT, options);\n }\n}\n\n/**\n * Value too long for the column's declared type (Prisma P2000)\n *\n * Raised where the database enforces a column length: PostgreSQL SQLSTATE 22001\n * (`string_data_right_truncation`) and MySQL errno 1406 (`ER_DATA_TOO_LONG`).\n *\n * **SQLite raises nothing comparable.** SQLite ignores declared type lengths entirely\n * (`VARCHAR(5)` stores any string), so an over-long value is written, not rejected; the only\n * related error, `SQLITE_TOOBIG`, fires at the ~1GB `SQLITE_MAX_LENGTH` limit and means a\n * different thing. Prisma behaves the same way — quaint's SQLite connector has no arm for it,\n * so it falls through to a generic query error rather than P2000\n * (`quaint/src/connector/sqlite/error.rs`). VibORM therefore keeps `QueryError` on SQLite\n * instead of manufacturing a P2000 that the engine cannot honestly promise.\n */\nexport class ValueTooLongError extends VibORMError {\n static override readonly diagnosticName = \"ValueTooLongError\";\n\n /** Literal discriminant: this class always carries `VALUE_TOO_LONG`. */\n declare readonly code: typeof VibORMErrorCode.VALUE_TOO_LONG;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.VALUE_TOO_LONG, options);\n }\n}\n\n/**\n * Type guard for unique constraint errors\n */\nexport function isUniqueConstraintError(\n error: unknown\n): error is UniqueConstraintError {\n return error instanceof UniqueConstraintError;\n}\n\n/**\n * Type guard for foreign key errors\n */\nexport function isForeignKeyError(error: unknown): error is ForeignKeyError {\n return error instanceof ForeignKeyError;\n}\n\n/**\n * Type guard for not-null constraint errors\n */\nexport function isNotNullConstraintError(\n error: unknown\n): error is NotNullConstraintError {\n return error instanceof NotNullConstraintError;\n}\n\n/**\n * Type guard for check constraint errors\n */\nexport function isCheckConstraintError(\n error: unknown\n): error is CheckConstraintError {\n return error instanceof CheckConstraintError;\n}\n\n/**\n * Type guard for value-too-long errors\n */\nexport function isValueTooLongError(\n error: unknown\n): error is ValueTooLongError {\n return error instanceof ValueTooLongError;\n}\n","import { isVibORMError, type VibORMError } from \"./base\";\nimport {\n getTrustedRecordSeriesProgress,\n type RecordSeriesProgress,\n registerTrustedRecordSeriesProgress,\n sanitizeRecordSeriesProgress,\n} from \"./diagnostics\";\nimport { QueryEngineError } from \"./query\";\n\n/**\n * Enrich the owned failure after segment-atomic execution has stopped. The\n * database executor supplies counters only; this errors-layer boundary validates\n * them, updates direct metadata, and updates trusted serialization together.\n */\nexport function attachRecordSeriesProgress<T extends VibORMError>(\n error: T,\n progress: RecordSeriesProgress\n): T;\nexport function attachRecordSeriesProgress(\n error: unknown,\n progress: RecordSeriesProgress\n): unknown;\nexport function attachRecordSeriesProgress(\n error: unknown,\n progress: RecordSeriesProgress\n): unknown {\n const ownedError = isVibORMError(error)\n ? error\n : new QueryEngineError(\n \"Record-series execution failed at a committed-segment boundary.\",\n error instanceof Error ? { cause: error } : undefined\n );\n // One failure crosses one terminal series boundary. If a wrapper encounters\n // the same error again, retain the first trusted observation so public\n // metadata and trusted serialization cannot diverge.\n const trusted = getTrustedRecordSeriesProgress(ownedError);\n const sanitized = trusted ?? sanitizeRecordSeriesProgress(progress);\n if (!sanitized) return error;\n Object.defineProperty(ownedError.meta, \"recordSeriesProgress\", {\n configurable: true,\n enumerable: true,\n value: sanitized,\n writable: true,\n });\n if (!trusted) {\n registerTrustedRecordSeriesProgress(ownedError, sanitized);\n }\n return ownedError;\n}\n\n/** A committed prefix forbids the routed whole-operation retry. */\nexport function hasCommittedRecordSeriesProgress(error: unknown): boolean {\n if (!isVibORMError(error)) return false;\n const progress = getTrustedRecordSeriesProgress(error);\n return (\n (progress?.committedSegments ?? 0) > 0 ||\n progress?.mayHaveCommittedSegment === true\n );\n}\n","/**\n * Query Engine Types\n *\n * Shared types used across the query engine.\n */\n\nimport type { DatabaseAdapter } from \"@adapters\";\nimport type { QueryExecutionContext } from \"@drivers/driver\";\nimport type { QueryResult } from \"@drivers/types\";\nimport type { Model } from \"@schema/model\";\nimport type { RelationCardinality } from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport type {\n ResolvedRelationIndex,\n ResolvedSlot,\n ResolvedVariantJunctionEdge,\n ResolvedVariantJunctionMember,\n ResolvedVariantRowEdge,\n ResolvedVariantRowMember,\n} from \"@schema/validation/relation-resolution\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\n\n// Re-export errors from unified error hierarchy\nexport {\n NestedWriteError,\n NotFoundError,\n QueryEngineError,\n ValidationError,\n} from \"@errors\";\n// Re-export Sql for convenience\nexport { Sql } from \"@sql\";\n\n// ============================================================\n// BATCH EXECUTION TYPES\n// ============================================================\n\n/** Raw rows/count produced by one mutation result-emulation scope. */\nexport interface MutationQueryResult {\n rows: Record<string, unknown>[];\n rowCount: number;\n}\n\n/**\n * Prepared query ready for batch execution\n */\nexport interface PreparedQuery {\n /** SQL string */\n sql: string;\n /** Query parameters */\n params: unknown[];\n /** Immutable attribution captured when the ORM operation was created. */\n context: QueryExecutionContext;\n}\n\n/**\n * One logical operation expanded into driver-level batch queries.\n */\nexport interface PreparedBatchOperation<T = unknown> {\n queries: PreparedQuery[];\n guards?: PreparedBatchGuard[];\n parseResult: (results: QueryResult<unknown>[]) => T;\n}\n\n/**\n * What a prepared guard publishes when its premise does not hold: the typed\n * failure taxonomy plus the `raceable` bit fixed by the guard's premise class.\n * `batch-error-attribution.ts` is the one algorithm that reads it, and the one\n * place it becomes an `Error`.\n */\nexport interface PreparedGuardFailure {\n readonly kind:\n | \"foreignKey\"\n | \"forbidden\"\n | \"nestedWrite\"\n | \"notFound\"\n | \"query\";\n readonly message: string;\n readonly relation?: string;\n readonly raceable: boolean;\n}\n\n/** Declarative ownership for one assertion query in a prepared operation. */\nexport interface PreparedBatchGuard {\n readonly queryIndex: number;\n readonly premise: \"exists\" | \"notExists\";\n readonly probe: import(\"@sql\").Sql;\n readonly failure: PreparedGuardFailure;\n readonly model: string;\n readonly operation: Operation;\n}\n\n/**\n * Options for engine.prepare()\n */\nexport interface PrepareOptions {\n /** Throw NotFoundError if result is null (for OrThrow variants) */\n throwIfNotFound?: boolean;\n /** Original operation name for error messages */\n originalOperation?: string;\n /**\n * The cache driver manages this execution: the operation completion closes\n * and hands over its cache outcome list.\n */\n skipSpan?: boolean;\n}\n\n/**\n * All supported operations.\n *\n * NOTE — `createManyAndReturn` / `updateManyAndReturn` / `deleteManyAndReturn`\n * are INTERNAL names, not client operations. The public surface has ONE name per\n * bulk family (maintainer decision D-1): `createMany` / `updateMany` /\n * `deleteMany` take an optional `select`, and its presence routes the tree to the\n * row-returning arm. These three tokens name that arm inside the SQL-building\n * substrate (result shape, program lowering, identity helpers); the client never\n * spells them, and they share their family's arg schema.\n */\nexport const OPERATIONS = [\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"create\",\n \"createMany\",\n \"createManyAndReturn\",\n \"update\",\n \"updateMany\",\n \"updateManyAndReturn\",\n \"delete\",\n \"deleteMany\",\n \"deleteManyAndReturn\",\n \"upsert\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n] as const;\n\nexport type Operation = (typeof OPERATIONS)[number];\n\n/** Operations that return BatchPayload { count: number } */\nexport const BATCH_OPERATIONS = [\n \"createMany\",\n \"updateMany\",\n \"deleteMany\",\n] as const;\nexport type BatchOperation = (typeof BATCH_OPERATIONS)[number];\n\n/** Check if operation is a batch operation */\nexport function isBatchOperation(op: Operation): op is BatchOperation {\n return (BATCH_OPERATIONS as readonly string[]).includes(op);\n}\n\n/** Requested fields inside one aggregate JSON carrier. */\nexport interface ExpectedAggregateResultShape {\n /** Undefined only for the scalar `_count: true` result. */\n fields?: ReadonlySet<string>;\n}\n\n/**\n * One arm of a polymorphic projection that the selection reads\n * (`selectedArm`, result/result-shape.ts); an arm `only` excludes is absent.\n */\nexport interface ExpectedPolymorphicVariantShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n}\n\n/** Exact target-specific result contracts for one polymorphic projection. */\nexport interface ExpectedPolymorphicResultShape {\n /** Which carrier the read emitted: the singular tagged CASE, or the collection document. */\n readonly cardinality: \"one\" | \"many\";\n readonly optional: boolean;\n readonly variants: ReadonlyMap<string, ExpectedPolymorphicVariantShape>;\n}\n\n/** Exact public result contract for one ordinary relation projection. */\nexport interface ExpectedRelationResultShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n readonly cardinality: RelationCardinality;\n readonly optional: boolean;\n /**\n * The admitted recurrence of a recursive slot, the same normalized value\n * execution consumes. `shape` is then the ONE repeated node, and the slot's\n * own key recurs inside every occurrence: absent at a numeric cutoff,\n * present on every occurrence of an exhaustive traversal.\n */\n readonly recurrence?: NormalizedRecurrence;\n}\n\n/** Exact raw columns and nested projections expected for one returned row. */\nexport interface ExpectedResultShape {\n /** Raw statement carrier declared by the compiled operation result. */\n carrier: \"rows\" | \"count\" | \"existence\";\n rawKeys: readonly string[];\n /** Scalar whose selected `_distance` expression produced the private column. */\n readonly distanceScalar?: Scalar;\n relations: ReadonlyMap<string, ExpectedRelationResultShape>;\n polymorphic: ReadonlyMap<string, ExpectedPolymorphicResultShape>;\n aggregates: ReadonlyMap<string, ExpectedAggregateResultShape>;\n relationCounts: ReadonlySet<string>;\n}\n\n/**\n * Minimal SQL-construction state shared by related model scopes.\n *\n * `relations` is the ONE index the composition root resolved, passed by\n * identity: a scope answers every topology question by looking this model's\n * slot up in it, so no scope, model or module holds a second topology view\n * (§8.3, §11.4.10).\n */\nexport interface QueryScope extends ScopeSource {\n readonly model: Model<any>;\n readonly nextAlias: () => string;\n readonly rootAlias: string;\n readonly mutationTable?: string;\n}\n\n/**\n * What a root scope is opened FROM: the dialect and the one resolved index.\n *\n * Both the engine and any existing scope satisfy it, which is what lets the\n * index travel by identity from the composition root to every scope without a\n * wrapper that copies it (§10E.10).\n */\nexport interface ScopeSource {\n readonly adapter: DatabaseAdapter;\n readonly relations: ResolvedRelationIndex;\n}\n\n/**\n * A contextual relation reference: the resolved slot the gate published, plus\n * the two facts a builder ADDRESSES it by.\n *\n * It stores no topology. `name` is the slot's own field key — variant-qualified\n * on a member view, which is what keeps step ids deterministic (§8.3) — and\n * `targetModel`/`cardinality` are projections of the resolved EDGE, taken where\n * the reference is made. There is no declared relation type, no foreign-key\n * field list, no optionality flag and no carrier brand to copy, because\n * `resolved.edge` answers each of those questions itself.\n */\nexport interface RelationRef {\n readonly name: string;\n readonly resolved: ResolvedSlot;\n readonly targetModel: Model<any>;\n readonly cardinality: RelationCardinality;\n}\n\n/** The row-held arm: a private `(type, id)` column pair on the owner's row. */\nexport interface VariantRowCarrierSlot {\n readonly slot: ResolvedSlot[\"slot\"];\n readonly edge: ResolvedVariantRowEdge;\n /** The public carrier slot spans the edge's complete member collection. */\n readonly member?: never;\n}\n\n/** The collection arm: one member junction table per configured variant. */\nexport interface VariantJunctionCarrierSlot {\n readonly slot: ResolvedSlot[\"slot\"];\n readonly edge: ResolvedVariantJunctionEdge;\n readonly member?: never;\n}\n\n/**\n * A direct variant relation's carrier slot.\n *\n * Spelled as the UNION of the two arms rather than one shape over the edge\n * union, so that the narrowing guard below SUBTRACTS: a caller that rules out\n * the row-held arm holds the collection arm, with no second test and no cast.\n */\nexport type VariantCarrierSlot =\n | VariantRowCarrierSlot\n | VariantJunctionCarrierSlot;\n\n/**\n * The NARROWING spelling of `carrier.edge.kind === \"variantRowCarrier\"`, for\n * the callers that must pass the CARRIER SLOT itself into a row-held-only slot.\n *\n * It is not a second owner of the question — its body is that one test, and a\n * caller that only needs the answer asks `edge.kind` inline. It exists because\n * the edge is a nested discriminant: testing it narrows the edge reference,\n * never the slot holding it. Same reason, same shape, as\n * `hasPolymorphicMembership` in `relation-data-builder.ts`.\n */\nexport function isVariantRowCarrier(\n carrier: VariantCarrierSlot\n): carrier is VariantRowCarrierSlot {\n return carrier.edge.kind === \"variantRowCarrier\";\n}\n\n/** A bound inverse: one existing member of someone else's row carrier. */\nexport interface VariantRowInverseSlot {\n readonly slot: ResolvedSlot[\"slot\"];\n readonly edge: ResolvedVariantRowEdge;\n readonly member: ResolvedVariantRowMember;\n}\n\n/** A bound inverse: one existing member of someone else's junction carrier. */\nexport interface VariantJunctionInverseSlot {\n readonly slot: ResolvedSlot[\"slot\"];\n readonly edge: ResolvedVariantJunctionEdge;\n readonly member: ResolvedVariantJunctionMember;\n}\n\n/**\n * The two NARROWING spellings of \"this slot is a bound inverse of that carrier\n * family\", for the callers that must hand the slot's edge and its member to one\n * function together.\n *\n * `edge` is a nested discriminant: testing `edge.kind` narrows the edge alone\n * and leaves `member` the union of both families, which is precisely the pairing\n * these two exist to keep. They are two because the two member records are two\n * types — one predicate returning either would hand its caller the union back.\n */\nexport function isVariantRowInverse(\n resolved: ResolvedSlot\n): resolved is VariantRowInverseSlot {\n return (\n resolved.edge.kind === \"variantRowCarrier\" && resolved.member !== undefined\n );\n}\n\nexport function isVariantJunctionInverse(\n resolved: ResolvedSlot\n): resolved is VariantJunctionInverseSlot {\n return (\n resolved.edge.kind === \"variantJunctionCarrier\" &&\n resolved.member !== undefined\n );\n}\n\n/**\n * One member of a row carrier, selected by a payload's public discriminator.\n *\n * The two objects the gate published, carried together — never a copy of their\n * contents, and never a synthesized relation (§8.3, D9). `ref` is the addressing\n * view the write parts spell error sentences and step ids with.\n */\nexport interface SelectedVariantRow {\n readonly carrier: VariantRowCarrierSlot;\n readonly member: ResolvedVariantRowMember;\n readonly ref: RelationRef;\n}\n\n/** One member of a junction carrier, selected by a payload's discriminator. */\nexport interface SelectedVariantMember {\n readonly carrier: VariantJunctionCarrierSlot;\n readonly member: ResolvedVariantJunctionMember;\n readonly ref: RelationRef;\n}\n\n// ============================================================\n// NARROWER TYPE DEFINITIONS\n// These provide better autocomplete and error messages\n// ============================================================\n\n/**\n * Scalar filter operators for where clauses\n */\nexport interface ScalarFilter<T = unknown> {\n equals?: T | null;\n not?: T | ScalarFilter<T> | null;\n in?: T[];\n notIn?: T[];\n lt?: T;\n lte?: T;\n gt?: T;\n gte?: T;\n}\n\n/**\n * String-specific filter operators\n */\nexport interface StringFilter extends ScalarFilter<string> {\n contains?: string;\n startsWith?: string;\n endsWith?: string;\n mode?: \"default\" | \"insensitive\";\n}\n\n/**\n * Array/list filter operators\n */\nexport interface ArrayFilter<T = unknown> {\n has?: T;\n hasEvery?: T[];\n hasSome?: T[];\n isEmpty?: boolean;\n}\n\n/**\n * Relation filter for to-one relations\n */\nexport interface ToOneRelationFilter {\n is?: WhereInput | null;\n isNot?: WhereInput | null;\n}\n\n/**\n * Relation filter for to-many relations\n */\nexport interface ToManyRelationFilter {\n some?: WhereInput;\n every?: WhereInput;\n none?: WhereInput;\n}\n\n/**\n * Where input for filtering records\n */\nexport interface WhereInput {\n AND?: WhereInput | WhereInput[];\n OR?: WhereInput[];\n NOT?: WhereInput | WhereInput[];\n [field: string]:\n | unknown\n | ScalarFilter\n | StringFilter\n | ArrayFilter\n | ToOneRelationFilter\n | ToManyRelationFilter\n | WhereInput\n | WhereInput[]\n | undefined;\n}\n\n/**\n * Order by direction\n */\nexport type SortOrder = \"asc\" | \"desc\";\n\n/**\n * Order by input for sorting\n */\nexport interface OrderByInput {\n [field: string]: SortOrder | OrderByInput;\n}\n\n/**\n * Select input for field selection\n */\nexport interface SelectInput {\n [field: string]: boolean | SelectInput | IncludeInput;\n}\n\n/**\n * Include input for relation inclusion\n */\nexport interface IncludeInput {\n [relation: string]:\n | boolean\n | {\n select?: SelectInput;\n include?: IncludeInput;\n where?: WhereInput;\n orderBy?: OrderByInput | OrderByInput[];\n take?: number;\n skip?: number;\n };\n}\n\n/**\n * Numeric update operations\n */\nexport interface NumericUpdateOperations<T = number> {\n set?: T;\n increment?: T;\n decrement?: T;\n multiply?: T;\n divide?: T;\n}\n\n/**\n * Array update operations\n */\nexport interface ArrayUpdateOperations<T = unknown> {\n set?: T[];\n push?: T | T[];\n}\n\n/**\n * Update data input\n */\nexport interface UpdateInput {\n [field: string]: unknown | NumericUpdateOperations | ArrayUpdateOperations;\n}\n\n/**\n * Create data input\n */\nexport interface CreateInput {\n [field: string]: unknown;\n}\n\n/**\n * Aggregate filter for HAVING clause\n */\nexport interface AggregateFilter {\n equals?: number;\n not?: number | null;\n gt?: number;\n gte?: number;\n lt?: number;\n lte?: number;\n in?: number[];\n notIn?: number[];\n}\n\n/**\n * Having input for groupBy\n */\nexport interface HavingInput {\n _count?: Record<string, AggregateFilter>;\n _avg?: Record<string, AggregateFilter>;\n _sum?: Record<string, AggregateFilter>;\n _min?: Record<string, AggregateFilter>;\n _max?: Record<string, AggregateFilter>;\n [field: string]:\n | unknown\n | AggregateFilter\n | Record<string, AggregateFilter>\n | undefined;\n}\n","/**\n * Cross-layer record of errors core has already selected for a log.\n *\n * One failure crosses two observers: the driver's statement completion selects\n * the failing *statement* for the error log and the query engine's operation\n * completion selects the failing *operation*. Both would report the same error\n * object, so the statement completion marks what it selected, synchronously,\n * and the operation completion skips anything already marked. Core selects and\n * marks; the official instrumentation extension only formats. The record lives\n * in `src/errors/` so that core has no runtime edge into the extension.\n *\n * ## Why a module-scoped WeakSet, and not the instrumentation context\n *\n * The de-duplication marker does not belong in the instrumentation context: it\n * describes one thrown error, not the client-wide observer configuration, and\n * the same context serves concurrent operations.\n *\n * ## Why not a property on the error\n *\n * The error is handed to the caller. Stamping it (the former\n * `Object.defineProperty(error, \"logged\", …)`) made an internal\n * de-duplication convention part of the public error's shape, and it could not\n * mark a frozen error at all — such an error was logged twice.\n *\n * ## Serverless note\n *\n * `src/instrumentation/AGENTS.md` Rule 3 keeps mutable state out of module\n * scope so nothing survives a request in a reused isolate. A `WeakSet` holds\n * no strong reference: an entry disappears with the error that keyed it, and\n * an error object never outlives the request that threw it. There is nothing\n * here to go stale, and nothing to grow.\n */\n\nconst loggedErrors = new WeakSet<Error>();\n\n/** Record that core has selected this error for a log. */\nexport function markErrorLogged(error: Error): void {\n loggedErrors.add(error);\n}\n\n/** Preserve the report record when package code replaces one failure with its successor. */\nexport function transferLoggedErrorEvidence(\n source: Error,\n successor: Error\n): void {\n if (loggedErrors.has(source)) loggedErrors.add(successor);\n}\n\n/** Whether core has already selected this error for a log. */\nexport function isErrorLogged(error: Error): boolean {\n return loggedErrors.has(error);\n}\n","import { TransactionError } from \"@errors\";\nimport type { TransactionPhaseNotifications } from \"../execution-context\";\n\nexport function nestedTransactionDispatchError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" received nested provider state outside TransactionBoundDriver.`,\n { meta: { driver: driverName, method: \"$transaction\" } }\n );\n}\n\nexport function unsupportedCallbackTransactionError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" does not support callback transactions.`,\n { meta: { driver: driverName, method: \"$transaction(callback)\" } }\n );\n}\n\n// A broken provider lifecycle cannot prove whether its handle remains safe.\nexport class ProviderTransactionContractError extends TransactionError {}\n\ntype LifecycleStep = () => unknown | Promise<unknown>;\n\nexport interface TransactionLifecycle<T> {\n readonly begin: LifecycleStep;\n readonly callback: () => Promise<T>;\n readonly commit: LifecycleStep;\n readonly rollback: LifecycleStep;\n readonly close?: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\nexport interface ProviderManagedTransaction<T, TTransaction> {\n readonly run: (\n callback: (tx: TTransaction) => Promise<T>\n ) => Promise<unknown>;\n readonly callback: (tx: TTransaction) => Promise<T>;\n readonly close: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\ntype ProviderCallbackOutcome<T> =\n | { readonly status: \"pending\" }\n | { readonly status: \"fulfilled\"; readonly value: T }\n | { readonly error: unknown; readonly status: \"rejected\" };\n\n/** Close provider-owned transaction state when its own cleanup/finalization fails. */\nexport async function runProviderManagedTransaction<T, TTransaction>(\n lifecycle: ProviderManagedTransaction<T, TTransaction>\n): Promise<T> {\n let callbackCallCount = 0;\n let callbackOutcome: ProviderCallbackOutcome<T> = {\n status: \"pending\",\n };\n const readCallbackOutcome = (): ProviderCallbackOutcome<T> => callbackOutcome;\n let callbackPromise: Promise<T> | undefined;\n let closeAttempted = false;\n const capturedCloseFailures: unknown[] = [];\n const closeBeforeCallbackDrain = async () => {\n closeAttempted = true;\n try {\n await lifecycle.close();\n } catch (error) {\n capturedCloseFailures.push(error);\n }\n };\n try {\n await lifecycle.run((tx) => {\n callbackCallCount++;\n if (callbackCallCount > 1) {\n throw new ProviderTransactionContractError(\n \"Transaction provider invoked the transaction callback more than once.\"\n );\n }\n callbackPromise = (async () => {\n try {\n const value = await lifecycle.callback(tx);\n lifecycle.phases?.readyToCommit();\n callbackOutcome = { status: \"fulfilled\", value };\n return value;\n } catch (error) {\n callbackOutcome = { status: \"rejected\", error };\n throw error;\n }\n })();\n callbackPromise.catch(() => undefined);\n return callbackPromise;\n });\n } catch (error) {\n const providerSettledBeforeCallback =\n callbackPromise !== undefined &&\n readCallbackOutcome().status === \"pending\";\n if (callbackPromise && providerSettledBeforeCallback) {\n await closeBeforeCallbackDrain();\n await callbackPromise.catch(() => undefined);\n }\n const settledOutcome = readCallbackOutcome();\n if (\n settledOutcome.status === \"rejected\" &&\n !providerSettledBeforeCallback &&\n error === settledOutcome.error\n ) {\n throw error;\n }\n const primaryFailure =\n settledOutcome.status === \"rejected\" ? settledOutcome.error : error;\n const cleanupFailures: unknown[] = [];\n if (providerSettledBeforeCallback) {\n cleanupFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider settled before the transaction callback settled.\"\n )\n );\n }\n if (\n settledOutcome.status === \"rejected\" &&\n error !== settledOutcome.error\n ) {\n cleanupFailures.push(\n ...readTransactionCleanupFailures(error, settledOutcome.error)\n );\n }\n cleanupFailures.push(...capturedCloseFailures);\n const cleanupSteps = cleanupFailures.map(failureStep);\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n const providerSettledBeforeCallback =\n callbackPromise !== undefined && readCallbackOutcome().status === \"pending\";\n if (callbackPromise && providerSettledBeforeCallback) {\n await closeBeforeCallbackDrain();\n await callbackPromise.catch(() => undefined);\n }\n const settledOutcome = readCallbackOutcome();\n const contractFailures: TransactionError[] = [];\n if (callbackCallCount !== 1) {\n contractFailures.push(\n new ProviderTransactionContractError(\n callbackCallCount === 0\n ? \"Transaction provider completed without invoking the transaction callback.\"\n : \"Transaction provider invoked the transaction callback more than once.\"\n )\n );\n }\n if (providerSettledBeforeCallback) {\n contractFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider completed before the transaction callback settled.\"\n )\n );\n }\n if (settledOutcome.status === \"rejected\") {\n contractFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider resolved after the transaction callback rejected.\"\n )\n );\n }\n if (contractFailures.length > 0) {\n const primaryFailure =\n settledOutcome.status === \"rejected\"\n ? settledOutcome.error\n : contractFailures.shift();\n const cleanupSteps = [\n ...contractFailures.map(failureStep),\n ...capturedCloseFailures.map(failureStep),\n ];\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n if (settledOutcome.status !== \"fulfilled\") {\n return throwAfterCleanup(\n new ProviderTransactionContractError(\n \"Transaction callback outcome was not recorded.\"\n ),\n [lifecycle.close]\n );\n }\n lifecycle.phases?.committed();\n return settledOutcome.value;\n}\n\n/** Run a top-level provider transaction without losing cleanup failures. */\nexport async function runTransactionLifecycle<T>(\n lifecycle: TransactionLifecycle<T>\n): Promise<T> {\n try {\n await lifecycle.begin();\n } catch (error) {\n return throwAfterCleanup(error, lifecycle.close ? [lifecycle.close] : []);\n }\n\n let result: T;\n try {\n result = await lifecycle.callback();\n } catch (error) {\n const cleanup = [lifecycle.rollback];\n if (lifecycle.close) cleanup.push(lifecycle.close);\n return throwAfterCleanup(error, cleanup);\n }\n\n lifecycle.phases?.readyToCommit();\n\n try {\n await lifecycle.commit();\n } catch (error) {\n const cleanup = [lifecycle.rollback];\n if (lifecycle.close) cleanup.push(lifecycle.close);\n return throwAfterCleanup(error, cleanup);\n }\n\n lifecycle.phases?.committed();\n\n if (lifecycle.close) await lifecycle.close();\n return result;\n}\n\nexport const runSavepoint = async <T>(\n executeStatement: (statement: string) => unknown | Promise<unknown>,\n fn: () => Promise<T>\n): Promise<T> => {\n const savepointName = `sp_${crypto.randomUUID().replace(/-/g, \"\")}`;\n await executeStatement(`SAVEPOINT ${savepointName}`);\n\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n return throwAfterCleanup(error, [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ]);\n }\n\n try {\n await executeStatement(`RELEASE SAVEPOINT ${savepointName}`);\n } catch (error) {\n return throwAfterCleanup(error, [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ]);\n }\n return result;\n};\n\nexport function createTransactionCleanupError(\n primaryFailure: unknown,\n cleanupFailures: readonly unknown[]\n): AggregateError {\n return new AggregateError(\n [primaryFailure, ...cleanupFailures],\n readFailureMessage(primaryFailure),\n { cause: primaryFailure }\n );\n}\n\nexport function readTransactionCleanupFailures(\n error: unknown,\n primaryFailure: unknown\n): readonly unknown[] {\n try {\n if (!(error instanceof AggregateError) || error.cause !== primaryFailure) {\n return [error];\n }\n return error.errors[0] === primaryFailure ? error.errors.slice(1) : [error];\n } catch {\n return [error];\n }\n}\n\nasync function throwAfterCleanup(\n primaryFailure: unknown,\n cleanupSteps: readonly LifecycleStep[]\n): Promise<never> {\n const cleanupFailures: unknown[] = [];\n for (const cleanupStep of cleanupSteps) {\n try {\n await cleanupStep();\n } catch (error) {\n cleanupFailures.push(error);\n }\n }\n\n if (cleanupFailures.length > 0) {\n throw createTransactionCleanupError(primaryFailure, cleanupFailures);\n }\n throw primaryFailure;\n}\n\nfunction failureStep(failure: unknown): LifecycleStep {\n return () => {\n throw failure;\n };\n}\n\nfunction readFailureMessage(error: unknown): string {\n try {\n return error instanceof Error && typeof error.message === \"string\"\n ? error.message\n : \"Transaction failed\";\n } catch {\n return \"Transaction failed\";\n }\n}\n","import {\n CacheConfigurationError,\n CacheInvalidKeyError,\n CacheInvalidTTLError,\n CacheOperationNotCacheableError,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n type DiagnosticDisclosure,\n FeatureNotSupportedError,\n ForbiddenError,\n ForeignKeyError,\n getTrustedErrorCause,\n getTrustedErrorDisclosure,\n InvalidTransactionInputError,\n MigrationError,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n NotNullConstraintError,\n PendingOperationError,\n QueryEngineError,\n QueryError,\n resolveDiagnosticDisclosure,\n sanitizeErrorMetadata,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n ValidationError,\n type ValidationErrorSource,\n ValueTooLongError,\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"@errors\";\nimport { OPERATIONS, type Operation } from \"@query-engine/types\";\nimport {\n isArrayValue,\n isError,\n isRecord,\n isTrustedCode,\n safeArrayLength,\n safeOwnPropertyDescriptor,\n sanitizeSqlState,\n} from \"../errors/diagnostic-safety\";\nimport { transferLoggedErrorEvidence } from \"../errors/logged-errors\";\nimport {\n readSuppressedFailures,\n withSuppressedFailure,\n} from \"./shared/suppressed-failure\";\nimport { ProviderTransactionContractError } from \"./shared/transactions\";\nimport type { Dialect } from \"./types\";\n\nexport interface DriverErrorShape {\n code?: string | number;\n bodyCode?: string | number;\n errno?: number;\n stringErrno?: string;\n constraint?: string;\n table?: string;\n column?: string;\n constraint_name?: string;\n table_name?: string;\n column_name?: string;\n sqlState?: string;\n sqlstate?: string;\n status?: string | number;\n statusCode?: string | number;\n}\n\nexport interface DriverErrorContext {\n driverName: string;\n /**\n * The SQL family that raised the error, when the normalizing call site knows\n * it. Only numeric provider codes need it: a symbolic name or a message\n * symbol identifies its own provider, but a bare integer does not.\n */\n dialect?: Dialect;\n model?: string;\n operation?: Operation | string;\n correlationId?: string;\n statementIndex?: number;\n query?: string;\n params?: unknown[];\n diagnostics?: DiagnosticDisclosure;\n callsite?: string;\n forceContext?: boolean;\n}\n\nconst EXECUTION_META_KEYS = [\n \"driver\",\n \"model\",\n \"operation\",\n \"correlationId\",\n \"callsite\",\n \"query\",\n \"params\",\n] as const;\nconst MYSQL_SQLSTATE_IN_MESSAGE_PATTERN = /\\(sqlstate ([^)]+)\\)/i;\nconst MYSQL_KEY_IN_MESSAGE_PATTERN = /for key '([^']+)'/;\n\nexport function readProperty(value: object, key: string): unknown {\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n\nexport function attachExecutionContext(\n error: VibORMError,\n context: DriverErrorContext\n): VibORMError {\n const snapshot = VibORMError.prototype.toJSON.call(error);\n const snapshotMeta = readProperty(snapshot, \"meta\");\n const mergedMeta = sanitizeErrorMetadata(\n isRecord(snapshotMeta) ? snapshotMeta : {},\n context.diagnostics\n );\n const forceContext = context.forceContext !== false;\n if (!forceContext) {\n if (\n resolveDiagnosticDisclosure(context.diagnostics).includeCallsite &&\n context.callsite\n )\n mergedMeta.callsite = context.callsite;\n return cloneVibORMError(error, mergedMeta, snapshot, context.diagnostics);\n }\n const additions = sanitizeErrorMetadata(\n buildMeta({}, context, \"\"),\n context.diagnostics\n );\n for (const key of EXECUTION_META_KEYS) {\n Reflect.deleteProperty(mergedMeta, key);\n }\n for (const key of Reflect.ownKeys(additions)) {\n if (typeof key !== \"string\") continue;\n Object.defineProperty(mergedMeta, key, {\n configurable: true,\n enumerable: true,\n value: additions[key],\n writable: true,\n });\n }\n return cloneVibORMError(error, mergedMeta, snapshot, context.diagnostics);\n}\n\n/** Clone one trusted failure with the exact durable write state now known. */\nexport function attachCommitCertainty(\n error: VibORMError,\n commitCertainty: NonNullable<VibORMErrorMeta[\"commitCertainty\"]>\n): VibORMError {\n const snapshot = VibORMError.prototype.toJSON.call(error);\n const snapshotMeta = readProperty(snapshot, \"meta\");\n const diagnostics = getTrustedErrorDisclosure(error);\n const meta = sanitizeErrorMetadata(\n isRecord(snapshotMeta) ? snapshotMeta : {},\n diagnostics\n );\n meta.commitCertainty = commitCertainty;\n return cloneVibORMError(error, meta, snapshot, diagnostics);\n}\n\nfunction cloneVibORMError(\n error: VibORMError,\n meta: VibORMErrorMeta,\n snapshot: Record<string, unknown>,\n diagnostics: DiagnosticDisclosure | undefined\n): VibORMError {\n // The clone runs only the base constructor under the chosen class.\n // ValidationError owns state that constructor cannot rebuild, so it is\n // rebuilt from its snapshot here; every other class keeps its identity only\n // when it is one VibORM defines without such state.\n let cloneConstructor: unknown = VibORMError;\n if (error instanceof ValidationError) {\n const validationClone = cloneValidationError(error, meta, diagnostics);\n if (validationClone) {\n transferLoggedErrorEvidence(error, validationClone);\n return transferSuppressedFailureEvidence(error, validationClone);\n }\n } else {\n cloneConstructor = getCloneConstructor(error);\n }\n const message =\n typeof snapshot.message === \"string\"\n ? snapshot.message\n : \"VibORM operation failed\";\n const code = isVibORMErrorCode(snapshot.code)\n ? snapshot.code\n : VibORMErrorCode.INTERNAL_ERROR;\n const cause = getTrustedErrorCause(error);\n const options = {\n ...(isError(cause) ? { cause } : {}),\n diagnostics,\n meta,\n };\n const newTarget =\n typeof cloneConstructor === \"function\" ? cloneConstructor : VibORMError;\n let candidate: unknown;\n try {\n candidate = Reflect.construct(\n VibORMError,\n [message, code, options],\n newTarget\n );\n } catch {\n candidate = new VibORMError(message, code, options);\n }\n const clonedError =\n candidate instanceof VibORMError\n ? candidate\n : new VibORMError(message, code, options);\n transferLoggedErrorEvidence(error, clonedError);\n return transferSuppressedFailureEvidence(error, clonedError);\n}\n\n/**\n * Carry the evidence a failure retained onto the failure that replaces it, so\n * rebuilding a primary (a clone, a mapped provider error) never drops it.\n */\nexport function transferSuppressedFailureEvidence(\n source: unknown,\n target: VibORMError\n): VibORMError {\n for (const failure of readSuppressedFailures(source)) {\n withSuppressedFailure(target, failure);\n }\n return target;\n}\n\nfunction cloneValidationError(\n error: ValidationError,\n meta: VibORMErrorMeta,\n diagnostics: DiagnosticDisclosure | undefined\n): ValidationError | undefined {\n const serialized = VibORMError.prototype.toJSON.call(error);\n const source = snapshotValidationSource(readProperty(serialized, \"source\"));\n const issues = readProperty(serialized, \"issues\");\n if (!(source && isArrayValue(issues))) return undefined;\n const issueSnapshot = snapshotValidationIssues(issues);\n const cause = getTrustedErrorCause(error);\n return new ValidationError(source, issueSnapshot, {\n ...(isError(cause) ? { cause } : {}),\n diagnostics,\n meta,\n });\n}\n\nfunction snapshotValidationSource(\n value: unknown\n): ValidationErrorSource | undefined {\n if (!isRecord(value)) return undefined;\n const kind = readProperty(value, \"kind\");\n if (kind === \"operation\") {\n const operation = readProperty(value, \"operation\");\n const model = readProperty(value, \"model\");\n if (!isOperation(operation)) return undefined;\n return {\n kind,\n operation,\n ...(typeof model === \"string\" ? { model } : {}),\n };\n }\n if (kind === \"registry\") {\n const model = readProperty(value, \"model\");\n const property = readProperty(value, \"property\");\n return {\n kind,\n ...(typeof model === \"string\" ? { model } : {}),\n ...(typeof property === \"string\" ? { property } : {}),\n };\n }\n if (kind === \"schema-builder\") {\n const builder = readProperty(value, \"builder\");\n const path = readProperty(value, \"path\");\n if (!(typeof builder === \"string\" && typeof path === \"string\")) {\n return undefined;\n }\n return { kind, builder, path };\n }\n if (kind === \"json-schema\") {\n const target = readProperty(value, \"target\");\n const schemaType = readProperty(value, \"schemaType\");\n return {\n kind,\n ...(typeof target === \"string\" ? { target } : {}),\n ...(typeof schemaType === \"string\" ? { schemaType } : {}),\n };\n }\n return undefined;\n}\n\nfunction snapshotValidationIssues(value: unknown[]): Array<{\n path: string;\n message: string;\n}> {\n const issues: Array<{ path: string; message: string }> = [];\n const length = Math.min(safeArrayLength(value), 128);\n for (let index = 0; index < length; index += 1) {\n const descriptor = safeOwnPropertyDescriptor(value, String(index));\n if (!(descriptor && \"value\" in descriptor && isRecord(descriptor.value))) {\n continue;\n }\n const path = readProperty(descriptor.value, \"path\");\n const message = readProperty(descriptor.value, \"message\");\n if (typeof path !== \"string\" || typeof message !== \"string\") continue;\n issues.push({ path, message });\n }\n return issues;\n}\n\nfunction isOperation(value: unknown): value is Operation {\n return (\n typeof value === \"string\" &&\n (OPERATIONS as readonly string[]).includes(value)\n );\n}\n\n// Every VibORM error class whose state the base constructor rebuilds, so its\n// identity survives cloning. A class outside it — a caller's subclass, which\n// may own state no clone can reconstruct, or SchemaValidationError with its\n// issues — degrades to the base class rather than a hollow instance that\n// passes \\`instanceof\\` but breaks on its own members. ValidationError is\n// absent on purpose: it is rebuilt from its snapshot.\nconst CLONE_CONSTRUCTORS = [\n CacheConfigurationError,\n CacheInvalidKeyError,\n CacheInvalidTTLError,\n CacheOperationNotCacheableError,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n FeatureNotSupportedError,\n ForbiddenError,\n ForeignKeyError,\n InvalidTransactionInputError,\n MigrationError,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n NotNullConstraintError,\n PendingOperationError,\n QueryEngineError,\n QueryError,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n ValueTooLongError,\n] as const;\n\nfunction getCloneConstructor(error: VibORMError): unknown {\n try {\n const prototype = Object.getPrototypeOf(error);\n if (prototype === ProviderTransactionContractError.prototype)\n return TransactionError;\n return (\n CLONE_CONSTRUCTORS.find((ctor) => ctor.prototype === prototype) ??\n VibORMError\n );\n } catch {\n return VibORMError;\n }\n}\n\n// The code shape rule, not membership in the enum object: reading the enum's\n// values would keep the whole object in every bundle, while member accesses\n// are inlined. The snapshot already passed the same rule when it was taken.\nfunction isVibORMErrorCode(value: unknown): value is VibORMErrorCode {\n return isTrustedCode(value);\n}\n\nexport function buildMeta(\n error: DriverErrorShape,\n context: DriverErrorContext,\n message: string\n): VibORMErrorMeta {\n const meta: VibORMErrorMeta = { driver: context.driverName };\n const disclosure = resolveDiagnosticDisclosure(context.diagnostics);\n\n if (disclosure.includeCallsite && context.callsite)\n meta.callsite = context.callsite;\n if (context.model) meta.model = context.model;\n if (context.operation) meta.operation = context.operation;\n if (context.correlationId) meta.correlationId = context.correlationId;\n if (context.statementIndex !== undefined) {\n meta.statementIndex = context.statementIndex;\n }\n if (disclosure.includeSql && context.query !== undefined) {\n meta.query = context.query;\n }\n if (disclosure.includeParams && context.params !== undefined) {\n meta.params = context.params;\n }\n\n const providerCode = error.code ?? error.bodyCode;\n if (typeof providerCode === \"string\" || typeof providerCode === \"number\") {\n meta.providerCode = providerCode;\n }\n if (typeof error.errno === \"number\") meta.providerErrno = error.errno;\n const sqlState =\n error.sqlState ??\n error.sqlstate ??\n sanitizeSqlState(providerCode) ??\n MYSQL_SQLSTATE_IN_MESSAGE_PATTERN.exec(message)?.[1];\n if (typeof sqlState === \"string\") meta.providerSqlState = sqlState;\n const status = error.status ?? error.statusCode;\n if (typeof status === \"string\" || typeof status === \"number\") {\n meta.providerStatus = status;\n }\n\n const constraint = error.constraint ?? error.constraint_name;\n const table = error.table ?? error.table_name;\n const column = error.column ?? error.column_name;\n if (constraint) meta.constraint = constraint;\n if (table) meta.table = table;\n if (column) meta.columns = [column];\n\n if (!meta.constraint) {\n const key = MYSQL_KEY_IN_MESSAGE_PATTERN.exec(message)?.[1];\n if (key) {\n const dotIndex = key.indexOf(\".\");\n if (dotIndex === -1) {\n meta.constraint = key;\n } else {\n meta.constraint = key.slice(dotIndex + 1);\n if (!meta.table) meta.table = key.slice(0, dotIndex);\n }\n }\n }\n return meta;\n}\n","import {\n attachRecordSeriesProgress,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n type DiagnosticDisclosure,\n ForeignKeyError,\n getTrustedRecordSeriesProgress,\n isVibORMError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NotNullConstraintError,\n QueryError,\n TransactionError,\n type TransactionErrorCode,\n UniqueConstraintError,\n ValueTooLongError,\n type VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"@errors\";\nimport {\n attachExecutionContext,\n buildMeta,\n type DriverErrorContext,\n type DriverErrorShape,\n readProperty,\n transferSuppressedFailureEvidence,\n} from \"./driver-error-context\";\nimport type { Dialect } from \"./types\";\n\n// Stop at \":\" so D1's \"users.email: SQLITE_CONSTRAINT\" suffix isn't captured\nconst BUN_SQL_STATE_PATTERN = /^[0-9A-Z]{5}$/;\nconst PROVIDER_CONNECTION_CODE_PATTERN =\n /^(?:CONNECTION_(?:CLOSED|DESTROYED|ENDED)$|ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|EPIPE$|ERR_POSTGRES_CONNECTION_|08[0-9A-Z]{3}$|57P0[123]$)/;\nconst SQLITE_CONSTRAINT_COLUMNS_PATTERN = /constraint failed: ([^:]+)/;\n// Symbolic BUSY/LOCKED codes are the exact base name or an underscore-delimited\n// extended family member. The delimiter is load-bearing: startsWith accepted\n// unrelated provider codes such as SQLITE_BUSYWORK and SQLITE_LOCKEDNESS.\nconst SQLITE_CONTENTION_FAMILY_PATTERN =\n /^SQLITE_(?:BUSY|LOCKED)(?:_[A-Z0-9]+)+$/;\nconst ASCII_PROVIDER_SYMBOL_PATTERN = /[A-Za-z0-9_]+/g;\n// An extended result code is `base | (sub << 8)`, so the whole family keeps its\n// base in the low byte. That byte alone proves nothing across providers —\n// MySQL errno 1029 also ends in 5 — so numeric recognition needs the dialect.\nconst SQLITE_BASE_CODE_MASK = 0xff;\nconst SQLITE_BUSY_BASE_CODE = 5;\nconst SQLITE_LOCKED_BASE_CODE = 6;\nconst MYSQL_ERRNO_IN_MESSAGE_PATTERN = /\\(errno (\\d+)\\)/;\n// Batch-plan assertions (adapter.assertions) fail on purpose with a\n// dialect-specific trick: division by zero on PG (SQLSTATE 22012), invalid\n// JSON via JSON_EXTRACT/json_extract on MySQL (errno 3141) and SQLite\n// (\"malformed JSON\"). The statements are identifiable by their column alias.\nexport const ASSERTION_MARKER = \"__viborm_assert__\";\n/**\n * A write judging the row it produces (`adapter.assertions.holds`) carries\n * this alias, and fails on its own refusal: the sentinel text its guard\n * names (PostgreSQL, SQLite: in the message) or, on MySQL, the invalid path\n * its sentinel is (errno 3143). Nothing else the statement raises is a\n * refusal, so a caller's division by zero or invalid JSON in it stays the\n * provider's failure (E5.6).\n */\nexport const JUDGEMENT_MARKER = \"__viborm_judged__\";\nconst REFUSAL_SENTINEL = \"__viborm_refused__\";\nconst MYSQL_INVALID_JSON_PATH = 3143;\nconst POSTGRES_DIVISION_BY_ZERO = \"22012\";\nconst MYSQL_INVALID_JSON_TEXT = 3141;\n\n// `json_each(?))` closes a bound member list (SQLite's `literals.list`): JSON\n// text the adapter stringified, which cannot raise \"malformed JSON\".\nconst JSON_ACCESS_SIGNATURE = /json(?!_each\\(\\?\\)\\))|->/i;\n\nconst FOREIGN_ASSERTION_SIGNATURE: Record<Dialect, RegExp> = {\n postgresql: /[/%]/,\n mysql: JSON_ACCESS_SIGNATURE,\n sqlite: JSON_ACCESS_SIGNATURE,\n};\n\n/**\n * Report whether an ordinary statement can raise the same provider error as a\n * batch assertion. Assertion statements carry {@link ASSERTION_MARKER}; all\n * other statements are checked against the executing dialect's failure\n * signature. With an ownership set, assertions outside that set also collide.\n * A conservative match leaves the raw provider error unattributed.\n */\nexport function batchMayContainAssertionCollision(\n statements: readonly { readonly sql: string }[],\n dialect: Dialect,\n ownedAssertions?: ReadonlySet<number>\n): boolean {\n const signature = FOREIGN_ASSERTION_SIGNATURE[dialect];\n for (const [index, statement] of statements.entries()) {\n if (\n statement.sql.includes(ASSERTION_MARKER) ||\n statement.sql.includes(JUDGEMENT_MARKER)\n ) {\n if (ownedAssertions && !ownedAssertions.has(index)) return true;\n continue;\n }\n if (signature.test(statement.sql)) return true;\n }\n return false;\n}\n\nfunction isRefusal(\n code: string | number | undefined,\n errno: number | undefined,\n message: string\n): boolean {\n return (\n message.includes(REFUSAL_SENTINEL) ||\n errno === MYSQL_INVALID_JSON_PATH ||\n code === \"ER_INVALID_JSON_PATH\"\n );\n}\n\nfunction isAssertionFailure(\n code: string | number | undefined,\n errno: number | undefined,\n message: string\n): boolean {\n return (\n code === POSTGRES_DIVISION_BY_ZERO ||\n code === \"ER_INVALID_JSON_TEXT_IN_PARAM\" ||\n errno === MYSQL_INVALID_JSON_TEXT ||\n message.includes(\"division by zero\") ||\n message.includes(\"malformed JSON\") ||\n message.includes(\"Invalid JSON text\")\n );\n}\n\nfunction isSQLiteContentionResultCode(\n value: string | number | undefined\n): boolean {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0) {\n return false;\n }\n // biome-ignore lint/suspicious/noBitwiseOperators: SQLite defines an extended result code as `base | (sub << 8)`.\n const base = value & SQLITE_BASE_CODE_MASK;\n return base === SQLITE_BUSY_BASE_CODE || base === SQLITE_LOCKED_BASE_CODE;\n}\n\nfunction isSQLiteContentionName(value: string): boolean {\n return (\n value === \"SQLITE_BUSY\" ||\n value === \"SQLITE_LOCKED\" ||\n SQLITE_CONTENTION_FAMILY_PATTERN.test(value)\n );\n}\n\n/**\n * Report whether a provider error is SQLite lock contention, across the three\n * shapes drivers use: an extended symbolic code, an extended numeric result\n * code, or a message carrying the symbol (D1, libsql).\n */\nfunction isSQLiteContention(\n code: string | number | undefined,\n errno: number | undefined,\n message: string,\n dialect: Dialect | undefined\n): boolean {\n if (dialect !== \"sqlite\") return false;\n if (typeof code === \"string\" && isSQLiteContentionName(code)) {\n return true;\n }\n if (\n isSQLiteContentionResultCode(code) ||\n isSQLiteContentionResultCode(errno)\n ) {\n return true;\n }\n return [...message.matchAll(ASCII_PROVIDER_SYMBOL_PATTERN)].some((match) =>\n isSQLiteContentionName(match[0])\n );\n}\n\n/**\n * A recognized failure's class, called with one options shape. `QueryError`\n * is not one: it is the unrecognized fallback, and its `code` family differs.\n */\ntype FailureClass = new (\n message: string,\n options: {\n cause: Error;\n code: TransactionErrorCode | undefined;\n diagnostics: DiagnosticDisclosure | undefined;\n meta: VibORMErrorMeta;\n }\n) => DriverFailure;\n\n/** What one recognized provider failure becomes: class, message, and code when the class has a family. */\ntype FailureConstruction = readonly [\n failure: FailureClass,\n message: string,\n code?: TransactionErrorCode | undefined,\n ...rest: unknown[],\n];\n\ntype ProviderFailure = readonly [\n failure: FailureClass,\n message: string,\n code: TransactionErrorCode | undefined,\n /** PostgreSQL SQLSTATEs and SQLite extended symbolic codes, matched against `code`. */\n providerCodes: readonly unknown[],\n /** MySQL errnos, matched against `errno`. */\n mysqlErrnos: readonly unknown[],\n /** MySQL symbolic names, matched against `code`. */\n mysqlNames: readonly unknown[],\n /** A fragment of the SQLite message that names this failure. */\n sqliteMessage?: string,\n /** Whether that SQLite message lists the failing columns. */\n sqliteColumns?: true,\n];\n\nconst ASSERTION_FAILURE: FailureConstruction = [\n NestedWriteAssertionError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n];\n// SQLite lock refusal is contention, not proof of a deadlock.\nconst SQLITE_CONTENTION_FAILURE: FailureConstruction = [\n TransactionError,\n \"Database is locked\",\n VibORMErrorCode.TRANSACTION_CONTENTION,\n];\n\n/**\n * The recognized provider failures. Precedence is the table read three times:\n * every row's provider code first, then every row's MySQL errno or name, then\n * (after SQLite lock contention) every row's SQLite message fragment. Within a\n * pass, the earlier row wins, so a MySQL errno outranks a later row's name.\n */\nconst PROVIDER_FAILURES: readonly ProviderFailure[] = [\n [\n UniqueConstraintError,\n \"Unique constraint violation\",\n undefined,\n [\"23505\", \"SQLITE_CONSTRAINT_UNIQUE\"],\n [1062],\n [\"ER_DUP_ENTRY\"],\n \"UNIQUE constraint failed\",\n true,\n ],\n [\n ForeignKeyError,\n \"Foreign key constraint violation\",\n undefined,\n // 23001 is restrict_violation — a RESTRICT referential action refused the\n // write. Stock PostgreSQL folds it into 23503; pg-wire servers (CockroachDB)\n // raise it as its own SQLSTATE with the same foreign-key metadata.\n [\"23503\", \"23001\", \"SQLITE_CONSTRAINT_FOREIGNKEY\"],\n // 1451 is ER_ROW_IS_REFERENCED_2: the parent row is still referenced.\n [1452, 1451],\n [\"ER_NO_REFERENCED_ROW_2\", \"ER_ROW_IS_REFERENCED_2\"],\n \"FOREIGN KEY constraint failed\",\n ],\n [\n NotNullConstraintError,\n \"Not-null constraint violation\",\n undefined,\n [\"23502\", \"SQLITE_CONSTRAINT_NOTNULL\"],\n [1048],\n [\"ER_BAD_NULL_ERROR\"],\n \"NOT NULL constraint failed\",\n true,\n ],\n [\n CheckConstraintError,\n \"Check constraint violation\",\n undefined,\n [\"23514\", \"SQLITE_CONSTRAINT_CHECK\"],\n [3819],\n [\"ER_CHECK_CONSTRAINT_VIOLATED\"],\n \"CHECK constraint failed\",\n ],\n [\n ValueTooLongError,\n \"Value too long for column type\",\n undefined,\n // 22001 is string_data_right_truncation and MySQL errno 1406 is\n // ER_DATA_TOO_LONG; Prisma maps both to LengthMismatch/P2000\n // (quaint/src/connector/{postgres,mysql}/error.rs). SQLite has no\n // counterpart: it does not enforce declared column lengths, and quaint's\n // SQLite connector leaves SQLITE_TOOBIG unmapped.\n [\"22001\"],\n [1406],\n [\"ER_DATA_TOO_LONG\"],\n ],\n [\n TransactionError,\n \"Transaction serialization failure\",\n VibORMErrorCode.SERIALIZATION_FAILURE,\n [\"40001\"],\n [],\n [],\n ],\n [\n TransactionError,\n \"Database lock is unavailable\",\n VibORMErrorCode.TRANSACTION_CONTENTION,\n [\"55P03\"],\n [],\n [],\n ],\n [\n TransactionError,\n \"Transaction deadlock detected\",\n VibORMErrorCode.DEADLOCK,\n [\"40P01\"],\n [1213],\n [\"ER_LOCK_DEADLOCK\"],\n ],\n];\n\n/**\n * Every error class {@link mapProviderError} constructs — the driver layer's failure\n * vocabulary, named so it is visible at the call sites instead of erased to `Error`.\n *\n * The members are disjoint by `code` — each class carries its literal — so this union is a\n * discriminated union: `if (failure.code === VibORMErrorCode.UNIQUE_CONSTRAINT)` selects\n * `UniqueConstraintError`, and an exhaustive `switch` over the codes bottoms out at `never`.\n *\n * `mapProviderError` is annotated with it, which is the point: adding a ninth class to the\n * mapper without adding it here is a compile error, not a silently widened return.\n */\nexport type DriverFailure =\n | ClientInitializationError\n | CheckConstraintError\n | ConnectionError\n | ForeignKeyError\n | NestedWriteAssertionError\n | NotNullConstraintError\n | QueryError\n | TransactionError\n | UniqueConstraintError\n | ValueTooLongError;\n\nfunction isConfigurationFailure(\n code: string | number | undefined,\n errno?: number\n): boolean {\n return (\n [\n \"28P01\",\n \"28000\",\n \"3D000\",\n \"ER_ACCESS_DENIED_ERROR\",\n \"ER_BAD_DB_ERROR\",\n ].includes(String(code)) ||\n errno === 1045 ||\n errno === 1049\n );\n}\n\nfunction isConnectionCapacityFailure(\n code: string | number | undefined,\n errno?: number\n): boolean {\n return (\n code === \"53300\" ||\n code === \"ER_CON_COUNT_ERROR\" ||\n code === \"ER_TOO_MANY_USER_CONNECTIONS\" ||\n errno === 1040 ||\n errno === 1203\n );\n}\n\nfunction configurationFailure(\n cause: Error,\n context: DriverErrorContext,\n meta: VibORMErrorMeta\n): ClientInitializationError {\n return new ClientInitializationError(\n \"Database authentication or configuration failed\",\n { cause, meta, diagnostics: context.diagnostics }\n );\n}\n\nfunction withProviderFailureEvidence<T extends DriverFailure>(\n error: unknown,\n failure: T\n): T {\n transferSuppressedFailureEvidence(error, failure);\n return failure;\n}\n\n/**\n * What {@link normalizeDriverError} can hand back.\n *\n * Two arms, and the type is the union of both. A raw provider error is mapped to a\n * {@link DriverFailure}. An error that is ALREADY a VibORM error is passed through with\n * execution context attached — and that arm is honestly `VibORMError`, not `DriverFailure`:\n * the incoming error can be any VibORM error the layers above threw (a `ValidationError`, an\n * engine refusal), `attachExecutionContext` clones it under its own class, and a stateful\n * class it cannot rebuild degrades to the base `VibORMError` (`driver-error-context.ts`).\n * Typing the whole function `DriverFailure` would be a claim this arm cannot keep.\n */\nexport type NormalizedDriverError = DriverFailure | VibORMError;\n\nexport function normalizeDriverError(\n error: unknown,\n context: DriverErrorContext\n): NormalizedDriverError {\n if (isKnownVibORMError(error)) {\n const normalized = attachExecutionContext(error, context);\n const progress = getTrustedRecordSeriesProgress(error);\n return progress\n ? attachRecordSeriesProgress(normalized, progress)\n : normalized;\n }\n return mapProviderError(error, context);\n}\n\n/**\n * Map a raw provider error onto the {@link DriverFailure} vocabulary. Split out of\n * {@link normalizeDriverError} so the constructed union has a return type to be checked\n * against — the passthrough arm above cannot carry that annotation, and a function has one\n * return type. {@link recognizeProviderFailure} decides which failure it is; this is the\n * one place it is constructed.\n */\nfunction mapProviderError(\n error: unknown,\n context: DriverErrorContext\n): DriverFailure {\n const cause = toError(error);\n const rawMessage = getErrorMessage(cause);\n const dbError = readDriverErrorShape(error);\n const meta = buildMeta(dbError, context, rawMessage);\n const stringErrno = dbError.stringErrno;\n const bunSqlState =\n context.driverName === \"bun-sql\" &&\n typeof dbError.code === \"string\" &&\n dbError.code.startsWith(\"ERR_POSTGRES\") &&\n BUN_SQL_STATE_PATTERN.test(stringErrno ?? \"\")\n ? stringErrno\n : undefined;\n const code = bunSqlState ?? dbError.sqlstate ?? dbError.code;\n if (bunSqlState) meta.providerCode = bunSqlState;\n if (isConfigurationFailure(code, dbError.errno))\n return withProviderFailureEvidence(\n error,\n configurationFailure(cause, context, meta)\n );\n if (typeof code === \"string\" && PROVIDER_CONNECTION_CODE_PATTERN.test(code)) {\n return withProviderFailureEvidence(\n error,\n new ConnectionError(\"Database connection failed\", {\n cause,\n diagnostics: context.diagnostics,\n meta,\n code:\n code === \"ETIMEDOUT\"\n ? VibORMErrorCode.CONNECTION_TIMEOUT\n : VibORMErrorCode.CONNECTION_FAILED,\n })\n );\n }\n const errno = dbError.errno ?? parseMessageErrno(rawMessage);\n if (errno !== undefined && meta.providerErrno === undefined) {\n meta.providerErrno = errno;\n }\n\n const diagnostics = context.diagnostics;\n // SQLSTATEs and MySQL constants name the physical failure, independently of\n // localized provider text. SQLite exposes these categories only in messages.\n const capacity = isConnectionCapacityFailure(code, errno);\n const schemaMismatch =\n code === \"42P01\" ||\n code === \"42703\" ||\n code === \"ER_NO_SUCH_TABLE\" ||\n code === \"ER_BAD_FIELD_ERROR\" ||\n errno === 1146 ||\n errno === 1054 ||\n (context.dialect === \"sqlite\" &&\n (rawMessage.includes(\"no such table:\") ||\n rawMessage.includes(\"no such column:\") ||\n rawMessage.includes(\"has no column named\")));\n const outOfRange =\n code === \"22003\" ||\n code === \"ER_WARN_DATA_OUT_OF_RANGE\" ||\n code === \"ER_DATA_OUT_OF_RANGE\" ||\n errno === 1264 ||\n errno === 1690 ||\n (context.dialect === \"sqlite\" && rawMessage.includes(\"integer overflow\"));\n if (capacity || schemaMismatch || outOfRange)\n return withProviderFailureEvidence(\n error,\n capacity\n ? new ConnectionError(\"Database connection capacity exhausted\", {\n cause,\n diagnostics,\n meta,\n code: VibORMErrorCode.CONNECTION_CAPACITY,\n })\n : new QueryError(\n schemaMismatch\n ? \"Database table or column does not exist\"\n : \"Value exceeds the database numeric range\",\n {\n cause,\n diagnostics,\n meta,\n code: schemaMismatch\n ? VibORMErrorCode.QUERY_SCHEMA_MISMATCH\n : VibORMErrorCode.QUERY_OUT_OF_RANGE,\n }\n )\n );\n if (code === \"57014\" || code === \"ER_LOCK_WAIT_TIMEOUT\" || errno === 1205) {\n return withProviderFailureEvidence(\n error,\n new QueryError(\"Query timed out\", {\n cause,\n diagnostics,\n meta,\n code: VibORMErrorCode.QUERY_TIMEOUT,\n })\n );\n }\n const recognized = recognizeProviderFailure(\n code,\n errno,\n rawMessage,\n meta,\n context\n );\n let failure: DriverFailure;\n if (recognized) {\n const [Failure, message, failureCode] = recognized;\n failure = new Failure(message, {\n cause,\n code: failureCode,\n diagnostics,\n meta,\n });\n } else {\n failure = new QueryError(\"Query execution failed\", {\n cause,\n diagnostics,\n meta,\n });\n }\n transferSuppressedFailureEvidence(error, failure);\n return failure;\n}\n\n/**\n * Which failure a raw provider error is. An assertion statement's own failure\n * comes first; then {@link PROVIDER_FAILURES} in its three passes, with SQLite\n * lock contention before the SQLite message pass. Anything else is not\n * recognized.\n */\nfunction recognizeProviderFailure(\n code: string | number | undefined,\n errno: number | undefined,\n message: string,\n meta: VibORMErrorMeta,\n context: DriverErrorContext\n): FailureConstruction | undefined {\n if (\n (context.query?.includes(JUDGEMENT_MARKER) &&\n isRefusal(code, errno, message)) ||\n (context.query?.includes(ASSERTION_MARKER) &&\n isAssertionFailure(code, errno, message))\n ) {\n return ASSERTION_FAILURE;\n }\n const recognized =\n PROVIDER_FAILURES.find((row) => row[3].includes(code)) ??\n PROVIDER_FAILURES.find(\n (row) => row[4].includes(errno) || row[5].includes(code)\n );\n if (recognized) {\n if (recognized[7] && typeof code === \"string\" && code.startsWith(\"SQLITE_\"))\n attachSQLiteColumns(message, meta);\n return recognized;\n }\n if (isSQLiteContention(code, errno, message, context.dialect)) {\n return SQLITE_CONTENTION_FAILURE;\n }\n return findSQLiteMessageFailure(message, meta);\n}\n\n/**\n * What {@link normalizeDriverConnectionError} can hand back — the connection variant of\n * {@link NormalizedDriverError}. The constructed arm is exactly {@link ConnectionError}; the\n * passthrough arm is `VibORMError` for the same two reasons documented there.\n */\nexport type NormalizedConnectionError = ConnectionError | VibORMError;\n\nexport function normalizeDriverConnectionError(\n error: unknown,\n context: DriverErrorContext,\n message = \"Database connection failed\"\n): NormalizedConnectionError {\n if (isKnownVibORMError(error)) {\n return attachExecutionContext(error, context);\n }\n\n const cause = toError(error);\n const rawMessage = getErrorMessage(cause);\n const dbError = readDriverErrorShape(error);\n const meta = buildMeta(dbError, context, rawMessage);\n const errno = dbError.errno ?? parseMessageErrno(rawMessage);\n if (errno !== undefined && meta.providerErrno === undefined) {\n meta.providerErrno = errno;\n }\n const code = dbError.sqlstate ?? dbError.code;\n if (isConfigurationFailure(code, errno))\n return withProviderFailureEvidence(\n error,\n configurationFailure(cause, context, meta)\n );\n return withProviderFailureEvidence(\n error,\n new ConnectionError(\n isConnectionCapacityFailure(code, errno)\n ? \"Database connection capacity exhausted\"\n : message,\n {\n cause,\n diagnostics: context.diagnostics,\n meta,\n code: isConnectionCapacityFailure(code, errno)\n ? VibORMErrorCode.CONNECTION_CAPACITY\n : code === \"ETIMEDOUT\"\n ? VibORMErrorCode.CONNECTION_TIMEOUT\n : VibORMErrorCode.CONNECTION_FAILED,\n }\n )\n );\n}\n\nfunction isKnownVibORMError(error: unknown): error is VibORMError {\n try {\n return isVibORMError(error);\n } catch {\n return false;\n }\n}\n\nfunction toError(error: unknown): Error {\n try {\n return error instanceof Error ? error : new Error(\"Unknown provider error\");\n } catch {\n return new Error(\"Unknown provider error\");\n }\n}\n\nfunction getErrorMessage(error: Error): string {\n try {\n return typeof error.message === \"string\"\n ? error.message\n : \"Unknown provider error\";\n } catch {\n return \"Unknown provider error\";\n }\n}\n\nfunction readDriverErrorShape(error: unknown): DriverErrorShape {\n if ((typeof error !== \"object\" && typeof error !== \"function\") || !error) {\n return {};\n }\n const body = readProperty(error, \"body\");\n const errno = readProperty(error, \"errno\");\n return {\n code: readStringOrNumber(error, \"code\"),\n bodyCode:\n body && (typeof body === \"object\" || typeof body === \"function\")\n ? readStringOrNumber(body, \"code\")\n : undefined,\n errno: typeof errno === \"number\" ? errno : undefined,\n stringErrno: typeof errno === \"string\" ? errno : undefined,\n constraint: readString(error, \"constraint\"),\n table: readString(error, \"table\"),\n column: readString(error, \"column\"),\n constraint_name: readString(error, \"constraint_name\"),\n table_name: readString(error, \"table_name\"),\n column_name: readString(error, \"column_name\"),\n sqlState: readString(error, \"sqlState\"),\n sqlstate: readString(error, \"sqlstate\"),\n status: readStringOrNumber(error, \"status\"),\n statusCode: readStringOrNumber(error, \"statusCode\"),\n };\n}\n\nfunction readString(value: object, key: string): string | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" ? member : undefined;\n}\n\nfunction readStringOrNumber(\n value: object,\n key: string\n): string | number | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" || typeof member === \"number\"\n ? member\n : undefined;\n}\n\nfunction parseMessageErrno(message: string): number | undefined {\n const match = MYSQL_ERRNO_IN_MESSAGE_PATTERN.exec(message);\n return match?.[1] ? Number(match[1]) : undefined;\n}\n\n/**\n * The first row whose SQLite message fragment the provider message carries, in\n * table order. UNIQUE and NOT NULL messages also name their columns.\n */\nfunction findSQLiteMessageFailure(\n message: string,\n meta: VibORMErrorMeta\n): ProviderFailure | undefined {\n const row = PROVIDER_FAILURES.find(\n (candidate) => candidate[6] && message.includes(candidate[6])\n );\n if (row?.[7]) attachSQLiteColumns(message, meta);\n return row;\n}\n\nfunction attachSQLiteColumns(message: string, meta: VibORMErrorMeta): void {\n const match = SQLITE_CONSTRAINT_COLUMNS_PATTERN.exec(message);\n if (!match?.[1]) return;\n // Accept only an unambiguous identifier list. Quoted dots/commas are leaves,\n // not separators; arbitrary constraint expressions never become column names.\n const identifier = String.raw`(?:\"(?:[^\"]|\"\")*\"|\\`(?:[^\\`]|\\`\\`)*\\`|\\[[^\\]]+\\]|[A-Za-z_][A-Za-z0-9_$]*)`;\n const path = `${identifier}(?:\\\\s*\\\\.\\\\s*${identifier})*`;\n if (!new RegExp(`^\\\\s*${path}(?:\\\\s*,\\\\s*${path})*\\\\s*$`).test(match[1]))\n return;\n const paths = match[1].match(new RegExp(path, \"g\"));\n if (!paths) return;\n const columns: string[] = [];\n const tables = new Set<string>();\n for (const qualified of paths) {\n const parts = qualified.match(new RegExp(identifier, \"g\"));\n if (!parts?.length) return;\n const names = parts.map((part) => {\n if (part.startsWith('\"')) return part.slice(1, -1).replaceAll('\"\"', '\"');\n if (part.startsWith(\"`\")) return part.slice(1, -1).replaceAll(\"``\", \"`\");\n if (part.startsWith(\"[\")) return part.slice(1, -1);\n return part;\n });\n const column = names.pop();\n if (column === undefined) return;\n columns.push(column);\n if (names.length) tables.add(names.join(\".\"));\n }\n meta.columns = columns;\n if (tables.size === 1) meta.table = tables.values().next().value;\n}\n"],"mappings":"oiBAKA,IAAa,sBAAb,cAA2C,CAAY,CACrD,OAAyB,eAAiB,wBAK1C,YAAY,EAAiB,EAA8B,CACzD,MAAM,EAAS,EAAgB,kBAAmB,EAAQ,GAOjD,gBAAb,cAAqC,CAAY,CAC/C,OAAyB,eAAiB,kBAK1C,YAAY,EAAiB,EAA8B,CACzD,MAAM,EAAS,EAAgB,uBAAwB,EAAQ,GAOtD,uBAAb,cAA4C,CAAY,CACtD,OAAyB,eAAiB,yBAK1C,YAAY,EAAiB,EAA8B,CACzD,MAAM,EAAS,EAAgB,oBAAqB,EAAQ,GAOnD,qBAAb,cAA0C,CAAY,CACpD,OAAyB,eAAiB,uBAK1C,YAAY,EAAiB,EAA8B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AAM,KAAK,IAAI,CAAC,CAE/C,EAAK,QAAU,EACX,EAAO,OAAS,IAAG,EAAK,MAAQ,EAAO,QAAQ,CAAC,MAAM,CAAC"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./client-q6ccRgdO.mjs";import{n,t as r}from"./libsql-DUO6vHad.mjs";import{t as i}from"./mysql-D1GlcktG.mjs";import{t as a}from"./postgres-Be0jMJWI.mjs";function registerEveryMigrationDriver(){t(a),t(n),t(r),t(i)}export{registerEveryMigrationDriver as t};
2
- //# sourceMappingURL=every-dpzVDwzu.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t}from"./validation-BamBwne9.mjs";import{E as n,g as r}from"./geo-point-codec-DyEHMdJg.mjs";import{o as i}from"./sql-Bhxq9arK.mjs";import{a}from"./physical-CAOaNM4R.mjs";import{t as o}from"./geo-area-codec-CbkmFArQ.mjs";import{r as s}from"./adapter-internals-AGgQRu5t.mjs";import{n as ee}from"./result-parsing-8wEK3GY1.mjs";import{r as c}from"./datetime-physical-codec-BEqQbIP_.mjs";import{A as l,C as u,D as d,E as f,M as p,N as te,S as m,T as h,_ as g,a as _,c as v,d as y,f as b,g as x,h as S,i as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,t as j,u as M,v as N,w as ne,x as P,y as F}from"./standard-sql-mJt0RHHE.mjs";import{n as I}from"./batch-refs-DoWlPD2h.mjs";import{t as L}from"./adapter-namespace-B8XWzCev.mjs";import{a as R,d as z,f as B,g as V,i as H,m as U,n as W,o as G,p as K,r as q,t as J,u as Y}from"./select-assembly-BxtETbG9.mjs";const X=te("`"),Z=U(()=>`PRIMARY`),Q={quotient:(e,t)=>i`CAST((${e} - MOD(${e}, ${t})) / ${t} AS DECIMAL(65,0))`,remainder:(e,t)=>i`MOD(${e}, ${t})`},mysqlMaximumCoefficient=e=>i.raw(`9`.repeat(e)),re=i`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`,$=i`JSON_EXTRACT('x', '$')`,decimalCast=(e,t,n)=>i`CAST(${e} AS ${i.raw(`DECIMAL(${t},${n})`)})`,mysqlCoefficient=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`TRUNCATE(${e}, 0)`;return i`(${a} * ${r} + ${decimalCast(i`(${decimalCast(i`(${e} - ${a})`,n+1,n)} * ${r})`,n,0)})`},mysqlLogical=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`MOD(${e}, ${r})`;return i`((${e} - ${a}) / ${r} + ${decimalCast(a,n,0)} * ${z(n)})`},mysqlGuardedDecimalAssignment=(e,t,n,r)=>{let a=mysqlMaximumCoefficient(n.precision),o=mysqlLogical(t,n);return i`${e} = CASE WHEN ${re} THEN ${o} WHEN ${e} IS NULL THEN NULL WHEN ${r} THEN CASE WHEN ${t} BETWEEN -${a} AND ${a} THEN ${o} ELSE ${$} END ELSE ${$} END`},mysqlDecimalIncrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} <= ${o} - ${a} WHEN ${a} < 0 THEN ${r} >= -${o} - ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} + ${a})`,n,s)},mysqlDecimalDecrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} >= -${o} + ${a} WHEN ${a} < 0 THEN ${r} <= ${o} + ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} - ${a})`,n,s)},mysqlDecimalMultiply=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(65);return mysqlGuardedDecimalAssignment(e,G(Q,i`(${r} * ${a})`,Y(n.scale)),n,i`CASE WHEN ${a} = 0 THEN TRUE ELSE ABS(${r}) <= ${Q.quotient(o,i`ABS(${a})`)} END`)},mysqlDecimalDivide=(e,t,n)=>{let r=mysqlCoefficient(t,n);return mysqlGuardedDecimalAssignment(e,G(Q,B(i`(${mysqlCoefficient(e,n)} * ${Y(n.scale)})`,r),i`ABS(${r})`),n,i.raw`TRUE`)},mysqlDecimalAverage=(e,t)=>mysqlLogical(G(Q,i`SUM(${mysqlCoefficient(e,t)})`,i`COUNT(${e})`),t),asciiCaseFold=e=>{let t=e;for(let e=0;e<26;e++){let n=i.raw(`'${`ABCDEFGHIJKLMNOPQRSTUVWXYZ`[e]}'`),r=i.raw(`'${`abcdefghijklmnopqrstuvwxyz`[e]}'`);t=i`REPLACE(${t}, ${n}, ${r})`}return t},ie=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?$/,naiveDateTimeToIso=e=>{let t=ie.exec(e);if(!t)return;let n=t[3]?t[3].padEnd(4,`0`).slice(0,4):`.000`;return`${t[1]}T${t[2]}${n}Z`},inlineIntegerLiteral=e=>{let t=e.values.length===1?e.values[0]:void 0;return typeof t==`number`&&Number.isInteger(t)?i.raw(String(t)):e},mysqlJsonObject=e=>{if(e.length===0)return i.raw`JSON_OBJECT()`;let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`JSON_OBJECT(${i.join(t,`, `)})`},mysqlJsonListValue=e=>i`CAST(${p(e)} AS JSON)`;var MySQLAdapter=class{constructor(e){L(this,e,`mysql`),this.identifiers=b(X,this.namespace),K(this,this.geoPoint),s(this,{batchRefs:this.#t,constraints:Z,select:this.#e.select})}raw=m();identifiers;literals={...f(),true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t,n)=>i`${n||e.length===10?e:c(e)}`,decimal:(e,t)=>i`CAST(${n(e,t,`text`)} AS ${i.raw(r(`mysql`,t))})`,id:(e,t)=>i`${e}`};operators={..._(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\\\'`,ilike:(e,t)=>i`${asciiCaseFold(e)} LIKE ${asciiCaseFold(t)} ESCAPE '\\\\'`,notIlike:(e,t)=>i`${asciiCaseFold(e)} NOT LIKE ${asciiCaseFold(t)} ESCAPE '\\\\'`,containsText:(e,t)=>i`LOCATE(BINARY ${t}, BINARY ${e}) > 0`,startsWithText:(e,t)=>i`LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,endsWithText:(e,t)=>i`RIGHT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,startsWithPrefix:(e,t)=>i`(${e} LIKE ${`${l(t)}%`} ESCAPE '\\\\' AND LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t})`,exactTextEq:(e,t)=>i`(${e} = ${t} AND BINARY ${e} = ${t})`,exactTextIn:(e,t)=>i`(${e} IN ${t} AND BINARY ${e} IN ${t})`,...x(),...N(),...P(),...S(this.literals.true,this.literals.false),...y()};expressions={...C(),asciiCaseFold,caseSensitiveText:e=>i`BINARY ${e}`,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`CONCAT(${i.join(e,`, `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`TRUNCATE(${e} / ${t}, 0)`,decimalCast:(e,t)=>decimalCast(e,t.precision,t.scale),idCast:(e,t)=>t===`bytes`?i`UNHEX(${e})`:i`CAST(${e} AS CHAR)`,cast:k({text:`CHAR`,integer:`SIGNED`,bigint:`SIGNED`,boolean:`UNSIGNED`,numeric:`DECIMAL`}),blobToHex:e=>i`LOWER(HEX(${e}))`};aggregates={...E(),decimalAvg:(e,t)=>mysqlDecimalAverage(e,t),decimalSumOperandPrecision:v(65)};json={equals:(e,t)=>i`${e} = ${t}`,number:e=>e,boolean:e=>i`JSON_EXTRACT(CASE WHEN ${e} THEN 'true' ELSE 'false' END, '$')`,document:e=>e,object:mysqlJsonObject,array:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,emptyArray:()=>i.raw`JSON_ARRAY()`,agg:e=>i`COALESCE(JSON_ARRAYAGG(${e}), JSON_ARRAY())`,objectFromColumns:mysqlJsonObject,extract:(e,t)=>i`JSON_EXTRACT(${e}, ${j(t)})`,extractText:(e,t)=>i`JSON_UNQUOTE(JSON_EXTRACT(${e}, ${j(t)}))`,numberAtPath:(e,t)=>{let n=j(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS DOUBLE) END)`},stringAtPath:(e,t)=>{let n=j(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS BINARY) END)`},contains:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,lastElement:e=>i`JSON_EXTRACT(${e}, '$[last]')`,value:e=>i`CAST(${p(e)} AS JSON)`};arrays={literal:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,value:mysqlJsonListValue,enumValue:mysqlJsonListValue,has:(e,t)=>i`JSON_CONTAINS(${e}, JSON_ARRAY(${t}))`,hasEvery:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,hasSome:(e,t)=>i`JSON_OVERLAPS(${e}, ${t})`,isEmpty:e=>i`(JSON_LENGTH(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS CHAR)`,length:e=>i`JSON_LENGTH(${e})`,get:(e,t)=>i`JSON_EXTRACT(${e}, CONCAT('$[', ${t}, ']'))`,push:(e,t)=>i`JSON_ARRAY_APPEND(${e}, '$', ${t})`,set:(e,t,n)=>i`JSON_SET(${e}, CONCAT('$[', ${t}, ']'), ${n})`};orderBy={...w(),...M()};clauses={...h(),limit:e=>i`LIMIT ${inlineIntegerLiteral(e)}`,offset:e=>i`OFFSET ${inlineIntegerLiteral(e)}`};set={...F(),increment:(e,t,n)=>n?.decimal?mysqlDecimalIncrement(e,t,n.decimal):i`${e} = ${e} + ${t}`,decrement:(e,t,n)=>n?.decimal?mysqlDecimalDecrement(e,t,n.decimal):i`${e} = ${e} - ${t}`,multiply:(e,t,n)=>n?.decimal?mysqlDecimalMultiply(e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?mysqlDecimalDivide(e,t,n.decimal):n?.integer?i`${e} = TRUNCATE(${e} / ${t}, 0)`:i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(COALESCE(${e}, JSON_ARRAY()), ${t})`,unshift:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(${t}, COALESCE(${e}, JSON_ARRAY()))`};filters=u();subqueries=d(X);noLimitValue=i.raw`18446744073709551615`;#e={select:e=>{let t={...e,limit:e.limit&&inlineIntegerLiteral(e.limit),offset:e.offset&&inlineIntegerLiteral(e.offset)};return t.distinct?J(t,t.distinct,this.identifiers.escape,this.noLimitValue):W(i`SELECT ${t.columns}`,t,{forUpdate:`append`,noLimitValue:this.noLimitValue})}};cte=A(X);mutations={skipDuplicatesStrategy:`recoverableUniqueError`,insert:O(X),insertDefault:e=>i`INSERT INTO ${e} () VALUES ()`,...g(),returning:e=>i.empty,onConflict:(e,t,n)=>i`ON DUPLICATE KEY UPDATE ${t}`,onConflictUpdate:(e,t)=>e,skipDuplicates:e=>{let t=i.raw(X(e));return{prefix:i.empty,suffix:i`ON DUPLICATE KEY UPDATE ${t} = ${t}`}}};assertions={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \`__viborm_judged__\`${t?i` FROM ${t}`:i``}`};joins={...D(),full:(e,t)=>{throw Error(`MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},...T(X)};setOperations=ne(X);capabilities={supportsReturning:!1,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!1,supportsTargetedUpsert:!1,supportsMutationTargetInSubquery:!1,supportsMutationRowLimit:!0,supportsRowLocks:!0};lastInsertId=()=>i.raw`LAST_INSERT_ID()`;#t=I({table:i.raw`\`__viborm_batch_refs\``,batchIdColumn:i.raw`\`batch_id\``,keyColumn:i.raw`\`ref_key\``,valueColumn:i.raw`\`ref_value\``,duplicateValue:i.raw`VALUES(\`ref_value\`)`,createTable:i.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \`__viborm_batch_refs\` (\`batch_id\` VARCHAR(191) NOT NULL, \`ref_key\` VARCHAR(191) NOT NULL, \`ref_value\` TEXT, PRIMARY KEY (\`batch_id\`, \`ref_key\`))`,castValue:e=>i`CAST((${e}) AS CHAR)`,lastInsertId:()=>this.lastInsertId()});vector=t;geoPoint=(()=>{let longitude=e=>i`ST_Longitude(${e})`,latitude=e=>i`ST_Latitude(${e})`;return{value:(e,t)=>i`ST_GeomFromText(CONCAT('POINT(', ${e}, ' ', ${t}, ')'), 4326, 'axis-order=long-lat')`,longitude,latitude,...q(longitude,latitude,this.operators,(e,t)=>{let n=H(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`MBRIntersects(${e}, ST_GeomFromGeoJSON(${t}, 1, 4326))`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_GeomFromGeoJSON(${R(t)}, 1, 4326)`}, ${e})`,distance:(e,t)=>i`ST_Distance_Sphere(${e}, ${t}, ${o})`}})();result={decimalListRepresentation:`coefficient`,idRepresentation:(e,t)=>a(e,t,`mysql`)?.representation??`text`,parseResult:V,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>{if(t===`boolean`){let t=ee(e===`0`?0:e===`1`?1:e);if(t!==void 0)return n(t)}if(t===`datetime`&&typeof e==`string`){let t=naiveDateTimeToIso(e);if(t!==void 0)return n(t)}return n()}}};export{MySQLAdapter as t};
2
- //# sourceMappingURL=mysql-adapter-ClOoHKpn.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mysql-adapter-ClOoHKpn.mjs","names":["sql","#batchRefs","#assemble"],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\nconst ASCII_UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst ASCII_LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\nconst asciiCaseFold = (expr: Sql): Sql => {\n let folded = expr;\n for (let index = 0; index < ASCII_UPPERCASE.length; index++) {\n const upper = sql.raw(`'${ASCII_UPPERCASE[index]}'`);\n const lower = sql.raw(`'${ASCII_LOWERCASE[index]}'`);\n folded = sql`REPLACE(${folded}, ${upper}, ${lower})`;\n }\n return folded;\n};\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n};\n\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder.\n // The literal is doubled ('\\\\') because MySQL's default mode treats\n // backslash as a string-literal escape; under NO_BACKSLASH_ESCAPES it\n // fails loudly rather than silently matching wildcards.\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} NOT LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n asciiCaseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: mysqlJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(path)}))`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n // The refusal is an invalid path (3143), never the invalid text (3141)\n // a premise fails with.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \\`__viborm_judged__\\`${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations(quoteIdent);\n\n capabilities = {\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"64BA4EA,MAAM,EAAa,GAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,oBAC1C,WAAY,EAAQ,IAAgB,CAAG,OAAO,EAAE,IAAI,EAAE,GACvD,CASK,wBAA2B,GAC/BA,EAAI,IAAI,IAAI,OAAO,EAAO,CAAC,CAEvB,GAAkB,CAAG,2HAErB,EAAyB,CAAG,yBAG5B,aAAe,EAAW,EAAmB,IACjD,CAAG,QAAQ,EAAK,MAAMA,EAAI,IAAI,WAAW,EAAU,GAAG,EAAM,GAAG,CAAC,GA0B5D,kBAAoB,EAAY,IAAuC,CAC3E,GAAM,CAAE,SAAU,EAClB,GAAI,IAAU,EAAG,OAAO,EACxB,IAAM,EAAS,EAAe,EAAM,CAC9B,E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CAAG,sBAAsB,EACzC,EACD,CAAC,YACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IACf,CAAG,sBAAsB,EAAK,IAAI,EAAM,IAAI,EAA8B,GAC7E,IACC,CASJ,OAA8B,CAM5B,0BAA2B,cAI3B,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,QAAQ,EAAE,gBAAkB,OAO9D,YAAa,EAEb,eACE,EACA,IACY,GAAM,CAEpB,YACE,EACA,EACA,IACY,CAEZ,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,GACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,mBAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{m as n,p as r}from"./validation-BamBwne9.mjs";import{E as i,g as a}from"./geo-point-codec-DyEHMdJg.mjs";import{o,t as s}from"./sql-Bhxq9arK.mjs";import{o as c}from"./native-types-asNCr26n.mjs";import{a as ee}from"./physical-CAOaNM4R.mjs";import{t as l}from"./geo-area-codec-CbkmFArQ.mjs";import{r as u}from"./adapter-internals-AGgQRu5t.mjs";import{a as d}from"./datetime-physical-codec-BEqQbIP_.mjs";import{t as f}from"./array-literal-BKdLfNzM.mjs";import{A as te,C as p,D as m,E as h,N as g,S as _,T as v,_ as y,a as b,b as x,c as S,d as C,f as w,h as T,i as E,j as D,l as O,m as k,n as A,o as j,p as M,r as ne,s as N,v as P,w as F,x as I,y as L}from"./standard-sql-mJt0RHHE.mjs";import{r as R}from"./batch-refs-DoWlPD2h.mjs";import{t as z}from"./adapter-namespace-B8XWzCev.mjs";import{a as B,c as V,g as H,i as U,l as W,m as G,n as K,p as q,r as J,s as Y,t as X}from"./select-assembly-BxtETbG9.mjs";var Z=class JsonParameter{json;constructor(e){this.json=e,Object.freeze(this)}static from(e){let t=JSON.stringify(e);return t===void 0?void 0:new JsonParameter(t)}toString(){return this.json}toJSON(){return JSON.parse(this.json)}};const Q=g(`"`);function postgresLikeLiteral(e){return o`REPLACE(REPLACE(REPLACE(${e}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`}function postgresAsciiCaseFold(e){return o`TRANSLATE(${e}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`}function postgresJsonObject(e){if(e.length===0)return o.raw`'{}'::json`;let t=[],n=o.raw(e.length>50?`jsonb_build_object`:`json_build_object`);for(let r=0;r<e.length;r+=50){let i=e.slice(r,r+50).flatMap(([e,t])=>[o`${e}::text`,t]);t.push(o`${n}(${o.join(i,`, `)})`)}return t.length===1?t[0]:o`(${o.join(t,` || `)})::json`}const re=G(e=>`${e}_pkey`);var CastParameter=class extends s{type;constructor(e,t){super([`CAST(`,` AS ${t})`],[e]),this.type=t}},ArrayParameter=class extends s{};const ie=h().list;function arrayParameter(e){let t=e[0];if(t===void 0)return;let n=t instanceof CastParameter?t.type:void 0,r=[];for(let t of e){let e=t instanceof CastParameter?t:void 0,[i,a,o]=t.strings;if(e?.type!==n||!e&&(i!==``||a!==``||o!==void 0))return;let s=t.values[0];if(s instanceof Uint8Array)r.push(`\\x${Array.from(s,e=>e.toString(16).padStart(2,`0`)).join(``)}`);else if(typeof s==`string`||typeof s==`number`||typeof s==`bigint`||typeof s==`boolean`)r.push(String(s));else return}let i=f(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>o`div(${e}, ${t})`,remainder:(e,t)=>o`mod(${e}, ${t})`},ae=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){z(this,e,`postgresql`),this.identifiers=w(Q,this.namespace),q(this,t?this.#r():void 0),u(this,{batchRefs:this.#n,constraints:re,select:this.#e.select})}raw=_();identifiers;literals={...h(),dateTime:e=>o`${d(e)}`,true:()=>o.raw`TRUE`,false:()=>o.raw`FALSE`,json:e=>o`${Z.from(e)}`,decimal:(e,t)=>new CastParameter(i(e,t,`text`),a(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):o`${e}`,list:e=>arrayParameter(e)??ie(e)};operators={...b(),like:(e,t)=>o`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>o`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>o`${postgresAsciiCaseFold(e)} LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,notIlike:(e,t)=>o`${postgresAsciiCaseFold(e)} NOT LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,containsText:(e,t)=>o`${e} LIKE ('%' || ${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,startsWithText:(e,t)=>o`${e} LIKE (${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,endsWithText:(e,t)=>o`${e} LIKE ('%' || ${postgresLikeLiteral(t)}) ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>o`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${te(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>o`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>this.operators.in(this.expressions.caseSensitiveText(e,n,!1),t),in:(e,t)=>t instanceof ArrayParameter?o`${e} = ANY(${t})`:o`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?o`${e} <> ALL(${t})`:o`${e} NOT IN ${t}`,...P(),...I(),...T(this.literals.true,this.literals.false),...C()};expressions={...E(),caseSensitiveText:(e,t,r=!1)=>{let i=c(t,`pg`)?.type;if(!r&&i?.toLowerCase()===`xml`)throw new n(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return r&&i&&ae.test(i)?o`CAST(${e} AS TEXT)`:e},asciiCaseFold:postgresAsciiCaseFold,concat:(...e)=>e.length===0?o.raw`''`:e.length===1?e[0]:o`(${o.join(e,` || `)})`,greatest:(...e)=>o`GREATEST(${o.join(e,`, `)})`,least:(...e)=>o`LEAST(${o.join(e,`, `)})`,integerDivide:(e,t)=>o`(${e} / ${t})`,decimalCast:(e,t)=>o`CAST(${e} AS ${o.raw(a(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?o`decode(${e}, 'hex')`:o`CAST(${e} AS ${o.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:ne({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>o`encode(${e}, 'hex')`};aggregates={...A(`'Infinity'::float8`),min:(e,t=!1)=>t?o`BOOL_AND(${e})`:o`MIN(${e})`,max:(e,t=!1)=>t?o`BOOL_OR(${e})`:o`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:S(1e3)};json={equals:(e,t)=>o`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?o.raw`'[]'::json`:o`json_build_array(${o.join(e,`, `)})`,emptyArray:()=>o.raw`'[]'::json`,agg:e=>o`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>o`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>o`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>o`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>o`((CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END) COLLATE "C")`,contains:(e,t)=>o`(${e})::jsonb @> ${t}`,lastElement:e=>o`(${e})::jsonb -> -1`,value:e=>o`${Z.from(e)}`};arrays={literal:e=>e.length===0?o.raw`'{}'`:o`ARRAY[${o.join(e,`, `)}]`,value:(e,t)=>o`${t?e.map(e=>typeof e==`string`?d(e):e):e}`,enumValue:e=>o`${f(e)}`,has:(e,t)=>o`${t} = ANY(${e})`,hasEvery:(e,t)=>o`${e} @> ${t}`,hasSome:(e,t)=>o`${e} && ${t}`,isEmpty:e=>o`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>o`CAST(${e} AS TEXT[])`,length:e=>o`cardinality(${e})`,get:(e,t)=>o`${e}[${t}]`,push:(e,t)=>o`array_append(${e}, ${t})`,set:(e,t,n)=>o`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...O(),nullsFirst:(e,t)=>t===`desc`?o`${e} DESC NULLS FIRST`:o`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?o`${e} DESC NULLS LAST`:o`${e} ASC NULLS LAST`};clauses=v();set={...L(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):o`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?V($,e,t,n.decimal):o`${e} = ${e} / ${t}`,push:(e,t)=>o`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>o`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=p();subqueries=m(Q);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e.distinct?o`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:o`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=N(Q);mutations={skipDuplicatesStrategy:`sql`,insert:M(Q),insertDefault:e=>o`INSERT INTO ${e} DEFAULT VALUES`,...y(),returning:e=>o`RETURNING ${e}`,...x()};assertions={exists:e=>o`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>o`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,holds:(e,t)=>o`SELECT CASE WHEN ${e} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS "__viborm_judged__"${t?o` FROM ${t}`:o``}`};joins={...j(),full:(e,t)=>o`FULL OUTER JOIN ${e} ON ${t}`,...k(Q)};setOperations=F(Q,(e,t,n)=>{let r=o.raw(Q(e.alias)),column=e=>o.raw(Q(e)),[i,...a]=t,s=i.map((t,n)=>o`COALESCE(${t}, (${r}."row").${column(e.columns[n])})`);return o`(SELECT NULL::${e.table} AS "row") AS ${r} CROSS JOIN LATERAL (VALUES ${o.join([s,...a].map(D),`, `)}) AS ${o.raw(Q(n))}(${o.join(e.columns.map(column),`, `)})`});capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0};lastInsertId=()=>o.raw`lastval()`;#t=R({table:o.raw`"__viborm_batch_refs"`,batchIdColumn:o.raw`"batch_id"`,keyColumn:o.raw`"ref_key"`,valueColumn:o.raw`"ref_value"`,createTable:o.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>o`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>o`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new r(`PostgreSQL vector components must fit a finite float32 value.`,{code:t.INVALID_INPUT});return o`${`[${e.join(`,`)}]`}::vector`},l2:(e,t)=>o`${e} <-> ${t}`,cosine:(e,t)=>o`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>o`ST_X(${e}::geometry)`,latitude=e=>o`ST_Y(${e}::geometry)`;return{value:(e,t)=>o`ST_SetSRID(ST_MakePoint(${e}, ${t}), 4326)::geography`,longitude,latitude,...J(longitude,latitude,this.operators,(e,t)=>{let n=U(t);if(n.length!==0)return this.operators.or(...n.map(t=>o`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>o`ST_Intersects(${o`ST_SetSRID(ST_GeomFromGeoJSON(${B(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=o`RADIANS(ST_X(${e}::geometry))`,r=o`RADIANS(ST_Y(${e}::geometry))`,i=o`RADIANS(ST_X(${t}::geometry))`,a=o`RADIANS(ST_Y(${t}::geometry))`;return o`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${l} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${o`POWER(SIN((${a} - ${r}) / 2), 2) + COS(${r}) * COS(${a}) * POWER(SIN((${i} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>ee(e,t,`pg`)?.representation??`text`,parseResult:H,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
2
- //# sourceMappingURL=postgres-adapter-BoQ4RRwr.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-adapter-BoQ4RRwr.mjs","names":["sql","#createGeoPointSql","#batchRefs","#assemble","#cteBatchRefs"],"sources":["../src/sql/json-parameter.ts","../src/adapters/databases/postgres/postgres-adapter.ts"],"sourcesContent":["/**\n * One JSON document, bound as one statement parameter.\n *\n * PostgreSQL's JSON literals bind CANONICAL JSON TEXT and let the server cast\n * that text from the parameter's column context. Nothing at the driver can\n * tell that text apart from an ordinary string, so every transport that\n * re-serializes a `json`/`jsonb` parameter has to be told not to, and only some\n * of them offer a place to say it: postgres.js takes a `json` type override\n * (`src/drivers/postgres/index.ts`), PGlite's own JSON serializer already\n * passes strings through, and node-postgres/Neon never touch a string. Bun SQL\n * offers no such hook and JSON-ENCODES a string bound to a `json`/`jsonb`\n * parameter, storing the physical document `\"[1,2,3]\"` — a JSON string — where\n * `[1,2,3]` was meant (upstream Drizzle #5287).\n *\n * This carrier is the missing distinction, and it needs no per-transport hook:\n * a PostgreSQL transport can only reach a bound value through string coercion\n * or through JSON serialization, and this renders as its canonical text under\n * BOTH. The text captured at construction is the ONE stored fact: `toJSON`\n * answers it parsed back, and `JSON.stringify` of its own output re-serializes\n * to those exact bytes, so both protocols agree even if the caller mutates the\n * original value after binding.\n * Bun, which serializes an object parameter for a `json`/`jsonb` column with\n * `JSON.stringify`, therefore stores the exact document for every JSON type,\n * including the number, boolean and null primitives that no bare JavaScript\n * value can express to it (a JS number is bound as `integer`, `null` as SQL\n * NULL).\n *\n * `json` is an own property rather than a private field because it is what a\n * parameter snapshot shows: diagnostics read own properties, so an opted-in\n * `includeParams` disclosure keeps the document instead of reporting `{}`.\n */\nexport class JsonParameter {\n /** The canonical JSON text — `JSON.stringify(value)`. */\n readonly json: string;\n\n private constructor(json: string) {\n this.json = json;\n Object.freeze(this);\n }\n\n /**\n * The carrier for `value`, or `undefined` when `JSON.stringify` has no text\n * for it (`undefined`, a function, a symbol). Those bound `undefined`\n * directly before this carrier existed, which providers send as SQL NULL;\n * carrying them would bind the text `\"undefined\"` instead.\n */\n static from(value: unknown): JsonParameter | undefined {\n // The lib signature says `string`, which is only true for the values it can\n // represent.\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? undefined : new JsonParameter(json);\n }\n\n toString(): string {\n return this.json;\n }\n\n toJSON(): unknown {\n return JSON.parse(this.json);\n }\n}\n","import {\n QueryError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport { JsonParameter } from \"../../../sql/json-parameter\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport { passThroughParseResult } from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createOnConflictBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n rowValues,\n} from \"../../shared/standard-sql\";\nimport { arrayLiteralText } from \"./array-literal\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\nfunction postgresLikeLiteral(value: Sql): Sql {\n return sql`REPLACE(REPLACE(REPLACE(${value}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`;\n}\nfunction postgresAsciiCaseFold(expr: Sql): Sql {\n return sql`TRANSLATE(${expr}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`;\n}\nfunction postgresJsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw`'{}'::json`;\n const chunks: Sql[] = [];\n const buildObject = sql.raw(\n pairs.length > 50 ? \"jsonb_build_object\" : \"json_build_object\"\n );\n // PostgreSQL limits a function call to 100 arguments. Chunking preserves\n // the surrounding aggregate scope, unlike moving values into a subquery.\n for (let start = 0; start < pairs.length; start += 50) {\n const args = pairs\n .slice(start, start + 50)\n .flatMap(([key, value]) => [sql`${key}::text`, value]);\n chunks.push(sql`${buildObject}(${sql.join(args, \", \")})`);\n }\n return chunks.length === 1\n ? chunks[0]!\n : sql`(${sql.join(chunks, \" || \")})::json`;\n}\nconst POSTGRES_CONSTRAINTS = createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n);\n\n/** An operand cast to the type its column holds: `uuid`, `NUMERIC(p,s)`. */\nclass CastParameter extends Sql {\n readonly type: string;\n constructor(value: unknown, type: string) {\n super([\"CAST(\", ` AS ${type})`], [value]);\n this.type = type;\n }\n}\n\n/** A value list bound as ONE array parameter: `= ANY(…)`, `<> ALL(…)`. */\nclass ArrayParameter extends Sql {}\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n\n/**\n * engine-09: a list whose members are each one parameter — bare, or all cast\n * to one type — as one array parameter: PostgreSQL's own array text, typed by\n * the members' cast or, bare, by the compared column, as a list column's\n * parameter is. Any other list keeps a parameter per member.\n */\nfunction arrayParameter(members: readonly Sql[]): ArrayParameter | undefined {\n const first = members[0];\n if (first === undefined) return;\n const type = first instanceof CastParameter ? first.type : undefined;\n const elements: string[] = [];\n for (const member of members) {\n const cast = member instanceof CastParameter ? member : undefined;\n const [head, tail, extra] = member.strings;\n if (\n cast?.type !== type ||\n (!cast && (head !== \"\" || tail !== \"\" || extra !== undefined))\n )\n return;\n const value = member.values[0];\n if (value instanceof Uint8Array)\n elements.push(\n `\\\\x${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`\n );\n else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n )\n elements.push(String(value));\n else return;\n }\n const text = arrayLiteralText(elements);\n return type === undefined\n ? new ArrayParameter([\"\", \"\"], [text])\n : new ArrayParameter([\"CAST(\", ` AS ${type}[])`], [text]);\n}\n\n/**\n * `div`/`mod` rather than `/` and a hand-rolled remainder: both are exact on\n * `numeric` for any operand, including a fractional divisor, and `div`\n * truncates toward zero — which is what the half-even rule's quotient means.\n * `/` on numerics picks its own result scale and would round the last digit.\n */\nconst POSTGRES_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`div(${n}, ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`mod(${n}, ${d})`,\n};\n\n/** The two characters PostgreSQL reads structurally inside a quoted member. */\n\n/**\n * PostgreSQL's own text spelling of one list, for a column whose element type\n * the driver cannot serialize.\n *\n * Every member is quoted, so a member that is empty, spells `NULL`, or holds a\n * brace, comma, quote or backslash is still exactly one member: those are the\n * only characters the server reads structurally, and quoting makes the reading\n * unambiguous without a per-member decision.\n */\n\nconst NON_TEXT_STRING_TYPE =\n /^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\\(|$)/i;\n\nexport class PostgresAdapter implements DatabaseAdapter {\n /**\n * The bound schema. PostgreSQL always qualifies, so this adapter has no\n * unbound mode: an omitted or explicitly `undefined` argument means the\n * `public` schema, whatever a connection's `search_path` says.\n */\n declare readonly namespace: string;\n readonly geoPoint: GeoPointSql | undefined;\n\n constructor(namespace = \"public\", postgis = false) {\n installAdapterNamespace(this, namespace, \"postgresql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${postgresAsciiCaseFold(column)} LIKE ${postgresAsciiCaseFold(pattern)} ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${postgresAsciiCaseFold(column)} NOT LIKE ${postgresAsciiCaseFold(pattern)} ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE (${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)}) ESCAPE '\\\\'`,\n // PostgreSQL is the one dialect where the escaped LIKE spelling is both\n // exact and index-usable, so it stands alone here: `LIKE` is case- and\n // accent-sensitive natively, which is the contract `startsWithText` holds,\n // and `match_pattern_prefix` extracts `name >= 'x' AND name < 'y'` from the\n // constant-folded pattern even though it arrives as a bound parameter.\n //\n // THE INDEX RANGE HAS A COLLATION PRECONDITION, and the common case does\n // not meet it. Measured, 20k rows, plain btree index:\n // - C-collated database (PGlite, `datcollate = 'C'`): Bitmap Index Scan\n // over 111 rows, where `LEFT(col, LENGTH($1)) = $1` is a Seq Scan over\n // all 20000.\n // - `en_US.utf8` (postgres:16 — the project's own test container, and\n // what a default `initdb` produces): BOTH spellings Seq Scan. Only a\n // `(col text_pattern_ops)` index ranges, and `generateCreateIndex`\n // (src/migrations/drivers/postgres/index.ts) emits no opclass, so\n // viborm cannot create one.\n // What survives on a default-locale cluster — and the reason this spelling\n // still stands there — is the row estimate: `LIKE` tracks the data\n // (202/1010/11111/19998 against truths 111/1111/11111/20000) while\n // `LEFT(...)` is an opaque function estimated at a flat 100 for every\n // prefix width, a 111x error at `name1%` that propagates into the row\n // estimate of any join above it. It is never worse than the spelling it\n // replaced on any measured leg. Full record: Decision 7.3 in\n // docs/architecture/query-performance-plan.md.\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\'`,\n\n // Preserve native equality and indexes; the shared text boundary refuses\n // native types such as XML that cannot express an exact comparison.\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} = ${value}`,\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n this.operators.in(\n this.expressions.caseSensitiveText(column, nativeType, false),\n values\n ),\n\n // Set membership: a bound list (`literals.list`) is an array, read by\n // ANY/ALL; a parenthesized list or a subquery is read by IN.\n in: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} = ANY(${values})`\n : sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} <> ALL(${values})`\n : sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation = false\n ): Sql => {\n const type = nativeTypeFor(nativeType, \"pg\")?.type;\n if (!textOperation && type?.toLowerCase() === \"xml\")\n throw new UnsupportedOperationError(\n \"PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.\",\n { meta: { dialect: \"pg\", scalarType: \"string\" } }\n );\n return textOperation && type && NON_TEXT_STRING_TYPE.test(type)\n ? sql`CAST(${expr} AS TEXT)`\n : expr;\n },\n asciiCaseFold: postgresAsciiCaseFold,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // PostgreSQL integer division already truncates toward zero, which is why\n // `set.divide` ignores `target.integer` here as well. Casting either side\n // would narrow a `bigint` operand to `int4`.\n integerDivide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`decode(${expr}, 'hex')`\n : sql`CAST(${expr} AS ${sql.raw(\n representation === \"uuid\" ? \"UUID\" : \"TEXT\"\n )})`,\n\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"BIGINT\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`encode(${expr}, 'hex')`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'Infinity'::float8\"),\n\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_AND(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_OR(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(POSTGRES_INTEGERS, column, descriptor),\n\n // `sum(numeric)` is itself unbounded on PostgreSQL; 1000 is the widest\n // `NUMERIC(p,s)` an operand can be CAST into to meet it, which is the\n // domain a comparison against that sum is actually limited by.\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(1000),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql =>\n sql`(${left})::jsonb = (${right})::jsonb`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n number: (expression: Sql): Sql => expression,\n\n object: postgresJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'[]'::json`;\n return sql`json_build_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`'[]'::json`,\n\n agg: (expr: Sql): Sql => sql`COALESCE(json_agg(${expr}), '[]'::json)`,\n\n objectFromColumns: postgresJsonObject,\n\n // #>/#>> with a text[] param handles every path shape uniformly:\n // '{}' returns the document root, and integer segments address array\n // elements (a single-segment `-> '0'` would only match an object key)\n extract: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>${path}::text[]`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>>${path}::text[]`,\n\n // jsonb_typeof gates the cast: a non-number (or an absent path, where\n // jsonb_typeof is NULL) short-circuits to NULL instead of raising\n // \"invalid input syntax for type double precision\"\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'number' THEN ((${column})::jsonb#>>${path}::text[])::double precision END)`,\n\n // COLLATE \"C\" pins byte (= code point) ordering; the database's default\n // collation (en_US.UTF-8 and friends) orders 'a' before 'B', which would\n // make < / > disagree with MySQL and SQLite\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'string' THEN (${column})::jsonb#>>${path}::text[] END) COLLATE \"C\")`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(${target})::jsonb @> ${value}`,\n\n lastElement: (target: Sql): Sql => sql`(${target})::jsonb -> -1`,\n\n // Serialized JSON text, same format literals.json writes — PG casts the\n // param to jsonb from the comparison context\n value: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'{}'`;\n return sql`ARRAY[${sql.join(items, \", \")}]`;\n },\n\n // Native array parameter; drivers serialize JS arrays to PG array format\n value: (values: unknown[], temporal?: \"date\" | \"datetime\"): Sql =>\n sql`${temporal ? values.map((value) => (typeof value === \"string\" ? encodePostgresTemporal(value) : value)) : values}`,\n\n // One untyped parameter holding PostgreSQL's own array literal. A managed\n // enum's array OID is created by the estate, so no driver has a serializer\n // for it and the native parameter above arrives malformed; an unknown\n // parameter instead takes its type from the column or operand it meets,\n // which is how the enum type is reached without naming it here.\n enumValue: (values: unknown[]): Sql => sql`${arrayLiteralText(values)}`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n const selectClause = parts.distinct\n ? sql`SELECT DISTINCT ON (${parts.distinct}) ${parts.columns}`\n : sql`SELECT ${parts.columns}`;\n\n return assembleSelectQuery(selectClause, parts, { forUpdate: \"append\" });\n },\n };\n\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n // The refusal names its sentinel (22P02, `invalid input syntax for type\n // integer: \"__viborm_refused__\"`), which no caller's division by zero\n // does; the text is a sublink, which PostgreSQL does not fold while\n // planning, so it is evaluated only where it is reached.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS \"__viborm_judged__\"${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n /**\n * The produced rows as a `VALUES` list: PostgreSQL parses each `UNION ALL`\n * arm one recursion deeper (`54001`, stack depth, at 8,000 rows on 16.14),\n * and a list is no deeper for its length. A `VALUES` column is typed by its\n * own rows, an unknown parameter as `text`, so the first row takes each\n * column's type from a NULL of the table's row type (`COALESCE`, the rule\n * a `UNION` arm met), beside the list, as a one-row FROM item. The NULL is\n * cast to the table's type, never read as `SELECT \"qN\" FROM table AS \"qN\"`:\n * there a column named `qN` would win over the whole-row reference (42809),\n * and the cast reads no relation at all.\n */\n setOperations = createSetOperations(quoteIdent, (typed, rows, alias) => {\n const name = sql.raw(quoteIdent(typed.alias));\n const column = (field: string) => sql.raw(quoteIdent(field));\n const [first, ...rest] = rows;\n const typedFirst = first!.map(\n (value, index) =>\n sql`COALESCE(${value}, (${name}.\"row\").${column(typed.columns[index]!)})`\n );\n return sql`(SELECT NULL::${typed.table} AS \"row\") AS ${name} CROSS JOIN LATERAL (VALUES ${sql.join(\n [typedFirst, ...rest].map(rowValues),\n \", \"\n )}) AS ${sql.raw(quoteIdent(alias))}(${sql.join(typed.columns.map(column), \", \")})`;\n });\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`lastval()`;\n\n readonly #cteBatchRefs = createOnConflictBatchRefs({\n table: sql.raw`\"__viborm_batch_refs\"`,\n batchIdColumn: sql.raw`\"batch_id\"`,\n keyColumn: sql.raw`\"ref_key\"`,\n valueColumn: sql.raw`\"ref_value\"`,\n // The table is not ON COMMIT DROP, so it survives the native batch that\n // created it (D-50); the scratch itself belongs to the dispatched batch —\n // each batch stores its own reference rows, reads back what it stored at\n // its own end and deletes them there (D-58), so a later batch never names\n // a reference an earlier one stored. The table lingers on the session like\n // the SQLite and MySQL scratch tables do.\n createTable: sql.raw`CREATE TEMP TABLE IF NOT EXISTS \"__viborm_batch_refs\" (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n // The exact identity of an INSERT, carried by the statement that runs it:\n // the INSERT is the data-modifying CTE, its RETURNING feeds the reference\n // row, and nothing session-global (lastval) is read.\n storeReturning: (batchId, key, insert, column) =>\n sql`WITH \"__viborm_inserted\" AS (${insert} RETURNING ${column}) INSERT INTO \"__viborm_batch_refs\" (\"batch_id\", \"ref_key\", \"ref_value\") SELECT ${batchId}, ${key}, CAST(${column} AS TEXT) FROM \"__viborm_inserted\"`,\n });\n\n // Whether this provider can mutate inside a CTE is the capability's fact,\n // read live: the CTE store and the key store it derives are offered only\n // while `capabilities.supportsCteWithMutations` holds, and a PostgreSQL\n // without it offers no exact key store at all (lastval() is not exact).\n readonly #batchRefs: BatchReferenceSqlAdapter = (() => {\n const withCte = this.#cteBatchRefs;\n const capabilities = this.capabilities;\n return {\n setup: withCte.setup,\n cleanup: withCte.cleanup,\n store: withCte.store,\n read: withCte.read,\n get storeReturning() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeReturning\n : undefined;\n },\n get storeInsertedKey() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeInsertedKey\n : undefined;\n },\n };\n })();\n\n vector = {\n literal: (values: number[]): Sql => {\n if (values.some((value) => !Number.isFinite(Math.fround(value))))\n throw new QueryError(\n \"PostgreSQL vector components must fit a finite float32 value.\",\n { code: VibORMErrorCode.INVALID_INPUT }\n );\n return sql`${`[${values.join(\",\")}]`}::vector`;\n },\n\n l2: (column: Sql, vector: Sql): Sql => sql`${column} <-> ${vector}`,\n\n cosine: (column: Sql, vector: Sql): Sql =>\n sql`NULLIF(${column} <=> ${vector}, 'NaN'::double precision)`,\n };\n\n #createGeoPointSql(): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point}::geometry)`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point}::geometry)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_SetSRID(ST_MakePoint(${pointLongitude}, ${pointLatitude}), 4326)::geography`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`${point} && ST_SetSRID(ST_GeomFromGeoJSON(${polygon}), 4326)::geography`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_SetSRID(ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}), 4326)::geography`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}::geometry))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}::geometry))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}::geometry))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}::geometry))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // PostgreSQL's LEAST/GREATEST ignore NULL operands. The explicit arm is\n // what keeps a nullable source point's distance NULL rather than zero.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n }\n\n result: DatabaseAdapter[\"result\"] = {\n // PostgreSQL returns native JS scalars and parseField below is a pure\n // passthrough, so the result parser may take the identity fast path for\n // plain string/int/number/boolean columns (byte-identical, guarded).\n nativeScalarPassthrough: true,\n\n // A managed enum's array OID is in no driver's result-type table, so an\n // enum LIST comes back as the array's own text rather than a JS array.\n enumListRepresentation: \"arrayText\",\n\n // The one physical promise an identifier column makes, derived from the\n // ONE storage owner so the column the migration creates, the parameter the\n // write binds and the value this reads back cannot be three decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"pg\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing. This leg used to offer\n // `convertBigIntToNumber(raw)`, but `Queries.decodeResult` hands it the\n // operation's ROW ARRAY, which is never a bigint, and an integer's width\n // is a VALUE's fact that the engine's `int` codec owns - it turns a bigint\n // or an integer text into a number and refuses one outside the safe range\n // (`raptor3/shared/query.ts`). Measured on live PostgreSQL over seven\n // operations and both routes, on `pg` and on `postgres.js`: 40 asks, 40\n // `undefined` (Arnaud's D-40, `g4/rulings/o2/receipts/leg-probe-pg.log`\n // and `leg-probe-postgresjs-2.log`), with `COUNT(*)` arriving as the text\n // `\"2\"` on both transports.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL returns native JSON objects - passthrough\n return next();\n },\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL has native types - passthrough\n return next();\n },\n };\n}\n"],"mappings":"69BA+BA,IAAa,EAAb,MAAa,aAAc,CAEzB,KAEA,YAAoB,EAAc,CAChC,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CASrB,OAAO,KAAK,EAA2C,CAGrD,IAAM,EAA2B,KAAK,UAAU,EAAM,CACtD,OAAO,IAAS,IAAA,GAAY,IAAA,GAAY,IAAI,cAAc,EAAK,CAGjE,UAAmB,CACjB,OAAO,KAAK,KAGd,QAAkB,CAChB,OAAO,KAAK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