jukebox-media-server 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2709 @@
1
+ import { $ as is, A as or, B as SQL, C as ne, D as notIlike, E as notExists, F as isConfig, G as Table, H as fillPlaceholders, I as mapResultRow, J as ViewBaseConfig, K as getTableName, L as mapUpdateSet, M as getTableColumns, N as getTableLikeName, O as notInArray, P as haveSameKeys, Q as entityKind, R as orderSelectedFields, S as lte, T as notBetween, U as sql, V as View, W as Columns, X as WithSubquery, Y as Subquery, Z as Column, _ as inArray, b as like, c as asc, d as between, f as eq, g as ilike, h as gte, j as applyMixins, k as notLike, l as desc, m as gt, n as SQLiteTable, p as exists, q as getTableUniqueName, s as SQLiteColumn, u as and, v as isNotNull, w as not, x as lt, y as isNull, z as Param } from "./indexes-VMR6QVVl.js";
2
+ import Client from "better-sqlite3";
3
+ //#region node_modules/drizzle-orm/alias.js
4
+ var ColumnAliasProxyHandler = class {
5
+ constructor(table) {
6
+ this.table = table;
7
+ }
8
+ static [entityKind] = "ColumnAliasProxyHandler";
9
+ get(columnObj, prop) {
10
+ if (prop === "table") return this.table;
11
+ return columnObj[prop];
12
+ }
13
+ };
14
+ var TableAliasProxyHandler = class {
15
+ constructor(alias, replaceOriginalName) {
16
+ this.alias = alias;
17
+ this.replaceOriginalName = replaceOriginalName;
18
+ }
19
+ static [entityKind] = "TableAliasProxyHandler";
20
+ get(target, prop) {
21
+ if (prop === Table.Symbol.IsAlias) return true;
22
+ if (prop === Table.Symbol.Name) return this.alias;
23
+ if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) return this.alias;
24
+ if (prop === ViewBaseConfig) return {
25
+ ...target[ViewBaseConfig],
26
+ name: this.alias,
27
+ isAlias: true
28
+ };
29
+ if (prop === Table.Symbol.Columns) {
30
+ const columns = target[Table.Symbol.Columns];
31
+ if (!columns) return columns;
32
+ const proxiedColumns = {};
33
+ Object.keys(columns).map((key) => {
34
+ proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
35
+ });
36
+ return proxiedColumns;
37
+ }
38
+ const value = target[prop];
39
+ if (is(value, Column)) return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
40
+ return value;
41
+ }
42
+ };
43
+ function aliasedTable(table, tableAlias) {
44
+ return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
45
+ }
46
+ function aliasedTableColumn(column, tableAlias) {
47
+ return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
48
+ }
49
+ function mapColumnsInAliasedSQLToAlias(query, alias) {
50
+ return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
51
+ }
52
+ function mapColumnsInSQLToAlias(query, alias) {
53
+ return sql.join(query.queryChunks.map((c) => {
54
+ if (is(c, Column)) return aliasedTableColumn(c, alias);
55
+ if (is(c, SQL)) return mapColumnsInSQLToAlias(c, alias);
56
+ if (is(c, SQL.Aliased)) return mapColumnsInAliasedSQLToAlias(c, alias);
57
+ return c;
58
+ }));
59
+ }
60
+ //#endregion
61
+ //#region node_modules/drizzle-orm/errors.js
62
+ var DrizzleError = class extends Error {
63
+ static [entityKind] = "DrizzleError";
64
+ constructor({ message, cause }) {
65
+ super(message);
66
+ this.name = "DrizzleError";
67
+ this.cause = cause;
68
+ }
69
+ };
70
+ var DrizzleQueryError = class DrizzleQueryError extends Error {
71
+ constructor(query, params, cause) {
72
+ super(`Failed query: ${query}
73
+ params: ${params}`);
74
+ this.query = query;
75
+ this.params = params;
76
+ this.cause = cause;
77
+ Error.captureStackTrace(this, DrizzleQueryError);
78
+ if (cause) this.cause = cause;
79
+ }
80
+ };
81
+ var TransactionRollbackError = class extends DrizzleError {
82
+ static [entityKind] = "TransactionRollbackError";
83
+ constructor() {
84
+ super({ message: "Rollback" });
85
+ }
86
+ };
87
+ //#endregion
88
+ //#region node_modules/drizzle-orm/logger.js
89
+ var ConsoleLogWriter = class {
90
+ static [entityKind] = "ConsoleLogWriter";
91
+ write(message) {
92
+ console.log(message);
93
+ }
94
+ };
95
+ var DefaultLogger = class {
96
+ static [entityKind] = "DefaultLogger";
97
+ writer;
98
+ constructor(config) {
99
+ this.writer = config?.writer ?? new ConsoleLogWriter();
100
+ }
101
+ logQuery(query, params) {
102
+ const stringifiedParams = params.map((p) => {
103
+ try {
104
+ return JSON.stringify(p);
105
+ } catch {
106
+ return String(p);
107
+ }
108
+ });
109
+ const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
110
+ this.writer.write(`Query: ${query}${paramsStr}`);
111
+ }
112
+ };
113
+ var NoopLogger = class {
114
+ static [entityKind] = "NoopLogger";
115
+ logQuery() {}
116
+ };
117
+ //#endregion
118
+ //#region node_modules/drizzle-orm/query-promise.js
119
+ var QueryPromise = class {
120
+ static [entityKind] = "QueryPromise";
121
+ [Symbol.toStringTag] = "QueryPromise";
122
+ catch(onRejected) {
123
+ return this.then(void 0, onRejected);
124
+ }
125
+ finally(onFinally) {
126
+ return this.then((value) => {
127
+ onFinally?.();
128
+ return value;
129
+ }, (reason) => {
130
+ onFinally?.();
131
+ throw reason;
132
+ });
133
+ }
134
+ then(onFulfilled, onRejected) {
135
+ return this.execute().then(onFulfilled, onRejected);
136
+ }
137
+ };
138
+ //#endregion
139
+ //#region node_modules/drizzle-orm/pg-core/table.js
140
+ const InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
141
+ const EnableRLS = Symbol.for("drizzle:EnableRLS");
142
+ var PgTable = class extends Table {
143
+ static [entityKind] = "PgTable";
144
+ /** @internal */
145
+ static Symbol = Object.assign({}, Table.Symbol, {
146
+ InlineForeignKeys,
147
+ EnableRLS
148
+ });
149
+ /**@internal */
150
+ [InlineForeignKeys] = [];
151
+ /** @internal */
152
+ [EnableRLS] = false;
153
+ /** @internal */
154
+ [Table.Symbol.ExtraConfigBuilder] = void 0;
155
+ /** @internal */
156
+ [Table.Symbol.ExtraConfigColumns] = {};
157
+ };
158
+ //#endregion
159
+ //#region node_modules/drizzle-orm/pg-core/primary-keys.js
160
+ var PrimaryKeyBuilder = class {
161
+ static [entityKind] = "PgPrimaryKeyBuilder";
162
+ /** @internal */
163
+ columns;
164
+ /** @internal */
165
+ name;
166
+ constructor(columns, name) {
167
+ this.columns = columns;
168
+ this.name = name;
169
+ }
170
+ /** @internal */
171
+ build(table) {
172
+ return new PrimaryKey(table, this.columns, this.name);
173
+ }
174
+ };
175
+ var PrimaryKey = class {
176
+ constructor(table, columns, name) {
177
+ this.table = table;
178
+ this.columns = columns;
179
+ this.name = name;
180
+ }
181
+ static [entityKind] = "PgPrimaryKey";
182
+ columns;
183
+ name;
184
+ getName() {
185
+ return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
186
+ }
187
+ };
188
+ //#endregion
189
+ //#region node_modules/drizzle-orm/relations.js
190
+ var Relation = class {
191
+ constructor(sourceTable, referencedTable, relationName) {
192
+ this.sourceTable = sourceTable;
193
+ this.referencedTable = referencedTable;
194
+ this.relationName = relationName;
195
+ this.referencedTableName = referencedTable[Table.Symbol.Name];
196
+ }
197
+ static [entityKind] = "Relation";
198
+ referencedTableName;
199
+ fieldName;
200
+ };
201
+ var Relations = class {
202
+ constructor(table, config) {
203
+ this.table = table;
204
+ this.config = config;
205
+ }
206
+ static [entityKind] = "Relations";
207
+ };
208
+ var One = class One extends Relation {
209
+ constructor(sourceTable, referencedTable, config, isNullable) {
210
+ super(sourceTable, referencedTable, config?.relationName);
211
+ this.config = config;
212
+ this.isNullable = isNullable;
213
+ }
214
+ static [entityKind] = "One";
215
+ withFieldName(fieldName) {
216
+ const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable);
217
+ relation.fieldName = fieldName;
218
+ return relation;
219
+ }
220
+ };
221
+ var Many = class Many extends Relation {
222
+ constructor(sourceTable, referencedTable, config) {
223
+ super(sourceTable, referencedTable, config?.relationName);
224
+ this.config = config;
225
+ }
226
+ static [entityKind] = "Many";
227
+ withFieldName(fieldName) {
228
+ const relation = new Many(this.sourceTable, this.referencedTable, this.config);
229
+ relation.fieldName = fieldName;
230
+ return relation;
231
+ }
232
+ };
233
+ function getOperators() {
234
+ return {
235
+ and,
236
+ between,
237
+ eq,
238
+ exists,
239
+ gt,
240
+ gte,
241
+ ilike,
242
+ inArray,
243
+ isNull,
244
+ isNotNull,
245
+ like,
246
+ lt,
247
+ lte,
248
+ ne,
249
+ not,
250
+ notBetween,
251
+ notExists,
252
+ notLike,
253
+ notIlike,
254
+ notInArray,
255
+ or,
256
+ sql
257
+ };
258
+ }
259
+ function getOrderByOperators() {
260
+ return {
261
+ sql,
262
+ asc,
263
+ desc
264
+ };
265
+ }
266
+ function extractTablesRelationalConfig(schema, configHelpers) {
267
+ if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) schema = schema["default"];
268
+ const tableNamesMap = {};
269
+ const relationsBuffer = {};
270
+ const tablesConfig = {};
271
+ for (const [key, value] of Object.entries(schema)) if (is(value, Table)) {
272
+ const dbName = getTableUniqueName(value);
273
+ const bufferedRelations = relationsBuffer[dbName];
274
+ tableNamesMap[dbName] = key;
275
+ tablesConfig[key] = {
276
+ tsName: key,
277
+ dbName: value[Table.Symbol.Name],
278
+ schema: value[Table.Symbol.Schema],
279
+ columns: value[Table.Symbol.Columns],
280
+ relations: bufferedRelations?.relations ?? {},
281
+ primaryKey: bufferedRelations?.primaryKey ?? []
282
+ };
283
+ for (const column of Object.values(value[Table.Symbol.Columns])) if (column.primary) tablesConfig[key].primaryKey.push(column);
284
+ const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
285
+ if (extraConfig) {
286
+ for (const configEntry of Object.values(extraConfig)) if (is(configEntry, PrimaryKeyBuilder)) tablesConfig[key].primaryKey.push(...configEntry.columns);
287
+ }
288
+ } else if (is(value, Relations)) {
289
+ const dbName = getTableUniqueName(value.table);
290
+ const tableName = tableNamesMap[dbName];
291
+ const relations2 = value.config(configHelpers(value.table));
292
+ let primaryKey;
293
+ for (const [relationName, relation] of Object.entries(relations2)) if (tableName) {
294
+ const tableConfig = tablesConfig[tableName];
295
+ tableConfig.relations[relationName] = relation;
296
+ } else {
297
+ if (!(dbName in relationsBuffer)) relationsBuffer[dbName] = {
298
+ relations: {},
299
+ primaryKey
300
+ };
301
+ relationsBuffer[dbName].relations[relationName] = relation;
302
+ }
303
+ }
304
+ return {
305
+ tables: tablesConfig,
306
+ tableNamesMap
307
+ };
308
+ }
309
+ function createOne(sourceTable) {
310
+ return function one(table, config) {
311
+ return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false);
312
+ };
313
+ }
314
+ function createMany(sourceTable) {
315
+ return function many(referencedTable, config) {
316
+ return new Many(sourceTable, referencedTable, config);
317
+ };
318
+ }
319
+ function normalizeRelation(schema, tableNamesMap, relation) {
320
+ if (is(relation, One) && relation.config) return {
321
+ fields: relation.config.fields,
322
+ references: relation.config.references
323
+ };
324
+ const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
325
+ if (!referencedTableTsName) throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`);
326
+ const referencedTableConfig = schema[referencedTableTsName];
327
+ if (!referencedTableConfig) throw new Error(`Table "${referencedTableTsName}" not found in schema`);
328
+ const sourceTable = relation.sourceTable;
329
+ const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
330
+ if (!sourceTableTsName) throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`);
331
+ const reverseRelations = [];
332
+ for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) reverseRelations.push(referencedTableRelation);
333
+ if (reverseRelations.length > 1) throw relation.relationName ? /* @__PURE__ */ new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : /* @__PURE__ */ new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
334
+ if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) return {
335
+ fields: reverseRelations[0].config.references,
336
+ references: reverseRelations[0].config.fields
337
+ };
338
+ throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`);
339
+ }
340
+ function createTableRelationsHelpers(sourceTable) {
341
+ return {
342
+ one: createOne(sourceTable),
343
+ many: createMany(sourceTable)
344
+ };
345
+ }
346
+ function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
347
+ const result = {};
348
+ for (const [selectionItemIndex, selectionItem] of buildQueryResultSelection.entries()) if (selectionItem.isJson) {
349
+ const relation = tableConfig.relations[selectionItem.tsKey];
350
+ const rawSubRows = row[selectionItemIndex];
351
+ const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
352
+ result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue));
353
+ } else {
354
+ const value = mapColumnValue(row[selectionItemIndex]);
355
+ const field = selectionItem.field;
356
+ let decoder;
357
+ if (is(field, Column)) decoder = field;
358
+ else if (is(field, SQL)) decoder = field.decoder;
359
+ else decoder = field.sql.decoder;
360
+ result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
361
+ }
362
+ return result;
363
+ }
364
+ //#endregion
365
+ //#region node_modules/drizzle-orm/selection-proxy.js
366
+ var SelectionProxyHandler = class SelectionProxyHandler {
367
+ static [entityKind] = "SelectionProxyHandler";
368
+ config;
369
+ constructor(config) {
370
+ this.config = { ...config };
371
+ }
372
+ get(subquery, prop) {
373
+ if (prop === "_") return {
374
+ ...subquery["_"],
375
+ selectedFields: new Proxy(subquery._.selectedFields, this)
376
+ };
377
+ if (prop === ViewBaseConfig) return {
378
+ ...subquery[ViewBaseConfig],
379
+ selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
380
+ };
381
+ if (typeof prop === "symbol") return subquery[prop];
382
+ const value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];
383
+ if (is(value, SQL.Aliased)) {
384
+ if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) return value.sql;
385
+ const newValue = value.clone();
386
+ newValue.isSelectionField = true;
387
+ return newValue;
388
+ }
389
+ if (is(value, SQL)) {
390
+ if (this.config.sqlBehavior === "sql") return value;
391
+ throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
392
+ }
393
+ if (is(value, Column)) {
394
+ if (this.config.alias) return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
395
+ return value;
396
+ }
397
+ if (typeof value !== "object" || value === null) return value;
398
+ return new Proxy(value, new SelectionProxyHandler(this.config));
399
+ }
400
+ };
401
+ //#endregion
402
+ //#region node_modules/drizzle-orm/sqlite-core/utils.js
403
+ function extractUsedTable(table) {
404
+ if (is(table, SQLiteTable)) return [`${table[Table.Symbol.BaseName]}`];
405
+ if (is(table, Subquery)) return table._.usedTables ?? [];
406
+ if (is(table, SQL)) return table.usedTables ?? [];
407
+ return [];
408
+ }
409
+ //#endregion
410
+ //#region node_modules/drizzle-orm/sqlite-core/query-builders/delete.js
411
+ var SQLiteDeleteBase = class extends QueryPromise {
412
+ constructor(table, session, dialect, withList) {
413
+ super();
414
+ this.table = table;
415
+ this.session = session;
416
+ this.dialect = dialect;
417
+ this.config = {
418
+ table,
419
+ withList
420
+ };
421
+ }
422
+ static [entityKind] = "SQLiteDelete";
423
+ /** @internal */
424
+ config;
425
+ /**
426
+ * Adds a `where` clause to the query.
427
+ *
428
+ * Calling this method will delete only those rows that fulfill a specified condition.
429
+ *
430
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
431
+ *
432
+ * @param where the `where` clause.
433
+ *
434
+ * @example
435
+ * You can use conditional operators and `sql function` to filter the rows to be deleted.
436
+ *
437
+ * ```ts
438
+ * // Delete all cars with green color
439
+ * db.delete(cars).where(eq(cars.color, 'green'));
440
+ * // or
441
+ * db.delete(cars).where(sql`${cars.color} = 'green'`)
442
+ * ```
443
+ *
444
+ * You can logically combine conditional operators with `and()` and `or()` operators:
445
+ *
446
+ * ```ts
447
+ * // Delete all BMW cars with a green color
448
+ * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
449
+ *
450
+ * // Delete all cars with the green or blue color
451
+ * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
452
+ * ```
453
+ */
454
+ where(where) {
455
+ this.config.where = where;
456
+ return this;
457
+ }
458
+ orderBy(...columns) {
459
+ if (typeof columns[0] === "function") {
460
+ const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
461
+ sqlAliasedBehavior: "alias",
462
+ sqlBehavior: "sql"
463
+ })));
464
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
465
+ this.config.orderBy = orderByArray;
466
+ } else {
467
+ const orderByArray = columns;
468
+ this.config.orderBy = orderByArray;
469
+ }
470
+ return this;
471
+ }
472
+ limit(limit) {
473
+ this.config.limit = limit;
474
+ return this;
475
+ }
476
+ returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
477
+ this.config.returning = orderSelectedFields(fields);
478
+ return this;
479
+ }
480
+ /** @internal */
481
+ getSQL() {
482
+ return this.dialect.buildDeleteQuery(this.config);
483
+ }
484
+ toSQL() {
485
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
486
+ return rest;
487
+ }
488
+ /** @internal */
489
+ _prepare(isOneTimeQuery = true) {
490
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, void 0, {
491
+ type: "delete",
492
+ tables: extractUsedTable(this.config.table)
493
+ });
494
+ }
495
+ prepare() {
496
+ return this._prepare(false);
497
+ }
498
+ run = (placeholderValues) => {
499
+ return this._prepare().run(placeholderValues);
500
+ };
501
+ all = (placeholderValues) => {
502
+ return this._prepare().all(placeholderValues);
503
+ };
504
+ get = (placeholderValues) => {
505
+ return this._prepare().get(placeholderValues);
506
+ };
507
+ values = (placeholderValues) => {
508
+ return this._prepare().values(placeholderValues);
509
+ };
510
+ async execute(placeholderValues) {
511
+ return this._prepare().execute(placeholderValues);
512
+ }
513
+ $dynamic() {
514
+ return this;
515
+ }
516
+ };
517
+ //#endregion
518
+ //#region node_modules/drizzle-orm/casing.js
519
+ function toSnakeCase(input) {
520
+ return (input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []).map((word) => word.toLowerCase()).join("_");
521
+ }
522
+ function toCamelCase(input) {
523
+ return (input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []).reduce((acc, word, i) => {
524
+ return acc + (i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`);
525
+ }, "");
526
+ }
527
+ function noopCase(input) {
528
+ return input;
529
+ }
530
+ var CasingCache = class {
531
+ static [entityKind] = "CasingCache";
532
+ /** @internal */
533
+ cache = {};
534
+ cachedTables = {};
535
+ convert;
536
+ constructor(casing) {
537
+ this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
538
+ }
539
+ getColumnCasing(column) {
540
+ if (!column.keyAsName) return column.name;
541
+ const key = `${column.table[Table.Symbol.Schema] ?? "public"}.${column.table[Table.Symbol.OriginalName]}.${column.name}`;
542
+ if (!this.cache[key]) this.cacheTable(column.table);
543
+ return this.cache[key];
544
+ }
545
+ cacheTable(table) {
546
+ const tableKey = `${table[Table.Symbol.Schema] ?? "public"}.${table[Table.Symbol.OriginalName]}`;
547
+ if (!this.cachedTables[tableKey]) {
548
+ for (const column of Object.values(table[Table.Symbol.Columns])) {
549
+ const columnKey = `${tableKey}.${column.name}`;
550
+ this.cache[columnKey] = this.convert(column.name);
551
+ }
552
+ this.cachedTables[tableKey] = true;
553
+ }
554
+ }
555
+ clearCache() {
556
+ this.cache = {};
557
+ this.cachedTables = {};
558
+ }
559
+ };
560
+ //#endregion
561
+ //#region node_modules/drizzle-orm/sqlite-core/view-base.js
562
+ var SQLiteViewBase = class extends View {
563
+ static [entityKind] = "SQLiteViewBase";
564
+ };
565
+ //#endregion
566
+ //#region node_modules/drizzle-orm/sqlite-core/dialect.js
567
+ var SQLiteDialect = class {
568
+ static [entityKind] = "SQLiteDialect";
569
+ /** @internal */
570
+ casing;
571
+ constructor(config) {
572
+ this.casing = new CasingCache(config?.casing);
573
+ }
574
+ escapeName(name) {
575
+ return `"${name}"`;
576
+ }
577
+ escapeParam(_num) {
578
+ return "?";
579
+ }
580
+ escapeString(str) {
581
+ return `'${str.replace(/'/g, "''")}'`;
582
+ }
583
+ buildWithCTE(queries) {
584
+ if (!queries?.length) return void 0;
585
+ const withSqlChunks = [sql`with `];
586
+ for (const [i, w] of queries.entries()) {
587
+ withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
588
+ if (i < queries.length - 1) withSqlChunks.push(sql`, `);
589
+ }
590
+ withSqlChunks.push(sql` `);
591
+ return sql.join(withSqlChunks);
592
+ }
593
+ buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) {
594
+ const withSql = this.buildWithCTE(withList);
595
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
596
+ return sql`${withSql}delete from ${table}${where ? sql` where ${where}` : void 0}${returningSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}`;
597
+ }
598
+ buildUpdateSet(table, set) {
599
+ const tableColumns = table[Table.Symbol.Columns];
600
+ const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0);
601
+ const setSize = columnNames.length;
602
+ return sql.join(columnNames.flatMap((colName, i) => {
603
+ const col = tableColumns[colName];
604
+ const onUpdateFnResult = col.onUpdateFn?.();
605
+ const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));
606
+ const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
607
+ if (i < setSize - 1) return [res, sql.raw(", ")];
608
+ return [res];
609
+ }));
610
+ }
611
+ buildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }) {
612
+ const withSql = this.buildWithCTE(withList);
613
+ const setSql = this.buildUpdateSet(table, set);
614
+ const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
615
+ const joinsSql = this.buildJoins(joins);
616
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
617
+ return sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${where ? sql` where ${where}` : void 0}${returningSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}`;
618
+ }
619
+ /**
620
+ * Builds selection SQL with provided fields/expressions
621
+ *
622
+ * Examples:
623
+ *
624
+ * `select <selection> from`
625
+ *
626
+ * `insert ... returning <selection>`
627
+ *
628
+ * If `isSingleTable` is true, then columns won't be prefixed with table name
629
+ */
630
+ buildSelection(fields, { isSingleTable = false } = {}) {
631
+ const columnsLen = fields.length;
632
+ const chunks = fields.flatMap(({ field }, i) => {
633
+ const chunk = [];
634
+ if (is(field, SQL.Aliased) && field.isSelectionField) chunk.push(sql.identifier(field.fieldAlias));
635
+ else if (is(field, SQL.Aliased) || is(field, SQL)) {
636
+ const query = is(field, SQL.Aliased) ? field.sql : field;
637
+ if (isSingleTable) chunk.push(new SQL(query.queryChunks.map((c) => {
638
+ if (is(c, Column)) return sql.identifier(this.casing.getColumnCasing(c));
639
+ return c;
640
+ })));
641
+ else chunk.push(query);
642
+ if (is(field, SQL.Aliased)) chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
643
+ } else if (is(field, Column)) {
644
+ const tableName = field.table[Table.Symbol.Name];
645
+ if (field.columnType === "SQLiteNumericBigInt") if (isSingleTable) chunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
646
+ else chunk.push(sql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
647
+ else if (isSingleTable) chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
648
+ else chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);
649
+ } else if (is(field, Subquery)) {
650
+ const entries = Object.entries(field._.selectedFields);
651
+ if (entries.length === 1) {
652
+ const entry = entries[0][1];
653
+ const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: (v) => entry.mapFromDriverValue(v) } : entry.sql.decoder;
654
+ if (fieldDecoder) field._.sql.decoder = fieldDecoder;
655
+ }
656
+ chunk.push(field);
657
+ }
658
+ if (i < columnsLen - 1) chunk.push(sql`, `);
659
+ return chunk;
660
+ });
661
+ return sql.join(chunks);
662
+ }
663
+ buildJoins(joins) {
664
+ if (!joins || joins.length === 0) return;
665
+ const joinsArray = [];
666
+ if (joins) for (const [index, joinMeta] of joins.entries()) {
667
+ if (index === 0) joinsArray.push(sql` `);
668
+ const table = joinMeta.table;
669
+ const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
670
+ if (is(table, SQLiteTable)) {
671
+ const tableName = table[SQLiteTable.Symbol.Name];
672
+ const tableSchema = table[SQLiteTable.Symbol.Schema];
673
+ const origTableName = table[SQLiteTable.Symbol.OriginalName];
674
+ const alias = tableName === origTableName ? void 0 : joinMeta.alias;
675
+ joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);
676
+ } else joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`);
677
+ if (index < joins.length - 1) joinsArray.push(sql` `);
678
+ }
679
+ return sql.join(joinsArray);
680
+ }
681
+ buildLimit(limit) {
682
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
683
+ }
684
+ buildOrderBy(orderBy) {
685
+ const orderByList = [];
686
+ if (orderBy) for (const [index, orderByValue] of orderBy.entries()) {
687
+ orderByList.push(orderByValue);
688
+ if (index < orderBy.length - 1) orderByList.push(sql`, `);
689
+ }
690
+ return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
691
+ }
692
+ buildFromTable(table) {
693
+ if (is(table, Table) && table[Table.Symbol.IsAlias]) return sql`${sql`${sql.identifier(table[Table.Symbol.Schema] ?? "")}.`.if(table[Table.Symbol.Schema])}${sql.identifier(table[Table.Symbol.OriginalName])} ${sql.identifier(table[Table.Symbol.Name])}`;
694
+ return table;
695
+ }
696
+ buildSelectQuery({ withList, fields, fieldsFlat, where, having, table, joins, orderBy, groupBy, limit, offset, distinct, setOperators }) {
697
+ const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
698
+ for (const f of fieldsList) if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, SQLiteViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])))(f.field.table)) {
699
+ const tableName = getTableName(f.field.table);
700
+ throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`);
701
+ }
702
+ const isSingleTable = !joins || joins.length === 0;
703
+ const withSql = this.buildWithCTE(withList);
704
+ const distinctSql = distinct ? sql` distinct` : void 0;
705
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
706
+ const tableSql = this.buildFromTable(table);
707
+ const joinsSql = this.buildJoins(joins);
708
+ const whereSql = where ? sql` where ${where}` : void 0;
709
+ const havingSql = having ? sql` having ${having}` : void 0;
710
+ const groupByList = [];
711
+ if (groupBy) for (const [index, groupByValue] of groupBy.entries()) {
712
+ groupByList.push(groupByValue);
713
+ if (index < groupBy.length - 1) groupByList.push(sql`, `);
714
+ }
715
+ const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0}${havingSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}${offset ? sql` offset ${offset}` : void 0}`;
716
+ if (setOperators.length > 0) return this.buildSetOperations(finalQuery, setOperators);
717
+ return finalQuery;
718
+ }
719
+ buildSetOperations(leftSelect, setOperators) {
720
+ const [setOperator, ...rest] = setOperators;
721
+ if (!setOperator) throw new Error("Cannot pass undefined values to any set operator");
722
+ if (rest.length === 0) return this.buildSetOperationQuery({
723
+ leftSelect,
724
+ setOperator
725
+ });
726
+ return this.buildSetOperations(this.buildSetOperationQuery({
727
+ leftSelect,
728
+ setOperator
729
+ }), rest);
730
+ }
731
+ buildSetOperationQuery({ leftSelect, setOperator: { type, isAll, rightSelect, limit, orderBy, offset } }) {
732
+ const leftChunk = sql`${leftSelect.getSQL()} `;
733
+ const rightChunk = sql`${rightSelect.getSQL()}`;
734
+ let orderBySql;
735
+ if (orderBy && orderBy.length > 0) {
736
+ const orderByValues = [];
737
+ for (const singleOrderBy of orderBy) if (is(singleOrderBy, SQLiteColumn)) orderByValues.push(sql.identifier(singleOrderBy.name));
738
+ else if (is(singleOrderBy, SQL)) {
739
+ for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
740
+ const chunk = singleOrderBy.queryChunks[i];
741
+ if (is(chunk, SQLiteColumn)) singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
742
+ }
743
+ orderByValues.push(sql`${singleOrderBy}`);
744
+ } else orderByValues.push(sql`${singleOrderBy}`);
745
+ orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
746
+ }
747
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
748
+ const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
749
+ const offsetSql = offset ? sql` offset ${offset}` : void 0;
750
+ return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
751
+ }
752
+ buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select }) {
753
+ const valuesSqlList = [];
754
+ const columns = table[Table.Symbol.Columns];
755
+ const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
756
+ const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));
757
+ if (select) {
758
+ const select2 = valuesOrSelect;
759
+ if (is(select2, SQL)) valuesSqlList.push(select2);
760
+ else valuesSqlList.push(select2.getSQL());
761
+ } else {
762
+ const values = valuesOrSelect;
763
+ valuesSqlList.push(sql.raw("values "));
764
+ for (const [valueIndex, value] of values.entries()) {
765
+ const valueList = [];
766
+ for (const [fieldName, col] of colEntries) {
767
+ const colValue = value[fieldName];
768
+ if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
769
+ let defaultValue;
770
+ if (col.default !== null && col.default !== void 0) defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
771
+ else if (col.defaultFn !== void 0) {
772
+ const defaultFnResult = col.defaultFn();
773
+ defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
774
+ } else if (!col.default && col.onUpdateFn !== void 0) {
775
+ const onUpdateFnResult = col.onUpdateFn();
776
+ defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
777
+ } else defaultValue = sql`null`;
778
+ valueList.push(defaultValue);
779
+ } else valueList.push(colValue);
780
+ }
781
+ valuesSqlList.push(valueList);
782
+ if (valueIndex < values.length - 1) valuesSqlList.push(sql`, `);
783
+ }
784
+ }
785
+ const withSql = this.buildWithCTE(withList);
786
+ const valuesSql = sql.join(valuesSqlList);
787
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
788
+ return sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflict?.length ? sql.join(onConflict) : void 0}${returningSql}`;
789
+ }
790
+ sqlToQuery(sql2, invokeSource) {
791
+ return sql2.toQuery({
792
+ casing: this.casing,
793
+ escapeName: this.escapeName,
794
+ escapeParam: this.escapeParam,
795
+ escapeString: this.escapeString,
796
+ invokeSource
797
+ });
798
+ }
799
+ buildRelationalQuery({ fullSchema, schema, tableNamesMap, table, tableConfig, queryConfig: config, tableAlias, nestedQueryRelation, joinOn }) {
800
+ let selection = [];
801
+ let limit, offset, orderBy = [], where;
802
+ const joins = [];
803
+ if (config === true) selection = Object.entries(tableConfig.columns).map(([key, value]) => ({
804
+ dbKey: value.name,
805
+ tsKey: key,
806
+ field: aliasedTableColumn(value, tableAlias),
807
+ relationTableTsKey: void 0,
808
+ isJson: false,
809
+ selection: []
810
+ }));
811
+ else {
812
+ const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
813
+ if (config.where) {
814
+ const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
815
+ where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
816
+ }
817
+ const fieldsSelection = [];
818
+ let selectedColumns = [];
819
+ if (config.columns) {
820
+ let isIncludeMode = false;
821
+ for (const [field, value] of Object.entries(config.columns)) {
822
+ if (value === void 0) continue;
823
+ if (field in tableConfig.columns) {
824
+ if (!isIncludeMode && value === true) isIncludeMode = true;
825
+ selectedColumns.push(field);
826
+ }
827
+ }
828
+ if (selectedColumns.length > 0) selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
829
+ } else selectedColumns = Object.keys(tableConfig.columns);
830
+ for (const field of selectedColumns) {
831
+ const column = tableConfig.columns[field];
832
+ fieldsSelection.push({
833
+ tsKey: field,
834
+ value: column
835
+ });
836
+ }
837
+ let selectedRelations = [];
838
+ if (config.with) selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({
839
+ tsKey,
840
+ queryConfig,
841
+ relation: tableConfig.relations[tsKey]
842
+ }));
843
+ let extras;
844
+ if (config.extras) {
845
+ extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
846
+ for (const [tsKey, value] of Object.entries(extras)) fieldsSelection.push({
847
+ tsKey,
848
+ value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
849
+ });
850
+ }
851
+ for (const { tsKey, value } of fieldsSelection) selection.push({
852
+ dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
853
+ tsKey,
854
+ field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
855
+ relationTableTsKey: void 0,
856
+ isJson: false,
857
+ selection: []
858
+ });
859
+ let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
860
+ if (!Array.isArray(orderByOrig)) orderByOrig = [orderByOrig];
861
+ orderBy = orderByOrig.map((orderByValue) => {
862
+ if (is(orderByValue, Column)) return aliasedTableColumn(orderByValue, tableAlias);
863
+ return mapColumnsInSQLToAlias(orderByValue, tableAlias);
864
+ });
865
+ limit = config.limit;
866
+ offset = config.offset;
867
+ for (const { tsKey: selectedRelationTsKey, queryConfig: selectedRelationConfigValue, relation } of selectedRelations) {
868
+ const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
869
+ const relationTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
870
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
871
+ const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias))));
872
+ const builtRelation = this.buildRelationalQuery({
873
+ fullSchema,
874
+ schema,
875
+ tableNamesMap,
876
+ table: fullSchema[relationTableTsName],
877
+ tableConfig: schema[relationTableTsName],
878
+ queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : {
879
+ ...selectedRelationConfigValue,
880
+ limit: 1
881
+ } : selectedRelationConfigValue,
882
+ tableAlias: relationTableAlias,
883
+ joinOn: joinOn2,
884
+ nestedQueryRelation: relation
885
+ });
886
+ const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
887
+ selection.push({
888
+ dbKey: selectedRelationTsKey,
889
+ tsKey: selectedRelationTsKey,
890
+ field,
891
+ relationTableTsKey: relationTableTsName,
892
+ isJson: true,
893
+ selection: builtRelation.selection
894
+ });
895
+ }
896
+ }
897
+ if (selection.length === 0) throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.` });
898
+ let result;
899
+ where = and(joinOn, where);
900
+ if (nestedQueryRelation) {
901
+ let field = sql`json_array(${sql.join(selection.map(({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`;
902
+ if (is(nestedQueryRelation, Many)) field = sql`coalesce(json_group_array(${field}), json_array())`;
903
+ const nestedSelection = [{
904
+ dbKey: "data",
905
+ tsKey: "data",
906
+ field: field.as("data"),
907
+ isJson: true,
908
+ relationTableTsKey: tableConfig.tsName,
909
+ selection
910
+ }];
911
+ if (limit !== void 0 || offset !== void 0 || orderBy.length > 0) {
912
+ result = this.buildSelectQuery({
913
+ table: aliasedTable(table, tableAlias),
914
+ fields: {},
915
+ fieldsFlat: [{
916
+ path: [],
917
+ field: sql.raw("*")
918
+ }],
919
+ where,
920
+ limit,
921
+ offset,
922
+ orderBy,
923
+ setOperators: []
924
+ });
925
+ where = void 0;
926
+ limit = void 0;
927
+ offset = void 0;
928
+ orderBy = void 0;
929
+ } else result = aliasedTable(table, tableAlias);
930
+ result = this.buildSelectQuery({
931
+ table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),
932
+ fields: {},
933
+ fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
934
+ path: [],
935
+ field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
936
+ })),
937
+ joins,
938
+ where,
939
+ limit,
940
+ offset,
941
+ orderBy,
942
+ setOperators: []
943
+ });
944
+ } else result = this.buildSelectQuery({
945
+ table: aliasedTable(table, tableAlias),
946
+ fields: {},
947
+ fieldsFlat: selection.map(({ field }) => ({
948
+ path: [],
949
+ field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
950
+ })),
951
+ joins,
952
+ where,
953
+ limit,
954
+ offset,
955
+ orderBy,
956
+ setOperators: []
957
+ });
958
+ return {
959
+ tableTsKey: tableConfig.tsName,
960
+ sql: result,
961
+ selection
962
+ };
963
+ }
964
+ };
965
+ var SQLiteSyncDialect = class extends SQLiteDialect {
966
+ static [entityKind] = "SQLiteSyncDialect";
967
+ migrate(migrations, session, config) {
968
+ const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
969
+ const migrationTableCreate = sql`
970
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
971
+ id SERIAL PRIMARY KEY,
972
+ hash text NOT NULL,
973
+ created_at numeric
974
+ )
975
+ `;
976
+ session.run(migrationTableCreate);
977
+ const lastDbMigration = session.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`)[0] ?? void 0;
978
+ session.run(sql`BEGIN`);
979
+ try {
980
+ for (const migration of migrations) if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
981
+ for (const stmt of migration.sql) session.run(sql.raw(stmt));
982
+ session.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
983
+ }
984
+ session.run(sql`COMMIT`);
985
+ } catch (e) {
986
+ session.run(sql`ROLLBACK`);
987
+ throw e;
988
+ }
989
+ }
990
+ };
991
+ //#endregion
992
+ //#region node_modules/drizzle-orm/query-builders/query-builder.js
993
+ var TypedQueryBuilder = class {
994
+ static [entityKind] = "TypedQueryBuilder";
995
+ /** @internal */
996
+ getSelectedFields() {
997
+ return this._.selectedFields;
998
+ }
999
+ };
1000
+ //#endregion
1001
+ //#region node_modules/drizzle-orm/sqlite-core/query-builders/select.js
1002
+ var SQLiteSelectBuilder = class {
1003
+ static [entityKind] = "SQLiteSelectBuilder";
1004
+ fields;
1005
+ session;
1006
+ dialect;
1007
+ withList;
1008
+ distinct;
1009
+ constructor(config) {
1010
+ this.fields = config.fields;
1011
+ this.session = config.session;
1012
+ this.dialect = config.dialect;
1013
+ this.withList = config.withList;
1014
+ this.distinct = config.distinct;
1015
+ }
1016
+ from(source) {
1017
+ const isPartialSelect = !!this.fields;
1018
+ let fields;
1019
+ if (this.fields) fields = this.fields;
1020
+ else if (is(source, Subquery)) fields = Object.fromEntries(Object.keys(source._.selectedFields).map((key) => [key, source[key]]));
1021
+ else if (is(source, SQLiteViewBase)) fields = source[ViewBaseConfig].selectedFields;
1022
+ else if (is(source, SQL)) fields = {};
1023
+ else fields = getTableColumns(source);
1024
+ return new SQLiteSelectBase({
1025
+ table: source,
1026
+ fields,
1027
+ isPartialSelect,
1028
+ session: this.session,
1029
+ dialect: this.dialect,
1030
+ withList: this.withList,
1031
+ distinct: this.distinct
1032
+ });
1033
+ }
1034
+ };
1035
+ var SQLiteSelectQueryBuilderBase = class extends TypedQueryBuilder {
1036
+ static [entityKind] = "SQLiteSelectQueryBuilder";
1037
+ _;
1038
+ /** @internal */
1039
+ config;
1040
+ joinsNotNullableMap;
1041
+ tableName;
1042
+ isPartialSelect;
1043
+ session;
1044
+ dialect;
1045
+ cacheConfig = void 0;
1046
+ usedTables = /* @__PURE__ */ new Set();
1047
+ constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
1048
+ super();
1049
+ this.config = {
1050
+ withList,
1051
+ table,
1052
+ fields: { ...fields },
1053
+ distinct,
1054
+ setOperators: []
1055
+ };
1056
+ this.isPartialSelect = isPartialSelect;
1057
+ this.session = session;
1058
+ this.dialect = dialect;
1059
+ this._ = {
1060
+ selectedFields: fields,
1061
+ config: this.config
1062
+ };
1063
+ this.tableName = getTableLikeName(table);
1064
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
1065
+ for (const item of extractUsedTable(table)) this.usedTables.add(item);
1066
+ }
1067
+ /** @internal */
1068
+ getUsedTables() {
1069
+ return [...this.usedTables];
1070
+ }
1071
+ createJoin(joinType) {
1072
+ return (table, on) => {
1073
+ const baseTableName = this.tableName;
1074
+ const tableName = getTableLikeName(table);
1075
+ for (const item of extractUsedTable(table)) this.usedTables.add(item);
1076
+ if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
1077
+ if (!this.isPartialSelect) {
1078
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
1079
+ if (typeof tableName === "string" && !is(table, SQL)) {
1080
+ const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
1081
+ this.config.fields[tableName] = selection;
1082
+ }
1083
+ }
1084
+ if (typeof on === "function") on = on(new Proxy(this.config.fields, new SelectionProxyHandler({
1085
+ sqlAliasedBehavior: "sql",
1086
+ sqlBehavior: "sql"
1087
+ })));
1088
+ if (!this.config.joins) this.config.joins = [];
1089
+ this.config.joins.push({
1090
+ on,
1091
+ table,
1092
+ joinType,
1093
+ alias: tableName
1094
+ });
1095
+ if (typeof tableName === "string") switch (joinType) {
1096
+ case "left":
1097
+ this.joinsNotNullableMap[tableName] = false;
1098
+ break;
1099
+ case "right":
1100
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
1101
+ this.joinsNotNullableMap[tableName] = true;
1102
+ break;
1103
+ case "cross":
1104
+ case "inner":
1105
+ this.joinsNotNullableMap[tableName] = true;
1106
+ break;
1107
+ case "full":
1108
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
1109
+ this.joinsNotNullableMap[tableName] = false;
1110
+ break;
1111
+ }
1112
+ return this;
1113
+ };
1114
+ }
1115
+ /**
1116
+ * Executes a `left join` operation by adding another table to the current query.
1117
+ *
1118
+ * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
1119
+ *
1120
+ * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
1121
+ *
1122
+ * @param table the table to join.
1123
+ * @param on the `on` clause.
1124
+ *
1125
+ * @example
1126
+ *
1127
+ * ```ts
1128
+ * // Select all users and their pets
1129
+ * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
1130
+ * .from(users)
1131
+ * .leftJoin(pets, eq(users.id, pets.ownerId))
1132
+ *
1133
+ * // Select userId and petId
1134
+ * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
1135
+ * userId: users.id,
1136
+ * petId: pets.id,
1137
+ * })
1138
+ * .from(users)
1139
+ * .leftJoin(pets, eq(users.id, pets.ownerId))
1140
+ * ```
1141
+ */
1142
+ leftJoin = this.createJoin("left");
1143
+ /**
1144
+ * Executes a `right join` operation by adding another table to the current query.
1145
+ *
1146
+ * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
1147
+ *
1148
+ * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
1149
+ *
1150
+ * @param table the table to join.
1151
+ * @param on the `on` clause.
1152
+ *
1153
+ * @example
1154
+ *
1155
+ * ```ts
1156
+ * // Select all users and their pets
1157
+ * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
1158
+ * .from(users)
1159
+ * .rightJoin(pets, eq(users.id, pets.ownerId))
1160
+ *
1161
+ * // Select userId and petId
1162
+ * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
1163
+ * userId: users.id,
1164
+ * petId: pets.id,
1165
+ * })
1166
+ * .from(users)
1167
+ * .rightJoin(pets, eq(users.id, pets.ownerId))
1168
+ * ```
1169
+ */
1170
+ rightJoin = this.createJoin("right");
1171
+ /**
1172
+ * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
1173
+ *
1174
+ * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
1175
+ *
1176
+ * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
1177
+ *
1178
+ * @param table the table to join.
1179
+ * @param on the `on` clause.
1180
+ *
1181
+ * @example
1182
+ *
1183
+ * ```ts
1184
+ * // Select all users and their pets
1185
+ * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
1186
+ * .from(users)
1187
+ * .innerJoin(pets, eq(users.id, pets.ownerId))
1188
+ *
1189
+ * // Select userId and petId
1190
+ * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
1191
+ * userId: users.id,
1192
+ * petId: pets.id,
1193
+ * })
1194
+ * .from(users)
1195
+ * .innerJoin(pets, eq(users.id, pets.ownerId))
1196
+ * ```
1197
+ */
1198
+ innerJoin = this.createJoin("inner");
1199
+ /**
1200
+ * Executes a `full join` operation by combining rows from two tables into a new table.
1201
+ *
1202
+ * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
1203
+ *
1204
+ * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
1205
+ *
1206
+ * @param table the table to join.
1207
+ * @param on the `on` clause.
1208
+ *
1209
+ * @example
1210
+ *
1211
+ * ```ts
1212
+ * // Select all users and their pets
1213
+ * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
1214
+ * .from(users)
1215
+ * .fullJoin(pets, eq(users.id, pets.ownerId))
1216
+ *
1217
+ * // Select userId and petId
1218
+ * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
1219
+ * userId: users.id,
1220
+ * petId: pets.id,
1221
+ * })
1222
+ * .from(users)
1223
+ * .fullJoin(pets, eq(users.id, pets.ownerId))
1224
+ * ```
1225
+ */
1226
+ fullJoin = this.createJoin("full");
1227
+ /**
1228
+ * Executes a `cross join` operation by combining rows from two tables into a new table.
1229
+ *
1230
+ * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
1231
+ *
1232
+ * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
1233
+ *
1234
+ * @param table the table to join.
1235
+ *
1236
+ * @example
1237
+ *
1238
+ * ```ts
1239
+ * // Select all users, each user with every pet
1240
+ * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
1241
+ * .from(users)
1242
+ * .crossJoin(pets)
1243
+ *
1244
+ * // Select userId and petId
1245
+ * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
1246
+ * userId: users.id,
1247
+ * petId: pets.id,
1248
+ * })
1249
+ * .from(users)
1250
+ * .crossJoin(pets)
1251
+ * ```
1252
+ */
1253
+ crossJoin = this.createJoin("cross");
1254
+ createSetOperator(type, isAll) {
1255
+ return (rightSelection) => {
1256
+ const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
1257
+ if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
1258
+ this.config.setOperators.push({
1259
+ type,
1260
+ isAll,
1261
+ rightSelect
1262
+ });
1263
+ return this;
1264
+ };
1265
+ }
1266
+ /**
1267
+ * Adds `union` set operator to the query.
1268
+ *
1269
+ * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
1270
+ *
1271
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
1272
+ *
1273
+ * @example
1274
+ *
1275
+ * ```ts
1276
+ * // Select all unique names from customers and users tables
1277
+ * await db.select({ name: users.name })
1278
+ * .from(users)
1279
+ * .union(
1280
+ * db.select({ name: customers.name }).from(customers)
1281
+ * );
1282
+ * // or
1283
+ * import { union } from 'drizzle-orm/sqlite-core'
1284
+ *
1285
+ * await union(
1286
+ * db.select({ name: users.name }).from(users),
1287
+ * db.select({ name: customers.name }).from(customers)
1288
+ * );
1289
+ * ```
1290
+ */
1291
+ union = this.createSetOperator("union", false);
1292
+ /**
1293
+ * Adds `union all` set operator to the query.
1294
+ *
1295
+ * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
1296
+ *
1297
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
1298
+ *
1299
+ * @example
1300
+ *
1301
+ * ```ts
1302
+ * // Select all transaction ids from both online and in-store sales
1303
+ * await db.select({ transaction: onlineSales.transactionId })
1304
+ * .from(onlineSales)
1305
+ * .unionAll(
1306
+ * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
1307
+ * );
1308
+ * // or
1309
+ * import { unionAll } from 'drizzle-orm/sqlite-core'
1310
+ *
1311
+ * await unionAll(
1312
+ * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
1313
+ * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
1314
+ * );
1315
+ * ```
1316
+ */
1317
+ unionAll = this.createSetOperator("union", true);
1318
+ /**
1319
+ * Adds `intersect` set operator to the query.
1320
+ *
1321
+ * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
1322
+ *
1323
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
1324
+ *
1325
+ * @example
1326
+ *
1327
+ * ```ts
1328
+ * // Select course names that are offered in both departments A and B
1329
+ * await db.select({ courseName: depA.courseName })
1330
+ * .from(depA)
1331
+ * .intersect(
1332
+ * db.select({ courseName: depB.courseName }).from(depB)
1333
+ * );
1334
+ * // or
1335
+ * import { intersect } from 'drizzle-orm/sqlite-core'
1336
+ *
1337
+ * await intersect(
1338
+ * db.select({ courseName: depA.courseName }).from(depA),
1339
+ * db.select({ courseName: depB.courseName }).from(depB)
1340
+ * );
1341
+ * ```
1342
+ */
1343
+ intersect = this.createSetOperator("intersect", false);
1344
+ /**
1345
+ * Adds `except` set operator to the query.
1346
+ *
1347
+ * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
1348
+ *
1349
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
1350
+ *
1351
+ * @example
1352
+ *
1353
+ * ```ts
1354
+ * // Select all courses offered in department A but not in department B
1355
+ * await db.select({ courseName: depA.courseName })
1356
+ * .from(depA)
1357
+ * .except(
1358
+ * db.select({ courseName: depB.courseName }).from(depB)
1359
+ * );
1360
+ * // or
1361
+ * import { except } from 'drizzle-orm/sqlite-core'
1362
+ *
1363
+ * await except(
1364
+ * db.select({ courseName: depA.courseName }).from(depA),
1365
+ * db.select({ courseName: depB.courseName }).from(depB)
1366
+ * );
1367
+ * ```
1368
+ */
1369
+ except = this.createSetOperator("except", false);
1370
+ /** @internal */
1371
+ addSetOperators(setOperators) {
1372
+ this.config.setOperators.push(...setOperators);
1373
+ return this;
1374
+ }
1375
+ /**
1376
+ * Adds a `where` clause to the query.
1377
+ *
1378
+ * Calling this method will select only those rows that fulfill a specified condition.
1379
+ *
1380
+ * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
1381
+ *
1382
+ * @param where the `where` clause.
1383
+ *
1384
+ * @example
1385
+ * You can use conditional operators and `sql function` to filter the rows to be selected.
1386
+ *
1387
+ * ```ts
1388
+ * // Select all cars with green color
1389
+ * await db.select().from(cars).where(eq(cars.color, 'green'));
1390
+ * // or
1391
+ * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
1392
+ * ```
1393
+ *
1394
+ * You can logically combine conditional operators with `and()` and `or()` operators:
1395
+ *
1396
+ * ```ts
1397
+ * // Select all BMW cars with a green color
1398
+ * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
1399
+ *
1400
+ * // Select all cars with the green or blue color
1401
+ * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
1402
+ * ```
1403
+ */
1404
+ where(where) {
1405
+ if (typeof where === "function") where = where(new Proxy(this.config.fields, new SelectionProxyHandler({
1406
+ sqlAliasedBehavior: "sql",
1407
+ sqlBehavior: "sql"
1408
+ })));
1409
+ this.config.where = where;
1410
+ return this;
1411
+ }
1412
+ /**
1413
+ * Adds a `having` clause to the query.
1414
+ *
1415
+ * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
1416
+ *
1417
+ * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
1418
+ *
1419
+ * @param having the `having` clause.
1420
+ *
1421
+ * @example
1422
+ *
1423
+ * ```ts
1424
+ * // Select all brands with more than one car
1425
+ * await db.select({
1426
+ * brand: cars.brand,
1427
+ * count: sql<number>`cast(count(${cars.id}) as int)`,
1428
+ * })
1429
+ * .from(cars)
1430
+ * .groupBy(cars.brand)
1431
+ * .having(({ count }) => gt(count, 1));
1432
+ * ```
1433
+ */
1434
+ having(having) {
1435
+ if (typeof having === "function") having = having(new Proxy(this.config.fields, new SelectionProxyHandler({
1436
+ sqlAliasedBehavior: "sql",
1437
+ sqlBehavior: "sql"
1438
+ })));
1439
+ this.config.having = having;
1440
+ return this;
1441
+ }
1442
+ groupBy(...columns) {
1443
+ if (typeof columns[0] === "function") {
1444
+ const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({
1445
+ sqlAliasedBehavior: "alias",
1446
+ sqlBehavior: "sql"
1447
+ })));
1448
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
1449
+ } else this.config.groupBy = columns;
1450
+ return this;
1451
+ }
1452
+ orderBy(...columns) {
1453
+ if (typeof columns[0] === "function") {
1454
+ const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({
1455
+ sqlAliasedBehavior: "alias",
1456
+ sqlBehavior: "sql"
1457
+ })));
1458
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
1459
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;
1460
+ else this.config.orderBy = orderByArray;
1461
+ } else {
1462
+ const orderByArray = columns;
1463
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;
1464
+ else this.config.orderBy = orderByArray;
1465
+ }
1466
+ return this;
1467
+ }
1468
+ /**
1469
+ * Adds a `limit` clause to the query.
1470
+ *
1471
+ * Calling this method will set the maximum number of rows that will be returned by this query.
1472
+ *
1473
+ * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
1474
+ *
1475
+ * @param limit the `limit` clause.
1476
+ *
1477
+ * @example
1478
+ *
1479
+ * ```ts
1480
+ * // Get the first 10 people from this query.
1481
+ * await db.select().from(people).limit(10);
1482
+ * ```
1483
+ */
1484
+ limit(limit) {
1485
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).limit = limit;
1486
+ else this.config.limit = limit;
1487
+ return this;
1488
+ }
1489
+ /**
1490
+ * Adds an `offset` clause to the query.
1491
+ *
1492
+ * Calling this method will skip a number of rows when returning results from this query.
1493
+ *
1494
+ * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
1495
+ *
1496
+ * @param offset the `offset` clause.
1497
+ *
1498
+ * @example
1499
+ *
1500
+ * ```ts
1501
+ * // Get the 10th-20th people from this query.
1502
+ * await db.select().from(people).offset(10).limit(10);
1503
+ * ```
1504
+ */
1505
+ offset(offset) {
1506
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).offset = offset;
1507
+ else this.config.offset = offset;
1508
+ return this;
1509
+ }
1510
+ /** @internal */
1511
+ getSQL() {
1512
+ return this.dialect.buildSelectQuery(this.config);
1513
+ }
1514
+ toSQL() {
1515
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
1516
+ return rest;
1517
+ }
1518
+ as(alias) {
1519
+ const usedTables = [];
1520
+ usedTables.push(...extractUsedTable(this.config.table));
1521
+ if (this.config.joins) for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
1522
+ return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), new SelectionProxyHandler({
1523
+ alias,
1524
+ sqlAliasedBehavior: "alias",
1525
+ sqlBehavior: "error"
1526
+ }));
1527
+ }
1528
+ /** @internal */
1529
+ getSelectedFields() {
1530
+ return new Proxy(this.config.fields, new SelectionProxyHandler({
1531
+ alias: this.tableName,
1532
+ sqlAliasedBehavior: "alias",
1533
+ sqlBehavior: "error"
1534
+ }));
1535
+ }
1536
+ $dynamic() {
1537
+ return this;
1538
+ }
1539
+ };
1540
+ var SQLiteSelectBase = class extends SQLiteSelectQueryBuilderBase {
1541
+ static [entityKind] = "SQLiteSelect";
1542
+ /** @internal */
1543
+ _prepare(isOneTimeQuery = true) {
1544
+ if (!this.session) throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
1545
+ const fieldsList = orderSelectedFields(this.config.fields);
1546
+ const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), fieldsList, "all", true, void 0, {
1547
+ type: "select",
1548
+ tables: [...this.usedTables]
1549
+ }, this.cacheConfig);
1550
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
1551
+ return query;
1552
+ }
1553
+ $withCache(config) {
1554
+ this.cacheConfig = config === void 0 ? {
1555
+ config: {},
1556
+ enable: true,
1557
+ autoInvalidate: true
1558
+ } : config === false ? { enable: false } : {
1559
+ enable: true,
1560
+ autoInvalidate: true,
1561
+ ...config
1562
+ };
1563
+ return this;
1564
+ }
1565
+ prepare() {
1566
+ return this._prepare(false);
1567
+ }
1568
+ run = (placeholderValues) => {
1569
+ return this._prepare().run(placeholderValues);
1570
+ };
1571
+ all = (placeholderValues) => {
1572
+ return this._prepare().all(placeholderValues);
1573
+ };
1574
+ get = (placeholderValues) => {
1575
+ return this._prepare().get(placeholderValues);
1576
+ };
1577
+ values = (placeholderValues) => {
1578
+ return this._prepare().values(placeholderValues);
1579
+ };
1580
+ async execute() {
1581
+ return this.all();
1582
+ }
1583
+ };
1584
+ applyMixins(SQLiteSelectBase, [QueryPromise]);
1585
+ function createSetOperator(type, isAll) {
1586
+ return (leftSelect, rightSelect, ...restSelects) => {
1587
+ const setOperators = [rightSelect, ...restSelects].map((select) => ({
1588
+ type,
1589
+ isAll,
1590
+ rightSelect: select
1591
+ }));
1592
+ for (const setOperator of setOperators) if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
1593
+ return leftSelect.addSetOperators(setOperators);
1594
+ };
1595
+ }
1596
+ const getSQLiteSetOperators = () => ({
1597
+ union,
1598
+ unionAll,
1599
+ intersect,
1600
+ except
1601
+ });
1602
+ const union = createSetOperator("union", false);
1603
+ const unionAll = createSetOperator("union", true);
1604
+ const intersect = createSetOperator("intersect", false);
1605
+ const except = createSetOperator("except", false);
1606
+ //#endregion
1607
+ //#region node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js
1608
+ var QueryBuilder = class {
1609
+ static [entityKind] = "SQLiteQueryBuilder";
1610
+ dialect;
1611
+ dialectConfig;
1612
+ constructor(dialect) {
1613
+ this.dialect = is(dialect, SQLiteDialect) ? dialect : void 0;
1614
+ this.dialectConfig = is(dialect, SQLiteDialect) ? void 0 : dialect;
1615
+ }
1616
+ $with = (alias, selection) => {
1617
+ const queryBuilder = this;
1618
+ const as = (qb) => {
1619
+ if (typeof qb === "function") qb = qb(queryBuilder);
1620
+ return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({
1621
+ alias,
1622
+ sqlAliasedBehavior: "alias",
1623
+ sqlBehavior: "error"
1624
+ }));
1625
+ };
1626
+ return { as };
1627
+ };
1628
+ with(...queries) {
1629
+ const self = this;
1630
+ function select(fields) {
1631
+ return new SQLiteSelectBuilder({
1632
+ fields: fields ?? void 0,
1633
+ session: void 0,
1634
+ dialect: self.getDialect(),
1635
+ withList: queries
1636
+ });
1637
+ }
1638
+ function selectDistinct(fields) {
1639
+ return new SQLiteSelectBuilder({
1640
+ fields: fields ?? void 0,
1641
+ session: void 0,
1642
+ dialect: self.getDialect(),
1643
+ withList: queries,
1644
+ distinct: true
1645
+ });
1646
+ }
1647
+ return {
1648
+ select,
1649
+ selectDistinct
1650
+ };
1651
+ }
1652
+ select(fields) {
1653
+ return new SQLiteSelectBuilder({
1654
+ fields: fields ?? void 0,
1655
+ session: void 0,
1656
+ dialect: this.getDialect()
1657
+ });
1658
+ }
1659
+ selectDistinct(fields) {
1660
+ return new SQLiteSelectBuilder({
1661
+ fields: fields ?? void 0,
1662
+ session: void 0,
1663
+ dialect: this.getDialect(),
1664
+ distinct: true
1665
+ });
1666
+ }
1667
+ getDialect() {
1668
+ if (!this.dialect) this.dialect = new SQLiteSyncDialect(this.dialectConfig);
1669
+ return this.dialect;
1670
+ }
1671
+ };
1672
+ //#endregion
1673
+ //#region node_modules/drizzle-orm/sqlite-core/query-builders/insert.js
1674
+ var SQLiteInsertBuilder = class {
1675
+ constructor(table, session, dialect, withList) {
1676
+ this.table = table;
1677
+ this.session = session;
1678
+ this.dialect = dialect;
1679
+ this.withList = withList;
1680
+ }
1681
+ static [entityKind] = "SQLiteInsertBuilder";
1682
+ values(values) {
1683
+ values = Array.isArray(values) ? values : [values];
1684
+ if (values.length === 0) throw new Error("values() must be called with at least one value");
1685
+ const mappedValues = values.map((entry) => {
1686
+ const result = {};
1687
+ const cols = this.table[Table.Symbol.Columns];
1688
+ for (const colKey of Object.keys(entry)) {
1689
+ const colValue = entry[colKey];
1690
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
1691
+ }
1692
+ return result;
1693
+ });
1694
+ return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
1695
+ }
1696
+ select(selectQuery) {
1697
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
1698
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");
1699
+ return new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
1700
+ }
1701
+ };
1702
+ var SQLiteInsertBase = class extends QueryPromise {
1703
+ constructor(table, values, session, dialect, withList, select) {
1704
+ super();
1705
+ this.session = session;
1706
+ this.dialect = dialect;
1707
+ this.config = {
1708
+ table,
1709
+ values,
1710
+ withList,
1711
+ select
1712
+ };
1713
+ }
1714
+ static [entityKind] = "SQLiteInsert";
1715
+ /** @internal */
1716
+ config;
1717
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
1718
+ this.config.returning = orderSelectedFields(fields);
1719
+ return this;
1720
+ }
1721
+ /**
1722
+ * Adds an `on conflict do nothing` clause to the query.
1723
+ *
1724
+ * Calling this method simply avoids inserting a row as its alternative action.
1725
+ *
1726
+ * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
1727
+ *
1728
+ * @param config The `target` and `where` clauses.
1729
+ *
1730
+ * @example
1731
+ * ```ts
1732
+ * // Insert one row and cancel the insert if there's a conflict
1733
+ * await db.insert(cars)
1734
+ * .values({ id: 1, brand: 'BMW' })
1735
+ * .onConflictDoNothing();
1736
+ *
1737
+ * // Explicitly specify conflict target
1738
+ * await db.insert(cars)
1739
+ * .values({ id: 1, brand: 'BMW' })
1740
+ * .onConflictDoNothing({ target: cars.id });
1741
+ * ```
1742
+ */
1743
+ onConflictDoNothing(config = {}) {
1744
+ if (!this.config.onConflict) this.config.onConflict = [];
1745
+ if (config.target === void 0) this.config.onConflict.push(sql` on conflict do nothing`);
1746
+ else {
1747
+ const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
1748
+ const whereSql = config.where ? sql` where ${config.where}` : sql``;
1749
+ this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);
1750
+ }
1751
+ return this;
1752
+ }
1753
+ /**
1754
+ * Adds an `on conflict do update` clause to the query.
1755
+ *
1756
+ * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
1757
+ *
1758
+ * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
1759
+ *
1760
+ * @param config The `target`, `set` and `where` clauses.
1761
+ *
1762
+ * @example
1763
+ * ```ts
1764
+ * // Update the row if there's a conflict
1765
+ * await db.insert(cars)
1766
+ * .values({ id: 1, brand: 'BMW' })
1767
+ * .onConflictDoUpdate({
1768
+ * target: cars.id,
1769
+ * set: { brand: 'Porsche' }
1770
+ * });
1771
+ *
1772
+ * // Upsert with 'where' clause
1773
+ * await db.insert(cars)
1774
+ * .values({ id: 1, brand: 'BMW' })
1775
+ * .onConflictDoUpdate({
1776
+ * target: cars.id,
1777
+ * set: { brand: 'newBMW' },
1778
+ * where: sql`${cars.createdAt} > '2023-01-01'::date`,
1779
+ * });
1780
+ * ```
1781
+ */
1782
+ onConflictDoUpdate(config) {
1783
+ if (config.where && (config.targetWhere || config.setWhere)) throw new Error("You cannot use both \"where\" and \"targetWhere\"/\"setWhere\" at the same time - \"where\" is deprecated, use \"targetWhere\" or \"setWhere\" instead.");
1784
+ if (!this.config.onConflict) this.config.onConflict = [];
1785
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
1786
+ const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
1787
+ const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
1788
+ const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
1789
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
1790
+ this.config.onConflict.push(sql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`);
1791
+ return this;
1792
+ }
1793
+ /** @internal */
1794
+ getSQL() {
1795
+ return this.dialect.buildInsertQuery(this.config);
1796
+ }
1797
+ toSQL() {
1798
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
1799
+ return rest;
1800
+ }
1801
+ /** @internal */
1802
+ _prepare(isOneTimeQuery = true) {
1803
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, void 0, {
1804
+ type: "insert",
1805
+ tables: extractUsedTable(this.config.table)
1806
+ });
1807
+ }
1808
+ prepare() {
1809
+ return this._prepare(false);
1810
+ }
1811
+ run = (placeholderValues) => {
1812
+ return this._prepare().run(placeholderValues);
1813
+ };
1814
+ all = (placeholderValues) => {
1815
+ return this._prepare().all(placeholderValues);
1816
+ };
1817
+ get = (placeholderValues) => {
1818
+ return this._prepare().get(placeholderValues);
1819
+ };
1820
+ values = (placeholderValues) => {
1821
+ return this._prepare().values(placeholderValues);
1822
+ };
1823
+ async execute() {
1824
+ return this.config.returning ? this.all() : this.run();
1825
+ }
1826
+ $dynamic() {
1827
+ return this;
1828
+ }
1829
+ };
1830
+ //#endregion
1831
+ //#region node_modules/drizzle-orm/sqlite-core/query-builders/update.js
1832
+ var SQLiteUpdateBuilder = class {
1833
+ constructor(table, session, dialect, withList) {
1834
+ this.table = table;
1835
+ this.session = session;
1836
+ this.dialect = dialect;
1837
+ this.withList = withList;
1838
+ }
1839
+ static [entityKind] = "SQLiteUpdateBuilder";
1840
+ set(values) {
1841
+ return new SQLiteUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);
1842
+ }
1843
+ };
1844
+ var SQLiteUpdateBase = class extends QueryPromise {
1845
+ constructor(table, set, session, dialect, withList) {
1846
+ super();
1847
+ this.session = session;
1848
+ this.dialect = dialect;
1849
+ this.config = {
1850
+ set,
1851
+ table,
1852
+ withList,
1853
+ joins: []
1854
+ };
1855
+ }
1856
+ static [entityKind] = "SQLiteUpdate";
1857
+ /** @internal */
1858
+ config;
1859
+ from(source) {
1860
+ this.config.from = source;
1861
+ return this;
1862
+ }
1863
+ createJoin(joinType) {
1864
+ return (table, on) => {
1865
+ const tableName = getTableLikeName(table);
1866
+ if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
1867
+ if (typeof on === "function") {
1868
+ const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0;
1869
+ on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
1870
+ sqlAliasedBehavior: "sql",
1871
+ sqlBehavior: "sql"
1872
+ })), from && new Proxy(from, new SelectionProxyHandler({
1873
+ sqlAliasedBehavior: "sql",
1874
+ sqlBehavior: "sql"
1875
+ })));
1876
+ }
1877
+ this.config.joins.push({
1878
+ on,
1879
+ table,
1880
+ joinType,
1881
+ alias: tableName
1882
+ });
1883
+ return this;
1884
+ };
1885
+ }
1886
+ leftJoin = this.createJoin("left");
1887
+ rightJoin = this.createJoin("right");
1888
+ innerJoin = this.createJoin("inner");
1889
+ fullJoin = this.createJoin("full");
1890
+ /**
1891
+ * Adds a 'where' clause to the query.
1892
+ *
1893
+ * Calling this method will update only those rows that fulfill a specified condition.
1894
+ *
1895
+ * See docs: {@link https://orm.drizzle.team/docs/update}
1896
+ *
1897
+ * @param where the 'where' clause.
1898
+ *
1899
+ * @example
1900
+ * You can use conditional operators and `sql function` to filter the rows to be updated.
1901
+ *
1902
+ * ```ts
1903
+ * // Update all cars with green color
1904
+ * db.update(cars).set({ color: 'red' })
1905
+ * .where(eq(cars.color, 'green'));
1906
+ * // or
1907
+ * db.update(cars).set({ color: 'red' })
1908
+ * .where(sql`${cars.color} = 'green'`)
1909
+ * ```
1910
+ *
1911
+ * You can logically combine conditional operators with `and()` and `or()` operators:
1912
+ *
1913
+ * ```ts
1914
+ * // Update all BMW cars with a green color
1915
+ * db.update(cars).set({ color: 'red' })
1916
+ * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
1917
+ *
1918
+ * // Update all cars with the green or blue color
1919
+ * db.update(cars).set({ color: 'red' })
1920
+ * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
1921
+ * ```
1922
+ */
1923
+ where(where) {
1924
+ this.config.where = where;
1925
+ return this;
1926
+ }
1927
+ orderBy(...columns) {
1928
+ if (typeof columns[0] === "function") {
1929
+ const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
1930
+ sqlAliasedBehavior: "alias",
1931
+ sqlBehavior: "sql"
1932
+ })));
1933
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
1934
+ this.config.orderBy = orderByArray;
1935
+ } else {
1936
+ const orderByArray = columns;
1937
+ this.config.orderBy = orderByArray;
1938
+ }
1939
+ return this;
1940
+ }
1941
+ limit(limit) {
1942
+ this.config.limit = limit;
1943
+ return this;
1944
+ }
1945
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
1946
+ this.config.returning = orderSelectedFields(fields);
1947
+ return this;
1948
+ }
1949
+ /** @internal */
1950
+ getSQL() {
1951
+ return this.dialect.buildUpdateQuery(this.config);
1952
+ }
1953
+ toSQL() {
1954
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
1955
+ return rest;
1956
+ }
1957
+ /** @internal */
1958
+ _prepare(isOneTimeQuery = true) {
1959
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, void 0, {
1960
+ type: "insert",
1961
+ tables: extractUsedTable(this.config.table)
1962
+ });
1963
+ }
1964
+ prepare() {
1965
+ return this._prepare(false);
1966
+ }
1967
+ run = (placeholderValues) => {
1968
+ return this._prepare().run(placeholderValues);
1969
+ };
1970
+ all = (placeholderValues) => {
1971
+ return this._prepare().all(placeholderValues);
1972
+ };
1973
+ get = (placeholderValues) => {
1974
+ return this._prepare().get(placeholderValues);
1975
+ };
1976
+ values = (placeholderValues) => {
1977
+ return this._prepare().values(placeholderValues);
1978
+ };
1979
+ async execute() {
1980
+ return this.config.returning ? this.all() : this.run();
1981
+ }
1982
+ $dynamic() {
1983
+ return this;
1984
+ }
1985
+ };
1986
+ //#endregion
1987
+ //#region node_modules/drizzle-orm/sqlite-core/query-builders/count.js
1988
+ var SQLiteCountBuilder = class SQLiteCountBuilder extends SQL {
1989
+ constructor(params) {
1990
+ super(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
1991
+ this.params = params;
1992
+ this.session = params.session;
1993
+ this.sql = SQLiteCountBuilder.buildCount(params.source, params.filters);
1994
+ }
1995
+ sql;
1996
+ static [entityKind] = "SQLiteCountBuilderAsync";
1997
+ [Symbol.toStringTag] = "SQLiteCountBuilderAsync";
1998
+ session;
1999
+ static buildEmbeddedCount(source, filters) {
2000
+ return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
2001
+ }
2002
+ static buildCount(source, filters) {
2003
+ return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`;
2004
+ }
2005
+ then(onfulfilled, onrejected) {
2006
+ return Promise.resolve(this.session.count(this.sql)).then(onfulfilled, onrejected);
2007
+ }
2008
+ catch(onRejected) {
2009
+ return this.then(void 0, onRejected);
2010
+ }
2011
+ finally(onFinally) {
2012
+ return this.then((value) => {
2013
+ onFinally?.();
2014
+ return value;
2015
+ }, (reason) => {
2016
+ onFinally?.();
2017
+ throw reason;
2018
+ });
2019
+ }
2020
+ };
2021
+ //#endregion
2022
+ //#region node_modules/drizzle-orm/sqlite-core/query-builders/query.js
2023
+ var RelationalQueryBuilder = class {
2024
+ constructor(mode, fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
2025
+ this.mode = mode;
2026
+ this.fullSchema = fullSchema;
2027
+ this.schema = schema;
2028
+ this.tableNamesMap = tableNamesMap;
2029
+ this.table = table;
2030
+ this.tableConfig = tableConfig;
2031
+ this.dialect = dialect;
2032
+ this.session = session;
2033
+ }
2034
+ static [entityKind] = "SQLiteAsyncRelationalQueryBuilder";
2035
+ findMany(config) {
2036
+ return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many");
2037
+ }
2038
+ findFirst(config) {
2039
+ return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? {
2040
+ ...config,
2041
+ limit: 1
2042
+ } : { limit: 1 }, "first") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? {
2043
+ ...config,
2044
+ limit: 1
2045
+ } : { limit: 1 }, "first");
2046
+ }
2047
+ };
2048
+ var SQLiteRelationalQuery = class extends QueryPromise {
2049
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
2050
+ super();
2051
+ this.fullSchema = fullSchema;
2052
+ this.schema = schema;
2053
+ this.tableNamesMap = tableNamesMap;
2054
+ this.table = table;
2055
+ this.tableConfig = tableConfig;
2056
+ this.dialect = dialect;
2057
+ this.session = session;
2058
+ this.config = config;
2059
+ this.mode = mode;
2060
+ }
2061
+ static [entityKind] = "SQLiteAsyncRelationalQuery";
2062
+ /** @internal */
2063
+ mode;
2064
+ /** @internal */
2065
+ getSQL() {
2066
+ return this.dialect.buildRelationalQuery({
2067
+ fullSchema: this.fullSchema,
2068
+ schema: this.schema,
2069
+ tableNamesMap: this.tableNamesMap,
2070
+ table: this.table,
2071
+ tableConfig: this.tableConfig,
2072
+ queryConfig: this.config,
2073
+ tableAlias: this.tableConfig.tsName
2074
+ }).sql;
2075
+ }
2076
+ /** @internal */
2077
+ _prepare(isOneTimeQuery = false) {
2078
+ const { query, builtQuery } = this._toSQL();
2079
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](builtQuery, void 0, this.mode === "first" ? "get" : "all", true, (rawRows, mapColumnValue) => {
2080
+ const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue));
2081
+ if (this.mode === "first") return rows[0];
2082
+ return rows;
2083
+ });
2084
+ }
2085
+ prepare() {
2086
+ return this._prepare(false);
2087
+ }
2088
+ _toSQL() {
2089
+ const query = this.dialect.buildRelationalQuery({
2090
+ fullSchema: this.fullSchema,
2091
+ schema: this.schema,
2092
+ tableNamesMap: this.tableNamesMap,
2093
+ table: this.table,
2094
+ tableConfig: this.tableConfig,
2095
+ queryConfig: this.config,
2096
+ tableAlias: this.tableConfig.tsName
2097
+ });
2098
+ return {
2099
+ query,
2100
+ builtQuery: this.dialect.sqlToQuery(query.sql)
2101
+ };
2102
+ }
2103
+ toSQL() {
2104
+ return this._toSQL().builtQuery;
2105
+ }
2106
+ /** @internal */
2107
+ executeRaw() {
2108
+ if (this.mode === "first") return this._prepare(false).get();
2109
+ return this._prepare(false).all();
2110
+ }
2111
+ async execute() {
2112
+ return this.executeRaw();
2113
+ }
2114
+ };
2115
+ var SQLiteSyncRelationalQuery = class extends SQLiteRelationalQuery {
2116
+ static [entityKind] = "SQLiteSyncRelationalQuery";
2117
+ sync() {
2118
+ return this.executeRaw();
2119
+ }
2120
+ };
2121
+ //#endregion
2122
+ //#region node_modules/drizzle-orm/sqlite-core/query-builders/raw.js
2123
+ var SQLiteRaw = class extends QueryPromise {
2124
+ constructor(execute, getSQL, action, dialect, mapBatchResult) {
2125
+ super();
2126
+ this.execute = execute;
2127
+ this.getSQL = getSQL;
2128
+ this.dialect = dialect;
2129
+ this.mapBatchResult = mapBatchResult;
2130
+ this.config = { action };
2131
+ }
2132
+ static [entityKind] = "SQLiteRaw";
2133
+ /** @internal */
2134
+ config;
2135
+ getQuery() {
2136
+ return {
2137
+ ...this.dialect.sqlToQuery(this.getSQL()),
2138
+ method: this.config.action
2139
+ };
2140
+ }
2141
+ mapResult(result, isFromBatch) {
2142
+ return isFromBatch ? this.mapBatchResult(result) : result;
2143
+ }
2144
+ _prepare() {
2145
+ return this;
2146
+ }
2147
+ /** @internal */
2148
+ isResponseInArrayMode() {
2149
+ return false;
2150
+ }
2151
+ };
2152
+ //#endregion
2153
+ //#region node_modules/drizzle-orm/sqlite-core/db.js
2154
+ var BaseSQLiteDatabase = class {
2155
+ constructor(resultKind, dialect, session, schema) {
2156
+ this.resultKind = resultKind;
2157
+ this.dialect = dialect;
2158
+ this.session = session;
2159
+ this._ = schema ? {
2160
+ schema: schema.schema,
2161
+ fullSchema: schema.fullSchema,
2162
+ tableNamesMap: schema.tableNamesMap
2163
+ } : {
2164
+ schema: void 0,
2165
+ fullSchema: {},
2166
+ tableNamesMap: {}
2167
+ };
2168
+ this.query = {};
2169
+ const query = this.query;
2170
+ if (this._.schema) for (const [tableName, columns] of Object.entries(this._.schema)) query[tableName] = new RelationalQueryBuilder(resultKind, schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session);
2171
+ this.$cache = { invalidate: async (_params) => {} };
2172
+ }
2173
+ static [entityKind] = "BaseSQLiteDatabase";
2174
+ query;
2175
+ /**
2176
+ * Creates a subquery that defines a temporary named result set as a CTE.
2177
+ *
2178
+ * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
2179
+ *
2180
+ * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
2181
+ *
2182
+ * @param alias The alias for the subquery.
2183
+ *
2184
+ * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
2185
+ *
2186
+ * @example
2187
+ *
2188
+ * ```ts
2189
+ * // Create a subquery with alias 'sq' and use it in the select query
2190
+ * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
2191
+ *
2192
+ * const result = await db.with(sq).select().from(sq);
2193
+ * ```
2194
+ *
2195
+ * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
2196
+ *
2197
+ * ```ts
2198
+ * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
2199
+ * const sq = db.$with('sq').as(db.select({
2200
+ * name: sql<string>`upper(${users.name})`.as('name'),
2201
+ * })
2202
+ * .from(users));
2203
+ *
2204
+ * const result = await db.with(sq).select({ name: sq.name }).from(sq);
2205
+ * ```
2206
+ */
2207
+ $with = (alias, selection) => {
2208
+ const self = this;
2209
+ const as = (qb) => {
2210
+ if (typeof qb === "function") qb = qb(new QueryBuilder(self.dialect));
2211
+ return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({
2212
+ alias,
2213
+ sqlAliasedBehavior: "alias",
2214
+ sqlBehavior: "error"
2215
+ }));
2216
+ };
2217
+ return { as };
2218
+ };
2219
+ $count(source, filters) {
2220
+ return new SQLiteCountBuilder({
2221
+ source,
2222
+ filters,
2223
+ session: this.session
2224
+ });
2225
+ }
2226
+ /**
2227
+ * Incorporates a previously defined CTE (using `$with`) into the main query.
2228
+ *
2229
+ * This method allows the main query to reference a temporary named result set.
2230
+ *
2231
+ * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
2232
+ *
2233
+ * @param queries The CTEs to incorporate into the main query.
2234
+ *
2235
+ * @example
2236
+ *
2237
+ * ```ts
2238
+ * // Define a subquery 'sq' as a CTE using $with
2239
+ * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
2240
+ *
2241
+ * // Incorporate the CTE 'sq' into the main query and select from it
2242
+ * const result = await db.with(sq).select().from(sq);
2243
+ * ```
2244
+ */
2245
+ with(...queries) {
2246
+ const self = this;
2247
+ function select(fields) {
2248
+ return new SQLiteSelectBuilder({
2249
+ fields: fields ?? void 0,
2250
+ session: self.session,
2251
+ dialect: self.dialect,
2252
+ withList: queries
2253
+ });
2254
+ }
2255
+ function selectDistinct(fields) {
2256
+ return new SQLiteSelectBuilder({
2257
+ fields: fields ?? void 0,
2258
+ session: self.session,
2259
+ dialect: self.dialect,
2260
+ withList: queries,
2261
+ distinct: true
2262
+ });
2263
+ }
2264
+ function update(table) {
2265
+ return new SQLiteUpdateBuilder(table, self.session, self.dialect, queries);
2266
+ }
2267
+ function insert(into) {
2268
+ return new SQLiteInsertBuilder(into, self.session, self.dialect, queries);
2269
+ }
2270
+ function delete_(from) {
2271
+ return new SQLiteDeleteBase(from, self.session, self.dialect, queries);
2272
+ }
2273
+ return {
2274
+ select,
2275
+ selectDistinct,
2276
+ update,
2277
+ insert,
2278
+ delete: delete_
2279
+ };
2280
+ }
2281
+ select(fields) {
2282
+ return new SQLiteSelectBuilder({
2283
+ fields: fields ?? void 0,
2284
+ session: this.session,
2285
+ dialect: this.dialect
2286
+ });
2287
+ }
2288
+ selectDistinct(fields) {
2289
+ return new SQLiteSelectBuilder({
2290
+ fields: fields ?? void 0,
2291
+ session: this.session,
2292
+ dialect: this.dialect,
2293
+ distinct: true
2294
+ });
2295
+ }
2296
+ /**
2297
+ * Creates an update query.
2298
+ *
2299
+ * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
2300
+ *
2301
+ * Use `.set()` method to specify which values to update.
2302
+ *
2303
+ * See docs: {@link https://orm.drizzle.team/docs/update}
2304
+ *
2305
+ * @param table The table to update.
2306
+ *
2307
+ * @example
2308
+ *
2309
+ * ```ts
2310
+ * // Update all rows in the 'cars' table
2311
+ * await db.update(cars).set({ color: 'red' });
2312
+ *
2313
+ * // Update rows with filters and conditions
2314
+ * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
2315
+ *
2316
+ * // Update with returning clause
2317
+ * const updatedCar: Car[] = await db.update(cars)
2318
+ * .set({ color: 'red' })
2319
+ * .where(eq(cars.id, 1))
2320
+ * .returning();
2321
+ * ```
2322
+ */
2323
+ update(table) {
2324
+ return new SQLiteUpdateBuilder(table, this.session, this.dialect);
2325
+ }
2326
+ $cache;
2327
+ /**
2328
+ * Creates an insert query.
2329
+ *
2330
+ * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
2331
+ *
2332
+ * See docs: {@link https://orm.drizzle.team/docs/insert}
2333
+ *
2334
+ * @param table The table to insert into.
2335
+ *
2336
+ * @example
2337
+ *
2338
+ * ```ts
2339
+ * // Insert one row
2340
+ * await db.insert(cars).values({ brand: 'BMW' });
2341
+ *
2342
+ * // Insert multiple rows
2343
+ * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
2344
+ *
2345
+ * // Insert with returning clause
2346
+ * const insertedCar: Car[] = await db.insert(cars)
2347
+ * .values({ brand: 'BMW' })
2348
+ * .returning();
2349
+ * ```
2350
+ */
2351
+ insert(into) {
2352
+ return new SQLiteInsertBuilder(into, this.session, this.dialect);
2353
+ }
2354
+ /**
2355
+ * Creates a delete query.
2356
+ *
2357
+ * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
2358
+ *
2359
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
2360
+ *
2361
+ * @param table The table to delete from.
2362
+ *
2363
+ * @example
2364
+ *
2365
+ * ```ts
2366
+ * // Delete all rows in the 'cars' table
2367
+ * await db.delete(cars);
2368
+ *
2369
+ * // Delete rows with filters and conditions
2370
+ * await db.delete(cars).where(eq(cars.color, 'green'));
2371
+ *
2372
+ * // Delete with returning clause
2373
+ * const deletedCar: Car[] = await db.delete(cars)
2374
+ * .where(eq(cars.id, 1))
2375
+ * .returning();
2376
+ * ```
2377
+ */
2378
+ delete(from) {
2379
+ return new SQLiteDeleteBase(from, this.session, this.dialect);
2380
+ }
2381
+ run(query) {
2382
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
2383
+ if (this.resultKind === "async") return new SQLiteRaw(async () => this.session.run(sequel), () => sequel, "run", this.dialect, this.session.extractRawRunValueFromBatchResult.bind(this.session));
2384
+ return this.session.run(sequel);
2385
+ }
2386
+ all(query) {
2387
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
2388
+ if (this.resultKind === "async") return new SQLiteRaw(async () => this.session.all(sequel), () => sequel, "all", this.dialect, this.session.extractRawAllValueFromBatchResult.bind(this.session));
2389
+ return this.session.all(sequel);
2390
+ }
2391
+ get(query) {
2392
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
2393
+ if (this.resultKind === "async") return new SQLiteRaw(async () => this.session.get(sequel), () => sequel, "get", this.dialect, this.session.extractRawGetValueFromBatchResult.bind(this.session));
2394
+ return this.session.get(sequel);
2395
+ }
2396
+ values(query) {
2397
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
2398
+ if (this.resultKind === "async") return new SQLiteRaw(async () => this.session.values(sequel), () => sequel, "values", this.dialect, this.session.extractRawValuesValueFromBatchResult.bind(this.session));
2399
+ return this.session.values(sequel);
2400
+ }
2401
+ transaction(transaction, config) {
2402
+ return this.session.transaction(transaction, config);
2403
+ }
2404
+ };
2405
+ //#endregion
2406
+ //#region node_modules/drizzle-orm/cache/core/cache.js
2407
+ var Cache = class {
2408
+ static [entityKind] = "Cache";
2409
+ };
2410
+ var NoopCache = class extends Cache {
2411
+ strategy() {
2412
+ return "all";
2413
+ }
2414
+ static [entityKind] = "NoopCache";
2415
+ async get(_key) {}
2416
+ async put(_hashedQuery, _response, _tables, _config) {}
2417
+ async onMutate(_params) {}
2418
+ };
2419
+ async function hashQuery(sql, params) {
2420
+ const dataToHash = `${sql}-${JSON.stringify(params)}`;
2421
+ const data = new TextEncoder().encode(dataToHash);
2422
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
2423
+ return [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
2424
+ }
2425
+ //#endregion
2426
+ //#region node_modules/drizzle-orm/sqlite-core/session.js
2427
+ var ExecuteResultSync = class extends QueryPromise {
2428
+ constructor(resultCb) {
2429
+ super();
2430
+ this.resultCb = resultCb;
2431
+ }
2432
+ static [entityKind] = "ExecuteResultSync";
2433
+ async execute() {
2434
+ return this.resultCb();
2435
+ }
2436
+ sync() {
2437
+ return this.resultCb();
2438
+ }
2439
+ };
2440
+ var SQLitePreparedQuery = class {
2441
+ constructor(mode, executeMethod, query, cache, queryMetadata, cacheConfig) {
2442
+ this.mode = mode;
2443
+ this.executeMethod = executeMethod;
2444
+ this.query = query;
2445
+ this.cache = cache;
2446
+ this.queryMetadata = queryMetadata;
2447
+ this.cacheConfig = cacheConfig;
2448
+ if (cache && cache.strategy() === "all" && cacheConfig === void 0) this.cacheConfig = {
2449
+ enable: true,
2450
+ autoInvalidate: true
2451
+ };
2452
+ if (!this.cacheConfig?.enable) this.cacheConfig = void 0;
2453
+ }
2454
+ static [entityKind] = "PreparedQuery";
2455
+ /** @internal */
2456
+ joinsNotNullableMap;
2457
+ /** @internal */
2458
+ async queryWithCache(queryString, params, query) {
2459
+ if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) try {
2460
+ return await query();
2461
+ } catch (e) {
2462
+ throw new DrizzleQueryError(queryString, params, e);
2463
+ }
2464
+ if (this.cacheConfig && !this.cacheConfig.enable) try {
2465
+ return await query();
2466
+ } catch (e) {
2467
+ throw new DrizzleQueryError(queryString, params, e);
2468
+ }
2469
+ if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) try {
2470
+ const [res] = await Promise.all([query(), this.cache.onMutate({ tables: this.queryMetadata.tables })]);
2471
+ return res;
2472
+ } catch (e) {
2473
+ throw new DrizzleQueryError(queryString, params, e);
2474
+ }
2475
+ if (!this.cacheConfig) try {
2476
+ return await query();
2477
+ } catch (e) {
2478
+ throw new DrizzleQueryError(queryString, params, e);
2479
+ }
2480
+ if (this.queryMetadata.type === "select") {
2481
+ const fromCache = await this.cache.get(this.cacheConfig.tag ?? await hashQuery(queryString, params), this.queryMetadata.tables, this.cacheConfig.tag !== void 0, this.cacheConfig.autoInvalidate);
2482
+ if (fromCache === void 0) {
2483
+ let result;
2484
+ try {
2485
+ result = await query();
2486
+ } catch (e) {
2487
+ throw new DrizzleQueryError(queryString, params, e);
2488
+ }
2489
+ await this.cache.put(this.cacheConfig.tag ?? await hashQuery(queryString, params), result, this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], this.cacheConfig.tag !== void 0, this.cacheConfig.config);
2490
+ return result;
2491
+ }
2492
+ return fromCache;
2493
+ }
2494
+ try {
2495
+ return await query();
2496
+ } catch (e) {
2497
+ throw new DrizzleQueryError(queryString, params, e);
2498
+ }
2499
+ }
2500
+ getQuery() {
2501
+ return this.query;
2502
+ }
2503
+ mapRunResult(result, _isFromBatch) {
2504
+ return result;
2505
+ }
2506
+ mapAllResult(_result, _isFromBatch) {
2507
+ throw new Error("Not implemented");
2508
+ }
2509
+ mapGetResult(_result, _isFromBatch) {
2510
+ throw new Error("Not implemented");
2511
+ }
2512
+ execute(placeholderValues) {
2513
+ if (this.mode === "async") return this[this.executeMethod](placeholderValues);
2514
+ return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));
2515
+ }
2516
+ mapResult(response, isFromBatch) {
2517
+ switch (this.executeMethod) {
2518
+ case "run": return this.mapRunResult(response, isFromBatch);
2519
+ case "all": return this.mapAllResult(response, isFromBatch);
2520
+ case "get": return this.mapGetResult(response, isFromBatch);
2521
+ }
2522
+ }
2523
+ };
2524
+ var SQLiteSession = class {
2525
+ constructor(dialect) {
2526
+ this.dialect = dialect;
2527
+ }
2528
+ static [entityKind] = "SQLiteSession";
2529
+ prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
2530
+ return this.prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig);
2531
+ }
2532
+ run(query) {
2533
+ const staticQuery = this.dialect.sqlToQuery(query);
2534
+ try {
2535
+ return this.prepareOneTimeQuery(staticQuery, void 0, "run", false).run();
2536
+ } catch (err) {
2537
+ throw new DrizzleError({
2538
+ cause: err,
2539
+ message: `Failed to run the query '${staticQuery.sql}'`
2540
+ });
2541
+ }
2542
+ }
2543
+ /** @internal */
2544
+ extractRawRunValueFromBatchResult(result) {
2545
+ return result;
2546
+ }
2547
+ all(query) {
2548
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).all();
2549
+ }
2550
+ /** @internal */
2551
+ extractRawAllValueFromBatchResult(_result) {
2552
+ throw new Error("Not implemented");
2553
+ }
2554
+ get(query) {
2555
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).get();
2556
+ }
2557
+ /** @internal */
2558
+ extractRawGetValueFromBatchResult(_result) {
2559
+ throw new Error("Not implemented");
2560
+ }
2561
+ values(query) {
2562
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).values();
2563
+ }
2564
+ async count(sql) {
2565
+ return (await this.values(sql))[0][0];
2566
+ }
2567
+ /** @internal */
2568
+ extractRawValuesValueFromBatchResult(_result) {
2569
+ throw new Error("Not implemented");
2570
+ }
2571
+ };
2572
+ var SQLiteTransaction = class extends BaseSQLiteDatabase {
2573
+ constructor(resultType, dialect, session, schema, nestedIndex = 0) {
2574
+ super(resultType, dialect, session, schema);
2575
+ this.schema = schema;
2576
+ this.nestedIndex = nestedIndex;
2577
+ }
2578
+ static [entityKind] = "SQLiteTransaction";
2579
+ rollback() {
2580
+ throw new TransactionRollbackError();
2581
+ }
2582
+ };
2583
+ //#endregion
2584
+ //#region node_modules/drizzle-orm/better-sqlite3/session.js
2585
+ var BetterSQLiteSession = class extends SQLiteSession {
2586
+ constructor(client, dialect, schema, options = {}) {
2587
+ super(dialect);
2588
+ this.client = client;
2589
+ this.schema = schema;
2590
+ this.logger = options.logger ?? new NoopLogger();
2591
+ this.cache = options.cache ?? new NoopCache();
2592
+ }
2593
+ static [entityKind] = "BetterSQLiteSession";
2594
+ logger;
2595
+ cache;
2596
+ prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
2597
+ return new PreparedQuery(this.client.prepare(query.sql), query, this.logger, this.cache, queryMetadata, cacheConfig, fields, executeMethod, isResponseInArrayMode, customResultMapper);
2598
+ }
2599
+ transaction(transaction, config = {}) {
2600
+ const tx = new BetterSQLiteTransaction("sync", this.dialect, this, this.schema);
2601
+ return this.client.transaction(transaction)[config.behavior ?? "deferred"](tx);
2602
+ }
2603
+ };
2604
+ var BetterSQLiteTransaction = class BetterSQLiteTransaction extends SQLiteTransaction {
2605
+ static [entityKind] = "BetterSQLiteTransaction";
2606
+ transaction(transaction) {
2607
+ const savepointName = `sp${this.nestedIndex}`;
2608
+ const tx = new BetterSQLiteTransaction("sync", this.dialect, this.session, this.schema, this.nestedIndex + 1);
2609
+ this.session.run(sql.raw(`savepoint ${savepointName}`));
2610
+ try {
2611
+ const result = transaction(tx);
2612
+ this.session.run(sql.raw(`release savepoint ${savepointName}`));
2613
+ return result;
2614
+ } catch (err) {
2615
+ this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));
2616
+ throw err;
2617
+ }
2618
+ }
2619
+ };
2620
+ var PreparedQuery = class extends SQLitePreparedQuery {
2621
+ constructor(stmt, query, logger, cache, queryMetadata, cacheConfig, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {
2622
+ super("sync", executeMethod, query, cache, queryMetadata, cacheConfig);
2623
+ this.stmt = stmt;
2624
+ this.logger = logger;
2625
+ this.fields = fields;
2626
+ this._isResponseInArrayMode = _isResponseInArrayMode;
2627
+ this.customResultMapper = customResultMapper;
2628
+ }
2629
+ static [entityKind] = "BetterSQLitePreparedQuery";
2630
+ run(placeholderValues) {
2631
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
2632
+ this.logger.logQuery(this.query.sql, params);
2633
+ return this.stmt.run(...params);
2634
+ }
2635
+ all(placeholderValues) {
2636
+ const { fields, joinsNotNullableMap, query, logger, stmt, customResultMapper } = this;
2637
+ if (!fields && !customResultMapper) {
2638
+ const params = fillPlaceholders(query.params, placeholderValues ?? {});
2639
+ logger.logQuery(query.sql, params);
2640
+ return stmt.all(...params);
2641
+ }
2642
+ const rows = this.values(placeholderValues);
2643
+ if (customResultMapper) return customResultMapper(rows);
2644
+ return rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
2645
+ }
2646
+ get(placeholderValues) {
2647
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
2648
+ this.logger.logQuery(this.query.sql, params);
2649
+ const { fields, stmt, joinsNotNullableMap, customResultMapper } = this;
2650
+ if (!fields && !customResultMapper) return stmt.get(...params);
2651
+ const row = stmt.raw().get(...params);
2652
+ if (!row) return;
2653
+ if (customResultMapper) return customResultMapper([row]);
2654
+ return mapResultRow(fields, row, joinsNotNullableMap);
2655
+ }
2656
+ values(placeholderValues) {
2657
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
2658
+ this.logger.logQuery(this.query.sql, params);
2659
+ return this.stmt.raw().all(...params);
2660
+ }
2661
+ /** @internal */
2662
+ isResponseInArrayMode() {
2663
+ return this._isResponseInArrayMode;
2664
+ }
2665
+ };
2666
+ //#endregion
2667
+ //#region node_modules/drizzle-orm/better-sqlite3/driver.js
2668
+ var BetterSQLite3Database = class extends BaseSQLiteDatabase {
2669
+ static [entityKind] = "BetterSQLite3Database";
2670
+ };
2671
+ function construct(client, config = {}) {
2672
+ const dialect = new SQLiteSyncDialect({ casing: config.casing });
2673
+ let logger;
2674
+ if (config.logger === true) logger = new DefaultLogger();
2675
+ else if (config.logger !== false) logger = config.logger;
2676
+ let schema;
2677
+ if (config.schema) {
2678
+ const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);
2679
+ schema = {
2680
+ fullSchema: config.schema,
2681
+ schema: tablesConfig.tables,
2682
+ tableNamesMap: tablesConfig.tableNamesMap
2683
+ };
2684
+ }
2685
+ const db = new BetterSQLite3Database("sync", dialect, new BetterSQLiteSession(client, dialect, schema, { logger }), schema);
2686
+ db.$client = client;
2687
+ return db;
2688
+ }
2689
+ function drizzle(...params) {
2690
+ if (params[0] === void 0 || typeof params[0] === "string") return construct(params[0] === void 0 ? new Client() : new Client(params[0]), params[1]);
2691
+ if (isConfig(params[0])) {
2692
+ const { connection, client, ...drizzleConfig } = params[0];
2693
+ if (client) return construct(client, drizzleConfig);
2694
+ if (typeof connection === "object") {
2695
+ const { source, ...options } = connection;
2696
+ return construct(new Client(source, options), drizzleConfig);
2697
+ }
2698
+ return construct(new Client(connection), drizzleConfig);
2699
+ }
2700
+ return construct(params[0], params[1]);
2701
+ }
2702
+ ((drizzle2) => {
2703
+ function mock(config) {
2704
+ return construct({}, config);
2705
+ }
2706
+ drizzle2.mock = mock;
2707
+ })(drizzle || (drizzle = {}));
2708
+ //#endregion
2709
+ export { drizzle };