@happyvertical/sql 0.112.0 → 0.112.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
@@ -1,564 +0,0 @@
1
- import { a as raw, i as parseConditionKey, n as buildWhere, s as unwrapRawKey } from "./schema-manager-tfASrb_b.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 (value === null) return "NULL";
27
- if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
28
- if (typeof value === "number") {
29
- if (!Number.isFinite(value)) throw new Error("Aggregate expression numbers must be finite");
30
- return String(value);
31
- }
32
- if (value instanceof Date) {
33
- if (Number.isNaN(value.getTime())) throw new Error("Aggregate expression dates must be valid");
34
- const placeholder = `$${ctx.nextIndex++}`;
35
- ctx.values.push(value.toISOString());
36
- if (ctx.adapterType === "duckdb" || ctx.adapterType === "json") return `CAST(${placeholder} AS TIMESTAMP)`;
37
- if (ctx.adapterType === "postgres") return `CAST(${placeholder} AS TIMESTAMPTZ)`;
38
- return placeholder;
39
- }
40
- if (typeof value === "string") {
41
- const placeholder = `$${ctx.nextIndex++}`;
42
- ctx.values.push(value);
43
- return placeholder;
44
- }
45
- throw new Error("Aggregate expression literal must be a string, number, boolean, Date or null");
46
- }
47
- function secondsBetween(adapterType, later, earlier) {
48
- if (adapterType === "postgres") return `CAST(EXTRACT(EPOCH FROM (${later} - ${earlier})) AS DOUBLE PRECISION)`;
49
- if (adapterType === "duckdb" || adapterType === "json") return `epoch(${later}) - epoch(${earlier})`;
50
- return `((julianday(${later}) - julianday(${earlier})) * 86400.0)`;
51
- }
52
- function renderOperand(node, state, depth) {
53
- if (depth > MAX_DEPTH) throw new Error(`Aggregate expression is nested deeper than ${MAX_DEPTH}`);
54
- state.ctx.nodeCount = (state.ctx.nodeCount ?? 0) + 1;
55
- if (state.ctx.nodeCount > MAX_NODES) throw new Error(`Aggregate expression has more than ${MAX_NODES} nodes`);
56
- if (!isRecord(node)) throw new Error("Aggregate expression node must be an object");
57
- const { ctx } = state;
58
- if ("col" in node) {
59
- const column = ctx.identifier(node.col);
60
- ctx.onColumn?.(column);
61
- return column;
62
- }
63
- if ("value" in node) return literal(node.value, state);
64
- const op = node.op;
65
- const child = (value) => renderOperand(value, state, depth + 1);
66
- if (typeof op === "string" && Object.hasOwn(ARITHMETIC, op)) {
67
- const arithmetic = op;
68
- const left = child(node.left);
69
- const right = child(node.right);
70
- if (arithmetic === "div") {
71
- const quotient = `((${left} * 1.0) / NULLIF(${right}, 0))`;
72
- if (ctx.adapterType === "postgres") return `CAST(${quotient} AS DOUBLE PRECISION)`;
73
- if (ctx.adapterType === "duckdb" || ctx.adapterType === "json") return `CAST(${quotient} AS DOUBLE)`;
74
- return quotient;
75
- }
76
- return `(${left} ${ARITHMETIC[arithmetic]} ${right})`;
77
- }
78
- if (op === "secondsBetween") return secondsBetween(ctx.adapterType, child(node.later), child(node.earlier));
79
- if (typeof op === "string" && Object.hasOwn(COMPARISON, op)) {
80
- const comparison = op;
81
- const against = (side) => isRecord(side) && "value" in side && side.value === null;
82
- if ((comparison === "eq" || comparison === "ne") && against(node.right)) return `(${child(node.left)} IS ${comparison === "eq" ? "NULL" : "NOT NULL"})`;
83
- if ((comparison === "eq" || comparison === "ne") && against(node.left)) return `(${child(node.right)} IS ${comparison === "eq" ? "NULL" : "NOT NULL"})`;
84
- return `(${child(node.left)} ${COMPARISON[comparison]} ${child(node.right)})`;
85
- }
86
- if (op === "and" || op === "or") {
87
- const operands = node.operands;
88
- if (!Array.isArray(operands) || operands.length === 0) throw new Error(`Aggregate expression ${op} requires at least one operand`);
89
- return `(${operands.map(child).join(op === "and" ? " AND " : " OR ")})`;
90
- }
91
- if (op === "not") return `(NOT ${child(node.operand)})`;
92
- if (op === "isNull" || op === "isNotNull") return `(${child(node.operand)} IS ${op === "isNull" ? "NULL" : "NOT NULL"})`;
93
- if (op === "coalesce") {
94
- const operands = node.operands;
95
- if (!Array.isArray(operands) || operands.length === 0) throw new Error("Aggregate expression coalesce requires at least one operand");
96
- return `COALESCE(${operands.map(child).join(", ")})`;
97
- }
98
- if (op === "asText") {
99
- const type = ctx.adapterType === "duckdb" || ctx.adapterType === "json" ? "VARCHAR" : "TEXT";
100
- return `CAST(${child(node.operand)} AS ${type})`;
101
- }
102
- throw new Error(`Unsupported aggregate expression operator: ${String(op)}`);
103
- }
104
- /**
105
- * Render an expression node to SQL, binding its string and date literals into
106
- * `ctx` as numbered parameters. Throws on any unknown operator, unsafe
107
- * identifier, non-finite number, or an expression too large to be legitimate.
108
- */
109
- function renderAggregateExpression(node, ctx) {
110
- return renderOperand(node, { ctx }, 0);
111
- }
112
- //#endregion
113
- //#region src/aggregate.ts
114
- var EXPRESSION_AGGREGATES = /* @__PURE__ */ new Set([
115
- "count",
116
- "sum",
117
- "avg",
118
- "min",
119
- "max"
120
- ]);
121
- var VALID_DIRECTIONS = /* @__PURE__ */ new Set(["ASC", "DESC"]);
122
- var VALID_BUCKET_UNITS = /* @__PURE__ */ new Set([
123
- "minute",
124
- "hour",
125
- "day",
126
- "week",
127
- "month",
128
- "quarter",
129
- "year"
130
- ]);
131
- function validateSqlIdentifier(identifier) {
132
- if (typeof identifier !== "string" || !/^[a-zA-Z0-9_.]+$/.test(identifier)) throw new Error(`Invalid SQL identifier: ${identifier}`);
133
- return identifier;
134
- }
135
- function normalizeAdapter(adapterType) {
136
- return adapterType ?? "sqlite";
137
- }
138
- function placeholder(index) {
139
- return `$${index}`;
140
- }
141
- function bucketExpr(adapterType, unit, column) {
142
- if (!VALID_BUCKET_UNITS.has(unit)) throw new Error(`Invalid aggregate bucket unit: ${unit}`);
143
- const col = validateSqlIdentifier(column);
144
- const adapter = normalizeAdapter(adapterType);
145
- if (adapter === "postgres" || adapter === "duckdb" || adapter === "json") return `date_trunc('${unit}', ${col})`;
146
- switch (unit) {
147
- case "minute": return `strftime('%Y-%m-%d %H:%M:00', ${col})`;
148
- case "hour": return `strftime('%Y-%m-%d %H:00:00', ${col})`;
149
- case "day": return `strftime('%Y-%m-%d 00:00:00', ${col})`;
150
- case "week": return `strftime('%Y-%m-%d 00:00:00', date(${col}, printf('-%d days', (CAST(strftime('%w', ${col}) AS INTEGER) + 6) % 7)))`;
151
- case "month": return `strftime('%Y-%m-01 00:00:00', ${col})`;
152
- 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'))`;
153
- case "year": return `strftime('%Y-01-01 00:00:00', ${col})`;
154
- }
155
- }
156
- function checkColumn(state, column) {
157
- const { scope } = state;
158
- if (scope && column.includes(".")) {
159
- const parts = column.split(".");
160
- if (parts.length !== 2 || !scope.has(parts[0])) throw new Error(`Aggregate column ${column} must be qualified by the from table or a join alias`);
161
- }
162
- return column;
163
- }
164
- function validateColumn(state, column) {
165
- return checkColumn(state, validateSqlIdentifier(column));
166
- }
167
- function renderExpression(state, node) {
168
- return renderAggregateExpression(node, state.ctx);
169
- }
170
- function aggregateExpression(expr, state) {
171
- const normalizedFn = String(expr.fn).toLowerCase();
172
- const fn = validateSqlIdentifier(String(expr.fn)).toUpperCase();
173
- if (expr.column !== void 0 && expr.expr !== void 0) throw new Error(`Aggregate ${expr.fn} takes a column or an expr, not both`);
174
- 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`);
175
- const hasArgument = Boolean(expr.column) || expr.expr !== void 0;
176
- const filter = expr.filter !== void 0 ? renderExpression(state, expr.filter) : void 0;
177
- if (normalizedFn === "count" && !hasArgument) {
178
- if (expr.distinct) throw new Error(`Aggregate ${expr.fn} with distinct requires a column`);
179
- return filter ? `COUNT(CASE WHEN ${filter} THEN 1 END)` : "COUNT(*)";
180
- }
181
- if (!hasArgument) throw new Error(`Aggregate ${expr.fn} requires a column`);
182
- const argument = expr.expr !== void 0 ? renderExpression(state, expr.expr) : validateColumn(state, expr.column);
183
- return `${fn}(${expr.distinct ? "DISTINCT " : ""}${filter ? `CASE WHEN ${filter} THEN ${argument} END` : argument})`;
184
- }
185
- function selectExpression(expr, adapterType, state) {
186
- if ([
187
- "fn" in expr,
188
- "expr" in expr && !("fn" in expr),
189
- "bucket" in expr
190
- ].filter(Boolean).length > 1) throw new Error("Aggregate select item mixes fn, bucket and expr");
191
- if ("fn" in expr) return {
192
- expression: aggregateExpression(expr, state),
193
- alias: validateSqlIdentifier(expr.as),
194
- groupingCandidate: false,
195
- computed: false
196
- };
197
- if ("expr" in expr) return {
198
- expression: renderExpression(state, expr.expr),
199
- alias: validateSqlIdentifier(expr.as),
200
- groupingCandidate: true,
201
- computed: true
202
- };
203
- if ("column" in expr && !("bucket" in expr)) return {
204
- expression: validateColumn(state, expr.column),
205
- alias: validateSqlIdentifier(expr.as ?? expr.column.split(".").pop() ?? expr.column),
206
- groupingCandidate: true,
207
- computed: false
208
- };
209
- const column = validateColumn(state, expr.column);
210
- const bucket = expr.bucket;
211
- return {
212
- expression: bucketExpr(adapterType, bucket, column),
213
- alias: validateSqlIdentifier(expr.as),
214
- groupingCandidate: true,
215
- computed: false
216
- };
217
- }
218
- function expandHavingKey(key, expressionByAlias) {
219
- if (unwrapRawKey(key).isRaw) return key;
220
- const parsed = parseConditionKey(key);
221
- return raw(`${expressionByAlias.get(parsed.field) ?? validateSqlIdentifier(parsed.field)} ${parsed.operator}`);
222
- }
223
- function expandHaving(having, expressionByAlias) {
224
- const expandCondition = (condition) => Object.fromEntries(Object.entries(condition).map(([key, value]) => [expandHavingKey(key, expressionByAlias), value]));
225
- if (Array.isArray(having)) return having.map((andGroup) => andGroup.map((condition) => expandCondition(condition)));
226
- return expandCondition(having);
227
- }
228
- function buildHaving(having, expressionByAlias, startIndex, adapterType) {
229
- if (!having) return {
230
- sql: "",
231
- values: []
232
- };
233
- const built = buildWhere(expandHaving(having, expressionByAlias), startIndex, adapterType);
234
- return {
235
- sql: built.sql ? built.sql.replace(/^WHERE/, "HAVING") : "",
236
- values: built.values
237
- };
238
- }
239
- function buildOrderBy(orderBy, state, aliases) {
240
- if (!orderBy) return "";
241
- return `ORDER BY ${(Array.isArray(orderBy) ? orderBy : [orderBy]).map((item) => {
242
- const [field, direction = "ASC"] = item.trim().split(/\s+/);
243
- const normalizedDirection = direction.toUpperCase();
244
- if (!VALID_DIRECTIONS.has(normalizedDirection)) throw new Error(`Invalid aggregate order direction: ${direction}`);
245
- return `${aliases.has(field) ? validateSqlIdentifier(field) : validateColumn(state, field)} ${normalizedDirection}`;
246
- }).join(", ")}`;
247
- }
248
- var VALID_JOIN_TYPES = /* @__PURE__ */ new Set(["inner", "left"]);
249
- var JOIN_ALIAS = /^[A-Za-z_][A-Za-z0-9_]*$/;
250
- function buildScope(fromAlias, joins, from) {
251
- if (joins.length === 0 && fromAlias === void 0) return void 0;
252
- const scope = /* @__PURE__ */ new Set();
253
- const claim = (name, what) => {
254
- if (typeof name !== "string" || !JOIN_ALIAS.test(name)) throw new Error(`Invalid aggregate ${what}: ${name}`);
255
- if (scope.has(name)) throw new Error(`Duplicate aggregate table name or alias: ${name}`);
256
- scope.add(name);
257
- };
258
- if (fromAlias !== void 0) claim(fromAlias, "from alias");
259
- else {
260
- if (from.includes(".")) throw new Error("AggregateSpec.fromAlias is required when joining a schema-qualified from table");
261
- claim(from, "from table");
262
- }
263
- for (const join of joins) claim(join.alias, "join alias");
264
- return scope;
265
- }
266
- function joinSql(state, joins) {
267
- return joins.map((join) => {
268
- const type = join.type ?? "inner";
269
- if (!VALID_JOIN_TYPES.has(type)) throw new Error(`Invalid aggregate join type: ${type}`);
270
- if (join.on === void 0) throw new Error(`Aggregate join ${join.alias} requires an on condition`);
271
- const table = validateSqlIdentifier(join.table);
272
- const alias = join.alias;
273
- if (typeof alias !== "string" || !JOIN_ALIAS.test(alias)) throw new Error(`Invalid aggregate join alias: ${String(alias)}`);
274
- const on = renderExpression(state, join.on);
275
- return `${type === "left" ? "LEFT" : "INNER"} JOIN ${table} AS ${alias} ON ${on}`;
276
- });
277
- }
278
- function buildAggregate(spec, startIndex = 1, adapterType) {
279
- const from = validateSqlIdentifier(spec.from);
280
- if (spec.select.length === 0) throw new Error("AggregateSpec.select must contain at least one expression");
281
- if (spec.joins !== void 0 && !Array.isArray(spec.joins)) throw new Error("AggregateSpec.joins must be an array");
282
- const values = [];
283
- const ctx = {
284
- adapterType,
285
- nextIndex: startIndex,
286
- values,
287
- identifier: validateSqlIdentifier
288
- };
289
- const fromAlias = spec.fromAlias;
290
- const joins = (spec.joins ?? []).map((join) => ({
291
- table: join.table,
292
- alias: join.alias,
293
- type: join.type,
294
- on: join.on
295
- }));
296
- const state = {
297
- ctx,
298
- scope: buildScope(fromAlias, joins, from)
299
- };
300
- ctx.onColumn = (column) => {
301
- checkColumn(state, column);
302
- };
303
- const expressionByAlias = /* @__PURE__ */ new Map();
304
- const ordinalByAlias = /* @__PURE__ */ new Map();
305
- const groupingAliases = [];
306
- const selectSql = spec.select.map((expr, position) => {
307
- const selected = selectExpression(expr, adapterType, state);
308
- if (expressionByAlias.has(selected.alias)) throw new Error(`Duplicate aggregate select alias: ${selected.alias}`);
309
- expressionByAlias.set(selected.alias, selected.expression);
310
- if (selected.computed) ordinalByAlias.set(selected.alias, position + 1);
311
- if (selected.groupingCandidate) groupingAliases.push(selected.alias);
312
- return `${selected.expression} AS ${selected.alias}`;
313
- });
314
- const joinParts = joinSql(state, joins);
315
- const where = spec.where ? buildWhere(spec.where, ctx.nextIndex, adapterType) : {
316
- sql: "",
317
- values: []
318
- };
319
- values.push(...where.values);
320
- ctx.nextIndex += where.values.length;
321
- let whereSql = where.sql;
322
- if (spec.whereExpr !== void 0) {
323
- const predicate = renderExpression(state, spec.whereExpr);
324
- whereSql = whereSql ? `WHERE (${whereSql.replace(/^WHERE /, "")}) AND ${predicate}` : `WHERE ${predicate}`;
325
- }
326
- const groupByItems = spec.groupBy ?? groupingAliases;
327
- 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(", ")}` : "";
328
- const having = buildHaving(spec.having, expressionByAlias, ctx.nextIndex, adapterType);
329
- values.push(...having.values);
330
- ctx.nextIndex += having.values.length;
331
- const orderBySql = buildOrderBy(spec.orderBy, state, new Set(expressionByAlias.keys()));
332
- const pagingSql = [];
333
- if (spec.limit !== void 0) {
334
- pagingSql.push(`LIMIT ${placeholder(ctx.nextIndex++)}`);
335
- values.push(spec.limit);
336
- } else if (spec.offset !== void 0 && normalizeAdapter(adapterType) === "sqlite") pagingSql.push("LIMIT -1");
337
- if (spec.offset !== void 0) {
338
- pagingSql.push(`OFFSET ${placeholder(ctx.nextIndex++)}`);
339
- values.push(spec.offset);
340
- }
341
- const fromSql = spec.fromAlias !== void 0 ? `${from} AS ${fromAlias}` : from;
342
- return {
343
- sql: [
344
- `SELECT ${selectSql.join(", ")}`,
345
- `FROM ${fromSql}`,
346
- ...joinParts,
347
- whereSql,
348
- groupBySql,
349
- having.sql,
350
- orderBySql,
351
- pagingSql.join(" ")
352
- ].filter(Boolean).join(" "),
353
- values
354
- };
355
- }
356
- //#endregion
357
- //#region src/shared/duckdb-schema-utils.ts
358
- /**
359
- * Parses a CREATE INDEX statement to extract index details
360
- *
361
- * @param indexSQL - CREATE INDEX statement
362
- * @returns Parsed index definition or null if parsing fails
363
- *
364
- * @example
365
- * ```typescript
366
- * const index = parseIndexStatement(
367
- * 'CREATE UNIQUE INDEX ds_slug_context_idx ON ds (slug, context)'
368
- * );
369
- * // Returns: {
370
- * // name: 'ds_slug_context_idx',
371
- * // columns: ['slug', 'context'],
372
- * // unique: true,
373
- * // sql: '...'
374
- * // }
375
- * ```
376
- */
377
- function parseIndexStatement(indexSQL) {
378
- const trimmed = indexSQL.trim();
379
- const match = trimmed.match(/CREATE\s+(UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)\s+ON\s+(?:"?\w+"?)\s*\(([^)]+)\)/i);
380
- if (!match) return null;
381
- const [, uniqueKeyword, name, columnsStr] = match;
382
- return {
383
- name,
384
- columns: columnsStr.split(",").map((col) => col.trim().replace(/^"|"$/g, "")),
385
- unique: Boolean(uniqueKeyword),
386
- sql: trimmed
387
- };
388
- }
389
- /**
390
- * Converts UNIQUE INDEX statements to inline UNIQUE constraints for DuckDB compatibility
391
- *
392
- * DuckDB's ON CONFLICT clause requires inline UNIQUE constraints, not separate indexes.
393
- * This function transforms SMRT-generated schemas to work with DuckDB's limitations.
394
- *
395
- * @param ddl - CREATE TABLE DDL statement
396
- * @param indexes - Array of CREATE INDEX statements (optional)
397
- * @returns Transformed DDL with inline UNIQUE constraints and filtered index list
398
- *
399
- * @example
400
- * ```typescript
401
- * const ddl = `
402
- * CREATE TABLE ds (
403
- * id TEXT PRIMARY KEY,
404
- * slug TEXT NOT NULL,
405
- * context TEXT NOT NULL
406
- * )
407
- * `;
408
- * const indexes = [
409
- * 'CREATE UNIQUE INDEX ds_slug_context_idx ON ds (slug, context)'
410
- * ];
411
- *
412
- * const result = convertUniqueIndexesToInlineConstraints(ddl, indexes);
413
- * // result.ddl:
414
- * // CREATE TABLE ds (
415
- * // id TEXT PRIMARY KEY,
416
- * // slug TEXT NOT NULL,
417
- * // context TEXT NOT NULL,
418
- * // UNIQUE(slug, context)
419
- * // )
420
- * // result.indexes: [] (UNIQUE index removed, non-UNIQUE indexes preserved)
421
- * ```
422
- */
423
- function convertUniqueIndexesToInlineConstraints(ddl, indexes) {
424
- if (!indexes || indexes.length === 0) return {
425
- ddl,
426
- indexes: []
427
- };
428
- const parsedIndexes = indexes.map(parseIndexStatement).filter((idx) => idx !== null);
429
- const uniqueIndexes = parsedIndexes.filter((idx) => idx.unique);
430
- const regularIndexes = parsedIndexes.filter((idx) => !idx.unique);
431
- if (uniqueIndexes.length === 0) return {
432
- ddl,
433
- indexes
434
- };
435
- const lines = ddl.split("\n");
436
- let closingParenIndex = -1;
437
- for (let i = lines.length - 1; i >= 0; i--) {
438
- const trimmed = lines[i].trim();
439
- if (trimmed === ")" || trimmed.startsWith(");")) {
440
- closingParenIndex = i;
441
- break;
442
- }
443
- }
444
- if (closingParenIndex === -1) {
445
- console.warn("[duckdb-schema-utils] Could not find closing parenthesis in CREATE TABLE statement");
446
- return {
447
- ddl,
448
- indexes
449
- };
450
- }
451
- const uniqueConstraints = uniqueIndexes.map((idx) => {
452
- return ` UNIQUE(${idx.columns.map((col) => `"${col}"`).join(", ")})`;
453
- });
454
- const modifiedLines = [...lines];
455
- modifiedLines[closingParenIndex].trim();
456
- if (closingParenIndex > 0) {
457
- if (!modifiedLines[closingParenIndex - 1].trim().endsWith(",")) modifiedLines[closingParenIndex - 1] = modifiedLines[closingParenIndex - 1].replace(/\s*$/, ",");
458
- }
459
- const constraintLines = uniqueConstraints.map((constraint, idx) => {
460
- return idx < uniqueConstraints.length - 1 ? `${constraint},` : constraint;
461
- });
462
- modifiedLines.splice(closingParenIndex, 0, ...constraintLines);
463
- return {
464
- ddl: modifiedLines.join("\n"),
465
- indexes: regularIndexes.map((idx) => idx.sql)
466
- };
467
- }
468
- //#endregion
469
- //#region src/shared/types.ts
470
- /**
471
- * Error thrown when `transaction()` is called on a transaction-scoped interface
472
- * belonging to an adapter whose engine has no savepoints.
473
- *
474
- * DuckDB — and therefore the JSON adapter built on it — does not implement
475
- * `SAVEPOINT`, so there is no way to re-enter the current transaction. Adapters
476
- * that can re-enter (PostgreSQL, SQLite) do so under a savepoint and never
477
- * throw this.
478
- *
479
- * The alternative would be to open a second, independent transaction, which is
480
- * what these adapters used to do; on a shared connection that silently
481
- * destroyed the enclosing transaction's uncommitted work.
482
- *
483
- * @example Ensuring a helper works on every adapter
484
- * ```typescript
485
- * // Take the transaction as a parameter rather than opening a nested one.
486
- * async function recordClick(db: DatabaseInterface, id: string) {
487
- * await db.update('links', { id }, { clicks: 1 });
488
- * }
489
- * await db.transaction(async (tx) => recordClick(tx, id));
490
- * ```
491
- */
492
- var NestedTransactionError = class extends DatabaseError {
493
- constructor(message, context) {
494
- super(message, context);
495
- this.name = "NestedTransactionError";
496
- }
497
- };
498
- /**
499
- * Resolves a SchemasOption to its concrete value.
500
- *
501
- * Adapters that need schemas (JSON, DuckDB) call this to unwrap the
502
- * lazy function. Adapters that don't (Postgres, SQLite) simply ignore
503
- * the `schemas` option without calling this.
504
- */
505
- function resolveSchemas(schemas) {
506
- if (!schemas) return void 0;
507
- if (typeof schemas === "function") return schemas();
508
- return schemas;
509
- }
510
- //#endregion
511
- //#region src/query.ts
512
- /**
513
- * Checks if a table exists in the database
514
- *
515
- * @param db - Database interface to use
516
- * @param tableName - Name of the table to check
517
- * @returns Promise resolving to boolean indicating if the table exists
518
- */
519
- async function tableExists(db, tableName) {
520
- return db.tableExists(tableName);
521
- }
522
- /**
523
- * Escapes and formats a value for use in SQL queries
524
- *
525
- * @param value - Value to escape
526
- * @returns String representation of the value safe for SQL use
527
- */
528
- function escapeSqlValue(value) {
529
- if (value === null) return "NULL";
530
- if (value instanceof Date) return `'${value.toISOString()}'`;
531
- if (typeof value === "number") return value.toString();
532
- if (typeof value === "boolean") return value ? "1" : "0";
533
- return `'${String(value).replace(/'/g, "''")}'`;
534
- }
535
- /**
536
- * Validates a column name for use in SQL queries
537
- *
538
- * @param column - Column name to validate
539
- * @returns The validated column name
540
- * @throws Error if the column name contains invalid characters
541
- */
542
- function validateColumnName(column) {
543
- if (typeof column !== "string" || !/^[a-zA-Z0-9_.]+$/.test(column)) throw new Error(`Invalid column name: ${column}`);
544
- return column;
545
- }
546
- /**
547
- * Synchronizes a SQL schema definition with a database
548
- * Creates tables if they don't exist and adds missing columns to existing tables
549
- *
550
- * @param options - Object containing database and schema
551
- * @param options.db - Database interface to use
552
- * @param options.schema - SQL schema definition
553
- * @throws Error if db or schema are missing or if the database doesn't support syncSchema
554
- */
555
- async function syncSchema(options) {
556
- const { db, schema } = options;
557
- if (!db || !schema) throw new Error("db and schema are required");
558
- if (db.syncSchema) await db.syncSchema(schema);
559
- else throw new Error("Database adapter does not support schema synchronization");
560
- }
561
- //#endregion
562
- export { NestedTransactionError as a, bucketExpr as c, validateColumnName as i, buildAggregate as l, syncSchema as n, resolveSchemas as o, tableExists as r, convertUniqueIndexesToInlineConstraints as s, escapeSqlValue as t };
563
-
564
- //# sourceMappingURL=query-i6IIkNhF.js.map