viborm 1.0.0 → 1.2.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 (300) hide show
  1. package/README.md +4 -3
  2. package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
  3. package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
  4. package/dist/adapters.d.mts +1 -1
  5. package/dist/adapters.mjs +1 -1
  6. package/dist/{array-literal-D9FexFqy.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  7. package/dist/{array-literal-D9FexFqy.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  8. package/dist/base-AdXAoy6l.mjs +2 -0
  9. package/dist/base-AdXAoy6l.mjs.map +1 -0
  10. package/dist/batch-refs-4L8ECdPU.mjs +2 -0
  11. package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
  12. package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
  13. package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
  14. package/dist/builder-Ycvq3ETg.mjs +2 -0
  15. package/dist/builder-Ycvq3ETg.mjs.map +1 -0
  16. package/dist/bun-sql.d.mts +19 -2
  17. package/dist/bun-sql.mjs +1 -1
  18. package/dist/bun-sql.mjs.map +1 -1
  19. package/dist/bun-sqlite.d.mts +9 -8
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/bun-sqlite.mjs.map +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/memory.mjs.map +1 -1
  27. package/dist/cache-BO57X0TT.mjs +2 -0
  28. package/dist/cache-BO57X0TT.mjs.map +1 -0
  29. package/dist/cache.d.mts +1 -1
  30. package/dist/cache.mjs +1 -1
  31. package/dist/cache.mjs.map +1 -1
  32. package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
  33. package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
  34. package/dist/chain-Dh0FV72b.mjs +2 -0
  35. package/dist/chain-Dh0FV72b.mjs.map +1 -0
  36. package/dist/cli.mjs +5 -6
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/client-BLiBmykn.mjs +2 -0
  39. package/dist/client-BLiBmykn.mjs.map +1 -0
  40. package/dist/client-CCgfcp5A.mjs +52 -0
  41. package/dist/client-CCgfcp5A.mjs.map +1 -0
  42. package/dist/client-CRBo95D0.d.mts +610 -0
  43. package/dist/client.d.mts +1 -1
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
  46. package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
  47. package/dist/config.d.mts +3 -3
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-DXgIn4zh.mjs +2 -0
  50. package/dist/controls-DXgIn4zh.mjs.map +1 -0
  51. package/dist/d1.d.mts +1 -1
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
  55. package/dist/datetime-physical-codec-oIhiYZEP.mjs.map +1 -0
  56. package/dist/driver-B19QlFqn.mjs +2 -0
  57. package/dist/{driver-CRaDT4B7.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
  58. package/dist/driver-BlnKXPFF.mjs +2 -0
  59. package/dist/driver-BlnKXPFF.mjs.map +1 -0
  60. package/dist/driver.d.mts +2 -2
  61. package/dist/driver.mjs +1 -1
  62. package/dist/error-mapping-CnPCv1dm.mjs +2 -0
  63. package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
  64. package/dist/every-4KE0p2Gw.mjs +2 -0
  65. package/dist/every-4KE0p2Gw.mjs.map +1 -0
  66. package/dist/execution-context-BKR3bgES.mjs +2 -0
  67. package/dist/execution-context-BKR3bgES.mjs.map +1 -0
  68. package/dist/fs-estate-CAhDg7nY.mjs +2 -0
  69. package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
  70. package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
  71. package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
  72. package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
  73. package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
  74. package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
  75. package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
  76. package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
  77. package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
  78. package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
  79. package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
  80. package/dist/identity-CLFhCTZx.mjs +2 -0
  81. package/dist/identity-CLFhCTZx.mjs.map +1 -0
  82. package/dist/{index-T0YKKw66.d.mts → index-C_XLSTy2.d.mts} +723 -400
  83. package/dist/index.d.mts +2 -2
  84. package/dist/index.mjs +1 -1
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/instrumentation.d.mts +1 -1
  87. package/dist/instrumentation.mjs +1 -1
  88. package/dist/instrumentation.mjs.map +1 -1
  89. package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
  90. package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
  91. package/dist/{json-number-C10HFiy6.mjs → json-number-CGXpPu4D.mjs} +1 -1
  92. package/dist/{json-number-C10HFiy6.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  93. package/dist/key-BeoOwGr3.mjs +2 -0
  94. package/dist/key-BeoOwGr3.mjs.map +1 -0
  95. package/dist/libsql-Bu_IdFU1.mjs +11 -0
  96. package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
  97. package/dist/libsql.d.mts +8 -3
  98. package/dist/libsql.mjs +1 -1
  99. package/dist/libsql.mjs.map +1 -1
  100. package/dist/memory-D4yxtCPK.mjs +2 -0
  101. package/dist/memory-D4yxtCPK.mjs.map +1 -0
  102. package/dist/migrations/mysql.d.mts +6 -0
  103. package/dist/migrations/mysql.mjs +2 -0
  104. package/dist/migrations/mysql.mjs.map +1 -0
  105. package/dist/migrations/postgres.d.mts +6 -0
  106. package/dist/migrations/postgres.mjs +2 -0
  107. package/dist/migrations/postgres.mjs.map +1 -0
  108. package/dist/migrations/sqlite.d.mts +6 -0
  109. package/dist/migrations/sqlite.mjs +2 -0
  110. package/dist/migrations/sqlite.mjs.map +1 -0
  111. package/dist/migrations/storage/durable-object.d.mts +17 -0
  112. package/dist/migrations/storage/durable-object.mjs +2 -0
  113. package/dist/migrations/storage/durable-object.mjs.map +1 -0
  114. package/dist/migrations/storage/fs.d.mts +6 -1
  115. package/dist/migrations/storage/fs.mjs +1 -1
  116. package/dist/migrations/storage/r2.d.mts +14 -0
  117. package/dist/migrations/storage/r2.mjs +2 -0
  118. package/dist/migrations/storage/r2.mjs.map +1 -0
  119. package/dist/migrations/tenant.d.mts +92 -0
  120. package/dist/migrations/tenant.mjs +2 -0
  121. package/dist/migrations/tenant.mjs.map +1 -0
  122. package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
  123. package/dist/migrations-DTObIjAm.mjs.map +1 -0
  124. package/dist/migrations.d.mts +6 -559
  125. package/dist/migrations.mjs +1 -1
  126. package/dist/migrations.mjs.map +1 -1
  127. package/dist/mysql-CibPaHSp.mjs +99 -0
  128. package/dist/mysql-CibPaHSp.mjs.map +1 -0
  129. package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
  130. package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
  131. package/dist/mysql2.d.mts +1 -3
  132. package/dist/mysql2.mjs +1 -1
  133. package/dist/mysql2.mjs.map +1 -1
  134. package/dist/neon-http.d.mts +1 -1
  135. package/dist/neon-http.mjs +1 -1
  136. package/dist/neon-http.mjs.map +1 -1
  137. package/dist/object-store-DQR6bTBY.mjs +2 -0
  138. package/dist/object-store-DQR6bTBY.mjs.map +1 -0
  139. package/dist/object-store-DyYOCtmX.d.mts +156 -0
  140. package/dist/observation-DUSm7oXK.mjs +2 -0
  141. package/dist/observation-DUSm7oXK.mjs.map +1 -0
  142. package/dist/pg.d.mts +37 -12
  143. package/dist/pg.mjs +1 -1
  144. package/dist/pg.mjs.map +1 -1
  145. package/dist/pglite.d.mts +2 -1
  146. package/dist/pglite.mjs +1 -1
  147. package/dist/pglite.mjs.map +1 -1
  148. package/dist/physical-6V_LNU3L.mjs +2 -0
  149. package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
  150. package/dist/pinned-session-CLxj5M5e.mjs +2 -0
  151. package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
  152. package/dist/planetscale.d.mts +1 -1
  153. package/dist/planetscale.mjs +1 -1
  154. package/dist/planetscale.mjs.map +1 -1
  155. package/dist/{planner-B11VjIin.d.mts → planner-C6Lfsasx.d.mts} +57 -3
  156. package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
  157. package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
  158. package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
  159. package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
  160. package/dist/postgres-oqNW9xqo.mjs +415 -0
  161. package/dist/postgres-oqNW9xqo.mjs.map +1 -0
  162. package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
  163. package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
  164. package/dist/postgres.d.mts +11 -1
  165. package/dist/postgres.mjs +1 -1
  166. package/dist/postgres.mjs.map +1 -1
  167. package/dist/provider-limits-BHATED_m.mjs +2 -0
  168. package/dist/provider-limits-BHATED_m.mjs.map +1 -0
  169. package/dist/registration-preflight-DEjv050M.mjs +4 -0
  170. package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
  171. package/dist/result-shape-CTNdNSW3.mjs +2 -0
  172. package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
  173. package/dist/scalar-U0wD5bKy.mjs +2 -0
  174. package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
  175. package/dist/schema/json.d.mts +1 -1
  176. package/dist/schema/json.mjs +1 -1
  177. package/dist/schema/json.mjs.map +1 -1
  178. package/dist/schema-Cjem1-0f.mjs +2 -0
  179. package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
  180. package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
  181. package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
  182. package/dist/schema.d.mts +1 -1
  183. package/dist/schema.mjs +1 -1
  184. package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
  185. package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
  186. package/dist/settle-B9Vg1FnP.mjs +2 -0
  187. package/dist/settle-B9Vg1FnP.mjs.map +1 -0
  188. package/dist/soft-delete.d.mts +1 -1
  189. package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
  190. package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
  191. package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
  192. package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
  193. package/dist/sql.d.mts +1 -1
  194. package/dist/sql.mjs +1 -1
  195. package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
  196. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
  197. package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
  198. package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
  199. package/dist/sqlite3.d.mts +2 -8
  200. package/dist/sqlite3.mjs +1 -1
  201. package/dist/sqlite3.mjs.map +1 -1
  202. package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
  203. package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
  204. package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
  205. package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
  206. package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
  207. package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
  208. package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
  209. package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
  210. package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
  211. package/dist/transaction-operation-CKK3l_9x.mjs.map +1 -0
  212. package/dist/{utils-DfztpPvR.mjs → utils-CZNaOZR7.mjs} +4 -3
  213. package/dist/utils-CZNaOZR7.mjs.map +1 -0
  214. package/dist/v-D5Z06FKN.mjs +2 -0
  215. package/dist/v-D5Z06FKN.mjs.map +1 -0
  216. package/dist/validation-Dk9Q_-C7.mjs +2 -0
  217. package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
  218. package/dist/validation-PF9-_nKd.mjs +2 -0
  219. package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
  220. package/dist/validation.d.mts +1 -1
  221. package/dist/validation.mjs +1 -1
  222. package/dist/validator-X9-bwtRo.mjs +2 -0
  223. package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
  224. package/dist/value-guards-CK9guf2Z.mjs +2 -0
  225. package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
  226. package/dist/version-JDaZht4U.mjs +2 -0
  227. package/dist/{version-Cr80LFvx.mjs.map → version-JDaZht4U.mjs.map} +1 -1
  228. package/package.json +75 -34
  229. package/dist/base-vfur-DaU.mjs +0 -2
  230. package/dist/base-vfur-DaU.mjs.map +0 -1
  231. package/dist/batch-refs-BY51FIXm.mjs +0 -6
  232. package/dist/batch-refs-BY51FIXm.mjs.map +0 -1
  233. package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
  234. package/dist/builder-bPfagDQV.mjs +0 -2
  235. package/dist/builder-bPfagDQV.mjs.map +0 -1
  236. package/dist/chain-uIFlkkXS.mjs +0 -2
  237. package/dist/chain-uIFlkkXS.mjs.map +0 -1
  238. package/dist/client-NleI4Nm-.mjs +0 -434
  239. package/dist/client-NleI4Nm-.mjs.map +0 -1
  240. package/dist/client-tjSMPjeZ.mjs +0 -2
  241. package/dist/client-tjSMPjeZ.mjs.map +0 -1
  242. package/dist/controls-BhxRnPYS.mjs +0 -2
  243. package/dist/controls-BhxRnPYS.mjs.map +0 -1
  244. package/dist/decimal-12NERGYZ.mjs +0 -3
  245. package/dist/decimal-12NERGYZ.mjs.map +0 -1
  246. package/dist/driver-CRaDT4B7.mjs +0 -2
  247. package/dist/driver-options-DxlB1tms.mjs +0 -2
  248. package/dist/driver-options-DxlB1tms.mjs.map +0 -1
  249. package/dist/driver-yCYqzIQg.mjs +0 -2
  250. package/dist/driver-yCYqzIQg.mjs.map +0 -1
  251. package/dist/error-mapping-BWzb-l02.mjs +0 -2
  252. package/dist/error-mapping-BWzb-l02.mjs.map +0 -1
  253. package/dist/execution-context-BPk0YLhd.mjs +0 -2
  254. package/dist/execution-context-BPk0YLhd.mjs.map +0 -1
  255. package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
  256. package/dist/fs-estate-BcjgY4iY.mjs +0 -2
  257. package/dist/fs-estate-BcjgY4iY.mjs.map +0 -1
  258. package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
  259. package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
  260. package/dist/identifiers-By-JRCb5.mjs +0 -2
  261. package/dist/identifiers-By-JRCb5.mjs.map +0 -1
  262. package/dist/key-DKaqPb8w.mjs +0 -2
  263. package/dist/key-DKaqPb8w.mjs.map +0 -1
  264. package/dist/migrations-BWZSBMZh.mjs.map +0 -1
  265. package/dist/mysql-adapter-D9FoHlWE.mjs +0 -2
  266. package/dist/mysql-adapter-D9FoHlWE.mjs.map +0 -1
  267. package/dist/observation-CLp8ylmL.mjs +0 -2
  268. package/dist/observation-CLp8ylmL.mjs.map +0 -1
  269. package/dist/physical-BkelResN.mjs +0 -2
  270. package/dist/pinned-session-Ca7C9yxY.mjs +0 -2
  271. package/dist/pinned-session-Ca7C9yxY.mjs.map +0 -1
  272. package/dist/postgres-adapter-T2Iko-vt.mjs +0 -2
  273. package/dist/postgres-adapter-T2Iko-vt.mjs.map +0 -1
  274. package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
  275. package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
  276. package/dist/result-shape-DKTu8yre.mjs +0 -2
  277. package/dist/result-shape-DKTu8yre.mjs.map +0 -1
  278. package/dist/scalar-BTktMqvO.mjs +0 -2
  279. package/dist/schema-BFNcMdO6.mjs +0 -2
  280. package/dist/schema-introspection-DsXPfCst.mjs +0 -6
  281. package/dist/schema-introspection-DsXPfCst.mjs.map +0 -1
  282. package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
  283. package/dist/sqlite-adapter-HqO3GpAK.mjs +0 -2
  284. package/dist/sqlite-adapter-HqO3GpAK.mjs.map +0 -1
  285. package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
  286. package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
  287. package/dist/transaction-operation-BC7aua5V.mjs.map +0 -1
  288. package/dist/transaction-oskVwmsf.mjs.map +0 -1
  289. package/dist/transactions-gjmrWN5W.mjs +0 -2
  290. package/dist/transactions-gjmrWN5W.mjs.map +0 -1
  291. package/dist/utils-DfztpPvR.mjs.map +0 -1
  292. package/dist/v-B2WwtcRz.mjs +0 -2
  293. package/dist/v-B2WwtcRz.mjs.map +0 -1
  294. package/dist/validation-Du6j0Q38.mjs +0 -2
  295. package/dist/validation-Du6j0Q38.mjs.map +0 -1
  296. package/dist/validation-tgjL_9n8.mjs +0 -2
  297. package/dist/validator-DMlEScV3.mjs +0 -2
  298. package/dist/version-Cr80LFvx.mjs +0 -2
  299. /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
  300. /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"select-assembly-BgqlrePH.mjs","names":["sql","sql"],"sources":["../src/adapters/adapter-result-parser.ts","../src/adapters/constraint-identity.ts","../src/adapters/database-adapter.ts","../src/adapters/shared/decimal-arithmetic.ts","../src/adapters/shared/geo-point.ts","../src/adapters/shared/select-assembly.ts"],"sourcesContent":["import type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport type { DecimalPhysicalRepresentation } from \"@validation/primitives/decimal-codec\";\nimport type {\n IdDomain,\n IdRepresentation,\n} from \"@validation/primitives/id-codec\";\n\nexport interface AdapterResultParser {\n /**\n * How this dialect physically spells a decimal on the way back.\n *\n * `\"coefficient\"` means the column stores (and therefore returns) the signed\n * unscaled integer, cast to text before a driver can round an int64 into a\n * double — the SQLite family, which has no exact decimal type. Every other\n * provider returns native exact decimal text, which is the default when this\n * is unset.\n *\n * It is DECLARED and never inferred: at scale 2 the text `\"120\"` is logical\n * 120 in one vocabulary and logical 1.2 in the other, so a value cannot be\n * read without knowing which promise produced it. Declaring it on the adapter\n * is also what keeps the result parser from asking a dialect question, which\n * the layering rule forbids.\n */\n decimalRepresentation?: DecimalPhysicalRepresentation;\n\n /**\n * How this dialect physically spells a decimal LIST on the way back.\n *\n * `\"coefficient\"` means the column holds a JSON array of unscaled coefficient\n * STRINGS, read back as the container text — JSON has no exact decimal, and a\n * numeric token would already have been rounded past 2^53 by JavaScript or D1\n * (plan 6.1). Unset means the column is a native decimal array whose members\n * arrive as exact decimal text, one JavaScript array member each.\n *\n * A SEPARATE declaration from {@link AdapterResultParser.decimalRepresentation}\n * because the two genuinely differ: MySQL's scalar column is `DECIMAL(p,s)`\n * and answers with text while its list column is JSON and answers with\n * coefficients. Deriving one from the other would decode every MySQL list\n * member at the wrong scale, and the two spellings are indistinguishable by\n * inspection — at scale 2 the member `\"120\"` is 120 in one and 1.2 in the\n * other.\n */\n decimalListRepresentation?: DecimalPhysicalRepresentation;\n\n /**\n * How this dialect physically spells a datetime column that DECLARES the given\n * native type. Unset means timestamp text for every field, which is what every\n * dialect with a temporal column type stores.\n *\n * A function rather than a value because this promise is per FIELD, not per\n * dialect: SQLite has no temporal type at all, so `s.dateTime()` accepts a\n * declaration choosing between TEXT, an INTEGER count of epoch milliseconds\n * and a REAL Julian day, and the DDL already builds the column that way. The\n * adapter is asked because the declaration is dialect vocabulary — a\n * PostgreSQL native type reaching a SQLite adapter describes no column here\n * and answers `\"text\"` like an undeclared field.\n *\n * It is DECLARED and never inferred for the same reason\n * {@link AdapterResultParser.decimalRepresentation} is: the number\n * `2460324.9375` is one instant as a Julian day and a completely different one\n * as milliseconds, so a value cannot be read without knowing which promise\n * produced it.\n */\n dateTimeRepresentation?: (\n nativeType: NativeTypeDeclaration | undefined\n ) => DateTimePhysicalForm;\n\n /**\n * How this dialect physically spells an enum LIST on the way back.\n *\n * `\"arrayText\"` means the column is a native enum array whose element type no\n * driver's result-type table knows, so the provider answers the array's own\n * text (`{ADMIN,USER}`) — PostgreSQL. Unset means the column is the dialect's\n * JSON list container and the members arrive through the JSON reading like\n * every other list.\n *\n * It is DECLARED and never inferred for the same reason\n * {@link AdapterResultParser.decimalRepresentation} is: the two spellings\n * collide on the empty container — `{}` is an empty PostgreSQL array AND a\n * valid JSON object — so a value cannot be read without knowing which promise\n * produced it, and reading array text on a JSON dialect would accept\n * malformed rows every other list type refuses.\n */\n enumListRepresentation?: \"arrayText\";\n\n /**\n * How this dialect physically spells one identifier DOMAIN on a column that\n * declares the given native type.\n *\n * `\"text\"` is the whole public string; `\"uuid\"` the payload as canonical UUID\n * text, which is what a PostgreSQL `uuid` column returns; `\"bytes\"` the\n * payload's own bytes, in whatever binary shape the driver spells them.\n *\n * A function of the DOMAIN and the field's own native type override, not a\n * constant, because both move the answer: a ULID is `bytea` on PostgreSQL and\n * `BINARY(16)` on MySQL, and a `varchar(26)` override keeps either one text\n * while the domain stays admitted. It is DECLARED and never inferred for the\n * same reason {@link AdapterResultParser.decimalRepresentation} is — sixteen\n * bytes and a 36-character string are the same identifier, and a value cannot\n * be read without knowing which promise produced it.\n *\n * Unset means the dialect stores every domain as text. Every shipped adapter\n * declares it; the option exists so a custom adapter that keeps text columns\n * is a complete adapter.\n */\n idRepresentation?: (\n domain: IdDomain,\n nativeType: NativeTypeDeclaration | undefined\n ) => IdRepresentation;\n\n /**\n * When `true`, {@link AdapterResultParser.parseField} performs NO\n * transformation for any scalar type (it is a pure `next()` passthrough) and\n * the provider returns native JS values (text→string, int→number,\n * bool→boolean, float→number). This lets the result parser take an identity\n * fast path for plain string/int/number/boolean columns, skipping the typed\n * decode switch. The path stays byte-identical: a per-value guard defers any\n * non-native value back to the full parser. Adapters that coerce field values\n * (MySQL/SQLite: 0/1→boolean, JSON-as-text, …) leave this unset.\n */\n nativeScalarPassthrough?: boolean;\n\n /**\n * One OPERATION's raw result, once, before it is decoded.\n *\n * This dialect's chance to reshape what the provider answered for a verb,\n * asked exactly once per operation by `Queries.decodeResult` (Arnaud's D-28)\n * with the operation's own rows — never per statement and never per member.\n * It is a REQUIRED member, and every adapter the estate ships installs the\n * one {@link passThroughParseResult} below for it: a result's MEANING belongs\n * to the engine's decoder, which asks for its own aliases and reads them\n * back, and a VALUE's meaning to {@link AdapterResultParser.parseField} and\n * the scalar codecs one level down. Arnaud's D-40 deleted the two legs that\n * decided otherwise (MySQL's count-column normalisation, PostgreSQL's bigint\n * conversion) after measuring both answering `undefined` on every live\n * operation.\n *\n * @param raw - Raw database result\n * @param operation - Query operation type\n * @param next - Call to continue with default parsing\n * - `next()` uses original raw value\n * - `next(transformed)` uses the transformed value\n *\n * @returns Parsed result or result of `next()`\n *\n * @example\n * // Every shipped adapter: the result is the decoder's.\n * parseResult: passThroughParseResult\n */\n parseResult: (\n raw: unknown,\n operation: import(\"../query-engine/types\").Operation,\n next: (value?: unknown) => unknown\n ) => unknown;\n\n /**\n * Parse relation value (nested JSON from includes)\n *\n * @param value - Raw relation value from database\n * @param next - Call to continue with default parsing\n * - `next()` uses original value\n * - `next(parsed)` uses the parsed value\n *\n * @returns Parsed relation or result of `next()`\n *\n * @example\n * // Parse JSON strings (MySQL/SQLite)\n * parseRelation: (value, next) => {\n * const parsed = tryParseJsonString(value);\n * return parsed !== undefined ? next(parsed) : next();\n * }\n */\n parseRelation: (\n value: unknown,\n next: (value?: unknown) => unknown\n ) => unknown;\n\n /**\n * Parse field value by type\n *\n * @param value - Raw field value from database\n * @param scalarType - Scalar type (boolean, datetime, bigint, etc.)\n * @param next - Pass a value to the query engine's strict scalar parser\n * - `next()` uses original value\n * - `next(converted)` uses the converted value\n *\n * @returns Decoded field value. The query engine strictly parses it once.\n *\n * @example\n * // Convert 0/1 to boolean (SQLite/MySQL)\n * parseField: (value, scalarType, next) => {\n * if (scalarType !== 'boolean') return next();\n * const bool = parseIntegerBoolean(value);\n * return bool === undefined ? next() : next(bool);\n * }\n */\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ) => unknown;\n}\n\n/**\n * The `parseResult` every adapter this estate ships installs: the contract's\n * shape, deciding nothing.\n *\n * ONE object, referenced by the SQLite, MySQL and PostgreSQL adapters, so the\n * answer \"this dialect decides nothing about a RESULT\" has a single owner\n * rather than three byte-identical members in three files (Arnaud's D-43). It\n * lives beside the member it implements because this is the file where the\n * contract's shape is declared: the required signature and the do-nothing\n * answer to it are then one fact in one place, and the doc above cannot drift\n * from the value below it.\n *\n * It does NOT close the seam. `Queries.decodeResult` still asks the adapter's\n * own `parseResult` once per operation, so an adapter from outside this estate\n * that installs its own — to recover a result whose transport reshaped it —\n * is still asked and still honoured (Arnaud's D-42: the member stays a public\n * extension point). Both facts are pinned together by \"the three shipped\n * adapters share one pass-through, and a custom adapter's own is still asked\"\n * in `tests/contracts/engine/query/parity-decoding.core.test.ts`.\n */\nexport const passThroughParseResult: AdapterResultParser[\"parseResult\"] = (\n _raw,\n _operation,\n next\n) => next();\n","/** The exact normalized provider evidence that identifies one constraint. */\nexport interface NormalizedConstraintDescriptor {\n readonly table?: string;\n readonly constraint?: string;\n readonly columns?: readonly string[];\n}\n\nexport interface ConstraintIdentity {\n readonly name: string;\n readonly normalizedError: NormalizedConstraintDescriptor;\n}\n\n/** Private adapter projection from a schema key to its physical identity. */\nexport interface ConstraintIdentities {\n readonly primaryKey: (\n tableName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n readonly unique: (\n tableName: string,\n keyName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n}\n\n/** PostgreSQL/MySQL errors identify named constraints and their table. */\nexport function createNamedConstraintIdentities(\n primaryKeyName: (tableName: string) => string\n): ConstraintIdentities {\n const identity = (tableName: string, name: string): ConstraintIdentity => ({\n name,\n normalizedError: { table: tableName, constraint: name },\n });\n return {\n primaryKey: (tableName) => identity(tableName, primaryKeyName(tableName)),\n unique: (tableName, keyName) =>\n identity(tableName, `${tableName}_${keyName}_key`),\n };\n}\n\n/** Driver normalization separates SQLite's physical table and columns. */\nexport const sqliteConstraintIdentities: ConstraintIdentities = {\n primaryKey: (tableName, columns) => ({\n name: `${tableName}_pkey`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n unique: (tableName, keyName, columns) => ({\n name: `${tableName}_${keyName}_key`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n};\n","import type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type { Sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type {\n GeoBounds,\n GeoPoint,\n GeoPolygon,\n} from \"@validation/primitives/geo-values\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nimport type { ArithmeticTarget, CastType } from \"./adapter-core-types\";\nimport type { AdapterResultParser } from \"./adapter-result-parser\";\n\nexport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nexport type {\n ArithmeticTarget,\n CastType,\n} from \"./adapter-core-types\";\nexport type { AdapterResultParser } from \"./adapter-result-parser\";\n\n/** The one physical SQL vocabulary for a logical EPSG:4326 GeoPoint. */\nexport interface GeoPointSql {\n /** Construct a stored point from already-bound longitude and latitude. */\n readonly value: (longitude: Sql, latitude: Sql) => Sql;\n /** Project the logical longitude from a stored point. */\n readonly longitude: (point: Sql) => Sql;\n /** Project the logical latitude from a stored point. */\n readonly latitude: (point: Sql) => Sql;\n /** Exact canonical coordinate equality. */\n readonly equals: (point: Sql, expected: GeoPoint) => Sql;\n /** Inclusive coordinate bounds, including antimeridian-crossing bounds. */\n readonly withinBounds: (point: Sql, bounds: GeoBounds) => Sql;\n /** Inclusive geographic polygon membership on full-tier providers. */\n readonly withinPolygon?: (point: Sql, polygon: GeoPolygon) => Sql;\n /** Fixed-radius spherical distance in meters on full-tier providers. */\n readonly distance?: (left: Sql, right: Sql) => Sql;\n}\n\n/** Install the adapter's settled GeoPoint protocol as one immutable fact. */\nexport function installGeoPointSql(\n adapter: object,\n geoPoint: GeoPointSql | undefined\n): void {\n let installed: GeoPointSql | undefined;\n if (geoPoint) {\n const withinPolygon = geoPoint.withinPolygon;\n const distance = geoPoint.distance;\n installed = Object.freeze<GeoPointSql>({\n value: geoPoint.value,\n longitude: geoPoint.longitude,\n latitude: geoPoint.latitude,\n equals: geoPoint.equals,\n withinBounds: geoPoint.withinBounds,\n ...(withinPolygon ? { withinPolygon } : {}),\n ...(distance ? { distance } : {}),\n });\n }\n Object.defineProperty(adapter, \"geoPoint\", {\n value: installed,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n}\n\n/**\n * DatabaseAdapter Interface\n *\n * A monadic, composable interface for database-specific SQL generation.\n * Each method is a pure function that transforms Sql fragments or primitives\n * into new Sql fragments, enabling clean composition without side effects.\n *\n * DESIGN PRINCIPLES:\n * - Pure functions: Same inputs always produce same outputs\n * - Composable: Outputs can be inputs to other methods\n * - Database-agnostic inputs: Query engine speaks neutral language\n * - Database-specific outputs: Adapter handles syntax differences\n *\n * USAGE:\n * The query engine calls adapter methods to build SQL fragments,\n * then composes them into complete queries. The adapter never\n * needs to understand query semantics - just SQL syntax.\n */\nexport interface DatabaseAdapter {\n /**\n * NAMESPACE\n * The one normalized SQL qualification value for this adapter's persistent\n * objects — a PostgreSQL schema, a MySQL database, or a requested Vitess\n * keyspace qualifier. `undefined` means deliberately unqualified: unbound\n * MySQL and every SQLite adapter. It is selected once at construction and\n * installed non-writable, and THAT INSTALL is where its immutability lives —\n * not a ban on copies: the two readers that capture it once, the bound\n * migration driver at bind time and the `readDriverIdentity` snapshot a cached\n * read takes, cannot go stale because the property they read can never be\n * reassigned.\n */\n readonly namespace?: string;\n\n /**\n * RAW\n * Escape hatch for raw SQL strings (use sparingly)\n */\n raw: (sqlString: string) => Sql;\n\n /**\n * IDENTIFIERS\n * Database-specific identifier escaping (table names, column names, aliases)\n */\n identifiers: {\n /** Escape a single identifier: \"name\" or `name` */\n escape: (name: string) => Sql;\n /** Create qualified column reference: \"alias\".\"field\" */\n column: (alias: string, field: string) => Sql;\n /**\n * The one renderer for a persistent model or junction table: applies the\n * adapter's namespace and, when an alias is given, the `AS` clause.\n * Statement-local names — CTEs, aliases, columns, constraints — use\n * `escape` instead, and an omitted alias is for a site that splices its own.\n */\n table: (tableName: string, alias?: string) => Sql;\n /** Create aliased expression: expr AS \"alias\" */\n aliased: (expression: Sql, alias: string) => Sql;\n };\n\n /**\n * LITERALS\n * Value wrapping with proper parameterization\n */\n literals: {\n /** Wrap a value as parameterized SQL */\n value: (v: unknown) => Sql;\n /** NULL keyword */\n null: () => Sql;\n /** TRUE literal (database-specific: TRUE vs 1) */\n true: () => Sql;\n /** FALSE literal (database-specific: FALSE vs 0) */\n false: () => Sql;\n /** Create a value list: ($1, $2, $3) */\n list: (values: Sql[]) => Sql;\n /** JSON value (PG: native, MySQL/SQLite: JSON.stringify) */\n json: (v: unknown) => Sql;\n /**\n * Datetime operand from a validated ISO-8601 string, in the PHYSICAL form\n * the destination column holds (PG: as-is, MySQL: naive UTC\n * 'YYYY-MM-DD HH:MM:SS.mmm').\n *\n * `nativeType` is the field's own declaration, threaded because SQLite has\n * no temporal type: a `s.dateTime(SQLITE.DATETIME.INTEGER)` column holds\n * epoch milliseconds and a `REAL` one holds a Julian day, so an ISO string\n * bound into either compares against nothing and stores text the typed read\n * then refuses. The dialects that DO have a temporal type ignore it — their\n * own native types all name a column that accepts this same spelling.\n */\n dateTime: (\n iso: string,\n nativeType?: NativeTypeDeclaration,\n member?: boolean\n ) => Sql;\n /**\n * Decimal operand from a canonical decimal string, in the DOMAIN it is\n * being compared or assigned against.\n *\n * The value binds as text and the DIALECT decides how to read it, because\n * the reading is where precision is won or lost. PostgreSQL and MySQL cast\n * it into their exact decimal type — MySQL in particular compares a\n * `DECIMAL` column against an uncast string operand as a *double*, which\n * would make an exact column compare inexactly with nothing to show for it.\n * SQLite has no exact decimal type and stores the unscaled integer\n * coefficient, so there the operand becomes that same coefficient.\n *\n * The descriptor is the operand's domain, which is USUALLY the field's and\n * deliberately not always: a `having: { _sum: ... }` operand is compared\n * against a sum that may legitimately be wider than any single row's\n * column, so the aggregate's caller widens the precision it passes. The\n * scale is the field's on every path — it is what makes the operand and the\n * column the same physical kind of number.\n */\n decimal: (canonical: string, descriptor: DecimalDescriptor) => Sql;\n /**\n * Identifier operand, in the PHYSICAL representation its column holds.\n *\n * The value arrives already encoded by the codec — canonical public text,\n * canonical UUID text, or the payload's own bytes — so nothing here reads a\n * format, a prefix or an alphabet. What the dialect owns is the BINDING: a\n * PostgreSQL `uuid` column takes text and wants the operand typed as\n * `uuid`, because an untyped text operand against a `uuid` column is\n * `operator does not exist: uuid = text`; a `bytea`, `BINARY(n)` or `BLOB`\n * column takes the bytes as an ordinary binary parameter, which every\n * driver already serializes for blob scalars.\n *\n * Separate from {@link DatabaseAdapter.literals.value} for the reason\n * `decimal` is: the operand and the column have to be ONE physical kind, and\n * a generic parameter leaves that to inference at every site.\n */\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ) => Sql;\n };\n\n /**\n * OPERATORS\n * Comparison and logical operators (pure Sql -> Sql)\n */\n operators: {\n // Comparison\n eq: (left: Sql, right: Sql) => Sql;\n neq: (left: Sql, right: Sql) => Sql;\n lt: (left: Sql, right: Sql) => Sql;\n lte: (left: Sql, right: Sql) => Sql;\n gt: (left: Sql, right: Sql) => Sql;\n gte: (left: Sql, right: Sql) => Sql;\n\n // Pattern matching\n like: (column: Sql, pattern: Sql) => Sql;\n notLike: (column: Sql, pattern: Sql) => Sql;\n /** Case-insensitive LIKE. */\n ilike: (column: Sql, pattern: Sql) => Sql;\n notIlike: (column: Sql, pattern: Sql) => Sql;\n /** Case-sensitive substring predicates, independent of database collation. */\n containsText: (column: Sql, value: Sql) => Sql;\n startsWithText: (column: Sql, value: Sql) => Sql;\n endsWithText: (column: Sql, value: Sql) => Sql;\n /**\n * `startsWithText` for a plain string operand, spelled so the dialect's\n * planner can turn it into an index range.\n *\n * Same answer as `startsWithText` on every input — it exists only because\n * `startsWithText` wraps the COLUMN in a function (`LEFT`/`substr`), which\n * no planner can range on. This one takes the raw JS string instead of a\n * bound `Sql` so the adapter can escape it into its own pattern language\n * and bind the finished pattern; a pattern assembled in SQL from the\n * operand would be non-constant and lose the range again.\n *\n * Only the where-builder's default-mode, plain-string, `string`-scalar path\n * reaches it. A field-reference operand, a JSON path, an enum column and\n * `mode: \"insensitive\"` all keep `startsWithText`: each of those either has\n * no client-side string to escape, or already wraps the column in a fold\n * that forecloses the range anyway.\n *\n * Each dialect's implementation must hold the case-sensitivity contract\n * `startsWithText` documents. See the per-adapter comments — the three\n * answers are not the same shape, and the measurements that forced that\n * are recorded in `docs/architecture/query-performance-plan.md`, §7.3.\n */\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n /**\n * `column = value` and `column IN (values)` on a TEXT column, under the\n * case-sensitive semantics `caseSensitiveText` spells, written so the\n * dialect's planner can still use an index.\n *\n * `column` arrives unwrapped: each adapter applies its own\n * `caseSensitiveText` where its own semantics need it, and is free to put\n * an index-usable conjunct in front of it. On PostgreSQL and SQLite that\n * is exactly `caseSensitiveText(column) <op> …` and nothing more — their\n * case-sensitive spellings are already index-usable. MySQL's is not: the\n * `BINARY` cast is a function of the column, so the planner drops to a full\n * scan, and MySQL adds a collation-native conjunct in front. See\n * `docs/architecture/query-performance-plan.md`, §10.2 for the plans.\n *\n * The operands are BOUND values, never referenced columns — the caller\n * routes a reference to the plain comparison, which has no index lookup to\n * preserve.\n */\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n // Set membership\n in: (column: Sql, values: Sql) => Sql;\n notIn: (column: Sql, values: Sql) => Sql;\n\n // Null checks\n isNull: (expr: Sql) => Sql;\n isNotNull: (expr: Sql) => Sql;\n\n // Range\n between: (column: Sql, min: Sql, max: Sql) => Sql;\n notBetween: (column: Sql, min: Sql, max: Sql) => Sql;\n\n // Logical\n and: (...conditions: Sql[]) => Sql;\n or: (...conditions: Sql[]) => Sql;\n not: (condition: Sql) => Sql;\n\n // Subquery existence\n exists: (subquery: Sql) => Sql;\n notExists: (subquery: Sql) => Sql;\n };\n\n /**\n * EXPRESSIONS\n * Computed values and functions\n */\n expressions: {\n /** Portable searched CASE expression. */\n caseWhen: (\n branches: readonly { readonly when: Sql; readonly then: Sql }[],\n otherwise: Sql\n ) => Sql;\n\n // Arithmetic\n add: (left: Sql, right: Sql) => Sql;\n subtract: (left: Sql, right: Sql) => Sql;\n multiply: (left: Sql, right: Sql) => Sql;\n divide: (left: Sql, right: Sql) => Sql;\n /**\n * The integer quotient of two integer operands, truncated toward zero.\n *\n * The same fact {@link DatabaseAdapter.set.divide}'s `target.integer` flag\n * already carries, as an EXPRESSION rather than an assignment: naming the\n * value an integer column will hold after `{ divide }` needs the dialect's\n * own truncation, and `/` does not agree across dialects. SQLite and\n * PostgreSQL truncate natively once both operands are integers, while MySQL\n * `/` yields a DECIMAL quotient and needs `TRUNCATE(…, 0)`. Casting the\n * quotient afterwards is not a substitute: MySQL and PostgreSQL ROUND on\n * cast, only SQLite truncates.\n */\n integerDivide: (left: Sql, right: Sql) => Sql;\n\n // String operations\n concat: (...parts: Sql[]) => Sql;\n upper: (expr: Sql) => Sql;\n lower: (expr: Sql) => Sql;\n /** Fold ASCII A-Z to a-z without provider-native Unicode case folding. */\n asciiCaseFold: (expr: Sql) => Sql;\n /** Force exact text comparison semantics independent of column/database collation. */\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation?: boolean\n ) => Sql;\n\n /** Cast a deferred value into one fixed-decimal field's exact domain. */\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * Bind a DEFERRED identifier back into its column's physical type — the\n * INVERSE of the transport spelling a byte column travels in (lowercase\n * hex, `query-engine/raptor3/shared/identifier.ts`\n * `transportedIdentifier`).\n *\n * NO ENGINE CALLER since the Raptor 3 port: that engine has no deferred\n * identifier — a located key is a raw column sub-select, already physical,\n * and the batch scratch carries integers only. The member stays declared\n * and pinned (`tests/contracts/adapters/identifier-storage.core.test.ts`)\n * until its owner retires or re-adopts it; the provenance below is the\n * retired engine's.\n *\n * The sibling of {@link DatabaseAdapter.expressions.decimalCast}, and\n * needed for the same reason: a relation key whose value does not exist at\n * build time — a `Ref` into a located parent's captured column — cannot go\n * through `literals.id`, and the generic `text` cast names a type the\n * column does not have. `CAST($1 AS TEXT)` against a PostgreSQL `uuid`\n * column is the 42804 this exists to avoid.\n *\n * A deferred value has exactly ONE provenance — a step output, which is a\n * row the driver returned — so it arrives in the spelling that projection\n * published: LOWERCASE HEX for a `bytes` column, canonical text for a\n * `uuid` or text-stored one. A plain cast of that hex into the binary type\n * would bind the hex text's own bytes, so the binary arm decodes it\n * (`decode(…, 'hex')`, `UNHEX`, `unhex`). SQLite's `unhex()` arrived in\n * 3.41, above this adapter's 3.35 floor: a compact identifier on SQLite\n * needs 3.41, and nothing else here does.\n */\n idCast: (expr: Sql, representation: IdRepresentation) => Sql;\n\n // Utility\n coalesce: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n greatest: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n least: (...exprs: Sql[]) => Sql;\n cast: (expr: Sql, type: CastType) => Sql;\n /**\n * Hex-encode a binary column for JSON embedding — JSON can't hold binary\n * (PG: encode(x, 'hex'), MySQL/SQLite: lower(hex(x))).\n * The result parser decodes hex back to Uint8Array.\n */\n blobToHex: (expr: Sql) => Sql;\n };\n\n /**\n * AGGREGATES\n * Aggregate functions\n */\n aggregates: {\n count: (expr?: Sql) => Sql;\n countDistinct: (expr: Sql) => Sql;\n sum: (expr: Sql) => Sql;\n avg: (expr: Sql) => Sql;\n min: (expr: Sql, boolean?: boolean) => Sql;\n max: (expr: Sql, boolean?: boolean) => Sql;\n /**\n * The average of an EXACT decimal column, in the column's own physical\n * domain and quantized to the field's scale with round-half-to-even.\n *\n * Separate from {@link DatabaseAdapter.aggregates.avg} because `AVG()` is a\n * different function on a decimal: SQLite computes it in a double, and\n * PostgreSQL/MySQL choose the result's scale themselves. This one is\n * derived from the exact `SUM` and `COUNT(column)` — so it is NULL for an\n * empty or all-null group — and rounds by the one shared rule rather than\n * by a provider default.\n */\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * The widened precision needed to cast this exact coefficient as a\n * `having _sum` operand, or `undefined` when the dialect cannot represent\n * that value exactly.\n *\n * `_sum` may exceed one row's precision, but its comparison domain is not\n * unbounded. PostgreSQL and MySQL admit by their exact decimal precision;\n * SQLite admits by signed-int64 VALUE, whose valid range contains some but\n * not all 19-digit coefficients. The adapter owns that provider fact so the\n * query engine never branches on a dialect or silently binds a saturated\n * value.\n */\n decimalSumOperandPrecision: (coefficient: string) => number | undefined;\n };\n\n /**\n * JSON\n * Database-specific JSON building and extraction\n */\n json: {\n /** Structural JSON equality: object key order is insignificant. */\n equals: (left: Sql, right: Sql) => Sql;\n /** Convert a SQL predicate into a JSON boolean value. */\n boolean: (condition: Sql) => Sql;\n /** Preserve a SQL expression as a JSON document when embedding it in JSON. */\n document: (expression: Sql) => Sql;\n /** Carry a finite number through JSON without losing binary precision. */\n number: (expression: Sql) => Sql;\n /** Build JSON object from key-value pairs */\n object: (pairs: [string, Sql][]) => Sql;\n /** Build JSON array from items */\n array: (items: Sql[]) => Sql;\n /** Empty JSON array literal: '[]'::json (PG), JSON_ARRAY() (MySQL), '[]' (SQLite) */\n emptyArray: () => Sql;\n /**\n * Aggregate rows into a JSON array. An empty aggregate is the empty array,\n * never SQL NULL, so no caller wraps it in its own COALESCE.\n */\n agg: (expr: Sql) => Sql;\n /** Build JSON object from explicit column list (works on all databases) */\n objectFromColumns: (columns: [string, Sql][]) => Sql;\n /**\n * Extract the JSON value at a path (empty path = document root) in a\n * form comparable against `json.value` params. Integer segments address\n * array elements. Used by JSON path filters in the where-builder.\n */\n extract: (column: Sql, path: string[]) => Sql;\n /**\n * Extract the value at a path as text (strings unquoted; empty path =\n * document root). Used by JSON string_contains/starts_with/ends_with.\n */\n extractText: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as a double-precision number, or SQL NULL when the\n * path is absent or the JSON value there is NOT a JSON number. Every\n * dialect gates the cast behind its own JSON type test (PG jsonb_typeof,\n * MySQL JSON_TYPE, SQLite json_type) so a non-numeric value yields NULL\n * instead of a cast error. Used by JSON lt/lte/gt/gte with number\n * operands: NULL never satisfies a comparison, so mismatched types and\n * absent paths never match and never error.\n */\n numberAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as unquoted text under a byte-ordered collation\n * (PG COLLATE \"C\", MySQL VARBINARY, SQLite COLLATE BINARY), or SQL NULL\n * when the path is absent or the JSON value there is NOT a JSON string.\n * The forced collation makes `<`/`>` code-point ordering on every\n * dialect instead of the database's default (locale) collation. Used by\n * JSON lt/lte/gt/gte with string operands.\n */\n stringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * JSON array containment: target is an array containing every element\n * of the candidate JSON array value (PG @>, MySQL JSON_CONTAINS,\n * SQLite json_each). Used by the array_contains filter.\n */\n contains: (target: Sql, value: Sql) => Sql;\n /**\n * Last element of a JSON array (PG -> -1, MySQL $[last],\n * SQLite $[#-1]). Used by the array_ends_with filter.\n */\n lastElement: (target: Sql) => Sql;\n /**\n * Parameterized JSON value usable in comparisons against a JSON column.\n * PG: plain param (jsonb), MySQL: CAST(? AS JSON) so equality compares\n * JSON documents instead of coercing to a JSON string scalar,\n * SQLite: canonical JSON text param.\n */\n value: (v: unknown) => Sql;\n };\n\n /**\n * ARRAYS\n * Array operations (PG: native arrays, MySQL/SQLite: JSON-based)\n */\n arrays: {\n /**\n * Create array literal. Reserved — not called by the query engine yet.\n */\n literal: (items: Sql[]) => Sql;\n /**\n * Parameterized value for a complete list in the dialect's storage\n * format: native array param (PG), CAST(? AS JSON) (MySQL), canonical\n * JSON text param (SQLite). Used for list writes and equals/not filters.\n */\n value: (values: unknown[], temporal?: \"date\" | \"datetime\") => Sql;\n /**\n * Parameterized value for a complete ENUM list.\n *\n * The one list whose element type no driver can serialize: a PostgreSQL\n * managed enum is created by the estate, so its array OID is in no driver's\n * serializer table and the native array parameter above reaches the server\n * as `ADMIN,USER` (22P02). PostgreSQL binds the array literal as ONE\n * untyped parameter and lets the column or operand it meets resolve the\n * type, so the enum's NAME stays with the migration driver that generated\n * it and never appears in runtime SQL. The JSON-backed dialects answer with\n * the same container every other list uses — there, an enum list has no\n * element type to spell at all.\n */\n enumValue: (values: unknown[]) => Sql;\n /** Check if array contains value */\n has: (column: Sql, value: Sql) => Sql;\n /** Check if array contains all values */\n hasEvery: (column: Sql, values: Sql) => Sql;\n /** Check if array contains any value */\n hasSome: (column: Sql, values: Sql) => Sql;\n /** Check if array is empty */\n isEmpty: (column: Sql) => Sql;\n /**\n * Project a numeric list without a provider/JSON carrier rounding members.\n *\n * Decimal, bigint and floating-point lists share this transport boundary.\n * On a native-array dialect the members are exact text, and\n * the whole-column TEXT cast every other decimal projection uses yields the\n * dialect's own array literal (`{1.20,-0.03}`) rather than an array of\n * members — while embedding the column in a JSON carrier uncast yields JSON\n * NUMBERS, which round past 2^53. Casting ELEMENT-WISE answers both: the\n * flat read gets an array of exact text and the carrier gets a JSON array of\n * strings. On a JSON-backed dialect the container is already an array of\n * coefficient strings and what this owns is that it arrives as TEXT rather\n * than as a driver-parsed document.\n *\n * One name, one meaning, three dialect spellings — the query engine asks for\n * a readable numeric list and never for a dialect cast.\n */\n exactNumericProjection: (column: Sql) => Sql;\n /** Get array length. Reserved — not called by the query engine yet. */\n length: (column: Sql) => Sql;\n /** Get element at index. Reserved — not called by the query engine yet. */\n get: (column: Sql, index: Sql) => Sql;\n /**\n * Append value to array. Reserved — not called by the query engine yet.\n */\n push: (column: Sql, value: Sql) => Sql;\n /** Set value at index. Reserved — not called by the query engine yet. */\n set: (column: Sql, index: Sql, value: Sql) => Sql;\n };\n\n /**\n * ORDER BY\n * Ordering helpers\n */\n orderBy: {\n asc: (column: Sql) => Sql;\n desc: (column: Sql) => Sql;\n /** Directed order placing NULLs first (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n /** Directed order placing NULLs last (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n };\n\n /**\n * CLAUSES\n * SQL clause keywords\n */\n /**\n * LIMIT value meaning \"no limit\", for dialects that reject OFFSET without\n * LIMIT (MySQL: 18446744073709551615, SQLite: -1).\n * Omit when the dialect supports bare OFFSET (PostgreSQL).\n *\n * It is also the bound an ORDERED derived table states when its caller asked\n * for no window: MySQL merges an unlimited derived table into the query that\n * reads it and the merge takes the ORDER BY with it, so a page whose order a\n * reader consumes (the to-many include's aggregate) spells this value rather\n * than losing it. A dialect that keeps a derived order unbounded declares\n * none and emits nothing.\n */\n noLimitValue?: Sql;\n\n clauses: {\n select: (columns: Sql) => Sql;\n selectDistinct: (columns: Sql) => Sql;\n from: (table: Sql) => Sql;\n where: (condition: Sql) => Sql;\n orderBy: (orders: Sql) => Sql;\n limit: (count: Sql) => Sql;\n offset: (count: Sql) => Sql;\n groupBy: (columns: Sql) => Sql;\n having: (condition: Sql) => Sql;\n };\n\n /**\n * SET\n * UPDATE SET operations\n */\n set: {\n /** Simple assignment: \"col\" = value */\n assign: (column: Sql, value: Sql) => Sql;\n /** Increment: \"col\" = \"col\" + value */\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /** Decrement: \"col\" = \"col\" - value */\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Multiply: \"col\" = \"col\" * value.\n * A decimal target rounds the product back to its scale (see\n * {@link ArithmeticTarget}); every other target multiplies natively.\n */\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Divide: \"col\" = \"col\" / value.\n * `target.integer` tells the adapter the target column is integer-typed\n * so it can force integer division where the dialect would otherwise do\n * real division. SQLite binds the operand as REAL, while MySQL `/` returns\n * a decimal quotient even for integer columns; both adapters use the flag\n * to preserve truncation toward zero. PostgreSQL integer division already\n * has that behavior and ignores the flag. A decimal target instead rounds\n * the quotient to its scale.\n */\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Array push: append the complete provider-encoded `values` container.\n * The query engine selects the scalar's list vocabulary once; the adapter\n * owns only how its dialect concatenates two containers.\n */\n push: (column: Sql, values: Sql) => Sql;\n /** Array unshift: prepend the complete provider-encoded container. */\n unshift: (column: Sql, values: Sql) => Sql;\n };\n\n /**\n * FILTERS\n * Relation filter wrappers for subqueries\n */\n filters: {\n /** EXISTS wrapper for \"some\" relation filter (to-many) */\n some: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"every\" - negated condition (to-many) */\n every: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"none\" (to-many) */\n none: (subquery: Sql) => Sql;\n /** EXISTS wrapper for \"is\" relation filter (to-one) */\n is: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"isNot\" relation filter (to-one) */\n isNot: (subquery: Sql) => Sql;\n };\n\n /**\n * SUBQUERIES\n * Subquery wrappers\n */\n subqueries: {\n /** Scalar subquery: (SELECT ...) */\n scalar: (query: Sql) => Sql;\n /** Correlated subquery with alias */\n correlate: (query: Sql, alias: string) => Sql;\n /** Build EXISTS-style subquery: SELECT 1 FROM table WHERE condition */\n existsCheck: (from: Sql, where: Sql) => Sql;\n };\n\n /**\n * CTE\n * Common Table Expressions\n */\n cte: {\n /** Build WITH clause: WITH name AS (query), ... */\n with: (definitions: { name: string; query: Sql }[]) => Sql;\n /**\n * Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).\n * The query engine calls only the `\"distinct\"` mode (`UNION`); the default\n * `\"all\"` mode is reserved — not called by the query engine yet.\n */\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union?: \"all\" | \"distinct\"\n ) => Sql;\n };\n\n /**\n * MUTATIONS\n * Insert, Update, Delete operations\n */\n mutations: {\n /** How top-level bulk create realizes duplicate-only skipping. */\n skipDuplicatesStrategy: \"sql\" | \"recoverableUniqueError\";\n /** INSERT INTO table (cols) from literal rows or a SELECT source. */\n insert: (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ) => Sql;\n /** Insert one row using only database defaults. */\n insertDefault: (table: Sql) => Sql;\n /** UPDATE table SET ... WHERE ... */\n update: (table: Sql, sets: Sql, where?: Sql) => Sql;\n /** DELETE FROM table WHERE ... */\n delete: (table: Sql, where?: Sql) => Sql;\n /** RETURNING clause (PG/SQLite) or empty (MySQL) */\n returning: (columns: Sql) => Sql;\n /**\n * ON CONFLICT / ON DUPLICATE KEY\n * @param target - Conflict target columns (e.g., \"id\")\n * @param action - Action to take (e.g., UPDATE SET ...)\n * @param targetWhere - Optional WHERE for partial unique index matching\n * PostgreSQL: ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n */\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql) => Sql;\n /**\n * Build update action for ON CONFLICT (PG/SQLite: UPDATE SET ..., MySQL: just the SET part)\n * @param sets - SET clause assignments\n * @param setWhere - Optional WHERE for conditional updates\n * PostgreSQL: ... DO UPDATE SET x = y WHERE <setWhere>\n */\n onConflictUpdate: (sets: Sql, setWhere?: Sql) => Sql;\n /**\n * Skip duplicate key errors (for createMany with skipDuplicates: true)\n * PostgreSQL/SQLite: ON CONFLICT DO NOTHING (suffix)\n * MySQL: duplicate-key-only no-op update (suffix)\n *\n * UNTARGETED ON PURPOSE, and that is the whole distinction from\n * {@link DatabaseAdapter.mutations.onConflict}: `createMany({\n * skipDuplicates: true })` promises to skip a row that collides with ANY\n * unique constraint, so naming one would be the wrong answer. A JUNCTION\n * membership insert asks the opposite question — skip only an exact repeat\n * of this complete `(owner, target)` key, and let a target-side UNIQUE\n * (a singular polymorphic member's occupied slot) raise — so it goes\n * through the targeted door instead. See `junctionDuplicateSkip` in\n * `query-engine/builders/many-to-many-utils.ts`; do not route it back here.\n */\n skipDuplicates: (duplicateNoopColumn: string) => {\n prefix: Sql;\n suffix: Sql;\n };\n };\n\n /**\n * ASSERTIONS\n * Dialect-specific statements that abort a batch when a precondition fails.\n */\n assertions: {\n /** Abort unless the provided SELECT returns at least one row. */\n exists: (query: Sql) => Sql;\n /** Abort unless the provided SELECT returns no rows. */\n notExists: (query: Sql) => Sql;\n };\n\n capabilities: DatabaseAdapterCapabilities;\n\n /**\n * LAST INSERT ID\n * Returns SQL for getting the last auto-generated ID.\n * Used only where the provider exposes an exact statement-local identity.\n *\n * PostgreSQL: lastval() exists for legacy/direct SQL uses, but batchRefs does not\n * expose it because another generated column or trigger can change the session value\n * SQLite: last_insert_rowid() - returns last ROWID inserted\n * MySQL: LAST_INSERT_ID() - returns last AUTO_INCREMENT value\n */\n lastInsertId: () => Sql;\n\n /**\n * JOINS\n * Join operations\n */\n joins: {\n inner: (table: Sql, condition: Sql) => Sql;\n left: (table: Sql, condition: Sql) => Sql;\n right: (table: Sql, condition: Sql) => Sql;\n full: (table: Sql, condition: Sql) => Sql;\n cross: (table: Sql) => Sql;\n /**\n * LATERAL subquery join (PostgreSQL 9.3+, MySQL 8.0.14+)\n * Allows referencing columns from preceding tables in the subquery.\n * Used for efficient nested includes.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns JOIN LATERAL (subquery) AS alias ON true\n */\n lateral: (subquery: Sql, alias: string) => Sql;\n /**\n * LEFT JOIN LATERAL - same as lateral but with LEFT JOIN semantics\n * Returns NULL for the joined columns when subquery returns no rows.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns LEFT JOIN LATERAL (subquery) AS alias ON true\n */\n lateralLeft: (subquery: Sql, alias: string) => Sql;\n };\n\n /**\n * SET OPERATIONS\n * UNION, INTERSECT, EXCEPT operations\n */\n setOperations: {\n /** UNION (removes duplicates) */\n union: (...queries: Sql[]) => Sql;\n /**\n * UNION ALL (keeps duplicates). Reserved — not called by the query engine\n * yet.\n */\n unionAll: (...queries: Sql[]) => Sql;\n /** INTERSECT */\n intersect: (...queries: Sql[]) => Sql;\n /** EXCEPT / MINUS */\n except: (left: Sql, right: Sql) => Sql;\n };\n\n /**\n * VECTOR\n * Vector operations for similarity search (pgvector)\n *\n * Matches filter schema: { l2, cosine }\n * Drivers that don't support vector operations can override\n * this property with an object that throws FeatureNotSupportedError.\n *\n * Reserved — the query engine does not call these yet; vector filters are\n * rejected in the where-builder today.\n */\n vector: {\n /** Create a vector literal from number array: '[1,2,3]'::vector */\n literal: (values: number[]) => Sql;\n /** L2 (Euclidean) distance operator for ORDER BY: column <-> vector */\n l2: (column: Sql, vector: Sql) => Sql;\n /** Cosine distance operator for ORDER BY: column <=> vector */\n cosine: (column: Sql, vector: Sql) => Sql;\n };\n\n /**\n * Exact EPSG:4326 point SQL. Absence means this adapter has no physical\n * GeoPoint tier; optional members distinguish the full polygon/distance tier.\n */\n readonly geoPoint?: GeoPointSql;\n\n result: AdapterResultParser;\n}\n","/**\n * The ONE round-half-to-even rule, spelled in each dialect's exact integer\n * vocabulary.\n *\n * Multiply, divide and average are the only operations that can create digits\n * beyond a decimal field's scale, so they are the only ones that round — and\n * they round the same way everywhere, because a rounding mode that came from\n * the provider would make the same query answer differently per database.\n * Nothing here consults a provider default: quotient, remainder and parity are\n * exact integer facts, and the arms are composed from them.\n *\n * WHY A QUOTIENT RULE AND NOT A ROUNDING FUNCTION. `ROUND()` is half-up on\n * MySQL, half-even-ish on PostgreSQL numerics, and absent on SQLite; every one\n * of them would have to be trusted at the exact tie this rule exists to decide.\n * Quotient/remainder/parity are the same three integers on all three.\n *\n * NO PATH CASTS THROUGH REAL. Every operand below is an integer or an exact\n * decimal, and every operator applied to them is exact in its dialect.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n/**\n * How one dialect spells EXACT truncated division and its remainder.\n *\n * `quotient(n, d)` truncates toward zero and `remainder(n, d)` carries the sign\n * of `n`, which is C semantics and what all three dialects already do — but\n * they spell it three ways, and one of the three (`n / d`) is only integer\n * division when both operands are integers. Each adapter declares its own pair\n * so this file never asks which database it is running against.\n */\nexport interface ExactIntegerArithmetic {\n /** `n / d` truncated toward zero. `d` is never zero unless `n` is NULL. */\n readonly quotient: (n: Sql, d: Sql) => Sql;\n /** `n - quotient(n, d) * d`; sign follows `n`. */\n readonly remainder: (n: Sql, d: Sql) => Sql;\n}\n\n/** `10^scale`, the factor between a logical value and its coefficient. */\nexport const scaleFactorSql = (scale: number): Sql =>\n sql.raw(`1${\"0\".repeat(scale)}`);\n\n/**\n * `10^-scale`: one unit in the last place of the field's domain, as an exact\n * decimal literal. Multiplying a coefficient by it is exact on PostgreSQL and\n * MySQL (scales add); DIVIDING by `10^scale` is not — MySQL computes a quotient\n * to `div_precision_increment` extra digits and rounds there, which would put a\n * provider default back in charge of the last digit.\n */\nexport const scaleUnitSql = (scale: number): Sql =>\n sql.raw(scale === 0 ? \"1\" : `0.${\"0\".repeat(scale - 1)}1`);\n\n/**\n * `n / d` rounded half to even, for `d > 0` and any sign of `n`.\n *\n * The three facts: `q` is the truncated quotient, `r` the remainder, and the\n * decision compares `|r|` against `d - |r|` — below is down, above is away from\n * zero, and EQUAL is the tie, resolved by `q`'s parity so the even neighbour\n * wins.\n *\n * WHY `|r| vs d - |r|` AND NOT `2|r| vs d`. They decide identically (`|r| >\n * d - |r|` is `2|r| > d` rearranged), but the doubled form is the only one that\n * can leave the dialect's exact domain: `|r| < d`, so `d - |r|` is bounded by\n * the divisor while `2|r|` needs one digit MORE than it. That extra digit is\n * the whole domain on the two dialects with a finite one — a 65-digit MySQL\n * divisor doubles to 66, and an int64 count doubles past int64 — so the\n * comparison is written in the form that never widens.\n *\n * The sign of the step reads `r`, not `n`: the step is taken only when `r <> 0`\n * (`|r| > d - |r| >= 0`, or `|r| = d - |r|` which needs `r <> 0` for a non-zero\n * `d`), and a non-zero remainder has exactly the sign of the dividend. Reading\n * `r` keeps one fewer copy of `n` in the emitted statement.\n *\n * `d` MUST be positive. A negative divisor would flip which neighbour is\n * \"away\", so the callers below normalize the sign onto the numerator instead.\n */\nexport const halfEvenQuotient = (\n integers: ExactIntegerArithmetic,\n n: Sql,\n d: Sql\n): Sql => {\n const q = integers.quotient(n, d);\n const r = integers.remainder(n, d);\n const parity = integers.remainder(q, sql.raw`2`);\n return sql`(${q} + (CASE WHEN ABS(${r}) > ${d} - ABS(${r}) OR (ABS(${r}) = ${d} - ABS(${r}) AND ${parity} <> 0) THEN (CASE WHEN ${r} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`;\n};\n\n/**\n * `n` with the divisor's sign folded in, so the half-even rule always sees a\n * positive divisor. `n x sign(d)` and `|d|` name the same quotient as `n / d`.\n */\nexport const signedNumerator = (n: Sql, d: Sql): Sql =>\n sql`(CASE WHEN ${d} < 0 THEN -${n} ELSE ${n} END)`;\n\n/**\n * `column = halfEven(column x by)` where the column holds the LOGICAL decimal\n * in a dialect whose exact decimal domain is UNBOUNDED — PostgreSQL's\n * `NUMERIC`, which computes an expression at whatever width the value needs.\n *\n * The rule is stated on the COEFFICIENT, so the product is scaled up by `10^s`\n * — leaving a value whose integer part is the answer's coefficient and whose\n * fraction is what has to be rounded away — rounded to an integer against a\n * divisor of one, and scaled back by one exact multiplication.\n *\n * The widest intermediate is `column x by x 10^s`, which needs `2p + s` digits.\n * That is why MySQL does NOT use this form: its exact domain stops at 65\n * digits, and past it MySQL rounds an over-scaled product to 30 fractional\n * digits or answers ZERO without a warning. MySQL spells the same rule in its\n * own bounded, coefficient-space form (`mysql-adapter.ts`); this one is\n * PostgreSQL's, where no such ceiling exists.\n */\nexport const logicalDecimalMultiply = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const scaled = sql`(${column} * ${by} * ${scaleFactorSql(descriptor.scale)})`;\n const coefficient = halfEvenQuotient(integers, scaled, sql.raw`1`);\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * `column = halfEven(column / by)` where the column holds the LOGICAL decimal\n * in an unbounded exact domain ({@link logicalDecimalMultiply}'s PostgreSQL).\n *\n * The quotient is never computed by the dialect's `/`: the answer's coefficient\n * is `halfEven((column x 10^s) / by)`, which is a quotient of an exact integer\n * by an exact decimal, so remainder and parity decide the last digit instead of\n * `div_precision_increment` or a numeric division's chosen scale.\n *\n * `by` is non-zero: division by canonical zero is refused before I/O, where the\n * operand's canonical text is still in hand (`set-builder.ts`).\n */\nexport const logicalDecimalDivide = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n signedNumerator(sql`(${column} * ${scaleFactorSql(descriptor.scale)})`, by),\n sql`ABS(${by})`\n );\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * The exact decimal average of a LOGICAL decimal column in an unbounded exact\n * domain ({@link logicalDecimalMultiply}'s PostgreSQL): the exact `SUM` over\n * `COUNT(column)`, quantized to the field's scale half to even.\n *\n * `COUNT(column)` counts NON-NULL values, which is what makes the empty and\n * all-null cases answer NULL rather than divide by zero: `SUM` of no non-null\n * rows is NULL, every operator below is null-strict, and the zero divisor is\n * therefore never reached with a non-null numerator.\n *\n * `AVG()` is deliberately unused. It is a double on SQLite, and on the other\n * two its result scale is the provider's choice rather than the field's.\n */\nexport const logicalDecimalAverage = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n sql`(SUM(${column}) * ${scaleFactorSql(descriptor.scale)})`,\n sql`COUNT(${column})`\n );\n return sql`(${coefficient} * ${scaleUnitSql(descriptor.scale)})`;\n};\n","import type { GeoPointSql } from \"@adapters/database-adapter\";\nimport { type Sql, sql } from \"@sql\";\nimport type {\n GeoBounds,\n GeoPolygon,\n} from \"@validation/primitives/geo-area-codec\";\n\ntype CoordinateOperations = {\n readonly and: (...conditions: Sql[]) => Sql;\n readonly or: (...conditions: Sql[]) => Sql;\n readonly eq: (left: Sql, right: Sql) => Sql;\n readonly gte: (left: Sql, right: Sql) => Sql;\n readonly lte: (left: Sql, right: Sql) => Sql;\n};\n\ntype IndexableBounds = (point: Sql, bounds: GeoBounds) => Sql | undefined;\n\n/**\n * Coordinate equality and inclusive bounds are one logical contract on every\n * provider. Only coordinate extraction differs, so this is their single owner.\n */\nexport function createGeoPointCoordinatePredicates(\n longitude: GeoPointSql[\"longitude\"],\n latitude: GeoPointSql[\"latitude\"],\n operators: CoordinateOperations,\n indexableBounds?: IndexableBounds\n): Pick<GeoPointSql, \"equals\" | \"withinBounds\"> {\n return {\n equals(point, expected) {\n const pointLongitude = longitude(point);\n let longitudeCondition = operators.eq(\n pointLongitude,\n sql`${expected.longitude}`\n );\n // -180 and +180 are one canonical meridian. Storage written outside the\n // ORM may still contain the physical -180 spelling that the value codec\n // presents as +180.\n if (expected.longitude === 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n return operators.and(\n longitudeCondition,\n operators.eq(latitude(point), sql`${expected.latitude}`)\n );\n },\n withinBounds(point, bounds) {\n const pointLongitude = longitude(point);\n const latitudeCondition = operators.and(\n operators.gte(latitude(point), sql`${bounds.south}`),\n operators.lte(latitude(point), sql`${bounds.north}`)\n );\n\n let exactCondition: Sql;\n if (bounds.west === -180 && bounds.east === 180) {\n exactCondition = latitudeCondition;\n } else {\n const westArm = operators.gte(pointLongitude, sql`${bounds.west}`);\n const eastArm = operators.lte(pointLongitude, sql`${bounds.east}`);\n let longitudeCondition =\n bounds.west > bounds.east\n ? operators.or(westArm, eastArm)\n : operators.and(westArm, eastArm);\n\n // GeoPoint canonicalizes -180 to +180. A normal interval whose western\n // boundary is -180 still contains that one physical meridian.\n if (bounds.west === -180 && bounds.east < 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${180}`)\n );\n }\n // The inverse endpoint is the same canonical meridian: an external\n // writer may have stored -180 while the logical interval ends at +180.\n if (bounds.east === 180 && bounds.west > -180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n exactCondition = operators.and(latitudeCondition, longitudeCondition);\n }\n const indexCondition = indexableBounds?.(point, bounds);\n return indexCondition\n ? operators.and(indexCondition, exactCondition)\n : exactCondition;\n },\n };\n}\n\n/**\n * GeoJSON rectangles safe to use only as conservative spatial-index probes.\n * Empty means the exact coordinate predicate is the only portable shape for\n * this boundary (world, pole, zero-area, or the canonical -180 meridian case).\n */\nexport function geoBoundsIndexPolygons(bounds: GeoBounds): readonly string[] {\n if (\n bounds.south === -90 ||\n bounds.north === 90 ||\n bounds.south === bounds.north ||\n bounds.west === bounds.east ||\n bounds.west > bounds.east ||\n bounds.west === -180 ||\n bounds.east === 180\n ) {\n return [];\n }\n return [\n boundsPolygonJson(bounds.west, bounds.east, bounds.south, bounds.north),\n ];\n}\n\nfunction boundsPolygonJson(\n west: number,\n east: number,\n south: number,\n north: number\n): string {\n // Geography edges are great-circle arcs. Include every axis meridian so\n // their geocentric bounding box encloses the full coordinate rectangle.\n const meridians = [\n west,\n ...[-90, 0, 90].filter((x) => west < x && x < east),\n east,\n ];\n const southEdge = meridians.map((longitude) => [longitude, south]);\n const northEdge = [...meridians]\n .reverse()\n .map((longitude) => [longitude, north]);\n return JSON.stringify({\n type: \"Polygon\",\n coordinates: [[...southEdge, ...northEdge, southEdge[0]]],\n });\n}\n\n/** One bound GeoJSON document; callers never contribute SQL or WKT text. */\nexport function geoPolygonJson(polygon: GeoPolygon): string {\n const rings: number[][][] = [closedRing(polygon.outer)];\n if (polygon.holes) {\n for (const hole of polygon.holes) rings.push(closedRing(hole));\n }\n return JSON.stringify({ type: \"Polygon\", coordinates: rings });\n}\n\nfunction closedRing(ring: GeoPolygon[\"outer\"]): number[][] {\n const result = new Array<number[]>(ring.length + 1);\n for (let index = 0; index < ring.length; index += 1) {\n const point = ring[index]!;\n result[index] = [point.longitude, point.latitude];\n }\n const first = ring[0]!;\n result[ring.length] = [first.longitude, first.latitude];\n return result;\n}\n","import { type Sql, sql } from \"@sql\";\nimport type { QueryParts } from \"../adapter-query-parts\";\n\ninterface SelectAssemblyOptions {\n forUpdate: \"append\" | \"omit\";\n /** LIMIT value meaning \"no limit\", for dialects that reject OFFSET without LIMIT */\n noLimitValue?: Sql;\n}\n\nexport const assembleSelectQuery = (\n selectClause: Sql,\n parts: QueryParts,\n options: SelectAssemblyOptions\n): Sql => {\n const fragments: Sql[] = [selectClause, sql`FROM ${parts.from}`];\n\n appendSelectParts(fragments, parts, options);\n\n if (options.forUpdate === \"append\" && parts.forUpdate) {\n fragments.push(sql.raw`FOR UPDATE`);\n }\n\n return sql.join(fragments, \" \");\n};\n\nconst appendSelectParts = (\n fragments: Sql[],\n parts: QueryParts,\n options: SelectAssemblyOptions\n): void => {\n if (parts.joins && parts.joins.length > 0) {\n fragments.push(...parts.joins);\n }\n\n if (parts.where) {\n fragments.push(sql`WHERE ${parts.where}`);\n }\n\n if (parts.groupBy) {\n fragments.push(sql`GROUP BY ${parts.groupBy}`);\n }\n\n if (parts.having) {\n fragments.push(sql`HAVING ${parts.having}`);\n }\n\n if (parts.orderBy) {\n fragments.push(sql`ORDER BY ${parts.orderBy}`);\n }\n\n appendLimitOffset(fragments, parts.limit, parts.offset, options.noLimitValue);\n};\n\nconst appendLimitOffset = (\n fragments: Sql[],\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n fragments.push(sql`LIMIT ${limit}`);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n fragments.push(sql`LIMIT ${noLimitValue}`);\n }\n\n if (offset) {\n fragments.push(sql`OFFSET ${offset}`);\n }\n};\n\n/**\n * Simulate `SELECT DISTINCT ON` using ROW_NUMBER() window functions.\n *\n * Used by MySQL/SQLite (no DISTINCT ON support) and by PostgreSQL when an\n * ORDER BY is present: DISTINCT ON would require the ORDER BY to lead with\n * the distinct columns, which changes result ordering. This emulation keeps\n * Prisma semantics — rows are ordered by the user's ORDER BY, then the first\n * row of each distinct group is kept, preserving that order.\n *\n * Generates:\n * SELECT col1, col2, ... FROM (\n * SELECT columns,\n * ROW_NUMBER() OVER (PARTITION BY distinct_cols ORDER BY order_cols) AS _rn,\n * ROW_NUMBER() OVER (ORDER BY order_cols) AS _ord -- only when ORDER BY present\n * FROM table\n * WHERE ...\n * ) AS _distinct_subquery\n * WHERE _rn = 1\n * ORDER BY _ord\n * LIMIT ... OFFSET ...\n *\n * The outer ORDER BY uses the precomputed _ord rank because the user's\n * ORDER BY references inner table aliases (and relation-order joins) that\n * are out of scope outside the subquery.\n */\nexport const assembleDistinctOnEmulation = (\n parts: QueryParts,\n distinct: Sql,\n escapeIdentifier: (name: string) => Sql,\n noLimitValue?: Sql\n): Sql => {\n // ORDER BY for ROW_NUMBER() - use provided orderBy or default to distinct columns\n const rowNumberOrder = parts.distinctOrderBy ?? parts.orderBy ?? distinct;\n\n const selectColumns: Sql[] = [\n parts.columns,\n sql`ROW_NUMBER() OVER (PARTITION BY ${distinct} ORDER BY ${rowNumberOrder}) AS ${escapeIdentifier(\"_rn\")}`,\n ];\n\n if (parts.orderBy) {\n selectColumns.push(\n sql`ROW_NUMBER() OVER (ORDER BY ${parts.orderBy}) AS ${escapeIdentifier(\"_ord\")}`\n );\n }\n\n // Inner query with ROW_NUMBER()\n const innerFragments: Sql[] = [\n sql`SELECT ${sql.join(selectColumns, \", \")}`,\n sql`FROM ${parts.from}`,\n ];\n\n if (parts.joins && parts.joins.length > 0) {\n innerFragments.push(...parts.joins);\n }\n\n if (parts.where) {\n innerFragments.push(sql`WHERE ${parts.where}`);\n }\n\n if (parts.groupBy) {\n innerFragments.push(sql`GROUP BY ${parts.groupBy}`);\n }\n\n if (parts.having) {\n innerFragments.push(sql`HAVING ${parts.having}`);\n }\n\n const innerQuery = sql.join(innerFragments, \" \");\n\n // Build outer SELECT - use explicit column aliases to exclude _rn/_ord\n let outerSelect: Sql;\n if (parts.distinctColumnAliases && parts.distinctColumnAliases.length > 0) {\n const aliasColumns = parts.distinctColumnAliases.map((alias) =>\n escapeIdentifier(alias)\n );\n outerSelect = sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")}`;\n } else {\n // Fallback to SELECT * (includes _rn/_ord)\n outerSelect = sql`SELECT * FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")}`;\n }\n\n // Outer query that filters for first row of each partition\n const outerFragments: Sql[] = [\n outerSelect,\n sql`WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ];\n\n if (parts.orderBy) {\n outerFragments.push(sql`ORDER BY ${escapeIdentifier(\"_ord\")}`);\n }\n\n appendLimitOffset(outerFragments, parts.limit, parts.offset, noLimitValue);\n\n return sql.join(outerFragments, \" \");\n};\n"],"mappings":"gFAgOA,MAAa,wBACX,EACA,EACA,IACG,GAAM,CC1MX,SAAgB,gCACd,EACsB,CACtB,IAAM,UAAY,EAAmB,KAAsC,CACzE,OACA,gBAAiB,CAAE,MAAO,EAAW,WAAY,EAAM,CACxD,EACD,MAAO,CACL,WAAa,GAAc,SAAS,EAAW,EAAe,EAAU,CAAC,CACzE,QAAS,EAAW,IAClB,SAAS,EAAW,GAAG,EAAU,GAAG,EAAQ,MAAM,CACrD,CAIH,MAAa,EAAmD,CAC9D,YAAa,EAAW,KAAa,CACnC,KAAM,GAAG,EAAU,OACnB,gBAAiB,CACf,MAAO,EACP,QAAS,CAAC,GAAG,EAAQ,CACtB,CACF,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AAO,EAAiB,MAAM,GACzG,CAEG,EAAM,SACR,EAAc,KACZ,CAAG,+BAA+B,EAAM,QAAQ,OAAO,EAAiB,OAAO,GAChF,CAIH,IAAM,EAAwB,CAC5B,CAAG,UAAUA,EAAI,KAAK,EAAe,KAAK,GAC1C,CAAG,QAAQ,EAAM,OAClB,CAEG,EAAM,OAAS,EAAM,MAAM,OAAS,GACtC,EAAe,KAAK,GAAG,EAAM,MAAM,CAGjC,EAAM,OACR,EAAe,KAAK,CAAG,SAAS,EAAM,QAAQ,CAG5C,EAAM,SACR,EAAe,KAAK,CAAG,YAAY,EAAM,UAAU,CAGjD,EAAM,QACR,EAAe,KAAK,CAAG,UAAU,EAAM,SAAS,CAGlD,IAAM,EAAaA,EAAI,KAAK,EAAgB,IAAI,CAG5C,EACJ,GAAI,EAAM,uBAAyB,EAAM,sBAAsB,OAAS,EAAG,CACzE,IAAM,EAAe,EAAM,sBAAsB,IAAK,GACpD,EAAiB,EAAM,CACxB,CACD,EAAc,CAAG,UAAUA,EAAI,KAAK,EAAc,KAAK,CAAC,SAAS,EAAW,OAAO,EAAiB,qBAAqB,QAGzH,EAAc,CAAG,kBAAkB,EAAW,OAAO,EAAiB,qBAAqB,GAI7F,IAAM,EAAwB,CAC5B,EACA,CAAG,SAAS,EAAiB,MAAM,CAAC,MACrC,CAQD,OANI,EAAM,SACR,EAAe,KAAK,CAAG,YAAY,EAAiB,OAAO,GAAG,CAGhE,kBAAkB,EAAgB,EAAM,MAAO,EAAM,OAAQ,EAAa,CAEnEA,EAAI,KAAK,EAAgB,IAAI"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t,y as n}from"./validation-Du6j0Q38.mjs";import{o as r}from"./sql--69HUgel.mjs";import{r as i}from"./adapter-internals-n3Mf3css.mjs";import{O as a}from"./geo-point-codec-DUTTtlav.mjs";import{s as o,t as s}from"./identifiers-By-JRCb5.mjs";import{a as ee,t as c}from"./physical-BkelResN.mjs";import{t as l}from"./json-number-C10HFiy6.mjs";import{A as u,C as d,D as f,E as te,M as p,O as m,P as h,S as g,T as _,a as v,b as y,c as b,f as x,g as S,h as C,j as w,k as T,l as E,m as D,o as O,r as k,s as A,t as j,u as M,v as N,w as P,x as F,y as I}from"./batch-refs-BY51FIXm.mjs";import{f as L,g as R,h as z,n as B,o as V,p as H,r as U,t as W,u as G}from"./select-assembly-BgqlrePH.mjs";const K=s(`"`),q={quotient:(e,t)=>r`(${e} / ${t})`,remainder:(e,t)=>r`(${e} % ${t})`};function sqliteIntegerPrecision(e){let t=w(e);if(t<19)return t;if(!(t>19))return(e.startsWith(`-`)?e.slice(1)<=`9223372036854775808`:e<=`9223372036854775807`)?t:void 0}const J=r.raw(`1000000000000000000`),overflowCoefficient=e=>r.raw(`1${`0`.repeat(Math.min(e.precision,18))}`),guardedCoefficientAssignment=(e,t,n,i)=>r`${e} = CASE WHEN ${e} IS NULL OR ${t} THEN ${n} ELSE ${overflowCoefficient(i)} END`,Y=/^\d+$/,X=/["\\]/,jsonPathLeg=e=>{if(Y.test(e))return`$[${e}]`;if(X.test(e))throw Error(`SQLite JSON path segments containing " or \\ must be rejected by the portable query contract.`);return`$."${e}"`},jsonExtract=(e,t)=>{let n=r`${e} -> '$'`;for(let e of t){let t=jsonPathLeg(e);n=r`${n} -> ${t}`}return n},jsonExtractText=(e,t)=>{let n=[];for(let e of t){let t=jsonPathLeg(e);n.push(t)}let i=n.pop();if(i===void 0)return r`${e} ->> '$'`;let a=e;for(let e of n)a=r`${a} -> ${e}`;return r`${a} ->> ${i}`},jsonArrayConcat=(e,t)=>r`(CASE WHEN ${e} = '[]' THEN ${t} WHEN ${t} = '[]' THEN ${e} ELSE substr(${e}, 1, length(${e}) - 1) || ',' || substr(${t}, 2) END)`,sqliteJsonListValue=e=>r`${h(e)}`,Z={...T(),value:e=>{if(typeof e==`bigint`&&sqliteIntegerPrecision(String(e))===void 0)throw new t(`SQLite bigint values must fit signed 64-bit integers.`);return r`${e}`},true:()=>r.raw(`1`),false:()=>r.raw(`0`),json:e=>r`${JSON.stringify(e)}`,dateTime:(e,t)=>r`${o(e,c(t))}`,decimal:(e,t)=>r`CAST(${a(e,t,`coefficient`)} AS INTEGER)`,id:(e,t)=>r`${e}`},Q={...b(),like:(e,t)=>r`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>r`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>r`lower(${e}) LIKE lower(${t}) ESCAPE '\\'`,notIlike:(e,t)=>r`lower(${e}) NOT LIKE lower(${t}) ESCAPE '\\'`,containsText:(e,t)=>r`instr(${e}, ${t}) > 0`,startsWithText:(e,t)=>r`substr(${e}, 1, length(${t})) COLLATE BINARY = ${t}`,endsWithText:(e,t)=>r`substr(${e}, length(${e}) - length(${t}) + 1) COLLATE BINARY = ${t}`,startsWithPrefix:(e,t)=>r`${e} GLOB ${`${p(t)}*`}`,exactTextEq:(e,t)=>r`${e} COLLATE BINARY = ${t}`,exactTextIn:(e,t)=>r`${e} COLLATE BINARY IN ${t}`,...I(),...F(),...P(),...N(Z.true,Z.false),...D()},ne={...A(),asciiCaseFold:e=>r`lower(${e})`,caseSensitiveText:e=>r`${e} COLLATE BINARY`,concat:(...e)=>e.length===0?r.raw(`''`):e.length===1?e[0]:r`(${r.join(e,` || `)})`,greatest:(...e)=>r`MAX(${r.join(e,`, `)})`,least:(...e)=>r`MIN(${r.join(e,`, `)})`,integerDivide:(e,t)=>r`(${e} / CAST(${t} AS INTEGER))`,decimalCast:(e,t)=>r`CAST(${e} AS INTEGER)`,idCast:(e,t)=>t===`bytes`?r`unhex(${e})`:r`CAST(${e} AS TEXT)`,cast:O({text:`TEXT`,integer:`INTEGER`,bigint:`INTEGER`,boolean:`INTEGER`,numeric:`NUMERIC`}),blobToHex:e=>r`lower(hex(${e}))`},re={...v(),decimalAvg:(e,t)=>V(q,r`SUM(${e})`,r`COUNT(${e})`),decimalSumOperandPrecision:sqliteIntegerPrecision};function sqliteJsonEquals(e,t){let nodes=e=>r`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${e})`;return r`(CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(e)} EXCEPT ${nodes(t)}) AND NOT EXISTS (${nodes(t)} EXCEPT ${nodes(e)}) END)`}const ie={equals:sqliteJsonEquals,number:e=>r`CASE WHEN ${e} IS NULL THEN NULL ELSE printf(${r.raw(`'${l}'`)}, ${e}) END`,boolean:e=>r`json(CASE WHEN ${e} THEN 'true' ELSE 'false' END)`,document:e=>r`json(${e})`,object:e=>{if(e.length===0)return r.raw(`json_object()`);let t=e.flatMap(([e,t])=>[r`${e}`,t]);return r`json_object(${r.join(t,`, `)})`},array:e=>e.length===0?r.raw(`json_array()`):r`json_array(${r.join(e,`, `)})`,emptyArray:()=>r.raw(`json_array()`),agg:e=>r`COALESCE(json_group_array(json(${e})), json_array())`,objectFromColumns:e=>{if(e.length===0)return r.raw(`json_object()`);let t=e.flatMap(([e,t])=>[r`${e}`,t]);return r`json_object(${r.join(t,`, `)})`},extract:jsonExtract,extractText:jsonExtractText,numberAtPath:(e,t)=>r`(CASE WHEN json_type(${jsonExtract(e,t)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(e,t)} AS REAL) END)`,stringAtPath:(e,t)=>r`((CASE WHEN json_type(${jsonExtract(e,t)}) = 'text' THEN ${jsonExtractText(e,t)} END) COLLATE BINARY)`,contains:(e,t)=>r`(json_type(${e}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${t}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${e}) AS candidate WHERE ${sqliteJsonEquals(r`${e} -> candidate.fullkey`,r`${t} -> required.fullkey`)})))`,lastElement:e=>r`${e} -> '$[#-1]'`,value:e=>r`${h(e)}`},ae={literal:e=>e.length===0?r.raw(`json_array()`):r`json_array(${r.join(e,`, `)})`,value:sqliteJsonListValue,enumValue:sqliteJsonListValue,has:(e,t)=>r`EXISTS (SELECT 1 FROM json_each(${e}) WHERE value = ${t})`,hasEvery:(e,t)=>r`(SELECT COUNT(*) FROM json_each(${t}) WHERE value IN (SELECT value FROM json_each(${e}))) = json_array_length(${t})`,hasSome:(e,t)=>r`EXISTS (SELECT 1 FROM json_each(${e}) AS a, json_each(${t}) AS b WHERE a.value = b.value)`,isEmpty:e=>r`(json_array_length(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>r`CAST(${e} AS TEXT)`,length:e=>r`json_array_length(${e})`,get:(e,t)=>r`json_extract(${e}, '$[' || ${t} || ']')`,push:(e,t)=>r`json_insert(${e}, '$[#]', ${t})`,set:(e,t,n)=>r`json_set(${e}, '$[' || ${t} || ']', ${n})`},oe={...x(),nullsFirst:(e,t)=>t===`desc`?r`${e} DESC NULLS FIRST`:r`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?r`${e} DESC NULLS LAST`:r`${e} ASC NULLS LAST`},se={...g(),multiply:(e,t,n)=>{let i=n?.decimal;return i?guardedCoefficientAssignment(e,r`${t} = 0 OR ABS(${e}) <= ${J} / ABS(${t})`,V(q,r`(${e} * ${t})`,G(i.scale)),i):r`${e} = ${e} * ${t}`},divide:(e,t,n)=>{let i=n?.decimal;if(i){let n=G(i.scale);return guardedCoefficientAssignment(e,r`ABS(${e}) <= ${J} / ${n}`,V(q,L(r`(${e} * ${n})`,t),r`ABS(${t})`),i)}return n?.integer?r`${e} = ${e} / CAST(${t} AS INTEGER)`:r`${e} = ${e} / ${t}`},push:(e,t)=>r`${e} = ${jsonArrayConcat(r`json(COALESCE(${e}, '[]'))`,t)}`,unshift:(e,t)=>r`${e} = ${jsonArrayConcat(t,r`json(COALESCE(${e}, '[]'))`)}`},ce={skipDuplicatesStrategy:`sql`,insert:S(K),insertDefault:e=>r`INSERT INTO ${e} DEFAULT VALUES`,...y(),returning:e=>r`RETURNING ${e}`,...d()},le={exists:e=>r`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,notExists:e=>r`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`},ue={...E(),right:(e,t)=>{throw Error(`SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.`)},full:(e,t)=>{throw Error(`SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},lateral:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)},lateralLeft:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)}},de={supportsReturning:!0,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!1,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!1},fe={decimalRepresentation:`coefficient`,decimalListRepresentation:`coefficient`,dateTimeRepresentation:c,idRepresentation:(e,t)=>ee(e,t,`sqlite`)?.representation??`text`,parseResult:R,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()},pe=C(K),$=m(),me=te(),he=u(K),ge=M(K),_e=f(),ve=_();var SQLiteAdapter=class{constructor({temporaryObjects:e=!0}={}){H(this,this.geoPoint);let t,createBatchRefs=()=>this.#t(e);i(this,{get batchRefs(){return t??=createBatchRefs(),t},constraints:z,select:this.#e.select})}raw=ve;identifiers={...pe};literals={...Z};operators={...Q};expressions={...ne};aggregates={...re};json={...ie};arrays={...ae};orderBy={...oe};clauses={...$};set={...se};filters={...me};subqueries={...he};noLimitValue=r.raw(`-1`);#e={select:e=>e.distinct?W(e,e.distinct,this.identifiers.escape,this.noLimitValue):B(r`SELECT ${e.columns}`,e,{forUpdate:`omit`,noLimitValue:this.noLimitValue})};cte={...ge};mutations={...ce};assertions={...le};joins={...ue};setOperations={..._e};capabilities={...de};lastInsertId=()=>r.raw(`last_insert_rowid()`);#t(e){let t=r.raw(K(j)),n=r.raw(e?`CREATE TEMP TABLE IF NOT EXISTS`:`CREATE TABLE IF NOT EXISTS`);return k({table:t,batchIdColumn:r.raw(`"batch_id"`),keyColumn:r.raw(`"ref_key"`),valueColumn:r.raw(`"ref_value"`),createTable:r`${n} ${t} ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>r`CAST((${e}) AS TEXT)`,lastInsertId:()=>this.lastInsertId()})}vector=n;geoPoint=(()=>{let longitude=e=>this.json.numberAtPath(e,[`longitude`]),latitude=e=>this.json.numberAtPath(e,[`latitude`]);return{value:(e,t)=>r`json_object('longitude', ${this.json.document(this.json.number(e))}, 'latitude', ${this.json.document(this.json.number(t))})`,longitude,latitude,...U(longitude,latitude,this.operators)}})();result={...fe}};export{SQLiteAdapter as t};
