azure-mock 2.20.0 → 2.22.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.
Files changed (45) hide show
  1. package/LICENSE +201 -201
  2. package/dist/better-sqlite3-CtLaF97z-DWR9uC3b.js +129 -0
  3. package/dist/chunk-2X2C5D2I-dJHtPFe9-DxsO-1YF.js +4026 -0
  4. package/dist/d1-pK2J-_yx-BoQTXsTa.js +185 -0
  5. package/dist/dialect-pBb6Cg_F-xgpUtfmk.js +570 -0
  6. package/dist/dist-C481edUb-CHbOkeXH.js +10131 -0
  7. package/dist/dist-DUzzleZr-DxHmeYjp.js +2 -0
  8. package/dist/index.d.ts +21 -21
  9. package/dist/index.js +20396 -18921
  10. package/dist/libsql-Nq-S0r5x-d2dAzhgO.js +240 -0
  11. package/dist/logger-TIsK7375-CLNNa25D.js +652 -0
  12. package/dist/migrator-B9kYwLqO-4g9JX3_v.js +8 -0
  13. package/dist/migrator-BfTfJctM-DrNlb1BS.js +8 -0
  14. package/dist/migrator-BjoW0_3j-CD-XdZ5a.js +8 -0
  15. package/dist/migrator-CWWlo_Jk-C4Hw4PPN.js +8 -0
  16. package/dist/migrator-CpiXRkls-COYfhljd.js +24 -0
  17. package/dist/migrator-CtqJkLVI-D1lU6ZV0.js +8 -0
  18. package/dist/migrator-CxcBjmET-Dcd21VIf.js +8 -0
  19. package/dist/migrator-Cyhbhxo_-Bh7sF0R3.js +21 -0
  20. package/dist/migrator-DG1mWUoR-DVfkqn_v.js +31 -0
  21. package/dist/migrator-DrWmHwY2-YjAfotd7.js +8 -0
  22. package/dist/migrator-WAPonQxA-CRvJJhKG.js +8 -0
  23. package/dist/migrator-Zdh8WMMx-gsmNXspd.js +8 -0
  24. package/dist/migrator-xRJ6NOTS-SsAuB-Gi.js +24 -0
  25. package/dist/migrator-xbWwvFYF-BjyVdQS8.js +8 -0
  26. package/dist/mysql2-DkoPEsRu-BMwVSCmY.js +251 -0
  27. package/dist/neon-serverless-BEVFA7yv-DGSPAG1z.js +205 -0
  28. package/dist/node-postgres-DQA7bEhW-CkM_cVLD.js +216 -0
  29. package/dist/nodefs-Bc8b83o_-DetP9qUa.js +24 -0
  30. package/dist/opfs-ahp-DbstDvx--CHskKtzG.js +365 -0
  31. package/dist/pg-ylxXyvKj-Hm8vcZoi.js +279 -0
  32. package/dist/pglite-CPs4w-D9-DHOg0D8W.js +179 -0
  33. package/dist/pglite-DMWgTUE6-BOIRUWUT.js +2 -0
  34. package/dist/planetscale-serverless-DUMheN-f-Dyc_W6V_.js +172 -0
  35. package/dist/query-builder-CLJAKedv-DTZiP7B6.js +1715 -0
  36. package/dist/query-builder-CT3_liD0-hhg5kRTk.js +1347 -0
  37. package/dist/session-BOEirggu-DTmpyU_x.js +2485 -0
  38. package/dist/session-CAUQtT0A-BoVK2x7A.js +745 -0
  39. package/dist/session-Cjeygn2Z-BO0mi6pq.js +989 -0
  40. package/dist/singlestore-Cdlo23hW-BuFJ4Zqb.js +1647 -0
  41. package/dist/sql-CNZp2yLp-Bwugq384.js +611 -0
  42. package/dist/sqlite-proxy-BgUfVEbZ-CsSkc-_K.js +190 -0
  43. package/dist/src-LcyXhCXE-C_vKJiLK.js +1920 -0
  44. package/dist/vercel-postgres-BYmFKsTS-CpV2usun.js +203 -0
  45. package/package.json +7 -8
