viborm 1.3.3 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/dist/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
  2. package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
  3. package/dist/{adapter-namespace-CWLEmon2.mjs → adapter-namespace-BLejG8FA.mjs} +1 -1
  4. package/dist/{adapter-namespace-CWLEmon2.mjs.map → adapter-namespace-BLejG8FA.mjs.map} +1 -1
  5. package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
  6. package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
  7. package/dist/adapters.d.mts +1 -1
  8. package/dist/adapters.mjs +1 -1
  9. package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  10. package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  11. package/dist/{batch-refs-DGJPz8-G.mjs → batch-refs-BYCu1JnQ.mjs} +1 -1
  12. package/dist/{batch-refs-DGJPz8-G.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
  13. package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
  14. package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
  15. package/dist/builder-BS8EW4BQ.mjs +2 -0
  16. package/dist/builder-BS8EW4BQ.mjs.map +1 -0
  17. package/dist/bun-sql.d.mts +3 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sql.mjs.map +1 -1
  20. package/dist/bun-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/cache/cloudflare-kv.d.mts +1 -1
  23. package/dist/cache/cloudflare-kv.mjs +1 -1
  24. package/dist/cache/memory.d.mts +1 -1
  25. package/dist/cache/memory.mjs +1 -1
  26. package/dist/cache.d.mts +1 -1
  27. package/dist/cache.mjs +1 -1
  28. package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
  29. package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
  30. package/dist/chain-D5J9hIw-.mjs +2 -0
  31. package/dist/chain-D5J9hIw-.mjs.map +1 -0
  32. package/dist/cli.mjs +1 -1
  33. package/dist/client-Bhl2mWam.mjs +2 -0
  34. package/dist/client-Bhl2mWam.mjs.map +1 -0
  35. package/dist/{client-DR0vYetv.d.mts → client-BzgBm_86.d.mts} +3 -1
  36. package/dist/{client-DjtWangN.mjs → client-aU3YhZ6G.mjs} +16 -16
  37. package/dist/client-aU3YhZ6G.mjs.map +1 -0
  38. package/dist/client.d.mts +1 -1
  39. package/dist/client.mjs +1 -1
  40. package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
  41. package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
  42. package/dist/config.d.mts +1 -1
  43. package/dist/config.mjs +1 -1
  44. package/dist/d1.d.mts +1 -1
  45. package/dist/d1.mjs +1 -1
  46. package/dist/d1.mjs.map +1 -1
  47. package/dist/{datetime-physical-codec-qKxFtI3B.mjs → datetime-physical-codec-lX7IJBlz.mjs} +1 -1
  48. package/dist/{datetime-physical-codec-qKxFtI3B.mjs.map → datetime-physical-codec-lX7IJBlz.mjs.map} +1 -1
  49. package/dist/driver-CQQbCQh9.mjs +2 -0
  50. package/dist/{driver-Bzc0GCQ4.mjs.map → driver-CQQbCQh9.mjs.map} +1 -1
  51. package/dist/{driver-BvP7eW0A.mjs → driver-u2qJicrE.mjs} +2 -2
  52. package/dist/{driver-BvP7eW0A.mjs.map → driver-u2qJicrE.mjs.map} +1 -1
  53. package/dist/driver.d.mts +1 -1
  54. package/dist/driver.mjs +1 -1
  55. package/dist/error-mapping-6op318w6.mjs.map +1 -1
  56. package/dist/every-CzF00eDV.mjs +2 -0
  57. package/dist/{every-WUr3mlvg.mjs.map → every-CzF00eDV.mjs.map} +1 -1
  58. package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
  59. package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.mjs.map} +1 -1
  60. package/dist/{identifier-conversion-Bs7A2GGU.mjs → identifier-conversion-Dc0Rf4Gi.mjs} +2 -2
  61. package/dist/{identifier-conversion-Bs7A2GGU.mjs.map → identifier-conversion-Dc0Rf4Gi.mjs.map} +1 -1
  62. package/dist/identity-CmRos0Yf.mjs +2 -0
  63. package/dist/identity-CmRos0Yf.mjs.map +1 -0
  64. package/dist/{index-B_jh2oaQ.d.mts → index-B4IWFJfv.d.mts} +1282 -1053
  65. package/dist/index.d.mts +1 -1
  66. package/dist/index.mjs +1 -1
  67. package/dist/instrumentation.d.mts +1 -1
  68. package/dist/instrumentation.mjs +1 -1
  69. package/dist/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
  70. package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
  71. package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
  72. package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  73. package/dist/{libsql-C8dn4id0.mjs → libsql-CrDXsfpL.mjs} +2 -2
  74. package/dist/{libsql-C8dn4id0.mjs.map → libsql-CrDXsfpL.mjs.map} +1 -1
  75. package/dist/libsql.d.mts +1 -1
  76. package/dist/libsql.mjs +1 -1
  77. package/dist/libsql.mjs.map +1 -1
  78. package/dist/{memory-B7CcHS6I.mjs → memory-TXO4KgBy.mjs} +2 -2
  79. package/dist/{memory-B7CcHS6I.mjs.map → memory-TXO4KgBy.mjs.map} +1 -1
  80. package/dist/migrations/mysql.d.mts +4 -4
  81. package/dist/migrations/mysql.mjs +1 -1
  82. package/dist/migrations/postgres.d.mts +4 -4
  83. package/dist/migrations/postgres.mjs +1 -1
  84. package/dist/migrations/sqlite.d.mts +4 -4
  85. package/dist/migrations/sqlite.mjs +1 -1
  86. package/dist/migrations/storage/durable-object.mjs +1 -1
  87. package/dist/migrations/storage/fs.mjs +1 -1
  88. package/dist/migrations/storage/r2.mjs +1 -1
  89. package/dist/migrations/tenant.d.mts +2 -2
  90. package/dist/migrations/tenant.mjs +1 -1
  91. package/dist/migrations.d.mts +4 -4
  92. package/dist/migrations.mjs +1 -1
  93. package/dist/{mysql-mUmhH9Cf.mjs → mysql-C2vOPcuA.mjs} +2 -2
  94. package/dist/{mysql-mUmhH9Cf.mjs.map → mysql-C2vOPcuA.mjs.map} +1 -1
  95. package/dist/mysql-adapter-C5CMIYRS.mjs +2 -0
  96. package/dist/{mysql-adapter-ABpgFB2N.mjs.map → mysql-adapter-C5CMIYRS.mjs.map} +1 -1
  97. package/dist/mysql2.d.mts +1 -1
  98. package/dist/mysql2.mjs +1 -1
  99. package/dist/mysql2.mjs.map +1 -1
  100. package/dist/neon-http.d.mts +3 -1
  101. package/dist/neon-http.mjs +1 -1
  102. package/dist/neon-http.mjs.map +1 -1
  103. package/dist/normalized-result-BF7gr4_b.mjs +2 -0
  104. package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
  105. package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
  106. package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
  107. package/dist/{object-store-Ds9NKRU6.d.mts → object-store-uRqi0URP.d.mts} +3 -3
  108. package/dist/permissions.d.mts +1 -1
  109. package/dist/pg.d.mts +26 -1
  110. package/dist/pg.mjs +1 -1
  111. package/dist/pg.mjs.map +1 -1
  112. package/dist/pglite.d.mts +3 -1
  113. package/dist/pglite.mjs +1 -1
  114. package/dist/pglite.mjs.map +1 -1
  115. package/dist/{pinned-session-C79aDzOg.mjs → pinned-session-FYOFV_gB.mjs} +2 -2
  116. package/dist/{pinned-session-C79aDzOg.mjs.map → pinned-session-FYOFV_gB.mjs.map} +1 -1
  117. package/dist/planetscale.d.mts +1 -1
  118. package/dist/planetscale.mjs +1 -1
  119. package/dist/planetscale.mjs.map +1 -1
  120. package/dist/{planner-DHZG9Vy7.d.mts → planner-SzkGh-3T.d.mts} +1 -1
  121. package/dist/{postgres-BACQ_wqF.mjs → postgres-BSmy1PYR.mjs} +2 -2
  122. package/dist/{postgres-BACQ_wqF.mjs.map → postgres-BSmy1PYR.mjs.map} +1 -1
  123. package/dist/postgres-adapter-B1RyJlWL.mjs +2 -0
  124. package/dist/{postgres-adapter-DaMvNOkx.mjs.map → postgres-adapter-B1RyJlWL.mjs.map} +1 -1
  125. package/dist/postgres-adapter-BAqRfWl1.mjs +2 -0
  126. package/dist/postgres-adapter-BAqRfWl1.mjs.map +1 -0
  127. package/dist/postgres-result-BCUQf8b_.mjs +2 -0
  128. package/dist/{postgres-result-D403cLyA.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
  129. package/dist/postgres.d.mts +3 -1
  130. package/dist/postgres.mjs +1 -1
  131. package/dist/postgres.mjs.map +1 -1
  132. package/dist/{provider-limits-DSv2tYFr.mjs → provider-limits-V09frtmK.mjs} +1 -1
  133. package/dist/{provider-limits-DSv2tYFr.mjs.map → provider-limits-V09frtmK.mjs.map} +1 -1
  134. package/dist/relation-bound-BrZLsSke.mjs +2 -0
  135. package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
  136. package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
  137. package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
  138. package/dist/result-shape-Fi1-Fvri.mjs +2 -0
  139. package/dist/result-shape-Fi1-Fvri.mjs.map +1 -0
  140. package/dist/{rows-v1VuwOTa.mjs → rows-BiaiswSV.mjs} +2 -2
  141. package/dist/{rows-v1VuwOTa.mjs.map → rows-BiaiswSV.mjs.map} +1 -1
  142. package/dist/schema/json.d.mts +1 -1
  143. package/dist/{schema-introspection-TdJrSaKd.mjs → schema-introspection-C1-XrQP4.mjs} +2 -2
  144. package/dist/{schema-introspection-TdJrSaKd.mjs.map → schema-introspection-C1-XrQP4.mjs.map} +1 -1
  145. package/dist/{schema-D3-ScVH6.mjs → schema-tGtziyCJ.mjs} +1 -1
  146. package/dist/{schema-D3-ScVH6.mjs.map → schema-tGtziyCJ.mjs.map} +1 -1
  147. package/dist/schema.d.mts +1 -1
  148. package/dist/schema.mjs +1 -1
  149. package/dist/select-assembly-BjT_fDbu.mjs +2 -0
  150. package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
  151. package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
  152. package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
  153. package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
  154. package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
  155. package/dist/soft-delete.d.mts +3 -3
  156. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
  157. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
  158. package/dist/sqlite-adapter-CoDeF2h2.mjs +2 -0
  159. package/dist/sqlite-adapter-CoDeF2h2.mjs.map +1 -0
  160. package/dist/{sqlite-utils-BvSlEs5W.mjs → sqlite-utils-C0TyzOys.mjs} +2 -2
  161. package/dist/{sqlite-utils-BvSlEs5W.mjs.map → sqlite-utils-C0TyzOys.mjs.map} +1 -1
  162. package/dist/sqlite3.d.mts +1 -1
  163. package/dist/sqlite3.mjs +1 -1
  164. package/dist/sqlite3.mjs.map +1 -1
  165. package/dist/{standard-sql-CYdZ_KXH.mjs → standard-sql-DmKF8msN.mjs} +2 -2
  166. package/dist/{standard-sql-CYdZ_KXH.mjs.map → standard-sql-DmKF8msN.mjs.map} +1 -1
  167. package/dist/transaction-operation-CU1zlxiG.mjs.map +1 -1
  168. package/dist/{utils-Qr8ug94X.mjs → utils-DkAxKcDD.mjs} +1 -1
  169. package/dist/{utils-Qr8ug94X.mjs.map → utils-DkAxKcDD.mjs.map} +1 -1
  170. package/dist/{validation-CPnrLcjW.mjs → validation-C7Z6wTJa.mjs} +1 -1
  171. package/dist/{validation-CPnrLcjW.mjs.map → validation-C7Z6wTJa.mjs.map} +1 -1
  172. package/dist/validation.d.mts +1 -1
  173. package/dist/validation.mjs +1 -1
  174. package/dist/version-n393hhwM.mjs +2 -0
  175. package/dist/{version-0RVYpih5.mjs.map → version-n393hhwM.mjs.map} +1 -1
  176. package/package.json +14 -14
  177. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs +0 -2
  178. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs.map +0 -1
  179. package/dist/builder-D6Ug-zjM.mjs +0 -2
  180. package/dist/builder-D6Ug-zjM.mjs.map +0 -1
  181. package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
  182. package/dist/chain-B5IbqLGi.mjs +0 -2
  183. package/dist/chain-B5IbqLGi.mjs.map +0 -1
  184. package/dist/client-BmcHzDBa.mjs +0 -2
  185. package/dist/client-BmcHzDBa.mjs.map +0 -1
  186. package/dist/client-DjtWangN.mjs.map +0 -1
  187. package/dist/driver-Bzc0GCQ4.mjs +0 -2
  188. package/dist/every-WUr3mlvg.mjs +0 -2
  189. package/dist/identity-Bj2EN6Ss.mjs +0 -2
  190. package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
  191. package/dist/mysql-adapter-ABpgFB2N.mjs +0 -2
  192. package/dist/postgres-adapter-Ci07rgh_.mjs +0 -2
  193. package/dist/postgres-adapter-Ci07rgh_.mjs.map +0 -1
  194. package/dist/postgres-adapter-DaMvNOkx.mjs +0 -2
  195. package/dist/postgres-result-D403cLyA.mjs +0 -2
  196. package/dist/result-shape-BKydBCsR.mjs +0 -2
  197. package/dist/result-shape-BKydBCsR.mjs.map +0 -1
  198. package/dist/select-assembly-uZfvbYjz.mjs +0 -2
  199. package/dist/select-assembly-uZfvbYjz.mjs.map +0 -1
  200. package/dist/sqlite-adapter-DPc9T6Lh.mjs +0 -2
  201. package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +0 -1
  202. package/dist/version-0RVYpih5.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"sql-statement-tokens-BW7Q-rF-.mjs","names":[],"sources":["../src/drivers/shared/sql-statement-tokens.ts"],"sourcesContent":["export interface SQLStatementToken {\n depth: number;\n kind: \"identifier\" | \"word\" | \"symbol\";\n value: string;\n}\n\nexport interface SQLStatementTokenOptions {\n /** MySQL string literals may escape the next character with a backslash. */\n backslashEscapes?: boolean;\n}\n\nconst WHITESPACE_REGEX = /\\s/;\nconst WORD_START_REGEX = /[A-Za-z_]/;\nconst WORD_PART_REGEX = /[A-Za-z0-9_$]/;\n\n/** Tokenize one SQL statement while ignoring comments, strings, and parameters. */\nexport function getTopLevelStatementTokens(\n sql: string,\n options: SQLStatementTokenOptions = {}\n): SQLStatementToken[] | undefined {\n const tokens: SQLStatementToken[] = [];\n let depth = 0;\n let index = 0;\n let statementEnded = false;\n\n while (index < sql.length) {\n const char = sql[index];\n const next = sql[index + 1];\n if (!char) break;\n if (WHITESPACE_REGEX.test(char)) {\n index += 1;\n continue;\n }\n if (char === \"-\" && next === \"-\") {\n index = skipLineComment(sql, index + 2);\n continue;\n }\n if (char === \"/\" && next === \"*\") {\n const commentEnd = sql.indexOf(\"*/\", index + 2);\n if (commentEnd < 0) return undefined;\n index = commentEnd + 2;\n continue;\n }\n if (char === \"'\") {\n const quotedEnd = skipQuoted(\n sql,\n index,\n char,\n options.backslashEscapes === true\n );\n if (quotedEnd < 0 || statementEnded) return undefined;\n index = quotedEnd;\n continue;\n }\n if (char === '\"' || char === \"`\" || char === \"[\") {\n const quote = char === \"[\" ? \"]\" : char;\n const identifier = readQuotedIdentifier(sql, index, quote);\n if (!identifier || statementEnded) return undefined;\n tokens.push({\n depth,\n kind: \"identifier\",\n value: identifier.value.toUpperCase(),\n });\n index = identifier.end;\n continue;\n }\n if (char === \";\" && depth === 0) {\n statementEnded = true;\n index += 1;\n continue;\n }\n if (statementEnded) return undefined;\n if (\n (char === \":\" || char === \"@\" || char === \"$\") &&\n WORD_START_REGEX.test(next ?? \"\")\n ) {\n index += 2;\n while (index < sql.length && WORD_PART_REGEX.test(sql[index] ?? \"\")) {\n index += 1;\n }\n continue;\n }\n if (char === \"(\") {\n tokens.push({ depth, kind: \"symbol\", value: char });\n depth += 1;\n index += 1;\n continue;\n }\n if (char === \")\") {\n depth -= 1;\n if (depth < 0) return undefined;\n tokens.push({ depth, kind: \"symbol\", value: char });\n index += 1;\n continue;\n }\n if (char === \"=\") {\n tokens.push({ depth, kind: \"symbol\", value: char });\n index += 1;\n continue;\n }\n if (WORD_START_REGEX.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && WORD_PART_REGEX.test(sql[index] ?? \"\")) {\n index += 1;\n }\n tokens.push({\n depth,\n kind: \"word\",\n value: sql.slice(start, index).toUpperCase(),\n });\n continue;\n }\n index += 1;\n }\n\n if (depth !== 0) return undefined;\n return tokens.filter((token) => token.depth === 0);\n}\n\nfunction skipLineComment(sql: string, index: number): number {\n const lineEnd = sql.indexOf(\"\\n\", index);\n return lineEnd < 0 ? sql.length : lineEnd + 1;\n}\n\nfunction skipQuoted(\n sql: string,\n index: number,\n quote: string,\n backslashEscapes: boolean\n): number {\n let cursor = index + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n if (cursor + 1 >= sql.length) return -1;\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== quote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return -1;\n}\n\nfunction readQuotedIdentifier(\n sql: string,\n index: number,\n quote: string\n): { end: number; value: string } | undefined {\n let cursor = index + 1;\n let value = \"\";\n while (cursor < sql.length) {\n const char = sql[cursor];\n if (char !== quote) {\n value += char;\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n value += quote;\n cursor += 2;\n continue;\n }\n return { end: cursor + 1, value };\n }\n return undefined;\n}\n"],"mappings":"yCAWA,MAAM,EAAmB,KACnB,EAAmB,YACnB,EAAkB,gBAGxB,SAAgB,2BACd,EACA,EAAoC,EAAE,CACL,CACjC,IAAM,EAA8B,EAAE,CAClC,EAAQ,EACR,EAAQ,EACR,EAAiB,GAErB,KAAO,EAAQ,EAAI,QAAQ,CACzB,IAAM,EAAO,EAAI,GACX,EAAO,EAAI,EAAQ,GACzB,GAAI,CAAC,EAAM,MACX,GAAI,EAAiB,KAAK,EAAK,CAAE,CAC/B,GAAS,EACT,SAEF,GAAI,IAAS,KAAO,IAAS,IAAK,CAChC,EAAQ,gBAAgB,EAAK,EAAQ,EAAE,CACvC,SAEF,GAAI,IAAS,KAAO,IAAS,IAAK,CAChC,IAAM,EAAa,EAAI,QAAQ,KAAM,EAAQ,EAAE,CAC/C,GAAI,EAAa,EAAG,OACpB,EAAQ,EAAa,EACrB,SAEF,GAAI,IAAS,IAAK,CAChB,IAAM,EAAY,WAChB,EACA,EACA,EACA,EAAQ,mBAAqB,GAC9B,CACD,GAAI,EAAY,GAAK,EAAgB,OACrC,EAAQ,EACR,SAEF,GAAI,IAAS,KAAO,IAAS,KAAO,IAAS,IAAK,CAEhD,IAAM,EAAa,qBAAqB,EAAK,EAD/B,IAAS,IAAM,IAAM,EACuB,CAC1D,GAAI,CAAC,GAAc,EAAgB,OACnC,EAAO,KAAK,CACV,QACA,KAAM,aACN,MAAO,EAAW,MAAM,aAAa,CACtC,CAAC,CACF,EAAQ,EAAW,IACnB,SAEF,GAAI,IAAS,KAAO,IAAU,EAAG,CAC/B,EAAiB,GACjB,GAAS,EACT,SAEF,GAAI,EAAgB,OACpB,IACG,IAAS,K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AAO,EAAS,EAElB,MAAO,GAGT,SAAS,qBACP,EACA,EACA,EAC4C,CAC5C,IAAI,EAAS,EAAQ,EACjB,EAAQ,GACZ,KAAO,EAAS,EAAI,QAAQ,CAC1B,IAAM,EAAO,EAAI,GACjB,GAAI,IAAS,EAAO,CAClB,GAAS,EACT,GAAU,EACV,SAEF,GAAI,EAAI,EAAS,KAAO,EAAO,CAC7B,GAAS,EACT,GAAU,EACV,SAEF,MAAO,CAAE,IAAK,EAAS,EAAG,QAAO"}