2
- //# sourceMappingURL=sqlite-adapter-HqO3GpAK.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sqlite-adapter-HqO3GpAK.mjs","names":["sql","#createBatchRefs","#assemble"],"sources":["../src/adapters/databases/sqlite/sqlite-adapter.ts"],"sourcesContent":["import { UnsupportedOperationError, unsupportedVector } from \"@errors\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { sqliteConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport {\n BATCH_REFS_TABLE,\n createOnConflictBatchRefs,\n} from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport { createGeoPointCoordinatePredicates } 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 createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n decimalCoefficientPrecision,\n escapeGlobLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\nimport { SQLITE_BINARY64_FORMAT } from \"./storage/json-number\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n\n/**\n * Every SQLite decimal expression is signed-int64 integer arithmetic on the\n * stored unscaled coefficient, so `/` IS truncating integer division and `%`\n * carries the dividend's sign. Neither is true once an operand becomes REAL or\n * TEXT, which is why every operand below arrives as an INTEGER column, an\n * integer literal, or a `CAST(... AS INTEGER)` bind.\n */\nconst SQLITE_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`(${n} / ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`(${n} % ${d})`,\n};\n\nconst SQLITE_INT64_NEGATIVE_MAGNITUDE = \"9223372036854775808\";\nconst SQLITE_INT64_MAX = \"9223372036854775807\";\n\n/** Admit the exact TEXT-to-INTEGER cast domain, including its 19-digit edges. */\nfunction sqliteIntegerPrecision(coefficient: string): number | undefined {\n const precision = decimalCoefficientPrecision(coefficient);\n if (precision < 19) return precision;\n if (precision > 19) return undefined;\n const isAdmitted = coefficient.startsWith(\"-\")\n ? coefficient.slice(1) <= SQLITE_INT64_NEGATIVE_MAGNITUDE\n : coefficient <= SQLITE_INT64_MAX;\n return isAdmitted ? precision : undefined;\n}\n\n/**\n * The widest intermediate the guarded arms will evaluate: 10^18.\n *\n * SQLite does not raise on an integer multiply that overflows — it converts the\n * expression to REAL, which is the one representation an exact decimal must\n * never touch. So the arms are GUARDED: the guard compares magnitudes by\n * DIVISION (`|x| <= LIMIT / |y|`, exact for integers) instead of computing the\n * product it is protecting, and a `CASE` evaluates only the branch it selects.\n *\n * 10^18 is not arbitrary, and it is not independent. `precision + scale <= 18`\n * is SQLite's declared field limit (plan 3.1), ENFORCED once when the schema is\n * bound (`client/decimal-provider-limits.ts`), so every mathematically in-range\n * result has `|x * y| <= 10^(p+s) <= 10^18`: the guard never rejects an answer\n * that fits the field, and int64 keeps a factor of nine in reserve for the\n * `+/- 1` step and the `d - |r|` tie test.\n *\n * THE COUPLING IS LOAD-BEARING, in both directions. This constant is flat where\n * the per-descriptor bound would be `B = scale === 0 ? M : M*F + F/2 - 1`, and\n * that is only equivalent because no descriptor past `p + s = 18` can reach it:\n * a product in `(B, 10^18]` is admitted here and then refused by the range\n * CHECK instead of by the sentinel — the same loud, atomic failure by the other\n * mechanism. Remove the bind limit and the flat guard stops being a bound on\n * the FIELD at all, which is exactly what {@link overflowCoefficient} depends\n * on below.\n */\nconst SQLITE_INTERMEDIATE_LIMIT = sql.raw(\"1000000000000000000\");\n\n/**\n * The coefficient an unsafe or out-of-domain arithmetic result becomes: 10^p,\n * the smallest integer OUTSIDE a `precision: p` field's declared range.\n *\n * The DDL's range check refuses it, so the statement fails atomically and\n * nothing is written — which is the contract for an overflow that is only\n * knowable mid-statement.\n *\n * THE CLAMP DEPENDS ON THE BIND LIMIT, and is only correct because of it. At 19\n * digits and beyond, `10^p` is a REAL to SQLite's own parser, so the sentinel\n * would stop being an integer the CHECK can refuse — and `min(p, 18)` would put\n * it INSIDE the range of a `precision >= 19` column, which is a silently\n * written wrong value rather than a failure. No such column exists: plan 3.1's\n * `precision <= 18 && precision + scale <= 18` is proven once at schema bind\n * (`client/decimal-provider-limits.ts`), before any I/O, so `min(p, 18)` is\n * `p` for every descriptor that ever reaches here. The clamp is what an\n * unreachable arm does when it is reached anyway, not a policy — and it is why\n * the bind limit is load-bearing rather than ergonomic.\n */\nconst overflowCoefficient = (descriptor: DecimalDescriptor): Sql =>\n sql.raw(`1${\"0\".repeat(Math.min(descriptor.precision, 18))}`);\n\n/**\n * `column = <exact coefficient arithmetic>`, or the constraint-breaking\n * coefficient when the intermediate would leave int64.\n *\n * A NULL column is safe by definition and takes the guarded arm, where every\n * operator is null-strict and the assignment stays NULL.\n */\nconst guardedCoefficientAssignment = (\n column: Sql,\n safe: Sql,\n value: Sql,\n descriptor: DecimalDescriptor\n): Sql =>\n sql`${column} = CASE WHEN ${column} IS NULL OR ${safe} THEN ${value} ELSE ${overflowCoefficient(descriptor)} END`;\n\n/**\n * The physical form a SQLite datetime column holds, from what the field\n * declared — the ONE reading of that declaration, shared by the value lowering\n * below and the result promise this adapter publishes.\n *\n * SQLite has no temporal type, so `s.dateTime(SQLITE.DATETIME.…)` is a real\n * storage choice the DDL already honors: INTEGER holds epoch milliseconds and\n * REAL holds a Julian day, which are the two spellings SQLite's own date\n * functions read. Anything else — a declaration for another dialect, an\n * explicit TEXT, no declaration at all — is the timestamp text this adapter has\n * always stored.\n */\n\nconst JSON_ARRAY_INDEX_SEGMENT = /^\\d+$/;\nconst JSON_UNADDRESSABLE_LABEL = /[\"\\\\]/;\n\n// Each path segment binds as its own single-leg JSONPath ('$[N]' for\n// array indices, '$.\"seg\"' otherwise) chained with -> , so segments can\n// never splice extra legs into the path. SQLite's path grammar has no\n// escape syntax inside quoted labels, so the portable query contract rejects\n// keys containing \" or \\ before adapter execution. This throw is defensive.\nconst jsonPathLeg = (segment: string): string => {\n if (JSON_ARRAY_INDEX_SEGMENT.test(segment)) {\n return `$[${segment}]`;\n }\n if (JSON_UNADDRESSABLE_LABEL.test(segment)) {\n throw new Error(\n 'SQLite JSON path segments containing \" or \\\\ must be rejected by the portable query contract.'\n );\n }\n return `$.\"${segment}\"`;\n};\n\n/** Chain one bound `-> '$leg'` per path segment ('$' alone = document root). */\nconst jsonExtract = (column: Sql, path: string[]): Sql => {\n let expr = sql`${column} -> '$'`;\n for (const segment of path) {\n const leg = jsonPathLeg(segment);\n expr = sql`${expr} -> ${leg}`;\n }\n return expr;\n};\n\n/** Same chain, but the final leg uses `->>` so strings come back unquoted. */\nconst jsonExtractText = (column: Sql, path: string[]): Sql => {\n const legs: string[] = [];\n for (const segment of path) {\n const leg = jsonPathLeg(segment);\n legs.push(leg);\n }\n const last = legs.pop();\n if (last === undefined) {\n return sql`${column} ->> '$'`;\n }\n let expr: Sql = column;\n for (const leg of legs) {\n expr = sql`${expr} -> ${leg}`;\n }\n return sql`${expr} ->> ${last}`;\n};\n\n/**\n * Concatenate two JSON array texts by string surgery: strip `left`'s closing\n * bracket and `right`'s opening bracket. SQLite has no JSON array-concat\n * function, and json_insert('$[#]') can only append one element per pair.\n * Both sides must be canonical JSON (json() output or JSON.stringify).\n */\nconst jsonArrayConcat = (left: Sql, right: Sql): Sql =>\n sql`(CASE WHEN ${left} = '[]' THEN ${right} WHEN ${right} = '[]' THEN ${left} ELSE substr(${left}, 1, length(${left}) - 1) || ',' || substr(${right}, 2) END)`;\n\n/**\n * SQLite Database Adapter\n *\n * Implements the DatabaseAdapter interface for SQLite-specific SQL generation.\n *\n * Key SQLite features:\n * - Double-quote identifier escaping: \"table\".\"column\"\n * - No native ARRAY type - uses JSON for arrays\n * - Portable text predicates do not depend on SQLite's LIKE behavior\n * - json_object(), json_group_array() for JSON operations (SQLite 3.38+)\n * - RETURNING clause supported (SQLite 3.35+)\n * - No NULLS FIRST/LAST ordering\n * - ON CONFLICT DO UPDATE/NOTHING (same as PostgreSQL)\n * - || for string concatenation\n * - Boolean stored as 0/1 integers\n */\n/** The one JSON list container every SQLite list value crosses as. */\nconst sqliteJsonListValue = (values: unknown[]): Sql =>\n sql`${stringifyJson(values)}`;\n\n/** Facts a SQLite driver states about its transport. */\nexport interface SQLiteAdapterOptions {\n /**\n * Whether the transport admits temporary objects (`CREATE TEMP TABLE`).\n * better-sqlite3, libSQL and bun:sqlite do; Cloudflare D1's authorizer\n * rejects them with `SQLITE_AUTH`, and rejects the whole batch with them.\n * Defaults to `true`.\n */\n readonly temporaryObjects?: boolean;\n}\n\n/**\n * The dialect's stateless SQL builders, built once per module. Each adapter\n * takes its own shallow copy of every group, so a driver that overrides one\n * hook (`driver.adapter.result.parseField = …`) changes only its own adapter,\n * as before, while a driver per request no longer rebuilds every closure.\n */\nconst SQLITE_LITERALS = {\n ...createStandardLiterals(),\n\n value: (value: unknown): Sql => {\n if (\n typeof value === \"bigint\" &&\n sqliteIntegerPrecision(String(value)) === undefined\n )\n throw new UnsupportedOperationError(\n \"SQLite bigint values must fit signed 64-bit integers.\"\n );\n return sql`${value}`;\n },\n\n // SQLite uses 1/0 for booleans\n true: (): Sql => sql.raw(\"1\"),\n\n false: (): Sql => sql.raw(\"0\"),\n\n // SQLite requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n // SQLite has no temporal type, so the field's declaration is what the column\n // physically holds and the operand has to be the same kind of value: an ISO\n // string bound against an epoch-millisecond INTEGER matches no row and,\n // written, stores text the typed read then refuses. A TEXT-declared or\n // undeclared field keeps the ISO spelling byte for byte. The string is a\n // validated ISO timestamp — the ISO boundary owns that — and every\n // four-digit public instant round-trips through the Julian-day double.\n dateTime: (iso: string, nativeType?: NativeTypeDeclaration): Sql =>\n sql`${encodePhysicalDateTime(iso, sqliteDateTimePhysicalForm(nativeType))}`,\n\n // SQLite has no exact decimal type, so a decimal column stores the UNSCALED\n // INTEGER COEFFICIENT and an operand becomes that same coefficient. Integer\n // comparison is then exact numeric comparison, and ordering, aggregation\n // and arithmetic are exact for the same reason.\n //\n // The digits bind as TEXT and `CAST(... AS INTEGER)` reads them, rather than\n // riding a JavaScript number (which rounds above 2^53) or a bigint (which\n // D1 will not bind). SQLite's TEXT-to-INTEGER cast is a decimal integer\n // parse, not a float one.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"coefficient\")} AS INTEGER)`,\n\n // Every compact domain is a `BLOB` here and takes the payload's bytes as\n // the ordinary binary parameter a blob scalar already binds; a text-stored\n // domain takes the public string unchanged.\n id: (physical: string | Uint8Array, _representation: IdRepresentation): Sql =>\n sql`${physical}`,\n};\n\nconst SQLITE_OPERATORS = {\n // Comparison\n ...createComparisonOperators(),\n\n // Pattern matching\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`lower(${column}) LIKE lower(${pattern}) ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) NOT LIKE lower(${pattern}) ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`instr(${column}, ${value}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, 1, length(${value})) COLLATE BINARY = ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, length(${column}) - length(${value}) + 1) COLLATE BINARY = ${value}`,\n // GLOB, not LIKE — and this is the one place the \"portable escaped LIKE\"\n // premise of Decision 7.3 does not survive contact with SQLite. Both of\n // SQLite's LIKE-optimization preconditions fail here: an ESCAPE clause\n // disqualifies the optimization outright, and with `case_sensitive_like`\n // off (the default, and connection-global, so not ours to flip) the\n // optimization additionally wants a NOCASE-collated index, while `push()`\n // only ever creates BINARY ones. Measured on better-sqlite3, 20k rows,\n // plain index: `col LIKE ? ESCAPE '\\'` is a SCAN — exactly what the\n // `substr` spelling above already costs — AND it answers case-insensitively,\n // which would break the case-sensitivity contract this operator holds.\n //\n // GLOB has neither problem. It compares bytes, so it is case- and\n // accent-sensitive by construction (that is what `COLLATE BINARY` buys\n // above, so nothing is lost by dropping it), and it ranges on the ordinary\n // BINARY index: the same probe plans this as a covering index SEARCH over\n // 111 rows against a 20000-row SCAN. Its wildcards are `*`/`?`/`[`, and it\n // has no ESCAPE clause, so `escapeGlobLiteral` quotes them as classes.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`${column} GLOB ${`${escapeGlobLiteral(value)}*`}`,\n\n // `COLLATE BINARY` names a COLLATION, not a function of the column, and\n // SQLite's ordinary index is a BINARY index — so the case-sensitive\n // spelling is already the index-usable one and there is nothing to add.\n // Byte-identical to what shipped before §10.2.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`${column} COLLATE BINARY = ${value}`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`${column} COLLATE BINARY IN ${values}`,\n\n // Set membership\n ...createMembershipOperators(),\n\n // Null checks\n ...createNullOperators(),\n\n // Range\n ...createRangeOperators(),\n\n // Logical (vacuous cases use SQLite's 1/0 booleans)\n ...createLogicalOperators(SQLITE_LITERALS.true, SQLITE_LITERALS.false),\n\n // Subquery existence\n ...createExistenceOperators(),\n};\n\nconst SQLITE_EXPRESSIONS = {\n ...createCommonExpressions(),\n\n // SQLite lower() intentionally provides the portable ASCII-only contract.\n asciiCaseFold: (expr: Sql): Sql => sql`lower(${expr})`,\n caseSensitiveText: (expr: Sql): Sql => sql`${expr} COLLATE BINARY`,\n\n // String concatenation via ||\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 // SQLite has no GREATEST/LEAST; multi-arg MAX/MIN are the scalar forms\n greatest: (...exprs: Sql[]): Sql => sql`MAX(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`MIN(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm, and for the same\n // reason: SQLite drivers bind JS numbers as REAL, so `x / ?` would run real\n // division. Casting the divisor to INTEGER makes it native INT/INT\n // division, truncating toward zero.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`(${left} / CAST(${right} AS INTEGER))`,\n\n // A deferred SQLite decimal is already a captured coefficient. The\n // descriptor still travels through the common contract so no caller can\n // select this physical cast without naming the destination domain.\n decimalCast: (expr: Sql, _descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS INTEGER)`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`unhex(${expr})`\n : sql`CAST(${expr} AS TEXT)`,\n\n // SQLite type mappings\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"INTEGER\",\n boolean: \"INTEGER\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`lower(hex(${expr}))`,\n};\n\nconst SQLITE_AGGREGATES = {\n ...createAggregateFunctions(),\n\n // The average of a coefficient column IS the half-even integer quotient of\n // its exact sum by its non-null count: dividing both the sum and the count\n // of `logical x 10^s` values leaves `average x 10^s`, so no scale factor\n // appears at all. `COUNT(column)` is zero exactly when `SUM` is NULL, so\n // the null-strict operators answer NULL for an empty or all-null group and\n // the zero divisor is never reached with a value.\n decimalAvg: (column: Sql, _descriptor: DecimalDescriptor): Sql =>\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`SUM(${column})`,\n sql`COUNT(${column})`\n ),\n\n // A SQLite decimal aggregate is an int64 `SUM` over coefficients. Exact\n // operand admission follows the signed range rather than digit count: some\n // 19-digit values fit, while the next value past either endpoint would make\n // `CAST(... AS INTEGER)` saturate. SUM results are not capped here; SQLite\n // raises on actual overflow.\n decimalSumOperandPrecision: sqliteIntegerPrecision,\n};\n\n// Compare every node, including empty containers. Array indices remain part\n// of the path; object property insertion order does not. JSON numbers share\n// one domain, while booleans, strings and JSON null retain their distinct type.\nfunction sqliteJsonEquals(left: Sql, right: Sql): Sql {\n const nodes = (value: Sql) =>\n sql`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${value})`;\n return sql`(CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(left)} EXCEPT ${nodes(right)}) AND NOT EXISTS (${nodes(right)} EXCEPT ${nodes(left)}) END)`;\n}\n\nconst SQLITE_JSON = {\n equals: sqliteJsonEquals,\n number: (expression: Sql): Sql =>\n sql`CASE WHEN ${expression} IS NULL THEN NULL ELSE printf(${sql.raw(`'${SQLITE_BINARY64_FORMAT}'`)}, ${expression}) END`,\n boolean: (condition: Sql): Sql =>\n sql`json(CASE WHEN ${condition} THEN 'true' ELSE 'false' END)`,\n // SQLite drops the JSON subtype across scalar-subquery boundaries. Restore it\n // before embedding the value in json_object/json_array, or an object becomes a\n // quoted JSON string inside the outer document.\n document: (expression: Sql): Sql => sql`json(${expression})`,\n\n object: (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw(\"json_object()\");\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`json_object(${sql.join(args, \", \")})`;\n },\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw(\"json_array()\"),\n\n // Use json() to ensure the aggregated value is treated as JSON, not string\n // Without json(), json_group_array produces [\"{...}\"] instead of [{...}]\n agg: (expr: Sql): Sql =>\n sql`COALESCE(json_group_array(json(${expr})), json_array())`,\n\n objectFromColumns: (columns: [string, Sql][]): Sql => {\n if (columns.length === 0) return sql.raw(\"json_object()\");\n const args = columns.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`json_object(${sql.join(args, \", \")})`;\n },\n\n // `->` returns the value as canonical JSON text ('\"str\"', '2', 'null'),\n // the same format json.value binds, so extracted values compare with\n // plain equality (json_extract would return native SQL values instead)\n extract: jsonExtract,\n\n // `->>` returns text with strings unquoted, for LIKE matching\n extractText: jsonExtractText,\n\n // json_type reads the chained `->` result (canonical JSON text), so it\n // sees 'integer'/'real' only for real JSON numbers; every other shape —\n // and an absent path, where `->` is NULL — falls through to NULL\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN json_type(${jsonExtract(column, path)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(column, path)} AS REAL) END)`,\n\n // COLLATE BINARY is SQLite's default for these columns; naming it keeps\n // the code-point ordering contract explicit alongside PG's COLLATE \"C\"\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN json_type(${jsonExtract(column, path)}) = 'text' THEN ${jsonExtractText(column, path)} END) COLLATE BINARY)`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(json_type(${target}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${value}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${target}) AS candidate WHERE ${sqliteJsonEquals(sql`${target} -> candidate.fullkey`, sql`${value} -> required.fullkey`)})))`,\n\n lastElement: (target: Sql): Sql => sql`${target} -> '$[#-1]'`,\n\n value: (v: unknown): Sql => sql`${stringifyJson(v)}`,\n};\n\nconst SQLITE_ARRAYS = {\n // SQLite uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n value: sqliteJsonListValue,\n\n // Deliberately the same container, by identity: SQLite stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The `TEXT CHECK(col IN ...)`\n // describes one member.\n enumValue: sqliteJsonListValue,\n\n // Check if value exists in JSON array using json_each\n has: (column: Sql, value: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ${value})`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`(SELECT COUNT(*) FROM json_each(${values}) WHERE value IN (SELECT value FROM json_each(${column}))) = json_array_length(${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) AS a, json_each(${values}) AS b WHERE a.value = b.value)`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(json_array_length(${column}) = 0 OR ${column} IS NULL)`,\n\n // The column already stores the container as TEXT (its declared type is\n // TEXT, not JSON, precisely so the descriptor's CHECK can hold it). The\n // cast is what stops a JSON carrier from embedding it as a document and a\n // driver from handing back anything but the stored bytes.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS TEXT)`,\n\n length: (column: Sql): Sql => sql`json_array_length(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`json_extract(${column}, '$[' || ${index} || ']')`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`json_insert(${column}, '$[#]', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`json_set(${column}, '$[' || ${index} || ']', ${value})`,\n};\n\nconst SQLITE_ORDER_BY = {\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\nconst SQLITE_SET = {\n ...createNumericSetOperations(),\n\n // `x * y / 10^s` in coefficient space, rounded half to even. The guard is\n // the multiply's own: `x * y` is the only intermediate here that can leave\n // int64, and it does so exactly when the result cannot fit the field.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (!descriptor) return sql`${column} = ${column} * ${by}`;\n return guardedCoefficientAssignment(\n column,\n sql`${by} = 0 OR ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ABS(${by})`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`(${column} * ${by})`,\n scaleFactorSql(descriptor.scale)\n ),\n descriptor\n );\n },\n\n // `x * 10^s / y` in coefficient space, rounded half to even; the divisor's\n // sign moves onto the numerator so the rule always sees a positive divisor.\n // `y` is never zero — division by canonical zero is refused before I/O.\n //\n // SQLite drivers bind JS numbers as REAL, so `col / ?` runs real division\n // and would persist a fractional value into an INTEGER column. Casting the\n // divisor to INTEGER makes it native INT/INT division (truncating toward\n // zero, matching Postgres) for integer columns; real columns keep real\n // division since the column itself carries REAL affinity.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (descriptor) {\n const factor = scaleFactorSql(descriptor.scale);\n return guardedCoefficientAssignment(\n column,\n sql`ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ${factor}`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n signedNumerator(sql`(${column} * ${factor})`, by),\n sql`ABS(${by})`\n ),\n descriptor\n );\n }\n return target?.integer\n ? sql`${column} = ${column} / CAST(${by} AS INTEGER)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n sql`json(COALESCE(${column}, '[]'))`,\n values\n )}`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n values,\n sql`json(COALESCE(${column}, '[]'))`\n )}`,\n};\n\nconst SQLITE_MUTATIONS = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n // SQLite 3.35+ supports RETURNING\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n // SQLite uses same ON CONFLICT syntax as PostgreSQL (3.24+/3.35+)\n ...createOnConflictBuilders(),\n};\n\nconst SQLITE_ASSERTIONS = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n};\n\nconst SQLITE_JOINS = {\n ...createCoreJoins(),\n\n // SQLite doesn't support RIGHT JOIN (before 3.39, and driver support varies).\n // Never silently downgrade: emitting LEFT JOIN without swapping operands\n // returns wrong rows. The query engine never calls this today.\n right: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.\"\n );\n },\n\n // SQLite doesn't support FULL OUTER JOIN (before 3.39, and driver support varies).\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // SQLite does NOT support LATERAL joins\n // These methods should never be called - query engine should check capability first\n lateral: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n\n lateralLeft: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n};\n\nconst SQLITE_CAPABILITIES = {\n supportsReturning: true, // SQLite 3.35+\n // FALSE IN FACT, and it read `true` until the Phase 8 fold gave the flag its\n // first reader (query-performance-plan Phase 10.1). SQLite's `WITH` grammar\n // admits a SELECT and nothing else: measured on SQLite 3.51.2, each of\n // `WITH x AS (UPDATE …/INSERT …/DELETE … RETURNING …) SELECT * FROM x` is a\n // parse error (`near \"UPDATE\": syntax error`). Kept as a capability rather\n // than deleted because Phase 8's `WITH u AS (UPDATE … RETURNING *) SELECT …`\n // fold reads it to decide whether it may emit at all.\n supportsCteWithMutations: false,\n supportsFullOuterJoin: false,\n supportsLateralJoins: false, // SQLite does not support LATERAL joins\n supportsVector: false,\n supportsUpsertWhere: true, // SQLite supports WHERE in ON CONFLICT (3.24+)\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n // UPDATE/DELETE ... LIMIT needs SQLITE_ENABLE_UPDATE_DELETE_LIMIT, which is\n // off in the builds this project targets (better-sqlite3, libSQL, D1).\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n};\n\nconst SQLITE_RESULT: AdapterResultParser = {\n // SQLite has no exact decimal type: a decimal column IS its unscaled\n // integer coefficient, and every projection casts it to text before a\n // driver turns an int64 into a double. The result boundary cannot tell the\n // two vocabularies apart by inspection, so the promise is declared here.\n decimalRepresentation: \"coefficient\",\n\n // A decimal LIST is TEXT holding a JSON array of those same coefficients,\n // stated separately because the two facts are separate: a dialect can spell\n // its scalar decimals exactly and still have no exact decimal inside JSON.\n decimalListRepresentation: \"coefficient\",\n\n // The same reading the `dateTime` literal above lowers through, so a column\n // is read back in the vocabulary it was written in.\n dateTimeRepresentation: sqliteDateTimePhysicalForm,\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"sqlite\")?.representation ?? \"text\",\n\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n};\n\nconst SQLITE_IDENTIFIERS = createIdentifiers(quoteIdent);\n\nconst SQLITE_CLAUSES = createStandardClauses();\n\nconst SQLITE_FILTERS = createRelationFilters();\n\nconst SQLITE_SUBQUERIES = createSubqueries(quoteIdent);\n\nconst SQLITE_CTE = createCteBuilders(quoteIdent);\n\nconst SQLITE_SET_OPERATIONS = createSetOperations();\n\nconst SQLITE_RAW = createRawSql();\n\nexport class SQLiteAdapter implements DatabaseAdapter {\n constructor({ temporaryObjects = true }: SQLiteAdapterOptions = {}) {\n installGeoPointSql(this, this.geoPoint);\n // Only batches read the reference-table SQL, so it is built on first use.\n let batchRefs: BatchReferenceSqlAdapter | undefined;\n const createBatchRefs = () => this.#createBatchRefs(temporaryObjects);\n installAdapterInternals(this, {\n get batchRefs() {\n batchRefs ??= createBatchRefs();\n return batchRefs;\n },\n constraints: sqliteConstraintIdentities,\n select: this.#assemble.select,\n });\n }\n\n // ============================================================\n // RAW\n // ============================================================\n\n raw = SQLITE_RAW;\n\n // ============================================================\n // IDENTIFIERS\n // ============================================================\n\n identifiers = { ...SQLITE_IDENTIFIERS };\n\n // ============================================================\n // LITERALS\n // ============================================================\n\n literals = { ...SQLITE_LITERALS };\n\n // ============================================================\n // OPERATORS\n // ============================================================\n\n operators = { ...SQLITE_OPERATORS };\n\n // ============================================================\n // EXPRESSIONS\n // ============================================================\n\n expressions = { ...SQLITE_EXPRESSIONS };\n\n // ============================================================\n // AGGREGATES\n // ============================================================\n\n aggregates = { ...SQLITE_AGGREGATES };\n\n // ============================================================\n // JSON (SQLite 3.38+ JSON functions)\n // ============================================================\n\n json = { ...SQLITE_JSON };\n\n // ============================================================\n // ARRAYS (JSON-based for SQLite)\n // ============================================================\n\n arrays = { ...SQLITE_ARRAYS };\n\n // ============================================================\n // ORDER BY\n // ============================================================\n\n // SQLite parses NULLS FIRST/LAST natively since 3.30 (2019-10-04), which is\n // below this adapter's documented 3.35+ floor. The `(col IS NULL)` emulation\n // this replaces was an extra leading sort key, and an index can never supply\n // a sort key that is an expression: on a 100,000-row table with an index over\n // the sort columns, the emulated spelling planned `SCAN t | USE TEMP B-TREE\n // FOR ORDER BY` at 3.356 ms per page and the native one plans `SCAN t USING\n // INDEX` at 0.005 ms. MySQL keeps the emulation — it has no native syntax at\n // any version.\n orderBy = { ...SQLITE_ORDER_BY };\n\n // ============================================================\n // CLAUSES\n // ============================================================\n\n clauses = { ...SQLITE_CLAUSES };\n\n // ============================================================\n // SET (UPDATE operations)\n // ============================================================\n\n set = { ...SQLITE_SET };\n\n // ============================================================\n // FILTERS (Relation subquery wrappers)\n // ============================================================\n\n filters = { ...SQLITE_FILTERS };\n\n // ============================================================\n // SUBQUERIES\n // ============================================================\n\n subqueries = { ...SQLITE_SUBQUERIES };\n\n // ============================================================\n // ASSEMBLE (Build complete SQL statements)\n // ============================================================\n\n // SQLite has no bare OFFSET; LIMIT -1 means \"no limit\"\n noLimitValue = sql.raw(\"-1\");\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // SQLite doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n // SQLite uses database-level locking, so FOR UPDATE is a no-op\n // (ignoring parts.forUpdate intentionally)\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"omit\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // ============================================================\n // CTE (Common Table Expressions)\n // ============================================================\n\n cte = { ...SQLITE_CTE };\n\n // ============================================================\n // MUTATIONS\n // ============================================================\n\n mutations = { ...SQLITE_MUTATIONS };\n\n assertions = { ...SQLITE_ASSERTIONS };\n\n // ============================================================\n // JOINS\n // ============================================================\n\n joins = { ...SQLITE_JOINS };\n\n // ============================================================\n // SET OPERATIONS\n // ============================================================\n\n setOperations = { ...SQLITE_SET_OPERATIONS };\n\n // ============================================================\n // CAPABILITIES\n // ============================================================\n\n capabilities = { ...SQLITE_CAPABILITIES };\n\n lastInsertId = (): Sql => sql.raw(\"last_insert_rowid()\");\n\n // The scratch is a TEMP table wherever the transport admits one, so it never\n // enters the user's database file. Where it does not (D1), it is an ordinary\n // table in `main`: created once, kept, and EMPTY between batches — every\n // batch deletes the rows it stored, keyed by its own batch id, inside that\n // same batch, and a batch that fails rolls its rows back with it. The table\n // itself persists; SQLite migration introspection leaves it out of the\n // snapshot (`src/migrations/drivers/sqlite/introspect.ts`).\n #createBatchRefs(temporaryObjects: boolean): BatchReferenceSqlAdapter {\n const table = sql.raw(quoteIdent(BATCH_REFS_TABLE));\n const create = sql.raw(\n temporaryObjects\n ? \"CREATE TEMP TABLE IF NOT EXISTS\"\n : \"CREATE TABLE IF NOT EXISTS\"\n );\n return createOnConflictBatchRefs({\n table,\n batchIdColumn: sql.raw('\"batch_id\"'),\n keyColumn: sql.raw('\"ref_key\"'),\n valueColumn: sql.raw('\"ref_value\"'),\n createTable: sql`${create} ${table} (\"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 lastInsertId: () => this.lastInsertId(),\n });\n }\n\n // ============================================================\n // VECTOR (not natively supported in SQLite)\n // ============================================================\n\n vector = unsupportedVector;\n\n // ============================================================\n // GEOPOINT (canonical JSON text transport)\n // ============================================================\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"longitude\"]);\n const latitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"latitude\"]);\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`json_object('longitude', ${this.json.document(this.json.number(pointLongitude))}, 'latitude', ${this.json.document(this.json.number(pointLatitude))})`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators\n ),\n };\n })();\n\n // RESULT PARSING\n // SQLite-specific parsing is handled by the driver (SQLite3Driver.result)\n // Adapter just passes through to default parsing\n // ============================================================\n\n result: AdapterResultParser = { ...SQLITE_RESULT };\n}\n"],"mappings":"6tBAyEA,MAAM,EAAa,EAAuB,IAAI,CASxC,EAA0C,CAC9C,UAAW,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACnD,WAAY,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACrD,CAMD,SAAS,uBAAuB,EAAyC,CACvE,IAAM,EAAY,EAA4B,EAAY,CAC1D,GAAI,EAAY,GAAI,OAAO,EACvB,OAAY,IAIhB,OAHmB,EAAY,WAAW,IAAI,CAC1C,EAAY,MAAM,EAAE,EAAI,sBACxB,GAAe,uBACC,EAAY,IAAA,GA4BlC,MAAM,EAA4BA,EAAI,IAAI,sBAAsB,CAqB1D,oBAAuB,GAC3BA,EAAI,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,EAAW,UAAW,GAAG,CAAC,GAAG,CASzD,8BACJ,EACA,EACA,EACA,IAEA,CAAG,GAAG,EAAO,eAAe,EAAO,cAAc,EAAK,QAAQ,EAAM,QAAQ,oBAAoB,EAAW,CAAC,MAexG,EAA2B,QAC3B,EAA2B,QAO3B,YAAe,GAA4B,CAC/C,GAAI,EAAyB,KAAK,EAAQ,CACxC,MAAO,KAAK,EAAQ,GAEtB,GAAI,EAAyB,KAAK,EAAQ,CACxC,MAAU,MACR,gGACD,CAEH,MAAO,MAAM,EAAQ,IAIjB,aAAe,EAAa,IAAwB,CACxD,IAAI,EAAO,CAAG,GAAG,EAAO,SACxB,IAAK,IAAM,KAAW,EAAM,CAC1B,IAAM,EAAM,YAAY,EAAQ,CAChC,EAAO,CAAG,GAAG,EAAK,MAAM,IAE1B,OAAO,GAIH,iBAAmB,EAAa,IAAwB,CAC5D,IAAM,EAAiB,EAAE,CACzB,IAAK,IAAM,KAAW,EAAM,CAC1B,IAAM,EAA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AG,EACD,UACA,SACA,KAAK,UACN,CACF,IACC,CAOJ,OAA8B,CAAE,GAAG,GAAe"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./result-parsing-DRXC89ek.mjs";function isSQLiteBinaryValue(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}function sqliteBinaryToUint8Array(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function convertValueForSQLite(e){return e instanceof Date?e.toISOString():typeof e==`boolean`?e?1:0:e===void 0?null:e}function convertValuesForSQLite(e){return e.map(convertValueForSQLite)}const n={parseField:parseSQLiteField};function parseSQLiteField(e,n,r){if(n===`boolean`){let i=t(e);if(i!==void 0)return r(i,n)}return r(n===`json`&&typeof e==`string`?JSON.parse(e):e,n)}function normalizeSQLiteRawRows(e){return e.map(e=>{if(typeof e!=`object`||!e)return e;let t={...e};for(let e of Object.keys(t)){let n=Reflect.get(t,e);typeof n==`bigint`&&n>=BigInt(-(2**53-1))&&n<=BigInt(2**53-1)&&Reflect.set(t,e,Number(n))}return t})}export{parseSQLiteField as a,normalizeSQLiteRawRows as i,convertValuesForSQLite as n,sqliteBinaryToUint8Array as o,isSQLiteBinaryValue as r,n as s,convertValueForSQLite as t};
2
- //# sourceMappingURL=sqlite-utils-D26BFuJJ.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sqlite-utils-D26BFuJJ.mjs","names":[],"sources":["../src/drivers/shared/sqlite-utils.ts"],"sourcesContent":["/**\n * Shared SQLite Utilities\n *\n * Common result parser and parameter conversion for SQLite-based drivers.\n */\n\nimport { parseIntegerBoolean } from \"@adapters/shared/result-parsing\";\nimport type { DriverResultParser } from \"../driver\";\n\nexport type SQLiteBinaryValue = ArrayBuffer | ArrayBufferView;\n\nexport function isSQLiteBinaryValue(\n value: unknown\n): value is SQLiteBinaryValue {\n return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n}\n\nexport function sqliteBinaryToUint8Array(value: SQLiteBinaryValue): Uint8Array {\n if (value instanceof ArrayBuffer) {\n return new Uint8Array(value);\n }\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n}\n\n/**\n * Convert provider-neutral scalar values to SQLite values. Binary values stay\n * in their standard Web API form; each provider owns any narrower conversion.\n */\nexport function convertValueForSQLite(value: unknown): unknown {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value === undefined) return null;\n return value;\n}\n\nexport function convertValuesForSQLite(values: unknown[]): unknown[] {\n return values.map(convertValueForSQLite);\n}\n\n/**\n * Shared result parser for the SQLite drivers. It speaks about ROW VALUES only:\n * - Boolean integer parsing (0/1 -> false/true)\n * - `json` columns, which SQLite stores as TEXT\n *\n * It says nothing about a RESULT (Arnaud's D-35). A SQLite transport answers a\n * `count`/`exist` in the shape the engine's own projection asked for — the\n * engine aliases that column `_count` and reads `_count` back — so the meaning\n * of a count and an exists answer has one authority, the engine's decoder, and\n * this middleware has nothing to add at the result boundary. Recovering a count\n * from a provider that did NOT preserve the alias is a dialect fact, stated\n * once at the adapter seam by the provider that needs it (MySQL).\n */\nexport const sqliteResultParser: DriverResultParser = {\n parseField: parseSQLiteField,\n};\n\n/**\n * The shipped parser's own field hook. `sqliteResultParser` is one mutable\n * object every SQLite-family driver shares, so a driver that must recognise\n * the shipped parser compares against this definition, never against what the\n * shared object holds when its module loads. The shipped parser defines no\n * `parseRelation` or `parseResult`.\n */\nexport function parseSQLiteField(\n value: unknown,\n scalarType: string,\n next: (value: unknown, scalarType: string) => unknown\n): unknown {\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(value);\n if (parsed !== undefined) return next(parsed, scalarType);\n }\n // SQLite stores json as TEXT — decode here where we know the string is\n // serialized JSON (the default parser never sniffs json strings)\n if (scalarType === \"json\" && typeof value === \"string\") {\n return next(JSON.parse(value), scalarType);\n }\n return next(value, scalarType);\n}\n\n/** Raw INTEGER leaves retain exact values; only safe-range values become numbers. */\nexport function normalizeSQLiteRawRows<T>(rows: T[]): T[] {\n return rows.map((row) => {\n if (row === null || typeof row !== \"object\") return row;\n const normalized = { ...row };\n for (const key of Object.keys(normalized)) {\n const value: unknown = Reflect.get(normalized, key);\n if (\n typeof value === \"bigint\" &&\n value >= BigInt(Number.MIN_SAFE_INTEGER) &&\n value <= BigInt(Number.MAX_SAFE_INTEGER)\n )\n Reflect.set(normalized, key, Number(value));\n }\n return normalized;\n });\n}\n"],"mappings":"2FAWA,SAAgB,oBACd,EAC4B,CAC5B,OAAO,aAAiB,aAAe,YAAY,OAAO,EAAM,CAGlE,SAAgB,yBAAyB,EAAsC,CAI7E,OAHI,aAAiB,YACZ,IAAI,WAAW,EAAM,CAEvB,IAAI,WAAW,EAAM,OAAQ,EAAM,WAAY,EAAM,WAAW,CAOzE,SAAgB,sBAAsB,EAAyB,CAI7D,OAHI,aAAiB,KAAa,EAAM,aAAa,CACjD,OAAO,GAAU,UAAkB,EAAQ,EAAI,EAC/C,IAAU,IAAA,GAAkB,KACzB,EAGT,SAAgB,uBAAuB,EAA8B,CACnE,OAAO,EAAO,IAAI,sBAAsB,CAgB1C,MAAa,EAAyC,CACpD,WAAY,iBACb,CASD,SAAgB,iBACd,EACA,EACA,EACS,CACT,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,EAAoB,EAAM,CACzC,GAAI,IAAW,IAAA,GAAW,OAAO,EAAK,EAAQ,EAAW,CAO3D,OAFS,EADL,IAAe,QAAU,OAAO,GAAU,SAChC,KAAK,MAAM,EAAM,CAEnB,EAFqB,EAAW,CAM9C,SAAgB,uBAA0B,EAAgB,CACxD,OAAO,EAAK,IAAK,GAAQ,CACvB,GAAoB,OAAO,GAAQ,WAA/B,EAAyC,OAAO,EACpD,IAAM,EAAa,CAAE,GAAG,EAAK,CAC7B,IAAK,IAAM,KAAO,OAAO,KAAK,EAAW,CAAE,CACzC,IAAM,EAAiB,QAAQ,IAAI,EAAY,EAAI,CAEjD,OAAO,GAAU,UACjB,GAAS,OAAO,WAAwB,EACxC,GAAS,eAA+B,EAExC,QAAQ,IAAI,EAAY,EAAK,OAAO,EAAM,CAAC,CAE/C,OAAO,GACP"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"transaction-operation-BC7aua5V.mjs","names":[],"sources":["../src/query-engine/transaction-operation.ts"],"sourcesContent":["import type {\n AnyDriver,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport { InvalidTransactionInputError } from \"@errors\";\nimport type { ObservationCompletionFactsReader } from \"@extensions/observation\";\nimport type {\n QueryInterceptorExecutionControl,\n TransactionWriteOutcomes,\n WriteOutcomeNotifications,\n} from \"@extensions/query\";\nimport type { PreparedBatchOperation, PreparedQuery } from \"./types\";\n\n/** One shared owner table registered once by each genuine operation class. */\nexport interface TransactionOperationOwner<Owner extends object = object> {\n clientId(owner: Owner): symbol;\n scopeId(owner: Owner): symbol;\n model(owner: Owner): string;\n operation(owner: Owner): string;\n context(owner: Owner): QueryExecutionContext;\n requiresInterception(owner: Owner): boolean;\n prepareAdmission(owner: Owner, phase?: \"input\" | \"plan\"): void;\n stagePackageWriteOutcomes(\n owner: Owner,\n outcomes: TransactionWriteOutcomes\n ): void;\n startInterception(\n owner: Owner,\n child: (notifications?: WriteOutcomeNotifications) => Promise<unknown>,\n outcomes: TransactionWriteOutcomes,\n control: QueryInterceptorExecutionControl\n ): Promise<unknown>;\n executeCore(\n owner: Owner,\n driver: AnyDriver,\n notifications?: WriteOutcomeNotifications\n ): Promise<unknown>;\n isWrite(owner: Owner): boolean;\n hasObservation(owner: Owner): boolean;\n observe(\n owner: Owner,\n child: () => Promise<unknown>,\n readCompletionFacts?: ObservationCompletionFactsReader\n ): Promise<unknown>;\n reserveWith(owner: Owner, driver: AnyDriver): void;\n executeWith(owner: Owner, driver: AnyDriver): Promise<unknown>;\n prepare(owner: Owner, driver?: AnyDriver): PreparedQuery | undefined;\n prepareBatch(\n owner: Owner,\n driver?: AnyDriver\n ): Promise<PreparedBatchOperation<unknown> | undefined>;\n parseResult(owner: Owner, raw: QueryResult<unknown>): unknown;\n observeBatchPhase<Result>(\n owner: Owner,\n driver: AnyDriver,\n execute: () => Result | Promise<Result>\n ): Promise<Result>;\n}\n\n/** The private authority resolved only while coordinating an array. */\nexport type TransactionOperationCapability = object;\n\ninterface RegisteredTransactionOperationOwner {\n readonly resolve: TransactionOperationResolver;\n}\n\ntype TransactionOperationResolver = (\n value: object\n) => TransactionOperationOwner<TransactionOperationCapability> | undefined;\n\nconst transactionOperationOwners: RegisteredTransactionOperationOwner[] = [];\nconst transactionOperationOwnersByPrototype = new WeakMap<\n object,\n TransactionOperationOwner<TransactionOperationCapability>\n>();\n\n/** Resolve the one class owner after the capability passed admission. */\nexport function transactionOperationOwner(\n operation: TransactionOperationCapability\n): TransactionOperationOwner<TransactionOperationCapability> {\n const prototype = Object.getPrototypeOf(operation);\n const owner = transactionOperationOwnersByPrototype.get(prototype);\n if (owner === undefined) throw new InvalidTransactionInputError();\n return owner;\n}\n\n/** Register one class-owned array authority for its exact private brand. */\nexport function registerTransactionOperationOwner<Owner extends object>(\n prototype: object,\n authenticate: (value: object) => value is Owner,\n owner: TransactionOperationOwner<Owner>\n): void {\n const resolvedOwner: TransactionOperationOwner<TransactionOperationCapability> =\n owner;\n const resolve = (\n value: object\n ): TransactionOperationOwner<TransactionOperationCapability> | undefined =>\n authenticate(value) && Object.getPrototypeOf(value) === prototype\n ? resolvedOwner\n : undefined;\n const registration: RegisteredTransactionOperationOwner = Object.freeze({\n resolve,\n });\n transactionOperationOwners.push(registration);\n transactionOperationOwnersByPrototype.set(prototype, resolvedOwner);\n}\n\n/** Resolve one owner only for an object constructed by its registered class. */\nexport function readTransactionOperation(\n value: object\n): TransactionOperationOwner<TransactionOperationCapability> | undefined {\n for (const registration of transactionOperationOwners) {\n try {\n const owner = registration.resolve(value);\n if (owner !== undefined) return owner;\n } catch {\n // A hostile candidate cannot interrupt the remaining genuine owners.\n }\n }\n return undefined;\n}\n\n/** The static thenable accepted by internal transaction composition. */\nexport interface TransactionOperation<T> extends PromiseLike<T> {}\n"],"mappings":"2RAuEA,MAAM,EAAoE,EAAE,CACtE,EAAwC,IAAI,QAMlD,SAAgB,0BACd,EAC2D,CAC3D,IAAM,EAAY,OAAO,eAAe,EAAU,CAC5C,EAAQ,EAAsC,IAAI,EAAU,CAClE,GAAI,IAAU,IAAA,GAAW,MAAM,IAAI,EACnC,OAAO,EAIT,SAAgB,kCACd,EACA,EACA,EACM,CACN,IAAM,EACJ,EACI,QACJ,GAEA,EAAa,EAAM,EAAI,OAAO,eAAe,EAAM,GAAK,EACpD,EACA,IAAA,GACA,EAAoD,OAAO,OAAO,CACtE,QACD,CAAC,CACF,EAA2B,KAAK,EAAa,CAC7C,EAAsC,IAAI,EAAW,EAAc,CAIrE,SAAgB,yBACd,EACuE,CACvE,IAAK,IAAM,KAAgB,EACzB,GAAI,CACF,IAAM,EAAQ,EAAa,QAAQ,EAAM,CACzC,GAAI,IAAU,IAAA,GAAW,OAAO,OAC1B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"transaction-oskVwmsf.mjs","names":[],"sources":["../src/errors/transaction.ts"],"sourcesContent":["import { VibORMError, VibORMErrorCode, type VibORMErrorMeta } from \"./base\";\nimport type { DiagnosticDisclosure } from \"./diagnostics\";\n\n/**\n * Every code {@link TransactionError} can carry.\n *\n * A family, not a single literal: the driver error mapping raises the same class for a plain\n * failure, a timeout, lock contention, a deadlock and a serialization failure, and the retry policy reads the\n * code to tell them apart. `INVALID_TRANSACTION_INPUT` is in the union too — the transaction\n * OPTION refusals (`drivers/shared/transaction-options.ts`) raise it through this class, while\n * {@link InvalidTransactionInputError} owns the `$transaction([...])` array-form refusal.\n * Measured at the construction sites; the two are told apart by class, not by code.\n */\nexport type TransactionErrorCode =\n | typeof VibORMErrorCode.TRANSACTION_FAILED\n | typeof VibORMErrorCode.TRANSACTION_TIMEOUT\n | typeof VibORMErrorCode.DEADLOCK\n | typeof VibORMErrorCode.SERIALIZATION_FAILURE\n | typeof VibORMErrorCode.INVALID_TRANSACTION_INPUT\n | typeof VibORMErrorCode.TRANSACTION_CONTENTION;\n\n/**\n * Transaction errors\n */\nexport class TransactionError extends VibORMError {\n static override readonly diagnosticName = \"TransactionError\";\n\n /** Discriminant: one of {@link TransactionErrorCode}, never a code outside the family. */\n declare readonly code: TransactionErrorCode;\n\n constructor(\n message: string,\n options?: {\n cause?: Error | undefined;\n diagnostics?: DiagnosticDisclosure | undefined;\n meta?: VibORMErrorMeta | undefined;\n code?: TransactionErrorCode | undefined;\n }\n ) {\n super(\n message,\n options?.code ?? VibORMErrorCode.TRANSACTION_FAILED,\n options\n );\n }\n}\n\n/**\n * Invalid input passed to $transaction array mode\n */\nexport class InvalidTransactionInputError extends VibORMError {\n static override readonly diagnosticName = \"InvalidTransactionInputError\";\n\n /** Literal discriminant: this class always carries `INVALID_TRANSACTION_INPUT`. */\n declare readonly code: typeof VibORMErrorCode.INVALID_TRANSACTION_INPUT;\n\n constructor(options?: { meta?: VibORMErrorMeta }) {\n super(\n \"$transaction array must contain only pending operations from client methods\",\n VibORMErrorCode.INVALID_TRANSACTION_INPUT,\n options\n );\n }\n}\n"],"mappings":"wFAwBA,IAAa,iBAAb,cAAsC,CAAY,CAChD,OAAyB,eAAiB,mBAK1C,YACE,EACA,EAMA,CACA,MACE,EACA,GAAS,MAAQ,EAAgB,mBACjC,EACD,GAOQ,6BAAb,cAAkD,CAAY,CAC5D,OAAyB,eAAiB,+BAK1C,YAAY,EAAsC,CAChD,MACE,8EACA,EAAgB,0BAChB,EACD"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./transaction-oskVwmsf.mjs";function nestedTransactionDispatchError(e){return new t(`Driver "${e}" received nested provider state outside TransactionBoundDriver.`,{meta:{driver:e,method:`$transaction`}})}function unsupportedCallbackTransactionError(e){return new t(`Driver "${e}" does not support callback transactions.`,{meta:{driver:e,method:`$transaction(callback)`}})}var ProviderTransactionContractError=class extends t{};async function runProviderManagedTransaction(e){let t=0,n={status:`pending`},readCallbackOutcome=()=>n,r,i=!1,a=[],closeBeforeCallbackDrain=async()=>{i=!0;try{await e.close()}catch(e){a.push(e)}};try{await e.run(i=>{if(t++,t>1)throw new ProviderTransactionContractError(`Transaction provider invoked the transaction callback more than once.`);return r=(async()=>{try{let t=await e.callback(i);return e.phases?.readyToCommit(),n={status:`fulfilled`,value:t},t}catch(e){throw n={status:`rejected`,error:e},e}})(),r.catch(()=>void 0),r})}catch(t){let n=r!==void 0&&readCallbackOutcome().status===`pending`;r&&n&&(await closeBeforeCallbackDrain(),await r.catch(()=>void 0));let o=readCallbackOutcome();if(o.status===`rejected`&&!n&&t===o.error)throw t;let s=o.status===`rejected`?o.error:t,c=[];n&&c.push(new ProviderTransactionContractError(`Transaction provider settled before the transaction callback settled.`)),o.status===`rejected`&&t!==o.error&&c.push(...readTransactionCleanupFailures(t,o.error)),c.push(...a);let l=c.map(failureStep);return i||l.push(e.close),throwAfterCleanup(s,l)}let o=r!==void 0&&readCallbackOutcome().status===`pending`;r&&o&&(await closeBeforeCallbackDrain(),await r.catch(()=>void 0));let s=readCallbackOutcome(),c=[];if(t!==1&&c.push(new ProviderTransactionContractError(t===0?`Transaction provider completed without invoking the transaction callback.`:`Transaction provider invoked the transaction callback more than once.`)),o&&c.push(new ProviderTransactionContractError(`Transaction provider completed before the transaction callback settled.`)),s.status===`rejected`&&c.push(new ProviderTransactionContractError(`Transaction provider resolved after the transaction callback rejected.`)),c.length>0){let t=s.status===`rejected`?s.error:c.shift(),n=[...c.map(failureStep),...a.map(failureStep)];return i||n.push(e.close),throwAfterCleanup(t,n)}return s.status===`fulfilled`?(e.phases?.committed(),s.value):throwAfterCleanup(new ProviderTransactionContractError(`Transaction callback outcome was not recorded.`),[e.close])}async function runTransactionLifecycle(e){try{await e.begin()}catch(t){return throwAfterCleanup(t,e.close?[e.close]:[])}let t;try{t=await e.callback()}catch(t){let n=[e.rollback];return e.close&&n.push(e.close),throwAfterCleanup(t,n)}e.phases?.readyToCommit();try{await e.commit()}catch(t){let n=[e.rollback];return e.close&&n.push(e.close),throwAfterCleanup(t,n)}return e.phases?.committed(),e.close&&await e.close(),t}const runSavepoint=async(e,t)=>{let n=`sp_${crypto.randomUUID().replace(/-/g,``)}`;await e(`SAVEPOINT ${n}`);let r;try{r=await t()}catch(t){return throwAfterCleanup(t,[()=>e(`ROLLBACK TO SAVEPOINT ${n}`),()=>e(`RELEASE SAVEPOINT ${n}`)])}try{await e(`RELEASE SAVEPOINT ${n}`)}catch(t){return throwAfterCleanup(t,[()=>e(`ROLLBACK TO SAVEPOINT ${n}`),()=>e(`RELEASE SAVEPOINT ${n}`)])}return r};function createTransactionCleanupError(e,t){return AggregateError([e,...t],readFailureMessage(e),{cause:e})}function readTransactionCleanupFailures(e,t){try{return!(e instanceof AggregateError)||e.cause!==t?[e]:e.errors[0]===t?e.errors.slice(1):[e]}catch{return[e]}}async function throwAfterCleanup(e,t){let n=[];for(let e of t)try{await e()}catch(e){n.push(e)}throw n.length>0?createTransactionCleanupError(e,n):e}function failureStep(e){return()=>{throw e}}function readFailureMessage(e){try{return e instanceof Error&&typeof e.message==`string`?e.message:`Transaction failed`}catch{return`Transaction failed`}}export{runProviderManagedTransaction as a,unsupportedCallbackTransactionError as c,readTransactionCleanupFailures as i,createTransactionCleanupError as n,runSavepoint as o,nestedTransactionDispatchError as r,runTransactionLifecycle as s,ProviderTransactionContractError as t};
2
- //# sourceMappingURL=transactions-gjmrWN5W.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"transactions-gjmrWN5W.mjs","names":["providerSettledBeforeCallback","settledOutcome"],"sources":["../src/drivers/shared/transactions.ts"],"sourcesContent":["import { TransactionError } from \"@errors\";\nimport type { TransactionPhaseNotifications } from \"../execution-context\";\n\nexport function nestedTransactionDispatchError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" received nested provider state outside TransactionBoundDriver.`,\n { meta: { driver: driverName, method: \"$transaction\" } }\n );\n}\n\nexport function unsupportedCallbackTransactionError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" does not support callback transactions.`,\n { meta: { driver: driverName, method: \"$transaction(callback)\" } }\n );\n}\n\n// A broken provider lifecycle cannot prove whether its handle remains safe.\nexport class ProviderTransactionContractError extends TransactionError {}\n\ntype LifecycleStep = () => unknown | Promise<unknown>;\n\nexport interface TransactionLifecycle<T> {\n readonly begin: LifecycleStep;\n readonly callback: () => Promise<T>;\n readonly commit: LifecycleStep;\n readonly rollback: LifecycleStep;\n readonly close?: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\nexport interface ProviderManagedTransaction<T, TTransaction> {\n readonly run: (\n callback: (tx: TTransaction) => Promise<T>\n ) => Promise<unknown>;\n readonly callback: (tx: TTransaction) => Promise<T>;\n readonly close: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\ntype ProviderCallbackOutcome<T> =\n | { readonly status: \"pending\" }\n | { readonly status: \"fulfilled\"; readonly value: T }\n | { readonly error: unknown; readonly status: \"rejected\" };\n\n/** Close provider-owned transaction state when its own cleanup/finalization fails. */\nexport async function runProviderManagedTransaction<T, TTransaction>(\n lifecycle: ProviderManagedTransaction<T, TTransaction>\n): Promise<T> {\n let callbackCallCount = 0;\n let callbackOutcome: ProviderCallbackOutcome<T> = {\n status: \"pending\",\n };\n const readCallbackOutcome = (): ProviderCallbackOutcome<T> => callbackOutcome;\n let callbackPromise: Promise<T> | undefined;\n let closeAttempted = false;\n const capturedCloseFailures: unknown[] = [];\n const closeBeforeCallbackDrain = async () => {\n closeAttempted = true;\n try {\n await lifecycle.close();\n } catch (error) {\n capturedCloseFailures.push(error);\n }\n };\n try {\n await lifecycle.run((tx) => {\n callbackCallCount++;\n if (callbackCallCount > 1) {\n throw new ProviderTransactionContractError(\n \"Transaction provider invoked the transaction callback more than once.\"\n );\n }\n callbackPromise = (async () => {\n try {\n const value = await lifecycle.callback(tx);\n lifecycle.phases?.readyToCommit();\n callbackOutcome = { status: \"fulfilled\", value };\n return value;\n } catch (error) {\n callbackOutcome = { status: \"rejected\", error };\n throw error;\n }\n })();\n callbackPromise.catch(() => undefined);\n return callbackPromise;\n });\n } catch (error) {\n const providerSettledBeforeCallback =\n callbackPromise !== undefined &&\n readCallbackOutcome().status === \"pending\";\n if (callbackPromise && providerSettledBeforeCallback) {\n await closeBeforeCallbackDrain();\n await callbackPromise.catch(() => undefined);\n }\n const settledOutcome = readCallbackOutcome();\n if (\n settledOutcome.status === \"rejected\" &&\n !providerSettledBeforeCallback &&\n error === settledOutcome.error\n ) {\n throw error;\n }\n const primaryFailure =\n settledOutcome.status === \"rejected\" ? settledOutcome.error : error;\n const cleanupFailures: unknown[] = [];\n if (providerSettledBeforeCallback) {\n cleanupFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider settled before the transaction callback settled.\"\n )\n );\n }\n if (\n settledOutcome.status === \"rejected\" &&\n error !== settledOutcome.error\n ) {\n cleanupFailures.push(\n ...readTransactionCleanupFailures(error, settledOutcome.error)\n );\n }\n cleanupFailures.push(...capturedCloseFailures);\n const cleanupSteps = cleanupFailures.map(failureStep);\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n const providerSettledBeforeCallback =\n callbackPromise !== undefined && readCallbackOutcome().status === \"pending\";\n if (callbackPromise && providerSettledBeforeCallback) {\n await closeBeforeCallbackDrain();\n await callbackPromise.catch(() => undefined);\n }\n const settledOutcome = readCallbackOutcome();\n const contractFailures: TransactionError[] = [];\n if (callbackCallCount !== 1) {\n contractFailures.push(\n new ProviderTransactionContractError(\n callbackCallCount === 0\n ? \"Transaction provider completed without invoking the transaction callback.\"\n : \"Transaction provider invoked the transaction callback more than once.\"\n )\n );\n }\n if (providerSettledBeforeCallback) {\n contractFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider completed before the transaction callback settled.\"\n )\n );\n }\n if (settledOutcome.status === \"rejected\") {\n contractFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider resolved after the transaction callback rejected.\"\n )\n );\n }\n if (contractFailures.length > 0) {\n const primaryFailure =\n settledOutcome.status === \"rejected\"\n ? settledOutcome.error\n : contractFailures.shift();\n const cleanupSteps = [\n ...contractFailures.map(failureStep),\n ...capturedCloseFailures.map(failureStep),\n ];\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n if (settledOutcome.status !== \"fulfilled\") {\n return throwAfterCleanup(\n new ProviderTransactionContractError(\n \"Transaction callback outcome was not recorded.\"\n ),\n [lifecycle.close]\n );\n }\n lifecycle.phases?.committed();\n return settledOutcome.value;\n}\n\n/** Run a top-level provider transaction without losing cleanup failures. */\nexport async function runTransactionLifecycle<T>(\n lifecycle: TransactionLifecycle<T>\n): Promise<T> {\n try {\n await lifecycle.begin();\n } catch (error) {\n return throwAfterCleanup(error, lifecycle.close ? [lifecycle.close] : []);\n }\n\n let result: T;\n try {\n result = await lifecycle.callback();\n } catch (error) {\n const cleanup = [lifecycle.rollback];\n if (lifecycle.close) cleanup.push(lifecycle.close);\n return throwAfterCleanup(error, cleanup);\n }\n\n lifecycle.phases?.readyToCommit();\n\n try {\n await lifecycle.commit();\n } catch (error) {\n const cleanup = [lifecycle.rollback];\n if (lifecycle.close) cleanup.push(lifecycle.close);\n return throwAfterCleanup(error, cleanup);\n }\n\n lifecycle.phases?.committed();\n\n if (lifecycle.close) await lifecycle.close();\n return result;\n}\n\nexport const runSavepoint = async <T>(\n executeStatement: (statement: string) => unknown | Promise<unknown>,\n fn: () => Promise<T>\n): Promise<T> => {\n const savepointName = `sp_${crypto.randomUUID().replace(/-/g, \"\")}`;\n await executeStatement(`SAVEPOINT ${savepointName}`);\n\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n return throwAfterCleanup(error, [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ]);\n }\n\n try {\n await executeStatement(`RELEASE SAVEPOINT ${savepointName}`);\n } catch (error) {\n return throwAfterCleanup(error, [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ]);\n }\n return result;\n};\n\nexport function createTransactionCleanupError(\n primaryFailure: unknown,\n cleanupFailures: readonly unknown[]\n): AggregateError {\n return new AggregateError(\n [primaryFailure, ...cleanupFailures],\n readFailureMessage(primaryFailure),\n { cause: primaryFailure }\n );\n}\n\nexport function readTransactionCleanupFailures(\n error: unknown,\n primaryFailure: unknown\n): readonly unknown[] {\n try {\n if (!(error instanceof AggregateError) || error.cause !== primaryFailure) {\n return [error];\n }\n return error.errors[0] === primaryFailure ? error.errors.slice(1) : [error];\n } catch {\n return [error];\n }\n}\n\nasync function throwAfterCleanup(\n primaryFailure: unknown,\n cleanupSteps: readonly LifecycleStep[]\n): Promise<never> {\n const cleanupFailures: unknown[] = [];\n for (const cleanupStep of cleanupSteps) {\n try {\n await cleanupStep();\n } catch (error) {\n cleanupFailures.push(error);\n }\n }\n\n if (cleanupFailures.length > 0) {\n throw createTransactionCleanupError(primaryFailure, cleanupFailures);\n }\n throw primaryFailure;\n}\n\nfunction failureStep(failure: unknown): LifecycleStep {\n return () => {\n throw failure;\n };\n}\n\nfunction readFailureMessage(error: unknown): string {\n try {\n return error instanceof Error && typeof error.message === \"string\"\n ? error.message\n : \"Transaction failed\";\n } catch {\n return \"Transaction failed\";\n }\n}\n"],"mappings":"wFAGA,SAAgB,+BACd,EACkB,CAClB,OAAO,IAAI,EACT,WAAW,EAAW,kEACtB,CAAE,KAAM,CAAE,OAAQ,EAAY,OAAQ,eAAgB,CAAE,CACzD,CAGH,SAAgB,oCACd,EACkB,CAClB,OAAO,IAAI,EACT,WAAW,EAAW,2CACtB,CAAE,KAAM,CAAE,OAAQ,EAAY,OAAQ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SACtD,EAAM,QACN,0BACE,CACN,MAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils-DfztpPvR.mjs","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["/**\n * CLI Utilities\n *\n * Configuration loading and other CLI utilities.\n *\n * Config file pattern similar to:\n * - drizzle.config.ts\n * - prisma (uses schema.prisma but we use TS)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { createJiti } from \"jiti\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport { isVibORMError } from \"../errors\";\nimport type { MigrationClient } from \"../migrations/push/planner\";\nimport type { MigrationStorageWriter } from \"../migrations/storage/contract\";\nimport type { ResolveCallback } from \"../migrations/types\";\nimport type { AnyModel } from \"../schema/model\";\nimport { validateSchemaOrThrow } from \"../schema/validation\";\n\n// =============================================================================\n// CONFIG TYPES\n// =============================================================================\n\n/**\n * Migration configuration options.\n */\nexport interface MigrationConfig {\n /** Estate directory (default: \"./migrations\") */\n dir?: string;\n /** Immutable exact physical table scope; include junctions and rename destinations. */\n tables?: readonly string[];\n /** Explicit rename, destructive-change and enum-value decisions for CLI planning. */\n resolve?: ResolveCallback;\n /**\n * Estate storage writer. Defaults to filesystem storage at `dir`.\n *\n * @example\n * ```ts\n * import { createFsStorageWriter } from \"viborm/migrations\";\n *\n * migrations: {\n * storage: createFsStorageWriter(\"./migrations\"),\n * }\n * ```\n */\n storage?: MigrationStorageWriter;\n}\n\n/**\n * VibORM configuration file format.\n *\n * Example viborm.config.ts:\n * ```ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport interface VibORMConfig {\n /** VibORM client instance */\n client: MigrationClient & { $disconnect(): Promise<void> };\n /** Optional: Migration configuration */\n migrations?: MigrationConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Path to config file (default: ./viborm.config.ts) */\n config?: string;\n /** Leave validation to the caller (`viborm check` reports every issue). */\n skipValidation?: boolean;\n}\n\nexport interface LoadedConfig {\n client: VibORMConfig[\"client\"];\n driver: AnyDriver;\n models: Record<string, AnyModel>;\n migrations?: MigrationConfig;\n}\n\n// =============================================================================\n// CONFIG FILE DISCOVERY\n// =============================================================================\n\nconst CONFIG_FILES = [\n \"viborm.config.ts\",\n \"viborm.config.mts\",\n \"viborm.config.js\",\n \"viborm.config.mjs\",\n];\n\n/**\n * Finds the first existing file from a list of candidates.\n */\nfunction findFile(cwd: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n// =============================================================================\n// CONFIG LOADING\n// =============================================================================\n\n/**\n * Loads VibORM configuration from viborm.config.ts file.\n *\n * The config file should export a default configuration object with:\n * - client: VibORM client instance created with createClient()\n */\nexport function failCli(error: unknown, json = false): never {\n const trusted = isVibORMError(error);\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"CLI operation failed\";\n const code = trusted ? error.code : undefined;\n const exitCode = code?.startsWith(\"V11\")\n ? Number(code.slice(1)) - 11_000 + 10\n : trusted\n ? 2\n : 1;\n process.stderr.write(\n json\n ? `${JSON.stringify({ error: trusted ? error.toJSON() : { name: error instanceof Error ? error.name : \"Error\", message }, exitCode })}\\n`\n : `${code ? `[${code}] ` : \"\"}${message}\\n`\n );\n process.exit(exitCode);\n}\n\n/** Await owned CLI cleanup before reporting either the primary or cleanup failure. */\nexport async function finishCli(\n client: { $disconnect(): Promise<void> } | undefined,\n failure: { value: unknown } | undefined,\n json = false\n): Promise<void> {\n let outcome = failure;\n try {\n await client?.$disconnect();\n } catch (cleanup) {\n outcome = {\n value: failure ? withSuppressedFailure(failure.value, cleanup) : cleanup,\n };\n }\n if (outcome) {\n if (json) failCli(outcome.value, true);\n else failCli(outcome.value);\n }\n}\n\nexport async function loadConfig(\n options: LoadConfigOptions = {}\n): Promise<LoadedConfig> {\n const cwd = process.cwd();\n const envPath = resolve(cwd, \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n\n // Find config file\n const configPath = options.config\n ? resolve(cwd, options.config)\n : findFile(cwd, CONFIG_FILES);\n\n if (!(configPath && existsSync(configPath))) {\n const searchedPaths = options.config ? [options.config] : CONFIG_FILES;\n\n throw new Error(\n \"Could not find VibORM configuration file.\\n\\n\" +\n `Searched for:\\n${searchedPaths.map((f) => ` - ${f}`).join(\"\\n\")}\\n\\n` +\n \"Create a viborm.config.ts file:\\n\\n\" +\n ` import { defineConfig } from \"viborm/config\";\\n` +\n ` import { client } from \"./src/db\";\\n\\n` +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n // Load the config file\n const configModule = await loadCliModule<\n VibORMConfig & { default?: VibORMConfig; config?: VibORMConfig }\n >(configPath);\n\n // Extract config (handle both default export and named export)\n const config: VibORMConfig =\n (Object.hasOwn(configModule, \"default\") && configModule.default) ||\n configModule.config ||\n configModule;\n\n // Validate client\n if (!config.client) {\n throw new Error(\n `Missing \"client\" in ${configPath}.\\n\\n` +\n \"Your config should include a VibORM client:\\n\\n\" +\n ` import { createClient } from \"viborm\";\\n` +\n \" const client = createClient({ driver, schema });\\n\\n\" +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n if (!isValidClient(config.client)) {\n throw new Error(\n `Invalid \"client\" in ${configPath}.\\n\\n` +\n \"The client must be created with createClient().\\n\"\n );\n }\n\n // Extract driver and schema from client\n const driver = config.client.$driver;\n const schemaInput = config.client.$schema;\n\n // Extract models from schema (filter out non-model exports)\n const models = extractModels(schemaInput);\n\n if (Object.keys(models).length === 0) {\n throw new Error(\n `No models found in client schema from ${configPath}.\\n\\n` +\n \"Make sure your client was created with schema models:\\n\\n\" +\n \" // src/schema.ts\\n\" +\n ` import { s } from \"viborm\";\\n\\n` +\n \" export const user = s.model({\\n\" +\n \" id: s.string().id(),\\n\" +\n \" name: s.string(),\\n\" +\n \" });\\n\"\n );\n }\n\n // Validate schema before proceeding\n if (!options.skipValidation) validateSchemaOrThrow(models);\n\n return {\n client: config.client,\n driver,\n models,\n migrations: config.migrations,\n };\n}\n\n/**\n * Dynamically imports a TypeScript/JavaScript module.\n */\nexport function loadCliModule<T>(filePath: string): Promise<T> {\n // Dependency imports need CJS interop; consumers select only authored defaults.\n return createJiti(filePath, {\n tsconfigPaths: true,\n interopDefault: true,\n }).import<T>(filePath);\n}\n\n/**\n * Extracts model objects from a module by checking for Model instances.\n */\nfunction extractModels(\n schema: Record<string, unknown>\n): Record<string, AnyModel> {\n const models: Record<string, AnyModel> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isModel(value)) {\n models[key] = value;\n }\n }\n\n return models;\n}\n\n/**\n * Checks if a value is a VibORM Model instance.\n */\nfunction isModel(value: unknown): value is AnyModel {\n if (value === null || typeof value !== \"object\") return false;\n const metadata = Reflect.get(value, \"~\");\n if (metadata === null || typeof metadata !== \"object\") return false;\n const state = Reflect.get(metadata, \"state\");\n // Model state exposes `scalars`/`relations` (never `fields`); the rest of\n // the codebase discriminates models the same way (see serializer).\n return state !== null && typeof state === \"object\" && \"scalars\" in state;\n}\n\n/**\n * Checks if a value is a valid VibORM client instance.\n */\nfunction isValidClient(value: unknown): boolean {\n // The client is a Proxy whose only trap is `get`, so `\"$driver\" in value`\n // (which triggers the `has` trap / falls back to the bare target) is always\n // false. Probe via property access instead.\n // `typeof null === \"object\"`, so null has to be refused here: Reflect.get\n // throws on it rather than answering undefined.\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return (\n Reflect.get(value, \"$driver\") !== undefined &&\n Reflect.get(value, \"$schema\") !== undefined\n );\n}\n\n// =============================================================================\n// DEFINE CONFIG HELPER\n// =============================================================================\n\n/**\n * Helper function for defining VibORM configuration with type safety.\n *\n * @example\n * ```ts\n * // viborm.config.ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport function defineConfig<const C extends VibORMConfig>(\n config: C &\n Record<Exclude<keyof C, keyof VibORMConfig>, never> &\n (C extends { migrations: infer M }\n ? {\n migrations: M &\n Record<Exclude<keyof M, keyof MigrationConfig>, never>;\n }\n : unknown)\n): C {\n return config;\n}\n"],"mappings":"qUA0FA,MAAM,EAAe,CACnB,mBACA,oBACA,mBACA,oBACD,CAKD,SAAS,SAAS,EAAa,EAAqC,CAClE,IAAK,IAAM,KAAa,EAAY,CAClC,IAAM,EAAW,EAAQ,EAAK,EAAU,CACxC,GAAI,EAAW,EAAS,CACtB,OAAO,EAGX,OAAO,KAaT,SAAgB,QAAQ,EAAgB,EAAO,GAAc,CAC3D,IAAM,EAAU,EAAc,EAAM,CAC9B,EACJ,aAAiB,MACb,EAAM,QACN,OAAO,GAAU,SACf,EACA,uBACF,EAAO,EAAU,EAAM,KAAO,IAAA,GAC9B,EAAW,GAAM,WAAW,MAAM,CACpC,OAAO,EAAK,MAAM,EAAE,CAAC,CAAG,KAAS,GACjC,EACE,EACA,EACN,QAAQ,OAAO,MACb,EACI,GAAG,KAAK,UAAU,CAAE,MAAO,EAAU,EAAM,QAAQ,CAAG,CAAE,KAAM,aAAiB,MAAQ,EAAM,KAAO,QAAS,UAAS,CAAE,WAAU,CAAC,CAAC,IACpI,GAAG,EAAO,IAAI,EAAK,IAAM,KAAK,EAAQ,IAC3C,CACD,QAAQ,KAAK,EAAS,CAIxB,eAAsB,UACpB,EACA,EACA,EAAO,GACQ,CACf,IAAI,EAAU,EACd,GAAI,CACF,MAAM,GAAQ,aAAa,OACpB,EAAS,CAChB,EAAU,CACR,MAAO,EAAU,EAAsB,EAAQ,MAAO,EAAQ,CAAG,EAClE,CAEC,IACE,EAAM,QAAQ,EAAQ,MAAO,GAAK,CACjC,QAAQ,EAAQ,MAAM,EAI/B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,OAAO,GAAU,WAAnC,EAA6C,MAAO,GACxD,IAAM,EAAW,QAAQ,IAAI,EAAO,IAAI,CACxC,GAAyB,OAAO,GAAa,WAAzC,EAAmD,MAAO,GAC9D,IAAM,EAAQ,QAAQ,IAAI,EAAU,QAAQ,CAG5C,OAAyB,OAAO,GAAU,YAAnC,GAA+C,YAAa,EAMrE,SAAS,cAAc,EAAyB,CAY9C,OALE,IAAU,MACT,OAAO,GAAU,UAAY,OAAO,GAAU,WAExC,GAGP,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,IAClC,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,GAsBtC,SAAgB,aACd,EAQG,CACH,OAAO"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,D as n,E as r,S as i,T as a,b as o,t as s,w as c,x as l}from"./validation-Du6j0Q38.mjs";import{g as u,m as ee,v as te,x as d,y as f}from"./terminal-BbRi0CNZ.mjs";import{o as ne,r as p}from"./sql--69HUgel.mjs";import{B as m,F as h,G as g,H as _,I as re,K as ie,R as v,U as y,V as b,W as x,a as S,d as C,f as w,i as ae,m as T,o as oe,p as E,q as D,r as se,xt as O,z as k}from"./geo-point-codec-DUTTtlav.mjs";function array(e){let t=e[`~standard`].validate,n=_(`array`,e=>ie(e,t));return n.item=e,n}const A=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected bigint`})])});function validateBigInt(e){return o(e)?x(e):A}function bigint(e){return b(`bigint`,validateBigInt,e)}const j=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Uint8Array`})])}),M=Object.getPrototypeOf(Uint8Array.prototype);function localBufferPrototype(){try{let e=Reflect.get(globalThis,`Buffer`);if(typeof e!=`function`)return;let t=Reflect.get(e,`prototype`);if(typeof t==`object`&&t&&Object.getPrototypeOf(t)===Uint8Array.prototype)return t}catch{return}}const N=localBufferPrototype();function hasOwnViewMetadata(e){return Object.getOwnPropertyDescriptor(e,`buffer`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteOffset`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteLength`)!==void 0}function hasTrustedLocalPrototype(e){let t=Object.getPrototypeOf(e);return(t===Uint8Array.prototype||t===N)&&!hasOwnViewMetadata(e)}function validateBlob(e){try{if(!n(e))return j;let t=Reflect.get(M,`buffer`,e),r=Reflect.get(M,`byteOffset`,e),i=Reflect.get(M,`byteLength`,e),a=hasTrustedLocalPrototype(e),o=new Uint8Array(t,r,i);return x(a?e:o)}catch{return j}}function blob(e){return b(`blob`,validateBlob,e)}const P=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected boolean`})])});function validateBoolean(e){return l(e)?x(e):P}function boolean(e){return b(`boolean`,validateBoolean,e)}const F=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Date`})])}),I=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected valid Date`})])});function validateDate(e){if(!i(e))return F;let t=Date.prototype.getTime.call(e);return Number.isNaN(t)?I:e instanceof Date?x(e):x(new Date(t))}function date(e){return b(`date`,validateDate,e)}const L=Object.freeze({issues:Object.freeze([Object.freeze({message:re})])});function validateDecimal(e){let t=v(e);return t===void 0?L:x(t)}function buildDecimalValueValidator(e){let t=e?.schema,n=e?.decimal,validate=validateDecimal;if(t!==void 0){let e=t[`~standard`].validate,n=validate;validate=t=>{let r=n(t);if(r.issues)return r;let i=e(h(r.value));if(`then`in i)return O(i),y(`Async schemas are not supported`);if(i.issues)return g(i.issues);let a=k(i.value);return a===void 0?y(`Expected a Decimal: a custom decimal schema may refine or brand the value it is given, but not return a string, a number, or a value of any other type`):x(a)}}if(n!==void 0){let e=validate;validate=t=>{let r=e(t);if(r.issues)return r;let i=m(r.value,n.precision,n.scale);return i===void 0?r:y(i)}}return validate}function decimal(e){let t=e===void 0?void 0:{...e,schema:void 0};return b(`decimal`,buildDecimalValueValidator(e),t)}function enum_(e,t){let n=new Set(e),baseValidate=t=>r(t)&&n.has(t)?x(t):{issues:[{message:`Expected one of: ${e.join(` | `)}`}]};return b(`enum`,baseValidate,t,{values:e})}function getNestedValue(e,t){let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r}function declaresPath(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:getNestedValue(e,t.slice(0,n));return a(r)&&t.slice(n+1)in r}function entriesFromObject(e,t){let n={};for(let r of Object.keys(e)){let i=getNestedValue(e[r],t);i!==void 0&&(n[r]=i)}return Object.keys(e).length>0&&Object.keys(n).length===0&&refuseUnmatchedPath(e,t),n}function fromObject(e,t,n){return T(entriesFromObject(e,t),n)}function refuseUnmatchedPath(e,t){if(!Object.values(e).some(e=>declaresPath(e,t)))throw new s({kind:`schema-builder`,builder:`fromObject`,path:t},[{path:t,message:`fromObject path "${t}" did not match any entries in the source object`}])}const R=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(?:Z|[+-](\d{2}):(\d{2}))$/,z=/^(\d{4})-(\d{2})-(\d{2})$/,B=/^\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/,V=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string or Date`})])}),H=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)`})])}),U=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date in ISO timestamp`})])});function validateIsoTimestamp(e){if(i(e))return w(Date.prototype.getTime.call(e))?x(Date.prototype.toISOString.call(e)):U;if(!r(e))return V;let t=R.exec(e);return t?!(E(Number(t[1]),Number(t[2]),Number(t[3]))&&C(Number(t[4]),Number(t[5]),Number(t[6])))||Number(t[7]??0)>23||Number(t[8]??0)>59||!w(Date.parse(e))?U:x(new Date(e).toISOString()):H}function isoTimestamp(e){return b(`iso_timestamp`,validateIsoTimestamp,e)}const W=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO date format (YYYY-MM-DD)`})])}),G=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date`})])});function validateIsoDate(e){if(i(e))return w(Date.prototype.getTime.call(e))?x(Date.prototype.toISOString.call(e).slice(0,10)):G;if(!r(e))return V;let t=z.exec(e);return t?E(Number(t[1]),Number(t[2]),Number(t[3]))?x(e):G:W}function isoDate(e){return b(`iso_date`,validateIsoDate,e)}const ce=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO time format (HH:mm:ss)`})])}),K=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid time`})])});function validateIsoTime(e){if(i(e))return Number.isNaN(Date.prototype.getTime.call(e))?K:x(Date.prototype.toISOString.call(e).split(`T`)[1].replace(`Z`,``));if(!r(e))return V;if(!B.test(e))return ce;let t=e.split(`:`),n=Number(t[0]),a=Number(t[1]),o=Math.trunc(Number(t[2]));return n<0||n>23||a<0||a>59||o<0||o>59?K:x(e.padEnd(12,e.includes(`.`)?`0`:`.000`))}function isoTime(e){return b(`iso_time`,validateIsoTime,e)}const le=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected JSON-compatible value`})])}),q=Symbol(`invalid JSON`);function normalizeJson(e,t=new WeakMap){if(e===null||r(e)||l(e))return e;if(c(e))return Number.isFinite(e)?e:q;if(!(a(e)||Array.isArray(e))||d(e))return q;let n=t.get(e);if(n!==void 0)return n;if(t.set(e,q),Array.isArray(e)){let n=[];for(let r of e){let e=r===void 0?null:normalizeJson(r,t);if(e===q)return q;n.push(e)}return t.set(e,n),n}let i=Object.getPrototypeOf(e);if(i!==null&&i!==Object.prototype)return q;let o={};for(let n of Object.keys(e)){let r=e[n];if(r===void 0)continue;let i=normalizeJson(r,t);if(i===q)return q;Object.defineProperty(o,n,{value:i,enumerable:!0,configurable:!0,writable:!0})}return t.set(e,o),o}function validateJson(e){let t=normalizeJson(e);return t===q?le:x(t)}function json(e){return b(`json`,validateJson,e)}const J=[`DbNull`,`JsonNull`,`AnyNull`];function listKinds(e){return e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} or ${e.at(-1)}`}function refuseSentinel(e,t,n){return y(`${J.filter(e=>!t.includes(e)).length===J.length?`JSON null sentinels are not supported in ${n}`:`${e.kind} is not supported in ${n}; that slot accepts ${listKinds(t)}`}.`)}function checkSentinel(e,t,n){return t.includes(e.kind)?x(e):refuseSentinel(e,t,n)}function copyOptionality(e,t,n){e.allowed=n,e.wrapped=t,e.acceptsUndefined=t.acceptsUndefined===!0}function jsonNullOr(e,t,n){let r=_(`json_null_or`,r=>u(r)?checkSentinel(r,e,n):D(t,r));return copyOptionality(r,t,e),r}function jsonWrite(e,t,n,r){let i=_(`json_write`,i=>{if(u(i))return checkSentinel(i,e,n);if(i===null)return y(r);let a=D(t,i);return!a.issues&&a.value===null&&i!==void 0?checkSentinel(ee,e,n):a});return copyOptionality(i,t,e),i}function lazy(e){let n=e,r,resolve=()=>(n&&=(r=n(),void 0),r);return new Proxy({},{get(e,n,r){let i=resolve(),a=Reflect.get(i,n,r);return t(a)?a.bind(i):a},has(e,t){return Reflect.has(resolve(),t)},ownKeys(e){return Reflect.ownKeys(resolve())},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(resolve(),t)},getPrototypeOf(e){return Reflect.getPrototypeOf(resolve())}})}function lazyRef(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return{type:`lazyRef`,get wrapped(){return resolve()},get entries(){return resolve().entries},"~standard":{version:1,vendor:`viborm`,validate:e=>resolve()[`~standard`].validate(e),get jsonSchema(){return resolve()[`~standard`].jsonSchema}}}}function literal(e,t){let n=e===null?`null`:String(e),r=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected literal: ${n}`})])}),baseValidate=t=>t===e?x(t):r;return b(`literal`,baseValidate,t,{value:e})}function nullable(e){let t=e[`~standard`].validate,n=_(`nullable`,e=>e===null?x(null):t(e));return n.wrapped=e,n}function maybeNullable(e,t){return t?nullable(e):e}function omit(e,t){return T(e.entries,{...e.options||{},omit:t})}let Y=0;function limitFilterDepth(e){let t=e[`~standard`].validate;return Object.defineProperty(e[`~standard`],`validate`,{value:e=>{if(Y>=16)return y(`Filter nesting exceeds 16 levels`);Y++;try{return t(e)}finally{Y--}}}),e}let X;const Z=new WeakMap;function runInOperandScope(e,t){let n=X;X=e;try{return t()}finally{X=n}}function scopeOperands(e,t){let n=e[`~standard`],r=n.validate;return n.validate=e=>runInOperandScope(t,()=>r(e)),limitFilterDepth(e)}function currentContext(){let e=X;if(!e)return;let t=Z.get(e);if(t)return t;let n={fields:te(e[`~`].names.ts??`unknown`,e),sql:ne};return Z.set(e,n),n}const Q="A filter callback must return a field reference (ctx.fields.<field>) or an SQL fragment (ctx.sql`…`)";function describe(e){return e===null?`null`:Array.isArray(e)?`an array`:`a value of type '${typeof e}'`}function resolveCallback(e,n){let r=currentContext();if(!r)return y(`A filter callback is only meaningful inside a model filter, where the model whose columns it names is known.`);let i;try{i=e(r)}catch(e){return y(`Filter callback threw: ${e instanceof Error?e.message:String(e)}`)}return d(i)?checkRef(i,n):p(i)?x(i):a(i)&&t(i.then)?(O(i),y(`${Q}; it returned a promise. Validation is synchronous, so a filter callback cannot be async.`)):y(`${Q}; it returned ${describe(i)}.`)}function comparisonOperand(e,n){let r=_(`comparison_operand`,r=>t(r)?resolveCallback(r,e):d(r)?checkRef(r,e):p(r)?x(r):D(n,r));return r.fieldType=e,r.wrapped=n,r.acceptsUndefined=n.acceptsUndefined===!0,r}function fieldRefOr(e,t){let n=_(`field_ref_or`,n=>d(n)?checkRef(n,e):D(t,n));return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function closeOperands(e,t,n){let r=e[`~standard`],i={"~standard":{version:r.version,vendor:r.vendor,validate:r.validate}},a=_(`no_field_ref`,e=>{let r=findOpaqueOperand(e,n);if(r)return y(`${r} is not supported in ${t}.`);let a=D(i,e);if(a.issues)return a;let o=findOpaqueOperand(a.value,n);return o?y(`${o} is not supported in ${t}.`):a});return a.wrapped=e,a.acceptsUndefined=e.acceptsUndefined??!1,a}function noFieldRef(e,t){return closeOperands(e,t,!1)}function noOperandExpression(e,t){return closeOperands(e,t,!0)}function findOpaqueOperand(e,t){let n=new WeakSet,r=[e];for(;r.length>0;){let e=r.pop();if(t&&typeof e==`function`)return`A filter callback`;if(!(typeof e!=`object`||!e)){if(d(e)){let t=f(e);return`Field reference '${t.model}.${t.field}'`}if(t&&p(e))return`An SQL fragment`;if(!n.has(e)&&(n.add(e),!(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))){if(Array.isArray(e)){for(let t of e)r.push(t);continue}for(let t of Object.keys(e))r.push(e[t])}}}}function checkRef(e,t){let n=f(e);return n.list?y(`Field reference '${n.model}.${n.field}' is a list field; list fields cannot be used as a comparison operand.`):n.type===t?x(e):y(`Field reference '${n.model}.${n.field}' is of type '${n.type}', but a '${t}' operand is required here.`)}function transform(e){return{type:`transform`,transform:e}}function pipe(e,...t){let n=_(`pipe`,n=>{let r=D(e,n);if(r.issues)return r;let i=r.value;for(let e of t)if(e.type===`transform`)try{i=e.transform(i)}catch(e){return y(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}return x(i)});return n.schema=e,n.actions=t,n}function point(e){return b(`point`,se,e)}function record(e,t){let n=_(`record`,n=>{if(!a(n))return y(`Expected object, received ${Array.isArray(n)?`array`:typeof n}`);let r={};for(let[i,a]of Object.entries(n)){let n=D(e,i);if(n.issues)return y(`Invalid key "${i}": ${n.issues[0].message}`,[i]);let o=D(t,a);if(o.issues){let e=o.issues[0],t=e.path?[i].concat(e.path):[i];return y(e.message,t)}r[n.value]=o.value}return x(r)});return n.key=e,n.value=t,n}function entriesFromKeys(e,t){let n={};for(let r of e)n[r]=t;return n}function fromKeys(e,t,n){return T(entriesFromKeys(e,t),n)}function refused(e){return _(`refused`,()=>y(e))}function coerce(e,t){let n=_(`transform`,n=>{let r=D(e,n);if(r.issues)return y(r.issues[0].message);try{return x(t(r.value))}catch(e){return y(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}});return n.wrapped=e,n.acceptsUndefined=e.acceptsUndefined===!0,n}const ue=coerce,shorthandFilter=e=>coerce(e,e=>({equals:e})),shorthandUpdate=e=>coerce(e,e=>({set:e})),shorthandArray=e=>coerce(e,e=>[e]);function union(e){let t=e.map(e=>e[`~standard`].validate),n=_(`union`,e=>{let n=null,r=null;for(let i of t){let t=i(e),a;if(`then`in t)O(t),a=`Async schemas are not supported`;else if(t.issues)a=t.issues[0].message;else return t;n===null?n=a:(r??=[]).push(a)}return y(`Value did not match any union member: ${r?`${n}, ${r.join(`, `)}`:n}`)});return n.options=e,n}const singleOrArray=e=>union([coerce(e,e=>[e]),array(e)]),de=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string`})])});function validateString(e){return r(e)?x(e):de}function string(e){return b(`string`,validateString,e)}const fe=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected array of numbers`})])});function createVectorValidator(e){let t=e===void 0?null:Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected vector of ${e} dimensions`})])});return n=>{if(!Array.isArray(n))return fe;let r=n.length;for(let e=0;e<r;e++)if(!(c(n[e])&&Number.isFinite(n[e])))return y(`Expected finite number at index ${e}`);return t&&r!==e?t:x(n)}}function vector(e,t){return b(`vector`,createVectorValidator(e),t,{dimensions:e})}const $={string,number:oe,integer:S,boolean,bigint,decimal,literal,enum:enum_,json,date,isoTimestamp,isoDate,isoTime,blob,vector,point,array,nullable,maybeNullable,optional:ae,object:T,omit,fromObject,union,pipe,transformAction:transform,record,fromKeys,coerce,map:ue,lazy,lazyRef,singleOrArray,shorthandFilter,shorthandUpdate,shorthandArray,comparisonOperand,fieldRefOr,noFieldRef,noOperandExpression,jsonNullOr,jsonWrite,refused};var pe=$;export{limitFilterDepth as a,validateIsoTimestamp as c,scopeOperands as i,entriesFromObject as l,pe as n,validateIsoDate as o,entriesFromKeys as r,validateIsoTime as s,$ as t};
2
- //# sourceMappingURL=v-B2WwtcRz.mjs.map