@voltro/database 0.85.0 → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/CHANGELOG.md +5987 -0
  2. package/THIRD-PARTY-NOTICES.md +5 -257
  3. package/dist/actorSnapshot.js +24 -0
  4. package/dist/arrayCodec.js +32 -0
  5. package/dist/branchExecute.js +92 -0
  6. package/dist/branching.js +106 -0
  7. package/dist/bulkInsertLimits.js +25 -0
  8. package/dist/cdcOffsetsTables.js +19 -0
  9. package/dist/changeEvent.js +41 -0
  10. package/dist/changeIdentity.js +65 -0
  11. package/dist/changeListenerCeiling.js +6 -0
  12. package/dist/columnReference.js +17 -0
  13. package/dist/columns.js +326 -0
  14. package/dist/committedChanges.js +12 -0
  15. package/dist/connectionIdentity.js +36 -0
  16. package/dist/coreTables.js +16 -0
  17. package/dist/coreTablesRegistry.js +10 -0
  18. package/dist/dataTransfers.js +23 -0
  19. package/dist/dbCause.js +222 -0
  20. package/dist/dbMetrics.js +65 -0
  21. package/dist/decimalComparison.js +27 -0
  22. package/dist/derivedRowId.js +5 -0
  23. package/dist/dialect.js +13 -0
  24. package/dist/enumRenames.js +14 -0
  25. package/dist/expiresMixin.js +10 -0
  26. package/dist/fieldEncryption.js +121 -0
  27. package/dist/frameworkTables.js +143 -0
  28. package/dist/ginIndex.js +10 -0
  29. package/dist/hybridSearch.js +32 -0
  30. package/dist/idGenerator.js +57 -0
  31. package/dist/identifierLimits.js +32 -0
  32. package/dist/index.d.ts +166 -22
  33. package/dist/index.js +82 -2183
  34. package/dist/indexAudit.js +61 -0
  35. package/dist/indexStorage.js +58 -0
  36. package/dist/joinCompiler.js +160 -0
  37. package/dist/jsonEagerCompiler.js +436 -0
  38. package/dist/jsonPatch.js +78 -0
  39. package/dist/jsonPatchAssignments.js +13 -0
  40. package/dist/jsonPath.js +31 -0
  41. package/dist/localFirstMixin.js +12 -0
  42. package/dist/migrate.js +644 -0
  43. package/dist/migration.js +18 -0
  44. package/dist/migrations/appliedAtValue.js +8 -0
  45. package/dist/migrations/applier.js +1100 -0
  46. package/dist/migrations/boot.js +196 -0
  47. package/dist/migrations/branchRehearsal.js +122 -0
  48. package/dist/migrations/columnEquivalence.js +85 -0
  49. package/dist/migrations/ddlError.js +63 -0
  50. package/dist/migrations/ddlStatements.js +9 -0
  51. package/dist/migrations/declaredSchema.js +162 -0
  52. package/dist/migrations/deployLedger.js +19 -0
  53. package/dist/migrations/fileBased.js +57 -0
  54. package/dist/migrations/fileContext.js +482 -0
  55. package/dist/migrations/fileDiscovery.js +332 -0
  56. package/dist/migrations/fileSkipProbes.js +117 -0
  57. package/dist/migrations/fingerprint.js +46 -0
  58. package/dist/migrations/fkCycles.js +13 -0
  59. package/dist/migrations/frameworkLiveTables.js +25 -0
  60. package/dist/migrations/idempotentDdl.js +37 -0
  61. package/dist/migrations/indexPredicate.js +50 -0
  62. package/dist/migrations/introspect.js +801 -0
  63. package/dist/migrations/ledgerRows.js +4 -0
  64. package/dist/migrations/lock.js +91 -0
  65. package/dist/migrations/migrationTableExists.js +9 -0
  66. package/dist/migrations/mssqlColumnDependencies.js +76 -0
  67. package/dist/migrations/mysqlEngine.js +11 -0
  68. package/dist/migrations/namespaceCharset.js +51 -0
  69. package/dist/migrations/planner.js +785 -0
  70. package/dist/migrations/postgresEnumCheck.js +22 -0
  71. package/dist/migrations/reactiveTriggerDrift.js +58 -0
  72. package/dist/migrations/reactiveTriggerName.js +7 -0
  73. package/dist/migrations/renameMssqlCheck.js +21 -0
  74. package/dist/migrations/restoreSnapshots.js +206 -0
  75. package/dist/migrations/resumeLedger.js +86 -0
  76. package/dist/migrations/rollingDeploy.js +106 -0
  77. package/dist/migrations/schemaOwner.js +46 -0
  78. package/dist/migrations/schemaOwnerTable.js +4 -0
  79. package/dist/migrations/softDropSnapshot.js +20 -0
  80. package/dist/migrations/sqlLimit.js +8 -0
  81. package/dist/migrations/sqliteCatalogName.js +13 -0
  82. package/dist/migrations/sqliteConstraintIdentity.js +97 -0
  83. package/dist/migrations/sqliteDecimalBoot.js +22 -0
  84. package/dist/migrations/sqliteDecimalPublication.js +257 -0
  85. package/dist/migrations/sqliteDecimalReview.js +30 -0
  86. package/dist/migrations/sqliteDecimalReviewStore.js +188 -0
  87. package/dist/migrations/sqliteDecimalReviewWitness.js +38 -0
  88. package/dist/migrations/sqliteDecimalSource.js +69 -0
  89. package/dist/migrations/sqliteDecimalStage.js +135 -0
  90. package/dist/migrations/sqliteForeignKeys.js +38 -0
  91. package/dist/migrations/sqliteMigrationBatch.js +37 -0
  92. package/dist/migrations/sqliteRetainedSource.js +106 -0
  93. package/dist/migrations/sqliteRowIdentity.js +63 -0
  94. package/dist/migrations/sqliteSchemaEpoch.js +12 -0
  95. package/dist/migrations/sqliteSnapshotGuard.js +10 -0
  96. package/dist/migrations/sqliteTableContents.js +34 -0
  97. package/dist/migrations/sqliteTableCopy.js +25 -0
  98. package/dist/migrations/sqliteTableSchema.js +19 -0
  99. package/dist/migrations/sqliteWitnessProtection.js +8 -0
  100. package/dist/migrations/squash.js +81 -0
  101. package/dist/migrations/storeCharset.js +66 -0
  102. package/dist/migrations/transactionCause.js +10 -0
  103. package/dist/migrations/undeclaredCharset.js +40 -0
  104. package/dist/migrations/uniqueActiveLowering.js +39 -0
  105. package/dist/mixins.js +22 -0
  106. package/dist/mssqlDecimalDistinct.js +51 -0
  107. package/dist/mssqlJsonValueCheck.js +42 -0
  108. package/dist/mssqlTextStorage.js +9 -0
  109. package/dist/namespace.js +21 -0
  110. package/dist/{wire-CG2j7J3f.js → optimisticVersion.js} +2 -2
  111. package/dist/pendingAttribution.js +79 -0
  112. package/dist/pluginRef.js +17 -0
  113. package/dist/predicate.js +273 -0
  114. package/dist/predicateCoercion.js +13 -0
  115. package/dist/projectedColumn.js +37 -0
  116. package/dist/queryBuilder.js +388 -0
  117. package/dist/rawSql.js +8 -0
  118. package/dist/relations.js +69 -0
  119. package/dist/relationsRegistry.js +38 -0
  120. package/dist/replaceInProgress.js +53 -0
  121. package/dist/requiredColumns.js +26 -0
  122. package/dist/residency.js +52 -0
  123. package/dist/retention.js +62 -0
  124. package/dist/rowDecoder.js +173 -0
  125. package/dist/rowKey.js +8 -0
  126. package/dist/rowSchema.js +31 -0
  127. package/dist/scopeKey.js +8 -0
  128. package/dist/seed.js +33 -0
  129. package/dist/snowflake.js +26 -0
  130. package/dist/sql.d.ts +2792 -3773
  131. package/dist/sql.js +42 -6905
  132. package/dist/sqlCompiler.js +360 -0
  133. package/dist/sqlError.js +8 -0
  134. package/dist/sqlMutation.js +55 -0
  135. package/dist/sqlPoolCapacity.js +12 -0
  136. package/dist/sqliteDecimal.js +22 -0
  137. package/dist/sqliteDecimalAggregateSql.js +61 -0
  138. package/dist/sqliteDecimalColumnSql.js +108 -0
  139. package/dist/sqliteDecimalConversion.js +15 -0
  140. package/dist/sqliteDecimalCte.js +154 -0
  141. package/dist/sqliteDecimalEncodeSql.js +32 -0
  142. package/dist/sqliteDecimalOutputs.js +74 -0
  143. package/dist/sqliteDecimalPredicate.js +66 -0
  144. package/dist/sqliteDecimalQuery.js +183 -0
  145. package/dist/sqliteDecimalQueryPlan.js +37 -0
  146. package/dist/sqliteDecimalResultSql.js +44 -0
  147. package/dist/sqliteDecimalRowQuery.js +63 -0
  148. package/dist/sqliteDecimalSetQuery.js +50 -0
  149. package/dist/sqliteDecimalSource.js +63 -0
  150. package/dist/sqliteDecimalStorage.js +29 -0
  151. package/dist/sqliteDecimalSubquery.js +19 -0
  152. package/dist/sqliteDecimalWindowQuery.js +196 -0
  153. package/dist/sqliteValueCoercion.js +4 -0
  154. package/dist/stampId.js +21 -0
  155. package/dist/storeErrors.js +9 -0
  156. package/dist/storeRefusal.js +20 -0
  157. package/dist/stream.js +36 -0
  158. package/dist/subjectGraph.js +175 -0
  159. package/dist/table.js +394 -0
  160. package/dist/tableRegistry.js +16 -0
  161. package/dist/tenantSelection.js +27 -0
  162. package/dist/transactionOutcome.js +100 -0
  163. package/dist/transientContention.js +36 -0
  164. package/dist/typeId.js +51 -0
  165. package/dist/typedStore.js +16 -0
  166. package/dist/upsertUpdate.js +20 -0
  167. package/dist/vectorEmbedding.js +31 -0
  168. package/dist/view.js +39 -0
  169. package/dist/wire.js +6 -2
  170. package/dist/writeAttribution.js +16 -0
  171. package/dist/writeRecorder.js +38 -0
  172. package/package.json +3 -4
  173. package/dist/replaceInProgress-DC88Pdiy.js +0 -3735
