@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
@@ -0,0 +1,154 @@
1
+ import { decimal as e, text as t } from "./columns.js";
2
+ import { sqliteDecimalOutputs as n } from "./sqliteDecimalOutputs.js";
3
+ import { compileSqliteDecimalEncodedSource as r } from "./sqliteDecimalEncodeSql.js";
4
+ //#region src/sqliteDecimalCte.ts
5
+ var i = (e) => e.replace(/[A-Z]/g, (e) => e.toLowerCase()), a = (e) => {
6
+ let t = /* @__PURE__ */ new Set(), n = (e) => {
7
+ "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);
8
+ }, r = (e) => {
9
+ t.add(i(e.table));
10
+ for (let r of e.joins ?? []) t.add(i(r.table)), n(r.on);
11
+ for (let n of e.ctes ?? []) t.add(i(n.name)), r(n.descriptor);
12
+ e.setOp?.queries.forEach(r), e.predicate && n(e.predicate), e.having && n(e.having);
13
+ };
14
+ r(e);
15
+ let a = 0;
16
+ return () => {
17
+ let e;
18
+ do
19
+ e = `__voltro_decimal_cte_${a++}`;
20
+ while (t.has(e));
21
+ return t.add(e), e;
22
+ };
23
+ }, o = (r, s, c = () => void 0, l = a(r)) => {
24
+ let u = /* @__PURE__ */ new Map();
25
+ for (let e of r.ctes ?? []) {
26
+ let t = i(e.name);
27
+ if (u.has(t)) throw Error("Duplicate exact decimal CTE name");
28
+ u.set(t, e);
29
+ }
30
+ let d = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Set(), p = [], m = (r) => {
31
+ let a = i(r), h = u.get(a);
32
+ if (!h) return c(a);
33
+ let g = d.get(a);
34
+ if (g) return g;
35
+ if (h.recursive) throw Error("Recursive exact decimal CTE composition is not integrated yet");
36
+ if (f.has(a)) throw Error(`Circular exact decimal CTE dependency: ${h.name}`);
37
+ f.add(a);
38
+ let _ = o(h.descriptor, s, m, l), v = n(_, s);
39
+ if (new Set(v.map((e) => i(e.name))).size !== v.length) throw Error("Duplicate exact decimal CTE output");
40
+ let y = l(), b = {
41
+ tableName: y,
42
+ fields: Object.fromEntries(v.map((n) => [n.name, n.decimal ? {
43
+ ...e(n.decimal.precision, n.decimal.scale).__definition(),
44
+ sqliteDecimalEncoding: "sortable-v1"
45
+ } : n.definition ?? t().__definition()]))
46
+ };
47
+ return d.set(a, b), f.delete(a), p.push({
48
+ ...h,
49
+ name: y,
50
+ descriptor: _
51
+ }), b;
52
+ };
53
+ for (let e of u.keys()) m(e);
54
+ let h = (e) => "and" in e ? { and: e.and.map(h) } : "or" in e ? { or: e.or.map(h) } : "not" in e ? { not: h(e.not) } : "subquery" in e ? {
55
+ ...e,
56
+ subquery: o(e.subquery, s, m, l)
57
+ } : e, g = m(r.table), { ctes: _, ...v } = r;
58
+ return {
59
+ ...v,
60
+ ...p?.length ? { ctes: p } : {},
61
+ ...g ? {
62
+ table: g.tableName,
63
+ alias: r.alias ?? r.table,
64
+ sourceTable: g
65
+ } : {},
66
+ ...r.joins ? { joins: r.joins.map((e) => {
67
+ let t = m(e.table);
68
+ return {
69
+ ...e,
70
+ ...t ? {
71
+ table: t.tableName,
72
+ sourceTable: t
73
+ } : {},
74
+ on: h(e.on)
75
+ };
76
+ }) } : {},
77
+ ...r.predicate ? { predicate: h(r.predicate) } : {},
78
+ ...r.having ? { having: h(r.having) } : {},
79
+ ...r.setOp ? { setOp: {
80
+ ...r.setOp,
81
+ queries: r.setOp.queries.map((e) => o(e, s, m, l))
82
+ } } : {}
83
+ };
84
+ }, s = (e, t) => {
85
+ 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 ? {
86
+ ...e,
87
+ subquery: i(e.subquery)
88
+ } : e, i = (e) => {
89
+ let { ctes: t, ...a } = e;
90
+ for (let e of t ?? []) {
91
+ let t = i(e.descriptor);
92
+ n.push({
93
+ ...e,
94
+ descriptor: t
95
+ });
96
+ }
97
+ return {
98
+ ...a,
99
+ ...a.joins ? { joins: a.joins.map((e) => ({
100
+ ...e,
101
+ on: r(e.on)
102
+ })) } : {},
103
+ ...a.predicate ? { predicate: r(a.predicate) } : {},
104
+ ...a.having ? { having: r(a.having) } : {},
105
+ ...a.setOp ? { setOp: {
106
+ ...a.setOp,
107
+ queries: a.setOp.queries.map(i)
108
+ } } : {}
109
+ };
110
+ }, a = i(o(e, t));
111
+ return n.length ? {
112
+ ...a,
113
+ ctes: n
114
+ } : a;
115
+ }, c = (e, t, a, o) => {
116
+ let s = (e.ctes ?? []).flatMap((e, s) => {
117
+ let c = n(e.descriptor, a), [l] = o(e.descriptor).compile(), u = (e) => "\"" + e.replaceAll("\"", "\"\"") + "\"", d = `decimal_cte_${s}_`, f = i(l + e.name);
118
+ for (; f.includes(d);) d += "_";
119
+ let p = c.map((e, t) => `${d}column_${t}`), m = [], h = /* @__PURE__ */ new Set(), [g, _] = o(e.descriptor, {
120
+ prefix: `${d}window_`,
121
+ append: (e, t) => {
122
+ m.push(`${e} AS MATERIALIZED (${t})`);
123
+ },
124
+ encodedOutput: (e) => {
125
+ h.add(e);
126
+ }
127
+ }).compile();
128
+ m.push(`${d}input AS (${g})`);
129
+ let v = (e, t) => {
130
+ m.push(`${e} AS (${t})`);
131
+ }, y = `${d}columns`;
132
+ v(y, `SELECT ${c.map((e, t) => `${u(e.name)} AS ${p[t]}`).join(",")} FROM ${d}input`);
133
+ for (let [e, t] of c.entries()) {
134
+ if (!t.decimal || h.has(t.name)) continue;
135
+ let n = p.filter((t, n) => n !== e), i = `SELECT ${p[e]} AS value${n.map((e) => "," + e).join("")} FROM ${y}`, a = r(i, t.decimal, n, {
136
+ prefix: `${d}${e}_`,
137
+ append: v
138
+ });
139
+ y = `${d}encoded_${e}`, v(y, `SELECT ${p.map((t, n) => n === e ? `value AS ${t}` : t).join(",")} FROM ${a}`);
140
+ }
141
+ let b = c.map((e, t) => `${p[t]} AS ${u(e.name)}`).join(",");
142
+ return [t.unsafe(m.join(","), _), t`${t(e.name)} AS (${t.unsafe(`SELECT ${b} FROM ${y}`)})`];
143
+ }), { ctes: c, ...l } = e, [u] = o(l).compile(), d = "decimal_cte_result_", f = i(u + s.map((e) => e.compile()[0]).join(""));
144
+ for (; f.includes(d);) d += "_";
145
+ let p = [], [m, h] = o(l, void 0, {
146
+ prefix: d,
147
+ append: (e, t) => {
148
+ p.push(`${e} AS MATERIALIZED (${t})`);
149
+ }
150
+ }).compile(), g = p.length ? t`WITH ${t.join(", ", !1)([...s, t.unsafe(p.join(","), h)])} ${t.unsafe(m)}` : t`WITH ${t.join(", ", !1)(s)} SELECT * FROM (${t.unsafe(m, h)})`;
151
+ return t.unsafe(...g.compile());
152
+ };
153
+ //#endregion
154
+ export { c as compileSqliteDecimalCtes, s as resolveSqliteDecimalSources };
@@ -0,0 +1,32 @@
1
+ import { encodeSqliteDecimal as e } from "./sqliteDecimal.js";
2
+ //#region src/sqliteDecimalEncodeSql.ts
3
+ var t = (t, n, r = [], i) => {
4
+ e("0", n);
5
+ let a = /* @__PURE__ */ new Set([
6
+ "value",
7
+ "negative",
8
+ "unsigned",
9
+ "integer_part",
10
+ "fraction",
11
+ "magnitude",
12
+ "padded",
13
+ "trimmed",
14
+ "alphabetic",
15
+ "complement"
16
+ ]);
17
+ if (new Set(r).size !== r.length || r.some((e) => !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e) || a.has(e.toLowerCase()))) throw Error("Invalid decimal source carry column");
18
+ if (i && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i.prefix)) throw Error("Invalid decimal encoding stage prefix");
19
+ let o = (e) => (i?.prefix ?? "") + "decimal_encode_" + e, s = "0".repeat(n.precision), c = "substr(trimmed,1,length(trimmed)-1)";
20
+ for (let e = 0; e < 10; e++) c = `replace(${c},'${e}','${String.fromCharCode(97 + e)}')`;
21
+ let l = c;
22
+ c = "alphabetic";
23
+ for (let e = 0; e < 10; e++) c = `replace(${c},'${String.fromCharCode(97 + e)}','${9 - e}')`;
24
+ let u = [], d = (e) => i?.reference?.(o(e)) ?? o(e), f = (e, t) => {
25
+ i ? i.append(o(e), t) : u.push(`${o(e)} AS (${t})`);
26
+ };
27
+ f("input", `SELECT * FROM (${t}) LIMIT -1 OFFSET 0`), f("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 ${d("input")} LIMIT -1 OFFSET 0`), f("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 ${d("sign")} LIMIT -1 OFFSET 0`), f("magnitude", `SELECT *,coalesce(nullif(ltrim(integer_part||substr(fraction||'${"0".repeat(n.scale)}',1,${n.scale}),'0'),''),'0') AS magnitude FROM ${d("parts")} LIMIT -1 OFFSET 0`), f("padded", `SELECT *,substr('${s}'||magnitude,-${n.precision}) AS padded FROM ${d("magnitude")} LIMIT -1 OFFSET 0`), f("trimmed", `SELECT *,rtrim(padded,'0') AS trimmed FROM ${d("padded")} LIMIT -1 OFFSET 0`), f("alphabetic", `SELECT *,${l} AS alphabetic FROM ${d("trimmed")} LIMIT -1 OFFSET 0`), f("complement", `SELECT *,${c} AS complement FROM ${d("alphabetic")} LIMIT -1 OFFSET 0`);
28
+ let p = `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)>${n.precision} OR substr(fraction,${n.scale + 1}) GLOB '*[1-9]*'`;
29
+ return `(${i ? "" : `WITH ${u.join(",")} `}SELECT ${r.map((e) => `"${e}",`).join("")}CASE WHEN value IS NULL THEN NULL WHEN ${p} 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 ${d("complement")})`;
30
+ };
31
+ //#endregion
32
+ export { t as compileSqliteDecimalEncodedSource };
@@ -0,0 +1,74 @@
1
+ import { integer as e } from "./columns.js";
2
+ import { getTable as t } from "./tableRegistry.js";
3
+ import { isSqliteDecimalEncodedColumn as n } from "./sqliteDecimalStorage.js";
4
+ import { projectedColumn as r } from "./projectedColumn.js";
5
+ //#region src/sqliteDecimalOutputs.ts
6
+ var i = (a, o) => {
7
+ if (a.setOp) {
8
+ let e = a.setOp.queries.map((e) => i(e, o));
9
+ if (e.length < 2) throw Error("Exact set operations require at least two inputs");
10
+ let t = e[0];
11
+ if (e.some((e) => e.length !== t.length)) throw Error("Exact set operation column counts differ");
12
+ return t.map((t, n) => {
13
+ let r = e.map((e) => e[n].decimal);
14
+ if (r.some(Boolean) && !r.every(Boolean)) throw Error("Exact set operation decimal and nondecimal outputs cannot be mixed");
15
+ if (!t.decimal) return t;
16
+ let i = Math.max(...r.map((e) => e.scale)), a = Math.max(...r.map((e) => e.precision - e.scale));
17
+ return {
18
+ name: t.name,
19
+ decimal: {
20
+ precision: a + i,
21
+ scale: i
22
+ }
23
+ };
24
+ });
25
+ }
26
+ let s = a.aggregations ?? [];
27
+ if (s.length) return s.map((t) => {
28
+ let i = r(t.column ?? "", a);
29
+ if (!n(i) || t.op.startsWith("count") || [
30
+ "window-row-number",
31
+ "window-rank",
32
+ "window-dense-rank"
33
+ ].includes(t.op)) return {
34
+ name: t.alias,
35
+ definition: t.op.startsWith("count") || [
36
+ "window-row-number",
37
+ "window-rank",
38
+ "window-dense-rank"
39
+ ].includes(t.op) ? e().__definition() : i ?? e().__definition()
40
+ };
41
+ let s = ["avg", "window-avg-over"].includes(t.op) ? o ?? i.scale : i.scale, c = [
42
+ "sum",
43
+ "avg",
44
+ "window-sum-over",
45
+ "window-avg-over"
46
+ ].includes(t.op);
47
+ return {
48
+ name: t.alias,
49
+ decimal: {
50
+ precision: i.precision + (c ? 20 : 0) + Math.max(0, s - i.scale),
51
+ scale: s
52
+ }
53
+ };
54
+ });
55
+ let c = a.sourceTable?.tableName === a.table ? a.sourceTable : t(a.table), l = a.joinedProjection ?? (a.projection?.length ? a.projection : Object.keys(c?.fields ?? {})).map((e) => ({
56
+ source: e,
57
+ outputKey: e.split(".").at(-1)
58
+ }));
59
+ if (!l.length) throw Error("Exact set operation requires declared output columns");
60
+ return l.map((e) => {
61
+ let t = r(e.source, a);
62
+ if (!t) throw Error("Exact set operation requires declared output columns");
63
+ return {
64
+ name: e.outputKey,
65
+ definition: t,
66
+ ...n(t) ? { decimal: {
67
+ precision: t.precision,
68
+ scale: t.scale
69
+ } } : {}
70
+ };
71
+ });
72
+ };
73
+ //#endregion
74
+ export { i as sqliteDecimalOutputs };
@@ -0,0 +1,66 @@
1
+ import { encodeSqliteDecimal as e } from "./sqliteDecimal.js";
2
+ import { sqliteDecimalResultKey as t } from "./sqliteDecimalResultSql.js";
3
+ //#region src/sqliteDecimalPredicate.ts
4
+ var n = (n, r, i) => {
5
+ if (e("0", r), n.path?.length) throw Error("Decimal JSON-path predicates are unsupported");
6
+ if (n.op === "isNull" || n.op === "isNotNull") return n;
7
+ if (![
8
+ "eq",
9
+ "neq",
10
+ "gt",
11
+ "gte",
12
+ "lt",
13
+ "lte",
14
+ "in",
15
+ "notIn"
16
+ ].includes(n.op)) throw Error("Unsupported exact decimal predicate");
17
+ let a = 10n ** BigInt(r.precision), o = -a + 1n, s = a - 1n, c = (e) => i === "aggregate" ? t(String(e), r.precision) : "D" + (e + a).toString().padStart(r.precision + 1, "0"), l = (e) => {
18
+ if (typeof e != "string" || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e)) throw TypeError("Exact decimal predicate requires a fixed-point decimal string");
19
+ let [t = "", n = ""] = e.replace(/^[+-]/, "").split("."), i = BigInt((t || "0") + n.slice(0, r.scale).padEnd(r.scale, "0")), a = /[1-9]/.test(n.slice(r.scale)), o = e.startsWith("-"), s = o ? -i : i;
20
+ return {
21
+ floor: s - (o && a ? 1n : 0n),
22
+ ceil: s + (!o && a ? 1n : 0n),
23
+ exact: !a
24
+ };
25
+ }, u = (e) => {
26
+ if (e === null) return null;
27
+ let t = l(e);
28
+ return t.exact && t.floor >= o && t.floor <= s ? c(t.floor) : "!decimal-unrepresentable";
29
+ };
30
+ if (n.op === "in" || n.op === "notIn") {
31
+ if (!Array.isArray(n.value)) throw TypeError("Decimal IN predicate requires an array");
32
+ return {
33
+ ...n,
34
+ value: n.value.map(u)
35
+ };
36
+ }
37
+ if (n.op === "eq" || n.op === "neq") return {
38
+ ...n,
39
+ value: u(n.value)
40
+ };
41
+ if (n.value === null) return n;
42
+ let d = l(n.value), f = n.op === "gte" || n.op === "lt" ? d.ceil : d.floor, p = (e) => ({
43
+ ...n,
44
+ op: e ? "gte" : "lt",
45
+ value: c(o)
46
+ });
47
+ if (n.op === "gte") {
48
+ if (f <= o) return p(!0);
49
+ if (f > s) return p(!1);
50
+ } else if (n.op === "gt") {
51
+ if (f < o) return p(!0);
52
+ if (f >= s) return p(!1);
53
+ } else if (n.op === "lt") {
54
+ if (f <= o) return p(!1);
55
+ if (f > s) return p(!0);
56
+ } else {
57
+ if (f < o) return p(!1);
58
+ if (f >= s) return p(!0);
59
+ }
60
+ return {
61
+ ...n,
62
+ value: c(f)
63
+ };
64
+ };
65
+ //#endregion
66
+ export { n as lowerSqliteDecimalPredicate };
@@ -0,0 +1,183 @@
1
+ import { columnComparisonOperators as e, isColumnReference as t } from "./columnReference.js";
2
+ import { isSqliteDecimalEncodedColumn as n } from "./sqliteDecimalStorage.js";
3
+ import { prepareProjectedColumn as r } from "./projectedColumn.js";
4
+ import { compileSqliteDecimalCtes as i, resolveSqliteDecimalSources as a } from "./sqliteDecimalCte.js";
5
+ import { qualifyTable as o } from "./namespace.js";
6
+ import { compileSqliteDecimalSubquery as s } from "./sqliteDecimalSubquery.js";
7
+ import { compileSqliteDecimalSetQuery as c } from "./sqliteDecimalSetQuery.js";
8
+ import { compileSqliteDecimalResult as l, compileSqliteDecimalResultComparison as u } from "./sqliteDecimalResultSql.js";
9
+ import { lowerSqliteDecimalPredicate as d } from "./sqliteDecimalPredicate.js";
10
+ import { compileSqliteDecimalSource as f } from "./sqliteDecimalSource.js";
11
+ import { compileSqliteDecimalRowQuery as p } from "./sqliteDecimalRowQuery.js";
12
+ import { compileSqliteDecimalAvg as m, compileSqliteDecimalSum as ee } from "./sqliteDecimalAggregateSql.js";
13
+ import { compileSqliteDecimalWindowQuery as h } from "./sqliteDecimalWindowQuery.js";
14
+ import { compilePredicate as g } from "./sqlCompiler.js";
15
+ //#region src/sqliteDecimalQuery.ts
16
+ var _ = (a, o, v, y, b, x) => {
17
+ if (!o.onDialectOrElse({
18
+ sqlite: () => !0,
19
+ orElse: () => !1
20
+ })) throw Error("Encoded decimal query integration requires a SQLite-family compiler");
21
+ if (a.ctes?.length) return i(a, o, v.resultScale, (e, t, n) => _(e, o, v, y, t, n));
22
+ if (a.setOp) return c(a, o, v, (e) => _(e, o, v, y));
23
+ let S = {
24
+ compile: (e) => _(e, o, v, y),
25
+ resultScale: v.resultScale,
26
+ sourceTable: y
27
+ }, C = a.aggregations ?? [];
28
+ if (C.length > 0 && C.every((e) => e.op === "column") && !a.groupBy?.length && !a.having || C.some((e) => e.op.startsWith("window-"))) return h(a, o, v, S, b, x);
29
+ let w = C.length === 0, T = C.filter((e) => e.op !== "column"), E = !w && T.length === 0, D = {
30
+ sum: "SUM",
31
+ avg: "AVG",
32
+ min: "MIN",
33
+ max: "MAX",
34
+ count: "COUNT",
35
+ "count-distinct": "COUNT"
36
+ };
37
+ if (E && !a.groupBy?.length || T.some((e) => !(e.op in D)) || a.setOp || a.distinctOn || a.ctes || a.annClause || a.spatialClause || a.fullTextSearch) throw Error("Exact decimal query integration requires supported grouped aggregate projections");
38
+ if (new Set(C.map((e) => e.alias)).size !== C.length) throw Error("Duplicate decimal result alias");
39
+ let O = r(a), k = a.groupBy ?? [], A = /* @__PURE__ */ new Map();
40
+ k.forEach((e, t) => {
41
+ A.has(e) || A.set(e, t);
42
+ });
43
+ for (let e of k) if (O(e) === void 0) throw Error("Exact decimal grouping requires declared source columns");
44
+ for (let e of C) if (e.op === "column" && !A.has(e.column ?? "")) throw Error("Projected group column is absent from GROUP BY");
45
+ let j = "__decimal_group_identity";
46
+ for (; C.some((e) => e.alias === j);) j += "_";
47
+ let M = [...(E ? [{
48
+ op: "count",
49
+ alias: j
50
+ }] : T).map((e) => ({
51
+ aggregate: e,
52
+ projection: e
53
+ })), ...C.filter((e) => e.op === "column" && n(O(e.column ?? ""))).map((e) => ({
54
+ aggregate: {
55
+ ...e,
56
+ op: "min"
57
+ },
58
+ projection: e
59
+ }))].map(({ aggregate: e, projection: t }, r) => {
60
+ if (e.column === void 0 && e.op !== "count") throw Error("Aggregate requires a source column");
61
+ let i = O(e.column ?? "");
62
+ if (e.column !== void 0 && i === void 0) throw Error("Aggregate requires a declared source column");
63
+ let a = n(i) && !e.op.startsWith("count");
64
+ if (a && (i.precision === void 0 || i.scale === void 0)) throw Error("Exact decimal aggregate requires declared precision and scale");
65
+ let o = a ? i.precision : 0, s = a ? i.scale : 0, c = e.op === "avg" ? v.resultScale ?? s : s;
66
+ return {
67
+ aggregate: e,
68
+ projection: t,
69
+ index: r,
70
+ exact: a,
71
+ precision: o,
72
+ inputScale: s,
73
+ scale: c,
74
+ digits: o + 20 + Math.max(0, c - s)
75
+ };
76
+ }), N = new Map(M.map((e) => [e.projection, e])), P = new Map(M.map((e) => [e.projection.alias, e])), F = /* @__PURE__ */ new Map(), I = C.map((e) => {
77
+ let t = N.get(e);
78
+ if (t) return F.set(e.alias, `result${t.index}.${t.exact ? "decimal_key" : "result_value"}`), o`${o(`result${t.index}.${t.exact ? "decimal_value" : "result_value"}`)} AS ${o(e.alias)}`;
79
+ let n = A.get(e.column ?? "") ?? -1;
80
+ if (n < 0) throw Error("Projected group column is absent from GROUP BY");
81
+ return F.set(e.alias, `result0.key${n}`), o`${o(`result0.key${n}`)} AS ${o(e.alias)}`;
82
+ }), L = (e) => {
83
+ if ("and" in e) return { and: e.and.map(L) };
84
+ if ("or" in e) return { or: e.or.map(L) };
85
+ if ("not" in e) return { not: L(e.not) };
86
+ if ("subquery" in e || !("column" in e) || !("op" in e)) throw Error("Decimal subquery predicates are not integrated yet");
87
+ if (t(e.value)) throw Error("Column references require result comparison lowering");
88
+ let n = P.get(e.column), r = F.get(e.column);
89
+ if (r === void 0) throw Error("HAVING references an unknown projected aggregate or group key");
90
+ return n?.exact ? d({
91
+ ...e,
92
+ column: r
93
+ }, {
94
+ precision: n.digits,
95
+ scale: n.scale
96
+ }, "aggregate") : {
97
+ ...e,
98
+ column: r
99
+ };
100
+ }, R = [...M.flatMap((e) => e.aggregate.column === void 0 ? [] : [{
101
+ source: e.aggregate.column,
102
+ outputKey: `value${e.index}`
103
+ }]), ...k.map((e, t) => ({
104
+ source: e,
105
+ outputKey: `group${t}`
106
+ }))], te = R.length ? o.join(", ", !1)(R.map((e) => o`${o(e.source)} AS ${o(e.outputKey)}`)) : o`1 AS decimal_query_row`, { from: z, where: B } = f(a, o, S);
107
+ if (w) return p(a, o, S, b, x);
108
+ let V = o`SELECT ${te} FROM ${z}${B}`.compile(), H = (e) => "\"" + e.replace(/"/g, "\"\"") + "\"", U = k.map((e, t) => `group${t}`), W = U.map((e, t) => `${H(e)} AS ${H(`key${t}`)}`).join(","), G = U.length ? ` GROUP BY ${U.map(H).join(",")}` : "", K = v.materialized ? "decimal_query_source" : `(${V[0]})`, q = M.map((e) => {
109
+ let { aggregate: t, index: n, precision: r, inputScale: i, scale: a, digits: o } = e, s = t.column === void 0 ? "*" : H(`value${n}`);
110
+ if (!e.exact) return `SELECT ${W ? W + "," : ""}${D[t.op]}(${t.op === "count-distinct" ? "DISTINCT " : ""}${s}) AS result_value FROM ${K}${G}`;
111
+ let c = {
112
+ sourceSql: t.op === "min" || t.op === "max" ? `SELECT ${U.length ? U.map(H).join(",") + "," : ""}${D[t.op]}(${s}) AS value FROM ${K}${G}` : `SELECT ${U.length ? U.map(H).join(",") + "," : ""}${s} AS value FROM ${K}`,
113
+ precision: r,
114
+ materialized: v.materialized,
115
+ ...k.length ? { scope: {
116
+ kind: "group",
117
+ columns: U
118
+ } } : {}
119
+ }, u = t.op === "avg" ? m({
120
+ ...c,
121
+ inputScale: i,
122
+ resultScale: a,
123
+ rounding: v.rounding ?? "half-even"
124
+ }) : ee(c);
125
+ return l({
126
+ sourceSql: u,
127
+ digits: o,
128
+ scale: a,
129
+ materialized: v.materialized
130
+ });
131
+ }), J = [...v.materialized ? [`decimal_query_source AS MATERIALIZED (${V[0]})`] : [], ...q.map((e, t) => {
132
+ let n = v.materialized ? e : `SELECT * FROM (${e}) LIMIT -1 OFFSET 0`;
133
+ return `result${t} AS${v.materialized ? " MATERIALIZED" : ""} (${n})`;
134
+ })].join(","), Y = M.slice(1).map((e) => k.length ? ` JOIN result${e.index} ON ${k.map((t, n) => `result0.${H(`key${n}`)} IS result${e.index}.${H(`key${n}`)}`).join(" AND ")}` : ` CROSS JOIN result${e.index}`).join(""), X = (n) => {
135
+ if ("not" in n) return o`NOT (${X(n.not)})`;
136
+ if ("and" in n) return n.and.length ? o.and(n.and.map(X)) : o`TRUE`;
137
+ if ("or" in n) return n.or.length ? o.or(n.or.map(X)) : o`FALSE`;
138
+ if ("subquery" in n) return s(n, o, S, (e) => {
139
+ let t = F.get(e);
140
+ if (!t) throw Error("HAVING references an unknown projected aggregate or group key");
141
+ let n = P.get(e);
142
+ return n?.exact ? {
143
+ value: o`${o(`result${n.index}.decimal_value`)}`,
144
+ scale: n.scale
145
+ } : { value: o`${o(t)}` };
146
+ });
147
+ if (!("value" in n) || !t(n.value)) return g(L(n), o);
148
+ let r = F.get(n.column), i = F.get(n.value.column);
149
+ if (r === void 0 || i === void 0) throw Error("HAVING references an unknown projected aggregate or group key");
150
+ let a = P.get(n.column), c = n.value.column, l = P.get(c);
151
+ if (!a?.exact && !l?.exact) return g({
152
+ ...n,
153
+ column: r,
154
+ value: {
155
+ ...n.value,
156
+ column: i
157
+ }
158
+ }, o);
159
+ if (!a?.exact || !l?.exact) throw Error("Exact aggregate comparisons require two decimal results");
160
+ if (!e.includes(n.op) || n.path?.length) throw Error("Unsupported exact decimal result comparison");
161
+ return o.unsafe(u({
162
+ expression: o`${o(r)}`.compile()[0],
163
+ digits: a.digits,
164
+ scale: a.scale
165
+ }, n.op, {
166
+ expression: o`${o(i)}`.compile()[0],
167
+ digits: l.digits,
168
+ scale: l.scale
169
+ }));
170
+ }, Z = a.having === void 0 ? o`` : o` WHERE ${X(a.having)}`, Q = a.order.length === 0 ? o`` : o` ORDER BY ${o.join(", ", !1)(a.order.map((e) => {
171
+ let t = F.get(e.column);
172
+ if (t === void 0) throw Error("Ordering references an unknown decimal result projection");
173
+ return e.direction === "desc" ? o`${o(t)} DESC` : o`${o(t)} ASC`;
174
+ }))}`;
175
+ for (let e of [a.take, a.skip]) if (e !== void 0 && (!Number.isSafeInteger(e) || e < 0)) throw Error("Invalid exact decimal pagination");
176
+ let ne = a.take === void 0 ? a.skip === void 0 ? o`` : o` LIMIT -1` : o` LIMIT ${a.take}`, re = a.skip === void 0 ? o`` : o` OFFSET ${a.skip}`, $ = o`WITH ${o.unsafe(J)} SELECT ${a.distinct ? o`DISTINCT ` : o``}${o.join(", ", !1)(I)} FROM result0${o.unsafe(Y)}${Z}${Q}${ne}${re}`.compile(), ie = v.materialized ? V[1] : M.flatMap(() => V[1]);
177
+ return o.unsafe($[0], [...ie, ...$[1]]);
178
+ }, v = (e, t, n, r = null) => {
179
+ let i = a(e, n.resultScale), s = new Set((i.ctes ?? []).map((e) => e.name));
180
+ return _(i, t, n, (e) => s.has(e) ? e : o(r, e));
181
+ };
182
+ //#endregion
183
+ export { v as compileSqliteDecimalQuery };
@@ -0,0 +1,37 @@
1
+ import { getTable as e } from "./tableRegistry.js";
2
+ import { isSqliteDecimalEncodedColumn as t } from "./sqliteDecimalStorage.js";
3
+ //#region src/sqliteDecimalQueryPlan.ts
4
+ var n = (e) => e.replace(/[A-Z]/g, (e) => e.toLowerCase()), r = (e) => {
5
+ if (Object.getPrototypeOf(e) !== Object.prototype) return !1;
6
+ for (let t of Object.values(Object.getOwnPropertyDescriptors(e))) {
7
+ if (!("value" in t) || !t.value || Object.getPrototypeOf(t.value) !== Object.prototype) return !1;
8
+ for (let e of [
9
+ "type",
10
+ "sqliteDecimalEncoding",
11
+ "precision",
12
+ "scale"
13
+ ]) {
14
+ let n = Object.getOwnPropertyDescriptor(t.value, e);
15
+ if (n && !("value" in n)) return !1;
16
+ }
17
+ }
18
+ return !0;
19
+ }, i = (i) => {
20
+ let a, o = !1, s, c = (e, t) => e ? "and" in e ? e.and.some((e) => c(e, t)) : "or" in e ? e.or.some((e) => c(e, t)) : "not" in e ? c(e.not, t) : "subquery" in e && l(e.subquery, t) : !1, l = (i, u) => {
21
+ let d = /* @__PURE__ */ new Set([...u, ...(i.ctes ?? []).map((e) => n(e.name))]), f = (i, c) => {
22
+ if (d.has(n(i))) return !1;
23
+ let l = c?.tableName === i ? c : e(i);
24
+ if (l === void 0) return !1;
25
+ if (a === void 0) return a = l, o = Object.values(l.fields).some(t), o;
26
+ s ??= /* @__PURE__ */ new Map([[a, { result: o }]]);
27
+ let u = s.get(l);
28
+ if (u !== void 0 && (u.ordinary ??= r(l.fields), u.ordinary)) return u.result;
29
+ let f = Object.values(l.fields).some(t);
30
+ return u === void 0 && s.set(l, { result: f }), f;
31
+ };
32
+ return f(i.table, i.sourceTable) || (i.joins ?? []).some((e) => f(e.table, e.sourceTable) || c(e.on, d)) || (i.ctes ?? []).some((e) => l(e.descriptor, d)) || (i.setOp?.queries ?? []).some((e) => l(e, d)) || c(i.predicate, d) || c(i.having, d);
33
+ };
34
+ return l(i, /* @__PURE__ */ new Set());
35
+ };
36
+ //#endregion
37
+ export { i as hasEncodedSqliteDecimalSource };
@@ -0,0 +1,44 @@
1
+ //#region src/sqliteDecimalResultSql.ts
2
+ var e = (e, t) => {
3
+ if (!Number.isSafeInteger(e) || e < 1 || !Number.isSafeInteger(t) || t < 0 || t > e) throw RangeError("Invalid decimal result shape");
4
+ }, t = (t, n) => {
5
+ if (e(n, 0), !/^-?(?:0|[1-9]\d*)$/.test(t)) throw TypeError("Expected canonical decimal units");
6
+ let r = t.replace(/^-/, "");
7
+ if (r.length > n) throw RangeError("Decimal result exceeds declared width");
8
+ let i = r.padStart(n, "0");
9
+ return t.startsWith("-") && r !== "0" ? "0" + i.replace(/\d/g, (e) => String(9 - Number(e))) : "1" + i;
10
+ }, n = ({ sourceSql: t, digits: n, scale: r, materialized: i = !1, stages: a }) => {
11
+ e(n, r);
12
+ let o = "0".repeat(n), s = "ltrim(units,'-')", c = `substr('${o}'||${s},-${n})`, l = c;
13
+ for (let e = 0; e < 10; e++) l = `replace(${l},'${e}','${String.fromCharCode(97 + e)}')`;
14
+ let u = l;
15
+ l = "decimal_complement";
16
+ for (let e = 0; e < 10; e++) l = `replace(${l},'${String.fromCharCode(97 + e)}','${9 - e}')`;
17
+ let d = `substr(units,1,1)='-' AND ${s}<>'0'`, f = `CASE WHEN ${d} THEN '0'||${l} ELSE '1'||${c} END`, p = `substr('${"0".repeat(r + 1)}'||${s},-max(length(${s}),${r + 1}))`, m = r === 0 ? s : `substr(${p},1,length(${p})-${r})||'.'||substr(${p},-${r})`, h = `WHEN length(${s})>${n} THEN abs(-9223372036854775808)`, g = i ? t : `SELECT * FROM (${t}) LIMIT -1 OFFSET 0`;
18
+ if (a && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a.prefix)) throw Error("Invalid decimal stage prefix");
19
+ let _ = (a?.prefix ?? "") + "decimal_result_source", v = _ + "_encoded", y = (e) => a?.reference?.(e) ?? e;
20
+ a && a.append(_, t, i);
21
+ let b = `SELECT ${_}.*,${u} AS decimal_complement FROM ${y(_)}`;
22
+ return a && a.append(v, b, i), `${a ? "" : `WITH ${_} AS${i ? " MATERIALIZED" : ""} (${g}), ${v} AS${i ? " MATERIALIZED" : ""} (${b}) `}SELECT ${v}.*,
23
+ CASE WHEN units IS NULL THEN NULL ${h} ELSE ${f} END AS decimal_key,
24
+ CASE WHEN units IS NULL THEN NULL ${h} ELSE (CASE WHEN ${d} THEN '-' ELSE '' END)||${m} END AS decimal_value
25
+ FROM ${y(v)}`;
26
+ }, r = (t, n, r) => {
27
+ e(t.digits, t.scale), e(r.digits, r.scale);
28
+ let i = {
29
+ eq: "=",
30
+ neq: "<>",
31
+ gt: ">",
32
+ gte: ">=",
33
+ lt: "<",
34
+ lte: "<="
35
+ }[n];
36
+ if (i === void 0) throw RangeError("Invalid decimal result comparison");
37
+ let a = Math.max(t.scale, r.scale), o = Math.max(t.digits - t.scale, r.digits - r.scale), s = ({ expression: e, digits: t, scale: n }) => {
38
+ let r = o - (t - n), i = a - n;
39
+ return `(CASE WHEN substr((${e}),1,1)='0' THEN '0${"9".repeat(r)}'||substr((${e}),2)||'${"9".repeat(i)}' ELSE '1${"0".repeat(r)}'||substr((${e}),2)||'${"0".repeat(i)}' END) COLLATE BINARY`;
40
+ };
41
+ return `(${s(t)} ${i} ${s(r)})`;
42
+ };
43
+ //#endregion
44
+ export { n as compileSqliteDecimalResult, r as compileSqliteDecimalResultComparison, t as sqliteDecimalResultKey };
@@ -0,0 +1,63 @@
1
+ import { getTable as e } from "./tableRegistry.js";
2
+ import { isSqliteDecimalEncodedColumn as t } from "./sqliteDecimalStorage.js";
3
+ import { prepareProjectedColumn as n } from "./projectedColumn.js";
4
+ import { compileSqliteDecimalDecodedRows as r } from "./sqliteDecimalColumnSql.js";
5
+ import { compileSqliteDecimalSource as i } from "./sqliteDecimalSource.js";
6
+ //#region src/sqliteDecimalRowQuery.ts
7
+ var a = (a, o, s, c, l) => {
8
+ if (a.groupBy?.length || a.having) throw Error("Row queries cannot contain aggregate clauses");
9
+ let u = n(a), d = a.sourceTable?.tableName === a.table ? a.sourceTable : e(a.table), f = a.joinedProjection ?? (a.projection?.length ? a.projection : Object.keys(d?.fields ?? {})).map((e) => ({
10
+ source: e.includes(".") ? e : `${a.alias ?? a.table}.${e}`,
11
+ outputKey: e.split(".").at(-1)
12
+ }));
13
+ if (!f.length) throw Error("Exact row projection requires declared source columns");
14
+ if (new Set(f.map((e) => e.outputKey)).size !== f.length) throw Error("Duplicate exact row output key");
15
+ let p = a.order.length >= 8 && f.length >= 8 ? new Map(f.map((e) => [e.outputKey, e.source])) : void 0, m = f.map((e, t) => {
16
+ let n = u(e.source);
17
+ if (!n) throw Error("Exact row projection requires declared source columns");
18
+ return {
19
+ ...e,
20
+ field: n,
21
+ internal: `v${t}`
22
+ };
23
+ }), h = a.order.map((e, t) => {
24
+ let n = (p === void 0 ? f.find((t) => t.outputKey === e.column)?.source : p.get(e.column)) ?? e.column, r = u(n);
25
+ if (!r) throw Error("Exact row order requires a declared source column");
26
+ return {
27
+ ...e,
28
+ source: n,
29
+ field: r,
30
+ internal: `o${t}`
31
+ };
32
+ });
33
+ for (let e of [a.take, a.skip]) if (e !== void 0 && (!Number.isSafeInteger(e) || e < 0)) throw Error("Invalid exact decimal pagination");
34
+ let { from: g, where: _ } = i(a, o, s), v = [...m, ...h], [y, b] = o`SELECT ${o.join(", ", !1)(v.map((e) => o`${o(e.source)} AS ${o(e.internal)}`))} FROM ${g}${_}`.compile(), x = l ?? c, S = x?.prefix ?? "__voltro_decimal_rows_";
35
+ for (; y.toLowerCase().includes(S.toLowerCase());) S += "_";
36
+ let C = [], w = (e, t) => {
37
+ x ? x.append(e, t) : C.push(`${e} AS MATERIALIZED (${t})`);
38
+ }, T = `${S}input`;
39
+ w(T, y);
40
+ let E = m.filter((e) => t(e.field));
41
+ if (c) for (let e of E) c.encodedOutput(e.outputKey);
42
+ let D = r(T, c ? [] : E.map((e) => ({
43
+ name: e.internal,
44
+ shape: {
45
+ precision: e.field.precision,
46
+ scale: e.field.scale
47
+ }
48
+ })), v.map((e) => e.internal), {
49
+ prefix: S,
50
+ append: w
51
+ });
52
+ T = D.source;
53
+ let O = m.map((e) => {
54
+ let t = D.values.get(e.internal);
55
+ return o`${t ? o.unsafe(t) : e.field.type === "bigint" ? o`CAST(${o(e.internal)} AS TEXT)` : o`${o(e.internal)}`} AS ${o(e.outputKey)}`;
56
+ }), k = h.length ? o` ORDER BY ${o.join(", ", !1)(h.map((e) => {
57
+ let n = t(e.field) ? o`${o(e.internal)} COLLATE BINARY` : o`${o(e.internal)}`;
58
+ return e.direction === "desc" ? o`${n} DESC` : o`${n} ASC`;
59
+ }))}` : o``, A = a.take === void 0 ? a.skip === void 0 ? o`` : o` LIMIT -1` : o` LIMIT ${a.take}`, j = a.skip === void 0 ? o`` : o` OFFSET ${a.skip}`, M = C.length ? `WITH ${C.join(",")} ` : "", N = o`SELECT ${a.distinct ? o`DISTINCT ` : o``}${o.join(", ", !1)(O)} FROM ${o(T)}${k}${A}${j}`.compile();
60
+ return o.unsafe(M + N[0], [...b, ...N[1]]);
61
+ };
62
+ //#endregion
63
+ export { a as compileSqliteDecimalRowQuery };