flint-orm 0.4.1 → 0.4.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 (48) hide show
  1. package/dist/config.d.ts +30 -0
  2. package/dist/drivers/better-sqlite3.d.ts +38 -0
  3. package/dist/drivers/bun-sqlite.d.ts +38 -0
  4. package/dist/drivers/libsql-web.d.ts +44 -0
  5. package/dist/drivers/libsql.d.ts +40 -0
  6. package/dist/drivers/turso-sync.d.ts +44 -0
  7. package/dist/drivers/turso.d.ts +38 -0
  8. package/dist/entries/better-sqlite3.d.ts +1 -0
  9. package/dist/entries/bun-sqlite.d.ts +1 -0
  10. package/dist/entries/config.d.ts +1 -0
  11. package/dist/entries/expressions.d.ts +5 -0
  12. package/dist/entries/libsql-web.d.ts +2 -0
  13. package/dist/entries/libsql.d.ts +2 -0
  14. package/dist/entries/table.d.ts +4 -0
  15. package/dist/entries/turso-sync.d.ts +2 -0
  16. package/dist/entries/turso.d.ts +1 -0
  17. package/dist/errors.d.ts +13 -0
  18. package/dist/executor.d.ts +16 -0
  19. package/dist/flint.d.ts +120 -0
  20. package/dist/index.d.ts +11 -0
  21. package/dist/migration/diff.d.ts +15 -0
  22. package/dist/migration/generate.d.ts +18 -0
  23. package/dist/migration/index.d.ts +11 -0
  24. package/dist/migration/migrate.d.ts +52 -0
  25. package/dist/migration/migration.d.ts +5 -0
  26. package/dist/migration/operations.d.ts +14 -0
  27. package/dist/migration/serialize.d.ts +3 -0
  28. package/dist/migration/sql.d.ts +2 -0
  29. package/dist/migration/types.d.ts +98 -0
  30. package/dist/query/aggregates.d.ts +47 -0
  31. package/dist/query/builder.d.ts +257 -0
  32. package/dist/query/conditions.d.ts +176 -0
  33. package/dist/schema/columns.d.ts +146 -0
  34. package/dist/schema/table.d.ts +74 -0
  35. package/dist/sqlite/introspect.d.ts +19 -0
  36. package/dist/src/cli.js +13818 -0
  37. package/dist/src/entries/better-sqlite3.js +2050 -0
  38. package/dist/src/entries/bun-sqlite.js +1284 -0
  39. package/dist/src/entries/config.js +55 -0
  40. package/dist/src/entries/expressions.js +1252 -0
  41. package/dist/src/entries/libsql-web.js +6065 -0
  42. package/dist/src/entries/libsql.js +7208 -0
  43. package/dist/src/entries/table.js +403 -0
  44. package/dist/src/entries/turso-sync.js +3504 -0
  45. package/dist/src/entries/turso.js +2379 -0
  46. package/dist/{index.js → src/index.js} +86 -22
  47. package/dist/src/migration/index.js +1066 -0
  48. package/package.json +1 -1
