viborm 1.3.0 → 1.3.2

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 (167) hide show
  1. package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-B8XWzCev.mjs} +1 -1
  2. package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-B8XWzCev.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DoWlPD2h.mjs} +1 -1
  6. package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DoWlPD2h.mjs.map} +1 -1
  7. package/dist/{builder-Df24l2Bd.mjs → builder-DhxaVYP2.mjs} +2 -2
  8. package/dist/{builder-Df24l2Bd.mjs.map → builder-DhxaVYP2.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +1 -1
  18. package/dist/cache.mjs +1 -1
  19. package/dist/cache.mjs.map +1 -1
  20. package/dist/chain-BjJ_M7EE.mjs +2 -0
  21. package/dist/chain-BjJ_M7EE.mjs.map +1 -0
  22. package/dist/cli.mjs +1 -1
  23. package/dist/client-BCgMXn6N.mjs +2 -0
  24. package/dist/client-BCgMXn6N.mjs.map +1 -0
  25. package/dist/{client-70MrTq1E.d.mts → client-Df81J4oB.d.mts} +1 -1
  26. package/dist/{client-DM1UHfYG.mjs → client-q6ccRgdO.mjs} +2 -2
  27. package/dist/{client-DM1UHfYG.mjs.map → client-q6ccRgdO.mjs.map} +1 -1
  28. package/dist/client.d.mts +1 -1
  29. package/dist/client.mjs +1 -1
  30. package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
  31. package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
  32. package/dist/config.d.mts +1 -1
  33. package/dist/config.mjs +1 -1
  34. package/dist/d1.d.mts +1 -1
  35. package/dist/d1.mjs +1 -1
  36. package/dist/{driver-CPD0Xxw2.mjs → driver-D6_Ik58x.mjs} +2 -2
  37. package/dist/{driver-CPD0Xxw2.mjs.map → driver-D6_Ik58x.mjs.map} +1 -1
  38. package/dist/{driver-B9fIori_.mjs → driver-Ddt147dK.mjs} +2 -2
  39. package/dist/{driver-B9fIori_.mjs.map → driver-Ddt147dK.mjs.map} +1 -1
  40. package/dist/driver.d.mts +1 -1
  41. package/dist/driver.mjs +1 -1
  42. package/dist/every-dpzVDwzu.mjs +2 -0
  43. package/dist/{every-1pKZteeB.mjs.map → every-dpzVDwzu.mjs.map} +1 -1
  44. package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
  45. package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
  46. package/dist/{hydration-DsyHNSDS.mjs → hydration-C2uXmJy6.mjs} +2 -2
  47. package/dist/{hydration-DsyHNSDS.mjs.map → hydration-C2uXmJy6.mjs.map} +1 -1
  48. package/dist/{identifier-conversion-DaZ9yNpv.mjs → identifier-conversion-C2pwwFOS.mjs} +2 -2
  49. package/dist/{identifier-conversion-DaZ9yNpv.mjs.map → identifier-conversion-C2pwwFOS.mjs.map} +1 -1
  50. package/dist/identity-Bj2EN6Ss.mjs +2 -0
  51. package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
  52. package/dist/{index-VsM29vYN.d.mts → index-D4O0Twvs.d.mts} +16 -8
  53. package/dist/index.d.mts +1 -1
  54. package/dist/index.mjs +1 -1
  55. package/dist/instrumentation.d.mts +1 -1
  56. package/dist/instrumentation.mjs +1 -1
  57. package/dist/{key-D_kagnFv.mjs → key-B7vuAYPG.mjs} +2 -2
  58. package/dist/{key-D_kagnFv.mjs.map → key-B7vuAYPG.mjs.map} +1 -1
  59. package/dist/{libsql-DFAoHXrI.mjs → libsql-DUO6vHad.mjs} +2 -2
  60. package/dist/{libsql-DFAoHXrI.mjs.map → libsql-DUO6vHad.mjs.map} +1 -1
  61. package/dist/libsql.d.mts +1 -1
  62. package/dist/libsql.mjs +1 -1
  63. package/dist/{memory-GTWgeDNY.mjs → memory-BApsTkt1.mjs} +2 -2
  64. package/dist/{memory-GTWgeDNY.mjs.map → memory-BApsTkt1.mjs.map} +1 -1
  65. package/dist/migrations/mysql.d.mts +4 -4
  66. package/dist/migrations/mysql.mjs +1 -1
  67. package/dist/migrations/postgres.d.mts +4 -4
  68. package/dist/migrations/postgres.mjs +1 -1
  69. package/dist/migrations/sqlite.d.mts +4 -4
  70. package/dist/migrations/sqlite.mjs +1 -1
  71. package/dist/migrations/storage/durable-object.mjs +1 -1
  72. package/dist/migrations/storage/fs.mjs +1 -1
  73. package/dist/migrations/storage/r2.mjs +1 -1
  74. package/dist/migrations/tenant.d.mts +2 -2
  75. package/dist/migrations/tenant.mjs +1 -1
  76. package/dist/migrations.d.mts +4 -4
  77. package/dist/migrations.mjs +1 -1
  78. package/dist/{mysql-xChEivOe.mjs → mysql-D1GlcktG.mjs} +2 -2
  79. package/dist/{mysql-xChEivOe.mjs.map → mysql-D1GlcktG.mjs.map} +1 -1
  80. package/dist/{mysql-adapter-C6c5govr.mjs → mysql-adapter-ClOoHKpn.mjs} +2 -2
  81. package/dist/{mysql-adapter-C6c5govr.mjs.map → mysql-adapter-ClOoHKpn.mjs.map} +1 -1
  82. package/dist/mysql2.d.mts +1 -1
  83. package/dist/mysql2.mjs +1 -1
  84. package/dist/neon-http.d.mts +1 -1
  85. package/dist/neon-http.mjs +1 -1
  86. package/dist/{object-store-D9mvOHP4.d.mts → object-store-BN64q8Zn.d.mts} +3 -3
  87. package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
  88. package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
  89. package/dist/permissions.d.mts +2 -2
  90. package/dist/permissions.mjs +1 -1
  91. package/dist/permissions.mjs.map +1 -1
  92. package/dist/pg.d.mts +1 -1
  93. package/dist/pg.mjs +1 -1
  94. package/dist/pglite.d.mts +1 -1
  95. package/dist/pglite.mjs +1 -1
  96. package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-CjvR0Ge2.mjs} +2 -2
  97. package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-CjvR0Ge2.mjs.map} +1 -1
  98. package/dist/planetscale.d.mts +1 -1
  99. package/dist/planetscale.mjs +1 -1
  100. package/dist/{planner-C1NzLBge.d.mts → planner-8smxUOt9.d.mts} +1 -1
  101. package/dist/{postgres-BqAxDWTQ.mjs → postgres-Be0jMJWI.mjs} +2 -2
  102. package/dist/{postgres-BqAxDWTQ.mjs.map → postgres-Be0jMJWI.mjs.map} +1 -1
  103. package/dist/{postgres-adapter-CxEit2-v.mjs → postgres-adapter-BoQ4RRwr.mjs} +2 -2
  104. package/dist/{postgres-adapter-CxEit2-v.mjs.map → postgres-adapter-BoQ4RRwr.mjs.map} +1 -1
  105. package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-C_Mt8lVC.mjs} +2 -2
  106. package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-C_Mt8lVC.mjs.map} +1 -1
  107. package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-CYu1dyI_.mjs} +1 -1
  108. package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-CYu1dyI_.mjs.map} +1 -1
  109. package/dist/postgres.d.mts +1 -1
  110. package/dist/postgres.mjs +1 -1
  111. package/dist/result-shape-DQc-tDJ5.mjs +2 -0
  112. package/dist/{result-shape-CDgX_vzn.mjs.map → result-shape-DQc-tDJ5.mjs.map} +1 -1
  113. package/dist/rows-JXjhWwyb.mjs +2 -0
  114. package/dist/rows-JXjhWwyb.mjs.map +1 -0
  115. package/dist/{scalar-S8yMvdmx.mjs → scalar-CqqZ6jWd.mjs} +2 -2
  116. package/dist/{scalar-S8yMvdmx.mjs.map → scalar-CqqZ6jWd.mjs.map} +1 -1
  117. package/dist/schema/json.d.mts +1 -1
  118. package/dist/schema/json.mjs +1 -1
  119. package/dist/{schema-9N9jQlVL.mjs → schema-Cv-hhpl5.mjs} +2 -2
  120. package/dist/{schema-9N9jQlVL.mjs.map → schema-Cv-hhpl5.mjs.map} +1 -1
  121. package/dist/{schema-introspection-CyXKReK1.mjs → schema-introspection-B2Rvqgut.mjs} +3 -3
  122. package/dist/{schema-introspection-CyXKReK1.mjs.map → schema-introspection-B2Rvqgut.mjs.map} +1 -1
  123. package/dist/schema.d.mts +1 -1
  124. package/dist/schema.mjs +1 -1
  125. package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-BxtETbG9.mjs} +1 -1
  126. package/dist/{select-assembly-CkGe2ABs.mjs.map → select-assembly-BxtETbG9.mjs.map} +1 -1
  127. package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
  128. package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
  129. package/dist/sha256-CEYo7k7R.mjs +2 -0
  130. package/dist/sha256-CEYo7k7R.mjs.map +1 -0
  131. package/dist/soft-delete.d.mts +1 -1
  132. package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
  133. package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
  134. package/dist/{sqlite-adapter-BXAJy3mI.mjs → sqlite-adapter-B_LNxPA0.mjs} +2 -2
  135. package/dist/{sqlite-adapter-BXAJy3mI.mjs.map → sqlite-adapter-B_LNxPA0.mjs.map} +1 -1
  136. package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-DIOll4P7.mjs} +1 -1
  137. package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-DIOll4P7.mjs.map} +1 -1
  138. package/dist/sqlite3.d.mts +1 -1
  139. package/dist/sqlite3.mjs +1 -1
  140. package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-mJt0RHHE.mjs} +1 -1
  141. package/dist/{standard-sql-CoGqv-iX.mjs.map → standard-sql-mJt0RHHE.mjs.map} +1 -1
  142. package/dist/{to-many-C1PuFIpf.mjs → to-many-BSipkSbK.mjs} +2 -2
  143. package/dist/{to-many-C1PuFIpf.mjs.map → to-many-BSipkSbK.mjs.map} +1 -1
  144. package/dist/{utils-CtFUE8UN.mjs → utils-DjXObbUK.mjs} +2 -2
  145. package/dist/{utils-CtFUE8UN.mjs.map → utils-DjXObbUK.mjs.map} +1 -1
  146. package/dist/v-CrJYqdzu.mjs +2 -0
  147. package/dist/v-CrJYqdzu.mjs.map +1 -0
  148. package/dist/validation.d.mts +1 -1
  149. package/dist/validation.mjs +1 -1
  150. package/dist/{validator-DgffZq9C.mjs → validator-BqzpyNmt.mjs} +2 -2
  151. package/dist/{validator-DgffZq9C.mjs.map → validator-BqzpyNmt.mjs.map} +1 -1
  152. package/dist/version-Dus3if78.mjs +2 -0
  153. package/dist/{version-CXuJzC-q.mjs.map → version-Dus3if78.mjs.map} +1 -1
  154. package/package.json +16 -15
  155. package/dist/chain-C7c1YTXD.mjs +0 -2
  156. package/dist/chain-C7c1YTXD.mjs.map +0 -1
  157. package/dist/client-_WKrPNmm.mjs +0 -2
  158. package/dist/client-_WKrPNmm.mjs.map +0 -1
  159. package/dist/controls-Da-efekX.mjs +0 -2
  160. package/dist/controls-Da-efekX.mjs.map +0 -1
  161. package/dist/every-1pKZteeB.mjs +0 -2
  162. package/dist/identity-oQvIe7u8.mjs +0 -2
  163. package/dist/identity-oQvIe7u8.mjs.map +0 -1
  164. package/dist/result-shape-CDgX_vzn.mjs +0 -2
  165. package/dist/v-CYTUI0H5.mjs +0 -2
  166. package/dist/v-CYTUI0H5.mjs.map +0 -1
  167. package/dist/version-CXuJzC-q.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-adapter-BXAJy3mI.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\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 // Use json() to ensure the aggregated value is treated as JSON, not string\n // Without json(), json_group_array produces [\"{...}\"] instead of [{...}]\n agg: (expr: Sql): Sql =>\n sql`COALESCE(json_group_array(json(${expr})), json_array())`,\n\n objectFromColumns: 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};\n\nconst SQLITE_RESULT: AdapterResultParser = {\n // SQLite has no exact decimal type: a decimal column IS its unscaled\n // integer coefficient, and every projection casts it to text before a\n // driver turns an int64 into a double. The result boundary cannot tell the\n // two vocabularies apart by inspection, so the promise is declared here.\n decimalRepresentation: \"coefficient\",\n\n // A decimal LIST is TEXT holding a JSON array of those same coefficients,\n // stated separately because the two facts are separate: a dialect can spell\n // its scalar decimals exactly and still have no exact decimal inside JSON.\n decimalListRepresentation: \"coefficient\",\n\n // The same reading the `dateTime` literal above lowers through, so a column\n // is read back in the vocabulary it was written in.\n dateTimeRepresentation: sqliteDateTimePhysicalForm,\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"sqlite\")?.representation ?? \"text\",\n\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n};\n\nconst SQLITE_IDENTIFIERS = createIdentifiers(quoteIdent);\n\nconst SQLITE_CLAUSES = createStandardClauses();\n\nconst SQLITE_FILTERS = createRelationFilters();\n\nconst SQLITE_SUBQUERIES = createSubqueries(quoteIdent);\n\nconst SQLITE_CTE = createCteBuilders(quoteIdent);\n\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 }: 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 }\n if (sharedRelationBodies) this.capabilities.sharesRelationBodies = true;\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":"qyBA0EA,MAAM,EAAa,GAAuB,IAAI,CASxC,EAA0C,CAC9C,UAAW,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACnD,WAAY,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACrD,CAMD,SAAS,uBAAuB,EAAyC,CACvE,IAAM,EAAY,EAA4B,EAAY,CAC1D,GAAI,EAAY,GAAI,OAAO,EACvB,OAAY,IAIhB,OAHmB,EAAY,WAAW,IAAI,CAC1C,EAAY,MAAM,EAAE,EAAI,sBACxB,GAAe,uBACC,EAAY,IAAA,GA4BlC,MAAM,EAA4BA,EAAI,IAAI,sBAAsB,CAqB1D,oBAAuB,GAC3BA,EAAI,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,EAAW,UAAW,GAAG,CAAC,GAAG,CAS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AC,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
