viborm 1.3.3 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/dist/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
  2. package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
  3. package/dist/{adapter-namespace-CWLEmon2.mjs → adapter-namespace-BLejG8FA.mjs} +1 -1
  4. package/dist/{adapter-namespace-CWLEmon2.mjs.map → adapter-namespace-BLejG8FA.mjs.map} +1 -1
  5. package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
  6. package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
  7. package/dist/adapters.d.mts +1 -1
  8. package/dist/adapters.mjs +1 -1
  9. package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  10. package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  11. package/dist/{batch-refs-DGJPz8-G.mjs → batch-refs-BYCu1JnQ.mjs} +1 -1
  12. package/dist/{batch-refs-DGJPz8-G.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
  13. package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
  14. package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
  15. package/dist/builder-BS8EW4BQ.mjs +2 -0
  16. package/dist/builder-BS8EW4BQ.mjs.map +1 -0
  17. package/dist/bun-sql.d.mts +3 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sql.mjs.map +1 -1
  20. package/dist/bun-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/cache/cloudflare-kv.d.mts +1 -1
  23. package/dist/cache/cloudflare-kv.mjs +1 -1
  24. package/dist/cache/memory.d.mts +1 -1
  25. package/dist/cache/memory.mjs +1 -1
  26. package/dist/cache.d.mts +1 -1
  27. package/dist/cache.mjs +1 -1
  28. package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
  29. package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
  30. package/dist/chain-D5J9hIw-.mjs +2 -0
  31. package/dist/chain-D5J9hIw-.mjs.map +1 -0
  32. package/dist/cli.mjs +1 -1
  33. package/dist/client-Bhl2mWam.mjs +2 -0
  34. package/dist/client-Bhl2mWam.mjs.map +1 -0
  35. package/dist/{client-DR0vYetv.d.mts → client-BzgBm_86.d.mts} +3 -1
  36. package/dist/{client-DjtWangN.mjs → client-aU3YhZ6G.mjs} +16 -16
  37. package/dist/client-aU3YhZ6G.mjs.map +1 -0
  38. package/dist/client.d.mts +1 -1
  39. package/dist/client.mjs +1 -1
  40. package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
  41. package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
  42. package/dist/config.d.mts +1 -1
  43. package/dist/config.mjs +1 -1
  44. package/dist/d1.d.mts +1 -1
  45. package/dist/d1.mjs +1 -1
  46. package/dist/d1.mjs.map +1 -1
  47. package/dist/{datetime-physical-codec-qKxFtI3B.mjs → datetime-physical-codec-lX7IJBlz.mjs} +1 -1
  48. package/dist/{datetime-physical-codec-qKxFtI3B.mjs.map → datetime-physical-codec-lX7IJBlz.mjs.map} +1 -1
  49. package/dist/driver-CQQbCQh9.mjs +2 -0
  50. package/dist/{driver-Bzc0GCQ4.mjs.map → driver-CQQbCQh9.mjs.map} +1 -1
  51. package/dist/{driver-BvP7eW0A.mjs → driver-u2qJicrE.mjs} +2 -2
  52. package/dist/{driver-BvP7eW0A.mjs.map → driver-u2qJicrE.mjs.map} +1 -1
  53. package/dist/driver.d.mts +1 -1
  54. package/dist/driver.mjs +1 -1
  55. package/dist/error-mapping-6op318w6.mjs.map +1 -1
  56. package/dist/every-CzF00eDV.mjs +2 -0
  57. package/dist/{every-WUr3mlvg.mjs.map → every-CzF00eDV.mjs.map} +1 -1
  58. package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
  59. package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.mjs.map} +1 -1
  60. package/dist/{identifier-conversion-Bs7A2GGU.mjs → identifier-conversion-Dc0Rf4Gi.mjs} +2 -2
  61. package/dist/{identifier-conversion-Bs7A2GGU.mjs.map → identifier-conversion-Dc0Rf4Gi.mjs.map} +1 -1
  62. package/dist/identity-CmRos0Yf.mjs +2 -0
  63. package/dist/identity-CmRos0Yf.mjs.map +1 -0
  64. package/dist/{index-B_jh2oaQ.d.mts → index-B4IWFJfv.d.mts} +1282 -1053
  65. package/dist/index.d.mts +1 -1
  66. package/dist/index.mjs +1 -1
  67. package/dist/instrumentation.d.mts +1 -1
  68. package/dist/instrumentation.mjs +1 -1
  69. package/dist/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
  70. package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
  71. package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
  72. package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  73. package/dist/{libsql-C8dn4id0.mjs → libsql-CrDXsfpL.mjs} +2 -2
  74. package/dist/{libsql-C8dn4id0.mjs.map → libsql-CrDXsfpL.mjs.map} +1 -1
  75. package/dist/libsql.d.mts +1 -1
  76. package/dist/libsql.mjs +1 -1
  77. package/dist/libsql.mjs.map +1 -1
  78. package/dist/{memory-B7CcHS6I.mjs → memory-TXO4KgBy.mjs} +2 -2
  79. package/dist/{memory-B7CcHS6I.mjs.map → memory-TXO4KgBy.mjs.map} +1 -1
  80. package/dist/migrations/mysql.d.mts +4 -4
  81. package/dist/migrations/mysql.mjs +1 -1
  82. package/dist/migrations/postgres.d.mts +4 -4
  83. package/dist/migrations/postgres.mjs +1 -1
  84. package/dist/migrations/sqlite.d.mts +4 -4
  85. package/dist/migrations/sqlite.mjs +1 -1
  86. package/dist/migrations/storage/durable-object.mjs +1 -1
  87. package/dist/migrations/storage/fs.mjs +1 -1
  88. package/dist/migrations/storage/r2.mjs +1 -1
  89. package/dist/migrations/tenant.d.mts +2 -2
  90. package/dist/migrations/tenant.mjs +1 -1
  91. package/dist/migrations.d.mts +4 -4
  92. package/dist/migrations.mjs +1 -1
  93. package/dist/{mysql-mUmhH9Cf.mjs → mysql-C2vOPcuA.mjs} +2 -2
  94. package/dist/{mysql-mUmhH9Cf.mjs.map → mysql-C2vOPcuA.mjs.map} +1 -1
  95. package/dist/mysql-adapter-C5CMIYRS.mjs +2 -0
  96. package/dist/{mysql-adapter-ABpgFB2N.mjs.map → mysql-adapter-C5CMIYRS.mjs.map} +1 -1
  97. package/dist/mysql2.d.mts +1 -1
  98. package/dist/mysql2.mjs +1 -1
  99. package/dist/mysql2.mjs.map +1 -1
  100. package/dist/neon-http.d.mts +3 -1
  101. package/dist/neon-http.mjs +1 -1
  102. package/dist/neon-http.mjs.map +1 -1
  103. package/dist/normalized-result-BF7gr4_b.mjs +2 -0
  104. package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
  105. package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
  106. package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
  107. package/dist/{object-store-Ds9NKRU6.d.mts → object-store-uRqi0URP.d.mts} +3 -3
  108. package/dist/permissions.d.mts +1 -1
  109. package/dist/pg.d.mts +26 -1
  110. package/dist/pg.mjs +1 -1
  111. package/dist/pg.mjs.map +1 -1
  112. package/dist/pglite.d.mts +3 -1
  113. package/dist/pglite.mjs +1 -1
  114. package/dist/pglite.mjs.map +1 -1
  115. package/dist/{pinned-session-C79aDzOg.mjs → pinned-session-FYOFV_gB.mjs} +2 -2
  116. package/dist/{pinned-session-C79aDzOg.mjs.map → pinned-session-FYOFV_gB.mjs.map} +1 -1
  117. package/dist/planetscale.d.mts +1 -1
  118. package/dist/planetscale.mjs +1 -1
  119. package/dist/planetscale.mjs.map +1 -1
  120. package/dist/{planner-DHZG9Vy7.d.mts → planner-SzkGh-3T.d.mts} +1 -1
  121. package/dist/{postgres-BACQ_wqF.mjs → postgres-BSmy1PYR.mjs} +2 -2
  122. package/dist/{postgres-BACQ_wqF.mjs.map → postgres-BSmy1PYR.mjs.map} +1 -1
  123. package/dist/postgres-adapter-B1RyJlWL.mjs +2 -0
  124. package/dist/{postgres-adapter-DaMvNOkx.mjs.map → postgres-adapter-B1RyJlWL.mjs.map} +1 -1
  125. package/dist/postgres-adapter-BAqRfWl1.mjs +2 -0
  126. package/dist/postgres-adapter-BAqRfWl1.mjs.map +1 -0
  127. package/dist/postgres-result-BCUQf8b_.mjs +2 -0
  128. package/dist/{postgres-result-D403cLyA.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
  129. package/dist/postgres.d.mts +3 -1
  130. package/dist/postgres.mjs +1 -1
  131. package/dist/postgres.mjs.map +1 -1
  132. package/dist/{provider-limits-DSv2tYFr.mjs → provider-limits-V09frtmK.mjs} +1 -1
  133. package/dist/{provider-limits-DSv2tYFr.mjs.map → provider-limits-V09frtmK.mjs.map} +1 -1
  134. package/dist/relation-bound-BrZLsSke.mjs +2 -0
  135. package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
  136. package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
  137. package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
  138. package/dist/result-shape-Fi1-Fvri.mjs +2 -0
  139. package/dist/result-shape-Fi1-Fvri.mjs.map +1 -0
  140. package/dist/{rows-v1VuwOTa.mjs → rows-BiaiswSV.mjs} +2 -2
  141. package/dist/{rows-v1VuwOTa.mjs.map → rows-BiaiswSV.mjs.map} +1 -1
  142. package/dist/schema/json.d.mts +1 -1
  143. package/dist/{schema-introspection-TdJrSaKd.mjs → schema-introspection-C1-XrQP4.mjs} +2 -2
  144. package/dist/{schema-introspection-TdJrSaKd.mjs.map → schema-introspection-C1-XrQP4.mjs.map} +1 -1
  145. package/dist/{schema-D3-ScVH6.mjs → schema-tGtziyCJ.mjs} +1 -1
  146. package/dist/{schema-D3-ScVH6.mjs.map → schema-tGtziyCJ.mjs.map} +1 -1
  147. package/dist/schema.d.mts +1 -1
  148. package/dist/schema.mjs +1 -1
  149. package/dist/select-assembly-BjT_fDbu.mjs +2 -0
  150. package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
  151. package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
  152. package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
  153. package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
  154. package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
  155. package/dist/soft-delete.d.mts +3 -3
  156. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
  157. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
  158. package/dist/sqlite-adapter-CoDeF2h2.mjs +2 -0
  159. package/dist/sqlite-adapter-CoDeF2h2.mjs.map +1 -0
  160. package/dist/{sqlite-utils-BvSlEs5W.mjs → sqlite-utils-C0TyzOys.mjs} +2 -2
  161. package/dist/{sqlite-utils-BvSlEs5W.mjs.map → sqlite-utils-C0TyzOys.mjs.map} +1 -1
  162. package/dist/sqlite3.d.mts +1 -1
  163. package/dist/sqlite3.mjs +1 -1
  164. package/dist/sqlite3.mjs.map +1 -1
  165. package/dist/{standard-sql-CYdZ_KXH.mjs → standard-sql-DmKF8msN.mjs} +2 -2
  166. package/dist/{standard-sql-CYdZ_KXH.mjs.map → standard-sql-DmKF8msN.mjs.map} +1 -1
  167. package/dist/transaction-operation-CU1zlxiG.mjs.map +1 -1
  168. package/dist/{utils-Qr8ug94X.mjs → utils-DkAxKcDD.mjs} +1 -1
  169. package/dist/{utils-Qr8ug94X.mjs.map → utils-DkAxKcDD.mjs.map} +1 -1
  170. package/dist/{validation-CPnrLcjW.mjs → validation-C7Z6wTJa.mjs} +1 -1
  171. package/dist/{validation-CPnrLcjW.mjs.map → validation-C7Z6wTJa.mjs.map} +1 -1
  172. package/dist/validation.d.mts +1 -1
  173. package/dist/validation.mjs +1 -1
  174. package/dist/version-n393hhwM.mjs +2 -0
  175. package/dist/{version-0RVYpih5.mjs.map → version-n393hhwM.mjs.map} +1 -1
  176. package/package.json +14 -14
  177. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs +0 -2
  178. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs.map +0 -1
  179. package/dist/builder-D6Ug-zjM.mjs +0 -2
  180. package/dist/builder-D6Ug-zjM.mjs.map +0 -1
  181. package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
  182. package/dist/chain-B5IbqLGi.mjs +0 -2
  183. package/dist/chain-B5IbqLGi.mjs.map +0 -1
  184. package/dist/client-BmcHzDBa.mjs +0 -2
  185. package/dist/client-BmcHzDBa.mjs.map +0 -1
  186. package/dist/client-DjtWangN.mjs.map +0 -1
  187. package/dist/driver-Bzc0GCQ4.mjs +0 -2
  188. package/dist/every-WUr3mlvg.mjs +0 -2
  189. package/dist/identity-Bj2EN6Ss.mjs +0 -2
  190. package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
  191. package/dist/mysql-adapter-ABpgFB2N.mjs +0 -2
  192. package/dist/postgres-adapter-Ci07rgh_.mjs +0 -2
  193. package/dist/postgres-adapter-Ci07rgh_.mjs.map +0 -1
  194. package/dist/postgres-adapter-DaMvNOkx.mjs +0 -2
  195. package/dist/postgres-result-D403cLyA.mjs +0 -2
  196. package/dist/result-shape-BKydBCsR.mjs +0 -2
  197. package/dist/result-shape-BKydBCsR.mjs.map +0 -1
  198. package/dist/select-assembly-uZfvbYjz.mjs +0 -2
  199. package/dist/select-assembly-uZfvbYjz.mjs.map +0 -1
  200. package/dist/sqlite-adapter-DPc9T6Lh.mjs +0 -2
  201. package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +0 -1
  202. package/dist/version-0RVYpih5.mjs +0 -2
@@ -0,0 +1,2 @@
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-gwZYm3Yn.mjs";import{E as i,g as a}from"./geo-point-codec-D95uXgDF.mjs";import{o,t as s}from"./sql-BvHwL73I.mjs";import{o as ee}from"./native-types-asNCr26n.mjs";import{a as te}from"./physical-uJfmo4-Z.mjs";import{t as c}from"./geo-area-codec-BmMmWgU_.mjs";import{t as l}from"./adapter-result-parser-D6lluSMi.mjs";import{r as u}from"./adapter-internals-Cy2QEBnH.mjs";import{a as d}from"./datetime-physical-codec-lX7IJBlz.mjs";import{t as f}from"./array-literal-BsbbSLw3.mjs";import{A as p,C as m,D as h,E as g,N as _,S as v,T as y,_ as b,a as x,b as S,c as C,d as w,f as T,h as E,i as D,j as O,l as k,m as A,n as j,o as M,p as ne,r as N,s as P,v as F,w as I,x as L,y as R}from"./standard-sql-DmKF8msN.mjs";import{r as z}from"./batch-refs-BYCu1JnQ.mjs";import{t as B}from"./adapter-namespace-BLejG8FA.mjs";import{a as V,c as H,i as U,l as W,m as G,n as K,p as q,r as J,s as Y,t as X}from"./select-assembly-BjT_fDbu.mjs";var Z=class JsonParameter{json;constructor(e){this.json=e,Object.freeze(this)}static from(e){let t=JSON.stringify(e);return t===void 0?void 0:new JsonParameter(t)}toString(){return this.json}toJSON(){return JSON.parse(this.json)}};const Q=_(`"`);function 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=g().list;function arrayParameter(e){let t=e[0];if(t===void 0)return;let n=t instanceof CastParameter?t.type:void 0,r=[];for(let t of e){let e=t instanceof CastParameter?t:void 0,[i,a,o]=t.strings;if(e?.type!==n||!e&&(i!==``||a!==``||o!==void 0))return;let s=t.values[0];if(s instanceof Uint8Array)r.push(`\\x${Array.from(s,e=>e.toString(16).padStart(2,`0`)).join(``)}`);else if(typeof s==`string`||typeof s==`number`||typeof s==`bigint`||typeof s==`boolean`)r.push(String(s));else return}let i=f(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>o`div(${e}, ${t})`,remainder:(e,t)=>o`mod(${e}, ${t})`},ae=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){B(this,e,`postgresql`),this.identifiers=T(Q,this.namespace,!0),q(this,t?this.#r():void 0),u(this,{batchRefs:this.#n,constraints:re,select:this.#e.select})}raw=v();identifiers;literals={...g(),dateTime:e=>o`${d(e)}`,true:()=>o.raw`TRUE`,false:()=>o.raw`FALSE`,json:e=>o`${Z.from(e)}`,decimal:(e,t)=>new CastParameter(i(e,t,`text`),a(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):o`${e}`,list:e=>arrayParameter(e)??ie(e)};operators={...x(),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 ${`${p(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>o`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>this.operators.in(this.expressions.caseSensitiveText(e,n,!1),t),in:(e,t)=>t instanceof ArrayParameter?o`${e} = ANY(${t})`:o`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?o`${e} <> ALL(${t})`:o`${e} NOT IN ${t}`,...F(),...L(),...E(this.literals.true,this.literals.false),...w()};expressions={...D(),caseSensitiveText:(e,t,r=!1)=>{let i=ee(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:N({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>o`encode(${e}, 'hex')`};aggregates={...j(`'Infinity'::float8`),min:(e,t=!1)=>t?o`BOOL_AND(${e})`:o`MIN(${e})`,max:(e,t=!1)=>t?o`BOOL_OR(${e})`:o`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:C(1e3)};json={equals:(e,t)=>o`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?o.raw`'[]'::json`:o`json_build_array(${o.join(e,`, `)})`,emptyArray:()=>o.raw`'[]'::json`,agg:e=>o`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>o`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>o`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>o`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>o`((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)}`,ofRows:e=>o`ARRAY(${e})`,has:(e,t)=>o`${t} = ANY(${e})`,hasEvery:(e,t)=>o`${e} @> ${t}`,hasSome:(e,t)=>o`${e} && ${t}`,isEmpty:e=>o`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>o`CAST(${e} AS TEXT[])`,length:e=>o`cardinality(${e})`,get:(e,t)=>o`${e}[${t}]`,push:(e,t)=>o`array_append(${e}, ${t})`,set:(e,t,n)=>o`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...k(),nullsFirst:(e,t)=>t===`desc`?o`${e} DESC NULLS FIRST`:o`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?o`${e} DESC NULLS LAST`:o`${e} ASC NULLS LAST`};clauses=y();set={...R(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):o`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?H($,e,t,n.decimal):o`${e} = ${e} / ${t}`,push:(e,t)=>o`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>o`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=m();subqueries=h(Q);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e.distinct?o`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:o`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=P(Q,{inlining:o.raw(`NOT MATERIALIZED`)});mutations={skipDuplicatesStrategy:`sql`,insert:ne(Q),insertDefault:e=>o`INSERT INTO ${e} DEFAULT VALUES`,...b(),returning:e=>o`RETURNING ${e}`,...S()};assertions={exists:e=>o`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>o`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,holds:(e,t)=>o`SELECT CASE WHEN ${e} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS "__viborm_judged__"${t?o` FROM ${t}`:o``}`};joins={...M(),full:(e,t)=>o`FULL OUTER JOIN ${e} ON ${t}`,...A(Q)};setOperations=I(Q,(e,t,n)=>{let r=o.raw(Q(e.alias)),column=e=>o.raw(Q(e)),[i,...a]=t,s=i.map((t,n)=>o`COALESCE(${t}, (${r}."row").${column(e.columns[n])})`);return o`(SELECT NULL::${e.table} AS "row") AS ${r} CROSS JOIN LATERAL (VALUES ${o.join([s,...a].map(O),`, `)}) AS ${o.raw(Q(n))}(${o.join(e.columns.map(column),`, `)})`});capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0,joinsJunctionFilters:`unbounded`};lastInsertId=()=>o.raw`lastval()`;#t=z({table:o.raw`"__viborm_batch_refs"`,batchIdColumn:o.raw`"batch_id"`,keyColumn:o.raw`"ref_key"`,valueColumn:o.raw`"ref_value"`,createTable:o.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>o`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>o`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new 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(${V(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=o`RADIANS(ST_X(${e}::geometry))`,r=o`RADIANS(ST_Y(${e}::geometry))`,i=o`RADIANS(ST_X(${t}::geometry))`,a=o`RADIANS(ST_Y(${t}::geometry))`;return o`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${c} 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)=>te(e,t,`pg`)?.representation??`text`,parseResult:l,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
2
+ //# sourceMappingURL=postgres-adapter-B1RyJlWL.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-adapter-DaMvNOkx.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, true);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // 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, sql.raw(\"NOT MATERIALIZED\"));\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,MAAM,KAAK,KAAK,GCuBhC,MAAM,EAAa,EAAuB,IAAI,CAC9C,SAAS,oBAAoB,EAAiB,CAC5C,MAAO,EAAG,2BAA2B,EAAM,4EAE7C,SAAS,sBAAsB,EAAgB,CAC7C,MAAO,EAAG,aAAa,EAAK,+DAE9B,SAA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ACT,GACC,CAAG,GAAG,EAAM,oCAAoC,EAAQ,qBAC3D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,iCAAiC,EACpD,EACD,CAAC,qBACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IAAU,CACzB,IAAM,EAAgB,CAAG,gBAAgB,EAAK,cACxC,EAAe,CAAG,gBAAgB,EAAK,cACvC,EAAiB,CAAG,gBAAgB,EAAM,cAC1C,EAAgB,CAAG,gBAAgB,EAAM,cAI/C,MAAO,EAAG,aAAa,EAAK,cAAc,EAAM,+BAA+B,EAA8B,6DAH3F,CAAG,cAAc,EAAc,KAAK,EAAa,mBAAmB,EAAa,UAAU,EAAc,iBAAiB,EAAe,KAAK,EAAc,YAGM,WAEvL,CAGH,OAAoC,CAIlC,wBAAyB,GAIzB,uBAAwB,YAKxB,kBAAmB,EAAQ,IACzB,GAAY,EAAQ,EAAY,KAAK,EAAE,gBAAkB,OAY3D,YAAa,EAEb,eACE,EACA,IAGO,GAAM,CAGf,YACE,EACA,EACA,IAGO,GAAM,CAEhB"}
1
+ {"version":3,"file":"postgres-adapter-B1RyJlWL.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, true);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // 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 ofRows: (query: Sql): Sql => sql`ARRAY(${query})`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n const selectClause = parts.distinct\n ? sql`SELECT DISTINCT ON (${parts.distinct}) ${parts.columns}`\n : sql`SELECT ${parts.columns}`;\n\n return assembleSelectQuery(selectClause, parts, { forUpdate: \"append\" });\n },\n };\n\n cte = createCteBuilders(quoteIdent, {\n inlining: sql.raw(\"NOT MATERIALIZED\"),\n });\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n // The refusal names its sentinel (22P02, `invalid input syntax for type\n // integer: \"__viborm_refused__\"`), which no caller's division by zero\n // does; the text is a sublink, which PostgreSQL does not fold while\n // planning, so it is evaluated only where it is reached.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS \"__viborm_judged__\"${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n /**\n * The produced rows as a `VALUES` list: PostgreSQL parses each `UNION ALL`\n * arm one recursion deeper (`54001`, stack depth, at 8,000 rows on 16.14),\n * and a list is no deeper for its length. A `VALUES` column is typed by its\n * own rows, an unknown parameter as `text`, so the first row takes each\n * column's type from a NULL of the table's row type (`COALESCE`, the rule\n * a `UNION` arm met), beside the list, as a one-row FROM item. The NULL is\n * cast to the table's type, never read as `SELECT \"qN\" FROM table AS \"qN\"`:\n * there a column named `qN` would win over the whole-row reference (42809),\n * and the cast reads no relation at all.\n */\n setOperations = createSetOperations(quoteIdent, (typed, rows, alias) => {\n const name = sql.raw(quoteIdent(typed.alias));\n const column = (field: string) => sql.raw(quoteIdent(field));\n const [first, ...rest] = rows;\n const typedFirst = first!.map(\n (value, index) =>\n sql`COALESCE(${value}, (${name}.\"row\").${column(typed.columns[index]!)})`\n );\n return sql`(SELECT NULL::${typed.table} AS \"row\") AS ${name} CROSS JOIN LATERAL (VALUES ${sql.join(\n [typedFirst, ...rest].map(rowValues),\n \", \"\n )}) AS ${sql.raw(quoteIdent(alias))}(${sql.join(typed.columns.map(column), \", \")})`;\n });\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n joinsJunctionFilters: \"unbounded\",\n };\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":"+gCA+BA,IAAa,EAAb,MAAa,aAAc,CAEzB,KAEA,YAAoB,EAAc,CAChC,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CASrB,OAAO,KAAK,EAA2C,CAGrD,IAAM,EAA2B,KAAK,UAAU,EAAM,CACtD,OAAO,IAAS,IAAA,GAAY,IAAA,GAAY,IAAI,cAAc,EAAK,CAGjE,UAAmB,CACjB,OAAO,KAAK,KAGd,QAAkB,CAChB,OAAO,KAAK,MAAM,KAAK,KAAK,GCuBhC,MAAM,EAAa,EAAuB,IAAI,CAC9C,SAAS,oBAAoB,EAAiB,CAC5C,MAAO,EAAG,2BAA2B,EAAM,4EAE7C,SAAS,sBAAsB,EAAgB,CAC7C,MAAO,EAAG,aAAa,EAAK,+DAE9B,SAAS,mBAAmB,EAA6B,CACvD,GAAI,EAAM,SAAW,EAAG,MAAO,GAAI,GAAG,aACtC,IAAM,EAAgB,EAAE,CAClB,EAAcA,EAAI,IACtB,EAAM,OAAS,GAAK,qBAAuB,oBAC5C,CAGD,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,GAAI,CACrD,IAAM,EAAO,EACV,MAAM,EAAO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B,IAAM,EAAgB,CAAG,gBAAgB,EAAK,cACxC,EAAe,CAAG,gBAAgB,EAAK,cACvC,EAAiB,CAAG,gBAAgB,EAAM,cAC1C,EAAgB,CAAG,gBAAgB,EAAM,cAI/C,MAAO,EAAG,aAAa,EAAK,cAAc,EAAM,+BAA+B,EAA8B,6DAH3F,CAAG,cAAc,EAAc,KAAK,EAAa,mBAAmB,EAAa,UAAU,EAAc,iBAAiB,EAAe,KAAK,EAAc,YAGM,WAEvL,CAGH,OAAoC,CAIlC,wBAAyB,GAIzB,uBAAwB,YAKxB,kBAAmB,EAAQ,IACzB,GAAY,EAAQ,EAAY,KAAK,EAAE,gBAAkB,OAY3D,YAAa,EAEb,eACE,EACA,IAGO,GAAM,CAGf,YACE,EACA,EACA,IAGO,GAAM,CAEhB"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,r as n}from"./validation-gwZYm3Yn.mjs";import{o as r}from"./driver-CQQbCQh9.mjs";import{t as i}from"./postgres-adapter-B1RyJlWL.mjs";function installPostgresAdapter(e,a,o){let s=new i(a,o.postgis===!0);s.capabilities.supportsVector=o.pgvector===!0;let c=o.relationsPerStatement;if(c!==void 0&&!(Number.isSafeInteger(c)&&c>0))throw new n(`The "relationsPerStatement" option must be a positive integer (256 for PlanetScale Neki); received ${typeof c==`number`?c:`type "${typeof c}"`}.`);o.sharedRelationBodies!==!1&&(s.capabilities.sharesRelationBodies=!0,s.capabilities.relationsPerStatement=c),o.pgvector||(s.vector=t),r(e,`adapter`,s)}export{installPostgresAdapter as t};
2
+ //# sourceMappingURL=postgres-adapter-BAqRfWl1.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-adapter-BAqRfWl1.mjs","names":[],"sources":["../src/drivers/shared/postgres-adapter.ts"],"sourcesContent":["import { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport { ClientInitializationError, unsupportedVector } from \"@errors\";\nimport { defineImmutableDriverFact } from \"./driver-options\";\n\n/**\n * Install a PostgreSQL driver's adapter: `pgvector` alone decides the vector\n * capability, `postgis` the spatial one, `sharedRelationBodies` whether a\n * statement states each relation body it repeats once (the default: the\n * answers are the same and the statement smaller; `false` keeps every body\n * inline, as 1.2.4 spelled it), `relationsPerStatement` the relations a\n * statement may reference before it trades plans for fewer (absent:\n * unbounded until the server says otherwise, `relation-bound.ts`; PlanetScale\n * Neki needs 256).\n */\nexport function installPostgresAdapter(\n driver: object,\n namespace: string | undefined,\n options: {\n readonly pgvector?: boolean;\n readonly postgis?: boolean;\n readonly sharedRelationBodies?: boolean;\n readonly relationsPerStatement?: number;\n }\n): void {\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n const bound = options.relationsPerStatement;\n // A bound of 0, a fraction or NaN would escalate every statement or none.\n if (bound !== undefined && !(Number.isSafeInteger(bound) && bound > 0))\n throw new ClientInitializationError(\n `The \"relationsPerStatement\" option must be a positive integer (256 for PlanetScale Neki); received ${typeof bound === \"number\" ? bound : `type \"${typeof bound}\"`}.`\n );\n if (options.sharedRelationBodies !== false) {\n adapter.capabilities.sharesRelationBodies = true;\n adapter.capabilities.relationsPerStatement = bound;\n }\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(driver, \"adapter\", adapter);\n}\n"],"mappings":"4LAcA,SAAgB,uBACd,EACA,EACA,EAMM,CACN,IAAM,EAAU,IAAI,EAAgB,EAAW,EAAQ,UAAY,GAAK,CACxE,EAAQ,aAAa,eAAiB,EAAQ,WAAa,GAC3D,IAAM,EAAQ,EAAQ,sBAEtB,GAAI,IAAU,IAAA,IAAa,EAAE,OAAO,cAAc,EAAM,EAAI,EAAQ,GAClE,MAAM,IAAI,EACR,sGAAsG,OAAO,GAAU,SAAW,EAAQ,SAAS,OAAO,EAAM,GAAG,GACpK,CACC,EAAQ,uBAAyB,KACnC,EAAQ,aAAa,qBAAuB,GAC5C,EAAQ,aAAa,sBAAwB,GAE1C,EAAQ,WAAU,EAAQ,OAAS,GACxC,EAA0B,EAAQ,UAAW,EAAQ"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t,r as n}from"./normalized-result-BF7gr4_b.mjs";import{p as r}from"./validation-gwZYm3Yn.mjs";const i=/\s+/,a=/^[A-Za-z]+$/,o=new Set([`COPY`,`DELETE`,`FETCH`,`INSERT`,`MERGE`,`MOVE`,`SELECT`,`UPDATE`]),s=new Set(`ALTER.ANALYZE.BEGIN.CALL.CHECKPOINT.CLOSE.CLUSTER.COMMENT.COMMIT.CREATE.DEALLOCATE.DECLARE.DISCARD.DO.DROP.END.EXPLAIN.GRANT.IMPORT.LISTEN.LOAD.LOCK.NOTIFY.PREPARE.REASSIGN.REFRESH.REINDEX.RELEASE.RESET.REVOKE.ROLLBACK.SAVEPOINT.SECURITY.SET.SHOW.START.TRUNCATE.UNLISTEN.VACUUM`.split(`.`));function malformedPostgresResult(e,t){return new r(`Driver "${e.provider}" returned malformed PostgreSQL result metadata for operation "${e.operation}": ${t}.`,{meta:n(e)})}function normalizePostgresRowCount(e,n,r,c){if(!Array.isArray(r))throw malformedPostgresResult(c,`the rows payload is not an array`);if(typeof n!=`string`||n.trim()===``)throw malformedPostgresResult(c,`the command tag is invalid`);let[l]=n.trim().split(i,1);if(!(l&&a.test(l)))throw malformedPostgresResult(c,`the command tag is invalid`);let u=l.toUpperCase(),d=o.has(u),f=s.has(u);if(!(d||f))throw malformedPostgresResult(c,`the command tag is unknown`);if(e!==null)return t(e,c);if(d)throw malformedPostgresResult(c,`command ${u} requires a numeric row count`);return r.length}export{normalizePostgresRowCount as t};
2
+ //# sourceMappingURL=postgres-result-BCUQf8b_.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-result-D403cLyA.mjs","names":[],"sources":["../src/drivers/shared/postgres-result.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport {\n createNormalizedResultMeta,\n type NormalizedResultContext,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\n\nconst COMMAND_SEPARATOR_REGEX = /\\s+/;\nconst COMMAND_TOKEN_REGEX = /^[A-Za-z]+$/;\n\nconst COUNTED_COMMANDS = new Set([\n \"COPY\",\n \"DELETE\",\n \"FETCH\",\n \"INSERT\",\n \"MERGE\",\n \"MOVE\",\n \"SELECT\",\n \"UPDATE\",\n]);\n\nconst NULLABLE_COUNT_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"BEGIN\",\n \"CALL\",\n \"CHECKPOINT\",\n \"CLOSE\",\n \"CLUSTER\",\n \"COMMENT\",\n \"COMMIT\",\n \"CREATE\",\n \"DEALLOCATE\",\n \"DECLARE\",\n \"DISCARD\",\n \"DO\",\n \"DROP\",\n \"END\",\n \"EXPLAIN\",\n \"GRANT\",\n \"IMPORT\",\n \"LISTEN\",\n \"LOAD\",\n \"LOCK\",\n \"NOTIFY\",\n \"PREPARE\",\n \"REASSIGN\",\n \"REFRESH\",\n \"REINDEX\",\n \"RELEASE\",\n \"RESET\",\n \"REVOKE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SECURITY\",\n \"SET\",\n \"SHOW\",\n \"START\",\n \"TRUNCATE\",\n \"UNLISTEN\",\n \"VACUUM\",\n]);\n\nfunction malformedPostgresResult(\n context: NormalizedResultContext,\n reason: string\n): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned malformed PostgreSQL result metadata for operation \"${context.operation}\": ${reason}.`,\n { meta: createNormalizedResultMeta(context) }\n );\n}\n\n/**\n * PostgreSQL command tags carry a numeric count only for a defined set of\n * commands. Other known tags legitimately expose null, while missing metadata\n * and null counts for counted commands are malformed provider successes.\n */\nexport function normalizePostgresRowCount(\n value: unknown,\n command: unknown,\n rows: unknown,\n context: NormalizedResultContext\n): number {\n if (!Array.isArray(rows)) {\n throw malformedPostgresResult(context, \"the rows payload is not an array\");\n }\n if (typeof command !== \"string\" || command.trim() === \"\") {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const [commandToken] = command.trim().split(COMMAND_SEPARATOR_REGEX, 1);\n if (!(commandToken && COMMAND_TOKEN_REGEX.test(commandToken))) {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const normalizedCommand = commandToken.toUpperCase();\n const isCountedCommand = COUNTED_COMMANDS.has(normalizedCommand);\n const isNullableCountCommand = NULLABLE_COUNT_COMMANDS.has(normalizedCommand);\n if (!(isCountedCommand || isNullableCountCommand)) {\n throw malformedPostgresResult(context, \"the command tag is unknown\");\n }\n if (value !== null) {\n return normalizeProviderRowCount(value, context);\n }\n if (isCountedCommand) {\n throw malformedPostgresResult(\n context,\n `command ${normalizedCommand} requires a numeric row count`\n );\n }\n return rows.length;\n}\n"],"mappings":"yJAOA,MAAM,EAA0B,MAC1B,EAAsB,cAEtB,EAAmB,IAAI,IAAI,CAC/B,OACA,SACA,QACA,SACA,QACA,OACA,SACA,SACD,CAAC,CAEI,EAA0B,IAAI,IAAI,kSAwCvC,CAAC,CAEF,SAAS,wBACP,EACA,EACY,CACZ,OAAO,IAAI,EACT,WAAW,EAAQ,SAAS,iEAAiE,EAAQ,UAAU,KAAK,EAAO,GAC3H,CAAE,KAAM,EAA2B,EAAQ,CAAE,CAC9C,CAQH,SAAgB,0BACd,EACA,EACA,EACA,EACQ,CACR,GAAI,CAAC,MAAM,QAAQ,EAAK,CACtB,MAAM,wBAAwB,EAAS,mCAAmC,CAE5E,GAAI,OAAO,GAAY,UAAY,EAAQ,MAAM,GAAK,GACpD,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAM,CAAC,GAAgB,EAAQ,MAAM,CAAC,MAAM,EAAyB,EAAE,CACvE,GAAI,EAAE,GAAgB,EAAoB,KAAK,EAAa,EAC1D,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,IAAM,EAAoB,EAAa,aAAa,CAC9C,EAAmB,EAAiB,IAAI,EAAkB,CAC1D,EAAyB,EAAwB,IAAI,EAAkB,CAC7E,GAAI,EAAE,GAAoB,GACxB,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAI,IAAU,KACZ,OAAO,EAA0B,EAAO,EAAQ,CAElD,GAAI,EACF,MAAM,wBACJ,EACA,WAAW,EAAkB,+BAC9B,CAEH,OAAO,EAAK"}
1
+ {"version":3,"file":"postgres-result-BCUQf8b_.mjs","names":[],"sources":["../src/drivers/shared/postgres-result.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport {\n createNormalizedResultMeta,\n type NormalizedResultContext,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\n\nconst COMMAND_SEPARATOR_REGEX = /\\s+/;\nconst COMMAND_TOKEN_REGEX = /^[A-Za-z]+$/;\n\nconst COUNTED_COMMANDS = new Set([\n \"COPY\",\n \"DELETE\",\n \"FETCH\",\n \"INSERT\",\n \"MERGE\",\n \"MOVE\",\n \"SELECT\",\n \"UPDATE\",\n]);\n\nconst NULLABLE_COUNT_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"BEGIN\",\n \"CALL\",\n \"CHECKPOINT\",\n \"CLOSE\",\n \"CLUSTER\",\n \"COMMENT\",\n \"COMMIT\",\n \"CREATE\",\n \"DEALLOCATE\",\n \"DECLARE\",\n \"DISCARD\",\n \"DO\",\n \"DROP\",\n \"END\",\n \"EXPLAIN\",\n \"GRANT\",\n \"IMPORT\",\n \"LISTEN\",\n \"LOAD\",\n \"LOCK\",\n \"NOTIFY\",\n \"PREPARE\",\n \"REASSIGN\",\n \"REFRESH\",\n \"REINDEX\",\n \"RELEASE\",\n \"RESET\",\n \"REVOKE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SECURITY\",\n \"SET\",\n \"SHOW\",\n \"START\",\n \"TRUNCATE\",\n \"UNLISTEN\",\n \"VACUUM\",\n]);\n\nfunction malformedPostgresResult(\n context: NormalizedResultContext,\n reason: string\n): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned malformed PostgreSQL result metadata for operation \"${context.operation}\": ${reason}.`,\n { meta: createNormalizedResultMeta(context) }\n );\n}\n\n/**\n * PostgreSQL command tags carry a numeric count only for a defined set of\n * commands. Other known tags legitimately expose null, while missing metadata\n * and null counts for counted commands are malformed provider successes.\n */\nexport function normalizePostgresRowCount(\n value: unknown,\n command: unknown,\n rows: unknown,\n context: NormalizedResultContext\n): number {\n if (!Array.isArray(rows)) {\n throw malformedPostgresResult(context, \"the rows payload is not an array\");\n }\n if (typeof command !== \"string\" || command.trim() === \"\") {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const [commandToken] = command.trim().split(COMMAND_SEPARATOR_REGEX, 1);\n if (!(commandToken && COMMAND_TOKEN_REGEX.test(commandToken))) {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const normalizedCommand = commandToken.toUpperCase();\n const isCountedCommand = COUNTED_COMMANDS.has(normalizedCommand);\n const isNullableCountCommand = NULLABLE_COUNT_COMMANDS.has(normalizedCommand);\n if (!(isCountedCommand || isNullableCountCommand)) {\n throw malformedPostgresResult(context, \"the command tag is unknown\");\n }\n if (value !== null) {\n return normalizeProviderRowCount(value, context);\n }\n if (isCountedCommand) {\n throw malformedPostgresResult(\n context,\n `command ${normalizedCommand} requires a numeric row count`\n );\n }\n return rows.length;\n}\n"],"mappings":"mJAOA,MAAM,EAA0B,MAC1B,EAAsB,cAEtB,EAAmB,IAAI,IAAI,CAC/B,OACA,SACA,QACA,SACA,QACA,OACA,SACA,SACD,CAAC,CAEI,EAA0B,IAAI,IAAI,kSAwCvC,CAAC,CAEF,SAAS,wBACP,EACA,EACY,CACZ,OAAO,IAAI,EACT,WAAW,EAAQ,SAAS,iEAAiE,EAAQ,UAAU,KAAK,EAAO,GAC3H,CAAE,KAAM,EAA2B,EAAQ,CAAE,CAC9C,CAQH,SAAgB,0BACd,EACA,EACA,EACA,EACQ,CACR,GAAI,CAAC,MAAM,QAAQ,EAAK,CACtB,MAAM,wBAAwB,EAAS,mCAAmC,CAE5E,GAAI,OAAO,GAAY,UAAY,EAAQ,MAAM,GAAK,GACpD,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAM,CAAC,GAAgB,EAAQ,MAAM,CAAC,MAAM,EAAyB,EAAE,CACvE,GAAI,EAAE,GAAgB,EAAoB,KAAK,EAAa,EAC1D,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,IAAM,EAAoB,EAAa,aAAa,CAC9C,EAAmB,EAAiB,IAAI,EAAkB,CAC1D,EAAyB,EAAwB,IAAI,EAAkB,CAC7E,GAAI,EAAE,GAAoB,GACxB,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAI,IAAU,KACZ,OAAO,EAA0B,EAAO,EAAQ,CAElD,GAAI,EACF,MAAM,wBACJ,EACA,WAAW,EAAkB,+BAC9B,CAEH,OAAO,EAAK"}
@@ -1,4 +1,4 @@
1
- import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-B_jh2oaQ.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-B4IWFJfv.mjs";
2
2
  import postgres, { Options, Sql } from "postgres";
3
3
 
4
4
  //#region src/drivers/postgres/index.d.ts
@@ -12,6 +12,8 @@ interface PostgresDriverOptions {
12
12
  postgis?: boolean;
13
13
  /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */
14
14
  sharedRelationBodies?: boolean;
15
+ /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. PlanetScale Neki refuses more than 256: absent, the driver reads each connection's startup, 256 on Neki and before the first connection, none elsewhere. A stated bound always wins. Only where relation bodies are shared. */
16
+ relationsPerStatement?: number;
15
17
  databaseUrl?: string;
16
18
  /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */
17
19
  namespace?: string;
package/dist/postgres.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{d as n,l as r,r as i}from"./error-mapping-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./suppressed-failure-Bdo2aK81.mjs";import{s}from"./execution-context-rJXTRVrJ.mjs";import{n as c}from"./client-BmcHzDBa.mjs";import{i as l,t as u}from"./pinned-session-C79aDzOg.mjs";import{c as d,d as f,f as p,i as m,o as h,s as g,t as _,u as v}from"./driver-Bzc0GCQ4.mjs";import{t as y}from"./postgres-result-D403cLyA.mjs";import{t as b}from"./postgres-adapter-Ci07rgh_.mjs";import x from"postgres";const S={timestamp:{to:1114,from:[1082,1114,1184],serialize:e=>e instanceof Date?e.toISOString():String(e),parse:e=>e},json:{to:114,from:[114,3802],serialize:e=>typeof e==`string`?e:JSON.stringify(e),parse:e=>JSON.parse(e)}};function encodeListParameters(e){return e.map(e=>Array.isArray(e)?`{${e.map(e=>e===null?`NULL`:`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`).join(`,`)}}`:e)}const withVibormTypes=(e={})=>({...e,types:{...S,...e.types}}),C={client:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0},isTransaction=e=>`savepoint`in e;var PostgresDriver=class extends _{maxBindParametersPerStatement=65533;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`postgres`);let t=f(e);this.driverOptions={databaseUrl:e.databaseUrl,options:{...e.options}},this.suppliedClient=e.client;let{host:n,hostname:r}=this.driverOptions.options??{};if(g(`postgres`,e,!!(this.suppliedClient||n||r)),this.suppliedClient){for(let e of[1082,1114,1184])if(this.suppliedClient.options?.parsers[e]!==S.timestamp?.parse)throw new a(`A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).`,{meta:{driver:`postgres`,operation:`configuration`}});this.client=this.suppliedClient}b(this,t,e),h(this,`migrationSessionAttestation`,v(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions;return[e,t?.host,t?.hostname,...this.suppliedClient?.options.host??[]]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{databaseUrl:e,options:t}=this.driverOptions;return e?x(p(e),withVibormTypes(t)):x(withVibormTypes(t))}async closeClient(e){e!==this.suppliedClient&&await e.end()}async execute(e,t,n,r){return this.executeQuery(e,t,encodeListParameters(n),r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=await e.unsafe(t,n,{prepare:this.driverOptions.options?.prepare===!0});return{rows:o,rowCount:y(o.count,o.command,o,{provider:`postgres`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,t,i,a){if(isTransaction(e))throw r(this.driverName);return n({run:async t=>{let n=!1;try{return await e.begin(e=>(n=!0,t(e)))}catch(t){throw!n&&this.isConnectionFailure(t)&&await this.recoverFailedBegin(e,t,a?.maxWaitMs??5e3),t}},callback:t,phases:s(i),close:async()=>void 0})}isConnectionFailure(e){let n=i(e,{driverName:this.driverName,dialect:this.dialect});return n.code===t.CONNECTION_FAILED||n.code===t.CONNECTION_TIMEOUT}async recoverFailedBegin(e,t,n){let r=Date.now()+n;for(let n=0;n<2;n++){let n=r-Date.now();if(n<=0)break;try{(await m(()=>e.reserve(),e=>e.release(),n,{driverName:this.driverName,form:`callback`})).release();return}catch(e){if(o(t,e),!this.isConnectionFailure(e))break}}}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(isTransaction(e))throw r(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>l({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.end({timeout:u/1e3})}})}}};function createClient(e){d(e,`postgres`,C);let{client:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=f(e),s=v(e);return c(e,new PostgresDriver({client:t,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,namespace:o,migrationSessionAttestation:s}))}export{PostgresDriver,createClient,S as vibormTypes};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{d as n,l as r,r as i}from"./error-mapping-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./suppressed-failure-Bdo2aK81.mjs";import{s}from"./execution-context-rJXTRVrJ.mjs";import{n as c}from"./client-Bhl2mWam.mjs";import{i as l,t as u}from"./pinned-session-FYOFV_gB.mjs";import{c as d,d as f,f as p,i as m,o as h,s as g,t as _,u as v}from"./driver-CQQbCQh9.mjs";import{t as y}from"./postgres-result-BCUQf8b_.mjs";import{t as b}from"./postgres-adapter-BAqRfWl1.mjs";import{n as x,t as S}from"./relation-bound-BrZLsSke.mjs";import C from"postgres";const w={timestamp:{to:1114,from:[1082,1114,1184],serialize:e=>e instanceof Date?e.toISOString():String(e),parse:e=>e},json:{to:114,from:[114,3802],serialize:e=>typeof e==`string`?e:JSON.stringify(e),parse:e=>JSON.parse(e)}};function encodeListParameters(e){return e.map(e=>Array.isArray(e)?`{${e.map(e=>e===null?`NULL`:`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`).join(`,`)}}`:e)}const withVibormTypes=(e={})=>({...e,types:{...w,...e.types}}),T={client:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0},isTransaction=e=>`savepoint`in e;var PostgresDriver=class extends _{maxBindParametersPerStatement=65533;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`postgres`);let t=f(e);this.driverOptions={databaseUrl:e.databaseUrl,options:{...e.options}},this.suppliedClient=e.client;let{host:n,hostname:r}=this.driverOptions.options??{};if(g(`postgres`,e,!!(this.suppliedClient||n||r)),this.suppliedClient){for(let e of[1082,1114,1184])if(this.suppliedClient.options?.parsers[e]!==w.timestamp?.parse)throw new a(`A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).`,{meta:{driver:`postgres`,operation:`configuration`}});this.client=this.suppliedClient}b(this,t,e),S(this.adapter,()=>{let e=this.client;return e&&!isTransaction(e)?e.parameters.server_version:void 0}),h(this,`migrationSessionAttestation`,v(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions;return[e,t?.host,t?.hostname,...this.suppliedClient?.options.host??[]]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{databaseUrl:e,options:t}=this.driverOptions;return e?C(p(e),withVibormTypes(t)):C(withVibormTypes(t))}async closeClient(e){e!==this.suppliedClient&&await e.end()}async execute(e,t,n,r){return this.executeQuery(e,t,encodeListParameters(n),r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=await e.unsafe(t,n,{prepare:this.driverOptions.options?.prepare===!0}).catch(e=>{throw x(this.adapter,e),e});return{rows:o,rowCount:y(o.count,o.command,o,{provider:`postgres`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,t,i,a){if(isTransaction(e))throw r(this.driverName);return n({run:async t=>{let n=!1;try{return await e.begin(e=>(n=!0,t(e)))}catch(t){throw!n&&this.isConnectionFailure(t)&&await this.recoverFailedBegin(e,t,a?.maxWaitMs??5e3),t}},callback:t,phases:s(i),close:async()=>void 0})}isConnectionFailure(e){let n=i(e,{driverName:this.driverName,dialect:this.dialect});return n.code===t.CONNECTION_FAILED||n.code===t.CONNECTION_TIMEOUT}async recoverFailedBegin(e,t,n){let r=Date.now()+n;for(let n=0;n<2;n++){let n=r-Date.now();if(n<=0)break;try{(await m(()=>e.reserve(),e=>e.release(),n,{driverName:this.driverName,form:`callback`})).release();return}catch(e){if(o(t,e),!this.isConnectionFailure(e))break}}}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(isTransaction(e))throw r(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>l({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.end({timeout:u/1e3})}})}}};function createClient(e){d(e,`postgres`,T);let{client:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=f(e),s=v(e);return c(e,new PostgresDriver({client:t,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:o,migrationSessionAttestation:s}))}export{PostgresDriver,createClient,w as vibormTypes};
2
2
  //# sourceMappingURL=postgres.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/drivers/postgres/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (postgres.js)\n *\n * Driver implementation for postgres.js - a modern, fast PostgreSQL client.\n *\n * Generated statements use unsafe(query, values, queryOptions). Preparation\n * defaults to false for pooler compatibility; options.prepare: true opts into\n * the provider's prepared-statement reuse on compatible sessions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, VibORMErrorCode } from \"@errors\";\nimport postgres, {\n type Options as PostgresOptionsType,\n type Sql as PostgresSql,\n} from \"postgres\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { normalizeDriverError } from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nexport type PostgresOptions = PostgresOptionsType<\n Record<string, postgres.PostgresType>\n>;\n\ntype PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;\n\nexport interface PostgresDriverOptions {\n client?: PostgresSql<Record<string, unknown>>;\n options?: PostgresOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport const vibormTypes: Record<string, postgres.PostgresType> = {\n // TIMESTAMP WITHOUT TIME ZONE (1114): postgres.js builds process-local\n // Dates, shifting the stored UTC wall clock by the process timezone. Keep\n // the raw string — the shared result parser builds a UTC Date from it,\n // matching every other driver. (DATE already arrives as a string.)\n timestamp: {\n to: 1114,\n from: [1082, 1114, 1184],\n serialize: (value: unknown) =>\n value instanceof Date ? value.toISOString() : String(value),\n parse: (value: string) => value,\n },\n // The adapter binds a `JsonParameter` carrier (src/sql/json-parameter.ts),\n // which the object arm serializes to its canonical text via `toJSON`. The\n // string arm exists for raw SQL: a caller's own JSON text bound to a\n // json/jsonb parameter must not be JSON.stringify'd a second time once the\n // server declares the param type — that double-encodes the stored value.\n json: {\n to: 114,\n from: [114, 3802],\n serialize: (value: unknown) =>\n typeof value === \"string\" ? value : JSON.stringify(value),\n parse: (value: string) => JSON.parse(value),\n },\n};\n\n/** Bind validated one-dimensional lists as PostgreSQL text, letting SQL infer\n * the column type; postgres.js otherwise guesses bigint[]/boolean[] wrongly. */\nfunction encodeListParameters(params: unknown[]): unknown[] {\n return params.map((value) =>\n Array.isArray(value)\n ? `{${value.map((member) => (member === null ? \"NULL\" : `\"${String(member).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`)).join(\",\")}}`\n : value\n );\n}\n\nconst withVibormTypes = (options: PostgresOptions = {}): PostgresOptions => ({\n ...options,\n types: { ...vibormTypes, ...options.types },\n});\n\nexport type PostgresClientConfig<C extends DriverConfig> =\n PostgresDriverOptions & C;\n\nconst POSTGRES_CONFIG_KEYS: Record<keyof PostgresDriverOptions, true> = {\n client: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n databaseUrl: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\ntype PostgresClient = PostgresSql<Record<string, unknown>>;\n\nconst isTransaction = (\n client: PostgresClient | PostgresTransaction\n): client is PostgresTransaction => {\n return \"savepoint\" in client;\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PostgresDriver extends Driver<\n PostgresClient,\n PostgresTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_533;\n\n private readonly driverOptions: PostgresDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: PostgresClient | undefined;\n\n constructor(options: PostgresDriverOptions = {}) {\n super(\"postgresql\", \"postgres\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = {\n databaseUrl: options.databaseUrl,\n options: { ...options.options },\n };\n this.suppliedClient = options.client;\n const { host, hostname } = this.driverOptions.options ?? {};\n refuseEmptyDatabaseUrl(\n \"postgres\",\n options,\n Boolean(this.suppliedClient || host || hostname)\n );\n\n if (this.suppliedClient) {\n for (const oid of [1082, 1114, 1184]) {\n if (\n this.suppliedClient.options?.parsers[oid] !==\n vibormTypes.timestamp?.parse\n ) {\n throw new ClientInitializationError(\n \"A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).\",\n { meta: { driver: \"postgres\", operation: \"configuration\" } }\n );\n }\n }\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n return [\n databaseUrl,\n options?.host,\n options?.hostname,\n ...(this.suppliedClient?.options.host ?? []),\n ];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<PostgresClient> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n // postgres.js reads the URL for the keys it carries and lets every key\n // set in options win, which is the documented precedence.\n const { databaseUrl, options } = this.driverOptions;\n return databaseUrl\n ? postgres(systemRootAsVerifyFull(databaseUrl), withVibormTypes(options))\n : postgres(withVibormTypes(options));\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to end it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: PostgresClient): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.end();\n }\n\n protected async execute<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n // postgres.js unsafe() takes (query, parameters?, queryOptions?)\n // parameters must be cast as postgres expects specific types\n return this.executeQuery(\n client,\n sqlStr,\n encodeListParameters(params),\n context,\n \"execute\"\n );\n }\n\n protected async executeRaw<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sqlStr, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.unsafe<T[]>(sqlStr, params, {\n prepare: this.driverOptions.options?.prepare === true,\n });\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n /**\n * postgres.js owns BEGIN inside `client.begin()`, so the isolation level goes\n * in as the transaction's first statement. It also owns connection\n * acquisition inside that same call: there is no acquisition step VibORM can\n * bound or abandon, so `maxWait` is refused rather than faked.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: PostgresClient | PostgresTransaction,\n fn: (tx: PostgresTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: async (callback) => {\n let entered = false;\n try {\n return await client.begin((tx) => {\n entered = true;\n return callback(tx);\n });\n } catch (error) {\n if (!entered && this.isConnectionFailure(error))\n await this.recoverFailedBegin(\n client,\n error,\n options?.maxWaitMs ?? 5000\n );\n throw error;\n }\n },\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n private isConnectionFailure(error: unknown): boolean {\n const failure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n });\n return (\n failure.code === VibORMErrorCode.CONNECTION_FAILED ||\n failure.code === VibORMErrorCode.CONNECTION_TIMEOUT\n );\n }\n\n private async recoverFailedBegin(\n client: PostgresClient,\n primary: unknown,\n maxWaitMs: number\n ): Promise<void> {\n // postgres.js can retain a fatal response across reconnect, rejecting the\n // next acquisition before dispatch. Drain that startup error with leases,\n // never caller SQL; the callback above has provably not entered. A drain\n // that cannot connect needs no quarantine: a connection failure before the\n // callback leaves no live session, and the next lease that connects\n // clears the state.\n const deadline = Date.now() + maxWaitMs;\n for (let attempt = 0; attempt < 2; attempt++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n try {\n const lease = await acquireWithMaxWait(\n () => client.reserve(),\n (late) => late.release(),\n remaining,\n { driverName: this.driverName, form: \"callback\" }\n );\n lease.release();\n return;\n } catch (cleanup) {\n withSuppressedFailure(primary, cleanup);\n if (!this.isConnectionFailure(cleanup)) break;\n }\n }\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for postgres.js.\n *\n * postgres.js exposes no destroy for a reserved connection, so a condemned\n * session is reset with PostgreSQL's own instrument before it goes back:\n * `pg_advisory_unlock_all()` releases every advisory lock the session still\n * holds, which is the exact state that must not survive the release. When\n * that reset FAILS the session's lock state is unknown, and the shared rule\n * below is what keeps it out of the pool — the reset's failure is not\n * swallowed, because a session that may still hold VibORM's migration lock is\n * not something a caller can be left unaware of.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PostgresClient | PostgresTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Ownership is the identity this driver settled at construction,\n // never a later read of the caller's options object: a `client` key\n // deleted after construction would otherwise make VibORM end a\n // transport it was handed.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it. `end()` can\n // reject — a socket already gone is the ordinary way — and\n // withdrawing afterwards left this exact transport installed,\n // so the next ordinary query ran on the connection whose\n // advisory-lock state is precisely what could not be\n // accounted for. The in-flight connect goes with it, because\n // `getClient()` answers from it when `client` is null.\n this.client = null;\n this.initPromise = null;\n // Bounded: an abandoned connection whose socket stopped\n // answering never finishes on its own, and `end()` without\n // a timeout waits for it. Past the bound postgres.js\n // terminates every connection of this transport.\n await client.end({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PostgresClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PostgresDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PostgresDriver }\n >]: LinkedClientConfig<C & { driver: PostgresDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"postgres\", POSTGRES_CONFIG_KEYS);\n const { client, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new PostgresDriver({\n client,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, PostgresDriver>(config, driver);\n}\n"],"mappings":"imBA+EA,MAAa,EAAqD,CAKhE,UAAW,CACT,GAAI,KACJ,KAAM,CAAC,KAAM,KAAM,KAAK,CACxB,UAAY,GACV,aAAiB,KAAO,EAAM,aAAa,CAAG,OAAO,EAAM,CAC7D,MAAQ,GAAkB,EAC3B,CAMD,KAAM,CACJ,GAAI,IACJ,KAAM,CAAC,IAAK,KAAK,CACjB,UAAY,GACV,OAAO,GAAU,SAAW,EAAQ,KAAK,UAAU,EAAM,CAC3D,MAAQ,GAAkB,KAAK,MAAM,EAAM,CAC5C,CACF,CAID,SAAS,qBAAqB,EAA8B,CAC1D,OAAO,EAAO,IAAK,GACjB,MAAM,Q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D,OAAO,EAAmD,EAZ3C,IAAI,eAAe,CAChC,SACA,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACA,qBAAsB,EAAO,qBAC7B,YACA,8BACD,CAAC,CAEuE"}
1
+ {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/drivers/postgres/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (postgres.js)\n *\n * Driver implementation for postgres.js - a modern, fast PostgreSQL client.\n *\n * Generated statements use unsafe(query, values, queryOptions). Preparation\n * defaults to false for pooler compatibility; options.prepare: true opts into\n * the provider's prepared-statement reuse on compatible sessions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, VibORMErrorCode } from \"@errors\";\nimport postgres, {\n type Options as PostgresOptionsType,\n type Sql as PostgresSql,\n} from \"postgres\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { normalizeDriverError } from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\nexport type PostgresOptions = PostgresOptionsType<\n Record<string, postgres.PostgresType>\n>;\n\ntype PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;\n\nexport interface PostgresDriverOptions {\n client?: PostgresSql<Record<string, unknown>>;\n options?: PostgresOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. PlanetScale Neki refuses more than 256: absent, the driver reads each connection's startup, 256 on Neki and before the first connection, none elsewhere. A stated bound always wins. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport const vibormTypes: Record<string, postgres.PostgresType> = {\n // TIMESTAMP WITHOUT TIME ZONE (1114): postgres.js builds process-local\n // Dates, shifting the stored UTC wall clock by the process timezone. Keep\n // the raw string — the shared result parser builds a UTC Date from it,\n // matching every other driver. (DATE already arrives as a string.)\n timestamp: {\n to: 1114,\n from: [1082, 1114, 1184],\n serialize: (value: unknown) =>\n value instanceof Date ? value.toISOString() : String(value),\n parse: (value: string) => value,\n },\n // The adapter binds a `JsonParameter` carrier (src/sql/json-parameter.ts),\n // which the object arm serializes to its canonical text via `toJSON`. The\n // string arm exists for raw SQL: a caller's own JSON text bound to a\n // json/jsonb parameter must not be JSON.stringify'd a second time once the\n // server declares the param type — that double-encodes the stored value.\n json: {\n to: 114,\n from: [114, 3802],\n serialize: (value: unknown) =>\n typeof value === \"string\" ? value : JSON.stringify(value),\n parse: (value: string) => JSON.parse(value),\n },\n};\n\n/** Bind validated one-dimensional lists as PostgreSQL text, letting SQL infer\n * the column type; postgres.js otherwise guesses bigint[]/boolean[] wrongly. */\nfunction encodeListParameters(params: unknown[]): unknown[] {\n return params.map((value) =>\n Array.isArray(value)\n ? `{${value.map((member) => (member === null ? \"NULL\" : `\"${String(member).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`)).join(\",\")}}`\n : value\n );\n}\n\nconst withVibormTypes = (options: PostgresOptions = {}): PostgresOptions => ({\n ...options,\n types: { ...vibormTypes, ...options.types },\n});\n\nexport type PostgresClientConfig<C extends DriverConfig> =\n PostgresDriverOptions & C;\n\nconst POSTGRES_CONFIG_KEYS: Record<keyof PostgresDriverOptions, true> = {\n client: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n databaseUrl: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\ntype PostgresClient = PostgresSql<Record<string, unknown>>;\n\nconst isTransaction = (\n client: PostgresClient | PostgresTransaction\n): client is PostgresTransaction => {\n return \"savepoint\" in client;\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PostgresDriver extends Driver<\n PostgresClient,\n PostgresTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_533;\n\n private readonly driverOptions: PostgresDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: PostgresClient | undefined;\n\n constructor(options: PostgresDriverOptions = {}) {\n super(\"postgresql\", \"postgres\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = {\n databaseUrl: options.databaseUrl,\n options: { ...options.options },\n };\n this.suppliedClient = options.client;\n const { host, hostname } = this.driverOptions.options ?? {};\n refuseEmptyDatabaseUrl(\n \"postgres\",\n options,\n Boolean(this.suppliedClient || host || hostname)\n );\n\n if (this.suppliedClient) {\n for (const oid of [1082, 1114, 1184]) {\n if (\n this.suppliedClient.options?.parsers[oid] !==\n vibormTypes.timestamp?.parse\n ) {\n throw new ClientInitializationError(\n \"A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).\",\n { meta: { driver: \"postgres\", operation: \"configuration\" } }\n );\n }\n }\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n // postgres.js keeps every parameter status its connections received.\n boundByServer(this.adapter, () => {\n const client = this.client;\n return client && !isTransaction(client)\n ? client.parameters.server_version\n : undefined;\n });\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n return [\n databaseUrl,\n options?.host,\n options?.hostname,\n ...(this.suppliedClient?.options.host ?? []),\n ];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<PostgresClient> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n // postgres.js reads the URL for the keys it carries and lets every key\n // set in options win, which is the documented precedence.\n const { databaseUrl, options } = this.driverOptions;\n return databaseUrl\n ? postgres(systemRootAsVerifyFull(databaseUrl), withVibormTypes(options))\n : postgres(withVibormTypes(options));\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to end it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: PostgresClient): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.end();\n }\n\n protected async execute<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n // postgres.js unsafe() takes (query, parameters?, queryOptions?)\n // parameters must be cast as postgres expects specific types\n return this.executeQuery(\n client,\n sqlStr,\n encodeListParameters(params),\n context,\n \"execute\"\n );\n }\n\n protected async executeRaw<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sqlStr, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client\n .unsafe<T[]>(sqlStr, params, {\n prepare: this.driverOptions.options?.prepare === true,\n })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n throw error;\n });\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n /**\n * postgres.js owns BEGIN inside `client.begin()`, so the isolation level goes\n * in as the transaction's first statement. It also owns connection\n * acquisition inside that same call: there is no acquisition step VibORM can\n * bound or abandon, so `maxWait` is refused rather than faked.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: PostgresClient | PostgresTransaction,\n fn: (tx: PostgresTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: async (callback) => {\n let entered = false;\n try {\n return await client.begin((tx) => {\n entered = true;\n return callback(tx);\n });\n } catch (error) {\n if (!entered && this.isConnectionFailure(error))\n await this.recoverFailedBegin(\n client,\n error,\n options?.maxWaitMs ?? 5000\n );\n throw error;\n }\n },\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n private isConnectionFailure(error: unknown): boolean {\n const failure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n });\n return (\n failure.code === VibORMErrorCode.CONNECTION_FAILED ||\n failure.code === VibORMErrorCode.CONNECTION_TIMEOUT\n );\n }\n\n private async recoverFailedBegin(\n client: PostgresClient,\n primary: unknown,\n maxWaitMs: number\n ): Promise<void> {\n // postgres.js can retain a fatal response across reconnect, rejecting the\n // next acquisition before dispatch. Drain that startup error with leases,\n // never caller SQL; the callback above has provably not entered. A drain\n // that cannot connect needs no quarantine: a connection failure before the\n // callback leaves no live session, and the next lease that connects\n // clears the state.\n const deadline = Date.now() + maxWaitMs;\n for (let attempt = 0; attempt < 2; attempt++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n try {\n const lease = await acquireWithMaxWait(\n () => client.reserve(),\n (late) => late.release(),\n remaining,\n { driverName: this.driverName, form: \"callback\" }\n );\n lease.release();\n return;\n } catch (cleanup) {\n withSuppressedFailure(primary, cleanup);\n if (!this.isConnectionFailure(cleanup)) break;\n }\n }\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for postgres.js.\n *\n * postgres.js exposes no destroy for a reserved connection, so a condemned\n * session is reset with PostgreSQL's own instrument before it goes back:\n * `pg_advisory_unlock_all()` releases every advisory lock the session still\n * holds, which is the exact state that must not survive the release. When\n * that reset FAILS the session's lock state is unknown, and the shared rule\n * below is what keeps it out of the pool — the reset's failure is not\n * swallowed, because a session that may still hold VibORM's migration lock is\n * not something a caller can be left unaware of.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PostgresClient | PostgresTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Ownership is the identity this driver settled at construction,\n // never a later read of the caller's options object: a `client` key\n // deleted after construction would otherwise make VibORM end a\n // transport it was handed.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it. `end()` can\n // reject — a socket already gone is the ordinary way — and\n // withdrawing afterwards left this exact transport installed,\n // so the next ordinary query ran on the connection whose\n // advisory-lock state is precisely what could not be\n // accounted for. The in-flight connect goes with it, because\n // `getClient()` answers from it when `client` is null.\n this.client = null;\n this.initPromise = null;\n // Bounded: an abandoned connection whose socket stopped\n // answering never finishes on its own, and `end()` without\n // a timeout waits for it. Past the bound postgres.js\n // terminates every connection of this transport.\n await client.end({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PostgresClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PostgresDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PostgresDriver }\n >]: LinkedClientConfig<C & { driver: PostgresDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"postgres\", POSTGRES_CONFIG_KEYS);\n const { client, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new PostgresDriver({\n client,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, PostgresDriver>(config, driver);\n}\n"],"mappings":"0pBAkFA,MAAa,EAAqD,CAKhE,UAAW,CACT,GAAI,KACJ,KAAM,CAAC,KAAM,KAAM,KAAK,CACxB,UAAY,GACV,aAAiB,KAAO,EAAM,aAAa,CAAG,OAAO,EAAM,CAC7D,MAAQ,GAAkB,EAC3B,CAMD,KAAM,CACJ,GAAI,IACJ,KAAM,CAAC,IAAK,KAAK,CACjB,UAAY,GACV,OAAO,GAAU,SAAW,EAAQ,KAAK,UAAU,EAAM,CAC3D,MAAQ,GAAkB,KAAK,MAAM,EAAM,CAC5C,CACF,CAID,SAAS,qBAAqB,EAA8B,CAC1D,OAAO,EAAO,IAAK,GACjB,MAAM,QAAQ,EAAM,CAChB,IAAI,EAAM,IAAK,GAAY,IAAW,KAAO,OAAS,IAAI,OAAO,EAAO,CAAC,QAAQ,MAAO,OAAO,CAAC,QAAQ,KAAM,MAAM,CAAC,GAAI,CAAC,KAAK,IAAI,CAAC,GACpI,EACL,CAGH,MAAM,iBAAmB,EAA2B,EAAE,IAAuB,CAC3E,GAAG,EACH,MAAO,CAAE,GAAG,EAAa,GAAG,EAAQ,MAAO,CAC5C,EAKK,EAAkE,CACtE,OAAQ,GACR,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,YAAa,GACb,UAAW,GACX,4BAA6B,GAC9B,CAIK,cACJ,GAEO,cAAe,EAOxB,IAAa,eAAb,cAA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import{T as t}from"./geo-point-codec-D95uXgDF.mjs";function decimalDialectOf(e){return e===`postgresql`?`pg`:e===`mysql`?`mysql`:`sqlite`}function findDecimalProviderLimitRefusal(e,n){let r=decimalDialectOf(n);for(let[i,a]of Object.entries(e)){let e=a[`~`].state.scalars;for(let[a,o]of Object.entries(e)){let e=o[`~`].state;if(e.type!==`decimal`||e.decimal===void 0)continue;let s=t(r,e.decimal);if(s!==void 0)return{modelName:i,fieldName:a,dialect:n,descriptor:e.decimal,reason:s}}}}function describeDecimalProviderLimitRefusal(e){return`Decimal field '${e.modelName}.${e.fieldName}' cannot be stored by the '${e.dialect}' driver: ${e.reason}.`}export{findDecimalProviderLimitRefusal as n,describeDecimalProviderLimitRefusal as t};
2
- //# sourceMappingURL=provider-limits-DSv2tYFr.mjs.map
2
+ //# sourceMappingURL=provider-limits-V09frtmK.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider-limits-DSv2tYFr.mjs","names":[],"sources":["../src/schema/scalars/decimal/provider-limits.ts"],"sourcesContent":["/**\n * The ONE schema-plus-provider fixed-decimal admission decision.\n *\n * A decimal descriptor is a valid schema fact independently of provider\n * limits. The first boundary that combines a complete model map with a chosen\n * provider asks this pure owner whether every declared scalar or list fits.\n * It returns one structured refusal and performs no boundary-specific throw;\n * client and migration composition roots retain their own error classes.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type DecimalDescriptor,\n type DecimalDialect,\n describeProviderLimitRefusal,\n} from \"@validation/primitives/decimal-codec\";\n\ntype ProviderDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\nexport interface DecimalProviderLimitRefusal {\n readonly modelName: string;\n readonly fieldName: string;\n readonly dialect: ProviderDialect;\n readonly descriptor: DecimalDescriptor;\n readonly reason: string;\n}\n\n/** The driver's dialect in the decimal codec's physical vocabulary. */\nfunction decimalDialectOf(dialect: ProviderDialect): DecimalDialect {\n if (dialect === \"postgresql\") return \"pg\";\n if (dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n}\n\n/** Return the first declared decimal domain the selected provider cannot hold. */\nexport function findDecimalProviderLimitRefusal(\n schema: Record<string, AnyModel>,\n dialect: ProviderDialect\n): DecimalProviderLimitRefusal | undefined {\n const decimalDialect = decimalDialectOf(dialect);\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n const state = scalar[\"~\"].state;\n if (state.type !== \"decimal\" || state.decimal === undefined) continue;\n const reason = describeProviderLimitRefusal(\n decimalDialect,\n state.decimal\n );\n if (reason === undefined) continue;\n return {\n modelName,\n fieldName,\n dialect,\n descriptor: state.decimal,\n reason,\n };\n }\n }\n return undefined;\n}\n\n/** The shared diagnostic body; each composition root chooses its error model. */\nexport function describeDecimalProviderLimitRefusal(\n refusal: DecimalProviderLimitRefusal\n): string {\n return `Decimal field '${refusal.modelName}.${refusal.fieldName}' cannot be stored by the '${refusal.dialect}' driver: ${refusal.reason}.`;\n}\n"],"mappings":"4FA6BA,SAAS,iBAAiB,EAA0C,CAGlE,OAFI,IAAY,aAAqB,KACjC,IAAY,QAAgB,QACzB,SAIT,SAAgB,gCACd,EACA,EACyC,CACzC,IAAM,EAAiB,iBAAiB,EAAQ,CAChD,IAAK,GAAM,CAAC,EAAW,KAAU,OAAO,QAAQ,EAAO,CAAE,CACvD,IAAM,EAAkC,EAAM,KAAK,MAAM,QACzD,IAAK,GAAM,CAAC,EAAW,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACzD,IAAM,EAAQ,EAAO,KAAK,MAC1B,GAAI,EAAM,OAAS,WAAa,EAAM,UAAY,IAAA,GAAW,SAC7D,IAAM,EAAS,EACb,EACA,EAAM,QACP,CACG,OAAW,IAAA,GACf,MAAO,CACL,YACA,YACA,UACA,WAAY,EAAM,QAClB,SACD,GAOP,SAAgB,oCACd,EACQ,CACR,MAAO,kBAAkB,EAAQ,UAAU,GAAG,EAAQ,UAAU,6BAA6B,EAAQ,QAAQ,YAAY,EAAQ,OAAO"}
1
+ {"version":3,"file":"provider-limits-V09frtmK.mjs","names":[],"sources":["../src/schema/scalars/decimal/provider-limits.ts"],"sourcesContent":["/**\n * The ONE schema-plus-provider fixed-decimal admission decision.\n *\n * A decimal descriptor is a valid schema fact independently of provider\n * limits. The first boundary that combines a complete model map with a chosen\n * provider asks this pure owner whether every declared scalar or list fits.\n * It returns one structured refusal and performs no boundary-specific throw;\n * client and migration composition roots retain their own error classes.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type DecimalDescriptor,\n type DecimalDialect,\n describeProviderLimitRefusal,\n} from \"@validation/primitives/decimal-codec\";\n\ntype ProviderDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\nexport interface DecimalProviderLimitRefusal {\n readonly modelName: string;\n readonly fieldName: string;\n readonly dialect: ProviderDialect;\n readonly descriptor: DecimalDescriptor;\n readonly reason: string;\n}\n\n/** The driver's dialect in the decimal codec's physical vocabulary. */\nfunction decimalDialectOf(dialect: ProviderDialect): DecimalDialect {\n if (dialect === \"postgresql\") return \"pg\";\n if (dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n}\n\n/** Return the first declared decimal domain the selected provider cannot hold. */\nexport function findDecimalProviderLimitRefusal(\n schema: Record<string, AnyModel>,\n dialect: ProviderDialect\n): DecimalProviderLimitRefusal | undefined {\n const decimalDialect = decimalDialectOf(dialect);\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n const state = scalar[\"~\"].state;\n if (state.type !== \"decimal\" || state.decimal === undefined) continue;\n const reason = describeProviderLimitRefusal(\n decimalDialect,\n state.decimal\n );\n if (reason === undefined) continue;\n return {\n modelName,\n fieldName,\n dialect,\n descriptor: state.decimal,\n reason,\n };\n }\n }\n return undefined;\n}\n\n/** The shared diagnostic body; each composition root chooses its error model. */\nexport function describeDecimalProviderLimitRefusal(\n refusal: DecimalProviderLimitRefusal\n): string {\n return `Decimal field '${refusal.modelName}.${refusal.fieldName}' cannot be stored by the '${refusal.dialect}' driver: ${refusal.reason}.`;\n}\n"],"mappings":"4FA6BA,SAAS,iBAAiB,EAA0C,CAGlE,OAFI,IAAY,aAAqB,KACjC,IAAY,QAAgB,QACzB,SAIT,SAAgB,gCACd,EACA,EACyC,CACzC,IAAM,EAAiB,iBAAiB,EAAQ,CAChD,IAAK,GAAM,CAAC,EAAW,KAAU,OAAO,QAAQ,EAAO,CAAE,CACvD,IAAM,EAAkC,EAAM,KAAK,MAAM,QACzD,IAAK,GAAM,CAAC,EAAW,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACzD,IAAM,EAAQ,EAAO,KAAK,MAC1B,GAAI,EAAM,OAAS,WAAa,EAAM,UAAY,IAAA,GAAW,SAC7D,IAAM,EAAS,EACb,EACA,EAAM,QACP,CACG,OAAW,IAAA,GACf,MAAO,CACL,YACA,YACA,UACA,WAAY,EAAM,QAClB,SACD,GAOP,SAAgB,oCACd,EACQ,CACR,MAAO,kBAAkB,EAAQ,UAAU,GAAG,EAAQ,UAAU,6BAA6B,EAAQ,QAAQ,YAAY,EAAQ,OAAO"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";function boundByServer(e,t){let n=e.capabilities;return n.sharesRelationBodies!==!0||n.relationsPerStatement!==void 0?!1:(Object.defineProperty(n,`relationsPerStatement`,{configurable:!0,enumerable:!0,get(){let e=t();return e===void 0||typeof e==`string`&&e.endsWith(`(Neki)`)?256:void 0}}),!0)}const t=/references more than (\d+) relations/;function learnRelationLimit(e,n){let r=e.capabilities;if(r.sharesRelationBodies!==!0||r.relationsPerStatement!==void 0||typeof n!=`object`||!n)return;let i=Reflect.get(n,`code`)===`54000`||Reflect.get(n,`errno`)===`54000`,a=t.exec(String(Reflect.get(n,`message`)));i&&a!==null&&Object.defineProperty(r,`relationsPerStatement`,{configurable:!0,enumerable:!0,writable:!0,value:Number(a[1])})}export{learnRelationLimit as n,boundByServer as t};
2
+ //# sourceMappingURL=relation-bound-BrZLsSke.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relation-bound-BrZLsSke.mjs","names":[],"sources":["../src/drivers/shared/relation-bound.ts"],"sourcesContent":["import type { DatabaseAdapter } from \"@adapters/database-adapter\";\n\n/**\n * What a PostgreSQL server says of itself that bounds the relations one\n * statement may reference (`capabilities.relationsPerStatement`). PlanetScale's\n * Neki refuses a statement referencing more than 256; it names itself in the\n * `server_version` of every connection's startup (`18.6 (…) (Neki)`), which\n * node-postgres (through the `Client` a driver's own pool makes) and\n * postgres.js (`sql.parameters`) receive with no statement of their own, and\n * in its refusal (SQLSTATE 54000, \"the statement references more than 256\n * relations, the limit for one statement\").\n *\n * Each fills an ABSENT bound only, and only where bodies are shared: a\n * `relationsPerStatement` the caller stated always wins, and\n * `sharedRelationBodies: false` keeps every statement's form.\n */\nconst NEKI_RELATIONS = 256;\n\n/**\n * The bound of a driver that reads its server's startup, `serverVersion`\n * (undefined until a connection opened): read as each statement is built, so\n * a statement built once a connection said what server it is, a transaction's\n * included, takes Neki's bound or none, and one built before (a driver's first\n * statement, an array transaction's members) takes Neki's, which costs only\n * plans elsewhere and only past 256 relations. Whether the bound is the\n * server's to say (no bound stated, bodies shared).\n */\nexport function boundByServer(\n adapter: DatabaseAdapter,\n serverVersion: () => unknown\n): boolean {\n const capabilities = adapter.capabilities;\n if (\n capabilities.sharesRelationBodies !== true ||\n capabilities.relationsPerStatement !== undefined\n )\n return false;\n Object.defineProperty(capabilities, \"relationsPerStatement\", {\n configurable: true,\n enumerable: true,\n get() {\n const version = serverVersion();\n return version === undefined ||\n (typeof version === \"string\" && version.endsWith(\"(Neki)\"))\n ? NEKI_RELATIONS\n : undefined;\n },\n });\n return true;\n}\n\nconst RELATION_LIMIT = /references more than (\\d+) relations/;\n\n/**\n * The bound a refusal names, for a transport whose startup is unread (Bun SQL,\n * a supplied pool): the refused statement fails, the next ones fit. The code\n * is node-postgres's and postgres.js's `code`, Bun SQL's `errno`.\n */\nexport function learnRelationLimit(\n adapter: DatabaseAdapter,\n error: unknown\n): void {\n const capabilities = adapter.capabilities;\n if (\n capabilities.sharesRelationBodies !== true ||\n capabilities.relationsPerStatement !== undefined ||\n typeof error !== \"object\" ||\n error === null\n )\n return;\n const refused =\n Reflect.get(error, \"code\") === \"54000\" ||\n Reflect.get(error, \"errno\") === \"54000\";\n const limit = RELATION_LIMIT.exec(String(Reflect.get(error, \"message\")));\n // A value, replacing a startup reader whose server did not say Neki.\n if (refused && limit !== null)\n Object.defineProperty(capabilities, \"relationsPerStatement\", {\n configurable: true,\n enumerable: true,\n writable: true,\n value: Number(limit[1]),\n });\n}\n"],"mappings":"yCA2BA,SAAgB,cACd,EACA,EACS,CACT,IAAM,EAAe,EAAQ,aAiB7B,OAfE,EAAa,uBAAyB,IACtC,EAAa,wBAA0B,IAAA,GAEhC,IACT,OAAO,eAAe,EAAc,wBAAyB,CAC3D,aAAc,GACd,WAAY,GACZ,KAAM,CACJ,IAAM,EAAU,GAAe,CAC/B,OAAO,IAAY,IAAA,IAChB,OAAO,GAAY,UAAY,EAAQ,SAAS,SAAS,CACxD,IACA,IAAA,IAEP,CAAC,CACK,IAGT,MAAM,EAAiB,uCAOvB,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAe,EAAQ,aAC7B,GACE,EAAa,uBAAyB,IACtC,EAAa,wBAA0B,IAAA,IACvC,OAAO,GAAU,WACjB,EAEA,OACF,IAAM,EACJ,QAAQ,IAAI,EAAO,OAAO,GAAK,SAC/B,QAAQ,IAAI,EAAO,QAAQ,GAAK,QAC5B,EAAQ,EAAe,KAAK,OAAO,QAAQ,IAAI,EAAO,UAAU,CAAC,CAAC,CAEpE,GAAW,IAAU,MACvB,OAAO,eAAe,EAAc,wBAAyB,CAC3D,aAAc,GACd,WAAY,GACZ,SAAU,GACV,MAAO,OAAO,EAAM,GAAG,CACxB,CAAC"}
@@ -1,2 +1,2 @@
1
1
  import{n as e}from"./chunk-BuuaeEvq.mjs";const t=`0viborm_count_result`;function parseIntegerBoolean(e){if(typeof e==`number`)return e===1?!0:e===0?!1:void 0;if(typeof e==`bigint`)return e===1n?!0:e===0n?!1:void 0;if(e==null)return null}export{parseIntegerBoolean as n,t};
2
- //# sourceMappingURL=result-parsing-8wEK3GY1.mjs.map
2
+ //# sourceMappingURL=result-parsing-CQf_eCl8.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"result-parsing-8wEK3GY1.mjs","names":[],"sources":["../src/adapters/shared/result-parsing.ts"],"sourcesContent":["/**\n * Shared Result Parsing Utilities\n *\n * Common parsing logic used by adapters for database-specific type conversions.\n * These utilities use `undefined` as a sentinel to indicate \"not handled\" -\n * allowing the caller to fall through to default parsing.\n *\n * @example\n * const parsed = tryParseJsonString(value);\n * if (parsed !== undefined) {\n * // Use parsed value\n * } else {\n * // Fall through to default\n * }\n */\n\n/**\n * The private column name a COUNT result carries in a RESULT SHAPE.\n *\n * It names a shape's single raw key, never a provider's row: its readers are\n * `query-engine/result/result-shape.ts` and `client/typescript-type-renderer.ts`,\n * both over DECODED values. A live row's\n * count arrives under the alias the engine asked for (`_count`), which the\n * engine's own decoder reads back (Arnaud's D-40).\n */\nexport const COUNT_RESULT_KEY = \"0viborm_count_result\" as const;\n\n/**\n * Parse JSON string values (MySQL/SQLite return JSON as strings).\n *\n * @param value - Raw value from database\n * @returns Parsed JSON object/array, or `undefined` if not a JSON string\n *\n * @example\n * tryParseJsonString('[1,2,3]') // [1, 2, 3]\n * tryParseJsonString('{\"a\":1}') // { a: 1 }\n * tryParseJsonString('hello') // undefined (not JSON)\n * tryParseJsonString(123) // undefined (not a string)\n * tryParseJsonString('[invalid') // undefined (invalid JSON)\n */\nexport function tryParseJsonString(value: unknown): unknown | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert SQLite/MySQL integer to boolean.\n * These databases store booleans as 0/1 integers.\n *\n * @param value - Raw value from database\n * @returns `true` for 1, `false` for 0, `null` for null/undefined,\n * or `undefined` if value is not an integer (fall through to default)\n *\n * @example\n * parseIntegerBoolean(1) // true\n * parseIntegerBoolean(0) // false\n * parseIntegerBoolean(null) // null\n * parseIntegerBoolean('true') // undefined (not handled, fall through)\n */\nexport function parseIntegerBoolean(\n value: unknown\n): boolean | null | undefined {\n if (typeof value === \"number\") {\n if (value === 1) return true;\n if (value === 0) return false;\n return undefined;\n }\n // SQLite drivers read integers safely (BigInt), including boolean columns\n if (typeof value === \"bigint\") {\n if (value === 1n) return true;\n if (value === 0n) return false;\n return undefined;\n }\n if (value === null || value === undefined) {\n return null;\n }\n return undefined;\n}\n"],"mappings":"yCAyBA,MAAa,EAAmB,uBAiDhC,SAAgB,oBACd,EAC4B,CAC5B,GAAI,OAAO,GAAU,SAGnB,OAFI,IAAU,EAAU,GACpB,IAAU,EAAU,GACxB,OAGF,GAAI,OAAO,GAAU,SAGnB,OAFI,IAAU,GAAW,GACrB,IAAU,GAAW,GACzB,OAEF,GAAI,GAAU,KACZ,OAAO"}
1
+ {"version":3,"file":"result-parsing-CQf_eCl8.mjs","names":[],"sources":["../src/adapters/shared/result-parsing.ts"],"sourcesContent":["/**\n * Shared Result Parsing Utilities\n *\n * Common parsing logic used by adapters for database-specific type conversions.\n * These utilities use `undefined` as a sentinel to indicate \"not handled\" -\n * allowing the caller to fall through to default parsing.\n *\n * @example\n * const parsed = tryParseJsonString(value);\n * if (parsed !== undefined) {\n * // Use parsed value\n * } else {\n * // Fall through to default\n * }\n */\n\n/**\n * The private column name a COUNT result carries in a RESULT SHAPE.\n *\n * It names a shape's single raw key, never a provider's row: its readers are\n * `query-engine/result/result-shape.ts` and `client/typescript-type-renderer.ts`,\n * both over DECODED values. A live row's\n * count arrives under the alias the engine asked for (`_count`), which the\n * engine's own decoder reads back (Arnaud's D-40).\n */\nexport const COUNT_RESULT_KEY = \"0viborm_count_result\" as const;\n\n/**\n * Parse JSON string values (MySQL/SQLite return JSON as strings).\n *\n * @param value - Raw value from database\n * @returns Parsed JSON object/array, or `undefined` if not a JSON string\n *\n * @example\n * tryParseJsonString('[1,2,3]') // [1, 2, 3]\n * tryParseJsonString('{\"a\":1}') // { a: 1 }\n * tryParseJsonString('hello') // undefined (not JSON)\n * tryParseJsonString(123) // undefined (not a string)\n * tryParseJsonString('[invalid') // undefined (invalid JSON)\n */\nexport function tryParseJsonString(value: unknown): unknown | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert SQLite/MySQL integer to boolean.\n * These databases store booleans as 0/1 integers.\n *\n * @param value - Raw value from database\n * @returns `true` for 1, `false` for 0, `null` for null/undefined,\n * or `undefined` if value is not an integer (fall through to default)\n *\n * @example\n * parseIntegerBoolean(1) // true\n * parseIntegerBoolean(0) // false\n * parseIntegerBoolean(null) // null\n * parseIntegerBoolean('true') // undefined (not handled, fall through)\n */\nexport function parseIntegerBoolean(\n value: unknown\n): boolean | null | undefined {\n if (typeof value === \"number\") {\n if (value === 1) return true;\n if (value === 0) return false;\n return undefined;\n }\n // SQLite drivers read integers safely (BigInt), including boolean columns\n if (typeof value === \"bigint\") {\n if (value === 1n) return true;\n if (value === 0n) return false;\n return undefined;\n }\n if (value === null || value === undefined) {\n return null;\n }\n return undefined;\n}\n"],"mappings":"yCAyBA,MAAa,EAAmB,uBAiDhC,SAAgB,oBACd,EAC4B,CAC5B,GAAI,OAAO,GAAU,SAGnB,OAFI,IAAU,EAAU,GACpB,IAAU,EAAU,GACxB,OAGF,GAAI,OAAO,GAAU,SAGnB,OAFI,IAAU,GAAW,GACrB,IAAU,GAAW,GACzB,OAEF,GAAI,GAAU,KACZ,OAAO"}