@@ -0,0 +1,1252 @@
1
+ // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __returnValue = (v) => v;
34
+ function __exportSetter(name, newValue) {
35
+ this[name] = __returnValue.bind(null, newValue);
36
+ }
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, {
40
+ get: all[name],
41
+ enumerable: true,
42
+ configurable: true,
43
+ set: __exportSetter.bind(all, name)
44
+ });
45
+ };
46
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
47
+ var __require = import.meta.require;
48
+
49
+ // src/query/conditions.ts
50
+ function isColumnDef(value) {
51
+ return value !== null && typeof value === "object" && "__internal" in value;
52
+ }
53
+ function eq(left, valueOrColumn) {
54
+ if (isColumnDef(valueOrColumn)) {
55
+ return { type: "eqColumn", left, right: valueOrColumn };
56
+ }
57
+ return { type: "eq", column: left, value: valueOrColumn };
58
+ }
59
+ function and(...conditions) {
60
+ return { type: "and", conditions };
61
+ }
62
+ function or(...conditions) {
63
+ return { type: "or", conditions };
64
+ }
65
+ function isIn(column, values) {
66
+ return { type: "in", column, values };
67
+ }
68
+ function isNotIn(column, values) {
69
+ return { type: "notIn", column, values };
70
+ }
71
+ function isNull(column) {
72
+ return { type: "isNull", column };
73
+ }
74
+ function isNotNull(column) {
75
+ return { type: "isNotNull", column };
76
+ }
77
+ function like(column, pattern) {
78
+ return { type: "like", column, pattern };
79
+ }
80
+ function glob(column, pattern) {
81
+ return { type: "glob", column, pattern };
82
+ }
83
+ function between(column, low, high) {
84
+ return { type: "between", column, low, high };
85
+ }
86
+ function gt(column, value) {
87
+ return { type: "gt", column, value };
88
+ }
89
+ function gte(column, value) {
90
+ return { type: "gte", column, value };
91
+ }
92
+ function lt(column, value) {
93
+ return { type: "lt", column, value };
94
+ }
95
+ function lte(column, value) {
96
+ return { type: "lte", column, value };
97
+ }
98
+ function neq(column, value) {
99
+ return { type: "neq", column, value };
100
+ }
101
+ function compileCondition(cond, params) {
102
+ switch (cond.type) {
103
+ case "eq":
104
+ params.push(cond.column.__internal.encode(cond.value));
105
+ return `${cond.column.name} = ?`;
106
+ case "eqColumn": {
107
+ const leftName = cond.left.__internal.tableName ? `${cond.left.__internal.tableName}.${cond.left.name}` : cond.left.name;
108
+ const rightName = cond.right.__internal.tableName ? `${cond.right.__internal.tableName}.${cond.right.name}` : cond.right.name;
109
+ return `${leftName} = ${rightName}`;
110
+ }
111
+ case "in": {
112
+ const encoded = cond.values.map((v) => cond.column.__internal.encode(v));
113
+ params.push(...encoded);
114
+ const placeholders = encoded.map(() => "?").join(", ");
115
+ return `${cond.column.name} IN (${placeholders})`;
116
+ }
117
+ case "notIn": {
118
+ const encoded = cond.values.map((v) => cond.column.__internal.encode(v));
119
+ params.push(...encoded);
120
+ const placeholders = encoded.map(() => "?").join(", ");
121
+ return `${cond.column.name} NOT IN (${placeholders})`;
122
+ }
123
+ case "isNull":
124
+ return `${cond.column.name} IS NULL`;
125
+ case "isNotNull":
126
+ return `${cond.column.name} IS NOT NULL`;
127
+ case "like":
128
+ params.push(cond.pattern);
129
+ return `${cond.column.name} LIKE ?`;
130
+ case "glob":
131
+ params.push(cond.pattern);
132
+ return `${cond.column.name} GLOB ?`;
133
+ case "between":
134
+ params.push(cond.column.__internal.encode(cond.low));
135
+ params.push(cond.column.__internal.encode(cond.high));
136
+ return `${cond.column.name} BETWEEN ? AND ?`;
137
+ case "gt":
138
+ params.push(cond.column.__internal.encode(cond.value));
139
+ return `${cond.column.name} > ?`;
140
+ case "gte":
141
+ params.push(cond.column.__internal.encode(cond.value));
142
+ return `${cond.column.name} >= ?`;
143
+ case "lt":
144
+ params.push(cond.column.__internal.encode(cond.value));
145
+ return `${cond.column.name} < ?`;
146
+ case "lte":
147
+ params.push(cond.column.__internal.encode(cond.value));
148
+ return `${cond.column.name} <= ?`;
149
+ case "neq":
150
+ params.push(cond.column.__internal.encode(cond.value));
151
+ return `${cond.column.name} != ?`;
152
+ case "and":
153
+ return cond.conditions.map((c) => compileCondition(c, params)).join(" AND ");
154
+ case "or":
155
+ return `(${cond.conditions.map((c) => compileCondition(c, params)).join(" OR ")})`;
156
+ }
157
+ }
158
+ function compileConditions(conditions, params) {
159
+ if (conditions.length === 0)
160
+ return "1=1";
161
+ return conditions.map((c) => compileCondition(c, params)).join(" AND ");
162
+ }
163
+
164
+ // src/errors.ts
165
+ var FlintError, FlintValidationError, FlintQueryError;
166
+ var init_errors = __esm(() => {
167
+ FlintError = class FlintError extends Error {
168
+ constructor(message) {
169
+ super(message);
170
+ this.name = "FlintError";
171
+ }
172
+ };
173
+ FlintValidationError = class FlintValidationError extends FlintError {
174
+ constructor(message) {
175
+ super(message);
176
+ this.name = "FlintValidationError";
177
+ }
178
+ };
179
+ FlintQueryError = class FlintQueryError extends FlintError {
180
+ originalError;
181
+ constructor(message, originalError) {
182
+ super(message);
183
+ this.name = "FlintQueryError";
184
+ this.originalError = originalError;
185
+ }
186
+ };
187
+ });
188
+
189
+ // src/query/builder.ts
190
+ function getCol(tbl, key) {
191
+ const col = tbl[key];
192
+ if (!col)
193
+ throw new FlintValidationError(`Column "${key}" not found in table`);
194
+ return col;
195
+ }
196
+ function columnEntries(tbl) {
197
+ return Object.entries(tbl).filter(([k]) => k !== "_" && k !== "__indexes");
198
+ }
199
+ function decodeRow(raw, tbl) {
200
+ const out = {};
201
+ for (const [key, col] of columnEntries(tbl)) {
202
+ out[key] = col.__internal.decode(raw[col.name]);
203
+ }
204
+ return out;
205
+ }
206
+ function decodeSelectedRow(raw, tbl, keys) {
207
+ const out = {};
208
+ for (const key of keys) {
209
+ const col = getCol(tbl, key);
210
+ out[key] = col.__internal.decode(raw[col.name]);
211
+ }
212
+ return out;
213
+ }
214
+ function findPKKey(tbl) {
215
+ for (const [key, col] of columnEntries(tbl)) {
216
+ if (col.__internal.isPrimaryKey)
217
+ return key;
218
+ }
219
+ throw new FlintValidationError("Table has no primary key column");
220
+ }
221
+ function resolveForeignKeyCondition(parent, parentName, child, childName) {
222
+ for (const [, col] of columnEntries(child)) {
223
+ if (col.__internal.referencesTable === parentName && col.__internal.referencesColumn) {
224
+ const parentCol = getCol(parent, col.__internal.referencesColumn);
225
+ if (parentCol) {
226
+ return eq(parentCol, col);
227
+ }
228
+ }
229
+ }
230
+ throw new FlintValidationError(`No foreign key reference found from "${childName}" to "${parentName}". Use .references() on the child table or provide an explicit condition.`);
231
+ }
232
+ function extractColumns(cond) {
233
+ switch (cond.type) {
234
+ case "eq":
235
+ return [cond.column];
236
+ case "eqColumn":
237
+ return [cond.left, cond.right];
238
+ case "in":
239
+ case "notIn":
240
+ case "isNull":
241
+ case "isNotNull":
242
+ case "like":
243
+ case "glob":
244
+ case "between":
245
+ return [cond.column];
246
+ case "and":
247
+ case "or":
248
+ return cond.conditions.flatMap(extractColumns);
249
+ default:
250
+ return [];
251
+ }
252
+ }
253
+ function validateColumnOwnership(conditions, allowedTables, context) {
254
+ const allowedColumns = new Set(allowedTables.flatMap((t) => columnEntries(t).map(([, c]) => c)));
255
+ for (const cond of conditions) {
256
+ const cols = extractColumns(cond);
257
+ for (const col of cols) {
258
+ if (!allowedColumns.has(col)) {
259
+ throw new FlintValidationError(`Column "${col.name}" does not belong to ${context}. ` + `Check that you're using a column from the queried table, not a different table.`);
260
+ }
261
+ }
262
+ }
263
+ }
264
+ function resolveColumns(table, selectedColumns, prefix) {
265
+ if (selectedColumns) {
266
+ return selectedColumns.map((k) => {
267
+ const name = getCol(table, k).name;
268
+ return prefix ? `${prefix}.${name}` : name;
269
+ }).join(", ");
270
+ }
271
+ const entries = columnEntries(table);
272
+ return entries.map(([, c]) => prefix ? `${prefix}.${c.name}` : c.name).join(", ");
273
+ }
274
+
275
+ class SelectFromBuilder {
276
+ #executor;
277
+ #conditions;
278
+ constructor(executor, conditions = []) {
279
+ this.#executor = executor;
280
+ this.#conditions = conditions;
281
+ }
282
+ from(table) {
283
+ return new SelectBuilder(this.#executor, table._.name, table, this.#conditions);
284
+ }
285
+ }
286
+
287
+ class SelectBuilder {
288
+ #executor;
289
+ #tableName;
290
+ #table;
291
+ #conditions;
292
+ #selectedColumns;
293
+ #orderByClauses;
294
+ #limitValue;
295
+ #offsetValue;
296
+ #distinct;
297
+ constructor(executor, tableName, table, conditions = [], selectedColumns = null, orderByClauses = [], limitValue = null, offsetValue = null, distinct = false) {
298
+ this.#executor = executor;
299
+ this.#tableName = tableName;
300
+ this.#table = table;
301
+ this.#conditions = conditions;
302
+ this.#selectedColumns = selectedColumns;
303
+ this.#orderByClauses = orderByClauses;
304
+ this.#limitValue = limitValue;
305
+ this.#offsetValue = offsetValue;
306
+ this.#distinct = distinct;
307
+ }
308
+ where(condition) {
309
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
310
+ }
311
+ columns(keys) {
312
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, keys, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
313
+ }
314
+ single() {
315
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
316
+ }
317
+ distinct() {
318
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, true);
319
+ }
320
+ orderBy(key, direction = "asc") {
321
+ const column = getCol(this.#table, key);
322
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue, this.#distinct);
323
+ }
324
+ limit(n) {
325
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue, this.#distinct);
326
+ }
327
+ offset(n) {
328
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n, this.#distinct);
329
+ }
330
+ toSQL() {
331
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
332
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
333
+ const params = [];
334
+ const distinct = this.#distinct ? "DISTINCT " : "";
335
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
336
+ const where = compileConditions(this.#conditions, params);
337
+ if (where !== "1=1")
338
+ sql += ` WHERE ${where}`;
339
+ if (this.#orderByClauses.length > 0) {
340
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
341
+ sql += ` ORDER BY ${orderClauses}`;
342
+ }
343
+ if (this.#limitValue !== null)
344
+ sql += ` LIMIT ${this.#limitValue}`;
345
+ if (this.#offsetValue !== null)
346
+ sql += ` OFFSET ${this.#offsetValue}`;
347
+ return { sql, params };
348
+ }
349
+ async execute() {
350
+ const { sql, params } = this.toSQL();
351
+ try {
352
+ const rows = await this.#executor.all(sql, params);
353
+ const records = rows;
354
+ if (this.#selectedColumns) {
355
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#selectedColumns));
356
+ }
357
+ return records.map((r) => decodeRow(r, this.#table));
358
+ } catch (e) {
359
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
360
+ }
361
+ }
362
+ }
363
+
364
+ class NarrowedSelectBuilder {
365
+ #executor;
366
+ #tableName;
367
+ #table;
368
+ #conditions;
369
+ #selectedColumns;
370
+ #orderByClauses;
371
+ #limitValue;
372
+ #offsetValue;
373
+ #distinct;
374
+ constructor(executor, tableName, table, conditions, selectedColumns, orderByClauses, limitValue, offsetValue, distinct) {
375
+ this.#executor = executor;
376
+ this.#tableName = tableName;
377
+ this.#table = table;
378
+ this.#conditions = conditions;
379
+ this.#selectedColumns = selectedColumns;
380
+ this.#orderByClauses = orderByClauses;
381
+ this.#limitValue = limitValue;
382
+ this.#offsetValue = offsetValue;
383
+ this.#distinct = distinct;
384
+ }
385
+ where(condition) {
386
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
387
+ }
388
+ distinct() {
389
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, true);
390
+ }
391
+ single() {
392
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
393
+ }
394
+ orderBy(key, direction = "asc") {
395
+ const column = getCol(this.#table, key);
396
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue, this.#distinct);
397
+ }
398
+ limit(n) {
399
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue, this.#distinct);
400
+ }
401
+ offset(n) {
402
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n, this.#distinct);
403
+ }
404
+ toSQL() {
405
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
406
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
407
+ const params = [];
408
+ const distinct = this.#distinct ? "DISTINCT " : "";
409
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
410
+ const where = compileConditions(this.#conditions, params);
411
+ if (where !== "1=1")
412
+ sql += ` WHERE ${where}`;
413
+ if (this.#orderByClauses.length > 0) {
414
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
415
+ sql += ` ORDER BY ${orderClauses}`;
416
+ }
417
+ if (this.#limitValue !== null)
418
+ sql += ` LIMIT ${this.#limitValue}`;
419
+ if (this.#offsetValue !== null)
420
+ sql += ` OFFSET ${this.#offsetValue}`;
421
+ return { sql, params };
422
+ }
423
+ async execute() {
424
+ const { sql, params } = this.toSQL();
425
+ try {
426
+ const rows = await this.#executor.all(sql, params);
427
+ return rows.map((r) => decodeSelectedRow(r, this.#table, this.#selectedColumns));
428
+ } catch (e) {
429
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
430
+ }
431
+ }
432
+ }
433
+
434
+ class SingleSelectBuilder {
435
+ #executor;
436
+ #tableName;
437
+ #table;
438
+ #conditions;
439
+ #selectedColumns;
440
+ #orderByClauses;
441
+ #offsetValue;
442
+ #distinct;
443
+ constructor(executor, tableName, table, conditions, selectedColumns = null, orderByClauses = [], offsetValue = null, distinct = false) {
444
+ this.#executor = executor;
445
+ this.#tableName = tableName;
446
+ this.#table = table;
447
+ this.#conditions = conditions;
448
+ this.#selectedColumns = selectedColumns;
449
+ this.#orderByClauses = orderByClauses;
450
+ this.#offsetValue = offsetValue;
451
+ this.#distinct = distinct;
452
+ }
453
+ where(condition) {
454
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
455
+ }
456
+ orderBy(key, direction = "asc") {
457
+ const column = getCol(this.#table, key);
458
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue, this.#distinct);
459
+ }
460
+ offset(n) {
461
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#distinct);
462
+ }
463
+ toSQL() {
464
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
465
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
466
+ const params = [];
467
+ const distinct = this.#distinct ? "DISTINCT " : "";
468
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
469
+ const where = compileConditions(this.#conditions, params);
470
+ if (where !== "1=1")
471
+ sql += ` WHERE ${where}`;
472
+ if (this.#orderByClauses.length > 0) {
473
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
474
+ sql += ` ORDER BY ${orderClauses}`;
475
+ }
476
+ sql += " LIMIT 1";
477
+ if (this.#offsetValue !== null)
478
+ sql += ` OFFSET ${this.#offsetValue}`;
479
+ return { sql, params };
480
+ }
481
+ async execute() {
482
+ const { sql, params } = this.toSQL();
483
+ try {
484
+ const row = await this.#executor.get(sql, params);
485
+ if (!row)
486
+ return null;
487
+ const record = row;
488
+ if (this.#selectedColumns) {
489
+ return decodeSelectedRow(record, this.#table, this.#selectedColumns);
490
+ }
491
+ return decodeRow(record, this.#table);
492
+ } catch (e) {
493
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
494
+ }
495
+ }
496
+ }
497
+
498
+ class NarrowedSingleSelectBuilder {
499
+ #executor;
500
+ #tableName;
501
+ #table;
502
+ #conditions;
503
+ #selectedColumns;
504
+ #orderByClauses;
505
+ #offsetValue;
506
+ #distinct;
507
+ constructor(executor, tableName, table, conditions, selectedColumns, orderByClauses, offsetValue, distinct) {
508
+ this.#executor = executor;
509
+ this.#tableName = tableName;
510
+ this.#table = table;
511
+ this.#conditions = conditions;
512
+ this.#selectedColumns = selectedColumns;
513
+ this.#orderByClauses = orderByClauses;
514
+ this.#offsetValue = offsetValue;
515
+ this.#distinct = distinct;
516
+ }
517
+ where(condition) {
518
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
519
+ }
520
+ orderBy(key, direction = "asc") {
521
+ const column = getCol(this.#table, key);
522
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue, this.#distinct);
523
+ }
524
+ offset(n) {
525
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#distinct);
526
+ }
527
+ toSQL() {
528
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
529
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
530
+ const params = [];
531
+ const distinct = this.#distinct ? "DISTINCT " : "";
532
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
533
+ const where = compileConditions(this.#conditions, params);
534
+ if (where !== "1=1")
535
+ sql += ` WHERE ${where}`;
536
+ if (this.#orderByClauses.length > 0) {
537
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
538
+ sql += ` ORDER BY ${orderClauses}`;
539
+ }
540
+ sql += " LIMIT 1";
541
+ if (this.#offsetValue !== null)
542
+ sql += ` OFFSET ${this.#offsetValue}`;
543
+ return { sql, params };
544
+ }
545
+ async execute() {
546
+ const { sql, params } = this.toSQL();
547
+ try {
548
+ const row = await this.#executor.get(sql, params);
549
+ if (!row)
550
+ return null;
551
+ return decodeSelectedRow(row, this.#table, this.#selectedColumns);
552
+ } catch (e) {
553
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
554
+ }
555
+ }
556
+ }
557
+
558
+ class JoinStage1 {
559
+ #executor;
560
+ #parent;
561
+ #parentName;
562
+ #joinType;
563
+ constructor(executor, parent, parentName, joinType) {
564
+ this.#executor = executor;
565
+ this.#parent = parent;
566
+ this.#parentName = parentName;
567
+ this.#joinType = joinType;
568
+ }
569
+ on(child, condition) {
570
+ const childName = child._.name;
571
+ const resolvedCondition = condition ?? resolveForeignKeyCondition(this.#parent, this.#parentName, child, childName);
572
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, [{ table: child, name: childName, condition: resolvedCondition }], this.#joinType);
573
+ }
574
+ }
575
+
576
+ class JoinBuilderImpl {
577
+ #executor;
578
+ #parent;
579
+ #parentName;
580
+ #joins;
581
+ #joinType;
582
+ #conditions;
583
+ #selectedColumns;
584
+ #orderByClauses;
585
+ #limitValue;
586
+ #offsetValue;
587
+ constructor(executor, parent, parentName, joins, joinType, conditions = [], selectedColumns = null, orderByClauses = [], limitValue = null, offsetValue = null) {
588
+ this.#executor = executor;
589
+ this.#parent = parent;
590
+ this.#parentName = parentName;
591
+ this.#joins = joins;
592
+ this.#joinType = joinType;
593
+ this.#conditions = conditions;
594
+ this.#selectedColumns = selectedColumns;
595
+ this.#orderByClauses = orderByClauses;
596
+ this.#limitValue = limitValue;
597
+ this.#offsetValue = offsetValue;
598
+ }
599
+ on(child, condition) {
600
+ const childName = child._.name;
601
+ const resolvedCondition = condition ?? resolveForeignKeyCondition(this.#parent, this.#parentName, child, childName);
602
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, [...this.#joins, { table: child, name: childName, condition: resolvedCondition }], this.#joinType, this.#conditions, this.#selectedColumns);
603
+ }
604
+ where(condition) {
605
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, [...this.#conditions, condition], this.#selectedColumns);
606
+ }
607
+ columns(keys) {
608
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, keys, this.#orderByClauses, this.#limitValue, this.#offsetValue);
609
+ }
610
+ orderBy(key, direction = "asc") {
611
+ const column = getCol(this.#parent, key);
612
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue);
613
+ }
614
+ limit(n) {
615
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue);
616
+ }
617
+ offset(n) {
618
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n);
619
+ }
620
+ single() {
621
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue);
622
+ }
623
+ toSQL() {
624
+ const allowedTables = [this.#parent, ...this.#joins.map((j) => j.table)];
625
+ validateColumnOwnership(this.#conditions, allowedTables, `SELECT from "${this.#parentName}"`);
626
+ const parentCols = resolveColumns(this.#parent, this.#selectedColumns, this.#parentName);
627
+ const childCols = [];
628
+ for (const join of this.#joins) {
629
+ const entries = columnEntries(join.table);
630
+ for (const [, c] of entries) {
631
+ childCols.push(`${join.name}.${c.name} AS ${join.name}_${c.name}`);
632
+ }
633
+ }
634
+ const joinKeyword = this.#joinType === "left" ? "LEFT JOIN" : "INNER JOIN";
635
+ const joinClauses = [];
636
+ const joinParams = [];
637
+ for (const join of this.#joins) {
638
+ const joinOn = compileConditions([join.condition], joinParams);
639
+ joinClauses.push(`${joinKeyword} ${join.name} ON ${joinOn}`);
640
+ }
641
+ const whereParams = [];
642
+ const where = compileConditions(this.#conditions, whereParams);
643
+ let sql = `SELECT ${parentCols}${childCols.length ? ", " + childCols.join(", ") : ""} FROM ${this.#parentName} ${joinClauses.join(" ")}`;
644
+ if (where !== "1=1")
645
+ sql += ` WHERE ${where}`;
646
+ if (this.#orderByClauses.length > 0) {
647
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
648
+ sql += ` ORDER BY ${orderClauses}`;
649
+ }
650
+ if (this.#limitValue !== null)
651
+ sql += ` LIMIT ${this.#limitValue}`;
652
+ if (this.#offsetValue !== null)
653
+ sql += ` OFFSET ${this.#offsetValue}`;
654
+ return { sql, params: [...joinParams, ...whereParams] };
655
+ }
656
+ async execute() {
657
+ const { sql, params } = this.toSQL();
658
+ try {
659
+ const rows = await this.#executor.all(sql, params);
660
+ return this.#decodeJoinRows(rows);
661
+ } catch (e) {
662
+ if (e instanceof FlintQueryError)
663
+ throw e;
664
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
665
+ }
666
+ }
667
+ #decodeJoinRows(rows) {
668
+ const parentEntries = columnEntries(this.#parent);
669
+ const pkKey = findPKKey(this.#parent);
670
+ const pkColName = getCol(this.#parent, pkKey).name;
671
+ const childEntryMaps = [];
672
+ for (const j of this.#joins) {
673
+ childEntryMaps.push({
674
+ name: j.name,
675
+ entries: columnEntries(j.table),
676
+ table: j.table
677
+ });
678
+ }
679
+ const grouped = new Map;
680
+ for (const row of rows) {
681
+ const pk = row[pkColName];
682
+ if (!grouped.has(pk)) {
683
+ const parentRow = {};
684
+ for (const [key, col] of parentEntries) {
685
+ parentRow[key] = row[col.name];
686
+ }
687
+ grouped.set(pk, {
688
+ parent: parentRow,
689
+ children: childEntryMaps.map(() => [])
690
+ });
691
+ }
692
+ const group = grouped.get(pk);
693
+ childEntryMaps.forEach((childMap, i) => {
694
+ const childRow = {};
695
+ let hasNonNullChild = false;
696
+ for (const [key, col] of childMap.entries) {
697
+ const val = row[`${childMap.name}_${col.name}`];
698
+ childRow[key] = val;
699
+ if (val != null)
700
+ hasNonNullChild = true;
701
+ }
702
+ if (this.#joinType === "left" && !hasNonNullChild)
703
+ return;
704
+ group.children[i].push(childRow);
705
+ });
706
+ }
707
+ const result = [];
708
+ for (const { parent, children } of grouped.values()) {
709
+ const decodedParent = this.#selectedColumns ? decodeSelectedRow(parent, this.#parent, this.#selectedColumns) : decodeRow(parent, this.#parent);
710
+ const nested = { ...decodedParent };
711
+ childEntryMaps.forEach((childMap, i) => {
712
+ nested[childMap.name] = children[i].map((c) => decodeRow(c, childMap.table));
713
+ });
714
+ result.push(nested);
715
+ }
716
+ return result;
717
+ }
718
+ }
719
+
720
+ class SingleJoinBuilderImpl {
721
+ #executor;
722
+ #parent;
723
+ #parentName;
724
+ #joins;
725
+ #joinType;
726
+ #conditions;
727
+ #selectedColumns;
728
+ #orderByClauses;
729
+ #offsetValue;
730
+ constructor(executor, parent, parentName, joins, joinType, conditions, selectedColumns = null, orderByClauses = [], offsetValue = null) {
731
+ this.#executor = executor;
732
+ this.#parent = parent;
733
+ this.#parentName = parentName;
734
+ this.#joins = joins;
735
+ this.#joinType = joinType;
736
+ this.#conditions = conditions;
737
+ this.#selectedColumns = selectedColumns;
738
+ this.#orderByClauses = orderByClauses;
739
+ this.#offsetValue = offsetValue;
740
+ }
741
+ where(condition) {
742
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue);
743
+ }
744
+ orderBy(key, direction = "asc") {
745
+ const column = getCol(this.#parent, key);
746
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue);
747
+ }
748
+ offset(n) {
749
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, n);
750
+ }
751
+ toSQL() {
752
+ const allowedTables = [this.#parent, ...this.#joins.map((j) => j.table)];
753
+ validateColumnOwnership(this.#conditions, allowedTables, `SELECT from "${this.#parentName}"`);
754
+ const parentCols = resolveColumns(this.#parent, this.#selectedColumns, this.#parentName);
755
+ const childCols = [];
756
+ for (const join of this.#joins) {
757
+ const entries = columnEntries(join.table);
758
+ for (const [, c] of entries) {
759
+ childCols.push(`${join.name}.${c.name} AS ${join.name}_${c.name}`);
760
+ }
761
+ }
762
+ const joinKeyword = this.#joinType === "left" ? "LEFT JOIN" : "INNER JOIN";
763
+ const joinClauses = [];
764
+ const joinParams = [];
765
+ for (const join of this.#joins) {
766
+ const joinOn = compileConditions([join.condition], joinParams);
767
+ joinClauses.push(`${joinKeyword} ${join.name} ON ${joinOn}`);
768
+ }
769
+ const whereParams = [];
770
+ const where = compileConditions(this.#conditions, whereParams);
771
+ let sql = `SELECT ${parentCols}${childCols.length ? ", " + childCols.join(", ") : ""} FROM ${this.#parentName} ${joinClauses.join(" ")}`;
772
+ if (where !== "1=1")
773
+ sql += ` WHERE ${where}`;
774
+ if (this.#orderByClauses.length > 0) {
775
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
776
+ sql += ` ORDER BY ${orderClauses}`;
777
+ }
778
+ sql += " LIMIT 1";
779
+ if (this.#offsetValue !== null)
780
+ sql += ` OFFSET ${this.#offsetValue}`;
781
+ return { sql, params: [...joinParams, ...whereParams] };
782
+ }
783
+ async execute() {
784
+ const { sql, params } = this.toSQL();
785
+ try {
786
+ const rows = await this.#executor.all(sql, params);
787
+ const records = rows;
788
+ if (records.length === 0)
789
+ return null;
790
+ return this.#decodeJoinRow(records);
791
+ } catch (e) {
792
+ if (e instanceof FlintQueryError)
793
+ throw e;
794
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
795
+ }
796
+ }
797
+ #decodeJoinRow(rows) {
798
+ const parentEntries = columnEntries(this.#parent);
799
+ const pkKey = findPKKey(this.#parent);
800
+ const pkColName = getCol(this.#parent, pkKey).name;
801
+ const childEntryMaps = [];
802
+ for (const j of this.#joins) {
803
+ childEntryMaps.push({
804
+ name: j.name,
805
+ entries: columnEntries(j.table),
806
+ table: j.table
807
+ });
808
+ }
809
+ const grouped = new Map;
810
+ for (const r of rows) {
811
+ const pk = r[pkColName];
812
+ if (!grouped.has(pk)) {
813
+ const parentRow = {};
814
+ for (const [key, col] of parentEntries) {
815
+ parentRow[key] = r[col.name];
816
+ }
817
+ grouped.set(pk, {
818
+ parent: parentRow,
819
+ children: childEntryMaps.map(() => [])
820
+ });
821
+ }
822
+ const group = grouped.get(pk);
823
+ childEntryMaps.forEach((childMap, i) => {
824
+ const childRow = {};
825
+ let hasNonNullChild = false;
826
+ for (const [key, col] of childMap.entries) {
827
+ const val = r[`${childMap.name}_${col.name}`];
828
+ childRow[key] = val;
829
+ if (val != null)
830
+ hasNonNullChild = true;
831
+ }
832
+ if (this.#joinType === "left" && !hasNonNullChild)
833
+ return;
834
+ group.children[i].push(childRow);
835
+ });
836
+ }
837
+ const first = grouped.values().next().value;
838
+ if (!first)
839
+ return null;
840
+ const decodedParent = this.#selectedColumns ? decodeSelectedRow(first.parent, this.#parent, this.#selectedColumns) : decodeRow(first.parent, this.#parent);
841
+ const nested = { ...decodedParent };
842
+ childEntryMaps.forEach((childMap, i) => {
843
+ nested[childMap.name] = first.children[i].map((c) => decodeRow(c, childMap.table));
844
+ });
845
+ return nested;
846
+ }
847
+ }
848
+
849
+ class InsertValuesBuilder {
850
+ #executor;
851
+ #tableName;
852
+ #table;
853
+ constructor(executor, tableName, table) {
854
+ this.#executor = executor;
855
+ this.#tableName = tableName;
856
+ this.#table = table;
857
+ }
858
+ values(rowOrRows) {
859
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, rowOrRows);
860
+ }
861
+ }
862
+
863
+ class InsertBuilder {
864
+ #executor;
865
+ #tableName;
866
+ #table;
867
+ #rows;
868
+ #returning;
869
+ #onConflict;
870
+ constructor(executor, tableName, table, rowOrRows, returning = false, onConflict) {
871
+ this.#executor = executor;
872
+ this.#tableName = tableName;
873
+ this.#table = table;
874
+ this.#rows = Array.isArray(rowOrRows) ? rowOrRows : [rowOrRows];
875
+ this.#returning = returning;
876
+ this.#onConflict = onConflict;
877
+ }
878
+ returning(keys) {
879
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, keys ?? true, this.#onConflict);
880
+ }
881
+ onConflictDoNothing() {
882
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, this.#returning, { mode: "nothing" });
883
+ }
884
+ onConflictDoUpdate(options) {
885
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, this.#returning, {
886
+ mode: "update",
887
+ target: options.target,
888
+ set: options.set
889
+ });
890
+ }
891
+ toSQL() {
892
+ const entries = columnEntries(this.#table);
893
+ const inserts = [];
894
+ for (const [key, c] of entries) {
895
+ const allUndefined = this.#rows.every((row) => row[key] === undefined);
896
+ if (allUndefined && (c.__internal.hasDefault || c.__internal.isAutoIncrement)) {
897
+ continue;
898
+ }
899
+ inserts.push([key, c]);
900
+ }
901
+ if (inserts.length === 0) {
902
+ const allDefault = entries.filter(([, c]) => c.__internal.hasDefault || c.__internal.isAutoIncrement || c.__internal.hasDefaultNow);
903
+ const names2 = allDefault.map(([, c]) => c.name).join(", ");
904
+ const placeholders = allDefault.map(() => "DEFAULT").join(", ");
905
+ return {
906
+ sql: `INSERT INTO ${this.#tableName} (${names2}) VALUES (${placeholders})`,
907
+ params: []
908
+ };
909
+ }
910
+ const names = inserts.map(([, c]) => c.name).join(", ");
911
+ const placeholderRow = inserts.map(() => "?").join(", ");
912
+ const allPlaceholders = this.#rows.map(() => `(${placeholderRow})`).join(", ");
913
+ const params = [];
914
+ for (const row of this.#rows) {
915
+ for (const [key, c] of inserts) {
916
+ const value = row[key];
917
+ if (value === undefined && c.__internal.hasDefaultNow) {
918
+ params.push(c.__internal.encode(new Date));
919
+ } else {
920
+ params.push(c.__internal.encode(value));
921
+ }
922
+ }
923
+ }
924
+ let sql = `INSERT INTO ${this.#tableName} (${names}) VALUES ${allPlaceholders}`;
925
+ if (this.#onConflict) {
926
+ if (this.#onConflict.mode === "nothing") {
927
+ sql += " ON CONFLICT DO NOTHING";
928
+ } else {
929
+ const target = this.#onConflict.target;
930
+ const targetCols = Array.isArray(target) ? target : [target];
931
+ const targetNames = targetCols.map((c) => c.name).join(", ");
932
+ const setEntries = Object.entries(this.#onConflict.set);
933
+ const setClauses = setEntries.map(([key, value]) => {
934
+ const col = getCol(this.#table, key);
935
+ if (value === undefined)
936
+ return null;
937
+ return `${col.name} = excluded.${col.name}`;
938
+ }).filter(Boolean);
939
+ if (setClauses.length > 0) {
940
+ sql += ` ON CONFLICT (${targetNames}) DO UPDATE SET ${setClauses.join(", ")}`;
941
+ }
942
+ }
943
+ }
944
+ if (this.#returning) {
945
+ if (Array.isArray(this.#returning)) {
946
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
947
+ sql += ` RETURNING ${cols}`;
948
+ } else {
949
+ sql += " RETURNING *";
950
+ }
951
+ }
952
+ return { sql, params };
953
+ }
954
+ async execute() {
955
+ const { sql, params } = this.toSQL();
956
+ try {
957
+ if (this.#returning) {
958
+ const rows = await this.#executor.all(sql, params);
959
+ const records = rows;
960
+ if (Array.isArray(this.#returning)) {
961
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
962
+ }
963
+ return records.map((r) => decodeRow(r, this.#table));
964
+ }
965
+ await this.#executor.run(sql, params);
966
+ return;
967
+ } catch (e) {
968
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
969
+ }
970
+ }
971
+ }
972
+
973
+ class UpdateSetBuilder {
974
+ #executor;
975
+ #tableName;
976
+ #table;
977
+ constructor(executor, tableName, table) {
978
+ this.#executor = executor;
979
+ this.#tableName = tableName;
980
+ this.#table = table;
981
+ }
982
+ set(partial) {
983
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, partial);
984
+ }
985
+ }
986
+
987
+ class UpdateBuilder {
988
+ #executor;
989
+ #tableName;
990
+ #table;
991
+ #set;
992
+ #conditions;
993
+ #returning;
994
+ constructor(executor, tableName, table, set, conditions = [], returning = false) {
995
+ this.#executor = executor;
996
+ this.#tableName = tableName;
997
+ this.#table = table;
998
+ this.#set = set;
999
+ this.#conditions = conditions;
1000
+ this.#returning = returning;
1001
+ }
1002
+ set(partial) {
1003
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, { ...this.#set, ...partial }, this.#conditions, this.#returning);
1004
+ }
1005
+ where(condition) {
1006
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, this.#set, [...this.#conditions, condition], this.#returning);
1007
+ }
1008
+ returning(keys) {
1009
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, this.#set, this.#conditions, keys ?? true);
1010
+ }
1011
+ toSQL() {
1012
+ validateColumnOwnership(this.#conditions, [this.#table], `UPDATE "${this.#tableName}"`);
1013
+ const params = [];
1014
+ const setClauses = [];
1015
+ for (const key of Object.keys(this.#set)) {
1016
+ const col = getCol(this.#table, key);
1017
+ if (col.__internal.hasOnUpdate) {
1018
+ setClauses.push(`${col.name} = ?`);
1019
+ params.push(col.__internal.encode(new Date));
1020
+ continue;
1021
+ }
1022
+ setClauses.push(`${col.name} = ?`);
1023
+ params.push(col.__internal.encode(this.#set[key]));
1024
+ }
1025
+ let sql = `UPDATE ${this.#tableName} SET ${setClauses.join(", ")}`;
1026
+ const where = compileConditions(this.#conditions, params);
1027
+ if (where !== "1=1")
1028
+ sql += ` WHERE ${where}`;
1029
+ if (this.#returning) {
1030
+ if (Array.isArray(this.#returning)) {
1031
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
1032
+ sql += ` RETURNING ${cols}`;
1033
+ } else {
1034
+ sql += " RETURNING *";
1035
+ }
1036
+ }
1037
+ return { sql, params };
1038
+ }
1039
+ async execute() {
1040
+ const { sql, params } = this.toSQL();
1041
+ try {
1042
+ if (this.#returning) {
1043
+ const rows = await this.#executor.all(sql, params);
1044
+ const records = rows;
1045
+ if (Array.isArray(this.#returning)) {
1046
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
1047
+ }
1048
+ return records.map((r) => decodeRow(r, this.#table));
1049
+ }
1050
+ await this.#executor.run(sql, params);
1051
+ return;
1052
+ } catch (e) {
1053
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1054
+ }
1055
+ }
1056
+ }
1057
+
1058
+ class DeleteBuilder {
1059
+ #executor;
1060
+ #tableName;
1061
+ #table;
1062
+ #conditions;
1063
+ #returning;
1064
+ constructor(executor, tableName, table, conditions = [], returning = false) {
1065
+ this.#executor = executor;
1066
+ this.#tableName = tableName;
1067
+ this.#table = table;
1068
+ this.#conditions = conditions;
1069
+ this.#returning = returning;
1070
+ }
1071
+ where(condition) {
1072
+ return new DeleteBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#returning);
1073
+ }
1074
+ returning(keys) {
1075
+ return new DeleteBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, keys ?? true);
1076
+ }
1077
+ toSQL() {
1078
+ validateColumnOwnership(this.#conditions, [this.#table], `DELETE from "${this.#tableName}"`);
1079
+ const params = [];
1080
+ let sql = `DELETE FROM ${this.#tableName}`;
1081
+ const where = compileConditions(this.#conditions, params);
1082
+ if (where !== "1=1")
1083
+ sql += ` WHERE ${where}`;
1084
+ if (this.#returning) {
1085
+ if (Array.isArray(this.#returning)) {
1086
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
1087
+ sql += ` RETURNING ${cols}`;
1088
+ } else {
1089
+ sql += " RETURNING *";
1090
+ }
1091
+ }
1092
+ return { sql, params };
1093
+ }
1094
+ async execute() {
1095
+ const { sql, params } = this.toSQL();
1096
+ try {
1097
+ if (this.#returning) {
1098
+ const rows = await this.#executor.all(sql, params);
1099
+ const records = rows;
1100
+ if (Array.isArray(this.#returning)) {
1101
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
1102
+ }
1103
+ return records.map((r) => decodeRow(r, this.#table));
1104
+ }
1105
+ await this.#executor.run(sql, params);
1106
+ return;
1107
+ } catch (e) {
1108
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1109
+ }
1110
+ }
1111
+ }
1112
+ var init_builder = __esm(() => {
1113
+ init_errors();
1114
+ });
1115
+
1116
+ // src/query/aggregates.ts
1117
+ function getTableName(table) {
1118
+ return table._.name;
1119
+ }
1120
+ function getColumnName(column) {
1121
+ return column.name;
1122
+ }
1123
+ function compileWhere(condition) {
1124
+ if (!condition) {
1125
+ return { whereSql: "", params: [] };
1126
+ }
1127
+ const params = [];
1128
+ const whereSql = compileCondition(condition, params);
1129
+ return { whereSql: ` WHERE ${whereSql}`, params };
1130
+ }
1131
+ async function count(executor, table, condition) {
1132
+ const tableName = getTableName(table);
1133
+ const { whereSql, params } = compileWhere(condition);
1134
+ const sql = `SELECT count(*) as cnt FROM ${tableName}${whereSql}`;
1135
+ const result = await executor.get(sql, params);
1136
+ return result.cnt;
1137
+ }
1138
+ async function countColumn(executor, table, column, condition) {
1139
+ const tableName = getTableName(table);
1140
+ const columnName = getColumnName(column);
1141
+ const { whereSql, params } = compileWhere(condition);
1142
+ const sql = `SELECT count(${columnName}) as cnt FROM ${tableName}${whereSql}`;
1143
+ const result = await executor.get(sql, params);
1144
+ return result.cnt;
1145
+ }
1146
+ async function sum(executor, table, column, condition) {
1147
+ const tableName = getTableName(table);
1148
+ const columnName = getColumnName(column);
1149
+ const { whereSql, params } = compileWhere(condition);
1150
+ const sql = `SELECT sum(${columnName}) as total FROM ${tableName}${whereSql}`;
1151
+ const result = await executor.get(sql, params);
1152
+ return result.total;
1153
+ }
1154
+ async function avg(executor, table, column, condition) {
1155
+ const tableName = getTableName(table);
1156
+ const columnName = getColumnName(column);
1157
+ const { whereSql, params } = compileWhere(condition);
1158
+ const sql = `SELECT avg(${columnName}) as average FROM ${tableName}${whereSql}`;
1159
+ const result = await executor.get(sql, params);
1160
+ return result.average;
1161
+ }
1162
+ async function min(executor, table, column, condition) {
1163
+ const tableName = getTableName(table);
1164
+ const columnName = getColumnName(column);
1165
+ const { whereSql, params } = compileWhere(condition);
1166
+ const sql = `SELECT min(${columnName}) as minimum FROM ${tableName}${whereSql}`;
1167
+ const result = await executor.get(sql, params);
1168
+ return result.minimum;
1169
+ }
1170
+ async function max(executor, table, column, condition) {
1171
+ const tableName = getTableName(table);
1172
+ const columnName = getColumnName(column);
1173
+ const { whereSql, params } = compileWhere(condition);
1174
+ const sql = `SELECT max(${columnName}) as maximum FROM ${tableName}${whereSql}`;
1175
+ const result = await executor.get(sql, params);
1176
+ return result.maximum;
1177
+ }
1178
+ var init_aggregates = () => {};
1179
+
1180
+ // src/flint.ts
1181
+ function createClient(executor) {
1182
+ return {
1183
+ select: () => new SelectFromBuilder(executor),
1184
+ insert: (table) => new InsertValuesBuilder(executor, table._.name, table),
1185
+ update: (table) => new UpdateSetBuilder(executor, table._.name, table),
1186
+ delete: (table) => new DeleteBuilder(executor, table._.name, table),
1187
+ leftJoin: (parent) => new JoinStage1(executor, parent, parent._.name, "left"),
1188
+ innerJoin: (parent) => new JoinStage1(executor, parent, parent._.name, "inner"),
1189
+ batch: (queries) => {
1190
+ const stmts = queries.map((q) => q.toSQL());
1191
+ return executor.transaction(async () => {
1192
+ for (const stmt of stmts) {
1193
+ await executor.run(stmt.sql, stmt.params);
1194
+ }
1195
+ });
1196
+ },
1197
+ count: (table, condition) => count(executor, table, condition),
1198
+ countColumn: (table, column, condition) => countColumn(executor, table, column, condition),
1199
+ sum: (table, column, condition) => sum(executor, table, column, condition),
1200
+ avg: (table, column, condition) => avg(executor, table, column, condition),
1201
+ min: (table, column, condition) => min(executor, table, column, condition),
1202
+ max: (table, column, condition) => max(executor, table, column, condition),
1203
+ $run(query, ...params) {
1204
+ return executor.run(query, params);
1205
+ },
1206
+ $executor: executor
1207
+ };
1208
+ }
1209
+ function sql(strings, ...values) {
1210
+ let query = "";
1211
+ const params = [];
1212
+ for (let i = 0;i < strings.length; i++) {
1213
+ query += strings[i];
1214
+ if (i < values.length) {
1215
+ query += "?";
1216
+ params.push(values[i]);
1217
+ }
1218
+ }
1219
+ return { sql: query, params };
1220
+ }
1221
+ var init_flint = __esm(() => {
1222
+ init_builder();
1223
+ init_aggregates();
1224
+ });
1225
+
1226
+ // src/entries/expressions.ts
1227
+ init_flint();
1228
+ init_aggregates();
1229
+ export {
1230
+ sum,
1231
+ sql,
1232
+ or,
1233
+ neq,
1234
+ min,
1235
+ max,
1236
+ lte,
1237
+ lt,
1238
+ like,
1239
+ isNull,
1240
+ isNotNull,
1241
+ isNotIn,
1242
+ isIn,
1243
+ gte,
1244
+ gt,
1245
+ glob,
1246
+ eq,
1247
+ countColumn,
1248
+ count,
1249
+ between,
1250
+ avg,
1251
+ and
1252
+ };