@@ -0,0 +1,1347 @@
1
+ import { C as sql, b as is, d as Table, f as TableName, g as entityKind, h as WithSubquery, m as ViewBaseConfig, p as View, r as Param, s as SQL, t as Column, u as Subquery, v as getTableName, y as getTableUniqueName } from "./sql-CNZp2yLp-Bwugq384.js";
2
+ import { A as mapColumnsInSQLToAlias, C as getOrderByOperators, D as haveSameKeys, F as orderSelectedFields, P as normalizeRelation, S as getOperators, T as getTableLikeName, _ as and, a as Many, b as eq, c as One, f as SelectionProxyHandler, g as aliasedTableColumn, h as aliasedTable, k as mapColumnsInAliasedSQLToAlias, m as TypedQueryBuilder, r as DrizzleError, t as CasingCache, u as QueryPromise, v as applyMixins, w as getTableColumns } from "./logger-TIsK7375-CLNNa25D.js";
3
+ //#region ../db/dist/query-builder-CT3_liD0.js
4
+ var CheckBuilder = class {
5
+ constructor(name, value) {
6
+ this.name = name;
7
+ this.value = value;
8
+ }
9
+ static [entityKind] = "SQLiteCheckBuilder";
10
+ brand;
11
+ build(table) {
12
+ return new Check(table, this);
13
+ }
14
+ };
15
+ var Check = class {
16
+ constructor(table, builder) {
17
+ this.table = table;
18
+ this.name = builder.name;
19
+ this.value = builder.value;
20
+ }
21
+ static [entityKind] = "SQLiteCheck";
22
+ name;
23
+ value;
24
+ };
25
+ var ForeignKeyBuilder = class {
26
+ static [entityKind] = "SQLiteForeignKeyBuilder";
27
+ /** @internal */
28
+ reference;
29
+ /** @internal */
30
+ _onUpdate;
31
+ /** @internal */
32
+ _onDelete;
33
+ constructor(config, actions) {
34
+ this.reference = () => {
35
+ const { name, columns, foreignColumns } = config();
36
+ return {
37
+ name,
38
+ columns,
39
+ foreignTable: foreignColumns[0].table,
40
+ foreignColumns
41
+ };
42
+ };
43
+ if (actions) {
44
+ this._onUpdate = actions.onUpdate;
45
+ this._onDelete = actions.onDelete;
46
+ }
47
+ }
48
+ onUpdate(action) {
49
+ this._onUpdate = action;
50
+ return this;
51
+ }
52
+ onDelete(action) {
53
+ this._onDelete = action;
54
+ return this;
55
+ }
56
+ /** @internal */
57
+ build(table) {
58
+ return new ForeignKey(table, this);
59
+ }
60
+ };
61
+ var ForeignKey = class {
62
+ constructor(table, builder) {
63
+ this.table = table;
64
+ this.reference = builder.reference;
65
+ this.onUpdate = builder._onUpdate;
66
+ this.onDelete = builder._onDelete;
67
+ }
68
+ static [entityKind] = "SQLiteForeignKey";
69
+ reference;
70
+ onUpdate;
71
+ onDelete;
72
+ getName() {
73
+ const { name, columns, foreignColumns } = this.reference();
74
+ const columnNames = columns.map((column) => column.name);
75
+ const foreignColumnNames = foreignColumns.map((column) => column.name);
76
+ const chunks = [
77
+ this.table[TableName],
78
+ ...columnNames,
79
+ foreignColumns[0].table[TableName],
80
+ ...foreignColumnNames
81
+ ];
82
+ return name ?? `${chunks.join("_")}_fk`;
83
+ }
84
+ };
85
+ function uniqueKeyName(table, columns) {
86
+ return `${table[TableName]}_${columns.join("_")}_unique`;
87
+ }
88
+ var UniqueConstraintBuilder = class {
89
+ constructor(columns, name) {
90
+ this.name = name;
91
+ this.columns = columns;
92
+ }
93
+ static [entityKind] = "SQLiteUniqueConstraintBuilder";
94
+ /** @internal */
95
+ columns;
96
+ /** @internal */
97
+ build(table) {
98
+ return new UniqueConstraint(table, this.columns, this.name);
99
+ }
100
+ };
101
+ var UniqueConstraint = class {
102
+ constructor(table, columns, name) {
103
+ this.table = table;
104
+ this.columns = columns;
105
+ this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));
106
+ }
107
+ static [entityKind] = "SQLiteUniqueConstraint";
108
+ columns;
109
+ name;
110
+ getName() {
111
+ return this.name;
112
+ }
113
+ };
114
+ var SQLiteColumn = class extends Column {
115
+ constructor(table, config) {
116
+ if (!config.uniqueName) config.uniqueName = uniqueKeyName(table, [config.name]);
117
+ super(table, config);
118
+ this.table = table;
119
+ }
120
+ static [entityKind] = "SQLiteColumn";
121
+ };
122
+ const InlineForeignKeys = Symbol.for("drizzle:SQLiteInlineForeignKeys");
123
+ var SQLiteTable = class extends Table {
124
+ static [entityKind] = "SQLiteTable";
125
+ /** @internal */
126
+ static Symbol = Object.assign({}, Table.Symbol, { InlineForeignKeys });
127
+ /** @internal */
128
+ [Table.Symbol.Columns];
129
+ /** @internal */
130
+ [InlineForeignKeys] = [];
131
+ /** @internal */
132
+ [Table.Symbol.ExtraConfigBuilder] = void 0;
133
+ };
134
+ var IndexBuilder = class {
135
+ static [entityKind] = "SQLiteIndexBuilder";
136
+ /** @internal */
137
+ config;
138
+ constructor(name, columns, unique) {
139
+ this.config = {
140
+ name,
141
+ columns,
142
+ unique,
143
+ where: void 0
144
+ };
145
+ }
146
+ /**
147
+ * Condition for partial index.
148
+ */
149
+ where(condition) {
150
+ this.config.where = condition;
151
+ return this;
152
+ }
153
+ /** @internal */
154
+ build(table) {
155
+ return new Index(this.config, table);
156
+ }
157
+ };
158
+ var Index = class {
159
+ static [entityKind] = "SQLiteIndex";
160
+ config;
161
+ constructor(config, table) {
162
+ this.config = {
163
+ ...config,
164
+ table
165
+ };
166
+ }
167
+ };
168
+ var PrimaryKeyBuilder = class {
169
+ static [entityKind] = "SQLitePrimaryKeyBuilder";
170
+ /** @internal */
171
+ columns;
172
+ /** @internal */
173
+ name;
174
+ constructor(columns, name) {
175
+ this.columns = columns;
176
+ this.name = name;
177
+ }
178
+ /** @internal */
179
+ build(table) {
180
+ return new PrimaryKey(table, this.columns, this.name);
181
+ }
182
+ };
183
+ var PrimaryKey = class {
184
+ constructor(table, columns, name) {
185
+ this.table = table;
186
+ this.columns = columns;
187
+ this.name = name;
188
+ }
189
+ static [entityKind] = "SQLitePrimaryKey";
190
+ columns;
191
+ name;
192
+ getName() {
193
+ return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
194
+ }
195
+ };
196
+ function getTableConfig(table) {
197
+ const columns = Object.values(table[SQLiteTable.Symbol.Columns]);
198
+ const indexes = [];
199
+ const checks = [];
200
+ const primaryKeys = [];
201
+ const uniqueConstraints = [];
202
+ const foreignKeys = Object.values(table[SQLiteTable.Symbol.InlineForeignKeys]);
203
+ const name = table[Table.Symbol.Name];
204
+ const extraConfigBuilder = table[SQLiteTable.Symbol.ExtraConfigBuilder];
205
+ if (extraConfigBuilder !== void 0) {
206
+ const extraConfig = extraConfigBuilder(table[SQLiteTable.Symbol.Columns]);
207
+ const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
208
+ for (const builder of Object.values(extraValues)) if (is(builder, IndexBuilder)) indexes.push(builder.build(table));
209
+ else if (is(builder, CheckBuilder)) checks.push(builder.build(table));
210
+ else if (is(builder, UniqueConstraintBuilder)) uniqueConstraints.push(builder.build(table));
211
+ else if (is(builder, PrimaryKeyBuilder)) primaryKeys.push(builder.build(table));
212
+ else if (is(builder, ForeignKeyBuilder)) foreignKeys.push(builder.build(table));
213
+ }
214
+ return {
215
+ columns,
216
+ indexes,
217
+ foreignKeys,
218
+ checks,
219
+ primaryKeys,
220
+ uniqueConstraints,
221
+ name
222
+ };
223
+ }
224
+ function extractUsedTable(table) {
225
+ if (is(table, SQLiteTable)) return [`${table[Table.Symbol.BaseName]}`];
226
+ if (is(table, Subquery)) return table._.usedTables ?? [];
227
+ if (is(table, SQL)) return table.usedTables ?? [];
228
+ return [];
229
+ }
230
+ var SQLiteViewBase = class extends View {
231
+ static [entityKind] = "SQLiteViewBase";
232
+ };
233
+ var SQLiteDialect = class {
234
+ static [entityKind] = "SQLiteDialect";
235
+ /** @internal */
236
+ casing;
237
+ constructor(config) {
238
+ this.casing = new CasingCache(config?.casing);
239
+ }
240
+ escapeName(name) {
241
+ return `"${name.replace(/"/g, "\"\"")}"`;
242
+ }
243
+ escapeParam(_num) {
244
+ return "?";
245
+ }
246
+ escapeString(str) {
247
+ return `'${str.replace(/'/g, "''")}'`;
248
+ }
249
+ buildWithCTE(queries) {
250
+ if (!queries?.length) return void 0;
251
+ const withSqlChunks = [sql`with `];
252
+ for (const [i, w] of queries.entries()) {
253
+ withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
254
+ if (i < queries.length - 1) withSqlChunks.push(sql`, `);
255
+ }
256
+ withSqlChunks.push(sql` `);
257
+ return sql.join(withSqlChunks);
258
+ }
259
+ buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) {
260
+ const withSql = this.buildWithCTE(withList);
261
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
262
+ return sql`${withSql}delete from ${table}${where ? sql` where ${where}` : void 0}${returningSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}`;
263
+ }
264
+ buildUpdateSet(table, set) {
265
+ const tableColumns = table[Table.Symbol.Columns];
266
+ const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0);
267
+ const setSize = columnNames.length;
268
+ return sql.join(columnNames.flatMap((colName, i) => {
269
+ const col = tableColumns[colName];
270
+ const onUpdateFnResult = col.onUpdateFn?.();
271
+ const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));
272
+ const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
273
+ if (i < setSize - 1) return [res, sql.raw(", ")];
274
+ return [res];
275
+ }));
276
+ }
277
+ buildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }) {
278
+ const withSql = this.buildWithCTE(withList);
279
+ const setSql = this.buildUpdateSet(table, set);
280
+ const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
281
+ const joinsSql = this.buildJoins(joins);
282
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
283
+ return sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${where ? sql` where ${where}` : void 0}${returningSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}`;
284
+ }
285
+ /**
286
+ * Builds selection SQL with provided fields/expressions
287
+ *
288
+ * Examples:
289
+ *
290
+ * `select <selection> from`
291
+ *
292
+ * `insert ... returning <selection>`
293
+ *
294
+ * If `isSingleTable` is true, then columns won't be prefixed with table name
295
+ */
296
+ buildSelection(fields, { isSingleTable = false } = {}) {
297
+ const columnsLen = fields.length;
298
+ const chunks = fields.flatMap(({ field }, i) => {
299
+ const chunk = [];
300
+ if (is(field, SQL.Aliased) && field.isSelectionField) chunk.push(sql.identifier(field.fieldAlias));
301
+ else if (is(field, SQL.Aliased) || is(field, SQL)) {
302
+ const query = is(field, SQL.Aliased) ? field.sql : field;
303
+ if (isSingleTable) chunk.push(new SQL(query.queryChunks.map((c) => {
304
+ if (is(c, Column)) return sql.identifier(this.casing.getColumnCasing(c));
305
+ return c;
306
+ })));
307
+ else chunk.push(query);
308
+ if (is(field, SQL.Aliased)) chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
309
+ } else if (is(field, Column)) {
310
+ const tableName = field.table[Table.Symbol.Name];
311
+ if (field.columnType === "SQLiteNumericBigInt") if (isSingleTable) chunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
312
+ else chunk.push(sql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
313
+ else if (isSingleTable) chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
314
+ else chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);
315
+ } else if (is(field, Subquery)) {
316
+ const entries = Object.entries(field._.selectedFields);
317
+ if (entries.length === 1) {
318
+ const entry = entries[0][1];
319
+ const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: (v) => entry.mapFromDriverValue(v) } : entry.sql.decoder;
320
+ if (fieldDecoder) field._.sql.decoder = fieldDecoder;
321
+ }
322
+ chunk.push(field);
323
+ }
324
+ if (i < columnsLen - 1) chunk.push(sql`, `);
325
+ return chunk;
326
+ });
327
+ return sql.join(chunks);
328
+ }
329
+ buildJoins(joins) {
330
+ if (!joins || joins.length === 0) return;
331
+ const joinsArray = [];
332
+ if (joins) for (const [index, joinMeta] of joins.entries()) {
333
+ if (index === 0) joinsArray.push(sql` `);
334
+ const table = joinMeta.table;
335
+ const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
336
+ if (is(table, SQLiteTable)) {
337
+ const tableName = table[SQLiteTable.Symbol.Name];
338
+ const tableSchema = table[SQLiteTable.Symbol.Schema];
339
+ const origTableName = table[SQLiteTable.Symbol.OriginalName];
340
+ const alias = tableName === origTableName ? void 0 : joinMeta.alias;
341
+ joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);
342
+ } else joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`);
343
+ if (index < joins.length - 1) joinsArray.push(sql` `);
344
+ }
345
+ return sql.join(joinsArray);
346
+ }
347
+ buildLimit(limit) {
348
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
349
+ }
350
+ buildOrderBy(orderBy) {
351
+ const orderByList = [];
352
+ if (orderBy) for (const [index, orderByValue] of orderBy.entries()) {
353
+ orderByList.push(orderByValue);
354
+ if (index < orderBy.length - 1) orderByList.push(sql`, `);
355
+ }
356
+ return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
357
+ }
358
+ buildFromTable(table) {
359
+ 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])}`;
360
+ return table;
361
+ }
362
+ buildSelectQuery({ withList, fields, fieldsFlat, where, having, table, joins, orderBy, groupBy, limit, offset, distinct, setOperators }) {
363
+ const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
364
+ 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)) {
365
+ const tableName = getTableName(f.field.table);
366
+ 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?`);
367
+ }
368
+ const isSingleTable = !joins || joins.length === 0;
369
+ const withSql = this.buildWithCTE(withList);
370
+ const distinctSql = distinct ? sql` distinct` : void 0;
371
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
372
+ const tableSql = this.buildFromTable(table);
373
+ const joinsSql = this.buildJoins(joins);
374
+ const whereSql = where ? sql` where ${where}` : void 0;
375
+ const havingSql = having ? sql` having ${having}` : void 0;
376
+ const groupByList = [];
377
+ if (groupBy) for (const [index, groupByValue] of groupBy.entries()) {
378
+ groupByList.push(groupByValue);
379
+ if (index < groupBy.length - 1) groupByList.push(sql`, `);
380
+ }
381
+ 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}`;
382
+ if (setOperators.length > 0) return this.buildSetOperations(finalQuery, setOperators);
383
+ return finalQuery;
384
+ }
385
+ buildSetOperations(leftSelect, setOperators) {
386
+ const [setOperator, ...rest] = setOperators;
387
+ if (!setOperator) throw new Error("Cannot pass undefined values to any set operator");
388
+ if (rest.length === 0) return this.buildSetOperationQuery({
389
+ leftSelect,
390
+ setOperator
391
+ });
392
+ return this.buildSetOperations(this.buildSetOperationQuery({
393
+ leftSelect,
394
+ setOperator
395
+ }), rest);
396
+ }
397
+ buildSetOperationQuery({ leftSelect, setOperator: { type, isAll, rightSelect, limit, orderBy, offset } }) {
398
+ const leftChunk = sql`${leftSelect.getSQL()} `;
399
+ const rightChunk = sql`${rightSelect.getSQL()}`;
400
+ let orderBySql;
401
+ if (orderBy && orderBy.length > 0) {
402
+ const orderByValues = [];
403
+ for (const singleOrderBy of orderBy) if (is(singleOrderBy, SQLiteColumn)) orderByValues.push(sql.identifier(singleOrderBy.name));
404
+ else if (is(singleOrderBy, SQL)) {
405
+ for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
406
+ const chunk = singleOrderBy.queryChunks[i];
407
+ if (is(chunk, SQLiteColumn)) singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
408
+ }
409
+ orderByValues.push(sql`${singleOrderBy}`);
410
+ } else orderByValues.push(sql`${singleOrderBy}`);
411
+ orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
412
+ }
413
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
414
+ const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
415
+ const offsetSql = offset ? sql` offset ${offset}` : void 0;
416
+ return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
417
+ }
418
+ buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select }) {
419
+ const valuesSqlList = [];
420
+ const columns = table[Table.Symbol.Columns];
421
+ const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
422
+ const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));
423
+ if (select) {
424
+ const select2 = valuesOrSelect;
425
+ if (is(select2, SQL)) valuesSqlList.push(select2);
426
+ else valuesSqlList.push(select2.getSQL());
427
+ } else {
428
+ const values = valuesOrSelect;
429
+ valuesSqlList.push(sql.raw("values "));
430
+ for (const [valueIndex, value] of values.entries()) {
431
+ const valueList = [];
432
+ for (const [fieldName, col] of colEntries) {
433
+ const colValue = value[fieldName];
434
+ if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
435
+ let defaultValue;
436
+ if (col.default !== null && col.default !== void 0) defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
437
+ else if (col.defaultFn !== void 0) {
438
+ const defaultFnResult = col.defaultFn();
439
+ defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
440
+ } else if (!col.default && col.onUpdateFn !== void 0) {
441
+ const onUpdateFnResult = col.onUpdateFn();
442
+ defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
443
+ } else defaultValue = sql`null`;
444
+ valueList.push(defaultValue);
445
+ } else valueList.push(colValue);
446
+ }
447
+ valuesSqlList.push(valueList);
448
+ if (valueIndex < values.length - 1) valuesSqlList.push(sql`, `);
449
+ }
450
+ }
451
+ const withSql = this.buildWithCTE(withList);
452
+ const valuesSql = sql.join(valuesSqlList);
453
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
454
+ return sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflict?.length ? sql.join(onConflict) : void 0}${returningSql}`;
455
+ }
456
+ sqlToQuery(sql2, invokeSource) {
457
+ return sql2.toQuery({
458
+ casing: this.casing,
459
+ escapeName: this.escapeName,
460
+ escapeParam: this.escapeParam,
461
+ escapeString: this.escapeString,
462
+ invokeSource
463
+ });
464
+ }
465
+ buildRelationalQuery({ fullSchema, schema, tableNamesMap, table, tableConfig, queryConfig: config, tableAlias, nestedQueryRelation, joinOn }) {
466
+ let selection = [];
467
+ let limit, offset, orderBy = [], where;
468
+ const joins = [];
469
+ if (config === true) selection = Object.entries(tableConfig.columns).map(([key, value]) => ({
470
+ dbKey: value.name,
471
+ tsKey: key,
472
+ field: aliasedTableColumn(value, tableAlias),
473
+ relationTableTsKey: void 0,
474
+ isJson: false,
475
+ selection: []
476
+ }));
477
+ else {
478
+ const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
479
+ if (config.where) {
480
+ const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
481
+ where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
482
+ }
483
+ const fieldsSelection = [];
484
+ let selectedColumns = [];
485
+ if (config.columns) {
486
+ let isIncludeMode = false;
487
+ for (const [field, value] of Object.entries(config.columns)) {
488
+ if (value === void 0) continue;
489
+ if (field in tableConfig.columns) {
490
+ if (!isIncludeMode && value === true) isIncludeMode = true;
491
+ selectedColumns.push(field);
492
+ }
493
+ }
494
+ if (selectedColumns.length > 0) selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
495
+ } else selectedColumns = Object.keys(tableConfig.columns);
496
+ for (const field of selectedColumns) {
497
+ const column = tableConfig.columns[field];
498
+ fieldsSelection.push({
499
+ tsKey: field,
500
+ value: column
501
+ });
502
+ }
503
+ let selectedRelations = [];
504
+ if (config.with) selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({
505
+ tsKey,
506
+ queryConfig,
507
+ relation: tableConfig.relations[tsKey]
508
+ }));
509
+ let extras;
510
+ if (config.extras) {
511
+ extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
512
+ for (const [tsKey, value] of Object.entries(extras)) fieldsSelection.push({
513
+ tsKey,
514
+ value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
515
+ });
516
+ }
517
+ for (const { tsKey, value } of fieldsSelection) selection.push({
518
+ dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
519
+ tsKey,
520
+ field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
521
+ relationTableTsKey: void 0,
522
+ isJson: false,
523
+ selection: []
524
+ });
525
+ let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
526
+ if (!Array.isArray(orderByOrig)) orderByOrig = [orderByOrig];
527
+ orderBy = orderByOrig.map((orderByValue) => {
528
+ if (is(orderByValue, Column)) return aliasedTableColumn(orderByValue, tableAlias);
529
+ return mapColumnsInSQLToAlias(orderByValue, tableAlias);
530
+ });
531
+ limit = config.limit;
532
+ offset = config.offset;
533
+ for (const { tsKey: selectedRelationTsKey, queryConfig: selectedRelationConfigValue, relation } of selectedRelations) {
534
+ const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
535
+ const relationTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
536
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
537
+ const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias))));
538
+ const builtRelation = this.buildRelationalQuery({
539
+ fullSchema,
540
+ schema,
541
+ tableNamesMap,
542
+ table: fullSchema[relationTableTsName],
543
+ tableConfig: schema[relationTableTsName],
544
+ queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : {
545
+ ...selectedRelationConfigValue,
546
+ limit: 1
547
+ } : selectedRelationConfigValue,
548
+ tableAlias: relationTableAlias,
549
+ joinOn: joinOn2,
550
+ nestedQueryRelation: relation
551
+ });
552
+ const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
553
+ selection.push({
554
+ dbKey: selectedRelationTsKey,
555
+ tsKey: selectedRelationTsKey,
556
+ field,
557
+ relationTableTsKey: relationTableTsName,
558
+ isJson: true,
559
+ selection: builtRelation.selection
560
+ });
561
+ }
562
+ }
563
+ 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.` });
564
+ let result;
565
+ where = and(joinOn, where);
566
+ if (nestedQueryRelation) {
567
+ 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`, `)})`;
568
+ if (is(nestedQueryRelation, Many)) field = sql`coalesce(json_group_array(${field}), json_array())`;
569
+ const nestedSelection = [{
570
+ dbKey: "data",
571
+ tsKey: "data",
572
+ field: field.as("data"),
573
+ isJson: true,
574
+ relationTableTsKey: tableConfig.tsName,
575
+ selection
576
+ }];
577
+ if (limit !== void 0 || offset !== void 0 || orderBy.length > 0) {
578
+ result = this.buildSelectQuery({
579
+ table: aliasedTable(table, tableAlias),
580
+ fields: {},
581
+ fieldsFlat: [{
582
+ path: [],
583
+ field: sql.raw("*")
584
+ }],
585
+ where,
586
+ limit,
587
+ offset,
588
+ orderBy,
589
+ setOperators: []
590
+ });
591
+ where = void 0;
592
+ limit = void 0;
593
+ offset = void 0;
594
+ orderBy = void 0;
595
+ } else result = aliasedTable(table, tableAlias);
596
+ result = this.buildSelectQuery({
597
+ table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),
598
+ fields: {},
599
+ fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
600
+ path: [],
601
+ field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
602
+ })),
603
+ joins,
604
+ where,
605
+ limit,
606
+ offset,
607
+ orderBy,
608
+ setOperators: []
609
+ });
610
+ } else result = this.buildSelectQuery({
611
+ table: aliasedTable(table, tableAlias),
612
+ fields: {},
613
+ fieldsFlat: selection.map(({ field }) => ({
614
+ path: [],
615
+ field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
616
+ })),
617
+ joins,
618
+ where,
619
+ limit,
620
+ offset,
621
+ orderBy,
622
+ setOperators: []
623
+ });
624
+ return {
625
+ tableTsKey: tableConfig.tsName,
626
+ sql: result,
627
+ selection
628
+ };
629
+ }
630
+ };
631
+ var SQLiteSyncDialect = class extends SQLiteDialect {
632
+ static [entityKind] = "SQLiteSyncDialect";
633
+ migrate(migrations, session, config) {
634
+ const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
635
+ const migrationTableCreate = sql`
636
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
637
+ id SERIAL PRIMARY KEY,
638
+ hash text NOT NULL,
639
+ created_at numeric
640
+ )
641
+ `;
642
+ session.run(migrationTableCreate);
643
+ const lastDbMigration = session.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`)[0] ?? void 0;
644
+ session.run(sql`BEGIN`);
645
+ try {
646
+ for (const migration of migrations) if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
647
+ for (const stmt of migration.sql) session.run(sql.raw(stmt));
648
+ session.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
649
+ }
650
+ session.run(sql`COMMIT`);
651
+ } catch (e) {
652
+ session.run(sql`ROLLBACK`);
653
+ throw e;
654
+ }
655
+ }
656
+ };
657
+ var SQLiteAsyncDialect = class extends SQLiteDialect {
658
+ static [entityKind] = "SQLiteAsyncDialect";
659
+ async migrate(migrations, session, config) {
660
+ const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
661
+ const migrationTableCreate = sql`
662
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
663
+ id SERIAL PRIMARY KEY,
664
+ hash text NOT NULL,
665
+ created_at numeric
666
+ )
667
+ `;
668
+ await session.run(migrationTableCreate);
669
+ const lastDbMigration = (await session.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`))[0] ?? void 0;
670
+ await session.transaction(async (tx) => {
671
+ for (const migration of migrations) if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
672
+ for (const stmt of migration.sql) await tx.run(sql.raw(stmt));
673
+ await tx.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
674
+ }
675
+ });
676
+ }
677
+ };
678
+ var SQLiteSelectBuilder = class {
679
+ static [entityKind] = "SQLiteSelectBuilder";
680
+ fields;
681
+ session;
682
+ dialect;
683
+ withList;
684
+ distinct;
685
+ constructor(config) {
686
+ this.fields = config.fields;
687
+ this.session = config.session;
688
+ this.dialect = config.dialect;
689
+ this.withList = config.withList;
690
+ this.distinct = config.distinct;
691
+ }
692
+ from(source) {
693
+ const isPartialSelect = !!this.fields;
694
+ let fields;
695
+ if (this.fields) fields = this.fields;
696
+ else if (is(source, Subquery)) fields = Object.fromEntries(Object.keys(source._.selectedFields).map((key) => [key, source[key]]));
697
+ else if (is(source, SQLiteViewBase)) fields = source[ViewBaseConfig].selectedFields;
698
+ else if (is(source, SQL)) fields = {};
699
+ else fields = getTableColumns(source);
700
+ return new SQLiteSelectBase({
701
+ table: source,
702
+ fields,
703
+ isPartialSelect,
704
+ session: this.session,
705
+ dialect: this.dialect,
706
+ withList: this.withList,
707
+ distinct: this.distinct
708
+ });
709
+ }
710
+ };
711
+ var SQLiteSelectQueryBuilderBase = class extends TypedQueryBuilder {
712
+ static [entityKind] = "SQLiteSelectQueryBuilder";
713
+ _;
714
+ /** @internal */
715
+ config;
716
+ joinsNotNullableMap;
717
+ tableName;
718
+ isPartialSelect;
719
+ session;
720
+ dialect;
721
+ cacheConfig = void 0;
722
+ usedTables = /* @__PURE__ */ new Set();
723
+ constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
724
+ super();
725
+ this.config = {
726
+ withList,
727
+ table,
728
+ fields: { ...fields },
729
+ distinct,
730
+ setOperators: []
731
+ };
732
+ this.isPartialSelect = isPartialSelect;
733
+ this.session = session;
734
+ this.dialect = dialect;
735
+ this._ = {
736
+ selectedFields: fields,
737
+ config: this.config
738
+ };
739
+ this.tableName = getTableLikeName(table);
740
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
741
+ for (const item of extractUsedTable(table)) this.usedTables.add(item);
742
+ }
743
+ /** @internal */
744
+ getUsedTables() {
745
+ return [...this.usedTables];
746
+ }
747
+ createJoin(joinType) {
748
+ return (table, on) => {
749
+ const baseTableName = this.tableName;
750
+ const tableName = getTableLikeName(table);
751
+ for (const item of extractUsedTable(table)) this.usedTables.add(item);
752
+ if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
753
+ if (!this.isPartialSelect) {
754
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
755
+ if (typeof tableName === "string" && !is(table, SQL)) {
756
+ const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
757
+ this.config.fields[tableName] = selection;
758
+ }
759
+ }
760
+ if (typeof on === "function") on = on(new Proxy(this.config.fields, new SelectionProxyHandler({
761
+ sqlAliasedBehavior: "sql",
762
+ sqlBehavior: "sql"
763
+ })));
764
+ if (!this.config.joins) this.config.joins = [];
765
+ this.config.joins.push({
766
+ on,
767
+ table,
768
+ joinType,
769
+ alias: tableName
770
+ });
771
+ if (typeof tableName === "string") switch (joinType) {
772
+ case "left":
773
+ this.joinsNotNullableMap[tableName] = false;
774
+ break;
775
+ case "right":
776
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
777
+ this.joinsNotNullableMap[tableName] = true;
778
+ break;
779
+ case "cross":
780
+ case "inner":
781
+ this.joinsNotNullableMap[tableName] = true;
782
+ break;
783
+ case "full":
784
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
785
+ this.joinsNotNullableMap[tableName] = false;
786
+ break;
787
+ }
788
+ return this;
789
+ };
790
+ }
791
+ /**
792
+ * Executes a `left join` operation by adding another table to the current query.
793
+ *
794
+ * 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.
795
+ *
796
+ * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
797
+ *
798
+ * @param table the table to join.
799
+ * @param on the `on` clause.
800
+ *
801
+ * @example
802
+ *
803
+ * ```ts
804
+ * // Select all users and their pets
805
+ * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
806
+ * .from(users)
807
+ * .leftJoin(pets, eq(users.id, pets.ownerId))
808
+ *
809
+ * // Select userId and petId
810
+ * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
811
+ * userId: users.id,
812
+ * petId: pets.id,
813
+ * })
814
+ * .from(users)
815
+ * .leftJoin(pets, eq(users.id, pets.ownerId))
816
+ * ```
817
+ */
818
+ leftJoin = this.createJoin("left");
819
+ /**
820
+ * Executes a `right join` operation by adding another table to the current query.
821
+ *
822
+ * 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.
823
+ *
824
+ * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
825
+ *
826
+ * @param table the table to join.
827
+ * @param on the `on` clause.
828
+ *
829
+ * @example
830
+ *
831
+ * ```ts
832
+ * // Select all users and their pets
833
+ * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
834
+ * .from(users)
835
+ * .rightJoin(pets, eq(users.id, pets.ownerId))
836
+ *
837
+ * // Select userId and petId
838
+ * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
839
+ * userId: users.id,
840
+ * petId: pets.id,
841
+ * })
842
+ * .from(users)
843
+ * .rightJoin(pets, eq(users.id, pets.ownerId))
844
+ * ```
845
+ */
846
+ rightJoin = this.createJoin("right");
847
+ /**
848
+ * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
849
+ *
850
+ * 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.
851
+ *
852
+ * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
853
+ *
854
+ * @param table the table to join.
855
+ * @param on the `on` clause.
856
+ *
857
+ * @example
858
+ *
859
+ * ```ts
860
+ * // Select all users and their pets
861
+ * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
862
+ * .from(users)
863
+ * .innerJoin(pets, eq(users.id, pets.ownerId))
864
+ *
865
+ * // Select userId and petId
866
+ * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
867
+ * userId: users.id,
868
+ * petId: pets.id,
869
+ * })
870
+ * .from(users)
871
+ * .innerJoin(pets, eq(users.id, pets.ownerId))
872
+ * ```
873
+ */
874
+ innerJoin = this.createJoin("inner");
875
+ /**
876
+ * Executes a `full join` operation by combining rows from two tables into a new table.
877
+ *
878
+ * 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.
879
+ *
880
+ * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
881
+ *
882
+ * @param table the table to join.
883
+ * @param on the `on` clause.
884
+ *
885
+ * @example
886
+ *
887
+ * ```ts
888
+ * // Select all users and their pets
889
+ * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
890
+ * .from(users)
891
+ * .fullJoin(pets, eq(users.id, pets.ownerId))
892
+ *
893
+ * // Select userId and petId
894
+ * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
895
+ * userId: users.id,
896
+ * petId: pets.id,
897
+ * })
898
+ * .from(users)
899
+ * .fullJoin(pets, eq(users.id, pets.ownerId))
900
+ * ```
901
+ */
902
+ fullJoin = this.createJoin("full");
903
+ /**
904
+ * Executes a `cross join` operation by combining rows from two tables into a new table.
905
+ *
906
+ * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
907
+ *
908
+ * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
909
+ *
910
+ * @param table the table to join.
911
+ *
912
+ * @example
913
+ *
914
+ * ```ts
915
+ * // Select all users, each user with every pet
916
+ * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
917
+ * .from(users)
918
+ * .crossJoin(pets)
919
+ *
920
+ * // Select userId and petId
921
+ * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
922
+ * userId: users.id,
923
+ * petId: pets.id,
924
+ * })
925
+ * .from(users)
926
+ * .crossJoin(pets)
927
+ * ```
928
+ */
929
+ crossJoin = this.createJoin("cross");
930
+ createSetOperator(type, isAll) {
931
+ return (rightSelection) => {
932
+ const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
933
+ 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");
934
+ this.config.setOperators.push({
935
+ type,
936
+ isAll,
937
+ rightSelect
938
+ });
939
+ return this;
940
+ };
941
+ }
942
+ /**
943
+ * Adds `union` set operator to the query.
944
+ *
945
+ * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
946
+ *
947
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
948
+ *
949
+ * @example
950
+ *
951
+ * ```ts
952
+ * // Select all unique names from customers and users tables
953
+ * await db.select({ name: users.name })
954
+ * .from(users)
955
+ * .union(
956
+ * db.select({ name: customers.name }).from(customers)
957
+ * );
958
+ * // or
959
+ * import { union } from 'drizzle-orm/sqlite-core'
960
+ *
961
+ * await union(
962
+ * db.select({ name: users.name }).from(users),
963
+ * db.select({ name: customers.name }).from(customers)
964
+ * );
965
+ * ```
966
+ */
967
+ union = this.createSetOperator("union", false);
968
+ /**
969
+ * Adds `union all` set operator to the query.
970
+ *
971
+ * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
972
+ *
973
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
974
+ *
975
+ * @example
976
+ *
977
+ * ```ts
978
+ * // Select all transaction ids from both online and in-store sales
979
+ * await db.select({ transaction: onlineSales.transactionId })
980
+ * .from(onlineSales)
981
+ * .unionAll(
982
+ * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
983
+ * );
984
+ * // or
985
+ * import { unionAll } from 'drizzle-orm/sqlite-core'
986
+ *
987
+ * await unionAll(
988
+ * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
989
+ * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
990
+ * );
991
+ * ```
992
+ */
993
+ unionAll = this.createSetOperator("union", true);
994
+ /**
995
+ * Adds `intersect` set operator to the query.
996
+ *
997
+ * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
998
+ *
999
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
1000
+ *
1001
+ * @example
1002
+ *
1003
+ * ```ts
1004
+ * // Select course names that are offered in both departments A and B
1005
+ * await db.select({ courseName: depA.courseName })
1006
+ * .from(depA)
1007
+ * .intersect(
1008
+ * db.select({ courseName: depB.courseName }).from(depB)
1009
+ * );
1010
+ * // or
1011
+ * import { intersect } from 'drizzle-orm/sqlite-core'
1012
+ *
1013
+ * await intersect(
1014
+ * db.select({ courseName: depA.courseName }).from(depA),
1015
+ * db.select({ courseName: depB.courseName }).from(depB)
1016
+ * );
1017
+ * ```
1018
+ */
1019
+ intersect = this.createSetOperator("intersect", false);
1020
+ /**
1021
+ * Adds `except` set operator to the query.
1022
+ *
1023
+ * 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.
1024
+ *
1025
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
1026
+ *
1027
+ * @example
1028
+ *
1029
+ * ```ts
1030
+ * // Select all courses offered in department A but not in department B
1031
+ * await db.select({ courseName: depA.courseName })
1032
+ * .from(depA)
1033
+ * .except(
1034
+ * db.select({ courseName: depB.courseName }).from(depB)
1035
+ * );
1036
+ * // or
1037
+ * import { except } from 'drizzle-orm/sqlite-core'
1038
+ *
1039
+ * await except(
1040
+ * db.select({ courseName: depA.courseName }).from(depA),
1041
+ * db.select({ courseName: depB.courseName }).from(depB)
1042
+ * );
1043
+ * ```
1044
+ */
1045
+ except = this.createSetOperator("except", false);
1046
+ /** @internal */
1047
+ addSetOperators(setOperators) {
1048
+ this.config.setOperators.push(...setOperators);
1049
+ return this;
1050
+ }
1051
+ /**
1052
+ * Adds a `where` clause to the query.
1053
+ *
1054
+ * Calling this method will select only those rows that fulfill a specified condition.
1055
+ *
1056
+ * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
1057
+ *
1058
+ * @param where the `where` clause.
1059
+ *
1060
+ * @example
1061
+ * You can use conditional operators and `sql function` to filter the rows to be selected.
1062
+ *
1063
+ * ```ts
1064
+ * // Select all cars with green color
1065
+ * await db.select().from(cars).where(eq(cars.color, 'green'));
1066
+ * // or
1067
+ * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
1068
+ * ```
1069
+ *
1070
+ * You can logically combine conditional operators with `and()` and `or()` operators:
1071
+ *
1072
+ * ```ts
1073
+ * // Select all BMW cars with a green color
1074
+ * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
1075
+ *
1076
+ * // Select all cars with the green or blue color
1077
+ * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
1078
+ * ```
1079
+ */
1080
+ where(where) {
1081
+ if (typeof where === "function") where = where(new Proxy(this.config.fields, new SelectionProxyHandler({
1082
+ sqlAliasedBehavior: "sql",
1083
+ sqlBehavior: "sql"
1084
+ })));
1085
+ this.config.where = where;
1086
+ return this;
1087
+ }
1088
+ /**
1089
+ * Adds a `having` clause to the query.
1090
+ *
1091
+ * 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.
1092
+ *
1093
+ * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
1094
+ *
1095
+ * @param having the `having` clause.
1096
+ *
1097
+ * @example
1098
+ *
1099
+ * ```ts
1100
+ * // Select all brands with more than one car
1101
+ * await db.select({
1102
+ * brand: cars.brand,
1103
+ * count: sql<number>`cast(count(${cars.id}) as int)`,
1104
+ * })
1105
+ * .from(cars)
1106
+ * .groupBy(cars.brand)
1107
+ * .having(({ count }) => gt(count, 1));
1108
+ * ```
1109
+ */
1110
+ having(having) {
1111
+ if (typeof having === "function") having = having(new Proxy(this.config.fields, new SelectionProxyHandler({
1112
+ sqlAliasedBehavior: "sql",
1113
+ sqlBehavior: "sql"
1114
+ })));
1115
+ this.config.having = having;
1116
+ return this;
1117
+ }
1118
+ groupBy(...columns) {
1119
+ if (typeof columns[0] === "function") {
1120
+ const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({
1121
+ sqlAliasedBehavior: "alias",
1122
+ sqlBehavior: "sql"
1123
+ })));
1124
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
1125
+ } else this.config.groupBy = columns;
1126
+ return this;
1127
+ }
1128
+ orderBy(...columns) {
1129
+ if (typeof columns[0] === "function") {
1130
+ const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({
1131
+ sqlAliasedBehavior: "alias",
1132
+ sqlBehavior: "sql"
1133
+ })));
1134
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
1135
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;
1136
+ else this.config.orderBy = orderByArray;
1137
+ } else {
1138
+ const orderByArray = columns;
1139
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;
1140
+ else this.config.orderBy = orderByArray;
1141
+ }
1142
+ return this;
1143
+ }
1144
+ /**
1145
+ * Adds a `limit` clause to the query.
1146
+ *
1147
+ * Calling this method will set the maximum number of rows that will be returned by this query.
1148
+ *
1149
+ * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
1150
+ *
1151
+ * @param limit the `limit` clause.
1152
+ *
1153
+ * @example
1154
+ *
1155
+ * ```ts
1156
+ * // Get the first 10 people from this query.
1157
+ * await db.select().from(people).limit(10);
1158
+ * ```
1159
+ */
1160
+ limit(limit) {
1161
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).limit = limit;
1162
+ else this.config.limit = limit;
1163
+ return this;
1164
+ }
1165
+ /**
1166
+ * Adds an `offset` clause to the query.
1167
+ *
1168
+ * Calling this method will skip a number of rows when returning results from this query.
1169
+ *
1170
+ * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
1171
+ *
1172
+ * @param offset the `offset` clause.
1173
+ *
1174
+ * @example
1175
+ *
1176
+ * ```ts
1177
+ * // Get the 10th-20th people from this query.
1178
+ * await db.select().from(people).offset(10).limit(10);
1179
+ * ```
1180
+ */
1181
+ offset(offset) {
1182
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).offset = offset;
1183
+ else this.config.offset = offset;
1184
+ return this;
1185
+ }
1186
+ /** @internal */
1187
+ getSQL() {
1188
+ return this.dialect.buildSelectQuery(this.config);
1189
+ }
1190
+ toSQL() {
1191
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
1192
+ return rest;
1193
+ }
1194
+ as(alias) {
1195
+ const usedTables = [];
1196
+ usedTables.push(...extractUsedTable(this.config.table));
1197
+ if (this.config.joins) for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
1198
+ return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), new SelectionProxyHandler({
1199
+ alias,
1200
+ sqlAliasedBehavior: "alias",
1201
+ sqlBehavior: "error"
1202
+ }));
1203
+ }
1204
+ /** @internal */
1205
+ getSelectedFields() {
1206
+ return new Proxy(this.config.fields, new SelectionProxyHandler({
1207
+ alias: this.tableName,
1208
+ sqlAliasedBehavior: "alias",
1209
+ sqlBehavior: "error"
1210
+ }));
1211
+ }
1212
+ $dynamic() {
1213
+ return this;
1214
+ }
1215
+ };
1216
+ var SQLiteSelectBase = class extends SQLiteSelectQueryBuilderBase {
1217
+ static [entityKind] = "SQLiteSelect";
1218
+ /** @internal */
1219
+ _prepare(isOneTimeQuery = true) {
1220
+ if (!this.session) throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
1221
+ const fieldsList = orderSelectedFields(this.config.fields);
1222
+ const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), fieldsList, "all", true, void 0, {
1223
+ type: "select",
1224
+ tables: [...this.usedTables]
1225
+ }, this.cacheConfig);
1226
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
1227
+ return query;
1228
+ }
1229
+ $withCache(config) {
1230
+ this.cacheConfig = config === void 0 ? {
1231
+ config: {},
1232
+ enable: true,
1233
+ autoInvalidate: true
1234
+ } : config === false ? { enable: false } : {
1235
+ enable: true,
1236
+ autoInvalidate: true,
1237
+ ...config
1238
+ };
1239
+ return this;
1240
+ }
1241
+ prepare() {
1242
+ return this._prepare(false);
1243
+ }
1244
+ run = (placeholderValues) => {
1245
+ return this._prepare().run(placeholderValues);
1246
+ };
1247
+ all = (placeholderValues) => {
1248
+ return this._prepare().all(placeholderValues);
1249
+ };
1250
+ get = (placeholderValues) => {
1251
+ return this._prepare().get(placeholderValues);
1252
+ };
1253
+ values = (placeholderValues) => {
1254
+ return this._prepare().values(placeholderValues);
1255
+ };
1256
+ async execute() {
1257
+ return this.all();
1258
+ }
1259
+ };
1260
+ applyMixins(SQLiteSelectBase, [QueryPromise]);
1261
+ function createSetOperator(type, isAll) {
1262
+ return (leftSelect, rightSelect, ...restSelects) => {
1263
+ const setOperators = [rightSelect, ...restSelects].map((select) => ({
1264
+ type,
1265
+ isAll,
1266
+ rightSelect: select
1267
+ }));
1268
+ 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");
1269
+ return leftSelect.addSetOperators(setOperators);
1270
+ };
1271
+ }
1272
+ const getSQLiteSetOperators = () => ({
1273
+ union,
1274
+ unionAll,
1275
+ intersect,
1276
+ except
1277
+ });
1278
+ const union = createSetOperator("union", false);
1279
+ const unionAll = createSetOperator("union", true);
1280
+ const intersect = createSetOperator("intersect", false);
1281
+ const except = createSetOperator("except", false);
1282
+ var QueryBuilder = class {
1283
+ static [entityKind] = "SQLiteQueryBuilder";
1284
+ dialect;
1285
+ dialectConfig;
1286
+ constructor(dialect) {
1287
+ this.dialect = is(dialect, SQLiteDialect) ? dialect : void 0;
1288
+ this.dialectConfig = is(dialect, SQLiteDialect) ? void 0 : dialect;
1289
+ }
1290
+ $with = (alias, selection) => {
1291
+ const queryBuilder = this;
1292
+ const as = (qb) => {
1293
+ if (typeof qb === "function") qb = qb(queryBuilder);
1294
+ return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({
1295
+ alias,
1296
+ sqlAliasedBehavior: "alias",
1297
+ sqlBehavior: "error"
1298
+ }));
1299
+ };
1300
+ return { as };
1301
+ };
1302
+ with(...queries) {
1303
+ const self = this;
1304
+ function select(fields) {
1305
+ return new SQLiteSelectBuilder({
1306
+ fields: fields ?? void 0,
1307
+ session: void 0,
1308
+ dialect: self.getDialect(),
1309
+ withList: queries
1310
+ });
1311
+ }
1312
+ function selectDistinct(fields) {
1313
+ return new SQLiteSelectBuilder({
1314
+ fields: fields ?? void 0,
1315
+ session: void 0,
1316
+ dialect: self.getDialect(),
1317
+ withList: queries,
1318
+ distinct: true
1319
+ });
1320
+ }
1321
+ return {
1322
+ select,
1323
+ selectDistinct
1324
+ };
1325
+ }
1326
+ select(fields) {
1327
+ return new SQLiteSelectBuilder({
1328
+ fields: fields ?? void 0,
1329
+ session: void 0,
1330
+ dialect: this.getDialect()
1331
+ });
1332
+ }
1333
+ selectDistinct(fields) {
1334
+ return new SQLiteSelectBuilder({
1335
+ fields: fields ?? void 0,
1336
+ session: void 0,
1337
+ dialect: this.getDialect(),
1338
+ distinct: true
1339
+ });
1340
+ }
1341
+ getDialect() {
1342
+ if (!this.dialect) this.dialect = new SQLiteSyncDialect(this.dialectConfig);
1343
+ return this.dialect;
1344
+ }
1345
+ };
1346
+ //#endregion
1347
+ export { SQLiteTable as a, getTableConfig as c, SQLiteSyncDialect as i, SQLiteAsyncDialect as n, SQLiteViewBase as o, SQLiteSelectBuilder as r, extractUsedTable as s, QueryBuilder as t };