viborm 1.16.1 → 1.17.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 (402) hide show
  1. package/dist/adapter-internals-Dz2nNEF5.mjs +2 -0
  2. package/dist/adapter-internals-Dz2nNEF5.mjs.map +1 -0
  3. package/dist/adapter-namespace-C1SUkH2U.mjs +2 -0
  4. package/dist/{adapter-namespace-DwFnfpED.mjs.map → adapter-namespace-C1SUkH2U.mjs.map} +1 -1
  5. package/dist/adapters.d.mts +50 -94
  6. package/dist/adapters.mjs +1 -1
  7. package/dist/{args-7WgBFd_f.mjs → args-DsGRkPRw.mjs} +2 -2
  8. package/dist/{args-7WgBFd_f.mjs.map → args-DsGRkPRw.mjs.map} +1 -1
  9. package/dist/{array-literal-BOzj0E2u.mjs → array-literal-U6SeastY.mjs} +1 -1
  10. package/dist/{array-literal-BOzj0E2u.mjs.map → array-literal-U6SeastY.mjs.map} +1 -1
  11. package/dist/auto-names-GpcDfhaw.mjs +2 -0
  12. package/dist/auto-names-GpcDfhaw.mjs.map +1 -0
  13. package/dist/batch-refs-BuICt2tu.mjs +2 -0
  14. package/dist/{batch-refs-Bd8HvwUc.mjs.map → batch-refs-BuICt2tu.mjs.map} +1 -1
  15. package/dist/better-auth.d.mts +1 -1
  16. package/dist/better-auth.mjs +2 -2
  17. package/dist/bun-sql.d.mts +1 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sqlite.d.mts +1 -1
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/cache/cloudflare-kv.d.mts +1 -1
  22. package/dist/cache/cloudflare-kv.mjs +1 -1
  23. package/dist/cache/memory.d.mts +1 -1
  24. package/dist/cache/memory.mjs +1 -1
  25. package/dist/cache.d.mts +2 -2
  26. package/dist/cache.mjs +1 -1
  27. package/dist/call-D2E7dPCd.mjs +2 -0
  28. package/dist/{call-0bd_B9Vp.mjs.map → call-D2E7dPCd.mjs.map} +1 -1
  29. package/dist/cli.mjs +6 -6
  30. package/dist/cli.mjs.map +1 -1
  31. package/dist/client-Cq_VcF43.d.mts +183 -0
  32. package/dist/client-DkNRAOuH.mjs +2 -0
  33. package/dist/client-DkNRAOuH.mjs.map +1 -0
  34. package/dist/{planner-CYu6_q4w.d.mts → client-driver-DuQy6lsN.d.mts} +3 -3
  35. package/dist/client-rIiFOn1W.mjs +9 -0
  36. package/dist/client-rIiFOn1W.mjs.map +1 -0
  37. package/dist/client.d.mts +2 -2
  38. package/dist/client.mjs +1 -1
  39. package/dist/config.d.mts +2 -2
  40. package/dist/config.mjs +1 -1
  41. package/dist/{confine-CyI9IwjC.mjs → confine-FIfjlAHp.mjs} +2 -2
  42. package/dist/{confine-CyI9IwjC.mjs.map → confine-FIfjlAHp.mjs.map} +1 -1
  43. package/dist/{object-store-BBDTj8x3.d.mts → conformance-C1JveA8y.d.mts} +5 -60
  44. package/dist/conformance-C4JYA0JG.mjs +2 -0
  45. package/dist/conformance-C4JYA0JG.mjs.map +1 -0
  46. package/dist/contract-BBone8RD.mjs +2 -0
  47. package/dist/contract-BBone8RD.mjs.map +1 -0
  48. package/dist/coordination-BxMskOgi.mjs +1 -1
  49. package/dist/d1.d.mts +1 -1
  50. package/dist/d1.mjs +1 -1
  51. package/dist/{database-adapter-01J6mYq5.d.mts → database-adapter-cW0nmWM6.d.mts} +2 -2
  52. package/dist/datetime-physical-codec-Ci0dyOot.mjs +2 -0
  53. package/dist/datetime-physical-codec-Ci0dyOot.mjs.map +1 -0
  54. package/dist/datetime-values-D_G6m5_o.mjs +2 -0
  55. package/dist/datetime-values-D_G6m5_o.mjs.map +1 -0
  56. package/dist/decimal-D4DRlT2y.mjs +2 -0
  57. package/dist/decimal-D4DRlT2y.mjs.map +1 -0
  58. package/dist/{defaults-DAPb-tJ4.mjs → defaults-BrXUK350.mjs} +2 -2
  59. package/dist/{defaults-DAPb-tJ4.mjs.map → defaults-BrXUK350.mjs.map} +1 -1
  60. package/dist/{document-DRPqjDv_.d.mts → document-B8ClXlb7.d.mts} +1 -1
  61. package/dist/{driver-kiIQS_Fd.mjs → driver-BOsmU3kz.mjs} +2 -2
  62. package/dist/{driver-kiIQS_Fd.mjs.map → driver-BOsmU3kz.mjs.map} +1 -1
  63. package/dist/{driver-CTjq1yxj.d.mts → driver-KgGMnfz8.d.mts} +1 -1
  64. package/dist/{driver-lShUkDmf.mjs → driver-PkP_1p80.mjs} +2 -2
  65. package/dist/{driver-lShUkDmf.mjs.map → driver-PkP_1p80.mjs.map} +1 -1
  66. package/dist/{driver-diagnostics-aQ54bArn.mjs → driver-diagnostics-sSpge6kv.mjs} +1 -1
  67. package/dist/{driver-diagnostics-aQ54bArn.mjs.map → driver-diagnostics-sSpge6kv.mjs.map} +1 -1
  68. package/dist/driver.d.mts +1 -1
  69. package/dist/driver.mjs +1 -1
  70. package/dist/durable-object.d.mts +1 -1
  71. package/dist/durable-object.mjs +2 -2
  72. package/dist/error-mapping-B9rSvgG9.mjs +1 -1
  73. package/dist/every-tAZuZ50K.mjs +2 -0
  74. package/dist/{every-CgeIFxWR.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
  75. package/dist/execution-context-couU2tgh.mjs +1 -1
  76. package/dist/{exports-nC8lsVKO.d.mts → exports-reE3GioL.d.mts} +1 -1
  77. package/dist/extension-Bf4vO5mp.mjs +2 -0
  78. package/dist/extension-Bf4vO5mp.mjs.map +1 -0
  79. package/dist/facts-Bjnzv3j-.mjs +2 -0
  80. package/dist/facts-Bjnzv3j-.mjs.map +1 -0
  81. package/dist/{fs-estate-n-QpsFqb.mjs → fs-estate-C3ahNKmi.mjs} +2 -2
  82. package/dist/{fs-estate-n-QpsFqb.mjs.map → fs-estate-C3ahNKmi.mjs.map} +1 -1
  83. package/dist/geo-area-codec-CBdiCOzj.mjs +2 -0
  84. package/dist/{geo-area-codec-Bti2PA2i.mjs.map → geo-area-codec-CBdiCOzj.mjs.map} +1 -1
  85. package/dist/geo-point-DCV0eO1p.mjs +2 -0
  86. package/dist/geo-point-DCV0eO1p.mjs.map +1 -0
  87. package/dist/id-domain-Cj6MnMxg.mjs +2 -0
  88. package/dist/{id-domain-Cg65TLZ-.mjs.map → id-domain-Cj6MnMxg.mjs.map} +1 -1
  89. package/dist/identifier-BdLx66pi.mjs +2 -0
  90. package/dist/identifier-BdLx66pi.mjs.map +1 -0
  91. package/dist/identifier-conversion-CMKVatU4.mjs +3 -0
  92. package/dist/identifier-conversion-CMKVatU4.mjs.map +1 -0
  93. package/dist/{identifiers-BxOf57qy.mjs → identifiers-BAZ_S6Lk.mjs} +1 -1
  94. package/dist/{identifiers-BxOf57qy.mjs.map → identifiers-BAZ_S6Lk.mjs.map} +1 -1
  95. package/dist/{identity-CJlRQA-m.mjs → identity-nPArhpsD.mjs} +2 -2
  96. package/dist/{identity-CJlRQA-m.mjs.map → identity-nPArhpsD.mjs.map} +1 -1
  97. package/dist/index.d.mts +2 -2
  98. package/dist/index.mjs +1 -1
  99. package/dist/index.mjs.map +1 -1
  100. package/dist/instrumentation.d.mts +1 -1
  101. package/dist/instrumentation.mjs +1 -1
  102. package/dist/introspect-dyBpdr2L.mjs +2 -0
  103. package/dist/{introspect-rGqr93B3.mjs.map → introspect-dyBpdr2L.mjs.map} +1 -1
  104. package/dist/json-DvvrTWUw.mjs +2 -0
  105. package/dist/{json-CsAdz9pg.mjs.map → json-DvvrTWUw.mjs.map} +1 -1
  106. package/dist/{json-number-C09rsm1g.mjs → json-number-Guh-5rff.mjs} +1 -1
  107. package/dist/{json-number-C09rsm1g.mjs.map → json-number-Guh-5rff.mjs.map} +1 -1
  108. package/dist/{json-parameter-D7hDrVKw.mjs → json-parameter-DtHhEfyE.mjs} +1 -1
  109. package/dist/{json-parameter-D7hDrVKw.mjs.map → json-parameter-DtHhEfyE.mjs.map} +1 -1
  110. package/dist/judge-words-CqNdnbou.mjs +2 -0
  111. package/dist/judge-words-CqNdnbou.mjs.map +1 -0
  112. package/dist/{key-BDH6oTyC.mjs → key-v4k7Cqb6.mjs} +2 -2
  113. package/dist/{key-BDH6oTyC.mjs.map → key-v4k7Cqb6.mjs.map} +1 -1
  114. package/dist/{keys-CIal55WQ.mjs → keys-BLWaO_YM.mjs} +1 -1
  115. package/dist/{keys-CIal55WQ.mjs.map → keys-BLWaO_YM.mjs.map} +1 -1
  116. package/dist/keys-o4Pl6Vsg.mjs +2 -0
  117. package/dist/{keys-DZdKAd4n.mjs.map → keys-o4Pl6Vsg.mjs.map} +1 -1
  118. package/dist/libsql-C0iMZifz.mjs +3 -0
  119. package/dist/libsql-C0iMZifz.mjs.map +1 -0
  120. package/dist/libsql.d.mts +1 -1
  121. package/dist/libsql.mjs +1 -1
  122. package/dist/light-reLULeHN.mjs +2 -0
  123. package/dist/{light-D2wNSbzY.mjs.map → light-reLULeHN.mjs.map} +1 -1
  124. package/dist/memory-DtTuFo-h.mjs +2 -0
  125. package/dist/memory-DtTuFo-h.mjs.map +1 -0
  126. package/dist/methods-part-Dsi0DBNU.mjs +2 -0
  127. package/dist/{methods-part-BaNx3o7b.mjs.map → methods-part-Dsi0DBNU.mjs.map} +1 -1
  128. package/dist/migrations/mysql/runtime.d.mts +7 -0
  129. package/dist/migrations/mysql/runtime.mjs +2 -0
  130. package/dist/migrations/mysql/runtime.mjs.map +1 -0
  131. package/dist/migrations/mysql.d.mts +7 -5
  132. package/dist/migrations/mysql.mjs +1 -1
  133. package/dist/migrations/mysql.mjs.map +1 -1
  134. package/dist/migrations/postgres/runtime.d.mts +7 -0
  135. package/dist/migrations/postgres/runtime.mjs +2 -0
  136. package/dist/migrations/postgres/runtime.mjs.map +1 -0
  137. package/dist/migrations/postgres.d.mts +7 -5
  138. package/dist/migrations/postgres.mjs +1 -1
  139. package/dist/migrations/postgres.mjs.map +1 -1
  140. package/dist/migrations/snowflake.d.mts +7 -5
  141. package/dist/migrations/snowflake.mjs +1 -1
  142. package/dist/migrations/snowflake.mjs.map +1 -1
  143. package/dist/migrations/sqlite/runtime.d.mts +7 -0
  144. package/dist/migrations/sqlite/runtime.mjs +2 -0
  145. package/dist/migrations/sqlite/runtime.mjs.map +1 -0
  146. package/dist/migrations/sqlite.d.mts +7 -5
  147. package/dist/migrations/sqlite.mjs +1 -1
  148. package/dist/migrations/sqlite.mjs.map +1 -1
  149. package/dist/migrations/storage/durable-object.d.mts +1 -1
  150. package/dist/migrations/storage/durable-object.mjs +1 -1
  151. package/dist/migrations/storage/fs.d.mts +1 -1
  152. package/dist/migrations/storage/fs.mjs +1 -1
  153. package/dist/migrations/storage/r2.d.mts +1 -1
  154. package/dist/migrations/storage/r2.mjs +1 -1
  155. package/dist/migrations/surrealdb.d.mts +7 -5
  156. package/dist/migrations/surrealdb.mjs +1 -1
  157. package/dist/migrations/surrealdb.mjs.map +1 -1
  158. package/dist/migrations/tenant.d.mts +4 -3
  159. package/dist/migrations/tenant.mjs +1 -1
  160. package/dist/migrations/tenant.mjs.map +1 -1
  161. package/dist/migrations.d.mts +7 -5
  162. package/dist/migrations.mjs +1 -1
  163. package/dist/migrations.mjs.map +1 -1
  164. package/dist/model-ByktcCGW.mjs +2 -0
  165. package/dist/model-ByktcCGW.mjs.map +1 -0
  166. package/dist/mysql-DPYi1p_g.mjs +4 -0
  167. package/dist/mysql-DPYi1p_g.mjs.map +1 -0
  168. package/dist/mysql-adapter-6gVm5PHp.mjs +2 -0
  169. package/dist/{mysql-adapter-BFWYPoM0.mjs.map → mysql-adapter-6gVm5PHp.mjs.map} +1 -1
  170. package/dist/mysql2.d.mts +1 -1
  171. package/dist/mysql2.mjs +1 -1
  172. package/dist/{named-statements-CkOOD__I.mjs → named-statements-CswIc5m1.mjs} +2 -2
  173. package/dist/{named-statements-CkOOD__I.mjs.map → named-statements-CswIc5m1.mjs.map} +1 -1
  174. package/dist/native-types-BUkcVedc.mjs +2 -0
  175. package/dist/native-types-BUkcVedc.mjs.map +1 -0
  176. package/dist/neon-http.d.mts +1 -1
  177. package/dist/neon-http.mjs +1 -1
  178. package/dist/normalized-result-D7nVkF36.mjs +1 -1
  179. package/dist/{object-store-Chq1PMYz.mjs → object-store-DnrLNxz_.mjs} +2 -2
  180. package/dist/{object-store-Chq1PMYz.mjs.map → object-store-DnrLNxz_.mjs.map} +1 -1
  181. package/dist/object-store-j4kgh61D.d.mts +59 -0
  182. package/dist/{on-ZkOVmE4-.mjs → on-nOenqmgP.mjs} +2 -2
  183. package/dist/{on-ZkOVmE4-.mjs.map → on-nOenqmgP.mjs.map} +1 -1
  184. package/dist/on.d.mts +1 -1
  185. package/dist/on.mjs +1 -1
  186. package/dist/ordering/keys.mjs +1 -1
  187. package/dist/ordering.d.mts +1 -1
  188. package/dist/ordering.mjs +2 -2
  189. package/dist/pending-operation-B5o-zhES.mjs +2 -0
  190. package/dist/{pending-operation-D4gUKMxD.mjs.map → pending-operation-B5o-zhES.mjs.map} +1 -1
  191. package/dist/permissions.d.mts +1 -1
  192. package/dist/permissions.mjs +1 -1
  193. package/dist/pg.d.mts +2 -2
  194. package/dist/pg.mjs +1 -1
  195. package/dist/pglite.d.mts +1 -1
  196. package/dist/pglite.mjs +1 -1
  197. package/dist/{physical-DO4PEYcc.mjs → physical-BheMRPY0.mjs} +2 -2
  198. package/dist/{physical-DO4PEYcc.mjs.map → physical-BheMRPY0.mjs.map} +1 -1
  199. package/dist/{pinned-session-Y7-2pRBJ.mjs → pinned-session-eNyd0dkT.mjs} +2 -2
  200. package/dist/{pinned-session-Y7-2pRBJ.mjs.map → pinned-session-eNyd0dkT.mjs.map} +1 -1
  201. package/dist/planetscale.d.mts +1 -1
  202. package/dist/planetscale.mjs +1 -1
  203. package/dist/postgres-CEGFOi8D.mjs +27 -0
  204. package/dist/postgres-CEGFOi8D.mjs.map +1 -0
  205. package/dist/postgres-adapter-B-im38AE.mjs +2 -0
  206. package/dist/postgres-adapter-B-im38AE.mjs.map +1 -0
  207. package/dist/{postgres-adapter-BpLizOaK.mjs → postgres-adapter-OoqoBdhb.mjs} +2 -2
  208. package/dist/{postgres-adapter-BpLizOaK.mjs.map → postgres-adapter-OoqoBdhb.mjs.map} +1 -1
  209. package/dist/{postgres-result-133boRW-.mjs → postgres-result-D-bqmofR.mjs} +1 -1
  210. package/dist/{postgres-result-133boRW-.mjs.map → postgres-result-D-bqmofR.mjs.map} +1 -1
  211. package/dist/postgres.d.mts +2 -2
  212. package/dist/postgres.mjs +1 -1
  213. package/dist/provider-limits-DvcCUw7l.mjs +2 -0
  214. package/dist/{provider-limits-SdI1SaJS.mjs.map → provider-limits-DvcCUw7l.mjs.map} +1 -1
  215. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs → provider-parameter-snapshot-DnJ6Av9y.mjs} +2 -2
  216. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs.map → provider-parameter-snapshot-DnJ6Av9y.mjs.map} +1 -1
  217. package/dist/push-fingerprint-CegYVFFp.mjs +18 -0
  218. package/dist/push-fingerprint-CegYVFFp.mjs.map +1 -0
  219. package/dist/{quantized-BKBs0joq.mjs → quantized-DLD2cd6q.mjs} +1 -1
  220. package/dist/{quantized-BKBs0joq.mjs.map → quantized-DLD2cd6q.mjs.map} +1 -1
  221. package/dist/query-DSEMPA7r.mjs +2 -0
  222. package/dist/query-DSEMPA7r.mjs.map +1 -0
  223. package/dist/query-backend-CzwVfrQ6.mjs +2 -0
  224. package/dist/{query-backend-TisPjCPF.mjs.map → query-backend-CzwVfrQ6.mjs.map} +1 -1
  225. package/dist/{query-inspection-DwYBKSDG.mjs → query-inspection-CvtTL5Fs.mjs} +2 -2
  226. package/dist/{query-inspection-DwYBKSDG.mjs.map → query-inspection-CvtTL5Fs.mjs.map} +1 -1
  227. package/dist/raw-B8cNef_V.mjs +2 -0
  228. package/dist/{raw-DqEb71JZ.mjs.map → raw-B8cNef_V.mjs.map} +1 -1
  229. package/dist/{relation-bound-CSNKLyDy.mjs → relation-bound-DHP5cpTE.mjs} +1 -1
  230. package/dist/{relation-bound-CSNKLyDy.mjs.map → relation-bound-DHP5cpTE.mjs.map} +1 -1
  231. package/dist/{result-parsing-BbffueEX.mjs → result-parsing-DfwBAXY2.mjs} +1 -1
  232. package/dist/{result-parsing-BbffueEX.mjs.map → result-parsing-DfwBAXY2.mjs.map} +1 -1
  233. package/dist/{rows-of-Bgl9GVtK.mjs → rows-of-UeSasWGq.mjs} +2 -2
  234. package/dist/{rows-of-Bgl9GVtK.mjs.map → rows-of-UeSasWGq.mjs.map} +1 -1
  235. package/dist/rule-words-ojG0-vSf.mjs +2 -0
  236. package/dist/{rule-words-DMbQuvD2.mjs.map → rule-words-ojG0-vSf.mjs.map} +1 -1
  237. package/dist/runtime-BAqlANG_.mjs +10 -0
  238. package/dist/runtime-BAqlANG_.mjs.map +1 -0
  239. package/dist/runtime-D0oaIS1E.mjs +2 -0
  240. package/dist/runtime-D0oaIS1E.mjs.map +1 -0
  241. package/dist/runtime-Dfkv59_p.mjs +15 -0
  242. package/dist/runtime-Dfkv59_p.mjs.map +1 -0
  243. package/dist/runtime-client-CvGGOOFd.d.mts +38 -0
  244. package/dist/runtime-client-xeiXA_1m.mjs +2 -0
  245. package/dist/runtime-client-xeiXA_1m.mjs.map +1 -0
  246. package/dist/scalar-BTYxpiP_.mjs +4 -0
  247. package/dist/scalar-BTYxpiP_.mjs.map +1 -0
  248. package/dist/schema/introspect.d.mts +2 -2
  249. package/dist/schema/introspect.mjs +1 -1
  250. package/dist/schema/json.d.mts +2 -2
  251. package/dist/schema/json.mjs +1 -1
  252. package/dist/schema-BzkBJTF-.mjs +2 -0
  253. package/dist/{schema-DDkAUfOb.mjs.map → schema-BzkBJTF-.mjs.map} +1 -1
  254. package/dist/schema-D7MyYTjA.mjs +2 -0
  255. package/dist/{schema-DqR_Kcje.mjs.map → schema-D7MyYTjA.mjs.map} +1 -1
  256. package/dist/{schema-introspection-Bbo4DN_d.mjs → schema-introspection-b4xPGPfu.mjs} +4 -4
  257. package/dist/{schema-introspection-Bbo4DN_d.mjs.map → schema-introspection-b4xPGPfu.mjs.map} +1 -1
  258. package/dist/schema.d.mts +1 -1
  259. package/dist/schema.mjs +1 -1
  260. package/dist/{select-assembly-CEpNu-Gw.mjs → select-assembly-B01JtBRm.mjs} +2 -2
  261. package/dist/{select-assembly-CEpNu-Gw.mjs.map → select-assembly-B01JtBRm.mjs.map} +1 -1
  262. package/dist/serializer-CIhcZMxs.mjs +7 -0
  263. package/dist/serializer-CIhcZMxs.mjs.map +1 -0
  264. package/dist/{settle-Pui-1tfJ.mjs → settle-CIbvnLED.mjs} +1 -1
  265. package/dist/{settle-Pui-1tfJ.mjs.map → settle-CIbvnLED.mjs.map} +1 -1
  266. package/dist/{settled-DYYPcaBX.mjs → settled-Clanz_kI.mjs} +2 -2
  267. package/dist/{settled-DYYPcaBX.mjs.map → settled-Clanz_kI.mjs.map} +1 -1
  268. package/dist/snowflake-C1dqbche.mjs +2 -0
  269. package/dist/{snowflake-B8Ei88bg.mjs.map → snowflake-C1dqbche.mjs.map} +1 -1
  270. package/dist/snowflake.d.mts +2 -2
  271. package/dist/snowflake.mjs +2 -2
  272. package/dist/snowflake.mjs.map +1 -1
  273. package/dist/soft-delete.d.mts +1 -1
  274. package/dist/soft-delete.mjs +1 -1
  275. package/dist/{spans-DwDXMvyd.mjs → spans-CVl3RKUR.mjs} +1 -1
  276. package/dist/{spans-DwDXMvyd.mjs.map → spans-CVl3RKUR.mjs.map} +1 -1
  277. package/dist/sql-AHN2niBz.mjs +2 -0
  278. package/dist/{sql-M5WsPhqr.mjs.map → sql-AHN2niBz.mjs.map} +1 -1
  279. package/dist/sql-control-Cdp0_Mwy.mjs +2 -0
  280. package/dist/sql-control-Cdp0_Mwy.mjs.map +1 -0
  281. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs → sql-statement-tokens-BdVJnUQY.mjs} +2 -2
  282. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs.map → sql-statement-tokens-BdVJnUQY.mjs.map} +1 -1
  283. package/dist/sql-tegqTqGq.mjs +1 -1
  284. package/dist/sql.d.mts +1 -1
  285. package/dist/sqlite-adapter-B7r7w3CS.mjs +2 -0
  286. package/dist/sqlite-adapter-B7r7w3CS.mjs.map +1 -0
  287. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs → sqlite-statement-classifier-CBmKy8Ta.mjs} +2 -2
  288. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs.map → sqlite-statement-classifier-CBmKy8Ta.mjs.map} +1 -1
  289. package/dist/sqlite-storage-audit-D8nA9ylL.mjs +2 -0
  290. package/dist/sqlite-storage-audit-D8nA9ylL.mjs.map +1 -0
  291. package/dist/{sqlite-utils-Bfmtkt1b.mjs → sqlite-utils-BAUMCrok.mjs} +2 -2
  292. package/dist/{sqlite-utils-Bfmtkt1b.mjs.map → sqlite-utils-BAUMCrok.mjs.map} +1 -1
  293. package/dist/sqlite3.d.mts +1 -1
  294. package/dist/sqlite3.mjs +1 -1
  295. package/dist/{standard-sql-Bl2OHGfi.mjs → standard-sql-tpcKlArE.mjs} +2 -2
  296. package/dist/{standard-sql-Bl2OHGfi.mjs.map → standard-sql-tpcKlArE.mjs.map} +1 -1
  297. package/dist/surrealdb.d.mts +2 -2
  298. package/dist/surrealdb.mjs +1 -1
  299. package/dist/surrealdb.mjs.map +1 -1
  300. package/dist/surrealql-AyDLKSEQ.mjs +2 -0
  301. package/dist/surrealql-AyDLKSEQ.mjs.map +1 -0
  302. package/dist/time-step-BIdl2Iy7.mjs +2 -0
  303. package/dist/time-step-BIdl2Iy7.mjs.map +1 -0
  304. package/dist/transaction-operation-CaWzo7gE.mjs +1 -1
  305. package/dist/type-mapping-BYre7JQ1.mjs +3 -0
  306. package/dist/type-mapping-BYre7JQ1.mjs.map +1 -0
  307. package/dist/{types-Dy33vBdd.mjs → types-M-IdB4Mo.mjs} +1 -1
  308. package/dist/{types-Dy33vBdd.mjs.map → types-M-IdB4Mo.mjs.map} +1 -1
  309. package/dist/{unit-DUPX5Sdd.mjs → unit-Dnp2HIWg.mjs} +2 -2
  310. package/dist/{unit-DUPX5Sdd.mjs.map → unit-Dnp2HIWg.mjs.map} +1 -1
  311. package/dist/{unit-words-BXpLpyr2.mjs → unit-words-DjVhRXAQ.mjs} +2 -2
  312. package/dist/{unit-words-BXpLpyr2.mjs.map → unit-words-DjVhRXAQ.mjs.map} +1 -1
  313. package/dist/{utils-BHkJsduV.mjs → utils-BB_4NZQC.mjs} +2 -2
  314. package/dist/{utils-BHkJsduV.mjs.map → utils-BB_4NZQC.mjs.map} +1 -1
  315. package/dist/utils-DYrxwV_M.mjs +2 -0
  316. package/dist/utils-DYrxwV_M.mjs.map +1 -0
  317. package/dist/{v1-parse-shared-cJ-uD14P.mjs → v1-parse-shared-CNiFHAJF.mjs} +1 -1
  318. package/dist/{v1-parse-shared-cJ-uD14P.mjs.map → v1-parse-shared-CNiFHAJF.mjs.map} +1 -1
  319. package/dist/validation-CEnhYqhl.mjs +2 -0
  320. package/dist/{validation-BHjx13zG.mjs.map → validation-CEnhYqhl.mjs.map} +1 -1
  321. package/dist/validation.d.mts +1 -1
  322. package/dist/validation.mjs +1 -1
  323. package/dist/validator-CISkL46K.mjs +2 -0
  324. package/dist/validator-CISkL46K.mjs.map +1 -0
  325. package/dist/{values-Ch2cTlss.mjs → values-D0k60ei0.mjs} +2 -2
  326. package/dist/{values-Ch2cTlss.mjs.map → values-D0k60ei0.mjs.map} +1 -1
  327. package/dist/{client-Bb2oZOzg.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
  328. package/dist/version-nEOMCWfV.mjs +2 -0
  329. package/dist/{version-Bu2LCuaj.mjs.map → version-nEOMCWfV.mjs.map} +1 -1
  330. package/dist/view-CmLQ0I6x.mjs +2 -0
  331. package/dist/{view-CHgjF2BO.mjs.map → view-CmLQ0I6x.mjs.map} +1 -1
  332. package/dist/write-sinks-BhwgQn_5.mjs +2 -0
  333. package/dist/{write-sinks-Bei5vFHP.mjs.map → write-sinks-BhwgQn_5.mjs.map} +1 -1
  334. package/package.json +27 -2
  335. package/dist/adapter-namespace-DwFnfpED.mjs +0 -2
  336. package/dist/batch-refs-Bd8HvwUc.mjs +0 -2
  337. package/dist/call-0bd_B9Vp.mjs +0 -2
  338. package/dist/client-BvAmGuYW.mjs +0 -9
  339. package/dist/client-BvAmGuYW.mjs.map +0 -1
  340. package/dist/client-Q4zkYZbn.mjs +0 -2
  341. package/dist/client-Q4zkYZbn.mjs.map +0 -1
  342. package/dist/datetime-physical-codec-DAF7WJpy.mjs +0 -2
  343. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +0 -1
  344. package/dist/every-CgeIFxWR.mjs +0 -2
  345. package/dist/extension-Dh1ddrlA.mjs +0 -2
  346. package/dist/extension-Dh1ddrlA.mjs.map +0 -1
  347. package/dist/geo-area-codec-Bti2PA2i.mjs +0 -2
  348. package/dist/id-domain-Cg65TLZ-.mjs +0 -2
  349. package/dist/identifier-conversion-BTDxDwDB.mjs +0 -2
  350. package/dist/identifier-conversion-BTDxDwDB.mjs.map +0 -1
  351. package/dist/introspect-rGqr93B3.mjs +0 -2
  352. package/dist/json-CsAdz9pg.mjs +0 -2
  353. package/dist/judge-words-k5GCc4cV.mjs +0 -2
  354. package/dist/judge-words-k5GCc4cV.mjs.map +0 -1
  355. package/dist/keys-DZdKAd4n.mjs +0 -2
  356. package/dist/libsql-BZAXy5PY.mjs +0 -3
  357. package/dist/libsql-BZAXy5PY.mjs.map +0 -1
  358. package/dist/light-D2wNSbzY.mjs +0 -2
  359. package/dist/memory-DgBGBQdJ.mjs +0 -2
  360. package/dist/memory-DgBGBQdJ.mjs.map +0 -1
  361. package/dist/methods-part-BaNx3o7b.mjs +0 -2
  362. package/dist/model-Dtd37Sky.mjs +0 -2
  363. package/dist/model-Dtd37Sky.mjs.map +0 -1
  364. package/dist/mysql-BjIAoFH6.mjs +0 -9
  365. package/dist/mysql-BjIAoFH6.mjs.map +0 -1
  366. package/dist/mysql-adapter-BFWYPoM0.mjs +0 -2
  367. package/dist/native-types-1ewJXVks.mjs +0 -2
  368. package/dist/native-types-1ewJXVks.mjs.map +0 -1
  369. package/dist/pending-operation-D4gUKMxD.mjs +0 -2
  370. package/dist/postgres-CaMB2Y4p.mjs +0 -35
  371. package/dist/postgres-CaMB2Y4p.mjs.map +0 -1
  372. package/dist/postgres-adapter-psTVfuw7.mjs +0 -2
  373. package/dist/postgres-adapter-psTVfuw7.mjs.map +0 -1
  374. package/dist/provider-limits-SdI1SaJS.mjs +0 -2
  375. package/dist/query-BTb6iakn.mjs +0 -2
  376. package/dist/query-BTb6iakn.mjs.map +0 -1
  377. package/dist/query-backend-TisPjCPF.mjs +0 -2
  378. package/dist/raw-DqEb71JZ.mjs +0 -2
  379. package/dist/rule-words-DMbQuvD2.mjs +0 -2
  380. package/dist/scalar-Dm9brvAU.mjs +0 -4
  381. package/dist/scalar-Dm9brvAU.mjs.map +0 -1
  382. package/dist/schema-DDkAUfOb.mjs +0 -2
  383. package/dist/schema-DqR_Kcje.mjs +0 -2
  384. package/dist/serializer-Br9JgpQI.mjs +0 -33
  385. package/dist/serializer-Br9JgpQI.mjs.map +0 -1
  386. package/dist/snowflake-B8Ei88bg.mjs +0 -2
  387. package/dist/sql-M5WsPhqr.mjs +0 -2
  388. package/dist/sqlite-adapter-Cb-SJw2f.mjs +0 -2
  389. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +0 -1
  390. package/dist/surrealql-f2Rgu47F.mjs +0 -2
  391. package/dist/surrealql-f2Rgu47F.mjs.map +0 -1
  392. package/dist/time-step-DJaIhpAz.mjs +0 -2
  393. package/dist/time-step-DJaIhpAz.mjs.map +0 -1
  394. package/dist/validation-BHjx13zG.mjs +0 -2
  395. package/dist/validator-DMzH5Tz0.mjs +0 -2
  396. package/dist/validator-DMzH5Tz0.mjs.map +0 -1
  397. package/dist/version-Bu2LCuaj.mjs +0 -2
  398. package/dist/view-CHgjF2BO.mjs +0 -2
  399. package/dist/write-sinks-Bei5vFHP.mjs +0 -2
  400. /package/dist/{contract-CxJn0_cV.d.mts → contract-CAoFgKSO.d.mts} +0 -0
  401. /package/dist/{named-statements-NF7Iycjk.d.mts → named-statements-CT4Gbd6t.d.mts} +0 -0
  402. /package/dist/{sql-C4_sFNDm.d.mts → sql-C-SBCGCx.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"select-assembly-CEpNu-Gw.mjs","names":["sql","sql"],"sources":["../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":["/** 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 { TimeStep } from \"@validation/model/args/time-step\";\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/**\n * The column a time-step period is taken of: a calendar date or a date and\n * time, whether it declares a zone, and its native type, which may state the\n * zone instead.\n */\nexport interface PeriodSource {\n readonly date: boolean;\n readonly withTimezone: boolean;\n readonly nativeType: NativeTypeDeclaration | undefined;\n}\n\n/** A `groupBy` time step's period: computed once, then spelled. */\nexport interface PeriodSql {\n /**\n * The first day of the `step` period holding `column`, as a date: what a\n * grouped read groups and orders. A column that stores an instant is read\n * as wall time in `zone` (an admitted IANA name); a date, or a date and\n * time with no zone, as written.\n */\n readonly of: (\n column: Sql,\n step: TimeStep,\n source: PeriodSource,\n zone: string\n ) => Sql;\n /**\n * That date as the text the engine publishes from, `YYYY-MM-DD AD` or\n * `YYYY-MM-DD BC`, whatever the session's date style or the driver.\n */\n readonly text: (period: Sql) => Sql;\n}\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 */\n/** The three substring filters, as `insensitiveText` names them. */\nexport type TextMatch = \"contains\" | \"startsWith\" | \"endsWith\";\n\n/** A vector distance as an order key: see {@link DatabaseAdapter.vector}. */\nexport type VectorOrderKey = \"exact\" | \"servable\";\n\n/**\n * What the engine reads of a driver in any language: strategy and decoding, and\n * nothing that spells a statement. A database with no SQL declares only this.\n */\nexport interface EngineFacts\n extends Pick<DatabaseAdapter, \"namespace\" | \"capabilities\" | \"result\"> {\n /** Set when this database holds a geographic point, however it writes one. */\n readonly geoPoint?: object;\n readonly mutations: Pick<\n DatabaseAdapter[\"mutations\"],\n \"skipDuplicatesStrategy\" | \"upserted\"\n >;\n readonly aggregates: Partial<\n Pick<DatabaseAdapter[\"aggregates\"], \"numberSum\" | \"integerSum\">\n >;\n}\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 /**\n * Returns the dialect's membership operand, valid only as `operators.in` /\n * `notIn` input: a parenthesized list, a PostgreSQL array parameter, or,\n * past 25 members, a SQLite `json_each` subquery.\n */\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 /** 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 * The same three predicates under `mode: \"insensitive\"`: letter case is\n * ignored the way THIS database folds it (its own `LOWER`/`ILIKE`), so the\n * answer for a non-ASCII letter follows the database and its locale.\n * Accents and every other difference still count.\n *\n * Both operands arrive raw: neither folded nor wrapped in\n * `caseSensitiveText`. A plain string `value` is a bare bound parameter,\n * which an adapter matching with `LIKE` escapes client-side.\n */\n insensitiveText: (\n kind: TextMatch,\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => 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 /**\n * Fold letter case the way this database does natively (its own `LOWER`),\n * for `mode: \"insensitive\"` equality, membership and ranges. The caller\n * compares the result under `caseSensitiveText`, so case is the only\n * difference it ignores. `expr` arrives raw, never wrapped in\n * `caseSensitiveText`, with the native type of the column it reads.\n */\n caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration) => 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 so does a bytes list longer than `literals.list` keeps\n * parenthesized; 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 /**\n * A double column's sum as two `SUM`s no row count can overflow: its\n * members of magnitude at least 1e-288 divided by 2^64, and the smaller\n * ones as they are. Dividing such a double by 2^64 is exact, so the first\n * part is the plain sum scaled exactly, and the reader's\n * `high * 2^64 + low` is that sum — `±Infinity` past the double range,\n * where PostgreSQL's own `SUM` raises and MySQL's answers 0 (engine-10).\n *\n * `having` compares `value` and a grouped `orderBy` sorts by `order`, so\n * a group is kept and placed by the sum the projection publishes.\n */\n numberSum: (expr: Sql) => {\n readonly parts: readonly [high: Sql, low: Sql];\n /** The joined sum as one comparable expression. */\n readonly value: Sql;\n /** Sort keys, most significant first, ordering by the joined sum. */\n readonly order: readonly Sql[];\n };\n /**\n * Stated only where an integer `SUM` is int64 and raises past it\n * (SQLite): an int64 column's sum as two `SUM`s no realistic row count\n * can overflow — each member's high 32 bits and the rest — read back\n * exactly as `high * 2^32 + low` (engine-10), compared and sorted as\n * `numberSum` states. PostgreSQL and MySQL already sum integers as exact\n * numerics.\n */\n integerSum?: DatabaseAdapter[\"aggregates\"][\"numberSum\"];\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. `expr` is a\n * JSON value as built here (`object`, `array`): one read back through a\n * subquery column goes through `document` first, which SQLite needs to\n * keep it a JSON value rather than a quoted string.\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 * `stringAtPath` in the database's own text type and collation, for\n * `mode: \"insensitive\"`: the byte-ordered pin stops a database folding\n * case (`LOWER`/`ILIKE` under PG `COLLATE \"C\"` fold `A`-`Z` only, and\n * MySQL's `LOWER` leaves a binary string as it is).\n */\n foldableStringAtPath: (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 /**\n * The values a one-column `query` answers, as one array, empty where it\n * answers none (PostgreSQL `ARRAY(…)`). A row tests a key set held this\n * way by {@link has} rather than by joining it: the array is computed once\n * per statement, where a joined set is read again for each row of a\n * correlated subquery. Absent where the dialect has no array value.\n */\n ofRows?: (query: Sql) => 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`: a row of the subquery exists (`some`, `is`). */\n some: (subquery: Sql) => Sql;\n /** `NOT EXISTS`: none does (`none`, `isNot`, and `every` over the negated condition). */\n none: (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 * `condition`, a conjunct of a `WHERE` (a NULL and a false refuse its\n * row alike), placed where its own depth is not added to the\n * expression that holds it: the identity, except where the transport\n * bounds expression depth and the dialect sums nested heights.\n */\n isolated: (condition: Sql) => Sql;\n /**\n * A raw read's `FROM` item for one model's rows (`$rows`): `from` read\n * as `row`, filtered by `where` (every row without one), named `alias`.\n * `implicitRowid`: the table keeps a rowid `SELECT *` leaves out; SQLite\n * carries it as `rowid`, the key an FTS5 table joins on.\n */\n rows: (\n from: Sql,\n row: string,\n where: Sql | undefined,\n alias: string,\n implicitRowid: boolean\n ) => Sql;\n };\n\n /**\n * CTE\n * Common Table Expressions\n */\n cte: {\n /**\n * Build WITH clause: WITH name AS (query), ... A member `inlined` is read\n * correlated to each outer row through its own columns: PostgreSQL would\n * materialize a member read twice and scan it, without an index, once\n * per row, so it is written `NOT MATERIALIZED` there. A member\n * `inlined: false` is computed once: SQLite would inline it at every\n * use, so it is written `MATERIALIZED` there. Without `inlined`, the\n * database decides. A `recursive` member's query is its two terms,\n * `anchor UNION recursive`, and makes the clause `WITH RECURSIVE`.\n */\n with: (\n definitions: {\n name: string;\n query: Sql;\n inlined?: boolean;\n recursive?: boolean;\n }[]\n ) => 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 /** Whether `query` opens with its own `WITH`: a statement holds only one. */\n opens: (query: Sql) => boolean;\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 /**\n * INSERT the rows that are not there, by `key`, the columns of one unique\n * constraint of `table`: a row that is there stays as it is, or takes\n * `sets`, unless it holds `unless` already. One statement where the\n * dialect names a conflict target, and elsewhere the statements that\n * leave the table the same.\n */\n insertAbsent: (\n table: Sql,\n columns: string[],\n rows: Sql[][],\n key: readonly string[],\n sets?: Sql,\n unless?: 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 /**\n * UPDATE table SET ... from `source` (a derived table, aliased) joined\n * `on` the row written, WHERE ...: `UPDATE … FROM` (PostgreSQL, SQLite),\n * `UPDATE … JOIN` (MySQL).\n */\n updateFrom: (\n table: Sql,\n sets: Sql,\n source: Sql,\n on: Sql,\n where?: Sql\n ) => 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 * A `RETURNING` expression true where an `INSERT … ON CONFLICT DO UPDATE`\n * inserted its row rather than updated it (PostgreSQL: `xmax = 0`).\n * Absent where the statement cannot say: an upsert that must report its\n * arm then reads the row first.\n */\n upserted?: 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 * The action that leaves a row in conflict as it is. Present where the\n * dialect has a targeted upsert (PostgreSQL, SQLite): MySQL's\n * `ON DUPLICATE KEY UPDATE` has no such action.\n */\n onConflictNothing?: () => 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 /** UNION ALL (keeps duplicates). */\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 * The `_distance` metrics `{ l2, cosine }`: the selected distance, and the\n * order key of a distance `orderBy`. Drivers that don't support vector\n * operations can override this property with an object that throws\n * FeatureNotSupportedError.\n *\n * Without `order` a metric is the distance VALUE. With it, an order key: an\n * `\"exact\"` key is one no index can serve, so the order is exact whatever\n * index the column has; a `\"servable\"` key is one a nearest-neighbour index\n * may serve, and is approximate where it does.\n */\n vector: {\n /** Create a vector literal from number array: '[1,2,3]'::vector */\n literal: (values: number[]) => Sql;\n /** L2 (Euclidean) distance: column <-> vector */\n l2: (column: Sql, vector: Sql, order?: VectorOrderKey) => Sql;\n /** Cosine distance: column <=> vector */\n cosine: (column: Sql, vector: Sql, order?: VectorOrderKey) => 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 /**\n * The periods of a `by` member grouped by a time step. Absence means this\n * adapter groups by no time step, and the engine refuses such a call before\n * any statement is sent.\n */\n readonly period?: PeriodSql;\n\n /**\n * The statement that recomputes the materialized view stored as `table`\n * (`$refresh()`), `concurrently` without blocking its readers. Absence\n * means this database stores no view's rows: a materialized view is an\n * ordinary one there, and `$refresh()` sends nothing.\n */\n readonly refresh?: (table: string, concurrently: boolean) => Sql;\n\n /**\n * The statements that recompute a view kept by triggers (`refresh: \"auto\"`)\n * from its body view, run atomically by `$refresh()`. Absence means the\n * database keeps the view itself (SurrealDB) and `$refresh()` sends nothing.\n */\n readonly refreshAuto?: (\n table: string,\n body: string,\n source: string,\n keyColumn: string\n ) => Sql[];\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 { 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\n/**\n * A statement's clauses, each word before its operand, as ONE fragment: a\n * fragment per clause and their join were up to seven more for every SELECT\n * the engine assembles, each made here and walked again where the statement\n * is rendered (2 % to 4 % of a read's client CPU).\n */\ninterface Clauses {\n readonly strings: string[];\n readonly values: Sql[];\n}\n\nconst clause = (into: Clauses, word: string, operand: Sql): void => {\n into.strings.push(word);\n into.values.push(operand);\n};\n\n/**\n * A SELECT's clauses, begun with room for the ones it takes next. A list of\n * two members that takes a third by `push` is copied into a store of\n * nineteen: 240 bytes more for every SELECT the engine assembles, seven of\n * them in a read of two relation levels. The lists are written longer and cut\n * back, which keeps their store, so a WHERE, an ORDER BY, a LIMIT and an\n * OFFSET land in place.\n */\nconst begun = (first: string, second: string, a: Sql, b: Sql): Clauses => {\n const strings = [first, second, \"\", \"\", \"\", \"\", \"\", \"\"];\n const values = [a, b, a, a, a, a];\n strings.length = 2;\n values.length = 2;\n return { strings, values };\n};\n\nconst closed = (clauses: Clauses, last = \"\"): Sql => {\n clauses.strings.push(last);\n return new Sql(clauses.strings, clauses.values);\n};\n\n/** `distinctOn`: the columns of PostgreSQL's `DISTINCT ON`, where the page is one. */\nexport const assembleSelectQuery = (\n parts: QueryParts,\n options: SelectAssemblyOptions,\n distinctOn?: Sql\n): Sql => {\n const query: Clauses = distinctOn\n ? {\n strings: [\"SELECT DISTINCT ON (\", \") \", \" FROM \"],\n values: [distinctOn, parts.columns, parts.from],\n }\n : begun(\"SELECT \", \" FROM \", parts.columns, parts.from);\n\n appendFilterParts(query, parts);\n\n if (parts.orderBy) {\n clause(query, \" ORDER BY \", parts.orderBy);\n }\n\n appendLimitOffset(query, parts.limit, parts.offset, options.noLimitValue);\n\n return closed(\n query,\n options.forUpdate === \"append\" && parts.forUpdate ? \" FOR UPDATE\" : \"\"\n );\n};\n\n/** Joins, WHERE, GROUP BY and HAVING: shared by the plain and the emulated-DISTINCT select. */\nconst appendFilterParts = (into: Clauses, parts: QueryParts): void => {\n if (parts.joins) {\n for (const join of parts.joins) clause(into, \" \", join);\n }\n\n if (parts.where) {\n clause(into, \" WHERE \", parts.where);\n }\n\n if (parts.groupBy) {\n clause(into, \" GROUP BY \", parts.groupBy);\n }\n\n if (parts.having) {\n clause(into, \" HAVING \", parts.having);\n }\n};\n\nconst appendLimitOffset = (\n into: Clauses,\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n clause(into, \" LIMIT \", limit);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n clause(into, \" LIMIT \", noLimitValue);\n }\n\n if (offset) {\n clause(into, \" OFFSET \", offset);\n }\n};\n\n/**\n * Simulate `SELECT DISTINCT ON` using one ROW_NUMBER() window.\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 * order_term_1 AS _ord0, ... -- only when ORDER BY present\n * ROW_NUMBER() OVER (PARTITION BY distinct_cols ORDER BY order_cols) AS _rn\n * FROM table\n * WHERE ...\n * ) AS _distinct_subquery\n * WHERE _rn = 1\n * ORDER BY _ord0, ...\n * LIMIT ... OFFSET ...\n *\n * The outer ORDER BY reads the projected `_ordN` terms because the user's\n * ORDER BY references inner table aliases (and relation-order joins) that\n * are out of scope outside the subquery. Ordering the kept rows by those\n * values (and not by a second window ranking every row) spares one sort.\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 const order = parts.distinctOrder;\n\n const selectColumns: Sql[] = [parts.columns];\n if (order) {\n selectColumns.push(order.keys);\n }\n selectColumns.push(\n sql`ROW_NUMBER() OVER (PARTITION BY ${distinct} ORDER BY ${rowNumberOrder}) AS ${escapeIdentifier(\"_rn\")}`\n );\n\n // Inner query with ROW_NUMBER()\n const inner: Clauses = {\n strings: [\"SELECT \", \" FROM \"],\n values: [sql.join(selectColumns, \", \"), parts.from],\n };\n\n appendFilterParts(inner, parts);\n\n const innerQuery = closed(inner);\n\n // Outer query that filters for first row of each partition. It names the\n // output columns so _rn/_ordN stay inside: every engine DISTINCT carrier\n // states its aliases.\n const aliasColumns = parts.distinctColumnAliases!.map(escapeIdentifier);\n const outer: Clauses = {\n strings: [\"\"],\n values: [\n sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")} WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ],\n };\n\n if (order) {\n clause(outer, \" ORDER BY \", order.orderBy);\n }\n\n appendLimitOffset(outer, parts.limit, parts.offset, noLimitValue);\n\n return closed(outer);\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"select-assembly-B01JtBRm.mjs","names":["sql","sql"],"sources":["../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":["/** 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 { TimeStep } from \"@validation/model/args/time-step\";\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/**\n * The column a time-step period is taken of: a calendar date or a date and\n * time, whether it declares a zone, and its native type, which may state the\n * zone instead.\n */\nexport interface PeriodSource {\n readonly date: boolean;\n readonly withTimezone: boolean;\n readonly nativeType: NativeTypeDeclaration | undefined;\n}\n\n/** A `groupBy` time step's period: computed once, then spelled. */\nexport interface PeriodSql {\n /**\n * The first day of the `step` period holding `column`, as a date: what a\n * grouped read groups and orders. A column that stores an instant is read\n * as wall time in `zone` (an admitted IANA name); a date, or a date and\n * time with no zone, as written.\n */\n readonly of: (\n column: Sql,\n step: TimeStep,\n source: PeriodSource,\n zone: string\n ) => Sql;\n /**\n * That date as the text the engine publishes from, `YYYY-MM-DD AD` or\n * `YYYY-MM-DD BC`, whatever the session's date style or the driver.\n */\n readonly text: (period: Sql) => Sql;\n}\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 */\n/** The three substring filters, as `insensitiveText` names them. */\nexport type TextMatch = \"contains\" | \"startsWith\" | \"endsWith\";\n\n/** A vector distance as an order key: see {@link DatabaseAdapter.vector}. */\nexport type VectorOrderKey = \"exact\" | \"servable\";\n\n/**\n * What the engine reads of a driver in any language: strategy and decoding, and\n * nothing that spells a statement. A database with no SQL declares only this.\n */\nexport interface EngineFacts\n extends Pick<DatabaseAdapter, \"namespace\" | \"capabilities\" | \"result\"> {\n /** Set when this database holds a geographic point, however it writes one. */\n readonly geoPoint?: object;\n readonly mutations: Pick<\n DatabaseAdapter[\"mutations\"],\n \"skipDuplicatesStrategy\" | \"upserted\"\n >;\n readonly aggregates: Partial<\n Pick<DatabaseAdapter[\"aggregates\"], \"numberSum\" | \"integerSum\">\n >;\n}\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 /**\n * Returns the dialect's membership operand, valid only as `operators.in` /\n * `notIn` input: a parenthesized list, a PostgreSQL array parameter, or,\n * past 25 members, a SQLite `json_each` subquery.\n */\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 /** 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 * The same three predicates under `mode: \"insensitive\"`: letter case is\n * ignored the way THIS database folds it (its own `LOWER`/`ILIKE`), so the\n * answer for a non-ASCII letter follows the database and its locale.\n * Accents and every other difference still count.\n *\n * Both operands arrive raw: neither folded nor wrapped in\n * `caseSensitiveText`. A plain string `value` is a bare bound parameter,\n * which an adapter matching with `LIKE` escapes client-side.\n */\n insensitiveText: (\n kind: TextMatch,\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => 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 /**\n * Fold letter case the way this database does natively (its own `LOWER`),\n * for `mode: \"insensitive\"` equality, membership and ranges. The caller\n * compares the result under `caseSensitiveText`, so case is the only\n * difference it ignores. `expr` arrives raw, never wrapped in\n * `caseSensitiveText`, with the native type of the column it reads.\n */\n caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration) => 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 so does a bytes list longer than `literals.list` keeps\n * parenthesized; 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 /**\n * A double column's sum as two `SUM`s no row count can overflow: its\n * members of magnitude at least 1e-288 divided by 2^64, and the smaller\n * ones as they are. Dividing such a double by 2^64 is exact, so the first\n * part is the plain sum scaled exactly, and the reader's\n * `high * 2^64 + low` is that sum — `±Infinity` past the double range,\n * where PostgreSQL's own `SUM` raises and MySQL's answers 0 (engine-10).\n *\n * `having` compares `value` and a grouped `orderBy` sorts by `order`, so\n * a group is kept and placed by the sum the projection publishes.\n */\n numberSum: (expr: Sql) => {\n readonly parts: readonly [high: Sql, low: Sql];\n /** The joined sum as one comparable expression. */\n readonly value: Sql;\n /** Sort keys, most significant first, ordering by the joined sum. */\n readonly order: readonly Sql[];\n };\n /**\n * Stated only where an integer `SUM` is int64 and raises past it\n * (SQLite): an int64 column's sum as two `SUM`s no realistic row count\n * can overflow — each member's high 32 bits and the rest — read back\n * exactly as `high * 2^32 + low` (engine-10), compared and sorted as\n * `numberSum` states. PostgreSQL and MySQL already sum integers as exact\n * numerics.\n */\n integerSum?: DatabaseAdapter[\"aggregates\"][\"numberSum\"];\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. `expr` is a\n * JSON value as built here (`object`, `array`): one read back through a\n * subquery column goes through `document` first, which SQLite needs to\n * keep it a JSON value rather than a quoted string.\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 * `stringAtPath` in the database's own text type and collation, for\n * `mode: \"insensitive\"`: the byte-ordered pin stops a database folding\n * case (`LOWER`/`ILIKE` under PG `COLLATE \"C\"` fold `A`-`Z` only, and\n * MySQL's `LOWER` leaves a binary string as it is).\n */\n foldableStringAtPath: (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 /**\n * The values a one-column `query` answers, as one array, empty where it\n * answers none (PostgreSQL `ARRAY(…)`). A row tests a key set held this\n * way by {@link has} rather than by joining it: the array is computed once\n * per statement, where a joined set is read again for each row of a\n * correlated subquery. Absent where the dialect has no array value.\n */\n ofRows?: (query: Sql) => 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`: a row of the subquery exists (`some`, `is`). */\n some: (subquery: Sql) => Sql;\n /** `NOT EXISTS`: none does (`none`, `isNot`, and `every` over the negated condition). */\n none: (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 * `condition`, a conjunct of a `WHERE` (a NULL and a false refuse its\n * row alike), placed where its own depth is not added to the\n * expression that holds it: the identity, except where the transport\n * bounds expression depth and the dialect sums nested heights.\n */\n isolated: (condition: Sql) => Sql;\n /**\n * A raw read's `FROM` item for one model's rows (`$rows`): `from` read\n * as `row`, filtered by `where` (every row without one), named `alias`.\n * `implicitRowid`: the table keeps a rowid `SELECT *` leaves out; SQLite\n * carries it as `rowid`, the key an FTS5 table joins on.\n */\n rows: (\n from: Sql,\n row: string,\n where: Sql | undefined,\n alias: string,\n implicitRowid: boolean\n ) => Sql;\n };\n\n /**\n * CTE\n * Common Table Expressions\n */\n cte: {\n /**\n * Build WITH clause: WITH name AS (query), ... A member `inlined` is read\n * correlated to each outer row through its own columns: PostgreSQL would\n * materialize a member read twice and scan it, without an index, once\n * per row, so it is written `NOT MATERIALIZED` there. A member\n * `inlined: false` is computed once: SQLite would inline it at every\n * use, so it is written `MATERIALIZED` there. Without `inlined`, the\n * database decides. A `recursive` member's query is its two terms,\n * `anchor UNION recursive`, and makes the clause `WITH RECURSIVE`.\n */\n with: (\n definitions: {\n name: string;\n query: Sql;\n inlined?: boolean;\n recursive?: boolean;\n }[]\n ) => 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 /** Whether `query` opens with its own `WITH`: a statement holds only one. */\n opens: (query: Sql) => boolean;\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 /**\n * INSERT the rows that are not there, by `key`, the columns of one unique\n * constraint of `table`: a row that is there stays as it is, or takes\n * `sets`, unless it holds `unless` already. One statement where the\n * dialect names a conflict target, and elsewhere the statements that\n * leave the table the same.\n */\n insertAbsent: (\n table: Sql,\n columns: string[],\n rows: Sql[][],\n key: readonly string[],\n sets?: Sql,\n unless?: 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 /**\n * UPDATE table SET ... from `source` (a derived table, aliased) joined\n * `on` the row written, WHERE ...: `UPDATE … FROM` (PostgreSQL, SQLite),\n * `UPDATE … JOIN` (MySQL).\n */\n updateFrom: (\n table: Sql,\n sets: Sql,\n source: Sql,\n on: Sql,\n where?: Sql\n ) => 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 * A `RETURNING` expression true where an `INSERT … ON CONFLICT DO UPDATE`\n * inserted its row rather than updated it (PostgreSQL: `xmax = 0`).\n * Absent where the statement cannot say: an upsert that must report its\n * arm then reads the row first.\n */\n upserted?: 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 * The action that leaves a row in conflict as it is. Present where the\n * dialect has a targeted upsert (PostgreSQL, SQLite): MySQL's\n * `ON DUPLICATE KEY UPDATE` has no such action.\n */\n onConflictNothing?: () => 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 /** UNION ALL (keeps duplicates). */\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 * The `_distance` metrics `{ l2, cosine }`: the selected distance, and the\n * order key of a distance `orderBy`. Drivers that don't support vector\n * operations can override this property with an object that throws\n * FeatureNotSupportedError.\n *\n * Without `order` a metric is the distance VALUE. With it, an order key: an\n * `\"exact\"` key is one no index can serve, so the order is exact whatever\n * index the column has; a `\"servable\"` key is one a nearest-neighbour index\n * may serve, and is approximate where it does.\n */\n vector: {\n /** Create a vector literal from number array: '[1,2,3]'::vector */\n literal: (values: number[]) => Sql;\n /** L2 (Euclidean) distance: column <-> vector */\n l2: (column: Sql, vector: Sql, order?: VectorOrderKey) => Sql;\n /** Cosine distance: column <=> vector */\n cosine: (column: Sql, vector: Sql, order?: VectorOrderKey) => 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 /**\n * The periods of a `by` member grouped by a time step. Absence means this\n * adapter groups by no time step, and the engine refuses such a call before\n * any statement is sent.\n */\n readonly period?: PeriodSql;\n\n /**\n * The statement that recomputes the materialized view stored as `table`\n * (`$refresh()`), `concurrently` without blocking its readers. Absence\n * means this database stores no view's rows: a materialized view is an\n * ordinary one there, and `$refresh()` sends nothing.\n */\n readonly refresh?: (table: string, concurrently: boolean) => Sql;\n\n /**\n * The statements that recompute a view kept by triggers (`refresh: \"auto\"`)\n * from its body view, run atomically by `$refresh()`. Absence means the\n * database keeps the view itself (SurrealDB) and `$refresh()` sends nothing.\n */\n readonly refreshAuto?: (\n table: string,\n body: string,\n source: string,\n keyColumn: string\n ) => Sql[];\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 { 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\n/**\n * A statement's clauses, each word before its operand, as ONE fragment: a\n * fragment per clause and their join were up to seven more for every SELECT\n * the engine assembles, each made here and walked again where the statement\n * is rendered (2 % to 4 % of a read's client CPU).\n */\ninterface Clauses {\n readonly strings: string[];\n readonly values: Sql[];\n}\n\nconst clause = (into: Clauses, word: string, operand: Sql): void => {\n into.strings.push(word);\n into.values.push(operand);\n};\n\n/**\n * A SELECT's clauses, begun with room for the ones it takes next. A list of\n * two members that takes a third by `push` is copied into a store of\n * nineteen: 240 bytes more for every SELECT the engine assembles, seven of\n * them in a read of two relation levels. The lists are written longer and cut\n * back, which keeps their store, so a WHERE, an ORDER BY, a LIMIT and an\n * OFFSET land in place.\n */\nconst begun = (first: string, second: string, a: Sql, b: Sql): Clauses => {\n const strings = [first, second, \"\", \"\", \"\", \"\", \"\", \"\"];\n const values = [a, b, a, a, a, a];\n strings.length = 2;\n values.length = 2;\n return { strings, values };\n};\n\nconst closed = (clauses: Clauses, last = \"\"): Sql => {\n clauses.strings.push(last);\n return new Sql(clauses.strings, clauses.values);\n};\n\n/** `distinctOn`: the columns of PostgreSQL's `DISTINCT ON`, where the page is one. */\nexport const assembleSelectQuery = (\n parts: QueryParts,\n options: SelectAssemblyOptions,\n distinctOn?: Sql\n): Sql => {\n const query: Clauses = distinctOn\n ? {\n strings: [\"SELECT DISTINCT ON (\", \") \", \" FROM \"],\n values: [distinctOn, parts.columns, parts.from],\n }\n : begun(\"SELECT \", \" FROM \", parts.columns, parts.from);\n\n appendFilterParts(query, parts);\n\n if (parts.orderBy) {\n clause(query, \" ORDER BY \", parts.orderBy);\n }\n\n appendLimitOffset(query, parts.limit, parts.offset, options.noLimitValue);\n\n return closed(\n query,\n options.forUpdate === \"append\" && parts.forUpdate ? \" FOR UPDATE\" : \"\"\n );\n};\n\n/** Joins, WHERE, GROUP BY and HAVING: shared by the plain and the emulated-DISTINCT select. */\nconst appendFilterParts = (into: Clauses, parts: QueryParts): void => {\n if (parts.joins) {\n for (const join of parts.joins) clause(into, \" \", join);\n }\n\n if (parts.where) {\n clause(into, \" WHERE \", parts.where);\n }\n\n if (parts.groupBy) {\n clause(into, \" GROUP BY \", parts.groupBy);\n }\n\n if (parts.having) {\n clause(into, \" HAVING \", parts.having);\n }\n};\n\nconst appendLimitOffset = (\n into: Clauses,\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n clause(into, \" LIMIT \", limit);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n clause(into, \" LIMIT \", noLimitValue);\n }\n\n if (offset) {\n clause(into, \" OFFSET \", offset);\n }\n};\n\n/**\n * Simulate `SELECT DISTINCT ON` using one ROW_NUMBER() window.\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 * order_term_1 AS _ord0, ... -- only when ORDER BY present\n * ROW_NUMBER() OVER (PARTITION BY distinct_cols ORDER BY order_cols) AS _rn\n * FROM table\n * WHERE ...\n * ) AS _distinct_subquery\n * WHERE _rn = 1\n * ORDER BY _ord0, ...\n * LIMIT ... OFFSET ...\n *\n * The outer ORDER BY reads the projected `_ordN` terms because the user's\n * ORDER BY references inner table aliases (and relation-order joins) that\n * are out of scope outside the subquery. Ordering the kept rows by those\n * values (and not by a second window ranking every row) spares one sort.\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 const order = parts.distinctOrder;\n\n const selectColumns: Sql[] = [parts.columns];\n if (order) {\n selectColumns.push(order.keys);\n }\n selectColumns.push(\n sql`ROW_NUMBER() OVER (PARTITION BY ${distinct} ORDER BY ${rowNumberOrder}) AS ${escapeIdentifier(\"_rn\")}`\n );\n\n // Inner query with ROW_NUMBER()\n const inner: Clauses = {\n strings: [\"SELECT \", \" FROM \"],\n values: [sql.join(selectColumns, \", \"), parts.from],\n };\n\n appendFilterParts(inner, parts);\n\n const innerQuery = closed(inner);\n\n // Outer query that filters for first row of each partition. It names the\n // output columns so _rn/_ordN stay inside: every engine DISTINCT carrier\n // states its aliases.\n const aliasColumns = parts.distinctColumnAliases!.map(escapeIdentifier);\n const outer: Clauses = {\n strings: [\"\"],\n values: [\n sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")} WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ],\n };\n\n if (order) {\n clause(outer, \" ORDER BY \", order.orderBy);\n }\n\n appendLimitOffset(outer, parts.limit, parts.offset, noLimitValue);\n\n return closed(outer);\n};\n"],"mappings":"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"}