1
+ {"version":3,"file":"sql-statement-tokens-4J5l5Lyt.mjs","names":[],"sources":["../src/drivers/shared/sql-statement-tokens.ts"],"sourcesContent":["export interface SQLStatementToken {\n depth: number;\n kind: \"identifier\" | \"word\" | \"symbol\";\n value: string;\n}\n\nexport interface SQLStatementTokenOptions {\n /** MySQL string literals may escape the next character with a backslash. */\n backslashEscapes?: boolean;\n}\n\nconst WHITESPACE_REGEX = /\\s/;\nconst WORD_START_REGEX = /[A-Za-z_]/;\nconst WORD_PART_REGEX = /[A-Za-z0-9_$]/;\n\n/** Tokenize one SQL statement while ignoring comments, strings, and parameters. */\nexport function getTopLevelStatementTokens(\n sql: string,\n options: SQLStatementTokenOptions = {}\n): SQLStatementToken[] | undefined {\n const tokens: SQLStatementToken[] = [];\n let depth = 0;\n let index = 0;\n let statementEnded = false;\n\n while (index < sql.length) {\n const char = sql[index];\n const next = sql[index + 1];\n if (!char) break;\n if (WHITESPACE_REGEX.test(char)) {\n index += 1;\n continue;\n }\n if (char === \"-\" && next === \"-\") {\n index = skipLineComment(sql, index + 2);\n continue;\n }\n if (char === \"/\" && next === \"*\") {\n const commentEnd = sql.indexOf(\"*/\", index + 2);\n if (commentEnd < 0) return undefined;\n index = commentEnd + 2;\n continue;\n }\n if (char === \"'\") {\n const quotedEnd = skipQuoted(\n sql,\n index,\n char,\n options.backslashEscapes === true\n );\n if (quotedEnd < 0 || statementEnded) return undefined;\n index = quotedEnd;\n continue;\n }\n if (char === '\"' || char === \"`\" || char === \"[\") {\n const quote = char === \"[\" ? \"]\" : char;\n const identifier = readQuotedIdentifier(sql, index, quote);\n if (!identifier || statementEnded) return undefined;\n tokens.push({\n depth,\n kind: \"identifier\",\n value: identifier.value.toUpperCase(),\n });\n index = identifier.end;\n continue;\n }\n if (char === \";\" && depth === 0) {\n statementEnded = true;\n index += 1;\n continue;\n }\n if (statementEnded) return undefined;\n if (\n (char === \":\" || char === \"@\" || char === \"$\") &&\n WORD_START_REGEX.test(next ?? \"\")\n ) {\n index += 2;\n while (index < sql.length && WORD_PART_REGEX.test(sql[index] ?? \"\")) {\n index += 1;\n }\n continue;\n }\n if (char === \"(\") {\n tokens.push({ depth, kind: \"symbol\", value: char });\n depth += 1;\n index += 1;\n continue;\n }\n if (char === \")\") {\n depth -= 1;\n if (depth < 0) return undefined;\n tokens.push({ depth, kind: \"symbol\", value: char });\n index += 1;\n continue;\n }\n if (char === \"=\") {\n tokens.push({ depth, kind: \"symbol\", value: char });\n index += 1;\n continue;\n }\n if (WORD_START_REGEX.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && WORD_PART_REGEX.test(sql[index] ?? \"\")) {\n index += 1;\n }\n tokens.push({\n depth,\n kind: \"word\",\n value: sql.slice(start, index).toUpperCase(),\n });\n continue;\n }\n index += 1;\n }\n\n if (depth !== 0) return undefined;\n return tokens.filter((token) => token.depth === 0);\n}\n\nfunction skipLineComment(sql: string, index: number): number {\n const lineEnd = sql.indexOf(\"\\n\", index);\n return lineEnd < 0 ? sql.length : lineEnd + 1;\n}\n\nfunction skipQuoted(\n sql: string,\n index: number,\n quote: string,\n backslashEscapes: boolean\n): number {\n let cursor = index + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n if (cursor + 1 >= sql.length) return -1;\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== quote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return -1;\n}\n\nfunction readQuotedIdentifier(\n sql: string,\n index: number,\n quote: string\n): { end: number; value: string } | undefined {\n let cursor = index + 1;\n let value = \"\";\n while (cursor < sql.length) {\n const char = sql[cursor];\n if (char !== quote) {\n value += char;\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n value += quote;\n cursor += 2;\n continue;\n }\n return { end: cursor + 1, value };\n }\n return undefined;\n}\n"],"mappings":"yCAWA,MAAM,EAAmB,KACnB,EAAmB,YACnB,EAAkB,gBAGxB,SAAgB,2BACd,EACA,EAAoC,EAAE,CACL,CACjC,IAAM,EAA8B,EAAE,CAClC,EAAQ,EACR,EAAQ,EACR,EAAiB,GAErB,KAAO,EAAQ,EAAI,QAAQ,CACzB,IAAM,EAAO,EAAI,GACX,EAAO,EAAI,EAAQ,GACzB,GAAI,CAAC,EAAM,MACX,GAAI,EAAiB,KAAK,EAAK,CAAE,CAC/B,GAAS,EACT,SAEF,GAAI,IAAS,KAAO,IAAS,IAAK,CAChC,EAAQ,gBAAgB,EAAK,EAAQ,EAAE,CACvC,SAEF,GAAI,IAAS,KAAO,IAAS,IAAK,CAChC,IAAM,EAAa,EAAI,QAAQ,KAAM,EAAQ,EAAE,CAC/C,GAAI,EAAa,EAAG,OACpB,EAAQ,EAAa,EACrB,SAEF,GAAI,IAAS,IAAK,CAChB,IAAM,EAAY,WAChB,EACA,EACA,EACA,EAAQ,mBAAqB,GAC9B,CACD,GAAI,EAAY,GAAK,EAAgB,OACrC,EAAQ,EACR,SAEF,GAAI,IAAS,KAAO,IAAS,KAAO,IAAS,IAAK,CAEhD,IAAM,EAAa,qBAAqB,EAAK,EAD/B,IAAS,IAAM,IAAM,EACuB,CAC1D,GAAI,CAAC,GAAc,EAAgB,OACnC,EAAO,KAAK,CACV,QACA,KAAM,aACN,MAAO,EAAW,MAAM,aAAa,CACtC,CAAC,CACF,EAAQ,EAAW,IACnB,SAEF,GAAI,IAAS,KAAO,IAAU,EAAG,CAC/B,EAAiB,GACjB,G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AI,EAAS,KAAO,EAAO,CAC7B,GAAU,EACV,SAEF,OAAO,EAAS,EAElB,MAAO,GAGT,SAAS,qBACP,EACA,EACA,EAC4C,CAC5C,IAAI,EAAS,EAAQ,EACjB,EAAQ,GACZ,KAAO,EAAS,EAAI,QAAQ,CAC1B,IAAM,EAAO,EAAI,GACjB,GAAI,IAAS,EAAO,CAClB,GAAS,EACT,GAAU,EACV,SAEF,GAAI,EAAI,EAAS,KAAO,EAAO,CAC7B,GAAS,EACT,GAAU,EACV,SAEF,MAAO,CAAE,IAAK,EAAS,EAAG,QAAO"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,m as n}from"./validation-gwZYm3Yn.mjs";import{E as r}from"./geo-point-codec-D95uXgDF.mjs";import{o as i,t as a}from"./sql-BvHwL73I.mjs";import{a as o,t as s}from"./physical-uJfmo4-Z.mjs";import{t as c}from"./adapter-result-parser-D6lluSMi.mjs";import{r as l}from"./adapter-internals-Cy2QEBnH.mjs";import{i as u}from"./datetime-physical-codec-lX7IJBlz.mjs";import{t as ee}from"./json-number-CGXpPu4D.mjs";import{C as d,D as f,E as p,M as m,N as h,O as te,S as ne,T as re,_ as ie,a as ae,b as oe,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,n as w,o as T,p as E,r as D,s as O,v as k,w as A,x as j,y as M}from"./standard-sql-DmKF8msN.mjs";import{r as N,t as P}from"./batch-refs-BYCu1JnQ.mjs";import{f as F,h as I,n as L,o as R,p as z,r as B,t as V,u as H}from"./select-assembly-BjT_fDbu.mjs";const U=h(`"`),W={quotient:(e,t)=>i`(${e} / ${t})`,remainder:(e,t)=>i`(${e} % ${t})`};function sqliteIntegerPrecision(e){let t=te(e);if(t<19)return t;if(!(t>19))return(e.startsWith(`-`)?e.slice(1)<=`9223372036854775808`:e<=`9223372036854775807`)?t:void 0}const G=i.raw(`1000000000000000000`),overflowCoefficient=e=>i.raw(`1${`0`.repeat(Math.min(e.precision,18))}`),guardedCoefficientAssignment=(e,t,n,r)=>i`${e} = CASE WHEN ${e} IS NULL OR ${t} THEN ${n} ELSE ${overflowCoefficient(r)} END`,K=/^\d+$/,q=/["\\]/,jsonPathLeg=e=>{if(K.test(e))return`$[${e}]`;if(q.test(e))throw Error(`SQLite JSON path segments containing " or \\ must be rejected by the portable query contract.`);return`$."${e}"`},jsonExtract=(e,t)=>{let n=i`${e} -> '$'`;for(let e of t)n=i`${n} -> ${jsonPathLeg(e)}`;return n},jsonExtractText=(e,t)=>{if(t.length===0)return i`${e} ->> '$'`;let n=t.map(jsonPathLeg),r=n.pop(),a=e;for(let e of n)a=i`${a} -> ${e}`;return i`${a} ->> ${r}`},jsonArrayConcat=(e,t)=>i`(CASE WHEN ${e} = '[]' THEN ${t} WHEN ${t} = '[]' THEN ${e} ELSE substr(${e}, 1, length(${e}) - 1) || ',' || substr(${t}, 2) END)`,sqliteJsonListValue=e=>i`${m(e)}`,se=[``,``],J=[`CAST(`,` AS INTEGER)`],ce=/\p{Cs}/u,Y=p().list;function jsonMember(e){return typeof e==`string`?ce.test(e)?void 0:JSON.stringify(e):e instanceof Uint8Array?`"${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}"`:typeof e==`bigint`||typeof e==`boolean`||Number.isSafeInteger(e)?String(e):void 0}function sqliteList(e){if(e.length<=25)return Y(e);let[t]=e,n=t?.strings[0]===J[0]?J:se,r=[],o=0;for(let t of e){let[i,a,s]=t.strings,c=t.values[0],l=jsonMember(c);if(l===void 0||i!==n[0]||a!==n[1]||s!==void 0)return Y(e);c instanceof Uint8Array&&o++,r.push(l)}return o!==0&&o!==e.length?Y(e):i`(SELECT ${new a(n,[i.raw(o===0?`value`:`unhex(value)`)])} FROM json_each(${`[${r.join(`,`)}]`}))`}const X={...p(),value:e=>{if(typeof e==`bigint`&&sqliteIntegerPrecision(String(e))===void 0)throw new n(`SQLite bigint values must fit signed 64-bit integers.`);return i`${e}`},true:()=>i.raw(`1`),false:()=>i.raw(`0`),json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t)=>i`${u(e,s(t))}`,decimal:(e,t)=>new a(J,[r(e,t,`coefficient`)]),id:(e,t)=>i`${e}`,list:sqliteList},Z={...ae(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>i`lower(${e}) LIKE lower(${t}) ESCAPE '\\'`,notIlike:(e,t)=>i`lower(${e}) NOT LIKE lower(${t}) ESCAPE '\\'`,containsText:(e,t)=>i`instr(${e}, ${t}) > 0`,startsWithText:(e,t)=>i`substr(${e}, 1, length(${t})) COLLATE BINARY = ${t}`,endsWithText:(e,t)=>i`substr(${e}, length(${e}) - length(${t}) + 1) COLLATE BINARY = ${t}`,startsWithPrefix:(e,t)=>i`${e} GLOB ${`${S(t)}*`}`,exactTextEq:(e,t)=>i`${e} COLLATE BINARY = ${t}`,exactTextIn:(e,t)=>i`${e} COLLATE BINARY IN ${t}`,...v(),...k(),...j(),...y(X.true,X.false),...g()},le={...b(),asciiCaseFold:e=>i`lower(${e})`,caseSensitiveText:e=>i`${e} COLLATE BINARY`,concat:(...e)=>e.length===0?i.raw(`''`):e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`MAX(${i.join(e,`, `)})`,least:(...e)=>i`MIN(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / CAST(${t} AS INTEGER))`,decimalCast:(e,t)=>i`CAST(${e} AS INTEGER)`,idCast:(e,t)=>t===`bytes`?i`unhex(${e})`:i`CAST(${e} AS TEXT)`,cast:D({text:`TEXT`,integer:`INTEGER`,bigint:`INTEGER`,boolean:`INTEGER`,numeric:`NUMERIC`}),blobToHex:e=>i`lower(hex(${e}))`},ue={...w(`9e999`),decimalAvg:(e,t)=>R(W,i`SUM(${e})`,i`COUNT(${e})`),decimalSumOperandPrecision:sqliteIntegerPrecision,integerSum:e=>{let t=i`SUM(${e} >> 32)`,n=i`SUM(${e} - ((${e} >> 32) << 32))`,r=i`(${t} + (${n} >> 32))`,a=i`(${n} & 4294967295)`,o=i`${r} * 4294967296.0 + ${a}`;return{parts:[t,n],value:i`CASE WHEN ${r} > 2147483647 THEN ${o} WHEN ${r} >= -2147483648 THEN ${r} * 4294967296 + ${a} ELSE MIN(${o}, -9223372036854777856.0) END`,order:[r,a]}}};function sqliteJsonEquals(e,t){let nodes=e=>i`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${e})`;return i`(CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(e)} EXCEPT ${nodes(t)}) AND NOT EXISTS (${nodes(t)} EXCEPT ${nodes(e)}) END)`}const sqliteJsonObject=e=>{if(e.length===0)return i.raw(`json_object()`);let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`json_object(${i.join(t,`, `)})`},de={equals:sqliteJsonEquals,number:e=>i`CASE WHEN ${e} IS NULL THEN NULL ELSE printf(${i.raw(`'${ee}'`)}, ${e}) END`,boolean:e=>i`json(CASE WHEN ${e} THEN 'true' ELSE 'false' END)`,document:e=>i`json(${e})`,object:sqliteJsonObject,array:e=>e.length===0?i.raw(`json_array()`):i`json_array(${i.join(e,`, `)})`,emptyArray:()=>i.raw(`json_array()`),agg:e=>i`json_group_array(${e})`,objectFromColumns:sqliteJsonObject,extract:jsonExtract,extractText:jsonExtractText,numberAtPath:(e,t)=>i`(CASE WHEN json_type(${jsonExtract(e,t)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(e,t)} AS REAL) END)`,stringAtPath:(e,t)=>i`((CASE WHEN json_type(${jsonExtract(e,t)}) = 'text' THEN ${jsonExtractText(e,t)} END) COLLATE BINARY)`,contains:(e,t)=>i`(json_type(${e}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${t}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${e}) AS candidate WHERE ${sqliteJsonEquals(i`${e} -> candidate.fullkey`,i`${t} -> required.fullkey`)})))`,lastElement:e=>i`${e} -> '$[#-1]'`,value:e=>i`${m(e)}`},fe={literal:e=>e.length===0?i.raw(`json_array()`):i`json_array(${i.join(e,`, `)})`,value:sqliteJsonListValue,enumValue:sqliteJsonListValue,has:(e,t)=>i`EXISTS (SELECT 1 FROM json_each(${e}) WHERE value = ${t})`,hasEvery:(e,t)=>i`(SELECT COUNT(*) FROM json_each(${t}) WHERE value IN (SELECT value FROM json_each(${e}))) = json_array_length(${t})`,hasSome:(e,t)=>i`EXISTS (SELECT 1 FROM json_each(${e}) AS a, json_each(${t}) AS b WHERE a.value = b.value)`,isEmpty:e=>i`(json_array_length(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT)`,length:e=>i`json_array_length(${e})`,get:(e,t)=>i`json_extract(${e}, '$[' || ${t} || ']')`,push:(e,t)=>i`json_insert(${e}, '$[#]', ${t})`,set:(e,t,n)=>i`json_set(${e}, '$[' || ${t} || ']', ${n})`},pe={...C(),nullsFirst:(e,t)=>t===`desc`?i`${e} DESC NULLS FIRST`:i`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?i`${e} DESC NULLS LAST`:i`${e} ASC NULLS LAST`},me={...M(),multiply:(e,t,n)=>{let r=n?.decimal;return r?guardedCoefficientAssignment(e,i`${t} = 0 OR ABS(${e}) <= ${G} / ABS(${t})`,R(W,i`(${e} * ${t})`,H(r.scale)),r):i`${e} = ${e} * ${t}`},divide:(e,t,n)=>{let r=n?.decimal;if(r){let n=H(r.scale);return guardedCoefficientAssignment(e,i`ABS(${e}) <= ${G} / ${n}`,R(W,F(i`(${e} * ${n})`,t),i`ABS(${t})`),r)}return n?.integer?i`${e} = ${e} / CAST(${t} AS INTEGER)`:i`${e} = ${e} / ${t}`},push:(e,t)=>i`${e} = ${jsonArrayConcat(i`json(COALESCE(${e}, '[]'))`,t)}`,unshift:(e,t)=>i`${e} = ${jsonArrayConcat(t,i`json(COALESCE(${e}, '[]'))`)}`},Q={skipDuplicatesStrategy:`sql`,insert:E(U),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...ie(),returning:e=>i`RETURNING ${e}`,...oe()},he={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE json_extract('{}', '__viborm_refused__') END AS "__viborm_judged__"${t?i` FROM ${t}`:i``}`},ge={...T(),right:(e,t)=>{throw Error(`SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.`)},full:(e,t)=>{throw Error(`SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},lateral:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)},lateralLeft:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)}},_e={supportsReturning:!0,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!1,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!1,joinsJunctionFilters:!0},ve={decimalRepresentation:`coefficient`,decimalListRepresentation:`coefficient`,dateTimeRepresentation:s,idRepresentation:(e,t)=>o(e,t,`sqlite`)?.representation??`text`,parseResult:c,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()},ye=_(U),be=re(),xe=d(),$=f(U),Se=O(U,{materializing:i.raw(`MATERIALIZED`)}),Ce=A(U,(e,t,n)=>i`(${e.head} UNION ALL VALUES ${i.join(t.map(x),`, `)}) AS ${i.raw(U(n))}`),we=ne();function balancedConjunction(e){let balanced=(...t)=>{if(t.length<=2)return e(...t);let n=Math.floor(t.length/2);return e(balanced(...t.slice(0,n)),balanced(...t.slice(n)))};return balanced}var SQLiteAdapter=class{constructor({temporaryObjects:e=!0,deepExpressions:t=!0,sharedRelationBodies:n=!1,compoundSelectTerms:r,relationsPerStatement:a}={}){z(this,this.geoPoint),t||(this.subqueries.existsCheck=(e,t)=>i`SELECT 1 FROM (${$.existsCheck(e,t)})`,this.subqueries.isolated=e=>i`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${e}))`,this.operators.and=balancedConjunction(Z.and),this.capabilities.boundsExpressionDepth=!0),n&&(this.capabilities.sharesRelationBodies=!0),r!==void 0&&(this.capabilities.compoundSelectTerms=r),a!==void 0&&(this.capabilities.relationsPerStatement=a);let o,createBatchRefs=()=>this.#t(e);l(this,{get batchRefs(){return o??=createBatchRefs(),o},constraints:I,select:this.#e.select})}raw=we;identifiers={...ye};literals={...X};operators={...Z};expressions={...le};aggregates={...ue};json={...de};arrays={...fe};orderBy={...pe};clauses={...be};set={...me};filters={...xe};subqueries={...$};noLimitValue=i.raw(`-1`);#e={select:e=>e.distinct?V(e,e.distinct,this.identifiers.escape,this.noLimitValue):L(i`SELECT ${e.columns}`,e,{forUpdate:`omit`,noLimitValue:this.noLimitValue})};cte={...Se};mutations={...Q};assertions={...he};joins={...ge};setOperations={...Ce};capabilities={..._e};lastInsertId=()=>i.raw(`last_insert_rowid()`);#t(e){let t=i.raw(U(P)),n=i.raw(e?`CREATE TEMP TABLE IF NOT EXISTS`:`CREATE TABLE IF NOT EXISTS`);return N({table:t,batchIdColumn:i.raw(`"batch_id"`),keyColumn:i.raw(`"ref_key"`),valueColumn:i.raw(`"ref_value"`),createTable:i`${n} ${t} ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>i`CAST((${e}) AS TEXT)`,lastInsertId:()=>this.lastInsertId()})}vector=t;geoPoint=(()=>{let longitude=e=>this.json.numberAtPath(e,[`longitude`]),latitude=e=>this.json.numberAtPath(e,[`latitude`]);return{value:(e,t)=>i`json_object('longitude', ${this.json.document(this.json.number(e))}, 'latitude', ${this.json.document(this.json.number(t))})`,longitude,latitude,...B(longitude,latitude,this.operators)}})();result={...ve}};export{SQLiteAdapter as t};
2
+ //# sourceMappingURL=sqlite-adapter-CoDeF2h2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-adapter-CoDeF2h2.mjs","names":["sql","#createBatchRefs","#assemble"],"sources":["../src/adapters/databases/sqlite/sqlite-adapter.ts"],"sourcesContent":["import { UnsupportedOperationError, unsupportedVector } from \"@errors\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { sqliteConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport {\n BATCH_REFS_TABLE,\n createOnConflictBatchRefs,\n} from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport { createGeoPointCoordinatePredicates } from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n decimalCoefficientPrecision,\n escapeGlobLiteral,\n rowValues,\n stringifyJson,\n} from \"../../shared/standard-sql\";\nimport { SQLITE_BINARY64_FORMAT } from \"./storage/json-number\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n\n/**\n * Every SQLite decimal expression is signed-int64 integer arithmetic on the\n * stored unscaled coefficient, so `/` IS truncating integer division and `%`\n * carries the dividend's sign. Neither is true once an operand becomes REAL or\n * TEXT, which is why every operand below arrives as an INTEGER column, an\n * integer literal, or a `CAST(... AS INTEGER)` bind.\n */\nconst SQLITE_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`(${n} / ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`(${n} % ${d})`,\n};\n\nconst SQLITE_INT64_NEGATIVE_MAGNITUDE = \"9223372036854775808\";\nconst SQLITE_INT64_MAX = \"9223372036854775807\";\n\n/** Admit the exact TEXT-to-INTEGER cast domain, including its 19-digit edges. */\nfunction sqliteIntegerPrecision(coefficient: string): number | undefined {\n const precision = decimalCoefficientPrecision(coefficient);\n if (precision < 19) return precision;\n if (precision > 19) return undefined;\n const isAdmitted = coefficient.startsWith(\"-\")\n ? coefficient.slice(1) <= SQLITE_INT64_NEGATIVE_MAGNITUDE\n : coefficient <= SQLITE_INT64_MAX;\n return isAdmitted ? precision : undefined;\n}\n\n/**\n * The widest intermediate the guarded arms will evaluate: 10^18.\n *\n * SQLite does not raise on an integer multiply that overflows — it converts the\n * expression to REAL, which is the one representation an exact decimal must\n * never touch. So the arms are GUARDED: the guard compares magnitudes by\n * DIVISION (`|x| <= LIMIT / |y|`, exact for integers) instead of computing the\n * product it is protecting, and a `CASE` evaluates only the branch it selects.\n *\n * 10^18 is not arbitrary, and it is not independent. `precision + scale <= 18`\n * is SQLite's declared field limit (plan 3.1), ENFORCED once when the schema is\n * bound (`schema/scalars/decimal/provider-limits.ts`), so every mathematically\n * in-range result has `|x * y| <= 10^(p+s) <= 10^18`: the guard never rejects\n * an answer that fits the field, and int64 keeps a factor of nine in reserve\n * for the `+/- 1` step and the `d - |r|` tie test.\n *\n * THE COUPLING IS LOAD-BEARING, in both directions. This constant is flat where\n * the per-descriptor bound would be `B = scale === 0 ? M : M*F + F/2 - 1`, and\n * that is only equivalent because no descriptor past `p + s = 18` can reach it:\n * a product in `(B, 10^18]` is admitted here and then refused by the range\n * CHECK instead of by the sentinel — the same loud, atomic failure by the other\n * mechanism. Remove the bind limit and the flat guard stops being a bound on\n * the FIELD at all, which is exactly what {@link overflowCoefficient} depends\n * on below.\n */\nconst SQLITE_INTERMEDIATE_LIMIT = sql.raw(\"1000000000000000000\");\n\n/**\n * The coefficient an unsafe or out-of-domain arithmetic result becomes: 10^p,\n * the smallest integer OUTSIDE a `precision: p` field's declared range.\n *\n * The DDL's range check refuses it, so the statement fails atomically and\n * nothing is written — which is the contract for an overflow that is only\n * knowable mid-statement.\n *\n * THE CLAMP DEPENDS ON THE BIND LIMIT, and is only correct because of it. At 19\n * digits and beyond, `10^p` is a REAL to SQLite's own parser, so the sentinel\n * would stop being an integer the CHECK can refuse — and `min(p, 18)` would put\n * it INSIDE the range of a `precision >= 19` column, which is a silently\n * written wrong value rather than a failure. No such column exists: plan 3.1's\n * `precision <= 18 && precision + scale <= 18` is proven once at schema bind\n * (`schema/scalars/decimal/provider-limits.ts`), before any I/O, so\n * `min(p, 18)` is `p` for every descriptor that ever reaches here. The clamp is\n * what an unreachable arm does when it is reached anyway, not a policy — and it\n * is why the bind limit is load-bearing rather than ergonomic.\n */\nconst overflowCoefficient = (descriptor: DecimalDescriptor): Sql =>\n sql.raw(`1${\"0\".repeat(Math.min(descriptor.precision, 18))}`);\n\n/**\n * `column = <exact coefficient arithmetic>`, or the constraint-breaking\n * coefficient when the intermediate would leave int64.\n *\n * A NULL column is safe by definition and takes the guarded arm, where every\n * operator is null-strict and the assignment stays NULL.\n */\nconst guardedCoefficientAssignment = (\n column: Sql,\n safe: Sql,\n value: Sql,\n descriptor: DecimalDescriptor\n): Sql =>\n sql`${column} = CASE WHEN ${column} IS NULL OR ${safe} THEN ${value} ELSE ${overflowCoefficient(descriptor)} END`;\n\nconst JSON_ARRAY_INDEX_SEGMENT = /^\\d+$/;\nconst JSON_UNADDRESSABLE_LABEL = /[\"\\\\]/;\n\n// Each path segment binds as its own single-leg JSONPath ('$[N]' for\n// array indices, '$.\"seg\"' otherwise) chained with -> , so segments can\n// never splice extra legs into the path. SQLite's path grammar has no\n// escape syntax inside quoted labels, so the portable query contract rejects\n// keys containing \" or \\ before adapter execution. This throw is defensive.\nconst jsonPathLeg = (segment: string): string => {\n if (JSON_ARRAY_INDEX_SEGMENT.test(segment)) {\n return `$[${segment}]`;\n }\n if (JSON_UNADDRESSABLE_LABEL.test(segment)) {\n throw new Error(\n 'SQLite JSON path segments containing \" or \\\\ must be rejected by the portable query contract.'\n );\n }\n return `$.\"${segment}\"`;\n};\n\n/** Chain one bound `-> '$leg'` per path segment ('$' alone = document root). */\nconst jsonExtract = (column: Sql, path: string[]): Sql => {\n let expr = sql`${column} -> '$'`;\n for (const segment of path) {\n expr = sql`${expr} -> ${jsonPathLeg(segment)}`;\n }\n return expr;\n};\n\n/** Same chain, but the final leg uses `->>` so strings come back unquoted. */\nconst jsonExtractText = (column: Sql, path: string[]): Sql => {\n if (path.length === 0) {\n return sql`${column} ->> '$'`;\n }\n const legs = path.map(jsonPathLeg);\n const last = legs.pop()!;\n let expr: Sql = column;\n for (const leg of legs) {\n expr = sql`${expr} -> ${leg}`;\n }\n return sql`${expr} ->> ${last}`;\n};\n\n/**\n * Concatenate two JSON array texts by string surgery: strip `left`'s closing\n * bracket and `right`'s opening bracket. SQLite has no JSON array-concat\n * function, and json_insert('$[#]') can only append one element per pair.\n * Both sides must be canonical JSON (json() output or JSON.stringify).\n */\nconst jsonArrayConcat = (left: Sql, right: Sql): Sql =>\n sql`(CASE WHEN ${left} = '[]' THEN ${right} WHEN ${right} = '[]' THEN ${left} ELSE substr(${left}, 1, length(${left}) - 1) || ',' || substr(${right}, 2) END)`;\n\n/** The one JSON list container every SQLite list value crosses as. */\nconst sqliteJsonListValue = (values: unknown[]): Sql =>\n sql`${stringifyJson(values)}`;\n\n/** A bare operand, and a decimal operand: its coefficient read as INTEGER. */\nconst PARAMETER = [\"\", \"\"];\nconst COEFFICIENT = [\"CAST(\", \" AS INTEGER)\"];\nconst LONE_SURROGATE = /\\p{Cs}/u;\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n/**\n * The longest list kept parenthesized. Without `sqlite_stat1` SQLite sizes an\n * `IN (SELECT …)` at 25 rows and a list at its length, so up to 25 members the\n * list is planned no worse: a key list beside another indexed equality still\n * seeks the key. It is also a quarter of D1's 100-value bind budget.\n */\nconst PLANNED_LIST = 25;\n\n/**\n * One member as JSON text that `json_each` reads back as the value its own\n * parameter binds, or `undefined`. A non-integer number is not one: SQLite\n * reparses JSON text with an error in the last place for some doubles; nor is\n * a string with a lone surrogate, which a driver binds as U+FFFD.\n */\nfunction jsonMember(value: unknown): string | undefined {\n if (typeof value === \"string\")\n return LONE_SURROGATE.test(value) ? undefined : JSON.stringify(value);\n if (value instanceof Uint8Array)\n return `\"${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}\"`;\n return typeof value === \"bigint\" ||\n typeof value === \"boolean\" ||\n Number.isSafeInteger(value)\n ? String(value)\n : undefined;\n}\n\n/**\n * engine-09: a list longer than {@link PLANNED_LIST} whose members are each one\n * parameter under one spelling — bare, or a decimal's coefficient cast — as\n * ONE parameter, a JSON array `json_each` reads back and spells per element as\n * each member was, so `IN` and `NOT IN` keep their answers, NULLs included.\n * Blobs travel as hex, read through `unhex` (SQLite 3.41). Any other list\n * keeps a parameter per member.\n */\nfunction sqliteList(members: Sql[]): Sql {\n if (members.length <= PLANNED_LIST) return PARENTHESIZED_LIST(members);\n const [first] = members;\n const spelling =\n first?.strings[0] === COEFFICIENT[0] ? COEFFICIENT : PARAMETER;\n const elements: string[] = [];\n let blobs = 0;\n for (const member of members) {\n const [head, tail, extra] = member.strings;\n const value = member.values[0];\n const element = jsonMember(value);\n if (\n element === undefined ||\n head !== spelling[0] ||\n tail !== spelling[1] ||\n extra !== undefined\n )\n return PARENTHESIZED_LIST(members);\n if (value instanceof Uint8Array) blobs++;\n elements.push(element);\n }\n // Blobs beside other values: nothing one spelling reads.\n if (blobs !== 0 && blobs !== members.length)\n return PARENTHESIZED_LIST(members);\n const read = new Sql(spelling, [\n sql.raw(blobs === 0 ? \"value\" : \"unhex(value)\"),\n ]);\n return sql`(SELECT ${read} FROM json_each(${`[${elements.join(\",\")}]`}))`;\n}\n\n/** Facts a SQLite driver states about its transport. */\nexport interface SQLiteAdapterOptions {\n /**\n * Whether the transport admits temporary objects (`CREATE TEMP TABLE`).\n * better-sqlite3, libSQL and bun:sqlite do; Cloudflare D1's authorizer\n * rejects them with `SQLITE_AUTH`, and rejects the whole batch with them.\n * Defaults to `true`.\n */\n readonly temporaryObjects?: boolean;\n /**\n * Whether the transport compiles deep expression trees. SQLite counts a\n * subquery's `WHERE` in the height of the expression that holds it, and sums\n * those heights again while it resolves names, so k nested relation filters\n * cost about k² of `SQLITE_MAX_EXPR_DEPTH`: SQLite's default (1000) admits\n * that; Cloudflare D1 compiles with 100 and refuses \"Expression tree is too\n * large\". Where it does not, each relation filter reads its rows from a\n * derived table, whose `WHERE` neither count reaches through the expression:\n * about four per level, the same plan (SQLite flattens it), one statement.\n * A conjunction of many members nests as a balanced tree where it does not,\n * as the engine already nests a disjunction: SQLite parses `a AND b AND …`\n * one level per member. A level's row domain, where the filter goes on\n * below it, is isolated the same way (`subqueries.isolated`), so a policy\n * costs its height once and not at every level (measured on D1: a\n * three-arm read policy 10 per level, failing at 9 levels; isolated, 5 per\n * level, 94 at the 15 levels admission takes).\n * Defaults to `true`.\n */\n readonly deepExpressions?: boolean;\n /**\n * Whether a statement states each relation filter body it repeats once\n * (`capabilities.sharesRelationBodies`), for a\n * transport that bounds statement text (Cloudflare D1: 100 KB). Defaults\n * to `false`.\n */\n readonly sharedRelationBodies?: boolean;\n /**\n * The most terms one compound `SELECT` may chain\n * (`capabilities.compoundSelectTerms`): Cloudflare D1 compiles SQLite with\n * 5 and refuses a sixth (\"too many terms in compound SELECT\"). Defaults to\n * SQLite's own bound, which the engine never reaches.\n */\n readonly compoundSelectTerms?: number;\n /**\n * Where bodies are shared, the relations a statement may reference before\n * its repeated walks become reaching sets and its rows join the key sets\n * they test (`capabilities.relationsPerStatement`). Absent: unbounded.\n */\n readonly relationsPerStatement?: number;\n}\n\n/**\n * The dialect's stateless SQL builders, built once per module. Each adapter\n * takes its own shallow copy of every group, so a driver that overrides one\n * hook (`driver.adapter.result.parseField = …`) changes only its own adapter,\n * as before, while a driver per request no longer rebuilds every closure.\n */\nconst SQLITE_LITERALS = {\n ...createStandardLiterals(),\n\n value: (value: unknown): Sql => {\n if (\n typeof value === \"bigint\" &&\n sqliteIntegerPrecision(String(value)) === undefined\n )\n throw new UnsupportedOperationError(\n \"SQLite bigint values must fit signed 64-bit integers.\"\n );\n return sql`${value}`;\n },\n\n // SQLite uses 1/0 for booleans\n true: (): Sql => sql.raw(\"1\"),\n\n false: (): Sql => sql.raw(\"0\"),\n\n // SQLite requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n // SQLite has no temporal type, so the field's declaration is what the column\n // physically holds and the operand has to be the same kind of value: an ISO\n // string bound against an epoch-millisecond INTEGER matches no row and,\n // written, stores text the typed read then refuses. A TEXT-declared or\n // undeclared field keeps the ISO spelling byte for byte. The string is a\n // validated ISO timestamp — the ISO boundary owns that — and every\n // four-digit public instant round-trips through the Julian-day double.\n dateTime: (iso: string, nativeType?: NativeTypeDeclaration): Sql =>\n sql`${encodePhysicalDateTime(iso, sqliteDateTimePhysicalForm(nativeType))}`,\n\n // SQLite has no exact decimal type, so a decimal column stores the UNSCALED\n // INTEGER COEFFICIENT and an operand becomes that same coefficient. Integer\n // comparison is then exact numeric comparison, and ordering, aggregation\n // and arithmetic are exact for the same reason.\n //\n // The digits bind as TEXT and `CAST(... AS INTEGER)` reads them, rather than\n // riding a JavaScript number (which rounds above 2^53) or a bigint (which\n // D1 will not bind). SQLite's TEXT-to-INTEGER cast is a decimal integer\n // parse, not a float one.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new Sql(COEFFICIENT, [\n encodePhysicalDecimal(canonical, descriptor, \"coefficient\"),\n ]),\n\n // Every compact domain is a `BLOB` here and takes the payload's bytes as\n // the ordinary binary parameter a blob scalar already binds; a text-stored\n // domain takes the public string unchanged.\n id: (physical: string | Uint8Array, _representation: IdRepresentation): Sql =>\n sql`${physical}`,\n\n list: sqliteList,\n};\n\nconst SQLITE_OPERATORS = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) LIKE lower(${pattern}) ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) NOT LIKE lower(${pattern}) ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`instr(${column}, ${value}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, 1, length(${value})) COLLATE BINARY = ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, length(${column}) - length(${value}) + 1) COLLATE BINARY = ${value}`,\n // GLOB, not LIKE — and this is the one place the \"portable escaped LIKE\"\n // premise of Decision 7.3 does not survive contact with SQLite. Both of\n // SQLite's LIKE-optimization preconditions fail here: an ESCAPE clause\n // disqualifies the optimization outright, and with `case_sensitive_like`\n // off (the default, and connection-global, so not ours to flip) the\n // optimization additionally wants a NOCASE-collated index, while `push()`\n // only ever creates BINARY ones. Measured on better-sqlite3, 20k rows,\n // plain index: `col LIKE ? ESCAPE '\\'` is a SCAN — exactly what the\n // `substr` spelling above already costs — AND it answers case-insensitively,\n // which would break the case-sensitivity contract this operator holds.\n //\n // GLOB has neither problem. It compares bytes, so it is case- and\n // accent-sensitive by construction (that is what `COLLATE BINARY` buys\n // above, so nothing is lost by dropping it), and it ranges on the ordinary\n // BINARY index: the same probe plans this as a covering index SEARCH over\n // 111 rows against a 20000-row SCAN. Its wildcards are `*`/`?`/`[`, and it\n // has no ESCAPE clause, so `escapeGlobLiteral` quotes them as classes.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`${column} GLOB ${`${escapeGlobLiteral(value)}*`}`,\n\n // `COLLATE BINARY` names a COLLATION, not a function of the column, and\n // SQLite's ordinary index is a BINARY index — so the case-sensitive\n // spelling is already the index-usable one and there is nothing to add.\n // Byte-identical to what shipped before §10.2.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`${column} COLLATE BINARY = ${value}`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`${column} COLLATE BINARY IN ${values}`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n // Logical (vacuous cases use SQLite's 1/0 booleans)\n ...createLogicalOperators(SQLITE_LITERALS.true, SQLITE_LITERALS.false),\n\n ...createExistenceOperators(),\n};\n\nconst SQLITE_EXPRESSIONS = {\n ...createCommonExpressions(),\n\n // SQLite lower() intentionally provides the portable ASCII-only contract.\n asciiCaseFold: (expr: Sql): Sql => sql`lower(${expr})`,\n caseSensitiveText: (expr: Sql): Sql => sql`${expr} COLLATE BINARY`,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw(\"''\");\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n // SQLite has no GREATEST/LEAST; multi-arg MAX/MIN are the scalar forms\n greatest: (...exprs: Sql[]): Sql => sql`MAX(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`MIN(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm, and for the same\n // reason: SQLite drivers bind JS numbers as REAL, so `x / ?` would run real\n // division. Casting the divisor to INTEGER makes it native INT/INT\n // division, truncating toward zero.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`(${left} / CAST(${right} AS INTEGER))`,\n\n // A deferred SQLite decimal is already a captured coefficient. The\n // descriptor still travels through the common contract so no caller can\n // select this physical cast without naming the destination domain.\n decimalCast: (expr: Sql, _descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS INTEGER)`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`unhex(${expr})`\n : sql`CAST(${expr} AS TEXT)`,\n\n // SQLite type mappings\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"INTEGER\",\n boolean: \"INTEGER\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`lower(hex(${expr}))`,\n};\n\nconst SQLITE_AGGREGATES = {\n ...createAggregateFunctions(\"9e999\"),\n\n // The average of a coefficient column IS the half-even integer quotient of\n // its exact sum by its non-null count: dividing both the sum and the count\n // of `logical x 10^s` values leaves `average x 10^s`, so no scale factor\n // appears at all. `COUNT(column)` is zero exactly when `SUM` is NULL, so\n // the null-strict operators answer NULL for an empty or all-null group and\n // the zero divisor is never reached with a value.\n decimalAvg: (column: Sql, _descriptor: DecimalDescriptor): Sql =>\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`SUM(${column})`,\n sql`COUNT(${column})`\n ),\n\n // A SQLite decimal aggregate is an int64 `SUM` over coefficients. Exact\n // operand admission follows the signed range rather than digit count: some\n // 19-digit values fit, while the next value past either endpoint would make\n // `CAST(... AS INTEGER)` saturate. The sum itself is `integerSum`'s, exact\n // past that range.\n decimalSumOperandPrecision: sqliteIntegerPrecision,\n\n // `>>` is arithmetic, so an int64 member is exactly `(x >> 32) * 2^32` plus\n // its second part. That part stays REAL for a non-integer member, which the\n // reader refuses as it refused the plain `SUM`.\n // `low` sums non-negative 32-bit remainders: carrying its high bits into\n // `high` leaves a pair that sorts exactly as the total. `value` is that\n // total inside int64 and its nearest double outside, below -2^63 at most\n // `-2^63 - 2048`: SQLite compares an integer with a double exactly, so it\n // is exact against every int64 operand (a decimal coefficient's whole\n // domain), and a number operand past int64 is told apart from every total\n // but those that round to it.\n integerSum: (column: Sql) => {\n const high = sql`SUM(${column} >> 32)`;\n const low = sql`SUM(${column} - ((${column} >> 32) << 32))`;\n const carried = sql`(${high} + (${low} >> 32))`;\n const rest = sql`(${low} & 4294967295)`;\n const double = sql`${carried} * 4294967296.0 + ${rest}`;\n return {\n parts: [high, low] as const,\n value: sql`CASE WHEN ${carried} > 2147483647 THEN ${double} WHEN ${carried} >= -2147483648 THEN ${carried} * 4294967296 + ${rest} ELSE MIN(${double}, -9223372036854777856.0) END`,\n order: [carried, rest],\n };\n },\n};\n\n// Compare every node, including empty containers. Array indices remain part\n// of the path; object property insertion order does not. JSON numbers share\n// one domain, while booleans, strings and JSON null retain their distinct type.\nfunction sqliteJsonEquals(left: Sql, right: Sql): Sql {\n const nodes = (value: Sql) =>\n sql`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${value})`;\n return sql`(CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(left)} EXCEPT ${nodes(right)}) AND NOT EXISTS (${nodes(right)} EXCEPT ${nodes(left)}) END)`;\n}\n\nconst sqliteJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw(\"json_object()\");\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`json_object(${sql.join(args, \", \")})`;\n};\n\nconst SQLITE_JSON = {\n equals: sqliteJsonEquals,\n number: (expression: Sql): Sql =>\n sql`CASE WHEN ${expression} IS NULL THEN NULL ELSE printf(${sql.raw(`'${SQLITE_BINARY64_FORMAT}'`)}, ${expression}) END`,\n boolean: (condition: Sql): Sql =>\n sql`json(CASE WHEN ${condition} THEN 'true' ELSE 'false' END)`,\n // SQLite drops the JSON subtype across scalar-subquery boundaries. Restore it\n // before embedding the value in json_object/json_array, or an object becomes a\n // quoted JSON string inside the outer document.\n document: (expression: Sql): Sql => sql`json(${expression})`,\n\n object: sqliteJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw(\"json_array()\"),\n\n // `expr` carries the JSON subtype (a json_object call, or a subquery\n // column restored through `document`), so it is aggregated as JSON, not\n // quoted as a string. Over no rows json_group_array is `[]`, never NULL.\n agg: (expr: Sql): Sql => sql`json_group_array(${expr})`,\n\n objectFromColumns: sqliteJsonObject,\n\n // `->` returns the value as canonical JSON text ('\"str\"', '2', 'null'),\n // the same format json.value binds, so extracted values compare with\n // plain equality (json_extract would return native SQL values instead)\n extract: jsonExtract,\n\n // `->>` returns text with strings unquoted, for LIKE matching\n extractText: jsonExtractText,\n\n // json_type reads the chained `->` result (canonical JSON text), so it\n // sees 'integer'/'real' only for real JSON numbers; every other shape —\n // and an absent path, where `->` is NULL — falls through to NULL\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN json_type(${jsonExtract(column, path)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(column, path)} AS REAL) END)`,\n\n // COLLATE BINARY is SQLite's default for these columns; naming it keeps\n // the code-point ordering contract explicit alongside PG's COLLATE \"C\"\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN json_type(${jsonExtract(column, path)}) = 'text' THEN ${jsonExtractText(column, path)} END) COLLATE BINARY)`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(json_type(${target}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${value}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${target}) AS candidate WHERE ${sqliteJsonEquals(sql`${target} -> candidate.fullkey`, sql`${value} -> required.fullkey`)})))`,\n\n lastElement: (target: Sql): Sql => sql`${target} -> '$[#-1]'`,\n\n value: (v: unknown): Sql => sql`${stringifyJson(v)}`,\n};\n\nconst SQLITE_ARRAYS = {\n // SQLite uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n value: sqliteJsonListValue,\n\n // Deliberately the same container, by identity: SQLite stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The `TEXT CHECK(col IN ...)`\n // describes one member.\n enumValue: sqliteJsonListValue,\n\n // Check if value exists in JSON array using json_each\n has: (column: Sql, value: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ${value})`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`(SELECT COUNT(*) FROM json_each(${values}) WHERE value IN (SELECT value FROM json_each(${column}))) = json_array_length(${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) AS a, json_each(${values}) AS b WHERE a.value = b.value)`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(json_array_length(${column}) = 0 OR ${column} IS NULL)`,\n\n // The column already stores the container as TEXT (its declared type is\n // TEXT, not JSON, precisely so the descriptor's CHECK can hold it). The\n // cast is what stops a JSON carrier from embedding it as a document and a\n // driver from handing back anything but the stored bytes.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS TEXT)`,\n\n length: (column: Sql): Sql => sql`json_array_length(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`json_extract(${column}, '$[' || ${index} || ']')`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`json_insert(${column}, '$[#]', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`json_set(${column}, '$[' || ${index} || ']', ${value})`,\n};\n\nconst SQLITE_ORDER_BY = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n};\n\nconst SQLITE_SET = {\n ...createNumericSetOperations(),\n\n // `x * y / 10^s` in coefficient space, rounded half to even. The guard is\n // the multiply's own: `x * y` is the only intermediate here that can leave\n // int64, and it does so exactly when the result cannot fit the field.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (!descriptor) return sql`${column} = ${column} * ${by}`;\n return guardedCoefficientAssignment(\n column,\n sql`${by} = 0 OR ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ABS(${by})`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`(${column} * ${by})`,\n scaleFactorSql(descriptor.scale)\n ),\n descriptor\n );\n },\n\n // `x * 10^s / y` in coefficient space, rounded half to even; the divisor's\n // sign moves onto the numerator so the rule always sees a positive divisor.\n // `y` is never zero — division by canonical zero is refused before I/O.\n //\n // SQLite drivers bind JS numbers as REAL, so `col / ?` runs real division\n // and would persist a fractional value into an INTEGER column. Casting the\n // divisor to INTEGER makes it native INT/INT division (truncating toward\n // zero, matching Postgres) for integer columns; real columns keep real\n // division since the column itself carries REAL affinity.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (descriptor) {\n const factor = scaleFactorSql(descriptor.scale);\n return guardedCoefficientAssignment(\n column,\n sql`ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ${factor}`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n signedNumerator(sql`(${column} * ${factor})`, by),\n sql`ABS(${by})`\n ),\n descriptor\n );\n }\n return target?.integer\n ? sql`${column} = ${column} / CAST(${by} AS INTEGER)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n sql`json(COALESCE(${column}, '[]'))`,\n values\n )}`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n values,\n sql`json(COALESCE(${column}, '[]'))`\n )}`,\n};\n\nconst SQLITE_MUTATIONS = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n // SQLite 3.35+ supports RETURNING\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n // SQLite uses same ON CONFLICT syntax as PostgreSQL (3.24+/3.35+)\n ...createOnConflictBuilders(),\n};\n\nconst SQLITE_ASSERTIONS = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n // The refusal names its sentinel (`bad JSON path: '__viborm_refused__'`).\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE json_extract('{}', '__viborm_refused__') END AS \"__viborm_judged__\"${from ? sql` FROM ${from}` : sql``}`,\n};\n\nconst SQLITE_JOINS = {\n ...createCoreJoins(),\n\n // SQLite doesn't support RIGHT JOIN (before 3.39, and driver support varies).\n // Never silently downgrade: emitting LEFT JOIN without swapping operands\n // returns wrong rows. The query engine never calls this today.\n right: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.\"\n );\n },\n\n // SQLite doesn't support FULL OUTER JOIN (before 3.39, and driver support varies).\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // SQLite does NOT support LATERAL joins\n // These methods should never be called - query engine should check capability first\n lateral: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n\n lateralLeft: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n};\n\nconst SQLITE_CAPABILITIES = {\n supportsReturning: true, // SQLite 3.35+\n // FALSE IN FACT, and it read `true` until the Phase 8 fold gave the flag its\n // first reader (query-performance-plan Phase 10.1). SQLite's `WITH` grammar\n // admits a SELECT and nothing else: measured on SQLite 3.51.2, each of\n // `WITH x AS (UPDATE …/INSERT …/DELETE … RETURNING …) SELECT * FROM x` is a\n // parse error (`near \"UPDATE\": syntax error`). Kept as a capability rather\n // than deleted because Phase 8's `WITH u AS (UPDATE … RETURNING *) SELECT …`\n // fold reads it to decide whether it may emit at all.\n supportsCteWithMutations: false,\n supportsFullOuterJoin: false,\n supportsLateralJoins: false, // SQLite does not support LATERAL joins\n supportsVector: false,\n supportsUpsertWhere: true, // SQLite supports WHERE in ON CONFLICT (3.24+)\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n // UPDATE/DELETE ... LIMIT needs SQLITE_ENABLE_UPDATE_DELETE_LIMIT, which is\n // off in the builds this project targets (better-sqlite3, libSQL, D1).\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n joinsJunctionFilters: true,\n};\n\nconst SQLITE_RESULT: AdapterResultParser = {\n // SQLite has no exact decimal type: a decimal column IS its unscaled\n // integer coefficient, and every projection casts it to text before a\n // driver turns an int64 into a double. The result boundary cannot tell the\n // two vocabularies apart by inspection, so the promise is declared here.\n decimalRepresentation: \"coefficient\",\n\n // A decimal LIST is TEXT holding a JSON array of those same coefficients,\n // stated separately because the two facts are separate: a dialect can spell\n // its scalar decimals exactly and still have no exact decimal inside JSON.\n decimalListRepresentation: \"coefficient\",\n\n // The same reading the `dateTime` literal above lowers through, so a column\n // is read back in the vocabulary it was written in.\n dateTimeRepresentation: sqliteDateTimePhysicalForm,\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"sqlite\")?.representation ?? \"text\",\n\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n};\n\nconst SQLITE_IDENTIFIERS = createIdentifiers(quoteIdent);\n\nconst SQLITE_CLAUSES = createStandardClauses();\n\nconst SQLITE_FILTERS = createRelationFilters();\n\nconst SQLITE_SUBQUERIES = createSubqueries(quoteIdent);\n\n// A member is written once and inlined at every use: one a nested body reads\n// is compiled again inside each use of that body, so it is materialized.\nconst SQLITE_CTE = createCteBuilders(quoteIdent, {\n materializing: sql.raw(\"MATERIALIZED\"),\n});\n\n/**\n * A multi-row `VALUES` is the one compound SQLite does not count against\n * `SQLITE_MAX_COMPOUND_SELECT` (500 terms; measured on 3.53.2: 500 `UNION\n * ALL SELECT` arms refused, 10,922 `VALUES` rows read), so the produced rows\n * follow their typed head as one: the head's columns still type every row,\n * as an arm's did (affinity and collation measured equal).\n */\nconst SQLITE_SET_OPERATIONS = createSetOperations(\n quoteIdent,\n (typed, rows, alias) =>\n sql`(${typed.head} UNION ALL VALUES ${sql.join(rows.map(rowValues), \", \")}) AS ${sql.raw(quoteIdent(alias))}`\n);\n\nconst SQLITE_RAW = createRawSql();\n\n/**\n * `and` nesting its members as a balanced tree, about log2(n) levels for n\n * members, where `and` itself nests one level per member.\n */\nfunction balancedConjunction(\n and: (...conditions: Sql[]) => Sql\n): (...conditions: Sql[]) => Sql {\n const balanced = (...conditions: Sql[]): Sql => {\n if (conditions.length <= 2) return and(...conditions);\n const middle = Math.floor(conditions.length / 2);\n return and(\n balanced(...conditions.slice(0, middle)),\n balanced(...conditions.slice(middle))\n );\n };\n return balanced;\n}\n\nexport class SQLiteAdapter implements DatabaseAdapter {\n constructor({\n temporaryObjects = true,\n deepExpressions = true,\n sharedRelationBodies = false,\n compoundSelectTerms,\n relationsPerStatement,\n }: SQLiteAdapterOptions = {}) {\n installGeoPointSql(this, this.geoPoint);\n if (!deepExpressions) {\n this.subqueries.existsCheck = (from, where) =>\n sql`SELECT 1 FROM (${SQLITE_SUBQUERIES.existsCheck(from, where)})`;\n // A derived table's `WHERE` is resolved on its own branch: a level's\n // row domain costs its height there, once, not at every level below.\n this.subqueries.isolated = (condition) =>\n sql`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${condition}))`;\n this.operators.and = balancedConjunction(SQLITE_OPERATORS.and);\n this.capabilities.boundsExpressionDepth = true;\n }\n if (sharedRelationBodies) this.capabilities.sharesRelationBodies = true;\n if (compoundSelectTerms !== undefined)\n this.capabilities.compoundSelectTerms = compoundSelectTerms;\n if (relationsPerStatement !== undefined)\n this.capabilities.relationsPerStatement = relationsPerStatement;\n // Only batches read the reference-table SQL, so it is built on first use.\n let batchRefs: BatchReferenceSqlAdapter | undefined;\n const createBatchRefs = () => this.#createBatchRefs(temporaryObjects);\n installAdapterInternals(this, {\n get batchRefs() {\n batchRefs ??= createBatchRefs();\n return batchRefs;\n },\n constraints: sqliteConstraintIdentities,\n select: this.#assemble.select,\n });\n }\n\n raw = SQLITE_RAW;\n\n identifiers = { ...SQLITE_IDENTIFIERS };\n\n literals = { ...SQLITE_LITERALS };\n\n operators = { ...SQLITE_OPERATORS };\n\n expressions = { ...SQLITE_EXPRESSIONS };\n\n aggregates = { ...SQLITE_AGGREGATES };\n\n // SQLite 3.38+ JSON functions\n json = { ...SQLITE_JSON };\n\n arrays = { ...SQLITE_ARRAYS };\n\n // SQLite parses NULLS FIRST/LAST natively since 3.30 (2019-10-04), which is\n // below this adapter's documented 3.35+ floor. The `(col IS NULL)` emulation\n // this replaces was an extra leading sort key, and an index can never supply\n // a sort key that is an expression: on a 100,000-row table with an index over\n // the sort columns, the emulated spelling planned `SCAN t | USE TEMP B-TREE\n // FOR ORDER BY` at 3.356 ms per page and the native one plans `SCAN t USING\n // INDEX` at 0.005 ms. MySQL keeps the emulation — it has no native syntax at\n // any version.\n orderBy = { ...SQLITE_ORDER_BY };\n\n clauses = { ...SQLITE_CLAUSES };\n\n set = { ...SQLITE_SET };\n\n filters = { ...SQLITE_FILTERS };\n\n subqueries = { ...SQLITE_SUBQUERIES };\n\n // SQLite has no bare OFFSET; LIMIT -1 means \"no limit\"\n noLimitValue = sql.raw(\"-1\");\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // SQLite doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n // SQLite uses database-level locking, so FOR UPDATE is a no-op\n // (ignoring parts.forUpdate intentionally)\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"omit\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n cte = { ...SQLITE_CTE };\n\n mutations = { ...SQLITE_MUTATIONS };\n\n assertions = { ...SQLITE_ASSERTIONS };\n\n joins = { ...SQLITE_JOINS };\n\n setOperations = { ...SQLITE_SET_OPERATIONS };\n\n capabilities: DatabaseAdapter[\"capabilities\"] = { ...SQLITE_CAPABILITIES };\n\n lastInsertId = (): Sql => sql.raw(\"last_insert_rowid()\");\n\n // The scratch is a TEMP table wherever the transport admits one, so it never\n // enters the user's database file. Where it does not (D1), it is an ordinary\n // table in `main`: created once, kept, and EMPTY between batches — every\n // batch deletes the rows it stored, keyed by its own batch id, inside that\n // same batch, and a batch that fails rolls its rows back with it. The table\n // itself persists; SQLite migration introspection leaves it out of the\n // snapshot (`src/migrations/drivers/sqlite/introspect.ts`).\n #createBatchRefs(temporaryObjects: boolean): BatchReferenceSqlAdapter {\n const table = sql.raw(quoteIdent(BATCH_REFS_TABLE));\n const create = sql.raw(\n temporaryObjects\n ? \"CREATE TEMP TABLE IF NOT EXISTS\"\n : \"CREATE TABLE IF NOT EXISTS\"\n );\n return createOnConflictBatchRefs({\n table,\n batchIdColumn: sql.raw('\"batch_id\"'),\n keyColumn: sql.raw('\"ref_key\"'),\n valueColumn: sql.raw('\"ref_value\"'),\n createTable: sql`${create} ${table} (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n lastInsertId: () => this.lastInsertId(),\n });\n }\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"longitude\"]);\n const latitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"latitude\"]);\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`json_object('longitude', ${this.json.document(this.json.number(pointLongitude))}, 'latitude', ${this.json.document(this.json.number(pointLatitude))})`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators\n ),\n };\n })();\n\n result: AdapterResultParser = { ...SQLITE_RESULT };\n}\n"],"mappings":"u1BA0EA,MAAM,EAAa,EAAuB,IAAI,CASxC,EAA0C,CAC9C,UAAW,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACnD,WAAY,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACrD,CAMD,SAAS,uBAAuB,EAAyC,CACvE,IAAM,EAAY,GAA4B,EAAY,CAC1D,GAAI,EAAY,GAAI,OAAO,EACvB,OAAY,IAIhB,OAHmB,EAAY,WAAW,IAAI,CAC1C,EAAY,MAAM,EAAE,EAAI,sBACxB,GAAe,uBACC,EAAY,IAAA,GA4BlC,MAAM,EAA4BA,EAAI,IAAI,sBAAsB,CAqB1D,oBAAuB,GAC3BA,EAAI,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,EAAW,UAAW,GAAG,CAAC,GAAG,CASzD,8BACJ,EACA,EACA,EACA,IAEA,CAAG,GAAG,EAAO,eAAe,EAAO,cAAc,EAAK,QAAQ,EAAM,QAAQ,oBAAoB,EAAW,CAAC,MAExG,EAA2B,QAC3B,EAA2B,QAO3B,YAAe,GAA4B,CAC/C,GAAI,EAAyB,KAAK,EAAQ,CACxC,MAAO,KAAK,EAAQ,GAEtB,GAAI,EAAyB,KAAK,EAAQ,CACxC,MAAU,MACR,gGACD,CAEH,MAAO,MAAM,EAAQ,IAIjB,aAAe,EAAa,IAAwB,CACxD,IAAI,EAAO,CAAG,GAAG,EAAO,SACxB,IAAK,IAAM,KAAW,EACpB,EAAO,CAAG,GAAG,EAAK,MAAM,YAAY,EAAQ,GAE9C,OAAO,GAIH,iBAAmB,EAAa,IAAwB,CAC5D,GAAI,EAAK,SAAW,EAClB,MAAO,EAAG,GAAG,EAAO,UAEtB,IAAM,EAAO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ACX,aAAc,KAAK,aACpB,CAAC,CAEL,CAED,IAAM,CAAE,GAAG,GAAY,CAEvB,UAAY,CAAE,GAAG,EAAkB,CAEnC,WAAa,CAAE,GAAG,GAAmB,CAErC,MAAQ,CAAE,GAAG,GAAc,CAE3B,cAAgB,CAAE,GAAG,GAAuB,CAE5C,aAAgD,CAAE,GAAG,GAAqB,CAE1E,iBAA0BA,EAAI,IAAI,sBAAsB,CASxD,GAAiB,EAAqD,CACpE,IAAM,EAAQA,EAAI,IAAI,EAAW,EAAiB,CAAC,CAC7C,EAASA,EAAI,IACjB,EACI,kCACA,6BACL,CACD,OAAO,EAA0B,CAC/B,QACA,cAAeA,EAAI,IAAI,aAAa,CACpC,UAAWA,EAAI,IAAI,YAAY,CAC/B,YAAaA,EAAI,IAAI,cAAc,CACnC,YAAa,CAAG,GAAG,EAAO,GAAG,EAAM,6GACnC,UAAY,GAAa,CAAG,SAAS,EAAS,YAC9C,iBAAoB,KAAK,cAAc,CACxC,CAAC,CAGJ,OAAS,EAET,cAAwC,CACtC,IAAM,UAAa,GACjB,KAAK,KAAK,aAAa,EAAO,CAAC,YAAY,CAAC,CACxC,SAAY,GAChB,KAAK,KAAK,aAAa,EAAO,CAAC,WAAW,CAAC,CAC7C,MAAO,CACL,OAAQ,EAAgB,IACtB,CAAG,4BAA4B,KAAK,KAAK,SAAS,KAAK,KAAK,OAAO,EAAe,CAAC,CAAC,gBAAgB,KAAK,KAAK,SAAS,KAAK,KAAK,OAAO,EAAc,CAAC,CAAC,GAC1J,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,UACN,CACF,IACC,CAEJ,OAA8B,CAAE,GAAG,GAAe"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./error-mapping-6op318w6.mjs";import{s as n}from"./execution-context-rJXTRVrJ.mjs";import{n as r}from"./result-parsing-8wEK3GY1.mjs";function isSQLiteBinaryValue(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}function sqliteBinaryToUint8Array(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function convertValueForSQLite(e){return e instanceof Date?e.toISOString():typeof e==`boolean`?e?1:0:e===void 0?null:e}function convertValuesForSQLite(e){return e.map(convertValueForSQLite)}const i={parseField:parseSQLiteField};function parseSQLiteField(e,t,n){if(t===`boolean`){let i=r(e);if(i!==void 0)return n(i,t)}return n(t===`json`&&typeof e==`string`?JSON.parse(e):e,t)}function normalizeSQLiteRawRows(e){return e.map(e=>{if(typeof e!=`object`||!e)return e;let t={...e};for(let e of Object.keys(t)){let n=Reflect.get(t,e);typeof n==`bigint`&&n>=BigInt(-(2**53-1))&&n<=BigInt(2**53-1)&&Reflect.set(t,e,Number(n))}return t})}const a=Object.freeze({isolationLevel:`serializable-only`,isolationLevelReason:`SQLite serializes transactions on a single connection and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:`queue`});function runLocalSQLiteTransaction(e,r,i){return t({begin:()=>e.exec(`BEGIN IMMEDIATE`),callback:()=>r(e),commit:()=>e.exec(`COMMIT`),rollback:()=>{e.inTransaction&&e.exec(`ROLLBACK`)},phases:n(i)})}export{normalizeSQLiteRawRows as a,sqliteBinaryToUint8Array as c,isSQLiteBinaryValue as i,i as l,convertValueForSQLite as n,parseSQLiteField as o,convertValuesForSQLite as r,runLocalSQLiteTransaction as s,a as t};
2
- //# sourceMappingURL=sqlite-utils-BvSlEs5W.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./error-mapping-6op318w6.mjs";import{s as n}from"./execution-context-rJXTRVrJ.mjs";import{n as r}from"./result-parsing-CQf_eCl8.mjs";function isSQLiteBinaryValue(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}function sqliteBinaryToUint8Array(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function convertValueForSQLite(e){return e instanceof Date?e.toISOString():typeof e==`boolean`?e?1:0:e===void 0?null:e}function convertValuesForSQLite(e){return e.map(convertValueForSQLite)}const i={parseField:parseSQLiteField};function parseSQLiteField(e,t,n){if(t===`boolean`){let i=r(e);if(i!==void 0)return n(i,t)}return n(t===`json`&&typeof e==`string`?JSON.parse(e):e,t)}function normalizeSQLiteRawRows(e){return e.map(e=>{if(typeof e!=`object`||!e)return e;let t={...e};for(let e of Object.keys(t)){let n=Reflect.get(t,e);typeof n==`bigint`&&n>=BigInt(-(2**53-1))&&n<=BigInt(2**53-1)&&Reflect.set(t,e,Number(n))}return t})}const a=Object.freeze({isolationLevel:`serializable-only`,isolationLevelReason:`SQLite serializes transactions on a single connection and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:`queue`});function runLocalSQLiteTransaction(e,r,i){return t({begin:()=>e.exec(`BEGIN IMMEDIATE`),callback:()=>r(e),commit:()=>e.exec(`COMMIT`),rollback:()=>{e.inTransaction&&e.exec(`ROLLBACK`)},phases:n(i)})}export{normalizeSQLiteRawRows as a,sqliteBinaryToUint8Array as c,isSQLiteBinaryValue as i,i as l,convertValueForSQLite as n,parseSQLiteField as o,convertValuesForSQLite as r,runLocalSQLiteTransaction as s,a as t};
2
+ //# sourceMappingURL=sqlite-utils-C0TyzOys.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-utils-BvSlEs5W.mjs","names":[],"sources":["../src/drivers/shared/sqlite-utils.ts"],"sourcesContent":["/**\n * Shared SQLite Utilities\n *\n * Common result parser and parameter conversion for SQLite-based drivers.\n */\n\nimport { parseIntegerBoolean } from \"@adapters/shared/result-parsing\";\nimport type { DriverResultParser } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport type { QueryExecutionContext } from \"../types\";\nimport type { TransactionOptionSupport } from \"./transaction-options\";\nimport { runTransactionLifecycle } from \"./transactions\";\n\nexport type SQLiteBinaryValue = ArrayBuffer | ArrayBufferView;\n\nexport function isSQLiteBinaryValue(\n value: unknown\n): value is SQLiteBinaryValue {\n return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n}\n\nexport function sqliteBinaryToUint8Array(value: SQLiteBinaryValue): Uint8Array {\n if (value instanceof ArrayBuffer) {\n return new Uint8Array(value);\n }\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n}\n\n/**\n * Convert provider-neutral scalar values to SQLite values. Binary values stay\n * in their standard Web API form; each provider owns any narrower conversion.\n */\nexport function convertValueForSQLite(value: unknown): unknown {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value === undefined) return null;\n return value;\n}\n\nexport function convertValuesForSQLite(values: unknown[]): unknown[] {\n return values.map(convertValueForSQLite);\n}\n\n/**\n * Shared result parser for the SQLite drivers. It speaks about ROW VALUES only:\n * - Boolean integer parsing (0/1 -> false/true)\n * - `json` columns, which SQLite stores as TEXT\n *\n * It says nothing about a RESULT (Arnaud's D-35). A SQLite transport answers a\n * `count`/`exist` in the shape the engine's own projection asked for — the\n * engine aliases that column `_count` and reads `_count` back — so the meaning\n * of a count and an exists answer has one authority, the engine's decoder, and\n * this middleware has nothing to add at the result boundary. Recovering a count\n * from a provider that did NOT preserve the alias is a dialect fact, stated\n * once at the adapter seam by the provider that needs it (MySQL).\n */\nexport const sqliteResultParser: DriverResultParser = {\n parseField: parseSQLiteField,\n};\n\n/**\n * The shipped parser's own field hook. `sqliteResultParser` is one mutable\n * object every SQLite-family driver shares, so a driver that must recognise\n * the shipped parser compares against this definition, never against what the\n * shared object holds when its module loads. The shipped parser defines no\n * `parseRelation` or `parseResult`.\n */\nexport function parseSQLiteField(\n value: unknown,\n scalarType: string,\n next: (value: unknown, scalarType: string) => unknown\n): unknown {\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(value);\n if (parsed !== undefined) return next(parsed, scalarType);\n }\n // SQLite stores json as TEXT — decode here where we know the string is\n // serialized JSON (the default parser never sniffs json strings)\n if (scalarType === \"json\" && typeof value === \"string\") {\n return next(JSON.parse(value), scalarType);\n }\n return next(value, scalarType);\n}\n\n/** Raw INTEGER leaves retain exact values; only safe-range values become numbers. */\nexport function normalizeSQLiteRawRows<T>(rows: T[]): T[] {\n return rows.map((row) => {\n if (row === null || typeof row !== \"object\") return row;\n const normalized = { ...row };\n for (const key of Object.keys(normalized)) {\n const value: unknown = Reflect.get(normalized, key);\n if (\n typeof value === \"bigint\" &&\n value >= BigInt(Number.MIN_SAFE_INTEGER) &&\n value <= BigInt(Number.MAX_SAFE_INTEGER)\n )\n Reflect.set(normalized, key, Number(value));\n }\n return normalized;\n });\n}\n\n/**\n * SQLite has no isolation-level statement: one writer at a time on one\n * connection makes every transaction serializable already. `Serializable` is\n * therefore honored by construction, with no SQL to emit; the three weaker\n * levels are refused because pretending to relax isolation we cannot relax\n * would misreport what the transaction actually guarantees.\n */\nexport const LOCAL_SQLITE_TRANSACTION_SUPPORT: TransactionOptionSupport =\n Object.freeze({\n isolationLevel: \"serializable-only\",\n isolationLevelReason:\n \"SQLite serializes transactions on a single connection and has no statement to weaken isolation, so only Serializable can be honored truthfully\",\n timeout: true,\n maxWait: \"queue\",\n });\n\n/** One transaction on a local, synchronous, single-connection SQLite handle. */\nexport function runLocalSQLiteTransaction<\n Client extends {\n exec(sql: string): unknown;\n readonly inTransaction: boolean;\n },\n T,\n>(\n client: Client,\n fn: (tx: Client) => Promise<T>,\n context: QueryExecutionContext | undefined\n): Promise<T> {\n return runTransactionLifecycle({\n begin: () => client.exec(\"BEGIN IMMEDIATE\"),\n callback: () => fn(client),\n commit: () => client.exec(\"COMMIT\"),\n // A failed BEGIN never grants rollback ownership. After a failed COMMIT,\n // successful rollback restores this same database, including :memory:.\n rollback: () => {\n if (client.inTransaction) client.exec(\"ROLLBACK\");\n },\n phases: getExecutionTransactionPhases(context),\n });\n}\n"],"mappings":"iMAeA,SAAgB,oBACd,EAC4B,CAC5B,OAAO,aAAiB,aAAe,YAAY,OAAO,EAAM,CAGlE,SAAgB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KAAK,WAAW,EAEnD,OAAQ,EAA8B,EAAQ,CAC/C,CAAC"}
1
+ {"version":3,"file":"sqlite-utils-C0TyzOys.mjs","names":[],"sources":["../src/drivers/shared/sqlite-utils.ts"],"sourcesContent":["/**\n * Shared SQLite Utilities\n *\n * Common result parser and parameter conversion for SQLite-based drivers.\n */\n\nimport { parseIntegerBoolean } from \"@adapters/shared/result-parsing\";\nimport type { DriverResultParser } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport type { QueryExecutionContext } from \"../types\";\nimport type { TransactionOptionSupport } from \"./transaction-options\";\nimport { runTransactionLifecycle } from \"./transactions\";\n\nexport type SQLiteBinaryValue = ArrayBuffer | ArrayBufferView;\n\nexport function isSQLiteBinaryValue(\n value: unknown\n): value is SQLiteBinaryValue {\n return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n}\n\nexport function sqliteBinaryToUint8Array(value: SQLiteBinaryValue): Uint8Array {\n if (value instanceof ArrayBuffer) {\n return new Uint8Array(value);\n }\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n}\n\n/**\n * Convert provider-neutral scalar values to SQLite values. Binary values stay\n * in their standard Web API form; each provider owns any narrower conversion.\n */\nexport function convertValueForSQLite(value: unknown): unknown {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value === undefined) return null;\n return value;\n}\n\nexport function convertValuesForSQLite(values: unknown[]): unknown[] {\n return values.map(convertValueForSQLite);\n}\n\n/**\n * Shared result parser for the SQLite drivers. It speaks about ROW VALUES only:\n * - Boolean integer parsing (0/1 -> false/true)\n * - `json` columns, which SQLite stores as TEXT\n *\n * It says nothing about a RESULT (Arnaud's D-35). A SQLite transport answers a\n * `count`/`exist` in the shape the engine's own projection asked for — the\n * engine aliases that column `_count` and reads `_count` back — so the meaning\n * of a count and an exists answer has one authority, the engine's decoder, and\n * this middleware has nothing to add at the result boundary. Recovering a count\n * from a provider that did NOT preserve the alias is a dialect fact, stated\n * once at the adapter seam by the provider that needs it (MySQL).\n */\nexport const sqliteResultParser: DriverResultParser = {\n parseField: parseSQLiteField,\n};\n\n/**\n * The shipped parser's own field hook. `sqliteResultParser` is one mutable\n * object every SQLite-family driver shares, so a driver that must recognise\n * the shipped parser compares against this definition, never against what the\n * shared object holds when its module loads. The shipped parser defines no\n * `parseRelation` or `parseResult`.\n */\nexport function parseSQLiteField(\n value: unknown,\n scalarType: string,\n next: (value: unknown, scalarType: string) => unknown\n): unknown {\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(value);\n if (parsed !== undefined) return next(parsed, scalarType);\n }\n // SQLite stores json as TEXT — decode here where we know the string is\n // serialized JSON (the default parser never sniffs json strings)\n if (scalarType === \"json\" && typeof value === \"string\") {\n return next(JSON.parse(value), scalarType);\n }\n return next(value, scalarType);\n}\n\n/** Raw INTEGER leaves retain exact values; only safe-range values become numbers. */\nexport function normalizeSQLiteRawRows<T>(rows: T[]): T[] {\n return rows.map((row) => {\n if (row === null || typeof row !== \"object\") return row;\n const normalized = { ...row };\n for (const key of Object.keys(normalized)) {\n const value: unknown = Reflect.get(normalized, key);\n if (\n typeof value === \"bigint\" &&\n value >= BigInt(Number.MIN_SAFE_INTEGER) &&\n value <= BigInt(Number.MAX_SAFE_INTEGER)\n )\n Reflect.set(normalized, key, Number(value));\n }\n return normalized;\n });\n}\n\n/**\n * SQLite has no isolation-level statement: one writer at a time on one\n * connection makes every transaction serializable already. `Serializable` is\n * therefore honored by construction, with no SQL to emit; the three weaker\n * levels are refused because pretending to relax isolation we cannot relax\n * would misreport what the transaction actually guarantees.\n */\nexport const LOCAL_SQLITE_TRANSACTION_SUPPORT: TransactionOptionSupport =\n Object.freeze({\n isolationLevel: \"serializable-only\",\n isolationLevelReason:\n \"SQLite serializes transactions on a single connection and has no statement to weaken isolation, so only Serializable can be honored truthfully\",\n timeout: true,\n maxWait: \"queue\",\n });\n\n/** One transaction on a local, synchronous, single-connection SQLite handle. */\nexport function runLocalSQLiteTransaction<\n Client extends {\n exec(sql: string): unknown;\n readonly inTransaction: boolean;\n },\n T,\n>(\n client: Client,\n fn: (tx: Client) => Promise<T>,\n context: QueryExecutionContext | undefined\n): Promise<T> {\n return runTransactionLifecycle({\n begin: () => client.exec(\"BEGIN IMMEDIATE\"),\n callback: () => fn(client),\n commit: () => client.exec(\"COMMIT\"),\n // A failed BEGIN never grants rollback ownership. After a failed COMMIT,\n // successful rollback restores this same database, including :memory:.\n rollback: () => {\n if (client.inTransaction) client.exec(\"ROLLBACK\");\n },\n phases: getExecutionTransactionPhases(context),\n });\n}\n"],"mappings":"iMAeA,SAAgB,oBACd,EAC4B,CAC5B,OAAO,aAAiB,aAAe,YAAY,OAAO,EAAM,CAGlE,SAAgB,yBAAyB,EAAsC,CAI7E,OAHI,aAAiB,YACZ,IAAI,WAAW,EAAM,CAEvB,IAAI,WAAW,EAAM,OAAQ,EAAM,WAAY,EAAM,WAAW,CAOzE,SAAgB,sBAAsB,EAAyB,CAI7D,OAHI,aAAiB,KAAa,EAAM,aAAa,CACjD,OAAO,GAAU,UAAkB,EAAQ,EAAI,EAC/C,IAAU,IAAA,GAAkB,KACzB,EAGT,SAAgB,uBAAuB,EAA8B,CACnE,OAAO,EAAO,IAAI,sBAAsB,CAgB1C,MAAa,EAAyC,CACpD,WAAY,iBACb,CASD,SAAgB,iBACd,EACA,EACA,EACS,CACT,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,EAAoB,EAAM,CACzC,GAAI,IAAW,IAAA,GAAW,OAAO,EAAK,EAAQ,EAAW,CAO3D,OAFS,EADL,IAAe,QAAU,OAAO,GAAU,SAChC,KAAK,MAAM,EAAM,CAEnB,EAFqB,EAAW,CAM9C,SAAgB,uBAA0B,EAAgB,CACxD,OAAO,EAAK,IAAK,GAAQ,CACvB,GAAoB,OAAO,GAAQ,WAA/B,EAAyC,OAAO,EACpD,IAAM,EAAa,CAAE,GAAG,EAAK,CAC7B,IAAK,IAAM,KAAO,OAAO,KAAK,EAAW,CAAE,CACzC,IAAM,EAAiB,QAAQ,IAAI,EAAY,EAAI,CAEjD,OAAO,GAAU,UACjB,GAAS,OAAO,WAAwB,EACxC,GAAS,eAA+B,EAExC,QAAQ,IAAI,EAAY,EAAK,OAAO,EAAM,CAAC,CAE/C,OAAO,GACP,CAUJ,MAAa,EACX,OAAO,OAAO,CACZ,eAAgB,oBAChB,qBACE,iJACF,QAAS,GACT,QAAS,QACV,CAAC,CAGJ,SAAgB,0BAOd,EACA,EACA,EACY,CACZ,OAAO,EAAwB,CAC7B,UAAa,EAAO,KAAK,kBAAkB,CAC3C,aAAgB,EAAG,EAAO,CAC1B,WAAc,EAAO,KAAK,SAAS,CAGnC,aAAgB,CACV,EAAO,eAAe,EAAO,KAAK,WAAW,EAEnD,OAAQ,EAA8B,EAAQ,CAC/C,CAAC"}
@@ -1,4 +1,4 @@
1
- import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, kn as TransactionOptionSupport, p as SqliteMigrationCapability, s as DatabaseAdapter, u as Driver } from "./index-B_jh2oaQ.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, kn as TransactionOptionSupport, p as SqliteMigrationCapability, s as DatabaseAdapter, u as Driver } from "./index-B4IWFJfv.mjs";
2
2
  import Database from "better-sqlite3";
3
3
 
4
4
  //#region src/drivers/sqlite3/index.d.ts
package/dist/sqlite3.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./bind-parameter-capacity-DiwRmZ1h.mjs";import{r as n}from"./validation-gwZYm3Yn.mjs";import{a as r,i,n as a,r as o}from"./client-BmcHzDBa.mjs";import{c as s,n as c,r as l,t as u}from"./driver-Bzc0GCQ4.mjs";import{a as d,c as f,i as p,l as m,n as h,o as g,s as _,t as v}from"./sqlite-utils-BvSlEs5W.mjs";import{t as y}from"./sqlite-adapter-DPc9T6Lh.mjs";import{Buffer as b}from"node:buffer";import x from"better-sqlite3";const S=new WeakMap,C=x.prototype.prepare;function cachedStatement(e,t,n){if(e.prepare!==C)return e.prepare(t);let r=S.get(e);r||(r=[new Map,new Map],S.set(e,r));let i=r[n?0:1],a=i.get(t);return a===void 0?(a=e.prepare(t),i.size===100&&i.delete(i.keys().next().value)):i.delete(t),i.set(t,a),a}function convertValuesForSQLite3(e){return e.map(e=>{let t=h(e);if(b.isBuffer(t)||!p(t))return t;let n=f(t);return b.from(n.buffer,n.byteOffset,n.byteLength)})}const w={client:!0,dataDir:!0,options:!0};var T=class SQLite3Driver extends u{static canonicalExecuteEntry=SQLite3Driver.prototype._execute;static canonicalExecute=SQLite3Driver.prototype.execute;static canonicalRunStatement=SQLite3Driver.prototype.runStatement;static canonicalTypedStatement=SQLite3Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=SQLite3Driver.prototype.executePositional;static canonicalNativePrepare=x.prototype.prepare;adapter=new y;maxBindParametersPerStatement=32766;result=m;sqliteMigrationCapability=c;serializeTransactions=!0;get numbersPlaceholders(){return!1}driverOptions;suppliedClient;canonicalAdapterParseResult=this.adapter.result.parseResult;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;constructor(e={}){if(super(`sqlite`,`sqlite3`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient){if(this.suppliedClient.pragma(`foreign_keys`,{simple:!0})!==1)throw new n(`A supplied SQLite database must enable PRAGMA foreign_keys = ON before wrapping.`,{meta:{driver:`sqlite3`}});this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:l(this.suppliedClient)})}SQLite3Driver.isPositionalCandidate(this)&&r(this,(e,t)=>this.executePositional(e,t),SQLite3Driver.isPositionalCandidate)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir??`:memory:`,t=this.driverOptions.options??{},n=new x(e,t);return n.pragma(`foreign_keys = ON`),t.timeout===void 0&&n.pragma(`busy_timeout = 5000`),n}async closeClient(e){e!==this.suppliedClient&&e.close()}async execute(e,t,n,r){let i=convertValuesForSQLite3(n);return this.runStatement(e,t,i,r?.model!==`$raw`)}async executeRaw(e,t,n){let r=n?convertValuesForSQLite3(n):void 0;return this.runStatement(e,t,r,!1)}async executePositional(e,n){let r,a=await this.executeTypedStatement(e,n,async(e,n,i,a)=>{let s={provider:this.driverName,operation:a.operation??`execute`};if(!SQLite3Driver.isPositionalProducer(this,e)){let r=await this.execute(e,n,i,a);return t(r,s),{kind:`borrowed`,result:r}}let c=convertValuesForSQLite3(i),l=cachedStatement(e,n,!0);if(!l.reader){let e={rows:[],rowCount:l.run(...c).changes};return t(e,s),{kind:`borrowed`,result:e}}r=e,l.safeIntegers(!0);let u=l.raw().all(...c),d=l.columns().map(e=>e.name);return o(u,d,s),{kind:`positional`,rows:u,columns:d}});return a.kind===`positional`&&!(r&&SQLite3Driver.isPositionalProducer(this,r))?{kind:`borrowed`,result:i(a)}:a}static isPositionalProducer(e,t){return SQLite3Driver.isPositionalCandidate(e)&&e.client===t}static isPositionalCandidate(e){return e instanceof SQLite3Driver?e.driverOptions.options?.nativeBinding===void 0&&SQLite3Driver.hasCanonicalProducerSurface(e)&&e.executeTypedStatement===SQLite3Driver.canonicalTypedStatement&&e.executePositional===SQLite3Driver.canonicalPositionalExecute&&e.result.parseField===g&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&(e.client===void 0||e.client===null||SQLite3Driver.isPositionalClient(e.client)):!1}static isPositionalClient(e){return Object.getPrototypeOf(e)===x.prototype&&!Object.hasOwn(e,`prepare`)&&Object.getOwnPropertyDescriptor(x.prototype,`prepare`)?.value===SQLite3Driver.canonicalNativePrepare}runStatement(e,t,n,r){let i=r?cachedStatement(e,t,!1):e.prepare(t);if(i.reader){i.safeIntegers(!0);let e=n?i.all(...n):i.all();return{rows:r?e:d(e),rowCount:e.length}}return{rows:[],rowCount:(n?i.run(...n):i.run()).changes}}static hasCanonicalProducerSurface(e){return Object.getPrototypeOf(e)===SQLite3Driver.prototype&&e._execute===SQLite3Driver.canonicalExecuteEntry&&e.execute===SQLite3Driver.canonicalExecute&&e.runStatement===SQLite3Driver.canonicalRunStatement&&e.result===m&&e.adapter.result.parseResult===e.canonicalAdapterParseResult}transactionOptionSupport(){return v}async transaction(e,t,n){return _(e,t,n)}};function createClient(e){s(e,`sqlite3`,w,{databaseUrl:`pass the database file as dataDir`});let{client:t,dataDir:n,options:r}=e;return a(e,new T({client:t,dataDir:n,options:r}))}export{T as SQLite3Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./normalized-result-BF7gr4_b.mjs";import{r as n}from"./validation-gwZYm3Yn.mjs";import{a as r,i,n as a,r as o}from"./client-Bhl2mWam.mjs";import{c as s,n as c,r as l,t as u}from"./driver-CQQbCQh9.mjs";import{a as d,c as f,i as p,l as m,n as h,o as g,s as _,t as v}from"./sqlite-utils-C0TyzOys.mjs";import{t as y}from"./sqlite-adapter-CoDeF2h2.mjs";import{Buffer as b}from"node:buffer";import x from"better-sqlite3";const S=new WeakMap,C=x.prototype.prepare;function cachedStatement(e,t,n){if(e.prepare!==C)return e.prepare(t);let r=S.get(e);r||(r=[new Map,new Map],S.set(e,r));let i=r[n?0:1],a=i.get(t);return a===void 0?(a=e.prepare(t),i.size===100&&i.delete(i.keys().next().value)):i.delete(t),i.set(t,a),a}function convertValuesForSQLite3(e){return e.map(e=>{let t=h(e);if(b.isBuffer(t)||!p(t))return t;let n=f(t);return b.from(n.buffer,n.byteOffset,n.byteLength)})}const w={client:!0,dataDir:!0,options:!0};var T=class SQLite3Driver extends u{static canonicalExecuteEntry=SQLite3Driver.prototype._execute;static canonicalExecute=SQLite3Driver.prototype.execute;static canonicalRunStatement=SQLite3Driver.prototype.runStatement;static canonicalTypedStatement=SQLite3Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=SQLite3Driver.prototype.executePositional;static canonicalNativePrepare=x.prototype.prepare;adapter=new y;maxBindParametersPerStatement=32766;result=m;sqliteMigrationCapability=c;serializeTransactions=!0;get numbersPlaceholders(){return!1}driverOptions;suppliedClient;canonicalAdapterParseResult=this.adapter.result.parseResult;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;constructor(e={}){if(super(`sqlite`,`sqlite3`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient){if(this.suppliedClient.pragma(`foreign_keys`,{simple:!0})!==1)throw new n(`A supplied SQLite database must enable PRAGMA foreign_keys = ON before wrapping.`,{meta:{driver:`sqlite3`}});this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:l(this.suppliedClient)})}SQLite3Driver.isPositionalCandidate(this)&&r(this,(e,t)=>this.executePositional(e,t),SQLite3Driver.isPositionalCandidate)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir??`:memory:`,t=this.driverOptions.options??{},n=new x(e,t);return n.pragma(`foreign_keys = ON`),t.timeout===void 0&&n.pragma(`busy_timeout = 5000`),n}async closeClient(e){e!==this.suppliedClient&&e.close()}async execute(e,t,n,r){let i=convertValuesForSQLite3(n);return this.runStatement(e,t,i,r?.model!==`$raw`)}async executeRaw(e,t,n){let r=n?convertValuesForSQLite3(n):void 0;return this.runStatement(e,t,r,!1)}async executePositional(e,n){let r,a=await this.executeTypedStatement(e,n,async(e,n,i,a)=>{let s={provider:this.driverName,operation:a.operation??`execute`};if(!SQLite3Driver.isPositionalProducer(this,e)){let r=await this.execute(e,n,i,a);return t(r,s),{kind:`borrowed`,result:r}}let c=convertValuesForSQLite3(i),l=cachedStatement(e,n,!0);if(!l.reader){let e={rows:[],rowCount:l.run(...c).changes};return t(e,s),{kind:`borrowed`,result:e}}r=e,l.safeIntegers(!0);let u=l.raw().all(...c),d=l.columns().map(e=>e.name);return o(u,d,s),{kind:`positional`,rows:u,columns:d}});return a.kind===`positional`&&!(r&&SQLite3Driver.isPositionalProducer(this,r))?{kind:`borrowed`,result:i(a)}:a}static isPositionalProducer(e,t){return SQLite3Driver.isPositionalCandidate(e)&&e.client===t}static isPositionalCandidate(e){return e instanceof SQLite3Driver?e.driverOptions.options?.nativeBinding===void 0&&SQLite3Driver.hasCanonicalProducerSurface(e)&&e.executeTypedStatement===SQLite3Driver.canonicalTypedStatement&&e.executePositional===SQLite3Driver.canonicalPositionalExecute&&e.result.parseField===g&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&(e.client===void 0||e.client===null||SQLite3Driver.isPositionalClient(e.client)):!1}static isPositionalClient(e){return Object.getPrototypeOf(e)===x.prototype&&!Object.hasOwn(e,`prepare`)&&Object.getOwnPropertyDescriptor(x.prototype,`prepare`)?.value===SQLite3Driver.canonicalNativePrepare}runStatement(e,t,n,r){let i=r?cachedStatement(e,t,!1):e.prepare(t);if(i.reader){i.safeIntegers(!0);let e=n?i.all(...n):i.all();return{rows:r?e:d(e),rowCount:e.length}}return{rows:[],rowCount:(n?i.run(...n):i.run()).changes}}static hasCanonicalProducerSurface(e){return Object.getPrototypeOf(e)===SQLite3Driver.prototype&&e._execute===SQLite3Driver.canonicalExecuteEntry&&e.execute===SQLite3Driver.canonicalExecute&&e.runStatement===SQLite3Driver.canonicalRunStatement&&e.result===m&&e.adapter.result.parseResult===e.canonicalAdapterParseResult}transactionOptionSupport(){return v}async transaction(e,t,n){return _(e,t,n)}};function createClient(e){s(e,`sqlite3`,w,{databaseUrl:`pass the database file as dataDir`});let{client:t,dataDir:n,options:r}=e;return a(e,new T({client:t,dataDir:n,options:r}))}export{T as SQLite3Driver,createClient};
2
2
  //# sourceMappingURL=sqlite3.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite3.mjs","names":[],"sources":["../src/drivers/sqlite3/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * SQLite3 Driver\n *\n * Driver implementation for better-sqlite3 (synchronous SQLite).\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport Database from \"better-sqlite3\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n SQLITE_MIGRATION_CAPABILITY,\n} from \"../driver\";\nimport { assertNormalizedQueryResult } from \"../normalized-result\";\nimport {\n assertPositionalRows,\n borrowPositionalResult,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n LOCAL_SQLITE_TRANSACTION_SUPPORT,\n normalizeSQLiteRawRows,\n parseSQLiteField,\n runLocalSQLiteTransaction,\n} from \"../shared/sqlite-utils\";\nimport type { QueryResult } from \"../types\";\n\ntype SQLite3Database = Database.Database;\ntype SQLite3Statement = Database.Statement;\n\n/**\n * Compiling SQL costs about as much as running a small read (~4 µs), and the\n * engine emits the same text for the same query shape, so each database keeps\n * its recent statements: one map for positional reads (raw, safe integers) and\n * one for keyed reads and writes, since a statement's modes are its own state.\n * Only a stock `prepare` is bypassed; a database whose `prepare` was replaced\n * sees every call. Oldest-first eviction bounds the native memory held.\n */\nconst STATEMENT_CACHE_LIMIT = 100;\nconst statementCaches = new WeakMap<\n SQLite3Database,\n readonly [Map<string, SQLite3Statement>, Map<string, SQLite3Statement>]\n>();\nconst stockPrepare = Database.prototype.prepare;\n\nfunction cachedStatement(\n db: SQLite3Database,\n sql: string,\n positional: boolean\n): SQLite3Statement {\n if (db.prepare !== stockPrepare) return db.prepare(sql);\n let caches = statementCaches.get(db);\n if (!caches) {\n caches = [new Map(), new Map()];\n statementCaches.set(db, caches);\n }\n const cache = caches[positional ? 0 : 1];\n let statement = cache.get(sql);\n if (statement === undefined) {\n statement = db.prepare(sql);\n if (cache.size === STATEMENT_CACHE_LIMIT)\n cache.delete(cache.keys().next().value as string);\n } else {\n cache.delete(sql);\n }\n cache.set(sql, statement);\n return statement;\n}\n\nfunction convertValuesForSQLite3(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (Buffer.isBuffer(value) || !isSQLiteBinaryValue(value)) {\n return value;\n }\n const bytes = sqliteBinaryToUint8Array(value);\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type SQLite3Options = Database.Options;\n\nexport interface SQLite3DriverOptions {\n client?: SQLite3Database;\n dataDir?: string;\n options?: SQLite3Options;\n}\n\nexport type SQLite3ClientConfig<C extends DriverConfig> = SQLite3DriverOptions &\n C;\n\nconst SQLITE3_CONFIG_KEYS: Record<keyof SQLite3DriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class SQLite3Driver extends Driver<SQLite3Database, SQLite3Database> {\n private static readonly canonicalExecuteEntry =\n SQLite3Driver.prototype._execute;\n private static readonly canonicalExecute = SQLite3Driver.prototype.execute;\n private static readonly canonicalRunStatement =\n SQLite3Driver.prototype.runStatement;\n private static readonly canonicalTypedStatement =\n SQLite3Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n SQLite3Driver.prototype.executePositional;\n private static readonly canonicalNativePrepare = Database.prototype.prepare;\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly sqliteMigrationCapability = SQLITE_MIGRATION_CAPABILITY;\n protected override readonly serializeTransactions = true;\n /** better-sqlite3 reads `?NNN` as a name, never by position. */\n protected override get numbersPlaceholders(): boolean {\n return false;\n }\n\n private readonly driverOptions: SQLite3DriverOptions;\n /**\n * The exact transport the caller handed over, captured from ONE read of\n * `options.client` at construction. That identity owns installation,\n * reconnect, and the close decision: a getter answering differently on a\n * second read used to leave this driver holding the caller's database while\n * believing it had made its own.\n */\n private readonly suppliedClient: SQLite3Database | undefined;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n\n constructor(options: SQLite3DriverOptions = {}) {\n super(\"sqlite\", \"sqlite3\");\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n if (this.suppliedClient.pragma(\"foreign_keys\", { simple: true }) !== 1) {\n throw new ClientInitializationError(\n \"A supplied SQLite database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"sqlite3\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n if (SQLite3Driver.isPositionalCandidate(this)) {\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n SQLite3Driver.isPositionalCandidate\n );\n }\n }\n\n protected async initClient(): Promise<SQLite3Database> {\n // A supplied database is reinstalled by the exact identity construction\n // captured: two namespace-scoped wrappers can share one transport, and a\n // reconnect that built a fresh `:memory:` database silently swapped the\n // caller's data for an empty file.\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n const options = this.driverOptions.options ?? {};\n\n const db = new Database(dataDir, options);\n // better-sqlite3 happens to enable this already; stated explicitly so FK\n // enforcement is a viborm guarantee, not an inherited library default.\n db.pragma(\"foreign_keys = ON\");\n // The caller's `timeout` is better-sqlite3's busy timeout and stands, as\n // libsql's does; VibORM's 5000 ms applies only when none is given.\n if (options.timeout === undefined) db.pragma(\"busy_timeout = 5000\");\n return db;\n }\n\n protected async closeClient(db: SQLite3Database): Promise<void> {\n // A supplied database belongs to the caller, who may be sharing it with a\n // sibling wrapper; the identity test is against the transport actually\n // being closed, not whatever the caller's record says now.\n if (db === this.suppliedClient) {\n return;\n }\n db.close();\n }\n\n protected async execute<T>(\n client: SQLite3Database,\n sql: string,\n params: unknown[],\n _context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForSQLite3(params);\n return this.runStatement<T>(\n client,\n sql,\n values,\n _context?.model !== \"$raw\"\n );\n }\n\n protected async executeRaw<T>(\n client: SQLite3Database,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForSQLite3(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private async executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n let producer: SQLite3Database | undefined;\n const response = await this.executeTypedStatement(\n query,\n context,\n async (\n client,\n statement,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n const resultContext = {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n };\n // Client initialization and observers can await or run caller work.\n if (!SQLite3Driver.isPositionalProducer(this, client)) {\n const result = await this.execute<unknown>(\n client,\n statement,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, resultContext);\n return { kind: \"borrowed\", result };\n }\n const values = convertValuesForSQLite3(params);\n const prepared = cachedStatement(client, statement, true);\n if (!prepared.reader) {\n const result = prepared.run(...values);\n const borrowed = { rows: [], rowCount: result.changes };\n assertNormalizedQueryResult(borrowed, resultContext);\n return { kind: \"borrowed\", result: borrowed };\n }\n producer = client;\n // A statement runs once, so integers are read exactly on that one run.\n // A re-read could not be proven harmless: a transform can make this an\n // `UPDATE … RETURNING`, and even a statement SQLite reports read-only\n // may call an application function with an observable effect.\n prepared.safeIntegers(true);\n const rows = prepared.raw().all(...values) as unknown[][];\n // Read after the run: SQLite reprepares a cached statement whose\n // schema changed (`SELECT *` after ADD COLUMN), so metadata read\n // before it would describe the previous columns.\n const columns = prepared.columns().map((column) => column.name);\n assertPositionalRows(rows, columns, resultContext);\n return { kind: \"positional\", rows, columns };\n }\n );\n if (\n response.kind === \"positional\" &&\n !(producer && SQLite3Driver.isPositionalProducer(this, producer))\n ) {\n return { kind: \"borrowed\", result: borrowPositionalResult(response) };\n }\n return response;\n }\n\n private static isPositionalProducer(\n driver: SQLite3Driver,\n client: SQLite3Database\n ): boolean {\n return (\n SQLite3Driver.isPositionalCandidate(driver) && driver.client === client\n );\n }\n\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof SQLite3Driver)) return false;\n return (\n driver.driverOptions.options?.nativeBinding === undefined &&\n SQLite3Driver.hasCanonicalProducerSurface(driver) &&\n driver.executeTypedStatement === SQLite3Driver.canonicalTypedStatement &&\n driver.executePositional === SQLite3Driver.canonicalPositionalExecute &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n (driver.client === undefined ||\n driver.client === null ||\n SQLite3Driver.isPositionalClient(driver.client))\n );\n }\n\n private static isPositionalClient(client: SQLite3Database): boolean {\n return (\n Object.getPrototypeOf(client) === Database.prototype &&\n !Object.hasOwn(client, \"prepare\") &&\n Object.getOwnPropertyDescriptor(Database.prototype, \"prepare\")?.value ===\n SQLite3Driver.canonicalNativePrepare\n );\n }\n\n private runStatement<T>(\n db: SQLite3Database,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt = typed ? cachedStatement(db, sql, false) : db.prepare(sql);\n\n if (stmt.reader) {\n // Read once without precision loss. Typed model parsing owns its domain;\n // raw results expose safe integers as numbers and wider integers as bigint.\n stmt.safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n /**\n * Whether the surface a caller can reach on this instance is still the\n * SHIPPED one.\n *\n * The result leg asks for the parser OBJECT, not for one of its hooks: a\n * positional result hands out the provider's own row arrays, so a driver is\n * stock only while `result` IS `sqliteResultParser` — the object\n * `shared/sqlite-utils.ts` owns — and anything a caller put there instead,\n * whatever hook it spells, is a middleware that will see those rows and\n * keeps the transport borrowed (root `AGENTS.md` rule 5: a stock driver with\n * \"unchanged typed execution/parser surfaces\", where \"a parser middleware …\n * stays borrowed\"). Asking only about `parseResult` asked a narrower\n * question, and since D-35 left the shipped parser with no result hook of its\n * own it admitted every object that merely lacks one (Arnaud's D-39).\n *\n * The adapter leg is unchanged, and is a different question: the adapter is\n * this driver's own object, captured once at construction, so what is asked\n * there is whether anything re-entered it afterwards.\n */\n private static hasCanonicalProducerSurface(driver: SQLite3Driver): boolean {\n return (\n Object.getPrototypeOf(driver) === SQLite3Driver.prototype &&\n driver._execute === SQLite3Driver.canonicalExecuteEntry &&\n driver.execute === SQLite3Driver.canonicalExecute &&\n driver.runStatement === SQLite3Driver.canonicalRunStatement &&\n driver.result === sqliteResultParser &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return LOCAL_SQLITE_TRANSACTION_SUPPORT;\n }\n\n protected async transaction<T>(\n client: SQLite3Database,\n fn: (tx: SQLite3Database) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runLocalSQLiteTransaction(client, fn, context);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: SQLite3ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, SQLite3DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: SQLite3Driver }\n >]: LinkedClientConfig<C & { driver: SQLite3Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"sqlite3\", SQLITE3_CONFIG_KEYS, {\n databaseUrl: \"pass the database file as dataDir\",\n });\n const { client, dataDir, options } = config;\n\n const driver = new SQLite3Driver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, SQLite3Driver>(config, driver);\n}\n"],"mappings":"ieA8DA,MACM,EAAkB,IAAI,QAItB,EAAe,EAAS,UAAU,QAExC,SAAS,gBACP,EACA,EACA,EACkB,CAClB,GAAI,EAAG,UAAY,EAAc,OAAO,EAAG,QAAQ,EAAI,CACvD,IAAI,EAAS,EAAgB,IAAI,EAAG,CAC/B,IACH,EAAS,CAAC,IAAI,IAAO,IAAI,IAAM,CAC/B,EAAgB,IAAI,EAAI,EAAO,EAEjC,IAAM,EAAQ,EAAO,EAAa,EAAI,GAClC,EAAY,EAAM,IAAI,EAAI,CAS9B,OARI,IAAc,IAAA,IAChB,EA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Q,UAAU,EACjC,OAAO,yBAAyB,EAAS,UAAW,UAAU,EAAE,QAC9D,cAAc,uBAIpB,aACE,EACA,EACA,EACA,EACgB,CAChB,IAAM,EAAO,EAAQ,gBAAgB,EAAI,EAAK,GAAM,CAAG,EAAG,QAAQ,EAAI,CAEtE,GAAI,EAAK,OAAQ,CAGf,EAAK,aAAa,GAAK,CACvB,IAAM,EAAQ,EAAS,EAAK,IAAI,GAAG,EAAO,CAAG,EAAK,KAAK,CACvD,MAAO,CACL,KAAM,EAAQ,EAAO,EAAuB,EAAK,CACjD,SAAU,EAAK,OAChB,CAIH,MAAO,CAAE,KAAM,EAAE,CAAS,UADX,EAAS,EAAK,IAAI,GAAG,EAAO,CAAG,EAAK,KAAK,EACb,QAAS,CAsBtD,OAAe,4BAA4B,EAAgC,CACzE,OACE,OAAO,eAAe,EAAO,GAAK,cAAc,WAChD,EAAO,WAAa,cAAc,uBAClC,EAAO,UAAY,cAAc,kBACjC,EAAO,eAAiB,cAAc,uBACtC,EAAO,SAAW,GAClB,EAAO,QAAQ,OAAO,cAAgB,EAAO,4BAIjD,0BAAwE,CACtE,OAAO,EAGT,MAAgB,YACd,EACA,EACA,EACY,CACZ,OAAO,EAA0B,EAAQ,EAAI,EAAQ,GAQzD,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,UAAW,EAAqB,CACpE,YAAa,oCACd,CAAC,CACF,GAAM,CAAE,SAAQ,UAAS,WAAY,EAIrC,OAAO,EAAkD,EAF1C,IAAI,EAAc,CAAE,SAAQ,UAAS,UAAS,CAAC,CAEU"}