@@ -1,3735 +0,0 @@
1
- import { Cause as e, Effect as t, Exit as n, Schema as r, Struct as i } from "effect";
2
- import { typeid as a } from "typeid-js";
3
- import { ulid as o } from "ulidx";
4
- import { SqlError as s, UnknownError as c } from "effect/sql/SqlError";
5
- //#region src/columns.ts
6
- var l = (e) => {
7
- let t = [];
8
- for (let [n, r] of Object.entries(e.fields)) r.serverOnly === !0 && t.push(n);
9
- return t;
10
- }, u = (e) => {
11
- let t = [];
12
- for (let [n, r] of Object.entries(e.fields)) r.crdtManaged === !0 && t.push(n);
13
- return t;
14
- }, d = (e) => {
15
- let t = [];
16
- for (let [n, r] of Object.entries(e.fields)) {
17
- let e = r.readableBy;
18
- e !== void 0 && e.length > 0 && t.push({
19
- column: n,
20
- scopes: e
21
- });
22
- }
23
- return t;
24
- }, f = (e) => {
25
- let t = [];
26
- for (let [n, r] of Object.entries(e.fields)) r.crdtManaged === !0 && t.push(n);
27
- return t;
28
- }, p = class e {
29
- definition;
30
- constructor(e) {
31
- this.definition = e;
32
- }
33
- rejectIfRaw(e) {
34
- if (this.definition.type === "raw") throw Error(`raw(...) column rejects .${e}() — the DDL fragment is the single source of truth for type/nullability/default. Encode ${e === "nullable" ? "NULL" : e === "unique" ? "UNIQUE" : "DEFAULT"} directly in the raw fragment instead.`);
35
- }
36
- nullable() {
37
- return this.rejectIfRaw("nullable"), new e({
38
- ...this.definition,
39
- nullable: !0
40
- });
41
- }
42
- externalId() {
43
- if (this.rejectIfRaw("externalId"), this.definition.type === "reference" || this.definition.type === "id") throw Error(`.externalId() requires a scalar non-primary-key column (got ${this.definition.type}) — \`reference()\` is local by definition and \`id()\` identifies this row.`);
44
- return new e({
45
- ...this.definition,
46
- externalId: !0
47
- });
48
- }
49
- encrypted() {
50
- return this.rejectIfRaw("encrypted"), new e({
51
- ...this.definition,
52
- encrypted: !0
53
- });
54
- }
55
- serverOnly() {
56
- if (this.rejectIfRaw("serverOnly"), this.definition.crdtManaged === !0) throw Error("serverOnly() on a CRDT column (crdtText()/crdtDoc()) is a contradiction: clients write CRDT updates and must read the merged state back. Remove serverOnly(), or use a plain bytes() column if only the server touches it.");
57
- return new e({
58
- ...this.definition,
59
- serverOnly: !0
60
- });
61
- }
62
- readableBy(...t) {
63
- if (this.rejectIfRaw("readableBy"), t.length === 0) throw Error(".readableBy() needs at least one scope — a column readable by nobody is .serverOnly(). List the scopes that may read it, e.g. .readableBy('billing:read').");
64
- if (t.find((e) => typeof e != "string" || e.trim() === "") !== void 0) throw Error(`.readableBy(...) rejects a blank scope — every scope must be a non-empty string (a blank scope can never be held, so it would hide the column from everyone). Got: ${JSON.stringify(t)}.`);
65
- let n = [...new Set(t)];
66
- return new e({
67
- ...this.definition,
68
- readableBy: n
69
- });
70
- }
71
- version() {
72
- if (this.rejectIfRaw("version"), this.definition.type !== "integer") throw Error(`.version() requires an integer() column (got ${this.definition.type}). The store increments it, so it has to be a number — and a timestamp version reintroduces exactly the clock problem optimistic locking exists to avoid: two writes in the same millisecond are indistinguishable, and replica clocks disagree.`);
73
- return new e({
74
- ...this.definition,
75
- versionColumn: !0,
76
- hasDefault: !0,
77
- defaultValue: 1
78
- });
79
- }
80
- sensitive(t) {
81
- return new e({
82
- ...this.definition,
83
- sensitive: { class: t }
84
- });
85
- }
86
- safe() {
87
- return new e({
88
- ...this.definition,
89
- safe: !0
90
- });
91
- }
92
- unique(t) {
93
- return this.rejectIfRaw("unique"), t?.dedup === void 0 ? new e({
94
- ...this.definition,
95
- unique: !0
96
- }) : new e({
97
- ...this.definition,
98
- unique: !0,
99
- uniqueSpec: { dedup: t.dedup }
100
- });
101
- }
102
- default(t) {
103
- return this.rejectIfRaw("default"), typeof t == "function" ? new e({
104
- ...this.definition,
105
- hasDefault: !0,
106
- defaultFactory: t
107
- }) : new e({
108
- ...this.definition,
109
- hasDefault: !0,
110
- defaultValue: t
111
- });
112
- }
113
- computed(t) {
114
- return new e({
115
- ...this.definition,
116
- computed: t
117
- });
118
- }
119
- onUpdate(t) {
120
- return new e({
121
- ...this.definition,
122
- onUpdate: t
123
- });
124
- }
125
- generatedAs(t, n) {
126
- return new e({
127
- ...this.definition,
128
- generatedAs: {
129
- expr: t,
130
- stored: n?.stored ?? !1
131
- }
132
- });
133
- }
134
- backfill(t, n) {
135
- let r = typeof t == "function" ? {
136
- kind: "js",
137
- fn: t,
138
- ...n?.batchSize === void 0 ? {} : { batchSize: n.batchSize },
139
- ...n?.sleepMs === void 0 ? {} : { sleepMs: n.sleepMs }
140
- } : {
141
- kind: "sql",
142
- sql: t,
143
- ...n?.batchSize === void 0 ? {} : { batchSize: n.batchSize },
144
- ...n?.sleepMs === void 0 ? {} : { sleepMs: n.sleepMs }
145
- };
146
- return new e({
147
- ...this.definition,
148
- backfill: r
149
- });
150
- }
151
- renamedFrom(t) {
152
- return new e({
153
- ...this.definition,
154
- renamedFrom: t
155
- });
156
- }
157
- narrowedFrom(t, n) {
158
- let r = n?.using === void 0 ? { from: t } : {
159
- from: t,
160
- using: n.using
161
- };
162
- return new e({
163
- ...this.definition,
164
- narrowedFrom: r
165
- });
166
- }
167
- oneOf(t) {
168
- return new e({
169
- ...this.definition,
170
- oneOf: t
171
- });
172
- }
173
- maxLength(t) {
174
- return new e({
175
- ...this.definition,
176
- maxLength: t
177
- });
178
- }
179
- check(t) {
180
- let n = this.definition.checks ? [...this.definition.checks, t] : [t];
181
- return new e({
182
- ...this.definition,
183
- checks: n
184
- });
185
- }
186
- __definition() {
187
- return this.definition;
188
- }
189
- }, m = (e) => new p({
190
- type: e,
191
- nullable: !1,
192
- unique: !1,
193
- hasDefault: !1
194
- });
195
- function h(e) {
196
- return new p({
197
- type: "id",
198
- nullable: !1,
199
- unique: !0,
200
- hasDefault: !1,
201
- idSchemeInput: e
202
- });
203
- }
204
- var g = () => m("text"), _ = () => m("integer"), v = () => m("real"), y = (e, t = 0) => {
205
- if (!Number.isInteger(e) || e <= 0) throw Error(`decimal(${String(e)}, ${String(t)}): precision must be a positive integer (the total number of significant digits, e.g. decimal(12, 2)).`);
206
- if (!Number.isInteger(t) || t < 0 || t > e) throw Error(`decimal(${String(e)}, ${String(t)}): scale must be an integer between 0 and precision (${e}).`);
207
- return new p({
208
- type: "decimal",
209
- nullable: !1,
210
- unique: !1,
211
- hasDefault: !1,
212
- precision: e,
213
- scale: t,
214
- sqliteDecimalEncoding: "sortable-v1"
215
- });
216
- }, b = y, x = () => m("bigint"), S = (e, t) => {
217
- if (t.length === 0) throw Error(`dbEnum('${e}', []): enum must have at least one value`);
218
- return {
219
- name: e,
220
- values: t,
221
- column: () => new p({
222
- type: "enum",
223
- nullable: !1,
224
- unique: !1,
225
- hasDefault: !1,
226
- enumName: e,
227
- enumValues: t
228
- })
229
- };
230
- }, C = () => m("boolean"), w = () => m("timestamp"), T = () => m("date"), E = () => m("json"), D = () => m("bytes"), O = () => new p({
231
- type: "bytes",
232
- nullable: !0,
233
- unique: !1,
234
- hasDefault: !1,
235
- crdtManaged: !0
236
- }), k = () => new p({
237
- type: "bytes",
238
- nullable: !0,
239
- unique: !1,
240
- hasDefault: !1,
241
- crdtManaged: !0
242
- }), ee = () => new p({
243
- type: "bytes",
244
- nullable: !0,
245
- unique: !1,
246
- hasDefault: !1,
247
- crdtSealed: !0
248
- }), A = () => new p({
249
- type: "bytes",
250
- nullable: !0,
251
- unique: !1,
252
- hasDefault: !1,
253
- crdtManaged: !0
254
- }), j = () => {
255
- throw Error("selfReference(): the target is resolved by table() — a column built with selfReference() must be declared inside a table({ … }) literal, not read before the table exists");
256
- };
257
- function M(e) {
258
- return N(j, e);
259
- }
260
- function N(e, t) {
261
- return new p({
262
- type: "reference",
263
- nullable: !1,
264
- unique: !1,
265
- hasDefault: !1,
266
- references: e,
267
- referenceStorage: t?.storage ?? "text",
268
- referenceColumn: t?.column ?? "id",
269
- onDelete: t?.onDelete ?? "restrict",
270
- refOnUpdate: t?.onUpdate ?? "noAction",
271
- ...t?.onSoftDelete === void 0 ? {} : { refOnSoftDelete: t.onSoftDelete },
272
- fkAutoIndex: t?.index ?? !0,
273
- ...t?.orphanPolicy ? { orphanPolicy: t.orphanPolicy } : {}
274
- });
275
- }
276
- var P = () => new p({
277
- type: "text",
278
- nullable: !0,
279
- unique: !1,
280
- hasDefault: !1,
281
- dropped: !0
282
- }), F = (e) => Object.keys(e.fields).filter((t) => e.fields[t]?.dropped !== !0), te = (e, t) => {
283
- if (!Number.isInteger(e) || e <= 0) throw Error(`vector(${String(e)}): dimension must be a positive integer (the embedding length, e.g. vector(1536)).`);
284
- return new p({
285
- type: "vector",
286
- nullable: !1,
287
- unique: !1,
288
- hasDefault: !1,
289
- vectorDim: e,
290
- vectorPrecision: t?.precision ?? "float32"
291
- });
292
- }, I = (e) => new p({
293
- type: "array",
294
- nullable: !1,
295
- unique: !1,
296
- hasDefault: !1,
297
- arrayElement: e.__definition().type
298
- }), ne = () => m("interval"), re = (e, t = 4326) => new p({
299
- type: "text",
300
- nullable: !1,
301
- unique: !1,
302
- hasDefault: !1,
303
- spatial: {
304
- kind: "geography",
305
- geomKind: e,
306
- srid: t
307
- }
308
- }), ie = (e, t = 4326) => new p({
309
- type: "text",
310
- nullable: !1,
311
- unique: !1,
312
- hasDefault: !1,
313
- spatial: {
314
- kind: "geometry",
315
- geomKind: e,
316
- srid: t
317
- }
318
- }), ae = (e) => new p({
319
- type: "raw",
320
- nullable: !1,
321
- unique: !1,
322
- hasDefault: !1,
323
- rawDdl: e
324
- }), oe = (e) => {
325
- let t = {};
326
- for (let [n, r] of Object.entries(e)) t[n] = r.__definition();
327
- return t;
328
- }, se = Symbol.for("@voltro/database/pluginRefSpec"), ce = (e) => {
329
- if (typeof e == "object" && e) return ("__definition" in e && typeof e.__definition == "function" ? e.__definition() : e)[se];
330
- }, le = (e, t = {}) => {
331
- let n = {
332
- target: e,
333
- orphanPolicy: t.orphanPolicy ?? "keep",
334
- onSoftDelete: t.onSoftDelete ?? !1
335
- };
336
- return new p({
337
- ...g().__definition(),
338
- [se]: n
339
- });
340
- }, ue = /* @__PURE__ */ new Map(), de = (e, t) => {
341
- if (t.from === t.to) throw Error(`declareEnumRename('${e}'): \`from\` and \`to\` are both '${t.from}' — a rename must change the value.`);
342
- let n = ue.get(e) ?? [];
343
- for (let r of n) {
344
- if (r.from === t.from && r.to === t.to) return;
345
- if (r.from === t.from && r.to !== t.to) throw Error(`declareEnumRename('${e}'): value '${t.from}' is already declared as renamed to '${r.to}', cannot also rename it to '${t.to}'.`);
346
- }
347
- n.push(t), ue.set(e, n);
348
- }, fe = (e) => ue.get(e) ?? [], pe = () => ue, me = () => {
349
- ue.clear();
350
- }, he = (t) => e.isCause(t) ? t : n.isExit(t) && n.isFailure(t) ? t.cause : typeof t == "object" && t && e.isCause(t.voltroCause) ? t.voltroCause : void 0, ge = (t) => {
351
- let n = he(t);
352
- return n === void 0 ? t : e.squash(n);
353
- }, _e = (t, n = 0) => {
354
- let r = n >= 4 ? void 0 : he(t);
355
- if (r === void 0) return [t];
356
- let i = r.reasons.flatMap((t) => e.isFailReason(t) ? [t.error] : e.isDieReason(t) ? [t.defect] : []);
357
- if (i.length === 0) return [e.squash(r)];
358
- let a = [];
359
- for (let e of i.slice(0, 8)) a.push(..._e(e, n + 1));
360
- return a;
361
- }, ve = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, ye = {
362
- 9: "SQLITE_INTERRUPT",
363
- 275: "SQLITE_CONSTRAINT_CHECK",
364
- 787: "SQLITE_CONSTRAINT_FOREIGNKEY",
365
- 1299: "SQLITE_CONSTRAINT_NOTNULL",
366
- 1555: "SQLITE_CONSTRAINT_PRIMARYKEY",
367
- 2067: "SQLITE_CONSTRAINT_UNIQUE"
368
- }, be = (e) => {
369
- let t = {}, n = [], r = ge(e);
370
- for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
371
- let e = r;
372
- t.dbCode === void 0 && (typeof e.code == "string" || typeof e.code == "number") && (t.dbCode = e.code), t.dbErrno === void 0 && typeof e.errno == "number" && (t.dbErrno = e.errno), t.dbErrno === void 0 && typeof e.errcode == "number" && (t.dbErrno = e.errcode), t.dbCode === "ERR_SQLITE_ERROR" && typeof t.dbErrno == "number" && (t.dbCode = ye[t.dbErrno] ?? t.dbCode), t.dbNumber === void 0 && typeof e.number == "number" && (t.dbNumber = e.number), t.dbSqlState === void 0 && typeof e.sqlState == "string" && (t.dbSqlState = e.sqlState), t.dbBindings === void 0 && typeof e.voltroBindings == "string" && (t.dbBindings = e.voltroBindings), t.dbStatement === void 0 && typeof e.sql == "string" && e.sql.includes("?") && (t.dbStatement = e.sql, t.dbPlaceholders = (e.sql.match(/\?/g) ?? []).length), t.dbFatal === void 0 && typeof e.fatal == "boolean" && (t.dbFatal = e.fatal), t.dbConstraint === void 0 && typeof e.constraint == "string" && (t.dbConstraint = e.constraint), t.dbTable === void 0 && typeof e.table == "string" && (t.dbTable = e.table), t.dbColumn === void 0 && typeof e.column == "string" && (t.dbColumn = e.column), t.dbSchema === void 0 && typeof e.schema == "string" && (t.dbSchema = e.schema);
373
- let i = e.sqlMessage ?? e.detail;
374
- t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
375
- let a = typeof e.constructor == "function" ? e.constructor.name : void 0, o = typeof e._tag == "string" && e._tag || typeof e.name == "string" && e.name || (typeof a == "string" && a !== "Object" ? a : void 0), s = typeof e.message == "string" ? e.message : void 0;
376
- (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = ge(e.reason ?? e.cause);
377
- }
378
- return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
379
- }, xe = (e) => {
380
- let t = _e(e).map(be);
381
- if (t.length <= 1) return t[0] ?? {};
382
- let n = t.find(ve) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
383
- if (r.length === 0) return n;
384
- let i = typeof n.dbCauseChain == "string" ? n.dbCauseChain : void 0;
385
- return {
386
- ...n,
387
- dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
388
- };
389
- }, Se = (e, t) => {
390
- let n = we(e);
391
- if (n !== void 0) return n;
392
- let r = xe(e), i = Ae(r, t);
393
- if (i !== void 0) {
394
- let e = i.constraint ?? i.column;
395
- return e === void 0 ? i.kind : `${i.kind}: ${e}`;
396
- }
397
- let a = r.dbCode ?? r.dbSqlState ?? r.dbErrno ?? r.dbNumber, o = De(e);
398
- return a !== void 0 && Te.test(String(a)) ? `${o} (${String(a)})` : o;
399
- }, Ce = Symbol.for("@voltro/database/authoredMessage"), L = (e, t) => {
400
- let n = t === void 0 ? Error(e) : Error(e, t);
401
- return Object.defineProperty(n, Ce, {
402
- value: !0,
403
- enumerable: !1
404
- }), n;
405
- }, we = (e) => {
406
- for (let t of _e(e)) {
407
- let e = t;
408
- for (let t = 0; typeof e == "object" && e && t < 8; t += 1) {
409
- if (e[Ce] === !0) {
410
- let t = e.message;
411
- if (typeof t == "string" && t.length > 0) return t;
412
- }
413
- e = e.cause;
414
- }
415
- }
416
- }, Te = /^[A-Za-z0-9_]{1,32}$/, Ee = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/, De = (e) => {
417
- let t = e?._tag, n = e?.name, r = (typeof t == "string" ? t : typeof n == "string" ? n : "").split(/[^A-Za-z0-9_]+/).filter(Boolean).pop();
418
- return r !== void 0 && Ee.test(r) ? r : "unknown";
419
- }, Oe = /^[A-Za-z_][A-Za-z0-9_$]*$/, R = (e) => e !== void 0 && e.length <= 128 && Oe.test(e) ? e : void 0, ke = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, z = (e, ...t) => {
420
- for (let n of t) {
421
- let t = n.exec(e);
422
- if (t?.[1] !== void 0) return t[1];
423
- }
424
- }, Ae = (e, t) => {
425
- let n = e.dbCode, r = e.dbErrno, i = e.dbNumber, a = typeof e.dbMessage == "string" ? e.dbMessage : "", o = `${typeof e.dbCauseChain == "string" ? e.dbCauseChain : ""} ${a}`;
426
- if (n === "23503") {
427
- let t = R(e.dbConstraint);
428
- return {
429
- kind: /is still referenced from table/i.test(o) ? "foreignKeyInUse" : "foreignKey",
430
- ...t === void 0 ? {} : { constraint: t }
431
- };
432
- }
433
- if (n === "23505") {
434
- let t = R(e.dbConstraint);
435
- return {
436
- kind: "unique",
437
- ...t === void 0 ? {} : { constraint: t }
438
- };
439
- }
440
- if (n === "23502") {
441
- let t = R(e.dbColumn);
442
- return {
443
- kind: "notNull",
444
- ...t === void 0 ? {} : { column: t }
445
- };
446
- }
447
- if (n === "23514") {
448
- let t = R(e.dbConstraint);
449
- return {
450
- kind: "check",
451
- ...t === void 0 ? {} : { constraint: t }
452
- };
453
- }
454
- if (r === 1452 || r === 1451) {
455
- let e = R(z(o, /CONSTRAINT `([^`]+)`/));
456
- return {
457
- kind: r === 1451 ? "foreignKeyInUse" : "foreignKey",
458
- ...e === void 0 ? {} : { constraint: e }
459
- };
460
- }
461
- if (r === 1062) {
462
- let e = R(ke(z(o, /for key '([^']+)'/)));
463
- return {
464
- kind: "unique",
465
- ...e === void 0 ? {} : { constraint: e }
466
- };
467
- }
468
- if (r === 1048 || r === 1364) {
469
- let e = R(z(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
470
- return {
471
- kind: "notNull",
472
- ...e === void 0 ? {} : { column: e }
473
- };
474
- }
475
- if (r === 3819 || r === 4025) {
476
- let e = R(z(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
477
- return {
478
- kind: "check",
479
- ...e === void 0 ? {} : { constraint: e }
480
- };
481
- }
482
- if (i === 547) {
483
- let e = z(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = z(o, /CHECK constraint "([^"]+)"/);
484
- if (t !== void 0 && e === void 0) {
485
- let e = R(t);
486
- return {
487
- kind: "check",
488
- ...e === void 0 ? {} : { constraint: e }
489
- };
490
- }
491
- let n = /REFERENCE constraint/.test(o), r = R(e);
492
- return {
493
- kind: n ? "foreignKeyInUse" : "foreignKey",
494
- ...r === void 0 ? {} : { constraint: r }
495
- };
496
- }
497
- if (i === 2627 || i === 2601) {
498
- let e = R(z(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
499
- return {
500
- kind: "unique",
501
- ...e === void 0 ? {} : { constraint: e }
502
- };
503
- }
504
- if (i === 515) {
505
- let e = R(z(o, /Cannot insert the value NULL into column '([^']+)'/));
506
- return {
507
- kind: "notNull",
508
- ...e === void 0 ? {} : { column: e }
509
- };
510
- }
511
- if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
512
- if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
513
- let e = R(ke(z(o, /UNIQUE constraint failed: ([^,\s]+)/)));
514
- return {
515
- kind: "unique",
516
- ...e === void 0 ? {} : { column: e }
517
- };
518
- }
519
- if (n === "SQLITE_CONSTRAINT_NOTNULL") {
520
- let e = R(ke(z(o, /NOT NULL constraint failed: ([^,\s]+)/)));
521
- return {
522
- kind: "notNull",
523
- ...e === void 0 ? {} : { column: e }
524
- };
525
- }
526
- if (n === "SQLITE_CONSTRAINT_CHECK") {
527
- let e = R(z(a, /CHECK constraint failed: (.+)$/));
528
- return {
529
- kind: "check",
530
- ...e === void 0 ? {} : { constraint: e }
531
- };
532
- }
533
- }, je = (e) => {
534
- let t = Ae(e)?.kind;
535
- return t === "foreignKey" || t === "foreignKeyInUse";
536
- }, Me = (e) => {
537
- let t = e.dbCode, n = e.dbErrno;
538
- return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
539
- }, Ne = (e) => {
540
- if (e.dbErrno !== 1366) return;
541
- let t = `${typeof e.dbCauseChain == "string" ? e.dbCauseChain : ""} ${typeof e.dbMessage == "string" ? e.dbMessage : ""}`;
542
- if (/Incorrect string value: '\\x(F[0-4])/i.exec(t) === null) return;
543
- let n = z(t, /for column [`']?(?:[^`'.]+[`']?\.[`']?)*([^`'.]+)[`']? at row/);
544
- return `${n === void 0 ? "the column" : `column '${n}'`} is stored in a character set that cannot hold a 4-byte character (utf8mb3). Declare the store's character set in app.config.ts — store: { dialect: 'mariadb' | 'mysql', charset: 'utf8mb4' } — and run \`voltro db plan\`: every declared table is created with it and converted to it.`;
545
- }, Pe = (e) => {
546
- let t = xe(e), n = [
547
- t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
548
- t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
549
- t.dbNumber === void 0 ? void 0 : `number=${String(t.dbNumber)}`,
550
- t.dbSqlState === void 0 ? void 0 : `sqlState=${String(t.dbSqlState)}`,
551
- t.dbConstraint === void 0 ? void 0 : `constraint=${String(t.dbConstraint)}`,
552
- t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
553
- ].filter((e) => e !== void 0), r = typeof e?.message == "string" ? e.message : void 0, i = typeof t.dbMessage == "string" ? t.dbMessage : void 0, a = i === void 0 ? void 0 : n.length > 0 || i !== r && i !== `Error: ${String(r)}` ? i : void 0, o = typeof t.dbBindings == "string" ? `\n bindings: ${t.dbBindings}` : "", s = typeof t.dbStatement == "string" ? `\n statement: ${t.dbStatement.length <= 400 ? t.dbStatement : `${t.dbStatement.slice(0, 400)}…`}` : "";
554
- if (a === void 0 && n.length === 0) return;
555
- let c = Ne(t), l = c === void 0 ? "" : `\n hint: ${c}`;
556
- return [a, n.length > 0 ? `[${n.join(" ")}]` : void 0].filter((e) => e !== void 0 && e !== "").join(" ") + l + s + o;
557
- }, Fe = (e) => Object.entries(e).map(([e, t]) => `${e}:${Ie(t)}`).join(" "), Ie = (e) => {
558
- if (e === null) return "null";
559
- if (e === void 0) return "undefined";
560
- if (typeof e == "bigint") return "bigint";
561
- if (typeof e != "object") return typeof e;
562
- if (e instanceof Date) return Number.isNaN(e.getTime()) ? "Date(Invalid)" : "Date";
563
- if (Array.isArray(e)) return "Array";
564
- if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
565
- let t = e.constructor?.name;
566
- return typeof t == "string" && t !== "" ? t : "Object";
567
- }, Le = 63, Re = 60, ze = /* @__PURE__ */ new Set(), Be = (e) => {
568
- ze.add(e);
569
- }, Ve = () => {
570
- let e = [...ze];
571
- return ze.clear(), e;
572
- }, He = /^[a-zA-Z_][a-zA-Z0-9_]*$/, Ue = (e, t) => {
573
- if (t.length === 0) throw Error(`${e} cannot be empty.`);
574
- if (!He.test(t)) throw Error(`${e} '${t}' contains characters outside [A-Za-z0-9_] or starts with a digit. Dialect-portable identifiers must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`);
575
- }, We = (e) => {
576
- if (Ue("table name", e), e.length > 63) throw Error(`table name '${e}' is ${e.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Shorten the name; long table names also cascade into auto-named indexes and FK constraints that would themselves exceed the limit.`);
577
- e.length > 60 && Be(`table name '${e}' is ${e.length} chars — ${63 - e.length} from the Postgres 63-byte limit. Auto-named indexes on this table will run out of room fast.`);
578
- }, Ge = (e, t) => {
579
- if (Ue("column name", t), t.length > 63) throw Error(`column '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Rename it.`);
580
- t.length > 60 && Be(`column '${t}' on table '${e}' is ${t.length} chars — close to the 63-byte limit.`);
581
- }, B = (e, t, n, r) => {
582
- if (Ue("index name", t), t.length > 63) throw Error(n ? `auto-named index '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Supply an explicit short name: .index('<shortName>', ${JSON.stringify([...r])}).` : `index name '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Shorten it.`);
583
- t.length > 60 && Be(`index '${t}' on table '${e}' is ${t.length} chars — ${63 - t.length} from the 63-byte limit. ${n ? `Consider .index('<shortName>', ${JSON.stringify([...r])}) before it grows.` : ""}`);
584
- }, Ke = (e, t) => {
585
- if (e.length === 0) throw Error(`typeid prefix on table '${t.tableName}' cannot be empty.`);
586
- if (!/^[a-z][a-z0-9_]*$/.test(e)) {
587
- let n = t.kind === "derived" ? "the derived prefix doesn't match typeid's required shape — supply an explicit one via id({ prefix: '...' })." : "the prefix must match typeid's required shape /^[a-z][a-z0-9_]*$/.";
588
- throw Error(`typeid prefix '${e}' on table '${t.tableName}' is invalid — ${n}`);
589
- }
590
- if (e.length > 63) {
591
- let n = t.kind === "derived" ? "shorten the table name, or supply an explicit short prefix via id({ prefix: '...' })." : "pick a shorter prefix.";
592
- throw Error(`typeid prefix '${e}' on table '${t.tableName}' is ${e.length} chars — exceeds the 63-byte limit; ${n}`);
593
- }
594
- e.length > 60 && Be(`typeid prefix '${e}' on table '${t.tableName}' is ${e.length} chars — close to the 63-byte limit. Generated ids will be even longer (prefix + '_' + 26).`);
595
- }, qe = 1704067200000n, Je = 10n, Ye = 12n, Xe = (1n << Je) - 1n, Ze = (1n << Ye) - 1n, Qe = Ye, $e = 22n, et = () => {
596
- let e = process.env.SNOWFLAKE_MACHINE_ID;
597
- if (e === void 0 || e === "") return 0n;
598
- let t = BigInt(e);
599
- if (t < 0n || t > Xe) throw Error(`SNOWFLAKE_MACHINE_ID out of range: ${e}. Must be 0..${Xe}.`);
600
- return t;
601
- }, tt = () => ({
602
- lastMs: 0n,
603
- sequence: 0n,
604
- machineId: et()
605
- }), nt, rt = () => (nt === void 0 && (nt = tt()), nt), it = () => {
606
- nt = tt();
607
- }, at = () => BigInt(Date.now()), ot = (e) => {
608
- let t = at();
609
- for (; t <= e;) t = at();
610
- return t;
611
- }, st = () => {
612
- let e = rt(), t = at();
613
- t === e.lastMs ? (e.sequence = e.sequence + 1n & Ze, e.sequence === 0n && (t = ot(e.lastMs), e.lastMs = t)) : (e.sequence = 0n, e.lastMs = t);
614
- let n = t - qe;
615
- if (n < 0n) throw Error("Snowflake timestamp before configured epoch (2024-01-01). System clock is wrong.");
616
- return (n << $e | e.machineId << Qe | e.sequence).toString();
617
- }, ct = (e) => {
618
- let t = e.toLowerCase();
619
- if (t.startsWith("_")) throw Error(`cannot derive a typeid prefix for table '${e}' (table names starting with '_' are not valid typeid prefixes). Pick an explicit prefix via id({ prefix: '...' }) or use a different scheme like id({ scheme: 'numeric' }) for internal tables.`);
620
- if (!/^[a-z][a-z0-9_]*$/.test(t)) throw Error(`cannot derive a typeid prefix from table name '${e}' (must match [a-z][a-z0-9_]*). Pick an explicit prefix via id({ prefix: '...' }).`);
621
- let n = t.endsWith("ies") && t.length > 3 ? t.slice(0, -3) + "y" : t.endsWith("ses") || t.endsWith("xes") || t.endsWith("zes") || t.endsWith("shes") || t.endsWith("ches") ? t.slice(0, -2) : t.endsWith("s") && t.length > 1 ? t.slice(0, -1) : t;
622
- return Ke(n, {
623
- kind: "derived",
624
- tableName: e
625
- }), n;
626
- }, lt = (e, t) => {
627
- if (e === void 0) return {
628
- kind: "typeid",
629
- prefix: ct(t)
630
- };
631
- if ("prefix" in e && !("scheme" in e)) return Ke(e.prefix, {
632
- kind: "explicit",
633
- tableName: t
634
- }), {
635
- kind: "typeid",
636
- prefix: e.prefix
637
- };
638
- if (!("scheme" in e)) throw Error("invalid id() options: no scheme or prefix");
639
- switch (e.scheme) {
640
- case "typeid": {
641
- let n = e.prefix ?? ct(t);
642
- return e.prefix !== void 0 && Ke(e.prefix, {
643
- kind: "explicit",
644
- tableName: t
645
- }), {
646
- kind: "typeid",
647
- prefix: n
648
- };
649
- }
650
- case "ulid": return { kind: "ulid" };
651
- case "numeric": return { kind: "numeric" };
652
- case "snowflake": return { kind: "snowflake" };
653
- case "custom": return {
654
- kind: "custom",
655
- generate: e.generate
656
- };
657
- }
658
- }, ut = (e, t) => {
659
- switch (e.kind) {
660
- case "typeid": return a(e.prefix).toString();
661
- case "ulid": return o();
662
- case "numeric": return null;
663
- case "snowflake": return st();
664
- case "custom": return e.generate(t);
665
- }
666
- }, dt = (e) => ({
667
- fields: oe(e.fields),
668
- ...e.id === void 0 ? {} : { id: e.id },
669
- ...e.requires === void 0 ? {} : { requires: e.requires },
670
- ...e.indexes === void 0 ? {} : { indexes: e.indexes },
671
- ...e.behaviors === void 0 ? {} : { behaviors: e.behaviors },
672
- ...e.policies === void 0 ? {} : { policies: e.policies }
673
- }), ft = dt, pt = (e) => {
674
- let t = /* @__PURE__ */ new Set(), n = [], r = (e) => {
675
- let i = e.id ?? e;
676
- if (!t.has(i)) {
677
- if (t.add(i), e.requires !== void 0) for (let t of e.requires) r(t);
678
- n.push(e);
679
- }
680
- };
681
- for (let t of e) r(t);
682
- return n;
683
- }, mt = (e, ...t) => {
684
- if (t.length === 0) throw Error(`jsonIndex("${e}"): at least one path segment is required`);
685
- let n = (r) => ({
686
- jsonPath: {
687
- column: e,
688
- path: t,
689
- numeric: r
690
- },
691
- numeric: () => n(!0)
692
- });
693
- return n(!1);
694
- }, ht = (e = "cosine", t = "float32") => {
695
- let n = t === "half" ? "halfvec" : "vector";
696
- switch (e) {
697
- case "cosine": return `${n}_cosine_ops`;
698
- case "l2": return `${n}_l2_ops`;
699
- case "inner": return `${n}_ip_ops`;
700
- }
701
- }, gt = [
702
- "id",
703
- "tenantId",
704
- "createdAt",
705
- "updatedAt",
706
- "createdBy",
707
- "updatedBy",
708
- "deletedAt",
709
- "deletedBy"
710
- ], _t = (e) => e.id ?? `<anonymous mixin: ${Object.keys(e.fields).join(", ")}>`, vt = (e, t) => `${e}_${t.join("_")}_idx`, yt = (e, t) => `${e}_${t.join("_")}_uq`, bt = (e, t, n, r, i) => {
711
- if (n !== "hnsw") return;
712
- if (r.length !== 1) throw Error(`hnsw index '${t}' on table '${e}' must cover exactly one vector column — got ${r.length} fields. pgvector's HNSW access method indexes a single vector column.`);
713
- let a = r[0];
714
- if (typeof a != "string") throw Error(`hnsw index '${t}' on table '${e}' must reference a vector COLUMN, not an expression. pgvector's HNSW access method indexes a column directly.`);
715
- let o = i[a];
716
- if (o === void 0) throw Error(`hnsw index '${t}' on table '${e}' references unknown column '${a}'.`);
717
- if (o.type !== "vector") throw Error(`hnsw index '${t}' on table '${e}' requires a vector() column — column '${a}' is '${o.type}'. HNSW is the pgvector approximate-nearest-neighbour method and only applies to vectors.`);
718
- }, xt = (e, t) => {
719
- let n;
720
- for (let [r, i] of Object.entries(e)) i.type === "id" && i.idScheme === void 0 && (n === void 0 && (n = { ...e }), n[r] = {
721
- ...i,
722
- idScheme: lt(i.idSchemeInput, t)
723
- });
724
- return n ?? e;
725
- }, St = (e, t) => {
726
- let n = (e) => Object.getPrototypeOf(e) === Object.prototype && Object.values(Object.getOwnPropertyDescriptors(e)).every((e) => "value" in e), r = (e) => {
727
- if (Object.getPrototypeOf(e) !== Array.prototype || Object.hasOwn(e, Symbol.iterator)) return !1;
728
- for (let t = 0; t < e.length; t++) {
729
- let n = Object.getOwnPropertyDescriptor(e, String(t));
730
- if (!n || !("value" in n) || typeof n.value != "string") return !1;
731
- }
732
- return !0;
733
- }, i = 0, a = t.every((e) => {
734
- let t = Object.getOwnPropertyDescriptor(e, "indexes");
735
- if (t === void 0) return Object.getPrototypeOf(e) === Object.prototype;
736
- if (!("value" in t)) return !1;
737
- let n = t.value;
738
- return n === void 0 ? !0 : Object.getPrototypeOf(n) !== Array.prototype || Object.hasOwn(n, Symbol.iterator) ? !1 : (i += n.length, !0);
739
- });
740
- if (!(i < 32 || !a)) {
741
- for (let e of t) {
742
- let t = e.indexes ?? [];
743
- for (let e = 0; e < t.length; e++) {
744
- let i = Object.getOwnPropertyDescriptor(t, String(e));
745
- if (!i || !("value" in i) || !n(i.value) || !r(i.value.fields)) return;
746
- }
747
- }
748
- return e.every(n) ? new Set(e.map((e) => e.name)) : void 0;
749
- }
750
- }, V = (e) => {
751
- let t = e.appliedPrimaryKey ?? [], n = Object.entries(e.fields).flatMap(([t, n]) => {
752
- let r = ce(n);
753
- if (r === void 0) return [];
754
- if (r.orphanPolicy === "null" && n.nullable !== !0) throw Error(`pluginRef: ${e.tableName}.${t} orphanPolicy: 'null' requires .nullable().`);
755
- return [{
756
- column: t,
757
- ...r
758
- }];
759
- });
760
- return {
761
- tableName: e.tableName,
762
- fields: e.fields,
763
- isReactive: e.isReactive,
764
- appliedMixins: e.appliedMixins,
765
- appliedIndexes: e.appliedIndexes,
766
- appliedUniques: e.appliedUniques,
767
- appliedFullText: e.appliedFullText,
768
- appliedChecks: e.appliedChecks,
769
- appliedRules: e.appliedRules ?? [],
770
- appliedPluginRefs: n,
771
- appliedPrimaryKey: t,
772
- ...e.previousTableName === void 0 ? {} : { previousTableName: e.previousTableName },
773
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
774
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema },
775
- fullTextIndex: ((t, n, r) => {
776
- if (n.length === 0) throw Error(`fullTextIndex '${t}' on '${e.tableName}' has no columns.`);
777
- if (B(e.tableName, t, !1, n), e.appliedFullText.some((e) => e.name === t)) throw Error(`duplicate full-text index '${t}' on table '${e.tableName}'.`);
778
- return V({
779
- ...e,
780
- tableName: e.tableName,
781
- fields: e.fields,
782
- isReactive: e.isReactive,
783
- appliedMixins: e.appliedMixins,
784
- appliedIndexes: e.appliedIndexes,
785
- appliedUniques: e.appliedUniques,
786
- appliedChecks: e.appliedChecks,
787
- appliedPrimaryKey: e.appliedPrimaryKey,
788
- appliedFullText: [...e.appliedFullText, {
789
- name: t,
790
- columns: [...n],
791
- ...r?.config === void 0 ? {} : { config: r.config },
792
- ...r?.weights === void 0 ? {} : { weights: r.weights }
793
- }],
794
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
795
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
796
- });
797
- }),
798
- with: ((...t) => {
799
- let n = pt(t), r = { ...e.fields }, i = /* @__PURE__ */ new Map();
800
- for (let e of Object.keys(r)) i.set(e, {
801
- id: "<table>",
802
- fields: {}
803
- });
804
- for (let t of n) for (let [n, a] of Object.entries(t.fields)) {
805
- let o = i.get(n);
806
- if (o !== void 0) throw Error(`mixin collision on column '${n}' in table '${e.tableName}': '${_t(o)}' and '${_t(t)}' both define it. If they're the same mixin reached via different paths, set a shared 'id' on both. If they're genuinely different concerns, rename one of the columns.`);
807
- Ge(e.tableName, n), r[n] = a, i.set(n, t);
808
- }
809
- let a = [...e.appliedIndexes], o = St(a, n);
810
- for (let t of n) for (let n of t.indexes ?? []) {
811
- let t = n.name ?? vt(e.tableName, n.fields);
812
- (o?.has(t) ?? a.some((e) => e.name === t)) || (B(e.tableName, t, n.name === void 0, n.fields), bt(e.tableName, t, n.kind, n.fields, r), a.push({
813
- name: t,
814
- fields: n.fields,
815
- ...n.kind === void 0 ? {} : { kind: n.kind },
816
- ...n.kindOptions === void 0 ? {} : { kindOptions: n.kindOptions }
817
- }), o?.add(t));
818
- }
819
- return V({
820
- ...e,
821
- tableName: e.tableName,
822
- fields: r,
823
- isReactive: e.isReactive,
824
- appliedMixins: [...e.appliedMixins, ...n],
825
- appliedIndexes: a,
826
- appliedUniques: e.appliedUniques,
827
- appliedFullText: e.appliedFullText,
828
- appliedChecks: e.appliedChecks,
829
- appliedPrimaryKey: e.appliedPrimaryKey,
830
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
831
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
832
- });
833
- }),
834
- index: ((...t) => {
835
- let n, r, i, a = Array.isArray(t[0]);
836
- if (a ? (r = t[0], i = t[1], n = vt(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`index '${n}' on table '${e.tableName}' has no fields — an index must cover at least one column.`);
837
- let o = r.filter((e) => typeof e == "string");
838
- if (B(e.tableName, n, a, o), bt(e.tableName, n, i?.kind, r, e.fields), e.appliedIndexes.some((e) => e.name === n)) throw t.length === 1 ? Error(`duplicate auto-named index '${n}' on table '${e.tableName}' — you've called .index(${JSON.stringify(r)}) twice. Pass an explicit name to the second one if both are intended (rare).`) : Error(`duplicate index '${n}' on table '${e.tableName}': each index name must be unique within a table.`);
839
- return V({
840
- ...e,
841
- tableName: e.tableName,
842
- fields: e.fields,
843
- isReactive: e.isReactive,
844
- appliedMixins: e.appliedMixins,
845
- appliedIndexes: [...e.appliedIndexes, {
846
- name: n,
847
- fields: [...r],
848
- ...i?.where === void 0 ? {} : { where: i.where },
849
- ...i?.kind === void 0 ? {} : { kind: i.kind },
850
- ...i?.kindOptions === void 0 ? {} : { kindOptions: i.kindOptions }
851
- }],
852
- appliedUniques: e.appliedUniques,
853
- appliedFullText: e.appliedFullText,
854
- appliedChecks: e.appliedChecks,
855
- appliedPrimaryKey: e.appliedPrimaryKey,
856
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
857
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
858
- });
859
- }),
860
- expressionIndex: ((t, n, r) => {
861
- if (n.length === 0) throw Error(`expressionIndex '${t}' on table '${e.tableName}' has no fields — an index must cover at least one column or expression.`);
862
- let i = n.filter((e) => typeof e == "string");
863
- if (B(e.tableName, t, !1, i), bt(e.tableName, t, r?.kind, n, e.fields), e.appliedIndexes.some((e) => e.name === t)) throw Error(`duplicate index '${t}' on table '${e.tableName}': each index name must be unique within a table.`);
864
- return V({
865
- ...e,
866
- tableName: e.tableName,
867
- fields: e.fields,
868
- isReactive: e.isReactive,
869
- appliedMixins: e.appliedMixins,
870
- appliedIndexes: [...e.appliedIndexes, {
871
- name: t,
872
- fields: [...n],
873
- ...r?.where === void 0 ? {} : { where: r.where },
874
- ...r?.kind === void 0 ? {} : { kind: r.kind },
875
- ...r?.kindOptions === void 0 ? {} : { kindOptions: r.kindOptions }
876
- }],
877
- appliedUniques: e.appliedUniques,
878
- appliedFullText: e.appliedFullText,
879
- appliedChecks: e.appliedChecks,
880
- appliedPrimaryKey: e.appliedPrimaryKey,
881
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
882
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
883
- });
884
- }),
885
- unique: ((...t) => {
886
- let n, r, i, a = Array.isArray(t[0]);
887
- if (a ? (r = t[0], i = t[1], n = yt(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`unique '${n}' on table '${e.tableName}' has no fields — a UNIQUE constraint must cover at least one column.`);
888
- if (B(e.tableName, n, a, r), e.appliedUniques.some((e) => e.name === n)) throw Error(a ? `duplicate auto-named UNIQUE '${n}' on table '${e.tableName}' — you've called .unique(${JSON.stringify(r)}) twice. Pass an explicit name to the second one if both are intended (very rare).` : `duplicate UNIQUE '${n}' on table '${e.tableName}': each constraint name must be unique within a table.`);
889
- return V({
890
- ...e,
891
- tableName: e.tableName,
892
- fields: e.fields,
893
- isReactive: e.isReactive,
894
- appliedMixins: e.appliedMixins,
895
- appliedIndexes: e.appliedIndexes,
896
- appliedUniques: [...e.appliedUniques, {
897
- name: n,
898
- fields: [...r],
899
- ...i?.dedup === void 0 ? {} : { dedup: i.dedup }
900
- }],
901
- appliedFullText: e.appliedFullText,
902
- appliedChecks: e.appliedChecks,
903
- appliedPrimaryKey: e.appliedPrimaryKey,
904
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
905
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
906
- });
907
- }),
908
- uniqueActive: ((...t) => {
909
- let n, r, i, a = Array.isArray(t[0]);
910
- if (a ? (r = t[0], i = t[1], n = vt(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`uniqueActive '${n}' on table '${e.tableName}' has no fields — a partial UNIQUE must cover at least one column.`);
911
- if (B(e.tableName, n, a, r), e.appliedIndexes.some((e) => e.name === n)) throw Error(`duplicate index '${n}' on table '${e.tableName}': each index name must be unique within a table (uniqueActive shares the index namespace).`);
912
- let o = i?.where ?? "\"deletedAt\" IS NULL";
913
- return V({
914
- ...e,
915
- tableName: e.tableName,
916
- fields: e.fields,
917
- isReactive: e.isReactive,
918
- appliedMixins: e.appliedMixins,
919
- appliedIndexes: [...e.appliedIndexes, {
920
- name: n,
921
- fields: [...r],
922
- where: o,
923
- unique: !0
924
- }],
925
- appliedUniques: e.appliedUniques,
926
- appliedFullText: e.appliedFullText,
927
- appliedChecks: e.appliedChecks,
928
- appliedPrimaryKey: e.appliedPrimaryKey,
929
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
930
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
931
- });
932
- }),
933
- check: ((t, n) => {
934
- if (n.trim().length === 0) throw Error(`CHECK '${t}' on table '${e.tableName}' has an empty expression.`);
935
- if (B(e.tableName, t, !1, []), e.appliedChecks.some((e) => e.name === t)) throw Error(`duplicate CHECK '${t}' on table '${e.tableName}': each constraint name must be unique within a table.`);
936
- return V({
937
- ...e,
938
- tableName: e.tableName,
939
- fields: e.fields,
940
- isReactive: e.isReactive,
941
- appliedMixins: e.appliedMixins,
942
- appliedIndexes: e.appliedIndexes,
943
- appliedUniques: e.appliedUniques,
944
- appliedFullText: e.appliedFullText,
945
- appliedChecks: [...e.appliedChecks, {
946
- name: t,
947
- expr: n
948
- }],
949
- appliedPrimaryKey: e.appliedPrimaryKey,
950
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
951
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
952
- });
953
- }),
954
- rule: ((t, n, r) => {
955
- if (t.trim().length === 0) throw Error(`rule on table '${e.tableName}' has an empty name.`);
956
- let i = e.appliedRules ?? [];
957
- if (i.some((e) => e.name === t)) throw Error(`duplicate rule '${t}' on table '${e.tableName}': each rule name must be unique within a table.`);
958
- return V({
959
- ...e,
960
- appliedRules: [...i, {
961
- name: t,
962
- predicate: n,
963
- severity: r?.severity ?? "error"
964
- }]
965
- });
966
- }),
967
- renamedFrom: ((t) => {
968
- if (t === e.tableName) throw Error(`renamedFrom('${t}') on table '${e.tableName}' names the table itself — drop the marker, there is nothing to rename.`);
969
- return We(t), V({
970
- ...e,
971
- previousTableName: t
972
- });
973
- }),
974
- primaryKey: ((n) => {
975
- if (n.length === 0) throw Error(`primaryKey([...]) on table '${e.tableName}' needs at least one column.`);
976
- let r = /* @__PURE__ */ new Set();
977
- for (let t of n) {
978
- if (!(t in e.fields)) throw Error(`primaryKey([...]) on table '${e.tableName}' references unknown column '${t}'.`);
979
- if (r.has(t)) throw Error(`primaryKey([...]) on table '${e.tableName}' lists column '${t}' twice.`);
980
- r.add(t);
981
- }
982
- if (t.length > 0) throw Error(`primaryKey([...]) declared twice on table '${e.tableName}'.`);
983
- for (let [t, r] of Object.entries(e.fields)) if (r.type === "id" && !n.includes(t)) throw Error(`primaryKey([...]) on table '${e.tableName}' conflicts with the id() column '${t}'. The explicit primary key IS the key — drop the id() column, or include '${t}' in the composite key.`);
984
- return V({
985
- ...e,
986
- tableName: e.tableName,
987
- fields: e.fields,
988
- isReactive: e.isReactive,
989
- appliedMixins: e.appliedMixins,
990
- appliedIndexes: e.appliedIndexes,
991
- appliedUniques: e.appliedUniques,
992
- appliedFullText: e.appliedFullText,
993
- appliedChecks: e.appliedChecks,
994
- appliedPrimaryKey: [...n],
995
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
996
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
997
- });
998
- }),
999
- nonReactive: (() => V({
1000
- ...e,
1001
- tableName: e.tableName,
1002
- fields: e.fields,
1003
- isReactive: !1,
1004
- appliedMixins: e.appliedMixins,
1005
- appliedIndexes: e.appliedIndexes,
1006
- appliedUniques: e.appliedUniques,
1007
- appliedFullText: e.appliedFullText,
1008
- appliedChecks: e.appliedChecks,
1009
- appliedPrimaryKey: e.appliedPrimaryKey,
1010
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
1011
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
1012
- })),
1013
- validate: ((t) => V({
1014
- ...e,
1015
- tableName: e.tableName,
1016
- fields: e.fields,
1017
- isReactive: e.isReactive,
1018
- appliedMixins: e.appliedMixins,
1019
- appliedIndexes: e.appliedIndexes,
1020
- appliedUniques: e.appliedUniques,
1021
- appliedFullText: e.appliedFullText,
1022
- appliedChecks: e.appliedChecks,
1023
- appliedPrimaryKey: e.appliedPrimaryKey,
1024
- insertSchema: t,
1025
- ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
1026
- })),
1027
- validatePatch: ((t) => V({
1028
- ...e,
1029
- tableName: e.tableName,
1030
- fields: e.fields,
1031
- isReactive: e.isReactive,
1032
- appliedMixins: e.appliedMixins,
1033
- appliedIndexes: e.appliedIndexes,
1034
- appliedUniques: e.appliedUniques,
1035
- appliedFullText: e.appliedFullText,
1036
- appliedChecks: e.appliedChecks,
1037
- appliedPrimaryKey: e.appliedPrimaryKey,
1038
- ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
1039
- validatePatchSchema: t.mapFields(i.map(r.optional))
1040
- }))
1041
- };
1042
- }, H = (e, t) => {
1043
- We(e);
1044
- let n = xt(oe(t), e);
1045
- for (let t of Object.keys(n)) Ge(e, t);
1046
- let r;
1047
- for (let [t, i] of Object.entries(n)) i.references === j && (i.references = () => {
1048
- if (r === void 0) throw Error(`selfReference() on '${e}.${t}' read before table() returned`);
1049
- return r;
1050
- });
1051
- return r = V({
1052
- tableName: e,
1053
- fields: n,
1054
- isReactive: !0,
1055
- appliedMixins: [],
1056
- appliedIndexes: [],
1057
- appliedUniques: [],
1058
- appliedFullText: [],
1059
- appliedChecks: [],
1060
- appliedRules: []
1061
- }), r;
1062
- }, Ct = (e) => e === "sqlite" || e === "turso", wt = (e) => e === "mysql" || e === "mariadb", Tt = (e, t) => {
1063
- switch (t) {
1064
- case "mysql":
1065
- case "mariadb": return `\`${e.replace(/`/g, "``")}\``;
1066
- case "mssql": return `[${e.replace(/\]/g, "]]")}]`;
1067
- case "postgres":
1068
- case "sqlite":
1069
- case "turso": return `"${e.replace(/"/g, "\"\"")}"`;
1070
- }
1071
- }, Et = 1e4, Dt = Symbol.for("@voltro/database/tableRegistry"), Ot = globalThis, U = Ot[Dt] ?? (Ot[Dt] = /* @__PURE__ */ new Map()), kt = (e) => {
1072
- let t = U.get(e.tableName);
1073
- if (t === void 0) {
1074
- U.set(e.tableName, e);
1075
- return;
1076
- }
1077
- if (t !== e) throw Error(`duplicate table '${e.tableName}' registration: two different table descriptors claim the same name. Rename one or import the shared module that defines it.`);
1078
- }, At = (e) => {
1079
- U.get(e.tableName) === void 0 && U.set(e.tableName, e);
1080
- }, W = (e) => U.get(e), jt = (e) => {
1081
- let t = U.get(e);
1082
- if (t === void 0) throw Error(`table '${e}' is not registered. Register it by wrapping it in \`databaseHandle({ ... })\` (the usual path) or call \`registerTable(t)\` explicitly before this runs. Note a \`queryFor(t)\` query carries its own source table, so eager-loads don't hit this — this error means a reconstructed descriptor or by-name tooling reached an unregistered table.`);
1083
- return t;
1084
- }, Mt = () => [...U.values()], Nt = (e) => U.delete(e), Pt = () => {
1085
- U.clear();
1086
- }, Ft = (e) => U.get(e)?.isReactive !== !1, It = (e) => e.order ?? [], Lt = (e) => ({
1087
- op: "count",
1088
- alias: e ?? "count"
1089
- }), Rt = (e, t) => ({
1090
- op: "count-distinct",
1091
- column: e,
1092
- alias: t ?? `count_distinct_${e}`
1093
- }), zt = (e, t) => ({
1094
- op: "sum",
1095
- column: e,
1096
- alias: t ?? `sum_${e}`
1097
- }), Bt = (e, t) => ({
1098
- op: "avg",
1099
- column: e,
1100
- alias: t ?? `avg_${e}`
1101
- }), Vt = (e, t) => ({
1102
- op: "min",
1103
- column: e,
1104
- alias: t ?? `min_${e}`
1105
- }), Ht = (e, t) => ({
1106
- op: "max",
1107
- column: e,
1108
- alias: t ?? `max_${e}`
1109
- }), Ut = (e, t) => ({
1110
- op: "column",
1111
- column: e,
1112
- alias: t ?? e
1113
- }), Wt = (e) => (...t) => {
1114
- if (t.length < 2) throw Error(`${e}: requires at least two queries`);
1115
- return K({
1116
- table: t[0].descriptor.table,
1117
- predicate: void 0,
1118
- order: [],
1119
- take: void 0,
1120
- skip: void 0,
1121
- projection: void 0,
1122
- setOp: {
1123
- kind: e,
1124
- queries: t.map((e) => e.descriptor)
1125
- }
1126
- });
1127
- }, Gt = Wt("union"), Kt = Wt("union-all"), qt = Wt("intersect"), Jt = Wt("except"), G = (e) => ({ over: (t) => ({
1128
- ...e,
1129
- window: t
1130
- }) }), Yt = (e = "rowNumber") => G({
1131
- op: "window-row-number",
1132
- alias: e
1133
- }), Xt = (e = "rank") => G({
1134
- op: "window-rank",
1135
- alias: e
1136
- }), Zt = (e = "denseRank") => G({
1137
- op: "window-dense-rank",
1138
- alias: e
1139
- }), Qt = (e, t = 1, n) => G({
1140
- op: "window-lag",
1141
- column: e,
1142
- alias: n ?? `lag_${e}`,
1143
- offset: t
1144
- }), $t = (e, t = 1, n) => G({
1145
- op: "window-lead",
1146
- column: e,
1147
- alias: n ?? `lead_${e}`,
1148
- offset: t
1149
- }), en = (e, t) => G({
1150
- op: "window-sum-over",
1151
- column: e,
1152
- alias: t ?? `sum_${e}_over`
1153
- }), tn = (e, t) => G({
1154
- op: "window-avg-over",
1155
- column: e,
1156
- alias: t ?? `avg_${e}_over`
1157
- }), nn = (e, t, n) => {
1158
- let r = n?.find((e) => e.name === t) ?? W(e)?.appliedFullText?.find((e) => e.name === t);
1159
- if (r === void 0) throw Error(`.matching('${t}', ...): no full-text index named '${t}' is declared on table '${e}'. Declare it with \`table(...).fullTextIndex('${t}', [columns])\` first.`);
1160
- return {
1161
- columns: r.columns,
1162
- ...r.config === void 0 ? {} : { config: r.config },
1163
- ...r.weights === void 0 ? {} : { weights: r.weights }
1164
- };
1165
- }, K = (e) => ({
1166
- descriptor: e,
1167
- where(t) {
1168
- let n = e.predicate ? { and: [e.predicate, t] } : t;
1169
- return K({
1170
- ...e,
1171
- predicate: n
1172
- });
1173
- },
1174
- orderBy(t, n = "asc") {
1175
- return K({
1176
- ...e,
1177
- order: [...e.order, {
1178
- column: t,
1179
- direction: n
1180
- }]
1181
- });
1182
- },
1183
- limit(t) {
1184
- return K({
1185
- ...e,
1186
- take: t
1187
- });
1188
- },
1189
- offset(t) {
1190
- return K({
1191
- ...e,
1192
- skip: t
1193
- });
1194
- },
1195
- select(...t) {
1196
- return K({
1197
- ...e,
1198
- projection: t
1199
- });
1200
- },
1201
- using(t) {
1202
- return K({
1203
- ...e,
1204
- usingIndex: t
1205
- });
1206
- },
1207
- withDeleted() {
1208
- return K({
1209
- ...e,
1210
- includeDeleted: !0
1211
- });
1212
- },
1213
- forUpdate() {
1214
- return K({
1215
- ...e,
1216
- lock: "update"
1217
- });
1218
- },
1219
- unscoped() {
1220
- return K({
1221
- ...e,
1222
- crossTenant: !0
1223
- });
1224
- },
1225
- with(t) {
1226
- let n = {
1227
- ...e.eager ?? {},
1228
- ...t
1229
- };
1230
- return K({
1231
- ...e,
1232
- eager: n
1233
- });
1234
- },
1235
- count() {
1236
- return K({
1237
- ...e,
1238
- projection: void 0,
1239
- aggregations: [{
1240
- op: "count",
1241
- alias: "count"
1242
- }]
1243
- });
1244
- },
1245
- aggregate(t) {
1246
- let n = Object.entries(t).map(([e, t]) => ({
1247
- ...t,
1248
- alias: e
1249
- }));
1250
- return K({
1251
- ...e,
1252
- projection: void 0,
1253
- aggregations: n
1254
- });
1255
- },
1256
- matching(t, n, r) {
1257
- let i = nn(e.table, t, e.fullTextIndexes);
1258
- return K({
1259
- ...e,
1260
- fullTextSearch: {
1261
- indexName: t,
1262
- query: n,
1263
- columns: i.columns,
1264
- ...r?.prefix === !0 ? { prefix: !0 } : {},
1265
- ...i.config === void 0 ? {} : { config: i.config },
1266
- ...i.weights === void 0 ? {} : { weights: i.weights }
1267
- }
1268
- });
1269
- },
1270
- rankBy(t) {
1271
- let n = e.fullTextSearch;
1272
- if (n === void 0) throw Error(".rankBy() requires a preceding .matching(...) clause — there is no full-text search to rank on this query.");
1273
- return K({
1274
- ...e,
1275
- fullTextSearch: {
1276
- ...n,
1277
- rank: {
1278
- alias: t?.alias ?? "rank",
1279
- order: t?.order ?? !0
1280
- }
1281
- }
1282
- });
1283
- },
1284
- nearestNeighbours(t, n, r) {
1285
- if (typeof t == "string" && Array.isArray(n)) {
1286
- let i = {
1287
- column: t,
1288
- queryVector: n,
1289
- distance: r?.distance ?? "cosine",
1290
- ...e.annClause?.ef === void 0 ? {} : { ef: e.annClause.ef }
1291
- };
1292
- return K({
1293
- ...e,
1294
- annClause: i
1295
- });
1296
- }
1297
- if (typeof t == "string" && typeof n == "number") {
1298
- let r = {
1299
- column: "",
1300
- queryText: t,
1301
- distance: "cosine",
1302
- ...e.annClause?.ef === void 0 ? {} : { ef: e.annClause.ef }
1303
- };
1304
- return K({
1305
- ...e,
1306
- annClause: r,
1307
- take: n
1308
- });
1309
- }
1310
- throw Error("nearestNeighbours: call as (column, queryVector, options?) or (queryString, k).");
1311
- },
1312
- efSearch(t) {
1313
- let n = e.annClause ?? {
1314
- column: "",
1315
- distance: "cosine"
1316
- };
1317
- return K({
1318
- ...e,
1319
- annClause: {
1320
- ...n,
1321
- ef: t
1322
- }
1323
- });
1324
- },
1325
- use(t) {
1326
- return K({ ...t(e) });
1327
- },
1328
- distinct() {
1329
- return K({
1330
- ...e,
1331
- distinct: !0
1332
- });
1333
- },
1334
- distinctOn(t) {
1335
- return K({
1336
- ...e,
1337
- distinctOn: [...t]
1338
- });
1339
- },
1340
- as(t) {
1341
- return K({
1342
- ...e,
1343
- alias: t
1344
- });
1345
- },
1346
- innerJoin(t, n, r) {
1347
- let i = typeof t == "string" ? t : t.tableName, a = [...e.joins ?? [], {
1348
- kind: "inner",
1349
- table: i,
1350
- alias: n,
1351
- on: r,
1352
- ...typeof t == "string" ? {} : { sourceTable: t }
1353
- }];
1354
- return K({
1355
- ...e,
1356
- joins: a
1357
- });
1358
- },
1359
- leftJoin(t, n, r) {
1360
- let i = typeof t == "string" ? t : t.tableName, a = [...e.joins ?? [], {
1361
- kind: "left",
1362
- table: i,
1363
- alias: n,
1364
- on: r,
1365
- ...typeof t == "string" ? {} : { sourceTable: t }
1366
- }];
1367
- return K({
1368
- ...e,
1369
- joins: a
1370
- });
1371
- },
1372
- selectJoined(t) {
1373
- let n = Object.entries(t).map(([e, t]) => ({
1374
- outputKey: e,
1375
- source: t
1376
- }));
1377
- return K({
1378
- ...e,
1379
- projection: void 0,
1380
- joinedProjection: n
1381
- });
1382
- },
1383
- withCte(t, n) {
1384
- let r = e.ctes ?? [];
1385
- if (r.some((e) => e.name === t)) throw Error(`Query.withCte: duplicate CTE name '${t}'`);
1386
- return K({
1387
- ...e,
1388
- ctes: [...r, {
1389
- name: t,
1390
- descriptor: n
1391
- }]
1392
- });
1393
- },
1394
- recursiveCte(t, n) {
1395
- let r = e.ctes ?? [];
1396
- if (r.some((e) => e.name === t)) throw Error(`Query.recursiveCte: duplicate CTE name '${t}'`);
1397
- return K({
1398
- ...e,
1399
- ctes: [...r, {
1400
- name: t,
1401
- descriptor: n,
1402
- recursive: !0
1403
- }]
1404
- });
1405
- },
1406
- groupBy(t) {
1407
- let n = e.groupBy ? [...e.groupBy, ...t] : [...t];
1408
- return K({
1409
- ...e,
1410
- groupBy: n
1411
- });
1412
- },
1413
- having(t) {
1414
- let n = e.having ? { and: [e.having, t] } : t;
1415
- return K({
1416
- ...e,
1417
- having: n
1418
- });
1419
- },
1420
- exists() {
1421
- return K({
1422
- ...e,
1423
- projection: void 0,
1424
- aggregations: [{
1425
- op: "count",
1426
- alias: "__exists__"
1427
- }],
1428
- take: 1
1429
- });
1430
- }
1431
- });
1432
- function rn(e) {
1433
- return K({
1434
- table: e.tableName,
1435
- predicate: void 0,
1436
- order: [],
1437
- take: void 0,
1438
- skip: void 0,
1439
- projection: void 0,
1440
- fullTextIndexes: e.appliedFullText,
1441
- sourceTable: e
1442
- });
1443
- }
1444
- var an = (e, t, n) => on(e, "id", t, n), on = (e, t, n, r, i = "asc") => {
1445
- let a = [...e.order.filter((e) => e.column !== t), {
1446
- column: t,
1447
- direction: i
1448
- }], o = n === void 0 ? void 0 : {
1449
- column: t,
1450
- op: i === "desc" ? "lt" : "gt",
1451
- value: n
1452
- }, s = o === void 0 ? e.predicate : e.predicate === void 0 ? o : { and: [e.predicate, o] };
1453
- return {
1454
- ...e,
1455
- predicate: s,
1456
- order: a,
1457
- take: r
1458
- };
1459
- }, sn = (e) => {
1460
- let t = {};
1461
- for (let [n, r] of Object.entries(e)) kt(r), t[n] = rn(r);
1462
- return t;
1463
- }, cn = (e) => e.isView === !0, ln = (e, t, n) => {
1464
- if (We(e), n.trim().length === 0) throw Error(`view('${e}', …): the SELECT body is empty — a view must define a query.`);
1465
- let r = oe(t);
1466
- for (let t of Object.keys(r)) Ge(e, t);
1467
- return {
1468
- tableName: e,
1469
- fields: r,
1470
- isView: !0,
1471
- viewSelect: n
1472
- };
1473
- }, un = (e) => rn({
1474
- ...e,
1475
- isReactive: !1,
1476
- appliedMixins: [],
1477
- appliedIndexes: [],
1478
- appliedUniques: [],
1479
- appliedFullText: [],
1480
- appliedChecks: []
1481
- }), dn = (e, t, n = null) => {
1482
- let r = n === null ? Tt(e.tableName, t) : `${Tt(n, t)}.${Tt(e.tableName, t)}`, i = e.viewSelect.trim();
1483
- switch (t) {
1484
- case "postgres":
1485
- case "mysql":
1486
- case "mariadb": return `CREATE OR REPLACE VIEW ${r} AS ${i};`;
1487
- case "mssql": return `CREATE OR ALTER VIEW ${r} AS ${i};`;
1488
- case "sqlite":
1489
- case "turso": return `DROP VIEW IF EXISTS ${r};\nCREATE VIEW ${r} AS ${i};`;
1490
- }
1491
- }, fn = ({ precision: e, scale: t }) => {
1492
- if (!Number.isSafeInteger(e) || e <= 0 || !Number.isSafeInteger(t) || t < 0 || t > e) throw RangeError("Invalid fixed-point decimal precision or scale");
1493
- return 10n ** BigInt(e);
1494
- }, q = (e, t) => {
1495
- let n = fn(t);
1496
- if (typeof e != "string" || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e)) throw TypeError("Expected a fixed-point decimal string");
1497
- let [r = "", i = ""] = e.replace(/^[+-]/, "").split(".");
1498
- if (/[1-9]/.test(i.slice(t.scale))) throw RangeError("Decimal value exceeds the declared scale");
1499
- let a = BigInt((r || "0") + i.slice(0, t.scale).padEnd(t.scale, "0"));
1500
- if (a >= n) throw RangeError("Decimal value exceeds the declared precision");
1501
- return "D" + ((e.startsWith("-") ? -a : a) + n).toString().padStart(t.precision + 1, "0");
1502
- }, pn = (e, t) => {
1503
- let n = fn(t);
1504
- if (typeof e != "string" || e.length !== t.precision + 2 || !/^D\d+$/.test(e)) throw TypeError("Expected an encoded fixed-point decimal value");
1505
- let r = BigInt(e.slice(1)) - n;
1506
- if (r <= -n || r >= n) throw RangeError("Encoded decimal value exceeds the declared precision");
1507
- let i = (r < 0n ? -r : r).toString().padStart(t.scale + 1, "0"), a = t.scale === 0 ? i : i.slice(0, -t.scale) + "." + i.slice(-t.scale);
1508
- return (r < 0n ? "-" : "") + a;
1509
- }, J = (e) => e?.type === "decimal" && mn(e) !== void 0, mn = (e) => {
1510
- if (e.sqliteDecimalEncoding === void 0) return;
1511
- if (e.precision === void 0 || e.scale === void 0) throw Error("Encoded SQLite decimal metadata requires precision and scale");
1512
- let t = {
1513
- precision: e.precision,
1514
- scale: e.scale
1515
- };
1516
- return q("0", t), t;
1517
- }, hn = (e) => (q("0", e), `VOLTRO_DECIMAL_V1_P${e.precision}_S${e.scale}_TEXT`), gn = (e) => {
1518
- let t = /^\s*VOLTRO_DECIMAL_V1_P(\d+)_S(\d+)_TEXT\s*$/i.exec(e);
1519
- if (!t) return;
1520
- let n = {
1521
- precision: Number(t[1]),
1522
- scale: Number(t[2])
1523
- };
1524
- return q("0", n), n;
1525
- }, _n = (e, t) => {
1526
- q("0", t);
1527
- let n = "D" + "0".repeat(t.precision + 1), r = "D2" + "0".repeat(t.precision);
1528
- return `(${e} IS NULL OR (typeof(${e}) = 'text' AND length(${e}) = ${t.precision + 2} AND substr(${e}, 1, 1) = 'D' AND substr(${e}, 2) NOT GLOB '*[^0-9]*' AND instr(${e}, char(0)) = 0 AND ${e} COLLATE BINARY > '${n}' AND ${e} COLLATE BINARY < '${r}'))`;
1529
- }, vn = (e, t) => {
1530
- if (e == null) return e;
1531
- if (typeof e != "string") throw TypeError("SQLite decimal defaults require exact strings");
1532
- return q(e, t);
1533
- }, Y = (e, t) => {
1534
- let n = e.lastIndexOf("."), r = n < 0 ? e : e.slice(n + 1), i = n < 0 ? void 0 : e.slice(0, n), a = i === void 0 || i === t.alias || i === t.table, o = a ? void 0 : t.joins?.find((e) => e.alias === i), s = a ? t.table : o?.table, c = a ? t.sourceTable : o?.sourceTable;
1535
- return (c?.tableName === s ? c : s === void 0 ? void 0 : W(s))?.fields[r];
1536
- }, yn = (e) => {
1537
- for (let t of [
1538
- "joins",
1539
- "alias",
1540
- "table",
1541
- "sourceTable"
1542
- ]) {
1543
- let n = Object.getOwnPropertyDescriptor(e, t);
1544
- if (n === void 0 ? t in e : !("value" in n)) return (t) => Y(t, e);
1545
- }
1546
- let t = e.joins;
1547
- if (t === void 0 || t.length < 8 || Object.getPrototypeOf(t) !== Array.prototype || t.find !== Array.prototype.find || t[Symbol.iterator] !== Array.prototype[Symbol.iterator]) return (t) => Y(t, e);
1548
- let n = /* @__PURE__ */ new Map();
1549
- for (let r = 0; r < t.length; r++) {
1550
- let i = Object.getOwnPropertyDescriptor(t, r);
1551
- if (i === void 0 || !("value" in i)) return (t) => Y(t, e);
1552
- let a = i.value;
1553
- for (let t of ["table", "sourceTable"]) {
1554
- let n = Object.getOwnPropertyDescriptor(a, t);
1555
- if (n === void 0 ? t in a : !("value" in n)) return (t) => Y(t, e);
1556
- }
1557
- let o = Object.getOwnPropertyDescriptor(a, "alias");
1558
- if (o === void 0 || !("value" in o) || typeof o.value != "string") return (t) => Y(t, e);
1559
- n.has(o.value) || n.set(o.value, a);
1560
- }
1561
- return (t) => {
1562
- let r = t.lastIndexOf("."), i = r < 0 ? t : t.slice(r + 1), a = r < 0 ? void 0 : t.slice(0, r), o = a === void 0 || a === e.alias || a === e.table, s = o ? void 0 : n.get(a), c = o ? e.table : s?.table, l = o ? e.sourceTable : s?.sourceTable;
1563
- return (l?.tableName === c ? l : c === void 0 ? void 0 : W(c))?.fields[i];
1564
- };
1565
- }, bn = (e) => e.replace(/[A-Z]/g, (e) => e.toLowerCase()), xn = (e) => {
1566
- if (Object.getPrototypeOf(e) !== Object.prototype) return !1;
1567
- for (let t of Object.values(Object.getOwnPropertyDescriptors(e))) {
1568
- if (!("value" in t) || !t.value || Object.getPrototypeOf(t.value) !== Object.prototype) return !1;
1569
- for (let e of [
1570
- "type",
1571
- "sqliteDecimalEncoding",
1572
- "precision",
1573
- "scale"
1574
- ]) {
1575
- let n = Object.getOwnPropertyDescriptor(t.value, e);
1576
- if (n && !("value" in n)) return !1;
1577
- }
1578
- }
1579
- return !0;
1580
- }, Sn = (e) => {
1581
- let t, n = !1, r, i = (e, t) => e ? "and" in e ? e.and.some((e) => i(e, t)) : "or" in e ? e.or.some((e) => i(e, t)) : "not" in e ? i(e.not, t) : "subquery" in e && a(e.subquery, t) : !1, a = (e, o) => {
1582
- let s = /* @__PURE__ */ new Set([...o, ...(e.ctes ?? []).map((e) => bn(e.name))]), c = (e, i) => {
1583
- if (s.has(bn(e))) return !1;
1584
- let a = i?.tableName === e ? i : W(e);
1585
- if (a === void 0) return !1;
1586
- if (t === void 0) return t = a, n = Object.values(a.fields).some(J), n;
1587
- r ??= /* @__PURE__ */ new Map([[t, { result: n }]]);
1588
- let o = r.get(a);
1589
- if (o !== void 0 && (o.ordinary ??= xn(a.fields), o.ordinary)) return o.result;
1590
- let c = Object.values(a.fields).some(J);
1591
- return o === void 0 && r.set(a, { result: c }), c;
1592
- };
1593
- return c(e.table, e.sourceTable) || (e.joins ?? []).some((e) => c(e.table, e.sourceTable) || i(e.on, s)) || (e.ctes ?? []).some((e) => a(e.descriptor, s)) || (e.setOp?.queries ?? []).some((e) => a(e, s)) || i(e.predicate, s) || i(e.having, s);
1594
- };
1595
- return a(e, /* @__PURE__ */ new Set());
1596
- }, X = (e, t) => {
1597
- if (e.setOp) {
1598
- let n = e.setOp.queries.map((e) => X(e, t));
1599
- if (n.length < 2) throw Error("Exact set operations require at least two inputs");
1600
- let r = n[0];
1601
- if (n.some((e) => e.length !== r.length)) throw Error("Exact set operation column counts differ");
1602
- return r.map((e, t) => {
1603
- let r = n.map((e) => e[t].decimal);
1604
- if (r.some(Boolean) && !r.every(Boolean)) throw Error("Exact set operation decimal and nondecimal outputs cannot be mixed");
1605
- if (!e.decimal) return e;
1606
- let i = Math.max(...r.map((e) => e.scale)), a = Math.max(...r.map((e) => e.precision - e.scale));
1607
- return {
1608
- name: e.name,
1609
- decimal: {
1610
- precision: a + i,
1611
- scale: i
1612
- }
1613
- };
1614
- });
1615
- }
1616
- let n = e.aggregations ?? [];
1617
- if (n.length) return n.map((n) => {
1618
- let r = Y(n.column ?? "", e);
1619
- if (!J(r) || n.op.startsWith("count") || [
1620
- "window-row-number",
1621
- "window-rank",
1622
- "window-dense-rank"
1623
- ].includes(n.op)) return {
1624
- name: n.alias,
1625
- definition: n.op.startsWith("count") || [
1626
- "window-row-number",
1627
- "window-rank",
1628
- "window-dense-rank"
1629
- ].includes(n.op) ? _().__definition() : r ?? _().__definition()
1630
- };
1631
- let i = ["avg", "window-avg-over"].includes(n.op) ? t ?? r.scale : r.scale, a = [
1632
- "sum",
1633
- "avg",
1634
- "window-sum-over",
1635
- "window-avg-over"
1636
- ].includes(n.op);
1637
- return {
1638
- name: n.alias,
1639
- decimal: {
1640
- precision: r.precision + (a ? 20 : 0) + Math.max(0, i - r.scale),
1641
- scale: i
1642
- }
1643
- };
1644
- });
1645
- let r = e.sourceTable?.tableName === e.table ? e.sourceTable : W(e.table), i = e.joinedProjection ?? (e.projection?.length ? e.projection : Object.keys(r?.fields ?? {})).map((e) => ({
1646
- source: e,
1647
- outputKey: e.split(".").at(-1)
1648
- }));
1649
- if (!i.length) throw Error("Exact set operation requires declared output columns");
1650
- return i.map((t) => {
1651
- let n = Y(t.source, e);
1652
- if (!n) throw Error("Exact set operation requires declared output columns");
1653
- return {
1654
- name: t.outputKey,
1655
- definition: n,
1656
- ...J(n) ? { decimal: {
1657
- precision: n.precision,
1658
- scale: n.scale
1659
- } } : {}
1660
- };
1661
- });
1662
- }, Cn = (e, t, n = [], r) => {
1663
- q("0", t);
1664
- let i = /* @__PURE__ */ new Set([
1665
- "value",
1666
- "negative",
1667
- "unsigned",
1668
- "integer_part",
1669
- "fraction",
1670
- "magnitude",
1671
- "padded",
1672
- "trimmed",
1673
- "alphabetic",
1674
- "complement"
1675
- ]);
1676
- if (new Set(n).size !== n.length || n.some((e) => !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e) || i.has(e.toLowerCase()))) throw Error("Invalid decimal source carry column");
1677
- if (r && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r.prefix)) throw Error("Invalid decimal encoding stage prefix");
1678
- let a = (e) => (r?.prefix ?? "") + "decimal_encode_" + e, o = "0".repeat(t.precision), s = "substr(trimmed,1,length(trimmed)-1)";
1679
- for (let e = 0; e < 10; e++) s = `replace(${s},'${e}','${String.fromCharCode(97 + e)}')`;
1680
- let c = s;
1681
- s = "alphabetic";
1682
- for (let e = 0; e < 10; e++) s = `replace(${s},'${String.fromCharCode(97 + e)}','${9 - e}')`;
1683
- let l = [], u = (e) => r?.reference?.(a(e)) ?? a(e), d = (e, t) => {
1684
- r ? r.append(a(e), t) : l.push(`${a(e)} AS (${t})`);
1685
- };
1686
- d("input", `SELECT * FROM (${e}) LIMIT -1 OFFSET 0`), d("sign", `SELECT *,substr(value,1,1)='-' AS negative,CASE WHEN substr(value,1,1) IN ('-','+') THEN substr(value,2) ELSE value END AS unsigned FROM ${u("input")} LIMIT -1 OFFSET 0`), d("parts", `SELECT *,CASE WHEN instr(unsigned,'.')=0 THEN unsigned ELSE substr(unsigned,1,instr(unsigned,'.')-1) END AS integer_part,CASE WHEN instr(unsigned,'.')=0 THEN '' ELSE substr(unsigned,instr(unsigned,'.')+1) END AS fraction FROM ${u("sign")} LIMIT -1 OFFSET 0`), d("magnitude", `SELECT *,coalesce(nullif(ltrim(integer_part||substr(fraction||'${"0".repeat(t.scale)}',1,${t.scale}),'0'),''),'0') AS magnitude FROM ${u("parts")} LIMIT -1 OFFSET 0`), d("padded", `SELECT *,substr('${o}'||magnitude,-${t.precision}) AS padded FROM ${u("magnitude")} LIMIT -1 OFFSET 0`), d("trimmed", `SELECT *,rtrim(padded,'0') AS trimmed FROM ${u("padded")} LIMIT -1 OFFSET 0`), d("alphabetic", `SELECT *,${c} AS alphabetic FROM ${u("trimmed")} LIMIT -1 OFFSET 0`), d("complement", `SELECT *,${s} AS complement FROM ${u("alphabetic")} LIMIT -1 OFFSET 0`);
1687
- let f = `typeof(value)<>'text' OR instr(value,char(0))<>0 OR unsigned GLOB '*[^0-9.]*' OR instr(fraction,'.')<>0 OR length(integer_part)+length(fraction)=0 OR length(magnitude)>${t.precision} OR substr(fraction,${t.scale + 1}) GLOB '*[1-9]*'`;
1688
- return `(${r ? "" : `WITH ${l.join(",")} `}SELECT ${n.map((e) => `"${e}",`).join("")}CASE WHEN value IS NULL THEN NULL WHEN ${f} THEN abs(-9223372036854775808) WHEN negative AND magnitude<>'0' THEN 'D0'||complement||CAST(10-CAST(substr(trimmed,-1) AS INTEGER) AS TEXT)||substr(padded,length(trimmed)+1) ELSE 'D1'||padded END AS value FROM ${u("complement")})`;
1689
- }, Z = (e) => e.replace(/[A-Z]/g, (e) => e.toLowerCase()), wn = (e) => {
1690
- let t = /* @__PURE__ */ new Set(), n = (e) => {
1691
- "and" in e ? e.and.forEach(n) : "or" in e ? e.or.forEach(n) : "not" in e ? n(e.not) : "subquery" in e && r(e.subquery);
1692
- }, r = (e) => {
1693
- t.add(Z(e.table));
1694
- for (let r of e.joins ?? []) t.add(Z(r.table)), n(r.on);
1695
- for (let n of e.ctes ?? []) t.add(Z(n.name)), r(n.descriptor);
1696
- e.setOp?.queries.forEach(r), e.predicate && n(e.predicate), e.having && n(e.having);
1697
- };
1698
- r(e);
1699
- let i = 0;
1700
- return () => {
1701
- let e;
1702
- do
1703
- e = `__voltro_decimal_cte_${i++}`;
1704
- while (t.has(e));
1705
- return t.add(e), e;
1706
- };
1707
- }, Tn = (e, t, n = () => void 0, r = wn(e)) => {
1708
- let i = /* @__PURE__ */ new Map();
1709
- for (let t of e.ctes ?? []) {
1710
- let e = Z(t.name);
1711
- if (i.has(e)) throw Error("Duplicate exact decimal CTE name");
1712
- i.set(e, t);
1713
- }
1714
- let a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Set(), s = [], c = (e) => {
1715
- let l = Z(e), u = i.get(l);
1716
- if (!u) return n(l);
1717
- let d = a.get(l);
1718
- if (d) return d;
1719
- if (u.recursive) throw Error("Recursive exact decimal CTE composition is not integrated yet");
1720
- if (o.has(l)) throw Error(`Circular exact decimal CTE dependency: ${u.name}`);
1721
- o.add(l);
1722
- let f = Tn(u.descriptor, t, c, r), p = X(f, t);
1723
- if (new Set(p.map((e) => Z(e.name))).size !== p.length) throw Error("Duplicate exact decimal CTE output");
1724
- let m = r(), h = {
1725
- tableName: m,
1726
- fields: Object.fromEntries(p.map((e) => [e.name, e.decimal ? {
1727
- ...y(e.decimal.precision, e.decimal.scale).__definition(),
1728
- sqliteDecimalEncoding: "sortable-v1"
1729
- } : e.definition ?? g().__definition()]))
1730
- };
1731
- return a.set(l, h), o.delete(l), s.push({
1732
- ...u,
1733
- name: m,
1734
- descriptor: f
1735
- }), h;
1736
- };
1737
- for (let e of i.keys()) c(e);
1738
- let l = (e) => "and" in e ? { and: e.and.map(l) } : "or" in e ? { or: e.or.map(l) } : "not" in e ? { not: l(e.not) } : "subquery" in e ? {
1739
- ...e,
1740
- subquery: Tn(e.subquery, t, c, r)
1741
- } : e, u = c(e.table), { ctes: d, ...f } = e;
1742
- return {
1743
- ...f,
1744
- ...s?.length ? { ctes: s } : {},
1745
- ...u ? {
1746
- table: u.tableName,
1747
- alias: e.alias ?? e.table,
1748
- sourceTable: u
1749
- } : {},
1750
- ...e.joins ? { joins: e.joins.map((e) => {
1751
- let t = c(e.table);
1752
- return {
1753
- ...e,
1754
- ...t ? {
1755
- table: t.tableName,
1756
- sourceTable: t
1757
- } : {},
1758
- on: l(e.on)
1759
- };
1760
- }) } : {},
1761
- ...e.predicate ? { predicate: l(e.predicate) } : {},
1762
- ...e.having ? { having: l(e.having) } : {},
1763
- ...e.setOp ? { setOp: {
1764
- ...e.setOp,
1765
- queries: e.setOp.queries.map((e) => Tn(e, t, c, r))
1766
- } } : {}
1767
- };
1768
- }, En = (e, t) => {
1769
- let n = [], r = (e) => "and" in e ? { and: e.and.map(r) } : "or" in e ? { or: e.or.map(r) } : "not" in e ? { not: r(e.not) } : "subquery" in e ? {
1770
- ...e,
1771
- subquery: i(e.subquery)
1772
- } : e, i = (e) => {
1773
- let { ctes: t, ...a } = e;
1774
- for (let e of t ?? []) {
1775
- let t = i(e.descriptor);
1776
- n.push({
1777
- ...e,
1778
- descriptor: t
1779
- });
1780
- }
1781
- return {
1782
- ...a,
1783
- ...a.joins ? { joins: a.joins.map((e) => ({
1784
- ...e,
1785
- on: r(e.on)
1786
- })) } : {},
1787
- ...a.predicate ? { predicate: r(a.predicate) } : {},
1788
- ...a.having ? { having: r(a.having) } : {},
1789
- ...a.setOp ? { setOp: {
1790
- ...a.setOp,
1791
- queries: a.setOp.queries.map(i)
1792
- } } : {}
1793
- };
1794
- }, a = i(Tn(e, t));
1795
- return n.length ? {
1796
- ...a,
1797
- ctes: n
1798
- } : a;
1799
- }, Dn = (e, t, n, r) => {
1800
- let i = (e.ctes ?? []).flatMap((e, i) => {
1801
- let a = X(e.descriptor, n), [o] = r(e.descriptor).compile(), s = (e) => "\"" + e.replaceAll("\"", "\"\"") + "\"", c = `decimal_cte_${i}_`, l = Z(o + e.name);
1802
- for (; l.includes(c);) c += "_";
1803
- let u = a.map((e, t) => `${c}column_${t}`), d = [], f = /* @__PURE__ */ new Set(), [p, m] = r(e.descriptor, {
1804
- prefix: `${c}window_`,
1805
- append: (e, t) => {
1806
- d.push(`${e} AS MATERIALIZED (${t})`);
1807
- },
1808
- encodedOutput: (e) => {
1809
- f.add(e);
1810
- }
1811
- }).compile();
1812
- d.push(`${c}input AS (${p})`);
1813
- let h = (e, t) => {
1814
- d.push(`${e} AS (${t})`);
1815
- }, g = `${c}columns`;
1816
- h(g, `SELECT ${a.map((e, t) => `${s(e.name)} AS ${u[t]}`).join(",")} FROM ${c}input`);
1817
- for (let [e, t] of a.entries()) {
1818
- if (!t.decimal || f.has(t.name)) continue;
1819
- let n = u.filter((t, n) => n !== e), r = Cn(`SELECT ${u[e]} AS value${n.map((e) => "," + e).join("")} FROM ${g}`, t.decimal, n, {
1820
- prefix: `${c}${e}_`,
1821
- append: h
1822
- });
1823
- g = `${c}encoded_${e}`, h(g, `SELECT ${u.map((t, n) => n === e ? `value AS ${t}` : t).join(",")} FROM ${r}`);
1824
- }
1825
- let _ = a.map((e, t) => `${u[t]} AS ${s(e.name)}`).join(",");
1826
- return [t.unsafe(d.join(","), m), t`${t(e.name)} AS (${t.unsafe(`SELECT ${_} FROM ${g}`)})`];
1827
- }), { ctes: a, ...o } = e, [s] = r(o).compile(), c = "decimal_cte_result_", l = Z(s + i.map((e) => e.compile()[0]).join(""));
1828
- for (; l.includes(c);) c += "_";
1829
- let u = [], [d, f] = r(o, void 0, {
1830
- prefix: c,
1831
- append: (e, t) => {
1832
- u.push(`${e} AS MATERIALIZED (${t})`);
1833
- }
1834
- }).compile(), p = u.length ? t`WITH ${t.join(", ", !1)([...i, t.unsafe(u.join(","), f)])} ${t.unsafe(d)}` : t`WITH ${t.join(", ", !1)(i)} SELECT * FROM (${t.unsafe(d, f)})`;
1835
- return t.unsafe(...p.compile());
1836
- }, On = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, kn = (e) => {
1837
- if (e == null || typeof e != "string") return e;
1838
- let t = e.trim();
1839
- if (t.length === 0) return e;
1840
- let n = t.charAt(0);
1841
- if (n !== "{" && n !== "[" && n !== "\"" && n !== "t" && n !== "f" && n !== "n" && (n < "0" || n > "9") && n !== "-") return e;
1842
- try {
1843
- return JSON.parse(t);
1844
- } catch {
1845
- return e;
1846
- }
1847
- }, An = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, jn = (e) => {
1848
- if (e == null || e instanceof Date) return e;
1849
- if (typeof e == "string") {
1850
- let t = new Date(e);
1851
- return isNaN(t.getTime()) ? e : t;
1852
- }
1853
- if (typeof e == "number") {
1854
- let t = new Date(e);
1855
- return isNaN(t.getTime()) ? e : t;
1856
- }
1857
- return e;
1858
- }, Mn = (e, t, n) => {
1859
- if (e == null) return e;
1860
- switch (t) {
1861
- case "boolean": return n === "postgres" ? e : On(e);
1862
- case "vector": return n === "postgres" ? kn(e) : e;
1863
- case "json": return n === "postgres" || n === "mysql" || n === "mariadb" ? e : kn(e);
1864
- case "array": return n === "postgres" ? e : kn(e);
1865
- case "timestamp":
1866
- case "date": return n === "sqlite" || n === "turso" ? jn(e) : e;
1867
- case "decimal":
1868
- if ((n === "sqlite" || n === "turso") && typeof e == "string" && /^D\d+$/.test(e)) throw TypeError("Decimal storage representation does not match the application schema; stop access and complete the verified storage migration before reading this column");
1869
- return An(e);
1870
- case "bigint": return An(e);
1871
- default: return e;
1872
- }
1873
- }, Nn = (e, t) => {
1874
- switch (e) {
1875
- case "boolean": return t !== "postgres";
1876
- case "vector": return t === "postgres";
1877
- case "json": return t !== "postgres" && t !== "mysql" && t !== "mariadb";
1878
- case "array": return t !== "postgres";
1879
- case "timestamp":
1880
- case "date": return t === "sqlite" || t === "turso";
1881
- case "decimal":
1882
- case "bigint": return !0;
1883
- default: return !1;
1884
- }
1885
- }, Pn = (e, t, n, r) => {
1886
- if (e.length === 0) return e;
1887
- if (r && (n === "sqlite" || n === "turso") && Sn(r)) {
1888
- let t = X(En(r, void 0), void 0);
1889
- return e.map((e) => {
1890
- let r = { ...e };
1891
- for (let e of t) {
1892
- let t = e.decimal ? "decimal" : e.definition?.type;
1893
- t && e.name in r && (r[e.name] = Mn(r[e.name], t, n));
1894
- }
1895
- return r;
1896
- });
1897
- }
1898
- if (r?.joinedProjection?.length) {
1899
- let t = r.joinedProjection.map((e) => ({
1900
- outputKey: e.outputKey,
1901
- definition: Y(e.source, r)
1902
- }));
1903
- return e.map((e) => {
1904
- let r = { ...e };
1905
- for (let { outputKey: e, definition: i } of t) i && e in r && (r[e] = Mn(r[e], i.type, n));
1906
- return r;
1907
- });
1908
- }
1909
- let i = r?.sourceTable?.tableName === t ? r.sourceTable : W(t);
1910
- return i === void 0 ? e : Fn(e, i, n);
1911
- }, Fn = (e, t, n) => {
1912
- if (e.length === 0) return e;
1913
- let r = t.fields, i = [];
1914
- for (let [e, t] of Object.entries(r)) {
1915
- let r = n === "sqlite" || n === "turso" ? mn(t) : void 0, a = t.type;
1916
- (r || Nn(a, n) || e in Object.prototype) && i.push({
1917
- key: e,
1918
- type: a,
1919
- ...r ? { decimalShape: r } : {}
1920
- });
1921
- }
1922
- return e.map((e) => {
1923
- let t = { ...e };
1924
- for (let { key: e, type: r, decimalShape: a } of i) e in t && (t[e] = a && t[e] !== null && t[e] !== void 0 ? pn(t[e], a) : Mn(t[e], r, n));
1925
- return t;
1926
- });
1927
- }, In = (e, t) => {
1928
- if (e == null) return e;
1929
- switch (t) {
1930
- case "json": return JSON.stringify(e);
1931
- case "array":
1932
- case "vector": return typeof e == "string" ? e : JSON.stringify(e);
1933
- default: return e;
1934
- }
1935
- }, Ln = (e, t, n = ["json", "array"]) => {
1936
- let r = W(t);
1937
- if (r === void 0) return e;
1938
- let i = r.fields, a = null;
1939
- for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
1940
- let n = r.type === "decimal" ? mn(r) : void 0, i = e[t];
1941
- if (n && i != null && typeof i != "string") throw TypeError("Encoded decimal writes require exact decimal strings");
1942
- let o = n && typeof i == "string" ? q(i, n) : In(i, r.type);
1943
- o !== e[t] && (a === null && (a = { ...e }), a[t] = o);
1944
- }
1945
- return a ?? e;
1946
- }, Rn = (e) => {
1947
- if (typeof e != "string" || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e)) return null;
1948
- let [t = "", n = ""] = e.replace(/^[+-]/, "").split("."), r = t.replace(/^0+/, "") || "0";
1949
- return {
1950
- negative: e.startsWith("-") && /[1-9]/.test(r + n),
1951
- whole: r,
1952
- fraction: n
1953
- };
1954
- }, zn = (e, t) => {
1955
- let n = Rn(e), r = Rn(t);
1956
- if (!n || !r) return null;
1957
- if (n.negative !== r.negative) return n.negative ? -1 : 1;
1958
- let i = n.whole.length - r.whole.length;
1959
- if (i === 0 && (i = n.whole === r.whole ? 0 : n.whole > r.whole ? 1 : -1), i === 0) {
1960
- let e = Math.max(n.fraction.length, r.fraction.length), t = n.fraction.padEnd(e, "0"), a = r.fraction.padEnd(e, "0");
1961
- i = t === a ? 0 : t > a ? 1 : -1;
1962
- }
1963
- return i === 0 ? 0 : (i > 0 ? 1 : -1) * (n.negative ? -1 : 1);
1964
- }, Bn = (e) => {
1965
- let t = Rn(e);
1966
- if (t === null) return null;
1967
- let n = t.fraction.replace(/0+$/, "");
1968
- return `${t.negative ? "-" : ""}${t.whole}${n ? "." + n : ""}`;
1969
- }, Vn = (e) => {
1970
- if (e.length === 0) throw RangeError("Column reference must not be empty");
1971
- return {
1972
- _tag: "ColumnReference",
1973
- column: e
1974
- };
1975
- }, Hn = (e) => typeof e == "object" && !!e && "_tag" in e && e._tag === "ColumnReference" && "column" in e && typeof e.column == "string", Un = [
1976
- "eq",
1977
- "neq",
1978
- "gt",
1979
- "gte",
1980
- "lt",
1981
- "lte"
1982
- ], Wn = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Wn(e)) : e, Gn = /^[A-Za-z_][A-Za-z0-9_]*$/, Kn = (e) => "$" + e.map((e) => typeof e == "number" ? `[${e}]` : Gn.test(e) ? `.${e}` : `."${e.replace(/"/g, "\\\"")}"`).join(""), qn = (e) => "{" + e.map((e) => {
1983
- let t = String(e);
1984
- return /^[A-Za-z0-9_]+$/.test(t) ? t : `"${t.replace(/(["\\])/g, "\\$1")}"`;
1985
- }).join(",") + "}", Q = (e, t, n, r = {}) => {
1986
- let i = Tt(e, n), a = r.numeric ?? !1;
1987
- if (n === "postgres") {
1988
- let e = `(${i} #>> '${qn(t)}'::text[])`;
1989
- return a ? `${e}::numeric` : e;
1990
- }
1991
- let o = Kn(t);
1992
- switch (n) {
1993
- case "mysql":
1994
- case "mariadb": {
1995
- let e = `JSON_UNQUOTE(JSON_EXTRACT(${i}, '${o}'))`;
1996
- return a ? `CAST(${e} AS DECIMAL(38,10))` : e;
1997
- }
1998
- case "mssql": {
1999
- let e = `JSON_VALUE(${i}, '${o}')`;
2000
- return a ? `CAST(${e} AS FLOAT)` : e;
2001
- }
2002
- case "sqlite":
2003
- case "turso": {
2004
- let e = `json_extract(${i}, '${o}')`;
2005
- return a ? `CAST(${e} AS REAL)` : e;
2006
- }
2007
- }
2008
- }, Jn = class extends Error {
2009
- _tag = "TenantNamespaceUnresolved";
2010
- constructor(e) {
2011
- super(e), this.name = "TenantNamespaceUnresolved";
2012
- }
2013
- }, Yn = class extends Error {
2014
- _tag = "TenantNamespaceInvalid";
2015
- constructor(e) {
2016
- super(e), this.name = "TenantNamespaceInvalid";
2017
- }
2018
- }, Xn = 63, Zn = "tenant_", Qn = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), $n = (e) => {
2019
- if (e == null || e === "") throw new Jn("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
2020
- let t = Qn(e);
2021
- if (t.replace(/_/g, "") === "") throw new Yn(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
2022
- let n = `${Zn}${t}`;
2023
- if (n.length > Xn) throw new Yn(`namespace '${n}' for tenant '${e}' exceeds the ${Xn}-byte identifier limit. Use a shorter tenant id.`);
2024
- return n;
2025
- }, er = (e, t) => e === null ? t : `${e}.${t}`, tr = /* @__PURE__ */ new Set(["timestamp", "date"]), nr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, rr = (e, t) => {
2026
- if (e === void 0 || t == null || !tr.has(e) || t instanceof Date) return t;
2027
- if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
2028
- if (typeof t == "string" && nr.test(t)) {
2029
- if (/:\d{2}\.\d{4,}/.test(t)) return t;
2030
- let e = new Date(t);
2031
- return Number.isNaN(e.getTime()) ? t : e;
2032
- }
2033
- return t;
2034
- }, ir = (e, t) => e === void 0 || !tr.has(e) ? t : t.map((t) => rr(e, t)), ar = (e) => {
2035
- if (!e.distinct && !e.distinctOn?.length || e.aggregations?.length || e.setOp) return;
2036
- let t = yn(e), n = e.sourceTable?.tableName === e.table ? e.sourceTable : W(e.table), r = e.joinedProjection ?? (e.projection?.length ? e.projection : Object.keys(n?.fields ?? {})).map((e) => ({
2037
- source: e,
2038
- outputKey: e.split(".").at(-1)
2039
- })), i = {};
2040
- for (let e of r) {
2041
- let n = t(e.source);
2042
- if (!n) return;
2043
- i[e.outputKey] = n;
2044
- }
2045
- if (!Object.values(i).some((e) => e.type === "decimal")) return;
2046
- let a = new Set([
2047
- e.table,
2048
- ...(e.ctes ?? []).map((e) => e.name),
2049
- ...(e.joins ?? []).map((e) => e.table)
2050
- ].map((e) => e.toLowerCase())), o = "__voltro_mssql_decimal_result";
2051
- for (; a.has(o.toLowerCase());) o += "_";
2052
- let s = e.order.length >= 8 && r.length >= 8 ? /* @__PURE__ */ new Map() : void 0;
2053
- if (s) for (let e of r) s.has(e.source) || s.set(e.source, e.outputKey);
2054
- return {
2055
- table: o,
2056
- sourceTable: {
2057
- tableName: o,
2058
- fields: i
2059
- },
2060
- predicate: void 0,
2061
- projection: void 0,
2062
- order: e.order.map((e) => ({
2063
- ...e,
2064
- column: (s === void 0 ? r.find((t) => t.source === e.column)?.outputKey : s.get(e.column)) ?? e.column
2065
- })),
2066
- take: e.take,
2067
- skip: e.skip,
2068
- ctes: [...e.ctes ?? [], {
2069
- name: o,
2070
- descriptor: {
2071
- ...e,
2072
- ctes: [],
2073
- order: [],
2074
- take: void 0,
2075
- skip: void 0
2076
- }
2077
- }]
2078
- };
2079
- }, or = (e, t, n, r) => {
2080
- let i = n.compile(e.subquery);
2081
- if (e.op === "exists") return t`EXISTS (${i})`;
2082
- if (e.op === "not-exists") return t`NOT EXISTS (${i})`;
2083
- let a = X(e.subquery, n.resultScale);
2084
- if (a.length !== 1) throw Error("Exact IN subquery must project exactly one column");
2085
- if (!("column" in e)) throw Error("Unsupported exact subquery predicate");
2086
- let o = r(e.column), s = a[0];
2087
- if (o.scale === void 0 != (s.decimal === void 0)) throw Error("Exact IN subquery cannot mix decimal and nondecimal values");
2088
- let c = Math.max(o.scale ?? 0, s.decimal?.scale ?? 0), l = (e, n) => {
2089
- let r = c - n;
2090
- return r ? t`${e} || ${(n === 0 ? "." : "") + "0".repeat(r)}` : e;
2091
- }, u = l(o.value, o.scale ?? 0), d = t`SELECT ${l(t`${t(s.name)}`, s.decimal?.scale ?? 0)} FROM (${i})`;
2092
- return e.op === "subquery-in" ? t`${u} IN (${d})` : t`${u} NOT IN (${d})`;
2093
- }, sr = (e, t, n, r) => {
2094
- let i = (e) => [
2095
- e.table,
2096
- ...(e.joins ?? []).map((e) => e.table),
2097
- ...e.setOp?.queries.flatMap(i) ?? []
2098
- ], a = "__voltro_decimal_set_";
2099
- for (; i(e).some((e) => e.toLowerCase().startsWith(a));) a += "_";
2100
- let o = [], s = (e) => {
2101
- let n = `${a}${o.length}`;
2102
- return o.push(t`${t(n)} AS (${e})`), n;
2103
- }, c = (e) => {
2104
- if (!e.setOp) throw Error("Missing exact set operation");
2105
- if (e.ctes || e.distinctOn || e.annClause || e.spatialClause || e.fullTextSearch) throw Error("Unsupported exact set query clause");
2106
- let i = X(e, n.resultScale);
2107
- if (new Set(i.map((e) => e.name)).size !== i.length) throw Error("Duplicate exact set output name");
2108
- let a = {
2109
- union: "UNION",
2110
- "union-all": "UNION ALL",
2111
- intersect: "INTERSECT",
2112
- except: "EXCEPT"
2113
- }[e.setOp.kind], o = e.setOp.queries.map((e) => {
2114
- let a = X(e, n.resultScale), o = i.map((e, n) => {
2115
- let r = t`${t(a[n].name)}`, i = (e.decimal?.scale ?? 0) - (a[n].decimal?.scale ?? 0), o = i > 0 ? (a[n].decimal.scale === 0 ? "." : "") + "0".repeat(i) : "";
2116
- return t`${o ? t`${r} || ${o}` : r} AS ${t(`v${n}`)}`;
2117
- }), l = s(e.setOp ? c(e) : r(e));
2118
- return t`SELECT ${t.join(", ", !1)(o)} FROM ${t(l)}`;
2119
- }).reduce((e, n) => t`${e} ${t.unsafe(a)} ${n}`), l = s(o), u = e.order.length ? t` ORDER BY ${t.join(", ", !1)(e.order.flatMap((e) => {
2120
- let n = i.findIndex((t) => t.name === e.column);
2121
- if (n < 0) throw Error("Exact set ordering references an unknown output");
2122
- let r = t`${t(`v${n}`)}`, a = e.direction !== "desc", o = (e, n) => n ? t`${e} ASC` : t`${e} DESC`;
2123
- if (!i[n].decimal) return [o(r, a)];
2124
- let s = t`substr(${r}, 1, 1) = '-'`;
2125
- return [
2126
- o(t`CASE WHEN ${r} IS NULL THEN NULL WHEN ${s} THEN 0 ELSE 1 END`, a),
2127
- o(t`CASE WHEN ${s} THEN length(${r}) END`, !a),
2128
- o(t`CASE WHEN NOT (${s}) THEN length(${r}) END`, a),
2129
- o(t`CASE WHEN ${s} THEN ${r} END COLLATE BINARY`, !a),
2130
- o(t`CASE WHEN NOT (${s}) THEN ${r} END COLLATE BINARY`, a)
2131
- ];
2132
- }))}` : t``;
2133
- for (let t of [e.take, e.skip]) if (t !== void 0 && (!Number.isSafeInteger(t) || t < 0)) throw Error("Invalid exact set pagination");
2134
- let d = e.take === void 0 ? e.skip === void 0 ? t`` : t` LIMIT -1` : t` LIMIT ${e.take}`, f = e.skip === void 0 ? t`` : t` OFFSET ${e.skip}`;
2135
- return t`SELECT ${t.join(", ", !1)(i.map((e, n) => t`${t(`v${n}`)} AS ${t(e.name)}`))} FROM ${t(l)}${u}${d}${f}`;
2136
- }, l = c(e);
2137
- return t`WITH ${t.join(", ", !1)(o)} ${l}`;
2138
- }, cr = {
2139
- eq: "=",
2140
- neq: "<>",
2141
- gt: ">",
2142
- gte: ">=",
2143
- lt: "<",
2144
- lte: "<="
2145
- }, lr = (e, t, n) => {
2146
- q("0", e.shape), q("0", n.shape);
2147
- let r = cr[t];
2148
- if (r === void 0) throw RangeError("Invalid decimal column comparison");
2149
- let i = Math.max(e.shape.scale, n.shape.scale), a = Math.max(e.shape.precision - e.shape.scale, n.shape.precision - n.shape.scale), o = ({ expression: e, shape: t }) => {
2150
- let n = a - (t.precision - t.scale), r = "0".repeat(i - t.scale);
2151
- return `(CASE WHEN substr((${e}), 2, 1) = '1' THEN '1${"0".repeat(n)}' ELSE '0${"9".repeat(n)}' END || substr((${e}), 3) || '${r}') COLLATE BINARY`;
2152
- };
2153
- return `(${o(e)} ${r} ${o(n)})`;
2154
- }, ur = ({ expression: e, shape: t }) => {
2155
- let n = dr(t, (e) => e), r = [`decimal_decode_input AS (SELECT (${e}) AS encoded LIMIT -1 OFFSET 0)`], i = "decimal_decode_input";
2156
- for (let [e, t] of n.steps) {
2157
- let n = `decimal_decode_${e}`;
2158
- r.push(`${n} AS (SELECT *,${t.join(",")} FROM ${i} LIMIT -1 OFFSET 0)`), i = n;
2159
- }
2160
- return `(WITH ${r.join(",")} SELECT ${n.value} AS value FROM ${i})`;
2161
- }, dr = (e, t) => {
2162
- q("0", e);
2163
- let n = t("encoded"), r = t("payload"), i = t("negative"), a = t("trimmed"), o = t("units"), s = t("magnitude"), c = t("padded"), l = `substr(${a},1,length(${a})-1)`;
2164
- for (let e = 0; e < 10; e++) l = `replace(${l},'${e}','${String.fromCharCode(97 + e)}')`;
2165
- let u = t("alphabetic");
2166
- for (let e = 0; e < 10; e++) u = `replace(${u},'${String.fromCharCode(97 + e)}','${9 - e}')`;
2167
- let d = [
2168
- ["parts", [`substr(${n},3) AS ${r}`, `substr(${n},2,1)='0' AS ${i}`]],
2169
- ["trimmed", [`rtrim(${r},'0') AS ${a}`]],
2170
- ["alphabetic", [`${l} AS ${t("alphabetic")}`]],
2171
- ["complement", [`${u} AS ${t("complement")}`]],
2172
- ["units", [`CASE WHEN ${i} THEN ${t("complement")}||CAST(10-CAST(substr(${a},-1) AS INTEGER) AS TEXT)||substr(${r},length(${a})+1) ELSE ${r} END AS ${o}`]],
2173
- ["magnitude", [`COALESCE(NULLIF(ltrim(${o},'0'),''),'0') AS ${s}`]],
2174
- ["padded", [`substr('${"0".repeat(e.scale + 1)}'||${s},-max(length(${s}),${e.scale + 1})) AS ${c}`]]
2175
- ], f = e.scale === 0 ? s : `substr(${c},1,length(${c})-${e.scale})||'.'||substr(${c},-${e.scale})`;
2176
- return {
2177
- steps: d,
2178
- retained: [
2179
- ["payload", "negative"],
2180
- [
2181
- "payload",
2182
- "negative",
2183
- "trimmed"
2184
- ],
2185
- [
2186
- "payload",
2187
- "negative",
2188
- "trimmed",
2189
- "alphabetic"
2190
- ],
2191
- [
2192
- "payload",
2193
- "negative",
2194
- "trimmed",
2195
- "complement"
2196
- ],
2197
- [
2198
- "negative",
2199
- "trimmed",
2200
- "units"
2201
- ],
2202
- [
2203
- "negative",
2204
- "trimmed",
2205
- "magnitude"
2206
- ],
2207
- [
2208
- "negative",
2209
- "trimmed",
2210
- "magnitude",
2211
- "padded"
2212
- ]
2213
- ],
2214
- value: `CASE WHEN ${n} IS NULL THEN NULL WHEN ${`typeof(${n})<>'text' OR length(${n})<>${e.precision + 2} OR substr(${n},1,1)<>'D' OR substr(${n},2,1) NOT IN ('0','1') OR substr(${n},2) GLOB '*[^0-9]*' OR (${i} AND length(${a})=0)`} THEN abs(-9223372036854775808) ELSE (CASE WHEN ${i} THEN '-' ELSE '' END)||${f} END`
2215
- };
2216
- }, fr = (e, t, n, r) => {
2217
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r.prefix)) throw Error("Invalid decimal decoder stage prefix");
2218
- if (new Set(t.map((e) => e.name)).size !== t.length || t.some((e) => !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.name))) throw Error("Invalid decimal decoder columns");
2219
- let i = new Set(n);
2220
- if (i.size !== n.length || n.some((e) => !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)) || t.some((e) => !i.has(e.name))) throw Error("Invalid decimal decoder input columns");
2221
- let a = t.map((e, t) => {
2222
- let n = (n) => n === "encoded" ? e.name : `${r.prefix}d${t}_${n}`;
2223
- return {
2224
- column: e,
2225
- ref: n,
2226
- plan: dr(e.shape, n)
2227
- };
2228
- });
2229
- for (let t = 0; t < (a[0]?.plan.steps.length ?? 0); t++) {
2230
- let i = `${r.prefix}decode_${t}`, o = a.flatMap(({ plan: e }) => e.steps[t][1]), s = a.flatMap(({ plan: e, ref: n }) => t === 0 ? [] : e.retained[t - 1].filter((n) => e.retained[t].includes(n)).map(n));
2231
- r.append(i, `SELECT ${[
2232
- ...n,
2233
- ...s,
2234
- ...o
2235
- ].join(",")} FROM ${e} LIMIT -1 OFFSET 0`), e = i;
2236
- }
2237
- return {
2238
- source: e,
2239
- values: new Map(a.map(({ column: e, plan: t }) => [e.name, t.value]))
2240
- };
2241
- }, pr = (e, t) => {
2242
- if (!Number.isSafeInteger(e) || e < 1 || !Number.isSafeInteger(t) || t < 0 || t > e) throw RangeError("Invalid decimal result shape");
2243
- }, mr = (e, t) => {
2244
- if (pr(t, 0), !/^-?(?:0|[1-9]\d*)$/.test(e)) throw TypeError("Expected canonical decimal units");
2245
- let n = e.replace(/^-/, "");
2246
- if (n.length > t) throw RangeError("Decimal result exceeds declared width");
2247
- let r = n.padStart(t, "0");
2248
- return e.startsWith("-") && n !== "0" ? "0" + r.replace(/\d/g, (e) => String(9 - Number(e))) : "1" + r;
2249
- }, hr = ({ sourceSql: e, digits: t, scale: n, materialized: r = !1, stages: i }) => {
2250
- pr(t, n);
2251
- let a = "0".repeat(t), o = "ltrim(units,'-')", s = `substr('${a}'||${o},-${t})`, c = s;
2252
- for (let e = 0; e < 10; e++) c = `replace(${c},'${e}','${String.fromCharCode(97 + e)}')`;
2253
- let l = c;
2254
- c = "decimal_complement";
2255
- for (let e = 0; e < 10; e++) c = `replace(${c},'${String.fromCharCode(97 + e)}','${9 - e}')`;
2256
- let u = `substr(units,1,1)='-' AND ${o}<>'0'`, d = `CASE WHEN ${u} THEN '0'||${c} ELSE '1'||${s} END`, f = `substr('${"0".repeat(n + 1)}'||${o},-max(length(${o}),${n + 1}))`, p = n === 0 ? o : `substr(${f},1,length(${f})-${n})||'.'||substr(${f},-${n})`, m = `WHEN length(${o})>${t} THEN abs(-9223372036854775808)`, h = r ? e : `SELECT * FROM (${e}) LIMIT -1 OFFSET 0`;
2257
- if (i && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i.prefix)) throw Error("Invalid decimal stage prefix");
2258
- let g = (i?.prefix ?? "") + "decimal_result_source", _ = g + "_encoded", v = (e) => i?.reference?.(e) ?? e;
2259
- i && i.append(g, e, r);
2260
- let y = `SELECT ${g}.*,${l} AS decimal_complement FROM ${v(g)}`;
2261
- return i && i.append(_, y, r), `${i ? "" : `WITH ${g} AS${r ? " MATERIALIZED" : ""} (${h}), ${_} AS${r ? " MATERIALIZED" : ""} (${y}) `}SELECT ${_}.*,
2262
- CASE WHEN units IS NULL THEN NULL ${m} ELSE ${d} END AS decimal_key,
2263
- CASE WHEN units IS NULL THEN NULL ${m} ELSE (CASE WHEN ${u} THEN '-' ELSE '' END)||${p} END AS decimal_value
2264
- FROM ${v(_)}`;
2265
- }, gr = (e, t, n) => {
2266
- pr(e.digits, e.scale), pr(n.digits, n.scale);
2267
- let r = {
2268
- eq: "=",
2269
- neq: "<>",
2270
- gt: ">",
2271
- gte: ">=",
2272
- lt: "<",
2273
- lte: "<="
2274
- }[t];
2275
- if (r === void 0) throw RangeError("Invalid decimal result comparison");
2276
- let i = Math.max(e.scale, n.scale), a = Math.max(e.digits - e.scale, n.digits - n.scale), o = ({ expression: e, digits: t, scale: n }) => {
2277
- let r = a - (t - n), o = i - n;
2278
- return `(CASE WHEN substr((${e}),1,1)='0' THEN '0${"9".repeat(r)}'||substr((${e}),2)||'${"9".repeat(o)}' ELSE '1${"0".repeat(r)}'||substr((${e}),2)||'${"0".repeat(o)}' END) COLLATE BINARY`;
2279
- };
2280
- return `(${o(e)} ${r} ${o(n)})`;
2281
- }, _r = (e, t, n) => {
2282
- if (q("0", t), e.path?.length) throw Error("Decimal JSON-path predicates are unsupported");
2283
- if (e.op === "isNull" || e.op === "isNotNull") return e;
2284
- if (![
2285
- "eq",
2286
- "neq",
2287
- "gt",
2288
- "gte",
2289
- "lt",
2290
- "lte",
2291
- "in",
2292
- "notIn"
2293
- ].includes(e.op)) throw Error("Unsupported exact decimal predicate");
2294
- let r = 10n ** BigInt(t.precision), i = -r + 1n, a = r - 1n, o = (e) => n === "aggregate" ? mr(String(e), t.precision) : "D" + (e + r).toString().padStart(t.precision + 1, "0"), s = (e) => {
2295
- if (typeof e != "string" || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e)) throw TypeError("Exact decimal predicate requires a fixed-point decimal string");
2296
- let [n = "", r = ""] = e.replace(/^[+-]/, "").split("."), i = BigInt((n || "0") + r.slice(0, t.scale).padEnd(t.scale, "0")), a = /[1-9]/.test(r.slice(t.scale)), o = e.startsWith("-"), s = o ? -i : i;
2297
- return {
2298
- floor: s - (o && a ? 1n : 0n),
2299
- ceil: s + (!o && a ? 1n : 0n),
2300
- exact: !a
2301
- };
2302
- }, c = (e) => {
2303
- if (e === null) return null;
2304
- let t = s(e);
2305
- return t.exact && t.floor >= i && t.floor <= a ? o(t.floor) : "!decimal-unrepresentable";
2306
- };
2307
- if (e.op === "in" || e.op === "notIn") {
2308
- if (!Array.isArray(e.value)) throw TypeError("Decimal IN predicate requires an array");
2309
- return {
2310
- ...e,
2311
- value: e.value.map(c)
2312
- };
2313
- }
2314
- if (e.op === "eq" || e.op === "neq") return {
2315
- ...e,
2316
- value: c(e.value)
2317
- };
2318
- if (e.value === null) return e;
2319
- let l = s(e.value), u = e.op === "gte" || e.op === "lt" ? l.ceil : l.floor, d = (t) => ({
2320
- ...e,
2321
- op: t ? "gte" : "lt",
2322
- value: o(i)
2323
- });
2324
- if (e.op === "gte") {
2325
- if (u <= i) return d(!0);
2326
- if (u > a) return d(!1);
2327
- } else if (e.op === "gt") {
2328
- if (u < i) return d(!0);
2329
- if (u >= a) return d(!1);
2330
- } else if (e.op === "lt") {
2331
- if (u <= i) return d(!1);
2332
- if (u > a) return d(!0);
2333
- } else {
2334
- if (u < i) return d(!1);
2335
- if (u >= a) return d(!0);
2336
- }
2337
- return {
2338
- ...e,
2339
- value: o(u)
2340
- };
2341
- }, vr = (e, t, n, r) => {
2342
- let i = (r) => {
2343
- if ("not" in r) return t`NOT (${i(r.not)})`;
2344
- if ("and" in r) return r.and.length ? t.and(r.and.map(i)) : t`TRUE`;
2345
- if ("or" in r) return r.or.length ? t.or(r.or.map(i)) : t`FALSE`;
2346
- if ("subquery" in r) return or(r, t, n, (n) => {
2347
- let r = Y(n, e);
2348
- if (!r) throw Error("Exact IN subquery requires a declared outer column");
2349
- let i = t`${t(n)}`;
2350
- return J(r) ? {
2351
- value: t.unsafe(ur({
2352
- expression: i.compile()[0],
2353
- shape: {
2354
- precision: r.precision,
2355
- scale: r.scale
2356
- }
2357
- })),
2358
- scale: r.scale
2359
- } : { value: i };
2360
- });
2361
- if (!("value" in r) || !Hn(r.value)) {
2362
- if (!("column" in r)) throw Error("Decimal subquery predicates are not integrated yet");
2363
- let n = Y(r.column, e);
2364
- return qr(J(n) ? _r(r, {
2365
- precision: n.precision,
2366
- scale: n.scale
2367
- }, "column") : r, t, null, e.table);
2368
- }
2369
- let a = Y(r.column, e), o = Y(r.value.column, e);
2370
- if (!a || !o) throw Error("Column comparisons require declared source columns");
2371
- if (!J(a) && !J(o)) return qr(r, t);
2372
- if (!J(a) || !J(o)) throw Error("Encoded decimal comparisons require two decimal columns");
2373
- if (!Un.includes(r.op) || r.path?.length) throw Error("Unsupported exact decimal column comparison");
2374
- let s = (e, n) => {
2375
- if (n.precision === void 0 || n.scale === void 0) throw Error("Decimal comparison requires declared precision and scale");
2376
- return {
2377
- expression: t`${t(e)}`.compile()[0],
2378
- shape: {
2379
- precision: n.precision,
2380
- scale: n.scale
2381
- }
2382
- };
2383
- };
2384
- return t.unsafe(lr(s(r.column, a), r.op, s(r.value.column, o)));
2385
- };
2386
- return i(r);
2387
- }, yr = (e, t, n) => {
2388
- let r = (r) => vr(e, t, n, r), i = n.sourceTable ?? ((e) => e), a = e.alias === void 0 ? t`${t(i(e.table))}` : t`${t(i(e.table))} AS ${t(e.alias)}`;
2389
- return {
2390
- from: (e.joins ?? []).reduce((e, n) => t`${e} ${n.kind === "inner" ? t`INNER` : t`LEFT`} JOIN ${t(i(n.table))} AS ${t(n.alias)} ON ${r(n.on)}`, a),
2391
- where: e.predicate === void 0 ? t`` : t` WHERE ${r(e.predicate)}`
2392
- };
2393
- }, br = (e, t, n, r, i) => {
2394
- if (e.groupBy?.length || e.having) throw Error("Row queries cannot contain aggregate clauses");
2395
- let a = yn(e), o = e.sourceTable?.tableName === e.table ? e.sourceTable : W(e.table), s = e.joinedProjection ?? (e.projection?.length ? e.projection : Object.keys(o?.fields ?? {})).map((t) => ({
2396
- source: t.includes(".") ? t : `${e.alias ?? e.table}.${t}`,
2397
- outputKey: t.split(".").at(-1)
2398
- }));
2399
- if (!s.length) throw Error("Exact row projection requires declared source columns");
2400
- if (new Set(s.map((e) => e.outputKey)).size !== s.length) throw Error("Duplicate exact row output key");
2401
- let c = e.order.length >= 8 && s.length >= 8 ? new Map(s.map((e) => [e.outputKey, e.source])) : void 0, l = s.map((e, t) => {
2402
- let n = a(e.source);
2403
- if (!n) throw Error("Exact row projection requires declared source columns");
2404
- return {
2405
- ...e,
2406
- field: n,
2407
- internal: `v${t}`
2408
- };
2409
- }), u = e.order.map((e, t) => {
2410
- let n = (c === void 0 ? s.find((t) => t.outputKey === e.column)?.source : c.get(e.column)) ?? e.column, r = a(n);
2411
- if (!r) throw Error("Exact row order requires a declared source column");
2412
- return {
2413
- ...e,
2414
- source: n,
2415
- field: r,
2416
- internal: `o${t}`
2417
- };
2418
- });
2419
- for (let t of [e.take, e.skip]) if (t !== void 0 && (!Number.isSafeInteger(t) || t < 0)) throw Error("Invalid exact decimal pagination");
2420
- let { from: d, where: f } = yr(e, t, n), p = [...l, ...u], [m, h] = t`SELECT ${t.join(", ", !1)(p.map((e) => t`${t(e.source)} AS ${t(e.internal)}`))} FROM ${d}${f}`.compile(), g = i ?? r, _ = g?.prefix ?? "__voltro_decimal_rows_";
2421
- for (; m.toLowerCase().includes(_.toLowerCase());) _ += "_";
2422
- let v = [], y = (e, t) => {
2423
- g ? g.append(e, t) : v.push(`${e} AS MATERIALIZED (${t})`);
2424
- }, b = `${_}input`;
2425
- y(b, m);
2426
- let x = l.filter((e) => J(e.field));
2427
- if (r) for (let e of x) r.encodedOutput(e.outputKey);
2428
- let S = fr(b, r ? [] : x.map((e) => ({
2429
- name: e.internal,
2430
- shape: {
2431
- precision: e.field.precision,
2432
- scale: e.field.scale
2433
- }
2434
- })), p.map((e) => e.internal), {
2435
- prefix: _,
2436
- append: y
2437
- });
2438
- b = S.source;
2439
- let C = l.map((e) => {
2440
- let n = S.values.get(e.internal);
2441
- return t`${n ? t.unsafe(n) : e.field.type === "bigint" ? t`CAST(${t(e.internal)} AS TEXT)` : t`${t(e.internal)}`} AS ${t(e.outputKey)}`;
2442
- }), w = u.length ? t` ORDER BY ${t.join(", ", !1)(u.map((e) => {
2443
- let n = J(e.field) ? t`${t(e.internal)} COLLATE BINARY` : t`${t(e.internal)}`;
2444
- return e.direction === "desc" ? t`${n} DESC` : t`${n} ASC`;
2445
- }))}` : t``, T = e.take === void 0 ? e.skip === void 0 ? t`` : t` LIMIT -1` : t` LIMIT ${e.take}`, E = e.skip === void 0 ? t`` : t` OFFSET ${e.skip}`, D = v.length ? `WITH ${v.join(",")} ` : "", O = t`SELECT ${e.distinct ? t`DISTINCT ` : t``}${t.join(", ", !1)(C)} FROM ${t(b)}${w}${T}${E}`.compile();
2446
- return t.unsafe(D + O[0], [...h, ...O[1]]);
2447
- }, xr = (e, t, n) => {
2448
- let r = n ? t : `SELECT * FROM (${t}) LIMIT -1 OFFSET 0`;
2449
- return `${e} AS${n ? " MATERIALIZED" : ""} (${r})`;
2450
- }, Sr = ({ sourceSql: e, precision: t, scope: n, materialized: r = !1, stages: i }) => {
2451
- if (!Number.isSafeInteger(t) || t <= 0) throw RangeError("Invalid decimal aggregate precision");
2452
- let a = 1e6, o = (9223372036854775807n / BigInt(a)).toString(), s = Math.ceil((t + 1) / 6), c = Math.ceil((t + 20) / 6) * 6, l = [];
2453
- if (i && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i.prefix)) throw Error("Invalid decimal stage prefix");
2454
- let u = (e) => (i?.prefix ?? "") + e, d = (e) => i?.reference?.(u(e)) ?? u(e), f = (e, t) => {
2455
- i ? i.append(u(e), t, r) : l.push(xr(e, t, r));
2456
- }, p = (e) => "\"" + e.replace(/"/g, "\"\"") + "\"", m = n?.kind === "group" ? n.columns.map((e, t) => `key${t}`) : n?.kind === "window" ? ["identity", ...(n.carryColumns ?? []).map((e, t) => `carry${t}`)] : [], h = m.length === 0 ? "" : m.join(",") + ",", g = n?.kind === "group" ? n.columns.map((e, t) => `${p(e)} AS key${t}`).join(",") : n?.kind === "window" ? [`${p(n.identity)} AS identity`, ...(n.carryColumns ?? []).map((e, t) => `${p(e)} AS carry${t}`)].join(",") : "", _ = n?.kind === "group" && n.columns.length > 0 ? ` GROUP BY ${n.columns.map(p).join(",")}` : "", v = n?.kind === "window" ? [...n.partitionBy?.length ? [`PARTITION BY ${n.partitionBy.map(p).join(",")}`] : [], ...n.orderBy?.length ? [`ORDER BY ${n.orderBy.map((e) => `${p(e.column)} ${e.direction === "desc" ? "DESC" : "ASC"}`).join(",")}`] : []] : [], y = n?.kind === "window" ? ` OVER (${v.join(" ")})` : "";
2457
- f("decimal_source", e);
2458
- let b = Array.from({ length: s }, (e, t) => `d${t}`), x = b.map((e, n) => {
2459
- let r = n === s - 1, i = r ? t + 1 - n * 6 : 6;
2460
- return `COALESCE(SUM(CAST(substr(value,${r ? 2 : -(n + 1) * 6},${i}) AS INTEGER))${y},0) AS ${e}`;
2461
- }), S = `COUNT(value)${y}`, C = `CASE WHEN ${S}>${o} THEN abs(-9223372036854775808) ELSE ${S} END`;
2462
- f("decimal_digits", `SELECT ${g ? g + "," : ""}${C} AS n,${x.join(",")} FROM ${d("decimal_source")}${_}`), f("decimal_add0", `SELECT *,0 AS carry,'' AS result FROM ${d("decimal_digits")}`);
2463
- for (let e = 0; e < s; e++) {
2464
- let t = `(carry+d${e})`;
2465
- f(`decimal_add${e + 1}`, `SELECT ${h}n,${b.join(",")},${t}/${a} AS carry,printf('%06d',${t}%${a})||result AS result FROM ${d(`decimal_add${e}`)}`);
2466
- }
2467
- f("decimal_operands", `SELECT ${h}COALESCE(NULLIF(ltrim(CASE WHEN carry>0 THEN CAST(carry AS TEXT) ELSE '' END||result,'0'),''),'0') AS a,CASE WHEN n=0 THEN '0' ELSE CAST(n AS TEXT)||'${"0".repeat(t)}' END AS b,n FROM ${d(`decimal_add${s}`)}`);
2468
- let w = "(length(a)>length(b) OR (length(a)=length(b) AND a>=b))";
2469
- f("decimal_magnitude", `SELECT ${h}CASE WHEN ${w} THEN a ELSE b END AS hi,CASE WHEN ${w} THEN b ELSE a END AS lo,CASE WHEN ${w} THEN '' ELSE '-' END AS sign,n FROM ${d("decimal_operands")}`);
2470
- let T = "0".repeat(c);
2471
- f("decimal_padded", `SELECT ${h}substr('${T}',1,${c}-length(hi))||hi AS hi,substr('${T}',1,${c}-length(lo))||lo AS lo,sign,n FROM ${d("decimal_magnitude")}`), f("decimal_sub0", `SELECT *,0 AS borrow,'' AS result FROM ${d("decimal_padded")}`);
2472
- let E = c / 6;
2473
- for (let e = 0; e < E; e++) {
2474
- let t = c + 1 - (e + 1) * 6, n = `(CAST(substr(hi,${t},6) AS INTEGER)-CAST(substr(lo,${t},6) AS INTEGER)-borrow)`;
2475
- f(`decimal_sub${e + 1}`, `SELECT ${h}hi,lo,sign,n,CASE WHEN ${n}<0 THEN 1 ELSE 0 END AS borrow,printf('%06d',(${n}+${a})%${a})||result AS result FROM ${d(`decimal_sub${e}`)}`);
2476
- }
2477
- return `${l.length ? `WITH ${l.join(",\n")} ` : ""}SELECT ${h}CASE WHEN n=0 THEN NULL WHEN ltrim(result,'0')='' THEN '0' ELSE sign||ltrim(result,'0') END AS units,CAST(n AS TEXT) AS count FROM ${d(`decimal_sub${E}`)}`;
2478
- }, Cr = (e) => {
2479
- let { precision: t, inputScale: n, resultScale: r, rounding: i, scope: a, materialized: o = !1, stages: s } = e;
2480
- if (!Number.isSafeInteger(n) || n < 0 || n > t || !Number.isSafeInteger(r) || r < 0) throw RangeError("Invalid decimal average scale");
2481
- let c = Sr(e), l = a?.kind === "group" ? a.columns.map((e, t) => `key${t}`) : a?.kind === "window" ? ["identity", ...(a.carryColumns ?? []).map((e, t) => `carry${t}`)] : [], u = l.length === 0 ? "" : l.join(",") + ",", d = r - n, f = Math.ceil((t + 20) / 6) * 6 + Math.max(d, 0), p = f + Math.min(d, 0), m = Math.ceil(p / 6) * 6, h = [];
2482
- if (s && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s.prefix)) throw Error("Invalid decimal stage prefix");
2483
- let g = (e) => (s?.prefix ?? "") + e, _ = (e) => s?.reference?.(g(e)) ?? g(e), v = (e, t) => {
2484
- s ? s.append(g(e), t, o) : h.push(xr(e, t, o));
2485
- };
2486
- v("decimal_avg_sum", c), v("decimal_avg_input", `SELECT ${u}count,CASE WHEN substr(units,1,1)='-' THEN '-' ELSE '' END AS sign,${`COALESCE(ltrim(units,'-'),'0')||'${"0".repeat(Math.max(d, 0))}'`} AS magnitude FROM ${_("decimal_avg_sum")}`), v("decimal_avg_div0", `SELECT ${u}count,sign,substr('${"0".repeat(f)}',1,${f}-length(magnitude))||magnitude AS digits,CASE WHEN count='0' THEN 1 ELSE CAST(count AS INTEGER) END AS denominator,0 AS remainder,'' AS result FROM ${_("decimal_avg_input")}`);
2487
- let y = 0;
2488
- for (let e = 1; e <= f; e += 5) {
2489
- let t = Math.min(5, f - e + 1), n = `(remainder*${10 ** t}+CAST(substr(digits,${e},${t}) AS INTEGER))`, r = y++;
2490
- v(`decimal_avg_div${y}`, `SELECT ${u}count,sign,digits,denominator,${n}%denominator AS remainder,result||printf('%0${t}d',${n}/denominator) AS result FROM ${_(`decimal_avg_div${r}`)}`);
2491
- }
2492
- let b = d < 0 ? `substr(result,1,${p})` : "result", x = i === "half-away" ? "1" : `CAST(substr(${b},-1,1) AS INTEGER)%2`, S;
2493
- if (d < 0) {
2494
- let e = `substr(result,${p + 1})`, t = `'5${"0".repeat(-d - 1)}'`;
2495
- S = `${e}>${t} OR (${e}=${t} AND (remainder>0 OR ${x}=1))`;
2496
- } else S = `remainder*2>denominator OR (remainder*2=denominator AND ${x}=1)`;
2497
- v("decimal_avg_round0", `SELECT ${u}count,sign,substr('${"0".repeat(m)}',1,${m}-${p})||${b} AS quotient,CASE WHEN ${S} THEN 1 ELSE 0 END AS carry,'' AS result FROM ${_(`decimal_avg_div${y}`)}`);
2498
- let C = m / 6;
2499
- for (let e = 1; e <= C; e++) {
2500
- let t = `(CAST(substr(quotient,${m + 1 - e * 6},6) AS INTEGER)+carry)`;
2501
- v(`decimal_avg_round${e}`, `SELECT ${u}count,sign,quotient,${t}/1000000 AS carry,printf('%06d',${t}%1000000)||result AS result FROM ${_(`decimal_avg_round${e - 1}`)}`);
2502
- }
2503
- return `${h.length ? `WITH ${h.join(",\n")} ` : ""}SELECT ${u}CASE WHEN count='0' THEN NULL WHEN ltrim(result,'0')='' THEN '0' ELSE sign||ltrim(result,'0') END AS units,count FROM ${_(`decimal_avg_round${C}`)}`;
2504
- }, wr = (e, t, n, r, i, a) => {
2505
- let o = yn(e), s = e.aggregations ?? [], c = {
2506
- "window-row-number": "ROW_NUMBER",
2507
- "window-rank": "RANK",
2508
- "window-dense-rank": "DENSE_RANK",
2509
- "window-lag": "LAG",
2510
- "window-lead": "LEAD",
2511
- "window-sum-over": "SUM",
2512
- "window-avg-over": "AVG"
2513
- };
2514
- if (e.groupBy?.length || e.having || e.setOp || e.ctes || e.distinctOn || e.annClause || e.spatialClause || e.fullTextSearch || s.some((e) => e.op !== "column" && !(e.op in c))) throw Error("Exact window queries require supported ungrouped window projections");
2515
- if (new Set(s.map((e) => e.alias)).size !== s.length) throw Error("Duplicate decimal result alias");
2516
- let l = [...new Set(s.flatMap((e) => [
2517
- ...e.column === void 0 ? [] : [e.column],
2518
- ...e.window?.partitionBy ?? [],
2519
- ...(e.window?.orderBy ?? []).map((e) => e.column)
2520
- ]))].map((e, t) => {
2521
- let n = o(e);
2522
- if (!n) throw Error("Exact window requires declared source columns");
2523
- return {
2524
- source: e,
2525
- name: `c${t}`,
2526
- field: n
2527
- };
2528
- }), u = new Map(l.map((e) => [e.source, e])), d = (e) => {
2529
- let t = u.get(e);
2530
- if (!t) throw Error("Unknown exact window source column");
2531
- return t.name;
2532
- }, f = (e) => "\"" + e.replace(/"/g, "\"\"") + "\"", { from: p, where: m } = yr(e, t, r), [h, g] = t`SELECT ${t.join(", ", !1)([t`ROW_NUMBER() OVER () AS identity`, ...l.map((e) => t`${t(e.source)} AS ${t(e.name)}`)])} FROM ${p}${m}`.compile(), _ = i ?? a, v = _?.prefix ?? "__voltro_decimal_window_", y = [e.table, ...(e.joins ?? []).map((e) => e.table)];
2533
- for (; y.some((e) => e.toLowerCase().startsWith(v));) v += "_";
2534
- let b = [], x = (e, t, n) => {
2535
- _ ? _.append(e, t) : b.push(`${e} AS MATERIALIZED (${t})`);
2536
- };
2537
- x(v + "source", h, n.materialized);
2538
- let S = [], C = /* @__PURE__ */ new Map(), w, T = !1, E = (t) => {
2539
- if (!T) {
2540
- T = !0;
2541
- let t = e.order;
2542
- if (t.length >= 32 && Object.getPrototypeOf(t) === Array.prototype && !Object.hasOwn(t, "some") && !Object.hasOwn(t, Symbol.iterator)) {
2543
- let e = [];
2544
- for (let n = 0; n < t.length; n++) {
2545
- let r = Object.getOwnPropertyDescriptor(t, String(n)), i = r && "value" in r ? Object.getOwnPropertyDescriptor(r.value, "column") : void 0;
2546
- if (!i || !("value" in i) || typeof i.value != "string") break;
2547
- e.push(i.value);
2548
- }
2549
- e.length === t.length && (w = new Set(e));
2550
- }
2551
- }
2552
- return w?.has(t) ?? e.order.some((e) => e.column === t);
2553
- };
2554
- for (let [e, t] of s.entries()) {
2555
- let r = `SELECT * FROM ${v}source`, a = t.column === void 0 ? void 0 : u.get(t.column);
2556
- if (t.op === "column") {
2557
- if (!a) throw Error("Window column projection requires a source column");
2558
- C.set(t.alias, {
2559
- value: a.name,
2560
- key: a.name,
2561
- encoded: a.field
2562
- });
2563
- continue;
2564
- }
2565
- let o = [
2566
- "window-lag",
2567
- "window-lead",
2568
- "window-sum-over",
2569
- "window-avg-over"
2570
- ].includes(t.op);
2571
- if (o && !a) throw Error("Window operation requires a source column");
2572
- let s = t.window?.partitionBy?.map(d), l = t.window?.orderBy?.map((e) => ({
2573
- ...e,
2574
- column: d(e.column)
2575
- })), p = `w${e}`, m = J(a?.field) && ["window-sum-over", "window-avg-over"].includes(t.op);
2576
- if (m) {
2577
- let o = a.field.precision, c = a.field.scale, u = t.op === "window-avg-over" ? n.resultScale ?? c : c, d = o + 20 + Math.max(0, u - c), m = {
2578
- kind: "window",
2579
- identity: "identity",
2580
- partitionBy: s ?? [],
2581
- orderBy: l ?? []
2582
- }, h = /* @__PURE__ */ new Map(), g = 0, _ = {
2583
- prefix: `${v}${e}_`,
2584
- reference: (e) => {
2585
- let t = h.get(e);
2586
- return t === void 0 ? e : `(${t}${t.endsWith("LIMIT -1 OFFSET 0") ? "" : " LIMIT -1 OFFSET 0"}) AS ${e}`;
2587
- },
2588
- append: (e, t, r) => {
2589
- n.materialized || ++g % 4 == 0 ? x(e, t, r) : h.set(e, t);
2590
- }
2591
- }, y = {
2592
- stages: _,
2593
- sourceSql: `SELECT *,${f(a.name)} AS value FROM (${r})`,
2594
- precision: o,
2595
- scope: m,
2596
- materialized: n.materialized
2597
- }, b = t.op === "window-avg-over" ? Cr({
2598
- ...y,
2599
- inputScale: c,
2600
- resultScale: u,
2601
- rounding: n.rounding ?? "half-even"
2602
- }) : Sr(y);
2603
- if (i) {
2604
- let e = Cn(`SELECT identity,units AS value FROM (${b})`, {
2605
- precision: d,
2606
- scale: 0
2607
- }, ["identity"], {
2608
- prefix: _.prefix,
2609
- reference: _.reference,
2610
- append: (e, t) => _.append(e, t, n.materialized)
2611
- });
2612
- r = `SELECT identity,value AS ${f(p)} FROM ${e}`, C.set(t.alias, {
2613
- value: p,
2614
- key: p,
2615
- encoded: {
2616
- ...a.field,
2617
- precision: d,
2618
- scale: u
2619
- }
2620
- });
2621
- } else {
2622
- let e = hr({
2623
- sourceSql: b,
2624
- digits: d,
2625
- scale: u,
2626
- materialized: n.materialized,
2627
- stages: _
2628
- }), i = E(t.alias);
2629
- r = `SELECT identity,decimal_value AS ${f(p)}${i ? `,decimal_key AS ${f(p + "_key")}` : ""} FROM (${e})`, C.set(t.alias, {
2630
- value: p,
2631
- key: i ? p + "_key" : p
2632
- });
2633
- }
2634
- } else {
2635
- let i = [...s?.length ? [`PARTITION BY ${s.map(f).join(",")}`] : [], ...l?.length ? [`ORDER BY ${l.map((e) => `${f(e.column)} ${e.direction === "desc" ? "DESC" : "ASC"}`).join(",")}`] : []].join(" "), u = t.op === "window-lag" || t.op === "window-lead", d = t.offset ?? 1;
2636
- if (u && (!Number.isSafeInteger(d) || d < 0)) throw Error("Invalid exact window offset");
2637
- let m = o ? f(a.name) + (u ? `,${d}` : "") : "";
2638
- if (t.op === "window-rank" || t.op === "window-dense-rank") {
2639
- let a = [.../* @__PURE__ */ new Set([...s ?? [], ...(l ?? []).map((e) => e.column)])], o = a.length ? `PARTITION BY ${a.map(f).join(",")}` : "";
2640
- if (t.op === "window-rank") r = `SELECT *,COUNT(*) OVER (${i})-COUNT(*) OVER (${o})+1 AS ${f(p)} FROM (${r})`;
2641
- else {
2642
- let t = `${p}_peer`, a = `${v}peer${e}`;
2643
- x(a, `SELECT *,CASE WHEN ROW_NUMBER() OVER (${o})=1 THEN 1 ELSE 0 END AS ${f(t)} FROM (${r})`, n.materialized), r = `SELECT *,SUM(${f(t)}) OVER (${i}) AS ${f(p)} FROM ${a}`;
2644
- }
2645
- } else if (u) {
2646
- let i = `${p}_position`, o = `${v}shift${e}`;
2647
- x(o, `SELECT *,ROW_NUMBER() OVER (${[...s?.length ? [`PARTITION BY ${s.map(f).join(",")}`] : [], `ORDER BY ${[...(l ?? []).map((e) => `${f(e.column)} ${e.direction === "desc" ? "DESC" : "ASC"}`), "identity ASC"].join(",")}`].join(" ")}) AS ${f(i)} FROM (${r})`, n.materialized);
2648
- let c = [...(s ?? []).map((e) => `shifted.${f(e)} IS current.${f(e)}`), `shifted.${f(i)}=current.${f(i)}${t.op === "window-lag" ? "-" : "+"}${d}`].join(" AND ");
2649
- r = `SELECT current.*,(SELECT shifted.${f(a.name)} FROM ${o} AS shifted WHERE ${c}) AS ${f(p)} FROM ${o} AS current`;
2650
- } else r = `SELECT *,${c[t.op]}(${m}) OVER (${i}) AS ${f(p)} FROM (${r}) LIMIT -1 OFFSET 0`;
2651
- C.set(t.alias, {
2652
- value: p,
2653
- key: p,
2654
- ...u ? { encoded: a.field } : {}
2655
- });
2656
- }
2657
- let h = `${v}stage${e}`, g = m && C.get(t.alias).key !== p ? [p, p + "_key"] : [p];
2658
- x(h, m ? r : `SELECT identity,${g.map(f).join(",")} FROM (${r})`, n.materialized), S.push({
2659
- stage: h,
2660
- values: g
2661
- });
2662
- }
2663
- let D = `${v}output`;
2664
- x(D, `SELECT ${["input.*", ...S.flatMap((e) => e.values.map((t) => `(SELECT result.${f(t)} FROM ${e.stage} AS result WHERE result.identity=input.identity) AS ${f(t)}`))].join(",")} FROM ${v}source AS input`, n.materialized);
2665
- let O = new Map([...C.values()].flatMap((e) => J(e.encoded) ? [[e.value, {
2666
- name: e.value,
2667
- shape: {
2668
- precision: e.encoded.precision,
2669
- scale: e.encoded.scale
2670
- }
2671
- }]] : [])), k = fr(D, i ? [] : [...O.values()], [
2672
- "identity",
2673
- ...l.map((e) => e.name),
2674
- ...S.flatMap((e) => e.values)
2675
- ], {
2676
- prefix: `${v}result_`,
2677
- append: (e, t) => x(e, t, n.materialized)
2678
- }), ee = s.map((e) => {
2679
- let t = C.get(e.alias), n = `window_output.${f(t.value)}`;
2680
- return i && J(t.encoded) ? (i.encodedOutput(e.alias), `${n} AS ${f(e.alias)}`) : `${k.values.get(t.value) ?? (t.encoded?.type === "bigint" ? `CAST(${n} AS TEXT)` : n)} AS ${f(e.alias)}`;
2681
- }), A = e.order.length ? " ORDER BY " + e.order.map((e) => {
2682
- let t = C.get(e.column);
2683
- if (!t) throw Error("Ordering references an unknown window result");
2684
- return `window_output.${f(t.key)} ${e.direction === "desc" ? "DESC" : "ASC"}`;
2685
- }).join(",") : "";
2686
- for (let t of [e.take, e.skip]) if (t !== void 0 && (!Number.isSafeInteger(t) || t < 0)) throw Error("Invalid exact decimal pagination");
2687
- let j = e.take === void 0 ? e.skip === void 0 ? "" : " LIMIT -1" : ` LIMIT ${e.take}`, M = e.skip === void 0 ? "" : ` OFFSET ${e.skip}`;
2688
- return t.unsafe(`${_ ? "" : `WITH ${b.join(",")} `}SELECT ${e.distinct ? "DISTINCT " : ""}${ee.join(",")} FROM ${k.source} AS window_output${A}${j}${M}`, g);
2689
- }, Tr = (e, t, n, r, i, a) => {
2690
- if (!t.onDialectOrElse({
2691
- sqlite: () => !0,
2692
- orElse: () => !1
2693
- })) throw Error("Encoded decimal query integration requires a SQLite-family compiler");
2694
- if (e.ctes?.length) return Dn(e, t, n.resultScale, (e, i, a) => Tr(e, t, n, r, i, a));
2695
- if (e.setOp) return sr(e, t, n, (e) => Tr(e, t, n, r));
2696
- let o = {
2697
- compile: (e) => Tr(e, t, n, r),
2698
- resultScale: n.resultScale,
2699
- sourceTable: r
2700
- }, s = e.aggregations ?? [];
2701
- if (s.length > 0 && s.every((e) => e.op === "column") && !e.groupBy?.length && !e.having || s.some((e) => e.op.startsWith("window-"))) return wr(e, t, n, o, i, a);
2702
- let c = s.length === 0, l = s.filter((e) => e.op !== "column"), u = !c && l.length === 0, d = {
2703
- sum: "SUM",
2704
- avg: "AVG",
2705
- min: "MIN",
2706
- max: "MAX",
2707
- count: "COUNT",
2708
- "count-distinct": "COUNT"
2709
- };
2710
- if (u && !e.groupBy?.length || l.some((e) => !(e.op in d)) || e.setOp || e.distinctOn || e.ctes || e.annClause || e.spatialClause || e.fullTextSearch) throw Error("Exact decimal query integration requires supported grouped aggregate projections");
2711
- if (new Set(s.map((e) => e.alias)).size !== s.length) throw Error("Duplicate decimal result alias");
2712
- let f = yn(e), p = e.groupBy ?? [], m = /* @__PURE__ */ new Map();
2713
- p.forEach((e, t) => {
2714
- m.has(e) || m.set(e, t);
2715
- });
2716
- for (let e of p) if (f(e) === void 0) throw Error("Exact decimal grouping requires declared source columns");
2717
- for (let e of s) if (e.op === "column" && !m.has(e.column ?? "")) throw Error("Projected group column is absent from GROUP BY");
2718
- let h = "__decimal_group_identity";
2719
- for (; s.some((e) => e.alias === h);) h += "_";
2720
- let g = [...(u ? [{
2721
- op: "count",
2722
- alias: h
2723
- }] : l).map((e) => ({
2724
- aggregate: e,
2725
- projection: e
2726
- })), ...s.filter((e) => e.op === "column" && J(f(e.column ?? ""))).map((e) => ({
2727
- aggregate: {
2728
- ...e,
2729
- op: "min"
2730
- },
2731
- projection: e
2732
- }))].map(({ aggregate: e, projection: t }, r) => {
2733
- if (e.column === void 0 && e.op !== "count") throw Error("Aggregate requires a source column");
2734
- let i = f(e.column ?? "");
2735
- if (e.column !== void 0 && i === void 0) throw Error("Aggregate requires a declared source column");
2736
- let a = J(i) && !e.op.startsWith("count");
2737
- if (a && (i.precision === void 0 || i.scale === void 0)) throw Error("Exact decimal aggregate requires declared precision and scale");
2738
- let o = a ? i.precision : 0, s = a ? i.scale : 0, c = e.op === "avg" ? n.resultScale ?? s : s;
2739
- return {
2740
- aggregate: e,
2741
- projection: t,
2742
- index: r,
2743
- exact: a,
2744
- precision: o,
2745
- inputScale: s,
2746
- scale: c,
2747
- digits: o + 20 + Math.max(0, c - s)
2748
- };
2749
- }), _ = new Map(g.map((e) => [e.projection, e])), v = new Map(g.map((e) => [e.projection.alias, e])), y = /* @__PURE__ */ new Map(), b = s.map((e) => {
2750
- let n = _.get(e);
2751
- if (n) return y.set(e.alias, `result${n.index}.${n.exact ? "decimal_key" : "result_value"}`), t`${t(`result${n.index}.${n.exact ? "decimal_value" : "result_value"}`)} AS ${t(e.alias)}`;
2752
- let r = m.get(e.column ?? "") ?? -1;
2753
- if (r < 0) throw Error("Projected group column is absent from GROUP BY");
2754
- return y.set(e.alias, `result0.key${r}`), t`${t(`result0.key${r}`)} AS ${t(e.alias)}`;
2755
- }), x = (e) => {
2756
- if ("and" in e) return { and: e.and.map(x) };
2757
- if ("or" in e) return { or: e.or.map(x) };
2758
- if ("not" in e) return { not: x(e.not) };
2759
- if ("subquery" in e || !("column" in e) || !("op" in e)) throw Error("Decimal subquery predicates are not integrated yet");
2760
- if (Hn(e.value)) throw Error("Column references require result comparison lowering");
2761
- let t = v.get(e.column), n = y.get(e.column);
2762
- if (n === void 0) throw Error("HAVING references an unknown projected aggregate or group key");
2763
- return t?.exact ? _r({
2764
- ...e,
2765
- column: n
2766
- }, {
2767
- precision: t.digits,
2768
- scale: t.scale
2769
- }, "aggregate") : {
2770
- ...e,
2771
- column: n
2772
- };
2773
- }, S = [...g.flatMap((e) => e.aggregate.column === void 0 ? [] : [{
2774
- source: e.aggregate.column,
2775
- outputKey: `value${e.index}`
2776
- }]), ...p.map((e, t) => ({
2777
- source: e,
2778
- outputKey: `group${t}`
2779
- }))], C = S.length ? t.join(", ", !1)(S.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : t`1 AS decimal_query_row`, { from: w, where: T } = yr(e, t, o);
2780
- if (c) return br(e, t, o, i, a);
2781
- let E = t`SELECT ${C} FROM ${w}${T}`.compile(), D = (e) => "\"" + e.replace(/"/g, "\"\"") + "\"", O = p.map((e, t) => `group${t}`), k = O.map((e, t) => `${D(e)} AS ${D(`key${t}`)}`).join(","), ee = O.length ? ` GROUP BY ${O.map(D).join(",")}` : "", A = n.materialized ? "decimal_query_source" : `(${E[0]})`, j = g.map((e) => {
2782
- let { aggregate: t, index: r, precision: i, inputScale: a, scale: o, digits: s } = e, c = t.column === void 0 ? "*" : D(`value${r}`);
2783
- if (!e.exact) return `SELECT ${k ? k + "," : ""}${d[t.op]}(${t.op === "count-distinct" ? "DISTINCT " : ""}${c}) AS result_value FROM ${A}${ee}`;
2784
- let l = {
2785
- sourceSql: t.op === "min" || t.op === "max" ? `SELECT ${O.length ? O.map(D).join(",") + "," : ""}${d[t.op]}(${c}) AS value FROM ${A}${ee}` : `SELECT ${O.length ? O.map(D).join(",") + "," : ""}${c} AS value FROM ${A}`,
2786
- precision: i,
2787
- materialized: n.materialized,
2788
- ...p.length ? { scope: {
2789
- kind: "group",
2790
- columns: O
2791
- } } : {}
2792
- };
2793
- return hr({
2794
- sourceSql: t.op === "avg" ? Cr({
2795
- ...l,
2796
- inputScale: a,
2797
- resultScale: o,
2798
- rounding: n.rounding ?? "half-even"
2799
- }) : Sr(l),
2800
- digits: s,
2801
- scale: o,
2802
- materialized: n.materialized
2803
- });
2804
- }), M = [...n.materialized ? [`decimal_query_source AS MATERIALIZED (${E[0]})`] : [], ...j.map((e, t) => {
2805
- let r = n.materialized ? e : `SELECT * FROM (${e}) LIMIT -1 OFFSET 0`;
2806
- return `result${t} AS${n.materialized ? " MATERIALIZED" : ""} (${r})`;
2807
- })].join(","), N = g.slice(1).map((e) => p.length ? ` JOIN result${e.index} ON ${p.map((t, n) => `result0.${D(`key${n}`)} IS result${e.index}.${D(`key${n}`)}`).join(" AND ")}` : ` CROSS JOIN result${e.index}`).join(""), P = (e) => {
2808
- if ("not" in e) return t`NOT (${P(e.not)})`;
2809
- if ("and" in e) return e.and.length ? t.and(e.and.map(P)) : t`TRUE`;
2810
- if ("or" in e) return e.or.length ? t.or(e.or.map(P)) : t`FALSE`;
2811
- if ("subquery" in e) return or(e, t, o, (e) => {
2812
- let n = y.get(e);
2813
- if (!n) throw Error("HAVING references an unknown projected aggregate or group key");
2814
- let r = v.get(e);
2815
- return r?.exact ? {
2816
- value: t`${t(`result${r.index}.decimal_value`)}`,
2817
- scale: r.scale
2818
- } : { value: t`${t(n)}` };
2819
- });
2820
- if (!("value" in e) || !Hn(e.value)) return Kr(x(e), t);
2821
- let n = y.get(e.column), r = y.get(e.value.column);
2822
- if (n === void 0 || r === void 0) throw Error("HAVING references an unknown projected aggregate or group key");
2823
- let i = v.get(e.column), a = e.value.column, s = v.get(a);
2824
- if (!i?.exact && !s?.exact) return Kr({
2825
- ...e,
2826
- column: n,
2827
- value: {
2828
- ...e.value,
2829
- column: r
2830
- }
2831
- }, t);
2832
- if (!i?.exact || !s?.exact) throw Error("Exact aggregate comparisons require two decimal results");
2833
- if (!Un.includes(e.op) || e.path?.length) throw Error("Unsupported exact decimal result comparison");
2834
- return t.unsafe(gr({
2835
- expression: t`${t(n)}`.compile()[0],
2836
- digits: i.digits,
2837
- scale: i.scale
2838
- }, e.op, {
2839
- expression: t`${t(r)}`.compile()[0],
2840
- digits: s.digits,
2841
- scale: s.scale
2842
- }));
2843
- }, F = e.having === void 0 ? t`` : t` WHERE ${P(e.having)}`, te = e.order.length === 0 ? t`` : t` ORDER BY ${t.join(", ", !1)(e.order.map((e) => {
2844
- let n = y.get(e.column);
2845
- if (n === void 0) throw Error("Ordering references an unknown decimal result projection");
2846
- return e.direction === "desc" ? t`${t(n)} DESC` : t`${t(n)} ASC`;
2847
- }))}`;
2848
- for (let t of [e.take, e.skip]) if (t !== void 0 && (!Number.isSafeInteger(t) || t < 0)) throw Error("Invalid exact decimal pagination");
2849
- let I = e.take === void 0 ? e.skip === void 0 ? t`` : t` LIMIT -1` : t` LIMIT ${e.take}`, ne = e.skip === void 0 ? t`` : t` OFFSET ${e.skip}`, re = t`WITH ${t.unsafe(M)} SELECT ${e.distinct ? t`DISTINCT ` : t``}${t.join(", ", !1)(b)} FROM result0${t.unsafe(N)}${F}${te}${I}${ne}`.compile(), ie = n.materialized ? E[1] : g.flatMap(() => E[1]);
2850
- return t.unsafe(re[0], [...ie, ...re[1]]);
2851
- }, Er = (e, t, n, r = null) => {
2852
- let i = En(e, n.resultScale), a = new Set((i.ctes ?? []).map((e) => e.name));
2853
- return Tr(i, t, n, (e) => a.has(e) ? e : er(r, e));
2854
- }, Dr = (e) => e.replace(/[A-Z]/g, (e) => e.toLowerCase()), Or = (e, t) => {
2855
- let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
2856
- for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
2857
- return t`${i}`;
2858
- }, kr = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), $ = (e, t, n = null, r, i = /* @__PURE__ */ new Set()) => {
2859
- if ("not" in e) return t`NOT (${$(e.not, t, n, r, i)})`;
2860
- if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => $(e, t, n, r, i)));
2861
- if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => $(e, t, n, r, i)));
2862
- if (e.op === "subquery-in" || e.op === "subquery-not-in") {
2863
- let r = e, a = Wr(r.subquery, t, n, void 0, i);
2864
- return r.op === "subquery-in" ? t`${t(r.column)} IN (${a})` : t`${t(r.column)} NOT IN (${a})`;
2865
- }
2866
- if (e.op === "exists" || e.op === "not-exists") {
2867
- let r = e, a = Wr(r.subquery, t, n, void 0, i);
2868
- return r.op === "exists" ? t`EXISTS (${a})` : t`NOT EXISTS (${a})`;
2869
- }
2870
- let a = e;
2871
- if (Hn(a.value)) {
2872
- if (!Un.some((e) => e === a.op) || a.path !== void 0) throw L("Column references require a scalar comparison without a JSON path");
2873
- let e = t(a.value.column), n = t(a.column);
2874
- switch (a.op) {
2875
- case "eq": return t`${n} = ${e}`;
2876
- case "neq": return t`${n} <> ${e}`;
2877
- case "gt": return t`${n} > ${e}`;
2878
- case "gte": return t`${n} >= ${e}`;
2879
- case "lt": return t`${n} < ${e}`;
2880
- case "lte": return t`${n} <= ${e}`;
2881
- }
2882
- }
2883
- let o = t(a.column), s = a.path, c = s !== void 0 && s.length > 0, l = () => t.onDialectOrElse({
2884
- mysql: () => t.unsafe(Q(a.column, s, "mysql")),
2885
- mssql: () => t.unsafe(Q(a.column, s, "mssql")),
2886
- sqlite: () => t.unsafe(Q(a.column, s, "sqlite")),
2887
- orElse: () => t.unsafe(Q(a.column, s, "postgres"))
2888
- }), u = () => t.onDialectOrElse({
2889
- mysql: () => t.unsafe(Q(a.column, s, "mysql", { numeric: !0 })),
2890
- mssql: () => t.unsafe(Q(a.column, s, "mssql", { numeric: !0 })),
2891
- sqlite: () => t.unsafe(Q(a.column, s, "sqlite", { numeric: !0 })),
2892
- orElse: () => t.unsafe(Q(a.column, s, "postgres", { numeric: !0 }))
2893
- }), d = c ? l() : o, f = c ? u() : o, p = (e) => c && e != null ? String(e) : e, m = (e) => c ? Number(e) : e, h = c || r === void 0 ? void 0 : W(r)?.fields?.[a.column]?.type, g = (e) => {
2894
- let n = rr(h, e);
2895
- return n instanceof Date ? t.onDialectOrElse({
2896
- sqlite: () => Wn(n),
2897
- orElse: () => n
2898
- }) : n;
2899
- };
2900
- switch (a.op) {
2901
- case "eq": return t`${d} = ${p(g(a.value))}`;
2902
- case "neq": return t`${d} <> ${p(g(a.value))}`;
2903
- case "gt": return t`${f} > ${m(g(a.value))}`;
2904
- case "gte": return t`${f} >= ${m(g(a.value))}`;
2905
- case "lt": return t`${f} < ${m(g(a.value))}`;
2906
- case "lte": return t`${f} <= ${m(g(a.value))}`;
2907
- case "in": {
2908
- let e = a.value ?? [];
2909
- return e.length === 0 ? t`FALSE` : t`${d} IN ${t.in(c ? e.map((e) => p(e)) : e.map(g))}`;
2910
- }
2911
- case "notIn": {
2912
- let e = a.value ?? [];
2913
- return e.length === 0 ? t`TRUE` : t`${d} NOT IN ${t.in(c ? e.map((e) => p(e)) : e.map(g))}`;
2914
- }
2915
- case "contains": {
2916
- let e = `%${kr(typeof a.value == "string" ? a.value : String(a.value ?? ""))}%`;
2917
- return t.onDialectOrElse({
2918
- mysql: () => t`LOWER(${d}) LIKE LOWER(${e})`,
2919
- mssql: () => t`LOWER(${d}) LIKE LOWER(${e})`,
2920
- sqlite: () => t`LOWER(${d}) LIKE LOWER(${e})`,
2921
- orElse: () => t`${d} ILIKE ${e} ESCAPE '\\'`
2922
- });
2923
- }
2924
- case "startsWith": {
2925
- let e = `${kr(typeof a.value == "string" ? a.value : String(a.value ?? ""))}%`;
2926
- return t.onDialectOrElse({
2927
- mysql: () => t`${d} LIKE ${e}`,
2928
- orElse: () => t`${d} LIKE ${e} ESCAPE '\\'`
2929
- });
2930
- }
2931
- case "arrayContains": {
2932
- let e = a.value ?? [];
2933
- return e.length === 0 ? t`TRUE` : t.onDialectOrElse({
2934
- mysql: () => t`JSON_CONTAINS(${d}, ${JSON.stringify(e)})`,
2935
- mssql: () => t`(SELECT COUNT(DISTINCT value) FROM OPENJSON(${d}) WHERE value IN ${t.in(e)}) = ${e.length}`,
2936
- sqlite: () => t`(SELECT COUNT(DISTINCT value) FROM json_each(${d}) WHERE value IN ${t.in(e)}) = ${e.length}`,
2937
- orElse: () => t`${d} @> ${e}`
2938
- });
2939
- }
2940
- case "arrayOverlaps": {
2941
- let e = a.value ?? [];
2942
- return e.length === 0 ? t`FALSE` : t.onDialectOrElse({
2943
- mysql: () => t.or(e.map((e) => t`JSON_CONTAINS(${d}, ${JSON.stringify(e)})`)),
2944
- mssql: () => t`EXISTS (SELECT 1 FROM OPENJSON(${d}) WHERE value IN ${t.in(e)})`,
2945
- sqlite: () => t`EXISTS (SELECT 1 FROM json_each(${d}) WHERE value IN ${t.in(e)})`,
2946
- orElse: () => t`${d} && ${e}`
2947
- });
2948
- }
2949
- case "arrayHas": return t.onDialectOrElse({
2950
- mysql: () => t`JSON_CONTAINS(${d}, ${JSON.stringify(a.value)})`,
2951
- mssql: () => t`${a.value} IN (SELECT value FROM OPENJSON(${d}))`,
2952
- sqlite: () => t`EXISTS (SELECT 1 FROM json_each(${d}) WHERE value = ${a.value})`,
2953
- orElse: () => t`${a.value} = ANY(${d})`
2954
- });
2955
- case "isNull": return t`${d} IS NULL`;
2956
- case "isNotNull": return t`${d} IS NOT NULL`;
2957
- case "spatial": {
2958
- let e = a.value, n = t.unsafe("::geometry"), r = e.bufferMeters === void 0 ? t`${e.geom}${n}` : t`ST_Buffer(${e.geom}::geography, ${e.bufferMeters})::geometry`;
2959
- return t.onDialectOrElse({
2960
- mysql: () => {
2961
- throw L("@voltro/plugin-postgis: spatial predicates are postgres-only");
2962
- },
2963
- mssql: () => {
2964
- throw L("@voltro/plugin-postgis: spatial predicates are postgres-only");
2965
- },
2966
- sqlite: () => {
2967
- throw L("@voltro/plugin-postgis: spatial predicates are postgres-only");
2968
- },
2969
- orElse: () => e.fn === "ST_DWithin" ? t`ST_DWithin(${o}::geography, ${e.geom}::geography, ${e.distanceMeters})` : e.fn === "&&" ? t`${o}${n} && ${r}` : t`${t.unsafe(e.fn)}(${o}${n}, ${r})`
2970
- });
2971
- }
2972
- }
2973
- }, Ar = (e, t) => {
2974
- let n = [];
2975
- return e.partitionBy && e.partitionBy.length > 0 && n.push(t`PARTITION BY ${t.join(", ", !1)(e.partitionBy.map((e) => t`${t(e)}`))}`), e.orderBy && e.orderBy.length > 0 && n.push(t`ORDER BY ${t.join(", ", !1)(e.orderBy.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), n.length === 0 ? t`` : n.length === 1 ? n[0] : n.reduce((e, n, r) => r === 0 ? n : t`${e} ${n}`);
2976
- }, jr = (e, t) => t.join(", ", !1)(e.map((e) => {
2977
- let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
2978
- if (e.op.startsWith("window-")) {
2979
- let r = Ar(e.window ?? {}, t);
2980
- switch (e.op) {
2981
- case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
2982
- case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
2983
- case "window-dense-rank": return t`DENSE_RANK() OVER (${r}) AS ${t(e.alias)}`;
2984
- case "window-lag": return t`LAG(${n}, ${t.unsafe(String(e.offset ?? 1))}) OVER (${r}) AS ${t(e.alias)}`;
2985
- case "window-lead": return t`LEAD(${n}, ${t.unsafe(String(e.offset ?? 1))}) OVER (${r}) AS ${t(e.alias)}`;
2986
- case "window-sum-over": return t`SUM(${n}) OVER (${r}) AS ${t(e.alias)}`;
2987
- case "window-avg-over": return t`AVG(${n}) OVER (${r}) AS ${t(e.alias)}`;
2988
- default: throw L(`compileAggregateProjection: unknown window op '${e.op}'`);
2989
- }
2990
- }
2991
- switch (e.op) {
2992
- case "count": return t`COUNT(${n}) AS ${t(e.alias)}`;
2993
- case "count-distinct": return t`COUNT(DISTINCT ${n}) AS ${t(e.alias)}`;
2994
- case "sum": return t`SUM(${n}) AS ${t(e.alias)}`;
2995
- case "avg": return t`AVG(${n}) AS ${t(e.alias)}`;
2996
- case "min": return t`MIN(${n}) AS ${t(e.alias)}`;
2997
- case "max": return t`MAX(${n}) AS ${t(e.alias)}`;
2998
- case "column":
2999
- if (e.column === void 0) throw L(`compileAggregateProjection: 'column' projection requires a column name (alias '${e.alias}')`);
3000
- return t`${t(e.column)} AS ${t(e.alias)}`;
3001
- default: throw L(`compileAggregateProjection: unknown op '${e.op}'`);
3002
- }
3003
- })), Mr = (e) => `[${e.join(",")}]`, Nr = (e, t) => {
3004
- if (e.queryVector === void 0) return null;
3005
- let n = t(e.column), r = Mr(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
3006
- return t.onDialectOrElse({
3007
- mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
3008
- mssql: () => t`NULL`,
3009
- sqlite: () => t`NULL`,
3010
- orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
3011
- });
3012
- }, Pr = (e, t) => {
3013
- let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
3014
- return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
3015
- }, Fr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Ir = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Lr = (e, t) => `${t}_${e.indexName}_fts`, Rr = (e) => e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((e) => e !== ""), zr = (e) => {
3016
- if (e.prefix !== !0) return;
3017
- let t = Rr(e.query);
3018
- if (t.length !== 0) return {
3019
- pg: t.map((e) => `${e}:*`).join(" & "),
3020
- mysql: t.map((e) => `+${e}*`).join(" "),
3021
- sqlite: t.map((e) => `"${e}"*`).join(" ")
3022
- };
3023
- }, Br = (e, t, n) => {
3024
- let r = n.join(", ", !1)(e.columns.map((e) => n`${n(e)}`)), i = `%${kr(e.query)}%`, a = zr(e), o = () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`));
3025
- return e.fallback === "like" ? o() : n.onDialectOrElse({
3026
- mysql: () => a === void 0 ? n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)` : n`MATCH(${r}) AGAINST(${a.mysql} IN BOOLEAN MODE)`,
3027
- sqlite: () => {
3028
- let r = n(Lr(e, t));
3029
- return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${a?.sqlite ?? e.query})`;
3030
- },
3031
- mssql: o,
3032
- orElse: () => a === void 0 ? n`${Ir(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})` : n`${Ir(e, n)} @@ to_tsquery(${e.config ?? "english"}, ${a.pg})`
3033
- });
3034
- }, Vr = (e, t, n) => {
3035
- let r = `%${kr(e.query)}%`, i = zr(e), a = () => e.columns.map((e) => n`(CASE WHEN LOWER(${n(e)}) LIKE LOWER(${r}) ESCAPE '\\' THEN 1 ELSE 0 END)`).reduce((e, t, r) => r === 0 ? t : n`${e} + ${t}`);
3036
- return e.fallback === "like" ? a() : n.onDialectOrElse({
3037
- mysql: () => i === void 0 ? n`MATCH(${n.join(", ", !1)(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)` : n`MATCH(${n.join(", ", !1)(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${i.mysql} IN BOOLEAN MODE)`,
3038
- sqlite: () => {
3039
- let r = n(Lr(e, t));
3040
- return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${i?.sqlite ?? e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
3041
- },
3042
- mssql: a,
3043
- orElse: () => i === void 0 ? n`ts_rank(${Ir(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))` : n`ts_rank(${Ir(e, n)}, to_tsquery(${e.config ?? "english"}, ${i.pg}))`
3044
- });
3045
- }, Hr = (e, t, n, r, i = !1) => {
3046
- let a = (e) => t(r && !e.includes(".") ? `${r}.${e}` : e), o = () => n?.length ? t.join(", ", !1)(n.map((e) => t`${a(e)}`)) : r ? t`${t(r)}.*` : t`*`, s = i && t.onDialectOrElse({
3047
- mssql: () => !0,
3048
- orElse: () => !1
3049
- });
3050
- return !e || !Object.values(e).some((e) => e.type === "bigint" || s && e.type === "decimal") ? o() : t.onDialectOrElse({
3051
- sqlite: () => t.join(", ", !1)((n?.length ? n : Object.keys(e)).map((n) => e[n]?.type === "bigint" ? t`CAST(${a(n)} AS TEXT) AS ${t(n)}` : t`${a(n)}`)),
3052
- mssql: () => s && Object.values(e).some((e) => e.type === "decimal") ? t.join(", ", !1)((n?.length ? n : Object.keys(e)).map((n) => e[n]?.type === "decimal" ? t`CONVERT(varchar(80), ${a(n)}) AS ${t(n)}` : t`${a(n)}`)) : o(),
3053
- orElse: o
3054
- });
3055
- }, Ur = (e, t, n) => Hr(W(e)?.fields, t, n), Wr = (e, t, n = null, r, i = /* @__PURE__ */ new Set(), a = !1) => {
3056
- let o = yn(e), s = /* @__PURE__ */ new Set([...i, ...(e.ctes ?? []).map((e) => Dr(e.name))]), c = (e) => s.has(Dr(e)) ? e : er(n, e), l = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Wr(e.descriptor, t, n, e.recursive && t.onDialectOrElse({
3057
- sqlite: () => !0,
3058
- orElse: () => !1
3059
- }) ? e.name : void 0, s)})`), u = (e.ctes ?? []).some((e) => e.recursive === !0), d = l.length > 0 ? t`WITH ${t.unsafe(u ? "RECURSIVE " : "")}${t.join(", ", !1)(l)} ` : t``;
3060
- if (e.setOp && e.setOp.queries.length >= 2) {
3061
- let i = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", a = t.onDialectOrElse({
3062
- sqlite: () => !0,
3063
- orElse: () => !1
3064
- }), o = e.setOp.queries.map((e) => {
3065
- if (!a) return t`(${Wr(e, t, n, void 0, s)})`;
3066
- if (r !== void 0) {
3067
- if (!(It(e).length > 0 || e.take !== void 0 || e.skip !== void 0 || e.setOp !== void 0 || (e.ctes?.length ?? 0) > 0)) return Wr(e, t, n, void 0, s);
3068
- let i = (e) => e.replace(/[A-Z]/g, (e) => e.toLowerCase()), a = (e) => i(e) === i(r);
3069
- if (a(e.table) || e.joins?.some((e) => a(e.table))) throw L("Recursive SQLite terms cannot use branch-local ordering, pagination or nested compounds; apply ordering and pagination to the recursive compound or its outer query");
3070
- }
3071
- return t`SELECT * FROM (${Wr(e, t, n, void 0, s)})`;
3072
- }).reduce((e, n, r) => r === 0 ? n : t`${e} ${t.unsafe(i)} ${n}`), c = [];
3073
- if (It(e).length > 0 && c.push(t` ORDER BY ${t.join(", ", !1)(It(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
3074
- if (!Number.isInteger(e.take) || e.take < 0) throw L(`compileSelect: invalid take ${e.take}`);
3075
- c.push(t` LIMIT ${t.unsafe(String(e.take))}`);
3076
- }
3077
- if (e.skip !== void 0) {
3078
- if (a && e.take === void 0 && c.push(t` LIMIT -1`), !Number.isInteger(e.skip) || e.skip < 0) throw L(`compileSelect: invalid skip ${e.skip}`);
3079
- c.push(t` OFFSET ${t.unsafe(String(e.skip))}`);
3080
- }
3081
- return t`${d}${o}${c.reduce((e, n) => t`${e}${n}`, t``)}`;
3082
- }
3083
- let f = e.annClause === void 0 ? null : Nr(e.annClause, t);
3084
- e.spatialClause !== void 0 && t.onDialectOrElse({
3085
- mysql: () => {
3086
- throw L("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
3087
- },
3088
- mssql: () => {
3089
- throw L("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
3090
- },
3091
- sqlite: () => {
3092
- throw L("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
3093
- },
3094
- orElse: () => t``
3095
- });
3096
- let p = e.spatialClause?.projectAs === void 0 ? null : Pr(e.spatialClause, t), m = e.aggregations && e.aggregations.length > 0 ? jr(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.join(", ", !1)(e.joinedProjection.map((e) => {
3097
- let n = t`${t(e.source)}`, r = o(e.source);
3098
- return t`${a && r?.type === "decimal" ? t.onDialectOrElse({
3099
- mssql: () => t`CONVERT(varchar(80), ${n})`,
3100
- orElse: () => n
3101
- }) : r?.type === "bigint" ? t.onDialectOrElse({
3102
- sqlite: () => t`CAST(${n} AS TEXT)`,
3103
- orElse: () => n
3104
- }) : n} AS ${t(e.outputKey)}`;
3105
- })) : Hr((e.sourceTable?.tableName === e.table ? e.sourceTable : W(e.table))?.fields, t, e.projection, (e.joins?.length ?? 0) > 0 ? e.alias ?? e.table : void 0, a), h = (e.aggregations && e.aggregations.length > 0) === !0, g = f !== null && !h ? t`${m}, ${f} AS ${t("distance")}` : m, _ = e.fullTextSearch, v = _?.rank !== void 0 && !h ? Vr(_, e.table, t) : null, y = v !== null && _?.rank !== void 0 ? t`${g}, ${v} AS ${t(_.rank.alias)}` : g, b = p !== null && !h && e.spatialClause?.projectAs !== void 0 ? t`${y}, ${p} AS ${t(e.spatialClause.projectAs)}` : y, x = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
3106
- orElse: () => t`DISTINCT ON (${t.join(", ", !1)(e.distinctOn.map((e) => t`${t(e)}`))}) `,
3107
- mysql: () => t`DISTINCT `,
3108
- mssql: () => t`DISTINCT `,
3109
- sqlite: () => t`DISTINCT `
3110
- }) : e.distinct ? t`DISTINCT ` : t``, S = e.lock === "update", C = S ? t.onDialectOrElse({
3111
- mssql: () => t` WITH (UPDLOCK, ROWLOCK)`,
3112
- orElse: () => t``
3113
- }) : t``, w = S ? t.onDialectOrElse({
3114
- mssql: () => t``,
3115
- sqlite: () => t``,
3116
- orElse: () => t` FOR UPDATE`
3117
- }) : t``, T = e.alias === void 0 ? t`${t(c(e.table))}${C}` : t`${t(c(e.table))} AS ${t(e.alias)}${C}`, E = (e.joins ?? []).map((e) => {
3118
- let r = e.kind === "inner" ? "INNER" : "LEFT";
3119
- return t` ${t.unsafe(r)} JOIN ${t(c(e.table))} AS ${t(e.alias)} ON ${$(e.on, t, n, void 0, s)}`;
3120
- }), D = E.length > 0 ? E.reduce((e, n) => t`${e}${n}`, T) : T, O = _ === void 0 ? null : Br(_, e.table, t), k = [e.predicate ? $(e.predicate, t, n, e.table, s) : null, O].filter((e) => e !== null), ee = k.length > 0 ? t` WHERE ${t.and(k)}` : t``, A = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.join(", ", !1)(e.groupBy.map((e) => t`${t(e)}`))}` : t``, j = e.having ? t` HAVING ${$(e.having, t, n, e.table, s)}` : t``, M = e.skip !== void 0, N = [];
3121
- f !== null && N.push(t`${f} ASC`), e.spatialClause?.order !== void 0 && N.push(e.spatialClause.order === "desc" ? t`${Fr(e.spatialClause, t)} DESC` : t`${Fr(e.spatialClause, t)} ASC`), v !== null && _?.rank?.order === !0 && N.push(t`${v} DESC`);
3122
- let P = It(e), F = P.length >= 8 && (e.joinedProjection?.length ?? 0) >= 8 ? /* @__PURE__ */ new Map() : void 0;
3123
- if (F) for (let t of e.joinedProjection ?? []) F.has(t.outputKey) || F.set(t.outputKey, t.source);
3124
- for (let n of P) {
3125
- let r = (F === void 0 ? e.joinedProjection?.find((e) => e.outputKey === n.column)?.source : F.get(n.column)) ?? n.column, i = a && !h && o(r)?.type === "decimal" ? t.onDialectOrElse({
3126
- mssql: () => t`${t(r.includes(".") ? r : `${e.alias ?? e.table}.${r}`)}`,
3127
- orElse: () => t`${t(n.column)}`
3128
- }) : !h && o(r)?.type === "bigint" ? t.onDialectOrElse({
3129
- sqlite: () => t`${t(r.includes(".") ? r : `${e.alias ?? e.table}.${r}`)}`,
3130
- orElse: () => t`${t(n.column)}`
3131
- }) : t`${t(n.column)}`;
3132
- N.push(n.direction === "desc" ? t`${i} DESC` : t`${i} ASC`);
3133
- }
3134
- let te = N.length > 0 ? t` ORDER BY ${t.join(", ", !1)(N)}` : M ? t.onDialectOrElse({
3135
- mssql: () => t` ORDER BY (SELECT NULL)`,
3136
- orElse: () => t``
3137
- }) : t``, I = (e) => {
3138
- if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw L(`compileSelect: expected non-negative integer take/skip, got ${e}`);
3139
- return t.unsafe(String(e));
3140
- };
3141
- return t.onDialectOrElse({
3142
- mssql: () => {
3143
- let n = e.take !== void 0 && !M ? t`TOP ${I(e.take)} ` : t``, r = M ? t` OFFSET ${I(e.skip)} ROWS FETCH NEXT ${I(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
3144
- return t`${d}SELECT ${n}${x}${b} FROM ${D}${ee}${A}${j}${te}${r}`;
3145
- },
3146
- orElse: () => {
3147
- let n = e.take === void 0 ? M ? t.onDialectOrElse({
3148
- sqlite: () => t` LIMIT -1`,
3149
- mysql: () => t` LIMIT 18446744073709551615`,
3150
- orElse: () => t``
3151
- }) : t`` : t` LIMIT ${I(e.take)}`, r = M ? t` OFFSET ${I(e.skip)}` : t``;
3152
- return t`${d}SELECT ${x}${b} FROM ${D}${ee}${A}${j}${te}${n}${r}${w}`;
3153
- }
3154
- });
3155
- }, Gr = (e, t, n = null) => t.onDialectOrElse({
3156
- sqlite: () => !0,
3157
- orElse: () => !1
3158
- }) && Sn(e) ? t`${Er(e, t, { materialized: !1 }, n)}` : Wr(t.onDialectOrElse({
3159
- mssql: () => ar(e) ?? e,
3160
- orElse: () => e
3161
- }), t, n, void 0, /* @__PURE__ */ new Set(), !0), Kr = (e, t, n = null, r) => {
3162
- if (r !== void 0 && t.onDialectOrElse({
3163
- sqlite: () => !0,
3164
- orElse: () => !1
3165
- })) {
3166
- let i = {
3167
- table: r,
3168
- predicate: e,
3169
- order: [],
3170
- projection: void 0,
3171
- take: void 0,
3172
- skip: void 0
3173
- };
3174
- if (Sn(i)) return vr(i, t, {
3175
- compile: (e) => Gr(e, t, n),
3176
- resultScale: void 0
3177
- }, e);
3178
- }
3179
- return $(e, t, n, r);
3180
- }, qr = (e, t, n = null, r) => $(e, t, n, r), Jr = (e, t) => ({
3181
- column: e,
3182
- op: "eq",
3183
- value: t
3184
- }), Yr = (e, t) => ({
3185
- column: e,
3186
- op: "neq",
3187
- value: t
3188
- }), Xr = (e, t) => ({
3189
- column: e,
3190
- op: "gt",
3191
- value: t
3192
- }), Zr = (e, t) => ({
3193
- column: e,
3194
- op: "gte",
3195
- value: t
3196
- }), Qr = (e, t) => ({
3197
- column: e,
3198
- op: "lt",
3199
- value: t
3200
- }), $r = (e, t) => ({
3201
- column: e,
3202
- op: "lte",
3203
- value: t
3204
- }), ei = (e, t) => ({
3205
- column: e,
3206
- op: "in",
3207
- value: t
3208
- }), ti = (e, t) => ({
3209
- column: e,
3210
- op: "notIn",
3211
- value: t
3212
- }), ni = (e, t) => ({
3213
- column: e,
3214
- op: "contains",
3215
- value: t
3216
- }), ri = (e, t) => ({
3217
- column: e,
3218
- op: "startsWith",
3219
- value: t
3220
- }), ii = (e, t) => ({
3221
- column: e,
3222
- op: "arrayContains",
3223
- value: t
3224
- }), ai = (e, t) => ({
3225
- column: e,
3226
- op: "arrayOverlaps",
3227
- value: t
3228
- }), oi = (e, t) => ({
3229
- column: e,
3230
- op: "arrayHas",
3231
- value: t
3232
- }), si = {
3233
- column: "id",
3234
- op: "in",
3235
- value: []
3236
- }, ci = (e) => ({
3237
- column: e,
3238
- op: "isNull"
3239
- }), li = (e) => ({
3240
- column: e,
3241
- op: "isNotNull"
3242
- }), ui = (e, t) => ({
3243
- column: e,
3244
- op: "spatial",
3245
- value: t
3246
- }), di = (...e) => ({ and: e }), fi = (...e) => ({ or: e }), pi = (e) => ({ not: e }), mi = (e, ...t) => {
3247
- if (t.length === 0) throw L(`jsonField("${e}"): at least one path segment is required`);
3248
- let n = (n, r) => ({
3249
- column: e,
3250
- path: t,
3251
- op: n,
3252
- value: r
3253
- });
3254
- return {
3255
- eq: (e) => n("eq", e),
3256
- neq: (e) => n("neq", e),
3257
- gt: (e) => n("gt", e),
3258
- gte: (e) => n("gte", e),
3259
- lt: (e) => n("lt", e),
3260
- lte: (e) => n("lte", e),
3261
- inSet: (e) => n("in", e),
3262
- notInSet: (e) => n("notIn", e),
3263
- contains: (e) => n("contains", e),
3264
- startsWith: (e) => n("startsWith", e),
3265
- isNull: () => n("isNull"),
3266
- isNotNull: () => n("isNotNull")
3267
- };
3268
- }, hi = (e) => "descriptor" in e ? e.descriptor : e, gi = (e, t) => ({
3269
- column: e,
3270
- op: "subquery-in",
3271
- subquery: hi(t)
3272
- }), _i = (e, t) => ({
3273
- column: e,
3274
- op: "subquery-not-in",
3275
- subquery: hi(t)
3276
- }), vi = (e) => ({
3277
- op: "exists",
3278
- subquery: hi(e)
3279
- }), yi = (e) => ({
3280
- op: "not-exists",
3281
- subquery: hi(e)
3282
- }), bi = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/, xi = (e) => {
3283
- if (e instanceof Date) return e.getTime();
3284
- if (typeof e == "string" && bi.test(e)) {
3285
- let t = Date.parse(e);
3286
- return Number.isNaN(t) ? void 0 : t;
3287
- }
3288
- }, Si = (e, t) => {
3289
- if (!(e instanceof Date) && !(t instanceof Date)) return;
3290
- let n = xi(e), r = xi(t);
3291
- return n === void 0 || r === void 0 ? void 0 : [n, r];
3292
- }, Ci = (e, t) => {
3293
- if (e === t) return !0;
3294
- if (e instanceof Uint8Array && t instanceof Uint8Array) {
3295
- if (e.length !== t.length) return !1;
3296
- for (let n = 0; n < e.length; n += 1) if (e[n] !== t[n]) return !1;
3297
- return !0;
3298
- }
3299
- let n = Si(e, t);
3300
- return n !== void 0 && n[0] === n[1];
3301
- }, wi = (e, t) => {
3302
- if (e == null || t == null) return null;
3303
- let n = Si(e, t);
3304
- if (n !== void 0) return n[0] === n[1] ? 0 : n[0] > n[1] ? 1 : -1;
3305
- let r = e instanceof Date ? e.getTime() : e, i = t instanceof Date ? t.getTime() : t;
3306
- return typeof r == typeof i ? r === i ? 0 : r > i ? 1 : -1 : null;
3307
- }, Ti = (e, t, n = null, r = {}) => Oi(e, t, n, r) === !0, Ei = (e, t = null, n = {}) => {
3308
- let r = /* @__PURE__ */ new Map(), i = (e) => {
3309
- if ("not" in e) {
3310
- i(e.not);
3311
- return;
3312
- }
3313
- if ("and" in e) {
3314
- e.and.forEach(i);
3315
- return;
3316
- }
3317
- if ("or" in e) {
3318
- e.or.forEach(i);
3319
- return;
3320
- }
3321
- if (e.op !== "in" && e.op !== "notIn" || n[e.column]?.type === "decimal") return;
3322
- let t = Object.getOwnPropertyDescriptor(e, "value");
3323
- if (t === void 0 || !("value" in t)) return;
3324
- let a = t.value;
3325
- if (!Array.isArray(a) || a.length < 16 || Object.getPrototypeOf(a) !== Array.prototype) return;
3326
- let o = Object.getOwnPropertyDescriptor(a, "some");
3327
- if (o !== void 0 && (!("value" in o) || o.value !== Array.prototype.some)) return;
3328
- for (let e = 0; e < a.length; e++) {
3329
- let t = Object.getOwnPropertyDescriptor(a, e);
3330
- if (t !== void 0 && !("value" in t)) return;
3331
- }
3332
- if (a.some((e) => typeof e == "object" && !!e)) return;
3333
- let s = Array.prototype.filter.call(a, (e) => !(typeof e == "number" && Number.isNaN(e)));
3334
- r.set(e, new Set(s));
3335
- };
3336
- return i(e), (i) => Oi(e, i, t, n, r) === !0;
3337
- }, Di = (e, t, n) => {
3338
- if (e.length < 128 || t.length < 16 || Object.getPrototypeOf(e) !== Array.prototype || Object.getPrototypeOf(t) !== Array.prototype || Object.getOwnPropertyDescriptor(e, "includes") !== void 0 || Object.getOwnPropertyDescriptor(t, n) !== void 0) return;
3339
- for (let n of [e, t]) for (let e = 0; e < n.length; e += 1) {
3340
- let t = Object.getOwnPropertyDescriptor(n, String(e));
3341
- if (t === void 0 || !("value" in t)) return;
3342
- }
3343
- let r = /* @__PURE__ */ new Set();
3344
- for (let t = 0; t < e.length; t += 1) r.add(e[t]);
3345
- return r;
3346
- }, Oi = (e, t, n = null, r = {}, i) => {
3347
- if (!t) return !1;
3348
- if ("not" in e) {
3349
- let a = Oi(e.not, t, n, r, i);
3350
- return a === null ? null : !a;
3351
- }
3352
- if ("and" in e) {
3353
- let a = !1;
3354
- for (let o of e.and) {
3355
- let e = Oi(o, t, n, r, i);
3356
- if (e === !1) return !1;
3357
- e === null && (a = !0);
3358
- }
3359
- return !a || null;
3360
- }
3361
- if ("or" in e) {
3362
- let a = !1;
3363
- for (let o of e.or) {
3364
- let e = Oi(o, t, n, r, i);
3365
- if (e === !0) return !0;
3366
- e === null && (a = !0);
3367
- }
3368
- return a ? null : !1;
3369
- }
3370
- if (e.op === "subquery-in" || e.op === "subquery-not-in") {
3371
- if (!n) return !1;
3372
- let i = n.get(e.subquery);
3373
- if (!(i instanceof Set)) return !1;
3374
- let a = t[e.column], o = r[e.column]?.type === "decimal" ? [...i].some((e) => zn(a, e) === 0) : i.has(a);
3375
- return e.op === "subquery-in" ? o : !o;
3376
- }
3377
- if (e.op === "exists" || e.op === "not-exists") {
3378
- if (!n) return !1;
3379
- let t = n.get(e.subquery), r = typeof t == "number" ? t > 0 : t instanceof Set && t.size > 0;
3380
- return e.op === "exists" ? r : !r;
3381
- }
3382
- let a = e, o = t[a.column], s = Hn(a.value) ? a.value : void 0;
3383
- if (s !== void 0 && (!Un.some((e) => e === a.op) || a.path !== void 0)) throw L("Column references require a scalar comparison without a JSON path");
3384
- let c = s === void 0 ? a.value : t[s.column];
3385
- if (s !== void 0 && (o == null || c == null)) return null;
3386
- let l = r[a.column]?.type === "decimal", u = i?.get(e);
3387
- if (u !== void 0 && !(o instanceof Date) && !(o instanceof Uint8Array)) {
3388
- let e = typeof o == "number" && Number.isNaN(o) ? !1 : u.has(o);
3389
- return a.op === "in" ? e : !e;
3390
- }
3391
- let d = (e, t) => l && e != null && t != null ? zn(e, t) === 0 : Ci(e, t), f = l ? zn : wi;
3392
- switch (a.op) {
3393
- case "eq": return d(o, c);
3394
- case "neq": return !d(o, c);
3395
- case "gt": return (f(o, c) ?? -1) > 0;
3396
- case "gte": return (f(o, c) ?? -1) >= 0;
3397
- case "lt": return (f(o, c) ?? 1) < 0;
3398
- case "lte": return (f(o, c) ?? 1) <= 0;
3399
- case "in": return Array.isArray(c) && c.some((e) => d(o, e));
3400
- case "notIn": return Array.isArray(c) && !c.some((e) => d(o, e));
3401
- case "contains": return typeof o == "string" && typeof c == "string" && o.toLowerCase().includes(c.toLowerCase());
3402
- case "startsWith": return typeof o == "string" && typeof c == "string" && o.startsWith(c);
3403
- case "arrayContains": {
3404
- let e = Array.isArray(o) ? o : [], t = Array.isArray(c) ? c : [];
3405
- if (e.length < 128 || t.length < 16) return t.every((t) => e.includes(t));
3406
- let n, r = 0;
3407
- return t.every((i) => (++r === 5 && (n = Di(e, t, "every")), n === void 0 ? e.includes(i) : n.has(i)));
3408
- }
3409
- case "arrayOverlaps": {
3410
- let e = Array.isArray(o) ? o : [], t = Array.isArray(c) ? c : [];
3411
- if (e.length < 128 || t.length < 16) return t.some((t) => e.includes(t));
3412
- let n, r = 0;
3413
- return t.some((i) => (++r === 5 && (n = Di(e, t, "some")), n === void 0 ? e.includes(i) : n.has(i)));
3414
- }
3415
- case "arrayHas": return Array.isArray(o) && o.includes(c);
3416
- case "isNull": return o == null;
3417
- case "isNotNull": return o != null;
3418
- case "spatial": throw L("@voltro/plugin-postgis: spatial predicates (ST_DWithin / ST_Contains / ST_Within / ST_Intersects / bbox &&) are not evaluable in-memory — use them in one-shot ctx.store.query reads, not reactive subscriptions.");
3419
- }
3420
- }, ki = function* (e) {
3421
- if ("not" in e) {
3422
- yield* ki(e.not);
3423
- return;
3424
- }
3425
- if ("and" in e) {
3426
- for (let t of e.and) yield* ki(t);
3427
- return;
3428
- }
3429
- if ("or" in e) {
3430
- for (let t of e.or) yield* ki(t);
3431
- return;
3432
- }
3433
- e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
3434
- kind: "in",
3435
- descriptor: e.subquery
3436
- } : (e.op === "exists" || e.op === "not-exists") && (yield {
3437
- kind: "exists",
3438
- descriptor: e.subquery
3439
- });
3440
- }, Ai = function* (e, t = !0) {
3441
- if ("not" in e) {
3442
- yield* Ai(e.not, !1);
3443
- return;
3444
- }
3445
- if ("and" in e) {
3446
- for (let n of e.and) yield* Ai(n, t);
3447
- return;
3448
- }
3449
- if ("or" in e) {
3450
- for (let t of e.or) yield* Ai(t, !1);
3451
- return;
3452
- }
3453
- e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
3454
- ...e,
3455
- conjunctive: t && !Hn(e.value)
3456
- });
3457
- }, ji = (e, t) => ({
3458
- name: e,
3459
- body: t
3460
- }), Mi = (e) => {
3461
- if (e.lifecycle === "cron" && !e.cron) throw Error(`seed "${e.id}": lifecycle 'cron' requires a 'cron' field`);
3462
- if (e.lifecycle === "onSchemaChange" && (!e.watchedTables || e.watchedTables.length === 0)) throw Error(`seed "${e.id}": lifecycle 'onSchemaChange' requires at least one entry in 'watchedTables'`);
3463
- let t = e.steps({ step: ji });
3464
- if (t.length === 0) throw Error(`seed "${e.id}": at least one step is required`);
3465
- return {
3466
- __seed: !0,
3467
- id: e.id,
3468
- name: e.name,
3469
- lifecycle: e.lifecycle,
3470
- ...e.cron === void 0 ? {} : { cron: e.cron },
3471
- ...e.timezone === void 0 ? {} : { timezone: e.timezone },
3472
- ...e.watchedTables === void 0 ? {} : { watchedTables: e.watchedTables },
3473
- ...e.fingerprint === void 0 ? {} : { fingerprint: e.fingerprint },
3474
- steps: t
3475
- };
3476
- }, Ni = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, Pi = null, Fi = null, Ii = (e) => {
3477
- Pi = e;
3478
- }, Li = (e) => {
3479
- Fi = e;
3480
- }, Ri = async (e) => {
3481
- let t = Pi;
3482
- t !== null && await t(e);
3483
- }, zi = async (e) => {
3484
- let t = Fi;
3485
- t !== null && e.changedTables.length !== 0 && await t(e);
3486
- }, Bi = ["before-schema", "after-schema"], Vi = (e) => {
3487
- if (!e.id || e.id.length === 0) throw Error("migration: `id` is required + must be non-empty");
3488
- if (!e.up || !e.down) throw Error(`migration ${e.id}: both \`up\` and \`down\` must be functions`);
3489
- if (!Bi.includes(e.phase)) throw Error(`migration ${e.id}: \`phase\` is required and must be one of ${Bi.map((e) => `'${e}'`).join(" | ")} — 'before-schema' runs before the declarative apply (a shape change the planner must not compute against), 'after-schema' runs after it (a body that needs the new shape, such as a back-fill into a table this deploy creates)`);
3490
- return e;
3491
- }, Hi = Symbol.for("voltro.migration.irreversible"), Ui = class extends Error {
3492
- migrationId;
3493
- reason;
3494
- _tag = "IrreversibleMigrationError";
3495
- constructor(e, t) {
3496
- super(`migration ${e} cannot be rolled back: ${t}`), this.migrationId = e, this.reason = t, this.name = "IrreversibleMigrationError";
3497
- }
3498
- }, Wi = (e) => {
3499
- if (!e || e.trim().length === 0) throw Error("irreversible(): a reason is required");
3500
- return Object.assign(() => t.fail(new Ui("<unknown>", e)), { [Hi]: e });
3501
- }, Gi = (e) => {
3502
- let t = e[Hi];
3503
- return typeof t == "string" ? t : void 0;
3504
- }, Ki = class {
3505
- reason;
3506
- _tag = "MigrationSkipped";
3507
- constructor(e) {
3508
- this.reason = e;
3509
- }
3510
- }, qi = class extends Error {
3511
- migrationId;
3512
- failed;
3513
- _tag = "MigrationExpectationFailed";
3514
- constructor(e, t) {
3515
- super(`migration ${e}: ${t.length} post-condition(s) did not hold after up():\n` + t.map((e) => ` - ${e}`).join("\n") + "\n The migration is NOT recorded; the next run applies it again."), this.migrationId = e, this.failed = t, this.name = "MigrationExpectationFailed";
3516
- }
3517
- }, Ji = class extends Error {
3518
- migrationId;
3519
- dialect;
3520
- _tag = "TransactionBrokenByBodyError";
3521
- constructor(e, t) {
3522
- super(`migration ${e} is transactional, and its body COMMITTED the transaction from inside — on ${t} a DDL statement commits everything before it. The work is in the database and the migration is recorded; it will not run again. What did not hold is the all-or-nothing guarantee. Either mark it \`transactional: false\` (per-statement, resumable through your own idempotency) or move the schema change into \`ctx.schema\` in a migration of its own and keep this one to data.`), this.migrationId = e, this.dialect = t, this.name = "TransactionBrokenByBodyError";
3523
- }
3524
- }, Yi = class extends Error {
3525
- migrationId;
3526
- operation;
3527
- _tag = "MigrationNeedsSqlClient";
3528
- constructor(e, t, n) {
3529
- super(`migration ${e}: ${t} — ${n}`), this.migrationId = e, this.operation = t, this.name = "MigrationNeedsSqlClient";
3530
- }
3531
- }, Xi = class extends Error {
3532
- table;
3533
- report;
3534
- _tag = "RewriteUnstableError";
3535
- constructor(e, t) {
3536
- super(`rewrite of ${e} did not stabilise after ${t.passes} pass(es): ${t.rewritten} rewritten, ${t.contended} contended on the last pass. Check for concurrent writes and guard values that cannot round-trip exactly before raising maxPasses.`), this.table = e, this.report = t, this.name = "RewriteUnstableError";
3537
- }
3538
- }, Zi = /^\d{8}_\d{6}_[a-z0-9_]+\.ts$/, Qi = (e) => typeof e == "object" && !!e && "id" in e && "up" in e && "down" in e && typeof e.id == "string" && typeof e.up == "function" && typeof e.down == "function", $i = /* @__PURE__ */ new Set(["voltro_isr_cache"]), ea = (e) => $i.has(e) || e.startsWith("_voltro_") || e.startsWith("_cloud_") || e.startsWith("cluster_") || e.startsWith("__turso_internal_"), ta = "_voltro_staging_", na = (e) => e.startsWith(ta), ra = /__dropped_\d{14}$/, ia = (e) => ra.test(e), aa = 7, oa = (e) => {
3539
- let t = /__dropped_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/.exec(e);
3540
- if (t === null) return;
3541
- let [, n, r, i, a, o, s] = t;
3542
- return new Date(Date.UTC(Number(n), Number(r) - 1, Number(i), Number(a), Number(o), Number(s)));
3543
- }, sa = (e, t = {}) => {
3544
- let n = t.now ?? /* @__PURE__ */ new Date(), r = t.retentionDays ?? 7, i = [], a = (e, t) => {
3545
- let a = oa(e);
3546
- if (a === void 0) return;
3547
- let o = Math.floor((n.getTime() - a.getTime()) / 864e5);
3548
- o >= r && i.push({
3549
- name: t,
3550
- droppedAt: a,
3551
- ageDays: o
3552
- });
3553
- };
3554
- for (let t of e.tables) if (a(t.name, t.name), !ia(t.name)) for (let e of t.columns ?? []) a(e.name, `${t.name}.${e.name}`);
3555
- return i;
3556
- }, ca = (e, t) => {
3557
- let n = e.reduce((e, t) => e.ageDays >= t.ageDays ? e : t), r = (/* @__PURE__ */ new Date(Date.now() - t * 864e5)).toISOString().slice(0, 10);
3558
- return `${e.length} soft-drop snapshot(s) older than ${t} day(s) still hold the dropped data (oldest: ${n.name}, ${n.ageDays}d) — ${e.map((e) => e.name).join(", ")}. Restore with \`voltro db restore-snapshot\` or reclaim with \`voltro db gc-snapshots --before ${r}\`; the window is \`database.softDropRetentionDays\` in app.config.`;
3559
- }, la = (e, t) => e.filter((e) => !ea(e.name) || t.has(e.name)), ua = (e, t) => new s({ reason: new c({
3560
- cause: t ?? Error(e),
3561
- message: e
3562
- }) }), da = H("_voltro_migrations", {
3563
- id: h({ prefix: "mig" }),
3564
- name: g(),
3565
- hash: g(),
3566
- status: g(),
3567
- appliedAt: w().nullable(),
3568
- durationMs: _().nullable(),
3569
- errorMessage: g().nullable(),
3570
- errorStack: g().nullable(),
3571
- workflowRunId: g().nullable(),
3572
- createdAt: w().default("now"),
3573
- updatedAt: w().default("now").onUpdate("now")
3574
- }).index(["status"]), fa = H("_voltro_seeds", {
3575
- id: h({ prefix: "seed" }),
3576
- name: g(),
3577
- lifecycle: g(),
3578
- fingerprint: g(),
3579
- cronSchedule: g().nullable(),
3580
- watchedTables: E().nullable(),
3581
- nextRunAt: w().nullable(),
3582
- lastRunStatus: g().nullable(),
3583
- lastRunAt: w().nullable(),
3584
- lastRunDurationMs: _().nullable(),
3585
- lastRunRowsTouched: _().nullable(),
3586
- lastError: g().nullable(),
3587
- workflowRunId: g().nullable(),
3588
- createdAt: w().default("now"),
3589
- updatedAt: w().default("now").onUpdate("now")
3590
- }).index(["lifecycle"]).index(["nextRunAt"]), pa = H("_voltro_schema_owner", {
3591
- id: h({ prefix: "own" }),
3592
- appName: g(),
3593
- projectName: g().nullable(),
3594
- frameworkVersion: g().nullable(),
3595
- claimedAt: w().default("now")
3596
- }), ma = H("_voltro_plugin_migrations", {
3597
- id: h({ prefix: "plm" }),
3598
- plugin_name: g(),
3599
- migration_id: g(),
3600
- description: g().nullable(),
3601
- applied_at: g()
3602
- }), ha = H("_voltro_migration_plans", {
3603
- id: h({ prefix: "plan" }),
3604
- fingerprint: g(),
3605
- liveFingerprint: g().nullable(),
3606
- operations: E(),
3607
- rollbackPlan: E().nullable(),
3608
- appliedBy: g(),
3609
- environment: g(),
3610
- source: g(),
3611
- onlineStrategy: g().nullable(),
3612
- durationMs: _(),
3613
- notes: g().nullable(),
3614
- squashedAt: w().nullable(),
3615
- appliedAt: w().default("now"),
3616
- createdAt: w().default("now"),
3617
- updatedAt: w().default("now").onUpdate("now")
3618
- }).index(["fingerprint"]).index(["environment"]), ga = H("_voltro_idempotency", {
3619
- id: h({ prefix: "idem" }),
3620
- scope: g(),
3621
- key: g(),
3622
- status: g(),
3623
- response: E().nullable(),
3624
- createdAt: w().default("now")
3625
- }).unique(["scope", "key"]).index(["createdAt"]), _a = H("_voltro_devices", {
3626
- id: h({ prefix: "device" }),
3627
- tenantId: g(),
3628
- name: g(),
3629
- scopes: E().nullable(),
3630
- pairingHash: g().maxLength(64).nullable(),
3631
- pairingExpiresAt: w().nullable(),
3632
- accessHash: g().maxLength(64).nullable(),
3633
- accessExpiresAt: w().nullable(),
3634
- refreshHash: g().maxLength(64).nullable(),
3635
- refreshExpiresAt: w().nullable(),
3636
- previousRefreshHash: g().maxLength(64).nullable(),
3637
- generation: _().default(0),
3638
- pairedAt: w().nullable(),
3639
- lastSeenAt: w().nullable(),
3640
- revokedAt: w().nullable(),
3641
- revokedReason: g().nullable(),
3642
- createdBy: g().nullable(),
3643
- metadata: E().nullable(),
3644
- createdAt: w()
3645
- }).index(["tenantId"]).index(["pairingHash"]).index(["accessHash"]).index(["refreshHash"]).index(["previousRefreshHash"]), va = H("_voltro_tenant_selections", {
3646
- id: h({ prefix: "tsel" }),
3647
- subjectType: g().maxLength(32),
3648
- subjectId: g(),
3649
- tenantId: g(),
3650
- selectedAt: w()
3651
- }).primaryKey(["id"]).nonReactive(), ya = H("_voltro_kv", {
3652
- id: h({ prefix: "kv" }),
3653
- key: g().unique(),
3654
- value: g().nullable(),
3655
- expiresAt: w().nullable(),
3656
- createdAt: w().default("now"),
3657
- updatedAt: w().default("now").onUpdate("now")
3658
- }).index(["expiresAt"]), ba = H("_voltro_api_keys", {
3659
- id: h({ prefix: "apikey" }),
3660
- tenantId: g().nullable(),
3661
- name: g(),
3662
- hashedKey: g().maxLength(64).unique(),
3663
- keyPrefix: g(),
3664
- scopes: E().nullable(),
3665
- lastUsedAt: w().nullable(),
3666
- requestCount: _().default(0),
3667
- expiresAt: w().nullable(),
3668
- revokedAt: w().nullable(),
3669
- createdBy: g().nullable(),
3670
- onBehalfOf: g().nullable(),
3671
- metadata: E().nullable(),
3672
- createdAt: w().default("now")
3673
- }).index("byApiKeyTenant", ["tenantId"]), xa = H("_voltro_replica_observations", {
3674
- id: h({ prefix: "robs" }),
3675
- replicaId: g().maxLength(191),
3676
- startedAt: w(),
3677
- version: g().maxLength(64).nullable(),
3678
- kind: g().maxLength(64),
3679
- payload: g().nullable(),
3680
- reachableAt: g().maxLength(255).nullable(),
3681
- writtenAt: w().default("now").onUpdate("now")
3682
- }).unique(["replicaId", "kind"]).index(["kind"]), Sa = [
3683
- da,
3684
- fa,
3685
- ha
3686
- ], Ca = "_voltro_replace_in_progress", wa = H(Ca, {
3687
- id: h({ prefix: "repl" }),
3688
- startedAt: w().default("now"),
3689
- kind: g().default("replace"),
3690
- tables: g().nullable(),
3691
- capture: g().nullable(),
3692
- via: g(),
3693
- staging: g().nullable(),
3694
- heartbeatAt: w().nullable(),
3695
- resumable: C().nullable()
3696
- }).nonReactive(), Ta = 30, Ea = (e, t) => {
3697
- let n = typeof t == "number" && Number.isFinite(t) && t > 0 ? t : 30, r = Number(e.VOLTRO_STAGING_STALE_MINUTES);
3698
- return (Number.isFinite(r) && r > 0 ? r : n) * 6e4;
3699
- }, Da = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), Oa = (e) => {
3700
- let t = e.filter((e) => e.kind !== "staging");
3701
- if (t.length !== 0) return `refusing to start: a destructive data operation did not finish.
3702
- ${t.map((e) => {
3703
- let t = Number.isFinite(e.startedAt.getTime()) ? `${Math.max(0, Math.round((Date.now() - e.startedAt.getTime()) / 6e4))} minute(s) ago` : "at an unknown time";
3704
- if (e.kind === "restore") return ` - a native \`restore\` over ${e.via} began loading an artefact over this database ${t}\n and never reported finishing.\n` + (e.capture === null ? " The artefact it was loading was not recorded. Re-run the restore from your backup\n directory, or restore from another backup." : ` The artefact it was loading:\n ${e.capture}\n Re-run it to completion with: voltro data restore ${e.capture} --allow-live`);
3705
- let n = e.tables === null ? "this database" : `${e.tables} table(s)`;
3706
- return ` - a \`replace\` over ${e.via} began emptying ${n} ${t} and never reported finishing.\n` + (e.capture === null ? " NO capture was taken for that run, so the previous rows are not recoverable from here.\n Restore from your own backup." : ` The target's previous rows were captured first:\n ${e.capture}\n Restore them with: voltro data import ${e.capture} --mode replace`);
3707
- }).join("\n")}\n
3708
- A half-replaced database is indistinguishable from an empty one from the inside — every table
3709
- exists, every constraint holds, and every query returns nothing without erroring. That is why
3710
- this is a refusal and not a warning.
3711
-
3712
- When the data is back, or you have decided the current state is correct, clear the marker:
3713
- voltro data clear-replace-marker --yes`;
3714
- }, ka = (e, t, n) => {
3715
- let r = e.filter((e) => e.kind === "staging");
3716
- return {
3717
- all: r,
3718
- droppable: r.filter((e) => {
3719
- if (e.resumable) return !1;
3720
- let r = (e.heartbeatAt ?? e.startedAt).getTime();
3721
- return Number.isFinite(r) ? t - r >= n : !1;
3722
- })
3723
- };
3724
- }, Aa = (e, t) => {
3725
- if (e.all.length === 0) return;
3726
- let n = new Set(e.droppable.map((e) => e.id));
3727
- return `staged data-import leftovers:
3728
- ${e.all.map((e) => {
3729
- let r = e.heartbeatAt ?? e.startedAt, i = Number.isFinite(r.getTime()) ? `${Math.max(0, Math.round((t - r.getTime()) / 6e4))} minute(s) ago` : "at an unknown time", a = `${e.staging.length} staging table(s) from a \`replace\` over ${e.via}, last active ${i}`;
3730
- return n.has(e.id) ? ` - ${a} — DROPPED: the run is not resumable and has been silent long enough that nothing is loading into them.` : e.resumable ? ` - ${a} — KEPT: the run was started \`--no-atomic\`, so these ARE its resume point. Re-run the same\n bundle to continue from them, or drop them with: voltro data clear-staging --yes` : ` - ${a} — KEPT: still beating, so an import is loading into them right now.`;
3731
- }).join("\n")}\n The target of a staged \`replace\` is untouched until one short swap at the end, so none of this is
3732
- a reason to refuse the boot — it is a reason to know the disk is holding a copy of a bundle.`;
3733
- };
3734
- //#endregion
3735
- export { oi as $, Le as $n, l as $r, pn as $t, la as A, Pt as An, A as Ar, rr as At, Wi as B, Tt as Bn, ie as Br, Hn as Bt, $i as C, nn as Cn, p as Cr, ri as Ct, ea as D, Gt as Dn, C as Dr, Ur as Dt, ca as E, en as En, x as Er, Or as Et, qi as F, jt as Fn, T as Fr, $n as Ft, zi as G, ft as Gn, oe as Gr, Pn as Gt, Qi as H, mt as Hn, _ as Hr, Bn as Ht, Yi as I, Nt as In, S as Ir, Qn as It, Li as J, ct as Jn, ae as Jr, J as Jt, Ri as K, dt as Kn, b as Kr, Ln as Kt, Ki as L, Et as Ln, y as Lr, Q as Lt, Zi as M, W as Mn, u as Mr, Yn as Mt, Ui as N, Ft as Nn, ee as Nr, Jn as Nt, ia as O, Kt as On, D as Or, Gr as Ot, Bi as P, kt as Pn, O as Pr, er as Pt, ii as Q, it as Qn, M as Qr, hn as Qt, Xi as R, wt as Rn, P as Rr, Wn as Rt, aa as S, Xt as Sn, ce as Sr, ui as St, sa as T, zt as Tn, I as Tr, Kr as Tt, Vi as U, H as Un, ne as Ur, Mn as Ut, Gi as V, gt as Vn, h as Vr, zn as Vt, Mi as W, ht as Wn, E as Wr, Fn as Wt, si as X, lt as Xn, v as Xr, _n as Xt, Ii as Y, ut as Yn, d as Yr, gn as Yt, di as Z, st as Zn, N as Zr, mn as Zt, pa as _, Vt as _n, pe as _r, yi as _t, Aa as a, Bt as an, Ke as ar, vi as at, Sa as b, an as bn, fe as br, fi as bt, Ea as c, Lt as cn, _e as cr, ei as ct, ga as d, Zt as dn, Pe as dr, ci as dt, g as ei, q as en, Re as er, ai as et, ya as f, Jt as fn, Fe as fr, mi as ft, xa as g, Ht as gn, Se as gr, pi as gt, ma as h, $t as hn, Me as hr, Yr as ht, Oa as i, dn as in, We as ir, Ti as it, oa as j, At as jn, f as jr, ir as jt, na as k, Mt as kn, k as kr, kr as kt, ba as l, Rt as ln, Ae as lr, gi as lt, da as m, Qt as mn, je as mr, $r as mt, Ta as n, te as ni, un as nn, Ge as nr, ni as nt, ka as o, tn as on, L as or, Xr as ot, ha as p, qt as pn, xe as pr, Qr as pt, Ni as q, pt as qn, F as qr, vn as qt, wa as r, ln as rn, B as rr, Jr as rt, Da as s, Ut as sn, we as sr, Zr as st, Ca as t, w as ti, cn as tn, Ve as tr, ki as tt, _a as u, sn as un, Ne as ur, li as ut, fa as v, It as vn, me as vr, ti as vt, ta as w, Yt as wn, j as wr, Ai as wt, ua as x, rn as xn, le as xr, Ei as xt, va as y, on as yn, de as yr, _i as yt, Ji as z, Ct as zn, re as zr, Vn as zt };