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