@@ -0,0 +1,7 @@
1
+ import{t as e}from"./migrations-DIUltjr3.mjs";import{a as t,m as n}from"./validation-ATmgN5RE.mjs";import{t as r}from"./sql-tegqTqGq.mjs";import{o as i}from"./value-guards-CBVIJXlI.mjs";import{Ft as a,gt as o,i as s,pt as c,r as l,t as u,vt as d,zt as f}from"./model-ByktcCGW.mjs";import{p,x as m}from"./datetime-values-D_G6m5_o.mjs";import{n as h,t as g}from"./facts-Bjnzv3j-.mjs";import{i as _}from"./keys-o4Pl6Vsg.mjs";import{E as v,T as y,n as b,t as x,y as S}from"./schema-BzkBJTF-.mjs";import{K as C,N as w,W as T}from"./query-DSEMPA7r.mjs";import{c as E}from"./time-step-BIdl2Iy7.mjs";import{r as D}from"./validation-CEnhYqhl.mjs";import{c as O,d as k,h as ee,l as te,n as A,p as j,u as M}from"./validator-CISkL46K.mjs";import{t as N}from"./physical-BheMRPY0.mjs";import{t as ne}from"./auto-names-GpcDfhaw.mjs";import{n as re,r as ie,t as ae}from"./provider-limits-DvcCUw7l.mjs";import{t as oe}from"./json-parameter-DtHhEfyE.mjs";import{In as se,Nn as ce,Tn as le,W as ue,Yt as de,_n as fe,c as pe,l as P,nn as me,t as he,tn as ge,vn as _e,zn as ve}from"./push-fingerprint-CegYVFFp.mjs";import{c as F,i as ye,n as be,s as xe}from"./identity-nPArhpsD.mjs";import{a as Se}from"./geo-point-DCV0eO1p.mjs";import{n as Ce,o as we}from"./decimal-D4DRlT2y.mjs";import{a as Te,c as Ee}from"./type-mapping-BYre7JQ1.mjs";import{t as De}from"./array-literal-U6SeastY.mjs";import{t as Oe}from"./light-reLULeHN.mjs";const ke=/^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/,Ae=/[A-Za-z_]/,je=/[A-Za-z0-9_$]/,Me=/^[a-z_][a-z0-9_$]*$/,Ne=/\s/;function Pe(e,t){return{...e,tables:t.type===`renameTable`?Fe(e.tables,t.from,t.to):Ie(e.tables,t.tableName,t.from,t.to)}}function Fe(e,t,n){return e.map(e=>({...e,name:e.name===t?n:e.name,foreignKeys:e.foreignKeys.map(e=>e.referencedTable===t?{...e,referencedTable:n}:e)}))}function Ie(e,t,n,r){let i=e=>e===n?r:e;return e.map(e=>{let a=e.name===t;return{...e,columns:a?e.columns.map(e=>e.name===n?{...e,name:r}:e):e.columns,...a&&e.primaryKey?{primaryKey:{...e.primaryKey,columns:e.primaryKey.columns.map(i)}}:{},indexes:a?e.indexes.map(e=>({...e,columns:e.columns.map(i),...e.where===void 0?{}:{where:Le(e.where,n,r)}})):e.indexes,foreignKeys:e.foreignKeys.map(e=>({...e,columns:a?e.columns.map(i):e.columns,referencedColumns:e.referencedTable===t?e.referencedColumns.map(i):e.referencedColumns})),uniqueConstraints:a?e.uniqueConstraints.map(e=>({...e,columns:e.columns.map(i)})):e.uniqueConstraints}})}function Le(e,t,n){let r=``,i=0;for(;i<e.length;){let a=e[i];if(a===`'`){let t=I(e,i,`'`,`'`);r+=e.slice(i,t),i=t;continue}if(a===`"`||a==="`"){let o=I(e,i,a,a);if(e[o-1]!==a){r+=e.slice(i,o),i=o;continue}let s=e.slice(i+1,o-1).replaceAll(`${a}${a}`,a);r+=s===t&&!L(e,i,o)?`${a}${n.replaceAll(a,`${a}${a}`)}${a}`:e.slice(i,o),i=o;continue}if(a===`[`){let a=I(e,i,`]`,`]`);if(e[a-1]!==`]`){r+=e.slice(i,a),i=a;continue}let o=e.slice(i+1,a-1).replaceAll(`]]`,`]`);r+=o===t&&!L(e,i,a)?`[${We(n)}]`:e.slice(i,a),i=a;continue}if(a===`-`&&e[i+1]===`-`){let t=e.indexOf(`
2
+ `,i+2),n=t<0?e.length:t;r+=e.slice(i,n),i=n;continue}if(a===`/`&&e[i+1]===`*`){let t=Re(e,i);r+=e.slice(i,t),i=t;continue}if(a===`$`){let t=ze(e,i);if(t!==void 0){let n=e.indexOf(t,i+t.length),a=n<0?e.length:n+t.length;r+=e.slice(i,a),i=a;continue}}if(Be(a)){let a=i+1;for(;a<e.length&&Ve(e[a]);)a+=1;let o=e.slice(i,a),s=o.toLowerCase(),c=s===`e`&&e[a]===`'`?a:s===`u`&&e[a]===`&`&&e[a+1]===`'`?a+1:void 0;if(c!==void 0){let t=I(e,c,`'`,`'`,!0);r+=e.slice(i,t),i=t;continue}let l=e[a]===`'`||s===`u`&&e[a]===`&`&&e[a+1]===`'`;r+=!(l||L(e,i,a))&&He(o,t)?Ue(n):o,i=a;continue}r+=a,i+=1}return r}function I(e,t,n,r,i=!1){let a=t+1;for(;a<e.length;){if(i&&e[a]===`\\`){a+=2;continue}if(e[a]!==n){a+=1;continue}if(e[a+1]===r){a+=2;continue}return a+1}return e.length}function Re(e,t){let n=t+2,r=1;for(;n<e.length&&r>0;)e[n]===`/`&&e[n+1]===`*`?(r+=1,n+=2):e[n]===`*`&&e[n+1]===`/`?(--r,n+=2):n+=1;return n}function ze(e,t){let n=e.slice(t);return ke.exec(n)?.[0]}function Be(e){return e!==void 0&&Ae.test(e)}function Ve(e){return je.test(e)}function He(e,t){return t===t.toLowerCase()&&e.toLowerCase()===t}function L(e,t,n){let r=n;for(;r<e.length&&Ne.test(e[r]);)r+=1;if(e[r]===`(`||e[r]===`=`&&e[r+1]===`>`)return!0;let i=t-1;for(;i>=0&&Ne.test(e[i]);)--i;if(e[i]===`.`||e[i]===`:`&&e[i-1]===`:`)return!0;let a=i+1;for(;i>=0&&Ve(e[i]);)--i;let o=e.slice(i+1,a).toLowerCase();return o===`as`||o===`collate`}function Ue(e){return Me.test(e)?e:`"${e.replaceAll(`"`,`""`)}"`}function We(e){return e.split(`]`).join(`]]`)}function Ge(e){if(F(e).length<=63)return e;let t=``;for(let n of e){if(F(t+n).length>54)break;t+=n}return`${t}_${xe(F(e)).slice(0,8)}`}function Ke(e,t){return t||`${e}_pkey`}const R={dropView:0,createEnum:1,dropForeignKey:2,dropIndex:3,dropUniqueConstraint:4,dropPrimaryKey:5,dropColumn:6,dropTable:7,createTable:8,renameTable:9,addColumn:10,renameColumn:11,alterColumn:12,addPrimaryKey:13,addUniqueConstraint:14,createIndex:15,addForeignKey:16,alterEnum:1.5,dropEnum:18,createView:19},qe=(R.createIndex+R.addForeignKey)/2;function Je(e){let t=new Set,n=new Set;for(let r of e)r.type===`createIndex`?t.add(r.index.name):r.type===`addUniqueConstraint`?t.add(r.constraint.name):r.type===`addPrimaryKey`&&r.primaryKey.name?t.add(r.primaryKey.name):r.type===`dropColumn`&&n.add(r.tableName);let r=new Set;for(let i of e)i.type===`dropIndex`&&!i.raw&&!t.has(i.indexName)&&!n.has(i.tableName)&&r.add(i);return r}function Ye(t){let n=Je(t),r=e=>n.has(e)?qe:R[e.type],i=t.map((e,t)=>({operation:e,index:t})).sort((e,t)=>r(e.operation)-r(t.operation)),a=i.filter(({operation:e})=>e.type===`renameTable`||e.type===`renameColumn`);if(a.length===0)return i.map(({operation:e})=>e);let o=[],s=new Set,c=new Set,l=t=>{if(!s.has(t.index)){if(c.has(t.index))throw new e(`Migration operations contain a cyclic native rename dependency`,`V11009`);c.add(t.index);for(let e of a){if(e.index===t.index)continue;let n=e.operation,r=t.operation;if(n.type===`renameTable`){if(r.type===`renameColumn`&&e.index>t.index&&a.some(n=>n.index>t.index&&n.index<e.index&&n.operation.type===`renameTable`&&n.operation.from===r.tableName))continue;(r.type===`renameTable`?e.index<t.index&&n.to===r.from:Xe(r,n.to))&&l(e)}else n.type===`renameColumn`&&(r.type===`renameTable`?e.index<t.index&&n.tableName===r.from:r.type===`renameColumn`?e.index<t.index&&n.tableName===r.tableName&&n.to===r.from:Ze(r,n.tableName,n.to))&&l(e)}c.delete(t.index),s.add(t.index),o.push(t.operation)}};for(let e of i)l(e);return o}function Xe(e,t){return e.type===`createTable`?e.table.name===t:e.type===`alterEnum`||e.type===`dropEnum`?e.dependentColumns?.some(e=>e.tableName===t)??!1:`tableName`in e&&e.tableName===t}function Ze(e,t,n){return e.type===`dropIndex`&&e.raw?!1:e.type===`dropIndex`||e.type===`dropUniqueConstraint`||e.type===`dropForeignKey`?e.tableName===t:e.type===`alterEnum`||e.type===`dropEnum`?e.dependentColumns?.some(e=>e.tableName===t&&e.columnName===n)??!1:`tableName`in e&&e.tableName===t&&`columnName`in e&&e.columnName===n}function Qe(e,t){if(!t.capabilities.supportsAddForeignKeyViaAlter)return e;let n=new Map,r=0;for(let t of e)t.type===`createTable`&&(n.set(t.table.name,r),r+=1);let i=[],a=[];for(let t of e){if(t.type!==`createTable`){i.push(t);continue}let e=n.get(t.table.name),r=t.table.foreignKeys.filter(t=>{let r=n.get(t.referencedTable);return!(r!==void 0&&e!==void 0&&r>e)});if(r.length===t.table.foreignKeys.length){i.push(t);continue}let o=t.table.foreignKeys.filter(e=>!r.includes(e));i.push({...t,table:{...t.table,foreignKeys:r}});for(let e of o)a.push({type:`addForeignKey`,tableName:t.table.name,fk:e})}return[...i,...a]}function $e(e,t,n){if(!n.capabilities.supportsAddForeignKeyViaAlter)return e;let r=new Set,i=new Set;for(let t of e)t.type===`dropTable`?r.add(t.tableName):t.type===`dropForeignKey`&&i.add(`${t.tableName} ${t.fkName}`);if(r.size===0)return e;let a=[];for(let e of t.tables)for(let t of e.foreignKeys)(r.has(e.name)||r.has(t.referencedTable))&&!i.has(`${e.name} ${t.name}`)&&a.push({type:`dropForeignKey`,tableName:e.name,fkName:t.name});return a.length===0?e:[...a,...e]}function et(e,t,n,r){return se(ve($e(Qe(e,r),t,r),t),t,n,r.dialect===`sqlite`,r.dialect===`surrealql`)}function tt(e){if(e.length===0)return`empty`;let t=e[0];if(!t)return`migration`;switch(t.type){case`createTable`:return e.length===1?`create-${t.table.name}`:`initial`;case`dropTable`:return`drop-${t.tableName}`;case`addColumn`:return`add-${t.column.name}-to-${t.tableName}`;case`dropColumn`:return`drop-${t.columnName}-from-${t.tableName}`;case`renameTable`:return`rename-${t.from}-to-${t.to}`;case`renameColumn`:return`rename-${t.from}-to-${t.to}`;case`createIndex`:return`add-index-${t.index.name}`;case`dropIndex`:return`drop-index-${t.indexName}`;case`addForeignKey`:return`add-fk-${t.fk.name}`;case`dropForeignKey`:return`drop-fk-${t.fkName}`;case`createEnum`:return`create-enum-${t.enumDef.name}`;case`dropEnum`:return`drop-enum-${t.enumName}`;case`alterEnum`:return`alter-enum-${t.enumName}`;case`createView`:return e.every(e=>e.type===`createView`)?`create-view-${t.view.name}`:`migration`;case`dropView`:return`drop-view-${t.viewName}`;default:return`migration`}}const nt=new WeakMap;function rt(e){return nt.get(e)}function it(e,t){let n=nt.get(e);nt.set(e,n!==void 0&&n.kind!==t.kind?{kind:`mixed`}:t)}function at(e){return{type:`destructive`,...e,proceed:()=>`proceed`,reject:()=>`reject`}}function ot(e){return{type:`ambiguous`,...e,rename:()=>`rename`,addAndDrop:()=>`addAndDrop`,reject:()=>`reject`}}function st(e){let t={type:`enumValueRemoval`,...e,mapValues:e=>{let n={};for(let[t,r]of Object.entries(e))n[t]=r;return Object.freeze(n),it(t,{kind:`mapValues`,mappings:n}),`enumMapped`},useNull:()=>(it(t,{kind:`useNull`}),`enumMapped`),reject:()=>`reject`};return t}function ct(t,n,r){if(r!==void 0){if(r===`reject`||t===`ambiguous`&&(r===`rename`||r===`addAndDrop`)||t===`destructive`&&r===`proceed`)return r;if(t===`enumValueRemoval`&&r===`enumMapped`){let e=rt(n);if(e!==void 0&&e.kind!==`mixed`)return r}throw new e(`Invalid resolution ${typeof r==`string`?`"${r}"`:r===null?`null`:typeof r} for ${t} change; use change helper method.`,`V11009`,{meta:{type:`invalid-resolution-result`}})}}function lt(e,t){return e.type===`ambiguousColumn`?t.type===`rename`?[{type:`renameColumn`,tableName:e.tableName,from:e.np.name,to:e.iu.name}]:[{type:`dropColumn`,tableName:e.tableName,columnName:e.np.name},{type:`addColumn`,tableName:e.tableName,column:e.iu}]:t.type===`rename`?[{type:`renameTable`,from:e.nb,to:e.ou}]:[{type:`dropTable`,tableName:e.nb},{type:`createTable`,table:e.e3}]}async function ut(t,n,r,i,a={}){let o=n,s=t,c=[],l=new Set,u=new Map(n.tables.map(e=>[e.name,e.name]));for(;s.rg.length>0;){let t=await i(s.rg);for(let n of s.rg){let r=dt(n);if(l.has(r))throw new e(`Ambiguous migration change did not converge after resolution: ${r}`,`V9001`);l.add(r);let i=t.get(n);if(!i)throw new e(`Missing resolution for ${Mt(n)}`,`V11010`);let s=lt(n,i);c.push(...s);for(let e of s)if(o=pt(o,e,a.pu),e.type===`renameTable`){let t=u.get(e.from)??e.from;u.delete(e.from),u.set(e.to,t)}else e.type===`dropTable`&&u.delete(e.tableName)}s=await on(o,r,ft(a,u))}return Ye([...c,...s.operations])}function dt(e){return e.type===`ambiguousTable`?`table:${e.nb}\u0000${e.ou}`:`column:${e.tableName}\u0000${e.np.name}\u0000${e.iu.name}`}function ft(e,t){let n=e.om;return n?{...e,om:(e,r)=>n(t.get(e)??e,r)}:e}function pt(e,t,n=Pe){return t.type===`renameTable`||t.type===`renameColumn`?n(e,t):t.type===`dropTable`?{...e,tables:e.tables.filter(e=>e.name!==t.tableName)}:t.type===`createTable`?{...e,tables:[...e.tables,t.table]}:t.type===`dropColumn`?{...e,tables:e.tables.map(e=>e.name===t.tableName?{...e,columns:e.columns.filter(e=>e.name!==t.columnName)}:e)}:t.type===`addColumn`?{...e,tables:e.tables.map(e=>e.name===t.tableName?{...e,columns:[...e.columns,t.column]}:e)}:e}function mt(e){return e.type===`ambiguousColumn`?ot({operation:`renameColumn`,table:e.tableName,column:e.iu.name,oldName:e.np.name,newName:e.iu.name,oldType:e.np.type,newType:e.iu.type,description:`Column "${e.np.name}" → "${e.iu.name}" in table "${e.tableName}" (rename or add+drop?)`}):ot({operation:`renameTable`,table:e.ou,oldName:e.nb,newName:e.ou,description:`Table "${e.nb}" → "${e.ou}" (rename or add+drop?)`})}function ht(t,n){return async r=>{let i=new Map;for(let a of r){let r=mt(a),o=await t(r);if(o===`rename`){i.set(a,{type:`rename`});continue}if(o===`addAndDrop`){i.set(a,{type:`addAndDrop`}),n?.add(gt(a));continue}throw new e(`Unresolved ambiguous change: ${r.description}\nGenerate requires change.rename() or change.addAndDrop() from the resolver.`,`V11010`)}return i}}function gt(e){return e.type===`ambiguousTable`?`table\u0000${e.nb}`:`column\u0000${e.tableName}\u0000${e.np.name}`}function _t(e){return e.type===`dropTable`?`table\u0000${e.tableName}`:e.type===`dropColumn`?`column\u0000${e.tableName}\u0000${e.columnName}`:``}async function vt(t,n,r,i=new Set){let a=t.filter(e=>e.type!==`alterEnum`&&sn(e)),o=a.map(yt),s=o.map(({column:e,...t})=>at(e===null?t:{...t,column:e}));if(!n&&s.length>0)throw new e(`Destructive changes need approval:\n${s.map(e=>`- ${e.description}`).join(`
3
+ `)}\n\nPass resolve returning change.proceed() or change.reject().`,`V11017`,{meta:{hint:`Pass resolve returning change.proceed().`}});for(let[t,o]of s.entries())if(!i.has(_t(a[t]))){let t=ct(`destructive`,o,await n?.(o));if(t===`reject`)throw new e(`Change rejected: ${o.description}`,`V11010`);if(t===void 0&&!r)throw new e(`Unresolved destructive change: ${o.description}\nReturn change.proceed() or change.reject() from the resolver.`,`V11010`)}return o.map(({operation:e,table:t,column:n})=>({operation:e,table:t,column:n}))}function yt(t){switch(t.type){case`dropTable`:return{operation:`dropTable`,table:t.tableName,column:null,description:`Drop table "${t.tableName}" (all data will be lost)`};case`dropColumn`:return{operation:`dropColumn`,table:t.tableName,column:t.columnName,description:`Drop column "${t.columnName}" from table "${t.tableName}" (data will be lost)`};case`addColumn`:return{operation:`addColumn`,table:t.tableName,column:t.column.name,description:`Add required column "${t.tableName}.${t.column.name}" without a backfill default (fails on populated tables)`};case`alterColumn`:return{operation:`alterColumn`,table:t.tableName,column:t.columnName,description:cn([t]).join(`; `)};default:throw new e(`Unexpected operation type: ${t.type}`,`V9001`)}}const bt=async e=>{let t=new Map;for(let n of e)t.set(n,{type:`addAndDrop`});return t},xt=async t=>{if(t.length>0)throw new e(`Ambiguous changes detected that require resolution:\n${t.map(e=>e.type===`ambiguousColumn`?`Column "${e.np.name}" was removed and "${e.iu.name}" was added in table "${e.tableName}"`:`Table "${e.nb}" was removed and "${e.ou}" was added`).join(`
4
+ `)}\n\nSupply a resolve callback choosing rename() or addAndDrop() for each change.`,`V11010`);return new Map},St={column:[`type`,`tableName`,`from`,`to`,`resolution`],table:[`type`,`from`,`to`,`resolution`],enumValueRemoval:[`type`,`tableName`,`columnName`,`mapValues`],destructive:[`type`,`operation`,`table`,`column`]},Ct=Object.keys(St),wt=[...new Set(Object.values(St).flat())],Tt=[`rename`,`addAndDrop`],Et=new WeakMap;function Dt(e){let t=fe(e,`decisions`,z).map(At),n=new Set,r=e=>{for(let r of t){let t=kt(r,e);if(t!==void 0)return n.add(r),t}};return Et.set(r,{decisions:t,used:n}),r}function Ot(e){let t=e&&Et.get(e);if(!t)return;let n=t.decisions.filter(e=>!t.used.has(e));t.used.clear(),n.length>0&&z(`Unused decisions match no change: ${JSON.stringify(n)}`)}function kt(e,t){switch(e.type){case`destructive`:return t.type===`destructive`&&t.operation===e.operation&&t.table===e.table&&(t.column??null)===e.column?t.proceed():void 0;case`enumValueRemoval`:return t.type===`enumValueRemoval`&&t.tableName===e.tableName&&t.columnName===e.columnName?t.mapValues(e.mapValues):void 0;default:return t.type===`ambiguous`&&t.oldName===e.from&&t.newName===e.to&&(e.type===`table`?t.operation===`renameTable`:t.operation===`renameColumn`&&t.table===e.tableName)?e.resolution===`rename`?t.rename():t.addAndDrop():void 0}}function At(e,t){let n=`decisions[${t}]`,r=_e(e,wt,n,z),i=Ct.find(e=>e===r.type)??z(`${n}.type must be one of ${Ct.join(`, `)}`),a=_e(r,St[i],n,z),o=e=>{let t=a[e];return typeof t==`string`?t:z(`${n}.${e} must be a string`)},s=()=>Tt.find(e=>e===a.resolution)??z(`${n}.resolution must be rename or addAndDrop`);switch(i){case`column`:return{type:i,tableName:o(`tableName`),from:o(`from`),to:o(`to`),resolution:s()};case`table`:return{type:i,from:o(`from`),to:o(`to`),resolution:s()};case`enumValueRemoval`:return{type:i,tableName:o(`tableName`),columnName:o(`columnName`),mapValues:jt(a.mapValues,`${n}.mapValues`)};default:return{type:i,...de(a,n,z)}}}function jt(e,t){if(!i(e))return z(`${t} must be an object`);let n={};for(let[r,i]of Object.entries(e))typeof i==`string`||i===null||z(`${t}.${r} must be a string or null`),n[r]=i;return Object.freeze(n)}function z(t,n){throw new e(t,`V4002`,{cause:n})}function Mt(e){return e.type===`ambiguousColumn`?`Column rename detected in table "${e.tableName}":\n "${e.np.name}" (${e.np.type}) → "${e.iu.name}" (${e.iu.type})`:`Table rename detected:
5
+ "${e.nb}" → "${e.ou}"`}const Nt=async e=>e.reject(),Pt=async e=>e.type===`destructive`?e.proceed():e.type===`ambiguous`?e.operation===`renameColumn`?e.rename():void 0:e.useNull(),Ft=async e=>e.type===`destructive`?e.proceed():e.type===`ambiguous`?e.addAndDrop():e.useNull(),It=/^(?:enum\(|text check\("(?:[^"]|"")*"\s+in\s+\()(\s*'(?:[^']|'')*'(?:\s*,\s*'(?:[^']|'')*')*\s*)\)\)?$/i;function Lt(e){let t=It.exec(e.trim());if(t?.[1])return e.trim().toLowerCase().startsWith(`enum(`)?Te(e)??void 0:Array.from(t[1].matchAll(/'((?:[^']|'')*)'/g),e=>e[1].replaceAll(`''`,`'`))}function Rt(t,n){let r=[];for(let i of t)if(i.type===`alterEnum`&&i.removeValues&&i.removeValues.length>0){let t=i.removeValues.filter(e=>{let t=i.valueReplacements!==void 0&&e in i.valueReplacements,n=i.defaultReplacement!==void 0;return!(t||n)});if(t.length>0){let a=i.dependentColumns||[];for(let o of a){let a=n.tables.find(e=>e.name===o.tableName);if(!a)throw new e(`Table "${o.tableName}" not found in current schema for enum "${i.enumName}"`,`V9001`);let s=a.columns.find(e=>e.name===o.columnName);if(!s)throw new e(`Column "${o.columnName}" not found in table "${o.tableName}" for enum "${i.enumName}"`,`V9001`);r.push({enumName:i.enumName,tableName:o.tableName,columnName:o.columnName,isNullable:s.nullable,removedValues:t,availableValues:i.newValues||[]})}}}return r}function zt(e,t){if(t.length===0)return e;let n=new Map;for(let e of t){let t=n.get(e.enumName)||[];t.push(e),n.set(e.enumName,t)}return e.map(e=>{if(e.type!==`alterEnum`||!e.removeValues)return e;let t=n.get(e.enumName);if(!t||t.length===0)return e;let r={...e.columnValueReplacements};for(let e of t){let t=Ht(e);r[t]={...r[t],...V(e.removedValues)}}return{...e,columnValueReplacements:r}})}async function Bt(t,n,r){let i=new Map;for(let a of t){let t=st({enumName:a.enumName,tableName:a.tableName,columnName:a.columnName,isNullable:a.isNullable,removedValues:a.removedValues,availableValues:a.availableValues,description:`Column "${a.tableName}.${a.columnName}" uses enum "${a.enumName}" - removing values: ${a.removedValues.join(`, `)}. Map to: ${a.availableValues.join(`, `)} or NULL`}),o=ct(`enumValueRemoval`,t,await n(t));if(o===`reject`)throw new e(`Change rejected: ${t.description}`,`V11010`);let s=Ht(a);if(o===void 0){if(r)B(i,a.enumName,s,V(a.removedValues));else throw new e(`Unresolved enum value removal: ${t.description}\nReturn change.mapValues() or change.useNull() from the resolver.`,`V11010`);continue}if(o===`enumMapped`){let e=rt(t);e?.kind===`mapValues`?B(i,a.enumName,s,e.mappings):e?.kind===`useNull`&&B(i,a.enumName,s,V(a.removedValues))}}return i}function Vt(e,t){let n=[];for(let r of e)if(r.type===`alterEnum`){let e=t.get(r.enumName);if(e&&e.size>0){let t={...r.columnValueReplacements};for(let[n,r]of e)t[n]={...t[n],...r};n.push({...r,columnValueReplacements:t})}else n.push(r)}return n}function B(e,t,n,r){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(n,r)}function V(e){let t={};for(let n of e)t[n]=null;return t}function Ht(e){return`${e.tableName}.${e.columnName}`}const Ut=new Map;function H(e,t){return`${e}\u0000${t}`}async function Wt(e,t,n){if(!n)return Ut;let r=new Map;for(let[i,a]of t){let t=e.get(i);if(!t)continue;let o=new Map((t.indexes??[]).map(e=>[e.name,e])),s=new Set;for(let e of a.indexes??[]){let t=o.get(e.name);if(!t)continue;let n=U(t.where),r=U(e.where);n===void 0||r===void 0||n===r||(s.add(n),s.add(r))}if(s.size===0)continue;let c=[...s],l=await n(i,c);for(let[e,t]of c.entries()){let n=l[e];n!==void 0&&r.set(H(i,t),n)}}return r}function Gt(e,t,n){return P(e.type)===P(t.type)&&e.nullable===t.nullable&&pe(e.default,e.type)===pe(t.default,t.type)&&Se(e)===Se(t)&&m(e.decimal,t.decimal)&&(!n||e.dateTime===t.dateTime)}function Kt(e,t,n){return e.name===t.name&&Gt(e,t,n)}function qt(e,t){if(P(e.type)===P(t.type))return!0;let n=we(e);return n!==void 0&&n===we(t)}function Jt(e){return e??`btree`}function Yt(e){return e??!1}function U(e){return e?.trim()||void 0}function Xt(e,t,n,r){let i=U(t.where),a=U(n.where);if(i===a)return!0;if(i===void 0||a===void 0)return!1;let o=r.get(H(e,i)),s=r.get(H(e,a));return o!==void 0&&o===s}function Zt(e,t,n,r){return t.raw||n.raw?t.name===n.name&&t.raw?.hash===n.raw?.hash&&W(t.columns,n.columns):t.name===n.name&&Yt(t.unique)===Yt(n.unique)&&W(t.columns,n.columns)&&Jt(t.type)===Jt(n.type)&&Xt(e,t,n,r)}function W(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}function Qt(e){return e??`noAction`}function G(e){return[e.columns.join(`\0`),e.referencedTable,e.referencedColumns.join(`\0`),Qt(e.onDelete),Qt(e.onUpdate)].join(``)}function K(e){return e.columns.join(`\0`)}function $t(e,t,n){let r=new Map;for(let[e,i]of t.entries()){let t=n(i),a=r.get(t);a?a.push(e):r.set(t,[e])}let i=new Set;return{matches:e.map(e=>{let a=r.get(n(e))?.shift();if(a!==void 0)return i.add(a),t[a]}),jx:t.filter((e,t)=>!i.has(t))}}function q(e,t,n,r,i,a){let{matches:o,jx:s}=$t(e,t,n);return[...e.flatMap((e,t)=>{let n=o[t];return n===void 0?[i(e)]:r(e,n)?[]:[i(e),a(n)]}),...s.map(a)]}function en(e,t,n,r){return q(t,n,e=>e.name,(t,n)=>Zt(e,t,n,r),t=>({type:`dropIndex`,tableName:e,indexName:t.name,...t.raw?{raw:!0}:{}}),t=>({type:`createIndex`,tableName:e,index:t}))}function tn(e,t){return e.name===t.name&&W(e.values,t.values)}function nn(t,n,r){throw new e(`Constraint "${t}.${n}" enforces "${r}" under different name; rename or drop first.`,`V8001`,{meta:{table:t,constraint:n}})}function rn(e,t,n,r){for(let i of n){if(t.some(e=>e.name===i.name))continue;let n=t.find(e=>r(e)===r(i));n&&nn(e,n.name,i.name)}}function an(e,t,n,r,i,a,o,s){let c=[],l=[];if(!i&&o){rn(e,t.foreignKeys,n.foreignKeys,G),rn(e,t.uniqueConstraints,n.uniqueConstraints,K);let r=t.primaryKey,i=n.primaryKey;if(r&&i&&W(r.columns,i.columns)){let t=r.name??`${e}_pkey`,n=i.name??`${e}_pkey`;t!==n&&nn(e,t,n)}}let u=new Map(t.columns.map(e=>[e.name,e])),d=new Map(n.columns.map(e=>[e.name,e])),f=[],p=[];for(let[e,t]of u)d.has(e)||f.push(t);for(let[e,t]of d)u.has(e)||p.push(t);let m=new Set,h=new Set,g=(n,r)=>s?.({tables:[t]},{type:`renameColumn`,tableName:e,from:n.name,to:r.name}).tables[0]?.columns.find(e=>e.name===r.name)??n;for(let t of f)for(let n of p)m.has(t.name)||h.has(n.name)||qt(g(t,n),n)&&(l.push({type:`ambiguousColumn`,tableName:e,np:t,iu:n}),m.add(t.name),h.add(n.name));for(let t of f)m.has(t.name)||c.push({type:`dropColumn`,tableName:e,columnName:t.name});for(let t of p)h.has(t.name)||c.push({type:`addColumn`,tableName:e,column:t});for(let[t,n]of d){let r=u.get(t);if(r&&!Kt(r,n,a)){let i=Lt(r.type),o=Lt(n.type);if(i&&o&&P(r.type)!==P(n.type)){c.push({type:`alterEnum`,enumName:n.type,newValues:o,addValues:o.filter(e=>!i.includes(e)),removeValues:i.filter(e=>!o.includes(e)),dependentColumns:[{tableName:e,columnName:t}]});let s={...r,type:n.type};Gt(s,n,a)||c.push({type:`alterColumn`,tableName:e,columnName:t,from:s,to:n})}else c.push({type:`alterColumn`,tableName:e,columnName:t,from:r,to:n})}}c.push(...en(e,t.indexes,n.indexes,r),...q(t.foreignKeys,n.foreignKeys,i?G:e=>e.name,(e,t)=>G(e)===G(t),t=>({type:`dropForeignKey`,tableName:e,fkName:t.name}),t=>({type:`addForeignKey`,tableName:e,fk:t})),...q(t.uniqueConstraints,n.uniqueConstraints,i?K:e=>e.name,(e,t)=>K(e)===K(t),t=>({type:`dropUniqueConstraint`,tableName:e,constraintName:t.name}),t=>({type:`addUniqueConstraint`,tableName:e,constraint:t})));let _=t.primaryKey,v=n.primaryKey;return _&&!v?c.push({type:`dropPrimaryKey`,tableName:e,constraintName:_.name||`${e}_pkey`}):!_&&v?c.push({type:`addPrimaryKey`,tableName:e,primaryKey:v}):_&&v&&(!W(_.columns,v.columns)||_.withoutRowid!==v.withoutRowid)&&(c.push({type:`dropPrimaryKey`,tableName:e,constraintName:_.name||`${e}_pkey`}),c.push({type:`addPrimaryKey`,tableName:e,primaryKey:v})),{operations:c,rg:l}}async function on(t,n,r={}){let i=he(t),a=he(n),o=[],s=[];for(let t of i.polymorphicStorage??[]){let n=a.polymorphicStorage?.find(e=>e.ownerTable===t.ownerTable&&e.relation===t.relation&&e.kind===t.kind);if(n)for(let r of t.members){let i=n.members.find(e=>e.publicType===r.publicType);if(i&&(i.storedType!==r.storedType||i.targetTable!==r.targetTable))throw new e(`Polymorphic "${t.ownerTable}.${t.relation}" changes "${r.publicType}" mapping; author manual transition.`,`V11010`)}}let c=new Map(i.tables.map(e=>[e.name,e])),l=new Map(a.tables.map(e=>[e.name,e])),u=new Map((i.views??[]).map(e=>[e.name,e])),d=new Map((a.views??[]).map(e=>[e.name,e])),f=[...d.keys()].filter(e=>{let t=d.get(e),n=u.get(e);return n?.hash===t.hash&&ce(n,t)}),p=await Wt(new Map([...c,...f.map(e=>[e,u.get(e)])]),new Map([...l,...f.map(e=>[e,d.get(e)])]),r.om),m=[],h=[];for(let[e]of c)l.has(e)||m.push(e);for(let[e]of l)c.has(e)||h.push(e);let g=new Set,_=new Set,v=m.flatMap(e=>{let t=c.get(e);return h.map(n=>{let r=l.get(n);return{s9:e,l7:n,nb:t,ou:r,yv:t.columns.filter(e=>r.columns.some(t=>Kt(e,t,!0))).length,km:t.columns.filter(e=>r.columns.some(t=>e.name===t.name)).length}})}).sort((e,t)=>t.km-e.km||t.yv-e.yv);for(let e of v){let{s9:t,l7:n,nb:r,ou:i}=e;g.has(t)||_.has(n)||(s.push({type:`ambiguousTable`,nb:t,ou:n,c3:r,e3:i}),g.add(t),_.add(n))}for(let e of m)g.has(e)||o.push({type:`dropTable`,tableName:e});for(let e of h)if(!_.has(e)){let t=l.get(e);o.push({type:`createTable`,table:t})}for(let[e,t]of l){let n=c.get(e);if(n){let i=an(e,n,t,p,r.lx??!1,r.ge??!1,r.ib??!1,r.pu);o.push(...i.operations),s.push(...i.rg)}}if(i.enums||a.enums){let e=new Map((i.enums||[]).map(e=>[e.name,e])),t=new Map((a.enums||[]).map(e=>[e.name,e])),n=e=>{let t=i.tables.flatMap(t=>t.columns.flatMap(n=>n.type===e||n.type===`${e}[]`?[{tableName:t.name,columnName:n.name}]:[]));return t.length>0?t:void 0};for(let[r]of e)t.has(r)||o.push({type:`dropEnum`,enumName:r,dependentColumns:n(r)});for(let[n,r]of t)e.has(n)||o.push({type:`createEnum`,enumDef:r});for(let[r,i]of t){let t=e.get(r);if(t&&!tn(t,i)){let e=i.values.filter(e=>!t.values.includes(e)),a=t.values.filter(e=>!i.values.includes(e));(e.length>0||a.length>0||!W(t.values,i.values))&&o.push({type:`alterEnum`,enumName:r,addValues:e.length>0?e:void 0,removeValues:a.length>0?a:void 0,newValues:i.values,dependentColumns:n(r)})}}}for(let[e,t]of u)f.includes(e)||o.push(le(t));for(let[e,t]of d)f.includes(e)||o.push({type:`createView`,view:t});for(let e of f)o.push(...en(e,u.get(e).indexes??[],d.get(e).indexes??[],p));return{operations:Ye(o.map(e=>{if(e.type===`createTable`)return{...e,table:n.tables.find(t=>t.name===e.table.name)??e.table};if(e.type===`addUniqueConstraint`){let t=n.tables.find(t=>t.name===e.tableName)?.indexes.find(t=>t.name===e.constraint.name);if(t)return{type:`createIndex`,tableName:e.tableName,index:t}}if(e.type===`dropUniqueConstraint`){let n=t.tables.find(t=>t.name===e.tableName)?.indexes.find(t=>t.name===e.constraintName);if(n)return{type:`dropIndex`,tableName:e.tableName,indexName:n.name}}return e})),rg:s}}function sn(e){return e.type===`alterEnum`?(e.removeValues?.length??0)>0:e.type===`addColumn`?!e.column.nullable&&e.column.default===void 0:e.type===`dropTable`||e.type===`dropColumn`?!0:e.type===`alterColumn`&&(P(e.from.type)!==P(e.to.type)||e.from.nullable&&!e.to.nullable||Ce(e.from,e.to))}function cn(e){let t=[];for(let n of e)if(n.type===`alterColumn`){let e=`"${n.tableName}"."${n.columnName}"`;P(n.from.type)!==P(n.to.type)&&t.push(`Change type of ${e} from ${n.from.type} to ${n.to.type} (may lose data)`),n.from.nullable&&!n.to.nullable&&t.push(`Make ${e} NOT NULL (fails if NULLs exist)`),n.from.decimal&&n.to.decimal&&Ce(n.from,n.to)&&t.push(`Narrow ${e} from ${p(n.from.decimal)} to ${p(n.to.decimal)}`)}return t}function J(e,t,n){switch(e.kind){case`and`:case`or`:for(let r of e.predicates)J(r,t,n);return;case`not`:J(e.predicate,t,n);return;case`always`:return;case`operation`:{let t=[...e.az?[e.az]:[],...e.operands??[]];(e.value instanceof r||t.some(e=>e.kind===`sql`||e.kind===`parameter`||e.kind===`value`&&e.value instanceof r))&&n(`filters with an SQL fragment`,`a view's query holds plain values, which its migration writes as literals`);return}default:n(`filters through a relation`,t.stale)}}function ln(e,t,n,r,i){let{documents:a,ty:o}=h(e);t.cursor!==void 0&&i(`pages from a cursor`,`a paging anchor is not a row set`),t.take!==void 0&&i(`takes a window`,r.unordered),t.skip!==void 0&&i(`skips rows`,r.unordered),t.orderBy!==void 0&&i(`orders its rows`,r.unordered),t.distinct!==void 0&&i(`keeps one row per distinct value`,r.distinct),t.having!==void 0&&i(`keeps the groups a having holds`,r.unfiltered);let[s]=a;s!==void 0&&i(`selects '${s}' through a relation`,r.stale);for(let e of Object.values(o?.origins??{}))e.step!==void 0&&i(`groups by a time step`,r.noStep);n!==void 0&&J(n,r,i)}const un={postgresql:`PostgreSQL`,mysql:`MySQL`,sqlite:`SQLite`},dn=/'/g,fn=/[\\\n\r]/,pn=/[\\\n\r]/g,mn={"\\":`\\\\`,"\n":`\\n`,"\r":`\\r`},hn=/\r|\n/,gn=/(\r|\n)/,_n=/^-?\d+$/,vn=e=>e instanceof Date?`Date`:Array.isArray(e)?`array`:e instanceof oe?`JsonParameter`:typeof e;function yn(e,t){let r=vn(t);throw new n(`A view body binds a value of kind "${r}", which has no ${un[e]} literal: no read of this dialect binds one.`,{meta:{dialect:e,feature:`view literal`,type:r}})}function bn(e){throw new n(`A view body binds a string holding a NUL character, which a ${un[e]} string literal cannot hold.`,{meta:{dialect:e,feature:`view literal`,type:`string`}})}const xn=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),Sn=e=>typeof e==`string`||typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`;function Y(e){e.includes(`\0`)&&bn(`postgresql`);let t=e.replace(dn,`''`);return fn.test(e)?`E'${t.replace(pn,e=>mn[e])}'`:`'${t}'`}function Cn(e){return e===null?`NULL`:typeof e==`string`?Y(e):typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`?Y(String(e)):e instanceof Uint8Array?`${Y(`\\x${xn(e)}`)}::bytea`:e instanceof oe?Y(e.json):Array.isArray(e)&&e.every(Sn)?Y(De(e)):yn(`postgresql`,e)}function wn(e){return e===null?`NULL`:typeof e==`string`?Ee(e):typeof e==`number`||typeof e==`bigint`?String(e):typeof e==`boolean`?e?`TRUE`:`FALSE`:e instanceof Uint8Array?`X'${xn(e)}'`:yn(`mysql`,e)}const Tn=e=>e.startsWith(`-`)?`(${e})`:e,En=e=>`'${e.replace(dn,`''`)}'`;function Dn(e){if(e===null)return`NULL`;if(typeof e==`string`)return e.includes(`\0`)&&bn(`sqlite`),hn.test(e)?`(${e.split(gn).filter(e=>e!==``).map(e=>e===`\r`?`char(13)`:e===`
6
+ `?`char(10)`:En(e)).join(` || `)})`:En(e);if(typeof e==`number`){let t=String(e);return Tn(_n.test(t)?`${t}.0`:t)}return typeof e==`bigint`?Tn(String(e)):typeof e==`boolean`?e?`1.0`:`0.0`:e instanceof Uint8Array?`X'${xn(e)}'`:yn(`sqlite`,e)}const On={postgresql:Cn,mysql:wn,sqlite:Dn};function kn(e,t){let n=On[e],{strings:i,values:a}=r.peek(t),o=i[0];for(let[e,t]of a.entries())o+=n(t)+i[e+1];return o}const An=/\.$/,jn={purpose:`root`,unique:!0};function X(e,t,r){throw new n(`View '${e}' cannot ${t}: ${r}.`,{meta:{model:e,feature:t}})}function Mn(e,t){if(t.cursor!==void 0&&X(e,`page from cursor`,`not a row set`),t.take!==void 0&&t.take<0&&X(e,`take negative window`,`not a row set`),t.take===void 0&&t.orderBy!==void 0&&X(e,`order without take`,`views are unordered`),t.take===void 0&&t.skip!==void 0&&X(e,`skip without take`,`views are unordered`),t.orderBy!==void 0)for(let n of b(t.orderBy))for(let t of Object.values(n))i(t)&&t._distance!==void 0&&X(e,`order by distance`,`binds per-call value`)}var Nn=class extends ie{#e;#t;#n;#r;unordered=!1;constructor(e,t,n,r){super(e,t),this.#e=S(n),this.#t=n,this.#n=r}ub(){return this.#r=super.ub(),this.#r}nd(e,t,n=!1){if(t===void 0||t!==this.#r)return super.nd(e,t,n);w(e)&&X(this.#e,`read recursive or polymorphic relation`,`decoding may refuse rows`);let{model:r}=e,i=[];for(let n of e.fields)n.kind===`distance`&&X(this.#e,`select distance`,`binds per-call value`),i.push(n.kind===`scalar`?this.adapter.identifiers.aliased(this.column(r,n.name,t),this.columnName(r,n.name)):super.nd({...e,fields:[n]},t)[0]);return i}pC(e,t,n){return n!==void 0&&n===this.#r?this.column(e,t,n):super.pC(e,t,n)}qk(e,t,n){let r=h(this.#t)?.ty;return n!==this.#r||r===void 0?super.qk(e,t,n):Object.entries(r.origins).flatMap(([t,{aggregate:r,field:i}])=>r===void 0?[]:[[t,this.#i(e,r,i,n,t)]])}#i(e,t,n,r,i){let a=this.adapter,o=n===void 0?void 0:this.column(e,n,r),s=n===void 0?void 0:y(e)[n]?.[`~`].state;if(t===`_min`||t===`_max`){let{id:r}=this.leaf(e,n),i=T(a,r,o),c=s?.type===`boolean`,l=t===`_min`?a.aggregates.min(i,c):a.aggregates.max(i,c);return C(r)?a.expressions.idCast(l,r.representation):l}let c=t===`_count`?a.aggregates.count(o):t===`_sum`?a.aggregates.sum(o):s?.decimal===void 0?a.aggregates.avg(o):a.aggregates.decimalAvg(o,s.decimal);return this.#n.e2(c,y(this.#t)[i])}a4(...e){return this.unordered?[]:super.a4(...e)}ue(e){return X(this.#e,`filter with SQL fragment`,`views admit literals only`)}};const Pn={stale:`triggers only track source table writes`,unordered:`triggers recompute on unordered rows`,distinct:`triggers require one row per source row`,unfiltered:`triggers do not filter groups`,noStep:`triggers key groups by stored columns`};function Fn(e,t,n,r){let i=S(e),a=(e,t)=>X(i,e,t),o=v(e);o.length>ne&&a(`use name '${o}' (> ${ne} chars)`,`exceeds 63-byte limit`),h(t)!==void 0&&a(`read view '${S(t)}'`,`triggers require a base table`),ln(e,n,n.where===void 0?void 0:r.tm(t,n.where).predicate,Pn,a);let{columns:s,ty:c}=h(e);if(c===void 0){_(t).addressableKeys.find(e=>e.kind===`primary`)?.fields.every(e=>s.includes(e))||a(`omit primary key of '${S(t)}'`,`triggers locate rows by primary key`);return}let l=c.by.find(e=>c.scalars[e]?.[`~`].state.nullable);l!==void 0&&a(`group by nullable '${l}'`,`triggers cannot key NULL groups`)}function In(e,t){if(!(e===`scalar`&&i(this)&&this.kind===`scalar`))return t instanceof Set?[...t]:t}function Ln(e,n){let{source:r,query:i,ty:a}=h(n),o=new x(e.schema,e.resolved),{adapter:s,columns:c}=e,l=new Set([v(r)]),{identifiers:u,period:d}=s;s.identifiers={...u,table:(e,t)=>(l.add(e),u.table(e,t))},d&&c.l6&&Object.assign(s,{period:{...d,text:e=>c.l6(e)}});let f=S(n),p=new Nn(o,s,n,c),m=a?`groupBy`:`findMany`,g;try{g=o.lf(r,m,i)}catch(e){X(f,`its source does not take`,e instanceof Error?e.message:String(e))}Mn(f,g),h(n).refresh===`auto`&&Fn(n,r,g,p),p.unordered=a!==void 0&&g.take===void 0;let _;try{_=a===void 0&&g.take===void 0&&g.distinct===void 0?p.select(r,g,void 0,jn).sql:p.read(r,m,g).query.sql}catch(e){throw e instanceof t&&X(f,`this database cannot read`,e.message.replace(An,``)),e}return{statement:_,shape:JSON.parse(JSON.stringify(p.ez(n,{}).shape,In)),reads:[...l]}}const Rn=new WeakMap,zn=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);var Bn=class{field;constructor(e){this.field=e}};const Vn={fields:new Proxy({},{get:(e,t)=>new Bn(String(t))})},Z=(e,t)=>{let n=a();return f(n,e,t),n};function Q(e){let t=c(e);if(t!==void 0)return Z(`$jsonNull`,t);if(typeof e==`bigint`)return Z(`$bigint`,e.toString());if(typeof e==`number`&&!Number.isFinite(e))return Z(`$number`,String(e));if(typeof e==`function`)return Q(e(Vn));if(typeof e!=`object`||!e)return e;if(e instanceof Date)return Z(`$date`,String(e.getTime()));if(e instanceof Uint8Array)return Z(`$bytes`,zn(e));if(e instanceof Bn)return Z(`$field`,e.field);if(d(e))return Z(`$field`,o(e).field);if(Array.isArray(e))return e.map(Q);if(`toJSON`in e&&typeof e.toJSON==`function`)return Z(`$json`,Q(e.toJSON()));let n=a();for(let[t,r]of Object.entries(e))r!==void 0&&f(n,t,Q(r));let r=Object.keys(n);return r.length===1&&r[0].startsWith(`$`)?Z(`$raw`,n):n}function Hn(e,t){return t instanceof u?{$table:t[`~`].names.sql}:typeof t==`object`&&t&&`~`in t?void 0:t}function $(e,t,n,r){if(Array.isArray(t)){for(let i of t)$(e,i,n,r);return}if(!i(t))return;let a=n.get(e),o=e[`~`].state,s=(t,i)=>{let o=a?.get(t);if(o===void 0)return;r.set(`${e[`~`].names.sql}.${t}`,o);let{edge:s}=o,c=`endpoints`in s?s.endpoints.map(({source:e})=>e):[s.carrier.source,...s.members.flatMap(e=>`targetModel`in e?[e.targetModel]:[e.tj.source.model,e.tj.target.model])],l=o.slot.source,u=c.every(e=>e===l);for(let e of new Set(c))(u||e!==l)&&$(e,i,n,r)};for(let[i,c]of Object.entries(t))if(!(i in o.scalars))if(i===`_count`&&c===!0)for(let[e,t]of Object.entries(o.relations))t[`~`].state.cardinality===`many`&&s(e,void 0);else a?.has(i)?s(i,c):$(e,c,n,r)}function Un(e,t,n){if(`write`in e)return e.write(t,n);let r=Ln({...t,adapter:e.adapter,columns:e.columns},n);return{sql:kn(e.dialect,r.statement),shape:r.shape,reads:r.reads}}function Wn(t,n){let{models:r,relations:i,migrationDriver:a}=n,{dialect:o}=a,s=a.cg();if(s===void 0)throw new e(`The view "${t[`~`].names.ts}" cannot be migrated: VibORM creates no view on ${o}.`,`V8001`,{meta:{feature:`view`,dialect:o}});let c=Rn.get(i);c===void 0&&(c={registry:D(r,i),validation:{modelToName:new Map(Object.entries(r).map(([e,t])=>[t,e])),tableToModels:new Map}},Rn.set(i,c));let l=O(new Map(Object.entries(r)),t[`~`].names.ts??``,t,c.validation);if(l.length>0)throw new e(l.map(({code:e,message:t})=>`${t} (${e})`).join(`; `),`V4002`,{meta:{feature:`view`,model:t[`~`].names.ts}});let u=Un(s,{schema:r,resolved:{index:i,registry:c.registry}},t),d=t[`~`].names.sql,f=[...new Set(u.reads)].filter(e=>e!==d).sort(),p=h(t),m=new Map;$(p.source,p.ty?p.query.where:p.query,i,m);let g=p.refresh===`auto`&&a.hh(),v=!g&&p.materialized===!0&&a.bm(),y=()=>_(t).addressableKeys.map(e=>e.fields),b=JSON.stringify({revision:1,source:p.source[`~`].names.sql,query:JSON.stringify(Q(p.query)),shape:u.shape,relations:[...m].sort(([e],[t])=>e<t?-1:1),...g?{auto:1,keys:y()}:v?{materialized:v,keys:y()}:{}},Hn);return{sql:u.sql,hash:ye(be.view,F(b)).slice(0,40),dependsOn:f,materialized:v,auto:g}}function Gn(e,t,n){if(Array.isArray(t)){for(let r of t)Gn(e,r,n);return}if(i(t))for(let[r,i]of Object.entries(t))r===`$field`&&typeof i==`string`?n.add(i):r in e&&n.add(r),Gn(e,i,n)}function Kn(e){let{source:t,query:n,columns:r,ty:i}=h(e),a=t[`~`].state.scalars,o=new Set;for(let e of r){let t=i?i.origins[e]?.field:e;t!==void 0&&o.add(t)}return Gn(a,Q(n.where),o),[...o].filter(e=>e in a).map(e=>t[`~`].getFieldName(e).sql).sort()}function qn(t,n){let r=re(t,n);if(r!==void 0)throw new e(ae(r),`V11009`)}function Jn(e){let t=new Map,n=[],r=e=>{let n=t.get(e);if(n)return n;let r={variants:[],foreignKeys:[]};return t.set(e,r),r};for(let t of k(e)){if(t.kind===`junction`){t.tj.declared||n.push(t);continue}if(t.kind===`foreignKey`){r(t.owner.source).foreignKeys.push(t);continue}r(t.carrier.source).variants.push(t)}return{p5:t,c0:n}}function Yn(e,t){return e.source===t.source&&e.field===t.field}function Xn(e,t){let[n,r]=e.endpoints;return Yn(n,t)?r:n}function Zn(e,t,n){return{name:n.options.name||`${t}_${n.fields.join(`_`)}_idx`,columns:n.fields.map(t=>e[`~`].getFieldName(t).sql),unique:n.options.unique??!1,type:n.options.type,where:n.options.where}}function Qn(e,t){let n=t=>e[`~`].getFieldName(t).sql;return[..._(e).addressableKeys.flatMap(e=>e.fields.length===0?[]:[{name:e.kind===`primary`?`${t}_pkey`:`${t}_${e.name??n(e.fields[0])}_key`,columns:e.fields.map(n),unique:!0}]),...e[`~`].state.indexes.map(n=>Zn(e,t,n))]}function $n(e,t,n){let r=h(e),{source:i,ty:a}=r,o=e[`~`].state.scalars,s=i[`~`].state.scalars,c=i[`~`].names.sql,l=t=>e[`~`].getFieldName(t).sql,u=r.columns.filter(e=>o[e]!==void 0).map(a=>{let u=o[a],d=g(r,a),f=d===void 0?n(e,t,a,u):n(i,c,d,s[d]),p=l(a);return{...f,name:p,type:f.name===p||!f.type.includes(`CHECK(`)?f.type:n(e,t,a,u).type,nullable:u[`~`].state.nullable,default:void 0,autoIncrement:!1}}),d=a?a.by:_(i).addressableKeys.find(e=>e.kind===`primary`)?.fields??[];return{source:c,columns:u,key:d.map(l),sourceKey:d.map(e=>i[`~`].getFieldName(e).sql),grouped:a!==void 0,reads:Kn(e)}}function er(e,t,r,i){let a=h(t),o=i.find(({name:e})=>e===r.source);if(o!==void 0)for(let i of a.columns){let s=g(a,i);if(s===void 0)continue;let c=t[`~`].getFieldName(i).sql,l=a.source[`~`].getFieldName(s).sql,u=r.columns.find(({name:e})=>e===c),d=o.columns.find(({name:e})=>e===l)?.type;if(!(d===void 0||u===void 0||u.type===d)){if(u.type.toUpperCase()===`TEXT`){u.type=d;continue}if(d.toUpperCase().includes(`TEXT`))throw new n(`Auto view '${e}' column '${c}' (${u.type}) narrower than source '${r.source}.${l}' (${d}).`,{meta:{model:e,feature:`auto view`}})}}}function tr(e,t){return E(e),qn(e,t.migrationDriver.dialect),nr(e,t.migrationDriver,A(e))}function nr(t,n,r){let{p5:i,c0:a}=Jn(r),o=[],c=[],u=new Set,d=[],f=new Map,p=[],m=[],g=(t,i,a,o)=>{let s=o[`~`].state,l=t[`~`].getFieldName(a).sql,d;if(s.type===`enum`&&(s.array!==!0||n.capabilities.supportsNativeArrays)){let t=o.enumValues;if(n.capabilities.supportsNativeEnums&&t){let r=s.enumName&&n.dialect===`postgresql`?s.enumName:n.nh(i,l,t),a=c.find(e=>e.name===r);if(a&&JSON.stringify(a.values)!==JSON.stringify(t))throw new e(`Enum type "${r}" is declared with incompatible values`,`V11009`);u.has(r)||(c.push({name:r,values:t}),u.add(r)),d=s.array?`${r}[]`:r}else d=n.nh(i,l,t||[])}else d=n.rf(o,s,j(t,a,r));return{name:l,type:d,nullable:s.nullable,default:n.tg(o,s),autoIncrement:s.autoGenerate?.kind===`increment`,decimal:s.decimal,geoPointEncoding:n.dialect===`sqlite`&&s.type===`point`?`binary64`:void 0,dateTime:n.dialect===`sqlite`&&s.type===`datetime`&&s.array!==!0?N(o[`~`].nativeType):void 0}};for(let[a,c]of Object.entries(t)){if(Oe.has(c))throw new e(`Model "${a}" is from a light schema; introspect without light to migrate.`,`V11009`);let u=c[`~`].state,_=c[`~`].names.sql||u.tableName||a.toLowerCase();if(h(c)!==void 0){let e=Wn(c,{models:t,relations:r,migrationDriver:n}),i=e.auto?$n(c,_,g):void 0,a=e.materialized||i?n.cv({name:_,columns:i?.columns??[],primaryKey:i?{columns:i.key}:void 0,indexes:Qn(c,_).filter(e=>e.columns.join(`\0`)!==i?.key.join(`\0`)),foreignKeys:[],uniqueConstraints:[]}):void 0,o=a?.indexes??[];i&&a&&(i.columns=a.columns);let s={name:_,hash:e.hash,sql:e.sql,dependsOn:[...e.dependsOn],...e.materialized?{materialized:!0}:{},...o.length>0?{indexes:o}:{}};p.push(s),i&&m.push([s,i,c]);continue}let v=[],y=[],b=[],x=[],S={},C,w=[];for(let[e,t]of Object.entries(u.scalars)){let n=t[`~`].state,r=g(c,_,e,t),i=r.name;v.push(r),n.isId&&w.push(i),n.isUnique&&!n.isId&&x.push({name:`${_}_${i}_key`,columns:[i]})}if(u.compoundId){let e=Object.keys(u.compoundId)[0],t=e?u.compoundId[e]:void 0;t?.entries&&w.push(...Object.keys(t.entries).map(e=>c[`~`].getFieldName(e).sql))}let T=c[`~`].withoutRowid&&n.dialect===`sqlite`,E=v.find(e=>e.autoIncrement);if(T&&E)throw new e(`"${a}" withoutRowid incompatible with .increment() on "${E.name}".`,`V4002`,{meta:{model:a,field:E.name}});if(T&&w.length===0)throw new e(`"${a}" withoutRowid requires a primary key.`,`V4002`,{meta:{model:a}});let D=v.find(e=>e.nullable&&w.includes(e.name));if(D)throw new e(`"${a}.${D.name}" PK column must be NOT NULL.`,`V4002`,{meta:{model:a,field:D.name}});w.length>0&&(C={columns:w,name:`${_}_pkey`,...T?{withoutRowid:!0}:{}});let O=u.compoundUniques;if(O)for(let[e,t]of Object.entries(O))t?.entries&&x.push({name:`${_}_${e}_key`,columns:Object.keys(t.entries).map(e=>c[`~`].getFieldName(e).sql)});let k=[];for(let e of u.indexes){let t=Zn(c,_,e);y.push(t),s(t)&&k.push(t.columns)}let A=ge[n.dialect];for(let t of c[`~`].rawIndexes){let r=A&&t.templates[A];if(r!==void 0){if(y.some(({name:e})=>e===t.name))throw new e(`Raw index "${a}.${t.name}" has the name of another index.`,`V4002`,{meta:{model:a,indexName:t.name}});y.push(me(a,t.name,r,n.dialect,e=>Object.hasOwn(u.scalars,e)?c[`~`].getFieldName(e).sql:void 0))}}let M=i.get(c)??{variants:[],foreignKeys:[]};for(let e of M.variants){if(e.kind===`variantJunctionCarrier`){let t=[];for(let i of e.members){let e=or(c,_,i,n,r),a=i.tj.dk,o=f.get(e.name);if(o&&(o.r7!==a||JSON.stringify(o.def)!==JSON.stringify(e)))throw rr(e.name);o||f.set(e.name,{def:e,r7:a});let s=i.tj.target.model,u=s[`~`].names.ts;t.push({publicType:i.variant,storedType:i.entry.storedValue,targetTable:l(s,u?.toLowerCase()??`unknown`),memberJunctionTable:i.tj.table,inverseCardinality:i.mw?`one`:`many`})}d.push({ownerTable:_,relation:e.carrier.field,kind:`toMany`,members:t});continue}let t=e.storage,i=t.typeColumn.scalar[`~`].state,a=t.idColumn.scalar[`~`].state;v.push({name:t.typeColumn.name,type:n.rf(t.typeColumn.scalar,i),nullable:t.typeColumn.nullable},{name:t.idColumn.name,type:n.rf(t.idColumn.scalar,a,t.idColumn.reference===void 0?void 0:j(t.idColumn.reference.model,t.idColumn.reference.field,r)),nullable:t.idColumn.nullable}),y.push({name:t.indexName,columns:[t.typeColumn.name,t.idColumn.name],unique:e.mw}),S[t.typeColumn.name]={kind:`polymorphicToOne`,typeColumn:t.typeColumn.name,idColumn:t.idColumn.name,index:t.indexName};let o=[];for(let t of e.members){let e=t.targetModel[`~`].names.ts;o.push({publicType:t.variant,storedType:t.entry.storedValue,targetTable:l(t.targetModel,e?.toLowerCase()??`unknown`)})}d.push({ownerTable:_,relation:e.carrier.field,kind:`toOne`,storageRef:t.typeColumn.name,members:o})}let N=[];for(let e of M.foreignKeys)e.unique&&N.push(e.reference.members.map(e=>c[`~`].getFieldName(e.tw).sql));for(let e of M.foreignKeys){let t=Xn(e,e.owner).source,n=t[`~`].state,r=t[`~`].names.sql||n.tableName||e.owner.field.toLowerCase(),i=e.reference.members.map(e=>e.tw).map(e=>c[`~`].getFieldName(e).sql),a=e.reference.members.map(e=>t[`~`].getFieldName(e.ee).sql);if(b.push({name:`${_}_${i.join(`_`)}_fkey`,columns:i,referencedTable:r,referencedColumns:a,onDelete:te(e),onUpdate:e.reference.onUpdate??`noAction`}),e.unique){let e=[...i].sort().join(`,`);[...w].sort().join(`,`)===e||x.some(t=>[...t.columns].sort().join(`,`)===e)||y.some(t=>t.unique&&s(t)&&[...t.columns].sort().join(`,`)===e)||x.push({name:`${_}_${i.join(`_`)}_key`,columns:i});continue}if([w,...x.map(e=>e.columns),...N,...k].some(e=>i.every((t,n)=>e[n]===t)))continue;let o=ee(_,i,new Set(y.map(e=>e.name)));o!==void 0&&y.push({name:o,columns:i,unique:!1})}o.push({name:_,columns:v,primaryKey:C,indexes:y,foreignKeys:b,uniqueConstraints:x,...Object.keys(S).length>0?{relationStorage:S}:{}})}for(let e of a){let t=e.endpoints[0],i=t.source,a=i[`~`].names.ts,o=i[`~`].names.sql||i[`~`].state.tableName||(a??``).toLowerCase(),s=Xn(e,t).source,c=s[`~`].names.ts;if(!(a&&c))throw Error(`Target model for relation "${t.field}" has no name. Schema may not be hydrated. Call hydrateSchemaNames() first.`);let l=s[`~`].names.sql;if(!l)throw Error(`Target model "${c}" has no SQL table name. Schema may not be hydrated. Call hydrateSchemaNames() first.`);let u=e.tj,[d,p]=u.ck?[a.toLowerCase(),c.toLowerCase()]:[c.toLowerCase(),a.toLowerCase()],m=ar({sourceModel:i,qh:o,targetModel:s,targetTable:l,tj:u,kh:{onDelete:M(u.source),onUpdate:u.source.onUpdate??`cascade`},kb:{onDelete:M(u.target),onUpdate:u.target.onUpdate??`cascade`},migrationDriver:n,relations:r}),h=`${d}::${p}::${u.dk??``}`,g=f.get(u.table);if(g){if(g.r7!==h||JSON.stringify(g.def)!==JSON.stringify(m))throw rr(u.table);continue}f.set(u.table,{def:m,r7:h})}for(let{def:e}of f.values())o.push(n.r3?.(e)??e);let _=o.map(e=>n.cv(e));for(let[e,t,r]of m){n.dialect===`mysql`&&er(e.name,r,t,_);let i=n.vs(e.name,t,_),a=i?.length?{...t,cascades:i}:t;e.auto={objects:n.pp(e.name,a),storage:a}}let v={tables:_,enums:c.length>0?c:void 0,...d.length>0?{polymorphicStorage:d}:{},...p.length>0?{views:p.sort((e,t)=>e.name<t.name?-1:Number(e.name>t.name))}:{}};return n.target?ue(v,n.target,!0):v}const rr=e=>Error(`Junction table "${e}" is shared by distinct relation pairs; use distinct .name() or .through().`),ir={onDelete:`cascade`,onUpdate:`cascade`};function ar({sourceModel:e,qh:t,targetModel:n,targetTable:r,tj:i,kh:a,kb:o,uk:s,migrationDriver:c,relations:l}){let u=(e,t)=>{let n=sr(e,c,l);return t.map((e,t)=>({column:e.ef,pk:n[t]}))},d=u(e,i.source.members),f=u(n,i.target.members),p={members:d,table:t,actions:a},m={members:f,table:r,actions:o},[h,g]=i.ck?[p,m]:[m,p],_=h.members.map(e=>e.column),v=g.members.map(e=>e.column),y=(e,t,n)=>({name:i.og(n),columns:t,referencedTable:e.table,referencedColumns:e.members.map(e=>e.pk.column),onDelete:e.actions.onDelete,onUpdate:e.actions.onUpdate});return{name:i.table,columns:[...h.members,...g.members].map(e=>({name:e.column,type:e.pk.type,nullable:!1})),primaryKey:{columns:[..._,...v]},indexes:s&&i.ck?[]:[{name:i.ug(),columns:v,unique:!1}],foreignKeys:[y(h,_,i.ck?`source`:`target`),y(g,v,i.ck?`target`:`source`)],uniqueConstraints:s?[{name:s(),columns:f.map(e=>e.column)}]:[]}}function or(e,t,n,r,i){let a=n.tj,o=a.target.model;return ar({sourceModel:e,qh:t,targetModel:o,targetTable:l(o,o[`~`].names.ts?.toLowerCase()??`unknown`),tj:a,kh:ir,kb:ir,uk:n.mw?()=>a.uk():void 0,migrationDriver:r,relations:i})}function sr(e,t,n){let r=e[`~`].state,i=e[`~`].names.ts,a=_(e).pl?.fields;if(!a||a.length===0)throw Error(`Model "${i}" has no primary key. Schema may not be hydrated.`);return a.map(a=>{let o=r.scalars[a];if(!o)throw Error(`Primary-key field '${a}' of model "${i}" is not a scalar.`);let s=o[`~`].state;return{field:a,column:e[`~`].getFieldName(a).sql,type:t.rf(o,s,j(e,a,n))}})}export{Ye as A,xt as C,Ge as D,Ke as E,tt as O,ut as S,rt as T,ht as _,ln as a,Ot as b,zt as c,Bt as d,Ft as f,vt as g,mt as h,Un as i,Pe as j,et as k,Vt as l,gt as m,tr as n,on as o,bt as p,nr as r,sn as s,qn as t,Rt as u,Dt as v,ct as w,Nt as x,Pt as y};
7
+ //# sourceMappingURL=serializer-CIhcZMxs.mjs.map