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,2050 @@
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
+ // node_modules/better-sqlite3/lib/util.js
50
+ var require_util = __commonJS((exports) => {
51
+ exports.getBooleanOption = (options, key) => {
52
+ let value = false;
53
+ if (key in options && typeof (value = options[key]) !== "boolean") {
54
+ throw new TypeError(`Expected the "${key}" option to be a boolean`);
55
+ }
56
+ return value;
57
+ };
58
+ exports.cppdb = Symbol();
59
+ exports.inspect = Symbol.for("nodejs.util.inspect.custom");
60
+ });
61
+
62
+ // node_modules/better-sqlite3/lib/sqlite-error.js
63
+ var require_sqlite_error = __commonJS((exports, module) => {
64
+ var descriptor = { value: "SqliteError", writable: true, enumerable: false, configurable: true };
65
+ function SqliteError(message, code) {
66
+ if (new.target !== SqliteError) {
67
+ return new SqliteError(message, code);
68
+ }
69
+ if (typeof code !== "string") {
70
+ throw new TypeError("Expected second argument to be a string");
71
+ }
72
+ Error.call(this, message);
73
+ descriptor.value = "" + message;
74
+ Object.defineProperty(this, "message", descriptor);
75
+ Error.captureStackTrace(this, SqliteError);
76
+ this.code = code;
77
+ }
78
+ Object.setPrototypeOf(SqliteError, Error);
79
+ Object.setPrototypeOf(SqliteError.prototype, Error.prototype);
80
+ Object.defineProperty(SqliteError.prototype, "name", descriptor);
81
+ module.exports = SqliteError;
82
+ });
83
+
84
+ // node_modules/file-uri-to-path/index.js
85
+ var require_file_uri_to_path = __commonJS((exports, module) => {
86
+ var sep = __require("path").sep || "/";
87
+ module.exports = fileUriToPath;
88
+ function fileUriToPath(uri) {
89
+ if (typeof uri != "string" || uri.length <= 7 || uri.substring(0, 7) != "file://") {
90
+ throw new TypeError("must pass in a file:// URI to convert to a file path");
91
+ }
92
+ var rest = decodeURI(uri.substring(7));
93
+ var firstSlash = rest.indexOf("/");
94
+ var host = rest.substring(0, firstSlash);
95
+ var path = rest.substring(firstSlash + 1);
96
+ if (host == "localhost")
97
+ host = "";
98
+ if (host) {
99
+ host = sep + sep + host;
100
+ }
101
+ path = path.replace(/^(.+)\|/, "$1:");
102
+ if (sep == "\\") {
103
+ path = path.replace(/\//g, "\\");
104
+ }
105
+ if (/^.+\:/.test(path)) {} else {
106
+ path = sep + path;
107
+ }
108
+ return host + path;
109
+ }
110
+ });
111
+
112
+ // node_modules/bindings/bindings.js
113
+ var require_bindings = __commonJS((exports, module) => {
114
+ var __filename = "/home/runner/work/flint-orm/flint-orm/node_modules/bindings/bindings.js";
115
+ var fs = __require("fs");
116
+ var path = __require("path");
117
+ var fileURLToPath = require_file_uri_to_path();
118
+ var join = path.join;
119
+ var dirname = path.dirname;
120
+ var exists = fs.accessSync && function(path2) {
121
+ try {
122
+ fs.accessSync(path2);
123
+ } catch (e) {
124
+ return false;
125
+ }
126
+ return true;
127
+ } || fs.existsSync || path.existsSync;
128
+ var defaults = {
129
+ arrow: process.env.NODE_BINDINGS_ARROW || " \u2192 ",
130
+ compiled: process.env.NODE_BINDINGS_COMPILED_DIR || "compiled",
131
+ platform: process.platform,
132
+ arch: process.arch,
133
+ nodePreGyp: "node-v" + process.versions.modules + "-" + process.platform + "-" + process.arch,
134
+ version: process.versions.node,
135
+ bindings: "bindings.node",
136
+ try: [
137
+ ["module_root", "build", "bindings"],
138
+ ["module_root", "build", "Debug", "bindings"],
139
+ ["module_root", "build", "Release", "bindings"],
140
+ ["module_root", "out", "Debug", "bindings"],
141
+ ["module_root", "Debug", "bindings"],
142
+ ["module_root", "out", "Release", "bindings"],
143
+ ["module_root", "Release", "bindings"],
144
+ ["module_root", "build", "default", "bindings"],
145
+ ["module_root", "compiled", "version", "platform", "arch", "bindings"],
146
+ ["module_root", "addon-build", "release", "install-root", "bindings"],
147
+ ["module_root", "addon-build", "debug", "install-root", "bindings"],
148
+ ["module_root", "addon-build", "default", "install-root", "bindings"],
149
+ ["module_root", "lib", "binding", "nodePreGyp", "bindings"]
150
+ ]
151
+ };
152
+ function bindings(opts) {
153
+ if (typeof opts == "string") {
154
+ opts = { bindings: opts };
155
+ } else if (!opts) {
156
+ opts = {};
157
+ }
158
+ Object.keys(defaults).map(function(i2) {
159
+ if (!(i2 in opts))
160
+ opts[i2] = defaults[i2];
161
+ });
162
+ if (!opts.module_root) {
163
+ opts.module_root = exports.getRoot(exports.getFileName());
164
+ }
165
+ if (path.extname(opts.bindings) != ".node") {
166
+ opts.bindings += ".node";
167
+ }
168
+ var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
169
+ var tries = [], i = 0, l = opts.try.length, n, b, err;
170
+ for (;i < l; i++) {
171
+ n = join.apply(null, opts.try[i].map(function(p) {
172
+ return opts[p] || p;
173
+ }));
174
+ tries.push(n);
175
+ try {
176
+ b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
177
+ if (!opts.path) {
178
+ b.path = n;
179
+ }
180
+ return b;
181
+ } catch (e) {
182
+ if (e.code !== "MODULE_NOT_FOUND" && e.code !== "QUALIFIED_PATH_RESOLUTION_FAILED" && !/not find/i.test(e.message)) {
183
+ throw e;
184
+ }
185
+ }
186
+ }
187
+ err = new Error(`Could not locate the bindings file. Tried:
188
+ ` + tries.map(function(a) {
189
+ return opts.arrow + a;
190
+ }).join(`
191
+ `));
192
+ err.tries = tries;
193
+ throw err;
194
+ }
195
+ module.exports = exports = bindings;
196
+ exports.getFileName = function getFileName(calling_file) {
197
+ var { prepareStackTrace: origPST, stackTraceLimit: origSTL } = Error, dummy = {}, fileName;
198
+ Error.stackTraceLimit = 10;
199
+ Error.prepareStackTrace = function(e, st) {
200
+ for (var i = 0, l = st.length;i < l; i++) {
201
+ fileName = st[i].getFileName();
202
+ if (fileName !== __filename) {
203
+ if (calling_file) {
204
+ if (fileName !== calling_file) {
205
+ return;
206
+ }
207
+ } else {
208
+ return;
209
+ }
210
+ }
211
+ }
212
+ };
213
+ Error.captureStackTrace(dummy);
214
+ dummy.stack;
215
+ Error.prepareStackTrace = origPST;
216
+ Error.stackTraceLimit = origSTL;
217
+ var fileSchema = "file://";
218
+ if (fileName.indexOf(fileSchema) === 0) {
219
+ fileName = fileURLToPath(fileName);
220
+ }
221
+ return fileName;
222
+ };
223
+ exports.getRoot = function getRoot(file) {
224
+ var dir = dirname(file), prev;
225
+ while (true) {
226
+ if (dir === ".") {
227
+ dir = process.cwd();
228
+ }
229
+ if (exists(join(dir, "package.json")) || exists(join(dir, "node_modules"))) {
230
+ return dir;
231
+ }
232
+ if (prev === dir) {
233
+ throw new Error('Could not find module root given file: "' + file + '". Do you have a `package.json` file? ');
234
+ }
235
+ prev = dir;
236
+ dir = join(dir, "..");
237
+ }
238
+ };
239
+ });
240
+
241
+ // node_modules/better-sqlite3/lib/methods/wrappers.js
242
+ var require_wrappers = __commonJS((exports) => {
243
+ var { cppdb } = require_util();
244
+ exports.prepare = function prepare(sql) {
245
+ return this[cppdb].prepare(sql, this, false);
246
+ };
247
+ exports.exec = function exec(sql) {
248
+ this[cppdb].exec(sql);
249
+ return this;
250
+ };
251
+ exports.close = function close() {
252
+ this[cppdb].close();
253
+ return this;
254
+ };
255
+ exports.loadExtension = function loadExtension(...args) {
256
+ this[cppdb].loadExtension(...args);
257
+ return this;
258
+ };
259
+ exports.defaultSafeIntegers = function defaultSafeIntegers(...args) {
260
+ this[cppdb].defaultSafeIntegers(...args);
261
+ return this;
262
+ };
263
+ exports.unsafeMode = function unsafeMode(...args) {
264
+ this[cppdb].unsafeMode(...args);
265
+ return this;
266
+ };
267
+ exports.getters = {
268
+ name: {
269
+ get: function name() {
270
+ return this[cppdb].name;
271
+ },
272
+ enumerable: true
273
+ },
274
+ open: {
275
+ get: function open() {
276
+ return this[cppdb].open;
277
+ },
278
+ enumerable: true
279
+ },
280
+ inTransaction: {
281
+ get: function inTransaction() {
282
+ return this[cppdb].inTransaction;
283
+ },
284
+ enumerable: true
285
+ },
286
+ readonly: {
287
+ get: function readonly() {
288
+ return this[cppdb].readonly;
289
+ },
290
+ enumerable: true
291
+ },
292
+ memory: {
293
+ get: function memory() {
294
+ return this[cppdb].memory;
295
+ },
296
+ enumerable: true
297
+ }
298
+ };
299
+ });
300
+
301
+ // node_modules/better-sqlite3/lib/methods/transaction.js
302
+ var require_transaction = __commonJS((exports, module) => {
303
+ var { cppdb } = require_util();
304
+ var controllers = new WeakMap;
305
+ module.exports = function transaction(fn) {
306
+ if (typeof fn !== "function")
307
+ throw new TypeError("Expected first argument to be a function");
308
+ const db = this[cppdb];
309
+ const controller = getController(db, this);
310
+ const { apply } = Function.prototype;
311
+ const properties = {
312
+ default: { value: wrapTransaction(apply, fn, db, controller.default) },
313
+ deferred: { value: wrapTransaction(apply, fn, db, controller.deferred) },
314
+ immediate: { value: wrapTransaction(apply, fn, db, controller.immediate) },
315
+ exclusive: { value: wrapTransaction(apply, fn, db, controller.exclusive) },
316
+ database: { value: this, enumerable: true }
317
+ };
318
+ Object.defineProperties(properties.default.value, properties);
319
+ Object.defineProperties(properties.deferred.value, properties);
320
+ Object.defineProperties(properties.immediate.value, properties);
321
+ Object.defineProperties(properties.exclusive.value, properties);
322
+ return properties.default.value;
323
+ };
324
+ var getController = (db, self) => {
325
+ let controller = controllers.get(db);
326
+ if (!controller) {
327
+ const shared = {
328
+ commit: db.prepare("COMMIT", self, false),
329
+ rollback: db.prepare("ROLLBACK", self, false),
330
+ savepoint: db.prepare("SAVEPOINT `\t_bs3.\t`", self, false),
331
+ release: db.prepare("RELEASE `\t_bs3.\t`", self, false),
332
+ rollbackTo: db.prepare("ROLLBACK TO `\t_bs3.\t`", self, false)
333
+ };
334
+ controllers.set(db, controller = {
335
+ default: Object.assign({ begin: db.prepare("BEGIN", self, false) }, shared),
336
+ deferred: Object.assign({ begin: db.prepare("BEGIN DEFERRED", self, false) }, shared),
337
+ immediate: Object.assign({ begin: db.prepare("BEGIN IMMEDIATE", self, false) }, shared),
338
+ exclusive: Object.assign({ begin: db.prepare("BEGIN EXCLUSIVE", self, false) }, shared)
339
+ });
340
+ }
341
+ return controller;
342
+ };
343
+ var wrapTransaction = (apply, fn, db, { begin, commit, rollback, savepoint, release, rollbackTo }) => function sqliteTransaction() {
344
+ let before, after, undo;
345
+ if (db.inTransaction) {
346
+ before = savepoint;
347
+ after = release;
348
+ undo = rollbackTo;
349
+ } else {
350
+ before = begin;
351
+ after = commit;
352
+ undo = rollback;
353
+ }
354
+ before.run();
355
+ try {
356
+ const result = apply.call(fn, this, arguments);
357
+ if (result && typeof result.then === "function") {
358
+ throw new TypeError("Transaction function cannot return a promise");
359
+ }
360
+ after.run();
361
+ return result;
362
+ } catch (ex) {
363
+ if (db.inTransaction) {
364
+ undo.run();
365
+ if (undo !== rollback)
366
+ after.run();
367
+ }
368
+ throw ex;
369
+ }
370
+ };
371
+ });
372
+
373
+ // node_modules/better-sqlite3/lib/methods/pragma.js
374
+ var require_pragma = __commonJS((exports, module) => {
375
+ var { getBooleanOption, cppdb } = require_util();
376
+ module.exports = function pragma(source, options) {
377
+ if (options == null)
378
+ options = {};
379
+ if (typeof source !== "string")
380
+ throw new TypeError("Expected first argument to be a string");
381
+ if (typeof options !== "object")
382
+ throw new TypeError("Expected second argument to be an options object");
383
+ const simple = getBooleanOption(options, "simple");
384
+ const stmt = this[cppdb].prepare(`PRAGMA ${source}`, this, true);
385
+ return simple ? stmt.pluck().get() : stmt.all();
386
+ };
387
+ });
388
+
389
+ // node_modules/better-sqlite3/lib/methods/backup.js
390
+ var require_backup = __commonJS((exports, module) => {
391
+ var fs = __require("fs");
392
+ var path = __require("path");
393
+ var { promisify } = __require("util");
394
+ var { cppdb } = require_util();
395
+ var fsAccess = promisify(fs.access);
396
+ module.exports = async function backup(filename, options) {
397
+ if (options == null)
398
+ options = {};
399
+ if (typeof filename !== "string")
400
+ throw new TypeError("Expected first argument to be a string");
401
+ if (typeof options !== "object")
402
+ throw new TypeError("Expected second argument to be an options object");
403
+ filename = filename.trim();
404
+ const attachedName = "attached" in options ? options.attached : "main";
405
+ const handler = "progress" in options ? options.progress : null;
406
+ if (!filename)
407
+ throw new TypeError("Backup filename cannot be an empty string");
408
+ if (filename === ":memory:")
409
+ throw new TypeError('Invalid backup filename ":memory:"');
410
+ if (typeof attachedName !== "string")
411
+ throw new TypeError('Expected the "attached" option to be a string');
412
+ if (!attachedName)
413
+ throw new TypeError('The "attached" option cannot be an empty string');
414
+ if (handler != null && typeof handler !== "function")
415
+ throw new TypeError('Expected the "progress" option to be a function');
416
+ await fsAccess(path.dirname(filename)).catch(() => {
417
+ throw new TypeError("Cannot save backup because the directory does not exist");
418
+ });
419
+ const isNewFile = await fsAccess(filename).then(() => false, () => true);
420
+ return runBackup(this[cppdb].backup(this, attachedName, filename, isNewFile), handler || null);
421
+ };
422
+ var runBackup = (backup, handler) => {
423
+ let rate = 0;
424
+ let useDefault = true;
425
+ return new Promise((resolve, reject) => {
426
+ setImmediate(function step() {
427
+ try {
428
+ const progress = backup.transfer(rate);
429
+ if (!progress.remainingPages) {
430
+ backup.close();
431
+ resolve(progress);
432
+ return;
433
+ }
434
+ if (useDefault) {
435
+ useDefault = false;
436
+ rate = 100;
437
+ }
438
+ if (handler) {
439
+ const ret = handler(progress);
440
+ if (ret !== undefined) {
441
+ if (typeof ret === "number" && ret === ret)
442
+ rate = Math.max(0, Math.min(2147483647, Math.round(ret)));
443
+ else
444
+ throw new TypeError("Expected progress callback to return a number or undefined");
445
+ }
446
+ }
447
+ setImmediate(step);
448
+ } catch (err) {
449
+ backup.close();
450
+ reject(err);
451
+ }
452
+ });
453
+ });
454
+ };
455
+ });
456
+
457
+ // node_modules/better-sqlite3/lib/methods/serialize.js
458
+ var require_serialize = __commonJS((exports, module) => {
459
+ var { cppdb } = require_util();
460
+ module.exports = function serialize(options) {
461
+ if (options == null)
462
+ options = {};
463
+ if (typeof options !== "object")
464
+ throw new TypeError("Expected first argument to be an options object");
465
+ const attachedName = "attached" in options ? options.attached : "main";
466
+ if (typeof attachedName !== "string")
467
+ throw new TypeError('Expected the "attached" option to be a string');
468
+ if (!attachedName)
469
+ throw new TypeError('The "attached" option cannot be an empty string');
470
+ return this[cppdb].serialize(attachedName);
471
+ };
472
+ });
473
+
474
+ // node_modules/better-sqlite3/lib/methods/function.js
475
+ var require_function = __commonJS((exports, module) => {
476
+ var { getBooleanOption, cppdb } = require_util();
477
+ module.exports = function defineFunction(name, options, fn) {
478
+ if (options == null)
479
+ options = {};
480
+ if (typeof options === "function") {
481
+ fn = options;
482
+ options = {};
483
+ }
484
+ if (typeof name !== "string")
485
+ throw new TypeError("Expected first argument to be a string");
486
+ if (typeof fn !== "function")
487
+ throw new TypeError("Expected last argument to be a function");
488
+ if (typeof options !== "object")
489
+ throw new TypeError("Expected second argument to be an options object");
490
+ if (!name)
491
+ throw new TypeError("User-defined function name cannot be an empty string");
492
+ const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
493
+ const deterministic = getBooleanOption(options, "deterministic");
494
+ const directOnly = getBooleanOption(options, "directOnly");
495
+ const varargs = getBooleanOption(options, "varargs");
496
+ let argCount = -1;
497
+ if (!varargs) {
498
+ argCount = fn.length;
499
+ if (!Number.isInteger(argCount) || argCount < 0)
500
+ throw new TypeError("Expected function.length to be a positive integer");
501
+ if (argCount > 100)
502
+ throw new RangeError("User-defined functions cannot have more than 100 arguments");
503
+ }
504
+ this[cppdb].function(fn, name, argCount, safeIntegers, deterministic, directOnly);
505
+ return this;
506
+ };
507
+ });
508
+
509
+ // node_modules/better-sqlite3/lib/methods/aggregate.js
510
+ var require_aggregate = __commonJS((exports, module) => {
511
+ var { getBooleanOption, cppdb } = require_util();
512
+ module.exports = function defineAggregate(name, options) {
513
+ if (typeof name !== "string")
514
+ throw new TypeError("Expected first argument to be a string");
515
+ if (typeof options !== "object" || options === null)
516
+ throw new TypeError("Expected second argument to be an options object");
517
+ if (!name)
518
+ throw new TypeError("User-defined function name cannot be an empty string");
519
+ const start = "start" in options ? options.start : null;
520
+ const step = getFunctionOption(options, "step", true);
521
+ const inverse = getFunctionOption(options, "inverse", false);
522
+ const result = getFunctionOption(options, "result", false);
523
+ const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
524
+ const deterministic = getBooleanOption(options, "deterministic");
525
+ const directOnly = getBooleanOption(options, "directOnly");
526
+ const varargs = getBooleanOption(options, "varargs");
527
+ let argCount = -1;
528
+ if (!varargs) {
529
+ argCount = Math.max(getLength(step), inverse ? getLength(inverse) : 0);
530
+ if (argCount > 0)
531
+ argCount -= 1;
532
+ if (argCount > 100)
533
+ throw new RangeError("User-defined functions cannot have more than 100 arguments");
534
+ }
535
+ this[cppdb].aggregate(start, step, inverse, result, name, argCount, safeIntegers, deterministic, directOnly);
536
+ return this;
537
+ };
538
+ var getFunctionOption = (options, key, required) => {
539
+ const value = key in options ? options[key] : null;
540
+ if (typeof value === "function")
541
+ return value;
542
+ if (value != null)
543
+ throw new TypeError(`Expected the "${key}" option to be a function`);
544
+ if (required)
545
+ throw new TypeError(`Missing required option "${key}"`);
546
+ return null;
547
+ };
548
+ var getLength = ({ length }) => {
549
+ if (Number.isInteger(length) && length >= 0)
550
+ return length;
551
+ throw new TypeError("Expected function.length to be a positive integer");
552
+ };
553
+ });
554
+
555
+ // node_modules/better-sqlite3/lib/methods/table.js
556
+ var require_table = __commonJS((exports, module) => {
557
+ var { cppdb } = require_util();
558
+ module.exports = function defineTable(name, factory) {
559
+ if (typeof name !== "string")
560
+ throw new TypeError("Expected first argument to be a string");
561
+ if (!name)
562
+ throw new TypeError("Virtual table module name cannot be an empty string");
563
+ let eponymous = false;
564
+ if (typeof factory === "object" && factory !== null) {
565
+ eponymous = true;
566
+ factory = defer(parseTableDefinition(factory, "used", name));
567
+ } else {
568
+ if (typeof factory !== "function")
569
+ throw new TypeError("Expected second argument to be a function or a table definition object");
570
+ factory = wrapFactory(factory);
571
+ }
572
+ this[cppdb].table(factory, name, eponymous);
573
+ return this;
574
+ };
575
+ function wrapFactory(factory) {
576
+ return function virtualTableFactory(moduleName, databaseName, tableName, ...args) {
577
+ const thisObject = {
578
+ module: moduleName,
579
+ database: databaseName,
580
+ table: tableName
581
+ };
582
+ const def = apply.call(factory, thisObject, args);
583
+ if (typeof def !== "object" || def === null) {
584
+ throw new TypeError(`Virtual table module "${moduleName}" did not return a table definition object`);
585
+ }
586
+ return parseTableDefinition(def, "returned", moduleName);
587
+ };
588
+ }
589
+ function parseTableDefinition(def, verb, moduleName) {
590
+ if (!hasOwnProperty.call(def, "rows")) {
591
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "rows" property`);
592
+ }
593
+ if (!hasOwnProperty.call(def, "columns")) {
594
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "columns" property`);
595
+ }
596
+ const rows = def.rows;
597
+ if (typeof rows !== "function" || Object.getPrototypeOf(rows) !== GeneratorFunctionPrototype) {
598
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "rows" property (should be a generator function)`);
599
+ }
600
+ let columns = def.columns;
601
+ if (!Array.isArray(columns) || !(columns = [...columns]).every((x) => typeof x === "string")) {
602
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "columns" property (should be an array of strings)`);
603
+ }
604
+ if (columns.length !== new Set(columns).size) {
605
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate column names`);
606
+ }
607
+ if (!columns.length) {
608
+ throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with zero columns`);
609
+ }
610
+ let parameters;
611
+ if (hasOwnProperty.call(def, "parameters")) {
612
+ parameters = def.parameters;
613
+ if (!Array.isArray(parameters) || !(parameters = [...parameters]).every((x) => typeof x === "string")) {
614
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "parameters" property (should be an array of strings)`);
615
+ }
616
+ } else {
617
+ parameters = inferParameters(rows);
618
+ }
619
+ if (parameters.length !== new Set(parameters).size) {
620
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate parameter names`);
621
+ }
622
+ if (parameters.length > 32) {
623
+ throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with more than the maximum number of 32 parameters`);
624
+ }
625
+ for (const parameter of parameters) {
626
+ if (columns.includes(parameter)) {
627
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with column "${parameter}" which was ambiguously defined as both a column and parameter`);
628
+ }
629
+ }
630
+ let safeIntegers = 2;
631
+ if (hasOwnProperty.call(def, "safeIntegers")) {
632
+ const bool = def.safeIntegers;
633
+ if (typeof bool !== "boolean") {
634
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "safeIntegers" property (should be a boolean)`);
635
+ }
636
+ safeIntegers = +bool;
637
+ }
638
+ let directOnly = false;
639
+ if (hasOwnProperty.call(def, "directOnly")) {
640
+ directOnly = def.directOnly;
641
+ if (typeof directOnly !== "boolean") {
642
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "directOnly" property (should be a boolean)`);
643
+ }
644
+ }
645
+ const columnDefinitions = [
646
+ ...parameters.map(identifier).map((str) => `${str} HIDDEN`),
647
+ ...columns.map(identifier)
648
+ ];
649
+ return [
650
+ `CREATE TABLE x(${columnDefinitions.join(", ")});`,
651
+ wrapGenerator(rows, new Map(columns.map((x, i) => [x, parameters.length + i])), moduleName),
652
+ parameters,
653
+ safeIntegers,
654
+ directOnly
655
+ ];
656
+ }
657
+ function wrapGenerator(generator, columnMap, moduleName) {
658
+ return function* virtualTable(...args) {
659
+ const output = args.map((x) => Buffer.isBuffer(x) ? Buffer.from(x) : x);
660
+ for (let i = 0;i < columnMap.size; ++i) {
661
+ output.push(null);
662
+ }
663
+ for (const row of generator(...args)) {
664
+ if (Array.isArray(row)) {
665
+ extractRowArray(row, output, columnMap.size, moduleName);
666
+ yield output;
667
+ } else if (typeof row === "object" && row !== null) {
668
+ extractRowObject(row, output, columnMap, moduleName);
669
+ yield output;
670
+ } else {
671
+ throw new TypeError(`Virtual table module "${moduleName}" yielded something that isn't a valid row object`);
672
+ }
673
+ }
674
+ };
675
+ }
676
+ function extractRowArray(row, output, columnCount, moduleName) {
677
+ if (row.length !== columnCount) {
678
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an incorrect number of columns`);
679
+ }
680
+ const offset = output.length - columnCount;
681
+ for (let i = 0;i < columnCount; ++i) {
682
+ output[i + offset] = row[i];
683
+ }
684
+ }
685
+ function extractRowObject(row, output, columnMap, moduleName) {
686
+ let count = 0;
687
+ for (const key of Object.keys(row)) {
688
+ const index = columnMap.get(key);
689
+ if (index === undefined) {
690
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an undeclared column "${key}"`);
691
+ }
692
+ output[index] = row[key];
693
+ count += 1;
694
+ }
695
+ if (count !== columnMap.size) {
696
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with missing columns`);
697
+ }
698
+ }
699
+ function inferParameters({ length }) {
700
+ if (!Number.isInteger(length) || length < 0) {
701
+ throw new TypeError("Expected function.length to be a positive integer");
702
+ }
703
+ const params = [];
704
+ for (let i = 0;i < length; ++i) {
705
+ params.push(`$${i + 1}`);
706
+ }
707
+ return params;
708
+ }
709
+ var { hasOwnProperty } = Object.prototype;
710
+ var { apply } = Function.prototype;
711
+ var GeneratorFunctionPrototype = Object.getPrototypeOf(function* () {});
712
+ var identifier = (str) => `"${str.replace(/"/g, '""')}"`;
713
+ var defer = (x) => () => x;
714
+ });
715
+
716
+ // node_modules/better-sqlite3/lib/methods/inspect.js
717
+ var require_inspect = __commonJS((exports, module) => {
718
+ var DatabaseInspection = function Database() {};
719
+ module.exports = function inspect(depth, opts) {
720
+ return Object.assign(new DatabaseInspection, this);
721
+ };
722
+ });
723
+
724
+ // node_modules/better-sqlite3/lib/database.js
725
+ var require_database = __commonJS((exports, module) => {
726
+ var fs = __require("fs");
727
+ var path = __require("path");
728
+ var util = require_util();
729
+ var SqliteError = require_sqlite_error();
730
+ var DEFAULT_ADDON;
731
+ function Database(filenameGiven, options) {
732
+ if (new.target == null) {
733
+ return new Database(filenameGiven, options);
734
+ }
735
+ let buffer;
736
+ if (Buffer.isBuffer(filenameGiven)) {
737
+ buffer = filenameGiven;
738
+ filenameGiven = ":memory:";
739
+ }
740
+ if (filenameGiven == null)
741
+ filenameGiven = "";
742
+ if (options == null)
743
+ options = {};
744
+ if (typeof filenameGiven !== "string")
745
+ throw new TypeError("Expected first argument to be a string");
746
+ if (typeof options !== "object")
747
+ throw new TypeError("Expected second argument to be an options object");
748
+ if ("readOnly" in options)
749
+ throw new TypeError('Misspelled option "readOnly" should be "readonly"');
750
+ if ("memory" in options)
751
+ throw new TypeError('Option "memory" was removed in v7.0.0 (use ":memory:" filename instead)');
752
+ const filename = filenameGiven.trim();
753
+ const anonymous = filename === "" || filename === ":memory:";
754
+ const readonly = util.getBooleanOption(options, "readonly");
755
+ const fileMustExist = util.getBooleanOption(options, "fileMustExist");
756
+ const timeout = "timeout" in options ? options.timeout : 5000;
757
+ const verbose = "verbose" in options ? options.verbose : null;
758
+ const nativeBinding = "nativeBinding" in options ? options.nativeBinding : null;
759
+ if (readonly && anonymous && !buffer)
760
+ throw new TypeError("In-memory/temporary databases cannot be readonly");
761
+ if (!Number.isInteger(timeout) || timeout < 0)
762
+ throw new TypeError('Expected the "timeout" option to be a positive integer');
763
+ if (timeout > 2147483647)
764
+ throw new RangeError('Option "timeout" cannot be greater than 2147483647');
765
+ if (verbose != null && typeof verbose !== "function")
766
+ throw new TypeError('Expected the "verbose" option to be a function');
767
+ if (nativeBinding != null && typeof nativeBinding !== "string" && typeof nativeBinding !== "object")
768
+ throw new TypeError('Expected the "nativeBinding" option to be a string or addon object');
769
+ let addon;
770
+ if (nativeBinding == null) {
771
+ addon = DEFAULT_ADDON || (DEFAULT_ADDON = require_bindings()("better_sqlite3.node"));
772
+ } else if (typeof nativeBinding === "string") {
773
+ const requireFunc = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : __require;
774
+ addon = requireFunc(path.resolve(nativeBinding).replace(/(\.node)?$/, ".node"));
775
+ } else {
776
+ addon = nativeBinding;
777
+ }
778
+ if (!addon.isInitialized) {
779
+ addon.setErrorConstructor(SqliteError);
780
+ addon.isInitialized = true;
781
+ }
782
+ if (!anonymous && !filename.startsWith("file:") && !fs.existsSync(path.dirname(filename))) {
783
+ throw new TypeError("Cannot open database because the directory does not exist");
784
+ }
785
+ Object.defineProperties(this, {
786
+ [util.cppdb]: { value: new addon.Database(filename, filenameGiven, anonymous, readonly, fileMustExist, timeout, verbose || null, buffer || null) },
787
+ ...wrappers.getters
788
+ });
789
+ }
790
+ var wrappers = require_wrappers();
791
+ Database.prototype.prepare = wrappers.prepare;
792
+ Database.prototype.transaction = require_transaction();
793
+ Database.prototype.pragma = require_pragma();
794
+ Database.prototype.backup = require_backup();
795
+ Database.prototype.serialize = require_serialize();
796
+ Database.prototype.function = require_function();
797
+ Database.prototype.aggregate = require_aggregate();
798
+ Database.prototype.table = require_table();
799
+ Database.prototype.loadExtension = wrappers.loadExtension;
800
+ Database.prototype.exec = wrappers.exec;
801
+ Database.prototype.close = wrappers.close;
802
+ Database.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
803
+ Database.prototype.unsafeMode = wrappers.unsafeMode;
804
+ Database.prototype[util.inspect] = require_inspect();
805
+ module.exports = Database;
806
+ });
807
+
808
+ // node_modules/better-sqlite3/lib/index.js
809
+ var require_lib = __commonJS((exports, module) => {
810
+ module.exports = require_database();
811
+ module.exports.SqliteError = require_sqlite_error();
812
+ });
813
+
814
+ // src/query/conditions.ts
815
+ function isColumnDef(value) {
816
+ return value !== null && typeof value === "object" && "__internal" in value;
817
+ }
818
+ function eq(left, valueOrColumn) {
819
+ if (isColumnDef(valueOrColumn)) {
820
+ return { type: "eqColumn", left, right: valueOrColumn };
821
+ }
822
+ return { type: "eq", column: left, value: valueOrColumn };
823
+ }
824
+ function and(...conditions) {
825
+ return { type: "and", conditions };
826
+ }
827
+ function or(...conditions) {
828
+ return { type: "or", conditions };
829
+ }
830
+ function isIn(column, values) {
831
+ return { type: "in", column, values };
832
+ }
833
+ function isNotIn(column, values) {
834
+ return { type: "notIn", column, values };
835
+ }
836
+ function isNull(column) {
837
+ return { type: "isNull", column };
838
+ }
839
+ function isNotNull(column) {
840
+ return { type: "isNotNull", column };
841
+ }
842
+ function like(column, pattern) {
843
+ return { type: "like", column, pattern };
844
+ }
845
+ function glob(column, pattern) {
846
+ return { type: "glob", column, pattern };
847
+ }
848
+ function between(column, low, high) {
849
+ return { type: "between", column, low, high };
850
+ }
851
+ function gt(column, value) {
852
+ return { type: "gt", column, value };
853
+ }
854
+ function gte(column, value) {
855
+ return { type: "gte", column, value };
856
+ }
857
+ function lt(column, value) {
858
+ return { type: "lt", column, value };
859
+ }
860
+ function lte(column, value) {
861
+ return { type: "lte", column, value };
862
+ }
863
+ function neq(column, value) {
864
+ return { type: "neq", column, value };
865
+ }
866
+ function compileCondition(cond, params) {
867
+ switch (cond.type) {
868
+ case "eq":
869
+ params.push(cond.column.__internal.encode(cond.value));
870
+ return `${cond.column.name} = ?`;
871
+ case "eqColumn": {
872
+ const leftName = cond.left.__internal.tableName ? `${cond.left.__internal.tableName}.${cond.left.name}` : cond.left.name;
873
+ const rightName = cond.right.__internal.tableName ? `${cond.right.__internal.tableName}.${cond.right.name}` : cond.right.name;
874
+ return `${leftName} = ${rightName}`;
875
+ }
876
+ case "in": {
877
+ const encoded = cond.values.map((v) => cond.column.__internal.encode(v));
878
+ params.push(...encoded);
879
+ const placeholders = encoded.map(() => "?").join(", ");
880
+ return `${cond.column.name} IN (${placeholders})`;
881
+ }
882
+ case "notIn": {
883
+ const encoded = cond.values.map((v) => cond.column.__internal.encode(v));
884
+ params.push(...encoded);
885
+ const placeholders = encoded.map(() => "?").join(", ");
886
+ return `${cond.column.name} NOT IN (${placeholders})`;
887
+ }
888
+ case "isNull":
889
+ return `${cond.column.name} IS NULL`;
890
+ case "isNotNull":
891
+ return `${cond.column.name} IS NOT NULL`;
892
+ case "like":
893
+ params.push(cond.pattern);
894
+ return `${cond.column.name} LIKE ?`;
895
+ case "glob":
896
+ params.push(cond.pattern);
897
+ return `${cond.column.name} GLOB ?`;
898
+ case "between":
899
+ params.push(cond.column.__internal.encode(cond.low));
900
+ params.push(cond.column.__internal.encode(cond.high));
901
+ return `${cond.column.name} BETWEEN ? AND ?`;
902
+ case "gt":
903
+ params.push(cond.column.__internal.encode(cond.value));
904
+ return `${cond.column.name} > ?`;
905
+ case "gte":
906
+ params.push(cond.column.__internal.encode(cond.value));
907
+ return `${cond.column.name} >= ?`;
908
+ case "lt":
909
+ params.push(cond.column.__internal.encode(cond.value));
910
+ return `${cond.column.name} < ?`;
911
+ case "lte":
912
+ params.push(cond.column.__internal.encode(cond.value));
913
+ return `${cond.column.name} <= ?`;
914
+ case "neq":
915
+ params.push(cond.column.__internal.encode(cond.value));
916
+ return `${cond.column.name} != ?`;
917
+ case "and":
918
+ return cond.conditions.map((c) => compileCondition(c, params)).join(" AND ");
919
+ case "or":
920
+ return `(${cond.conditions.map((c) => compileCondition(c, params)).join(" OR ")})`;
921
+ }
922
+ }
923
+ function compileConditions(conditions, params) {
924
+ if (conditions.length === 0)
925
+ return "1=1";
926
+ return conditions.map((c) => compileCondition(c, params)).join(" AND ");
927
+ }
928
+
929
+ // src/errors.ts
930
+ var FlintError, FlintValidationError, FlintQueryError;
931
+ var init_errors = __esm(() => {
932
+ FlintError = class FlintError extends Error {
933
+ constructor(message) {
934
+ super(message);
935
+ this.name = "FlintError";
936
+ }
937
+ };
938
+ FlintValidationError = class FlintValidationError extends FlintError {
939
+ constructor(message) {
940
+ super(message);
941
+ this.name = "FlintValidationError";
942
+ }
943
+ };
944
+ FlintQueryError = class FlintQueryError extends FlintError {
945
+ originalError;
946
+ constructor(message, originalError) {
947
+ super(message);
948
+ this.name = "FlintQueryError";
949
+ this.originalError = originalError;
950
+ }
951
+ };
952
+ });
953
+
954
+ // src/query/builder.ts
955
+ function getCol(tbl, key) {
956
+ const col = tbl[key];
957
+ if (!col)
958
+ throw new FlintValidationError(`Column "${key}" not found in table`);
959
+ return col;
960
+ }
961
+ function columnEntries(tbl) {
962
+ return Object.entries(tbl).filter(([k]) => k !== "_" && k !== "__indexes");
963
+ }
964
+ function decodeRow(raw, tbl) {
965
+ const out = {};
966
+ for (const [key, col] of columnEntries(tbl)) {
967
+ out[key] = col.__internal.decode(raw[col.name]);
968
+ }
969
+ return out;
970
+ }
971
+ function decodeSelectedRow(raw, tbl, keys) {
972
+ const out = {};
973
+ for (const key of keys) {
974
+ const col = getCol(tbl, key);
975
+ out[key] = col.__internal.decode(raw[col.name]);
976
+ }
977
+ return out;
978
+ }
979
+ function findPKKey(tbl) {
980
+ for (const [key, col] of columnEntries(tbl)) {
981
+ if (col.__internal.isPrimaryKey)
982
+ return key;
983
+ }
984
+ throw new FlintValidationError("Table has no primary key column");
985
+ }
986
+ function resolveForeignKeyCondition(parent, parentName, child, childName) {
987
+ for (const [, col] of columnEntries(child)) {
988
+ if (col.__internal.referencesTable === parentName && col.__internal.referencesColumn) {
989
+ const parentCol = getCol(parent, col.__internal.referencesColumn);
990
+ if (parentCol) {
991
+ return eq(parentCol, col);
992
+ }
993
+ }
994
+ }
995
+ throw new FlintValidationError(`No foreign key reference found from "${childName}" to "${parentName}". Use .references() on the child table or provide an explicit condition.`);
996
+ }
997
+ function extractColumns(cond) {
998
+ switch (cond.type) {
999
+ case "eq":
1000
+ return [cond.column];
1001
+ case "eqColumn":
1002
+ return [cond.left, cond.right];
1003
+ case "in":
1004
+ case "notIn":
1005
+ case "isNull":
1006
+ case "isNotNull":
1007
+ case "like":
1008
+ case "glob":
1009
+ case "between":
1010
+ return [cond.column];
1011
+ case "and":
1012
+ case "or":
1013
+ return cond.conditions.flatMap(extractColumns);
1014
+ default:
1015
+ return [];
1016
+ }
1017
+ }
1018
+ function validateColumnOwnership(conditions, allowedTables, context) {
1019
+ const allowedColumns = new Set(allowedTables.flatMap((t) => columnEntries(t).map(([, c]) => c)));
1020
+ for (const cond of conditions) {
1021
+ const cols = extractColumns(cond);
1022
+ for (const col of cols) {
1023
+ if (!allowedColumns.has(col)) {
1024
+ 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.`);
1025
+ }
1026
+ }
1027
+ }
1028
+ }
1029
+ function resolveColumns(table, selectedColumns, prefix) {
1030
+ if (selectedColumns) {
1031
+ return selectedColumns.map((k) => {
1032
+ const name = getCol(table, k).name;
1033
+ return prefix ? `${prefix}.${name}` : name;
1034
+ }).join(", ");
1035
+ }
1036
+ const entries = columnEntries(table);
1037
+ return entries.map(([, c]) => prefix ? `${prefix}.${c.name}` : c.name).join(", ");
1038
+ }
1039
+
1040
+ class SelectFromBuilder {
1041
+ #executor;
1042
+ #conditions;
1043
+ constructor(executor, conditions = []) {
1044
+ this.#executor = executor;
1045
+ this.#conditions = conditions;
1046
+ }
1047
+ from(table) {
1048
+ return new SelectBuilder(this.#executor, table._.name, table, this.#conditions);
1049
+ }
1050
+ }
1051
+
1052
+ class SelectBuilder {
1053
+ #executor;
1054
+ #tableName;
1055
+ #table;
1056
+ #conditions;
1057
+ #selectedColumns;
1058
+ #orderByClauses;
1059
+ #limitValue;
1060
+ #offsetValue;
1061
+ #distinct;
1062
+ constructor(executor, tableName, table, conditions = [], selectedColumns = null, orderByClauses = [], limitValue = null, offsetValue = null, distinct = false) {
1063
+ this.#executor = executor;
1064
+ this.#tableName = tableName;
1065
+ this.#table = table;
1066
+ this.#conditions = conditions;
1067
+ this.#selectedColumns = selectedColumns;
1068
+ this.#orderByClauses = orderByClauses;
1069
+ this.#limitValue = limitValue;
1070
+ this.#offsetValue = offsetValue;
1071
+ this.#distinct = distinct;
1072
+ }
1073
+ where(condition) {
1074
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
1075
+ }
1076
+ columns(keys) {
1077
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, keys, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
1078
+ }
1079
+ single() {
1080
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
1081
+ }
1082
+ distinct() {
1083
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, true);
1084
+ }
1085
+ orderBy(key, direction = "asc") {
1086
+ const column = getCol(this.#table, key);
1087
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue, this.#distinct);
1088
+ }
1089
+ limit(n) {
1090
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue, this.#distinct);
1091
+ }
1092
+ offset(n) {
1093
+ return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n, this.#distinct);
1094
+ }
1095
+ toSQL() {
1096
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
1097
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
1098
+ const params = [];
1099
+ const distinct = this.#distinct ? "DISTINCT " : "";
1100
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
1101
+ const where = compileConditions(this.#conditions, params);
1102
+ if (where !== "1=1")
1103
+ sql += ` WHERE ${where}`;
1104
+ if (this.#orderByClauses.length > 0) {
1105
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
1106
+ sql += ` ORDER BY ${orderClauses}`;
1107
+ }
1108
+ if (this.#limitValue !== null)
1109
+ sql += ` LIMIT ${this.#limitValue}`;
1110
+ if (this.#offsetValue !== null)
1111
+ sql += ` OFFSET ${this.#offsetValue}`;
1112
+ return { sql, params };
1113
+ }
1114
+ async execute() {
1115
+ const { sql, params } = this.toSQL();
1116
+ try {
1117
+ const rows = await this.#executor.all(sql, params);
1118
+ const records = rows;
1119
+ if (this.#selectedColumns) {
1120
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#selectedColumns));
1121
+ }
1122
+ return records.map((r) => decodeRow(r, this.#table));
1123
+ } catch (e) {
1124
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1125
+ }
1126
+ }
1127
+ }
1128
+
1129
+ class NarrowedSelectBuilder {
1130
+ #executor;
1131
+ #tableName;
1132
+ #table;
1133
+ #conditions;
1134
+ #selectedColumns;
1135
+ #orderByClauses;
1136
+ #limitValue;
1137
+ #offsetValue;
1138
+ #distinct;
1139
+ constructor(executor, tableName, table, conditions, selectedColumns, orderByClauses, limitValue, offsetValue, distinct) {
1140
+ this.#executor = executor;
1141
+ this.#tableName = tableName;
1142
+ this.#table = table;
1143
+ this.#conditions = conditions;
1144
+ this.#selectedColumns = selectedColumns;
1145
+ this.#orderByClauses = orderByClauses;
1146
+ this.#limitValue = limitValue;
1147
+ this.#offsetValue = offsetValue;
1148
+ this.#distinct = distinct;
1149
+ }
1150
+ where(condition) {
1151
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct);
1152
+ }
1153
+ distinct() {
1154
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, true);
1155
+ }
1156
+ single() {
1157
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
1158
+ }
1159
+ orderBy(key, direction = "asc") {
1160
+ const column = getCol(this.#table, key);
1161
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue, this.#distinct);
1162
+ }
1163
+ limit(n) {
1164
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue, this.#distinct);
1165
+ }
1166
+ offset(n) {
1167
+ return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n, this.#distinct);
1168
+ }
1169
+ toSQL() {
1170
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
1171
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
1172
+ const params = [];
1173
+ const distinct = this.#distinct ? "DISTINCT " : "";
1174
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
1175
+ const where = compileConditions(this.#conditions, params);
1176
+ if (where !== "1=1")
1177
+ sql += ` WHERE ${where}`;
1178
+ if (this.#orderByClauses.length > 0) {
1179
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
1180
+ sql += ` ORDER BY ${orderClauses}`;
1181
+ }
1182
+ if (this.#limitValue !== null)
1183
+ sql += ` LIMIT ${this.#limitValue}`;
1184
+ if (this.#offsetValue !== null)
1185
+ sql += ` OFFSET ${this.#offsetValue}`;
1186
+ return { sql, params };
1187
+ }
1188
+ async execute() {
1189
+ const { sql, params } = this.toSQL();
1190
+ try {
1191
+ const rows = await this.#executor.all(sql, params);
1192
+ return rows.map((r) => decodeSelectedRow(r, this.#table, this.#selectedColumns));
1193
+ } catch (e) {
1194
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1195
+ }
1196
+ }
1197
+ }
1198
+
1199
+ class SingleSelectBuilder {
1200
+ #executor;
1201
+ #tableName;
1202
+ #table;
1203
+ #conditions;
1204
+ #selectedColumns;
1205
+ #orderByClauses;
1206
+ #offsetValue;
1207
+ #distinct;
1208
+ constructor(executor, tableName, table, conditions, selectedColumns = null, orderByClauses = [], offsetValue = null, distinct = false) {
1209
+ this.#executor = executor;
1210
+ this.#tableName = tableName;
1211
+ this.#table = table;
1212
+ this.#conditions = conditions;
1213
+ this.#selectedColumns = selectedColumns;
1214
+ this.#orderByClauses = orderByClauses;
1215
+ this.#offsetValue = offsetValue;
1216
+ this.#distinct = distinct;
1217
+ }
1218
+ where(condition) {
1219
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
1220
+ }
1221
+ orderBy(key, direction = "asc") {
1222
+ const column = getCol(this.#table, key);
1223
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue, this.#distinct);
1224
+ }
1225
+ offset(n) {
1226
+ return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#distinct);
1227
+ }
1228
+ toSQL() {
1229
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
1230
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
1231
+ const params = [];
1232
+ const distinct = this.#distinct ? "DISTINCT " : "";
1233
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
1234
+ const where = compileConditions(this.#conditions, params);
1235
+ if (where !== "1=1")
1236
+ sql += ` WHERE ${where}`;
1237
+ if (this.#orderByClauses.length > 0) {
1238
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
1239
+ sql += ` ORDER BY ${orderClauses}`;
1240
+ }
1241
+ sql += " LIMIT 1";
1242
+ if (this.#offsetValue !== null)
1243
+ sql += ` OFFSET ${this.#offsetValue}`;
1244
+ return { sql, params };
1245
+ }
1246
+ async execute() {
1247
+ const { sql, params } = this.toSQL();
1248
+ try {
1249
+ const row = await this.#executor.get(sql, params);
1250
+ if (!row)
1251
+ return null;
1252
+ const record = row;
1253
+ if (this.#selectedColumns) {
1254
+ return decodeSelectedRow(record, this.#table, this.#selectedColumns);
1255
+ }
1256
+ return decodeRow(record, this.#table);
1257
+ } catch (e) {
1258
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1259
+ }
1260
+ }
1261
+ }
1262
+
1263
+ class NarrowedSingleSelectBuilder {
1264
+ #executor;
1265
+ #tableName;
1266
+ #table;
1267
+ #conditions;
1268
+ #selectedColumns;
1269
+ #orderByClauses;
1270
+ #offsetValue;
1271
+ #distinct;
1272
+ constructor(executor, tableName, table, conditions, selectedColumns, orderByClauses, offsetValue, distinct) {
1273
+ this.#executor = executor;
1274
+ this.#tableName = tableName;
1275
+ this.#table = table;
1276
+ this.#conditions = conditions;
1277
+ this.#selectedColumns = selectedColumns;
1278
+ this.#orderByClauses = orderByClauses;
1279
+ this.#offsetValue = offsetValue;
1280
+ this.#distinct = distinct;
1281
+ }
1282
+ where(condition) {
1283
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct);
1284
+ }
1285
+ orderBy(key, direction = "asc") {
1286
+ const column = getCol(this.#table, key);
1287
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue, this.#distinct);
1288
+ }
1289
+ offset(n) {
1290
+ return new NarrowedSingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#distinct);
1291
+ }
1292
+ toSQL() {
1293
+ validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`);
1294
+ const cols = resolveColumns(this.#table, this.#selectedColumns);
1295
+ const params = [];
1296
+ const distinct = this.#distinct ? "DISTINCT " : "";
1297
+ let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`;
1298
+ const where = compileConditions(this.#conditions, params);
1299
+ if (where !== "1=1")
1300
+ sql += ` WHERE ${where}`;
1301
+ if (this.#orderByClauses.length > 0) {
1302
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
1303
+ sql += ` ORDER BY ${orderClauses}`;
1304
+ }
1305
+ sql += " LIMIT 1";
1306
+ if (this.#offsetValue !== null)
1307
+ sql += ` OFFSET ${this.#offsetValue}`;
1308
+ return { sql, params };
1309
+ }
1310
+ async execute() {
1311
+ const { sql, params } = this.toSQL();
1312
+ try {
1313
+ const row = await this.#executor.get(sql, params);
1314
+ if (!row)
1315
+ return null;
1316
+ return decodeSelectedRow(row, this.#table, this.#selectedColumns);
1317
+ } catch (e) {
1318
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1319
+ }
1320
+ }
1321
+ }
1322
+
1323
+ class JoinStage1 {
1324
+ #executor;
1325
+ #parent;
1326
+ #parentName;
1327
+ #joinType;
1328
+ constructor(executor, parent, parentName, joinType) {
1329
+ this.#executor = executor;
1330
+ this.#parent = parent;
1331
+ this.#parentName = parentName;
1332
+ this.#joinType = joinType;
1333
+ }
1334
+ on(child, condition) {
1335
+ const childName = child._.name;
1336
+ const resolvedCondition = condition ?? resolveForeignKeyCondition(this.#parent, this.#parentName, child, childName);
1337
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, [{ table: child, name: childName, condition: resolvedCondition }], this.#joinType);
1338
+ }
1339
+ }
1340
+
1341
+ class JoinBuilderImpl {
1342
+ #executor;
1343
+ #parent;
1344
+ #parentName;
1345
+ #joins;
1346
+ #joinType;
1347
+ #conditions;
1348
+ #selectedColumns;
1349
+ #orderByClauses;
1350
+ #limitValue;
1351
+ #offsetValue;
1352
+ constructor(executor, parent, parentName, joins, joinType, conditions = [], selectedColumns = null, orderByClauses = [], limitValue = null, offsetValue = null) {
1353
+ this.#executor = executor;
1354
+ this.#parent = parent;
1355
+ this.#parentName = parentName;
1356
+ this.#joins = joins;
1357
+ this.#joinType = joinType;
1358
+ this.#conditions = conditions;
1359
+ this.#selectedColumns = selectedColumns;
1360
+ this.#orderByClauses = orderByClauses;
1361
+ this.#limitValue = limitValue;
1362
+ this.#offsetValue = offsetValue;
1363
+ }
1364
+ on(child, condition) {
1365
+ const childName = child._.name;
1366
+ const resolvedCondition = condition ?? resolveForeignKeyCondition(this.#parent, this.#parentName, child, childName);
1367
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, [...this.#joins, { table: child, name: childName, condition: resolvedCondition }], this.#joinType, this.#conditions, this.#selectedColumns);
1368
+ }
1369
+ where(condition) {
1370
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, [...this.#conditions, condition], this.#selectedColumns);
1371
+ }
1372
+ columns(keys) {
1373
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, keys, this.#orderByClauses, this.#limitValue, this.#offsetValue);
1374
+ }
1375
+ orderBy(key, direction = "asc") {
1376
+ const column = getCol(this.#parent, key);
1377
+ 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);
1378
+ }
1379
+ limit(n) {
1380
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue);
1381
+ }
1382
+ offset(n) {
1383
+ return new JoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n);
1384
+ }
1385
+ single() {
1386
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue);
1387
+ }
1388
+ toSQL() {
1389
+ const allowedTables = [this.#parent, ...this.#joins.map((j) => j.table)];
1390
+ validateColumnOwnership(this.#conditions, allowedTables, `SELECT from "${this.#parentName}"`);
1391
+ const parentCols = resolveColumns(this.#parent, this.#selectedColumns, this.#parentName);
1392
+ const childCols = [];
1393
+ for (const join of this.#joins) {
1394
+ const entries = columnEntries(join.table);
1395
+ for (const [, c] of entries) {
1396
+ childCols.push(`${join.name}.${c.name} AS ${join.name}_${c.name}`);
1397
+ }
1398
+ }
1399
+ const joinKeyword = this.#joinType === "left" ? "LEFT JOIN" : "INNER JOIN";
1400
+ const joinClauses = [];
1401
+ const joinParams = [];
1402
+ for (const join of this.#joins) {
1403
+ const joinOn = compileConditions([join.condition], joinParams);
1404
+ joinClauses.push(`${joinKeyword} ${join.name} ON ${joinOn}`);
1405
+ }
1406
+ const whereParams = [];
1407
+ const where = compileConditions(this.#conditions, whereParams);
1408
+ let sql = `SELECT ${parentCols}${childCols.length ? ", " + childCols.join(", ") : ""} FROM ${this.#parentName} ${joinClauses.join(" ")}`;
1409
+ if (where !== "1=1")
1410
+ sql += ` WHERE ${where}`;
1411
+ if (this.#orderByClauses.length > 0) {
1412
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
1413
+ sql += ` ORDER BY ${orderClauses}`;
1414
+ }
1415
+ if (this.#limitValue !== null)
1416
+ sql += ` LIMIT ${this.#limitValue}`;
1417
+ if (this.#offsetValue !== null)
1418
+ sql += ` OFFSET ${this.#offsetValue}`;
1419
+ return { sql, params: [...joinParams, ...whereParams] };
1420
+ }
1421
+ async execute() {
1422
+ const { sql, params } = this.toSQL();
1423
+ try {
1424
+ const rows = await this.#executor.all(sql, params);
1425
+ return this.#decodeJoinRows(rows);
1426
+ } catch (e) {
1427
+ if (e instanceof FlintQueryError)
1428
+ throw e;
1429
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1430
+ }
1431
+ }
1432
+ #decodeJoinRows(rows) {
1433
+ const parentEntries = columnEntries(this.#parent);
1434
+ const pkKey = findPKKey(this.#parent);
1435
+ const pkColName = getCol(this.#parent, pkKey).name;
1436
+ const childEntryMaps = [];
1437
+ for (const j of this.#joins) {
1438
+ childEntryMaps.push({
1439
+ name: j.name,
1440
+ entries: columnEntries(j.table),
1441
+ table: j.table
1442
+ });
1443
+ }
1444
+ const grouped = new Map;
1445
+ for (const row of rows) {
1446
+ const pk = row[pkColName];
1447
+ if (!grouped.has(pk)) {
1448
+ const parentRow = {};
1449
+ for (const [key, col] of parentEntries) {
1450
+ parentRow[key] = row[col.name];
1451
+ }
1452
+ grouped.set(pk, {
1453
+ parent: parentRow,
1454
+ children: childEntryMaps.map(() => [])
1455
+ });
1456
+ }
1457
+ const group = grouped.get(pk);
1458
+ childEntryMaps.forEach((childMap, i) => {
1459
+ const childRow = {};
1460
+ let hasNonNullChild = false;
1461
+ for (const [key, col] of childMap.entries) {
1462
+ const val = row[`${childMap.name}_${col.name}`];
1463
+ childRow[key] = val;
1464
+ if (val != null)
1465
+ hasNonNullChild = true;
1466
+ }
1467
+ if (this.#joinType === "left" && !hasNonNullChild)
1468
+ return;
1469
+ group.children[i].push(childRow);
1470
+ });
1471
+ }
1472
+ const result = [];
1473
+ for (const { parent, children } of grouped.values()) {
1474
+ const decodedParent = this.#selectedColumns ? decodeSelectedRow(parent, this.#parent, this.#selectedColumns) : decodeRow(parent, this.#parent);
1475
+ const nested = { ...decodedParent };
1476
+ childEntryMaps.forEach((childMap, i) => {
1477
+ nested[childMap.name] = children[i].map((c) => decodeRow(c, childMap.table));
1478
+ });
1479
+ result.push(nested);
1480
+ }
1481
+ return result;
1482
+ }
1483
+ }
1484
+
1485
+ class SingleJoinBuilderImpl {
1486
+ #executor;
1487
+ #parent;
1488
+ #parentName;
1489
+ #joins;
1490
+ #joinType;
1491
+ #conditions;
1492
+ #selectedColumns;
1493
+ #orderByClauses;
1494
+ #offsetValue;
1495
+ constructor(executor, parent, parentName, joins, joinType, conditions, selectedColumns = null, orderByClauses = [], offsetValue = null) {
1496
+ this.#executor = executor;
1497
+ this.#parent = parent;
1498
+ this.#parentName = parentName;
1499
+ this.#joins = joins;
1500
+ this.#joinType = joinType;
1501
+ this.#conditions = conditions;
1502
+ this.#selectedColumns = selectedColumns;
1503
+ this.#orderByClauses = orderByClauses;
1504
+ this.#offsetValue = offsetValue;
1505
+ }
1506
+ where(condition) {
1507
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#offsetValue);
1508
+ }
1509
+ orderBy(key, direction = "asc") {
1510
+ const column = getCol(this.#parent, key);
1511
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#offsetValue);
1512
+ }
1513
+ offset(n) {
1514
+ return new SingleJoinBuilderImpl(this.#executor, this.#parent, this.#parentName, this.#joins, this.#joinType, this.#conditions, this.#selectedColumns, this.#orderByClauses, n);
1515
+ }
1516
+ toSQL() {
1517
+ const allowedTables = [this.#parent, ...this.#joins.map((j) => j.table)];
1518
+ validateColumnOwnership(this.#conditions, allowedTables, `SELECT from "${this.#parentName}"`);
1519
+ const parentCols = resolveColumns(this.#parent, this.#selectedColumns, this.#parentName);
1520
+ const childCols = [];
1521
+ for (const join of this.#joins) {
1522
+ const entries = columnEntries(join.table);
1523
+ for (const [, c] of entries) {
1524
+ childCols.push(`${join.name}.${c.name} AS ${join.name}_${c.name}`);
1525
+ }
1526
+ }
1527
+ const joinKeyword = this.#joinType === "left" ? "LEFT JOIN" : "INNER JOIN";
1528
+ const joinClauses = [];
1529
+ const joinParams = [];
1530
+ for (const join of this.#joins) {
1531
+ const joinOn = compileConditions([join.condition], joinParams);
1532
+ joinClauses.push(`${joinKeyword} ${join.name} ON ${joinOn}`);
1533
+ }
1534
+ const whereParams = [];
1535
+ const where = compileConditions(this.#conditions, whereParams);
1536
+ let sql = `SELECT ${parentCols}${childCols.length ? ", " + childCols.join(", ") : ""} FROM ${this.#parentName} ${joinClauses.join(" ")}`;
1537
+ if (where !== "1=1")
1538
+ sql += ` WHERE ${where}`;
1539
+ if (this.#orderByClauses.length > 0) {
1540
+ const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", ");
1541
+ sql += ` ORDER BY ${orderClauses}`;
1542
+ }
1543
+ sql += " LIMIT 1";
1544
+ if (this.#offsetValue !== null)
1545
+ sql += ` OFFSET ${this.#offsetValue}`;
1546
+ return { sql, params: [...joinParams, ...whereParams] };
1547
+ }
1548
+ async execute() {
1549
+ const { sql, params } = this.toSQL();
1550
+ try {
1551
+ const rows = await this.#executor.all(sql, params);
1552
+ const records = rows;
1553
+ if (records.length === 0)
1554
+ return null;
1555
+ return this.#decodeJoinRow(records);
1556
+ } catch (e) {
1557
+ if (e instanceof FlintQueryError)
1558
+ throw e;
1559
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1560
+ }
1561
+ }
1562
+ #decodeJoinRow(rows) {
1563
+ const parentEntries = columnEntries(this.#parent);
1564
+ const pkKey = findPKKey(this.#parent);
1565
+ const pkColName = getCol(this.#parent, pkKey).name;
1566
+ const childEntryMaps = [];
1567
+ for (const j of this.#joins) {
1568
+ childEntryMaps.push({
1569
+ name: j.name,
1570
+ entries: columnEntries(j.table),
1571
+ table: j.table
1572
+ });
1573
+ }
1574
+ const grouped = new Map;
1575
+ for (const r of rows) {
1576
+ const pk = r[pkColName];
1577
+ if (!grouped.has(pk)) {
1578
+ const parentRow = {};
1579
+ for (const [key, col] of parentEntries) {
1580
+ parentRow[key] = r[col.name];
1581
+ }
1582
+ grouped.set(pk, {
1583
+ parent: parentRow,
1584
+ children: childEntryMaps.map(() => [])
1585
+ });
1586
+ }
1587
+ const group = grouped.get(pk);
1588
+ childEntryMaps.forEach((childMap, i) => {
1589
+ const childRow = {};
1590
+ let hasNonNullChild = false;
1591
+ for (const [key, col] of childMap.entries) {
1592
+ const val = r[`${childMap.name}_${col.name}`];
1593
+ childRow[key] = val;
1594
+ if (val != null)
1595
+ hasNonNullChild = true;
1596
+ }
1597
+ if (this.#joinType === "left" && !hasNonNullChild)
1598
+ return;
1599
+ group.children[i].push(childRow);
1600
+ });
1601
+ }
1602
+ const first = grouped.values().next().value;
1603
+ if (!first)
1604
+ return null;
1605
+ const decodedParent = this.#selectedColumns ? decodeSelectedRow(first.parent, this.#parent, this.#selectedColumns) : decodeRow(first.parent, this.#parent);
1606
+ const nested = { ...decodedParent };
1607
+ childEntryMaps.forEach((childMap, i) => {
1608
+ nested[childMap.name] = first.children[i].map((c) => decodeRow(c, childMap.table));
1609
+ });
1610
+ return nested;
1611
+ }
1612
+ }
1613
+
1614
+ class InsertValuesBuilder {
1615
+ #executor;
1616
+ #tableName;
1617
+ #table;
1618
+ constructor(executor, tableName, table) {
1619
+ this.#executor = executor;
1620
+ this.#tableName = tableName;
1621
+ this.#table = table;
1622
+ }
1623
+ values(rowOrRows) {
1624
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, rowOrRows);
1625
+ }
1626
+ }
1627
+
1628
+ class InsertBuilder {
1629
+ #executor;
1630
+ #tableName;
1631
+ #table;
1632
+ #rows;
1633
+ #returning;
1634
+ #onConflict;
1635
+ constructor(executor, tableName, table, rowOrRows, returning = false, onConflict) {
1636
+ this.#executor = executor;
1637
+ this.#tableName = tableName;
1638
+ this.#table = table;
1639
+ this.#rows = Array.isArray(rowOrRows) ? rowOrRows : [rowOrRows];
1640
+ this.#returning = returning;
1641
+ this.#onConflict = onConflict;
1642
+ }
1643
+ returning(keys) {
1644
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, keys ?? true, this.#onConflict);
1645
+ }
1646
+ onConflictDoNothing() {
1647
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, this.#returning, { mode: "nothing" });
1648
+ }
1649
+ onConflictDoUpdate(options) {
1650
+ return new InsertBuilder(this.#executor, this.#tableName, this.#table, this.#rows, this.#returning, {
1651
+ mode: "update",
1652
+ target: options.target,
1653
+ set: options.set
1654
+ });
1655
+ }
1656
+ toSQL() {
1657
+ const entries = columnEntries(this.#table);
1658
+ const inserts = [];
1659
+ for (const [key, c] of entries) {
1660
+ const allUndefined = this.#rows.every((row) => row[key] === undefined);
1661
+ if (allUndefined && (c.__internal.hasDefault || c.__internal.isAutoIncrement)) {
1662
+ continue;
1663
+ }
1664
+ inserts.push([key, c]);
1665
+ }
1666
+ if (inserts.length === 0) {
1667
+ const allDefault = entries.filter(([, c]) => c.__internal.hasDefault || c.__internal.isAutoIncrement || c.__internal.hasDefaultNow);
1668
+ const names2 = allDefault.map(([, c]) => c.name).join(", ");
1669
+ const placeholders = allDefault.map(() => "DEFAULT").join(", ");
1670
+ return {
1671
+ sql: `INSERT INTO ${this.#tableName} (${names2}) VALUES (${placeholders})`,
1672
+ params: []
1673
+ };
1674
+ }
1675
+ const names = inserts.map(([, c]) => c.name).join(", ");
1676
+ const placeholderRow = inserts.map(() => "?").join(", ");
1677
+ const allPlaceholders = this.#rows.map(() => `(${placeholderRow})`).join(", ");
1678
+ const params = [];
1679
+ for (const row of this.#rows) {
1680
+ for (const [key, c] of inserts) {
1681
+ const value = row[key];
1682
+ if (value === undefined && c.__internal.hasDefaultNow) {
1683
+ params.push(c.__internal.encode(new Date));
1684
+ } else {
1685
+ params.push(c.__internal.encode(value));
1686
+ }
1687
+ }
1688
+ }
1689
+ let sql = `INSERT INTO ${this.#tableName} (${names}) VALUES ${allPlaceholders}`;
1690
+ if (this.#onConflict) {
1691
+ if (this.#onConflict.mode === "nothing") {
1692
+ sql += " ON CONFLICT DO NOTHING";
1693
+ } else {
1694
+ const target = this.#onConflict.target;
1695
+ const targetCols = Array.isArray(target) ? target : [target];
1696
+ const targetNames = targetCols.map((c) => c.name).join(", ");
1697
+ const setEntries = Object.entries(this.#onConflict.set);
1698
+ const setClauses = setEntries.map(([key, value]) => {
1699
+ const col = getCol(this.#table, key);
1700
+ if (value === undefined)
1701
+ return null;
1702
+ return `${col.name} = excluded.${col.name}`;
1703
+ }).filter(Boolean);
1704
+ if (setClauses.length > 0) {
1705
+ sql += ` ON CONFLICT (${targetNames}) DO UPDATE SET ${setClauses.join(", ")}`;
1706
+ }
1707
+ }
1708
+ }
1709
+ if (this.#returning) {
1710
+ if (Array.isArray(this.#returning)) {
1711
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
1712
+ sql += ` RETURNING ${cols}`;
1713
+ } else {
1714
+ sql += " RETURNING *";
1715
+ }
1716
+ }
1717
+ return { sql, params };
1718
+ }
1719
+ async execute() {
1720
+ const { sql, params } = this.toSQL();
1721
+ try {
1722
+ if (this.#returning) {
1723
+ const rows = await this.#executor.all(sql, params);
1724
+ const records = rows;
1725
+ if (Array.isArray(this.#returning)) {
1726
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
1727
+ }
1728
+ return records.map((r) => decodeRow(r, this.#table));
1729
+ }
1730
+ await this.#executor.run(sql, params);
1731
+ return;
1732
+ } catch (e) {
1733
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1734
+ }
1735
+ }
1736
+ }
1737
+
1738
+ class UpdateSetBuilder {
1739
+ #executor;
1740
+ #tableName;
1741
+ #table;
1742
+ constructor(executor, tableName, table) {
1743
+ this.#executor = executor;
1744
+ this.#tableName = tableName;
1745
+ this.#table = table;
1746
+ }
1747
+ set(partial) {
1748
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, partial);
1749
+ }
1750
+ }
1751
+
1752
+ class UpdateBuilder {
1753
+ #executor;
1754
+ #tableName;
1755
+ #table;
1756
+ #set;
1757
+ #conditions;
1758
+ #returning;
1759
+ constructor(executor, tableName, table, set, conditions = [], returning = false) {
1760
+ this.#executor = executor;
1761
+ this.#tableName = tableName;
1762
+ this.#table = table;
1763
+ this.#set = set;
1764
+ this.#conditions = conditions;
1765
+ this.#returning = returning;
1766
+ }
1767
+ set(partial) {
1768
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, { ...this.#set, ...partial }, this.#conditions, this.#returning);
1769
+ }
1770
+ where(condition) {
1771
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, this.#set, [...this.#conditions, condition], this.#returning);
1772
+ }
1773
+ returning(keys) {
1774
+ return new UpdateBuilder(this.#executor, this.#tableName, this.#table, this.#set, this.#conditions, keys ?? true);
1775
+ }
1776
+ toSQL() {
1777
+ validateColumnOwnership(this.#conditions, [this.#table], `UPDATE "${this.#tableName}"`);
1778
+ const params = [];
1779
+ const setClauses = [];
1780
+ for (const key of Object.keys(this.#set)) {
1781
+ const col = getCol(this.#table, key);
1782
+ if (col.__internal.hasOnUpdate) {
1783
+ setClauses.push(`${col.name} = ?`);
1784
+ params.push(col.__internal.encode(new Date));
1785
+ continue;
1786
+ }
1787
+ setClauses.push(`${col.name} = ?`);
1788
+ params.push(col.__internal.encode(this.#set[key]));
1789
+ }
1790
+ let sql = `UPDATE ${this.#tableName} SET ${setClauses.join(", ")}`;
1791
+ const where = compileConditions(this.#conditions, params);
1792
+ if (where !== "1=1")
1793
+ sql += ` WHERE ${where}`;
1794
+ if (this.#returning) {
1795
+ if (Array.isArray(this.#returning)) {
1796
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
1797
+ sql += ` RETURNING ${cols}`;
1798
+ } else {
1799
+ sql += " RETURNING *";
1800
+ }
1801
+ }
1802
+ return { sql, params };
1803
+ }
1804
+ async execute() {
1805
+ const { sql, params } = this.toSQL();
1806
+ try {
1807
+ if (this.#returning) {
1808
+ const rows = await this.#executor.all(sql, params);
1809
+ const records = rows;
1810
+ if (Array.isArray(this.#returning)) {
1811
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
1812
+ }
1813
+ return records.map((r) => decodeRow(r, this.#table));
1814
+ }
1815
+ await this.#executor.run(sql, params);
1816
+ return;
1817
+ } catch (e) {
1818
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1819
+ }
1820
+ }
1821
+ }
1822
+
1823
+ class DeleteBuilder {
1824
+ #executor;
1825
+ #tableName;
1826
+ #table;
1827
+ #conditions;
1828
+ #returning;
1829
+ constructor(executor, tableName, table, conditions = [], returning = false) {
1830
+ this.#executor = executor;
1831
+ this.#tableName = tableName;
1832
+ this.#table = table;
1833
+ this.#conditions = conditions;
1834
+ this.#returning = returning;
1835
+ }
1836
+ where(condition) {
1837
+ return new DeleteBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#returning);
1838
+ }
1839
+ returning(keys) {
1840
+ return new DeleteBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, keys ?? true);
1841
+ }
1842
+ toSQL() {
1843
+ validateColumnOwnership(this.#conditions, [this.#table], `DELETE from "${this.#tableName}"`);
1844
+ const params = [];
1845
+ let sql = `DELETE FROM ${this.#tableName}`;
1846
+ const where = compileConditions(this.#conditions, params);
1847
+ if (where !== "1=1")
1848
+ sql += ` WHERE ${where}`;
1849
+ if (this.#returning) {
1850
+ if (Array.isArray(this.#returning)) {
1851
+ const cols = this.#returning.map((k) => getCol(this.#table, k).name).join(", ");
1852
+ sql += ` RETURNING ${cols}`;
1853
+ } else {
1854
+ sql += " RETURNING *";
1855
+ }
1856
+ }
1857
+ return { sql, params };
1858
+ }
1859
+ async execute() {
1860
+ const { sql, params } = this.toSQL();
1861
+ try {
1862
+ if (this.#returning) {
1863
+ const rows = await this.#executor.all(sql, params);
1864
+ const records = rows;
1865
+ if (Array.isArray(this.#returning)) {
1866
+ return records.map((r) => decodeSelectedRow(r, this.#table, this.#returning));
1867
+ }
1868
+ return records.map((r) => decodeRow(r, this.#table));
1869
+ }
1870
+ await this.#executor.run(sql, params);
1871
+ return;
1872
+ } catch (e) {
1873
+ throw new FlintQueryError(`Failed to execute query: ${sql}`, e);
1874
+ }
1875
+ }
1876
+ }
1877
+ var init_builder = __esm(() => {
1878
+ init_errors();
1879
+ });
1880
+
1881
+ // src/query/aggregates.ts
1882
+ function getTableName(table) {
1883
+ return table._.name;
1884
+ }
1885
+ function getColumnName(column) {
1886
+ return column.name;
1887
+ }
1888
+ function compileWhere(condition) {
1889
+ if (!condition) {
1890
+ return { whereSql: "", params: [] };
1891
+ }
1892
+ const params = [];
1893
+ const whereSql = compileCondition(condition, params);
1894
+ return { whereSql: ` WHERE ${whereSql}`, params };
1895
+ }
1896
+ async function count(executor, table, condition) {
1897
+ const tableName = getTableName(table);
1898
+ const { whereSql, params } = compileWhere(condition);
1899
+ const sql = `SELECT count(*) as cnt FROM ${tableName}${whereSql}`;
1900
+ const result = await executor.get(sql, params);
1901
+ return result.cnt;
1902
+ }
1903
+ async function countColumn(executor, table, column, condition) {
1904
+ const tableName = getTableName(table);
1905
+ const columnName = getColumnName(column);
1906
+ const { whereSql, params } = compileWhere(condition);
1907
+ const sql = `SELECT count(${columnName}) as cnt FROM ${tableName}${whereSql}`;
1908
+ const result = await executor.get(sql, params);
1909
+ return result.cnt;
1910
+ }
1911
+ async function sum(executor, table, column, condition) {
1912
+ const tableName = getTableName(table);
1913
+ const columnName = getColumnName(column);
1914
+ const { whereSql, params } = compileWhere(condition);
1915
+ const sql = `SELECT sum(${columnName}) as total FROM ${tableName}${whereSql}`;
1916
+ const result = await executor.get(sql, params);
1917
+ return result.total;
1918
+ }
1919
+ async function avg(executor, table, column, condition) {
1920
+ const tableName = getTableName(table);
1921
+ const columnName = getColumnName(column);
1922
+ const { whereSql, params } = compileWhere(condition);
1923
+ const sql = `SELECT avg(${columnName}) as average FROM ${tableName}${whereSql}`;
1924
+ const result = await executor.get(sql, params);
1925
+ return result.average;
1926
+ }
1927
+ async function min(executor, table, column, condition) {
1928
+ const tableName = getTableName(table);
1929
+ const columnName = getColumnName(column);
1930
+ const { whereSql, params } = compileWhere(condition);
1931
+ const sql = `SELECT min(${columnName}) as minimum FROM ${tableName}${whereSql}`;
1932
+ const result = await executor.get(sql, params);
1933
+ return result.minimum;
1934
+ }
1935
+ async function max(executor, table, column, condition) {
1936
+ const tableName = getTableName(table);
1937
+ const columnName = getColumnName(column);
1938
+ const { whereSql, params } = compileWhere(condition);
1939
+ const sql = `SELECT max(${columnName}) as maximum FROM ${tableName}${whereSql}`;
1940
+ const result = await executor.get(sql, params);
1941
+ return result.maximum;
1942
+ }
1943
+ var init_aggregates = () => {};
1944
+
1945
+ // src/flint.ts
1946
+ function createClient(executor) {
1947
+ return {
1948
+ select: () => new SelectFromBuilder(executor),
1949
+ insert: (table) => new InsertValuesBuilder(executor, table._.name, table),
1950
+ update: (table) => new UpdateSetBuilder(executor, table._.name, table),
1951
+ delete: (table) => new DeleteBuilder(executor, table._.name, table),
1952
+ leftJoin: (parent) => new JoinStage1(executor, parent, parent._.name, "left"),
1953
+ innerJoin: (parent) => new JoinStage1(executor, parent, parent._.name, "inner"),
1954
+ batch: (queries) => {
1955
+ const stmts = queries.map((q) => q.toSQL());
1956
+ return executor.transaction(async () => {
1957
+ for (const stmt of stmts) {
1958
+ await executor.run(stmt.sql, stmt.params);
1959
+ }
1960
+ });
1961
+ },
1962
+ count: (table, condition) => count(executor, table, condition),
1963
+ countColumn: (table, column, condition) => countColumn(executor, table, column, condition),
1964
+ sum: (table, column, condition) => sum(executor, table, column, condition),
1965
+ avg: (table, column, condition) => avg(executor, table, column, condition),
1966
+ min: (table, column, condition) => min(executor, table, column, condition),
1967
+ max: (table, column, condition) => max(executor, table, column, condition),
1968
+ $run(query, ...params) {
1969
+ return executor.run(query, params);
1970
+ },
1971
+ $executor: executor
1972
+ };
1973
+ }
1974
+ function sql(strings, ...values) {
1975
+ let query = "";
1976
+ const params = [];
1977
+ for (let i = 0;i < strings.length; i++) {
1978
+ query += strings[i];
1979
+ if (i < values.length) {
1980
+ query += "?";
1981
+ params.push(values[i]);
1982
+ }
1983
+ }
1984
+ return { sql: query, params };
1985
+ }
1986
+ var init_flint = __esm(() => {
1987
+ init_builder();
1988
+ init_aggregates();
1989
+ });
1990
+
1991
+ // src/drivers/better-sqlite3.ts
1992
+ var exports_better_sqlite3 = {};
1993
+ __export(exports_better_sqlite3, {
1994
+ flint: () => flint,
1995
+ BetterSqlite3Executor: () => BetterSqlite3Executor
1996
+ });
1997
+
1998
+ class BetterSqlite3Executor {
1999
+ #client;
2000
+ constructor(client) {
2001
+ this.#client = client;
2002
+ }
2003
+ all(sql2, params) {
2004
+ return Promise.resolve(this.#client.prepare(sql2).all(...params));
2005
+ }
2006
+ get(sql2, params) {
2007
+ return Promise.resolve(this.#client.prepare(sql2).get(...params));
2008
+ }
2009
+ run(sql2, params) {
2010
+ this.#client.prepare(sql2).run(...params);
2011
+ return Promise.resolve();
2012
+ }
2013
+ transaction(fn) {
2014
+ this.#client.exec("BEGIN");
2015
+ try {
2016
+ const result = fn();
2017
+ if (result instanceof Promise) {
2018
+ return result.then(() => {
2019
+ this.#client.exec("COMMIT");
2020
+ }, (err) => {
2021
+ this.#client.exec("ROLLBACK");
2022
+ throw err;
2023
+ });
2024
+ }
2025
+ this.#client.exec("COMMIT");
2026
+ return Promise.resolve();
2027
+ } catch (err) {
2028
+ this.#client.exec("ROLLBACK");
2029
+ throw err;
2030
+ }
2031
+ }
2032
+ close() {
2033
+ this.#client.close();
2034
+ }
2035
+ }
2036
+ function flint(details) {
2037
+ const client = new import_better_sqlite3.default(details.url);
2038
+ return createClient(new BetterSqlite3Executor(client));
2039
+ }
2040
+ var import_better_sqlite3;
2041
+ var init_better_sqlite3 = __esm(() => {
2042
+ init_flint();
2043
+ import_better_sqlite3 = __toESM(require_lib(), 1);
2044
+ });
2045
+
2046
+ // src/entries/better-sqlite3.ts
2047
+ init_better_sqlite3();
2048
+ export {
2049
+ flint
2050
+ };