+ {"version":3,"file":"sqlite-adapter-B_LNxPA0.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\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 // Use json() to ensure the aggregated value is treated as JSON, not string\n // Without json(), json_group_array produces [\"{...}\"] instead of [{...}]\n agg: (expr: Sql): Sql =>\n sql`COALESCE(json_group_array(json(${expr})), json_array())`,\n\n objectFromColumns: 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};\n\nconst SQLITE_RESULT: AdapterResultParser = {\n // SQLite has no exact decimal type: a decimal column IS its unscaled\n // integer coefficient, and every projection casts it to text before a\n // driver turns an int64 into a double. The result boundary cannot tell the\n // two vocabularies apart by inspection, so the promise is declared here.\n decimalRepresentation: \"coefficient\",\n\n // A decimal LIST is TEXT holding a JSON array of those same coefficients,\n // stated separately because the two facts are separate: a dialect can spell\n // its scalar decimals exactly and still have no exact decimal inside JSON.\n decimalListRepresentation: \"coefficient\",\n\n // The same reading the `dateTime` literal above lowers through, so a column\n // is read back in the vocabulary it was written in.\n dateTimeRepresentation: sqliteDateTimePhysicalForm,\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"sqlite\")?.representation ?? \"text\",\n\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n};\n\nconst SQLITE_IDENTIFIERS = createIdentifiers(quoteIdent);\n\nconst SQLITE_CLAUSES = createStandardClauses();\n\nconst SQLITE_FILTERS = createRelationFilters();\n\nconst SQLITE_SUBQUERIES = createSubqueries(quoteIdent);\n\nconst SQLITE_CTE = createCteBuilders(quoteIdent);\n\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 }: 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 }\n if (sharedRelationBodies) this.capabilities.sharesRelationBodies = true;\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":"qyBA0EA,MAAM,EAAa,GAAuB,IAAI,CASxC,EAA0C,CAC9C,UAAW,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACnD,WAAY,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACrD,CAMD,SAAS,uBAAuB,EAAyC,CACvE,IAAM,EAAY,EAA4B,EAAY,CAC1D,GAAI,EAAY,GAAI,OAAO,EACvB,OAAY,IAIhB,OAHmB,EAAY,WAAW,IAAI,CAC1C,EAAY,MAAM,EAAE,EAAI,sBACxB,GAAe,uBACC,EAAY,IAAA,GA4BlC,MAAM,EAA4BA,EAAI,IAAI,sBAAsB,CAqB1D,oBAAuB,GAC3BA,EAAI,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,EAAW,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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
1
  import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./error-mapping-C9WgitPi.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-D_cypcyW.mjs.map
2
+ //# sourceMappingURL=sqlite-utils-DIOll4P7.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-utils-D_cypcyW.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
+ {"version":3,"file":"sqlite-utils-DIOll4P7.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-VsM29vYN.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-D4O0Twvs.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-qfEejeOX.mjs";import{r as n}from"./validation-BamBwne9.mjs";import{a as r,i,n as a,r as o}from"./client-_WKrPNmm.mjs";import{c as s,n as c,r as l,t as u}from"./driver-B9fIori_.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-D_cypcyW.mjs";import{t as y}from"./sqlite-adapter-BXAJy3mI.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{i as t}from"./bind-parameter-capacity-qfEejeOX.mjs";import{r as n}from"./validation-BamBwne9.mjs";import{a as r,i,n as a,r as o}from"./client-BCgMXn6N.mjs";import{c as s,n as c,r as l,t as u}from"./driver-Ddt147dK.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-DIOll4P7.mjs";import{t as y}from"./sqlite-adapter-B_LNxPA0.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
@@ -3,4 +3,4 @@ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t,t as n}from"./sql-Bhxq9ar
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-CoGqv-iX.mjs.map
6
+ //# sourceMappingURL=standard-sql-mJt0RHHE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"standard-sql-CoGqv-iX.mjs","names":["sql"],"sources":["../src/sql/identifiers.ts","../src/adapters/shared/standard-sql.ts"],"sourcesContent":["/**\n * Identifier text primitives.\n *\n * Quoting one name for a dialect, and composing a namespace-qualified object\n * name, are string concerns with no `Sql` involvement: runtime adapters wrap the\n * result in `Sql`, migration drivers splice it into DDL text. Both pass their\n * own quoter — the two differ in escape semantics and null handling — so what is\n * shared here is the composition rule alone, and it has one owner.\n */\n\n/** Quote a single identifier for the dialect: `\"name\"` or `` `name` ``. */\nexport type IdentifierQuoter = (name: string) => string;\n\n/** Build an identifier quoter that doubles embedded quote characters to prevent SQL injection. */\nexport const createIdentifierQuoter =\n (quoteChar: '\"' | \"`\"): IdentifierQuoter =>\n (name: string): string => {\n const escaped =\n name.indexOf(quoteChar) === -1\n ? name\n : name.replaceAll(quoteChar, quoteChar + quoteChar);\n return quoteChar + escaped + quoteChar;\n };\n\n/**\n * The one qualification rule. A present namespace contributes a quoted prefix;\n * an absent one contributes nothing, which is what unbound MySQL and every\n * SQLite adapter mean.\n */\nconst qualifiedPrefix = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string\n): string => `${quoteIdentifier(namespace)}.`;\n\n/**\n * Compose one namespace-qualified object name. The namespace must already be\n * normalized: this primitive validates nothing, holds nothing, and returns text\n * for exactly one object.\n */\nexport const renderQualifiedIdentifier = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined,\n object: string\n): string =>\n namespace === undefined\n ? quoteIdentifier(object)\n : qualifiedPrefix(quoteIdentifier, namespace) + quoteIdentifier(object);\n\n/**\n * Bind one namespace so its prefix is quoted once per adapter rather than once\n * per rendered statement. The returned function renders exactly what\n * `renderQualifiedIdentifier` would for the same namespace.\n */\nexport const createQualifiedIdentifierRenderer = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined\n): IdentifierQuoter => {\n if (namespace === undefined) {\n return quoteIdentifier;\n }\n const prefix = qualifiedPrefix(quoteIdentifier, namespace);\n return (object: string): string => prefix + quoteIdentifier(object);\n};\n","import { Sql, sql } from \"@sql\";\nimport {\n createQualifiedIdentifierRenderer,\n type IdentifierQuoter,\n} from \"../../sql/identifiers\";\nimport type { CastType, DatabaseAdapter } from \"../database-adapter\";\n\ntype StandardLiterals = Pick<\n DatabaseAdapter[\"literals\"],\n \"value\" | \"null\" | \"list\"\n>;\n\ntype ComparisonOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"eq\" | \"neq\" | \"lt\" | \"lte\" | \"gt\" | \"gte\"\n>;\n\ntype NullOperators = Pick<DatabaseAdapter[\"operators\"], \"isNull\" | \"isNotNull\">;\n\ntype RangeOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"between\" | \"notBetween\"\n>;\n\ntype ExistenceOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"exists\" | \"notExists\"\n>;\n\ntype DirectionOrderBy = Pick<DatabaseAdapter[\"orderBy\"], \"asc\" | \"desc\">;\n\ntype NumericSetOperations = Pick<\n DatabaseAdapter[\"set\"],\n \"assign\" | \"increment\" | \"decrement\"\n>;\n\ntype MutationCommands = Pick<DatabaseAdapter[\"mutations\"], \"update\" | \"delete\">;\n\nexport const createRawSql = (): DatabaseAdapter[\"raw\"] => {\n return (sqlString: string): Sql => sql.raw(sqlString);\n};\n\n/**\n * JSON-serialize a value for dialects that store lists/JSON as JSON text\n * (MySQL, SQLite). BigInt has no JSON representation, so it serializes as a\n * string; the result parser converts it back via the scalar's bigint type.\n */\nexport const stringifyJson = (value: unknown): string =>\n JSON.stringify(value, (_key, v) =>\n typeof v === \"bigint\" ? v.toString() : v\n );\n\nconst JSON_PATH_ARRAY_INDEX = /^\\d+$/;\n\n/**\n * Build a MySQL/SQLite JSONPath string from path segments: '$' plus `[N]`\n * for integer segments (array indices) and `.\"seg\"` for object keys.\n * Keys are JSON-string-escaped so quotes/dots/backslashes in a segment\n * cannot alter the path structure; the result is bound as a parameter.\n */\nexport const buildJsonPath = (path: string[]): string => {\n let jsonPath = \"$\";\n for (const segment of path) {\n jsonPath += JSON_PATH_ARRAY_INDEX.test(segment)\n ? `[${segment}]`\n : `.${JSON.stringify(segment)}`;\n }\n return jsonPath;\n};\n\nexport const createStandardLiterals = (): StandardLiterals => ({\n value: (v: unknown): Sql => sql`${v}`,\n null: (): Sql => sql.raw(\"NULL\"),\n list: (values: Sql[]): Sql => {\n if (values.length === 0) return sql.raw(\"()\");\n return sql`(${sql.join(values, \", \")})`;\n },\n});\n\nexport const createComparisonOperators = (): ComparisonOperators => ({\n eq: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n neq: (left: Sql, right: Sql): Sql => sql`${left} <> ${right}`,\n lt: (left: Sql, right: Sql): Sql => sql`${left} < ${right}`,\n lte: (left: Sql, right: Sql): Sql => sql`${left} <= ${right}`,\n gt: (left: Sql, right: Sql): Sql => sql`${left} > ${right}`,\n gte: (left: Sql, right: Sql): Sql => sql`${left} >= ${right}`,\n});\n\nexport const createNullOperators = (): NullOperators => ({\n isNull: (expr: Sql): Sql => sql`${expr} IS NULL`,\n isNotNull: (expr: Sql): Sql => sql`${expr} IS NOT NULL`,\n});\n\nexport const createRangeOperators = (): RangeOperators => ({\n between: (column: Sql, min: Sql, max: Sql): Sql =>\n sql`${column} BETWEEN ${min} AND ${max}`,\n notBetween: (column: Sql, min: Sql, max: Sql): Sql =>\n sql`${column} NOT BETWEEN ${min} AND ${max}`,\n});\n\nexport const createExistenceOperators = (): ExistenceOperators => ({\n exists: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n notExists: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n});\n\ntype StandardAggregates = Omit<\n DatabaseAdapter[\"aggregates\"],\n \"decimalAvg\" | \"decimalSumOperandPrecision\"\n>;\n\n/**\n * The aggregate functions every dialect spells identically. `decimalAvg` is\n * deliberately absent: an exact decimal average is derived from `SUM` and\n * `COUNT` in the column's own physical domain, which is the one thing the three\n * dialects do not agree on, so each adapter states it.\n * `decimalSumOperandPrecision` is absent because each dialect also owns exact\n * admission of an operand compared with a widened sum.\n *\n * `infinity` is the dialect's infinite double literal; MySQL has none.\n */\nexport const createAggregateFunctions = (\n infinity?: string\n): StandardAggregates => ({\n count: (expr?: Sql): Sql =>\n expr ? sql`COUNT(${expr})` : sql.raw(\"COUNT(*)\"),\n countDistinct: (expr: Sql): Sql => sql`COUNT(DISTINCT ${expr})`,\n sum: (expr: Sql): Sql => sql`SUM(${expr})`,\n numberSum: (expr: Sql) => {\n const high = sql`SUM(CASE WHEN ABS(${expr}) >= 1e-288 THEN ${expr} / 4294967296.0 / 4294967296.0 END)`;\n const low = sql`SUM(CASE WHEN ABS(${expr}) < 1e-288 THEN ${expr} END)`;\n // The reader's join in SQL: scaling `high` back by 2^64 is exact below\n // 2^960 and leaves the double range from there, where this multiplies\n // nothing — PostgreSQL and MySQL raise on an overflowing product. Without\n // an infinite double (MySQL) the overflow clamps to the largest finite\n // one, which a `having` operand of exactly that value cannot tell apart,\n // and `high` then sorts an infinite sum past a clamped one.\n const bound = sql.raw(infinity ?? \"1.7976931348623157e308\");\n const value = sql`CASE WHEN ${high} IS NULL THEN ${low} WHEN ABS(${high}) < 9.7453140114e288 THEN ${high} * 4294967296.0 * 4294967296.0 + COALESCE(${low}, 0) WHEN ${high} > 0 THEN ${bound} ELSE -${bound} END`;\n return {\n parts: [high, low] as const,\n value,\n order: infinity ? [value] : [value, high],\n };\n },\n avg: (expr: Sql): Sql => sql`AVG(${expr})`,\n min: (expr: Sql): Sql => sql`MIN(${expr})`,\n max: (expr: Sql): Sql => sql`MAX(${expr})`,\n});\n\n/** The widened precision carried by one trusted coefficient spelling. */\nexport function decimalCoefficientPrecision(coefficient: string): number {\n return coefficient.startsWith(\"-\")\n ? coefficient.length - 1\n : coefficient.length;\n}\n\n/** Exact-decimal aggregate operand admission for precision-bounded dialects. */\nexport function createDecimalSumOperandPrecision(\n maxPrecision: number\n): (coefficient: string) => number | undefined {\n return (coefficient) => {\n const precision = decimalCoefficientPrecision(coefficient);\n return precision <= maxPrecision ? precision : undefined;\n };\n}\n\nexport const createDirectionOrderBy = (): DirectionOrderBy => ({\n asc: (column: Sql): Sql => sql`${column} ASC`,\n desc: (column: Sql): Sql => sql`${column} DESC`,\n});\n\nconst directionKeyword = (direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\" ? sql.raw(\"DESC\") : sql.raw(\"ASC\");\n\n/**\n * NULLS FIRST/LAST emulation for dialects without native support\n * (MySQL, SQLite): prepend an IS NULL sort key. IS NULL yields 1 for\n * NULL rows, so DESC puts them first and ASC puts them last.\n */\nexport const createEmulatedNullsOrderBy = (): Pick<\n DatabaseAdapter[\"orderBy\"],\n \"nullsFirst\" | \"nullsLast\"\n> => ({\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n sql`(${column} IS NULL) DESC, ${column} ${directionKeyword(direction)}`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n sql`(${column} IS NULL) ASC, ${column} ${directionKeyword(direction)}`,\n});\n\nexport const createStandardClauses = (): DatabaseAdapter[\"clauses\"] => ({\n select: (columns: Sql): Sql => sql`SELECT ${columns}`,\n selectDistinct: (columns: Sql): Sql => sql`SELECT DISTINCT ${columns}`,\n from: (table: Sql): Sql => sql`FROM ${table}`,\n where: (condition: Sql): Sql => sql`WHERE ${condition}`,\n orderBy: (orders: Sql): Sql => sql`ORDER BY ${orders}`,\n limit: (count: Sql): Sql => sql`LIMIT ${count}`,\n offset: (count: Sql): Sql => sql`OFFSET ${count}`,\n groupBy: (columns: Sql): Sql => sql`GROUP BY ${columns}`,\n having: (condition: Sql): Sql => sql`HAVING ${condition}`,\n});\n\n/**\n * The native arithmetic every dialect shares.\n *\n * `increment`/`decrement` are complete here for EVERY scalar including decimal:\n * addition of two values already in the column's domain — logical decimals on\n * PostgreSQL/MySQL, unscaled coefficients at the same scale on SQLite — creates\n * no digit beyond that domain and therefore never rounds.\n *\n * `multiply` and `divide` do create such digits, so each adapter overrides them\n * to route a decimal target through the shared half-even rule.\n */\nexport const createNumericSetOperations = (): NumericSetOperations => ({\n assign: (column: Sql, value: Sql): Sql => sql`${column} = ${value}`,\n increment: (column: Sql, by: Sql): Sql => sql`${column} = ${column} + ${by}`,\n decrement: (column: Sql, by: Sql): Sql => sql`${column} = ${column} - ${by}`,\n});\n\nexport const createRelationFilters = (): DatabaseAdapter[\"filters\"] => ({\n some: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n every: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n none: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n is: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n isNot: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n});\n\nexport const createMutationCommands = (): MutationCommands => ({\n update: (table: Sql, sets: Sql, where?: Sql): Sql => {\n if (where) {\n return sql`UPDATE ${table} SET ${sets} WHERE ${where}`;\n }\n return sql`UPDATE ${table} SET ${sets}`;\n },\n delete: (table: Sql, where?: Sql): Sql => {\n if (where) {\n return sql`DELETE FROM ${table} WHERE ${where}`;\n }\n return sql`DELETE FROM ${table}`;\n },\n});\n\ntype TypedRows = DatabaseAdapter[\"setOperations\"][\"typedRows\"];\n\n/** One row's values, in order: `(a, b)`. */\nexport const rowValues = (row: readonly Sql[]): Sql =>\n sql`(${sql.join(row, \", \")})`;\n\n/**\n * `typedRows`' default form: the empty typed read, then one `UNION ALL\n * SELECT` per row, each typed against the arms before it.\n */\nconst unionTypedRows =\n (quoteIdent: IdentifierQuoter): TypedRows =>\n (typed, rows, alias) =>\n sql`(${sql.join(\n [typed.head, ...rows.map((row) => sql`SELECT ${sql.join(row, \", \")}`)],\n \" UNION ALL \"\n )}) AS ${sql.raw(quoteIdent(alias))}`;\n\nexport const createSetOperations = (\n quoteIdent: IdentifierQuoter,\n typedRows: TypedRows = unionTypedRows(quoteIdent)\n): DatabaseAdapter[\"setOperations\"] => ({\n union: (...queries: Sql[]): Sql => sql.join(queries, \" UNION \"),\n unionAll: (...queries: Sql[]): Sql => sql.join(queries, \" UNION ALL \"),\n intersect: (...queries: Sql[]): Sql => sql.join(queries, \" INTERSECT \"),\n except: (left: Sql, right: Sql): Sql => sql`${left} EXCEPT ${right}`,\n typedRows,\n});\n\n// ============================================================\n// Dialect-parameterized factories: identical grammar across\n// adapters, differing only in the identifier quote character.\n// ============================================================\n\n/**\n * `namespace` is the adapter's prevalidated database namespace, or `undefined`\n * for the unqualified dialects. It is quoted once here, at adapter\n * construction — `table()` runs once per persistent table per compiled\n * statement and must not re-quote it.\n */\nexport const createIdentifiers = (\n quoteIdent: IdentifierQuoter,\n namespace?: string\n): DatabaseAdapter[\"identifiers\"] => {\n const qualify = createQualifiedIdentifierRenderer(quoteIdent, namespace);\n return {\n escape: (name: string): Sql => sql.raw(quoteIdent(name)),\n\n column: (alias: string, field: string): Sql => {\n const identifier = alias\n ? `${quoteIdent(alias)}.${quoteIdent(field)}`\n : quoteIdent(field);\n return sql.raw(identifier);\n },\n\n table: (tableName: string, alias?: string): Sql => {\n const qualified = qualify(tableName);\n return sql.raw(\n alias === undefined ? qualified : `${qualified} AS ${quoteIdent(alias)}`\n );\n },\n\n aliased: (expression: Sql, alias: string): Sql =>\n new Sql([\"\", ` AS ${quoteIdent(alias)}`], [expression]),\n };\n};\n\nexport const createSubqueries = (\n quoteIdent: IdentifierQuoter\n): DatabaseAdapter[\"subqueries\"] => ({\n scalar: (query: Sql): Sql => sql`(${query})`,\n\n correlate: (query: Sql, alias: string): Sql =>\n sql`(${query}) AS ${sql.raw(quoteIdent(alias))}`,\n\n existsCheck: (from: Sql, where: Sql): Sql =>\n sql`SELECT 1 FROM ${from} WHERE ${where}`,\n\n isolated: (condition: Sql): Sql => condition,\n});\n\nexport const createCteBuilders = (\n quoteIdent: IdentifierQuoter\n): DatabaseAdapter[\"cte\"] => ({\n with: (definitions: { name: string; query: Sql }[]): Sql => {\n const defs = definitions.map(\n ({ name, query }) => sql`${sql.raw(quoteIdent(name))} AS (${query})`\n );\n return sql`WITH ${sql.join(defs, \", \")}`;\n },\n\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union: \"all\" | \"distinct\" = \"all\"\n ): Sql => {\n const unionKeyword =\n union === \"all\" ? sql.raw(\"UNION ALL\") : sql.raw(\"UNION\");\n return sql`WITH RECURSIVE ${sql.raw(quoteIdent(name))} AS (\n ${anchor}\n ${unionKeyword}\n ${recursive}\n )`;\n },\n});\n\nexport const createInsertStatement =\n (quoteIdent: IdentifierQuoter): DatabaseAdapter[\"mutations\"][\"insert\"] =>\n (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ): Sql => {\n const cols = columns.map((c) => sql.raw(quoteIdent(c)));\n const body = Array.isArray(source)\n ? sql`VALUES ${sql.join(\n source.map((row) => sql`(${sql.join(row, \", \")})`),\n \", \"\n )}`\n : source.select;\n const prefixPart = prefix ? sql`${prefix} ` : sql``;\n return sql`INSERT ${prefixPart}INTO ${table} (${sql.join(\n cols,\n \", \"\n )}) ${body}`;\n };\n\n/**\n * Standard ON CONFLICT grammar shared by PostgreSQL and SQLite.\n * MySQL's ON DUPLICATE KEY UPDATE is a different grammar with different\n * semantics — it stays in the MySQL adapter.\n */\nexport const createOnConflictBuilders = (): Pick<\n DatabaseAdapter[\"mutations\"],\n \"onConflict\" | \"onConflictUpdate\" | \"skipDuplicates\"\n> => ({\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql): Sql => {\n if (target) {\n if (targetWhere) {\n // ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n return sql`ON CONFLICT (${target}) WHERE ${targetWhere} DO ${action}`;\n }\n return sql`ON CONFLICT (${target}) DO ${action}`;\n }\n return sql`ON CONFLICT DO ${action}`;\n },\n\n onConflictUpdate: (sets: Sql, setWhere?: Sql): Sql => {\n if (setWhere) {\n // UPDATE SET x = y WHERE <setWhere>\n return sql`UPDATE SET ${sets} WHERE ${setWhere}`;\n }\n return sql`UPDATE SET ${sets}`;\n },\n\n // The UNTARGETED skip, and the only caller left is top-level `createMany`,\n // whose `skipDuplicates: true` means \"any unique constraint\". Junction\n // membership inserts want the opposite — only an exact repeat of the complete\n // membership key — and reach `onConflict` above with that key as the target.\n skipDuplicates: () => ({\n prefix: sql``,\n suffix: sql`ON CONFLICT DO NOTHING`,\n }),\n});\n\nexport const createMembershipOperators = (): Pick<\n DatabaseAdapter[\"operators\"],\n \"in\" | \"notIn\"\n> => ({\n in: (column: Sql, values: Sql): Sql => sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql => sql`${column} NOT IN ${values}`,\n});\n\n/**\n * AND/OR/NOT with vacuous-case literals: the dialect's TRUE for an empty\n * AND and FALSE for an empty OR (pass the adapter's literals.true/false).\n */\nexport const createLogicalOperators = (\n vacuousTrue: () => Sql,\n vacuousFalse: () => Sql\n): Pick<DatabaseAdapter[\"operators\"], \"and\" | \"or\" | \"not\"> => ({\n and: (...conditions: Sql[]): Sql => {\n if (conditions.length === 0) return vacuousTrue();\n if (conditions.length === 1) return conditions[0]!;\n return sql`(${sql.join(conditions, \" AND \")})`;\n },\n\n or: (...conditions: Sql[]): Sql => {\n if (conditions.length === 0) return vacuousFalse();\n if (conditions.length === 1) return conditions[0]!;\n return sql`(${sql.join(conditions, \" OR \")})`;\n },\n\n not: (condition: Sql): Sql => sql`NOT (${condition})`,\n});\n\nexport const createCommonExpressions = (): Pick<\n DatabaseAdapter[\"expressions\"],\n | \"caseWhen\"\n | \"add\"\n | \"subtract\"\n | \"multiply\"\n | \"divide\"\n | \"upper\"\n | \"lower\"\n | \"coalesce\"\n> => ({\n caseWhen: (branches, otherwise): Sql =>\n branches.length === 0\n ? otherwise\n : sql`CASE ${sql.join(\n branches.map(\n (branch) => sql`WHEN ${branch.when} THEN ${branch.then}`\n ),\n \" \"\n )} ELSE ${otherwise} END`,\n add: (left: Sql, right: Sql): Sql => sql`(${left} + ${right})`,\n subtract: (left: Sql, right: Sql): Sql => sql`(${left} - ${right})`,\n multiply: (left: Sql, right: Sql): Sql => sql`(${left} * ${right})`,\n divide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n upper: (expr: Sql): Sql => sql`UPPER(${expr})`,\n lower: (expr: Sql): Sql => sql`LOWER(${expr})`,\n coalesce: (...exprs: Sql[]): Sql => sql`COALESCE(${sql.join(exprs, \", \")})`,\n});\n\nexport const createCastExpression =\n (typeMap: Record<CastType, string>): DatabaseAdapter[\"expressions\"][\"cast\"] =>\n (expr: Sql, type: CastType): Sql =>\n sql`CAST(${expr} AS ${sql.raw(typeMap[type])})`;\n\nexport const createCoreJoins = (): Pick<\n DatabaseAdapter[\"joins\"],\n \"inner\" | \"left\" | \"right\" | \"cross\"\n> => ({\n inner: (table: Sql, condition: Sql): Sql =>\n sql`INNER JOIN ${table} ON ${condition}`,\n\n left: (table: Sql, condition: Sql): Sql =>\n sql`LEFT JOIN ${table} ON ${condition}`,\n\n right: (table: Sql, condition: Sql): Sql =>\n sql`RIGHT JOIN ${table} ON ${condition}`,\n\n cross: (table: Sql): Sql => sql`CROSS JOIN ${table}`,\n});\n\nexport const createLateralJoins = (\n quoteIdent: IdentifierQuoter\n): Pick<DatabaseAdapter[\"joins\"], \"lateral\" | \"lateralLeft\"> => ({\n lateral: (subquery: Sql, alias: string): Sql =>\n sql`JOIN LATERAL (${subquery}) AS ${sql.raw(quoteIdent(alias))} ON TRUE`,\n\n lateralLeft: (subquery: Sql, alias: string): Sql =>\n sql`LEFT JOIN LATERAL (${subquery}) AS ${sql.raw(quoteIdent(alias))} ON TRUE`,\n});\n\n/**\n * Escape a user value so a SQL `LIKE` pattern matches it literally.\n *\n * `%`, `_` and the escape character itself become escaped; every other\n * character is left alone. The caller appends its own wildcard and must emit\n * a matching `ESCAPE` clause — backslash is only the escape character because\n * every `ESCAPE` clause in this codebase spells backslash.\n */\nexport const escapeLikeLiteral = (value: string): string =>\n value.replace(/[\\\\%_]/g, (char) => `\\\\${char}`);\n\n/**\n * Escape a user value so a SQLite `GLOB` pattern matches it literally.\n *\n * GLOB has no `ESCAPE` clause, so a metacharacter is quoted by wrapping it in\n * a one-character class: `*` becomes `[*]`. Only `*`, `?` and `[` need it —\n * a `]` outside a class is already literal in SQLite's GLOB, and backslash is\n * not a GLOB metacharacter at all.\n */\nexport const escapeGlobLiteral = (value: string): string =>\n value.replace(/[*?[]/g, (char) => `[${char}]`);\n"],"mappings":"uFAcA,MAAa,uBACV,GACA,GAKQ,GAHL,EAAK,QAAQ,EAAU,GAAK,GACxB,EACA,EAAK,WAAW,EAAW,EAAY,EAAU,EAC1B,EAQ3B,iBACJ,EACA,IACW,GAAG,EAAgB,EAAU,CAAC,GAO9B,2BACX,EACA,EACA,IAEA,IAAc,IAAA,GACV,EAAgB,EAAO,CACvB,gBAAgB,EAAiB,EAAU,CAAG,EAAgB,EAAO,CAO9D,mCACX,EACA,IACqB,CACrB,GAAI,IAAc,IAAA,GAChB,OAAO,EAET,IAAM,EAAS,gBAAgB,EAAiB,EAAU,CAC1D,MAAQ,IAA2B,EAAS,EAAgB,EAAO,ECvBxD,iBACH,GAA2BA,EAAI,IAAI,EAAU,CAQ1C,cAAiB,GAC5B,KAAK,UAAU,GAAQ,EAAM,IAC3B,OAAO,GAAM,SAAW,EAAE,UAAU,CAAG,EACxC,CAEG,EAAwB,QAQjB,cAAiB,GAA2B,CACvD,IAAI,EAAW,IACf,IAAK,IAAM,KA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AAW,IAAoB,CAAG,IAAI,EAAK,KAAK,EAAM,GACjE,UAAW,EAAW,IAAoB,CAAG,IAAI,EAAK,KAAK,EAAM,GACjE,QAAS,EAAW,IAAoB,CAAG,IAAI,EAAK,KAAK,EAAM,GAC/D,MAAQ,GAAmB,CAAG,SAAS,EAAK,GAC5C,MAAQ,GAAmB,CAAG,SAAS,EAAK,GAC5C,UAAW,GAAG,IAAsB,CAAG,YAAYA,EAAI,KAAK,EAAO,KAAK,CAAC,GAC1E,EAEY,qBACV,IACA,EAAW,IACV,CAAG,QAAQ,EAAK,MAAMA,EAAI,IAAI,EAAQ,GAAM,CAAC,GAEpC,qBAGP,CACJ,OAAQ,EAAY,IAClB,CAAG,cAAc,EAAM,MAAM,IAE/B,MAAO,EAAY,IACjB,CAAG,aAAa,EAAM,MAAM,IAE9B,OAAQ,EAAY,IAClB,CAAG,cAAc,EAAM,MAAM,IAE/B,MAAQ,GAAoB,CAAG,cAAc,IAC9C,EAEY,mBACX,IAC+D,CAC/D,SAAU,EAAe,IACvB,CAAG,iBAAiB,EAAS,OAAOA,EAAI,IAAI,EAAW,EAAM,CAAC,CAAC,UAEjE,aAAc,EAAe,IAC3B,CAAG,sBAAsB,EAAS,OAAOA,EAAI,IAAI,EAAW,EAAM,CAAC,CAAC,UACvE,EAUY,kBAAqB,GAChC,EAAM,QAAQ,UAAY,GAAS,KAAK,IAAO,CAUpC,kBAAqB,GAChC,EAAM,QAAQ,SAAW,GAAS,IAAI,EAAK,GAAG"}
1
+ {"version":3,"file":"standard-sql-mJt0RHHE.mjs","names":["sql"],"sources":["../src/sql/identifiers.ts","../src/adapters/shared/standard-sql.ts"],"sourcesContent":["/**\n * Identifier text primitives.\n *\n * Quoting one name for a dialect, and composing a namespace-qualified object\n * name, are string concerns with no `Sql` involvement: runtime adapters wrap the\n * result in `Sql`, migration drivers splice it into DDL text. Both pass their\n * own quoter — the two differ in escape semantics and null handling — so what is\n * shared here is the composition rule alone, and it has one owner.\n */\n\n/** Quote a single identifier for the dialect: `\"name\"` or `` `name` ``. */\nexport type IdentifierQuoter = (name: string) => string;\n\n/** Build an identifier quoter that doubles embedded quote characters to prevent SQL injection. */\nexport const createIdentifierQuoter =\n (quoteChar: '\"' | \"`\"): IdentifierQuoter =>\n (name: string): string => {\n const escaped =\n name.indexOf(quoteChar) === -1\n ? name\n : name.replaceAll(quoteChar, quoteChar + quoteChar);\n return quoteChar + escaped + quoteChar;\n };\n\n/**\n * The one qualification rule. A present namespace contributes a quoted prefix;\n * an absent one contributes nothing, which is what unbound MySQL and every\n * SQLite adapter mean.\n */\nconst qualifiedPrefix = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string\n): string => `${quoteIdentifier(namespace)}.`;\n\n/**\n * Compose one namespace-qualified object name. The namespace must already be\n * normalized: this primitive validates nothing, holds nothing, and returns text\n * for exactly one object.\n */\nexport const renderQualifiedIdentifier = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined,\n object: string\n): string =>\n namespace === undefined\n ? quoteIdentifier(object)\n : qualifiedPrefix(quoteIdentifier, namespace) + quoteIdentifier(object);\n\n/**\n * Bind one namespace so its prefix is quoted once per adapter rather than once\n * per rendered statement. The returned function renders exactly what\n * `renderQualifiedIdentifier` would for the same namespace.\n */\nexport const createQualifiedIdentifierRenderer = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined\n): IdentifierQuoter => {\n if (namespace === undefined) {\n return quoteIdentifier;\n }\n const prefix = qualifiedPrefix(quoteIdentifier, namespace);\n return (object: string): string => prefix + quoteIdentifier(object);\n};\n","import { Sql, sql } from \"@sql\";\nimport {\n createQualifiedIdentifierRenderer,\n type IdentifierQuoter,\n} from \"../../sql/identifiers\";\nimport type { CastType, DatabaseAdapter } from \"../database-adapter\";\n\ntype StandardLiterals = Pick<\n DatabaseAdapter[\"literals\"],\n \"value\" | \"null\" | \"list\"\n>;\n\ntype ComparisonOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"eq\" | \"neq\" | \"lt\" | \"lte\" | \"gt\" | \"gte\"\n>;\n\ntype NullOperators = Pick<DatabaseAdapter[\"operators\"], \"isNull\" | \"isNotNull\">;\n\ntype RangeOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"between\" | \"notBetween\"\n>;\n\ntype ExistenceOperators = Pick<\n DatabaseAdapter[\"operators\"],\n \"exists\" | \"notExists\"\n>;\n\ntype DirectionOrderBy = Pick<DatabaseAdapter[\"orderBy\"], \"asc\" | \"desc\">;\n\ntype NumericSetOperations = Pick<\n DatabaseAdapter[\"set\"],\n \"assign\" | \"increment\" | \"decrement\"\n>;\n\ntype MutationCommands = Pick<DatabaseAdapter[\"mutations\"], \"update\" | \"delete\">;\n\nexport const createRawSql = (): DatabaseAdapter[\"raw\"] => {\n return (sqlString: string): Sql => sql.raw(sqlString);\n};\n\n/**\n * JSON-serialize a value for dialects that store lists/JSON as JSON text\n * (MySQL, SQLite). BigInt has no JSON representation, so it serializes as a\n * string; the result parser converts it back via the scalar's bigint type.\n */\nexport const stringifyJson = (value: unknown): string =>\n JSON.stringify(value, (_key, v) =>\n typeof v === \"bigint\" ? v.toString() : v\n );\n\nconst JSON_PATH_ARRAY_INDEX = /^\\d+$/;\n\n/**\n * Build a MySQL/SQLite JSONPath string from path segments: '$' plus `[N]`\n * for integer segments (array indices) and `.\"seg\"` for object keys.\n * Keys are JSON-string-escaped so quotes/dots/backslashes in a segment\n * cannot alter the path structure; the result is bound as a parameter.\n */\nexport const buildJsonPath = (path: string[]): string => {\n let jsonPath = \"$\";\n for (const segment of path) {\n jsonPath += JSON_PATH_ARRAY_INDEX.test(segment)\n ? `[${segment}]`\n : `.${JSON.stringify(segment)}`;\n }\n return jsonPath;\n};\n\nexport const createStandardLiterals = (): StandardLiterals => ({\n value: (v: unknown): Sql => sql`${v}`,\n null: (): Sql => sql.raw(\"NULL\"),\n list: (values: Sql[]): Sql => {\n if (values.length === 0) return sql.raw(\"()\");\n return sql`(${sql.join(values, \", \")})`;\n },\n});\n\nexport const createComparisonOperators = (): ComparisonOperators => ({\n eq: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n neq: (left: Sql, right: Sql): Sql => sql`${left} <> ${right}`,\n lt: (left: Sql, right: Sql): Sql => sql`${left} < ${right}`,\n lte: (left: Sql, right: Sql): Sql => sql`${left} <= ${right}`,\n gt: (left: Sql, right: Sql): Sql => sql`${left} > ${right}`,\n gte: (left: Sql, right: Sql): Sql => sql`${left} >= ${right}`,\n});\n\nexport const createNullOperators = (): NullOperators => ({\n isNull: (expr: Sql): Sql => sql`${expr} IS NULL`,\n isNotNull: (expr: Sql): Sql => sql`${expr} IS NOT NULL`,\n});\n\nexport const createRangeOperators = (): RangeOperators => ({\n between: (column: Sql, min: Sql, max: Sql): Sql =>\n sql`${column} BETWEEN ${min} AND ${max}`,\n notBetween: (column: Sql, min: Sql, max: Sql): Sql =>\n sql`${column} NOT BETWEEN ${min} AND ${max}`,\n});\n\nexport const createExistenceOperators = (): ExistenceOperators => ({\n exists: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n notExists: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n});\n\ntype StandardAggregates = Omit<\n DatabaseAdapter[\"aggregates\"],\n \"decimalAvg\" | \"decimalSumOperandPrecision\"\n>;\n\n/**\n * The aggregate functions every dialect spells identically. `decimalAvg` is\n * deliberately absent: an exact decimal average is derived from `SUM` and\n * `COUNT` in the column's own physical domain, which is the one thing the three\n * dialects do not agree on, so each adapter states it.\n * `decimalSumOperandPrecision` is absent because each dialect also owns exact\n * admission of an operand compared with a widened sum.\n *\n * `infinity` is the dialect's infinite double literal; MySQL has none.\n */\nexport const createAggregateFunctions = (\n infinity?: string\n): StandardAggregates => ({\n count: (expr?: Sql): Sql =>\n expr ? sql`COUNT(${expr})` : sql.raw(\"COUNT(*)\"),\n countDistinct: (expr: Sql): Sql => sql`COUNT(DISTINCT ${expr})`,\n sum: (expr: Sql): Sql => sql`SUM(${expr})`,\n numberSum: (expr: Sql) => {\n const high = sql`SUM(CASE WHEN ABS(${expr}) >= 1e-288 THEN ${expr} / 4294967296.0 / 4294967296.0 END)`;\n const low = sql`SUM(CASE WHEN ABS(${expr}) < 1e-288 THEN ${expr} END)`;\n // The reader's join in SQL: scaling `high` back by 2^64 is exact below\n // 2^960 and leaves the double range from there, where this multiplies\n // nothing — PostgreSQL and MySQL raise on an overflowing product. Without\n // an infinite double (MySQL) the overflow clamps to the largest finite\n // one, which a `having` operand of exactly that value cannot tell apart,\n // and `high` then sorts an infinite sum past a clamped one.\n const bound = sql.raw(infinity ?? \"1.7976931348623157e308\");\n const value = sql`CASE WHEN ${high} IS NULL THEN ${low} WHEN ABS(${high}) < 9.7453140114e288 THEN ${high} * 4294967296.0 * 4294967296.0 + COALESCE(${low}, 0) WHEN ${high} > 0 THEN ${bound} ELSE -${bound} END`;\n return {\n parts: [high, low] as const,\n value,\n order: infinity ? [value] : [value, high],\n };\n },\n avg: (expr: Sql): Sql => sql`AVG(${expr})`,\n min: (expr: Sql): Sql => sql`MIN(${expr})`,\n max: (expr: Sql): Sql => sql`MAX(${expr})`,\n});\n\n/** The widened precision carried by one trusted coefficient spelling. */\nexport function decimalCoefficientPrecision(coefficient: string): number {\n return coefficient.startsWith(\"-\")\n ? coefficient.length - 1\n : coefficient.length;\n}\n\n/** Exact-decimal aggregate operand admission for precision-bounded dialects. */\nexport function createDecimalSumOperandPrecision(\n maxPrecision: number\n): (coefficient: string) => number | undefined {\n return (coefficient) => {\n const precision = decimalCoefficientPrecision(coefficient);\n return precision <= maxPrecision ? precision : undefined;\n };\n}\n\nexport const createDirectionOrderBy = (): DirectionOrderBy => ({\n asc: (column: Sql): Sql => sql`${column} ASC`,\n desc: (column: Sql): Sql => sql`${column} DESC`,\n});\n\nconst directionKeyword = (direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\" ? sql.raw(\"DESC\") : sql.raw(\"ASC\");\n\n/**\n * NULLS FIRST/LAST emulation for dialects without native support\n * (MySQL, SQLite): prepend an IS NULL sort key. IS NULL yields 1 for\n * NULL rows, so DESC puts them first and ASC puts them last.\n */\nexport const createEmulatedNullsOrderBy = (): Pick<\n DatabaseAdapter[\"orderBy\"],\n \"nullsFirst\" | \"nullsLast\"\n> => ({\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n sql`(${column} IS NULL) DESC, ${column} ${directionKeyword(direction)}`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n sql`(${column} IS NULL) ASC, ${column} ${directionKeyword(direction)}`,\n});\n\nexport const createStandardClauses = (): DatabaseAdapter[\"clauses\"] => ({\n select: (columns: Sql): Sql => sql`SELECT ${columns}`,\n selectDistinct: (columns: Sql): Sql => sql`SELECT DISTINCT ${columns}`,\n from: (table: Sql): Sql => sql`FROM ${table}`,\n where: (condition: Sql): Sql => sql`WHERE ${condition}`,\n orderBy: (orders: Sql): Sql => sql`ORDER BY ${orders}`,\n limit: (count: Sql): Sql => sql`LIMIT ${count}`,\n offset: (count: Sql): Sql => sql`OFFSET ${count}`,\n groupBy: (columns: Sql): Sql => sql`GROUP BY ${columns}`,\n having: (condition: Sql): Sql => sql`HAVING ${condition}`,\n});\n\n/**\n * The native arithmetic every dialect shares.\n *\n * `increment`/`decrement` are complete here for EVERY scalar including decimal:\n * addition of two values already in the column's domain — logical decimals on\n * PostgreSQL/MySQL, unscaled coefficients at the same scale on SQLite — creates\n * no digit beyond that domain and therefore never rounds.\n *\n * `multiply` and `divide` do create such digits, so each adapter overrides them\n * to route a decimal target through the shared half-even rule.\n */\nexport const createNumericSetOperations = (): NumericSetOperations => ({\n assign: (column: Sql, value: Sql): Sql => sql`${column} = ${value}`,\n increment: (column: Sql, by: Sql): Sql => sql`${column} = ${column} + ${by}`,\n decrement: (column: Sql, by: Sql): Sql => sql`${column} = ${column} - ${by}`,\n});\n\nexport const createRelationFilters = (): DatabaseAdapter[\"filters\"] => ({\n some: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n every: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n none: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n is: (subquery: Sql): Sql => sql`EXISTS (${subquery})`,\n isNot: (subquery: Sql): Sql => sql`NOT EXISTS (${subquery})`,\n});\n\nexport const createMutationCommands = (): MutationCommands => ({\n update: (table: Sql, sets: Sql, where?: Sql): Sql => {\n if (where) {\n return sql`UPDATE ${table} SET ${sets} WHERE ${where}`;\n }\n return sql`UPDATE ${table} SET ${sets}`;\n },\n delete: (table: Sql, where?: Sql): Sql => {\n if (where) {\n return sql`DELETE FROM ${table} WHERE ${where}`;\n }\n return sql`DELETE FROM ${table}`;\n },\n});\n\ntype TypedRows = DatabaseAdapter[\"setOperations\"][\"typedRows\"];\n\n/** One row's values, in order: `(a, b)`. */\nexport const rowValues = (row: readonly Sql[]): Sql =>\n sql`(${sql.join(row, \", \")})`;\n\n/**\n * `typedRows`' default form: the empty typed read, then one `UNION ALL\n * SELECT` per row, each typed against the arms before it.\n */\nconst unionTypedRows =\n (quoteIdent: IdentifierQuoter): TypedRows =>\n (typed, rows, alias) =>\n sql`(${sql.join(\n [typed.head, ...rows.map((row) => sql`SELECT ${sql.join(row, \", \")}`)],\n \" UNION ALL \"\n )}) AS ${sql.raw(quoteIdent(alias))}`;\n\nexport const createSetOperations = (\n quoteIdent: IdentifierQuoter,\n typedRows: TypedRows = unionTypedRows(quoteIdent)\n): DatabaseAdapter[\"setOperations\"] => ({\n union: (...queries: Sql[]): Sql => sql.join(queries, \" UNION \"),\n unionAll: (...queries: Sql[]): Sql => sql.join(queries, \" UNION ALL \"),\n intersect: (...queries: Sql[]): Sql => sql.join(queries, \" INTERSECT \"),\n except: (left: Sql, right: Sql): Sql => sql`${left} EXCEPT ${right}`,\n typedRows,\n});\n\n// ============================================================\n// Dialect-parameterized factories: identical grammar across\n// adapters, differing only in the identifier quote character.\n// ============================================================\n\n/**\n * `namespace` is the adapter's prevalidated database namespace, or `undefined`\n * for the unqualified dialects. It is quoted once here, at adapter\n * construction — `table()` runs once per persistent table per compiled\n * statement and must not re-quote it.\n */\nexport const createIdentifiers = (\n quoteIdent: IdentifierQuoter,\n namespace?: string\n): DatabaseAdapter[\"identifiers\"] => {\n const qualify = createQualifiedIdentifierRenderer(quoteIdent, namespace);\n return {\n escape: (name: string): Sql => sql.raw(quoteIdent(name)),\n\n column: (alias: string, field: string): Sql => {\n const identifier = alias\n ? `${quoteIdent(alias)}.${quoteIdent(field)}`\n : quoteIdent(field);\n return sql.raw(identifier);\n },\n\n table: (tableName: string, alias?: string): Sql => {\n const qualified = qualify(tableName);\n return sql.raw(\n alias === undefined ? qualified : `${qualified} AS ${quoteIdent(alias)}`\n );\n },\n\n aliased: (expression: Sql, alias: string): Sql =>\n new Sql([\"\", ` AS ${quoteIdent(alias)}`], [expression]),\n };\n};\n\nexport const createSubqueries = (\n quoteIdent: IdentifierQuoter\n): DatabaseAdapter[\"subqueries\"] => ({\n scalar: (query: Sql): Sql => sql`(${query})`,\n\n correlate: (query: Sql, alias: string): Sql =>\n sql`(${query}) AS ${sql.raw(quoteIdent(alias))}`,\n\n existsCheck: (from: Sql, where: Sql): Sql =>\n sql`SELECT 1 FROM ${from} WHERE ${where}`,\n\n isolated: (condition: Sql): Sql => condition,\n});\n\nexport const createCteBuilders = (\n quoteIdent: IdentifierQuoter\n): DatabaseAdapter[\"cte\"] => ({\n with: (definitions: { name: string; query: Sql }[]): Sql => {\n const defs = definitions.map(\n ({ name, query }) => sql`${sql.raw(quoteIdent(name))} AS (${query})`\n );\n return sql`WITH ${sql.join(defs, \", \")}`;\n },\n\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union: \"all\" | \"distinct\" = \"all\"\n ): Sql => {\n const unionKeyword =\n union === \"all\" ? sql.raw(\"UNION ALL\") : sql.raw(\"UNION\");\n return sql`WITH RECURSIVE ${sql.raw(quoteIdent(name))} AS (\n ${anchor}\n ${unionKeyword}\n ${recursive}\n )`;\n },\n});\n\nexport const createInsertStatement =\n (quoteIdent: IdentifierQuoter): DatabaseAdapter[\"mutations\"][\"insert\"] =>\n (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ): Sql => {\n const cols = columns.map((c) => sql.raw(quoteIdent(c)));\n const body = Array.isArray(source)\n ? sql`VALUES ${sql.join(\n source.map((row) => sql`(${sql.join(row, \", \")})`),\n \", \"\n )}`\n : source.select;\n const prefixPart = prefix ? sql`${prefix} ` : sql``;\n return sql`INSERT ${prefixPart}INTO ${table} (${sql.join(\n cols,\n \", \"\n )}) ${body}`;\n };\n\n/**\n * Standard ON CONFLICT grammar shared by PostgreSQL and SQLite.\n * MySQL's ON DUPLICATE KEY UPDATE is a different grammar with different\n * semantics — it stays in the MySQL adapter.\n */\nexport const createOnConflictBuilders = (): Pick<\n DatabaseAdapter[\"mutations\"],\n \"onConflict\" | \"onConflictUpdate\" | \"skipDuplicates\"\n> => ({\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql): Sql => {\n if (target) {\n if (targetWhere) {\n // ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n return sql`ON CONFLICT (${target}) WHERE ${targetWhere} DO ${action}`;\n }\n return sql`ON CONFLICT (${target}) DO ${action}`;\n }\n return sql`ON CONFLICT DO ${action}`;\n },\n\n onConflictUpdate: (sets: Sql, setWhere?: Sql): Sql => {\n if (setWhere) {\n // UPDATE SET x = y WHERE <setWhere>\n return sql`UPDATE SET ${sets} WHERE ${setWhere}`;\n }\n return sql`UPDATE SET ${sets}`;\n },\n\n // The UNTARGETED skip, and the only caller left is top-level `createMany`,\n // whose `skipDuplicates: true` means \"any unique constraint\". Junction\n // membership inserts want the opposite — only an exact repeat of the complete\n // membership key — and reach `onConflict` above with that key as the target.\n skipDuplicates: () => ({\n prefix: sql``,\n suffix: sql`ON CONFLICT DO NOTHING`,\n }),\n});\n\nexport const createMembershipOperators = (): Pick<\n DatabaseAdapter[\"operators\"],\n \"in\" | \"notIn\"\n> => ({\n in: (column: Sql, values: Sql): Sql => sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql => sql`${column} NOT IN ${values}`,\n});\n\n/**\n * AND/OR/NOT with vacuous-case literals: the dialect's TRUE for an empty\n * AND and FALSE for an empty OR (pass the adapter's literals.true/false).\n */\nexport const createLogicalOperators = (\n vacuousTrue: () => Sql,\n vacuousFalse: () => Sql\n): Pick<DatabaseAdapter[\"operators\"], \"and\" | \"or\" | \"not\"> => ({\n and: (...conditions: Sql[]): Sql => {\n if (conditions.length === 0) return vacuousTrue();\n if (conditions.length === 1) return conditions[0]!;\n return sql`(${sql.join(conditions, \" AND \")})`;\n },\n\n or: (...conditions: Sql[]): Sql => {\n if (conditions.length === 0) return vacuousFalse();\n if (conditions.length === 1) return conditions[0]!;\n return sql`(${sql.join(conditions, \" OR \")})`;\n },\n\n not: (condition: Sql): Sql => sql`NOT (${condition})`,\n});\n\nexport const createCommonExpressions = (): Pick<\n DatabaseAdapter[\"expressions\"],\n | \"caseWhen\"\n | \"add\"\n | \"subtract\"\n | \"multiply\"\n | \"divide\"\n | \"upper\"\n | \"lower\"\n | \"coalesce\"\n> => ({\n caseWhen: (branches, otherwise): Sql =>\n branches.length === 0\n ? otherwise\n : sql`CASE ${sql.join(\n branches.map(\n (branch) => sql`WHEN ${branch.when} THEN ${branch.then}`\n ),\n \" \"\n )} ELSE ${otherwise} END`,\n add: (left: Sql, right: Sql): Sql => sql`(${left} + ${right})`,\n subtract: (left: Sql, right: Sql): Sql => sql`(${left} - ${right})`,\n multiply: (left: Sql, right: Sql): Sql => sql`(${left} * ${right})`,\n divide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n upper: (expr: Sql): Sql => sql`UPPER(${expr})`,\n lower: (expr: Sql): Sql => sql`LOWER(${expr})`,\n coalesce: (...exprs: Sql[]): Sql => sql`COALESCE(${sql.join(exprs, \", \")})`,\n});\n\nexport const createCastExpression =\n (typeMap: Record<CastType, string>): DatabaseAdapter[\"expressions\"][\"cast\"] =>\n (expr: Sql, type: CastType): Sql =>\n sql`CAST(${expr} AS ${sql.raw(typeMap[type])})`;\n\nexport const createCoreJoins = (): Pick<\n DatabaseAdapter[\"joins\"],\n \"inner\" | \"left\" | \"right\" | \"cross\"\n> => ({\n inner: (table: Sql, condition: Sql): Sql =>\n sql`INNER JOIN ${table} ON ${condition}`,\n\n left: (table: Sql, condition: Sql): Sql =>\n sql`LEFT JOIN ${table} ON ${condition}`,\n\n right: (table: Sql, condition: Sql): Sql =>\n sql`RIGHT JOIN ${table} ON ${condition}`,\n\n cross: (table: Sql): Sql => sql`CROSS JOIN ${table}`,\n});\n\nexport const createLateralJoins = (\n quoteIdent: IdentifierQuoter\n): Pick<DatabaseAdapter[\"joins\"], \"lateral\" | \"lateralLeft\"> => ({\n lateral: (subquery: Sql, alias: string): Sql =>\n sql`JOIN LATERAL (${subquery}) AS ${sql.raw(quoteIdent(alias))} ON TRUE`,\n\n lateralLeft: (subquery: Sql, alias: string): Sql =>\n sql`LEFT JOIN LATERAL (${subquery}) AS ${sql.raw(quoteIdent(alias))} ON TRUE`,\n});\n\n/**\n * Escape a user value so a SQL `LIKE` pattern matches it literally.\n *\n * `%`, `_` and the escape character itself become escaped; every other\n * character is left alone. The caller appends its own wildcard and must emit\n * a matching `ESCAPE` clause — backslash is only the escape character because\n * every `ESCAPE` clause in this codebase spells backslash.\n */\nexport const escapeLikeLiteral = (value: string): string =>\n value.replace(/[\\\\%_]/g, (char) => `\\\\${char}`);\n\n/**\n * Escape a user value so a SQLite `GLOB` pattern matches it literally.\n *\n * GLOB has no `ESCAPE` clause, so a metacharacter is quoted by wrapping it in\n * a one-character class: `*` becomes `[*]`. Only `*`, `?` and `[` need it —\n * a `]` outside a class is already literal in SQLite's GLOB, and backslash is\n * not a GLOB metacharacter at all.\n */\nexport const escapeGlobLiteral = (value: string): string =>\n value.replace(/[*?[]/g, (char) => `[${char}]`);\n"],"mappings":"uFAcA,MAAa,uBACV,GACA,GAKQ,GAHL,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