@happyvertical/sql 0.112.1 → 0.112.3

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 (51) hide show
  1. package/AGENT.md +65 -3
  2. package/README.md +146 -19
  3. package/dist/aggregate-expression.d.ts +77 -3
  4. package/dist/aggregate-expression.d.ts.map +1 -1
  5. package/dist/aggregate.d.ts +3 -2
  6. package/dist/aggregate.d.ts.map +1 -1
  7. package/dist/chunks/{duckdb-CpeXdf0i.js → duckdb-DCV4JFWK.js} +23 -52
  8. package/dist/chunks/duckdb-DCV4JFWK.js.map +1 -0
  9. package/dist/chunks/{postgres-dialect-DIy5f5YR.js → postgres-dialect-CaNhva-C.js} +28 -328
  10. package/dist/chunks/postgres-dialect-CaNhva-C.js.map +1 -0
  11. package/dist/chunks/query-Dz0TZ0pY.js +970 -0
  12. package/dist/chunks/query-Dz0TZ0pY.js.map +1 -0
  13. package/dist/chunks/{schema-manager-tfASrb_b.js → schema-manager-psLzQ2yh.js} +471 -18
  14. package/dist/chunks/schema-manager-psLzQ2yh.js.map +1 -0
  15. package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js → sqlite-connection-cache-BycfrYfi.js} +2 -2
  16. package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js.map → sqlite-connection-cache-BycfrYfi.js.map} +1 -1
  17. package/dist/chunks/{sqlite-BdM-nAQD.js → sqlite-nNhv0FMq.js} +22 -22
  18. package/dist/chunks/sqlite-nNhv0FMq.js.map +1 -0
  19. package/dist/chunks/{sqlite-native-DngobJtv.js → sqlite-native-CZGNm9zh.js} +40 -37
  20. package/dist/chunks/sqlite-native-CZGNm9zh.js.map +1 -0
  21. package/dist/doctor.d.ts.map +1 -1
  22. package/dist/duckdb.d.ts.map +1 -1
  23. package/dist/index.d.ts +3 -2
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +44 -77
  26. package/dist/index.js.map +1 -1
  27. package/dist/json.d.ts.map +1 -1
  28. package/dist/pglite.js +2 -2
  29. package/dist/query.d.ts +3 -0
  30. package/dist/query.d.ts.map +1 -1
  31. package/dist/query.js +3 -3
  32. package/dist/schema-manager.d.ts.map +1 -1
  33. package/dist/shared/alter-utils.d.ts +43 -7
  34. package/dist/shared/alter-utils.d.ts.map +1 -1
  35. package/dist/shared/duckdb-schema-utils.d.ts.map +1 -1
  36. package/dist/shared/postgres-dialect.d.ts.map +1 -1
  37. package/dist/shared/types.d.ts +1 -0
  38. package/dist/shared/types.d.ts.map +1 -1
  39. package/dist/shared/utils.d.ts +12 -1
  40. package/dist/shared/utils.d.ts.map +1 -1
  41. package/dist/sqlite-native.d.ts.map +1 -1
  42. package/dist/sqlite.d.ts.map +1 -1
  43. package/metadata.json +4 -4
  44. package/package.json +4 -4
  45. package/dist/chunks/duckdb-CpeXdf0i.js.map +0 -1
  46. package/dist/chunks/postgres-dialect-DIy5f5YR.js.map +0 -1
  47. package/dist/chunks/query-i6IIkNhF.js +0 -564
  48. package/dist/chunks/query-i6IIkNhF.js.map +0 -1
  49. package/dist/chunks/schema-manager-tfASrb_b.js.map +0 -1
  50. package/dist/chunks/sqlite-BdM-nAQD.js.map +0 -1
  51. package/dist/chunks/sqlite-native-DngobJtv.js.map +0 -1
