viborm 1.14.2 → 1.16.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 (483) hide show
  1. package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +26 -10
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/args-7WgBFd_f.mjs +2 -0
  6. package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
  7. package/dist/array-literal-BOzj0E2u.mjs +2 -0
  8. package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
  9. package/dist/base-17NSFtrA.mjs +2 -0
  10. package/dist/base-17NSFtrA.mjs.map +1 -0
  11. package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
  12. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
  13. package/dist/better-auth.d.mts +116 -0
  14. package/dist/better-auth.mjs +6 -0
  15. package/dist/better-auth.mjs.map +1 -0
  16. package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
  17. package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/bun-sqlite.mjs.map +1 -1
  24. package/dist/cache/cloudflare-kv.d.mts +1 -1
  25. package/dist/cache/cloudflare-kv.mjs +1 -1
  26. package/dist/cache/cloudflare-kv.mjs.map +1 -1
  27. package/dist/cache/memory.d.mts +1 -1
  28. package/dist/cache/memory.mjs +1 -1
  29. package/dist/cache/memory.mjs.map +1 -1
  30. package/dist/cache.d.mts +2 -2
  31. package/dist/cache.mjs +1 -1
  32. package/dist/cache.mjs.map +1 -1
  33. package/dist/call-0bd_B9Vp.mjs +2 -0
  34. package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
  35. package/dist/cli.mjs +6 -6
  36. package/dist/cli.mjs.map +1 -1
  37. package/dist/client-D7sWgUt2.mjs +2 -0
  38. package/dist/client-D7sWgUt2.mjs.map +1 -0
  39. package/dist/client-DEfFqv4S.mjs +9 -0
  40. package/dist/client-DEfFqv4S.mjs.map +1 -0
  41. package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
  42. package/dist/client.d.mts +3 -3
  43. package/dist/client.mjs +1 -1
  44. package/dist/client.mjs.map +1 -1
  45. package/dist/config.d.mts +2 -2
  46. package/dist/config.mjs +1 -1
  47. package/dist/confine-CyI9IwjC.mjs +2 -0
  48. package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
  49. package/dist/coordination-BxMskOgi.mjs +2 -0
  50. package/dist/coordination-BxMskOgi.mjs.map +1 -0
  51. package/dist/d1.d.mts +2 -30
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
  55. package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
  56. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
  57. package/dist/defaults-DAPb-tJ4.mjs +2 -0
  58. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
  59. package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
  60. package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
  61. package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
  62. package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
  63. package/dist/driver-kiIQS_Fd.mjs +2 -0
  64. package/dist/driver-kiIQS_Fd.mjs.map +1 -0
  65. package/dist/driver-lShUkDmf.mjs +2 -0
  66. package/dist/driver-lShUkDmf.mjs.map +1 -0
  67. package/dist/driver.d.mts +1 -1
  68. package/dist/driver.mjs +1 -1
  69. package/dist/durable-object.d.mts +1 -1
  70. package/dist/durable-object.mjs +2 -2
  71. package/dist/durable-object.mjs.map +1 -1
  72. package/dist/error-mapping-B9rSvgG9.mjs +2 -0
  73. package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
  74. package/dist/every-JpbiHdMb.mjs +2 -0
  75. package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
  76. package/dist/execution-context-couU2tgh.mjs +2 -0
  77. package/dist/execution-context-couU2tgh.mjs.map +1 -0
  78. package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
  79. package/dist/extension-Dh1ddrlA.mjs +2 -0
  80. package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
  81. package/dist/fs-estate-n-QpsFqb.mjs +2 -0
  82. package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
  83. package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
  84. package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
  85. package/dist/id-domain-Cg65TLZ-.mjs +2 -0
  86. package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
  87. package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
  88. package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
  89. package/dist/identifiers-BxOf57qy.mjs +2 -0
  90. package/dist/identifiers-BxOf57qy.mjs.map +1 -0
  91. package/dist/identity-CJlRQA-m.mjs +2 -0
  92. package/dist/identity-CJlRQA-m.mjs.map +1 -0
  93. package/dist/index.d.mts +3 -3
  94. package/dist/index.mjs +1 -1
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/instrumentation.d.mts +1 -1
  97. package/dist/instrumentation.mjs +1 -1
  98. package/dist/instrumentation.mjs.map +1 -1
  99. package/dist/introspect-q3Rf_Xv8.mjs +2 -0
  100. package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
  101. package/dist/json-CsAdz9pg.mjs +2 -0
  102. package/dist/json-CsAdz9pg.mjs.map +1 -0
  103. package/dist/json-number-C09rsm1g.mjs +2 -0
  104. package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
  105. package/dist/json-parameter-D7hDrVKw.mjs +2 -0
  106. package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
  107. package/dist/judge-words-k5GCc4cV.mjs +2 -0
  108. package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
  109. package/dist/key-BDH6oTyC.mjs +2 -0
  110. package/dist/key-BDH6oTyC.mjs.map +1 -0
  111. package/dist/keys-CIal55WQ.mjs +2 -0
  112. package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
  113. package/dist/keys-DZdKAd4n.mjs +2 -0
  114. package/dist/keys-DZdKAd4n.mjs.map +1 -0
  115. package/dist/libsql-DEZ0uhK2.mjs +3 -0
  116. package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
  117. package/dist/libsql.d.mts +2 -20
  118. package/dist/libsql.mjs +1 -1
  119. package/dist/libsql.mjs.map +1 -1
  120. package/dist/light-D2wNSbzY.mjs +2 -0
  121. package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
  122. package/dist/memory-BaGWNdvk.mjs +2 -0
  123. package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
  124. package/dist/methods-part-BaNx3o7b.mjs +2 -0
  125. package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
  126. package/dist/migrations/mysql.d.mts +5 -5
  127. package/dist/migrations/mysql.mjs +1 -1
  128. package/dist/migrations/postgres.d.mts +5 -5
  129. package/dist/migrations/postgres.mjs +1 -1
  130. package/dist/migrations/snowflake.d.mts +5 -5
  131. package/dist/migrations/snowflake.mjs +1 -1
  132. package/dist/migrations/sqlite.d.mts +5 -5
  133. package/dist/migrations/sqlite.mjs +1 -1
  134. package/dist/migrations/storage/durable-object.d.mts +1 -1
  135. package/dist/migrations/storage/durable-object.mjs +1 -1
  136. package/dist/migrations/storage/durable-object.mjs.map +1 -1
  137. package/dist/migrations/storage/fs.d.mts +1 -1
  138. package/dist/migrations/storage/fs.mjs +1 -1
  139. package/dist/migrations/storage/r2.d.mts +1 -1
  140. package/dist/migrations/storage/r2.mjs +1 -1
  141. package/dist/migrations/storage/r2.mjs.map +1 -1
  142. package/dist/migrations/surrealdb.d.mts +5 -5
  143. package/dist/migrations/surrealdb.mjs +1 -1
  144. package/dist/migrations/tenant.d.mts +3 -3
  145. package/dist/migrations/tenant.mjs +1 -1
  146. package/dist/migrations/tenant.mjs.map +1 -1
  147. package/dist/migrations-DIUltjr3.mjs +2 -0
  148. package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
  149. package/dist/migrations.d.mts +5 -5
  150. package/dist/migrations.mjs +1 -1
  151. package/dist/model-Dtd37Sky.mjs +2 -0
  152. package/dist/model-Dtd37Sky.mjs.map +1 -0
  153. package/dist/mysql-BFPF8xyv.mjs +9 -0
  154. package/dist/mysql-BFPF8xyv.mjs.map +1 -0
  155. package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
  156. package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
  157. package/dist/mysql2.d.mts +2 -27
  158. package/dist/mysql2.mjs +1 -1
  159. package/dist/mysql2.mjs.map +1 -1
  160. package/dist/named-statements-CkOOD__I.mjs +2 -0
  161. package/dist/named-statements-CkOOD__I.mjs.map +1 -0
  162. package/dist/named-statements-NF7Iycjk.d.mts +13 -0
  163. package/dist/native-types-1ewJXVks.mjs +2 -0
  164. package/dist/native-types-1ewJXVks.mjs.map +1 -0
  165. package/dist/neon-http.d.mts +1 -1
  166. package/dist/neon-http.mjs +1 -1
  167. package/dist/neon-http.mjs.map +1 -1
  168. package/dist/normalized-result-D7nVkF36.mjs +2 -0
  169. package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
  170. package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
  171. package/dist/object-store-Chq1PMYz.mjs +2 -0
  172. package/dist/object-store-Chq1PMYz.mjs.map +1 -0
  173. package/dist/on-ZkOVmE4-.mjs +2 -0
  174. package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
  175. package/dist/on.d.mts +1 -1
  176. package/dist/on.mjs +1 -1
  177. package/dist/on.mjs.map +1 -1
  178. package/dist/ordering/keys.mjs +1 -1
  179. package/dist/ordering.d.mts +9 -3
  180. package/dist/ordering.mjs +10 -10
  181. package/dist/ordering.mjs.map +1 -1
  182. package/dist/pending-operation-D4gUKMxD.mjs +2 -0
  183. package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
  184. package/dist/permissions.d.mts +1 -1
  185. package/dist/permissions.mjs +1 -1
  186. package/dist/permissions.mjs.map +1 -1
  187. package/dist/pg.d.mts +16 -99
  188. package/dist/pg.mjs +1 -1
  189. package/dist/pg.mjs.map +1 -1
  190. package/dist/pglite.d.mts +3 -1
  191. package/dist/pglite.mjs +1 -1
  192. package/dist/pglite.mjs.map +1 -1
  193. package/dist/physical-DO4PEYcc.mjs +2 -0
  194. package/dist/physical-DO4PEYcc.mjs.map +1 -0
  195. package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
  196. package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
  197. package/dist/planetscale.d.mts +1 -1
  198. package/dist/planetscale.mjs +1 -1
  199. package/dist/planetscale.mjs.map +1 -1
  200. package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
  201. package/dist/postgres-DQQE2ys_.mjs +34 -0
  202. package/dist/postgres-DQQE2ys_.mjs.map +1 -0
  203. package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
  204. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
  205. package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
  206. package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
  207. package/dist/postgres-result-133boRW-.mjs +2 -0
  208. package/dist/postgres-result-133boRW-.mjs.map +1 -0
  209. package/dist/postgres.d.mts +27 -59
  210. package/dist/postgres.mjs +1 -1
  211. package/dist/postgres.mjs.map +1 -1
  212. package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
  213. package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
  214. package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
  215. package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
  216. package/dist/quantized-BKBs0joq.mjs +2 -0
  217. package/dist/quantized-BKBs0joq.mjs.map +1 -0
  218. package/dist/query-BTb6iakn.mjs +2 -0
  219. package/dist/query-BTb6iakn.mjs.map +1 -0
  220. package/dist/query-backend-TisPjCPF.mjs +2 -0
  221. package/dist/query-backend-TisPjCPF.mjs.map +1 -0
  222. package/dist/query-inspection-DwYBKSDG.mjs +2 -0
  223. package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
  224. package/dist/raw-DqEb71JZ.mjs +2 -0
  225. package/dist/raw-DqEb71JZ.mjs.map +1 -0
  226. package/dist/relation-bound-CSNKLyDy.mjs +2 -0
  227. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
  228. package/dist/result-parsing-BbffueEX.mjs +2 -0
  229. package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
  230. package/dist/routed-operations-CcKOdn51.mjs +2 -0
  231. package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
  232. package/dist/rows-of-Bgl9GVtK.mjs +2 -0
  233. package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
  234. package/dist/rule-words-DMbQuvD2.mjs +2 -0
  235. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
  236. package/dist/scalar-Dm9brvAU.mjs +4 -0
  237. package/dist/scalar-Dm9brvAU.mjs.map +1 -0
  238. package/dist/schema/introspect.d.mts +2 -2
  239. package/dist/schema/introspect.mjs +1 -1
  240. package/dist/schema/json.d.mts +6 -4
  241. package/dist/schema/json.mjs +1 -1
  242. package/dist/schema-DDkAUfOb.mjs +2 -0
  243. package/dist/schema-DDkAUfOb.mjs.map +1 -0
  244. package/dist/schema-DqR_Kcje.mjs +2 -0
  245. package/dist/schema-DqR_Kcje.mjs.map +1 -0
  246. package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
  247. package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
  248. package/dist/schema.d.mts +2 -2
  249. package/dist/schema.mjs +1 -1
  250. package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
  251. package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
  252. package/dist/serializer-ettLu5xG.mjs +33 -0
  253. package/dist/serializer-ettLu5xG.mjs.map +1 -0
  254. package/dist/settle-Pui-1tfJ.mjs +2 -0
  255. package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
  256. package/dist/settled-DYYPcaBX.mjs +2 -0
  257. package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
  258. package/dist/snowflake-BfF8xwfP.mjs +2 -0
  259. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
  260. package/dist/snowflake.d.mts +3 -3
  261. package/dist/snowflake.mjs +2 -2
  262. package/dist/snowflake.mjs.map +1 -1
  263. package/dist/soft-delete.d.mts +9 -3
  264. package/dist/soft-delete.mjs +1 -1
  265. package/dist/soft-delete.mjs.map +1 -1
  266. package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
  267. package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
  268. package/dist/sql-Bu63iAfT.mjs +2 -0
  269. package/dist/sql-Bu63iAfT.mjs.map +1 -0
  270. package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
  271. package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
  272. package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
  273. package/dist/sql-tegqTqGq.mjs +2 -0
  274. package/dist/sql-tegqTqGq.mjs.map +1 -0
  275. package/dist/sql.d.mts +1 -1
  276. package/dist/sql.mjs +1 -1
  277. package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
  278. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
  279. package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
  280. package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
  281. package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
  282. package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
  283. package/dist/sqlite3.d.mts +2 -46
  284. package/dist/sqlite3.mjs +1 -1
  285. package/dist/sqlite3.mjs.map +1 -1
  286. package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
  287. package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
  288. package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
  289. package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
  290. package/dist/surrealdb.d.mts +2 -2
  291. package/dist/surrealdb.mjs +1 -1
  292. package/dist/surrealdb.mjs.map +1 -1
  293. package/dist/surrealql-DY74AUeD.mjs +2 -0
  294. package/dist/surrealql-DY74AUeD.mjs.map +1 -0
  295. package/dist/time-step-DJaIhpAz.mjs +2 -0
  296. package/dist/time-step-DJaIhpAz.mjs.map +1 -0
  297. package/dist/transaction-Bv5nyp-U.mjs +2 -0
  298. package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
  299. package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
  300. package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
  301. package/dist/types-Dy33vBdd.mjs +2 -0
  302. package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
  303. package/dist/unit-DUPX5Sdd.mjs +2 -0
  304. package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
  305. package/dist/unit-words-BXpLpyr2.mjs +2 -0
  306. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
  307. package/dist/utils-BHkJsduV.mjs +26 -0
  308. package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
  309. package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
  310. package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
  311. package/dist/validation-ATmgN5RE.mjs +2 -0
  312. package/dist/validation-ATmgN5RE.mjs.map +1 -0
  313. package/dist/validation-BHjx13zG.mjs +2 -0
  314. package/dist/validation-BHjx13zG.mjs.map +1 -0
  315. package/dist/validation.d.mts +1 -1
  316. package/dist/validation.mjs +1 -1
  317. package/dist/validator-DMzH5Tz0.mjs +2 -0
  318. package/dist/validator-DMzH5Tz0.mjs.map +1 -0
  319. package/dist/value-guards-CBVIJXlI.mjs +2 -0
  320. package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
  321. package/dist/values-Ch2cTlss.mjs +2 -0
  322. package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
  323. package/dist/version-0BDwfy7C.mjs +2 -0
  324. package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
  325. package/dist/view-CHgjF2BO.mjs +2 -0
  326. package/dist/view-CHgjF2BO.mjs.map +1 -0
  327. package/dist/write-sinks-Bei5vFHP.mjs +2 -0
  328. package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
  329. package/package.json +50 -37
  330. package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
  331. package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
  332. package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
  333. package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
  334. package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
  335. package/dist/args-764KdWMr.mjs +0 -2
  336. package/dist/array-literal-DHinAnVs.mjs +0 -2
  337. package/dist/base-z-cH5ZBI.mjs +0 -2
  338. package/dist/base-z-cH5ZBI.mjs.map +0 -1
  339. package/dist/batch-refs-C-gx7A4-.mjs +0 -2
  340. package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
  341. package/dist/call-Cz8XUmrl.mjs +0 -2
  342. package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
  343. package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
  344. package/dist/chunk-BuuaeEvq.mjs +0 -1
  345. package/dist/client-DRpX3-vw.mjs +0 -2
  346. package/dist/client-DRpX3-vw.mjs.map +0 -1
  347. package/dist/client-y7TV0PRZ.mjs +0 -9
  348. package/dist/client-y7TV0PRZ.mjs.map +0 -1
  349. package/dist/confine-DqFBTUw6.mjs +0 -2
  350. package/dist/coordination-6qZHx_kl.mjs +0 -2
  351. package/dist/coordination-6qZHx_kl.mjs.map +0 -1
  352. package/dist/current-DBTlPsQg.mjs +0 -2
  353. package/dist/current-DBTlPsQg.mjs.map +0 -1
  354. package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
  355. package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
  356. package/dist/defaults-DwOHWI_M.mjs +0 -2
  357. package/dist/driver-BGVcgnIX.mjs +0 -2
  358. package/dist/driver-BGVcgnIX.mjs.map +0 -1
  359. package/dist/driver-BIXhOH2_.mjs +0 -2
  360. package/dist/driver-BIXhOH2_.mjs.map +0 -1
  361. package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
  362. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  363. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  364. package/dist/every-tOgQmaIE.mjs +0 -2
  365. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  366. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  367. package/dist/extension-CGepsF-p.mjs +0 -2
  368. package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
  369. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  370. package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
  371. package/dist/hydration-A3zffFWP.mjs +0 -2
  372. package/dist/hydration-A3zffFWP.mjs.map +0 -1
  373. package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
  374. package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
  375. package/dist/identifiers-s00pGES8.mjs +0 -2
  376. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  377. package/dist/identity-CtW15WlB.mjs +0 -2
  378. package/dist/identity-CtW15WlB.mjs.map +0 -1
  379. package/dist/introspect-Bm6xnXcG.mjs +0 -2
  380. package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
  381. package/dist/json-DgMc8-GU.mjs +0 -2
  382. package/dist/json-DgMc8-GU.mjs.map +0 -1
  383. package/dist/json-number-AI-SdUUn.mjs +0 -2
  384. package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
  385. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  386. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  387. package/dist/key-hxFFCKed.mjs +0 -2
  388. package/dist/key-hxFFCKed.mjs.map +0 -1
  389. package/dist/keys-BQxM4c_a.mjs +0 -2
  390. package/dist/libsql-DuGR904j.mjs +0 -3
  391. package/dist/libsql-DuGR904j.mjs.map +0 -1
  392. package/dist/light-BkJe3-yW.mjs +0 -2
  393. package/dist/memory-G4cSuc6A.mjs +0 -2
  394. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  395. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  396. package/dist/migrations-BMiRjR-N.mjs +0 -2
  397. package/dist/mysql-BNXWfTOo.mjs +0 -100
  398. package/dist/mysql-BNXWfTOo.mjs.map +0 -1
  399. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  400. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  401. package/dist/native-types-DgjMUikz.mjs +0 -2
  402. package/dist/native-types-DgjMUikz.mjs.map +0 -1
  403. package/dist/normalized-result-B8pifWS0.mjs +0 -2
  404. package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
  405. package/dist/object-store-DS0F0yZX.mjs +0 -2
  406. package/dist/object-store-DS0F0yZX.mjs.map +0 -1
  407. package/dist/on-ylYaKuRu.mjs +0 -2
  408. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  409. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  410. package/dist/physical-CeE2nYmI.mjs +0 -2
  411. package/dist/physical-CeE2nYmI.mjs.map +0 -1
  412. package/dist/pinned-session-DCoAZDOz.mjs +0 -2
  413. package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
  414. package/dist/postgres-CDdh5dSP.mjs +0 -437
  415. package/dist/postgres-CDdh5dSP.mjs.map +0 -1
  416. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  417. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  418. package/dist/postgres-adapter-axapXX8d.mjs +0 -2
  419. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  420. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  421. package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
  422. package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
  423. package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
  424. package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
  425. package/dist/query-BZVHfA0s.mjs +0 -2
  426. package/dist/query-BZVHfA0s.mjs.map +0 -1
  427. package/dist/query-inspection-BoG-yAln.mjs +0 -2
  428. package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
  429. package/dist/raw-Dyq6Y6UX.mjs +0 -2
  430. package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
  431. package/dist/relation-bound-ku_cMdye.mjs +0 -2
  432. package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
  433. package/dist/routed-operations-wytpbYKv.mjs +0 -2
  434. package/dist/rule-words-ZIGm7cDm.mjs +0 -2
  435. package/dist/scalar-BHCh7aUz.mjs +0 -4
  436. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  437. package/dist/schema-BYA-_bpk.mjs +0 -2
  438. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  439. package/dist/schema-CFIaebgi.mjs +0 -2
  440. package/dist/schema-CFIaebgi.mjs.map +0 -1
  441. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  442. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  443. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  444. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  445. package/dist/serializer-rBq3v1xr.mjs +0 -51
  446. package/dist/serializer-rBq3v1xr.mjs.map +0 -1
  447. package/dist/settle-1cy5x_52.mjs +0 -2
  448. package/dist/settled-BjyuA76m.mjs +0 -2
  449. package/dist/snowflake-UOCC820W.mjs +0 -2
  450. package/dist/sql-3o4DOKm9.mjs +0 -2
  451. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  452. package/dist/sql-Dl6nykFV.mjs +0 -2
  453. package/dist/sql-Dl6nykFV.mjs.map +0 -1
  454. package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
  455. package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
  456. package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
  457. package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
  458. package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
  459. package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
  460. package/dist/standard-sql-qLcQyCtK.mjs +0 -6
  461. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  462. package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
  463. package/dist/surrealql-C1dp1sWw.mjs +0 -2
  464. package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
  465. package/dist/to-many-BybuKQM1.mjs +0 -2
  466. package/dist/to-many-BybuKQM1.mjs.map +0 -1
  467. package/dist/transaction-BNomMtme.mjs +0 -2
  468. package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
  469. package/dist/types-DtDnXhwa.mjs +0 -2
  470. package/dist/unit-BhHbZyuJ.mjs +0 -2
  471. package/dist/unit-words-CT0yeqfZ.mjs +0 -2
  472. package/dist/utils-CpAojrCj.mjs +0 -26
  473. package/dist/validation--qS7OPmg.mjs +0 -2
  474. package/dist/validation--qS7OPmg.mjs.map +0 -1
  475. package/dist/validation-CYaJ8ndO.mjs +0 -2
  476. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  477. package/dist/validator-CZLW7aR3.mjs +0 -2
  478. package/dist/validator-CZLW7aR3.mjs.map +0 -1
  479. package/dist/value-guards-CBuxSC66.mjs +0 -2
  480. package/dist/values-B4aj1i1f.mjs +0 -2
  481. package/dist/version-CXGIA82S.mjs +0 -2
  482. package/dist/write-sinks-3IKCDF-S.mjs +0 -2
  483. /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"surrealdb.mjs","names":["refuse","sql","#queries","#hoisted","#above","#lets","#hoists","#read","prepared","#filter","#operand","#rows","#aggregation","#walksForward","#linked","#holders","#namesOneRow","#statedValue","#gatedHere","#judging","#walk","#carriesText","#carried","#driven","#clauses","#extremes","#namesDecimal","#numeric","#leaf","#aggregateLeaf","#having","#groupOrder","#firstGroups","#indexed","#hoist","fields","#compare","#decimalOperand","#ordered","#orderTerms","#page","#nearest","#walking","index","#cursorGuard","#guardsCursor","#inRelation","#parents","#part","#declaredOf","name","#linkField","key","#linkMatch","#ordering","#cursor","#distinctly","#distinct","#pageBound","#relationOrder","#scalarOrder","plain","#distance","#gated","#members","#related","#links","#traversal","#field","#relation","#truth","#gateHolds","#evidence","#absentArm","#layerHolds","#isRecord","#relationRead","#destructure","#declaredMembers","#carrier","#distinctMembers","read","#pagesOfParents","extras","clauses","#correlated","#children","#reached","#hopIdiom","#walked","#identityOf","#heldRecord","#operation","#relationFilter","#jsonOperation","#spatial","asked","value","#rowAbove","asText","to","wanted","found","#closure","inner","#selecting","#relatedThrough","refuse","sql","#backend","prepared","#waiting","#free","#client","#slots","#log","#open","#ended","#conflicted","#reserveSequences","name","#replay","#end","sql","a","b","#apart","#q","#low","#heard","#rowMembers","#recordKey","#row","#assigned","#judges","#staysAcyclic","#judgedNext","#leaving","#created","#rows","joined","#refusal","#listed","#returning","#frame","before","#keyChange","#as","#moveRecord","#withoutKeys","#stated","#judgedRows","#assignments","#keyFollowers","stored","#follow","#heldBack","name","far","#movedKey","#movement","#standIns","action","table","#rerunsOnConflict","#options"],"sources":["../src/drivers/surrealdb/read-backend.ts","../src/drivers/surrealdb/queries.ts","../src/drivers/surrealdb/transaction.ts","../src/drivers/surrealdb/writer.ts","../src/drivers/surrealdb/index.ts"],"sourcesContent":["/**\n * `docs/architecture/query-backend-frontier.md` step 4.\n *\n * Writes idiomatic SurrealQL from the engine's `Prepared*` descriptions, from\n * the relation and not from a translation of the SQL: a to-many is a reference\n * traversal holding its own query, `<~(SELECT * FROM post FIELD author …)`, a\n * to-one follows its link, and a junction is an edge table walked as a graph,\n * `->tagged->(SELECT * FROM tag …)`. No alias exists: each lowering knows the row\n * it writes for. What it does not cover refuses by name rather than read wrongly.\n */\n\nimport { UnsupportedOperationError } from \"@errors\";\nimport type {\n FieldGate,\n PreparedPredicate,\n PreparedProjection,\n PreparedProjectionField,\n Queries,\n Query,\n Read,\n ReadBackend,\n} from \"@query-engine/raptor3/shared/query\";\nimport {\n approximateOrder,\n firstRow,\n rowSet,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n Arguments,\n Input,\n ReadOperation,\n} from \"@query-engine/raptor3/shared/schema\";\nimport type { Membership } from \"@query-engine/raptor3/shared/storage\";\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport { Sql, sql } from \"@sql\";\nimport { Decimal, GeometryPoint, RecordId } from \"surrealdb\";\nimport type { SurrealQueries } from \"./queries\";\n\ntype AnyModel = PreparedProjection[\"model\"];\ntype Relation = Extract<PreparedProjectionField, { kind: \"relation\" }>;\ntype Reference = Extract<Membership, { kind: \"reference\" }>;\ntype Junction = Extract<Membership, { kind: \"junction\" }>;\ntype Member = Junction[\"sourceSide\"][\"members\"][number];\ntype VariantJunctionMember = Extract<\n Membership[\"scope\"][\"edge\"],\n { kind: \"variantJunctionCarrier\" }\n>[\"members\"][number];\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n/** What a path reads as an array index, as PostgreSQL's `#>` does: `01` and `-1` too. */\nconst INDEX = /^-?\\d{1,9}$/;\nconst QUOTABLE = /^[^`]+$/;\n/**\n * How many rows a filter's body reads ahead of a page before it stops: past this,\n * walking the page's own rows finds what it needs sooner than listing every holder.\n */\nconst HOLDERS_AHEAD = 1000;\n/** How deep an exhaustive walk goes: as deep as a SurrealDB recursion may. */\nconst MAX_WALK = 256;\nconst ARMS = 16;\n\nfunction refuse(what: string): never {\n throw new UnsupportedOperationError(\n `The SurrealDB read backend does not support ${what} yet.`\n );\n}\n\nfunction name(identifier: string): Sql {\n if (IDENTIFIER.test(identifier)) return sql.raw(identifier);\n if (QUOTABLE.test(identifier)) return sql.raw(`\\`${identifier}\\``);\n return refuse(`the name '${identifier}'`);\n}\n\nfunction tableOf(model: AnyModel): string {\n return model[\"~\"].names.sql!;\n}\n\nfunction isSingleKey(queries: Queries, model: AnyModel, field: string) {\n const keys = queries.keyOrder(model);\n return keys.length === 1 && keys[0] === field;\n}\n\nfunction reference(edge: Membership): Reference {\n if (edge.kind !== \"reference\") refuse(\"a junction here\");\n return edge;\n}\n\nconst BOOLEAN_LEAF = {\n kind: \"scalar\",\n type: \"boolean\",\n nullable: false,\n} as const;\nconst COUNT_LEAF = { kind: \"scalar\", type: \"int\", nullable: false } as const;\nconst AGGREGATE_NAMES: readonly string[] = [\n \"_count\",\n \"_avg\",\n \"_sum\",\n \"_min\",\n \"_max\",\n];\nconst AGGREGATE_FUNCTIONS: Readonly<Record<string, string>> = {\n _avg: \"math::mean\",\n _sum: \"math::sum\",\n _min: \"array::min\",\n _max: \"array::max\",\n};\n\ntype OrderTerm = {\n readonly expression: Sql;\n /** A plain column: `ORDER BY` can read it without selecting it. */\n readonly named: boolean;\n /** The model's own field it orders by, when it is one. */\n readonly field?: string;\n readonly descending: boolean;\n readonly nullable: boolean;\n readonly nulls?: \"first\" | \"last\";\n};\n\nconst HOLDS_SUBQUERY = /\\bSELECT\\b/;\n/** Past this many, seeking one group after another costs more than reading them all. */\nconst GROUPS_SOUGHT = 20;\nconst PARENTS_READ_APART = 20;\nconst READS_A_ROW_ABOVE = /\\$(?:parent|this|owner|row)\\b/;\nconst COMPARISONS: Readonly<Record<string, string>> = {\n equals: \"=\",\n gt: \">\",\n gte: \">=\",\n lt: \"<\",\n lte: \"<=\",\n};\n\nconst FUNCTIONS: Readonly<Record<string, string>> = {\n contains: \"string::contains\",\n startsWith: \"string::starts_with\",\n endsWith: \"string::ends_with\",\n};\n\ntype ScalarFacts = {\n readonly type?: string;\n readonly array?: boolean;\n};\n\ntype GeoPointValue = { readonly latitude: number; readonly longitude: number };\n\nfunction geometry(point: GeoPointValue): GeometryPoint {\n return new GeometryPoint([point.longitude, point.latitude]);\n}\n\n/** A value as the database stores it: admission hands dates and decimals over as text. */\nfunction stored(state: ScalarFacts | undefined, value: unknown): unknown {\n if (value === null || value === undefined) return value;\n if (state?.array === true && Array.isArray(value))\n return value.map((member) => stored({ ...state, array: false }, member));\n switch (state?.type) {\n case \"datetime\":\n return new Date(value as string);\n case \"decimal\":\n return new Decimal(String(value));\n case \"point\":\n return geometry(value as GeoPointValue);\n default:\n return value;\n }\n}\n\nfunction isIntegerKey(model: AnyModel, field: string): boolean {\n const type = model[\"~\"].state.scalars[field]?.[\"~\"].state.type;\n return type === \"int\" || type === \"bigint\";\n}\n\n/** A key read back from text: an integer key's record names a number. */\nfunction keyCast(model: AnyModel, field: string, value: Sql): Sql {\n return isIntegerKey(model, field) ? sql`<int>${value}` : value;\n}\n\n/** An exact decimal lands back on its scale, ties to even as `numeric` does here. */\nexport function quantized(\n state: { readonly decimal?: { readonly scale: number } } | undefined,\n value: Sql\n): Sql {\n const scale = state?.decimal?.scale;\n if (scale === undefined) return value;\n const factor = sql.raw(`1${\"0\".repeat(scale)}dec`);\n return sql`(math::round(${value} * ${factor}) / ${factor})`;\n}\n\n/** One step of a JSON path: a key, bound, or both of what a number can name. */\nfunction jsonStep(at: Sql, step: string): Sql {\n return INDEX.test(step)\n ? sql`(IF type::is_array(${at}) { array::at(${at}, ${sql.raw(String(Number(step)))}) } ELSE { ${at}[${step}] })`\n : sql`${at}[${step}]`;\n}\n\nconst sameValue = (_key: string, value: unknown) =>\n typeof value === \"bigint\" ? `${value}n` : value;\n\n/** Whether this is a value bound as it stands, with nothing stated around it. */\nexport function isOneValue(member: Sql): boolean {\n return (\n member.values.length === 1 && member.strings.every((text) => text === \"\")\n );\n}\n\n/**\n * A list as one parameter where each member is one value: a statement holds about\n * 65,000 values at most (\"IR table full\"), and a parser reads each it is given.\n */\nexport function boundList(members: readonly Sql[]): Sql {\n return members.every(isOneValue)\n ? sql`${members.map((member) => member.values[0])}`\n : sql`[${sql.join([...members], \", \")}]`;\n}\n\n/** A record's key cannot be an instant or a decimal, so a key that is one is its text. */\nfunction keyPart(model: AnyModel, field: string, value: unknown): unknown {\n const type = model[\"~\"].state.scalars[field]?.[\"~\"].state.type;\n if (type === \"datetime\") return new Date(value as string).toISOString();\n if (type === \"decimal\") return new Decimal(String(value)).toString();\n return value;\n}\n\n/** Whether a predicate is only rows being among lists, which nothing unset is. */\nfunction onlyLists(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"and\":\n return predicate.predicates.some(onlyLists);\n case \"or\":\n return predicate.predicates.every(onlyLists);\n case \"layer\":\n return onlyLists(predicate.predicate);\n case \"relation\":\n return (\n !predicate.closure &&\n (predicate.quantifier === \"some\" || predicate.quantifier === \"is\") &&\n predicate.predicate !== undefined\n );\n default:\n return false;\n }\n}\n\n/** Whether a predicate reads a row a filter stepped away from, at any depth. */\nfunction readsAbove(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.some(readsAbove);\n case \"not\":\n case \"layer\":\n return readsAbove(predicate.predicate);\n case \"relation\":\n return (\n (predicate.predicate !== undefined &&\n readsAbove(predicate.predicate)) ||\n (predicate.link !== undefined && readsAbove(predicate.link))\n );\n case \"operation\":\n return [predicate.operand, ...(predicate.operands ?? [])].some(\n (operand) => operand?.kind === \"field\" && Boolean(operand.up)\n );\n default:\n return false;\n }\n}\n\n/**\n * Each condition once. It asks nothing more, and the server fails a statement stating\n * one equality twice with the same value (\"Internal database error: stale IR id\").\n */\nexport function onceEach(conditions: readonly Sql[]): Sql[] {\n const seen = new Set<string>();\n return conditions.filter((condition) => {\n const key = `${condition.toStatement()} ${JSON.stringify(condition.values, sameValue)}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** Arms joined in parentheses of at most `ARMS` each: a parser counts each `OR` as a level. */\nfunction joined(arms: readonly Sql[], word: string): Sql {\n if (arms.length <= ARMS) return sql.join([...arms], word);\n const groups: Sql[] = [];\n for (let at = 0; at < arms.length; at += ARMS)\n groups.push(sql`(${sql.join(arms.slice(at, at + ARMS), word)})`);\n return joined(groups, word);\n}\n\n/** Whether a predicate reads other rows, through a relation or a whole table. */\nexport function walksFurther(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.some(walksFurther);\n case \"not\":\n return walksFurther(predicate.predicate);\n case \"layer\":\n return walksFurther(predicate.predicate);\n case \"relation\":\n case \"exists\":\n return true;\n default:\n return false;\n }\n}\n\n/** What a statement's text says outside its comments and string literals. */\nconst NOT_STATED =\n /\\/\\*[\\s\\S]*?\\*\\/|--[^\\n]*|\\/\\/[^\\n]*|#[^\\n]*|'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"/g;\n/** The one field an index is on, written as its placeholder. */\nconst ON_ONE_FIELD =\n /\\b(?:FIELDS|COLUMNS)\\s+\\{([^{}]+)\\}(?=\\s+[A-Za-z]|\\s*;?\\s*$)/i;\nconst HNSW = /\\bHNSW\\b/i;\nconst DIST = /\\bDIST\\s+([A-Za-z_]+)/i;\nconst DIMENSION = /\\bDIMENSION\\s+(\\d+)/i;\nconst DISTANCES: Readonly<Record<string, string>> = {\n l2: \"EUCLIDEAN\",\n cosine: \"COSINE\",\n};\n/** The least candidates a nearest-neighbour search keeps: pgvector's own default. */\nconst EF_SEARCH = 40;\n\n/** A declared HNSW index on one field: its distance and dimension. */\ninterface NearestIndex {\n readonly field: string;\n readonly distance: string;\n readonly dimension: number | undefined;\n}\nconst nearestIndexes = new WeakMap<AnyModel, readonly NearestIndex[]>();\n\n/** The HNSW indexes a model's raw `surrealdb` texts declare, read once per model. */\nfunction nearestIndexesOf(model: AnyModel): readonly NearestIndex[] {\n const known = nearestIndexes.get(model);\n if (known) return known;\n const found = model[\"~\"].rawIndexes.flatMap((index): NearestIndex[] => {\n const text = index.templates.surrealdb?.replace(NOT_STATED, \" \");\n const field = text && ON_ONE_FIELD.exec(text)?.[1];\n if (!(field && HNSW.test(text))) return [];\n const dimension = DIMENSION.exec(text)?.[1];\n return [\n {\n field,\n // SurrealDB's own default.\n distance: (DIST.exec(text)?.[1] ?? \"EUCLIDEAN\").toUpperCase(),\n dimension: dimension === undefined ? undefined : Number(dimension),\n },\n ];\n });\n nearestIndexes.set(model, found);\n return found;\n}\n\nexport class SurrealReadBackend implements ReadBackend {\n readonly #queries: SurrealQueries;\n\n constructor(queries: SurrealQueries) {\n this.#queries = queries;\n }\n\n /** The subqueries a statement computes once, ahead of itself, while it is built. */\n #lets: Sql[] | undefined;\n #hoists = 0;\n readonly #hoisted = new Map<string, Sql>();\n /** How many relation reads are being written around this point of a statement. */\n #inRelation = 0;\n #guardsCursor = false;\n #cursorGuard: Sql | undefined;\n /** The relation filter a page reads by walking, with its list already too long. */\n #walking: PreparedPredicate | undefined;\n /** The rows a root page reads, when they are few enough to give each its own read. */\n #parents:\n | { readonly read: Sql; readonly count: number; ids?: Sql }\n | undefined;\n /** Whether what is being lowered reads rows a write would leave. */\n #judging = false;\n /** What holds each row a relation filter stepped away from, innermost last. */\n readonly #above: string[] = [];\n\n /**\n * A statement that may compute what reads no row ahead of itself. A list held\n * in a variable reads each of its records by key, where the same subquery in a\n * `WHERE` is probed row by row, and it stays one statement, so one transaction.\n */\n hoisted(build: () => Sql): Sql {\n if (this.#lets) return build();\n this.#lets = [];\n this.#hoists = 0;\n this.#hoisted.clear();\n try {\n const body = build();\n // Each at the top level: a server compiles a statement in the square of the\n // subqueries it holds, and keeps each statement it has compiled.\n return this.#lets.length\n ? sql`${sql.join(this.#lets, \" \")} ${body}`\n : body;\n } finally {\n this.#lets = undefined;\n }\n }\n\n /**\n * `build` reading rows a write would leave: a to-one link is the row's own value,\n * not the stored one, so a list of what holds reads targets, not who stores them.\n */\n judging(build: () => Sql): Sql {\n return this.judgingAll(build);\n }\n\n #hoist(expression: Sql): Sql | undefined {\n if (!this.#lets) return undefined;\n // A policy states one subquery for every action it answers: it runs once.\n const key = `${expression.toStatement()} ${JSON.stringify(expression.values, sameValue)}`;\n const known = this.#hoisted.get(key);\n if (known) return known;\n this.#hoists += 1;\n const variable = sql.raw(`$h${this.#hoists}`);\n this.#lets.push(sql`LET ${variable} = ${expression};`);\n this.#hoisted.set(key, variable);\n return variable;\n }\n\n read(model: AnyModel, operation: ReadOperation, args: Arguments): Read {\n let read: Read | undefined;\n const statement = this.hoisted(() => {\n read = this.#read(model, operation, args);\n return read.query.sql;\n });\n return { ...read!, query: { ...read!.query, sql: statement } };\n }\n\n #read(model: AnyModel, operation: ReadOperation, args: Arguments): Read {\n const q = this.#queries;\n const projected = () => q.prepareProjection(model, args);\n switch (operation) {\n case \"findUnique\": {\n const prepared = projected();\n const selector =\n args.where === undefined\n ? undefined\n : q.prepareSelector(model, args.where, true, false);\n const query = {\n // One row at most: an order would only sort it.\n sql: this.statement(\n model,\n prepared,\n { ...args, unordered: true },\n q.scoped(model, selector?.predicate, \"root\")\n ),\n shape: prepared.shape,\n };\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"findFirst\": {\n const prepared = projected();\n // A negative take reads from the end: the flipped order still gives one row.\n const take = args.take === undefined ? 1 : Math.sign(args.take);\n const query = {\n sql: this.statement(\n model,\n prepared,\n { ...args, take, nearest: approximateOrder(operation, args) },\n this.#filter(model, args)\n ),\n shape: prepared.shape,\n };\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"findMany\": {\n const prepared = projected();\n const query = {\n sql: this.statement(\n model,\n prepared,\n { ...args, nearest: approximateOrder(operation, args) },\n this.#filter(model, args)\n ),\n shape: prepared.shape,\n };\n return {\n query,\n single: false,\n value: rowSet(query),\n result:\n (args.take ?? 0) < 0\n ? (rows) => [...rows].reverse()\n : (rows) => rows,\n };\n }\n case \"exist\": {\n const table = name(tableOf(model));\n const predicate = this.#filter(model, args);\n const where = predicate\n ? sql`WHERE ${this.predicate(predicate, true)} `\n : sql.raw(\"\");\n return {\n query: {\n sql: sql`RETURN [{ _count: array::len(SELECT VALUE id FROM ${table} ${where}LIMIT 1) > 0 }]`,\n shape: { kind: \"object\", fields: { _count: BOOLEAN_LEAF } },\n },\n single: false,\n value: BOOLEAN_LEAF,\n result: (rows) => rows[0]?._count ?? false,\n };\n }\n case \"count\": {\n const selected = args.select as Input | undefined;\n const outputs: readonly (readonly [string, string | undefined])[] =\n selected\n ? [\n ...(selected._all ? [[\"_all\", undefined] as const] : []),\n ...Object.keys(selected)\n .filter((field) => field !== \"_all\" && selected[field])\n .map((field) => [field, field] as const),\n ]\n : [[\"_count\", undefined] as const];\n const counted = sql.join(\n outputs.map(([alias, field]) =>\n field === undefined\n ? sql`count() AS ${name(alias)}`\n : sql`count(${this.#operand(model, field)} != NONE) AS ${name(alias)}`\n ),\n \", \"\n );\n const query = {\n sql: sql`SELECT ${counted} FROM ${this.#rows(model, args)} GROUP ALL`,\n shape: {\n kind: \"object\" as const,\n fields: Object.fromEntries(\n outputs.map(([alias]) => [alias, COUNT_LEAF])\n ),\n },\n };\n return {\n query,\n single: selected !== undefined,\n value: selected ? query.shape : COUNT_LEAF,\n result: (rows) =>\n selected ? (rows[0] ?? {}) : ((rows[0]?._count as number) ?? 0),\n };\n }\n case \"aggregate\": {\n const query = this.#aggregation(model, args, []);\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"groupBy\": {\n const query = this.#aggregation(model, args, args.by as string[]);\n return {\n query,\n single: false,\n value: rowSet(query),\n result: (rows) => rows,\n };\n }\n default:\n return refuse(`'${operation}'`);\n }\n }\n\n /**\n * Where a field is stored. A record's key is its id: a single key is `id`\n * whatever the field is called, and a compound key is an array id, read by\n * position.\n */\n physical(model: AnyModel, field: string): Sql {\n const keys = this.#queries.keyOrder(model);\n const position = keys.indexOf(field);\n if (position < 0) return name(this.#queries.columnName(model, field));\n return sql.raw(keys.length === 1 ? \"id\" : `id[${position}]`);\n }\n\n /**\n * Whether a predicate of one row can be answered by following its links, each a\n * read by key, and by lists of who holds what lies at their ends.\n */\n #walksForward(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.every((arm) => this.#walksForward(arm));\n case \"not\":\n case \"layer\":\n return this.#walksForward(predicate.predicate);\n case \"always\":\n case \"operation\":\n return true;\n case \"relation\": {\n const { edge, closure, link, predicate: inner } = predicate;\n if (closure || link) return false;\n const asked = this.#queries.scoped(edge.target, inner, \"related\");\n if (\n edge.kind === \"reference\" &&\n !edge.many &&\n edge.owner === \"source\" &&\n this.#linked(edge)\n )\n return (\n !(asked && readsAbove(asked)) &&\n (asked === undefined || this.#walksForward(asked))\n );\n return (\n asked !== undefined &&\n predicate.quantifier !== \"every\" &&\n !readsAbove(asked) &&\n this.#holders(predicate, asked) !== undefined\n );\n }\n default:\n return false;\n }\n }\n\n /** Whether a predicate names one row by its whole key. */\n #namesOneRow(model: AnyModel, predicate: PreparedPredicate): boolean {\n const named = new Set<string>();\n const collect = (node: PreparedPredicate) => {\n if (node.kind === \"and\") node.predicates.forEach(collect);\n else if (\n node.kind === \"operation\" &&\n node.operator === \"equals\" &&\n node.target.kind === \"column\" &&\n node.target.scalar.model === model\n )\n named.add(node.target.scalar.field);\n };\n collect(predicate);\n return this.#queries.keyOrder(model).every((key) => named.has(key));\n }\n\n /** A filter's conditions: one that names a row follows its links from that row. */\n located(\n model: AnyModel,\n predicate: PreparedPredicate,\n named = this.#namesOneRow(model, predicate)\n ): Sql[] {\n return named\n ? this.judgingAll(() => this.conjuncts(predicate))\n : this.conjuncts(predicate);\n }\n\n /** What an operation compares with, where the call states it. */\n #statedValue(arm: PreparedPredicate): unknown {\n if (arm.kind !== \"operation\") return undefined;\n const { operand } = arm;\n if (operand === undefined) return arm.value;\n if (operand.kind === \"value\") return operand.value;\n if (operand.kind === \"parameter\")\n return this.#queries.callValue(operand.parameter);\n return undefined;\n }\n\n /**\n * The record a filter names by its whole key, and what else it asks of that row.\n * A statement over the record itself costs about half one that filters the table\n * on `id`, though both fetch the one record.\n */\n namedRecord(\n model: AnyModel,\n predicate: PreparedPredicate\n ):\n | { readonly record: Sql; readonly rest: PreparedPredicate | undefined }\n | undefined {\n const q = this.#queries;\n const keys = q.keyOrder(model);\n const flat = (node: PreparedPredicate): PreparedPredicate[] =>\n node.kind === \"and\" ? node.predicates.flatMap(flat) : [node];\n const named = new Map<string, unknown>();\n const others: PreparedPredicate[] = [];\n for (const arm of flat(predicate)) {\n const value = this.#statedValue(arm);\n const field =\n arm.kind === \"operation\" &&\n arm.operator === \"equals\" &&\n !arm.insensitive &&\n value !== null &&\n value !== undefined &&\n !(value instanceof Sql) &&\n arm.target.kind === \"column\" &&\n arm.target.path === undefined &&\n arm.target.scalar.model === model\n ? arm.target.scalar.field\n : undefined;\n if (\n field !== undefined &&\n keys.includes(field) &&\n !named.has(field) &&\n !this.#gatedHere(model, field)\n )\n named.set(field, value);\n else others.push(arm);\n }\n if (!keys.every((key) => named.has(key))) return undefined;\n const [only] = keys;\n let record: Sql | undefined;\n if (keys.length > 1)\n record = sql`${this.recordOf(model, Object.fromEntries(named) as Input)}`;\n else if (isSingleKey(q, model, only!))\n record = this.value(model, only!, named.get(only!));\n if (!record) return undefined;\n let rest: PreparedPredicate | undefined;\n if (others.length > 1) rest = { kind: \"and\", predicates: others };\n else rest = others[0];\n return { record, rest };\n }\n\n judgingAll<T>(build: () => T): T {\n const outer = this.#judging;\n this.#judging = true;\n try {\n return build();\n } finally {\n this.#judging = outer;\n }\n }\n\n /** A predicate's conditions, to state beside others, each once ({@link onceEach}). */\n conjuncts(predicate: PreparedPredicate): Sql[] {\n return predicate.kind === \"and\"\n ? predicate.predicates.flatMap((inner) => this.conjuncts(inner))\n : [this.predicate(predicate, true)];\n }\n\n /** Whether a relation's link is a record, which a graph read can follow. */\n isLinked(edge: Reference): boolean {\n return this.#linked(edge);\n }\n\n /**\n * What a row reaches along a to-one link, as a write would leave it. The walk is\n * physical: a cycle through a hidden row is still one.\n */\n walkFrom(edge: Membership, row: Sql): Sql {\n return this.#walk(edge, {} as never, false, row);\n }\n\n #linked(edge: Reference): boolean {\n if (edge.pairs.length !== 1 || edge.discriminator) return false;\n const q = this.#queries;\n const { source, target } = edge.pairs[0]!;\n return edge.owner === \"source\"\n ? isSingleKey(q, edge.target, target) &&\n !q.keyOrder(edge.source).includes(source)\n : isSingleKey(q, edge.source, source) &&\n !q.keyOrder(edge.target).includes(target);\n }\n\n /** Whether a private carrier column holds keys as text: its arms' keys differ. */\n #carriesText(model: AnyModel, field: string): boolean {\n const { scalar } = this.#queries.schema.physicalField(model, field);\n return scalar[\"~\"].state.type === \"string\";\n }\n\n #carried(model: AnyModel, field: string, key: Sql): Sql {\n return this.#carriesText(model, field) ? sql`<string>${key}` : key;\n }\n\n /**\n * A relation by its fields alone, from a row that is `$parent` here. A variant\n * relation's id column holds the key as text, whichever model it names.\n */\n #correlated(edge: Reference, row: string): Sql {\n const q = this.#queries;\n const pairs = edge.pairs.map(({ source, target }) => {\n const parent = sql`${sql.raw(row)}.${this.physical(edge.source, source)}`;\n const column = this.physical(edge.target, target);\n if (\n isSingleKey(q, edge.target, target) &&\n !this.holdsRecord(edge.source, source)\n )\n return sql`id = type::record(${tableOf(edge.target)}, ${keyCast(edge.target, target, parent)})`;\n if (\n isSingleKey(q, edge.source, source) &&\n !this.holdsRecord(edge.target, target)\n ) {\n const key = sql`record::id(${parent})`;\n return sql`${column} = ${edge.discriminator ? this.#carried(edge.target, target, key) : key}`;\n }\n return sql`${column} = ${parent}`;\n });\n const { discriminator } = edge;\n if (discriminator) {\n const owner = discriminator.side === \"source\" ? edge.source : edge.target;\n const column = this.physical(owner, discriminator.field);\n pairs.push(\n discriminator.side === \"source\"\n ? sql`${sql.raw(row)}.${column} = ${discriminator.value}`\n : sql`${column} = ${discriminator.value}`\n );\n }\n return sql.join(pairs, \" AND \");\n }\n\n /** The rows an aggregate reads: the filtered table, or its page. */\n #rows(model: AnyModel, args: Arguments, within?: Sql): Sql {\n const { from, rest } = this.#driven(model, this.#filter(model, args));\n if (within)\n return sql`${from} WHERE ${sql.join(\n [...(rest ? [this.predicate(rest, true)] : []), within],\n \" AND \"\n )}`;\n const paged =\n args.take !== undefined ||\n args.skip !== undefined ||\n args.cursor !== undefined;\n if (paged) {\n const { extras, clauses } = this.#clauses(model, args, rest);\n return sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${from} ${sql.join(clauses, \" \")})`;\n }\n return rest ? sql`${from} WHERE ${this.predicate(rest, true)}` : from;\n }\n\n /**\n * `aggregate` and `groupBy`: flat aggregates inside, the public shape outside,\n * where a `having` and an order read them by name. `math::sum` of nothing is 0,\n * and SQL's is NULL, so each aggregate carries how many values it saw.\n */\n #aggregation(model: AnyModel, args: Arguments, by: readonly string[]): Query {\n const extremes = this.#extremes(model, args, by);\n if (extremes) return extremes;\n const inner = new Map<string, Sql>();\n const flat = (alias: string, expression: Sql) => {\n inner.set(alias, sql`${expression} AS ${name(alias)}`);\n return name(alias);\n };\n // A field that is always there has as many values as rows.\n const seen = (field: string) =>\n model[\"~\"].state.scalars[field]?.[\"~\"].state.nullable ||\n this.#gatedHere(model, field)\n ? flat(\n `__n_${field}`,\n sql`count(${this.#operand(model, field)} != NONE)`\n )\n : flat(\"__count__all\", sql`count()`);\n const of = (aggregate: string, field: string) => {\n if (aggregate === \"_count\" && field === \"_all\")\n return flat(\"__count__all\", sql`count()`);\n const column = this.#operand(model, field);\n if (aggregate === \"_count\")\n return flat(`__count_${field}`, sql`count(${column} != NONE)`);\n const value = sql`${sql.raw(AGGREGATE_FUNCTIONS[aggregate]!)}(${\n this.#namesDecimal(model, field) ? this.#numeric(column, false) : column\n })`;\n return flat(\n `_${aggregate}_${field}`,\n aggregate === \"_avg\"\n ? quantized(model[\"~\"].state.scalars[field]?.[\"~\"].state, value)\n : value\n );\n };\n const fields: Record<string, unknown> = {};\n const outer: Sql[] = [];\n for (const field of by) {\n const column = flat(field, this.#operand(model, field));\n outer.push(sql`(${column} ?? NULL) AS ${name(field)}`);\n fields[field] = this.#gatedHere(model, field)\n ? { ...(this.#leaf(model, field) as object), nullable: true }\n : this.#leaf(model, field);\n }\n for (const aggregate of AGGREGATE_NAMES) {\n const selection = args[aggregate as keyof Arguments];\n if (!selection) continue;\n if (aggregate === \"_count\" && selection === true) {\n outer.push(sql`${of(\"_count\", \"_all\")} AS _count`);\n fields._count = COUNT_LEAF;\n continue;\n }\n const selected = Object.entries(selection as Input).filter(\n ([, include]) => include\n );\n if (selected.length === 0) continue;\n const leaves: Record<string, unknown> = {};\n const members = selected.map(([field]) => {\n leaves[field] = this.#aggregateLeaf(model, aggregate, field);\n const value = of(aggregate, field);\n return aggregate === \"_count\"\n ? sql`${name(field)}: ${value}`\n : sql`${name(field)}: (IF ${seen(field)} = 0 { NULL } ELSE { ${value} })`;\n });\n outer.push(sql`{ ${sql.join(members, \", \")} } AS ${name(aggregate)}`);\n fields[aggregate] = { kind: \"object\", fields: leaves };\n }\n const having = args.having\n ? this.#having(model, args.having as Input, of, seen, true)\n : undefined;\n const { order, flags } = this.#groupOrder(\n model,\n args.orderBy,\n of,\n seen,\n by\n );\n if (by.length === 0 && inner.size === 0) flat(\"__count__all\", sql`count()`);\n const grouping = by.length\n ? sql`GROUP BY ${sql.join(\n by.map((field) => name(field)),\n \", \"\n )}`\n : sql.raw(\"GROUP ALL\");\n const clauses = [\n ...(having ? [sql`WHERE ${having}`] : []),\n ...(order.length ? [sql`ORDER BY ${sql.join(order, \", \")}`] : []),\n ...(by.length && args.take !== undefined\n ? [sql.raw(`LIMIT ${Number(args.take)}`)]\n : []),\n ...(by.length && args.skip !== undefined\n ? [sql.raw(`START ${Number(args.skip)}`)]\n : []),\n ];\n const rows = by.length\n ? this.#rows(\n model,\n {\n ...args,\n take: undefined,\n skip: undefined,\n cursor: undefined,\n },\n this.#firstGroups(model, args, by)\n )\n : this.#rows(model, args);\n return {\n sql: sql.join(\n [\n sql`SELECT ${sql.join(outer.length || flags.length ? [...outer, ...flags] : [sql.raw(\"true AS __row\")], \", \")} FROM (SELECT ${sql.join([...inner.values()], \", \")} FROM ${rows} ${grouping})`,\n ...clauses,\n ],\n \" \"\n ),\n shape: { kind: \"object\", fields } as Query[\"shape\"],\n };\n }\n\n /**\n * A `groupBy` reads every row before it can take any group, so a page of few groups\n * first seeks them on the index of the field it orders by, one value after the last,\n * each a statement of its own as a closure's variable never seeks, and reads only\n * their rows. Only a filter of its own columns goes along: each seek\n * states it again.\n */\n #firstGroups(\n model: AnyModel,\n args: Arguments,\n by: readonly string[]\n ): Sql | undefined {\n const groups = Number(args.take ?? 0) + Number(args.skip ?? 0);\n const orders = args.orderBy ? [args.orderBy as Input].flat() : [];\n const [field, spec] = Object.entries((orders[0] ?? {}) as Input)[0] ?? [\n by[0],\n \"asc\",\n ];\n if (\n !this.#lets ||\n Number(args.take ?? 0) <= 0 ||\n groups > GROUPS_SOUGHT ||\n args.having ||\n !by.includes(field as string) ||\n (spec !== \"asc\" && spec !== \"desc\") ||\n model[\"~\"].state.scalars[field as string]?.[\"~\"].state.nullable ||\n this.#gatedHere(model, field as string) ||\n // An index seeks the next text, not the next number.\n this.#namesDecimal(model, field as string) ||\n !this.#indexed(model, field as string)\n )\n return undefined;\n const filter = this.#filter(model, args);\n const where = filter ? [this.predicate(filter, true)] : [];\n if (where.some((part) => HOLDS_SUBQUERY.test(part.toStatement())))\n return undefined;\n const column = this.physical(model, field as string);\n const direction = sql.raw(spec === \"desc\" ? \"DESC\" : \"ASC\");\n const beyond = sql.raw(spec === \"desc\" ? \"<\" : \">\");\n const seek = (past: readonly Sql[]) => {\n const conditions = [...where, ...past];\n return sql`(SELECT VALUE ${column} FROM ${name(tableOf(model))}${conditions.length ? sql` WHERE ${sql.join(conditions, \" AND \")}` : sql.raw(\"\")} ORDER BY ${column} ${direction} LIMIT 1)[0]`;\n };\n // Past the last group a seek finds nothing, and the next finds a group again:\n // one already listed, which changes nothing.\n const found: Sql[] = [];\n for (let at = 0; at < groups; at++) {\n const last = found.at(-1);\n const next = this.#hoist(\n seek(last ? [sql`${column} ${beyond} ${last}`] : [])\n );\n if (!next) return undefined;\n found.push(next);\n }\n return sql`${column} IN [${sql.join(found, \", \")}]`;\n }\n\n /** Whether an index holds the field: one declared, or a foreign key's. */\n #indexed(model: AnyModel, field: string): boolean {\n const { indexes, relations } = model[\"~\"].state;\n return (\n indexes.some((index) =>\n (index.fields as readonly string[]).includes(field)\n ) ||\n Object.values(\n relations as Record<\n string,\n { \"~\": { state: { foreignKey?: { fields: readonly string[] } } } }\n >\n ).some((relation) =>\n relation[\"~\"].state.foreignKey?.fields.includes(field)\n )\n );\n }\n\n /**\n * `_min` and `_max` alone, over every row a filter leaves: each is the one row an\n * index finds walking no further, where an aggregate reads them all.\n */\n #extremes(\n model: AnyModel,\n args: Arguments,\n by: readonly string[]\n ): Query | undefined {\n const selected = ([\"_min\", \"_max\"] as const).flatMap((aggregate) => {\n const fields = Object.entries((args[aggregate] ?? {}) as Input)\n .filter(([, include]) => include)\n .map(([field]) => field);\n return fields.length > 0 ? [{ aggregate, fields }] : [];\n });\n const physical = selected.every(({ fields }) =>\n fields.every(\n (field) =>\n // An index's first row holds the least text, not the least number.\n !(\n this.#gatedHere(model, field) || this.#namesDecimal(model, field)\n ) &&\n this.#operand(model, field).toStatement() ===\n this.physical(model, field).toStatement()\n )\n );\n if (\n selected.length === 0 ||\n !physical ||\n by.length > 0 ||\n args.take !== undefined ||\n args.skip !== undefined ||\n args.cursor !== undefined ||\n args.having ||\n args._count ||\n args._avg ||\n args._sum\n )\n return undefined;\n const { from, rest } = this.#driven(model, this.#filter(model, args));\n const filter = rest ? [this.predicate(rest, true)] : [];\n const fields: Record<string, unknown> = {};\n const members = selected.map(({ aggregate, fields: chosen }) => {\n const leaves: Record<string, unknown> = {};\n const values = chosen.map((field) => {\n leaves[field] = this.#aggregateLeaf(model, aggregate, field);\n const column = this.physical(model, field);\n const where = model[\"~\"].state.scalars[field]?.[\"~\"].state.nullable\n ? [...filter, sql`${column} != NONE`]\n : filter;\n return sql`${name(field)}: ((SELECT VALUE ${column} FROM ${from}${where.length ? sql` WHERE ${sql.join(where, \" AND \")}` : sql.raw(\"\")} ORDER BY ${column} ${sql.raw(aggregate === \"_max\" ? \"DESC\" : \"ASC\")} LIMIT 1)[0] ?? NULL)`;\n });\n fields[aggregate] = { kind: \"object\", fields: leaves };\n return sql`${name(aggregate)}: { ${sql.join(values, \", \")} }`;\n });\n return {\n sql: sql`RETURN [{ ${sql.join(members, \", \")} }]`,\n shape: { kind: \"object\", fields } as Query[\"shape\"],\n };\n }\n\n #leaf(model: AnyModel, field: string): unknown {\n return (\n this.#queries.prepareProjection(\n model,\n { select: { [field]: true } },\n true\n ).shape as { fields: Record<string, unknown> }\n ).fields[field];\n }\n\n #aggregateLeaf(model: AnyModel, aggregate: string, field: string): unknown {\n if (aggregate === \"_count\") return COUNT_LEAF;\n const leaf = this.#leaf(model, field) as { type: string };\n if (aggregate === \"_avg\" && leaf.type !== \"decimal\")\n return { kind: \"scalar\", type: \"number\", nullable: true };\n return {\n ...leaf,\n nullable: true,\n // A decimal's sum may pass the field's precision; the others read as they are.\n widened:\n aggregate === \"_sum\" && leaf.type === \"decimal\" ? true : undefined,\n };\n }\n\n /**\n * `positive` carries a negation down to each comparison, as a filter's does: an\n * aggregate of no values is NULL, whose comparison holds neither way.\n */\n #having(\n model: AnyModel,\n having: Input,\n of: (aggregate: string, field: string) => Sql,\n seen: (field: string) => Sql,\n positive: boolean\n ): Sql {\n const clauses: Sql[] = [];\n const all = positive ? \" AND \" : \" OR \";\n const any = positive ? \" OR \" : \" AND \";\n for (const [key, value] of Object.entries(having)) {\n if (value === undefined) continue;\n if (key === \"AND\" || key === \"OR\" || key === \"NOT\") {\n const arms = [value]\n .flat()\n .map((arm) =>\n this.#having(\n model,\n arm as Input,\n of,\n seen,\n positive === (key !== \"NOT\")\n )\n );\n if (arms.length === 0) {\n // An empty OR holds of nothing; an empty AND or NOT asks nothing.\n if (key === \"OR\") clauses.push(sql.raw(positive ? \"false\" : \"true\"));\n continue;\n }\n clauses.push(sql`(${sql.join(arms, key === \"OR\" ? any : all)})`);\n continue;\n }\n const filter = value as Input;\n const aggregated = AGGREGATE_NAMES.filter(\n (aggregate) => filter[aggregate] !== undefined\n );\n if (aggregated.length === 0) {\n clauses.push(\n this.predicate(\n this.#queries.prepareSelector(model, { [key]: value }).predicate!,\n positive\n )\n );\n continue;\n }\n for (const aggregate of aggregated) {\n const counted = aggregate === \"_count\";\n clauses.push(\n this.#compare(\n model,\n key,\n counted,\n of(aggregate, key),\n filter[aggregate] as Input,\n positive,\n counted ? undefined : seen(key)\n )\n );\n }\n }\n return clauses.length\n ? sql`(${sql.join(clauses, all)})`\n : sql.raw(positive ? \"true\" : \"false\");\n }\n\n /** `seen`, where one is given, counts the values: none is an aggregate's NULL. */\n #compare(\n model: AnyModel,\n field: string,\n counted: boolean,\n expression: Sql,\n filter: Input,\n positive: boolean,\n seen?: Sql\n ): Sql {\n const bind = (value: unknown) =>\n counted\n ? sql`${value}`\n : this.#namesDecimal(model, field)\n ? this.#decimalOperand(value)\n : this.value(model, field, value);\n const given = Object.entries(filter).filter(\n ([, operand]) => operand !== undefined\n );\n if (given.length === 0) return sql.raw(positive ? \"true\" : \"false\");\n const known = (test: Sql) => {\n const asked = positive ? test : sql`!(${test})`;\n return seen ? sql`(${seen} > 0 AND ${asked})` : asked;\n };\n const tests = given.map(([operator, operand]) => {\n const nested = (inner: Input, sign: boolean) =>\n this.#compare(model, field, counted, expression, inner, sign, seen);\n if (operator === \"not\") return nested({ equals: operand }, !positive);\n if (operator === \"equals\" && operand === null) {\n if (!seen) return sql.raw(positive ? \"false\" : \"true\");\n return sql`${seen} ${sql.raw(positive ? \"=\" : \">\")} 0`;\n }\n if (COMPARISONS[operator])\n return known(\n sql`${expression} ${sql.raw(COMPARISONS[operator])} ${bind(operand)}`\n );\n if (operator === \"in\" || operator === \"notIn\") {\n const members = operand as unknown[];\n // An empty list asks nothing of the group, so a missing value does not matter.\n if (members.length === 0)\n return sql.raw(\n (operator === \"notIn\") === positive ? \"true\" : \"false\"\n );\n return known(\n sql`${expression} ${sql.raw(operator === \"in\" ? \"IN\" : \"NOT IN\")} [${sql.join(members.map(bind), \", \")}]`\n );\n }\n return refuse(`the '${operator}' operator in a having`);\n });\n return sql`(${sql.join(tests, positive ? \" AND \" : \" OR \")})`;\n }\n\n /** A group's order, with a flag for what is NULL: as PostgreSQL, the largest. */\n #groupOrder(\n model: AnyModel,\n input: unknown,\n of: (aggregate: string, field: string) => Sql,\n seen: (field: string) => Sql,\n by: readonly string[]\n ): { readonly order: Sql[]; readonly flags: Sql[] } {\n const order: Sql[] = [];\n const flags: Sql[] = [];\n const nullable = (field: string) =>\n model[\"~\"].state.scalars[field]?.[\"~\"].state.nullable === true ||\n this.#gatedHere(model, field);\n const term = (\n value: Sql,\n missing: Sql | undefined,\n sort: unknown,\n nulls?: unknown\n ) => {\n if (missing) {\n const flag = name(`__m${flags.length}`);\n flags.push(sql`(${missing}) AS ${flag}`);\n const first =\n (nulls ?? (sort === \"desc\" ? \"first\" : \"last\")) === \"first\";\n order.push(sql`${flag} ${sql.raw(first ? \"DESC\" : \"ASC\")}`);\n }\n order.push(sql`${value} ${sql.raw(sort === \"desc\" ? \"DESC\" : \"ASC\")}`);\n };\n // A group's field orders by its alias, and one naming a decimal by a number of its own.\n const grouped = (field: string) => {\n if (!this.#namesDecimal(model, field)) return name(field);\n const sorted = name(`__s${flags.length}`);\n flags.push(sql`${this.#numeric(name(field), false)} AS ${sorted}`);\n return sorted;\n };\n for (const entry of input === undefined ? [] : [input].flat()) {\n for (const [key, spec] of Object.entries(entry as Input)) {\n if (spec === undefined) continue;\n if (AGGREGATE_NAMES.includes(key)) {\n for (const [field, direction] of Object.entries(spec as Input))\n term(\n of(key, field),\n key !== \"_count\" && field !== \"_all\" && nullable(field)\n ? sql`${seen(field)} = 0`\n : undefined,\n direction\n );\n continue;\n }\n const { sort, nulls } = (\n typeof spec === \"string\" ? { sort: spec } : spec\n ) as Input;\n term(\n grouped(key),\n nullable(key) ? sql`${name(key)} = NONE` : undefined,\n sort,\n nulls\n );\n }\n }\n if (order.length === 0)\n for (const field of by)\n term(\n grouped(field),\n nullable(field) ? sql`${name(field)} = NONE` : undefined,\n \"asc\"\n );\n return { order, flags };\n }\n\n /**\n * The key order, as a mutation limit reads it: what the rows must also select\n * (`ORDER BY` reads only a field, so an expression is read by its alias), and\n * the order.\n */\n order(\n model: AnyModel,\n input: Arguments[\"orderBy\"]\n ): { readonly extras: Sql[]; readonly order: Sql } {\n const { extras, order } = this.#ordered(this.#orderTerms(model, input));\n return { extras, order: sql.join(order, \", \") };\n }\n\n #filter(model: AnyModel, args: Arguments): PreparedPredicate | undefined {\n const q = this.#queries;\n return q.scoped(\n model,\n args.where === undefined\n ? undefined\n : q.prepareSelector(model, args.where).predicate,\n \"root\"\n );\n }\n\n statement(\n model: AnyModel,\n prepared: PreparedProjection,\n args: Partial<Arguments> & {\n readonly unordered?: boolean;\n /** The order an index may serve: {@link approximateOrder}. */\n readonly nearest?: ReturnType<typeof approximateOrder>;\n },\n predicate: PreparedPredicate | undefined,\n conditions: readonly Sql[] = [],\n path?: Sql\n ): Sql {\n if (path || args.distinct?.length)\n return this.#page(\n model,\n prepared,\n args,\n path ?? name(tableOf(model)),\n predicate,\n conditions\n );\n const { from, rest, ahead, named } = this.#driven(\n model,\n predicate,\n args.take !== undefined\n );\n const listed = this.#page(\n model,\n prepared,\n named ? { ...args, named, unordered: true } : args,\n from,\n rest,\n conditions\n );\n if (!ahead)\n return this.#nearest(\n model,\n prepared,\n args,\n from,\n rest,\n conditions,\n listed\n );\n // The list is complete or it is not, and only a read can tell. What the walk\n // computes for itself waits in its own branch, where it may never run.\n const lets = this.#lets;\n const own: Sql[] = [];\n this.#lets = own;\n this.#walking = ahead.arm;\n // Too many hold for a list: the page reads in order, following each row's links.\n const walked = this.judgingAll(() =>\n this.#page(\n model,\n prepared,\n args,\n name(tableOf(model)),\n predicate,\n conditions\n )\n );\n this.#walking = undefined;\n this.#lets = lets;\n return sql`IF array::len(${ahead.rows}) < ${sql.raw(String(HOLDERS_AHEAD))} { ${listed} } ELSE { ${sql.join([...own, walked], \" \")} }`;\n }\n\n /**\n * A page an HNSW index may answer: its nearest `k` among the rows the filter\n * keeps, in the exact order. `<|k,ef|>` reads an HNSW index on the field, and\n * the first one when there are several, whatever its distance: so only a\n * table's one declared index of this distance, on a field no gate masks,\n * read from the table itself (a named record or a list of ids holds no\n * index: it answers nothing). With no such index built, it answers nothing,\n * so then — or with nothing left beside it — the exact page answers.\n */\n #nearest(\n model: AnyModel,\n prepared: PreparedProjection,\n args: Parameters<SurrealReadBackend[\"statement\"]>[2],\n from: Sql,\n rest: PreparedPredicate | undefined,\n conditions: readonly Sql[],\n exact: Sql\n ): Sql {\n const nearest = args.nearest;\n if (\n !nearest ||\n from.toStatement() !== name(tableOf(model)).toStatement() ||\n this.#gatedHere(model, nearest.field)\n )\n return exact;\n const to = nearest.distance.to as number[];\n const indexes = nearestIndexesOf(model).filter(\n (index) => index.field === nearest.field\n );\n const index = indexes.length === 1 ? indexes[0] : undefined;\n if (\n !index ||\n index.distance !== DISTANCES[nearest.distance.metric as string] ||\n (index.dimension !== undefined && index.dimension !== to.length)\n )\n return exact;\n const column = this.physical(model, nearest.field);\n const searched = sql`${column} ${sql.raw(\n `<|${nearest.take},${Math.max(EF_SEARCH, nearest.take)}|>`\n )} ${to}`;\n // An index may hold a zero vector among a cosine's nearest, which has no\n // cosine: it is left out, as an index leaves it out on PostgreSQL.\n const directed =\n nearest.distance.metric === \"cosine\"\n ? [sql`vector::magnitude(${column}) > 0`]\n : [];\n const found = this.#hoist(\n this.#page(model, prepared, args, from, rest, [\n ...conditions,\n searched,\n ...directed,\n ])\n );\n return found\n ? sql`IF array::len(${found}) > 0 { ${found} } ELSE { ${exact} }`\n : exact;\n }\n\n /** One page of rows, from wherever a statement reads them. */\n #page(\n model: AnyModel,\n prepared: PreparedProjection,\n args: Partial<Arguments> & {\n readonly named?: boolean;\n readonly unordered?: boolean;\n },\n from: Sql,\n rest: PreparedPredicate | undefined,\n conditions: readonly Sql[]\n ): Sql {\n this.#cursorGuard = undefined;\n this.#guardsCursor = true;\n const fromTable =\n this.#inRelation === 0 &&\n !this.#walking &&\n (args.named === true ||\n from.toStatement() === name(tableOf(model)).toStatement());\n const { extras, clauses } = this.#clauses(\n model,\n { ...args, fromTable },\n rest,\n conditions\n );\n this.#guardsCursor = false;\n let count = Number(args.take ?? 0);\n if (count <= 0)\n count = Number(\n args.named === true ||\n (rest !== undefined && this.#namesOneRow(model, rest))\n );\n const statedOnce = sql.join(clauses, \" \");\n this.#parents =\n fromTable &&\n args.cursor === undefined &&\n !args.distinct &&\n extras.length === 0 &&\n count > 0 &&\n count <= PARENTS_READ_APART &&\n !HOLDS_SUBQUERY.test(statedOnce.toStatement())\n ? { read: sql`(SELECT VALUE id FROM ${from} ${statedOnce})`, count }\n : undefined;\n const guard = this.#cursorGuard as Sql | undefined;\n const guarded = (body: Sql) =>\n guard ? sql`IF ${guard} { ${body} } ELSE { [] }` : body;\n // An alias that names another column would answer an `ORDER BY` of it, so\n // the rows are chosen under their own names and named after.\n const columns = this.#queries.schema.storedFields(model);\n const shadowed = prepared.fields.some((field) =>\n columns.some(\n (other) =>\n other !== field.name &&\n this.#queries.columnName(model, other) === field.name\n )\n );\n const stated = this.columns(prepared);\n this.#parents = undefined;\n if (shadowed)\n return guarded(\n sql`SELECT ${stated} FROM (${sql.join(\n [\n sql`SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${from}`,\n ...clauses,\n ],\n \" \"\n )})`\n );\n return guarded(\n sql.join(\n [\n sql`SELECT ${sql.join([stated, ...extras], \", \")} FROM ${from}`,\n ...clauses,\n ],\n \" \"\n )\n );\n }\n\n /**\n * A correlated read never walks an index in order: `<~` reads every reference and\n * sorts them, whatever the page takes, where a read of a statement's own variable\n * seeks. So a page of few rows reads ahead which they are, and each one's children\n * in a read of its own. Each read is stated once per row, which only a filter\n * without a subquery of its own, or a row above it, can afford.\n */\n #pagesOfParents(\n edge: Reference,\n predicate: PreparedPredicate | undefined,\n args: Relation[\"arguments\"]\n ): Sql | undefined {\n const parents = this.#parents;\n if (\n !parents ||\n this.#inRelation !== 1 ||\n !this.#linked(edge) ||\n Number(args.take ?? 0) <= 0 ||\n args.cursor !== undefined ||\n args.distinct\n )\n return undefined;\n parents.ids ??= this.#hoist(parents.read);\n if (!parents.ids) return undefined;\n const { target } = edge;\n const link = name(this.#queries.columnName(target, edge.pairs[0]!.target));\n const pages: Sql[] = [];\n for (let at = 0; at < parents.count; at++) {\n const { extras, clauses } = this.#clauses(\n target,\n { ...args, fromTable: true },\n predicate,\n [sql`${link} = ${parents.ids}[${sql.raw(String(at))}]`]\n );\n const page = sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")})`;\n if (\n at === 0 &&\n (HOLDS_SUBQUERY.test(sql.join(clauses, \" \").toStatement()) ||\n READS_A_ROW_ABOVE.test(sql.join(clauses, \" \").toStatement()))\n )\n return undefined;\n pages.push(page);\n }\n const read = this.#hoist(sql`[${sql.join(pages, \", \")}]`);\n return read && sql`${read}[array::find_index(${parents.ids}, $this.id)]`;\n }\n\n /** The row `identity` names, every key field equal. */\n identity(model: AnyModel, identity: Input): Sql {\n const keys = this.#queries.keyOrder(model);\n const named = Object.keys(identity);\n if (keys.length > 1 && keys.every((key) => named.includes(key)))\n return sql`id = ${this.recordOf(model, identity)}`;\n return sql.join(\n Object.entries(identity).map(\n ([field, value]) =>\n sql`${this.physical(model, field)} = ${this.value(model, field, value)}`\n ),\n \" AND \"\n );\n }\n\n /** The record a row's key fields name, however many there are. */\n recordOfRow(model: AnyModel, row: Input): Sql {\n const keys = this.#queries.keyOrder(model);\n return keys.length === 1\n ? this.value(model, keys[0]!, row[keys[0]!])\n : sql`${this.recordOf(model, row)}`;\n }\n\n /** A compound key's record. */\n recordOf(model: AnyModel, row: Input): RecordId {\n return new RecordId(\n tableOf(model),\n this.#queries\n .keyOrder(model)\n .map((key) => this.#part(model, key, row[key])) as never\n );\n }\n\n /** One stated part of an array id, as a value. */\n keyPart(model: AnyModel, field: string, value: unknown): Sql {\n return sql`${this.#part(model, field, value)}`;\n }\n\n /** One part of an array id: a link stays a record, as its field holds it. */\n #part(model: AnyModel, field: string, value: unknown): unknown {\n for (const slot of Object.keys(model[\"~\"].state.relations)) {\n const { edges } = this.#queries.countedMemberships(model, slot);\n const edge = edges[0];\n if (\n edges.length === 1 &&\n edge?.kind === \"reference\" &&\n edge.owner === \"source\" &&\n edge.pairs.length === 1 &&\n edge.pairs[0]!.source === field &&\n isSingleKey(this.#queries, edge.target, edge.pairs[0]!.target)\n )\n return new RecordId(tableOf(edge.target), value as string);\n }\n return stored(model[\"~\"].state.scalars[field]?.[\"~\"].state, value);\n }\n\n /** The target rows of `edge` for this parent. */\n member(edge: Membership, parent: Input): Sql {\n if (edge.kind === \"junction\") {\n const list = edge.declared\n ? this.#declaredOf(edge, parent)\n : this.membersOf(edge, parent);\n return sql`id IN ${list}`;\n }\n const reached = reference(edge);\n const held = reached.pairs.map(({ source }) => parent[source]);\n const { discriminator } = reached;\n if (\n held.some((value) => value === null || value === undefined) ||\n (discriminator?.side === \"source\" &&\n parent[discriminator.field] !== discriminator.value)\n )\n return sql.raw(\"false\");\n return sql.join(\n [\n ...reached.pairs.map(\n ({ target }, index) =>\n sql`${this.physical(reached.target, target)} = ${this.value(reached.target, target, held[index])}`\n ),\n ...(discriminator?.side === \"target\"\n ? [\n sql`${this.physical(reached.target, discriminator.field)} = ${discriminator.value}`,\n ]\n : []),\n ],\n \" AND \"\n );\n }\n\n /**\n * A generated junction as an edge table. `in` is its canonical first side, so\n * the direction does not depend on which model declared the relation, and a\n * self relation tells its two directions apart by it.\n */\n edgeOf(edge: Junction) {\n const resolved = edge.scope.edge;\n if (edge.declared) refuse(\"a declared junction as an edge\");\n const topology =\n resolved.kind === \"junction\"\n ? resolved.topology\n : resolved.kind === \"variantJunctionCarrier\"\n ? (edge.scope.member as VariantJunctionMember).topology\n : refuse(\"this junction\");\n for (const side of [edge.sourceSide, edge.targetSide]) {\n const keys = this.#queries.keyOrder(side.model);\n if (\n side.members.length !== keys.length ||\n !side.members.every((pair) => keys.includes(pair.referencedField))\n )\n refuse(\"a junction over anything but a record's own key\");\n }\n const first = topology.sourceIsFirst ? topology.source : topology.target;\n const outward = edge.sourceSide === first;\n const arrow = outward ? \"->\" : \"<-\";\n return {\n table: name(edge.table),\n near: name(outward ? \"in\" : \"out\"),\n far: name(outward ? \"out\" : \"in\"),\n hop: sql.raw(`${arrow}${name(edge.table).toStatement()}${arrow}`),\n back: sql.raw(\n `${outward ? \"<-\" : \"->\"}${name(edge.table).toStatement()}${outward ? \"<-\" : \"->\"}`\n ),\n out: sql.raw(`${arrow}${name(edge.table).toStatement()}`),\n };\n }\n\n /** The field of a declared junction's model that holds this column. */\n #linkField(edge: Junction, column: string): string {\n const model = edge.declared!.model;\n const field = this.#queries.schema\n .storedFields(model)\n .find((name) => this.#queries.columnName(model, name) === column);\n return field ?? refuse(`the link column '${column}'`);\n }\n\n /** Whether a field reads as a record: a key, or a link to one. */\n #isRecord(model: AnyModel, field: string): boolean {\n return (\n isSingleKey(this.#queries, model, field) || this.holdsRecord(model, field)\n );\n }\n\n /** Whether a model's field holds a record rather than the key's own value. */\n holdsRecord(model: AnyModel, field: string): boolean {\n const q = this.#queries;\n return Object.keys(model[\"~\"].state.relations).some((slot) => {\n const { edges } = q.countedMemberships(model, slot);\n const edge = edges[0];\n return (\n edges.length === 1 &&\n edge?.kind === \"reference\" &&\n edge.owner === \"source\" &&\n edge.pairs.length === 1 &&\n edge.pairs[0]!.source === field &&\n isSingleKey(q, edge.target, edge.pairs[0]!.target)\n );\n });\n }\n\n /** This link's columns against the row a variable holds, one side of it. */\n #linkMatch(edge: Junction, side: Junction[\"sourceSide\"], row: string): Sql[] {\n const link = edge.declared!.model;\n return side.members.map((pair) => {\n const field = this.#linkField(edge, pair.junctionField);\n const held = sql`${sql.raw(row)}.${this.physical(side.model, pair.referencedField)}`;\n const plainKey =\n isSingleKey(this.#queries, side.model, pair.referencedField) &&\n !this.holdsRecord(link, field);\n return sql`${this.physical(link, field)} = ${plainKey ? sql`record::id(${held})` : held}`;\n });\n }\n\n /** The record of a side, read from a link row a variable or the row itself holds. */\n linkTarget(edge: Junction, side: Junction[\"sourceSide\"], row: string): Sql {\n const link = edge.declared!.model;\n const keys = this.#queries.keyOrder(side.model);\n // A link over fields other than the key names its record by looking it up.\n if (\n !keys.every((key) => side.members.some((m) => m.referencedField === key))\n ) {\n const named = side.members.map((pair) => {\n const column = this.physical(\n link,\n this.#linkField(edge, pair.junctionField)\n );\n return sql`${this.physical(side.model, pair.referencedField)} = ${sql.raw(row || \"$parent\")}.${column}`;\n });\n return sql`(SELECT VALUE id FROM ${name(tableOf(side.model))} WHERE ${sql.join(named, \" AND \")} LIMIT 1)[0]`;\n }\n const parts = keys.map((key) => {\n const pair = side.members.find(\n (member) => member.referencedField === key\n )!;\n const field = this.#linkField(edge, pair.junctionField);\n const column = this.physical(link, field);\n return {\n read: row ? sql`${sql.raw(row)}.${column}` : column,\n record: this.holdsRecord(link, field),\n };\n });\n if (parts.length === 1 && parts[0]!.record) return parts[0]!.read;\n const key =\n parts.length === 1\n ? parts[0]!.read\n : sql`[${sql.join(\n parts.map((part) => part.read),\n \", \"\n )}]`;\n return sql`type::record(${tableOf(side.model)}, ${key})`;\n }\n\n /** A row's links through a declared junction, narrowed by the link's own filter. */\n #links(edge: Junction, row: string, where?: PreparedPredicate): Sql {\n const conditions = [\n ...this.#linkMatch(edge, edge.sourceSide, row),\n ...(where ? [this.predicate(where, true)] : []),\n ];\n return sql`(SELECT * FROM ${name(tableOf(edge.declared!.model))} WHERE ${sql.join(conditions, \" AND \")})`;\n }\n\n /** The record one side of a junction holds, however its key is spelled in `read`. */\n end(side: Junction[\"sourceSide\"], read: (pair: Member) => unknown): Sql {\n if (side.members.length === 1) {\n const pair = side.members[0]!;\n return this.value(side.model, pair.referencedField, read(pair));\n }\n const row = Object.fromEntries(\n side.members.map((pair) => [pair.referencedField, read(pair)])\n );\n return sql`${this.recordOf(side.model, row)}`;\n }\n\n /** The field of a declared junction's model that a column names, for its writes. */\n linkFieldOf(edge: Junction, column: string): string {\n return this.#linkField(edge, column);\n }\n\n /** The target records of a declared junction for a parent's known values. */\n #declaredOf(edge: Junction, parent: Input): Sql {\n const link = edge.declared!.model;\n const conditions = edge.sourceSide.members.map((pair) => {\n const field = this.#linkField(edge, pair.junctionField);\n return sql`${this.physical(link, field)} = ${this.value(link, field, parent[pair.referencedField])}`;\n });\n return sql`(SELECT VALUE ${this.linkTarget(edge, edge.targetSide, \"\")} FROM ${name(tableOf(link))} WHERE ${sql.join(conditions, \" AND \")})`;\n }\n\n /** The path from one record to its members through an edge table. */\n membersOf(edge: Junction, parent: Input): Sql {\n const { hop } = this.edgeOf(edge);\n const start = this.end(\n edge.sourceSide,\n (pair) => parent[pair.referencedField]\n );\n return sql`${start}${hop}${name(tableOf(edge.target))}`;\n }\n\n #clauses(\n model: AnyModel,\n args: Pick<\n Partial<Arguments>,\n \"orderBy\" | \"take\" | \"skip\" | \"cursor\" | \"distinct\"\n > & {\n readonly unordered?: boolean;\n readonly fromTable?: boolean;\n readonly named?: boolean;\n },\n predicate: PreparedPredicate | undefined,\n conditions: readonly Sql[] = []\n ): { readonly extras: Sql[]; readonly clauses: Sql[] } {\n const { terms, forward } = this.#ordering(model, args);\n const { extras, order } = this.#ordered(terms);\n const located = [\n ...(predicate\n ? args.named\n ? this.located(model, predicate, true)\n : this.located(model, predicate)\n : []),\n ...conditions,\n ];\n const cursor =\n args.cursor === undefined\n ? []\n : [this.#cursor(model, args.cursor as Input, terms)];\n const clauses: Sql[] = [];\n const distinct = args.distinct as string[] | undefined;\n if (this.#distinctly(model, distinct)) {\n // Each tuple's row is chosen in the caller's order, whichever way this page reads.\n const chosen = this.#ordered(forward);\n // The cursor is among what a tuple's row is chosen from, as `DISTINCT ON`\n // reads only what its `WHERE` leaves.\n clauses.push(\n sql`WHERE ${this.#distinct(\n model,\n distinct!,\n [...located, ...cursor],\n chosen.order,\n chosen.extras\n )}`\n );\n } else {\n const where = onceEach([...located, ...cursor]);\n const bound = args.fromTable\n ? this.#pageBound(model, args, terms, where)\n : undefined;\n const all = bound ? [...where, bound] : where;\n if (all.length > 0) clauses.push(sql`WHERE ${sql.join(all, \" AND \")}`);\n }\n if (!args.unordered) clauses.push(sql`ORDER BY ${sql.join(order, \", \")}`);\n // A bound LIMIT is what a nested read's index needs written, so both inline\n // an integer admission has already checked.\n if (args.take !== undefined)\n clauses.push(sql.raw(`LIMIT ${Math.abs(Number(args.take))}`));\n if (args.skip !== undefined)\n clauses.push(sql.raw(`START ${Number(args.skip)}`));\n return { extras, clauses };\n }\n\n /**\n * A descending page over an ascending key has an order no index holds, so it sorts\n * every row. The first term's value at the page's last row bounds what it sorts,\n * and an index finds that value walking no further than the page. Short of that\n * many rows there is no value, and every row is at least NONE.\n */\n #pageBound(\n model: AnyModel,\n args: Pick<Partial<Arguments>, \"take\" | \"skip\">,\n terms: readonly OrderTerm[],\n where: readonly Sql[]\n ): Sql | undefined {\n const [first, ...rest] = terms;\n const take = Math.abs(Number(args.take ?? 0));\n if (\n take === 0 ||\n first?.field === undefined ||\n !first.descending ||\n first.nullable ||\n rest.every((term) => term.descending) ||\n !this.#indexed(model, first.field)\n )\n return undefined;\n const filter = where.length\n ? sql`WHERE ${sql.join(where, \" AND \")} `\n : sql.raw(\"\");\n // Stating subqueries twice costs more to compile than the sort does to run.\n if (HOLDS_SUBQUERY.test(filter.toStatement())) return undefined;\n const value = this.#hoist(\n sql`(SELECT VALUE ${first.expression} FROM ${name(tableOf(model))} ${filter}ORDER BY ${first.expression} DESC LIMIT 1 START ${sql.raw(String(take + Number(args.skip ?? 0) - 1))})[0]`\n );\n return value && sql`${first.expression} >= ${value}`;\n }\n\n /** The terms a read walks, and those of the caller's own order. */\n #ordering(\n model: AnyModel,\n args: Pick<Partial<Arguments>, \"orderBy\" | \"take\">\n ): { readonly terms: OrderTerm[]; readonly forward: OrderTerm[] } {\n const forward = this.#orderTerms(model, args.orderBy);\n return {\n forward,\n terms:\n (args.take ?? 0) < 0\n ? forward.map((term) => ({\n ...term,\n descending: !term.descending,\n nulls:\n term.nulls &&\n (term.nulls === \"first\"\n ? (\"last\" as const)\n : (\"first\" as const)),\n }))\n : forward,\n };\n }\n\n /** Terms as `ORDER BY` reads them. A missing value sorts by its own flag. */\n #ordered(terms: readonly OrderTerm[]): {\n readonly extras: Sql[];\n readonly order: Sql[];\n } {\n const extras: Sql[] = [];\n const order = terms.flatMap((term, index) => {\n const direction = sql.raw(term.descending ? \"DESC\" : \"ASC\");\n let reads = term.expression;\n if (!term.named) {\n reads = name(`__o${index}`);\n extras.push(sql`${term.expression} AS ${reads}`);\n }\n if (!term.nullable) return [sql`${reads} ${direction}`];\n const missing = name(`__m${index}`);\n extras.push(sql`(${term.expression} = NONE) AS ${missing}`);\n return [\n sql`${missing} ${sql.raw(term.nulls === \"first\" ? \"DESC\" : \"ASC\")}`,\n sql`${reads} ${direction}`,\n ];\n });\n return { extras, order };\n }\n\n /** The first row of each tuple, in this read's own order: `GROUP BY` keeps it. */\n #distinct(\n model: AnyModel,\n fields: readonly string[],\n where: readonly Sql[],\n order: readonly Sql[],\n extras: readonly Sql[]\n ): Sql {\n const table = name(tableOf(model));\n // A gated field groups by its alias: `GROUP BY` takes no expression.\n const columns = fields.map((field, index) =>\n this.#gatedHere(model, field)\n ? {\n read: sql`${this.#operand(model, field)} AS ${sql.raw(`__d${index}`)}`,\n group: sql.raw(`__d${index}`),\n }\n : {\n read: this.physical(model, field),\n group: this.physical(model, field),\n }\n );\n const filter = where.length\n ? sql`WHERE ${sql.join(where, \" AND \")} `\n : sql.raw(\"\");\n const ordered = sql`SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${table} ${filter}ORDER BY ${sql.join(order, \", \")}`;\n const tuple = sql.join(\n columns.map(({ read }) => read),\n \", \"\n );\n const grouped = sql.join(\n columns.map(({ group }) => group),\n \", \"\n );\n return sql`id IN (SELECT VALUE array::first(id) FROM (SELECT ${tuple}, id FROM (${ordered}) GROUP BY ${grouped}))`;\n }\n\n /** The rows from the cursor's on, in the order this read walks them. */\n #cursor(model: AnyModel, cursor: Input, terms: readonly OrderTerm[]): Sql {\n const table = name(tableOf(model));\n // The anchor is a candidate like any other: a hidden one is a missing one.\n const q = this.#queries;\n const stated = q.scoped(\n model,\n q.prepareSelector(model, cursor, true, false).predicate,\n this.#inRelation > 0 ? \"related\" : \"root\"\n )!;\n // A cursor that states its key is the record itself, read without a filter.\n const named = this.namedRecord(model, stated);\n const source = named?.record ?? table;\n const asked = named ? named.rest : stated;\n const located = asked\n ? sql` WHERE ${this.predicate(asked, true)}`\n : sql.raw(\"\");\n const walked = terms.flatMap((term): OrderTerm[] =>\n term.nullable\n ? [\n {\n ...term,\n expression: sql`(${term.expression} = NONE)`,\n descending: term.nulls === \"first\",\n },\n term,\n ]\n : [term]\n );\n // The anchor's values in one read, ahead of the statement where a statement can:\n // in a `WHERE` it would run for each row the scan passes.\n const read = sql`(SELECT ${sql.join(\n walked.map(\n (term, index) => sql`${term.expression} AS ${sql.raw(`c${index}`)}`\n ),\n \", \"\n )} FROM ${source}${located} LIMIT 1)[0]`;\n const anchor = this.#hoist(read) ?? read;\n const found = sql`${anchor} != NONE`;\n // `a >= x AND (a > x OR …)`: the same rows as `a > x OR (a = x AND …)`, which\n // reads two ranges of an index and sorts them, where this walks one in order.\n const after = walked.reduceRight<Sql | undefined>((rest, term, index) => {\n const value = sql`${anchor}.${sql.raw(`c${index}`)}`;\n const reached = sql`${term.expression} ${sql.raw(term.descending ? \"<=\" : \">=\")} ${value}`;\n if (!rest) return reached;\n return sql`${reached} AND (${term.expression} ${sql.raw(term.descending ? \"<\" : \">\")} ${value} OR (${rest}))`;\n }, undefined)!;\n // Beside a bare condition, a seek on the key becomes a scan, so where a whole\n // statement can answer \"no such cursor\", it answers ahead of its `WHERE`.\n if (this.#guardsCursor && this.#lets) {\n this.#cursorGuard = found;\n return after;\n }\n return sql`(${found} AND ${after})`;\n }\n\n /** The caller's order, completed by the key: every page has one total order. */\n #orderTerms(model: AnyModel, input: Arguments[\"orderBy\"]): OrderTerm[] {\n const q = this.#queries;\n const terms: OrderTerm[] = [];\n const ordered = new Set<string>();\n const stated = input ?? q.orderOf(model);\n const orders = stated === undefined ? [] : [stated].flat();\n for (const order of orders) {\n for (const [field, spec] of Object.entries(order)) {\n if (spec === undefined) continue;\n if (model[\"~\"].state.relations[field]) {\n terms.push(this.#relationOrder(model, field, spec as Input));\n continue;\n }\n ordered.add(field);\n terms.push(this.#scalarOrder(model, field, spec, \"\"));\n }\n }\n for (const field of q.keyOrder(model)) {\n if (ordered.has(field)) continue;\n const plain = !this.#namesDecimal(model, field);\n terms.push({\n expression: plain\n ? this.#operand(model, field)\n : this.#numeric(\n this.#operand(model, field),\n !this.#gatedHere(model, field)\n ),\n named: plain,\n descending: false,\n nullable: false,\n });\n }\n return terms;\n }\n\n #scalarOrder(\n model: AnyModel,\n field: string,\n spec: unknown,\n path: string\n ): OrderTerm {\n const state0 = model[\"~\"].state.scalars[field]?.[\"~\"].state;\n const distance = (spec as Input | undefined)?._distance as\n | Input\n | undefined;\n if (distance && state0) {\n if (path) refuse(\"ordering by a distance through a relation\");\n return {\n expression: this.#distance(\n this.#operand(model, field),\n state0,\n field,\n distance,\n \"orderBy\"\n ),\n named: false,\n descending: distance.sort === \"desc\",\n nullable: true,\n nulls: \"last\",\n };\n }\n const { sort, nulls } = (\n typeof spec === \"string\" ? { sort: spec } : spec\n ) as { sort?: string; nulls?: \"first\" | \"last\" };\n if (sort !== \"asc\" && sort !== \"desc\")\n refuse(`ordering by '${field}' with this specification`);\n const state = model[\"~\"].state.scalars[field]?.[\"~\"].state;\n if (!state) refuse(`ordering by '${field}'`);\n const column = this.#gated(\n model,\n field,\n sql.raw(`${path}${this.physical(model, field).toStatement()}`),\n path\n );\n const plain = !this.#namesDecimal(model, field);\n return {\n expression: plain ? column : this.#numeric(column, false),\n named: plain && path === \"\" && !this.#gatedHere(model, field),\n field: plain && path === \"\" ? field : undefined,\n descending: sort === \"desc\",\n nullable:\n path !== \"\" || state.nullable === true || this.#gatedHere(model, field),\n // As PostgreSQL: a missing value counts as the largest.\n nulls: nulls ?? (sort === \"desc\" ? \"first\" : \"last\"),\n };\n }\n\n #relationOrder(\n model: AnyModel,\n field: string,\n spec: Input,\n path = \"\"\n ): OrderTerm {\n const { edges } = this.#queries.countedMemberships(model, field);\n const edge = edges[0]!;\n if (spec._count !== undefined) {\n if (path) refuse(`ordering by a count through '${field}'`);\n return {\n expression: sql.join(\n edges.map(\n (member) =>\n sql`array::len(${this.#members(member, this.#queries.scoped(member.target, undefined, \"related\"))})`\n ),\n \" + \"\n ),\n named: false,\n descending: spec._count === \"desc\",\n nullable: false,\n };\n }\n const [nested, inner] = Object.entries(spec)[0]!;\n if (edge.many) refuse(`ordering by the relation '${field}'`);\n const linked = edge.kind === \"reference\" && this.#linked(edge);\n if (path && !linked)\n refuse(`ordering by the relation '${field}' through another relation`);\n // A link is the row's own field; the other side is a lookup of the records\n // referencing the row the path has reached, which a path's last record leads.\n const prefix =\n linked && edge.owner === \"source\"\n ? `${path}${this.physical(edge.source, edge.pairs[0]!.source).toStatement()}.`\n : `(${path.slice(0, -1)}${this.#members(edge).toStatement()})[0].`;\n const term = edge.target[\"~\"].state.relations[nested]\n ? this.#relationOrder(edge.target, nested, inner as Input, prefix)\n : this.#scalarOrder(edge.target, nested, inner, prefix);\n if (this.#queries.domainOf(edge.target, \"related\") === undefined)\n return term;\n return {\n ...term,\n expression: sql`(IF ${this.#related(edge, \"some\", undefined, path)} { ${term.expression} } ELSE { NONE })`,\n named: false,\n nullable: true,\n };\n }\n\n /** Every member of a to-many, unfiltered, as a value. */\n #members(edge: Membership, predicate?: PreparedPredicate): Sql {\n if (edge.kind === \"junction\" && edge.declared) {\n const where = predicate\n ? sql` WHERE id IN $linked AND ${this.predicate(predicate, true)}`\n : sql` WHERE id IN $linked`;\n return sql`({ LET $owner = $this; LET $linked = (SELECT VALUE ${this.linkTarget(edge, edge.targetSide, \"\")} FROM ${this.#links(edge, \"$owner\")}); (SELECT VALUE id FROM ${name(tableOf(edge.target))}${where}) })`;\n }\n if (edge.kind === \"junction\") {\n const { hop } = this.edgeOf(edge);\n const target = name(tableOf(edge.target));\n return predicate\n ? sql`${hop}(${target} WHERE ${this.predicate(predicate, true)})`\n : sql`${hop}${target}`;\n }\n return this.#traversal(reference(edge), predicate, { unordered: true });\n }\n\n columns(prepared: PreparedProjection): Sql {\n return sql.join(\n prepared.fields.map((field) => this.column(prepared.model, field)),\n \", \"\n );\n }\n\n /** One projected field, as a `SELECT` or a `RETURN` lists it. */\n column(model: AnyModel, field: PreparedProjectionField): Sql {\n const { value, alias } = this.#field(model, field);\n const named = name(alias);\n // A column under its own name needs no alias, which costs a little per row.\n return value.toStatement() === named.toStatement()\n ? value\n : sql`${value} AS ${named}`;\n }\n\n #destructure(prepared: PreparedProjection): Sql {\n return sql`.{ ${sql.join(\n prepared.fields.map((field) => {\n const { value, alias } = this.#field(prepared.model, field);\n return sql`${name(alias)}: ${value}`;\n }),\n \", \"\n )} }`;\n }\n\n #field(\n model: AnyModel,\n field: PreparedProjectionField\n ): { readonly value: Sql; readonly alias: string } {\n switch (field.kind) {\n case \"scalar\": {\n const column = this.physical(model, field.name);\n const state = model[\"~\"].state.scalars[field.name]?.[\"~\"].state;\n const nullable = state?.nullable;\n // A point is GeoJSON to the database and a latitude and longitude here.\n if (state?.type === \"point\" && !state.array) {\n const point = sql`{ latitude: ${column}.coordinates[1], longitude: ${column}.coordinates[0] }`;\n return {\n value: nullable\n ? sql`(IF ${column} != NONE { ${point} } ELSE { NULL })`\n : point,\n alias: field.name,\n };\n }\n // An absent field is NONE, which the client reads as `undefined` under its\n // key, and the driver as null: `?? NULL` would cost each row for nothing.\n return { value: column, alias: field.name };\n }\n case \"relation\":\n return { value: this.#relation(field), alias: field.name };\n case \"gate\":\n return {\n value: this.#truth(this.#gateHolds(model, field.gate)),\n alias: field.name,\n };\n case \"evidence\":\n return { value: this.#evidence(model, field), alias: field.name };\n case \"sentinel\":\n return { value: sql.raw(\"true\"), alias: field.name };\n case \"distance\": {\n const state = model[\"~\"].state.scalars[field.field]![\"~\"].state;\n const distance = this.#distance(\n this.physical(model, field.field),\n state,\n field.field,\n field.specification,\n \"select\"\n );\n return { value: sql`(${distance} ?? NULL)`, alias: field.name };\n }\n case \"variants\":\n return {\n value: sql`{ ${sql.join(\n field.arms.map((arm) => {\n const row = this.#relation({\n kind: \"relation\",\n name: arm.variant,\n ...arm,\n });\n const edge = arm.edge;\n if (field.many || edge.kind !== \"reference\")\n return sql`${name(arm.variant)}: ${row}`;\n // A claimed arm whose row is gone is an empty document, which\n // the decoder refuses; an unclaimed one is an empty slot.\n const claim = this.physical(\n edge.source,\n edge.discriminator!.field\n );\n return sql`${name(arm.variant)}: (IF ${claim} = ${edge.discriminator!.value} { ${row} ?? ${this.#absentArm(edge)} } ELSE { NULL })`;\n }),\n \", \"\n )} }`,\n alias: field.name,\n };\n case \"counts\":\n return {\n value: sql`{ ${sql.join(\n field.counts.map((count) => {\n const predicate = count.selector?.predicate;\n const counted =\n predicate && count.negated\n ? ({ kind: \"not\", predicate } as const)\n : predicate;\n const lengths = count.edges.map(\n (edge) =>\n sql`array::len(${this.#members(edge, this.#queries.scoped(edge.target, counted, \"related\"))})`\n );\n return sql`${name(count.relation)}: ${sql.join(lengths, \" + \")}`;\n }),\n \", \"\n )} }`,\n alias: field.name,\n };\n default:\n return refuse(`a '${(field as { kind: string }).kind}' projection`);\n }\n }\n\n /** Whether a layer's `input` holds of this row; `undefined` where it always does. */\n #layerHolds(\n model: AnyModel,\n layer: number,\n input: Input,\n path = \"\"\n ): Sql | undefined {\n const { predicate } = this.#queries.domain!.project!.layered(\n model,\n layer,\n input\n );\n return predicate && this.predicate(predicate, true, path);\n }\n\n /**\n * A column as an operand the caller wrote: a read-gated field is absent on a row\n * that does not carry it, wherever it is read. Every such row is one the domain\n * takes, so `read` holds there and the field's own predicate decides. A layer's\n * predicates read the column itself.\n */\n #gated(model: AnyModel, field: string, column: Sql, path = \"\"): Sql {\n const q = this.#queries;\n if (q.lowersLayer) return column;\n const gate = q.domain?.project?.projected(model)?.gates.get(field);\n if (!gate) return column;\n const held = gate.flatMap(([layer, read, input]) => {\n if (input === read) return [];\n const lowered = this.#layerHolds(model, layer, input);\n return lowered ? [lowered] : [];\n });\n if (held.length === 0) return column;\n const holds = sql.join(held, \" AND \");\n return path\n ? sql`(IF array::len(SELECT VALUE id FROM $this.${sql.raw(path.slice(0, -1))} WHERE ${holds}) > 0 { ${column} } ELSE { NONE })`\n : sql`(IF ${holds} { ${column} } ELSE { NONE })`;\n }\n\n /** Whether an operand over this field can read absent because of its gate. */\n #gatedHere(model: AnyModel, field: string): boolean {\n const q = this.#queries;\n return (\n !q.lowersLayer &&\n q.domain?.project?.projected(model)?.gates.has(field) === true\n );\n }\n\n #operand(model: AnyModel, field: string): Sql {\n return this.#gated(model, field, this.physical(model, field));\n }\n\n /**\n * Whether `field` holds a record that names a decimal by its text, a key or a link\n * to one: as text, 10 sorts before 2, so it compares and sorts as {@link #numeric}.\n * (A dateTime's text is as wide at every instant it holds, and sorts as it does.)\n */\n #namesDecimal(model: AnyModel, field: string): boolean {\n return (\n model[\"~\"].state.scalars[field]?.[\"~\"].state.type === \"decimal\" &&\n this.#isRecord(model, field)\n );\n }\n\n /**\n * The number the record `column` reads names ({@link #namesDecimal}): no index\n * holds it, so a read that compares or sorts by it reads every row. A missing\n * record stays missing; `present` where the row's own key is read, never missing.\n */\n #numeric(column: Sql, present: boolean): Sql {\n const value = sql`<decimal>record::id(${column})`;\n return present ? value : sql`(IF ${column} { ${value} })`;\n }\n\n /** What a {@link #numeric} column compares with: the number a value is. */\n #decimalOperand(value: unknown): Sql {\n return value instanceof Sql\n ? sql`<decimal>${value}`\n : sql`<decimal>${String(value)}`;\n }\n\n /** Where a read-gated field's row carries it: every gating layer's `read` and predicate. */\n #gateHolds(model: AnyModel, gate: FieldGate): Sql | undefined {\n const held = gate.flatMap(([layer, read, input]) =>\n (input === read ? [read] : [read, input]).flatMap((where) => {\n const lowered = this.#layerHolds(model, layer, where);\n return lowered ? [lowered] : [];\n })\n );\n return held.length ? sql`(${sql.join(held, \" AND \")})` : undefined;\n }\n\n /** A condition as a value: true or false, never unset. */\n #truth(condition: Sql | undefined): Sql {\n return condition\n ? sql`(IF ${condition} { true } ELSE { false })`\n : sql.raw(\"true\");\n }\n\n /** A declared projection key on this row: the layer's `read` around one boolean per name. */\n #evidence(\n model: AnyModel,\n field: Extract<PreparedProjectionField, { kind: \"evidence\" }>\n ): Sql {\n const { layer, read } = field.evidence;\n const visible = this.#layerHolds(model, layer, read);\n const test = (input: Input) =>\n input === read ? undefined : this.#layerHolds(model, layer, input);\n const held = sql.join(\n field.names.map(\n ([name, input]) =>\n sql`${sql.raw(JSON.stringify(name))}: ${this.#truth(test(input))}`\n ),\n \", \"\n );\n if (!visible) return sql`{ ${held} }`;\n const none = field.names\n .map(([name]) => `${JSON.stringify(name)}: false`)\n .join(\", \");\n return sql`(IF ${visible} { { ${held} } } ELSE { { ${sql.raw(none)} } })`;\n }\n\n /**\n * What a claimed arm whose row did not come back carries: the empty document, \"the\n * row is gone\", which the decoder refuses. Under a related domain the row may exist\n * and be hidden, which reads as an empty slot.\n */\n #absentArm(edge: Reference): Sql {\n if (this.#queries.domainOf(edge.target, \"related\") === undefined)\n return sql.raw(\"{}\");\n return sql`(IF array::len(${this.#traversal(edge, undefined, { take: 1 })}) > 0 { NULL } ELSE { {} })`;\n }\n\n #relation(given: Relation): Sql {\n const predicate = this.#queries.scoped(\n given.edge.target,\n given.arguments.selector?.predicate,\n \"related\"\n );\n const field: Relation = predicate\n ? {\n ...given,\n arguments: {\n ...given.arguments,\n selector: { ...given.arguments.selector, predicate } as never,\n },\n }\n : given;\n this.#inRelation += 1;\n try {\n return this.#relationRead(field);\n } finally {\n this.#inRelation -= 1;\n }\n }\n\n #relationRead(field: Relation): Sql {\n const { arguments: args, projection } = field;\n const predicate = args.selector?.predicate;\n const members = this.#destructure(projection);\n if (field.edge.kind === \"junction\" && field.edge.declared)\n return this.#declaredMembers(field, field.edge);\n if (field.recurrence)\n return this.#carrier(field.edge, args, field.recurrence.depth, members);\n if (\n this.#distinctly(field.edge.target, args.distinct as string[] | undefined)\n )\n return this.#distinctMembers(field.edge, args, members);\n if (field.edge.kind === \"junction\") {\n const { hop } = this.edgeOf(field.edge);\n const target = field.edge.target;\n const { extras, clauses } = this.#clauses(\n target,\n args,\n args.selector?.predicate\n );\n const read = sql`${hop}(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")})`;\n return field.edge.many\n ? sql`${read}${members}`\n : sql`((${read}${members})[0] ?? NULL)`;\n }\n const edge = reference(field.edge);\n if (!edge.many && edge.owner === \"source\" && this.#linked(edge)) {\n const link = name(\n this.#queries.columnName(edge.source, edge.pairs[0]!.source)\n );\n // A hidden target reads as an absent one.\n if (predicate)\n return sql`(IF ${link} = NONE { NULL } ELSE { ((SELECT * FROM $this.${link} WHERE ${this.predicate(predicate, true)})${members})[0] ?? NULL })`;\n return sql`(${name(this.#queries.columnName(edge.source, edge.pairs[0]!.source))}${members} ?? NULL)`;\n }\n const paged = edge.many\n ? this.#pagesOfParents(edge, predicate, args)\n : undefined;\n const read = paged ?? this.#traversal(edge, args.selector?.predicate, args);\n return edge.many\n ? sql`${read}${members}`\n : sql`((${read}${members})[0] ?? NULL)`;\n }\n\n /**\n * A relation through a model of its own: the row's links, then the rows they\n * name. Each row may carry the link that produced it, as `$through`.\n */\n #declaredMembers(field: Relation, edge: Junction): Sql {\n const { arguments: args, projection, linkRow, linkWhere } = field;\n const target = edge.target;\n const link = edge.declared!.model;\n if (field.recurrence)\n return this.#carrier(\n edge,\n args,\n field.recurrence.depth,\n this.#destructure(projection)\n );\n const fields = projection.fields.map((member) => {\n const { value, alias } = this.#field(projection.model, member);\n return sql`${name(alias)}: ${value}`;\n });\n if (linkRow) {\n const columns = linkRow.fields.map((member) => {\n const { value, alias } = this.#field(link, {\n kind: \"scalar\",\n name: member,\n });\n return sql`${name(alias)}: ${value}`;\n });\n const named = this.linkTarget(edge, edge.targetSide, \"\");\n // The link that named this row.\n fields.push(\n sql`\\`$through\\`: ($links[WHERE ${named} = $row])[0].{ ${sql.join(columns, \", \")} }`\n );\n }\n const { extras, clauses } = this.#clauses(\n target,\n args,\n args.selector?.predicate,\n [sql.raw(\"id IN $linked\")]\n );\n const page = sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")})`;\n const rows = linkRow\n ? sql`${page}.map(|$item| { LET $row = $item.id; $item.{ ${sql.join(fields, \", \")} } })`\n : sql`${page}.{ ${sql.join(fields, \", \")} }`;\n const read = edge.many ? rows : sql`(${rows})[0] ?? NULL`;\n return sql`({ LET $owner = $this; LET $links = ${this.#links(edge, \"$owner\", linkWhere?.predicate)}; LET $linked = (SELECT VALUE ${this.linkTarget(edge, edge.targetSide, \"\")} FROM $links); ${read} })`;\n }\n\n /** The records one step along `edge` from the record `parent` holds, in order. */\n #children(\n edge: Membership,\n parent: string,\n args: Relation[\"arguments\"]\n ): Sql {\n const predicate = args.selector?.predicate;\n const target = edge.target;\n const held = sql.raw(parent);\n const narrowed = () => this.#clauses(target, args, predicate);\n if (edge.kind === \"junction\" && edge.declared) {\n const { extras, clauses } = this.#clauses(target, args, predicate, [\n // One subquery less than `#links`: a parser counts its depth.\n sql`id IN (SELECT VALUE ${this.linkTarget(edge, edge.targetSide, \"\")} FROM ${name(tableOf(edge.declared.model))} WHERE ${sql.join(this.#linkMatch(edge, edge.sourceSide, parent), \" AND \")})`,\n ]);\n return sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")}).id`;\n }\n if (edge.kind === \"junction\") {\n const { hop } = this.edgeOf(edge);\n const { extras, clauses } = narrowed();\n return sql`${held}${hop}(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")}).id`;\n }\n const reached = reference(edge);\n if (this.#linked(reached)) {\n if (reached.owner === \"source\") {\n const link = this.physical(reached.source, reached.pairs[0]!.source);\n if (predicate) {\n const { extras, clauses } = narrowed();\n return sql`(IF ${held}.${link} != NONE { (SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${held}.${link} ${sql.join(clauses, \" \")}).id } ELSE { [] })`;\n }\n return sql`(IF ${held}.${link} != NONE { [${held}.${link}] } ELSE { [] })`;\n }\n const { extras, clauses } = narrowed();\n return sql`${held}<~(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} FIELD ${name(this.#queries.columnName(target, reached.pairs[0]!.target))} ${sql.join(clauses, \" \")}).id`;\n }\n const { extras, clauses } = this.#clauses(target, args, predicate, [\n this.#correlated(reached, parent),\n ]);\n return sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")}).id`;\n }\n\n /**\n * A breadth-first walk from a record, as one value: a fold over the levels,\n * each the distinct records the last one reached. A numeric depth labels each\n * edge with its level. An exhaustive one keeps what it has seen, which is what\n * ends a cycle, and refuses past the depth SurrealDB allows a recursion rather\n * than answer a part of the graph.\n */\n #walk(\n edge: Membership,\n args: Relation[\"arguments\"],\n depth: number | false,\n root: Sql\n ): Sql {\n if (depth === 0) return sql.raw(\"{ level: [], edges: [] }\");\n const children = this.#children(edge, \"$p\", args);\n if (depth === false) {\n const reached = this.#reached(edge, args, root);\n if (reached)\n return sql`({ LET $r = ${reached}; { level: [], edges: array::flatten(array::distinct(array::concat([${root}], $r)).map(|$p| (${children}).map(|$c| { p: $p, c: $c }))) } })`;\n }\n if (depth !== false)\n return sql`array::fold(array::range(1, ${sql.raw(String(depth + 1))}), { level: [${root}], edges: [] }, |$walk, $depth| { LET $pairs = array::flatten($walk.level.map(|$p| (${children}).map(|$c| { p: $p, c: $c, d: $depth }))); { level: array::distinct($pairs.c), edges: array::concat($walk.edges, $pairs) } })`;\n return sql`array::fold(array::range(1, ${sql.raw(String(MAX_WALK + 1))}), { level: [${root}], seen: [${root}], edges: [] }, |$walk, $depth| { LET $pairs = array::flatten($walk.level.map(|$p| (${children}).map(|$c| { p: $p, c: $c }))); LET $reached = array::complement(array::distinct($pairs.c), $walk.seen); { level: $reached, seen: array::concat($walk.seen, $reached), edges: array::concat($walk.edges, $pairs) } })`;\n }\n\n /** One step along `edge` as an idiom, which a recursion can repeat. */\n #hopIdiom(edge: Membership, args: Relation[\"arguments\"]): Sql | undefined {\n const target = edge.target;\n const narrowed = () =>\n this.#clauses(target, { unordered: true }, args.selector?.predicate)\n .clauses;\n if (edge.kind === \"junction\") {\n if (edge.declared) return undefined;\n return sql`${this.edgeOf(edge).hop}(SELECT * FROM ${name(tableOf(target))} ${sql.join(narrowed(), \" \")}).id`;\n }\n const held = reference(edge);\n if (!this.#linked(held)) return undefined;\n if (held.owner === \"source\")\n return args.selector?.predicate\n ? undefined\n : sql`.${this.physical(held.source, held.pairs[0]!.source)}`;\n return sql`<~(SELECT * FROM ${name(tableOf(target))} FIELD ${name(this.#queries.columnName(target, held.pairs[0]!.target))} ${sql.join(narrowed(), \" \")}).id`;\n }\n\n /** Every record an exhaustive walk reaches, in one recursion rather than a fold. */\n #reached(\n edge: Membership,\n args: Relation[\"arguments\"],\n root: Sql\n ): Sql | undefined {\n const hop = this.#hopIdiom(edge, args);\n return hop && sql`array::distinct(${root}.{..+collect}${hop})`;\n }\n\n /** A walk's own statements in a block: `$w`, and the refusal an endless one owes. */\n #walked(walk: Sql, root: Sql = sql.raw(\"$this.id\")): Sql {\n return sql`LET $root = ${root}; LET $w = ${walk}; IF array::len($w.level) > 0 AND $w.seen != NONE { THROW ${`A recursive read walked past ${MAX_WALK} levels.`} };`;\n }\n\n /** The path a column of `up` rows above this one is read at. */\n #rowAbove(up: number | undefined, path: string): string {\n if (!up) return path;\n const row = this.#above.at(-up);\n if (row === undefined)\n throw new UnsupportedOperationError(\n \"An enclosing row's column ({ $row, up }) has no row to read here.\"\n );\n return `${row}.`;\n }\n\n /** A record's key as the identity tuple the recursive decoder reads. */\n #identityOf(model: AnyModel, record: Sql): Sql {\n return this.#queries.keyOrder(model).length === 1\n ? sql`[record::id(${record})]`\n : sql`record::id(${record})`;\n }\n\n /** What `decodeRecursiveCarrier` reads: the root, its nodes and its edges. */\n #carrier(\n edge: Membership,\n args: Relation[\"arguments\"],\n depth: number | false,\n members: Sql\n ): Sql {\n const { source, target } = edge;\n const walk = this.#walk(edge, args, depth, sql.raw(\"$root\"));\n const labelled =\n depth === false ? sql.raw(\"\") : sql.raw(\", __rq_depth: $e.d\");\n // A block answers with its last expression: a `RETURN` in one would leave\n // whatever expression holds the block, negations included.\n return sql`({ ${this.#walked(walk)} { __rq_root: ${this.#identityOf(source, sql.raw(\"$root\"))}, __rq_nodes: array::distinct($w.edges.c).map(|$n| { __rq_key: ${this.#identityOf(target, sql.raw(\"$n\"))}, __rq_row: $n${members} }), __rq_edges: $w.edges.map(|$e| { __rq_parent: ${this.#identityOf(source, sql.raw(\"$e.p\"))}, __rq_child: ${this.#identityOf(target, sql.raw(\"$e.c\"))}${labelled} }) } })`;\n }\n\n /** Whether a `distinct` narrows at all: one holding the whole key does not. */\n #distinctly(model: AnyModel, fields: readonly string[] | undefined): boolean {\n return (\n fields !== undefined &&\n fields.length > 0 &&\n !this.#queries.keyOrder(model).every((key) => fields.includes(key))\n );\n }\n\n /**\n * A relation's first row of each tuple. A parent's members are a value here,\n * so they group as one, where a subquery past the first could not see `$parent`.\n */\n #distinctMembers(\n edge: Membership,\n args: Relation[\"arguments\"],\n members: Sql\n ): Sql {\n const target = edge.target;\n const predicate = args.selector?.predicate;\n const { terms } = this.#ordering(target, { ...args, take: undefined });\n const { extras: inner, order: forward } = this.#ordered(terms);\n const sorted =\n edge.kind === \"junction\"\n ? sql`${this.edgeOf(edge).hop}(SELECT ${sql.join([sql.raw(\"*\"), ...inner], \", \")} FROM ${name(tableOf(target))}${predicate ? sql` WHERE ${this.predicate(predicate, true)}` : sql.raw(\"\")} ORDER BY ${sql.join(forward, \", \")})`\n : this.#traversal(reference(edge), predicate, {\n orderBy: args.orderBy,\n });\n const tuple = sql.join(\n (args.distinct as string[]).map((field) => this.#operand(target, field)),\n \", \"\n );\n const after =\n args.cursor === undefined\n ? sql.raw(\"\")\n : sql` WHERE ${this.#cursor(target, args.cursor as Input, this.#ordering(target, args).terms)}`;\n const { extras, clauses } = this.#clauses(\n target,\n { ...args, distinct: undefined, cursor: undefined },\n undefined,\n [sql.raw(\"id IN $first\")]\n );\n return sql`({ LET $all = ${sorted}; LET $first = (SELECT VALUE array::first(id) FROM (SELECT ${tuple}, id FROM $all${after} GROUP BY ${tuple})); (SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM $all ${sql.join(clauses, \" \")})${members} })`;\n }\n\n /**\n * The one record a to-one's fields name, when they name its whole key: read by\n * key, where a filter on the same fields would scan its table for each row.\n */\n #heldRecord(edge: Reference): Sql | undefined {\n if (edge.many || edge.owner !== \"source\") return undefined;\n const keys = this.#queries.keyOrder(edge.target);\n const parts = keys.map((key) => {\n const pair = edge.pairs.find(({ target }) => target === key);\n return pair && sql`$owner.${this.physical(edge.source, pair.source)}`;\n });\n if (parts.some((part) => part === undefined)) return undefined;\n const held = parts as Sql[];\n const key =\n held.length === 1\n ? keyCast(edge.target, keys[0]!, held[0]!)\n : sql`[${sql.join(held, \", \")}]`;\n const record = sql`type::record(${tableOf(edge.target)}, ${key})`;\n // An arm another row's type names reads nothing; an unset part names no record.\n const { discriminator } = edge;\n return discriminator\n ? sql`(IF $owner.${this.physical(edge.source, discriminator.field)} = ${discriminator.value} { ${record} } ELSE { [] })`\n : record;\n }\n\n /**\n * The rows holding a link to this one: `FIELD` is what names the relation,\n * since without it `<~` reads every reference from that table.\n */\n #traversal(\n edge: Reference,\n predicate: PreparedPredicate | undefined,\n args: Pick<\n Partial<Arguments>,\n \"orderBy\" | \"take\" | \"skip\" | \"cursor\" | \"distinct\"\n > & { readonly unordered?: boolean }\n ): Sql {\n const target = edge.target;\n const linked = this.#linked(edge);\n const record = linked ? undefined : this.#heldRecord(edge);\n if (record) {\n const { extras, clauses } = this.#clauses(target, args, predicate);\n return sql`({ LET $owner = $this; SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${record} ${sql.join(clauses, \" \")} })`;\n }\n const { extras, clauses } = this.#clauses(\n target,\n args,\n predicate,\n linked ? [] : [this.#correlated(edge, \"$owner\")]\n );\n const read = sql`SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))}`;\n return linked\n ? sql`<~(${read} FIELD ${name(this.#queries.columnName(target, edge.pairs[0]!.target))} ${sql.join(clauses, \" \")})`\n : sql`({ LET $owner = $this; ${read} ${sql.join(clauses, \" \")} })`;\n }\n\n /**\n * `positive` carries a negation down to each comparison: SurrealQL compares in\n * two values, where `age != 20` holds of a row with no age, and viborm's filters\n * read as SQL's, where neither `age = 20` nor its negation does.\n */\n predicate(predicate: PreparedPredicate, positive: boolean, path = \"\"): Sql {\n switch (predicate.kind) {\n case \"and\":\n case \"or\": {\n if (predicate.predicates.length === 0)\n return sql.raw(\n (predicate.kind === \"and\") === positive ? \"true\" : \"false\"\n );\n // Each parenthesis counts against the parser's depth, so one arm has none.\n if (predicate.predicates.length === 1)\n return this.predicate(predicate.predicates[0]!, positive, path);\n const conjunction = (predicate.kind === \"and\") === positive;\n const arms = (node: PreparedPredicate): PreparedPredicate[] =>\n node.kind === predicate.kind ? node.predicates.flatMap(arms) : [node];\n const lowered = onceEach(\n arms(predicate).map((inner) => this.predicate(inner, positive, path))\n );\n // Arms with nothing in them hold as an empty one does.\n if (lowered.length === 0)\n return sql.raw(\n (predicate.kind === \"and\") === positive ? \"true\" : \"false\"\n );\n if (lowered.length === 1) return lowered[0]!;\n return sql`(${joined(lowered, conjunction ? \" AND \" : \" OR \")})`;\n }\n case \"not\":\n return this.predicate(predicate.predicate, !positive, path);\n case \"always\":\n return sql.raw(predicate.value === positive ? \"true\" : \"false\");\n case \"layer\": {\n // A layer the call drops is no filter at all.\n const lowered = this.#queries.layer(predicate, (resolved) =>\n this.predicate(resolved, positive, path)\n );\n return lowered ?? sql.raw(positive ? \"true\" : \"false\");\n }\n case \"exists\": {\n const body = this.#queries.scoped(\n predicate.model,\n predicate.predicate,\n \"related\"\n );\n const rows = sql`SELECT VALUE id FROM ${name(tableOf(predicate.model))}${body ? sql` WHERE ${this.predicate(body, true)}` : sql.raw(\"\")} LIMIT 1`;\n return sql`array::len(${rows}) ${sql.raw(positive ? \">\" : \"=\")} ${sql.raw(positive ? \"0\" : \"0\")}`;\n }\n case \"condition\":\n return sql.raw(\n this.#queries.holds(predicate.condition) === positive\n ? \"true\"\n : \"false\"\n );\n case \"operation\":\n return this.#operation(predicate, positive, path);\n case \"relation\":\n return this.#relationFilter(predicate, positive, path);\n default:\n return refuse(`a '${predicate.kind}' filter`);\n }\n }\n\n #operation(\n predicate: Extract<PreparedPredicate, { kind: \"operation\" }>,\n positive: boolean,\n path: string\n ): Sql {\n const { target, operator } = predicate;\n if (target.kind !== \"column\") refuse(\"this filter target\");\n const { scalar } = target;\n let column = this.#gated(\n scalar.model,\n scalar.field,\n sql.raw(\n `${path}${this.physical(scalar.model, scalar.field).toStatement()}`\n ),\n path\n );\n const facts = scalar.physical.scalar[\"~\"].state;\n if (facts.type === \"json\" && facts.array !== true)\n return this.#jsonOperation(predicate, column, positive);\n if (target.path) refuse(\"this filter target\");\n const spatial = this.#spatial(predicate, column, facts);\n if (spatial) {\n const asked = positive ? spatial : sql`!(${spatial})`;\n return scalar.physical.nullable ||\n this.#gatedHere(scalar.model, scalar.field)\n ? sql`(${column} != NONE AND ${asked})`\n : asked;\n }\n const bind = (value: unknown): Sql =>\n this.value(scalar.model, scalar.field, value);\n const guards: Sql[] = [];\n const operandOf = (\n operand: NonNullable<typeof predicate.operand>\n ): unknown => {\n if (operand.kind === \"field\") {\n const read = operand.scalar;\n const other = sql.raw(\n `${this.#rowAbove(operand.up, path)}${this.physical(read.model, read.field).toStatement()}`\n );\n if (read.physical.nullable) guards.push(sql`${other} != NONE`);\n // A key is a record and a plain column its text: they compare by the text.\n return this.#isRecord(read.model, read.field)\n ? sql`record::id(${other})`\n : other;\n }\n if (operand.kind === \"parameter\")\n return this.#queries.callValue(operand.parameter);\n if (operand.kind !== \"value\") refuse(`a '${operand.kind}' operand`);\n return operand.value;\n };\n if (predicate.operand === undefined && operator === \"isNull\")\n return sql`${column} ${sql.raw(positive ? \"=\" : \"!=\")} NONE`;\n const value =\n predicate.operand === undefined\n ? predicate.value\n : operandOf(predicate.operand);\n if (operator === \"equals\" && value === null)\n return sql`${column} ${sql.raw(positive ? \"=\" : \"!=\")} NONE`;\n const fold = (text: Sql) =>\n predicate.insensitive ? sql`string::lowercase(${text})` : text;\n // A key or a link is a record, and its text is what a pattern or a case reads.\n const isRecord = this.#isRecord(scalar.model, scalar.field);\n const asText = isRecord\n ? sql`<string>record::id(${column})`\n : this.#queries.keyOrder(scalar.model).includes(scalar.field)\n ? sql`<string>${column}`\n : column;\n const comparedToField =\n predicate.operand?.kind === \"field\" ||\n predicate.operands?.some((operand) => operand.kind === \"field\");\n // What a decimal range reads is the record itself: see #numeric.\n const record = column;\n if (comparedToField && isRecord) column = sql`record::id(${column})`;\n const read = predicate.insensitive ? asText : column;\n const compared = (member: unknown) =>\n predicate.insensitive && isRecord\n ? sql`string::lowercase(${member})`\n : fold(bind(member));\n let test: Sql;\n if (\n COMPARISONS[operator] &&\n operator !== \"equals\" &&\n this.#namesDecimal(scalar.model, scalar.field)\n ) {\n test = sql`${this.#numeric(record, false)} ${sql.raw(COMPARISONS[operator])} ${this.#decimalOperand(value)}`;\n } else if (COMPARISONS[operator]) {\n test = sql`${fold(read)} ${sql.raw(COMPARISONS[operator])} ${compared(value)}`;\n } else if (FUNCTIONS[operator]) {\n test = sql`${sql.raw(FUNCTIONS[operator])}(${fold(asText)}, ${fold(sql`${value}`)})`;\n } else if (operator === \"has\") {\n if (value === null) return sql.raw(positive ? \"false\" : \"true\");\n test = sql`${column} CONTAINS ${sql`${stored({ ...facts, array: false }, value)}`}`;\n } else if (operator === \"hasEvery\") {\n if ((value as unknown[]).length === 0)\n return sql`${column} ${sql.raw(positive ? \"!=\" : \"=\")} NONE`;\n test = sql`${column} CONTAINSALL ${bind(value)}`;\n } else if (operator === \"hasSome\") {\n if ((value as unknown[]).length === 0)\n return sql.raw(positive ? \"false\" : \"true\");\n test = sql`${column} CONTAINSANY ${bind(value)}`;\n } else if (operator === \"isEmpty\") {\n // A list that is not there counts as empty, on every dialect.\n const empty = sql`array::len(${column} ?? []) ${sql.raw(value ? \"=\" : \">\")} 0`;\n return positive ? empty : sql`!(${empty})`;\n } else if (operator === \"in\" || operator === \"notIn\") {\n // A call's list is the list, as one value of the caller's would be.\n const list = predicate.operands\n ? predicate.operands.flatMap((operand) => {\n const read = operandOf(operand);\n return operand.kind === \"parameter\" && Array.isArray(read)\n ? read\n : [read];\n })\n : (value as unknown[]);\n // An empty list asks nothing of the row, so a missing value does not matter.\n if (list.length === 0)\n return sql.raw((operator === \"notIn\") === positive ? \"true\" : \"false\");\n const bound = boundList(list.map(compared));\n test = sql`${fold(read)} ${sql.raw(operator === \"in\" ? \"IN\" : \"NOT IN\")} ${bound}`;\n } else {\n return refuse(`the '${operator}' operator`);\n }\n const nullable =\n scalar.physical.nullable || this.#gatedHere(scalar.model, scalar.field);\n const asked = positive ? test : sql`!(${test})`;\n const required = [...(nullable ? [sql`${column} != NONE`] : []), ...guards];\n return required.length\n ? sql`(${sql.join(required, \" AND \")} AND ${asked})`\n : asked;\n }\n\n /** A point's or a vector's own operators, which read no comparison below. */\n #spatial(\n predicate: Extract<PreparedPredicate, { kind: \"operation\" }>,\n column: Sql,\n facts: ScalarFacts\n ): Sql | undefined {\n const { operator, value } = predicate;\n if (operator === \"distance\") {\n const spec = value as Input;\n const distance = this.#distance(\n column,\n facts,\n predicate.target.scalar!.field,\n spec,\n \"filter\"\n );\n const bounds = [\"lt\", \"lte\", \"gt\", \"gte\"]\n .filter((bound) => spec[bound] !== undefined)\n .map(\n (bound) =>\n sql`${distance} ${sql.raw(COMPARISONS[bound]!)} ${spec[bound]}`\n );\n return sql`(${sql.join(bounds, \" AND \")})`;\n }\n if (facts.type !== \"point\" || facts.array) return undefined;\n const longitude = sql`${column}.coordinates[0]`;\n const latitude = sql`${column}.coordinates[1]`;\n if (operator === \"equals\") {\n if (value === null) return undefined;\n const point = value as GeoPointValue;\n // -180 and +180 are one meridian, whichever a writer stored.\n const meridian =\n point.longitude === 180\n ? sql`(${longitude} = 180 OR ${longitude} = -180)`\n : sql`${longitude} = ${point.longitude}`;\n return sql`(${meridian} AND ${latitude} = ${point.latitude})`;\n }\n if (operator !== \"within\") return undefined;\n const area = value as {\n readonly bounds?: {\n readonly north: number;\n readonly south: number;\n readonly east: number;\n readonly west: number;\n };\n readonly polygon?: {\n readonly outer: readonly GeoPointValue[];\n readonly holes?: readonly (readonly GeoPointValue[])[];\n };\n };\n if (area.polygon) {\n const { outer, holes = [] } = area.polygon;\n // `INTERSECTS` holds a polygon's boundary and not its holes, as PostGIS\n // does. Its plane has an edge at 180: a ring crossing it is unwrapped past\n // it, and a point read at both its longitudes.\n const crosses = [outer, ...holes].some((ring) =>\n ring.some(\n (point, index) =>\n Math.abs(\n point.longitude - ring[(index + 1) % ring.length]!.longitude\n ) > 180\n )\n );\n const coordinates = [outer, ...holes].map((ring) => {\n const points = ring.map((point) => [\n crosses && point.longitude < 0\n ? point.longitude + 360\n : point.longitude,\n point.latitude,\n ]);\n return [...points, points[0]!];\n });\n const polygon = sql`<geometry>${{ type: \"Polygon\", coordinates }}`;\n return crosses\n ? sql`(type::point([(IF ${longitude} < 0 { ${longitude} + 360 } ELSE { ${longitude} }), ${latitude}]) INTERSECTS ${polygon})`\n : sql`${column} INTERSECTS ${polygon}`;\n }\n const { north, south, east, west } = area.bounds!;\n const inLatitude = sql`${latitude} >= ${south} AND ${latitude} <= ${north}`;\n if (west === -180 && east === 180) return sql`(${inLatitude})`;\n const westArm = sql`${longitude} >= ${west}`;\n const eastArm = sql`${longitude} <= ${east}`;\n const arms = [\n west > east\n ? sql`(${westArm} OR ${eastArm})`\n : sql`(${westArm} AND ${eastArm})`,\n ...(west === -180 && east < 180 ? [sql`${longitude} = 180`] : []),\n ...(east === 180 && west > -180 ? [sql`${longitude} = -180`] : []),\n ];\n return sql`(${inLatitude} AND (${sql.join(arms, \" OR \")}))`;\n }\n\n #distance(\n column: Sql,\n facts: ScalarFacts & { readonly dimension?: number },\n field: string,\n spec: Input,\n usage: string\n ): Sql {\n if (facts.type === \"point\") {\n const to = spec.to as GeoPointValue;\n return sql`(IF ${column} != NONE { geo::distance(${column}, ${geometry(to)}) } ELSE { NONE })`;\n }\n const to = spec.to as number[];\n if (facts.dimension !== undefined && to.length !== facts.dimension)\n throw new UnsupportedOperationError(\n `Vector distance ${usage} dimension mismatch for '${field}': expected ${facts.dimension} values, received ${to.length}.`\n );\n // A zero vector has no direction, so no cosine: NONE, as PostgreSQL's NULL.\n if (spec.metric === \"cosine\")\n return sql`(IF ${column} != NONE AND vector::magnitude(${column}) > 0 { 1 - vector::similarity::cosine(${column}, ${to}) } ELSE { NONE })`;\n return sql`(IF ${column} != NONE { vector::distance::euclidean(${column}, ${to}) } ELSE { NONE })`;\n }\n\n /** A JSON filter: a missing path answers neither a test nor its negation. */\n #jsonOperation(\n predicate: Extract<PreparedPredicate, { kind: \"operation\" }>,\n column: Sql,\n positive: boolean\n ): Sql {\n const { target, operator, value, insensitive } = predicate;\n const steps = target.kind === \"column\" ? (target.path ?? []) : [];\n const at = steps.reduce(jsonStep, column);\n const answer = (test: Sql, reads: Sql = at) =>\n positive ? test : sql`(${reads} != NONE AND !(${test}))`;\n // A value this operator cannot compare answers neither it nor its negation.\n const typed = (guard: Sql, test: Sql) =>\n sql`(${guard} AND ${positive ? test : sql`!(${test})`})`;\n const text = (fn: string) => {\n const fold = (member: Sql) =>\n insensitive ? sql`string::lowercase(${member})` : member;\n return typed(\n sql`type::is_string(${at})`,\n sql`${sql.raw(fn)}(${fold(at)}, ${fold(sql`${value}`)})`\n );\n };\n const isArray = sql`type::is_array(${at})`;\n switch (operator) {\n case \"equals\": {\n const sentinel = jsonNullKindOf(value);\n if (sentinel === \"DbNull\" || (value === null && steps.length === 0))\n return sql`${column} ${sql.raw(positive ? \"=\" : \"!=\")} NONE`;\n if (sentinel === \"JsonNull\") return answer(sql`${at} = NULL`, column);\n if (sentinel)\n return answer(sql`(${column} = NONE OR ${at} = NULL)`, column);\n return answer(sql`${at} = ${value}`);\n }\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\": {\n const kind = typeof value === \"number\" ? \"number\" : \"string\";\n return typed(\n sql`${sql.raw(`type::is_${kind}`)}(${at})`,\n sql`${at} ${sql.raw(COMPARISONS[operator]!)} ${value}`\n );\n }\n case \"string_contains\":\n return text(\"string::contains\");\n case \"string_starts_with\":\n return text(\"string::starts_with\");\n case \"string_ends_with\":\n return text(\"string::ends_with\");\n case \"array_contains\":\n return typed(\n isArray,\n sql`${at} CONTAINSALL ${Array.isArray(value) ? value : [value]}`\n );\n case \"array_starts_with\":\n return typed(isArray, sql`${at}[0] = ${value}`);\n case \"array_ends_with\":\n return typed(isArray, sql`array::last(${at}) = ${value}`);\n default:\n return refuse(`the '${operator}' operator`);\n }\n }\n\n /** A key or a link is a record: its value is bound as one, never as a string. */\n value(model: AnyModel, field: string, value: unknown): Sql {\n const q = this.#queries;\n // A value this statement reads for itself ({@link SurrealQueries.locatedValue}):\n // a record, where a private column holds its key.\n if (value instanceof Sql)\n return model[\"~\"].state.scalars[field]\n ? value\n : this.#carried(model, field, sql`record::id(${value})`);\n if (isSingleKey(q, model, field))\n return sql`${new RecordId(\n tableOf(model),\n (isIntegerKey(model, field) && typeof value === \"string\"\n ? Number(value)\n : keyPart(model, field, value)) as string\n )}`;\n for (const slot of Object.keys(model[\"~\"].state.relations)) {\n const { edges } = q.countedMemberships(model, slot);\n const edge = edges[0];\n if (\n edges.length === 1 &&\n edge?.kind === \"reference\" &&\n edge.owner === \"source\" &&\n // A variant relation's column holds the key itself, whichever model it names.\n !edge.discriminator &&\n edge.pairs.length === 1 &&\n edge.pairs[0]!.source === field &&\n isSingleKey(q, edge.target, edge.pairs[0]!.target)\n )\n return sql`${new RecordId(\n tableOf(edge.target),\n keyPart(edge.target, edge.pairs[0]!.target, value) as string\n )}`;\n }\n const sentinel = jsonNullKindOf(value);\n if (sentinel)\n return sentinel === \"JsonNull\" ? sql`${null}` : sql.raw(\"NONE\");\n const state = model[\"~\"].state.scalars[field]?.[\"~\"].state;\n return state\n ? sql`${stored(state, value)}`\n : sql`${this.#carriesText(model, field) && value !== null && value !== undefined ? String(value) : value}`;\n }\n\n #relationFilter(\n predicate: Extract<PreparedPredicate, { kind: \"relation\" }>,\n positive: boolean,\n path: string\n ): Sql {\n const edge = predicate.edge;\n const { quantifier } = predicate;\n const inner = predicate.predicate;\n if (predicate.closure) {\n if (path) refuse(\"a recursive filter through a to-one link\");\n const wanted = quantifier === \"some\" || quantifier === \"is\";\n const found = this.#closure(edge, predicate.closure, quantifier, inner);\n return wanted === positive ? found : sql`!(${found})`;\n }\n // As the SQL lowering's EXISTS and NOT EXISTS: a body-less `is` asks that no\n // related row exists (`author: null`), a body-less `isNot` that one does.\n const wanted =\n quantifier === \"some\" ||\n (quantifier === \"is\" && inner !== undefined) ||\n (quantifier === \"isNot\" && inner === undefined);\n const asked = this.#queries.scoped(\n edge.target,\n quantifier === \"every\" && inner\n ? ({ kind: \"not\", predicate: inner } as const)\n : inner,\n \"related\"\n );\n const heldLink =\n this.#judging &&\n this.#lets &&\n asked &&\n !predicate.link &&\n !readsAbove(asked) &&\n edge.kind === \"reference\" &&\n !edge.many &&\n edge.owner === \"source\" &&\n this.#linked(edge);\n if (heldLink && this.#walksForward(asked)) {\n // One row's link is one read, where a list of all that hold is many.\n const link = `${path}${this.physical(edge.source, edge.pairs[0]!.source).toStatement()}`;\n const inner = this.predicate(asked, true, `${link}.`);\n // A list holds nothing unset, so asking is enough, and a scan can stop early.\n const held = onlyLists(asked)\n ? inner\n : sql`(${sql.raw(link)} != NONE AND ${inner})`;\n return wanted === positive ? held : sql`!(${held})`;\n }\n if (heldLink && !path) {\n const targets = this.#hoist(\n this.#selecting(edge.target, sql.raw(\"id\"), asked)\n )!;\n const held = sql`${this.physical(edge.source, edge.pairs[0]!.source)} IN ${targets}`;\n return wanted === positive ? held : sql`!(${held})`;\n }\n // A row above stays in its own statement: a list hoisted out of it has no such row.\n const holders =\n (!path || this.#judging) &&\n asked &&\n predicate !== this.#walking &&\n !readsAbove(asked) &&\n this.#holders(predicate, asked);\n if (holders) {\n const held = this.#hoist(holders.list(holders.rows()))!;\n return sql`${sql.raw(path ? path.slice(0, -1) : \"id\")} ${sql.raw(wanted === positive ? \"IN\" : \"NOT IN\")} ${held}`;\n }\n if (predicate.link) this.#queries.refuseHiddenLink(edge, predicate);\n const above = `$above${this.#above.length}`;\n this.#above.push(above);\n let found: Sql;\n try {\n found =\n edge.kind === \"junction\" && edge.declared\n ? this.#relatedThrough(edge, quantifier, inner, predicate.link, path)\n : this.#related(edge, quantifier, inner, path);\n } finally {\n this.#above.pop();\n }\n const row = path ? `$this.${path.slice(0, -1)}` : \"$this\";\n const within =\n asked && readsAbove(asked)\n ? sql`({ LET ${sql.raw(above)} = ${sql.raw(row)}; ${found} })`\n : found;\n return wanted === positive ? within : sql`!(${within})`;\n }\n\n /**\n * The records holding a relation to the rows a body holds of, walked from those\n * rows: a list computed once, however many rows the statement then reads. `rows`\n * reads what each body row holds, and `list` makes those one list of records.\n */\n #holders(\n filter: Extract<PreparedPredicate, { kind: \"relation\" }>,\n body: PreparedPredicate\n ):\n | {\n readonly rows: (limit?: number) => Sql;\n readonly list: (rows: Sql) => Sql;\n }\n | undefined {\n const edge = filter.edge;\n if (!this.#lets || filter.closure || filter.link) return undefined;\n const target = edge.target;\n const distinct = (rows: Sql) => sql`array::distinct(${rows})`;\n const flat = (rows: Sql) => sql`array::flatten(${rows})`;\n if (edge.kind === \"junction\") {\n if (edge.declared) return undefined;\n const { back } = this.edgeOf(edge);\n return {\n rows: (limit) =>\n this.#selecting(\n target,\n sql`${back}${name(tableOf(edge.source))}`,\n body,\n limit\n ),\n list: (rows) => distinct(flat(rows)),\n };\n }\n const held = reference(edge);\n if (!this.#linked(held)) return undefined;\n const { source, target: holder } = held.pairs[0]!;\n if (held.owner === \"source\")\n return {\n // Counting toward a limit reads the index on the link, which stops at it:\n // from each target, one with many holders would be read whole.\n rows: (limit) =>\n limit === undefined\n ? this.#selecting(\n target,\n sql`<~(${name(tableOf(held.source))} FIELD ${name(this.#queries.columnName(held.source, source))})`,\n body\n )\n : sql`(SELECT VALUE id FROM ${name(tableOf(held.source))} WHERE ${this.physical(held.source, source)} IN ${this.#hoist(this.#selecting(target, sql.raw(\"id\"), body))!} LIMIT ${sql.raw(String(limit))})`,\n list: flat,\n };\n const column = name(this.#queries.columnName(target, holder));\n return {\n rows: (limit) => this.#selecting(target, column, body, limit),\n list: distinct,\n };\n }\n\n /** `SELECT VALUE` over the rows a predicate holds of, driven as a statement is. */\n #selecting(\n model: AnyModel,\n value: Sql,\n body: PreparedPredicate,\n limit?: number\n ): Sql {\n const { from, rest } = this.#driven(model, body);\n return sql`(SELECT VALUE ${value} FROM ${from}${\n rest ? sql` WHERE ${this.predicate(rest, true)}` : sql.raw(\"\")\n }${limit === undefined ? sql.raw(\"\") : sql.raw(` LIMIT ${limit}`)})`;\n }\n\n /**\n * Where a statement reads its rows: the table, or a relation filter's holders\n * when every row must be one of them, which then reads only those.\n */\n #driven(\n model: AnyModel,\n predicate: PreparedPredicate | undefined,\n paged = false\n ): {\n readonly from: Sql;\n readonly rest: PreparedPredicate | undefined;\n /** A page may need fewer rows than the list holds: read only so far ahead. */\n readonly ahead?: { readonly rows: Sql; readonly arm: PreparedPredicate };\n /** `from` is the one record the filter names, and `rest` asks more of it. */\n readonly named?: boolean;\n } {\n const table = name(tableOf(model));\n if (!(predicate && this.#lets)) return { from: table, rest: predicate };\n // A row named by its key is read, and its links followed.\n if (this.#namesOneRow(model, predicate)) {\n const named = this.namedRecord(model, predicate);\n return named\n ? { from: named.record, rest: named.rest, named: true }\n : { from: table, rest: predicate };\n }\n const flat = (node: PreparedPredicate): PreparedPredicate[] =>\n node.kind === \"and\" ? node.predicates.flatMap(flat) : [node];\n const arms = flat(predicate);\n /** A list, where `arm` is a relation filter some row can hold. */\n const listed = (arm: PreparedPredicate) => {\n if (\n arm.kind !== \"relation\" ||\n !arm.predicate ||\n (arm.quantifier !== \"some\" && arm.quantifier !== \"is\")\n )\n return undefined;\n // Among the rows this call may see of them, as a filter reads them anywhere.\n const asked = this.#queries.scoped(\n arm.edge.target,\n arm.predicate,\n \"related\"\n )!;\n // A row above stays in its own statement: a list hoisted out of it has no such row.\n if (readsAbove(asked)) return undefined;\n const holders = this.#holders(arm, asked);\n if (!holders) return undefined;\n if (!paged) return { from: this.#hoist(holders.list(holders.rows()))! };\n const rows = this.#hoist(holders.rows(HOLDERS_AHEAD))!;\n return {\n from: this.#hoist(holders.list(rows))!,\n ahead: { rows, arm },\n };\n };\n const without = (at: number) => {\n const others = arms.filter((_, position) => position !== at);\n return others.length\n ? ({ kind: \"and\", predicates: others } as const)\n : undefined;\n };\n for (const [index, arm] of arms.entries()) {\n if (arm.kind !== \"layer\") {\n const found = listed(arm);\n if (found) return { ...found, rest: without(index) };\n continue;\n }\n // A rule's own arms read as its layer reads them, with what is left of it kept.\n const resolved = this.#queries.resolved(arm);\n if (!resolved) continue;\n const inner = flat(resolved);\n for (const [position, candidate] of inner.entries()) {\n let found: ReturnType<typeof listed>;\n this.#queries.layer(arm, () => {\n found = listed(candidate);\n return sql.raw(\"\");\n });\n if (!found) continue;\n const left: PreparedPredicate = {\n kind: \"and\",\n predicates: inner.filter((_, at) => at !== position),\n };\n const others = arms.filter((_, at) => at !== index);\n // What is left of the layer is what it resolved to for this call, less the arm taken.\n const kept: PreparedPredicate[] = left.predicates.length\n ? [...others, { ...arm, predicate: left, resolve: () => left }]\n : others;\n return {\n ...(found as NonNullable<typeof found>),\n rest: kept.length ? { kind: \"and\", predicates: kept } : undefined,\n };\n }\n }\n return { from: table, rest: predicate };\n }\n\n /** Whether a link and the row it names hold what a quantifier asks, together. */\n #relatedThrough(\n edge: Junction,\n quantifier: string,\n inner: PreparedPredicate | undefined,\n link: PreparedPredicate | undefined,\n path: string\n ): Sql {\n if (path) refuse(\"a filter through a to-one link into a declared junction\");\n const narrowed =\n quantifier === \"every\" && inner\n ? ({ kind: \"not\", predicate: inner } as const)\n : inner;\n const named = this.linkTarget(edge, edge.targetSide, \"\");\n // `every` over a pair: no link of this row fails the link's test and the\n // row's together. Their halves cannot answer it one after the other.\n if (quantifier === \"every\" && link) {\n const fails = [\n this.predicate(link, false, \"$l.\"),\n ...(inner\n ? [\n sql`array::len(SELECT VALUE id FROM ${name(tableOf(edge.target))} WHERE id = ${this.linkTarget(edge, edge.targetSide, \"$l\")} AND ${this.predicate(inner, false)} LIMIT 1) > 0`,\n ]\n : []),\n ];\n return sql`({ LET $owner = $this; array::len(${this.#links(edge, \"$owner\")}.filter(|$l| ${sql.join(fails, \" OR \")})) > 0 })`;\n }\n const rows = narrowed\n ? sql`SELECT VALUE id FROM ${name(tableOf(edge.target))} WHERE id IN $linked AND ${this.predicate(narrowed, true)} LIMIT 1`\n : sql.raw(\"SELECT VALUE id FROM $linked LIMIT 1\");\n return sql`({ LET $owner = $this; LET $linked = (SELECT VALUE ${named} FROM ${this.#links(edge, \"$owner\", link)}); array::len(${rows}) > 0 })`;\n }\n\n /** Whether the rows a walk from this one reaches hold what a quantifier asks. */\n #closure(\n edge: Membership,\n closure: { readonly depth: number | false; readonly self: boolean },\n quantifier: string,\n inner: PreparedPredicate | undefined\n ): Sql {\n const narrowed =\n quantifier === \"every\" && inner\n ? ({ kind: \"not\", predicate: inner } as const)\n : inner;\n const test = (rows: Sql) =>\n narrowed\n ? sql`array::len(SELECT VALUE id FROM ${rows} WHERE ${this.predicate(narrowed, true)} LIMIT 1) > 0`\n : sql`array::len(${rows}) > 0`;\n const scope = this.#queries.scoped(edge.target, undefined, \"related\");\n const args = (scope ? { selector: { predicate: scope } } : {}) as never;\n // Without `self`, a link's first step is the row's own value: a judged row's\n // is the one it would leave, not the one stored.\n const root = sql.raw(\n edge.kind === \"reference\" && edge.owner === \"source\" && !closure.self\n ? \"$this\"\n : \"$this.id\"\n );\n const recursion =\n closure.depth === false\n ? this.#reached(edge, args, sql.raw(\"$root\"))\n : undefined;\n if (recursion)\n return sql`({ LET $root = ${root}; LET $r = ${recursion}; ${test(closure.self ? sql.raw(\"array::concat([$root], $r)\") : sql.raw(\"$r\"))} })`;\n const walk = this.#walk(edge, args, closure.depth, sql.raw(\"$root\"));\n const reached = closure.self\n ? sql.raw(\"array::concat([$root], $w.edges.c)\")\n : sql.raw(\"$w.edges.c\");\n return sql`({ ${this.#walked(walk, root)} ${test(reached)} })`;\n }\n\n /** Whether a related row exists, among those the quantifier looks at. */\n #related(\n relation: Membership,\n quantifier: string,\n inner: PreparedPredicate | undefined,\n path: string\n ): Sql {\n const narrowed = this.#queries.scoped(\n relation.target,\n quantifier === \"every\" && inner\n ? ({ kind: \"not\", predicate: inner } as const)\n : inner,\n \"related\"\n );\n if (relation.kind === \"junction\") {\n if (path) refuse(\"a to-many filter through a to-one link\");\n const { hop } = this.edgeOf(relation);\n const target = name(tableOf(relation.target));\n return narrowed\n ? sql`${hop}(${target} WHERE ${this.predicate(narrowed, true)})`\n : sql`${hop}${target}`;\n }\n const edge = reference(relation);\n if (!edge.many && edge.owner === \"source\" && this.#linked(edge)) {\n const link = `${path}${name(this.#queries.columnName(edge.source, edge.pairs[0]!.source)).toStatement()}`;\n if (narrowed && walksFurther(narrowed))\n return sql`(${sql.raw(link)} != NONE AND array::len(SELECT VALUE id FROM ${sql.raw(`$this.${link}`)} WHERE ${this.predicate(narrowed, true)}) > 0)`;\n return narrowed\n ? sql`(${sql.raw(link)} != NONE AND ${this.predicate(narrowed, true, `${link}.`)})`\n : sql`${sql.raw(link)} != NONE`;\n }\n if (path) refuse(\"a to-many filter through a to-one link\");\n // A non-empty list holds, in one parser level fewer than asking for its length.\n return this.#traversal(edge, narrowed, { take: 1 });\n }\n}\n","/**\n * `docs/architecture/query-backend-frontier.md` step 5.\n *\n * `Commands` locates and captures rows through `Queries.select`, so a nested\n * write reads through this. Everything else it asks of `Queries` is shared.\n */\n\nimport type { Dialect } from \"@drivers/types\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport type { ModelSql } from \"@query-engine/raptor3/shared/insert-value\";\nimport {\n type PreparedDomain,\n type PreparedPredicate,\n type PreparedProjection,\n type PreparedSelector,\n Queries,\n type Query,\n type SelectControls,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n CallScope,\n Condition,\n Parameter,\n RowPurpose,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Arguments, Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { Membership } from \"@query-engine/raptor3/shared/storage\";\nimport { Sql, sql } from \"@sql\";\nimport { SurrealReadBackend } from \"./read-backend\";\n\ntype AnyModel = Parameters<Queries[\"select\"]>[0];\n\nfunction refuse(what: string): never {\n throw new UnsupportedOperationError(\n `The SurrealDB write backend does not support ${what} yet.`\n );\n}\n\nexport class SurrealQueries extends Queries {\n /** `id` is the record's: a field of that name beside a key of another lives apart. */\n override columnName(model: AnyModel, field: string): string {\n const column = super.columnName(model, field);\n return column === \"id\" && !this.keyOrder(model).includes(field)\n ? \"id_field\"\n : column;\n }\n\n /** A caller's filter on a link row is a test of what a direct read could hide. */\n refuseHiddenLink(\n edge: Membership,\n filter: { readonly linkFields?: readonly string[] }\n ): void {\n if (!this.lowersLayer)\n this.domain?.refuseHiddenLinkRow(\n this,\n edge,\n filter.linkFields!,\n \"filter\"\n );\n }\n\n override under(domain: PreparedDomain, call?: CallScope): Queries {\n return new SurrealQueries(\n this.schema,\n this.adapter,\n this.result,\n domain,\n call\n );\n }\n\n /** A layer's predicate for this call, read while it lowers: `undefined` where it drops. */\n /** A layer's predicate for this call, `undefined` where the call drops it. */\n resolved(\n node: Extract<PreparedPredicate, { kind: \"layer\" }>\n ): PreparedPredicate | undefined {\n return node.resolve(this);\n }\n\n layer(\n node: Extract<PreparedPredicate, { kind: \"layer\" }>,\n lower: (resolved: PreparedPredicate) => Sql\n ): Sql | undefined {\n const resolved = node.resolve(this);\n if (resolved === undefined) return undefined;\n const excluded = (this.excluded ??= []);\n excluded.push(node.layer);\n try {\n return lower(resolved);\n } finally {\n excluded.pop();\n }\n }\n\n /** `predicate` among the rows this call may see for `purpose`. */\n scoped(\n model: AnyModel,\n predicate: PreparedPredicate | undefined,\n purpose: RowPurpose\n ): PreparedPredicate | undefined {\n const scope = this.scope(model, purpose)?.predicate;\n if (scope === undefined) return predicate;\n return predicate === undefined\n ? scope\n : { kind: \"and\", predicates: [predicate, scope] };\n }\n\n /** Whether a layer's predicates are lowering here, which read every column as it is. */\n get lowersLayer(): boolean {\n return (this.excluded?.length ?? 0) > 0;\n }\n\n /** The order this call's extensions give a read that states none. */\n orderOf(model: AnyModel): Arguments[\"orderBy\"] {\n return this.defaultOrder(model);\n }\n\n /** What a call's value is, in a domain's condition or operand. */\n callValue(parameter: Parameter): unknown {\n return parameter.read(this.values, this.instant);\n }\n\n holds(condition: Condition): boolean {\n return condition.holds(this.values, this.instant);\n }\n\n override read(\n model: AnyModel,\n operation: Parameters<Queries[\"read\"]>[1],\n args: Arguments\n ) {\n return this.lowering.read(model, operation, args);\n }\n\n /** These spell a statement's parts, and only a statement written whole is read here. */\n override updateAssignment(): Sql {\n return refuse(\"an assignment spelled apart from its statement\");\n }\n\n override lowerSelector(): Sql | undefined {\n return refuse(\"a condition spelled apart from its statement\");\n }\n\n spelling(model: AnyModel, dialect: Dialect): ModelSql {\n const low = this.lowering;\n return {\n dialect,\n table: () => sql.raw(model[\"~\"].names.sql!),\n column: (field) => low.physical(model, field),\n value: (field, value) => low.value(model, field, value),\n name: (...path) => sql.raw(path.join(\".\")),\n visible: (_alias, options) => {\n if (options?.update)\n throw new UnsupportedOperationError(\n \"SurrealDB: the rows a call may update are not a condition yet\"\n );\n const seen = this.scoped(\n model,\n options?.where === undefined\n ? undefined\n : this.prepareSelector(\n model,\n this.schema.admit(model, \"findMany\", {\n where: options.where as Input,\n }).where as Input\n ).predicate,\n \"root\"\n );\n return seen ? low.predicate(seen, true) : sql.raw(\"true\");\n },\n };\n }\n\n #backend: SurrealReadBackend | undefined;\n\n /** What spells this call's reads, and the parts of its writes that read: one, so that what a statement computes ahead of itself is stated once. */\n get lowering(): SurrealReadBackend {\n this.#backend ??= new SurrealReadBackend(this);\n return this.#backend;\n }\n\n /** A field of the row `selector` names, read inside the statement that spends it. */\n override locatedValue(\n model: AnyModel,\n field: string,\n selector: PreparedSelector\n ): Sql {\n const where = selector.predicate\n ? sql`WHERE ${this.lowering.predicate(selector.predicate, true)} `\n : sql.raw(\"\");\n return sql`(SELECT VALUE ${this.lowering.physical(model, field)} FROM ${sql.raw(model[\"~\"].names.sql!)} ${where}LIMIT 1)[0]`;\n }\n\n /** Rows a write named, by key, in the order it named them: a list reads so. */\n override selectSeries(\n prepared: PreparedProjection,\n identities: Input[],\n operation: \"createMany\" | \"updateMany\" = \"createMany\"\n ): Query {\n const { model } = prepared;\n const records = sql.join(\n identities.map((identity) => this.lowering.recordOfRow(model, identity)),\n \", \"\n );\n return {\n sql: sql`SELECT ${this.lowering.columns(prepared)} FROM [${records}]`,\n shape: prepared.shape,\n expectedRows: this.seriesExpectation(model, identities.length, operation),\n };\n }\n\n /**\n * `forUpdate` reads as it is: SurrealDB takes no lock, and a transaction that\n * writes a row another committed fails at its own commit.\n */\n override select(\n model: AnyModel,\n args: Partial<Arguments>,\n membership?: { edge: Membership; parent: Input },\n controls: SelectControls = {}\n ): Query {\n if (controls.source) refuse(\"a read over a write's own rows\");\n const projection =\n controls.projection ?? this.prepareProjection(model, args);\n const given = controls.selector\n ? controls.selector.predicate\n : args.where === undefined\n ? undefined\n : this.prepareSelector(model, args.where).predicate;\n const predicate = controls.purpose\n ? this.scoped(model, given, controls.purpose)\n : given;\n // A path reads a record's members without scanning the table holding them.\n const path =\n membership?.edge.kind === \"junction\" && !membership.edge.declared\n ? this.lowering.membersOf(membership.edge, membership.parent)\n : undefined;\n // A whole key stated as values is the record itself, read without a filter.\n const identity = controls.identity;\n const record =\n identity &&\n !path &&\n this.keyOrder(model).every(\n (key) => identity[key] != null && !(identity[key] instanceof Sql)\n )\n ? this.lowering.recordOfRow(model, identity)\n : undefined;\n const conditions = () => [\n ...(membership && !path\n ? [this.lowering.member(membership.edge, membership.parent)]\n : []),\n ...(identity && !record ? [this.lowering.identity(model, identity)] : []),\n ...(controls.unless?.predicate\n ? [this.lowering.predicate(controls.unless.predicate, false)]\n : []),\n ];\n return {\n sql: this.lowering.hoisted(() =>\n this.lowering.statement(\n model,\n projection,\n record ? { ...args, unordered: true } : args,\n predicate,\n conditions(),\n path ?? record\n )\n ),\n shape: projection.shape,\n };\n }\n}\n","/**\n * A SurrealDB transaction that can go back.\n *\n * SurrealQL has no savepoints, and writers meet at commit, where the loser has\n * written nothing. Both are answered by the same record: every statement this\n * transaction ran, with what it answered. Going back is a new transaction running\n * those statements again.\n *\n * That is sound when every statement answers as it did: nothing the caller was\n * told has changed, so it cannot tell this transaction from one that began later.\n * A different answer ends it with a conflict, since what the caller decided from\n * no longer holds. The new transaction sees newer rows, so a read is checked as\n * strictly as a write. Holding the answers costs no work until they are compared.\n */\n\nimport { TransactionError } from \"@errors\";\nimport type { Surreal, SurrealTransaction } from \"surrealdb\";\nimport { acquireWithMaxWait } from \"../shared/transaction-options\";\n\nconst CONFLICT = /can be retried|read or write conflict/;\n\n/** What a statement throws where a row it would leave is not permitted. */\nexport const FORBIDDEN_ROW = \"viborm: a row this write leaves is not permitted\";\n\n/** What a text sent whole throws where one of its statements asks what is not so. */\nexport const STOPPED = \"viborm: what this write asks is not so\";\n\n/** Two transactions that met at commit, in the words SurrealDB has for it. */\nexport function isConflict(error: unknown): boolean {\n return (\n error instanceof Error &&\n (CONFLICT.test(error.message) ||\n (error.cause instanceof Error && CONFLICT.test(error.cause.message)))\n );\n}\n\n/**\n * What may write wherever it stands in a text: a statement, a subquery or a block\n * (keywords are any case), or a function defined in the database or a module.\n */\nconst MAY_WRITE =\n /\\b(?:CREATE|UPDATE|UPSERT|DELETE|INSERT|RELATE|DEFINE|REMOVE|ALTER|REBUILD)\\b|\\b(?:fn|mod|silo|api)::/i;\nconst SELECTS = /^SELECT\\b/i;\n/** The form that reports a conflict by answering nothing, having written nothing. */\nconst IGNORES_CONFLICT = /^INSERT IGNORE\\b/i;\n/** A clause after which an insert answers nothing, whether it wrote or not. */\nconst ANSWERS_NOTHING = /\\bRETURN\\s+(?:NONE|BEFORE|VALUE\\s+NONE)\\b/i;\nconst NEXT_VALUE = /sequence::nextval\\(\\$(p\\d+)\\)/g;\n\n/** Each attempt is won by someone, so this bounds the writers that can meet at once. */\nexport const COMMITS = 16;\n\n/**\n * The wait after attempt `attempt` met another writer at its commit: at random,\n * since two losers running again together would only meet again, below a\n * ceiling that doubles from 20 ms to 1 s. Over {@link COMMITS} attempts that is\n * about 5 s in all (10 s at most), where a ceiling of 10 ms per attempt gave a\n * writer still busy after a second no chance to finish.\n */\nexport const backOff = (attempt: number): Promise<void> =>\n new Promise((resolve) =>\n setTimeout(resolve, Math.random() * Math.min(1000, 10 * 2 ** attempt))\n );\n\ninterface Statement {\n text: string;\n values: Record<string, unknown>;\n /** Absent when it failed, having perhaps written part of its change. */\n answer?: unknown;\n}\n\n/**\n * A read that writes nowhere in its text, or one ignored insert, alone in its text,\n * that answers no row although it answers each row it writes.\n */\nconst wroteNothing = ({ text, answer }: Statement) => {\n if (SELECTS.test(text)) return !MAY_WRITE.test(text);\n const rest = text.replace(IGNORES_CONFLICT, \"\");\n return (\n rest !== text &&\n !(MAY_WRITE.test(rest) || ANSWERS_NOTHING.test(rest)) &&\n Array.isArray(answer) &&\n answer.length === 1 &&\n Array.isArray(answer[0]) &&\n answer[0].length === 0\n );\n};\n\nconst asText = (answer: unknown) =>\n JSON.stringify(answer, (_key, value) =>\n typeof value === \"bigint\" ? `${value}n` : value\n );\n\n/**\n * A connection holds 64 open transactions and refuses the next (\"Too many open\n * transactions\"), so the others wait for one to end, as they would for a pool.\n */\nconst OPEN_TRANSACTIONS = 64;\n\nclass Slots {\n #free = OPEN_TRANSACTIONS;\n readonly #waiting: (() => void)[] = [];\n\n async take(): Promise<void> {\n if (this.#free > 0) {\n this.#free -= 1;\n return;\n }\n await new Promise<void>((resolve) => this.#waiting.push(resolve));\n }\n\n give(): void {\n const next = this.#waiting.shift();\n if (next) next();\n else this.#free += 1;\n }\n}\n\nconst slotsOf = new WeakMap<Surreal, Slots>();\n\nexport class ReplayedTransaction {\n readonly #client: Surreal;\n readonly #slots: Slots;\n #open: SurrealTransaction;\n #ended = false;\n readonly #log: Statement[] = [];\n #conflicted = false;\n\n private constructor(client: Surreal, slots: Slots, open: SurrealTransaction) {\n this.#client = client;\n this.#slots = slots;\n this.#open = open;\n }\n\n static async begin(\n client: Surreal,\n maxWaitMs?: number\n ): Promise<ReplayedTransaction> {\n let slots = slotsOf.get(client);\n if (!slots) {\n slots = new Slots();\n slotsOf.set(client, slots);\n }\n const held = slots;\n await acquireWithMaxWait(\n () => held.take(),\n () => held.give(),\n maxWaitMs,\n { driverName: \"surrealdb\", form: \"callback\" }\n );\n try {\n return new ReplayedTransaction(\n client,\n slots,\n await client.beginTransaction()\n );\n } catch (error) {\n slots.give();\n throw error;\n }\n }\n\n #end(): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#slots.give();\n }\n\n /** A concurrent write changed what it was told, whatever the caller then did. */\n get conflicted(): boolean {\n return this.#conflicted;\n }\n\n /** How far this transaction has come, to {@link rollbackTo} later. */\n get mark(): number {\n return this.#log.length;\n }\n\n async query<R>(text: string, values: Record<string, unknown>): Promise<R> {\n const statement: Statement = { text, values };\n // In the order they were sent, whichever answers first.\n this.#log.push(statement);\n await this.#reserveSequences(statement);\n statement.answer = await this.#open.query(statement.text, statement.values);\n return statement.answer as R;\n }\n\n /**\n * A sequence stands outside any transaction, so a statement running again would\n * take another value. Each is taken ahead instead, and the statement holds it.\n */\n async #reserveSequences(statement: Statement): Promise<void> {\n const taken = [...statement.text.matchAll(NEXT_VALUE)];\n if (taken.length === 0) return;\n const [reserved] = await this.#client.query<[unknown[]]>(\n `RETURN [${taken.map(([call]) => call).join(\", \")}]`,\n statement.values\n );\n const values = { ...statement.values };\n let index = 0;\n statement.text = statement.text.replace(NEXT_VALUE, () => {\n const name = `reserved${index}`;\n values[name] = reserved[index++];\n return `$${name}`;\n });\n statement.values = values;\n }\n\n /**\n * What a savepoint's rollback does: everything after `mark` never happened. Only\n * statements that cannot have written are left to stand without running the\n * others again, since the server refuses to commit over a partial write.\n */\n async rollbackTo(mark: number): Promise<void> {\n if (!this.#log.splice(mark).every(wroteNothing)) await this.#replay();\n }\n\n async #replay(): Promise<void> {\n await this.#open.cancel().catch(() => undefined);\n this.#open = await this.#client.beginTransaction();\n for (const statement of this.#log) {\n const answer = await this.#open.query(statement.text, statement.values);\n if (asText(answer) !== asText(statement.answer)) {\n this.#conflicted = true;\n throw new TransactionError(\n \"A concurrent write changed what this transaction read, so it cannot go on. This transaction can be retried.\"\n );\n }\n }\n }\n\n /** A write conflict leaves nothing applied, so the statements can run again. */\n async commit(): Promise<void> {\n try {\n for (let attempt = 1; ; attempt++) {\n try {\n await this.#open.commit();\n return;\n } catch (error) {\n if (!isConflict(error) || attempt === COMMITS) throw error;\n }\n await backOff(attempt);\n await this.#replay();\n }\n } catch (error) {\n // A replay that found another answer leaves its transaction open.\n await this.#open.cancel().catch(() => undefined);\n throw error;\n } finally {\n this.#end();\n }\n }\n\n async cancel(): Promise<void> {\n try {\n await this.#open.cancel();\n } finally {\n this.#end();\n }\n }\n}\n","/**\n * The write path's statements in SurrealQL. What a call means, which rows it\n * knows and in what order its statements go are the engine's\n * (`query-engine/raptor3/write`); here is only how each statement is said\n * where a record is its id, a many-to-many an edge, and a judged write a\n * block that refuses before it writes.\n */\n\nimport type { AnyDriver } from \"@drivers/exports\";\nimport {\n NestedWriteAssertionError,\n QueryEngineError,\n type UniqueConstraintError,\n UnsupportedOperationError,\n} from \"@errors\";\nimport { dividesByZero } from \"@query-engine/raptor3/shared/decimal\";\nimport { JoinedValue } from \"@query-engine/raptor3/shared/insert-value\";\nimport {\n type PreparedProjection,\n type PreparedSelector,\n wholeValue,\n} from \"@query-engine/raptor3/shared/query\";\nimport type { WriteJudgement } from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { SqlOperationContext } from \"@query-engine/raptor3/shared/sql-operation-context\";\nimport {\n linkJudgement,\n linkMembers,\n type Membership,\n} from \"@query-engine/raptor3/shared/storage\";\nimport {\n prepared,\n type Sent,\n type Statement,\n Stopped,\n} from \"@query-engine/raptor3/write/send\";\nimport {\n type Junction,\n type Question,\n Writer,\n} from \"@query-engine/raptor3/write/statements\";\nimport type { PreparedGuardFailure } from \"@query-engine/types\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport { Sql, sql } from \"@sql\";\nimport { Decimal, RecordId } from \"surrealdb\";\nimport type { SurrealQueries } from \"./queries\";\nimport {\n isOneValue,\n onceEach,\n quantized,\n type SurrealReadBackend,\n walksFurther,\n} from \"./read-backend\";\nimport { FORBIDDEN_ROW, isConflict, STOPPED } from \"./transaction\";\n\ntype AnyModel = PreparedProjection[\"model\"];\n\nconst ARITHMETIC: Readonly<Record<string, string>> = {\n increment: \"+\",\n decrement: \"-\",\n multiply: \"*\",\n divide: \"/\",\n};\n\n/**\n * A key a moved row can hold beside its old self: only what its field's type\n * admits, and nothing it could ever keep, since it is overwritten in that statement.\n */\nconst STAND_INS: Readonly<Record<string, Sql>> = {\n string: sql.raw(\"rand::string(32)\"),\n int: sql.raw(\"rand::int(-2147483648, 2147483647)\"),\n bigint: sql.raw(\"rand::int(-2147483648, 2147483647)\"),\n float: sql.raw(\"rand::float()\"),\n decimal: sql.raw(\"<decimal>rand::int(-2147483648, 2147483647)\"),\n datetime: sql.raw(\"time::from_millis(rand::int(0, 2147483647))\"),\n};\n\nconst JUDGED = sql.raw(`\"${FORBIDDEN_ROW}\"`);\nconst NOTHING = sql.raw(\"\");\n\n/** How many times a call is made again after meeting another at commit. */\nconst RERUNS = 16;\n\n/** A relation whose row holds a value of another in its own key. */\ntype FollowingEdge = Extract<Membership, { kind: \"reference\" }>;\n\n/** What a write holds at the top level ahead of itself, and what refuses with it. */\ninterface Ahead {\n readonly lets: Sql;\n readonly checks: Sql;\n}\n\nconst NOTHING_AHEAD: Ahead = { lets: NOTHING, checks: NOTHING };\n\n/** The parts of a text that say something, in order. */\nconst seq = (...parts: Sql[]): Sql =>\n sql.join(\n parts.filter((part) => part.toStatement() !== \"\"),\n \" \"\n );\n\nfunction refuse(what: string): never {\n throw new UnsupportedOperationError(\n `The SurrealDB write backend does not support ${what} yet.`\n );\n}\n\nconst fieldName = (identifier: string): Sql => sql.raw(identifier);\n\n/** A key part's value after arithmetic, computed here since a record's id is fixed. */\nfunction arithmetic(\n type: string,\n current: unknown,\n operator: string,\n operand: unknown\n): unknown {\n const zero = () => new QueryEngineError(\"Cannot divide a key by zero.\");\n if (type === \"decimal\") {\n const [a, b] = [new Decimal(String(current)), new Decimal(String(operand))];\n if (operator === \"divide\" && dividesByZero(operand)) throw zero();\n return (\n operator === \"increment\"\n ? a.add(b)\n : operator === \"decrement\"\n ? a.sub(b)\n : operator === \"multiply\"\n ? a.mul(b)\n : a.div(b)\n ).toString();\n }\n if (type === \"bigint\") {\n const [a, b] = [BigInt(String(current)), BigInt(String(operand))];\n if (operator === \"divide\" && b === 0n) throw zero();\n return operator === \"increment\"\n ? a + b\n : operator === \"decrement\"\n ? a - b\n : operator === \"multiply\"\n ? a * b\n : a / b;\n }\n if (type !== \"int\") refuse(`arithmetic on a key of type '${type}'`);\n const [a, b] = [Number(current), Number(operand)];\n if (operator === \"divide\" && b === 0) throw zero();\n return operator === \"increment\"\n ? a + b\n : operator === \"decrement\"\n ? a - b\n : operator === \"multiply\"\n ? a * b\n : Math.trunc(a / b);\n}\n\n/**\n * One call on SurrealDB. A write's own statement answers any read of the\n * rows it writes: `RETURN` reads after the write, and a delete reads ahead\n * of itself. No locks: two writers meet at commit, and the loser, having\n * written nothing, is made again from what the winner committed.\n */\nexport class SurrealCall extends SqlOperationContext {\n /** A request of several statements failed: it does not say which, so the call is made again, each statement its own request. */\n #apart: boolean | undefined;\n\n override answersInStatement(): boolean {\n return true;\n }\n\n override async again(error: unknown, attempt: number): Promise<boolean> {\n if (isConflict(error)) {\n if (attempt === RERUNS) return false;\n // Two losers made again together would only meet again.\n await new Promise((resolve) =>\n setTimeout(resolve, 5 + Math.random() * 45 * attempt)\n );\n return true;\n }\n return this.#apart === false && (this.#apart = true);\n }\n\n /**\n * A text takes any number of statements, and answers each: sent as the\n * driver's batch, where each statement is still seen as its own.\n */\n override together(\n driver: AnyDriver,\n statements: readonly Statement[],\n whole: boolean\n ): Promise<Sent[]> | undefined {\n if (this.#apart) return undefined;\n return driver\n ._executeBatch<Input>(\n statements.map((statement) => {\n const { believed, probe, premise } = statement;\n const text = believed ? probe! : statement.sql;\n return prepared(this, driver, {\n ...statement,\n // In a text that is its own unit, what is asked stops the text where it is not so.\n sql:\n whole && text === probe\n ? sql`IF array::len({ ${text} }) ${sql.raw(premise === \"exists\" ? \"=\" : \">\")} 0 { THROW ${sql.raw(`\"${STOPPED}\"`)} }`\n : text,\n });\n }),\n undefined,\n this.attribution\n )\n .catch((error) => {\n this.#apart ??= false;\n throw error;\n });\n }\n}\n\nexport class SurrealWriter extends Writer {\n readonly #q: SurrealQueries;\n readonly #low: SurrealReadBackend;\n\n constructor(operation: SqlOperationContext, hears?: Writer[\"hears\"]) {\n super(operation, hears);\n this.#q = operation.queries as unknown as SurrealQueries;\n this.#low = this.#q.lowering;\n }\n\n /** Asks the database in the call's unit, before the statement being written is sent. */\n async #heard(statement: Sql, model: AnyModel): Promise<Input[]> {\n if (!this.hears) refuse(\"a write that reads before it writes, in a batch\");\n return (await this.hears(statement, model)) as Input[];\n }\n\n /** `INSERT IGNORE` answers with the rows it wrote: none is a row passed by, and nothing failed. */\n override get passes(): boolean {\n return true;\n }\n\n /** A question is asked as it is: its answer is heard, and nothing here fails to say no. */\n protected override asserts(probe: Sql): Sql {\n return probe;\n }\n\n override asks(\n asked: readonly (readonly [Question, (Input | Input[])?])[],\n believed: \"presumed\" | \"read\"\n ): Statement {\n const [first] = asked as [readonly [Question, (Input | Input[])?]];\n if (asked.length === 1) return super.asks(asked, believed);\n // One row answers where every question names one.\n const probe = this.#low.hoisted(\n () =>\n sql`SELECT true AS found FROM [0] WHERE ${sql.join(\n asked.map(\n (each) =>\n sql`array::len((${super.asks([each], believed).probe!})) > 0`\n ),\n \" AND \"\n )}`\n );\n return { ...super.asks([first], believed), sql: probe, probe };\n }\n\n /** One row as an object literal: an absent or null field stores nothing. */\n #row(model: AnyModel, row: Input): Sql {\n const members = this.#rowMembers(model, row).map(\n ([column, value]) => sql`${fieldName(column)}: ${value}`\n );\n return sql`{ ${sql.join(members, \", \")} }`;\n }\n\n /** A row's columns and what each holds, its record first. */\n #rowMembers(model: AnyModel, row: Input): [string, Sql][] {\n const keys = this.#q.keyOrder(model);\n const members = Object.entries(row)\n .filter(\n ([field, value]) =>\n value !== null && value !== undefined && !keys.includes(field)\n )\n .map(([field, value]): [string, Sql] => [\n this.#q.columnName(model, field),\n this.#low.value(model, field, value),\n ]);\n // Written here, not left to its default: a transaction reserves what it states.\n const { scalars } = model[\"~\"].state;\n const generated = Object.keys(scalars)\n .filter(\n (field) =>\n scalars[field]![\"~\"].state.autoGenerate?.kind === \"increment\" &&\n !keys.includes(field) &&\n row[field] === undefined\n )\n .map((field): [string, Sql] => {\n const column = this.#q.columnName(model, field);\n return [\n column,\n sql`sequence::nextval(${`${model[\"~\"].names.sql!}_${column}_seq`})`,\n ];\n });\n return [\n [\"id\", this.#recordKey(model, row, keys)],\n ...members,\n ...generated,\n ];\n }\n\n /**\n * One row created at its record, where the row states it. `INSERT` costs about\n * twice as much for one row, and refuses a taken record or a unique value in the\n * same words. A key a sequence gives, or the statement reads, is no record yet.\n */\n #created(model: AnyModel, row: Input): Sql | undefined {\n const [stated, ...members] = this.#rowMembers(model, row);\n const record = stated![1];\n if (!(isOneValue(record) && record.values[0] instanceof RecordId))\n return undefined;\n const content = members.every(([, value]) => isOneValue(value))\n ? sql`${Object.fromEntries(\n members.map(([column, value]) => [column, value.values[0]])\n )}`\n : sql`{ ${sql.join(\n members.map(([column, value]) => sql`${fieldName(column)}: ${value}`),\n \", \"\n )} }`;\n return sql`CREATE ${record} CONTENT ${content}`;\n }\n\n /** Rows as a list: one parameter, where each value of each is one. */\n #rows(model: AnyModel, rows: readonly Input[]): Sql {\n const members = rows.map((row) => this.#rowMembers(model, row));\n const held = members.every((row) =>\n row.every(([, value]) => isOneValue(value))\n );\n if (!held)\n return sql`[${sql.join(\n rows.map((row) => this.#row(model, row)),\n \", \"\n )}]`;\n return sql`${members.map((row) =>\n Object.fromEntries(\n row.map(([column, value]) => [column, value.values[0]])\n )\n )}`;\n }\n\n /** A row's id: what it states, or the next of its sequence. */\n #recordKey(model: AnyModel, row: Input, keys: readonly string[]): Sql {\n const next = (key: string, sequence: string) => {\n if (\n model[\"~\"].state.scalars[key]?.[\"~\"].state.autoGenerate?.kind !==\n \"increment\"\n )\n refuse(\"a key the database generates\");\n return sql`sequence::nextval(${sequence})`;\n };\n const table = model[\"~\"].names.sql!;\n if (keys.length === 1) {\n const given = row[keys[0]!];\n return given === undefined\n ? next(keys[0]!, `${table}_seq`)\n : this.#low.value(model, keys[0]!, given);\n }\n if (\n keys.every((key) => row[key] !== undefined && !(row[key] instanceof Sql))\n )\n return sql`${this.#low.recordOf(model, row)}`;\n const parts = keys.map((key) => {\n if (row[key] instanceof Sql) return row[key];\n if (row[key] !== undefined)\n return this.#low.keyPart(model, key, row[key]);\n return next(key, `${table}_${this.#q.columnName(model, key)}_seq`);\n });\n return sql`[${sql.join(parts, \", \")}]`;\n }\n\n #assignments(model: AnyModel, values: Input): Sql {\n return sql.join(\n this.#assigned(model, values).map(\n ({ column, value }) => sql`${column} = ${value}`\n ),\n \", \"\n );\n }\n\n /** Each field an update writes, and what it writes there. */\n #assigned(model: AnyModel, values: Input): { column: Sql; value: Sql }[] {\n const low = this.#low;\n return Object.entries(values).map(([field, given]) => {\n const column = low.physical(model, field);\n const whole = wholeValue(given);\n if (whole) {\n return {\n column,\n value:\n whole.value === null\n ? sql.raw(\"NONE\")\n : low.value(model, field, whole.value),\n };\n }\n const [operator, operand] = Object.entries(given as Input)[0]!;\n const state = model[\"~\"].state.scalars[field]?.[\"~\"].state;\n if (operator === \"push\" || operator === \"unshift\") {\n const members = low.value(model, field, [operand].flat());\n return {\n column,\n value:\n operator === \"push\"\n ? sql`array::concat(${column} ?? [], ${members})`\n : sql`array::concat(${members}, ${column} ?? [])`,\n };\n }\n const sign = ARITHMETIC[operator];\n if (!sign) refuse(`the '${operator}' update`);\n if (operator === \"divide\" && state?.decimal && dividesByZero(operand))\n throw new QueryEngineError(\n `Cannot divide decimal field '${field}' by zero.`\n );\n const computed = sql`${column} ${sql.raw(sign)} ${low.value(model, field, operand)}`;\n const change =\n operator === \"multiply\" || operator === \"divide\"\n ? quantized(state, computed)\n : computed;\n // SQL leaves NULL as it is, where NONE would refuse the arithmetic.\n return {\n column,\n value: state?.nullable\n ? sql`(IF ${column} = NONE { NONE } ELSE { ${change} })`\n : change,\n };\n });\n }\n\n /** What a write answers with: the rows as the call reads them, their ids where it counts them, or nothing. */\n #returning(\n projection: PreparedProjection | undefined,\n counted: boolean\n ): Sql {\n if (projection) return sql`RETURN ${this.#low.columns(projection)}`;\n return sql.raw(counted ? \"RETURN id\" : \"RETURN NONE\");\n }\n\n /**\n * Where a write finds its rows: the records `keys` name, the record the\n * question names by its whole key, or the table; what else is asked of\n * them; and what the statement states ahead of itself.\n */\n #frame(\n question: Question,\n keys?: readonly Input[]\n ): { readonly before: Sql; readonly target: Sql; readonly where: Sql } {\n const { model, member } = question;\n const low = this.#low;\n const selector = keys\n ? this.selector({\n ...question,\n // Rows the call knows are named by their keys; what found them is said again only where asked.\n where: question.again ? question.where : undefined,\n unique: false,\n only: undefined,\n })\n : this.selector(question);\n let from = fieldName(model[\"~\"].names.sql!);\n let predicate = selector.predicate;\n let named = false;\n if (keys) {\n named = true;\n from =\n keys.length === 1\n ? low.recordOfRow(model, keys[0]!)\n : sql`[${sql.join(\n keys.map((key) => low.recordOfRow(model, key)),\n \", \"\n )}]`;\n } else if (!member && predicate) {\n const record = low.namedRecord(model, predicate);\n if (record) {\n named = true;\n from = record.record;\n predicate = record.rest;\n }\n }\n const conditions = onceEach([\n ...(member ? [low.member(member.edge, member.of)] : []),\n ...(predicate\n ? member\n ? low.conjuncts(predicate)\n : low.located(model, predicate, named || undefined)\n : []),\n ]);\n const where = conditions.length\n ? sql`WHERE ${sql.join(conditions, \" AND \")}`\n : NOTHING;\n const limit = keys || member ? undefined : question.limit;\n if (limit !== undefined) {\n // The first rows of it in key order.\n const { extras, order } = low.order(model, undefined);\n const taken = sql`ORDER BY ${order} LIMIT ${sql.raw(String(Number(limit)))}`;\n return {\n before: NOTHING,\n where: NOTHING,\n target:\n extras.length === 0\n ? sql`(SELECT VALUE id FROM ${seq(from, where, taken)})`\n : sql`(SELECT id, ${sql.join(extras, \", \")} FROM ${seq(from, where, taken)}).id`,\n };\n }\n // A statement here evaluates its `WHERE` row by row and sees what it has\n // already written, where SQL reads a snapshot: a filter that reads other\n // rows finds its rows first.\n if (selector.predicate && walksFurther(selector.predicate))\n return {\n before: sql`LET $targets = (SELECT VALUE id FROM ${seq(from, where)});`,\n target: sql.raw(\"$targets\"),\n where: NOTHING,\n };\n return { before: NOTHING, target: from, where };\n }\n\n /**\n * Refused where a junction holds one of `rows` back. A record's edges go with it,\n * before anything in the database could object, so this is the engine's: a raw\n * delete does not hold back.\n */\n #heldBack(model: AnyModel, rows: Sql): Sql | undefined {\n const { schema } = this.operation;\n const refusals = schema.restrictingSlots(model).flatMap((slot) => {\n const edge = schema.membership(model, slot);\n if (edge.kind !== \"junction\" || edge.declared) return [];\n const { table, near } = this.#low.edgeOf(edge);\n return [\n sql`IF array::len(SELECT VALUE id FROM ${table} WHERE ${near} IN (SELECT VALUE id FROM ${rows}) LIMIT 1) > 0 { THROW ${`ON DELETE REJECT: ${edge.name}`} };`,\n ];\n });\n return refusals.length ? sql.join(refusals, \" \") : undefined;\n }\n\n /** Refused unless every row in `rows`, read as a list, holds what judges it. */\n #judges(rows: string, judge: PreparedSelector | undefined): Ahead {\n if (!judge?.predicate) return NOTHING_AHEAD;\n const holds = this.#low.judging(() =>\n this.#low.predicate(judge.predicate!, true)\n );\n return {\n lets: sql`LET $judged = (SELECT VALUE 1 FROM ${sql.raw(rows)} WHERE ${holds});`,\n checks: sql`IF array::len($judged) != array::len(${sql.raw(rows)}) { THROW ${JUDGED} };`,\n };\n }\n\n /**\n * What an update states ahead of itself: the rows it would leave, as `next`\n * states them, each refused unless it holds what judges it. So the refusal\n * comes before a unique index or a reference could object, as a judged\n * statement's does in SQL. Nothing where nothing judges them.\n */\n #judgedNext(\n model: AnyModel,\n next: () => Sql,\n assigned: readonly string[],\n judgement: WriteJudgement | undefined,\n candidatesJudged = true\n ): Ahead {\n const judges = this.#q.domain?.judge;\n if (judgement === undefined || judges === undefined) return NOTHING_AHEAD;\n const judge = judges.produced(\n model,\n judgement,\n candidatesJudged ? assigned : undefined\n );\n const cycles = judges.cycles(model, judgement);\n if (!judge?.predicate && cycles.length === 0) return NOTHING_AHEAD;\n const { lets, checks } = this.#judges(\"$next\", judge);\n return {\n lets: seq(sql`LET $next = ${next()};`, lets),\n checks: seq(\n checks,\n ...cycles.map((relation) => this.#staysAcyclic(model, relation))\n ),\n };\n }\n\n /** {@link #judgedNext} over the rows of `source` as an update writing `values` leaves them. */\n #judgedRows(\n model: AnyModel,\n source: Sql,\n values: Input,\n judgement: WriteJudgement | undefined,\n candidatesJudged = true\n ): Ahead {\n return this.#judgedNext(\n model,\n () => sql`(SELECT ${this.#leaving(model, values)} FROM ${source})`,\n Object.keys(values),\n judgement,\n candidatesJudged\n );\n }\n\n /** A row as an update writing `values` leaves it, read from the row it reads. */\n #leaving(model: AnyModel, values: Input): Sql {\n const written = this.#assigned(model, values).map(\n ({ column, value }) => sql`${value} AS ${column}`\n );\n return sql.join([sql.raw(\"*\"), ...written], \", \");\n }\n\n /**\n * A write with what it holds ahead of it. What is held stands at the top level, and\n * the block holds only what must refuse together with the write, as one transaction.\n */\n #stated(before: Sql, ahead: Ahead, write: Sql): Sql {\n if (ahead === NOTHING_AHEAD) return seq(before, write);\n return seq(before, ahead.lets, sql`RETURN { ${seq(ahead.checks, write)} }`);\n }\n\n /** Refused where a row in `$next` would hold itself among what its link walks to. */\n #staysAcyclic(model: AnyModel, relation: string): Sql {\n const edge = this.operation.schema.membership(model, relation);\n if (edge.kind === \"reference\" && this.#low.isLinked(edge)) {\n const link = this.#low.physical(model, edge.pairs[0]!.source);\n return sql`IF array::len(SELECT VALUE 1 FROM $next WHERE ${link} != NONE AND (${link} = id OR id IN ${link}.{..+collect}.${link})) > 0 { THROW ${JUDGED} };`;\n }\n return sql`IF array::len(array::filter($next, |$candidate| $candidate.id IN ${this.#low.walkFrom(edge, sql.raw(\"$candidate\"))}.edges.c)) > 0 { THROW ${JUDGED} };`;\n }\n\n /** What a judged write of the rows a question names refuses with. */\n #refusal(\n question: Question,\n judgement: WriteJudgement | undefined\n ): PreparedGuardFailure | undefined {\n const judge = this.#q.domain?.judge;\n if (!(judgement && judge)) return undefined;\n return judge.refusal(\n this.operation.operation,\n question.model,\n judgement,\n question.verb,\n (question.member?.edge ?? question.through)?.name\n );\n }\n\n override async insert(\n model: AnyModel,\n values: Input[],\n relation?: string,\n returns?: PreparedProjection,\n beside?: readonly string[],\n skips = false\n ): Promise<Statement> {\n const low = this.#low;\n const rows = await this.computed(model, values);\n const table = fieldName(model[\"~\"].names.sql!);\n const judges = this.#q.domain?.judge;\n const judge = judges?.produced(model);\n const judged = judge?.predicate !== undefined;\n const verb = sql.raw(skips ? \"INSERT IGNORE\" : \"INSERT\");\n const statement = low.hoisted(() => {\n // With what the database decides of the row beside, where the call needs both.\n const seen = new Set<string>();\n const answered = [returns, beside && this.fields(model, beside)].flatMap(\n (read) =>\n read?.fields\n .filter((field) => !seen.has(field.name) && seen.add(field.name))\n .map((field) => low.column(model, field)) ?? []\n );\n // Its own rows' count is what a call that creates many answers with.\n const returning = answered.length\n ? sql`RETURN ${sql.join(answered, \", \")}`\n : sql.raw(\n relation === undefined || skips ? \"RETURN id\" : \"RETURN NONE\"\n );\n const created =\n rows.length === 1 && !skips && !judged\n ? this.#created(model, rows[0]!)\n : undefined;\n if (created) return sql`${created} ${returning}`;\n const insert = (held: Sql) =>\n sql`${verb} INTO ${table} ${held} ${returning}`;\n if (!judged) return insert(this.#rows(model, rows));\n const { lets, checks } = this.#judges(\"$rows\", judge);\n // The rows stand outside the block: an `IF` in a block beside a long literal takes\n // about the cube of its length (800 rows, 6 s; 1,600 never ends and holds the server).\n return sql`LET $rows = ${this.#rows(model, rows)}; ${lets} RETURN { ${checks} ${insert(sql.raw(\"$rows\"))} }`;\n });\n return {\n model,\n sql: statement,\n ...(judged && {\n stops: judges!.refusal(\n this.operation.operation,\n model,\n undefined,\n \"create\",\n relation\n ),\n }),\n };\n }\n\n override async update(\n question: Question,\n values: Input,\n keys?: readonly Input[],\n projection?: PreparedProjection,\n counted = !keys\n ): Promise<Statement> {\n const { model } = question;\n const low = this.#low;\n const [field, joined] = (Object.entries(values).find(\n ([, value]) => value instanceof JoinedValue\n ) ?? []) as [string, JoinedValue] | [];\n const [given] = await this.computed(model, [\n Object.fromEntries(\n Object.entries(values).filter(([, value]) => value !== joined)\n ),\n ]);\n const judgement = this.judged(question);\n const stops = this.#refusal(question, judgement);\n if (joined)\n return {\n model,\n stops,\n sql: await this.#listed(\n question,\n field!,\n joined,\n given!,\n keys,\n projection\n ),\n };\n const returning = this.#returning(projection, counted);\n const answer = projection ? low.columns(projection) : sql.raw(\"id\");\n const located = (columns: Sql) =>\n low.hoisted(() => {\n const { before, target, where } = this.#frame(question, keys);\n return seq(before, sql`SELECT ${columns} FROM`, target, where);\n });\n if (this.#keyChange(model, given!).length > 0) {\n // A record's id cannot change: each row is found, moved, and the rest of the write follows it.\n const moved: Input[] = [];\n for (const row of await this.#heard(\n located(this.#as(model, this.#q.keyOrder(model))),\n model\n ))\n moved.push(await this.#moveRecord(model, row, given!));\n if (moved.length === 0) return { model, sql: sql`RETURN []` };\n const rest = this.#withoutKeys(model, given!);\n const records = sql`[${sql.join(\n moved.map((row) => low.recordOfRow(model, row)),\n \", \"\n )}]`;\n // The moved records are what the update produces, judged as its rows would be\n // where nothing moved: their candidates stood under the keys they left.\n return {\n model,\n stops,\n sql: low.hoisted(() =>\n this.#stated(\n NOTHING,\n this.#judgedRows(model, records, rest, judgement, false),\n Object.keys(rest).length > 0\n ? sql`UPDATE ${records} SET ${this.#assignments(model, rest)} ${returning}`\n : sql`SELECT ${answer} FROM ${records}`\n )\n ),\n };\n }\n const statement = low.hoisted(() => {\n const { before, target, where } = this.#frame(question, keys);\n return this.#stated(\n before,\n this.#judgedRows(model, seq(target, where), given!, judgement),\n seq(\n sql`UPDATE ${target} SET ${this.#assignments(model, given!)}`,\n where,\n returning\n )\n );\n });\n const followers = this.#keyFollowers(model, given!);\n if (followers.length === 0) return { model, sql: statement, stops };\n // Nothing in the database moves a record: those holding what this write\n // changes in their own keys are moved here, once it is written.\n const stored = this.#as(model, this.operation.schema.storedFields(model));\n const before = await this.#heard(located(stored), model);\n const said = await this.#heard(statement, model).catch((error) => {\n throw stops && error instanceof NestedWriteAssertionError\n ? new Stopped({ model, sql: statement, stops })\n : error;\n });\n await this.#follow(model, followers, before, stored);\n return { model, sql: sql`RETURN ${said}` };\n }\n\n /** Fields of a row as a read names them here: each under its own name. */\n #as(model: AnyModel, fields: readonly string[]): Sql {\n return sql.join(\n fields.map(\n (field) =>\n sql`${this.#low.physical(model, field)} AS ${fieldName(field)}`\n ),\n \", \"\n );\n }\n\n /**\n * A value each row takes from a list: what gives the value names the rows, read\n * in the call's unit, and the one statement writes a row only while it holds what\n * it was named by.\n */\n async #listed(\n question: Question,\n field: string,\n joined: JoinedValue,\n beside: Input,\n keys: readonly Input[] | undefined,\n projection: PreparedProjection | undefined\n ): Promise<Sql> {\n const { model } = question;\n const q = this.#q;\n const low = this.#low;\n const selector = this.selector(question, keys);\n const spelt = q.spelling(model, this.operation.driver.dialect);\n const entries = await joined.rows(\n {\n ...spelt,\n // The rows this update may write are those its own question names.\n visible: (alias, options) =>\n options?.update\n ? selector.predicate\n ? low.predicate(selector.predicate, true)\n : sql.raw(\"true\")\n : spelt.visible(alias, options),\n },\n (statement) => this.#heard(statement, model)\n );\n const identity = q.keyOrder(model);\n const writes = entries.map(({ where, value }) => ({\n record: low.recordOfRow(\n model,\n Object.fromEntries(identity.map((key) => [key, where[key]]))\n ),\n values: { [field]: value, ...beside } as Input,\n where: sql.join(\n [\n sql.raw(\"true\"),\n ...Object.entries(where)\n .filter(([held]) => !identity.includes(held))\n .map(([held, was]) =>\n was === null || was === undefined\n ? sql`${low.physical(model, held)} = NONE`\n : sql`${low.physical(model, held)} = ${low.value(model, held, was)}`\n ),\n ],\n \" AND \"\n ),\n }));\n if (writes.length === 0) return sql`RETURN []`;\n // Each row is judged as it would be left, as the rows of an update are.\n return low.hoisted(() => {\n const written = sql`array::flatten([${sql.join(\n writes.map(\n ({ record, values, where }) =>\n sql`(UPDATE ${record} SET ${this.#assignments(model, values)} WHERE ${where} RETURN id)`\n ),\n \", \"\n )}])`;\n return this.#stated(\n NOTHING,\n this.#judgedNext(\n model,\n () =>\n sql`array::flatten([${sql.join(\n writes.map(\n ({ record, values, where }) =>\n sql`(SELECT ${this.#leaving(model, values)} FROM ${record} WHERE ${where})`\n ),\n \", \"\n )}])`,\n [field, ...Object.keys(beside)],\n this.judged(question)\n ),\n projection\n ? sql`LET $written = ${written}.id; RETURN (SELECT ${low.columns(projection)} FROM $written);`\n : sql`RETURN ${written}`\n );\n });\n }\n\n override remove(\n question: Question,\n keys?: readonly Input[],\n projection?: PreparedProjection,\n counted = !keys\n ): Statement {\n const { model } = question;\n const low = this.#low;\n return {\n model,\n sql: low.hoisted(() => {\n const { before, target, where } = this.#frame(\n { ...question, intent: \"delete\" },\n keys\n );\n const heldBack = this.#heldBack(model, sql.raw(\"$rows\"));\n if (!(heldBack || projection))\n return seq(\n before,\n sql`DELETE`,\n target,\n where,\n sql.raw(counted ? \"RETURN BEFORE\" : \"RETURN NONE\")\n );\n // `RETURN BEFORE` is the row alone, so what it answers reads ahead of it, in\n // the one statement: a block runs as a transaction of its own.\n return seq(\n before,\n sql`LET $rows = (SELECT VALUE id FROM ${seq(target, where)});`,\n projection\n ? sql`LET $answer = (SELECT ${low.columns(projection)} FROM $rows);`\n : NOTHING,\n sql`RETURN { ${seq(\n heldBack ?? NOTHING,\n projection\n ? sql`DELETE $rows; RETURN $answer;`\n : sql`DELETE $rows RETURN BEFORE`\n )} }`\n );\n }),\n };\n }\n\n override async either(\n question: Question,\n row: Input,\n set: Input,\n projection: PreparedProjection\n ): Promise<Statement> {\n const { model } = question;\n const low = this.#low;\n const [given] = await this.computed(model, [row]);\n const [updates] = await this.computed(model, [set]);\n const target = this.selector(question).uniqueKey!.fields;\n const table = fieldName(model[\"~\"].names.sql!);\n const returning = this.#returning(projection, true);\n return {\n model,\n sql: low.hoisted(() => {\n const created = this.#row(model, given!);\n const assignments = this.#assignments(model, updates!);\n if (this.#q.keyOrder(model).every((key) => target.includes(key)))\n return sql`INSERT INTO ${table} ${created} ON DUPLICATE KEY UPDATE ${assignments} ${returning}`;\n // `ON DUPLICATE KEY` takes a conflict on any index, and only the target's\n // may update: the record is found by it, and another conflict still refuses.\n const found = sql.join(\n target.map(\n (field) =>\n sql`${low.physical(model, field)} = ${low.value(model, field, given![field])}`\n ),\n \" AND \"\n );\n return sql`RETURN { LET $found = (SELECT VALUE id FROM ${table} WHERE ${found} LIMIT 1)[0]; RETURN IF $found != NONE { UPDATE $found SET ${assignments} ${returning} } ELSE { INSERT INTO ${table} [${created}] ${returning} }; }`;\n }),\n };\n }\n\n override async link(\n edge: Junction,\n pairs: readonly (readonly [Input, Input])[],\n through?: Input\n ): Promise<Statement[]> {\n const low = this.#low;\n const { uniqueSide } = edge;\n const statements: Sql[] = [];\n const own = uniqueSide === \"source\" ? 0 : 1;\n if (edge.declared) {\n const { model } = edge.declared;\n const members = linkMembers(edge);\n const table = fieldName(model[\"~\"].names.sql!);\n const taken = await this.linked(\n edge,\n members.map(({ pair }) => pair.junctionField),\n through\n );\n const holds = (side: Junction[\"sourceSide\"], row: Input) =>\n sql.join(\n side.members.map((pair) => {\n const field = low.linkFieldOf(edge, pair.junctionField);\n return sql`${low.physical(model, field)} = ${low.value(model, field, row[pair.referencedField])}`;\n }),\n \" AND \"\n );\n for (const pair of pairs) {\n // The link that side holds takes the other row: the one it held goes.\n if (uniqueSide)\n statements.push(\n sql`DELETE ${table} WHERE ${holds(edge[`${uniqueSide}Side`], pair[own])} AND !(${holds(\n edge[uniqueSide === \"source\" ? \"targetSide\" : \"sourceSide\"],\n pair[1 - own]!\n )}) RETURN NONE`\n );\n const row = this.#row(model, {\n ...Object.fromEntries(\n members.map(({ side, pair: member }) => [\n low.linkFieldOf(edge, member.junctionField),\n pair[side === edge.sourceSide ? 0 : 1][member.referencedField],\n ])\n ),\n ...taken.row,\n });\n statements.push(\n taken.sets\n ? sql`INSERT INTO ${table} ${row} ON DUPLICATE KEY UPDATE ${this.#assignments(model, taken.sets)} RETURN NONE`\n : sql`INSERT IGNORE INTO ${table} [${row}] RETURN NONE`\n );\n }\n } else {\n const { table, near, far } = low.edgeOf(edge);\n const ends = pairs.map(\n (pair) =>\n [\n low.end(\n edge.sourceSide,\n (member) => pair[0][member.referencedField]\n ),\n low.end(\n edge.targetSide,\n (member) => pair[1][member.referencedField]\n ),\n ] as const\n );\n if (uniqueSide) {\n // A singular relation needs its index, so its edges carry a record, and a\n // `RELATE` would refuse the pair an idempotent link must skip. The edge\n // that side holds to another row goes first.\n const [held, other] = own === 0 ? [near, far] : [far, near];\n for (const pair of ends)\n statements.push(\n sql`DELETE ${table} WHERE ${held} = ${pair[own]} AND ${other} != ${pair[1 - own]!} RETURN NONE`\n );\n statements.push(\n sql`INSERT RELATION IGNORE INTO ${table} [${sql.join(\n ends.map(\n ([source, target]) =>\n sql`{ ${near}: ${source}, ${far}: ${target} }`\n ),\n \", \"\n )}] RETURN NONE`\n );\n } else {\n // A `LIGHTWEIGHT` edge is its pair, so `RELATE` is idempotent by itself and\n // takes one source's targets in one statement.\n const forward = near.toStatement() === \"in\";\n const bySource = new Map<string, { source: Sql; targets: Sql[] }>();\n for (const [source, target] of ends) {\n const name = `${source.toStatement()} ${source.values.map(String).join(\" \")}`;\n const run = bySource.get(name) ?? { source, targets: [] };\n run.targets.push(target);\n bySource.set(name, run);\n }\n for (const { source, targets } of bySource.values()) {\n const all = sql`[${sql.join(targets, \", \")}]`;\n statements.push(\n forward\n ? sql`RELATE (${source})->${table}->(${all}) RETURN NONE`\n : sql`RELATE (${all})->${table}->(${source}) RETURN NONE`\n );\n }\n }\n }\n return statements.map((statement) => ({\n sql: statement,\n model: edge.source,\n }));\n }\n\n override unlink(\n edge: Junction,\n from: Input,\n to: Input | undefined,\n kept: readonly Input[]\n ): Statement {\n const low = this.#low;\n // Every link but those kept: of the rows the call may take out, and no other.\n const allowed = to\n ? undefined\n : this.#q.domainOf(edge.target, \"related\", linkJudgement(edge))\n ?.predicate;\n const writable = allowed\n ? sql`LET $writable = (SELECT VALUE id FROM ${fieldName(edge.target[\"~\"].names.sql!)} WHERE ${low.predicate(allowed, true)});`\n : NOTHING;\n const among = (far: Sql) => (allowed ? [sql`${far} IN $writable`] : []);\n if (edge.declared) {\n const { model } = edge.declared;\n const holds = (side: Junction[\"sourceSide\"], row: Input) =>\n sql.join(\n side.members.map((pair) => {\n const field = low.linkFieldOf(edge, pair.junctionField);\n return sql`${low.physical(model, field)} = ${low.value(model, field, row[pair.referencedField])}`;\n }),\n \" AND \"\n );\n return {\n model: edge.source,\n sql: seq(\n writable,\n sql`DELETE ${fieldName(model[\"~\"].names.sql!)} WHERE ${sql.join(\n [\n holds(edge.sourceSide, from),\n ...(to ? [holds(edge.targetSide, to)] : []),\n ...kept.map((row) => sql`!(${holds(edge.targetSide, row)})`),\n ...among(low.linkTarget(edge, edge.targetSide, \"\")),\n ],\n \" AND \"\n )} RETURN NONE`\n ),\n };\n }\n const { far, out } = low.edgeOf(edge);\n const end = (side: Junction[\"sourceSide\"], row: Input) =>\n low.end(side, (pair) => row[pair.referencedField]);\n const conditions = [\n ...(to ? [sql`${far} = ${end(edge.targetSide, to)}`] : []),\n ...(kept.length\n ? [\n sql`${far} NOT IN [${sql.join(\n kept.map((row) => end(edge.targetSide, row)),\n \", \"\n )}]`,\n ]\n : []),\n ...among(far),\n ];\n // From its source, an edge is reached along the record's own list.\n return {\n model: edge.source,\n sql: seq(\n writable,\n sql`DELETE ${end(edge.sourceSide, from)}${out}`,\n conditions.length\n ? sql`WHERE ${sql.join(conditions, \" AND \")}`\n : NOTHING,\n sql`RETURN NONE`\n ),\n };\n }\n\n /**\n * A refusal here says what it met: the record, where the row's own key was\n * taken, or the index, under the name a migration gives a model's key.\n */\n override refusedFor(\n model: AnyModel,\n key: NonNullable<PreparedSelector[\"uniqueKey\"]>,\n error: UniqueConstraintError\n ): boolean {\n const table = model[\"~\"].names.sql!;\n return error.message.includes(\n key.kind === \"primary\"\n ? `Database record \\`${table}:`\n : `index \\`${table}_${key.name ?? this.#q.columnName(model, key.fields[0]!)}_key\\``\n );\n }\n\n /** The key fields a write states. */\n #keyChange(model: AnyModel, given: Input): readonly string[] {\n return this.#q.keyOrder(model).filter((key) => Object.hasOwn(given, key));\n }\n\n /** The values a write states beside a key it has already moved. */\n #withoutKeys(model: AnyModel, given: Input): Input {\n const keys = this.#q.keyOrder(model);\n return Object.fromEntries(\n Object.entries(given).filter(([field]) => !keys.includes(field))\n );\n }\n\n /**\n * What stands in for a moved row's unique fields while both copies exist: its\n * unique indexes would read the old row as a duplicate of the new one. One field\n * out of the way frees a key over several, and a missing value is in no index.\n */\n #standIns(model: AnyModel): Map<string, Sql | undefined> {\n const keys = this.#q.keyOrder(model);\n const scalars = model[\"~\"].state.scalars;\n const standIns = new Map<string, Sql | undefined>();\n const standIn = (field: string) => {\n const state = scalars[field]?.[\"~\"].state;\n return !state || state.array || this.#low.holdsRecord(model, field)\n ? undefined\n : STAND_INS[state.type as string];\n };\n for (const fields of getModelKeyCatalog(model).referenceableKeys) {\n // The id holds a key naming it: no index does.\n if (fields.some((field) => keys.includes(field))) continue;\n const held = fields.find((field) => standIn(field));\n if (held) {\n standIns.set(held, standIn(held));\n continue;\n }\n const absent = fields.find(\n (field) => scalars[field]?.[\"~\"].state.nullable\n );\n if (!absent)\n refuse(\n `changing the key of '${model[\"~\"].names.ts}', whose unique ${fields.join(\", \")} has no value to stand in`\n );\n standIns.set(absent, undefined);\n }\n return standIns;\n }\n\n /** One row moved to the key a write gives it: one statement, a transaction of its own. */\n async #moveRecord(\n model: AnyModel,\n identity: Input,\n given: Input\n ): Promise<Input> {\n const next = { ...identity };\n for (const key of this.#keyChange(model, given))\n next[key] = await this.#movedKey(model, key, identity[key], given[key]);\n const statement = await this.#movement(model, identity, next, { count: 0 });\n await this.#heard(sql`RETURN { ${statement} RETURN []; }`, model);\n return next;\n }\n\n /** What a write leaves a key part at: what it states, reads, or computes from it. */\n async #movedKey(\n model: AnyModel,\n key: string,\n current: unknown,\n given: unknown\n ): Promise<unknown> {\n const whole = wholeValue(given);\n if (whole && !(whole.value instanceof Sql)) return whole.value;\n if (whole)\n return (\n await this.#heard(sql`RETURN [{ value: ${whole.value as Sql} }]`, model)\n )[0]?.value;\n const [operator, operand] = Object.entries(given as Input)[0]!;\n const { type } = model[\"~\"].state.scalars[key]![\"~\"].state;\n if (!ARITHMETIC[operator]) refuse(`the '${operator}' update`);\n return arithmetic(type as string, current, operator, operand);\n }\n\n /**\n * Who holds a non-key field of `model` in their own key, cascading: nothing in the\n * database can move a record, so an update of the field moves them here.\n */\n #keyFollowers(model: AnyModel, given: Input): readonly FollowingEdge[] {\n const q = this.#q;\n const keys = q.keyOrder(model);\n const found: FollowingEdge[] = [];\n for (const source of Object.values(this.operation.schema.schema))\n for (const slot of Object.keys(source[\"~\"].state.relations)) {\n const { edges } = q.countedMemberships(source, slot);\n for (const edge of edges)\n if (\n edge.kind === \"reference\" &&\n edge.target === model &&\n edge.owner === \"source\" &&\n !edge.discriminator &&\n edge.reference?.onUpdate === \"cascade\" &&\n edge.pairs.some(\n ({ source: part, target }) =>\n !keys.includes(target) &&\n Object.hasOwn(given, target) &&\n q.keyOrder(source).includes(part)\n )\n )\n found.push(edge);\n }\n return found;\n }\n\n /** The records holding, in their own keys, what a write changed of the rows that were `before`: each moved after it. */\n async #follow(\n model: AnyModel,\n followers: readonly FollowingEdge[],\n before: readonly Input[],\n stored: Sql\n ): Promise<void> {\n const low = this.#low;\n const q = this.#q;\n const keys = q.keyOrder(model);\n for (const was of before) {\n const [now] = await this.#heard(\n sql`SELECT ${stored} FROM ${low.recordOfRow(model, this.operation.schema.identity(model, was))}`,\n model\n );\n if (!now) continue;\n for (const edge of followers) {\n const { source } = edge;\n const held = await this.#heard(\n sql`SELECT ${this.#as(source, q.keyOrder(source))} FROM ${fieldName(source[\"~\"].names.sql!)} WHERE ${sql.join(\n edge.pairs.map(\n ({ source: part, target }) =>\n sql`${low.physical(source, part)} = ${low.value(source, part, was[target])}`\n ),\n \" AND \"\n )}`,\n model\n );\n for (const row of held)\n await this.#moveRecord(\n source,\n row,\n Object.fromEntries(\n edge.pairs\n .filter(\n ({ source: part, target }) =>\n !keys.includes(target) && q.keyOrder(source).includes(part)\n )\n .map(({ source: part, target }) => [part, now[target]])\n )\n );\n }\n }\n }\n\n /**\n * A record's id cannot change, so a new key is a new record: the row is copied\n * under it, what points at it does what its action says, and the old one goes.\n * A record holding the key in its own key moves with it, inside the same block.\n */\n async #movement(\n model: AnyModel,\n identity: Input,\n next: Input,\n moves: { count: number }\n ): Promise<Sql> {\n const q = this.#q;\n const low = this.#low;\n const { schema } = this.operation;\n const at = moves.count++;\n const named = (variable: string) => sql.raw(`$${variable}${at}`);\n const old = named(\"old\");\n const moved = named(\"new\");\n const held = named(\"row\");\n const other = named(\"other\");\n const others = named(\"others\");\n const keys = q.keyOrder(model);\n const standIns = this.#standIns(model);\n const copied = schema\n .storedFields(model)\n .filter(\n (field) =>\n !keys.includes(field) && (!standIns.has(field) || standIns.get(field))\n )\n .map((field) => {\n const column = fieldName(q.columnName(model, field));\n return sql`${column}: ${standIns.get(field) ?? sql`${held}.${column}`}`;\n });\n const restored = [...standIns.keys()].map((field) => {\n const column = fieldName(q.columnName(model, field));\n return sql`${column} = ${held}.${column}`;\n });\n const refusals: Sql[] = [];\n const follow: Sql[] = [];\n let quiet = false;\n for (const source of Object.values(schema.schema))\n for (const slot of Object.keys(source[\"~\"].state.relations)) {\n const { edges } = q.countedMemberships(source, slot);\n for (const edge of edges) {\n if (edge.target !== model) continue;\n if (edge.kind === \"junction\") {\n // A declared link is a row of its model, reached by its own references.\n if (edge.declared) continue;\n const { table, near, far } = low.edgeOf(edge);\n // Nothing in the database holds an edge's key back, so the engine does.\n const action = edge.targetSide.onUpdate ?? \"cascade\";\n if (action === \"restrict\" || action === \"noAction\") {\n refusals.push(\n sql`IF array::len(SELECT VALUE id FROM ${table} WHERE ${far} = ${old} LIMIT 1) > 0 { THROW ${`ON UPDATE REJECT: ${edge.name}`} };`\n );\n continue;\n }\n const linked = sql`(SELECT VALUE ${near} FROM ${table} WHERE ${far} = ${old})`;\n // An edge's ends are fixed: it is related again from the new record. A\n // singular one holds its index until it is gone.\n follow.push(\n edge.uniqueSide\n ? sql`LET ${others} = ${linked}; DELETE ${table} WHERE ${far} = ${old}; FOR ${other} IN ${others} { INSERT RELATION INTO ${table} [{ ${near}: ${other}, ${far}: ${moved} }] };`\n : near.toStatement() === \"in\"\n ? sql`FOR ${other} IN ${linked} { RELATE ${other}->${table}->${moved} };`\n : sql`FOR ${other} IN ${linked} { RELATE ${moved}->${table}->${other} };`\n );\n continue;\n }\n if (edge.owner !== \"source\" || edge.discriminator) continue;\n // An event answers for it: a move's old copy says so, and it stays quiet.\n if (\n edge.pairs.length > 1 ||\n !low.holdsRecord(source, edge.pairs[0]!.source)\n )\n quiet = true;\n // Not by the key: the value stays with the row, and so do those holding it.\n if (!edge.pairs.some(({ target }) => keys.includes(target))) continue;\n const stored = edge.pairs.every(({ target }) => keys.includes(target))\n ? identity\n : {\n ...(\n await this.#heard(\n sql`SELECT ${this.#as(model, schema.storedFields(model))} FROM ${low.recordOfRow(model, identity)}`,\n model\n )\n )[0],\n ...identity,\n };\n const holders = edge.pairs.map(({ source: part, target }) => ({\n part,\n column: low.physical(source, part),\n now: keys.includes(target) ? next[target] : stored[target],\n value: low.value(\n source,\n part,\n keys.includes(target) ? next[target] : stored[target]\n ),\n was: low.value(source, part, stored[target]),\n }));\n const table = fieldName(source[\"~\"].names.sql!);\n const holding = sql.join(\n holders.map(({ column, was }) => sql`${column} = ${was}`),\n \" AND \"\n );\n // As SQL's foreign keys: left unsaid, a key that is held refuses to change.\n const action = edge.reference?.onUpdate ?? \"noAction\";\n if (action === \"restrict\" || action === \"noAction\") {\n refusals.push(\n sql`IF array::len(SELECT VALUE id FROM ${table} WHERE ${holding} LIMIT 1) > 0 { THROW ${`ON UPDATE REJECT: ${edge.name}`} };`\n );\n continue;\n }\n if (\n holders.some(({ column }) => column.toStatement().startsWith(\"id\"))\n ) {\n if (action === \"setNull\")\n refuse(\"setNull on a key that holds another\");\n for (const row of await this.#heard(\n sql`SELECT ${this.#as(source, q.keyOrder(source))} FROM ${table} WHERE ${holding}`,\n model\n ))\n follow.push(\n await this.#movement(\n source,\n row,\n {\n ...row,\n ...Object.fromEntries(\n holders.map(({ part, now }) => [part, now])\n ),\n },\n moves\n )\n );\n continue;\n }\n follow.push(\n sql`UPDATE ${table} SET ${sql.join(\n holders.map(({ column, value }) =>\n action === \"setNull\"\n ? sql`${column} = NONE`\n : sql`${column} = ${value}`\n ),\n \", \"\n )} WHERE ${holding};`\n );\n }\n }\n return sql`LET ${old} = ${low.recordOfRow(model, identity)}; LET ${moved} = ${low.recordOfRow(model, next)}; IF ${moved} = ${old} { RETURN []; }; ${sql.join(refusals, \" \")} LET ${held} = (SELECT * FROM ONLY ${old}); IF ${held} = NONE { RETURN []; }; ${quiet ? sql`UPDATE ${old} SET viborm_moved = true;` : NOTHING} INSERT INTO ${fieldName(model[\"~\"].names.sql!)} [{ ${sql.join([sql`id: ${moved}`, ...copied], \", \")} }] RETURN NONE; ${sql.join(follow, \" \")} DELETE ${old}; ${restored.length ? sql`UPDATE ${moved} SET ${sql.join(restored, \", \")};` : NOTHING}`;\n }\n}\n","/**\n * `viborm/surrealdb`: a driver whose database reads SurrealQL. {@link SurrealQueries}\n * and {@link SurrealWriter} write its statements, and it declares only what\n * the engine asks of any driver. `docs/architecture/query-backend-frontier.md`.\n */\n\nimport { passThroughParseResult } from \"@adapters/adapter-result-parser\";\nimport type { EngineFacts } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n ForeignKeyError,\n NestedWriteAssertionError,\n QueryError,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport { queryBackend } from \"@query-engine/raptor3/shared/query-backend\";\nimport type { Sql } from \"@sql\";\nimport {\n DateTime,\n Decimal,\n GeometryPoint,\n RecordId,\n SizedNumber,\n Surreal,\n Uuid,\n} from \"surrealdb\";\nimport {\n type CommitRerunningDriver,\n Driver,\n TransactionBoundDriver,\n} from \"../driver\";\nimport { getExecutionExtensionChain } from \"../execution-context\";\nimport type {\n DriverTransactionOptions,\n TransactionOptionSupport,\n TransactionOptions,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { createTransactionCleanupError } from \"../shared/transactions\";\nimport type { BatchQuery, QueryExecutionContext, QueryResult } from \"../types\";\nimport { SurrealQueries } from \"./queries\";\nimport {\n backOff,\n COMMITS,\n FORBIDDEN_ROW,\n isConflict,\n ReplayedTransaction,\n STOPPED,\n} from \"./transaction\";\nimport { SurrealCall, SurrealWriter } from \"./writer\";\n\n/** In a text of several statements, where one's answers end: a statement may hold several of its own ahead of itself. */\nconst MARKED = \"viborm:|\";\nconst NAMED_PARAMETER = /\\$p(\\d+)\\b/g;\n\n/**\n * A statement that holds what it reads ahead of itself, where no transaction\n * holds it: this driver makes it one transaction of its own.\n */\nconst standsAlone = (client: unknown, statement: string): boolean =>\n !(client instanceof ReplayedTransaction) && statement.startsWith(\"LET \");\n\n/** What the engine asks of any driver. */\nconst FACTS: EngineFacts = {\n namespace: undefined,\n // A point's statements are this driver's own: the fact is that it holds them.\n geoPoint: {},\n // A strategy `Commands` asks about, not syntax: `INSERT IGNORE` skips.\n mutations: { skipDuplicatesStrategy: \"sql\" },\n // A widened sum asks whether it travels in parts here, and it never does.\n aggregates: {},\n result: {\n nativeScalarPassthrough: true,\n parseResult: passThroughParseResult,\n parseRelation: (_value, next) => next(),\n parseField: (_value, _type, next) => next(),\n },\n capabilities: {\n supportsReturning: true,\n supportsCteWithMutations: false,\n supportsFullOuterJoin: false,\n supportsLateralJoins: false,\n supportsVector: true,\n supportsUpsertWhere: false,\n supportsTargetedUpsert: true,\n supportsMutationTargetInSubquery: false,\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n },\n};\n\n/** A provider value as the engine's decoders read it. */\nfunction plain(value: unknown): unknown {\n if (value === undefined) return null;\n if (value instanceof RecordId) return plain(value.id);\n if (value instanceof GeometryPoint) return value.toJSON();\n if (value instanceof DateTime) return value.toISOString();\n if (value instanceof Decimal || value instanceof Uuid)\n return value.toString();\n if (value instanceof SizedNumber) return value.value;\n if (Array.isArray(value)) return value.map(plain);\n if (ArrayBuffer.isView(value)) return value;\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n if (value !== null && typeof value === \"object\" && !(value instanceof Date)) {\n const members = Object.entries(value).map(([key, member]) => [\n key,\n plain(member),\n ]);\n // The SDK decodes a map by assignment, so a stored `__proto__` key becomes the\n // object's prototype, which every read of the row would then inherit from.\n const inherited = Object.getPrototypeOf(value);\n if (\n inherited === null ||\n (inherited !== Object.prototype &&\n Object.getPrototypeOf(inherited) === Object.prototype &&\n !Object.hasOwn(inherited, \"constructor\"))\n )\n members.unshift([\"__proto__\", plain(inherited)]);\n return Object.fromEntries(members);\n }\n return value;\n}\n\nconst UNIQUE_REFUSAL = /already contains|already exists/;\nconst REFERENCE_REFUSAL =\n /must conform to.*exists\\(\\)|ON (?:DELETE|UPDATE) REJECT/s;\nconst OUT_OF_RANGE =\n /Expected `(?:none \\| )?i32` but found|must conform to.*math::abs|Cannot perform (?:addition|subtraction|multiplication) with/s;\nconst TOO_DEEP = /Exceeded (?:query|expression) recursion depth limit/;\n\n/**\n * A provider failure in viborm's own words. Refusals carry no code here, so their\n * sentences are the only evidence.\n */\nfunction refusal(error: unknown): unknown {\n const message = error instanceof Error ? error.message : String(error);\n const cause = error instanceof Error ? error : undefined;\n if (isConflict(error)) return new TransactionError(message, { cause });\n // The statement stopped itself: its call says what it refuses with.\n if (message.includes(FORBIDDEN_ROW) || message.includes(STOPPED))\n return new NestedWriteAssertionError(message, { cause });\n if (UNIQUE_REFUSAL.test(message))\n return new UniqueConstraintError(`Unique constraint failed: ${message}`, {\n cause,\n });\n if (REFERENCE_REFUSAL.test(message))\n return new ForeignKeyError(message, { cause });\n if (OUT_OF_RANGE.test(message))\n return new QueryError(message, {\n cause,\n code: VibORMErrorCode.QUERY_OUT_OF_RANGE,\n });\n if (TOO_DEEP.test(message))\n return new UnsupportedOperationError(\n \"This statement nests deeper than the SurrealDB server parses: raise its SURREAL_MAX_QUERY_PARSING_DEPTH, or read in two steps.\",\n { cause }\n );\n return error;\n}\n\n/** SurrealQL names its parameters: `$p1`, as {@link SurrealDriver.execute} binds them. */\nfunction namedStatement(query: Sql): string {\n return query.strings.reduce(\n (text, next, index) => `${text}$p${index}${next}`\n );\n}\n\nclass SurrealTransactionDriver extends TransactionBoundDriver<\n Surreal,\n ReplayedTransaction\n> {\n readonly replayed: ReplayedTransaction;\n\n constructor(\n base: Driver<Surreal, ReplayedTransaction>,\n tx: ReplayedTransaction,\n context?: QueryExecutionContext\n ) {\n super(base, tx, context);\n this.replayed = tx;\n }\n\n protected override buildStatement(query: Sql): string {\n return namedStatement(query);\n }\n\n protected override createTransactionBoundDriver(\n tx: ReplayedTransaction,\n context: QueryExecutionContext\n ): SurrealTransactionDriver {\n return new SurrealTransactionDriver(this, tx, context);\n }\n\n /** A nested scope is a savepoint, which the transaction keeps for itself. */\n protected override async transaction<T>(\n client: Surreal | ReplayedTransaction,\n fn: (tx: ReplayedTransaction) => Promise<T>\n ): Promise<T> {\n const tx = client as ReplayedTransaction;\n const mark = tx.mark;\n try {\n return await fn(tx);\n } catch (error) {\n await tx.rollbackTo(mark).catch((cleanup: unknown) => {\n throw createTransactionCleanupError(error, [cleanup]);\n });\n throw error;\n }\n }\n}\n\nconst CALLBACK = \"$transaction(callback)\";\n\nexport interface SurrealDriverOptions {\n /** A client you connected, which stays yours: the driver never closes it. */\n readonly client?: Surreal;\n /** Where to connect, when the driver opens its own client. */\n readonly url?: string;\n readonly namespace?: string;\n readonly database?: string;\n readonly authentication?: {\n readonly username: string;\n readonly password: string;\n };\n /**\n * How many more times a `$transaction` callback may run when a concurrent write\n * changed what it read, instead of failing with `V5001`. PostgreSQL would make it\n * wait, and running it again is the only way to give it the new value. Everything\n * the callback does outside the database happens again too, such as sending an\n * email, so this is off unless asked for.\n */\n readonly rerunsOnConflict?: number;\n}\n\nexport class SurrealDriver\n extends Driver<Surreal, ReplayedTransaction>\n implements CommitRerunningDriver\n{\n readonly adapter = FACTS;\n override readonly backend = queryBackend({\n queries: SurrealQueries,\n context: SurrealCall,\n writer: SurrealWriter,\n });\n readonly supportsTransactions = true;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = false;\n\n readonly #rerunsOnConflict: number;\n readonly #options: SurrealDriverOptions;\n\n constructor(options: SurrealDriverOptions = {}) {\n super(\"surrealql\", \"surrealdb\");\n if (options.client) this.client = options.client;\n this.#options = options;\n this.#rerunsOnConflict = options.rerunsOnConflict ?? 0;\n }\n\n /**\n * A caller's callback runs again only when asked. A conflict its statements can\n * replay never reaches here, and an extension that hears writes has already\n * been told what the failed run wrote, so its callback does not run twice.\n */\n override async withTransaction<T>(\n fn: (txDriver: Driver<Surreal, ReplayedTransaction>) => Promise<T>,\n options?: TransactionOptions,\n context?: QueryExecutionContext\n ): Promise<T> {\n let reruns =\n context?.operation === CALLBACK &&\n !getExecutionExtensionChain(context)?.collect\n ? this.#rerunsOnConflict\n : 0;\n for (let run = 1; ; run++) {\n let replayed: ReplayedTransaction | undefined;\n try {\n return await super.withTransaction(\n (driver) => {\n ({ replayed } = driver as SurrealTransactionDriver);\n return fn(driver);\n },\n options,\n context\n );\n } catch (error) {\n // A refusal after the conflict hides it, so the transaction is who says.\n if (reruns-- === 0 || !replayed?.conflicted) throw error;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, Math.random() * 20 * run)\n );\n }\n }\n\n protected override buildStatement(query: Sql): string {\n return namedStatement(query);\n }\n\n protected override createTransactionBoundDriver(\n tx: ReplayedTransaction,\n context: QueryExecutionContext\n ): SurrealTransactionDriver {\n return new SurrealTransactionDriver(this, tx, context);\n }\n\n protected async initClient(): Promise<Surreal> {\n const { url, namespace, database, authentication } = this.#options;\n if (!url)\n throw new ClientInitializationError(\n 'Driver \"surrealdb\" needs a connected client or a url.',\n { meta: { driver: \"surrealdb\", operation: \"configuration\" } }\n );\n const client = new Surreal();\n await client.connect(url, {\n ...(namespace ? { namespace } : {}),\n ...(database ? { database } : {}),\n ...(authentication ? { authentication: { ...authentication } } : {}),\n });\n return client;\n }\n\n protected async closeClient(): Promise<void> {\n // A client handed in is the caller's.\n if (this.#options.client) return;\n await (this.client as Surreal | null)?.close();\n }\n\n protected async execute<T>(\n client: Surreal | ReplayedTransaction,\n statement: string,\n params: unknown[]\n ): Promise<QueryResult<T>> {\n const values = Object.fromEntries(\n params.map((value, index) => [`p${index + 1}`, value])\n );\n try {\n // What a statement holds ahead of itself is read with it, as one transaction.\n const stated = standsAlone(client, statement)\n ? `BEGIN; ${statement}; COMMIT;`\n : statement;\n // The SDK's client answers the same call.\n const answers = await (client as ReplayedTransaction).query<unknown[]>(\n stated,\n values\n );\n // What a statement holds ahead of itself answers first, and `COMMIT` last.\n const result = answers.at(stated.endsWith(\"; COMMIT;\") ? -2 : -1);\n const rows = Array.isArray(result) ? result : [];\n return { rows: plain(rows) as T[], rowCount: rows.length };\n } catch (error) {\n throw refusal(error);\n }\n }\n\n /**\n * Statements that go together, as one text: a transaction of its own\n * outside any, and part of the one that holds it inside. A text that fails\n * says the failure of its first statement, whichever failed.\n */\n protected override async executeBatch<T>(\n client: Surreal | ReplayedTransaction,\n queries: BatchQuery[]\n ): Promise<QueryResult<T>[]> {\n const values: Record<string, unknown> = {};\n let bound = 0;\n const texts = queries.map(({ sql, params = [] }) => {\n const from = bound;\n for (const value of params) values[`p${++bound}`] = value;\n return `${sql.replace(NAMED_PARAMETER, (_, at) => `$p${from + Number(at)}`)}; RETURN \"${MARKED}\";`;\n });\n const whole = !(client instanceof ReplayedTransaction);\n try {\n const answers = await (client as ReplayedTransaction).query<unknown[]>(\n whole ? `BEGIN; ${texts.join(\" \")} COMMIT;` : texts.join(\" \"),\n values\n );\n const results: QueryResult<T>[] = [];\n let last: unknown;\n for (const answer of answers) {\n if (answer === MARKED) {\n const rows = Array.isArray(last) ? last : [];\n results.push({ rows: plain(rows) as T[], rowCount: rows.length });\n }\n last = answer;\n }\n return results;\n } catch (error) {\n throw refusal(error);\n }\n }\n\n protected executeRaw<T>(\n client: Surreal | ReplayedTransaction,\n statement: string,\n params: unknown[] | undefined,\n _context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.execute<T>(client, statement, params ?? []);\n }\n\n /**\n * A migration statement led by `LET` is one transaction this driver opens for\n * it ({@link standsAlone}). Refused at its commit because another writer met\n * it there, it wrote nothing and answered no one: it runs again, as it would\n * have a moment later. A migration's rewrite of a table's rows is one, and\n * meets the server's own background writes to that table. That transaction\n * is the whole statement because a migration holds no `BEGIN`, `COMMIT` or\n * `CANCEL` (`statement-safety.ts`). A caller's raw statement can, and part of\n * it may have committed before the refusal, so it is never run again: it\n * fails with the conflict.\n *\n * One rerun is not enough: in #171's reproduction the background writes met\n * the rewrite in 40 of 150 first attempts, and nothing keeps them from\n * meeting a second one. The bound is the one a replayed transaction's commit\n * uses ({@link COMMITS}). This driver itself, never one bound to a\n * transaction, implements this, so a conflict inside a transaction stays\n * that transaction's.\n *\n * Statements a migration commits together, sent as one batch, are one\n * transaction too: this driver wraps a batch outside a transaction in\n * `BEGIN` and `COMMIT` ({@link executeBatch}), so a refusal leaves nothing\n * of it applied, and it runs again the same way.\n */\n async rerunRefusedCommit(\n statement: string | readonly BatchQuery[],\n send: () => Promise<unknown>\n ): Promise<unknown> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await send();\n } catch (error) {\n if (\n attempt === COMMITS ||\n !isConflict(error) ||\n (typeof statement === \"string\" &&\n !standsAlone(this.client, statement))\n )\n throw error;\n }\n await backOff(attempt);\n }\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"snapshot-only\",\n isolationLevelReason:\n \"a SurrealDB transaction reads a snapshot, where two may each read what the other writes\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Surreal | ReplayedTransaction,\n fn: (tx: ReplayedTransaction) => Promise<T>,\n _context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n const transaction = await ReplayedTransaction.begin(\n client as Surreal,\n options?.maxWaitMs\n );\n let result: T;\n try {\n result = await fn(transaction);\n } catch (error) {\n await transaction.cancel().catch(() => undefined);\n throw error;\n }\n try {\n await transaction.commit();\n } catch (error) {\n throw refusal(error);\n }\n return result;\n }\n}\n\nexport type SurrealClientConfig<C extends DriverConfig> = SurrealDriverOptions &\n C;\n\nconst SURREAL_CONFIG_KEYS: Record<keyof SurrealDriverOptions, true> = {\n client: true,\n url: true,\n namespace: true,\n database: true,\n authentication: true,\n rerunsOnConflict: true,\n};\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: SurrealClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, SurrealDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: SurrealDriver }\n >]: LinkedClientConfig<C & { driver: SurrealDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"surrealdb\", SURREAL_CONFIG_KEYS);\n const { client, url, namespace, database, authentication, rerunsOnConflict } =\n config;\n return createClientFromDriverConfig<S, C, SurrealDriver>(\n config,\n new SurrealDriver({\n client,\n url,\n namespace,\n database,\n authentication,\n rerunsOnConflict,\n })\n );\n}\n"],"mappings":"m2BAgDA,MAAM,GAAa,2BAEb,GAAQ,cACR,GAAW,UAUjB,SAASA,SAAO,EAAqB,CACnC,MAAM,IAAI,EACR,+CAA+C,EAAK,OACrD,sBAGH,SAAS,KAAK,EAAyB,CAGrC,OAFI,GAAW,KAAK,EAAW,CAASC,EAAI,IAAI,EAAW,CACvD,GAAS,KAAK,EAAW,CAASA,EAAI,IAAI,KAAK,EAAW,IAAI,CAC3DD,SAAO,aAAa,EAAW,GAAG,CAG3C,SAAS,QAAQ,EAAyB,CACxC,OAAO,EAAM,KAAK,MAAM,IAG1B,SAAS,YAAY,EAAkB,EAAiB,EAAe,CACrE,IAAM,EAAO,EAAQ,SAAS,EAAM,CACpC,OAAO,EAAK,SAAW,GAAK,EAAK,KAAO,EAG1C,SAAS,UAAU,EAA6B,CAE9C,OADI,EAAK,OAAS,aAAa,SAAO,kBAAkB,CACjD,EAGT,MAAM,EAAe,CACnB,KAAM,SACN,KAAM,UACN,SAAU,GACX,CACK,EAAa,CAAE,KAAM,SAAU,KAAM,MAAO,SAAU,GAAO,CAC7D,EAAqC,CACzC,SACA,OACA,OACA,OACA,OACD,CACK,GAAwD,CAC5D,KAAM,aACN,KAAM,YACN,KAAM,aACN,KAAM,aACP,CAaK,EAAiB,aAIjB,GAAoB,gCACpB,EAAgD,CACpD,OAAQ,IACR,GAAI,IACJ,IAAK,KACL,GAAI,IACJ,IAAK,KACN,CAEK,EAA8C,CAClD,SAAU,mBACV,WAAY,sBACZ,SAAU,oBACX,CASD,SA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AAM,EAAK,CAAS,SAAU,EAAK,OAAQ,CAAC,CAEnE,EAAO,EAET,OAAO,QACA,EAAO,CACd,MAAM,QAAQ,EAAM,EAIxB,WACE,EACA,EACA,EACA,EACyB,CACzB,OAAO,KAAK,QAAW,EAAQ,EAAW,GAAU,EAAE,CAAC,CA0BzD,MAAM,mBACJ,EACA,EACkB,CAClB,IAAK,IAAI,EAAU,GAAK,IAAW,CACjC,GAAI,CACF,OAAO,MAAM,GAAM,OACZ,EAAO,CACd,GACE,IAAY,IACZ,CAAC,WAAW,EAAM,EACjB,OAAO,GAAc,UACpB,CAAC,YAAY,KAAK,OAAQ,EAAU,CAEtC,MAAM,EAEV,MAAM,QAAQ,EAAQ,EAI1B,0BAAwE,CACtE,MAAO,CACL,eAAgB,gBAChB,qBACE,0FACF,QAAS,GACT,QAAS,cACV,CAGH,MAAgB,YACd,EACA,EACA,EACA,EACY,CACZ,IAAM,EAAc,MAAM,EAAoB,MAC5C,EACA,GAAS,UACV,CACG,EACJ,GAAI,CACF,EAAS,MAAM,EAAG,EAAY,OACvB,EAAO,CAEd,MADA,MAAM,EAAY,QAAQ,CAAC,UAAY,IAAA,GAAU,CAC3C,EAER,GAAI,CACF,MAAM,EAAY,QAAQ,OACnB,EAAO,CACd,MAAM,QAAQ,EAAM,CAEtB,OAAO,IAOX,MAAM,GAAgE,CACpE,OAAQ,GACR,IAAK,GACL,UAAW,GACX,SAAU,GACV,eAAgB,GAChB,iBAAkB,GACnB,CAED,SAAgB,aACd,EAOC,CACD,GAA8B,EAAQ,YAAa,GAAoB,CACvE,GAAM,CAAE,SAAQ,MAAK,YAAW,WAAU,iBAAgB,oBACxD,EACF,OAAO,EACL,EACA,IAAI,cAAc,CAChB,SACA,MACA,YACA,WACA,iBACA,mBACD,CAAC,CACH"}
1
+ {"version":3,"file":"surrealdb.mjs","names":[],"sources":["../src/drivers/surrealdb/facts.ts","../src/drivers/surrealdb/read-backend.ts","../src/drivers/surrealdb/queries.ts","../src/drivers/surrealdb/transaction.ts","../src/drivers/surrealdb/writer.ts","../src/drivers/surrealdb/index.ts"],"sourcesContent":["/**\n * What the engine asks of the SurrealDB driver, in a module of its own: the\n * migrations write a view's body with the engine view a client of this driver\n * reads it with, and import this without the driver.\n */\n\nimport { passThroughParseResult } from \"@adapters/adapter-result-parser\";\nimport type { EngineFacts } from \"@adapters/database-adapter\";\n\n/** What the engine asks of any driver. */\nexport const SURREAL_FACTS: EngineFacts = {\n namespace: undefined,\n // A point's statements are this driver's own: the fact is that it holds them.\n geoPoint: {},\n // A strategy `Commands` asks about, not syntax: `INSERT IGNORE` skips.\n mutations: { skipDuplicatesStrategy: \"sql\" },\n // A widened sum asks whether it travels in parts here, and it never does.\n aggregates: {},\n result: {\n nativeScalarPassthrough: true,\n parseResult: passThroughParseResult,\n parseRelation: (_value, next) => next(),\n parseField: (_value, _type, next) => next(),\n },\n capabilities: {\n supportsReturning: true,\n supportsCteWithMutations: false,\n supportsFullOuterJoin: false,\n supportsLateralJoins: false,\n supportsVector: true,\n supportsUpsertWhere: false,\n supportsTargetedUpsert: true,\n supportsMutationTargetInSubquery: false,\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n },\n};\n","/**\n * `docs/architecture/query-backend-frontier.md` step 4.\n *\n * Writes idiomatic SurrealQL from the engine's `Prepared*` descriptions, from\n * the relation and not from a translation of the SQL: a to-many is a reference\n * traversal holding its own query, `<~(SELECT * FROM post FIELD author …)`, a\n * to-one follows its link, and a junction is an edge table walked as a graph,\n * `->tagged->(SELECT * FROM tag …)`. No alias exists: each lowering knows the row\n * it writes for. What it does not cover refuses by name rather than read wrongly.\n */\n\nimport { UnsupportedOperationError } from \"@errors\";\nimport type {\n FieldGate,\n PreparedPredicate,\n PreparedProjection,\n PreparedProjectionField,\n Queries,\n Query,\n Read,\n ReadBackend,\n} from \"@query-engine/raptor3/shared/query\";\nimport {\n approximateOrder,\n firstRow,\n rowSet,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n Arguments,\n Input,\n ReadOperation,\n} from \"@query-engine/raptor3/shared/schema\";\nimport type { Membership } from \"@query-engine/raptor3/shared/storage\";\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport { viewFacts, viewTable } from \"@schema/view/facts\";\nimport { Sql, sql } from \"@sql\";\nimport { timeStepUnsupported } from \"@validation/model/args/time-step\";\nimport { Decimal, GeometryPoint, RecordId } from \"surrealdb\";\nimport { quantized } from \"./quantized\";\nimport type { SurrealQueries } from \"./queries\";\n\ntype AnyModel = PreparedProjection[\"model\"];\ntype Relation = Extract<PreparedProjectionField, { kind: \"relation\" }>;\ntype Reference = Extract<Membership, { kind: \"reference\" }>;\ntype Junction = Extract<Membership, { kind: \"junction\" }>;\ntype Member = Junction[\"sourceSide\"][\"members\"][number];\ntype VariantJunctionMember = Extract<\n Membership[\"scope\"][\"edge\"],\n { kind: \"variantJunctionCarrier\" }\n>[\"members\"][number];\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n/** What a path reads as an array index, as PostgreSQL's `#>` does: `01` and `-1` too. */\nconst INDEX = /^-?\\d{1,9}$/;\nconst QUOTABLE = /^[^`]+$/;\n/**\n * How many rows a filter's body reads ahead of a page before it stops: past this,\n * walking the page's own rows finds what it needs sooner than listing every holder.\n */\nconst HOLDERS_AHEAD = 1000;\n/** How deep an exhaustive walk goes: as deep as a SurrealDB recursion may. */\nconst MAX_WALK = 256;\nconst ARMS = 16;\n\nfunction refuse(what: string): never {\n throw new UnsupportedOperationError(\n `The SurrealDB read backend does not support ${what} yet.`\n );\n}\n\nfunction name(identifier: string): Sql {\n if (IDENTIFIER.test(identifier)) return sql.raw(identifier);\n if (QUOTABLE.test(identifier)) return sql.raw(`\\`${identifier}\\``);\n return refuse(`the name '${identifier}'`);\n}\n\nfunction tableOf(model: AnyModel): string {\n return model[\"~\"].names.sql!;\n}\n\n/**\n * A table's name as a string literal, not a bound value: an order term reads a\n * relation through a path written as text, which keeps no bound value.\n */\nfunction tableText(table: string): Sql {\n return sql.raw(JSON.stringify(table));\n}\n\n/**\n * Whether a model's records are groups: an aggregated view's, or those of a\n * view of rows over one, which keeps its source's ids.\n */\nfunction isGroup(model: AnyModel): boolean {\n const facts = viewFacts(model);\n return (\n facts !== undefined &&\n (facts.aggregated !== undefined || isGroup(facts.source))\n );\n}\n\n/**\n * Whether a record's id is its key's one value (`t:1`), not the list of its\n * parts (`t:[1, 'a']`). The database ids a group by the list of the values it\n * groups by, even of one (`v:['EUR']`, measured on SurrealDB 4.0).\n */\nfunction idIsValue(keys: readonly string[], model: AnyModel): boolean {\n return keys.length === 1 && !isGroup(model);\n}\n\nfunction isSingleKey(queries: Queries, model: AnyModel, field: string) {\n const keys = queries.keyOrder(model);\n return idIsValue(keys, model) && keys[0] === field;\n}\n\nfunction reference(edge: Membership): Reference {\n if (edge.kind !== \"reference\") refuse(\"a junction here\");\n return edge;\n}\n\nconst BOOLEAN_LEAF = {\n kind: \"scalar\",\n type: \"boolean\",\n nullable: false,\n} as const;\nconst COUNT_LEAF = { kind: \"scalar\", type: \"int\", nullable: false } as const;\nconst AGGREGATE_NAMES: readonly string[] = [\n \"_count\",\n \"_avg\",\n \"_sum\",\n \"_min\",\n \"_max\",\n];\nconst AGGREGATE_FUNCTIONS: Readonly<Record<string, string>> = {\n _avg: \"math::mean\",\n _sum: \"math::sum\",\n _min: \"array::min\",\n _max: \"array::max\",\n};\n\ntype OrderTerm = {\n readonly expression: Sql;\n /** A plain column: `ORDER BY` can read it without selecting it. */\n readonly named: boolean;\n /** The model's own field it orders by, when it is one. */\n readonly field?: string;\n readonly descending: boolean;\n readonly nullable: boolean;\n readonly nulls?: \"first\" | \"last\";\n};\n\nconst HOLDS_SUBQUERY = /\\bSELECT\\b/;\n/** Past this many, seeking one group after another costs more than reading them all. */\nconst GROUPS_SOUGHT = 20;\nconst PARENTS_READ_APART = 20;\nconst READS_A_ROW_ABOVE = /\\$(?:parent|this|owner|row)\\b/;\nconst COMPARISONS: Readonly<Record<string, string>> = {\n equals: \"=\",\n gt: \">\",\n gte: \">=\",\n lt: \"<\",\n lte: \"<=\",\n};\n\nconst FUNCTIONS: Readonly<Record<string, string>> = {\n contains: \"string::contains\",\n startsWith: \"string::starts_with\",\n endsWith: \"string::ends_with\",\n};\n\ntype ScalarFacts = {\n readonly type?: string;\n readonly array?: boolean;\n};\n\ntype GeoPointValue = { readonly latitude: number; readonly longitude: number };\n\nfunction geometry(point: GeoPointValue): GeometryPoint {\n return new GeometryPoint([point.longitude, point.latitude]);\n}\n\n/** A value as the database stores it: admission hands dates and decimals over as text. */\nfunction stored(state: ScalarFacts | undefined, value: unknown): unknown {\n if (value === null || value === undefined) return value;\n if (state?.array === true && Array.isArray(value))\n return value.map((member) => stored({ ...state, array: false }, member));\n switch (state?.type) {\n case \"datetime\":\n return new Date(value as string);\n case \"decimal\":\n return new Decimal(String(value));\n case \"point\":\n return geometry(value as GeoPointValue);\n default:\n return value;\n }\n}\n\nfunction isIntegerKey(model: AnyModel, field: string): boolean {\n const type = model[\"~\"].state.scalars[field]?.[\"~\"].state.type;\n return type === \"int\" || type === \"bigint\";\n}\n\n/**\n * A key read back from another column: an integer key's record names an\n * `int`, which a lookup by record tells from a narrower integer and from\n * text. An unset value stays unset and names no record, where `<int>` would\n * fail the statement (measured on SurrealDB 4.0).\n */\nfunction keyCast(model: AnyModel, field: string, value: Sql): Sql {\n return isIntegerKey(model, field) ? sql`<option<int>>${value}` : value;\n}\n\n/**\n * The type a record's key is cast to once read out of the record: a decimal\n * or an instant, which the record holds as its text (`keyPart`) and every\n * other column as the value. Any other key is read as it is held.\n */\nfunction textKeyType(model: AnyModel, field: string): string | undefined {\n const type = model[\"~\"].state.scalars[field]?.[\"~\"].state.type;\n return type === \"decimal\" || type === \"datetime\" ? type : undefined;\n}\n\n/**\n * A value as the key of the record that names it: an instant as the text\n * `keyPart` writes (its ISO form to the millisecond), unset where the value\n * is, and any other as a lookup by record reads it (`keyCast`; a decimal\n * names its record by the text it prints as, measured).\n */\nfunction recordKey(model: AnyModel, field: string, value: Sql): Sql {\n return textKeyType(model, field) === \"datetime\"\n ? sql`(IF ${value} { time::format(${value}, \"%Y-%m-%dT%H:%M:%S%.3fZ\") })`\n : keyCast(model, field, value);\n}\n\n/** One step of a JSON path: a key, bound, or both of what a number can name. */\nfunction jsonStep(at: Sql, step: string): Sql {\n return INDEX.test(step)\n ? sql`(IF type::is_array(${at}) { array::at(${at}, ${sql.raw(String(Number(step)))}) } ELSE { ${at}[${step}] })`\n : sql`${at}[${step}]`;\n}\n\nconst sameValue = (_key: string, value: unknown) =>\n typeof value === \"bigint\" ? `${value}n` : value;\n\n/** Whether this is a value bound as it stands, with nothing stated around it. */\nexport function isOneValue(member: Sql): boolean {\n return (\n member.values.length === 1 && member.strings.every((text) => text === \"\")\n );\n}\n\n/**\n * A list as one parameter where each member is one value: a statement holds about\n * 65,000 values at most (\"IR table full\"), and a parser reads each it is given.\n */\nexport function boundList(members: readonly Sql[]): Sql {\n return members.every(isOneValue)\n ? sql`${members.map((member) => member.values[0])}`\n : sql`[${sql.join([...members], \", \")}]`;\n}\n\n/** A record's key cannot be an instant or a decimal, so a key that is one is its text. */\nfunction keyPart(model: AnyModel, field: string, value: unknown): unknown {\n const type = model[\"~\"].state.scalars[field]?.[\"~\"].state.type;\n if (type === \"datetime\") return new Date(value as string).toISOString();\n if (type === \"decimal\") return new Decimal(String(value)).toString();\n return value;\n}\n\n/** Whether a predicate is only rows being among lists, which nothing unset is. */\nfunction onlyLists(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"and\":\n return predicate.predicates.some(onlyLists);\n case \"or\":\n return predicate.predicates.every(onlyLists);\n case \"layer\":\n return onlyLists(predicate.predicate);\n case \"relation\":\n return (\n !predicate.closure &&\n (predicate.quantifier === \"some\" || predicate.quantifier === \"is\") &&\n predicate.predicate !== undefined\n );\n default:\n return false;\n }\n}\n\n/** Whether a predicate reads a row a filter stepped away from, at any depth. */\nfunction readsAbove(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.some(readsAbove);\n case \"not\":\n case \"layer\":\n return readsAbove(predicate.predicate);\n case \"relation\":\n return (\n (predicate.predicate !== undefined &&\n readsAbove(predicate.predicate)) ||\n (predicate.link !== undefined && readsAbove(predicate.link))\n );\n case \"operation\":\n return [predicate.operand, ...(predicate.operands ?? [])].some(\n (operand) => operand?.kind === \"field\" && Boolean(operand.up)\n );\n default:\n return false;\n }\n}\n\n/**\n * Each condition once. It asks nothing more, and the server fails a statement stating\n * one equality twice with the same value (\"Internal database error: stale IR id\").\n */\nexport function onceEach(conditions: readonly Sql[]): Sql[] {\n const seen = new Set<string>();\n return conditions.filter((condition) => {\n const key = `${condition.toStatement()} ${JSON.stringify(condition.values, sameValue)}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** Arms joined in parentheses of at most `ARMS` each: a parser counts each `OR` as a level. */\nfunction joined(arms: readonly Sql[], word: string): Sql {\n if (arms.length <= ARMS) return sql.join([...arms], word);\n const groups: Sql[] = [];\n for (let at = 0; at < arms.length; at += ARMS)\n groups.push(sql`(${sql.join(arms.slice(at, at + ARMS), word)})`);\n return joined(groups, word);\n}\n\n/** Whether a predicate reads other rows, through a relation or a whole table. */\nexport function walksFurther(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.some(walksFurther);\n case \"not\":\n return walksFurther(predicate.predicate);\n case \"layer\":\n return walksFurther(predicate.predicate);\n case \"relation\":\n case \"exists\":\n return true;\n default:\n return false;\n }\n}\n\n/** What a statement's text says outside its comments and string literals. */\nconst NOT_STATED =\n /\\/\\*[\\s\\S]*?\\*\\/|--[^\\n]*|\\/\\/[^\\n]*|#[^\\n]*|'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"/g;\n/** The one field an index is on, written as its placeholder. */\nconst ON_ONE_FIELD =\n /\\b(?:FIELDS|COLUMNS)\\s+\\{([^{}]+)\\}(?=\\s+[A-Za-z]|\\s*;?\\s*$)/i;\nconst HNSW = /\\bHNSW\\b/i;\nconst DIST = /\\bDIST\\s+([A-Za-z_]+)/i;\nconst DIMENSION = /\\bDIMENSION\\s+(\\d+)/i;\nconst DISTANCES: Readonly<Record<string, string>> = {\n l2: \"EUCLIDEAN\",\n cosine: \"COSINE\",\n};\n/** The least candidates a nearest-neighbour search keeps: pgvector's own default. */\nconst EF_SEARCH = 40;\n\n/** A declared HNSW index on one field: its distance and dimension. */\ninterface NearestIndex {\n readonly field: string;\n readonly distance: string;\n readonly dimension: number | undefined;\n}\nconst nearestIndexes = new WeakMap<AnyModel, readonly NearestIndex[]>();\n\n/** The HNSW indexes a model's raw `surrealdb` texts declare, read once per model. */\nfunction nearestIndexesOf(model: AnyModel): readonly NearestIndex[] {\n const known = nearestIndexes.get(model);\n if (known) return known;\n const found = model[\"~\"].rawIndexes.flatMap((index): NearestIndex[] => {\n const text = index.templates.surrealdb?.replace(NOT_STATED, \" \");\n const field = text && ON_ONE_FIELD.exec(text)?.[1];\n if (!(field && HNSW.test(text))) return [];\n const dimension = DIMENSION.exec(text)?.[1];\n return [\n {\n field,\n // SurrealDB's own default.\n distance: (DIST.exec(text)?.[1] ?? \"EUCLIDEAN\").toUpperCase(),\n dimension: dimension === undefined ? undefined : Number(dimension),\n },\n ];\n });\n nearestIndexes.set(model, found);\n return found;\n}\n\nexport class SurrealReadBackend implements ReadBackend {\n readonly #queries: SurrealQueries;\n\n constructor(queries: SurrealQueries) {\n this.#queries = queries;\n }\n\n /** The subqueries a statement computes once, ahead of itself, while it is built. */\n #lets: Sql[] | undefined;\n #hoists = 0;\n readonly #hoisted = new Map<string, Sql>();\n /** How many relation reads are being written around this point of a statement. */\n #inRelation = 0;\n #guardsCursor = false;\n #cursorGuard: Sql | undefined;\n /** The relation filter a page reads by walking, with its list already too long. */\n #walking: PreparedPredicate | undefined;\n /** The rows a root page reads, when they are few enough to give each its own read. */\n #parents:\n | { readonly read: Sql; readonly count: number; ids?: Sql }\n | undefined;\n /** Whether what is being lowered reads rows a write would leave. */\n #judging = false;\n /** What holds each row a relation filter stepped away from, innermost last. */\n readonly #above: string[] = [];\n\n /**\n * A statement that may compute what reads no row ahead of itself. A list held\n * in a variable reads each of its records by key, where the same subquery in a\n * `WHERE` is probed row by row, and it stays one statement, so one transaction.\n */\n hoisted(build: () => Sql): Sql {\n if (this.#lets) return build();\n this.#lets = [];\n this.#hoists = 0;\n this.#hoisted.clear();\n try {\n const body = build();\n // Each at the top level: a server compiles a statement in the square of the\n // subqueries it holds, and keeps each statement it has compiled.\n return this.#lets.length\n ? sql`${sql.join(this.#lets, \" \")} ${body}`\n : body;\n } finally {\n this.#lets = undefined;\n }\n }\n\n /**\n * `build` reading rows a write would leave: a to-one link is the row's own value,\n * not the stored one, so a list of what holds reads targets, not who stores them.\n */\n judging(build: () => Sql): Sql {\n return this.judgingAll(build);\n }\n\n #hoist(expression: Sql): Sql | undefined {\n if (!this.#lets) return undefined;\n // A policy states one subquery for every action it answers: it runs once.\n const key = `${expression.toStatement()} ${JSON.stringify(expression.values, sameValue)}`;\n const known = this.#hoisted.get(key);\n if (known) return known;\n this.#hoists += 1;\n const variable = sql.raw(`$h${this.#hoists}`);\n this.#lets.push(sql`LET ${variable} = ${expression};`);\n this.#hoisted.set(key, variable);\n return variable;\n }\n\n read(model: AnyModel, operation: ReadOperation, args: Arguments): Read {\n let read: Read | undefined;\n const statement = this.hoisted(() => {\n read = this.#read(model, operation, args);\n return read.query.sql;\n });\n return { ...read!, query: { ...read!.query, sql: statement } };\n }\n\n #read(model: AnyModel, operation: ReadOperation, args: Arguments): Read {\n const q = this.#queries;\n const projected = () => q.prepareProjection(model, args);\n switch (operation) {\n case \"findUnique\": {\n const prepared = projected();\n const selector =\n args.where === undefined\n ? undefined\n : q.prepareSelector(model, args.where, true, false);\n const query = {\n // One row at most: an order would only sort it.\n sql: this.statement(\n model,\n prepared,\n { ...args, unordered: true },\n q.scoped(model, selector?.predicate, \"root\")\n ),\n shape: prepared.shape,\n };\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"findFirst\": {\n const prepared = projected();\n // A negative take reads from the end: the flipped order still gives one row.\n const take = args.take === undefined ? 1 : Math.sign(args.take);\n const query = {\n sql: this.statement(\n model,\n prepared,\n { ...args, take, nearest: approximateOrder(operation, args) },\n this.#filter(model, args)\n ),\n shape: prepared.shape,\n };\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"findMany\": {\n const prepared = projected();\n const query = {\n sql: this.statement(\n model,\n prepared,\n { ...args, nearest: approximateOrder(operation, args) },\n this.#filter(model, args)\n ),\n shape: prepared.shape,\n };\n return {\n query,\n single: false,\n value: rowSet(query),\n result:\n (args.take ?? 0) < 0\n ? (rows) => [...rows].reverse()\n : (rows) => rows,\n };\n }\n case \"exist\": {\n const table = name(tableOf(model));\n const predicate = this.#filter(model, args);\n const where = predicate\n ? sql`WHERE ${this.predicate(predicate, true)} `\n : sql.raw(\"\");\n return {\n query: {\n sql: sql`RETURN [{ _count: array::len(SELECT VALUE id FROM ${table} ${where}LIMIT 1) > 0 }]`,\n shape: { kind: \"object\", fields: { _count: BOOLEAN_LEAF } },\n },\n single: false,\n value: BOOLEAN_LEAF,\n result: (rows) => rows[0]?._count ?? false,\n };\n }\n case \"count\": {\n const selected = args.select as Input | undefined;\n const outputs: readonly (readonly [string, string | undefined])[] =\n selected\n ? [\n ...(selected._all ? [[\"_all\", undefined] as const] : []),\n ...Object.keys(selected)\n .filter((field) => field !== \"_all\" && selected[field])\n .map((field) => [field, field] as const),\n ]\n : [[\"_count\", undefined] as const];\n const counted = sql.join(\n outputs.map(([alias, field]) =>\n field === undefined\n ? sql`count() AS ${name(alias)}`\n : sql`count(${this.#operand(model, field)} != NONE) AS ${name(alias)}`\n ),\n \", \"\n );\n const query = {\n sql: sql`SELECT ${counted} FROM ${this.#rows(model, args)} GROUP ALL`,\n shape: {\n kind: \"object\" as const,\n fields: Object.fromEntries(\n outputs.map(([alias]) => [alias, COUNT_LEAF])\n ),\n },\n };\n return {\n query,\n single: selected !== undefined,\n value: selected ? query.shape : COUNT_LEAF,\n result: (rows) =>\n selected ? (rows[0] ?? {}) : ((rows[0]?._count as number) ?? 0),\n };\n }\n case \"aggregate\": {\n const query = this.#aggregation(model, args, []);\n return {\n query,\n single: true,\n value: query.shape,\n result: firstRow,\n };\n }\n case \"groupBy\": {\n const by = args.by!.map((member) => {\n if (typeof member === \"string\") return member;\n throw timeStepUnsupported();\n });\n const query = this.#aggregation(model, args, by);\n return {\n query,\n single: false,\n value: rowSet(query),\n result: (rows) => rows,\n };\n }\n default:\n return refuse(`'${operation}'`);\n }\n }\n\n /**\n * Where a field is stored. A record's key is its id: a single key is `id`\n * whatever the field is called, and a compound key or a group's is an array\n * id, read by position.\n */\n physical(model: AnyModel, field: string): Sql {\n const keys = this.#queries.keyOrder(model);\n const position = keys.indexOf(field);\n if (position < 0) return name(this.#queries.columnName(model, field));\n return sql.raw(idIsValue(keys, model) ? \"id\" : `id[${position}]`);\n }\n\n /**\n * Whether a predicate of one row can be answered by following its links, each a\n * read by key, and by lists of who holds what lies at their ends.\n */\n #walksForward(predicate: PreparedPredicate): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.every((arm) => this.#walksForward(arm));\n case \"not\":\n case \"layer\":\n return this.#walksForward(predicate.predicate);\n case \"always\":\n case \"operation\":\n return true;\n case \"relation\": {\n const { edge, closure, link, predicate: inner } = predicate;\n if (closure || link) return false;\n const asked = this.#queries.scoped(edge.target, inner, \"related\");\n if (\n edge.kind === \"reference\" &&\n !edge.many &&\n edge.owner === \"source\" &&\n this.#linked(edge)\n )\n return (\n !(asked && readsAbove(asked)) &&\n (asked === undefined || this.#walksForward(asked))\n );\n return (\n asked !== undefined &&\n predicate.quantifier !== \"every\" &&\n !readsAbove(asked) &&\n this.#holders(predicate, asked) !== undefined\n );\n }\n default:\n return false;\n }\n }\n\n /** Whether a predicate names one row by its whole key. */\n #namesOneRow(model: AnyModel, predicate: PreparedPredicate): boolean {\n const named = new Set<string>();\n const collect = (node: PreparedPredicate) => {\n if (node.kind === \"and\") node.predicates.forEach(collect);\n else if (\n node.kind === \"operation\" &&\n node.operator === \"equals\" &&\n node.target.kind === \"column\" &&\n node.target.scalar.model === model\n )\n named.add(node.target.scalar.field);\n };\n collect(predicate);\n return this.#queries.keyOrder(model).every((key) => named.has(key));\n }\n\n /** A filter's conditions: one that names a row follows its links from that row. */\n located(\n model: AnyModel,\n predicate: PreparedPredicate,\n named = this.#namesOneRow(model, predicate)\n ): Sql[] {\n return named\n ? this.judgingAll(() => this.conjuncts(predicate))\n : this.conjuncts(predicate);\n }\n\n /** What an operation compares with, where the call states it. */\n #statedValue(arm: PreparedPredicate): unknown {\n if (arm.kind !== \"operation\") return undefined;\n const { operand } = arm;\n if (operand === undefined) return arm.value;\n if (operand.kind === \"value\") return operand.value;\n if (operand.kind === \"parameter\")\n return this.#queries.callValue(operand.parameter);\n return undefined;\n }\n\n /**\n * The record a filter names by its whole key, and what else it asks of that row.\n * A statement over the record itself costs about half one that filters the table\n * on `id`, though both fetch the one record.\n */\n namedRecord(\n model: AnyModel,\n predicate: PreparedPredicate\n ):\n | { readonly record: Sql; readonly rest: PreparedPredicate | undefined }\n | undefined {\n const q = this.#queries;\n const keys = q.keyOrder(model);\n const flat = (node: PreparedPredicate): PreparedPredicate[] =>\n node.kind === \"and\" ? node.predicates.flatMap(flat) : [node];\n const named = new Map<string, unknown>();\n const others: PreparedPredicate[] = [];\n for (const arm of flat(predicate)) {\n const value = this.#statedValue(arm);\n const field =\n arm.kind === \"operation\" &&\n arm.operator === \"equals\" &&\n !arm.insensitive &&\n value !== null &&\n value !== undefined &&\n !(value instanceof Sql) &&\n arm.target.kind === \"column\" &&\n arm.target.path === undefined &&\n arm.target.scalar.model === model\n ? arm.target.scalar.field\n : undefined;\n if (\n field !== undefined &&\n keys.includes(field) &&\n !named.has(field) &&\n !this.#gatedHere(model, field)\n )\n named.set(field, value);\n else others.push(arm);\n }\n if (!keys.every((key) => named.has(key))) return undefined;\n // A group's double is a float in its id, which an integral value of the\n // call names as an int: that group is found by its fields, not fetched.\n if (\n isGroup(model) &&\n keys.some(\n (key) => model[\"~\"].state.scalars[key]?.[\"~\"].state.type === \"number\"\n )\n )\n return undefined;\n const [only] = keys;\n let record: Sql | undefined;\n if (!idIsValue(keys, model))\n record = sql`${this.recordOf(model, Object.fromEntries(named) as Input)}`;\n else if (isSingleKey(q, model, only!))\n record = this.value(model, only!, named.get(only!));\n if (!record) return undefined;\n let rest: PreparedPredicate | undefined;\n if (others.length > 1) rest = { kind: \"and\", predicates: others };\n else rest = others[0];\n return { record, rest };\n }\n\n judgingAll<T>(build: () => T): T {\n const outer = this.#judging;\n this.#judging = true;\n try {\n return build();\n } finally {\n this.#judging = outer;\n }\n }\n\n /** A predicate's conditions, to state beside others, each once ({@link onceEach}). */\n conjuncts(predicate: PreparedPredicate): Sql[] {\n return predicate.kind === \"and\"\n ? predicate.predicates.flatMap((inner) => this.conjuncts(inner))\n : [this.predicate(predicate, true)];\n }\n\n /** Whether a relation's link is a record, which a graph read can follow. */\n isLinked(edge: Reference): boolean {\n return this.#linked(edge);\n }\n\n /**\n * What a row reaches along a to-one link, as a write would leave it. The walk is\n * physical: a cycle through a hidden row is still one.\n */\n walkFrom(edge: Membership, row: Sql): Sql {\n return this.#walk(edge, {} as never, false, row);\n }\n\n #linked(edge: Reference): boolean {\n if (edge.pairs.length !== 1 || edge.discriminator) return false;\n // A view's relation, its source's slot, is no link of its own: `<~` reads\n // a field a table's `REFERENCE` defines, which a view has none of.\n if (viewFacts(edge.source)) return false;\n const q = this.#queries;\n const { source, target } = edge.pairs[0]!;\n return edge.owner === \"source\"\n ? isSingleKey(q, edge.target, target) &&\n !q.keyOrder(edge.source).includes(source)\n : isSingleKey(q, edge.source, source) &&\n !q.keyOrder(edge.target).includes(target);\n }\n\n /** Whether a private carrier column holds keys as text: its arms' keys differ. */\n #carriesText(model: AnyModel, field: string): boolean {\n const { scalar } = this.#queries.schema.physicalField(model, field);\n return scalar[\"~\"].state.type === \"string\";\n }\n\n #carried(model: AnyModel, field: string, key: Sql): Sql {\n return this.#carriesText(model, field) ? sql`<string>${key}` : key;\n }\n\n /**\n * A relation by its fields alone, from a row that is `$parent` here. A variant\n * relation's id column holds the key as text, whichever model it names.\n */\n #correlated(edge: Reference, row: string): Sql {\n const q = this.#queries;\n const pairs = edge.pairs.map(({ source, target }) => {\n const parent = sql`${sql.raw(row)}.${this.physical(edge.source, source)}`;\n const held = this.#heldAs(\n edge.source,\n source,\n parent,\n edge.target,\n target\n );\n const carried =\n edge.discriminator &&\n isSingleKey(q, edge.source, source) &&\n this.#heldTable(edge.target, target) === undefined;\n return sql`${this.physical(edge.target, target)} = ${carried ? this.#carried(edge.target, target, held) : held}`;\n });\n const { discriminator } = edge;\n if (discriminator) {\n const owner = discriminator.side === \"source\" ? edge.source : edge.target;\n const column = this.physical(owner, discriminator.field);\n pairs.push(\n discriminator.side === \"source\"\n ? sql`${sql.raw(row)}.${column} = ${discriminator.value}`\n : sql`${column} = ${discriminator.value}`\n );\n }\n return sql.join(pairs, \" AND \");\n }\n\n /** The rows an aggregate reads: the filtered table, or its page. */\n #rows(model: AnyModel, args: Arguments, within?: Sql): Sql {\n const { from, rest } = this.#driven(model, this.#filter(model, args));\n if (within)\n return sql`${from} WHERE ${sql.join(\n [...(rest ? [this.predicate(rest, true)] : []), within],\n \" AND \"\n )}`;\n const paged =\n args.take !== undefined ||\n args.skip !== undefined ||\n args.cursor !== undefined;\n if (paged) {\n const { extras, clauses } = this.#clauses(model, args, rest);\n return sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${from} ${sql.join(clauses, \" \")})`;\n }\n return rest ? sql`${from} WHERE ${this.predicate(rest, true)}` : from;\n }\n\n /**\n * `aggregate` and `groupBy`: flat aggregates inside, the public shape outside,\n * where a `having` and an order read them by name. `math::sum` of nothing is 0,\n * and SQL's is NULL, so each aggregate carries how many values it saw.\n */\n #aggregation(model: AnyModel, args: Arguments, by: readonly string[]): Query {\n const extremes = this.#extremes(model, args, by);\n if (extremes) return extremes;\n const inner = new Map<string, Sql>();\n const flat = (alias: string, expression: Sql) => {\n inner.set(alias, sql`${expression} AS ${name(alias)}`);\n return name(alias);\n };\n // A field that is always there has as many values as rows.\n const seen = (field: string) =>\n model[\"~\"].state.scalars[field]?.[\"~\"].state.nullable ||\n this.#gatedHere(model, field)\n ? flat(\n `__n_${field}`,\n sql`count(${this.#operand(model, field)} != NONE)`\n )\n : flat(\"__count__all\", sql`count()`);\n const of = (aggregate: string, field: string) => {\n if (aggregate === \"_count\" && field === \"_all\")\n return flat(\"__count__all\", sql`count()`);\n const column = this.#operand(model, field);\n if (aggregate === \"_count\")\n return flat(`__count_${field}`, sql`count(${column} != NONE)`);\n const value = sql`${sql.raw(AGGREGATE_FUNCTIONS[aggregate]!)}(${\n this.#namesDecimal(model, field) ? this.#numeric(column, false) : column\n })`;\n return flat(\n `_${aggregate}_${field}`,\n aggregate === \"_avg\"\n ? quantized(model[\"~\"].state.scalars[field]?.[\"~\"].state, value)\n : value\n );\n };\n const fields: Record<string, unknown> = {};\n const outer: Sql[] = [];\n for (const field of by) {\n const column = flat(field, this.#operand(model, field));\n outer.push(sql`(${column} ?? NULL) AS ${name(field)}`);\n fields[field] = this.#gatedHere(model, field)\n ? { ...(this.#leaf(model, field) as object), nullable: true }\n : this.#leaf(model, field);\n }\n for (const aggregate of AGGREGATE_NAMES) {\n const selection = args[aggregate as keyof Arguments];\n if (!selection) continue;\n if (aggregate === \"_count\" && selection === true) {\n outer.push(sql`${of(\"_count\", \"_all\")} AS _count`);\n fields._count = COUNT_LEAF;\n continue;\n }\n const selected = Object.entries(selection as Input).filter(\n ([, include]) => include\n );\n if (selected.length === 0) continue;\n const leaves: Record<string, unknown> = {};\n const members = selected.map(([field]) => {\n leaves[field] = this.#aggregateLeaf(model, aggregate, field);\n const value = of(aggregate, field);\n return aggregate === \"_count\"\n ? sql`${name(field)}: ${value}`\n : sql`${name(field)}: (IF ${seen(field)} = 0 { NULL } ELSE { ${value} })`;\n });\n outer.push(sql`{ ${sql.join(members, \", \")} } AS ${name(aggregate)}`);\n fields[aggregate] = { kind: \"object\", fields: leaves };\n }\n const having = args.having\n ? this.#having(model, args.having as Input, of, seen, true)\n : undefined;\n const { order, flags } = this.#groupOrder(\n model,\n args.orderBy,\n of,\n seen,\n by\n );\n if (by.length === 0 && inner.size === 0) flat(\"__count__all\", sql`count()`);\n const grouping = by.length\n ? sql`GROUP BY ${sql.join(\n by.map((field) => name(field)),\n \", \"\n )}`\n : sql.raw(\"GROUP ALL\");\n const clauses = [\n ...(having ? [sql`WHERE ${having}`] : []),\n ...(order.length ? [sql`ORDER BY ${sql.join(order, \", \")}`] : []),\n ...(by.length && args.take !== undefined\n ? [sql.raw(`LIMIT ${Number(args.take)}`)]\n : []),\n ...(by.length && args.skip !== undefined\n ? [sql.raw(`START ${Number(args.skip)}`)]\n : []),\n ];\n const rows = by.length\n ? this.#rows(\n model,\n {\n ...args,\n take: undefined,\n skip: undefined,\n cursor: undefined,\n },\n this.#firstGroups(model, args, by)\n )\n : this.#rows(model, args);\n return {\n sql: sql.join(\n [\n sql`SELECT ${sql.join(outer.length || flags.length ? [...outer, ...flags] : [sql.raw(\"true AS __row\")], \", \")} FROM (SELECT ${sql.join([...inner.values()], \", \")} FROM ${rows} ${grouping})`,\n ...clauses,\n ],\n \" \"\n ),\n shape: { kind: \"object\", fields } as Query[\"shape\"],\n };\n }\n\n /**\n * A `groupBy` reads every row before it can take any group, so a page of few groups\n * first seeks them on the index of the field it orders by, one value after the last,\n * each a statement of its own as a closure's variable never seeks, and reads only\n * their rows. Only a filter of its own columns goes along: each seek\n * states it again.\n */\n #firstGroups(\n model: AnyModel,\n args: Arguments,\n by: readonly string[]\n ): Sql | undefined {\n const groups = Number(args.take ?? 0) + Number(args.skip ?? 0);\n const orders = args.orderBy ? [args.orderBy as Input].flat() : [];\n const [field, spec] = Object.entries((orders[0] ?? {}) as Input)[0] ?? [\n by[0],\n \"asc\",\n ];\n if (\n !this.#lets ||\n Number(args.take ?? 0) <= 0 ||\n groups > GROUPS_SOUGHT ||\n args.having ||\n !by.includes(field as string) ||\n (spec !== \"asc\" && spec !== \"desc\") ||\n model[\"~\"].state.scalars[field as string]?.[\"~\"].state.nullable ||\n this.#gatedHere(model, field as string) ||\n // An index seeks the next text, not the next number.\n this.#namesDecimal(model, field as string) ||\n !this.#indexed(model, field as string)\n )\n return undefined;\n const filter = this.#filter(model, args);\n const where = filter ? [this.predicate(filter, true)] : [];\n if (where.some((part) => HOLDS_SUBQUERY.test(part.toStatement())))\n return undefined;\n const column = this.physical(model, field as string);\n const direction = sql.raw(spec === \"desc\" ? \"DESC\" : \"ASC\");\n const beyond = sql.raw(spec === \"desc\" ? \"<\" : \">\");\n const seek = (past: readonly Sql[]) => {\n const conditions = [...where, ...past];\n return sql`(SELECT VALUE ${column} FROM ${name(tableOf(model))}${conditions.length ? sql` WHERE ${sql.join(conditions, \" AND \")}` : sql.raw(\"\")} ORDER BY ${column} ${direction} LIMIT 1)[0]`;\n };\n // Past the last group a seek finds nothing, and the next finds a group again:\n // one already listed, which changes nothing.\n const found: Sql[] = [];\n for (let at = 0; at < groups; at++) {\n const last = found.at(-1);\n const next = this.#hoist(\n seek(last ? [sql`${column} ${beyond} ${last}`] : [])\n );\n if (!next) return undefined;\n found.push(next);\n }\n return sql`${column} IN [${sql.join(found, \", \")}]`;\n }\n\n /** Whether an index holds the field: one declared, or a foreign key's. */\n #indexed(model: AnyModel, field: string): boolean {\n const { indexes, relations } = model[\"~\"].state;\n return (\n indexes.some((index) =>\n (index.fields as readonly string[]).includes(field)\n ) ||\n Object.values(\n relations as Record<\n string,\n { \"~\": { state: { foreignKey?: { fields: readonly string[] } } } }\n >\n ).some((relation) =>\n relation[\"~\"].state.foreignKey?.fields.includes(field)\n )\n );\n }\n\n /**\n * `_min` and `_max` alone, over every row a filter leaves: each is the one row an\n * index finds walking no further, where an aggregate reads them all.\n */\n #extremes(\n model: AnyModel,\n args: Arguments,\n by: readonly string[]\n ): Query | undefined {\n const selected = ([\"_min\", \"_max\"] as const).flatMap((aggregate) => {\n const fields = Object.entries((args[aggregate] ?? {}) as Input)\n .filter(([, include]) => include)\n .map(([field]) => field);\n return fields.length > 0 ? [{ aggregate, fields }] : [];\n });\n const physical = selected.every(({ fields }) =>\n fields.every(\n (field) =>\n // An index's first row holds the least text, not the least number.\n !(\n this.#gatedHere(model, field) || this.#namesDecimal(model, field)\n ) &&\n this.#operand(model, field).toStatement() ===\n this.physical(model, field).toStatement()\n )\n );\n if (\n selected.length === 0 ||\n !physical ||\n by.length > 0 ||\n args.take !== undefined ||\n args.skip !== undefined ||\n args.cursor !== undefined ||\n args.having ||\n args._count ||\n args._avg ||\n args._sum\n )\n return undefined;\n const { from, rest } = this.#driven(model, this.#filter(model, args));\n const filter = rest ? [this.predicate(rest, true)] : [];\n const fields: Record<string, unknown> = {};\n const members = selected.map(({ aggregate, fields: chosen }) => {\n const leaves: Record<string, unknown> = {};\n const values = chosen.map((field) => {\n leaves[field] = this.#aggregateLeaf(model, aggregate, field);\n const column = this.physical(model, field);\n const where = model[\"~\"].state.scalars[field]?.[\"~\"].state.nullable\n ? [...filter, sql`${column} != NONE`]\n : filter;\n return sql`${name(field)}: ((SELECT VALUE ${column} FROM ${from}${where.length ? sql` WHERE ${sql.join(where, \" AND \")}` : sql.raw(\"\")} ORDER BY ${column} ${sql.raw(aggregate === \"_max\" ? \"DESC\" : \"ASC\")} LIMIT 1)[0] ?? NULL)`;\n });\n fields[aggregate] = { kind: \"object\", fields: leaves };\n return sql`${name(aggregate)}: { ${sql.join(values, \", \")} }`;\n });\n return {\n sql: sql`RETURN [{ ${sql.join(members, \", \")} }]`,\n shape: { kind: \"object\", fields } as Query[\"shape\"],\n };\n }\n\n #leaf(model: AnyModel, field: string): unknown {\n return (\n this.#queries.prepareProjection(\n model,\n { select: { [field]: true } },\n true\n ).shape as { fields: Record<string, unknown> }\n ).fields[field];\n }\n\n #aggregateLeaf(model: AnyModel, aggregate: string, field: string): unknown {\n if (aggregate === \"_count\") return COUNT_LEAF;\n const leaf = this.#leaf(model, field) as { type: string };\n if (aggregate === \"_avg\" && leaf.type !== \"decimal\")\n return { kind: \"scalar\", type: \"number\", nullable: true };\n return {\n ...leaf,\n nullable: true,\n // A decimal's sum may pass the field's precision; the others read as they are.\n widened:\n aggregate === \"_sum\" && leaf.type === \"decimal\" ? true : undefined,\n };\n }\n\n /**\n * `positive` carries a negation down to each comparison, as a filter's does: an\n * aggregate of no values is NULL, whose comparison holds neither way.\n */\n #having(\n model: AnyModel,\n having: Input,\n of: (aggregate: string, field: string) => Sql,\n seen: (field: string) => Sql,\n positive: boolean\n ): Sql {\n const clauses: Sql[] = [];\n const all = positive ? \" AND \" : \" OR \";\n const any = positive ? \" OR \" : \" AND \";\n for (const [key, value] of Object.entries(having)) {\n if (value === undefined) continue;\n if (key === \"AND\" || key === \"OR\" || key === \"NOT\") {\n const arms = [value]\n .flat()\n .map((arm) =>\n this.#having(\n model,\n arm as Input,\n of,\n seen,\n positive === (key !== \"NOT\")\n )\n );\n if (arms.length === 0) {\n // An empty OR holds of nothing; an empty AND or NOT asks nothing.\n if (key === \"OR\") clauses.push(sql.raw(positive ? \"false\" : \"true\"));\n continue;\n }\n clauses.push(sql`(${sql.join(arms, key === \"OR\" ? any : all)})`);\n continue;\n }\n const filter = value as Input;\n const aggregated = AGGREGATE_NAMES.filter(\n (aggregate) => filter[aggregate] !== undefined\n );\n if (aggregated.length === 0) {\n clauses.push(\n this.predicate(\n this.#queries.prepareSelector(model, { [key]: value }).predicate!,\n positive\n )\n );\n continue;\n }\n for (const aggregate of aggregated) {\n const counted = aggregate === \"_count\";\n clauses.push(\n this.#compare(\n model,\n key,\n counted,\n of(aggregate, key),\n filter[aggregate] as Input,\n positive,\n counted ? undefined : seen(key)\n )\n );\n }\n }\n return clauses.length\n ? sql`(${sql.join(clauses, all)})`\n : sql.raw(positive ? \"true\" : \"false\");\n }\n\n /** `seen`, where one is given, counts the values: none is an aggregate's NULL. */\n #compare(\n model: AnyModel,\n field: string,\n counted: boolean,\n expression: Sql,\n filter: Input,\n positive: boolean,\n seen?: Sql\n ): Sql {\n const bind = (value: unknown) =>\n counted\n ? sql`${value}`\n : this.#namesDecimal(model, field)\n ? this.#decimalOperand(value)\n : this.value(model, field, value);\n const given = Object.entries(filter).filter(\n ([, operand]) => operand !== undefined\n );\n if (given.length === 0) return sql.raw(positive ? \"true\" : \"false\");\n const known = (test: Sql) => {\n const asked = positive ? test : sql`!(${test})`;\n return seen ? sql`(${seen} > 0 AND ${asked})` : asked;\n };\n const tests = given.map(([operator, operand]) => {\n const nested = (inner: Input, sign: boolean) =>\n this.#compare(model, field, counted, expression, inner, sign, seen);\n if (operator === \"not\") return nested({ equals: operand }, !positive);\n if (operator === \"equals\" && operand === null) {\n if (!seen) return sql.raw(positive ? \"false\" : \"true\");\n return sql`${seen} ${sql.raw(positive ? \"=\" : \">\")} 0`;\n }\n if (COMPARISONS[operator])\n return known(\n sql`${expression} ${sql.raw(COMPARISONS[operator])} ${bind(operand)}`\n );\n if (operator === \"in\" || operator === \"notIn\") {\n const members = operand as unknown[];\n // An empty list asks nothing of the group, so a missing value does not matter.\n if (members.length === 0)\n return sql.raw(\n (operator === \"notIn\") === positive ? \"true\" : \"false\"\n );\n return known(\n sql`${expression} ${sql.raw(operator === \"in\" ? \"IN\" : \"NOT IN\")} [${sql.join(members.map(bind), \", \")}]`\n );\n }\n return refuse(`the '${operator}' operator in a having`);\n });\n return sql`(${sql.join(tests, positive ? \" AND \" : \" OR \")})`;\n }\n\n /** A group's order, with a flag for what is NULL: as PostgreSQL, the largest. */\n #groupOrder(\n model: AnyModel,\n input: unknown,\n of: (aggregate: string, field: string) => Sql,\n seen: (field: string) => Sql,\n by: readonly string[]\n ): { readonly order: Sql[]; readonly flags: Sql[] } {\n const order: Sql[] = [];\n const flags: Sql[] = [];\n const nullable = (field: string) =>\n model[\"~\"].state.scalars[field]?.[\"~\"].state.nullable === true ||\n this.#gatedHere(model, field);\n const term = (\n value: Sql,\n missing: Sql | undefined,\n sort: unknown,\n nulls?: unknown\n ) => {\n if (missing) {\n const flag = name(`__m${flags.length}`);\n flags.push(sql`(${missing}) AS ${flag}`);\n const first =\n (nulls ?? (sort === \"desc\" ? \"first\" : \"last\")) === \"first\";\n order.push(sql`${flag} ${sql.raw(first ? \"DESC\" : \"ASC\")}`);\n }\n order.push(sql`${value} ${sql.raw(sort === \"desc\" ? \"DESC\" : \"ASC\")}`);\n };\n // A group's field orders by its alias, and one naming a decimal by a number of its own.\n const grouped = (field: string) => {\n if (!this.#namesDecimal(model, field)) return name(field);\n const sorted = name(`__s${flags.length}`);\n flags.push(sql`${this.#numeric(name(field), false)} AS ${sorted}`);\n return sorted;\n };\n for (const entry of input === undefined ? [] : [input].flat()) {\n for (const [key, spec] of Object.entries(entry as Input)) {\n if (spec === undefined) continue;\n if (AGGREGATE_NAMES.includes(key)) {\n for (const [field, direction] of Object.entries(spec as Input))\n term(\n of(key, field),\n key !== \"_count\" && field !== \"_all\" && nullable(field)\n ? sql`${seen(field)} = 0`\n : undefined,\n direction\n );\n continue;\n }\n const { sort, nulls } = (\n typeof spec === \"string\" ? { sort: spec } : spec\n ) as Input;\n term(\n grouped(key),\n nullable(key) ? sql`${name(key)} = NONE` : undefined,\n sort,\n nulls\n );\n }\n }\n if (order.length === 0)\n for (const field of by)\n term(\n grouped(field),\n nullable(field) ? sql`${name(field)} = NONE` : undefined,\n \"asc\"\n );\n return { order, flags };\n }\n\n /**\n * The key order, as a mutation limit reads it: what the rows must also select\n * (`ORDER BY` reads only a field, so an expression is read by its alias), and\n * the order.\n */\n order(\n model: AnyModel,\n input: Arguments[\"orderBy\"]\n ): { readonly extras: Sql[]; readonly order: Sql } {\n const { extras, order } = this.#ordered(this.#orderTerms(model, input));\n return { extras, order: sql.join(order, \", \") };\n }\n\n #filter(model: AnyModel, args: Arguments): PreparedPredicate | undefined {\n const q = this.#queries;\n return q.scoped(\n model,\n args.where === undefined\n ? undefined\n : q.prepareSelector(model, args.where).predicate,\n \"root\"\n );\n }\n\n statement(\n model: AnyModel,\n prepared: PreparedProjection,\n args: Partial<Arguments> & {\n readonly unordered?: boolean;\n /** The order an index may serve: {@link approximateOrder}. */\n readonly nearest?: ReturnType<typeof approximateOrder>;\n },\n predicate: PreparedPredicate | undefined,\n conditions: readonly Sql[] = [],\n path?: Sql\n ): Sql {\n if (path || args.distinct?.length)\n return this.#page(\n model,\n prepared,\n args,\n path ?? name(tableOf(model)),\n predicate,\n conditions\n );\n const { from, rest, ahead, named } = this.#driven(\n model,\n predicate,\n args.take !== undefined\n );\n const listed = this.#page(\n model,\n prepared,\n named ? { ...args, named, unordered: true } : args,\n from,\n rest,\n conditions\n );\n if (!ahead)\n return this.#nearest(\n model,\n prepared,\n args,\n from,\n rest,\n conditions,\n listed\n );\n // The list is complete or it is not, and only a read can tell. What the walk\n // computes for itself waits in its own branch, where it may never run.\n const lets = this.#lets;\n const own: Sql[] = [];\n this.#lets = own;\n this.#walking = ahead.arm;\n // Too many hold for a list: the page reads in order, following each row's links.\n const walked = this.judgingAll(() =>\n this.#page(\n model,\n prepared,\n args,\n name(tableOf(model)),\n predicate,\n conditions\n )\n );\n this.#walking = undefined;\n this.#lets = lets;\n return sql`IF array::len(${ahead.rows}) < ${sql.raw(String(HOLDERS_AHEAD))} { ${listed} } ELSE { ${sql.join([...own, walked], \" \")} }`;\n }\n\n /**\n * A page an HNSW index may answer: its nearest `k` among the rows the filter\n * keeps, in the exact order. `<|k,ef|>` reads an HNSW index on the field, and\n * the first one when there are several, whatever its distance: so only a\n * table's one declared index of this distance, on a field no gate masks,\n * read from the table itself (a named record or a list of ids holds no\n * index: it answers nothing). With no such index built, it answers nothing,\n * so then — or with nothing left beside it — the exact page answers.\n */\n #nearest(\n model: AnyModel,\n prepared: PreparedProjection,\n args: Parameters<SurrealReadBackend[\"statement\"]>[2],\n from: Sql,\n rest: PreparedPredicate | undefined,\n conditions: readonly Sql[],\n exact: Sql\n ): Sql {\n const nearest = args.nearest;\n if (\n !nearest ||\n from.toStatement() !== name(tableOf(model)).toStatement() ||\n this.#gatedHere(model, nearest.field)\n )\n return exact;\n const to = nearest.distance.to as number[];\n const indexes = nearestIndexesOf(model).filter(\n (index) => index.field === nearest.field\n );\n const index = indexes.length === 1 ? indexes[0] : undefined;\n if (\n !index ||\n index.distance !== DISTANCES[nearest.distance.metric as string] ||\n (index.dimension !== undefined && index.dimension !== to.length)\n )\n return exact;\n const column = this.physical(model, nearest.field);\n const searched = sql`${column} ${sql.raw(\n `<|${nearest.take},${Math.max(EF_SEARCH, nearest.take)}|>`\n )} ${to}`;\n // An index may hold a zero vector among a cosine's nearest, which has no\n // cosine: it is left out, as an index leaves it out on PostgreSQL.\n const directed =\n nearest.distance.metric === \"cosine\"\n ? [sql`vector::magnitude(${column}) > 0`]\n : [];\n const found = this.#hoist(\n this.#page(model, prepared, args, from, rest, [\n ...conditions,\n searched,\n ...directed,\n ])\n );\n return found\n ? sql`IF array::len(${found}) > 0 { ${found} } ELSE { ${exact} }`\n : exact;\n }\n\n /** One page of rows, from wherever a statement reads them. */\n #page(\n model: AnyModel,\n prepared: PreparedProjection,\n args: Partial<Arguments> & {\n readonly named?: boolean;\n readonly unordered?: boolean;\n },\n from: Sql,\n rest: PreparedPredicate | undefined,\n conditions: readonly Sql[]\n ): Sql {\n this.#cursorGuard = undefined;\n this.#guardsCursor = true;\n const fromTable =\n this.#inRelation === 0 &&\n !this.#walking &&\n (args.named === true ||\n from.toStatement() === name(tableOf(model)).toStatement());\n const { extras, clauses } = this.#clauses(\n model,\n { ...args, fromTable },\n rest,\n conditions\n );\n this.#guardsCursor = false;\n let count = Number(args.take ?? 0);\n if (count <= 0)\n count = Number(\n args.named === true ||\n (rest !== undefined && this.#namesOneRow(model, rest))\n );\n const statedOnce = sql.join(clauses, \" \");\n this.#parents =\n fromTable &&\n args.cursor === undefined &&\n !args.distinct &&\n extras.length === 0 &&\n count > 0 &&\n count <= PARENTS_READ_APART &&\n !HOLDS_SUBQUERY.test(statedOnce.toStatement())\n ? { read: sql`(SELECT VALUE id FROM ${from} ${statedOnce})`, count }\n : undefined;\n const guard = this.#cursorGuard as Sql | undefined;\n const guarded = (body: Sql) =>\n guard ? sql`IF ${guard} { ${body} } ELSE { [] }` : body;\n // An alias that names another column would answer an `ORDER BY` of it, so\n // the rows are chosen under their own names and named after.\n const columns = this.#queries.schema.storedFields(model);\n const shadowed = prepared.fields.some((field) =>\n columns.some(\n (other) =>\n other !== field.name &&\n this.#queries.columnName(model, other) === field.name\n )\n );\n const stated = this.columns(prepared);\n this.#parents = undefined;\n if (shadowed)\n return guarded(\n sql`SELECT ${stated} FROM (${sql.join(\n [\n sql`SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${from}`,\n ...clauses,\n ],\n \" \"\n )})`\n );\n return guarded(\n sql.join(\n [\n sql`SELECT ${sql.join([stated, ...extras], \", \")} FROM ${from}`,\n ...clauses,\n ],\n \" \"\n )\n );\n }\n\n /**\n * A correlated read never walks an index in order: `<~` reads every reference and\n * sorts them, whatever the page takes, where a read of a statement's own variable\n * seeks. So a page of few rows reads ahead which they are, and each one's children\n * in a read of its own. Each read is stated once per row, which only a filter\n * without a subquery of its own, or a row above it, can afford.\n */\n #pagesOfParents(\n edge: Reference,\n predicate: PreparedPredicate | undefined,\n args: Relation[\"arguments\"]\n ): Sql | undefined {\n const parents = this.#parents;\n if (\n !parents ||\n this.#inRelation !== 1 ||\n !this.#linked(edge) ||\n Number(args.take ?? 0) <= 0 ||\n args.cursor !== undefined ||\n args.distinct\n )\n return undefined;\n parents.ids ??= this.#hoist(parents.read);\n if (!parents.ids) return undefined;\n const { target } = edge;\n const link = name(this.#queries.columnName(target, edge.pairs[0]!.target));\n const pages: Sql[] = [];\n for (let at = 0; at < parents.count; at++) {\n const { extras, clauses } = this.#clauses(\n target,\n { ...args, fromTable: true },\n predicate,\n [sql`${link} = ${parents.ids}[${sql.raw(String(at))}]`]\n );\n const page = sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")})`;\n if (\n at === 0 &&\n (HOLDS_SUBQUERY.test(sql.join(clauses, \" \").toStatement()) ||\n READS_A_ROW_ABOVE.test(sql.join(clauses, \" \").toStatement()))\n )\n return undefined;\n pages.push(page);\n }\n const read = this.#hoist(sql`[${sql.join(pages, \", \")}]`);\n return read && sql`${read}[array::find_index(${parents.ids}, $this.id)]`;\n }\n\n /** The row `identity` names, every key field equal. */\n identity(model: AnyModel, identity: Input): Sql {\n const keys = this.#queries.keyOrder(model);\n const named = Object.keys(identity);\n if (keys.length > 1 && keys.every((key) => named.includes(key)))\n return sql`id = ${this.recordOf(model, identity)}`;\n return sql.join(\n Object.entries(identity).map(\n ([field, value]) =>\n sql`${this.physical(model, field)} = ${this.value(model, field, value)}`\n ),\n \" AND \"\n );\n }\n\n /** The record a row's key fields name, however many there are. */\n recordOfRow(model: AnyModel, row: Input): Sql {\n const keys = this.#queries.keyOrder(model);\n return idIsValue(keys, model)\n ? this.value(model, keys[0]!, row[keys[0]!])\n : sql`${this.recordOf(model, row)}`;\n }\n\n /** A compound key's record. */\n recordOf(model: AnyModel, row: Input): RecordId {\n return new RecordId(\n tableOf(model),\n this.#queries\n .keyOrder(model)\n .map((key) => this.#part(model, key, row[key])) as never\n );\n }\n\n /** One stated part of an array id, as a value. */\n keyPart(model: AnyModel, field: string, value: unknown): Sql {\n return sql`${this.#part(model, field, value)}`;\n }\n\n /**\n * One part of an array id: a link stays a record, as its field holds it. A\n * view's record is its source's, under its own table: its parts are too. A\n * group's part is a value of its column's scalar.\n */\n #part(model: AnyModel, field: string, value: unknown): unknown {\n const facts = viewFacts(model);\n if (facts && !facts.aggregated)\n return this.#part(facts.source, field, value);\n const link = facts ? undefined : this.#linkOf(model, field);\n if (link) return new RecordId(tableOf(link.target), value as string);\n return stored(model[\"~\"].state.scalars[field]?.[\"~\"].state, value);\n }\n\n /** The target rows of `edge` for this parent. */\n member(edge: Membership, parent: Input): Sql {\n if (edge.kind === \"junction\") {\n const list = edge.declared\n ? this.#declaredOf(edge, parent)\n : this.membersOf(edge, parent);\n return sql`id IN ${list}`;\n }\n const reached = reference(edge);\n const held = reached.pairs.map(({ source }) => parent[source]);\n const { discriminator } = reached;\n if (\n held.some((value) => value === null || value === undefined) ||\n (discriminator?.side === \"source\" &&\n parent[discriminator.field] !== discriminator.value)\n )\n return sql.raw(\"false\");\n return sql.join(\n [\n ...reached.pairs.map(\n ({ target }, index) =>\n sql`${this.physical(reached.target, target)} = ${this.value(reached.target, target, held[index])}`\n ),\n ...(discriminator?.side === \"target\"\n ? [\n sql`${this.physical(reached.target, discriminator.field)} = ${discriminator.value}`,\n ]\n : []),\n ],\n \" AND \"\n );\n }\n\n /**\n * A generated junction as an edge table. `in` is its canonical first side, so\n * the direction does not depend on which model declared the relation, and a\n * self relation tells its two directions apart by it.\n */\n edgeOf(edge: Junction) {\n const resolved = edge.scope.edge;\n if (edge.declared) refuse(\"a declared junction as an edge\");\n const topology =\n resolved.kind === \"junction\"\n ? resolved.topology\n : resolved.kind === \"variantJunctionCarrier\"\n ? (edge.scope.member as VariantJunctionMember).topology\n : refuse(\"this junction\");\n for (const side of [edge.sourceSide, edge.targetSide]) {\n const keys = this.#queries.keyOrder(side.model);\n if (\n side.members.length !== keys.length ||\n !side.members.every((pair) => keys.includes(pair.referencedField))\n )\n refuse(\"a junction over anything but a record's own key\");\n }\n const first = topology.sourceIsFirst ? topology.source : topology.target;\n const outward = edge.sourceSide === first;\n const arrow = outward ? \"->\" : \"<-\";\n // The edge table links the source's records; a view's row is its source\n // record under the view's own table, so the walk starts from that record.\n const from = viewFacts(edge.source)\n ? sql`(type::record(${tableOf(edge.sourceSide.model)}, record::id(id)))`\n : sql``;\n return {\n from,\n table: name(edge.table),\n near: name(outward ? \"in\" : \"out\"),\n far: name(outward ? \"out\" : \"in\"),\n hop: sql.raw(`${arrow}${name(edge.table).toStatement()}${arrow}`),\n back: sql.raw(\n `${outward ? \"<-\" : \"->\"}${name(edge.table).toStatement()}${outward ? \"<-\" : \"->\"}`\n ),\n out: sql.raw(`${arrow}${name(edge.table).toStatement()}`),\n };\n }\n\n /** The field of a declared junction's model that holds this column. */\n #linkField(edge: Junction, column: string): string {\n const model = edge.declared!.model;\n const field = this.#queries.schema\n .storedFields(model)\n .find((name) => this.#queries.columnName(model, name) === column);\n return field ?? refuse(`the link column '${column}'`);\n }\n\n /** Whether a field reads as a record: a key, or a link to one. */\n isRecord(model: AnyModel, field: string): boolean {\n return (\n isSingleKey(this.#queries, model, field) || this.holdsRecord(model, field)\n );\n }\n\n /**\n * Whether a model's field holds a record rather than the key's own value. A\n * view's field holds what its source's holds (`DEFINE TABLE … AS SELECT`\n * copies it). An aggregated view holds no record: its body groups by a\n * key's or a link's value.\n */\n holdsRecord(model: AnyModel, field: string): boolean {\n const facts = viewFacts(model);\n if (facts)\n return !facts.aggregated && this.holdsRecord(facts.source, field);\n return this.#linkOf(model, field) !== undefined;\n }\n\n /**\n * The table whose record a field holds: its model's own for its single\n * key, the target's for a link it holds, none for a field holding the key\n * itself. A view's field holds what its source's holds: a record of the\n * table its source's link targets.\n */\n #heldTable(model: AnyModel, field: string): string | undefined {\n if (isSingleKey(this.#queries, model, field)) return tableOf(model);\n const facts = viewFacts(model);\n // An aggregated view holds values: its body groups by a key's or a\n // link's value, never by the record.\n if (facts)\n return facts.aggregated\n ? undefined\n : this.#heldTable(facts.source, field);\n const link = this.#linkOf(model, field);\n // A variant relation's column holds the key itself, whichever model it names.\n return link && !link.discriminator ? tableOf(link.target) : undefined;\n }\n\n /**\n * `model`'s `field`, read as `read`, as `other`'s `otherField` holds it:\n * the same record, the record of the key it names in another table, or the\n * key itself. One end of a relation names the other's row by the key alone\n * when the two hold it differently: a view's copy of its source's link is\n * a record of the table that link targets, never of a view. An unset link\n * names no record; a row's own key is always set.\n */\n #heldAs(\n model: AnyModel,\n field: string,\n read: Sql,\n other: AnyModel,\n otherField: string\n ): Sql {\n const from = this.#heldTable(model, field);\n const to = this.#heldTable(other, otherField);\n if (from === to) return read;\n if (to !== undefined)\n return sql`type::record(${tableText(to)}, ${from === undefined ? recordKey(other, otherField, read) : read})`;\n const type = textKeyType(model, field);\n const key = type\n ? sql`<${sql.raw(type)}> record::id(${read})`\n : sql`record::id(${read})`;\n return isSingleKey(this.#queries, model, field)\n ? key\n : sql`(IF ${read} { ${key} })`;\n }\n\n /**\n * The relation whose link a table's field holds as a record: one it owns,\n * naming another table's single key (no relation targets a view).\n */\n #linkOf(model: AnyModel, field: string): Reference | undefined {\n const q = this.#queries;\n for (const slot of Object.keys(model[\"~\"].state.relations)) {\n const { edges } = q.countedMemberships(model, slot);\n const edge = edges[0];\n if (\n edges.length === 1 &&\n edge?.kind === \"reference\" &&\n edge.owner === \"source\" &&\n edge.pairs.length === 1 &&\n edge.pairs[0]!.source === field &&\n isSingleKey(q, edge.target, edge.pairs[0]!.target)\n )\n return edge;\n }\n return undefined;\n }\n\n /** This link's columns against the row a variable holds, one side of it. */\n #linkMatch(edge: Junction, side: Junction[\"sourceSide\"], row: string): Sql[] {\n const link = edge.declared!.model;\n return side.members.map((pair) => {\n const field = this.#linkField(edge, pair.junctionField);\n const read = sql`${sql.raw(row)}.${this.physical(side.model, pair.referencedField)}`;\n const singleKey = isSingleKey(\n this.#queries,\n side.model,\n pair.referencedField\n );\n const plainKey = singleKey && !this.holdsRecord(link, field);\n // A view's row is its source record under the view's own table: the\n // link names the source's.\n const held =\n singleKey && side === edge.sourceSide && viewFacts(edge.source)\n ? sql`type::record(${tableOf(side.model)}, record::id(${read}))`\n : read;\n return sql`${this.physical(link, field)} = ${plainKey ? sql`record::id(${held})` : held}`;\n });\n }\n\n /** The record of a side, read from a link row a variable or the row itself holds. */\n linkTarget(edge: Junction, side: Junction[\"sourceSide\"], row: string): Sql {\n const link = edge.declared!.model;\n const keys = this.#queries.keyOrder(side.model);\n // A link over fields other than the key names its record by looking it up.\n if (\n !keys.every((key) => side.members.some((m) => m.referencedField === key))\n ) {\n const named = side.members.map((pair) => {\n const column = this.physical(\n link,\n this.#linkField(edge, pair.junctionField)\n );\n return sql`${this.physical(side.model, pair.referencedField)} = ${sql.raw(row || \"$parent\")}.${column}`;\n });\n return sql`(SELECT VALUE id FROM ${name(tableOf(side.model))} WHERE ${sql.join(named, \" AND \")} LIMIT 1)[0]`;\n }\n const parts = keys.map((key) => {\n const pair = side.members.find(\n (member) => member.referencedField === key\n )!;\n const field = this.#linkField(edge, pair.junctionField);\n const column = this.physical(link, field);\n return {\n read: row ? sql`${sql.raw(row)}.${column}` : column,\n record: this.holdsRecord(link, field),\n };\n });\n if (parts.length === 1 && parts[0]!.record) return parts[0]!.read;\n const key =\n parts.length === 1\n ? parts[0]!.read\n : sql`[${sql.join(\n parts.map((part) => part.read),\n \", \"\n )}]`;\n return sql`type::record(${tableOf(side.model)}, ${key})`;\n }\n\n /** A row's links through a declared junction, narrowed by the link's own filter. */\n #links(edge: Junction, row: string, where?: PreparedPredicate): Sql {\n const conditions = [\n ...this.#linkMatch(edge, edge.sourceSide, row),\n ...(where ? [this.predicate(where, true)] : []),\n ];\n return sql`(SELECT * FROM ${name(tableOf(edge.declared!.model))} WHERE ${sql.join(conditions, \" AND \")})`;\n }\n\n /** The record one side of a junction holds, however its key is spelled in `read`. */\n end(side: Junction[\"sourceSide\"], read: (pair: Member) => unknown): Sql {\n if (side.members.length === 1) {\n const pair = side.members[0]!;\n return this.value(side.model, pair.referencedField, read(pair));\n }\n const row = Object.fromEntries(\n side.members.map((pair) => [pair.referencedField, read(pair)])\n );\n return sql`${this.recordOf(side.model, row)}`;\n }\n\n /** The field of a declared junction's model that a column names, for its writes. */\n linkFieldOf(edge: Junction, column: string): string {\n return this.#linkField(edge, column);\n }\n\n /** The target records of a declared junction for a parent's known values. */\n #declaredOf(edge: Junction, parent: Input): Sql {\n const link = edge.declared!.model;\n const conditions = edge.sourceSide.members.map((pair) => {\n const field = this.#linkField(edge, pair.junctionField);\n return sql`${this.physical(link, field)} = ${this.value(link, field, parent[pair.referencedField])}`;\n });\n return sql`(SELECT VALUE ${this.linkTarget(edge, edge.targetSide, \"\")} FROM ${name(tableOf(link))} WHERE ${sql.join(conditions, \" AND \")})`;\n }\n\n /** The path from one record to its members through an edge table. */\n membersOf(edge: Junction, parent: Input): Sql {\n const { hop } = this.edgeOf(edge);\n const start = this.end(\n edge.sourceSide,\n (pair) => parent[pair.referencedField]\n );\n return sql`${start}${hop}${name(tableOf(edge.target))}`;\n }\n\n #clauses(\n model: AnyModel,\n args: Pick<\n Partial<Arguments>,\n \"orderBy\" | \"take\" | \"skip\" | \"cursor\" | \"distinct\"\n > & {\n readonly unordered?: boolean;\n readonly fromTable?: boolean;\n readonly named?: boolean;\n },\n predicate: PreparedPredicate | undefined,\n conditions: readonly Sql[] = []\n ): { readonly extras: Sql[]; readonly clauses: Sql[] } {\n const { terms, forward } = this.#ordering(model, args);\n const { extras, order } = this.#ordered(terms);\n const located = [\n ...(predicate\n ? args.named\n ? this.located(model, predicate, true)\n : this.located(model, predicate)\n : []),\n ...conditions,\n ];\n const cursor =\n args.cursor === undefined\n ? []\n : [this.#cursor(model, args.cursor as Input, terms)];\n const clauses: Sql[] = [];\n const distinct = args.distinct as string[] | undefined;\n if (this.#distinctly(model, distinct)) {\n // Each tuple's row is chosen in the caller's order, whichever way this page reads.\n const chosen = this.#ordered(forward);\n // The cursor is among what a tuple's row is chosen from, as `DISTINCT ON`\n // reads only what its `WHERE` leaves.\n clauses.push(\n sql`WHERE ${this.#distinct(\n model,\n distinct!,\n [...located, ...cursor],\n chosen.order,\n chosen.extras\n )}`\n );\n } else {\n const where = onceEach([...located, ...cursor]);\n const bound = args.fromTable\n ? this.#pageBound(model, args, terms, where)\n : undefined;\n const all = bound ? [...where, bound] : where;\n if (all.length > 0) clauses.push(sql`WHERE ${sql.join(all, \" AND \")}`);\n }\n if (!args.unordered) clauses.push(sql`ORDER BY ${sql.join(order, \", \")}`);\n // A bound LIMIT is what a nested read's index needs written, so both inline\n // an integer admission has already checked.\n if (args.take !== undefined)\n clauses.push(sql.raw(`LIMIT ${Math.abs(Number(args.take))}`));\n if (args.skip !== undefined)\n clauses.push(sql.raw(`START ${Number(args.skip)}`));\n return { extras, clauses };\n }\n\n /**\n * A descending page over an ascending key has an order no index holds, so it sorts\n * every row. The first term's value at the page's last row bounds what it sorts,\n * and an index finds that value walking no further than the page. Short of that\n * many rows there is no value, and every row is at least NONE.\n */\n #pageBound(\n model: AnyModel,\n args: Pick<Partial<Arguments>, \"take\" | \"skip\">,\n terms: readonly OrderTerm[],\n where: readonly Sql[]\n ): Sql | undefined {\n const [first, ...rest] = terms;\n const take = Math.abs(Number(args.take ?? 0));\n if (\n take === 0 ||\n first?.field === undefined ||\n !first.descending ||\n first.nullable ||\n rest.every((term) => term.descending) ||\n !this.#indexed(model, first.field)\n )\n return undefined;\n const filter = where.length\n ? sql`WHERE ${sql.join(where, \" AND \")} `\n : sql.raw(\"\");\n // Stating subqueries twice costs more to compile than the sort does to run.\n if (HOLDS_SUBQUERY.test(filter.toStatement())) return undefined;\n const value = this.#hoist(\n sql`(SELECT VALUE ${first.expression} FROM ${name(tableOf(model))} ${filter}ORDER BY ${first.expression} DESC LIMIT 1 START ${sql.raw(String(take + Number(args.skip ?? 0) - 1))})[0]`\n );\n return value && sql`${first.expression} >= ${value}`;\n }\n\n /** The terms a read walks, and those of the caller's own order. */\n #ordering(\n model: AnyModel,\n args: Pick<Partial<Arguments>, \"orderBy\" | \"take\">\n ): { readonly terms: OrderTerm[]; readonly forward: OrderTerm[] } {\n const forward = this.#orderTerms(model, args.orderBy);\n return {\n forward,\n terms:\n (args.take ?? 0) < 0\n ? forward.map((term) => ({\n ...term,\n descending: !term.descending,\n nulls:\n term.nulls &&\n (term.nulls === \"first\"\n ? (\"last\" as const)\n : (\"first\" as const)),\n }))\n : forward,\n };\n }\n\n /** Terms as `ORDER BY` reads them. A missing value sorts by its own flag. */\n #ordered(terms: readonly OrderTerm[]): {\n readonly extras: Sql[];\n readonly order: Sql[];\n } {\n const extras: Sql[] = [];\n const order = terms.flatMap((term, index) => {\n const direction = sql.raw(term.descending ? \"DESC\" : \"ASC\");\n let reads = term.expression;\n if (!term.named) {\n reads = name(`__o${index}`);\n extras.push(sql`${term.expression} AS ${reads}`);\n }\n if (!term.nullable) return [sql`${reads} ${direction}`];\n const missing = name(`__m${index}`);\n extras.push(sql`(${term.expression} = NONE) AS ${missing}`);\n return [\n sql`${missing} ${sql.raw(term.nulls === \"first\" ? \"DESC\" : \"ASC\")}`,\n sql`${reads} ${direction}`,\n ];\n });\n return { extras, order };\n }\n\n /** The first row of each tuple, in this read's own order: `GROUP BY` keeps it. */\n #distinct(\n model: AnyModel,\n fields: readonly string[],\n where: readonly Sql[],\n order: readonly Sql[],\n extras: readonly Sql[]\n ): Sql {\n const table = name(tableOf(model));\n // A gated field groups by its alias: `GROUP BY` takes no expression.\n const columns = fields.map((field, index) =>\n this.#gatedHere(model, field)\n ? {\n read: sql`${this.#operand(model, field)} AS ${sql.raw(`__d${index}`)}`,\n group: sql.raw(`__d${index}`),\n }\n : {\n read: this.physical(model, field),\n group: this.physical(model, field),\n }\n );\n const filter = where.length\n ? sql`WHERE ${sql.join(where, \" AND \")} `\n : sql.raw(\"\");\n const ordered = sql`SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${table} ${filter}ORDER BY ${sql.join(order, \", \")}`;\n const tuple = sql.join(\n columns.map(({ read }) => read),\n \", \"\n );\n const grouped = sql.join(\n columns.map(({ group }) => group),\n \", \"\n );\n return sql`id IN (SELECT VALUE array::first(id) FROM (SELECT ${tuple}, id FROM (${ordered}) GROUP BY ${grouped}))`;\n }\n\n /** The rows from the cursor's on, in the order this read walks them. */\n #cursor(model: AnyModel, cursor: Input, terms: readonly OrderTerm[]): Sql {\n const table = name(tableOf(model));\n // The anchor is a candidate like any other: a hidden one is a missing one.\n const q = this.#queries;\n const stated = q.scoped(\n model,\n q.prepareSelector(model, cursor, true, false).predicate,\n this.#inRelation > 0 ? \"related\" : \"root\"\n )!;\n // A cursor that states its key is the record itself, read without a filter.\n const named = this.namedRecord(model, stated);\n const source = named?.record ?? table;\n const asked = named ? named.rest : stated;\n const located = asked\n ? sql` WHERE ${this.predicate(asked, true)}`\n : sql.raw(\"\");\n const walked = terms.flatMap((term): OrderTerm[] =>\n term.nullable\n ? [\n {\n ...term,\n expression: sql`(${term.expression} = NONE)`,\n descending: term.nulls === \"first\",\n },\n term,\n ]\n : [term]\n );\n // The anchor's values in one read, ahead of the statement where a statement can:\n // in a `WHERE` it would run for each row the scan passes.\n const read = sql`(SELECT ${sql.join(\n walked.map(\n (term, index) => sql`${term.expression} AS ${sql.raw(`c${index}`)}`\n ),\n \", \"\n )} FROM ${source}${located} LIMIT 1)[0]`;\n const anchor = this.#hoist(read) ?? read;\n const found = sql`${anchor} != NONE`;\n // `a >= x AND (a > x OR …)`: the same rows as `a > x OR (a = x AND …)`, which\n // reads two ranges of an index and sorts them, where this walks one in order.\n const after = walked.reduceRight<Sql | undefined>((rest, term, index) => {\n const value = sql`${anchor}.${sql.raw(`c${index}`)}`;\n const reached = sql`${term.expression} ${sql.raw(term.descending ? \"<=\" : \">=\")} ${value}`;\n if (!rest) return reached;\n return sql`${reached} AND (${term.expression} ${sql.raw(term.descending ? \"<\" : \">\")} ${value} OR (${rest}))`;\n }, undefined)!;\n // Beside a bare condition, a seek on the key becomes a scan, so where a whole\n // statement can answer \"no such cursor\", it answers ahead of its `WHERE`.\n if (this.#guardsCursor && this.#lets) {\n this.#cursorGuard = found;\n return after;\n }\n return sql`(${found} AND ${after})`;\n }\n\n /** The caller's order, completed by the key: every page has one total order. */\n #orderTerms(model: AnyModel, input: Arguments[\"orderBy\"]): OrderTerm[] {\n const q = this.#queries;\n const terms: OrderTerm[] = [];\n const ordered = new Set<string>();\n const stated = input ?? q.orderOf(model);\n const orders = stated === undefined ? [] : [stated].flat();\n for (const order of orders) {\n for (const [field, spec] of Object.entries(order)) {\n if (spec === undefined) continue;\n if (model[\"~\"].state.relations[field]) {\n terms.push(this.#relationOrder(model, field, spec as Input));\n continue;\n }\n ordered.add(field);\n terms.push(this.#scalarOrder(model, field, spec, \"\"));\n }\n }\n for (const field of q.keyOrder(model)) {\n if (ordered.has(field)) continue;\n const plain = !this.#namesDecimal(model, field);\n terms.push({\n expression: plain\n ? this.#operand(model, field)\n : this.#numeric(\n this.#operand(model, field),\n !this.#gatedHere(model, field)\n ),\n named: plain,\n descending: false,\n nullable: false,\n });\n }\n return terms;\n }\n\n #scalarOrder(\n model: AnyModel,\n field: string,\n spec: unknown,\n path: string\n ): OrderTerm {\n const state0 = model[\"~\"].state.scalars[field]?.[\"~\"].state;\n const distance = (spec as Input | undefined)?._distance as\n | Input\n | undefined;\n if (distance && state0) {\n if (path) refuse(\"ordering by a distance through a relation\");\n return {\n expression: this.#distance(\n this.#operand(model, field),\n state0,\n field,\n distance,\n \"orderBy\"\n ),\n named: false,\n descending: distance.sort === \"desc\",\n nullable: true,\n nulls: \"last\",\n };\n }\n const { sort, nulls } = (\n typeof spec === \"string\" ? { sort: spec } : spec\n ) as { sort?: string; nulls?: \"first\" | \"last\" };\n if (sort !== \"asc\" && sort !== \"desc\")\n refuse(`ordering by '${field}' with this specification`);\n const state = model[\"~\"].state.scalars[field]?.[\"~\"].state;\n if (!state) refuse(`ordering by '${field}'`);\n const column = this.#gated(\n model,\n field,\n sql.raw(`${path}${this.physical(model, field).toStatement()}`),\n path\n );\n const plain = !this.#namesDecimal(model, field);\n return {\n expression: plain ? column : this.#numeric(column, false),\n named: plain && path === \"\" && !this.#gatedHere(model, field),\n field: plain && path === \"\" ? field : undefined,\n descending: sort === \"desc\",\n nullable:\n path !== \"\" || state.nullable === true || this.#gatedHere(model, field),\n // As PostgreSQL: a missing value counts as the largest.\n nulls: nulls ?? (sort === \"desc\" ? \"first\" : \"last\"),\n };\n }\n\n #relationOrder(\n model: AnyModel,\n field: string,\n spec: Input,\n path = \"\"\n ): OrderTerm {\n const { edges } = this.#queries.countedMemberships(model, field);\n const edge = edges[0]!;\n if (spec._count !== undefined) {\n if (path) refuse(`ordering by a count through '${field}'`);\n return {\n expression: sql.join(\n edges.map(\n (member) =>\n sql`array::len(${this.#members(member, this.#queries.scoped(member.target, undefined, \"related\"))})`\n ),\n \" + \"\n ),\n named: false,\n descending: spec._count === \"desc\",\n nullable: false,\n };\n }\n const [nested, inner] = Object.entries(spec)[0]!;\n if (edge.many) refuse(`ordering by '${nested}' of the relation '${field}'`);\n const linked = edge.kind === \"reference\" && this.#linked(edge);\n if (path && !linked)\n refuse(`ordering by the relation '${field}' through another relation`);\n // A link is the row's own field; the other side is a lookup of the records\n // referencing the row the path has reached, which a path's last record leads.\n const prefix =\n linked && edge.owner === \"source\"\n ? `${path}${this.physical(edge.source, edge.pairs[0]!.source).toStatement()}.`\n : `(${path.slice(0, -1)}${this.#members(edge).toStatement()})[0].`;\n const term = edge.target[\"~\"].state.relations[nested]\n ? this.#relationOrder(edge.target, nested, inner as Input, prefix)\n : this.#scalarOrder(edge.target, nested, inner, prefix);\n if (this.#queries.domainOf(edge.target, \"related\") === undefined)\n return term;\n return {\n ...term,\n expression: sql`(IF ${this.#related(edge, \"some\", undefined, path)} { ${term.expression} } ELSE { NONE })`,\n named: false,\n nullable: true,\n };\n }\n\n /** Every member of a to-many, unfiltered, as a value. */\n #members(edge: Membership, predicate?: PreparedPredicate): Sql {\n if (edge.kind === \"junction\" && edge.declared) {\n const where = predicate\n ? sql` WHERE id IN $linked AND ${this.predicate(predicate, true)}`\n : sql` WHERE id IN $linked`;\n return sql`({ LET $owner = $this; LET $linked = (SELECT VALUE ${this.linkTarget(edge, edge.targetSide, \"\")} FROM ${this.#links(edge, \"$owner\")}); (SELECT VALUE id FROM ${name(tableOf(edge.target))}${where}) })`;\n }\n if (edge.kind === \"junction\") {\n const { from, hop } = this.edgeOf(edge);\n const target = name(tableOf(edge.target));\n return predicate\n ? sql`${from}${hop}(${target} WHERE ${this.predicate(predicate, true)})`\n : sql`${from}${hop}${target}`;\n }\n return this.#traversal(reference(edge), predicate, { unordered: true });\n }\n\n columns(prepared: PreparedProjection): Sql {\n return sql.join(\n prepared.fields.map((field) => this.column(prepared.model, field)),\n \", \"\n );\n }\n\n /** One projected field, as a `SELECT` or a `RETURN` lists it. */\n column(model: AnyModel, field: PreparedProjectionField): Sql {\n const { value, alias } = this.#field(model, field);\n const named = name(alias);\n // A column under its own name needs no alias, which costs a little per row.\n return value.toStatement() === named.toStatement()\n ? value\n : sql`${value} AS ${named}`;\n }\n\n #destructure(prepared: PreparedProjection): Sql {\n return sql`.{ ${sql.join(\n prepared.fields.map((field) => {\n const { value, alias } = this.#field(prepared.model, field);\n return sql`${name(alias)}: ${value}`;\n }),\n \", \"\n )} }`;\n }\n\n #field(\n model: AnyModel,\n field: PreparedProjectionField\n ): { readonly value: Sql; readonly alias: string } {\n switch (field.kind) {\n case \"scalar\": {\n const column = this.physical(model, field.name);\n const state = model[\"~\"].state.scalars[field.name]?.[\"~\"].state;\n const nullable = state?.nullable;\n // A point is GeoJSON to the database and a latitude and longitude here.\n if (state?.type === \"point\" && !state.array) {\n const point = sql`{ latitude: ${column}.coordinates[1], longitude: ${column}.coordinates[0] }`;\n return {\n value: nullable\n ? sql`(IF ${column} != NONE { ${point} } ELSE { NULL })`\n : point,\n alias: field.name,\n };\n }\n // An absent field is NONE, which the client reads as `undefined` under its\n // key, and the driver as null: `?? NULL` would cost each row for nothing.\n return { value: column, alias: field.name };\n }\n case \"relation\":\n return { value: this.#relation(field), alias: field.name };\n case \"gate\":\n return {\n value: this.#truth(this.#gateHolds(model, field.gate)),\n alias: field.name,\n };\n case \"evidence\":\n return { value: this.#evidence(model, field), alias: field.name };\n case \"sentinel\":\n return { value: sql.raw(\"true\"), alias: field.name };\n case \"distance\": {\n const state = model[\"~\"].state.scalars[field.field]![\"~\"].state;\n const distance = this.#distance(\n this.physical(model, field.field),\n state,\n field.field,\n field.specification,\n \"select\"\n );\n return { value: sql`(${distance} ?? NULL)`, alias: field.name };\n }\n case \"variants\":\n return {\n value: sql`{ ${sql.join(\n field.arms.map((arm) => {\n const row = this.#relation({\n kind: \"relation\",\n name: arm.variant,\n ...arm,\n });\n const edge = arm.edge;\n if (field.many || edge.kind !== \"reference\")\n return sql`${name(arm.variant)}: ${row}`;\n // A claimed arm whose row is gone is an empty document, which\n // the decoder refuses; an unclaimed one is an empty slot.\n const claim = this.physical(\n edge.source,\n edge.discriminator!.field\n );\n return sql`${name(arm.variant)}: (IF ${claim} = ${edge.discriminator!.value} { ${row} ?? ${this.#absentArm(edge)} } ELSE { NULL })`;\n }),\n \", \"\n )} }`,\n alias: field.name,\n };\n case \"counts\":\n return {\n value: sql`{ ${sql.join(\n field.counts.map((count) => {\n const predicate = count.selector?.predicate;\n const counted =\n predicate && count.negated\n ? ({ kind: \"not\", predicate } as const)\n : predicate;\n const lengths = count.edges.map(\n (edge) =>\n sql`array::len(${this.#members(edge, this.#queries.scoped(edge.target, counted, \"related\"))})`\n );\n return sql`${name(count.relation)}: ${sql.join(lengths, \" + \")}`;\n }),\n \", \"\n )} }`,\n alias: field.name,\n };\n case \"aggregates\":\n return refuse(\"the aggregates of a relation's rows ('_aggregate')\");\n default:\n return refuse(`a '${(field as { kind: string }).kind}' projection`);\n }\n }\n\n /** Whether a layer's `input` holds of this row; `undefined` where it always does. */\n #layerHolds(\n model: AnyModel,\n layer: number,\n input: Input,\n path = \"\"\n ): Sql | undefined {\n const { predicate } = this.#queries.domain!.project!.layered(\n model,\n layer,\n input\n );\n return predicate && this.predicate(predicate, true, path);\n }\n\n /**\n * A column as an operand the caller wrote: a read-gated field is absent on a row\n * that does not carry it, wherever it is read. Every such row is one the domain\n * takes, so `read` holds there and the field's own predicate decides. A layer's\n * predicates read the column itself.\n */\n #gated(model: AnyModel, field: string, column: Sql, path = \"\"): Sql {\n const q = this.#queries;\n if (q.lowersLayer) return column;\n const gate = q.domain?.project?.projected(model)?.gates.get(field);\n if (!gate) return column;\n const held = gate.flatMap(([layer, read, input]) => {\n if (input === read) return [];\n const lowered = this.#layerHolds(model, layer, input);\n return lowered ? [lowered] : [];\n });\n if (held.length === 0) return column;\n const holds = sql.join(held, \" AND \");\n return path\n ? sql`(IF array::len(SELECT VALUE id FROM $this.${sql.raw(path.slice(0, -1))} WHERE ${holds}) > 0 { ${column} } ELSE { NONE })`\n : sql`(IF ${holds} { ${column} } ELSE { NONE })`;\n }\n\n /** Whether an operand over this field can read absent because of its gate. */\n #gatedHere(model: AnyModel, field: string): boolean {\n const q = this.#queries;\n return (\n !q.lowersLayer &&\n q.domain?.project?.projected(model)?.gates.has(field) === true\n );\n }\n\n #operand(model: AnyModel, field: string): Sql {\n return this.#gated(model, field, this.physical(model, field));\n }\n\n /**\n * Whether `field` holds a record that names a decimal by its text, a key or a link\n * to one: as text, 10 sorts before 2, so it compares and sorts as {@link #numeric}.\n * (A dateTime's text is as wide at every instant it holds, and sorts as it does.)\n */\n #namesDecimal(model: AnyModel, field: string): boolean {\n return (\n model[\"~\"].state.scalars[field]?.[\"~\"].state.type === \"decimal\" &&\n this.isRecord(model, field)\n );\n }\n\n /**\n * The number the record `column` reads names ({@link #namesDecimal}): no index\n * holds it, so a read that compares or sorts by it reads every row. A missing\n * record stays missing; `present` where the row's own key is read, never missing.\n */\n #numeric(column: Sql, present: boolean): Sql {\n const value = sql`<decimal>record::id(${column})`;\n return present ? value : sql`(IF ${column} { ${value} })`;\n }\n\n /** What a {@link #numeric} column compares with: the number a value is. */\n #decimalOperand(value: unknown): Sql {\n return value instanceof Sql\n ? sql`<decimal>${value}`\n : sql`<decimal>${String(value)}`;\n }\n\n /** Where a read-gated field's row carries it: every gating layer's `read` and predicate. */\n #gateHolds(model: AnyModel, gate: FieldGate): Sql | undefined {\n const held = gate.flatMap(([layer, read, input]) =>\n (input === read ? [read] : [read, input]).flatMap((where) => {\n const lowered = this.#layerHolds(model, layer, where);\n return lowered ? [lowered] : [];\n })\n );\n return held.length ? sql`(${sql.join(held, \" AND \")})` : undefined;\n }\n\n /** A condition as a value: true or false, never unset. */\n #truth(condition: Sql | undefined): Sql {\n return condition\n ? sql`(IF ${condition} { true } ELSE { false })`\n : sql.raw(\"true\");\n }\n\n /** A declared projection key on this row: the layer's `read` around one boolean per name. */\n #evidence(\n model: AnyModel,\n field: Extract<PreparedProjectionField, { kind: \"evidence\" }>\n ): Sql {\n const { layer, read } = field.evidence;\n const visible = this.#layerHolds(model, layer, read);\n const test = (input: Input) =>\n input === read ? undefined : this.#layerHolds(model, layer, input);\n const held = sql.join(\n field.names.map(\n ([name, input]) =>\n sql`${sql.raw(JSON.stringify(name))}: ${this.#truth(test(input))}`\n ),\n \", \"\n );\n if (!visible) return sql`{ ${held} }`;\n const none = field.names\n .map(([name]) => `${JSON.stringify(name)}: false`)\n .join(\", \");\n return sql`(IF ${visible} { { ${held} } } ELSE { { ${sql.raw(none)} } })`;\n }\n\n /**\n * What a claimed arm whose row did not come back carries: the empty document, \"the\n * row is gone\", which the decoder refuses. Under a related domain the row may exist\n * and be hidden, which reads as an empty slot.\n */\n #absentArm(edge: Reference): Sql {\n if (this.#queries.domainOf(edge.target, \"related\") === undefined)\n return sql.raw(\"{}\");\n return sql`(IF array::len(${this.#traversal(edge, undefined, { take: 1 })}) > 0 { NULL } ELSE { {} })`;\n }\n\n #relation(given: Relation): Sql {\n const predicate = this.#queries.scoped(\n given.edge.target,\n given.arguments.selector?.predicate,\n \"related\"\n );\n const field: Relation = predicate\n ? {\n ...given,\n arguments: {\n ...given.arguments,\n selector: { ...given.arguments.selector, predicate } as never,\n },\n }\n : given;\n this.#inRelation += 1;\n try {\n return this.#relationRead(field);\n } finally {\n this.#inRelation -= 1;\n }\n }\n\n #relationRead(field: Relation): Sql {\n const { arguments: args, projection } = field;\n const predicate = args.selector?.predicate;\n const members = this.#destructure(projection);\n if (field.edge.kind === \"junction\" && field.edge.declared)\n return this.#declaredMembers(field, field.edge);\n if (field.recurrence)\n return this.#carrier(field.edge, args, field.recurrence.depth, members);\n if (\n this.#distinctly(field.edge.target, args.distinct as string[] | undefined)\n )\n return this.#distinctMembers(field.edge, args, members);\n if (field.edge.kind === \"junction\") {\n const { from, hop } = this.edgeOf(field.edge);\n const target = field.edge.target;\n const { extras, clauses } = this.#clauses(\n target,\n args,\n args.selector?.predicate\n );\n const read = sql`${from}${hop}(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")})`;\n return field.edge.many\n ? sql`${read}${members}`\n : sql`((${read}${members})[0] ?? NULL)`;\n }\n const edge = reference(field.edge);\n if (!edge.many && edge.owner === \"source\" && this.#linked(edge)) {\n const link = name(\n this.#queries.columnName(edge.source, edge.pairs[0]!.source)\n );\n // A hidden target reads as an absent one.\n if (predicate)\n return sql`(IF ${link} = NONE { NULL } ELSE { ((SELECT * FROM $this.${link} WHERE ${this.predicate(predicate, true)})${members})[0] ?? NULL })`;\n return sql`(${name(this.#queries.columnName(edge.source, edge.pairs[0]!.source))}${members} ?? NULL)`;\n }\n const paged = edge.many\n ? this.#pagesOfParents(edge, predicate, args)\n : undefined;\n const read = paged ?? this.#traversal(edge, args.selector?.predicate, args);\n return edge.many\n ? sql`${read}${members}`\n : sql`((${read}${members})[0] ?? NULL)`;\n }\n\n /**\n * A relation through a model of its own: the row's links, then the rows they\n * name. Each row may carry the link that produced it, as `$through`.\n */\n #declaredMembers(field: Relation, edge: Junction): Sql {\n const { arguments: args, projection, linkRow, linkWhere } = field;\n const target = edge.target;\n const link = edge.declared!.model;\n if (field.recurrence)\n return this.#carrier(\n edge,\n args,\n field.recurrence.depth,\n this.#destructure(projection)\n );\n const fields = projection.fields.map((member) => {\n const { value, alias } = this.#field(projection.model, member);\n return sql`${name(alias)}: ${value}`;\n });\n if (linkRow) {\n const columns = linkRow.fields.map((member) => {\n const { value, alias } = this.#field(link, {\n kind: \"scalar\",\n name: member,\n });\n return sql`${name(alias)}: ${value}`;\n });\n const named = this.linkTarget(edge, edge.targetSide, \"\");\n // The link that named this row.\n fields.push(\n sql`\\`$through\\`: ($links[WHERE ${named} = $row])[0].{ ${sql.join(columns, \", \")} }`\n );\n }\n const { extras, clauses } = this.#clauses(\n target,\n args,\n args.selector?.predicate,\n [sql.raw(\"id IN $linked\")]\n );\n const page = sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")})`;\n const rows = linkRow\n ? sql`${page}.map(|$item| { LET $row = $item.id; $item.{ ${sql.join(fields, \", \")} } })`\n : sql`${page}.{ ${sql.join(fields, \", \")} }`;\n const read = edge.many ? rows : sql`(${rows})[0] ?? NULL`;\n return sql`({ LET $owner = $this; LET $links = ${this.#links(edge, \"$owner\", linkWhere?.predicate)}; LET $linked = (SELECT VALUE ${this.linkTarget(edge, edge.targetSide, \"\")} FROM $links); ${read} })`;\n }\n\n /** The records one step along `edge` from the record `parent` holds, in order. */\n #children(\n edge: Membership,\n parent: string,\n args: Relation[\"arguments\"]\n ): Sql {\n const predicate = args.selector?.predicate;\n const target = edge.target;\n const held = sql.raw(parent);\n const narrowed = () => this.#clauses(target, args, predicate);\n if (edge.kind === \"junction\" && edge.declared) {\n const { extras, clauses } = this.#clauses(target, args, predicate, [\n // One subquery less than `#links`: a parser counts its depth.\n sql`id IN (SELECT VALUE ${this.linkTarget(edge, edge.targetSide, \"\")} FROM ${name(tableOf(edge.declared.model))} WHERE ${sql.join(this.#linkMatch(edge, edge.sourceSide, parent), \" AND \")})`,\n ]);\n return sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")}).id`;\n }\n if (edge.kind === \"junction\") {\n const { hop } = this.edgeOf(edge);\n const { extras, clauses } = narrowed();\n return sql`${held}${hop}(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")}).id`;\n }\n const reached = reference(edge);\n if (this.#linked(reached)) {\n if (reached.owner === \"source\") {\n const link = this.physical(reached.source, reached.pairs[0]!.source);\n if (predicate) {\n const { extras, clauses } = narrowed();\n return sql`(IF ${held}.${link} != NONE { (SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${held}.${link} ${sql.join(clauses, \" \")}).id } ELSE { [] })`;\n }\n return sql`(IF ${held}.${link} != NONE { [${held}.${link}] } ELSE { [] })`;\n }\n const { extras, clauses } = narrowed();\n return sql`${held}<~(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} FIELD ${name(this.#queries.columnName(target, reached.pairs[0]!.target))} ${sql.join(clauses, \" \")}).id`;\n }\n const { extras, clauses } = this.#clauses(target, args, predicate, [\n this.#correlated(reached, parent),\n ]);\n return sql`(SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))} ${sql.join(clauses, \" \")}).id`;\n }\n\n /**\n * A breadth-first walk from a record, as one value: a fold over the levels,\n * each the distinct records the last one reached. A numeric depth labels each\n * edge with its level. An exhaustive one keeps what it has seen, which is what\n * ends a cycle, and refuses past the depth SurrealDB allows a recursion rather\n * than answer a part of the graph.\n */\n #walk(\n edge: Membership,\n args: Relation[\"arguments\"],\n depth: number | false,\n root: Sql\n ): Sql {\n if (depth === 0) return sql.raw(\"{ level: [], edges: [] }\");\n const children = this.#children(edge, \"$p\", args);\n if (depth === false) {\n const reached = this.#reached(edge, args, root);\n if (reached)\n return sql`({ LET $r = ${reached}; { level: [], edges: array::flatten(array::distinct(array::concat([${root}], $r)).map(|$p| (${children}).map(|$c| { p: $p, c: $c }))) } })`;\n }\n if (depth !== false)\n return sql`array::fold(array::range(1, ${sql.raw(String(depth + 1))}), { level: [${root}], edges: [] }, |$walk, $depth| { LET $pairs = array::flatten($walk.level.map(|$p| (${children}).map(|$c| { p: $p, c: $c, d: $depth }))); { level: array::distinct($pairs.c), edges: array::concat($walk.edges, $pairs) } })`;\n return sql`array::fold(array::range(1, ${sql.raw(String(MAX_WALK + 1))}), { level: [${root}], seen: [${root}], edges: [] }, |$walk, $depth| { LET $pairs = array::flatten($walk.level.map(|$p| (${children}).map(|$c| { p: $p, c: $c }))); LET $reached = array::complement(array::distinct($pairs.c), $walk.seen); { level: $reached, seen: array::concat($walk.seen, $reached), edges: array::concat($walk.edges, $pairs) } })`;\n }\n\n /** One step along `edge` as an idiom, which a recursion can repeat. */\n #hopIdiom(edge: Membership, args: Relation[\"arguments\"]): Sql | undefined {\n const target = edge.target;\n const narrowed = () =>\n this.#clauses(target, { unordered: true }, args.selector?.predicate)\n .clauses;\n if (edge.kind === \"junction\") {\n if (edge.declared) return undefined;\n return sql`${this.edgeOf(edge).hop}(SELECT * FROM ${name(tableOf(target))} ${sql.join(narrowed(), \" \")}).id`;\n }\n const held = reference(edge);\n if (!this.#linked(held)) return undefined;\n if (held.owner === \"source\")\n return args.selector?.predicate\n ? undefined\n : sql`.${this.physical(held.source, held.pairs[0]!.source)}`;\n return sql`<~(SELECT * FROM ${name(tableOf(target))} FIELD ${name(this.#queries.columnName(target, held.pairs[0]!.target))} ${sql.join(narrowed(), \" \")}).id`;\n }\n\n /** Every record an exhaustive walk reaches, in one recursion rather than a fold. */\n #reached(\n edge: Membership,\n args: Relation[\"arguments\"],\n root: Sql\n ): Sql | undefined {\n const hop = this.#hopIdiom(edge, args);\n return hop && sql`array::distinct(${root}.{..+collect}${hop})`;\n }\n\n /** A walk's own statements in a block: `$w`, and the refusal an endless one owes. */\n /**\n * The record a walk from this row starts at: the row's own, or, for a\n * view's, its source record, whose links the tables hold.\n */\n #walkRoot(edge: Membership): Sql {\n const table = viewTable(edge.source);\n return table === edge.source\n ? sql.raw(\"$this.id\")\n : sql`type::record(${tableOf(table)}, record::id($this.id))`;\n }\n\n #walked(walk: Sql, root: Sql = sql.raw(\"$this.id\")): Sql {\n return sql`LET $root = ${root}; LET $w = ${walk}; IF array::len($w.level) > 0 AND $w.seen != NONE { THROW ${`A recursive read walked past ${MAX_WALK} levels.`} };`;\n }\n\n /** The path a column of `up` rows above this one is read at. */\n #rowAbove(up: number | undefined, path: string): string {\n if (!up) return path;\n const row = this.#above.at(-up);\n if (row === undefined)\n throw new UnsupportedOperationError(\n \"An enclosing row's column ({ $row, up }) has no row to read here.\"\n );\n return `${row}.`;\n }\n\n /** A record's key as the identity tuple the recursive decoder reads. */\n #identityOf(model: AnyModel, record: Sql): Sql {\n return idIsValue(this.#queries.keyOrder(model), model)\n ? sql`[record::id(${record})]`\n : sql`record::id(${record})`;\n }\n\n /** What `decodeRecursiveCarrier` reads: the root, its nodes and its edges. */\n #carrier(\n edge: Membership,\n args: Relation[\"arguments\"],\n depth: number | false,\n members: Sql\n ): Sql {\n const { source, target } = edge;\n const walk = this.#walk(edge, args, depth, sql.raw(\"$root\"));\n const labelled =\n depth === false ? sql.raw(\"\") : sql.raw(\", __rq_depth: $e.d\");\n // A block answers with its last expression: a `RETURN` in one would leave\n // whatever expression holds the block, negations included.\n return sql`({ ${this.#walked(walk, this.#walkRoot(edge))} { __rq_root: ${this.#identityOf(source, sql.raw(\"$root\"))}, __rq_nodes: array::distinct($w.edges.c).map(|$n| { __rq_key: ${this.#identityOf(target, sql.raw(\"$n\"))}, __rq_row: $n${members} }), __rq_edges: $w.edges.map(|$e| { __rq_parent: ${this.#identityOf(source, sql.raw(\"$e.p\"))}, __rq_child: ${this.#identityOf(target, sql.raw(\"$e.c\"))}${labelled} }) } })`;\n }\n\n /** Whether a `distinct` narrows at all: one holding the whole key does not. */\n #distinctly(model: AnyModel, fields: readonly string[] | undefined): boolean {\n return (\n fields !== undefined &&\n fields.length > 0 &&\n !this.#queries.keyOrder(model).every((key) => fields.includes(key))\n );\n }\n\n /**\n * A relation's first row of each tuple. A parent's members are a value here,\n * so they group as one, where a subquery past the first could not see `$parent`.\n */\n #distinctMembers(\n edge: Membership,\n args: Relation[\"arguments\"],\n members: Sql\n ): Sql {\n const target = edge.target;\n const predicate = args.selector?.predicate;\n const { terms } = this.#ordering(target, { ...args, take: undefined });\n const { extras: inner, order: forward } = this.#ordered(terms);\n const sorted =\n edge.kind === \"junction\"\n ? sql`${this.edgeOf(edge).from}${this.edgeOf(edge).hop}(SELECT ${sql.join([sql.raw(\"*\"), ...inner], \", \")} FROM ${name(tableOf(target))}${predicate ? sql` WHERE ${this.predicate(predicate, true)}` : sql.raw(\"\")} ORDER BY ${sql.join(forward, \", \")})`\n : this.#traversal(reference(edge), predicate, {\n orderBy: args.orderBy,\n });\n const tuple = sql.join(\n (args.distinct as string[]).map((field) => this.#operand(target, field)),\n \", \"\n );\n const after =\n args.cursor === undefined\n ? sql.raw(\"\")\n : sql` WHERE ${this.#cursor(target, args.cursor as Input, this.#ordering(target, args).terms)}`;\n const { extras, clauses } = this.#clauses(\n target,\n { ...args, distinct: undefined, cursor: undefined },\n undefined,\n [sql.raw(\"id IN $first\")]\n );\n return sql`({ LET $all = ${sorted}; LET $first = (SELECT VALUE array::first(id) FROM (SELECT ${tuple}, id FROM $all${after} GROUP BY ${tuple})); (SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM $all ${sql.join(clauses, \" \")})${members} })`;\n }\n\n /**\n * The one record a to-one's fields name, when they name its whole key: read by\n * key, where a filter on the same fields would scan its table for each row.\n */\n #heldRecord(edge: Reference): Sql | undefined {\n if (edge.many || edge.owner !== \"source\") return undefined;\n const keys = this.#queries.keyOrder(edge.target);\n const parts: Sql[] = [];\n for (const key of keys) {\n const pair = edge.pairs.find(({ target }) => target === key);\n if (!pair) return undefined;\n const part = this.#heldAs(\n edge.source,\n pair.source,\n sql`$owner.${this.physical(edge.source, pair.source)}`,\n edge.target,\n key\n );\n // A lookup by record tells an integer part from a narrower integer.\n parts.push(\n this.#heldTable(edge.target, key) === undefined\n ? keyCast(edge.target, key, part)\n : part\n );\n }\n // A single key's part is the record already; a compound key's, and a\n // group's of any length, is the list its record is named by.\n const record = idIsValue(keys, edge.target)\n ? parts[0]!\n : sql`type::record(${tableOf(edge.target)}, [${sql.join(parts, \", \")}])`;\n // An arm another row's type names reads nothing; an unset part names no record.\n const { discriminator } = edge;\n return discriminator\n ? sql`(IF $owner.${this.physical(edge.source, discriminator.field)} = ${discriminator.value} { ${record} } ELSE { [] })`\n : record;\n }\n\n /**\n * The rows holding a link to this one: `FIELD` is what names the relation,\n * since without it `<~` reads every reference from that table.\n */\n #traversal(\n edge: Reference,\n predicate: PreparedPredicate | undefined,\n args: Pick<\n Partial<Arguments>,\n \"orderBy\" | \"take\" | \"skip\" | \"cursor\" | \"distinct\"\n > & { readonly unordered?: boolean }\n ): Sql {\n const target = edge.target;\n const linked = this.#linked(edge);\n const record = linked ? undefined : this.#heldRecord(edge);\n if (record) {\n const { extras, clauses } = this.#clauses(target, args, predicate);\n return sql`({ LET $owner = $this; SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${record} ${sql.join(clauses, \" \")} })`;\n }\n const { extras, clauses } = this.#clauses(\n target,\n args,\n predicate,\n linked ? [] : [this.#correlated(edge, \"$owner\")]\n );\n const read = sql`SELECT ${sql.join([sql.raw(\"*\"), ...extras], \", \")} FROM ${name(tableOf(target))}`;\n return linked\n ? sql`<~(${read} FIELD ${name(this.#queries.columnName(target, edge.pairs[0]!.target))} ${sql.join(clauses, \" \")})`\n : sql`({ LET $owner = $this; ${read} ${sql.join(clauses, \" \")} })`;\n }\n\n /**\n * `positive` carries a negation down to each comparison: SurrealQL compares in\n * two values, where `age != 20` holds of a row with no age, and viborm's filters\n * read as SQL's, where neither `age = 20` nor its negation does.\n */\n predicate(predicate: PreparedPredicate, positive: boolean, path = \"\"): Sql {\n switch (predicate.kind) {\n case \"and\":\n case \"or\": {\n if (predicate.predicates.length === 0)\n return sql.raw(\n (predicate.kind === \"and\") === positive ? \"true\" : \"false\"\n );\n // Each parenthesis counts against the parser's depth, so one arm has none.\n if (predicate.predicates.length === 1)\n return this.predicate(predicate.predicates[0]!, positive, path);\n const conjunction = (predicate.kind === \"and\") === positive;\n const arms = (node: PreparedPredicate): PreparedPredicate[] =>\n node.kind === predicate.kind ? node.predicates.flatMap(arms) : [node];\n const lowered = onceEach(\n arms(predicate).map((inner) => this.predicate(inner, positive, path))\n );\n // Arms with nothing in them hold as an empty one does.\n if (lowered.length === 0)\n return sql.raw(\n (predicate.kind === \"and\") === positive ? \"true\" : \"false\"\n );\n if (lowered.length === 1) return lowered[0]!;\n return sql`(${joined(lowered, conjunction ? \" AND \" : \" OR \")})`;\n }\n case \"not\":\n return this.predicate(predicate.predicate, !positive, path);\n case \"always\":\n return sql.raw(predicate.value === positive ? \"true\" : \"false\");\n case \"layer\": {\n // A layer the call drops is no filter at all.\n const lowered = this.#queries.layer(predicate, (resolved) =>\n this.predicate(resolved, positive, path)\n );\n return lowered ?? sql.raw(positive ? \"true\" : \"false\");\n }\n case \"exists\": {\n const body = this.#queries.scoped(\n predicate.model,\n predicate.predicate,\n \"related\"\n );\n const rows = sql`SELECT VALUE id FROM ${name(tableOf(predicate.model))}${body ? sql` WHERE ${this.predicate(body, true)}` : sql.raw(\"\")} LIMIT 1`;\n return sql`array::len(${rows}) ${sql.raw(positive ? \">\" : \"=\")} ${sql.raw(positive ? \"0\" : \"0\")}`;\n }\n case \"condition\":\n return sql.raw(\n this.#queries.holds(predicate.condition) === positive\n ? \"true\"\n : \"false\"\n );\n case \"operation\":\n return this.#operation(predicate, positive, path);\n case \"relation\":\n return this.#relationFilter(predicate, positive, path);\n default:\n return refuse(`a '${predicate.kind}' filter`);\n }\n }\n\n #operation(\n predicate: Extract<PreparedPredicate, { kind: \"operation\" }>,\n positive: boolean,\n path: string\n ): Sql {\n const { target, operator } = predicate;\n if (target.kind !== \"column\") refuse(\"this filter target\");\n const { scalar } = target;\n let column = this.#gated(\n scalar.model,\n scalar.field,\n sql.raw(\n `${path}${this.physical(scalar.model, scalar.field).toStatement()}`\n ),\n path\n );\n const facts = scalar.physical.scalar[\"~\"].state;\n if (facts.type === \"json\" && facts.array !== true)\n return this.#jsonOperation(predicate, column, positive);\n if (target.path) refuse(\"this filter target\");\n const spatial = this.#spatial(predicate, column, facts);\n if (spatial) {\n const asked = positive ? spatial : sql`!(${spatial})`;\n return scalar.physical.nullable ||\n this.#gatedHere(scalar.model, scalar.field)\n ? sql`(${column} != NONE AND ${asked})`\n : asked;\n }\n const bind = (value: unknown): Sql =>\n this.value(scalar.model, scalar.field, value);\n const guards: Sql[] = [];\n const operandOf = (\n operand: NonNullable<typeof predicate.operand>\n ): unknown => {\n if (operand.kind === \"field\") {\n const read = operand.scalar;\n const other = sql.raw(\n `${this.#rowAbove(operand.up, path)}${this.physical(read.model, read.field).toStatement()}`\n );\n if (read.physical.nullable) guards.push(sql`${other} != NONE`);\n // A key is a record and a plain column its text: they compare by the text.\n return this.isRecord(read.model, read.field)\n ? sql`record::id(${other})`\n : other;\n }\n if (operand.kind === \"parameter\")\n return this.#queries.callValue(operand.parameter);\n if (operand.kind !== \"value\") refuse(`a '${operand.kind}' operand`);\n return operand.value;\n };\n if (predicate.operand === undefined && operator === \"isNull\")\n return sql`${column} ${sql.raw(positive ? \"=\" : \"!=\")} NONE`;\n const value =\n predicate.operand === undefined\n ? predicate.value\n : operandOf(predicate.operand);\n if (operator === \"equals\" && value === null)\n return sql`${column} ${sql.raw(positive ? \"=\" : \"!=\")} NONE`;\n const fold = (text: Sql) =>\n predicate.insensitive ? sql`string::lowercase(${text})` : text;\n // A key or a link is a record, and its text is what a pattern or a case reads.\n const isRecord = this.isRecord(scalar.model, scalar.field);\n const asText = isRecord\n ? sql`<string>record::id(${column})`\n : this.#queries.keyOrder(scalar.model).includes(scalar.field)\n ? sql`<string>${column}`\n : column;\n const comparedToField =\n predicate.operand?.kind === \"field\" ||\n predicate.operands?.some((operand) => operand.kind === \"field\");\n // What a decimal range reads is the record itself: see #numeric.\n const record = column;\n if (comparedToField && isRecord) column = sql`record::id(${column})`;\n const read = predicate.insensitive ? asText : column;\n const compared = (member: unknown) =>\n predicate.insensitive && isRecord\n ? sql`string::lowercase(${member})`\n : fold(bind(member));\n let test: Sql;\n if (\n COMPARISONS[operator] &&\n operator !== \"equals\" &&\n this.#namesDecimal(scalar.model, scalar.field)\n ) {\n test = sql`${this.#numeric(record, false)} ${sql.raw(COMPARISONS[operator])} ${this.#decimalOperand(value)}`;\n } else if (COMPARISONS[operator]) {\n test = sql`${fold(read)} ${sql.raw(COMPARISONS[operator])} ${compared(value)}`;\n } else if (FUNCTIONS[operator]) {\n test = sql`${sql.raw(FUNCTIONS[operator])}(${fold(asText)}, ${fold(sql`${value}`)})`;\n } else if (operator === \"has\") {\n if (value === null) return sql.raw(positive ? \"false\" : \"true\");\n test = sql`${column} CONTAINS ${sql`${stored({ ...facts, array: false }, value)}`}`;\n } else if (operator === \"hasEvery\") {\n if ((value as unknown[]).length === 0)\n return sql`${column} ${sql.raw(positive ? \"!=\" : \"=\")} NONE`;\n test = sql`${column} CONTAINSALL ${bind(value)}`;\n } else if (operator === \"hasSome\") {\n if ((value as unknown[]).length === 0)\n return sql.raw(positive ? \"false\" : \"true\");\n test = sql`${column} CONTAINSANY ${bind(value)}`;\n } else if (operator === \"isEmpty\") {\n // A list that is not there counts as empty, on every dialect.\n const empty = sql`array::len(${column} ?? []) ${sql.raw(value ? \"=\" : \">\")} 0`;\n return positive ? empty : sql`!(${empty})`;\n } else if (operator === \"in\" || operator === \"notIn\") {\n // A call's list is the list, as one value of the caller's would be.\n const list = predicate.operands\n ? predicate.operands.flatMap((operand) => {\n const read = operandOf(operand);\n return operand.kind === \"parameter\" && Array.isArray(read)\n ? read\n : [read];\n })\n : (value as unknown[]);\n // An empty list asks nothing of the row, so a missing value does not matter.\n if (list.length === 0)\n return sql.raw((operator === \"notIn\") === positive ? \"true\" : \"false\");\n const bound = boundList(list.map(compared));\n test = sql`${fold(read)} ${sql.raw(operator === \"in\" ? \"IN\" : \"NOT IN\")} ${bound}`;\n } else {\n return refuse(`the '${operator}' operator`);\n }\n const nullable =\n scalar.physical.nullable || this.#gatedHere(scalar.model, scalar.field);\n const asked = positive ? test : sql`!(${test})`;\n const required = [...(nullable ? [sql`${column} != NONE`] : []), ...guards];\n return required.length\n ? sql`(${sql.join(required, \" AND \")} AND ${asked})`\n : asked;\n }\n\n /** A point's or a vector's own operators, which read no comparison below. */\n #spatial(\n predicate: Extract<PreparedPredicate, { kind: \"operation\" }>,\n column: Sql,\n facts: ScalarFacts\n ): Sql | undefined {\n const { operator, value } = predicate;\n if (operator === \"distance\") {\n const spec = value as Input;\n const distance = this.#distance(\n column,\n facts,\n predicate.target.scalar!.field,\n spec,\n \"filter\"\n );\n const bounds = [\"lt\", \"lte\", \"gt\", \"gte\"]\n .filter((bound) => spec[bound] !== undefined)\n .map(\n (bound) =>\n sql`${distance} ${sql.raw(COMPARISONS[bound]!)} ${spec[bound]}`\n );\n return sql`(${sql.join(bounds, \" AND \")})`;\n }\n if (facts.type !== \"point\" || facts.array) return undefined;\n const longitude = sql`${column}.coordinates[0]`;\n const latitude = sql`${column}.coordinates[1]`;\n if (operator === \"equals\") {\n if (value === null) return undefined;\n const point = value as GeoPointValue;\n // -180 and +180 are one meridian, whichever a writer stored.\n const meridian =\n point.longitude === 180\n ? sql`(${longitude} = 180 OR ${longitude} = -180)`\n : sql`${longitude} = ${point.longitude}`;\n return sql`(${meridian} AND ${latitude} = ${point.latitude})`;\n }\n if (operator !== \"within\") return undefined;\n const area = value as {\n readonly bounds?: {\n readonly north: number;\n readonly south: number;\n readonly east: number;\n readonly west: number;\n };\n readonly polygon?: {\n readonly outer: readonly GeoPointValue[];\n readonly holes?: readonly (readonly GeoPointValue[])[];\n };\n };\n if (area.polygon) {\n const { outer, holes = [] } = area.polygon;\n // `INTERSECTS` holds a polygon's boundary and not its holes, as PostGIS\n // does. Its plane has an edge at 180: a ring crossing it is unwrapped past\n // it, and a point read at both its longitudes.\n const crosses = [outer, ...holes].some((ring) =>\n ring.some(\n (point, index) =>\n Math.abs(\n point.longitude - ring[(index + 1) % ring.length]!.longitude\n ) > 180\n )\n );\n const coordinates = [outer, ...holes].map((ring) => {\n const points = ring.map((point) => [\n crosses && point.longitude < 0\n ? point.longitude + 360\n : point.longitude,\n point.latitude,\n ]);\n return [...points, points[0]!];\n });\n const polygon = sql`<geometry>${{ type: \"Polygon\", coordinates }}`;\n return crosses\n ? sql`(type::point([(IF ${longitude} < 0 { ${longitude} + 360 } ELSE { ${longitude} }), ${latitude}]) INTERSECTS ${polygon})`\n : sql`${column} INTERSECTS ${polygon}`;\n }\n const { north, south, east, west } = area.bounds!;\n const inLatitude = sql`${latitude} >= ${south} AND ${latitude} <= ${north}`;\n if (west === -180 && east === 180) return sql`(${inLatitude})`;\n const westArm = sql`${longitude} >= ${west}`;\n const eastArm = sql`${longitude} <= ${east}`;\n const arms = [\n west > east\n ? sql`(${westArm} OR ${eastArm})`\n : sql`(${westArm} AND ${eastArm})`,\n ...(west === -180 && east < 180 ? [sql`${longitude} = 180`] : []),\n ...(east === 180 && west > -180 ? [sql`${longitude} = -180`] : []),\n ];\n return sql`(${inLatitude} AND (${sql.join(arms, \" OR \")}))`;\n }\n\n #distance(\n column: Sql,\n facts: ScalarFacts & { readonly dimension?: number },\n field: string,\n spec: Input,\n usage: string\n ): Sql {\n if (facts.type === \"point\") {\n const to = spec.to as GeoPointValue;\n return sql`(IF ${column} != NONE { geo::distance(${column}, ${geometry(to)}) } ELSE { NONE })`;\n }\n const to = spec.to as number[];\n if (facts.dimension !== undefined && to.length !== facts.dimension)\n throw new UnsupportedOperationError(\n `Vector distance ${usage} dimension mismatch for '${field}': expected ${facts.dimension} values, received ${to.length}.`\n );\n // A zero vector has no direction, so no cosine: NONE, as PostgreSQL's NULL.\n if (spec.metric === \"cosine\")\n return sql`(IF ${column} != NONE AND vector::magnitude(${column}) > 0 { 1 - vector::similarity::cosine(${column}, ${to}) } ELSE { NONE })`;\n return sql`(IF ${column} != NONE { vector::distance::euclidean(${column}, ${to}) } ELSE { NONE })`;\n }\n\n /** A JSON filter: a missing path answers neither a test nor its negation. */\n #jsonOperation(\n predicate: Extract<PreparedPredicate, { kind: \"operation\" }>,\n column: Sql,\n positive: boolean\n ): Sql {\n const { target, operator, value, insensitive } = predicate;\n const steps = target.kind === \"column\" ? (target.path ?? []) : [];\n const at = steps.reduce(jsonStep, column);\n const answer = (test: Sql, reads: Sql = at) =>\n positive ? test : sql`(${reads} != NONE AND !(${test}))`;\n // A value this operator cannot compare answers neither it nor its negation.\n const typed = (guard: Sql, test: Sql) =>\n sql`(${guard} AND ${positive ? test : sql`!(${test})`})`;\n const text = (fn: string) => {\n const fold = (member: Sql) =>\n insensitive ? sql`string::lowercase(${member})` : member;\n return typed(\n sql`type::is_string(${at})`,\n sql`${sql.raw(fn)}(${fold(at)}, ${fold(sql`${value}`)})`\n );\n };\n const isArray = sql`type::is_array(${at})`;\n switch (operator) {\n case \"equals\": {\n const sentinel = jsonNullKindOf(value);\n if (sentinel === \"DbNull\" || (value === null && steps.length === 0))\n return sql`${column} ${sql.raw(positive ? \"=\" : \"!=\")} NONE`;\n if (sentinel === \"JsonNull\") return answer(sql`${at} = NULL`, column);\n if (sentinel)\n return answer(sql`(${column} = NONE OR ${at} = NULL)`, column);\n return answer(sql`${at} = ${value}`);\n }\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\": {\n const kind = typeof value === \"number\" ? \"number\" : \"string\";\n return typed(\n sql`${sql.raw(`type::is_${kind}`)}(${at})`,\n sql`${at} ${sql.raw(COMPARISONS[operator]!)} ${value}`\n );\n }\n case \"string_contains\":\n return text(\"string::contains\");\n case \"string_starts_with\":\n return text(\"string::starts_with\");\n case \"string_ends_with\":\n return text(\"string::ends_with\");\n case \"array_contains\":\n return typed(\n isArray,\n sql`${at} CONTAINSALL ${Array.isArray(value) ? value : [value]}`\n );\n case \"array_starts_with\":\n return typed(isArray, sql`${at}[0] = ${value}`);\n case \"array_ends_with\":\n return typed(isArray, sql`array::last(${at}) = ${value}`);\n default:\n return refuse(`the '${operator}' operator`);\n }\n }\n\n /** A key or a link is a record: its value is bound as one, never as a string. */\n value(model: AnyModel, field: string, value: unknown): Sql {\n const q = this.#queries;\n // A value this statement reads for itself ({@link SurrealQueries.locatedValue}):\n // a record, where a private column holds its key.\n if (value instanceof Sql)\n return model[\"~\"].state.scalars[field]\n ? value\n : this.#carried(model, field, sql`record::id(${value})`);\n if (isSingleKey(q, model, field))\n return sql`${new RecordId(\n tableOf(model),\n (isIntegerKey(model, field) && typeof value === \"string\"\n ? Number(value)\n : keyPart(model, field, value)) as string\n )}`;\n // A view's field holds what its source's holds, bound as the source's\n // is. An aggregated view's columns hold values of their own scalars, its\n // key parts included (a key or a link of its source as the key's value).\n const facts = viewFacts(model);\n if (facts && !facts.aggregated)\n return this.value(facts.source, field, value);\n const link = facts ? undefined : this.#linkOf(model, field);\n // A variant relation's column holds the key itself, whichever model it names.\n if (link && !link.discriminator)\n return sql`${new RecordId(\n tableOf(link.target),\n keyPart(link.target, link.pairs[0]!.target, value) as string\n )}`;\n const sentinel = jsonNullKindOf(value);\n if (sentinel)\n return sentinel === \"JsonNull\" ? sql`${null}` : sql.raw(\"NONE\");\n const state = model[\"~\"].state.scalars[field]?.[\"~\"].state;\n return state\n ? sql`${stored(state, value)}`\n : sql`${this.#carriesText(model, field) && value !== null && value !== undefined ? String(value) : value}`;\n }\n\n #relationFilter(\n predicate: Extract<PreparedPredicate, { kind: \"relation\" }>,\n positive: boolean,\n path: string\n ): Sql {\n const edge = predicate.edge;\n const { quantifier } = predicate;\n const inner = predicate.predicate;\n if (predicate.closure) {\n if (path) refuse(\"a recursive filter through a to-one link\");\n const wanted = quantifier === \"some\" || quantifier === \"is\";\n const found = this.#closure(edge, predicate.closure, quantifier, inner);\n return wanted === positive ? found : sql`!(${found})`;\n }\n // As the SQL lowering's EXISTS and NOT EXISTS: a body-less `is` asks that no\n // related row exists (`author: null`), a body-less `isNot` that one does.\n const wanted =\n quantifier === \"some\" ||\n (quantifier === \"is\" && inner !== undefined) ||\n (quantifier === \"isNot\" && inner === undefined);\n const asked = this.#queries.scoped(\n edge.target,\n quantifier === \"every\" && inner\n ? ({ kind: \"not\", predicate: inner } as const)\n : inner,\n \"related\"\n );\n const heldLink =\n this.#judging &&\n this.#lets &&\n asked &&\n !predicate.link &&\n !readsAbove(asked) &&\n edge.kind === \"reference\" &&\n !edge.many &&\n edge.owner === \"source\" &&\n this.#linked(edge);\n if (heldLink && this.#walksForward(asked)) {\n // One row's link is one read, where a list of all that hold is many.\n const link = `${path}${this.physical(edge.source, edge.pairs[0]!.source).toStatement()}`;\n const inner = this.predicate(asked, true, `${link}.`);\n // A list holds nothing unset, so asking is enough, and a scan can stop early.\n const held = onlyLists(asked)\n ? inner\n : sql`(${sql.raw(link)} != NONE AND ${inner})`;\n return wanted === positive ? held : sql`!(${held})`;\n }\n if (heldLink && !path) {\n const targets = this.#hoist(\n this.#selecting(edge.target, sql.raw(\"id\"), asked)\n )!;\n const held = sql`${this.physical(edge.source, edge.pairs[0]!.source)} IN ${targets}`;\n return wanted === positive ? held : sql`!(${held})`;\n }\n // A row above stays in its own statement: a list hoisted out of it has no such row.\n const holders =\n (!path || this.#judging) &&\n asked &&\n predicate !== this.#walking &&\n !readsAbove(asked) &&\n this.#holders(predicate, asked);\n if (holders) {\n const held = this.#hoist(holders.list(holders.rows()))!;\n return sql`${sql.raw(path ? path.slice(0, -1) : \"id\")} ${sql.raw(wanted === positive ? \"IN\" : \"NOT IN\")} ${held}`;\n }\n if (predicate.link) this.#queries.refuseHiddenLink(edge, predicate);\n const above = `$above${this.#above.length}`;\n this.#above.push(above);\n let found: Sql;\n try {\n found =\n edge.kind === \"junction\" && edge.declared\n ? this.#relatedThrough(edge, quantifier, inner, predicate.link, path)\n : this.#related(edge, quantifier, inner, path);\n } finally {\n this.#above.pop();\n }\n const row = path ? `$this.${path.slice(0, -1)}` : \"$this\";\n const within =\n asked && readsAbove(asked)\n ? sql`({ LET ${sql.raw(above)} = ${sql.raw(row)}; ${found} })`\n : found;\n return wanted === positive ? within : sql`!(${within})`;\n }\n\n /**\n * The records holding a relation to the rows a body holds of, walked from those\n * rows: a list computed once, however many rows the statement then reads. `rows`\n * reads what each body row holds, and `list` makes those one list of records.\n */\n #holders(\n filter: Extract<PreparedPredicate, { kind: \"relation\" }>,\n body: PreparedPredicate\n ):\n | {\n readonly rows: (limit?: number) => Sql;\n readonly list: (rows: Sql) => Sql;\n }\n | undefined {\n const edge = filter.edge;\n // A view's rows are its source's records under its own table, which no\n // holder a link or an edge names: they are asked row by row.\n if (!this.#lets || filter.closure || filter.link || viewFacts(edge.source))\n return undefined;\n const target = edge.target;\n const distinct = (rows: Sql) => sql`array::distinct(${rows})`;\n const flat = (rows: Sql) => sql`array::flatten(${rows})`;\n if (edge.kind === \"junction\") {\n if (edge.declared) return undefined;\n const { back } = this.edgeOf(edge);\n return {\n rows: (limit) =>\n this.#selecting(\n target,\n sql`${back}${name(tableOf(edge.source))}`,\n body,\n limit\n ),\n list: (rows) => distinct(flat(rows)),\n };\n }\n const held = reference(edge);\n if (!this.#linked(held)) return undefined;\n const { source, target: holder } = held.pairs[0]!;\n if (held.owner === \"source\")\n return {\n // Counting toward a limit reads the index on the link, which stops at it:\n // from each target, one with many holders would be read whole.\n rows: (limit) =>\n limit === undefined\n ? this.#selecting(\n target,\n sql`<~(${name(tableOf(held.source))} FIELD ${name(this.#queries.columnName(held.source, source))})`,\n body\n )\n : sql`(SELECT VALUE id FROM ${name(tableOf(held.source))} WHERE ${this.physical(held.source, source)} IN ${this.#hoist(this.#selecting(target, sql.raw(\"id\"), body))!} LIMIT ${sql.raw(String(limit))})`,\n list: flat,\n };\n const column = name(this.#queries.columnName(target, holder));\n return {\n rows: (limit) => this.#selecting(target, column, body, limit),\n list: distinct,\n };\n }\n\n /** `SELECT VALUE` over the rows a predicate holds of, driven as a statement is. */\n #selecting(\n model: AnyModel,\n value: Sql,\n body: PreparedPredicate,\n limit?: number\n ): Sql {\n const { from, rest } = this.#driven(model, body);\n return sql`(SELECT VALUE ${value} FROM ${from}${\n rest ? sql` WHERE ${this.predicate(rest, true)}` : sql.raw(\"\")\n }${limit === undefined ? sql.raw(\"\") : sql.raw(` LIMIT ${limit}`)})`;\n }\n\n /**\n * Where a statement reads its rows: the table, or a relation filter's holders\n * when every row must be one of them, which then reads only those.\n */\n #driven(\n model: AnyModel,\n predicate: PreparedPredicate | undefined,\n paged = false\n ): {\n readonly from: Sql;\n readonly rest: PreparedPredicate | undefined;\n /** A page may need fewer rows than the list holds: read only so far ahead. */\n readonly ahead?: { readonly rows: Sql; readonly arm: PreparedPredicate };\n /** `from` is the one record the filter names, and `rest` asks more of it. */\n readonly named?: boolean;\n } {\n const table = name(tableOf(model));\n if (!(predicate && this.#lets)) return { from: table, rest: predicate };\n // A row named by its key is read, and its links followed.\n if (this.#namesOneRow(model, predicate)) {\n const named = this.namedRecord(model, predicate);\n return named\n ? { from: named.record, rest: named.rest, named: true }\n : { from: table, rest: predicate };\n }\n const flat = (node: PreparedPredicate): PreparedPredicate[] =>\n node.kind === \"and\" ? node.predicates.flatMap(flat) : [node];\n const arms = flat(predicate);\n /** A list, where `arm` is a relation filter some row can hold. */\n const listed = (arm: PreparedPredicate) => {\n if (\n arm.kind !== \"relation\" ||\n !arm.predicate ||\n (arm.quantifier !== \"some\" && arm.quantifier !== \"is\")\n )\n return undefined;\n // Among the rows this call may see of them, as a filter reads them anywhere.\n const asked = this.#queries.scoped(\n arm.edge.target,\n arm.predicate,\n \"related\"\n )!;\n // A row above stays in its own statement: a list hoisted out of it has no such row.\n if (readsAbove(asked)) return undefined;\n const holders = this.#holders(arm, asked);\n if (!holders) return undefined;\n if (!paged) return { from: this.#hoist(holders.list(holders.rows()))! };\n const rows = this.#hoist(holders.rows(HOLDERS_AHEAD))!;\n return {\n from: this.#hoist(holders.list(rows))!,\n ahead: { rows, arm },\n };\n };\n const without = (at: number) => {\n const others = arms.filter((_, position) => position !== at);\n return others.length\n ? ({ kind: \"and\", predicates: others } as const)\n : undefined;\n };\n for (const [index, arm] of arms.entries()) {\n if (arm.kind !== \"layer\") {\n const found = listed(arm);\n if (found) return { ...found, rest: without(index) };\n continue;\n }\n // A rule's own arms read as its layer reads them, with what is left of it kept.\n const resolved = this.#queries.resolved(arm);\n if (!resolved) continue;\n const inner = flat(resolved);\n for (const [position, candidate] of inner.entries()) {\n let found: ReturnType<typeof listed>;\n this.#queries.layer(arm, () => {\n found = listed(candidate);\n return sql.raw(\"\");\n });\n if (!found) continue;\n const left: PreparedPredicate = {\n kind: \"and\",\n predicates: inner.filter((_, at) => at !== position),\n };\n const others = arms.filter((_, at) => at !== index);\n // What is left of the layer is what it resolved to for this call, less the arm taken.\n const kept: PreparedPredicate[] = left.predicates.length\n ? [...others, { ...arm, predicate: left, resolve: () => left }]\n : others;\n return {\n ...(found as NonNullable<typeof found>),\n rest: kept.length ? { kind: \"and\", predicates: kept } : undefined,\n };\n }\n }\n return { from: table, rest: predicate };\n }\n\n /** Whether a link and the row it names hold what a quantifier asks, together. */\n #relatedThrough(\n edge: Junction,\n quantifier: string,\n inner: PreparedPredicate | undefined,\n link: PreparedPredicate | undefined,\n path: string\n ): Sql {\n if (path) refuse(\"a filter through a to-one link into a declared junction\");\n const narrowed =\n quantifier === \"every\" && inner\n ? ({ kind: \"not\", predicate: inner } as const)\n : inner;\n const named = this.linkTarget(edge, edge.targetSide, \"\");\n // `every` over a pair: no link of this row fails the link's test and the\n // row's together. Their halves cannot answer it one after the other.\n if (quantifier === \"every\" && link) {\n const fails = [\n this.predicate(link, false, \"$l.\"),\n ...(inner\n ? [\n sql`array::len(SELECT VALUE id FROM ${name(tableOf(edge.target))} WHERE id = ${this.linkTarget(edge, edge.targetSide, \"$l\")} AND ${this.predicate(inner, false)} LIMIT 1) > 0`,\n ]\n : []),\n ];\n return sql`({ LET $owner = $this; array::len(${this.#links(edge, \"$owner\")}.filter(|$l| ${sql.join(fails, \" OR \")})) > 0 })`;\n }\n const rows = narrowed\n ? sql`SELECT VALUE id FROM ${name(tableOf(edge.target))} WHERE id IN $linked AND ${this.predicate(narrowed, true)} LIMIT 1`\n : sql.raw(\"SELECT VALUE id FROM $linked LIMIT 1\");\n return sql`({ LET $owner = $this; LET $linked = (SELECT VALUE ${named} FROM ${this.#links(edge, \"$owner\", link)}); array::len(${rows}) > 0 })`;\n }\n\n /** Whether the rows a walk from this one reaches hold what a quantifier asks. */\n #closure(\n edge: Membership,\n closure: { readonly depth: number | false; readonly self: boolean },\n quantifier: string,\n inner: PreparedPredicate | undefined\n ): Sql {\n const narrowed =\n quantifier === \"every\" && inner\n ? ({ kind: \"not\", predicate: inner } as const)\n : inner;\n const test = (rows: Sql) =>\n narrowed\n ? sql`array::len(SELECT VALUE id FROM ${rows} WHERE ${this.predicate(narrowed, true)} LIMIT 1) > 0`\n : sql`array::len(${rows}) > 0`;\n const scope = this.#queries.scoped(edge.target, undefined, \"related\");\n const args = (scope ? { selector: { predicate: scope } } : {}) as never;\n // Without `self`, a link's first step is the row's own value: a judged row's\n // is the one it would leave, not the one stored.\n const root =\n edge.kind === \"reference\" && edge.owner === \"source\" && !closure.self\n ? sql.raw(\"$this\")\n : this.#walkRoot(edge);\n const recursion =\n closure.depth === false\n ? this.#reached(edge, args, sql.raw(\"$root\"))\n : undefined;\n if (recursion)\n return sql`({ LET $root = ${root}; LET $r = ${recursion}; ${test(closure.self ? sql.raw(\"array::concat([$root], $r)\") : sql.raw(\"$r\"))} })`;\n const walk = this.#walk(edge, args, closure.depth, sql.raw(\"$root\"));\n const reached = closure.self\n ? sql.raw(\"array::concat([$root], $w.edges.c)\")\n : sql.raw(\"$w.edges.c\");\n return sql`({ ${this.#walked(walk, root)} ${test(reached)} })`;\n }\n\n /** Whether a related row exists, among those the quantifier looks at. */\n #related(\n relation: Membership,\n quantifier: string,\n inner: PreparedPredicate | undefined,\n path: string\n ): Sql {\n const narrowed = this.#queries.scoped(\n relation.target,\n quantifier === \"every\" && inner\n ? ({ kind: \"not\", predicate: inner } as const)\n : inner,\n \"related\"\n );\n if (relation.kind === \"junction\") {\n if (path) refuse(\"a to-many filter through a to-one link\");\n const { from, hop } = this.edgeOf(relation);\n const target = name(tableOf(relation.target));\n return narrowed\n ? sql`${from}${hop}(${target} WHERE ${this.predicate(narrowed, true)})`\n : sql`${from}${hop}${target}`;\n }\n const edge = reference(relation);\n if (!edge.many && edge.owner === \"source\" && this.#linked(edge)) {\n const link = `${path}${name(this.#queries.columnName(edge.source, edge.pairs[0]!.source)).toStatement()}`;\n if (narrowed && walksFurther(narrowed))\n return sql`(${sql.raw(link)} != NONE AND array::len(SELECT VALUE id FROM ${sql.raw(`$this.${link}`)} WHERE ${this.predicate(narrowed, true)}) > 0)`;\n return narrowed\n ? sql`(${sql.raw(link)} != NONE AND ${this.predicate(narrowed, true, `${link}.`)})`\n : sql`${sql.raw(link)} != NONE`;\n }\n if (path) refuse(\"a to-many filter through a to-one link\");\n // A non-empty list holds, in one parser level fewer than asking for its length.\n return this.#traversal(edge, narrowed, { take: 1 });\n }\n}\n","/**\n * `docs/architecture/query-backend-frontier.md` step 5.\n *\n * `Commands` locates and captures rows through `Queries.select`, so a nested\n * write reads through this. Everything else it asks of `Queries` is shared.\n */\n\nimport type { Dialect } from \"@drivers/types\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport type { ModelSql } from \"@query-engine/raptor3/shared/insert-value\";\nimport {\n type PreparedDomain,\n type PreparedPredicate,\n type PreparedProjection,\n type PreparedSelector,\n Queries,\n type Query,\n type SelectControls,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n CallScope,\n Condition,\n Parameter,\n RowPurpose,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Arguments, Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { Membership } from \"@query-engine/raptor3/shared/storage\";\nimport { viewFacts } from \"@schema/view/facts\";\nimport { Sql, sql } from \"@sql\";\nimport { SurrealReadBackend } from \"./read-backend\";\n\ntype AnyModel = Parameters<Queries[\"select\"]>[0];\n\nfunction refuse(what: string): never {\n throw new UnsupportedOperationError(\n `The SurrealDB write backend does not support ${what} yet.`\n );\n}\n\nexport class SurrealQueries extends Queries {\n /**\n * A view (`DEFINE TABLE … AS SELECT … FROM <source>`) keys each of its rows\n * by its source record's id, under its own table (measured on SurrealDB\n * 4.0: `v:p1` for `t:p1`, an array id kept whole). So a view's record holds\n * its source's key, whether or not its query projects it, and every key\n * part is read where the source's is: a view's key order is its source's.\n * An aggregated view's row is a group, which the database ids by the list\n * of its `by` values (`v:[1, 'EUR']`): its key order is its `by` list, a\n * nullable member included (a group of NONE is `v:[NONE]`).\n */\n override keyOrder(model: AnyModel): readonly string[] {\n const facts = viewFacts(model);\n if (facts === undefined) return super.keyOrder(model);\n return facts.aggregated?.by ?? this.keyOrder(facts.source);\n }\n\n /** `id` is the record's: a field of that name beside a key of another lives apart. */\n override columnName(model: AnyModel, field: string): string {\n const column = super.columnName(model, field);\n return column === \"id\" && !this.keyOrder(model).includes(field)\n ? \"id_field\"\n : column;\n }\n\n /** A caller's filter on a link row is a test of what a direct read could hide. */\n refuseHiddenLink(\n edge: Membership,\n filter: { readonly linkFields?: readonly string[] }\n ): void {\n if (!this.lowersLayer)\n this.domain?.refuseHiddenLinkRow(\n this,\n edge,\n filter.linkFields!,\n \"filter\"\n );\n }\n\n override under(domain: PreparedDomain, call?: CallScope): Queries {\n return new SurrealQueries(\n this.schema,\n this.adapter,\n this.result,\n domain,\n call\n );\n }\n\n /** A layer's predicate for this call, read while it lowers: `undefined` where it drops. */\n /** A layer's predicate for this call, `undefined` where the call drops it. */\n resolved(\n node: Extract<PreparedPredicate, { kind: \"layer\" }>\n ): PreparedPredicate | undefined {\n return node.resolve(this);\n }\n\n layer(\n node: Extract<PreparedPredicate, { kind: \"layer\" }>,\n lower: (resolved: PreparedPredicate) => Sql\n ): Sql | undefined {\n const resolved = node.resolve(this);\n if (resolved === undefined) return undefined;\n const excluded = (this.excluded ??= []);\n excluded.push(node.layer);\n try {\n return lower(resolved);\n } finally {\n excluded.pop();\n }\n }\n\n /** `predicate` among the rows this call may see for `purpose`. */\n scoped(\n model: AnyModel,\n predicate: PreparedPredicate | undefined,\n purpose: RowPurpose\n ): PreparedPredicate | undefined {\n const scope = this.scope(model, purpose)?.predicate;\n if (scope === undefined) return predicate;\n return predicate === undefined\n ? scope\n : { kind: \"and\", predicates: [predicate, scope] };\n }\n\n /** Whether a layer's predicates are lowering here, which read every column as it is. */\n get lowersLayer(): boolean {\n return (this.excluded?.length ?? 0) > 0;\n }\n\n /** The order this call's extensions give a read that states none. */\n orderOf(model: AnyModel): Arguments[\"orderBy\"] {\n return this.defaultOrder(model);\n }\n\n /** What a call's value is, in a domain's condition or operand. */\n callValue(parameter: Parameter): unknown {\n return parameter.read(this.values, this.instant);\n }\n\n holds(condition: Condition): boolean {\n return condition.holds(this.values, this.instant);\n }\n\n override read(\n model: AnyModel,\n operation: Parameters<Queries[\"read\"]>[1],\n args: Arguments\n ) {\n return this.lowering.read(model, operation, args);\n }\n\n /** These spell a statement's parts, and only a statement written whole is read here. */\n override updateAssignment(): Sql {\n return refuse(\"an assignment spelled apart from its statement\");\n }\n\n override lowerSelector(): Sql | undefined {\n return refuse(\"a condition spelled apart from its statement\");\n }\n\n spelling(model: AnyModel, dialect: Dialect): ModelSql {\n const low = this.lowering;\n return {\n dialect,\n table: () => sql.raw(model[\"~\"].names.sql!),\n column: (field) => low.physical(model, field),\n value: (field, value) => low.value(model, field, value),\n name: (...path) => sql.raw(path.join(\".\")),\n visible: (_alias, options) => {\n if (options?.update)\n throw new UnsupportedOperationError(\n \"SurrealDB: the rows a call may update are not a condition yet\"\n );\n const seen = this.scoped(\n model,\n options?.where === undefined\n ? undefined\n : this.prepareSelector(\n model,\n this.schema.admit(model, \"findMany\", {\n where: options.where as Input,\n }).where as Input\n ).predicate,\n \"root\"\n );\n return seen ? low.predicate(seen, true) : sql.raw(\"true\");\n },\n };\n }\n\n #backend: SurrealReadBackend | undefined;\n\n /** What spells this call's reads, and the parts of its writes that read: one, so that what a statement computes ahead of itself is stated once. */\n get lowering(): SurrealReadBackend {\n this.#backend ??= new SurrealReadBackend(this);\n return this.#backend;\n }\n\n /** A field of the row `selector` names, read inside the statement that spends it. */\n override locatedValue(\n model: AnyModel,\n field: string,\n selector: PreparedSelector\n ): Sql {\n const where = selector.predicate\n ? sql`WHERE ${this.lowering.predicate(selector.predicate, true)} `\n : sql.raw(\"\");\n return sql`(SELECT VALUE ${this.lowering.physical(model, field)} FROM ${sql.raw(model[\"~\"].names.sql!)} ${where}LIMIT 1)[0]`;\n }\n\n /** Rows a write named, by key, in the order it named them: a list reads so. */\n override selectSeries(\n prepared: PreparedProjection,\n identities: Input[],\n operation: \"createMany\" | \"updateMany\" = \"createMany\"\n ): Query {\n const { model } = prepared;\n const records = sql.join(\n identities.map((identity) => this.lowering.recordOfRow(model, identity)),\n \", \"\n );\n return {\n sql: sql`SELECT ${this.lowering.columns(prepared)} FROM [${records}]`,\n shape: prepared.shape,\n expectedRows: this.seriesExpectation(model, identities.length, operation),\n };\n }\n\n /**\n * `forUpdate` reads as it is: SurrealDB takes no lock, and a transaction that\n * writes a row another committed fails at its own commit.\n */\n override select(\n model: AnyModel,\n args: Partial<Arguments>,\n membership?: { edge: Membership; parent: Input },\n controls: SelectControls = {}\n ): Query {\n if (controls.source) refuse(\"a read over a write's own rows\");\n const projection =\n controls.projection ?? this.prepareProjection(model, args);\n const given = controls.selector\n ? controls.selector.predicate\n : args.where === undefined\n ? undefined\n : this.prepareSelector(model, args.where).predicate;\n const predicate = controls.purpose\n ? this.scoped(model, given, controls.purpose)\n : given;\n // A path reads a record's members without scanning the table holding them.\n const path =\n membership?.edge.kind === \"junction\" && !membership.edge.declared\n ? this.lowering.membersOf(membership.edge, membership.parent)\n : undefined;\n // A whole key stated as values is the record itself, read without a filter.\n const identity = controls.identity;\n const record =\n identity &&\n !path &&\n this.keyOrder(model).every(\n (key) => identity[key] != null && !(identity[key] instanceof Sql)\n )\n ? this.lowering.recordOfRow(model, identity)\n : undefined;\n const conditions = () => [\n ...(membership && !path\n ? [this.lowering.member(membership.edge, membership.parent)]\n : []),\n ...(identity && !record ? [this.lowering.identity(model, identity)] : []),\n ...(controls.unless?.predicate\n ? [this.lowering.predicate(controls.unless.predicate, false)]\n : []),\n ];\n return {\n sql: this.lowering.hoisted(() =>\n this.lowering.statement(\n model,\n projection,\n record ? { ...args, unordered: true } : args,\n predicate,\n conditions(),\n path ?? record\n )\n ),\n shape: projection.shape,\n };\n }\n}\n","/**\n * A SurrealDB transaction that can go back.\n *\n * SurrealQL has no savepoints, and writers meet at commit, where the loser has\n * written nothing. Both are answered by the same record: every statement this\n * transaction ran, with what it answered. Going back is a new transaction running\n * those statements again.\n *\n * That is sound when every statement answers as it did: nothing the caller was\n * told has changed, so it cannot tell this transaction from one that began later.\n * A different answer ends it with a conflict, since what the caller decided from\n * no longer holds. The new transaction sees newer rows, so a read is checked as\n * strictly as a write. Holding the answers costs no work until they are compared.\n */\n\nimport { TransactionError } from \"@errors\";\nimport type { Surreal, SurrealTransaction } from \"surrealdb\";\nimport { acquireWithMaxWait } from \"../shared/transaction-options\";\n\nconst CONFLICT = /can be retried|read or write conflict/;\n\n/** What a statement throws where a row it would leave is not permitted. */\nexport const FORBIDDEN_ROW = \"viborm: a row this write leaves is not permitted\";\n\n/** What a text sent whole throws where one of its statements asks what is not so. */\nexport const STOPPED = \"viborm: what this write asks is not so\";\n\n/** Two transactions that met at commit, in the words SurrealDB has for it. */\nexport function isConflict(error: unknown): boolean {\n return (\n error instanceof Error &&\n (CONFLICT.test(error.message) ||\n (error.cause instanceof Error && CONFLICT.test(error.cause.message)))\n );\n}\n\n/**\n * What may write wherever it stands in a text: a statement, a subquery or a block\n * (keywords are any case), or a function defined in the database or a module.\n */\nconst MAY_WRITE =\n /\\b(?:CREATE|UPDATE|UPSERT|DELETE|INSERT|RELATE|DEFINE|REMOVE|ALTER|REBUILD)\\b|\\b(?:fn|mod|silo|api)::/i;\nconst SELECTS = /^SELECT\\b/i;\n/** The form that reports a conflict by answering nothing, having written nothing. */\nconst IGNORES_CONFLICT = /^INSERT IGNORE\\b/i;\n/** A clause after which an insert answers nothing, whether it wrote or not. */\nconst ANSWERS_NOTHING = /\\bRETURN\\s+(?:NONE|BEFORE|VALUE\\s+NONE)\\b/i;\nconst NEXT_VALUE = /sequence::nextval\\(\\$(p\\d+)\\)/g;\n\n/** Each attempt is won by someone, so this bounds the writers that can meet at once. */\nexport const COMMITS = 16;\n\n/**\n * The wait after attempt `attempt` met another writer at its commit: at random,\n * since two losers running again together would only meet again, below a\n * ceiling that doubles from 20 ms to 1 s. Over {@link COMMITS} attempts that is\n * about 5 s in all (10 s at most), where a ceiling of 10 ms per attempt gave a\n * writer still busy after a second no chance to finish.\n */\nexport const backOff = (attempt: number): Promise<void> =>\n new Promise((resolve) =>\n setTimeout(resolve, Math.random() * Math.min(1000, 10 * 2 ** attempt))\n );\n\ninterface Statement {\n text: string;\n values: Record<string, unknown>;\n /** Absent when it failed, having perhaps written part of its change. */\n answer?: unknown;\n}\n\n/**\n * A read that writes nowhere in its text, or one ignored insert, alone in its text,\n * that answers no row although it answers each row it writes.\n */\nconst wroteNothing = ({ text, answer }: Statement) => {\n if (SELECTS.test(text)) return !MAY_WRITE.test(text);\n const rest = text.replace(IGNORES_CONFLICT, \"\");\n return (\n rest !== text &&\n !(MAY_WRITE.test(rest) || ANSWERS_NOTHING.test(rest)) &&\n Array.isArray(answer) &&\n answer.length === 1 &&\n Array.isArray(answer[0]) &&\n answer[0].length === 0\n );\n};\n\nconst asText = (answer: unknown) =>\n JSON.stringify(answer, (_key, value) =>\n typeof value === \"bigint\" ? `${value}n` : value\n );\n\n/**\n * A connection holds 64 open transactions and refuses the next (\"Too many open\n * transactions\"), so the others wait for one to end, as they would for a pool.\n */\nconst OPEN_TRANSACTIONS = 64;\n\nclass Slots {\n #free = OPEN_TRANSACTIONS;\n readonly #waiting: (() => void)[] = [];\n\n async take(): Promise<void> {\n if (this.#free > 0) {\n this.#free -= 1;\n return;\n }\n await new Promise<void>((resolve) => this.#waiting.push(resolve));\n }\n\n give(): void {\n const next = this.#waiting.shift();\n if (next) next();\n else this.#free += 1;\n }\n}\n\nconst slotsOf = new WeakMap<Surreal, Slots>();\n\nexport class ReplayedTransaction {\n readonly #client: Surreal;\n readonly #slots: Slots;\n #open: SurrealTransaction;\n #ended = false;\n readonly #log: Statement[] = [];\n #conflicted = false;\n\n private constructor(client: Surreal, slots: Slots, open: SurrealTransaction) {\n this.#client = client;\n this.#slots = slots;\n this.#open = open;\n }\n\n static async begin(\n client: Surreal,\n maxWaitMs?: number\n ): Promise<ReplayedTransaction> {\n let slots = slotsOf.get(client);\n if (!slots) {\n slots = new Slots();\n slotsOf.set(client, slots);\n }\n const held = slots;\n await acquireWithMaxWait(\n () => held.take(),\n () => held.give(),\n maxWaitMs,\n { driverName: \"surrealdb\", form: \"callback\" }\n );\n try {\n return new ReplayedTransaction(\n client,\n slots,\n await client.beginTransaction()\n );\n } catch (error) {\n slots.give();\n throw error;\n }\n }\n\n #end(): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#slots.give();\n }\n\n /** A concurrent write changed what it was told, whatever the caller then did. */\n get conflicted(): boolean {\n return this.#conflicted;\n }\n\n /** How far this transaction has come, to {@link rollbackTo} later. */\n get mark(): number {\n return this.#log.length;\n }\n\n async query<R>(text: string, values: Record<string, unknown>): Promise<R> {\n const statement: Statement = { text, values };\n // In the order they were sent, whichever answers first.\n this.#log.push(statement);\n await this.#reserveSequences(statement);\n statement.answer = await this.#open.query(statement.text, statement.values);\n return statement.answer as R;\n }\n\n /**\n * A sequence stands outside any transaction, so a statement running again would\n * take another value. Each is taken ahead instead, and the statement holds it.\n */\n async #reserveSequences(statement: Statement): Promise<void> {\n const taken = [...statement.text.matchAll(NEXT_VALUE)];\n if (taken.length === 0) return;\n const [reserved] = await this.#client.query<[unknown[]]>(\n `RETURN [${taken.map(([call]) => call).join(\", \")}]`,\n statement.values\n );\n const values = { ...statement.values };\n let index = 0;\n statement.text = statement.text.replace(NEXT_VALUE, () => {\n const name = `reserved${index}`;\n values[name] = reserved[index++];\n return `$${name}`;\n });\n statement.values = values;\n }\n\n /**\n * What a savepoint's rollback does: everything after `mark` never happened. Only\n * statements that cannot have written are left to stand without running the\n * others again, since the server refuses to commit over a partial write.\n */\n async rollbackTo(mark: number): Promise<void> {\n if (!this.#log.splice(mark).every(wroteNothing)) await this.#replay();\n }\n\n async #replay(): Promise<void> {\n await this.#open.cancel().catch(() => undefined);\n this.#open = await this.#client.beginTransaction();\n for (const statement of this.#log) {\n const answer = await this.#open.query(statement.text, statement.values);\n if (asText(answer) !== asText(statement.answer)) {\n this.#conflicted = true;\n throw new TransactionError(\n \"A concurrent write changed what this transaction read, so it cannot go on. This transaction can be retried.\"\n );\n }\n }\n }\n\n /** A write conflict leaves nothing applied, so the statements can run again. */\n async commit(): Promise<void> {\n try {\n for (let attempt = 1; ; attempt++) {\n try {\n await this.#open.commit();\n return;\n } catch (error) {\n if (!isConflict(error) || attempt === COMMITS) throw error;\n }\n await backOff(attempt);\n await this.#replay();\n }\n } catch (error) {\n // A replay that found another answer leaves its transaction open.\n await this.#open.cancel().catch(() => undefined);\n throw error;\n } finally {\n this.#end();\n }\n }\n\n async cancel(): Promise<void> {\n try {\n await this.#open.cancel();\n } finally {\n this.#end();\n }\n }\n}\n","/**\n * The write path's statements in SurrealQL. What a call means, which rows it\n * knows and in what order its statements go are the engine's\n * (`query-engine/raptor3/write`); here is only how each statement is said\n * where a record is its id, a many-to-many an edge, and a judged write a\n * block that refuses before it writes.\n */\n\nimport type { AnyDriver } from \"@drivers/exports\";\nimport {\n NestedWriteAssertionError,\n QueryEngineError,\n type UniqueConstraintError,\n UnsupportedOperationError,\n} from \"@errors\";\nimport { dividesByZero } from \"@query-engine/raptor3/shared/decimal\";\nimport { JoinedValue } from \"@query-engine/raptor3/shared/insert-value\";\nimport {\n type PreparedProjection,\n type PreparedSelector,\n wholeValue,\n} from \"@query-engine/raptor3/shared/query\";\nimport type { WriteJudgement } from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { SqlOperationContext } from \"@query-engine/raptor3/shared/sql-operation-context\";\nimport {\n linkJudgement,\n linkMembers,\n type Membership,\n} from \"@query-engine/raptor3/shared/storage\";\nimport {\n prepared,\n type Sent,\n type Statement,\n Stopped,\n} from \"@query-engine/raptor3/write/send\";\nimport {\n type Junction,\n type Question,\n Writer,\n} from \"@query-engine/raptor3/write/statements\";\nimport type { PreparedGuardFailure } from \"@query-engine/types\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport { viewFacts } from \"@schema/view/facts\";\nimport { Sql, sql } from \"@sql\";\nimport { Decimal, RecordId } from \"surrealdb\";\nimport { quantized } from \"./quantized\";\nimport type { SurrealQueries } from \"./queries\";\nimport {\n isOneValue,\n onceEach,\n type SurrealReadBackend,\n walksFurther,\n} from \"./read-backend\";\nimport { FORBIDDEN_ROW, isConflict, STOPPED } from \"./transaction\";\n\ntype AnyModel = PreparedProjection[\"model\"];\n\nconst ARITHMETIC: Readonly<Record<string, string>> = {\n increment: \"+\",\n decrement: \"-\",\n multiply: \"*\",\n divide: \"/\",\n};\n\n/**\n * A key a moved row can hold beside its old self: only what its field's type\n * admits, and nothing it could ever keep, since it is overwritten in that statement.\n */\nconst STAND_INS: Readonly<Record<string, Sql>> = {\n string: sql.raw(\"rand::string(32)\"),\n int: sql.raw(\"rand::int(-2147483648, 2147483647)\"),\n bigint: sql.raw(\"rand::int(-2147483648, 2147483647)\"),\n float: sql.raw(\"rand::float()\"),\n decimal: sql.raw(\"<decimal>rand::int(-2147483648, 2147483647)\"),\n datetime: sql.raw(\"time::from_millis(rand::int(0, 2147483647))\"),\n};\n\nconst JUDGED = sql.raw(`\"${FORBIDDEN_ROW}\"`);\nconst NOTHING = sql.raw(\"\");\n\n/** How many times a call is made again after meeting another at commit. */\nconst RERUNS = 16;\n\n/** A relation whose row holds a value of another in its own key. */\ntype FollowingEdge = Extract<Membership, { kind: \"reference\" }>;\n\n/** What a write holds at the top level ahead of itself, and what refuses with it. */\ninterface Ahead {\n readonly lets: Sql;\n readonly checks: Sql;\n}\n\nconst NOTHING_AHEAD: Ahead = { lets: NOTHING, checks: NOTHING };\n\n/** The parts of a text that say something, in order. */\nconst seq = (...parts: Sql[]): Sql =>\n sql.join(\n parts.filter((part) => part.toStatement() !== \"\"),\n \" \"\n );\n\nfunction refuse(what: string): never {\n throw new UnsupportedOperationError(\n `The SurrealDB write backend does not support ${what} yet.`\n );\n}\n\nconst fieldName = (identifier: string): Sql => sql.raw(identifier);\n\n/** A key part's value after arithmetic, computed here since a record's id is fixed. */\nfunction arithmetic(\n type: string,\n current: unknown,\n operator: string,\n operand: unknown\n): unknown {\n const zero = () => new QueryEngineError(\"Cannot divide a key by zero.\");\n if (type === \"decimal\") {\n const [a, b] = [new Decimal(String(current)), new Decimal(String(operand))];\n if (operator === \"divide\" && dividesByZero(operand)) throw zero();\n return (\n operator === \"increment\"\n ? a.add(b)\n : operator === \"decrement\"\n ? a.sub(b)\n : operator === \"multiply\"\n ? a.mul(b)\n : a.div(b)\n ).toString();\n }\n if (type === \"bigint\") {\n const [a, b] = [BigInt(String(current)), BigInt(String(operand))];\n if (operator === \"divide\" && b === 0n) throw zero();\n return operator === \"increment\"\n ? a + b\n : operator === \"decrement\"\n ? a - b\n : operator === \"multiply\"\n ? a * b\n : a / b;\n }\n if (type !== \"int\") refuse(`arithmetic on a key of type '${type}'`);\n const [a, b] = [Number(current), Number(operand)];\n if (operator === \"divide\" && b === 0) throw zero();\n return operator === \"increment\"\n ? a + b\n : operator === \"decrement\"\n ? a - b\n : operator === \"multiply\"\n ? a * b\n : Math.trunc(a / b);\n}\n\n/**\n * The relations whose links a model's records hold, which a write that moves\n * a key follows: a table's own. A view's rows are computed by the database\n * from its source's, so the source's links are the ones a write moves.\n */\nconst slotsHeld = (model: AnyModel): readonly string[] =>\n viewFacts(model) ? [] : Object.keys(model[\"~\"].state.relations);\n\n/**\n * One call on SurrealDB. A write's own statement answers any read of the\n * rows it writes: `RETURN` reads after the write, and a delete reads ahead\n * of itself. No locks: two writers meet at commit, and the loser, having\n * written nothing, is made again from what the winner committed.\n */\nexport class SurrealCall extends SqlOperationContext {\n /** A request of several statements failed: it does not say which, so the call is made again, each statement its own request. */\n #apart: boolean | undefined;\n\n override answersInStatement(): boolean {\n return true;\n }\n\n override async again(error: unknown, attempt: number): Promise<boolean> {\n if (isConflict(error)) {\n if (attempt === RERUNS) return false;\n // Two losers made again together would only meet again.\n await new Promise((resolve) =>\n setTimeout(resolve, 5 + Math.random() * 45 * attempt)\n );\n return true;\n }\n return this.#apart === false && (this.#apart = true);\n }\n\n /**\n * A text takes any number of statements, and answers each: sent as the\n * driver's batch, where each statement is still seen as its own.\n */\n override together(\n driver: AnyDriver,\n statements: readonly Statement[],\n whole: boolean\n ): Promise<Sent[]> | undefined {\n if (this.#apart) return undefined;\n return driver\n ._executeBatch<Input>(\n statements.map((statement) => {\n const { believed, probe, premise } = statement;\n const text = believed ? probe! : statement.sql;\n return prepared(this, driver, {\n ...statement,\n // In a text that is its own unit, what is asked stops the text where it is not so.\n sql:\n whole && text === probe\n ? sql`IF array::len({ ${text} }) ${sql.raw(premise === \"exists\" ? \"=\" : \">\")} 0 { THROW ${sql.raw(`\"${STOPPED}\"`)} }`\n : text,\n });\n }),\n undefined,\n this.attribution\n )\n .catch((error) => {\n this.#apart ??= false;\n throw error;\n });\n }\n}\n\nexport class SurrealWriter extends Writer {\n readonly #q: SurrealQueries;\n readonly #low: SurrealReadBackend;\n\n constructor(operation: SqlOperationContext, hears?: Writer[\"hears\"]) {\n super(operation, hears);\n this.#q = operation.queries as unknown as SurrealQueries;\n this.#low = this.#q.lowering;\n }\n\n /** Asks the database in the call's unit, before the statement being written is sent. */\n async #heard(statement: Sql, model: AnyModel): Promise<Input[]> {\n if (!this.hears) refuse(\"a write that reads before it writes, in a batch\");\n return (await this.hears(statement, model)) as Input[];\n }\n\n /** `INSERT IGNORE` answers with the rows it wrote: none is a row passed by, and nothing failed. */\n override get passes(): boolean {\n return true;\n }\n\n /** A question is asked as it is: its answer is heard, and nothing here fails to say no. */\n protected override asserts(probe: Sql): Sql {\n return probe;\n }\n\n override asks(\n asked: readonly (readonly [Question, (Input | Input[])?])[],\n believed: \"presumed\" | \"read\"\n ): Statement {\n const [first] = asked as [readonly [Question, (Input | Input[])?]];\n if (asked.length === 1) return super.asks(asked, believed);\n // One row answers where every question names one.\n const probe = this.#low.hoisted(\n () =>\n sql`SELECT true AS found FROM [0] WHERE ${sql.join(\n asked.map(\n (each) =>\n sql`array::len((${super.asks([each], believed).probe!})) > 0`\n ),\n \" AND \"\n )}`\n );\n return { ...super.asks([first], believed), sql: probe, probe };\n }\n\n /** One row as an object literal: an absent or null field stores nothing. */\n #row(model: AnyModel, row: Input): Sql {\n const members = this.#rowMembers(model, row).map(\n ([column, value]) => sql`${fieldName(column)}: ${value}`\n );\n return sql`{ ${sql.join(members, \", \")} }`;\n }\n\n /** A row's columns and what each holds, its record first. */\n #rowMembers(model: AnyModel, row: Input): [string, Sql][] {\n const keys = this.#q.keyOrder(model);\n const members = Object.entries(row)\n .filter(\n ([field, value]) =>\n value !== null && value !== undefined && !keys.includes(field)\n )\n .map(([field, value]): [string, Sql] => [\n this.#q.columnName(model, field),\n this.#low.value(model, field, value),\n ]);\n // Written here, not left to its default: a transaction reserves what it states.\n const { scalars } = model[\"~\"].state;\n const generated = Object.keys(scalars)\n .filter(\n (field) =>\n scalars[field]![\"~\"].state.autoGenerate?.kind === \"increment\" &&\n !keys.includes(field) &&\n row[field] === undefined\n )\n .map((field): [string, Sql] => {\n const column = this.#q.columnName(model, field);\n return [\n column,\n sql`sequence::nextval(${`${model[\"~\"].names.sql!}_${column}_seq`})`,\n ];\n });\n return [\n [\"id\", this.#recordKey(model, row, keys)],\n ...members,\n ...generated,\n ];\n }\n\n /**\n * One row created at its record, where the row states it. `INSERT` costs about\n * twice as much for one row, and refuses a taken record or a unique value in the\n * same words. A key a sequence gives, or the statement reads, is no record yet.\n */\n #created(model: AnyModel, row: Input): Sql | undefined {\n const [stated, ...members] = this.#rowMembers(model, row);\n const record = stated![1];\n if (!(isOneValue(record) && record.values[0] instanceof RecordId))\n return undefined;\n const content = members.every(([, value]) => isOneValue(value))\n ? sql`${Object.fromEntries(\n members.map(([column, value]) => [column, value.values[0]])\n )}`\n : sql`{ ${sql.join(\n members.map(([column, value]) => sql`${fieldName(column)}: ${value}`),\n \", \"\n )} }`;\n return sql`CREATE ${record} CONTENT ${content}`;\n }\n\n /** Rows as a list: one parameter, where each value of each is one. */\n #rows(model: AnyModel, rows: readonly Input[]): Sql {\n const members = rows.map((row) => this.#rowMembers(model, row));\n const held = members.every((row) =>\n row.every(([, value]) => isOneValue(value))\n );\n if (!held)\n return sql`[${sql.join(\n rows.map((row) => this.#row(model, row)),\n \", \"\n )}]`;\n return sql`${members.map((row) =>\n Object.fromEntries(\n row.map(([column, value]) => [column, value.values[0]])\n )\n )}`;\n }\n\n /** A row's id: what it states, or the next of its sequence. */\n #recordKey(model: AnyModel, row: Input, keys: readonly string[]): Sql {\n const next = (key: string, sequence: string) => {\n if (\n model[\"~\"].state.scalars[key]?.[\"~\"].state.autoGenerate?.kind !==\n \"increment\"\n )\n refuse(\"a key the database generates\");\n return sql`sequence::nextval(${sequence})`;\n };\n const table = model[\"~\"].names.sql!;\n if (keys.length === 1) {\n const given = row[keys[0]!];\n return given === undefined\n ? next(keys[0]!, `${table}_seq`)\n : this.#low.value(model, keys[0]!, given);\n }\n if (\n keys.every((key) => row[key] !== undefined && !(row[key] instanceof Sql))\n )\n return sql`${this.#low.recordOf(model, row)}`;\n const parts = keys.map((key) => {\n if (row[key] instanceof Sql) return row[key];\n if (row[key] !== undefined)\n return this.#low.keyPart(model, key, row[key]);\n return next(key, `${table}_${this.#q.columnName(model, key)}_seq`);\n });\n return sql`[${sql.join(parts, \", \")}]`;\n }\n\n #assignments(model: AnyModel, values: Input): Sql {\n return sql.join(\n this.#assigned(model, values).map(\n ({ column, value }) => sql`${column} = ${value}`\n ),\n \", \"\n );\n }\n\n /** Each field an update writes, and what it writes there. */\n #assigned(model: AnyModel, values: Input): { column: Sql; value: Sql }[] {\n const low = this.#low;\n return Object.entries(values).map(([field, given]) => {\n const column = low.physical(model, field);\n const whole = wholeValue(given);\n if (whole) {\n return {\n column,\n value:\n whole.value === null\n ? sql.raw(\"NONE\")\n : low.value(model, field, whole.value),\n };\n }\n const [operator, operand] = Object.entries(given as Input)[0]!;\n const state = model[\"~\"].state.scalars[field]?.[\"~\"].state;\n if (operator === \"push\" || operator === \"unshift\") {\n const members = low.value(model, field, [operand].flat());\n return {\n column,\n value:\n operator === \"push\"\n ? sql`array::concat(${column} ?? [], ${members})`\n : sql`array::concat(${members}, ${column} ?? [])`,\n };\n }\n const sign = ARITHMETIC[operator];\n if (!sign) refuse(`the '${operator}' update`);\n if (operator === \"divide\" && state?.decimal && dividesByZero(operand))\n throw new QueryEngineError(\n `Cannot divide decimal field '${field}' by zero.`\n );\n const computed = sql`${column} ${sql.raw(sign)} ${low.value(model, field, operand)}`;\n const change =\n operator === \"multiply\" || operator === \"divide\"\n ? quantized(state, computed)\n : computed;\n // SQL leaves NULL as it is, where NONE would refuse the arithmetic.\n return {\n column,\n value: state?.nullable\n ? sql`(IF ${column} = NONE { NONE } ELSE { ${change} })`\n : change,\n };\n });\n }\n\n /** What a write answers with: the rows as the call reads them, their ids where it counts them, or nothing. */\n #returning(\n projection: PreparedProjection | undefined,\n counted: boolean\n ): Sql {\n if (projection) return sql`RETURN ${this.#low.columns(projection)}`;\n return sql.raw(counted ? \"RETURN id\" : \"RETURN NONE\");\n }\n\n /**\n * Where a write finds its rows: the records `keys` name, the record the\n * question names by its whole key, or the table; what else is asked of\n * them; and what the statement states ahead of itself.\n */\n #frame(\n question: Question,\n keys?: readonly Input[]\n ): { readonly before: Sql; readonly target: Sql; readonly where: Sql } {\n const { model, member } = question;\n const low = this.#low;\n const selector = keys\n ? this.selector({\n ...question,\n // Rows the call knows are named by their keys; what found them is said again only where asked.\n where: question.again ? question.where : undefined,\n unique: false,\n only: undefined,\n })\n : this.selector(question);\n let from = fieldName(model[\"~\"].names.sql!);\n let predicate = selector.predicate;\n let named = false;\n if (keys) {\n named = true;\n from =\n keys.length === 1\n ? low.recordOfRow(model, keys[0]!)\n : sql`[${sql.join(\n keys.map((key) => low.recordOfRow(model, key)),\n \", \"\n )}]`;\n } else if (!member && predicate) {\n const record = low.namedRecord(model, predicate);\n if (record) {\n named = true;\n from = record.record;\n predicate = record.rest;\n }\n }\n const conditions = onceEach([\n ...(member ? [low.member(member.edge, member.of)] : []),\n ...(predicate\n ? member\n ? low.conjuncts(predicate)\n : low.located(model, predicate, named || undefined)\n : []),\n ]);\n const where = conditions.length\n ? sql`WHERE ${sql.join(conditions, \" AND \")}`\n : NOTHING;\n const limit = keys || member ? undefined : question.limit;\n if (limit !== undefined) {\n // The first rows of it in key order.\n const { extras, order } = low.order(model, undefined);\n const taken = sql`ORDER BY ${order} LIMIT ${sql.raw(String(Number(limit)))}`;\n return {\n before: NOTHING,\n where: NOTHING,\n target:\n extras.length === 0\n ? sql`(SELECT VALUE id FROM ${seq(from, where, taken)})`\n : sql`(SELECT id, ${sql.join(extras, \", \")} FROM ${seq(from, where, taken)}).id`,\n };\n }\n // A statement here evaluates its `WHERE` row by row and sees what it has\n // already written, where SQL reads a snapshot: a filter that reads other\n // rows finds its rows first.\n if (selector.predicate && walksFurther(selector.predicate))\n return {\n before: sql`LET $targets = (SELECT VALUE id FROM ${seq(from, where)});`,\n target: sql.raw(\"$targets\"),\n where: NOTHING,\n };\n return { before: NOTHING, target: from, where };\n }\n\n /**\n * Refused where a junction holds one of `rows` back. A record's edges go with it,\n * before anything in the database could object, so this is the engine's: a raw\n * delete does not hold back.\n */\n #heldBack(model: AnyModel, rows: Sql): Sql | undefined {\n const { schema } = this.operation;\n const refusals = schema.restrictingSlots(model).flatMap((slot) => {\n const edge = schema.membership(model, slot);\n if (edge.kind !== \"junction\" || edge.declared) return [];\n const { table, near } = this.#low.edgeOf(edge);\n return [\n sql`IF array::len(SELECT VALUE id FROM ${table} WHERE ${near} IN (SELECT VALUE id FROM ${rows}) LIMIT 1) > 0 { THROW ${`ON DELETE REJECT: ${edge.name}`} };`,\n ];\n });\n return refusals.length ? sql.join(refusals, \" \") : undefined;\n }\n\n /** Refused unless every row in `rows`, read as a list, holds what judges it. */\n #judges(rows: string, judge: PreparedSelector | undefined): Ahead {\n if (!judge?.predicate) return NOTHING_AHEAD;\n const holds = this.#low.judging(() =>\n this.#low.predicate(judge.predicate!, true)\n );\n return {\n lets: sql`LET $judged = (SELECT VALUE 1 FROM ${sql.raw(rows)} WHERE ${holds});`,\n checks: sql`IF array::len($judged) != array::len(${sql.raw(rows)}) { THROW ${JUDGED} };`,\n };\n }\n\n /**\n * What an update states ahead of itself: the rows it would leave, as `next`\n * states them, each refused unless it holds what judges it. So the refusal\n * comes before a unique index or a reference could object, as a judged\n * statement's does in SQL. Nothing where nothing judges them.\n */\n #judgedNext(\n model: AnyModel,\n next: () => Sql,\n assigned: readonly string[],\n judgement: WriteJudgement | undefined,\n candidatesJudged = true\n ): Ahead {\n const judges = this.#q.domain?.judge;\n if (judgement === undefined || judges === undefined) return NOTHING_AHEAD;\n const judge = judges.produced(\n model,\n judgement,\n candidatesJudged ? assigned : undefined\n );\n const cycles = judges.cycles(model, judgement);\n if (!judge?.predicate && cycles.length === 0) return NOTHING_AHEAD;\n const { lets, checks } = this.#judges(\"$next\", judge);\n return {\n lets: seq(sql`LET $next = ${next()};`, lets),\n checks: seq(\n checks,\n ...cycles.map((relation) => this.#staysAcyclic(model, relation))\n ),\n };\n }\n\n /** {@link #judgedNext} over the rows of `source` as an update writing `values` leaves them. */\n #judgedRows(\n model: AnyModel,\n source: Sql,\n values: Input,\n judgement: WriteJudgement | undefined,\n candidatesJudged = true\n ): Ahead {\n return this.#judgedNext(\n model,\n () => sql`(SELECT ${this.#leaving(model, values)} FROM ${source})`,\n Object.keys(values),\n judgement,\n candidatesJudged\n );\n }\n\n /** A row as an update writing `values` leaves it, read from the row it reads. */\n #leaving(model: AnyModel, values: Input): Sql {\n const written = this.#assigned(model, values).map(\n ({ column, value }) => sql`${value} AS ${column}`\n );\n return sql.join([sql.raw(\"*\"), ...written], \", \");\n }\n\n /**\n * A write with what it holds ahead of it. What is held stands at the top level, and\n * the block holds only what must refuse together with the write, as one transaction.\n */\n #stated(before: Sql, ahead: Ahead, write: Sql): Sql {\n if (ahead === NOTHING_AHEAD) return seq(before, write);\n return seq(before, ahead.lets, sql`RETURN { ${seq(ahead.checks, write)} }`);\n }\n\n /** Refused where a row in `$next` would hold itself among what its link walks to. */\n #staysAcyclic(model: AnyModel, relation: string): Sql {\n const edge = this.operation.schema.membership(model, relation);\n if (edge.kind === \"reference\" && this.#low.isLinked(edge)) {\n const link = this.#low.physical(model, edge.pairs[0]!.source);\n return sql`IF array::len(SELECT VALUE 1 FROM $next WHERE ${link} != NONE AND (${link} = id OR id IN ${link}.{..+collect}.${link})) > 0 { THROW ${JUDGED} };`;\n }\n return sql`IF array::len(array::filter($next, |$candidate| $candidate.id IN ${this.#low.walkFrom(edge, sql.raw(\"$candidate\"))}.edges.c)) > 0 { THROW ${JUDGED} };`;\n }\n\n /** What a judged write of the rows a question names refuses with. */\n #refusal(\n question: Question,\n judgement: WriteJudgement | undefined\n ): PreparedGuardFailure | undefined {\n const judge = this.#q.domain?.judge;\n if (!(judgement && judge)) return undefined;\n return judge.refusal(\n this.operation.operation,\n question.model,\n judgement,\n question.verb,\n (question.member?.edge ?? question.through)?.name\n );\n }\n\n override async insert(\n model: AnyModel,\n values: Input[],\n relation?: string,\n returns?: PreparedProjection,\n beside?: readonly string[],\n skips = false\n ): Promise<Statement> {\n const low = this.#low;\n const rows = await this.computed(model, values);\n const table = fieldName(model[\"~\"].names.sql!);\n const judges = this.#q.domain?.judge;\n const judge = judges?.produced(model);\n const judged = judge?.predicate !== undefined;\n const verb = sql.raw(skips ? \"INSERT IGNORE\" : \"INSERT\");\n const statement = low.hoisted(() => {\n // With what the database decides of the row beside, where the call needs both.\n const seen = new Set<string>();\n const answered = [returns, beside && this.fields(model, beside)].flatMap(\n (read) =>\n read?.fields\n .filter((field) => !seen.has(field.name) && seen.add(field.name))\n .map((field) => low.column(model, field)) ?? []\n );\n // Its own rows' count is what a call that creates many answers with.\n const returning = answered.length\n ? sql`RETURN ${sql.join(answered, \", \")}`\n : sql.raw(\n relation === undefined || skips ? \"RETURN id\" : \"RETURN NONE\"\n );\n const created =\n rows.length === 1 && !skips && !judged\n ? this.#created(model, rows[0]!)\n : undefined;\n if (created) return sql`${created} ${returning}`;\n const insert = (held: Sql) =>\n sql`${verb} INTO ${table} ${held} ${returning}`;\n if (!judged) return insert(this.#rows(model, rows));\n const { lets, checks } = this.#judges(\"$rows\", judge);\n // The rows stand outside the block: an `IF` in a block beside a long literal takes\n // about the cube of its length (800 rows, 6 s; 1,600 never ends and holds the server).\n return sql`LET $rows = ${this.#rows(model, rows)}; ${lets} RETURN { ${checks} ${insert(sql.raw(\"$rows\"))} }`;\n });\n return {\n model,\n sql: statement,\n ...(judged && {\n stops: judges!.refusal(\n this.operation.operation,\n model,\n undefined,\n \"create\",\n relation\n ),\n }),\n };\n }\n\n override async update(\n question: Question,\n values: Input,\n keys?: readonly Input[],\n projection?: PreparedProjection,\n counted = !keys\n ): Promise<Statement> {\n const { model } = question;\n const low = this.#low;\n const [field, joined] = (Object.entries(values).find(\n ([, value]) => value instanceof JoinedValue\n ) ?? []) as [string, JoinedValue] | [];\n const [given] = await this.computed(model, [\n Object.fromEntries(\n Object.entries(values).filter(([, value]) => value !== joined)\n ),\n ]);\n const judgement = this.judged(question);\n const stops = this.#refusal(question, judgement);\n if (joined)\n return {\n model,\n stops,\n sql: await this.#listed(\n question,\n field!,\n joined,\n given!,\n keys,\n projection\n ),\n };\n const returning = this.#returning(projection, counted);\n const answer = projection ? low.columns(projection) : sql.raw(\"id\");\n const located = (columns: Sql) =>\n low.hoisted(() => {\n const { before, target, where } = this.#frame(question, keys);\n return seq(before, sql`SELECT ${columns} FROM`, target, where);\n });\n if (this.#keyChange(model, given!).length > 0) {\n // A record's id cannot change: each row is found, moved, and the rest of the write follows it.\n const moved: Input[] = [];\n for (const row of await this.#heard(\n located(this.#as(model, this.#q.keyOrder(model))),\n model\n ))\n moved.push(await this.#moveRecord(model, row, given!));\n if (moved.length === 0) return { model, sql: sql`RETURN []` };\n const rest = this.#withoutKeys(model, given!);\n const records = sql`[${sql.join(\n moved.map((row) => low.recordOfRow(model, row)),\n \", \"\n )}]`;\n // The moved records are what the update produces, judged as its rows would be\n // where nothing moved: their candidates stood under the keys they left.\n return {\n model,\n stops,\n sql: low.hoisted(() =>\n this.#stated(\n NOTHING,\n this.#judgedRows(model, records, rest, judgement, false),\n Object.keys(rest).length > 0\n ? sql`UPDATE ${records} SET ${this.#assignments(model, rest)} ${returning}`\n : sql`SELECT ${answer} FROM ${records}`\n )\n ),\n };\n }\n const statement = low.hoisted(() => {\n const { before, target, where } = this.#frame(question, keys);\n return this.#stated(\n before,\n this.#judgedRows(model, seq(target, where), given!, judgement),\n seq(\n sql`UPDATE ${target} SET ${this.#assignments(model, given!)}`,\n where,\n returning\n )\n );\n });\n const followers = this.#keyFollowers(model, given!);\n if (followers.length === 0) return { model, sql: statement, stops };\n // Nothing in the database moves a record: those holding what this write\n // changes in their own keys are moved here, once it is written.\n const stored = this.#as(model, this.operation.schema.storedFields(model));\n const before = await this.#heard(located(stored), model);\n const said = await this.#heard(statement, model).catch((error) => {\n throw stops && error instanceof NestedWriteAssertionError\n ? new Stopped({ model, sql: statement, stops })\n : error;\n });\n await this.#follow(model, followers, before, stored);\n return { model, sql: sql`RETURN ${said}` };\n }\n\n /** Fields of a row as a read names them here: each under its own name. */\n #as(model: AnyModel, fields: readonly string[]): Sql {\n return sql.join(\n fields.map(\n (field) =>\n sql`${this.#low.physical(model, field)} AS ${fieldName(field)}`\n ),\n \", \"\n );\n }\n\n /**\n * A value each row takes from a list: what gives the value names the rows, read\n * in the call's unit, and the one statement writes a row only while it holds what\n * it was named by.\n */\n async #listed(\n question: Question,\n field: string,\n joined: JoinedValue,\n beside: Input,\n keys: readonly Input[] | undefined,\n projection: PreparedProjection | undefined\n ): Promise<Sql> {\n const { model } = question;\n const q = this.#q;\n const low = this.#low;\n const selector = this.selector(question, keys);\n const spelt = q.spelling(model, this.operation.driver.dialect);\n const entries = await joined.rows(\n {\n ...spelt,\n // The rows this update may write are those its own question names.\n visible: (alias, options) =>\n options?.update\n ? selector.predicate\n ? low.predicate(selector.predicate, true)\n : sql.raw(\"true\")\n : spelt.visible(alias, options),\n },\n (statement) => this.#heard(statement, model)\n );\n const identity = q.keyOrder(model);\n const writes = entries.map(({ where, value }) => ({\n record: low.recordOfRow(\n model,\n Object.fromEntries(identity.map((key) => [key, where[key]]))\n ),\n values: { [field]: value, ...beside } as Input,\n where: sql.join(\n [\n sql.raw(\"true\"),\n ...Object.entries(where)\n .filter(([held]) => !identity.includes(held))\n .map(([held, was]) =>\n was === null || was === undefined\n ? sql`${low.physical(model, held)} = NONE`\n : sql`${low.physical(model, held)} = ${low.value(model, held, was)}`\n ),\n ],\n \" AND \"\n ),\n }));\n if (writes.length === 0) return sql`RETURN []`;\n // Each row is judged as it would be left, as the rows of an update are.\n return low.hoisted(() => {\n const written = sql`array::flatten([${sql.join(\n writes.map(\n ({ record, values, where }) =>\n sql`(UPDATE ${record} SET ${this.#assignments(model, values)} WHERE ${where} RETURN id)`\n ),\n \", \"\n )}])`;\n return this.#stated(\n NOTHING,\n this.#judgedNext(\n model,\n () =>\n sql`array::flatten([${sql.join(\n writes.map(\n ({ record, values, where }) =>\n sql`(SELECT ${this.#leaving(model, values)} FROM ${record} WHERE ${where})`\n ),\n \", \"\n )}])`,\n [field, ...Object.keys(beside)],\n this.judged(question)\n ),\n projection\n ? sql`LET $written = ${written}.id; RETURN (SELECT ${low.columns(projection)} FROM $written);`\n : sql`RETURN ${written}`\n );\n });\n }\n\n override remove(\n question: Question,\n keys?: readonly Input[],\n projection?: PreparedProjection,\n counted = !keys\n ): Statement {\n const { model } = question;\n const low = this.#low;\n return {\n model,\n sql: low.hoisted(() => {\n const { before, target, where } = this.#frame(\n { ...question, intent: \"delete\" },\n keys\n );\n const heldBack = this.#heldBack(model, sql.raw(\"$rows\"));\n if (!(heldBack || projection))\n return seq(\n before,\n sql`DELETE`,\n target,\n where,\n sql.raw(counted ? \"RETURN BEFORE\" : \"RETURN NONE\")\n );\n // `RETURN BEFORE` is the row alone, so what it answers reads ahead of it, in\n // the one statement: a block runs as a transaction of its own.\n return seq(\n before,\n sql`LET $rows = (SELECT VALUE id FROM ${seq(target, where)});`,\n projection\n ? sql`LET $answer = (SELECT ${low.columns(projection)} FROM $rows);`\n : NOTHING,\n sql`RETURN { ${seq(\n heldBack ?? NOTHING,\n projection\n ? sql`DELETE $rows; RETURN $answer;`\n : sql`DELETE $rows RETURN BEFORE`\n )} }`\n );\n }),\n };\n }\n\n override async either(\n question: Question,\n row: Input,\n set: Input,\n projection: PreparedProjection\n ): Promise<Statement> {\n const { model } = question;\n const low = this.#low;\n const [given] = await this.computed(model, [row]);\n const [updates] = await this.computed(model, [set]);\n const target = this.selector(question).uniqueKey!.fields;\n const table = fieldName(model[\"~\"].names.sql!);\n const returning = this.#returning(projection, true);\n return {\n model,\n sql: low.hoisted(() => {\n const created = this.#row(model, given!);\n const assignments = this.#assignments(model, updates!);\n if (this.#q.keyOrder(model).every((key) => target.includes(key)))\n return sql`INSERT INTO ${table} ${created} ON DUPLICATE KEY UPDATE ${assignments} ${returning}`;\n // `ON DUPLICATE KEY` takes a conflict on any index, and only the target's\n // may update: the record is found by it, and another conflict still refuses.\n const found = sql.join(\n target.map(\n (field) =>\n sql`${low.physical(model, field)} = ${low.value(model, field, given![field])}`\n ),\n \" AND \"\n );\n return sql`RETURN { LET $found = (SELECT VALUE id FROM ${table} WHERE ${found} LIMIT 1)[0]; RETURN IF $found != NONE { UPDATE $found SET ${assignments} ${returning} } ELSE { INSERT INTO ${table} [${created}] ${returning} }; }`;\n }),\n };\n }\n\n override async link(\n edge: Junction,\n pairs: readonly (readonly [Input, Input])[],\n through?: Input\n ): Promise<Statement[]> {\n const low = this.#low;\n const { uniqueSide } = edge;\n const statements: Sql[] = [];\n const own = uniqueSide === \"source\" ? 0 : 1;\n if (edge.declared) {\n const { model } = edge.declared;\n const members = linkMembers(edge);\n const table = fieldName(model[\"~\"].names.sql!);\n const taken = await this.linked(\n edge,\n members.map(({ pair }) => pair.junctionField),\n through\n );\n const holds = (side: Junction[\"sourceSide\"], row: Input) =>\n sql.join(\n side.members.map((pair) => {\n const field = low.linkFieldOf(edge, pair.junctionField);\n return sql`${low.physical(model, field)} = ${low.value(model, field, row[pair.referencedField])}`;\n }),\n \" AND \"\n );\n for (const pair of pairs) {\n // The link that side holds takes the other row: the one it held goes.\n if (uniqueSide)\n statements.push(\n sql`DELETE ${table} WHERE ${holds(\n uniqueSide === \"source\" ? edge.sourceSide : edge.targetSide,\n pair[own]\n )} AND !(${holds(\n uniqueSide === \"source\" ? edge.targetSide : edge.sourceSide,\n pair[1 - own]!\n )}) RETURN NONE`\n );\n const row = this.#row(model, {\n ...Object.fromEntries(\n members.map(({ side, pair: member }) => [\n low.linkFieldOf(edge, member.junctionField),\n pair[side === edge.sourceSide ? 0 : 1][member.referencedField],\n ])\n ),\n ...taken.row,\n });\n statements.push(\n taken.sets\n ? sql`INSERT INTO ${table} ${row} ON DUPLICATE KEY UPDATE ${this.#assignments(model, taken.sets)} RETURN NONE`\n : sql`INSERT IGNORE INTO ${table} [${row}] RETURN NONE`\n );\n }\n } else {\n const { table, near, far } = low.edgeOf(edge);\n const ends = pairs.map(\n (pair) =>\n [\n low.end(\n edge.sourceSide,\n (member) => pair[0][member.referencedField]\n ),\n low.end(\n edge.targetSide,\n (member) => pair[1][member.referencedField]\n ),\n ] as const\n );\n if (uniqueSide) {\n // A singular relation needs its index, so its edges carry a record, and a\n // `RELATE` would refuse the pair an idempotent link must skip. The edge\n // that side holds to another row goes first.\n const [held, other] = own === 0 ? [near, far] : [far, near];\n for (const pair of ends)\n statements.push(\n sql`DELETE ${table} WHERE ${held} = ${pair[own]} AND ${other} != ${pair[1 - own]!} RETURN NONE`\n );\n statements.push(\n sql`INSERT RELATION IGNORE INTO ${table} [${sql.join(\n ends.map(\n ([source, target]) =>\n sql`{ ${near}: ${source}, ${far}: ${target} }`\n ),\n \", \"\n )}] RETURN NONE`\n );\n } else {\n // A `LIGHTWEIGHT` edge is its pair, so `RELATE` is idempotent by itself and\n // takes one source's targets in one statement.\n const forward = near.toStatement() === \"in\";\n const bySource = new Map<string, { source: Sql; targets: Sql[] }>();\n for (const [source, target] of ends) {\n const name = `${source.toStatement()} ${source.values.map(String).join(\" \")}`;\n const run = bySource.get(name) ?? { source, targets: [] };\n run.targets.push(target);\n bySource.set(name, run);\n }\n for (const { source, targets } of bySource.values()) {\n const all = sql`[${sql.join(targets, \", \")}]`;\n statements.push(\n forward\n ? sql`RELATE (${source})->${table}->(${all}) RETURN NONE`\n : sql`RELATE (${all})->${table}->(${source}) RETURN NONE`\n );\n }\n }\n }\n return statements.map((statement) => ({\n sql: statement,\n model: edge.source,\n }));\n }\n\n override unlink(\n edge: Junction,\n from: Input,\n to: Input | undefined,\n kept: readonly Input[]\n ): Statement {\n const low = this.#low;\n // Every link but those kept: of the rows the call may take out, and no other.\n const allowed = to\n ? undefined\n : this.#q.domainOf(edge.target, \"related\", linkJudgement(edge))\n ?.predicate;\n const writable = allowed\n ? sql`LET $writable = (SELECT VALUE id FROM ${fieldName(edge.target[\"~\"].names.sql!)} WHERE ${low.predicate(allowed, true)});`\n : NOTHING;\n const among = (far: Sql) => (allowed ? [sql`${far} IN $writable`] : []);\n if (edge.declared) {\n const { model } = edge.declared;\n const holds = (side: Junction[\"sourceSide\"], row: Input) =>\n sql.join(\n side.members.map((pair) => {\n const field = low.linkFieldOf(edge, pair.junctionField);\n return sql`${low.physical(model, field)} = ${low.value(model, field, row[pair.referencedField])}`;\n }),\n \" AND \"\n );\n return {\n model: edge.source,\n sql: seq(\n writable,\n sql`DELETE ${fieldName(model[\"~\"].names.sql!)} WHERE ${sql.join(\n [\n holds(edge.sourceSide, from),\n ...(to ? [holds(edge.targetSide, to)] : []),\n ...kept.map((row) => sql`!(${holds(edge.targetSide, row)})`),\n ...among(low.linkTarget(edge, edge.targetSide, \"\")),\n ],\n \" AND \"\n )} RETURN NONE`\n ),\n };\n }\n const { far, out } = low.edgeOf(edge);\n const end = (side: Junction[\"sourceSide\"], row: Input) =>\n low.end(side, (pair) => row[pair.referencedField]);\n const conditions = [\n ...(to ? [sql`${far} = ${end(edge.targetSide, to)}`] : []),\n ...(kept.length\n ? [\n sql`${far} NOT IN [${sql.join(\n kept.map((row) => end(edge.targetSide, row)),\n \", \"\n )}]`,\n ]\n : []),\n ...among(far),\n ];\n // From its source, an edge is reached along the record's own list.\n return {\n model: edge.source,\n sql: seq(\n writable,\n sql`DELETE ${end(edge.sourceSide, from)}${out}`,\n conditions.length\n ? sql`WHERE ${sql.join(conditions, \" AND \")}`\n : NOTHING,\n sql`RETURN NONE`\n ),\n };\n }\n\n /**\n * A refusal here says what it met: the record, where the row's own key was\n * taken, or the index, under the name a migration gives a model's key.\n */\n override refusedFor(\n model: AnyModel,\n key: NonNullable<PreparedSelector[\"uniqueKey\"]>,\n error: UniqueConstraintError\n ): boolean {\n const table = model[\"~\"].names.sql!;\n return error.message.includes(\n key.kind === \"primary\"\n ? `Database record \\`${table}:`\n : `index \\`${table}_${key.name ?? this.#q.columnName(model, key.fields[0]!)}_key\\``\n );\n }\n\n /** The key fields a write states. */\n #keyChange(model: AnyModel, given: Input): readonly string[] {\n return this.#q.keyOrder(model).filter((key) => Object.hasOwn(given, key));\n }\n\n /** The values a write states beside a key it has already moved. */\n #withoutKeys(model: AnyModel, given: Input): Input {\n const keys = this.#q.keyOrder(model);\n return Object.fromEntries(\n Object.entries(given).filter(([field]) => !keys.includes(field))\n );\n }\n\n /**\n * What stands in for a moved row's unique fields while both copies exist: its\n * unique indexes would read the old row as a duplicate of the new one. One field\n * out of the way frees a key over several, and a missing value is in no index.\n */\n #standIns(model: AnyModel): Map<string, Sql | undefined> {\n const keys = this.#q.keyOrder(model);\n const scalars = model[\"~\"].state.scalars;\n const standIns = new Map<string, Sql | undefined>();\n const standIn = (field: string) => {\n const state = scalars[field]?.[\"~\"].state;\n return !state || state.array || this.#low.holdsRecord(model, field)\n ? undefined\n : STAND_INS[state.type as string];\n };\n for (const fields of getModelKeyCatalog(model).referenceableKeys) {\n // The id holds a key naming it: no index does.\n if (fields.some((field) => keys.includes(field))) continue;\n const held = fields.find((field) => standIn(field));\n if (held) {\n standIns.set(held, standIn(held));\n continue;\n }\n const absent = fields.find(\n (field) => scalars[field]?.[\"~\"].state.nullable\n );\n if (!absent)\n refuse(\n `changing the key of '${model[\"~\"].names.ts}', whose unique ${fields.join(\", \")} has no value to stand in`\n );\n standIns.set(absent, undefined);\n }\n return standIns;\n }\n\n /** One row moved to the key a write gives it: one statement, a transaction of its own. */\n async #moveRecord(\n model: AnyModel,\n identity: Input,\n given: Input\n ): Promise<Input> {\n const next = { ...identity };\n for (const key of this.#keyChange(model, given))\n next[key] = await this.#movedKey(model, key, identity[key], given[key]);\n const statement = await this.#movement(model, identity, next, { count: 0 });\n await this.#heard(sql`RETURN { ${statement} RETURN []; }`, model);\n return next;\n }\n\n /** What a write leaves a key part at: what it states, reads, or computes from it. */\n async #movedKey(\n model: AnyModel,\n key: string,\n current: unknown,\n given: unknown\n ): Promise<unknown> {\n const whole = wholeValue(given);\n if (whole && !(whole.value instanceof Sql)) return whole.value;\n if (whole)\n return (\n await this.#heard(sql`RETURN [{ value: ${whole.value as Sql} }]`, model)\n )[0]?.value;\n const [operator, operand] = Object.entries(given as Input)[0]!;\n const { type } = model[\"~\"].state.scalars[key]![\"~\"].state;\n if (!ARITHMETIC[operator]) refuse(`the '${operator}' update`);\n return arithmetic(type as string, current, operator, operand);\n }\n\n /**\n * Who holds a non-key field of `model` in their own key, cascading: nothing in the\n * database can move a record, so an update of the field moves them here.\n */\n #keyFollowers(model: AnyModel, given: Input): readonly FollowingEdge[] {\n const q = this.#q;\n const keys = q.keyOrder(model);\n const found: FollowingEdge[] = [];\n for (const source of Object.values(this.operation.schema.schema))\n for (const slot of slotsHeld(source)) {\n const { edges } = q.countedMemberships(source, slot);\n for (const edge of edges)\n if (\n edge.kind === \"reference\" &&\n edge.target === model &&\n edge.owner === \"source\" &&\n !edge.discriminator &&\n edge.reference?.onUpdate === \"cascade\" &&\n edge.pairs.some(\n ({ source: part, target }) =>\n !keys.includes(target) &&\n Object.hasOwn(given, target) &&\n q.keyOrder(source).includes(part)\n )\n )\n found.push(edge);\n }\n return found;\n }\n\n /** The records holding, in their own keys, what a write changed of the rows that were `before`: each moved after it. */\n async #follow(\n model: AnyModel,\n followers: readonly FollowingEdge[],\n before: readonly Input[],\n stored: Sql\n ): Promise<void> {\n const low = this.#low;\n const q = this.#q;\n const keys = q.keyOrder(model);\n for (const was of before) {\n const [now] = await this.#heard(\n sql`SELECT ${stored} FROM ${low.recordOfRow(model, this.operation.schema.identity(model, was))}`,\n model\n );\n if (!now) continue;\n for (const edge of followers) {\n const { source } = edge;\n const held = await this.#heard(\n sql`SELECT ${this.#as(source, q.keyOrder(source))} FROM ${fieldName(source[\"~\"].names.sql!)} WHERE ${sql.join(\n edge.pairs.map(\n ({ source: part, target }) =>\n sql`${low.physical(source, part)} = ${low.value(source, part, was[target])}`\n ),\n \" AND \"\n )}`,\n model\n );\n for (const row of held)\n await this.#moveRecord(\n source,\n row,\n Object.fromEntries(\n edge.pairs\n .filter(\n ({ source: part, target }) =>\n !keys.includes(target) && q.keyOrder(source).includes(part)\n )\n .map(({ source: part, target }) => [part, now[target]])\n )\n );\n }\n }\n }\n\n /**\n * A record's id cannot change, so a new key is a new record: the row is copied\n * under it, what points at it does what its action says, and the old one goes.\n * A record holding the key in its own key moves with it, inside the same block.\n */\n async #movement(\n model: AnyModel,\n identity: Input,\n next: Input,\n moves: { count: number }\n ): Promise<Sql> {\n const q = this.#q;\n const low = this.#low;\n const { schema } = this.operation;\n const at = moves.count++;\n const named = (variable: string) => sql.raw(`$${variable}${at}`);\n const old = named(\"old\");\n const moved = named(\"new\");\n const held = named(\"row\");\n const other = named(\"other\");\n const others = named(\"others\");\n const keys = q.keyOrder(model);\n const standIns = this.#standIns(model);\n const copied = schema\n .storedFields(model)\n .filter(\n (field) =>\n !keys.includes(field) && (!standIns.has(field) || standIns.get(field))\n )\n .map((field) => {\n const column = fieldName(q.columnName(model, field));\n return sql`${column}: ${standIns.get(field) ?? sql`${held}.${column}`}`;\n });\n const restored = [...standIns.keys()].map((field) => {\n const column = fieldName(q.columnName(model, field));\n return sql`${column} = ${held}.${column}`;\n });\n const refusals: Sql[] = [];\n const follow: Sql[] = [];\n let quiet = false;\n for (const source of Object.values(schema.schema))\n for (const slot of slotsHeld(source)) {\n const { edges } = q.countedMemberships(source, slot);\n for (const edge of edges) {\n if (edge.target !== model) continue;\n if (edge.kind === \"junction\") {\n // A declared link is a row of its model, reached by its own references.\n if (edge.declared) continue;\n const { table, near, far } = low.edgeOf(edge);\n // Nothing in the database holds an edge's key back, so the engine does.\n const action = edge.targetSide.onUpdate ?? \"cascade\";\n if (action === \"restrict\" || action === \"noAction\") {\n refusals.push(\n sql`IF array::len(SELECT VALUE id FROM ${table} WHERE ${far} = ${old} LIMIT 1) > 0 { THROW ${`ON UPDATE REJECT: ${edge.name}`} };`\n );\n continue;\n }\n const linked = sql`(SELECT VALUE ${near} FROM ${table} WHERE ${far} = ${old})`;\n // An edge's ends are fixed: it is related again from the new record. A\n // singular one holds its index until it is gone.\n follow.push(\n edge.uniqueSide\n ? sql`LET ${others} = ${linked}; DELETE ${table} WHERE ${far} = ${old}; FOR ${other} IN ${others} { INSERT RELATION INTO ${table} [{ ${near}: ${other}, ${far}: ${moved} }] };`\n : near.toStatement() === \"in\"\n ? sql`FOR ${other} IN ${linked} { RELATE ${other}->${table}->${moved} };`\n : sql`FOR ${other} IN ${linked} { RELATE ${moved}->${table}->${other} };`\n );\n continue;\n }\n if (edge.owner !== \"source\" || edge.discriminator) continue;\n // An event answers for it: a move's old copy says so, and it stays quiet.\n if (\n edge.pairs.length > 1 ||\n !low.holdsRecord(source, edge.pairs[0]!.source)\n )\n quiet = true;\n // Not by the key: the value stays with the row, and so do those holding it.\n if (!edge.pairs.some(({ target }) => keys.includes(target))) continue;\n const stored = edge.pairs.every(({ target }) => keys.includes(target))\n ? identity\n : {\n ...(\n await this.#heard(\n sql`SELECT ${this.#as(model, schema.storedFields(model))} FROM ${low.recordOfRow(model, identity)}`,\n model\n )\n )[0],\n ...identity,\n };\n const holders = edge.pairs.map(({ source: part, target }) => ({\n part,\n column: low.physical(source, part),\n now: keys.includes(target) ? next[target] : stored[target],\n value: low.value(\n source,\n part,\n keys.includes(target) ? next[target] : stored[target]\n ),\n was: low.value(source, part, stored[target]),\n }));\n const table = fieldName(source[\"~\"].names.sql!);\n const holding = sql.join(\n holders.map(({ column, was }) => sql`${column} = ${was}`),\n \" AND \"\n );\n // As SQL's foreign keys: left unsaid, a key that is held refuses to change.\n const action = edge.reference?.onUpdate ?? \"noAction\";\n if (action === \"restrict\" || action === \"noAction\") {\n refusals.push(\n sql`IF array::len(SELECT VALUE id FROM ${table} WHERE ${holding} LIMIT 1) > 0 { THROW ${`ON UPDATE REJECT: ${edge.name}`} };`\n );\n continue;\n }\n if (\n holders.some(({ column }) => column.toStatement().startsWith(\"id\"))\n ) {\n if (action === \"setNull\")\n refuse(\"setNull on a key that holds another\");\n for (const row of await this.#heard(\n sql`SELECT ${this.#as(source, q.keyOrder(source))} FROM ${table} WHERE ${holding}`,\n model\n ))\n follow.push(\n await this.#movement(\n source,\n row,\n {\n ...row,\n ...Object.fromEntries(\n holders.map(({ part, now }) => [part, now])\n ),\n },\n moves\n )\n );\n continue;\n }\n follow.push(\n sql`UPDATE ${table} SET ${sql.join(\n holders.map(({ column, value }) =>\n action === \"setNull\"\n ? sql`${column} = NONE`\n : sql`${column} = ${value}`\n ),\n \", \"\n )} WHERE ${holding};`\n );\n }\n }\n return sql`LET ${old} = ${low.recordOfRow(model, identity)}; LET ${moved} = ${low.recordOfRow(model, next)}; IF ${moved} = ${old} { RETURN []; }; ${sql.join(refusals, \" \")} LET ${held} = (SELECT * FROM ONLY ${old}); IF ${held} = NONE { RETURN []; }; ${quiet ? sql`UPDATE ${old} SET viborm_moved = true;` : NOTHING} INSERT INTO ${fieldName(model[\"~\"].names.sql!)} [{ ${sql.join([sql`id: ${moved}`, ...copied], \", \")} }] RETURN NONE; ${sql.join(follow, \" \")} DELETE ${old}; ${restored.length ? sql`UPDATE ${moved} SET ${sql.join(restored, \", \")};` : NOTHING}`;\n }\n}\n","/**\n * `viborm/surrealdb`: a driver whose database reads SurrealQL. {@link SurrealQueries}\n * and {@link SurrealWriter} write its statements, and it declares only what\n * the engine asks of any driver. `docs/architecture/query-backend-frontier.md`.\n */\n\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n ConnectionError,\n ForeignKeyError,\n NestedWriteAssertionError,\n QueryError,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport { queryBackend } from \"@query-engine/raptor3/shared/query-backend\";\nimport type { Sql } from \"@sql\";\nimport {\n DateTime,\n Decimal,\n GeometryPoint,\n RecordId,\n SizedNumber,\n Surreal,\n Uuid,\n} from \"surrealdb\";\nimport {\n type CommitRerunningDriver,\n Driver,\n TransactionBoundDriver,\n} from \"../driver\";\nimport { getExecutionExtensionChain } from \"../execution-context\";\nimport type {\n DriverTransactionOptions,\n TransactionOptionSupport,\n TransactionOptions,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { createTransactionCleanupError } from \"../shared/transactions\";\nimport type { BatchQuery, QueryExecutionContext, QueryResult } from \"../types\";\nimport { SURREAL_FACTS } from \"./facts\";\nimport { SurrealQueries } from \"./queries\";\nimport {\n backOff,\n COMMITS,\n FORBIDDEN_ROW,\n isConflict,\n ReplayedTransaction,\n STOPPED,\n} from \"./transaction\";\nimport { SurrealCall, SurrealWriter } from \"./writer\";\n\n/** In a text of several statements, where one's answers end: a statement may hold several of its own ahead of itself. */\nconst MARKED = \"viborm:|\";\nconst NAMED_PARAMETER = /\\$p(\\d+)\\b/g;\n\n/**\n * How long the first connection of a driver given a `url` may take. The SDK\n * retries a connection that does not open for as long as it stays shut, the\n * first one included: an address nothing answers at (a typo, a stopped\n * server) left a command waiting for good, without a word. Past this the\n * client is closed and the call fails as a connection failure (`V1001`); a\n * connection that opened keeps the SDK's reconnection.\n */\nconst FIRST_CONNECTION_MS = 10_000;\n/** How long the client of a first connection that expired is waited for to close. */\nconst FIRST_CONNECTION_CLOSE_MS = 1000;\n\n/** `promise`'s answer, or `\"expired\"` once `ms` passed first. */\nconst within = async <T>(\n promise: Promise<T>,\n ms: number\n): Promise<T | \"expired\"> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<\"expired\">((resolve) => {\n timer = setTimeout(() => resolve(\"expired\"), ms);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n};\n\n/**\n * A statement that holds what it reads ahead of itself, where no transaction\n * holds it: this driver makes it one transaction of its own.\n */\nconst standsAlone = (client: unknown, statement: string): boolean =>\n !(client instanceof ReplayedTransaction) && statement.startsWith(\"LET \");\n\n/** A provider value as the engine's decoders read it. */\nfunction plain(value: unknown): unknown {\n if (value === undefined) return null;\n if (value instanceof RecordId) return plain(value.id);\n if (value instanceof GeometryPoint) return value.toJSON();\n if (value instanceof DateTime) return value.toISOString();\n if (value instanceof Decimal || value instanceof Uuid)\n return value.toString();\n if (value instanceof SizedNumber) return value.value;\n if (Array.isArray(value)) return value.map(plain);\n if (ArrayBuffer.isView(value)) return value;\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n if (value !== null && typeof value === \"object\" && !(value instanceof Date)) {\n const members = Object.entries(value).map(([key, member]) => [\n key,\n plain(member),\n ]);\n // The SDK decodes a map by assignment, so a stored `__proto__` key becomes the\n // object's prototype, which every read of the row would then inherit from.\n const inherited = Object.getPrototypeOf(value);\n if (\n inherited === null ||\n (inherited !== Object.prototype &&\n Object.getPrototypeOf(inherited) === Object.prototype &&\n !Object.hasOwn(inherited, \"constructor\"))\n )\n members.unshift([\"__proto__\", plain(inherited)]);\n return Object.fromEntries(members);\n }\n return value;\n}\n\nconst UNIQUE_REFUSAL = /already contains|already exists/;\nconst REFERENCE_REFUSAL =\n /must conform to.*exists\\(\\)|ON (?:DELETE|UPDATE) REJECT/s;\nconst OUT_OF_RANGE =\n /Expected `(?:none \\| )?i32` but found|must conform to.*math::abs|Cannot perform (?:addition|subtraction|multiplication) with/s;\nconst TOO_DEEP = /Exceeded (?:query|expression) recursion depth limit/;\n\n/**\n * A provider failure in viborm's own words. Refusals carry no code here, so their\n * sentences are the only evidence.\n */\nfunction refusal(error: unknown): unknown {\n const message = error instanceof Error ? error.message : String(error);\n const cause = error instanceof Error ? error : undefined;\n if (isConflict(error)) return new TransactionError(message, { cause });\n // The statement stopped itself: its call says what it refuses with.\n if (message.includes(FORBIDDEN_ROW) || message.includes(STOPPED))\n return new NestedWriteAssertionError(message, { cause });\n if (UNIQUE_REFUSAL.test(message))\n return new UniqueConstraintError(`Unique constraint failed: ${message}`, {\n cause,\n });\n if (REFERENCE_REFUSAL.test(message))\n return new ForeignKeyError(message, { cause });\n if (OUT_OF_RANGE.test(message))\n return new QueryError(message, {\n cause,\n code: VibORMErrorCode.QUERY_OUT_OF_RANGE,\n });\n if (TOO_DEEP.test(message))\n return new UnsupportedOperationError(\n \"This statement nests deeper than the SurrealDB server parses: raise its SURREAL_MAX_QUERY_PARSING_DEPTH, or read in two steps.\",\n { cause }\n );\n return error;\n}\n\n/** SurrealQL names its parameters: `$p1`, as {@link SurrealDriver.execute} binds them. */\nfunction namedStatement(query: Sql): string {\n return query.strings.reduce(\n (text, next, index) => `${text}$p${index}${next}`\n );\n}\n\nclass SurrealTransactionDriver extends TransactionBoundDriver<\n Surreal,\n ReplayedTransaction\n> {\n readonly replayed: ReplayedTransaction;\n\n constructor(\n base: Driver<Surreal, ReplayedTransaction>,\n tx: ReplayedTransaction,\n context?: QueryExecutionContext\n ) {\n super(base, tx, context);\n this.replayed = tx;\n }\n\n protected override buildStatement(query: Sql): string {\n return namedStatement(query);\n }\n\n protected override createTransactionBoundDriver(\n tx: ReplayedTransaction,\n context: QueryExecutionContext\n ): SurrealTransactionDriver {\n return new SurrealTransactionDriver(this, tx, context);\n }\n\n /** A nested scope is a savepoint, which the transaction keeps for itself. */\n protected override async transaction<T>(\n client: Surreal | ReplayedTransaction,\n fn: (tx: ReplayedTransaction) => Promise<T>\n ): Promise<T> {\n const tx = client as ReplayedTransaction;\n const mark = tx.mark;\n try {\n return await fn(tx);\n } catch (error) {\n await tx.rollbackTo(mark).catch((cleanup: unknown) => {\n throw createTransactionCleanupError(error, [cleanup]);\n });\n throw error;\n }\n }\n}\n\nconst CALLBACK = \"$transaction(callback)\";\n\nexport interface SurrealDriverOptions {\n /** A client you connected, which stays yours: the driver never closes it. */\n readonly client?: Surreal;\n /** Where to connect, when the driver opens its own client. */\n readonly url?: string;\n readonly namespace?: string;\n readonly database?: string;\n readonly authentication?: {\n readonly username: string;\n readonly password: string;\n };\n /**\n * How many more times a `$transaction` callback may run when a concurrent write\n * changed what it read, instead of failing with `V5001`. PostgreSQL would make it\n * wait, and running it again is the only way to give it the new value. Everything\n * the callback does outside the database happens again too, such as sending an\n * email, so this is off unless asked for.\n */\n readonly rerunsOnConflict?: number;\n}\n\nexport class SurrealDriver\n extends Driver<Surreal, ReplayedTransaction>\n implements CommitRerunningDriver\n{\n readonly adapter = SURREAL_FACTS;\n override readonly backend = queryBackend({\n queries: SurrealQueries,\n context: SurrealCall,\n writer: SurrealWriter,\n });\n readonly supportsTransactions = true;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = false;\n\n readonly #rerunsOnConflict: number;\n readonly #options: SurrealDriverOptions;\n\n constructor(options: SurrealDriverOptions = {}) {\n super(\"surrealql\", \"surrealdb\");\n if (options.client) this.client = options.client;\n this.#options = options;\n this.#rerunsOnConflict = options.rerunsOnConflict ?? 0;\n }\n\n /**\n * A caller's callback runs again only when asked. A conflict its statements can\n * replay never reaches here, and an extension that hears writes has already\n * been told what the failed run wrote, so its callback does not run twice.\n */\n override async withTransaction<T>(\n fn: (txDriver: Driver<Surreal, ReplayedTransaction>) => Promise<T>,\n options?: TransactionOptions,\n context?: QueryExecutionContext\n ): Promise<T> {\n let reruns =\n context?.operation === CALLBACK &&\n !getExecutionExtensionChain(context)?.collect\n ? this.#rerunsOnConflict\n : 0;\n for (let run = 1; ; run++) {\n let replayed: ReplayedTransaction | undefined;\n try {\n return await super.withTransaction(\n (driver) => {\n ({ replayed } = driver as SurrealTransactionDriver);\n return fn(driver);\n },\n options,\n context\n );\n } catch (error) {\n // A refusal after the conflict hides it, so the transaction is who says.\n if (reruns-- === 0 || !replayed?.conflicted) throw error;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, Math.random() * 20 * run)\n );\n }\n }\n\n protected override buildStatement(query: Sql): string {\n return namedStatement(query);\n }\n\n protected override createTransactionBoundDriver(\n tx: ReplayedTransaction,\n context: QueryExecutionContext\n ): SurrealTransactionDriver {\n return new SurrealTransactionDriver(this, tx, context);\n }\n\n protected async initClient(): Promise<Surreal> {\n const { url, namespace, database, authentication } = this.#options;\n if (!url)\n throw new ClientInitializationError(\n 'Driver \"surrealdb\" needs a connected client or a url.',\n { meta: { driver: \"surrealdb\", operation: \"configuration\" } }\n );\n const client = new Surreal();\n const connected = client.connect(url, {\n ...(namespace ? { namespace } : {}),\n ...(database ? { database } : {}),\n ...(authentication ? { authentication: { ...authentication } } : {}),\n });\n if ((await within(connected, FIRST_CONNECTION_MS)) !== \"expired\")\n return client;\n // Closing ends the SDK's retries; the connection it was still trying for\n // then fails into the race above, which already handles it. A socket that\n // opened waits for the server to acknowledge its close, which a server\n // that stalled (or SurrealDB Cloud, which never answers it) may never do:\n // the close is waited for a second at most.\n await within(\n client.close().catch(() => undefined),\n FIRST_CONNECTION_CLOSE_MS\n );\n // Ours, so its words reach the caller as they are (a provider's failure\n // is redacted); the url may carry credentials and is not named.\n throw new ConnectionError(\n `SurrealDB did not connect within ${FIRST_CONNECTION_MS / 1000} s.`,\n { meta: { driver: this.driverName, operation: \"connect\" } }\n );\n }\n\n protected async closeClient(): Promise<void> {\n // A client handed in is the caller's.\n if (this.#options.client) return;\n await (this.client as Surreal | null)?.close();\n }\n\n protected async execute<T>(\n client: Surreal | ReplayedTransaction,\n statement: string,\n params: unknown[]\n ): Promise<QueryResult<T>> {\n const values = Object.fromEntries(\n params.map((value, index) => [`p${index + 1}`, value])\n );\n try {\n // What a statement holds ahead of itself is read with it, as one transaction.\n const stated = standsAlone(client, statement)\n ? `BEGIN; ${statement}; COMMIT;`\n : statement;\n // The SDK's client answers the same call.\n const answers = await (client as ReplayedTransaction).query<unknown[]>(\n stated,\n values\n );\n // What a statement holds ahead of itself answers first, and `COMMIT` last.\n const result = answers.at(stated.endsWith(\"; COMMIT;\") ? -2 : -1);\n const rows = Array.isArray(result) ? result : [];\n return { rows: plain(rows) as T[], rowCount: rows.length };\n } catch (error) {\n throw refusal(error);\n }\n }\n\n /**\n * Statements that go together, as one text: a transaction of its own\n * outside any, and part of the one that holds it inside. A text that fails\n * says the failure of its first statement, whichever failed.\n */\n protected override async executeBatch<T>(\n client: Surreal | ReplayedTransaction,\n queries: BatchQuery[]\n ): Promise<QueryResult<T>[]> {\n const values: Record<string, unknown> = {};\n let bound = 0;\n const texts = queries.map(({ sql, params = [] }) => {\n const from = bound;\n for (const value of params) values[`p${++bound}`] = value;\n return `${sql.replace(NAMED_PARAMETER, (_, at) => `$p${from + Number(at)}`)}; RETURN \"${MARKED}\";`;\n });\n const whole = !(client instanceof ReplayedTransaction);\n try {\n const answers = await (client as ReplayedTransaction).query<unknown[]>(\n whole ? `BEGIN; ${texts.join(\" \")} COMMIT;` : texts.join(\" \"),\n values\n );\n const results: QueryResult<T>[] = [];\n let last: unknown;\n for (const answer of answers) {\n if (answer === MARKED) {\n const rows = Array.isArray(last) ? last : [];\n results.push({ rows: plain(rows) as T[], rowCount: rows.length });\n }\n last = answer;\n }\n return results;\n } catch (error) {\n throw refusal(error);\n }\n }\n\n protected executeRaw<T>(\n client: Surreal | ReplayedTransaction,\n statement: string,\n params: unknown[] | undefined,\n _context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.execute<T>(client, statement, params ?? []);\n }\n\n /**\n * A migration statement led by `LET` is one transaction this driver opens for\n * it ({@link standsAlone}). Refused at its commit because another writer met\n * it there, it wrote nothing and answered no one: it runs again, as it would\n * have a moment later. A migration's rewrite of a table's rows is one, and\n * meets the server's own background writes to that table. That transaction\n * is the whole statement because a migration holds no `BEGIN`, `COMMIT` or\n * `CANCEL` (`statement-safety.ts`). A caller's raw statement can, and part of\n * it may have committed before the refusal, so it is never run again: it\n * fails with the conflict.\n *\n * One rerun is not enough: in #171's reproduction the background writes met\n * the rewrite in 40 of 150 first attempts, and nothing keeps them from\n * meeting a second one. The bound is the one a replayed transaction's commit\n * uses ({@link COMMITS}). This driver itself, never one bound to a\n * transaction, implements this, so a conflict inside a transaction stays\n * that transaction's.\n *\n * Statements a migration commits together, sent as one batch, are one\n * transaction too: this driver wraps a batch outside a transaction in\n * `BEGIN` and `COMMIT` ({@link executeBatch}), so a refusal leaves nothing\n * of it applied, and it runs again the same way.\n */\n async rerunRefusedCommit(\n statement: string | readonly BatchQuery[],\n send: () => Promise<unknown>\n ): Promise<unknown> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await send();\n } catch (error) {\n if (\n attempt === COMMITS ||\n !isConflict(error) ||\n (typeof statement === \"string\" &&\n !standsAlone(this.client, statement))\n )\n throw error;\n }\n await backOff(attempt);\n }\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"snapshot-only\",\n isolationLevelReason:\n \"a SurrealDB transaction reads a snapshot, where two may each read what the other writes\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Surreal | ReplayedTransaction,\n fn: (tx: ReplayedTransaction) => Promise<T>,\n _context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n const transaction = await ReplayedTransaction.begin(\n client as Surreal,\n options?.maxWaitMs\n );\n let result: T;\n try {\n result = await fn(transaction);\n } catch (error) {\n await transaction.cancel().catch(() => undefined);\n throw error;\n }\n try {\n await transaction.commit();\n } catch (error) {\n throw refusal(error);\n }\n return result;\n }\n}\n\nexport type SurrealClientConfig<C extends DriverConfig> = SurrealDriverOptions &\n C;\n\nconst SURREAL_CONFIG_KEYS: Record<keyof SurrealDriverOptions, true> = {\n client: true,\n url: true,\n namespace: true,\n database: true,\n authentication: true,\n rerunsOnConflict: true,\n};\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: SurrealClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, SurrealDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: SurrealDriver }\n >]: LinkedClientConfig<C & { driver: SurrealDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"surrealdb\", SURREAL_CONFIG_KEYS);\n const { client, url, namespace, database, authentication, rerunsOnConflict } =\n config;\n return createClientFromDriverConfig<S, C, SurrealDriver>(\n config,\n new SurrealDriver({\n client,\n url,\n namespace,\n database,\n authentication,\n rerunsOnConflict,\n })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