1
+ {"version":3,"file":"sqlite3.mjs","names":[],"sources":["../src/drivers/sqlite3/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * SQLite3 Driver\n *\n * Driver implementation for better-sqlite3 (synchronous SQLite).\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport Database from \"better-sqlite3\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n SQLITE_MIGRATION_CAPABILITY,\n} from \"../driver\";\nimport { assertNormalizedQueryResult } from \"../normalized-result\";\nimport {\n assertPositionalRows,\n borrowPositionalResult,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n LOCAL_SQLITE_TRANSACTION_SUPPORT,\n normalizeSQLiteRawRows,\n parseSQLiteField,\n runLocalSQLiteTransaction,\n} from \"../shared/sqlite-utils\";\nimport type { QueryResult } from \"../types\";\n\ntype SQLite3Database = Database.Database;\ntype SQLite3Statement = Database.Statement;\n\n/**\n * Compiling SQL costs about as much as running a small read (~4 µs), and the\n * engine emits the same text for the same query shape, so each database keeps\n * its recent statements: one map for positional reads (raw, safe integers) and\n * one for keyed reads and writes, since a statement's modes are its own state.\n * Only a stock `prepare` is bypassed; a database whose `prepare` was replaced\n * sees every call. Oldest-first eviction bounds the native memory held.\n */\nconst STATEMENT_CACHE_LIMIT = 100;\nconst statementCaches = new WeakMap<\n SQLite3Database,\n readonly [Map<string, SQLite3Statement>, Map<string, SQLite3Statement>]\n>();\nconst stockPrepare = Database.prototype.prepare;\n\nfunction cachedStatement(\n db: SQLite3Database,\n sql: string,\n positional: boolean\n): SQLite3Statement {\n if (db.prepare !== stockPrepare) return db.prepare(sql);\n let caches = statementCaches.get(db);\n if (!caches) {\n caches = [new Map(), new Map()];\n statementCaches.set(db, caches);\n }\n const cache = caches[positional ? 0 : 1];\n let statement = cache.get(sql);\n if (statement === undefined) {\n statement = db.prepare(sql);\n if (cache.size === STATEMENT_CACHE_LIMIT)\n cache.delete(cache.keys().next().value as string);\n } else {\n cache.delete(sql);\n }\n cache.set(sql, statement);\n return statement;\n}\n\nfunction convertValuesForSQLite3(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (Buffer.isBuffer(value) || !isSQLiteBinaryValue(value)) {\n return value;\n }\n const bytes = sqliteBinaryToUint8Array(value);\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type SQLite3Options = Database.Options;\n\nexport interface SQLite3DriverOptions {\n client?: SQLite3Database;\n dataDir?: string;\n options?: SQLite3Options;\n}\n\nexport type SQLite3ClientConfig<C extends DriverConfig> = SQLite3DriverOptions &\n C;\n\nconst SQLITE3_CONFIG_KEYS: Record<keyof SQLite3DriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class SQLite3Driver extends Driver<SQLite3Database, SQLite3Database> {\n private static readonly canonicalExecuteEntry =\n SQLite3Driver.prototype._execute;\n private static readonly canonicalExecute = SQLite3Driver.prototype.execute;\n private static readonly canonicalRunStatement =\n SQLite3Driver.prototype.runStatement;\n private static readonly canonicalTypedStatement =\n SQLite3Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n SQLite3Driver.prototype.executePositional;\n private static readonly canonicalNativePrepare = Database.prototype.prepare;\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly sqliteMigrationCapability = SQLITE_MIGRATION_CAPABILITY;\n protected override readonly serializeTransactions = true;\n /** better-sqlite3 reads `?NNN` as a name, never by position. */\n protected override get numbersPlaceholders(): boolean {\n return false;\n }\n\n private readonly driverOptions: SQLite3DriverOptions;\n /**\n * The exact transport the caller handed over, captured from ONE read of\n * `options.client` at construction. That identity owns installation,\n * reconnect, and the close decision: a getter answering differently on a\n * second read used to leave this driver holding the caller's database while\n * believing it had made its own.\n */\n private readonly suppliedClient: SQLite3Database | undefined;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n\n constructor(options: SQLite3DriverOptions = {}) {\n super(\"sqlite\", \"sqlite3\");\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n if (this.suppliedClient.pragma(\"foreign_keys\", { simple: true }) !== 1) {\n throw new ClientInitializationError(\n \"A supplied SQLite database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"sqlite3\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n if (SQLite3Driver.isPositionalCandidate(this)) {\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n SQLite3Driver.isPositionalCandidate\n );\n }\n }\n\n protected async initClient(): Promise<SQLite3Database> {\n // A supplied database is reinstalled by the exact identity construction\n // captured: two namespace-scoped wrappers can share one transport, and a\n // reconnect that built a fresh `:memory:` database silently swapped the\n // caller's data for an empty file.\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n const options = this.driverOptions.options ?? {};\n\n const db = new Database(dataDir, options);\n // better-sqlite3 happens to enable this already; stated explicitly so FK\n // enforcement is a viborm guarantee, not an inherited library default.\n db.pragma(\"foreign_keys = ON\");\n // The caller's `timeout` is better-sqlite3's busy timeout and stands, as\n // libsql's does; VibORM's 5000 ms applies only when none is given.\n if (options.timeout === undefined) db.pragma(\"busy_timeout = 5000\");\n return db;\n }\n\n protected async closeClient(db: SQLite3Database): Promise<void> {\n // A supplied database belongs to the caller, who may be sharing it with a\n // sibling wrapper; the identity test is against the transport actually\n // being closed, not whatever the caller's record says now.\n if (db === this.suppliedClient) {\n return;\n }\n db.close();\n }\n\n protected async execute<T>(\n client: SQLite3Database,\n sql: string,\n params: unknown[],\n _context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForSQLite3(params);\n return this.runStatement<T>(\n client,\n sql,\n values,\n _context?.model !== \"$raw\"\n );\n }\n\n protected async executeRaw<T>(\n client: SQLite3Database,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForSQLite3(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private async executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n let producer: SQLite3Database | undefined;\n const response = await this.executeTypedStatement(\n query,\n context,\n async (\n client,\n statement,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n const resultContext = {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n };\n // Client initialization and observers can await or run caller work.\n if (!SQLite3Driver.isPositionalProducer(this, client)) {\n const result = await this.execute<unknown>(\n client,\n statement,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, resultContext);\n return { kind: \"borrowed\", result };\n }\n const values = convertValuesForSQLite3(params);\n const prepared = cachedStatement(client, statement, true);\n if (!prepared.reader) {\n const result = prepared.run(...values);\n const borrowed = { rows: [], rowCount: result.changes };\n assertNormalizedQueryResult(borrowed, resultContext);\n return { kind: \"borrowed\", result: borrowed };\n }\n producer = client;\n // A statement runs once, so integers are read exactly on that one run.\n // A re-read could not be proven harmless: a transform can make this an\n // `UPDATE … RETURNING`, and even a statement SQLite reports read-only\n // may call an application function with an observable effect.\n prepared.safeIntegers(true);\n const rows = prepared.raw().all(...values) as unknown[][];\n // Read after the run: SQLite reprepares a cached statement whose\n // schema changed (`SELECT *` after ADD COLUMN), so metadata read\n // before it would describe the previous columns.\n const columns = prepared.columns().map((column) => column.name);\n assertPositionalRows(rows, columns, resultContext);\n return { kind: \"positional\", rows, columns };\n }\n );\n if (\n response.kind === \"positional\" &&\n !(producer && SQLite3Driver.isPositionalProducer(this, producer))\n ) {\n return { kind: \"borrowed\", result: borrowPositionalResult(response) };\n }\n return response;\n }\n\n private static isPositionalProducer(\n driver: SQLite3Driver,\n client: SQLite3Database\n ): boolean {\n return (\n SQLite3Driver.isPositionalCandidate(driver) && driver.client === client\n );\n }\n\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof SQLite3Driver)) return false;\n return (\n driver.driverOptions.options?.nativeBinding === undefined &&\n SQLite3Driver.hasCanonicalProducerSurface(driver) &&\n driver.executeTypedStatement === SQLite3Driver.canonicalTypedStatement &&\n driver.executePositional === SQLite3Driver.canonicalPositionalExecute &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n (driver.client === undefined ||\n driver.client === null ||\n SQLite3Driver.isPositionalClient(driver.client))\n );\n }\n\n private static isPositionalClient(client: SQLite3Database): boolean {\n return (\n Object.getPrototypeOf(client) === Database.prototype &&\n !Object.hasOwn(client, \"prepare\") &&\n Object.getOwnPropertyDescriptor(Database.prototype, \"prepare\")?.value ===\n SQLite3Driver.canonicalNativePrepare\n );\n }\n\n private runStatement<T>(\n db: SQLite3Database,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt = typed ? cachedStatement(db, sql, false) : db.prepare(sql);\n\n if (stmt.reader) {\n // Read once without precision loss. Typed model parsing owns its domain;\n // raw results expose safe integers as numbers and wider integers as bigint.\n stmt.safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n /**\n * Whether the surface a caller can reach on this instance is still the\n * SHIPPED one.\n *\n * The result leg asks for the parser OBJECT, not for one of its hooks: a\n * positional result hands out the provider's own row arrays, so a driver is\n * stock only while `result` IS `sqliteResultParser` — the object\n * `shared/sqlite-utils.ts` owns — and anything a caller put there instead,\n * whatever hook it spells, is a middleware that will see those rows and\n * keeps the transport borrowed (root `AGENTS.md` rule 5: a stock driver with\n * \"unchanged typed execution/parser surfaces\", where \"a parser middleware …\n * stays borrowed\"). Asking only about `parseResult` asked a narrower\n * question, and since D-35 left the shipped parser with no result hook of its\n * own it admitted every object that merely lacks one (Arnaud's D-39).\n *\n * The adapter leg is unchanged, and is a different question: the adapter is\n * this driver's own object, captured once at construction, so what is asked\n * there is whether anything re-entered it afterwards.\n */\n private static hasCanonicalProducerSurface(driver: SQLite3Driver): boolean {\n return (\n Object.getPrototypeOf(driver) === SQLite3Driver.prototype &&\n driver._execute === SQLite3Driver.canonicalExecuteEntry &&\n driver.execute === SQLite3Driver.canonicalExecute &&\n driver.runStatement === SQLite3Driver.canonicalRunStatement &&\n driver.result === sqliteResultParser &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return LOCAL_SQLITE_TRANSACTION_SUPPORT;\n }\n\n protected async transaction<T>(\n client: SQLite3Database,\n fn: (tx: SQLite3Database) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runLocalSQLiteTransaction(client, fn, context);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: SQLite3ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, SQLite3DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: SQLite3Driver }\n >]: LinkedClientConfig<C & { driver: SQLite3Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"sqlite3\", SQLITE3_CONFIG_KEYS, {\n databaseUrl: \"pass the database file as dataDir\",\n });\n const { client, dataDir, options } = config;\n\n const driver = new SQLite3Driver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, SQLite3Driver>(config, driver);\n}\n"],"mappings":"2dA8DA,MACM,EAAkB,IAAI,QAItB,EAAe,EAAS,UAAU,QAExC,SAAS,gBACP,EACA,EACA,EACkB,CAClB,GAAI,EAAG,UAAY,EAAc,OAAO,EAAG,QAAQ,EAAI,CACvD,IAAI,EAAS,EAAgB,IAAI,EAAG,CAC/B,IACH,EAAS,CAAC,IAAI,IAAO,IAAI,IAAM,CAC/B,EAAgB,IAAI,EAAI,EAAO,EAEjC,IAAM,EAAQ,EAAO,EAAa,EAAI,GAClC,EAAY,EAAM,IAAI,EAAI,CAS9B,OARI,IAAc,IAAA,IAChB,EAAY,EAAG,QAAQ,EAAI,CACvB,EAAM,OAAS,KACjB,EAAM,OAAO,EAAM,MAAM,CAAC,MAAM,CAAC,MAAgB,EAEnD,EAAM,OAAO,EAAI,CAEnB,EAAM,IAAI,EAAK,EAAU,CAClB,EAGT,SAAS,wBAAwB,EAA8B,CAC7D,OAAO,EAAO,IAAK,GAAc,CAC/B,IAAM,EAAQ,EAAsB,EAAU,CAC9C,GAAI,EAAO,SAAS,EAAM,EAAI,CAAC,EAAoB,EAAM,CACvD,OAAO,EAET,IAAM,EAAQ,EAAyB,EAAM,CAC7C,OAAO,EAAO,KAAK,EAAM,OAAQ,EAAM,WAAY,EAAM,WAAW,EACpE,CAkBJ,MAAM,EAAgE,CACpE,OAAQ,GACR,QAAS,GACT,QAA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tD,OAAe,4BAA4B,EAAgC,CACzE,OACE,OAAO,eAAe,EAAO,GAAK,cAAc,WAChD,EAAO,WAAa,cAAc,uBAClC,EAAO,UAAY,cAAc,kBACjC,EAAO,eAAiB,cAAc,uBACtC,EAAO,SAAW,GAClB,EAAO,QAAQ,OAAO,cAAgB,EAAO,4BAIjD,0BAAwE,CACtE,OAAO,EAGT,MAAgB,YACd,EACA,EACA,EACY,CACZ,OAAO,EAA0B,EAAQ,EAAI,EAAQ,GAQzD,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,UAAW,EAAqB,CACpE,YAAa,oCACd,CAAC,CACF,GAAM,CAAE,SAAQ,UAAS,WAAY,EAIrC,OAAO,EAAkD,EAF1C,IAAI,EAAc,CAAE,SAAQ,UAAS,UAAS,CAAC,CAEU"}
@@ -1,6 +1,6 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t,t as n}from"./sql-BvHwL73I.mjs";const createIdentifierQuoter=e=>t=>e+(t.indexOf(e)===-1?t:t.replaceAll(e,e+e))+e,qualifiedPrefix=(e,t)=>`${e(t)}.`,renderQualifiedIdentifier=(e,t,n)=>t===void 0?e(n):qualifiedPrefix(e,t)+e(n),createQualifiedIdentifierRenderer=(e,t)=>{if(t===void 0)return e;let n=qualifiedPrefix(e,t);return t=>n+e(t)},createRawSql=()=>e=>t.raw(e),stringifyJson=e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t),r=/^\d+$/,buildJsonPath=e=>{let t=`$`;for(let n of e)t+=r.test(n)?`[${n}]`:`.${JSON.stringify(n)}`;return t},createStandardLiterals=()=>({value:e=>t`${e}`,null:()=>t.raw(`NULL`),list:e=>e.length===0?t.raw(`()`):t`(${t.join(e,`, `)})`}),createComparisonOperators=()=>({eq:(e,n)=>t`${e} = ${n}`,neq:(e,n)=>t`${e} <> ${n}`,lt:(e,n)=>t`${e} < ${n}`,lte:(e,n)=>t`${e} <= ${n}`,gt:(e,n)=>t`${e} > ${n}`,gte:(e,n)=>t`${e} >= ${n}`}),createNullOperators=()=>({isNull:e=>t`${e} IS NULL`,isNotNull:e=>t`${e} IS NOT NULL`}),createRangeOperators=()=>({between:(e,n,r)=>t`${e} BETWEEN ${n} AND ${r}`,notBetween:(e,n,r)=>t`${e} NOT BETWEEN ${n} AND ${r}`}),createExistenceOperators=()=>({exists:e=>t`EXISTS (${e})`,notExists:e=>t`NOT EXISTS (${e})`}),createAggregateFunctions=e=>({count:e=>e?t`COUNT(${e})`:t.raw(`COUNT(*)`),countDistinct:e=>t`COUNT(DISTINCT ${e})`,sum:e=>t`SUM(${e})`,numberSum:n=>{let r=t`SUM(CASE WHEN ABS(${n}) >= 1e-288 THEN ${n} / 4294967296.0 / 4294967296.0 END)`,i=t`SUM(CASE WHEN ABS(${n}) < 1e-288 THEN ${n} END)`,a=t.raw(e??`1.7976931348623157e308`),o=t`CASE WHEN ${r} IS NULL THEN ${i} WHEN ABS(${r}) < 9.7453140114e288 THEN ${r} * 4294967296.0 * 4294967296.0 + COALESCE(${i}, 0) WHEN ${r} > 0 THEN ${a} ELSE -${a} END`;return{parts:[r,i],value:o,order:e?[o]:[o,r]}},avg:e=>t`AVG(${e})`,min:e=>t`MIN(${e})`,max:e=>t`MAX(${e})`});function decimalCoefficientPrecision(e){return e.startsWith(`-`)?e.length-1:e.length}function createDecimalSumOperandPrecision(e){return t=>{let n=decimalCoefficientPrecision(t);return n<=e?n:void 0}}const createDirectionOrderBy=()=>({asc:e=>t`${e} ASC`,desc:e=>t`${e} DESC`}),directionKeyword=e=>e===`desc`?t.raw(`DESC`):t.raw(`ASC`),createEmulatedNullsOrderBy=()=>({nullsFirst:(e,n)=>t`(${e} IS NULL) DESC, ${e} ${directionKeyword(n)}`,nullsLast:(e,n)=>t`(${e} IS NULL) ASC, ${e} ${directionKeyword(n)}`}),createStandardClauses=()=>({select:e=>t`SELECT ${e}`,selectDistinct:e=>t`SELECT DISTINCT ${e}`,from:e=>t`FROM ${e}`,where:e=>t`WHERE ${e}`,orderBy:e=>t`ORDER BY ${e}`,limit:e=>t`LIMIT ${e}`,offset:e=>t`OFFSET ${e}`,groupBy:e=>t`GROUP BY ${e}`,having:e=>t`HAVING ${e}`}),createNumericSetOperations=()=>({assign:(e,n)=>t`${e} = ${n}`,increment:(e,n)=>t`${e} = ${e} + ${n}`,decrement:(e,n)=>t`${e} = ${e} - ${n}`}),createRelationFilters=()=>({some:e=>t`EXISTS (${e})`,every:e=>t`NOT EXISTS (${e})`,none:e=>t`NOT EXISTS (${e})`,is:e=>t`EXISTS (${e})`,isNot:e=>t`NOT EXISTS (${e})`}),createMutationCommands=()=>({update:(e,n,r)=>r?t`UPDATE ${e} SET ${n} WHERE ${r}`:t`UPDATE ${e} SET ${n}`,delete:(e,n)=>n?t`DELETE FROM ${e} WHERE ${n}`:t`DELETE FROM ${e}`}),rowValues=e=>t`(${t.join(e,`, `)})`,unionTypedRows=e=>(n,r,i)=>t`(${t.join([n.head,...r.map(e=>t`SELECT ${t.join(e,`, `)}`)],` UNION ALL `)}) AS ${t.raw(e(i))}`,createSetOperations=(e,n=unionTypedRows(e))=>({union:(...e)=>t.join(e,` UNION `),unionAll:(...e)=>t.join(e,` UNION ALL `),intersect:(...e)=>t.join(e,` INTERSECT `),except:(e,n)=>t`${e} EXCEPT ${n}`,typedRows:n}),isQualifiedColumnNamed=(e,t,n)=>{if(e===void 0||!e.endsWith(t))return!1;let r=e.slice(0,-t.length-1);return e[r.length]===`.`&&r.length>=2&&r[0]===n&&r.at(-1)===n&&!r.slice(1,-1).replaceAll(n+n,``).includes(n)},createIdentifiers=(e,r,i=!1)=>{let a=createQualifiedIdentifierRenderer(e,r),o=e(``)[0];return{escape:n=>t.raw(e(n)),column:(n,r)=>{let i=n?`${e(n)}.${e(r)}`:e(r);return t.raw(i)},table:(n,r)=>{let i=a(n);return t.raw(r===void 0?i:`${i} AS ${e(r)}`)},aliased:(t,r)=>{let a=e(r);return i&&isQualifiedColumnNamed(n.leafText(t),a,o)?t:new n([``,` AS ${a}`],[t])}}},createSubqueries=e=>({scalar:e=>t`(${e})`,correlate:(n,r)=>t`(${n}) AS ${t.raw(e(r))}`,existsCheck:(e,n)=>t`SELECT 1 FROM ${e} WHERE ${n}`,isolated:e=>e}),createCteBuilders=(e,n)=>({with:r=>{let i=r.map(({name:r,query:i,inlined:a})=>a&&n?t`${t.raw(e(r))} AS ${n} (${i})`:t`${t.raw(e(r))} AS (${i})`);return t`WITH ${t.join(i,`, `)}`},recursive:(n,r,i,a=`all`)=>{let o=a===`all`?t.raw(`UNION ALL`):t.raw(`UNION`);return t`WITH RECURSIVE ${t.raw(e(n))} AS (
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t,t as n}from"./sql-BvHwL73I.mjs";const createIdentifierQuoter=e=>t=>e+(t.indexOf(e)===-1?t:t.replaceAll(e,e+e))+e,qualifiedPrefix=(e,t)=>`${e(t)}.`,renderQualifiedIdentifier=(e,t,n)=>t===void 0?e(n):qualifiedPrefix(e,t)+e(n),createQualifiedIdentifierRenderer=(e,t)=>{if(t===void 0)return e;let n=qualifiedPrefix(e,t);return t=>n+e(t)},createRawSql=()=>e=>t.raw(e),stringifyJson=e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t),r=/^\d+$/,buildJsonPath=e=>{let t=`$`;for(let n of e)t+=r.test(n)?`[${n}]`:`.${JSON.stringify(n)}`;return t},createStandardLiterals=()=>({value:e=>t`${e}`,null:()=>t.raw(`NULL`),list:e=>e.length===0?t.raw(`()`):t`(${t.join(e,`, `)})`}),createComparisonOperators=()=>({eq:(e,n)=>t`${e} = ${n}`,neq:(e,n)=>t`${e} <> ${n}`,lt:(e,n)=>t`${e} < ${n}`,lte:(e,n)=>t`${e} <= ${n}`,gt:(e,n)=>t`${e} > ${n}`,gte:(e,n)=>t`${e} >= ${n}`}),createNullOperators=()=>({isNull:e=>t`${e} IS NULL`,isNotNull:e=>t`${e} IS NOT NULL`}),createRangeOperators=()=>({between:(e,n,r)=>t`${e} BETWEEN ${n} AND ${r}`,notBetween:(e,n,r)=>t`${e} NOT BETWEEN ${n} AND ${r}`}),createExistenceOperators=()=>({exists:e=>t`EXISTS (${e})`,notExists:e=>t`NOT EXISTS (${e})`}),createAggregateFunctions=e=>({count:e=>e?t`COUNT(${e})`:t.raw(`COUNT(*)`),countDistinct:e=>t`COUNT(DISTINCT ${e})`,sum:e=>t`SUM(${e})`,numberSum:n=>{let r=t`SUM(CASE WHEN ABS(${n}) >= 1e-288 THEN ${n} / 4294967296.0 / 4294967296.0 END)`,i=t`SUM(CASE WHEN ABS(${n}) < 1e-288 THEN ${n} END)`,a=t.raw(e??`1.7976931348623157e308`),o=t`CASE WHEN ${r} IS NULL THEN ${i} WHEN ABS(${r}) < 9.7453140114e288 THEN ${r} * 4294967296.0 * 4294967296.0 + COALESCE(${i}, 0) WHEN ${r} > 0 THEN ${a} ELSE -${a} END`;return{parts:[r,i],value:o,order:e?[o]:[o,r]}},avg:e=>t`AVG(${e})`,min:e=>t`MIN(${e})`,max:e=>t`MAX(${e})`});function decimalCoefficientPrecision(e){return e.startsWith(`-`)?e.length-1:e.length}function createDecimalSumOperandPrecision(e){return t=>{let n=decimalCoefficientPrecision(t);return n<=e?n:void 0}}const createDirectionOrderBy=()=>({asc:e=>t`${e} ASC`,desc:e=>t`${e} DESC`}),directionKeyword=e=>e===`desc`?t.raw(`DESC`):t.raw(`ASC`),createEmulatedNullsOrderBy=()=>({nullsFirst:(e,n)=>t`(${e} IS NULL) DESC, ${e} ${directionKeyword(n)}`,nullsLast:(e,n)=>t`(${e} IS NULL) ASC, ${e} ${directionKeyword(n)}`}),createStandardClauses=()=>({select:e=>t`SELECT ${e}`,selectDistinct:e=>t`SELECT DISTINCT ${e}`,from:e=>t`FROM ${e}`,where:e=>t`WHERE ${e}`,orderBy:e=>t`ORDER BY ${e}`,limit:e=>t`LIMIT ${e}`,offset:e=>t`OFFSET ${e}`,groupBy:e=>t`GROUP BY ${e}`,having:e=>t`HAVING ${e}`}),createNumericSetOperations=()=>({assign:(e,n)=>t`${e} = ${n}`,increment:(e,n)=>t`${e} = ${e} + ${n}`,decrement:(e,n)=>t`${e} = ${e} - ${n}`}),createRelationFilters=()=>({some:e=>t`EXISTS (${e})`,every:e=>t`NOT EXISTS (${e})`,none:e=>t`NOT EXISTS (${e})`,is:e=>t`EXISTS (${e})`,isNot:e=>t`NOT EXISTS (${e})`}),createMutationCommands=()=>({update:(e,n,r)=>r?t`UPDATE ${e} SET ${n} WHERE ${r}`:t`UPDATE ${e} SET ${n}`,delete:(e,n)=>n?t`DELETE FROM ${e} WHERE ${n}`:t`DELETE FROM ${e}`}),rowValues=e=>t`(${t.join(e,`, `)})`,unionTypedRows=e=>(n,r,i)=>t`(${t.join([n.head,...r.map(e=>t`SELECT ${t.join(e,`, `)}`)],` UNION ALL `)}) AS ${t.raw(e(i))}`,createSetOperations=(e,n=unionTypedRows(e))=>({union:(...e)=>t.join(e,` UNION `),unionAll:(...e)=>t.join(e,` UNION ALL `),intersect:(...e)=>t.join(e,` INTERSECT `),except:(e,n)=>t`${e} EXCEPT ${n}`,typedRows:n}),isQualifiedColumnNamed=(e,t,n)=>{if(e===void 0||!e.endsWith(t))return!1;let r=e.slice(0,-t.length-1);return e[r.length]===`.`&&r.length>=2&&r[0]===n&&r.at(-1)===n&&!r.slice(1,-1).replaceAll(n+n,``).includes(n)},createIdentifiers=(e,r,i=!1)=>{let a=createQualifiedIdentifierRenderer(e,r),o=e(``)[0];return{escape:n=>t.raw(e(n)),column:(n,r)=>{let i=n?`${e(n)}.${e(r)}`:e(r);return t.raw(i)},table:(n,r)=>{let i=a(n);return t.raw(r===void 0?i:`${i} AS ${e(r)}`)},aliased:(t,r)=>{let a=e(r);return i&&isQualifiedColumnNamed(n.leafText(t),a,o)?t:new n([``,` AS ${a}`],[t])}}},createSubqueries=e=>({scalar:e=>t`(${e})`,correlate:(n,r)=>t`(${n}) AS ${t.raw(e(r))}`,existsCheck:(e,n)=>t`SELECT 1 FROM ${e} WHERE ${n}`,isolated:e=>e}),createCteBuilders=(e,n={})=>({with:r=>{let i=r.map(({name:r,query:i,inlined:a})=>{let o;return a!==void 0&&(o=a?n.inlining:n.materializing),o?t`${t.raw(e(r))} AS ${o} (${i})`:t`${t.raw(e(r))} AS (${i})`});return r.some(e=>e.recursive)?t`WITH RECURSIVE ${t.join(i,`, `)}`:t`WITH ${t.join(i,`, `)}`},recursive:(n,r,i,a=`all`)=>{let o=a===`all`?t.raw(`UNION ALL`):t.raw(`UNION`);return t`WITH RECURSIVE ${t.raw(e(n))} AS (
2
2
  ${r}
3
3
  ${o}
4
4
  ${i}
5
5
  )`}}),createInsertStatement=e=>(n,r,i,a)=>{let o=r.map(n=>t.raw(e(n))),s=Array.isArray(i)?t`VALUES ${t.join(i.map(e=>t`(${t.join(e,`, `)})`),`, `)}`:i.select;return t`INSERT ${a?t`${a} `:t``}INTO ${n} (${t.join(o,`, `)}) ${s}`},createOnConflictBuilders=()=>({onConflict:(e,n,r)=>e?r?t`ON CONFLICT (${e}) WHERE ${r} DO ${n}`:t`ON CONFLICT (${e}) DO ${n}`:t`ON CONFLICT DO ${n}`,onConflictUpdate:(e,n)=>n?t`UPDATE SET ${e} WHERE ${n}`:t`UPDATE SET ${e}`,skipDuplicates:()=>({prefix:t``,suffix:t`ON CONFLICT DO NOTHING`})}),createMembershipOperators=()=>({in:(e,n)=>t`${e} IN ${n}`,notIn:(e,n)=>t`${e} NOT IN ${n}`}),createLogicalOperators=(e,n)=>({and:(...n)=>n.length===0?e():n.length===1?n[0]:t`(${t.join(n,` AND `)})`,or:(...e)=>e.length===0?n():e.length===1?e[0]:t`(${t.join(e,` OR `)})`,not:e=>t`NOT (${e})`}),createCommonExpressions=()=>({caseWhen:(e,n)=>e.length===0?n:t`CASE ${t.join(e.map(e=>t`WHEN ${e.when} THEN ${e.then}`),` `)} ELSE ${n} END`,add:(e,n)=>t`(${e} + ${n})`,subtract:(e,n)=>t`(${e} - ${n})`,multiply:(e,n)=>t`(${e} * ${n})`,divide:(e,n)=>t`(${e} / ${n})`,upper:e=>t`UPPER(${e})`,lower:e=>t`LOWER(${e})`,coalesce:(...e)=>t`COALESCE(${t.join(e,`, `)})`}),createCastExpression=e=>(n,r)=>t`CAST(${n} AS ${t.raw(e[r])})`,createCoreJoins=()=>({inner:(e,n)=>t`INNER JOIN ${e} ON ${n}`,left:(e,n)=>t`LEFT JOIN ${e} ON ${n}`,right:(e,n)=>t`RIGHT JOIN ${e} ON ${n}`,cross:e=>t`CROSS JOIN ${e}`}),createLateralJoins=e=>({lateral:(n,r)=>t`JOIN LATERAL (${n}) AS ${t.raw(e(r))} ON TRUE`,lateralLeft:(n,r)=>t`LEFT JOIN LATERAL (${n}) AS ${t.raw(e(r))} ON TRUE`}),escapeLikeLiteral=e=>e.replace(/[\\%_]/g,e=>`\\${e}`),escapeGlobLiteral=e=>e.replace(/[*?[]/g,e=>`[${e}]`);export{escapeLikeLiteral as A,createRelationFilters as C,createSubqueries as D,createStandardLiterals as E,stringifyJson as M,createIdentifierQuoter as N,decimalCoefficientPrecision as O,renderQualifiedIdentifier as P,createRawSql as S,createStandardClauses as T,createMutationCommands as _,createComparisonOperators as a,createOnConflictBuilders as b,createDecimalSumOperandPrecision as c,createExistenceOperators as d,createIdentifiers as f,createMembershipOperators as g,createLogicalOperators as h,createCommonExpressions as i,rowValues as j,escapeGlobLiteral as k,createDirectionOrderBy as l,createLateralJoins as m,createAggregateFunctions as n,createCoreJoins as o,createInsertStatement as p,createCastExpression as r,createCteBuilders as s,buildJsonPath as t,createEmulatedNullsOrderBy as u,createNullOperators as v,createSetOperations as w,createRangeOperators as x,createNumericSetOperations as y};
6
- //# sourceMappingURL=standard-sql-CYdZ_KXH.mjs.map
6
+ //# sourceMappingURL=standard-sql-DmKF8msN.mjs.map