@@ -0,0 +1,970 @@
1
+ import { _ as quoteLiteralIdentifier, a as parseConditionKey, h as isLegacyNumericSqlToken, l as unwrapRawKey, m as identifierParts, o as raw, r as buildWhere, x as renderIdentifier } from "./schema-manager-psLzQ2yh.js";
2
+ import { DatabaseError } from "@happyvertical/utils";
3
+ //#region src/aggregate-expression.ts
4
+ var MAX_DEPTH = 24;
5
+ /** Node budget for a whole spec (every select item, join, filter and predicate together). */
6
+ var MAX_NODES = 1024;
7
+ var ARITHMETIC = {
8
+ add: "+",
9
+ sub: "-",
10
+ mul: "*",
11
+ div: "/"
12
+ };
13
+ var COMPARISON = {
14
+ eq: "=",
15
+ ne: "<>",
16
+ lt: "<",
17
+ lte: "<=",
18
+ gt: ">",
19
+ gte: ">="
20
+ };
21
+ function isRecord(value) {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+ function literal(value, state) {
25
+ const { ctx } = state;
26
+ if (isRecord(value) && "kind" in value) return typedDate(value, state);
27
+ if (value === null) return "NULL";
28
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
29
+ if (typeof value === "number") {
30
+ if (!Number.isFinite(value)) throw new ExpressionError("INVALID_EXPRESSION", "Aggregate expression numbers must be finite");
31
+ return String(value);
32
+ }
33
+ if (value instanceof Date) {
34
+ if (Number.isNaN(value.getTime())) throw new ExpressionError("INVALID_EXPRESSION", "Aggregate expression dates must be valid");
35
+ if (ctx.mode === "ddl") fail("NON_IMMUTABLE", "Legacy Date literals are not immutable; use a typed date literal");
36
+ const placeholder = `$${ctx.nextIndex++}`;
37
+ ctx.values.push(value.toISOString());
38
+ if (ctx.adapterType === "duckdb" || ctx.adapterType === "json") return `CAST(${placeholder} AS TIMESTAMP)`;
39
+ if (ctx.adapterType === "postgres") return `CAST(${placeholder} AS TIMESTAMPTZ)`;
40
+ return placeholder;
41
+ }
42
+ if (typeof value === "string") {
43
+ if (ctx.mode && value.includes("\0")) fail("INVALID_EXPRESSION", "NUL is not a portable SQL string");
44
+ if (ctx.mode === "ddl") return quoteString(value, ctx.adapterType === "postgres");
45
+ const placeholder = `$${ctx.nextIndex++}`;
46
+ ctx.values.push(value);
47
+ return placeholder;
48
+ }
49
+ throw new ExpressionError("INVALID_EXPRESSION", "Aggregate expression literal must be a string, number, boolean, Date or null");
50
+ }
51
+ function secondsBetween(adapterType, later, earlier) {
52
+ if (adapterType === "postgres") return `CAST(EXTRACT(EPOCH FROM (${later} - ${earlier})) AS DOUBLE PRECISION)`;
53
+ if (adapterType === "duckdb" || adapterType === "json") return `epoch(${later}) - epoch(${earlier})`;
54
+ return `((julianday(${later}) - julianday(${earlier})) * 86400.0)`;
55
+ }
56
+ function renderOperandUnchecked(node, state, depth) {
57
+ if (depth > MAX_DEPTH) throw new ExpressionError("EXPRESSION_LIMIT", `Aggregate expression is nested deeper than ${MAX_DEPTH}`);
58
+ state.ctx.nodeCount = (state.ctx.nodeCount ?? 0) + 1;
59
+ if (state.ctx.nodeCount > MAX_NODES) throw new ExpressionError("EXPRESSION_LIMIT", `Aggregate expression has more than ${MAX_NODES} nodes`);
60
+ if (!isRecord(node)) throw new ExpressionError("INVALID_EXPRESSION", "Aggregate expression node must be an object");
61
+ const { ctx } = state;
62
+ if (ctx.mode || typeof node.op === "string" && Object.hasOwn(PORTABLE_FIELDS, node.op)) validateShape(node);
63
+ if ("col" in node) {
64
+ ctx.onColumn?.(node.col);
65
+ return ctx.identifier(node.col);
66
+ }
67
+ if ("value" in node && !("op" in node)) return literal(node.value, state);
68
+ const op = node.op;
69
+ const child = (value) => renderOperand(value, state, depth + 1);
70
+ if (typeof op === "string" && Object.hasOwn(ARITHMETIC, op)) {
71
+ const arithmetic = op;
72
+ const left = child(node.left);
73
+ const right = child(node.right);
74
+ if (arithmetic === "div") {
75
+ const quotient = `((${left} * 1.0) / NULLIF(${right}, 0))`;
76
+ if (ctx.adapterType === "postgres") return `CAST(${quotient} AS DOUBLE PRECISION)`;
77
+ if (ctx.adapterType === "duckdb" || ctx.adapterType === "json") return `CAST(${quotient} AS DOUBLE)`;
78
+ return quotient;
79
+ }
80
+ return `(${left} ${ARITHMETIC[arithmetic]} ${right})`;
81
+ }
82
+ if (op === "secondsBetween") {
83
+ if (ctx.mode === "ddl") {
84
+ requireTemporal(node.later, state);
85
+ requireTemporal(node.earlier, state);
86
+ }
87
+ return secondsBetween(ctx.adapterType, temporalSeconds(node.later, child(node.later), ctx), temporalSeconds(node.earlier, child(node.earlier), ctx));
88
+ }
89
+ if (typeof op === "string" && Object.hasOwn(COMPARISON, op)) {
90
+ const comparison = op;
91
+ const against = (side) => isRecord(side) && "value" in side && side.value === null;
92
+ if ((comparison === "eq" || comparison === "ne") && against(node.right)) return `(${child(node.left)} IS ${comparison === "eq" ? "NULL" : "NOT NULL"})`;
93
+ if ((comparison === "eq" || comparison === "ne") && against(node.left)) return `(${child(node.right)} IS ${comparison === "eq" ? "NULL" : "NOT NULL"})`;
94
+ return `(${child(node.left)} ${COMPARISON[comparison]} ${child(node.right)})`;
95
+ }
96
+ if (op === "and" || op === "or") {
97
+ const operands = node.operands;
98
+ if (!Array.isArray(operands) || operands.length === 0) throw new ExpressionError("INVALID_EXPRESSION", `Aggregate expression ${op} requires at least one operand`);
99
+ return `(${operands.map(child).join(op === "and" ? " AND " : " OR ")})`;
100
+ }
101
+ if (op === "not") return `(NOT ${child(node.operand)})`;
102
+ if (op === "isNull" || op === "isNotNull") return `(${child(node.operand)} IS ${op === "isNull" ? "NULL" : "NOT NULL"})`;
103
+ if (op === "coalesce") {
104
+ const operands = node.operands;
105
+ if (!Array.isArray(operands) || operands.length === 0) throw new ExpressionError("INVALID_EXPRESSION", "Aggregate expression coalesce requires at least one operand");
106
+ return `COALESCE(${operands.map(child).join(", ")})`;
107
+ }
108
+ if (op === "asText") {
109
+ if (ctx.mode === "ddl" && ![
110
+ "number",
111
+ "text",
112
+ "boolean",
113
+ "null"
114
+ ].includes(resultType(node.operand, ctx))) fail("NON_IMMUTABLE", "Generated asText requires known number/text/boolean input; date output depends on session settings");
115
+ const type = ctx.adapterType === "duckdb" || ctx.adapterType === "json" ? "VARCHAR" : "TEXT";
116
+ return `CAST(${child(node.operand)} AS ${type})`;
117
+ }
118
+ const portable = renderPortable(node, state, child);
119
+ if (portable !== void 0) return portable;
120
+ throw new ExpressionError("INVALID_EXPRESSION", `Unsupported aggregate expression operator: ${String(op)}`);
121
+ }
122
+ /**
123
+ * Render an expression node to SQL, binding its string and date literals into
124
+ * `ctx` as numbered parameters. Throws on any unknown operator, unsafe
125
+ * identifier, non-finite number, or an expression too large to be legitimate.
126
+ */
127
+ function renderAggregateExpression(node, ctx) {
128
+ let sql = renderOperand(node, { ctx }, 0);
129
+ if (resultType(node, ctx) === "date" && isRecord(node) && "op" in node) {
130
+ if (ctx.adapterType === "postgres") sql = postgresDateISO(sql);
131
+ else if (ctx.adapterType === "duckdb" || ctx.adapterType === "json") sql = `CAST(${sql} AS VARCHAR)`;
132
+ ctx.sqlWork = (ctx.sqlWork ?? 0) + sql.length;
133
+ if (ctx.sqlWork > MAX_SQL_WORK) fail("EXPRESSION_LIMIT", "Expression date output exceeds SQL limit");
134
+ }
135
+ return sql;
136
+ }
137
+ /** Coded validation failures suitable for persisted/untrusted expression data. */
138
+ var ExpressionError = class extends Error {
139
+ code;
140
+ constructor(code, message) {
141
+ super(message);
142
+ this.code = code;
143
+ this.name = "ExpressionError";
144
+ }
145
+ };
146
+ function fail(code, message) {
147
+ throw new ExpressionError(code, message);
148
+ }
149
+ var MAX_SQL_WORK = 262144;
150
+ function renderOperand(node, state, depth) {
151
+ const sql = renderOperandUnchecked(node, state, depth);
152
+ state.ctx.sqlWork = (state.ctx.sqlWork ?? 0) + sql.length;
153
+ if (state.ctx.sqlWork > MAX_SQL_WORK) fail("EXPRESSION_LIMIT", `Expression SQL exceeds ${MAX_SQL_WORK} characters of rendering work`);
154
+ return sql;
155
+ }
156
+ function quoteString(value, postgres = false) {
157
+ if (postgres) return `(E'${value.replace(/\\/g, "\\\\").replace(/'/g, "''")}' COLLATE "C")`;
158
+ return `'${value.replace(/'/g, "''")}'`;
159
+ }
160
+ function typedDate(value, state) {
161
+ const { kind, iso } = value;
162
+ if (kind !== "date" && kind !== "datetime" || typeof iso !== "string" || Object.keys(value).some((key) => key !== "kind" && key !== "iso")) fail("INVALID_EXPRESSION", "Expected typed date {kind, iso}");
163
+ const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso);
164
+ if (!match || Number(match[1]) < 1) fail("INVALID_EXPRESSION", "Invalid ISO calendar date");
165
+ const year = Number(match[1]);
166
+ const month = Number(match[2]);
167
+ const day = Number(match[3]);
168
+ const days = [
169
+ 31,
170
+ year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28,
171
+ 31,
172
+ 30,
173
+ 31,
174
+ 30,
175
+ 31,
176
+ 31,
177
+ 30,
178
+ 31,
179
+ 30,
180
+ 31
181
+ ];
182
+ if (month < 1 || month > 12 || day < 1 || day > days[month - 1]) fail("INVALID_EXPRESSION", "Invalid ISO calendar date");
183
+ let canonical = iso;
184
+ if (kind === "date") {
185
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(iso)) fail("INVALID_EXPRESSION", "Date requires YYYY-MM-DD");
186
+ } else {
187
+ if (!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,3})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(iso)) fail("INVALID_EXPRESSION", "Datetime requires ISO seconds and an explicit UTC offset");
188
+ const date = new Date(iso);
189
+ if (!Number.isFinite(date.getTime())) fail("INVALID_EXPRESSION", "Invalid ISO datetime");
190
+ canonical = date.toISOString();
191
+ if (!/^\d{4}-/.test(canonical) || canonical.startsWith("0000")) fail("INVALID_EXPRESSION", "Datetime outside years 0001..9999");
192
+ }
193
+ const { ctx } = state;
194
+ let sql;
195
+ if (ctx.mode === "ddl") sql = quoteString(canonical, ctx.adapterType === "postgres");
196
+ else {
197
+ sql = `$${ctx.nextIndex++}`;
198
+ ctx.values.push(canonical);
199
+ }
200
+ if (ctx.adapterType === "postgres" || ctx.adapterType === "duckdb" || ctx.adapterType === "json") {
201
+ if (kind === "datetime") {
202
+ const utc = canonical.slice(0, -1).replace("T", " ");
203
+ if (ctx.mode === "ddl") sql = quoteString(utc, ctx.adapterType === "postgres");
204
+ else ctx.values[ctx.values.length - 1] = utc;
205
+ }
206
+ return `CAST(${sql} AS ${kind === "date" ? "DATE" : "TIMESTAMP"})`;
207
+ }
208
+ return sql;
209
+ }
210
+ function resultType(node, ctx, depth = 0, budget = { nodes: 0 }) {
211
+ if (depth > MAX_DEPTH || ++budget.nodes > MAX_NODES) fail("EXPRESSION_LIMIT", "Expression type analysis exceeds depth/node limit");
212
+ if (!isRecord(node)) return "unknown";
213
+ if ("col" in node) return ctx.columnType?.(node.col) ?? "unknown";
214
+ if (!("op" in node) && "value" in node) {
215
+ const value = node.value;
216
+ if (value === null) return "null";
217
+ if (value instanceof Date) return "unknown";
218
+ if (isRecord(value) && (value.kind === "date" || value.kind === "datetime")) return value.kind;
219
+ if (typeof value === "number") return "number";
220
+ if (typeof value === "boolean") return "boolean";
221
+ if (typeof value === "string") return "text";
222
+ }
223
+ const op = node.op;
224
+ if (typeof op === "string" && (Object.hasOwn(ARITHMETIC, op) || Object.hasOwn(COMPARISON, op))) return Object.hasOwn(ARITHMETIC, op) ? "number" : "boolean";
225
+ if ([
226
+ "and",
227
+ "or",
228
+ "not",
229
+ "isNull",
230
+ "isNotNull"
231
+ ].includes(op)) return "boolean";
232
+ if ([
233
+ "round",
234
+ "abs",
235
+ "floor",
236
+ "ceil",
237
+ "least",
238
+ "greatest",
239
+ "mod",
240
+ "length",
241
+ "year",
242
+ "month",
243
+ "day",
244
+ "daysBetween",
245
+ "secondsBetween"
246
+ ].includes(op)) return "number";
247
+ if ([
248
+ "concat",
249
+ "lower",
250
+ "upper",
251
+ "trim",
252
+ "substring",
253
+ "asText"
254
+ ].includes(op)) return "text";
255
+ if (op === "addDays") return "date";
256
+ const merge = (nodes) => {
257
+ const types = nodes.map((n) => resultType(n, ctx, depth + 1, budget)).filter((t) => t !== "null");
258
+ return !types.length ? "null" : types.every((t) => t === types[0]) ? types[0] : "unknown";
259
+ };
260
+ if (op === "if") return merge([node.then, node.else]);
261
+ if (op === "case" && Array.isArray(node.branches)) return merge([...node.branches.map((b) => isRecord(b) ? b.then : void 0), node.else]);
262
+ if (op === "coalesce" && Array.isArray(node.operands)) return merge(node.operands);
263
+ return "unknown";
264
+ }
265
+ function requireTemporal(node, state) {
266
+ const type = resultType(node, state.ctx);
267
+ if (type !== "date" && type !== "datetime" && type !== "null") fail("NON_IMMUTABLE", "Generated date operations require typed date/datetime operands (timezone-free UTC); unknown or timestamptz columns are unsafe");
268
+ }
269
+ /** Guard portable integer arguments; dynamic out-of-range inputs yield NULL. */
270
+ function integerArg(node, sql, min, max) {
271
+ if (isRecord(node) && !("op" in node) && "value" in node && node.value !== null) {
272
+ if (typeof node.value !== "number" || !Number.isInteger(node.value) || node.value < min || node.value > max) fail("INVALID_EXPRESSION", `Expected integer argument in ${min}..${max}`);
273
+ }
274
+ return `CASE WHEN ${sql} BETWEEN ${min} AND ${max} THEN CASE WHEN ${sql} = CAST(${sql} AS INTEGER) THEN CAST(${sql} AS INTEGER) ELSE NULL END ELSE NULL END`;
275
+ }
276
+ function renderPortable(node, state, child) {
277
+ const { op } = node;
278
+ const pg = state.ctx.adapterType === "postgres";
279
+ const duck = state.ctx.adapterType === "duckdb" || state.ctx.adapterType === "json";
280
+ const numeric = (sql) => pg ? `CAST(${sql} AS DOUBLE PRECISION)` : duck ? `CAST(${sql} AS DOUBLE)` : sql;
281
+ const strict = (args, body) => `(CASE WHEN ${args.map((a) => `${a} IS NULL`).join(" OR ")} THEN NULL ELSE ${body} END)`;
282
+ if (op === "case" || op === "if") {
283
+ const branches = op === "if" ? [{
284
+ when: node.condition,
285
+ then: node.then
286
+ }] : node.branches;
287
+ if (!Array.isArray(branches) || branches.length === 0) fail("INVALID_EXPRESSION", "case requires at least one when/then branch");
288
+ const expression = `(CASE ${branches.map((b) => {
289
+ if (!isRecord(b)) fail("INVALID_EXPRESSION", "case branch requires when/then");
290
+ return `WHEN ${child(b.when)} THEN ${child(b.then)}`;
291
+ }).join(" ")} ELSE ${child(node.else)} END)`;
292
+ return resultType(node, state.ctx) === "number" ? numeric(expression) : expression;
293
+ }
294
+ if (op === "least" || op === "greatest" || op === "concat") {
295
+ if (!Array.isArray(node.operands) || node.operands.length < (op === "concat" ? 1 : 2)) fail("INVALID_EXPRESSION", `${op} requires at least ${op === "concat" ? 1 : 2} operands`);
296
+ const args = node.operands.map(child);
297
+ if (op === "concat") return `(${args.join(" || ")})`;
298
+ return numeric(strict(args, `${!pg && !duck ? op === "least" ? "MIN" : "MAX" : op.toUpperCase()}(${args.join(", ")})`));
299
+ }
300
+ if (op === "mod") {
301
+ const left = child(node.left), right = child(node.right);
302
+ const quotient = `((${left} * 1.0) / NULLIF(${right}, 0))`;
303
+ return numeric(`(${left} - (CASE WHEN ${quotient} < 0 THEN ${!pg && !duck ? sqliteIntegral(quotient, "ceil") : `CEIL(${quotient})`} ELSE ${!pg && !duck ? sqliteIntegral(quotient, "floor") : `FLOOR(${quotient})`} END) * ${right})`);
304
+ }
305
+ if (op === "round") {
306
+ const value = child(node.value), digitsSql = child(node.digits);
307
+ const digits = integerArg(node.digits, digitsSql, -12, 12);
308
+ if (pg) return `CAST(ROUND(CAST(${value} AS NUMERIC), (${digits})) AS DOUBLE PRECISION)`;
309
+ if (duck) return `ROUND(CAST(${value} AS DOUBLE), (${digits}))`;
310
+ const factor = `(CASE (${digits}) ${Array.from({ length: 12 }, (_, i) => `WHEN -${i + 1} THEN ${10 ** (i + 1)}`).join(" ")} ELSE NULL END)`;
311
+ return `(CASE WHEN (${digits}) < 0 THEN ROUND((${value} * 1.0) / ${factor}, 0) * ${factor} ELSE ROUND(${value}, (${digits})) END)`;
312
+ }
313
+ if (op === "substring") {
314
+ const value = child(node.value), start = child(node.start), length = child(node.length);
315
+ return `SUBSTR(${value}, (${integerArg(node.start, start, 1, 2147483647)}), (${integerArg(node.length, length, 0, 2147483647)}))`;
316
+ }
317
+ if (op === "daysBetween") {
318
+ if (state.ctx.mode === "ddl") {
319
+ requireTemporal(node.later, state);
320
+ requireTemporal(node.earlier, state);
321
+ }
322
+ const later = child(node.later), earlier = child(node.earlier);
323
+ if (pg || duck) return `CAST((CAST(${later} AS DATE) - CAST(${earlier} AS DATE)) AS ${pg ? "DOUBLE PRECISION" : "DOUBLE"})`;
324
+ return `(julianday(DATE(${later})) - julianday(DATE(${earlier})))`;
325
+ }
326
+ if (op === "addDays") {
327
+ if (state.ctx.mode === "ddl") requireTemporal(node.value, state);
328
+ const value = child(node.value), daysSql = child(node.days);
329
+ const days = integerArg(node.days, daysSql, -365e3, 365e3);
330
+ const added = pg || duck ? `(CAST(${value} AS DATE) + (${days}))` : `DATE(${value}, CAST((${days}) AS TEXT) || ' days')`;
331
+ const bound = (iso) => pg || duck ? `CAST('${iso}' AS DATE)` : `'${iso}'`;
332
+ return `(CASE WHEN ${added} BETWEEN ${bound("0001-01-01")} AND ${bound("9999-12-31")} THEN ${added} ELSE NULL END)`;
333
+ }
334
+ if (op === "year" || op === "month" || op === "day") {
335
+ if (state.ctx.mode === "ddl") requireTemporal(node.value, state);
336
+ const value = child(node.value);
337
+ if (pg || duck) return `CAST(EXTRACT(${op.toUpperCase()} FROM CAST(${value} AS TIMESTAMP)) AS INTEGER)`;
338
+ return `CAST(STRFTIME('${op === "year" ? "%Y" : op === "month" ? "%m" : "%d"}', ${value}) AS INTEGER)`;
339
+ }
340
+ if (op === "lower" || op === "upper") {
341
+ let value = child(node.value);
342
+ if (pg) return `TRANSLATE(${value}, '${op === "lower" ? "ABCDEFGHIJKLMNOPQRSTUVWXYZ" : "abcdefghijklmnopqrstuvwxyz"}', '${op === "lower" ? "abcdefghijklmnopqrstuvwxyz" : "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}')`;
343
+ for (let i = 0; i < 26; i++) {
344
+ const upper = String.fromCharCode(65 + i), lower = String.fromCharCode(97 + i);
345
+ value = `REPLACE(${value}${pg ? " COLLATE \"C\"" : ""}, ${quoteString(op === "lower" ? upper : lower, pg)}, ${quoteString(op === "lower" ? lower : upper, pg)})`;
346
+ }
347
+ return value;
348
+ }
349
+ if ((op === "floor" || op === "ceil") && !pg && !duck) return sqliteIntegral(child(node.value), op);
350
+ if (op === "abs" || op === "floor" || op === "ceil" || op === "trim" || op === "length") return [
351
+ "abs",
352
+ "floor",
353
+ "ceil"
354
+ ].includes(op) ? numeric(`${op.toUpperCase()}(${child(node.value)})`) : `${op.toUpperCase()}(${child(node.value)})`;
355
+ }
356
+ /** Render a closed scalar expression. DDL additionally requires immutability. */
357
+ function renderExpression$1(node, options) {
358
+ if (![
359
+ "sqlite",
360
+ "postgres",
361
+ "duckdb",
362
+ "json"
363
+ ].includes(options.dialect) || !["ddl", "query"].includes(options.mode)) fail("INVALID_EXPRESSION", "Invalid expression dialect or mode");
364
+ const columns = /* @__PURE__ */ new Map();
365
+ const resolve = (name) => {
366
+ if (typeof name !== "string" || !name.length || name.includes("\0")) fail("INVALID_EXPRESSION", "Invalid expression column");
367
+ let column = columns.get(name);
368
+ if (!column) {
369
+ const found = options.resolveColumn?.(name) ?? name;
370
+ column = typeof found === "string" ? {
371
+ name: found,
372
+ type: "unknown"
373
+ } : found;
374
+ if (!column || typeof column.name !== "string" || !column.name.length || column.name.includes("\0") || column.name.split(".").some((p) => !p)) fail("INVALID_EXPRESSION", "Invalid resolved column identifier");
375
+ columns.set(name, column);
376
+ }
377
+ return column;
378
+ };
379
+ const ctx = {
380
+ adapterType: options.dialect,
381
+ nextIndex: 1,
382
+ values: [],
383
+ mode: options.mode,
384
+ identifier: (name) => resolve(name).name.split(".").map(quoteLiteralIdentifier).join("."),
385
+ columnType: (name) => resolve(name).type
386
+ };
387
+ const sql = renderAggregateExpression(node, ctx);
388
+ const immutable = {
389
+ sqlite: true,
390
+ postgres: true,
391
+ duckdb: true
392
+ };
393
+ for (const dialect of [
394
+ "sqlite",
395
+ "postgres",
396
+ "duckdb"
397
+ ]) try {
398
+ renderAggregateExpression(node, {
399
+ ...ctx,
400
+ adapterType: dialect,
401
+ mode: "ddl",
402
+ nextIndex: 1,
403
+ values: [],
404
+ nodeCount: 0,
405
+ sqlWork: 0
406
+ });
407
+ } catch (error) {
408
+ if (error instanceof ExpressionError && error.code === "NON_IMMUTABLE") immutable[dialect] = false;
409
+ else throw error;
410
+ }
411
+ if (options.mode === "ddl" && !Object.values(immutable).every(Boolean)) fail("NON_IMMUTABLE", "Expression must be immutable on every dialect for generated use");
412
+ return {
413
+ sql,
414
+ values: ctx.values,
415
+ resultType: resultType(node, ctx),
416
+ immutable
417
+ };
418
+ }
419
+ function sqliteIntegral(value, op) {
420
+ const trunc = `CAST(${value} AS INTEGER)`;
421
+ return `(CASE WHEN ${value} >= 4503599627370496 OR ${value} <= -4503599627370496 THEN ${value} WHEN ${trunc} ${op === "floor" ? ">" : "<"} ${value} THEN ${trunc} ${op === "floor" ? "-" : "+"} 1 ELSE ${trunc} END)`;
422
+ }
423
+ function postgresDateISO(value) {
424
+ const part = (unit, width) => `LPAD(CAST(CAST(EXTRACT(${unit} FROM ${value}) AS INTEGER) AS TEXT), ${width}, '0')`;
425
+ return `(${part("YEAR", 4)} || '-' || ${part("MONTH", 2)} || '-' || ${part("DAY", 2)})`;
426
+ }
427
+ var PORTABLE_FIELDS = {
428
+ case: ["branches", "else"],
429
+ if: [
430
+ "condition",
431
+ "then",
432
+ "else"
433
+ ],
434
+ round: ["value", "digits"],
435
+ abs: ["value"],
436
+ floor: ["value"],
437
+ ceil: ["value"],
438
+ lower: ["value"],
439
+ upper: ["value"],
440
+ trim: ["value"],
441
+ length: ["value"],
442
+ year: ["value"],
443
+ month: ["value"],
444
+ day: ["value"],
445
+ least: ["operands"],
446
+ greatest: ["operands"],
447
+ concat: ["operands"],
448
+ mod: ["left", "right"],
449
+ substring: [
450
+ "value",
451
+ "start",
452
+ "length"
453
+ ],
454
+ daysBetween: ["later", "earlier"],
455
+ addDays: ["value", "days"]
456
+ };
457
+ function validateShape(node) {
458
+ let fields;
459
+ if (!("op" in node)) fields = "col" in node ? ["col"] : ["value"];
460
+ else {
461
+ const op = node.op;
462
+ if (typeof op !== "string") fail("INVALID_EXPRESSION", "Expression requires an operator");
463
+ if (Object.hasOwn(PORTABLE_FIELDS, op)) fields = ["op", ...PORTABLE_FIELDS[op]];
464
+ else if (Object.hasOwn(ARITHMETIC, op) || Object.hasOwn(COMPARISON, op)) fields = [
465
+ "op",
466
+ "left",
467
+ "right"
468
+ ];
469
+ else if (op === "secondsBetween") fields = [
470
+ "op",
471
+ "later",
472
+ "earlier"
473
+ ];
474
+ else if ([
475
+ "and",
476
+ "or",
477
+ "coalesce"
478
+ ].includes(op)) fields = ["op", "operands"];
479
+ else if ([
480
+ "not",
481
+ "isNull",
482
+ "isNotNull",
483
+ "asText"
484
+ ].includes(op)) fields = ["op", "operand"];
485
+ else fail("INVALID_EXPRESSION", `Unsupported aggregate expression operator: ${op}`);
486
+ }
487
+ if (fields.some((key) => !Object.hasOwn(node, key)) || Object.keys(node).some((key) => !fields.includes(key))) fail("INVALID_EXPRESSION", "Expression has missing or unknown fields");
488
+ if (node.op === "case" && Array.isArray(node.branches)) {
489
+ for (const b of node.branches) if (!isRecord(b) || Object.keys(b).length !== 2 || !Object.hasOwn(b, "when") || !Object.hasOwn(b, "then")) fail("INVALID_EXPRESSION", "case branch requires only when/then");
490
+ }
491
+ }
492
+ function temporalSeconds(node, sql, ctx) {
493
+ if ((ctx.adapterType === "postgres" || ctx.adapterType === "duckdb" || ctx.adapterType === "json") && resultType(node, ctx) === "date") return `CAST(${sql} AS TIMESTAMP)`;
494
+ return sql;
495
+ }
496
+ //#endregion
497
+ //#region src/aggregate.ts
498
+ var EXPRESSION_AGGREGATES = /* @__PURE__ */ new Set([
499
+ "count",
500
+ "sum",
501
+ "avg",
502
+ "min",
503
+ "max"
504
+ ]);
505
+ var VALID_DIRECTIONS = /* @__PURE__ */ new Set(["ASC", "DESC"]);
506
+ var VALID_BUCKET_UNITS = /* @__PURE__ */ new Set([
507
+ "minute",
508
+ "hour",
509
+ "day",
510
+ "week",
511
+ "month",
512
+ "quarter",
513
+ "year"
514
+ ]);
515
+ function aggregateIdentifierParts(identifier) {
516
+ if (isLegacyNumericSqlToken(identifier)) return identifier.split(".").map((name) => ({
517
+ name,
518
+ exact: false
519
+ }));
520
+ return identifierParts(identifier);
521
+ }
522
+ function validateSqlIdentifier(identifier) {
523
+ aggregateIdentifierParts(identifier);
524
+ return identifier;
525
+ }
526
+ function renderAggregateIdentifier(identifier, adapterType, options) {
527
+ return isLegacyNumericSqlToken(identifier) ? identifier : renderIdentifier(identifier, adapterType, options);
528
+ }
529
+ function normalizeAdapter(adapterType) {
530
+ return adapterType ?? "sqlite";
531
+ }
532
+ function placeholder(index) {
533
+ return `$${index}`;
534
+ }
535
+ function bucketExpr(adapterType, unit, column, options = {}) {
536
+ if (!VALID_BUCKET_UNITS.has(unit)) throw new Error(`Invalid aggregate bucket unit: ${unit}`);
537
+ const col = renderAggregateIdentifier(column, adapterType, options);
538
+ const adapter = normalizeAdapter(adapterType);
539
+ if (adapter === "postgres" || adapter === "duckdb" || adapter === "json") return `date_trunc('${unit}', ${col})`;
540
+ switch (unit) {
541
+ case "minute": return `strftime('%Y-%m-%d %H:%M:00', ${col})`;
542
+ case "hour": return `strftime('%Y-%m-%d %H:00:00', ${col})`;
543
+ case "day": return `strftime('%Y-%m-%d 00:00:00', ${col})`;
544
+ case "week": return `strftime('%Y-%m-%d 00:00:00', date(${col}, printf('-%d days', (CAST(strftime('%w', ${col}) AS INTEGER) + 6) % 7)))`;
545
+ case "month": return `strftime('%Y-%m-01 00:00:00', ${col})`;
546
+ case "quarter": return `strftime('%Y-%m-%d 00:00:00', date(strftime('%Y-', ${col}) || printf('%02d', ((CAST(strftime('%m', ${col}) AS INTEGER) - 1) / 3) * 3 + 1) || '-01'))`;
547
+ case "year": return `strftime('%Y-01-01 00:00:00', ${col})`;
548
+ }
549
+ }
550
+ function checkColumn(state, column) {
551
+ const { scope } = state;
552
+ const parts = aggregateIdentifierParts(column);
553
+ if (scope && parts.length > 1) {
554
+ if (parts.length !== 2 || !scope.has(parts[0].name)) throw new Error(`Aggregate column ${column} must be qualified by the from table or a join alias`);
555
+ }
556
+ return column;
557
+ }
558
+ function validateColumn(state, column) {
559
+ checkColumn(state, validateSqlIdentifier(column));
560
+ return state.ctx.identifier(column);
561
+ }
562
+ function renderExpression(state, node) {
563
+ return renderAggregateExpression(node, state.ctx);
564
+ }
565
+ function aggregateExpression(expr, state) {
566
+ const normalizedFn = String(expr.fn).toLowerCase();
567
+ const functionName = String(expr.fn);
568
+ if (!/^[a-zA-Z0-9_.]+$/.test(functionName)) throw new Error(`Invalid SQL identifier: ${functionName}`);
569
+ const fn = functionName.toUpperCase();
570
+ if (expr.column !== void 0 && expr.expr !== void 0) throw new Error(`Aggregate ${expr.fn} takes a column or an expr, not both`);
571
+ if ((expr.expr !== void 0 || expr.filter !== void 0) && !EXPRESSION_AGGREGATES.has(normalizedFn)) throw new Error(`Aggregate ${expr.fn} cannot take an expr or filter; use count, sum, avg, min or max`);
572
+ const hasArgument = Boolean(expr.column) || expr.expr !== void 0;
573
+ const filter = expr.filter !== void 0 ? renderExpression(state, expr.filter) : void 0;
574
+ if (normalizedFn === "count" && !hasArgument) {
575
+ if (expr.distinct) throw new Error(`Aggregate ${expr.fn} with distinct requires a column`);
576
+ return filter ? `COUNT(CASE WHEN ${filter} THEN 1 END)` : "COUNT(*)";
577
+ }
578
+ if (!hasArgument) throw new Error(`Aggregate ${expr.fn} requires a column`);
579
+ const argument = expr.expr !== void 0 ? renderExpression(state, expr.expr) : validateColumn(state, expr.column);
580
+ return `${fn}(${expr.distinct ? "DISTINCT " : ""}${filter ? `CASE WHEN ${filter} THEN ${argument} END` : argument})`;
581
+ }
582
+ function selectExpression(expr, adapterType, state) {
583
+ if ([
584
+ "fn" in expr,
585
+ "expr" in expr && !("fn" in expr),
586
+ "bucket" in expr
587
+ ].filter(Boolean).length > 1) throw new Error("Aggregate select item mixes fn, bucket and expr");
588
+ if ("fn" in expr) return {
589
+ expression: aggregateExpression(expr, state),
590
+ alias: validateSqlIdentifier(expr.as),
591
+ groupingCandidate: false,
592
+ computed: false
593
+ };
594
+ if ("expr" in expr) return {
595
+ expression: renderExpression(state, expr.expr),
596
+ alias: validateSqlIdentifier(expr.as),
597
+ groupingCandidate: true,
598
+ computed: true
599
+ };
600
+ if ("column" in expr && !("bucket" in expr)) return {
601
+ expression: validateColumn(state, expr.column),
602
+ alias: validateSqlIdentifier(expr.as ?? (() => {
603
+ const part = aggregateIdentifierParts(expr.column).at(-1);
604
+ if (!part) throw new Error(`Invalid SQL identifier: ${expr.column}`);
605
+ return part.exact ? quoteLiteralIdentifier(part.name) : part.name;
606
+ })()),
607
+ groupingCandidate: true,
608
+ computed: false
609
+ };
610
+ const column = expr.column;
611
+ validateColumn(state, column);
612
+ const bucket = expr.bucket;
613
+ return {
614
+ expression: bucketExpr(adapterType, bucket, column, state.options),
615
+ alias: validateSqlIdentifier(expr.as),
616
+ groupingCandidate: true,
617
+ computed: false
618
+ };
619
+ }
620
+ function expandHavingKey(key, expressionByAlias, identifier) {
621
+ if (unwrapRawKey(key).isRaw) return key;
622
+ const parsed = parseConditionKey(key);
623
+ return raw(`${expressionByAlias.get(parsed.field) ?? identifier(parsed.field)} ${parsed.operator}`);
624
+ }
625
+ function expandHaving(having, expressionByAlias, identifier) {
626
+ const expandCondition = (condition) => Object.fromEntries(Object.entries(condition).map(([key, value]) => [expandHavingKey(key, expressionByAlias, identifier), value]));
627
+ if (Array.isArray(having)) return having.map((andGroup) => andGroup.map((condition) => expandCondition(condition)));
628
+ return expandCondition(having);
629
+ }
630
+ function buildHaving(having, expressionByAlias, startIndex, adapterType, identifier) {
631
+ if (!having) return {
632
+ sql: "",
633
+ values: []
634
+ };
635
+ const built = buildWhere(expandHaving(having, expressionByAlias, identifier), startIndex, adapterType);
636
+ return {
637
+ sql: built.sql ? built.sql.replace(/^WHERE/, "HAVING") : "",
638
+ values: built.values
639
+ };
640
+ }
641
+ function buildOrderBy(orderBy, state, aliases) {
642
+ if (!orderBy) return "";
643
+ return `ORDER BY ${(Array.isArray(orderBy) ? orderBy : [orderBy]).map((item) => {
644
+ const match = /^((?:[^\s"]|"(?:[^"]|"")*")+)(?:\s+(\S+))?/.exec(item.trim());
645
+ const field = match?.[1] ?? item.trim();
646
+ const direction = match?.[2] ?? "ASC";
647
+ const normalizedDirection = direction.toUpperCase();
648
+ if (!VALID_DIRECTIONS.has(normalizedDirection)) throw new Error(`Invalid aggregate order direction: ${direction}`);
649
+ return `${aliases.has(field) ? state.renderName(field) : validateColumn(state, field)} ${normalizedDirection}`;
650
+ }).join(", ")}`;
651
+ }
652
+ var VALID_JOIN_TYPES = /* @__PURE__ */ new Set(["inner", "left"]);
653
+ var JOIN_ALIAS = /^[A-Za-z_][A-Za-z0-9_]*$/;
654
+ function buildScope(fromAlias, joins, from) {
655
+ if (joins.length === 0 && fromAlias === void 0) return void 0;
656
+ const scope = /* @__PURE__ */ new Set();
657
+ const claim = (name, what) => {
658
+ if (typeof name !== "string" || !JOIN_ALIAS.test(name)) throw new Error(`Invalid aggregate ${what}: ${name}`);
659
+ if (scope.has(name)) throw new Error(`Duplicate aggregate table name or alias: ${name}`);
660
+ scope.add(name);
661
+ };
662
+ if (fromAlias !== void 0) claim(fromAlias, "from alias");
663
+ else {
664
+ if (from.includes(".")) throw new Error("AggregateSpec.fromAlias is required when joining a schema-qualified from table");
665
+ claim(from, "from table");
666
+ }
667
+ for (const join of joins) claim(join.alias, "join alias");
668
+ return scope;
669
+ }
670
+ function joinSql(state, joins) {
671
+ return joins.map((join) => {
672
+ const type = join.type ?? "inner";
673
+ if (!VALID_JOIN_TYPES.has(type)) throw new Error(`Invalid aggregate join type: ${type}`);
674
+ if (join.on === void 0) throw new Error(`Aggregate join ${join.alias} requires an on condition`);
675
+ const table = state.renderName(join.table);
676
+ const alias = join.alias;
677
+ if (typeof alias !== "string" || !JOIN_ALIAS.test(alias)) throw new Error(`Invalid aggregate join alias: ${String(alias)}`);
678
+ const on = renderExpression(state, join.on);
679
+ return `${type === "left" ? "LEFT" : "INNER"} JOIN ${table} AS ${state.renderName(alias)} ON ${on}`;
680
+ });
681
+ }
682
+ function buildAggregate(spec, startIndex = 1, adapterType, options = {}) {
683
+ const from = validateSqlIdentifier(spec.from);
684
+ if (spec.select.length === 0) throw new Error("AggregateSpec.select must contain at least one expression");
685
+ if (spec.joins !== void 0 && !Array.isArray(spec.joins)) throw new Error("AggregateSpec.joins must be an array");
686
+ const values = [];
687
+ const ctx = {
688
+ adapterType,
689
+ nextIndex: startIndex,
690
+ values,
691
+ identifier: (name) => renderAggregateIdentifier(name, adapterType, options)
692
+ };
693
+ const fromAlias = spec.fromAlias;
694
+ const joins = (spec.joins ?? []).map((join) => ({
695
+ table: join.table,
696
+ alias: join.alias,
697
+ type: join.type,
698
+ on: join.on
699
+ }));
700
+ const state = {
701
+ ctx,
702
+ renderName: (name) => renderIdentifier(name, adapterType, options),
703
+ scope: buildScope(fromAlias, joins, from),
704
+ options
705
+ };
706
+ ctx.onColumn = (column) => {
707
+ checkColumn(state, column);
708
+ };
709
+ const expressionByAlias = /* @__PURE__ */ new Map();
710
+ const ordinalByAlias = /* @__PURE__ */ new Map();
711
+ const groupingAliases = [];
712
+ const selectSql = spec.select.map((expr, position) => {
713
+ const selected = selectExpression(expr, adapterType, state);
714
+ if (expressionByAlias.has(selected.alias)) throw new Error(`Duplicate aggregate select alias: ${selected.alias}`);
715
+ expressionByAlias.set(selected.alias, selected.expression);
716
+ if (selected.computed) ordinalByAlias.set(selected.alias, position + 1);
717
+ if (selected.groupingCandidate) groupingAliases.push(selected.alias);
718
+ return `${selected.expression} AS ${state.renderName(selected.alias)}`;
719
+ });
720
+ const joinParts = joinSql(state, joins);
721
+ const where = spec.where ? buildWhere(spec.where, ctx.nextIndex, adapterType, options) : {
722
+ sql: "",
723
+ values: []
724
+ };
725
+ values.push(...where.values);
726
+ ctx.nextIndex += where.values.length;
727
+ let whereSql = where.sql;
728
+ if (spec.whereExpr !== void 0) {
729
+ const predicate = renderExpression(state, spec.whereExpr);
730
+ whereSql = whereSql ? `WHERE (${whereSql.replace(/^WHERE /, "")}) AND ${predicate}` : `WHERE ${predicate}`;
731
+ }
732
+ const groupByItems = spec.groupBy ?? groupingAliases;
733
+ const groupBySql = groupByItems.length > 0 ? `GROUP BY ${groupByItems.map((item) => ordinalByAlias.has(item) ? String(ordinalByAlias.get(item)) : expressionByAlias.has(item) ? expressionByAlias.get(item) : validateColumn(state, item)).join(", ")}` : "";
734
+ const having = buildHaving(spec.having, expressionByAlias, ctx.nextIndex, adapterType, ctx.identifier);
735
+ values.push(...having.values);
736
+ ctx.nextIndex += having.values.length;
737
+ const orderBySql = buildOrderBy(spec.orderBy, state, new Set(expressionByAlias.keys()));
738
+ const pagingSql = [];
739
+ if (spec.limit !== void 0) {
740
+ pagingSql.push(`LIMIT ${placeholder(ctx.nextIndex++)}`);
741
+ values.push(spec.limit);
742
+ } else if (spec.offset !== void 0 && normalizeAdapter(adapterType) === "sqlite") pagingSql.push("LIMIT -1");
743
+ if (spec.offset !== void 0) {
744
+ pagingSql.push(`OFFSET ${placeholder(ctx.nextIndex++)}`);
745
+ values.push(spec.offset);
746
+ }
747
+ const fromSql = spec.fromAlias !== void 0 ? `${state.renderName(from)} AS ${state.renderName(fromAlias)}` : state.renderName(from);
748
+ return {
749
+ sql: [
750
+ `SELECT ${selectSql.join(", ")}`,
751
+ `FROM ${fromSql}`,
752
+ ...joinParts,
753
+ whereSql,
754
+ groupBySql,
755
+ having.sql,
756
+ orderBySql,
757
+ pagingSql.join(" ")
758
+ ].filter(Boolean).join(" "),
759
+ values
760
+ };
761
+ }
762
+ //#endregion
763
+ //#region src/shared/duckdb-schema-utils.ts
764
+ /**
765
+ * Parses a CREATE INDEX statement to extract index details
766
+ *
767
+ * @param indexSQL - CREATE INDEX statement
768
+ * @returns Parsed index definition or null if parsing fails
769
+ *
770
+ * @example
771
+ * ```typescript
772
+ * const index = parseIndexStatement(
773
+ * 'CREATE UNIQUE INDEX ds_slug_context_idx ON ds (slug, context)'
774
+ * );
775
+ * // Returns: {
776
+ * // name: 'ds_slug_context_idx',
777
+ * // columns: ['slug', 'context'],
778
+ * // unique: true,
779
+ * // sql: '...'
780
+ * // }
781
+ * ```
782
+ */
783
+ function parseIndexStatement(indexSQL) {
784
+ const trimmed = indexSQL.trim();
785
+ const match = trimmed.match(/CREATE\s+(UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)\s+ON\s+(?:"?\w+"?)\s*\(([^)]+)\)/i);
786
+ if (!match) return null;
787
+ const [, uniqueKeyword, name, columnsStr] = match;
788
+ return {
789
+ name,
790
+ columns: columnsStr.split(",").map((col) => col.trim().replace(/^"|"$/g, "")),
791
+ unique: Boolean(uniqueKeyword),
792
+ sql: trimmed
793
+ };
794
+ }
795
+ /**
796
+ * Converts UNIQUE INDEX statements to inline UNIQUE constraints for DuckDB compatibility
797
+ *
798
+ * DuckDB's ON CONFLICT clause requires inline UNIQUE constraints, not separate indexes.
799
+ * This function transforms SMRT-generated schemas to work with DuckDB's limitations.
800
+ *
801
+ * @param ddl - CREATE TABLE DDL statement
802
+ * @param indexes - Array of CREATE INDEX statements (optional)
803
+ * @returns Transformed DDL with inline UNIQUE constraints and filtered index list
804
+ *
805
+ * @example
806
+ * ```typescript
807
+ * const ddl = `
808
+ * CREATE TABLE ds (
809
+ * id TEXT PRIMARY KEY,
810
+ * slug TEXT NOT NULL,
811
+ * context TEXT NOT NULL
812
+ * )
813
+ * `;
814
+ * const indexes = [
815
+ * 'CREATE UNIQUE INDEX ds_slug_context_idx ON ds (slug, context)'
816
+ * ];
817
+ *
818
+ * const result = convertUniqueIndexesToInlineConstraints(ddl, indexes);
819
+ * // result.ddl:
820
+ * // CREATE TABLE ds (
821
+ * // id TEXT PRIMARY KEY,
822
+ * // slug TEXT NOT NULL,
823
+ * // context TEXT NOT NULL,
824
+ * // UNIQUE(slug, context)
825
+ * // )
826
+ * // result.indexes: [] (UNIQUE index removed, non-UNIQUE indexes preserved)
827
+ * ```
828
+ */
829
+ function convertUniqueIndexesToInlineConstraints(ddl, indexes) {
830
+ if (!indexes || indexes.length === 0) return {
831
+ ddl,
832
+ indexes: []
833
+ };
834
+ const parsedIndexes = indexes.map(parseIndexStatement).filter((idx) => idx !== null);
835
+ const uniqueIndexes = parsedIndexes.filter((idx) => idx.unique);
836
+ const regularIndexes = parsedIndexes.filter((idx) => !idx.unique);
837
+ if (uniqueIndexes.length === 0) return {
838
+ ddl,
839
+ indexes
840
+ };
841
+ const lines = ddl.split("\n");
842
+ let closingParenIndex = -1;
843
+ for (let i = lines.length - 1; i >= 0; i--) {
844
+ const trimmed = lines[i].trim();
845
+ if (trimmed === ")" || trimmed.startsWith(");")) {
846
+ closingParenIndex = i;
847
+ break;
848
+ }
849
+ }
850
+ if (closingParenIndex === -1) {
851
+ console.warn("[duckdb-schema-utils] Could not find closing parenthesis in CREATE TABLE statement");
852
+ return {
853
+ ddl,
854
+ indexes
855
+ };
856
+ }
857
+ const uniqueConstraints = uniqueIndexes.map((idx) => {
858
+ return ` UNIQUE(${idx.columns.map(quoteLiteralIdentifier).join(", ")})`;
859
+ });
860
+ const modifiedLines = [...lines];
861
+ modifiedLines[closingParenIndex].trim();
862
+ if (closingParenIndex > 0) {
863
+ if (!modifiedLines[closingParenIndex - 1].trim().endsWith(",")) modifiedLines[closingParenIndex - 1] = modifiedLines[closingParenIndex - 1].replace(/\s*$/, ",");
864
+ }
865
+ const constraintLines = uniqueConstraints.map((constraint, idx) => {
866
+ return idx < uniqueConstraints.length - 1 ? `${constraint},` : constraint;
867
+ });
868
+ modifiedLines.splice(closingParenIndex, 0, ...constraintLines);
869
+ return {
870
+ ddl: modifiedLines.join("\n"),
871
+ indexes: regularIndexes.map((idx) => idx.sql)
872
+ };
873
+ }
874
+ //#endregion
875
+ //#region src/shared/types.ts
876
+ /**
877
+ * Error thrown when `transaction()` is called on a transaction-scoped interface
878
+ * belonging to an adapter whose engine has no savepoints.
879
+ *
880
+ * DuckDB — and therefore the JSON adapter built on it — does not implement
881
+ * `SAVEPOINT`, so there is no way to re-enter the current transaction. Adapters
882
+ * that can re-enter (PostgreSQL, SQLite) do so under a savepoint and never
883
+ * throw this.
884
+ *
885
+ * The alternative would be to open a second, independent transaction, which is
886
+ * what these adapters used to do; on a shared connection that silently
887
+ * destroyed the enclosing transaction's uncommitted work.
888
+ *
889
+ * @example Ensuring a helper works on every adapter
890
+ * ```typescript
891
+ * // Take the transaction as a parameter rather than opening a nested one.
892
+ * async function recordClick(db: DatabaseInterface, id: string) {
893
+ * await db.update('links', { id }, { clicks: 1 });
894
+ * }
895
+ * await db.transaction(async (tx) => recordClick(tx, id));
896
+ * ```
897
+ */
898
+ var NestedTransactionError = class extends DatabaseError {
899
+ constructor(message, context) {
900
+ super(message, context);
901
+ this.name = "NestedTransactionError";
902
+ }
903
+ };
904
+ /**
905
+ * Resolves a SchemasOption to its concrete value.
906
+ *
907
+ * Adapters that need schemas (JSON, DuckDB) call this to unwrap the
908
+ * lazy function. Adapters that don't (Postgres, SQLite) simply ignore
909
+ * the `schemas` option without calling this.
910
+ */
911
+ function resolveSchemas(schemas) {
912
+ if (!schemas) return void 0;
913
+ if (typeof schemas === "function") return schemas();
914
+ return schemas;
915
+ }
916
+ //#endregion
917
+ //#region src/query.ts
918
+ /**
919
+ * Checks if a table exists in the database
920
+ *
921
+ * @param db - Database interface to use
922
+ * @param tableName - Name of the table to check
923
+ * @returns Promise resolving to boolean indicating if the table exists
924
+ */
925
+ async function tableExists(db, tableName) {
926
+ return db.tableExists(tableName);
927
+ }
928
+ /**
929
+ * Escapes and formats a value for use in SQL queries
930
+ *
931
+ * @param value - Value to escape
932
+ * @returns String representation of the value safe for SQL use
933
+ */
934
+ function escapeSqlValue(value) {
935
+ if (value === null) return "NULL";
936
+ if (value instanceof Date) return `'${value.toISOString()}'`;
937
+ if (typeof value === "number") return value.toString();
938
+ if (typeof value === "boolean") return value ? "1" : "0";
939
+ return `'${String(value).replace(/'/g, "''")}'`;
940
+ }
941
+ /**
942
+ * Validates a column name for use in SQL queries
943
+ *
944
+ * @param column - Column name to validate
945
+ * @returns The validated column name
946
+ * @throws Error if the column name contains invalid characters
947
+ */
948
+ function validateColumnName(column) {
949
+ if (typeof column !== "string" || !/^[a-zA-Z0-9_.]+$/.test(column)) throw new Error(`Invalid column name: ${column}`);
950
+ return column;
951
+ }
952
+ /**
953
+ * Synchronizes a SQL schema definition with a database
954
+ * Creates tables if they don't exist and adds missing columns to existing tables
955
+ *
956
+ * @param options - Object containing database and schema
957
+ * @param options.db - Database interface to use
958
+ * @param options.schema - SQL schema definition
959
+ * @throws Error if db or schema are missing or if the database doesn't support syncSchema
960
+ */
961
+ async function syncSchema(options) {
962
+ const { db, schema } = options;
963
+ if (!db || !schema) throw new Error("db and schema are required");
964
+ if (db.syncSchema) await db.syncSchema(schema);
965
+ else throw new Error("Database adapter does not support schema synchronization");
966
+ }
967
+ //#endregion
968
+ export { NestedTransactionError as a, bucketExpr as c, renderExpression$1 as d, validateColumnName as i, buildAggregate as l, syncSchema as n, resolveSchemas as o, tableExists as r, convertUniqueIndexesToInlineConstraints as s, escapeSqlValue as t, ExpressionError as u };
969
+
970
+ //# sourceMappingURL=query-Dz0TZ0pY.js.map