@type32/tauri-sqlite-orm 0.2.12 → 0.2.15

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.
package/dist/index.mjs CHANGED
@@ -1,174 +1,81 @@
1
- // src/builders/query-base.ts
2
- var BaseQueryBuilder = class {
1
+ // src/orm.ts
2
+ import { Kysely as Kysely4, sql as kyselySql } from "kysely";
3
+
4
+ // src/dialect.ts
5
+ import {
6
+ CompiledQuery,
7
+ SqliteAdapter,
8
+ SqliteIntrospector,
9
+ SqliteQueryCompiler
10
+ } from "kysely";
11
+ var TauriConnection = class {
3
12
  constructor(db) {
4
13
  this.db = db;
5
14
  }
6
- query = "";
7
- params = [];
8
- where(condition) {
9
- this.query += ` WHERE ${condition.sql}`;
10
- this.params.push(...condition.params);
11
- return this;
12
- }
13
- orderBy(column, direction = "ASC") {
14
- if ("sql" in column) {
15
- this.query += ` ORDER BY ${column.sql} ${direction}`;
16
- this.params.push(...column.params);
17
- } else {
18
- this.query += ` ORDER BY ${column._.name} ${direction}`;
15
+ async executeQuery(compiledQuery) {
16
+ const { sql: sql6, parameters } = compiledQuery;
17
+ const params = parameters;
18
+ const trimmed = sql6.trimStart();
19
+ const isSelect = /^\s*(SELECT|WITH|PRAGMA)/i.test(trimmed);
20
+ const hasReturning = /\bRETURNING\b/i.test(sql6);
21
+ if (isSelect || hasReturning) {
22
+ const rows = await this.db.select(sql6, params);
23
+ return { rows };
19
24
  }
20
- return this;
21
- }
22
- limit(count2) {
23
- this.query += ` LIMIT ${count2}`;
24
- return this;
25
- }
26
- offset(count2) {
27
- this.query += ` OFFSET ${count2}`;
28
- return this;
29
- }
30
- build() {
25
+ const result = await this.db.execute(sql6, params);
31
26
  return {
32
- sql: this.query,
33
- params: this.params
27
+ rows: [],
28
+ insertId: BigInt(Math.round(result.lastInsertId ?? 0)),
29
+ numAffectedRows: BigInt(result.rowsAffected ?? 0)
34
30
  };
35
31
  }
36
- toSQL() {
37
- return this.build();
32
+ async *streamQuery(_compiledQuery) {
33
+ throw new Error("Streaming queries are not supported by @tauri-apps/plugin-sql");
38
34
  }
39
35
  };
40
-
41
- // src/operators.ts
42
- var eq = (column, value, tableAlias) => {
43
- const columnName = tableAlias ? `${tableAlias}.${column._.name}` : column._.name;
44
- return {
45
- sql: `${columnName} = ?`,
46
- params: [value]
47
- };
48
- };
49
- var ne = (column, value, tableAlias) => {
50
- const columnName = tableAlias ? `${tableAlias}.${column._.name}` : column._.name;
51
- return {
52
- sql: `${columnName} != ?`,
53
- params: [value]
54
- };
55
- };
56
- var and = (...conditions) => ({
57
- sql: conditions.map((c) => `(${c.sql})`).join(" AND "),
58
- params: conditions.flatMap((c) => c.params)
59
- });
60
- var or = (...conditions) => ({
61
- sql: conditions.map((c) => `(${c.sql})`).join(" OR "),
62
- params: conditions.flatMap((c) => c.params)
63
- });
64
- var not = (condition) => ({
65
- sql: `NOT (${condition.sql})`,
66
- params: condition.params
67
- });
68
- var gt = (column, value) => ({
69
- sql: `${column._.name} > ?`,
70
- params: [value]
71
- });
72
- var gte = (column, value) => ({
73
- sql: `${column._.name} >= ?`,
74
- params: [value]
75
- });
76
- var lt = (column, value) => ({
77
- sql: `${column._.name} < ?`,
78
- params: [value]
79
- });
80
- var lte = (column, value) => ({
81
- sql: `${column._.name} <= ?`,
82
- params: [value]
83
- });
84
- var like = (column, pattern) => ({
85
- sql: `${column._.name} LIKE ?`,
86
- params: [pattern]
87
- });
88
- var ilike = (column, pattern) => ({
89
- sql: `${column._.name} LIKE ? COLLATE NOCASE`,
90
- params: [pattern]
91
- });
92
- var startsWith = (column, value) => ({
93
- sql: `${column._.name} LIKE ?`,
94
- params: [`${value}%`]
95
- });
96
- var endsWith = (column, value) => ({
97
- sql: `${column._.name} LIKE ?`,
98
- params: [`%${value}`]
99
- });
100
- var contains = (column, value) => ({
101
- sql: `${column._.name} LIKE ?`,
102
- params: [`%${value}%`]
103
- });
104
- var isNull = (column) => ({
105
- sql: `${column._.name} IS NULL`,
106
- params: []
107
- });
108
- var isNotNull = (column) => ({
109
- sql: `${column._.name} IS NOT NULL`,
110
- params: []
111
- });
112
- var exists = (subquery2) => ({
113
- sql: `EXISTS (${subquery2.sql})`,
114
- params: subquery2.params
115
- });
116
- var notExists = (subquery2) => ({
117
- sql: `NOT EXISTS (${subquery2.sql})`,
118
- params: subquery2.params
119
- });
120
- var eqSubquery = (column, subquery2) => ({
121
- sql: `${column._.name} = ${subquery2.sql}`,
122
- params: subquery2.params
123
- });
124
- var neSubquery = (column, subquery2) => ({
125
- sql: `${column._.name} != ${subquery2.sql}`,
126
- params: subquery2.params
127
- });
128
- var gtSubquery = (column, subquery2) => ({
129
- sql: `${column._.name} > ${subquery2.sql}`,
130
- params: subquery2.params
131
- });
132
- var gteSubquery = (column, subquery2) => ({
133
- sql: `${column._.name} >= ${subquery2.sql}`,
134
- params: subquery2.params
135
- });
136
- var ltSubquery = (column, subquery2) => ({
137
- sql: `${column._.name} < ${subquery2.sql}`,
138
- params: subquery2.params
139
- });
140
- var lteSubquery = (column, subquery2) => ({
141
- sql: `${column._.name} <= ${subquery2.sql}`,
142
- params: subquery2.params
143
- });
144
- var inArray = (column, values) => {
145
- if ("_isSubquery" in values && values._isSubquery) {
146
- return {
147
- sql: `${column._.name} IN ${values.sql}`,
148
- params: values.params
149
- };
36
+ var TauriDriver = class {
37
+ constructor(db) {
38
+ this.db = db;
39
+ }
40
+ async init() {
41
+ }
42
+ async acquireConnection() {
43
+ return new TauriConnection(this.db);
44
+ }
45
+ async beginTransaction(conn, _settings) {
46
+ await conn.executeQuery(CompiledQuery.raw("BEGIN"));
47
+ }
48
+ async commitTransaction(conn) {
49
+ await conn.executeQuery(CompiledQuery.raw("COMMIT"));
50
+ }
51
+ async rollbackTransaction(conn) {
52
+ await conn.executeQuery(CompiledQuery.raw("ROLLBACK"));
53
+ }
54
+ async releaseConnection(_conn) {
55
+ }
56
+ async destroy() {
150
57
  }
151
- return {
152
- sql: `${column._.name} IN (${values.map(() => "?").join(",")})`,
153
- params: values
154
- };
155
58
  };
156
- var notIn = (column, values) => {
157
- if ("_isSubquery" in values && values._isSubquery) {
158
- return {
159
- sql: `${column._.name} NOT IN ${values.sql}`,
160
- params: values.params
161
- };
59
+ var TauriDialect = class {
60
+ constructor(db) {
61
+ this.db = db;
62
+ }
63
+ createAdapter() {
64
+ return new SqliteAdapter();
65
+ }
66
+ createDriver() {
67
+ return new TauriDriver(this.db);
68
+ }
69
+ createIntrospector(db) {
70
+ return new SqliteIntrospector(db);
71
+ }
72
+ createQueryCompiler() {
73
+ return new SqliteQueryCompiler();
162
74
  }
163
- return {
164
- sql: `${column._.name} NOT IN (${values.map(() => "?").join(",")})`,
165
- params: values
166
- };
167
75
  };
168
- var between = (column, min2, max2) => ({
169
- sql: `${column._.name} BETWEEN ? AND ?`,
170
- params: [min2, max2]
171
- });
76
+
77
+ // src/builders/select.ts
78
+ import { sql } from "kysely";
172
79
 
173
80
  // src/serialization.ts
174
81
  function serializeValue(value, column) {
@@ -272,71 +179,116 @@ function deserializeValue(value, column) {
272
179
  }
273
180
 
274
181
  // src/builders/select.ts
275
- var SelectQueryBuilder = class extends BaseQueryBuilder {
276
- constructor(db, table, columns) {
277
- super(db);
278
- this.table = table;
279
- this.columns = columns;
280
- this.selectedTableAlias = table._.name;
281
- const selected = columns ? columns.map((c) => this.table._.columns[c]) : Object.values(this.table._.columns);
282
- this.selectedColumns = selected.map(
283
- (col) => `${this.selectedTableAlias}.${col._.name} AS "${this.selectedTableAlias}.${col._.name}"`
182
+ function getDbNameToTsName(table) {
183
+ const map = {};
184
+ for (const [tsName, col] of Object.entries(table._.columns)) {
185
+ map[col._.name] = tsName;
186
+ }
187
+ return map;
188
+ }
189
+ function normalizeRowKey(key) {
190
+ if (key.startsWith('"') && key.endsWith('"')) {
191
+ return key.slice(1, -1);
192
+ }
193
+ return key;
194
+ }
195
+ function resolveRelationColumns(table, include) {
196
+ const allEntries = Object.entries(table._.columns);
197
+ if (include === true || typeof include !== "object") {
198
+ return allEntries.map(([, col]) => col);
199
+ }
200
+ const cols = include.columns;
201
+ if (!cols) {
202
+ return allEntries.map(([, col]) => col);
203
+ }
204
+ const names = Array.isArray(cols) ? cols : Object.entries(cols).filter(([, v]) => v).map(([k]) => k);
205
+ const pkNames = allEntries.filter(([, c]) => c.options.primaryKey).map(([k]) => k);
206
+ const combined = /* @__PURE__ */ new Set([...names, ...pkNames]);
207
+ return allEntries.filter(([tsName]) => combined.has(tsName)).map(([, col]) => col);
208
+ }
209
+ var SelectQueryBuilder = class {
210
+ constructor(kysely, table, columns) {
211
+ this.kysely = kysely;
212
+ this._table = table;
213
+ this._columns = columns;
214
+ const selected = columns ? columns.map((c) => table._.columns[c]) : Object.values(table._.columns);
215
+ const colSelections = selected.map(
216
+ (col) => `${table._.name}.${col._.name} as "${table._.name}.${col._.name}"`
284
217
  );
285
- this.query = `FROM ${table._.name} ${this.selectedTableAlias}`;
286
- }
287
- isDistinct = false;
288
- groupByColumns = [];
289
- havingCondition = null;
290
- joins = [];
291
- includeRelations = {};
292
- selectedTableAlias;
293
- selectedColumns = [];
218
+ this._includedColumnAliases = colSelections;
219
+ this._builder = kysely.selectFrom(table._.name).select(colSelections);
220
+ }
221
+ _builder;
222
+ _table;
223
+ _columns;
224
+ _includeRelations = {};
225
+ _manualJoins = [];
226
+ _isDistinct = false;
227
+ _includedColumnAliases = [];
294
228
  distinct() {
295
- this.isDistinct = true;
229
+ this._isDistinct = true;
230
+ this._builder = this._builder.distinct();
231
+ return this;
232
+ }
233
+ where(condition) {
234
+ this._builder = this._builder.where(condition);
235
+ return this;
236
+ }
237
+ orderBy(column, direction = "asc") {
238
+ if ("toOperationNode" in column) {
239
+ this._builder = this._builder.orderBy(column, direction);
240
+ } else {
241
+ this._builder = this._builder.orderBy(
242
+ sql.ref(column._.name),
243
+ direction
244
+ );
245
+ }
246
+ return this;
247
+ }
248
+ limit(count2) {
249
+ this._builder = this._builder.limit(count2);
250
+ return this;
251
+ }
252
+ offset(count2) {
253
+ this._builder = this._builder.offset(count2);
296
254
  return this;
297
255
  }
298
256
  groupBy(...columns) {
299
- this.groupByColumns.push(...columns);
300
- const columnNames = columns.map((col) => `${this.selectedTableAlias}.${col._.name}`).join(", ");
301
- this.query += ` GROUP BY ${columnNames}`;
257
+ for (const col of columns) {
258
+ this._builder = this._builder.groupBy(
259
+ sql`${sql.ref(this._table._.name)}.${sql.ref(col._.name)}`
260
+ );
261
+ }
302
262
  return this;
303
263
  }
304
264
  having(condition) {
305
- this.havingCondition = condition;
306
- this.query += ` HAVING ${condition.sql}`;
307
- this.params.push(...condition.params);
265
+ this._builder = this._builder.having(condition);
308
266
  return this;
309
267
  }
310
268
  leftJoin(table, condition, alias2) {
311
- this.joins.push({ type: "LEFT", table, condition, alias: alias2 });
312
- const aliasedColumns = Object.values(table._.columns).map(
313
- (col) => `${alias2}.${col._.name} AS "${alias2}.${col._.name}"`
269
+ this._manualJoins.push({ type: "LEFT", table, condition, alias: alias2 });
270
+ const aliasedCols = Object.values(table._.columns).map(
271
+ (col) => `${alias2}.${col._.name} as "${alias2}.${col._.name}"`
314
272
  );
315
- this.selectedColumns.push(...aliasedColumns);
273
+ this._builder = this._builder.leftJoin(`${table._.name} as ${alias2}`, (join) => join.on(condition)).select(aliasedCols);
316
274
  return this;
317
275
  }
318
276
  innerJoin(table, condition, alias2) {
319
- this.joins.push({ type: "INNER", table, condition, alias: alias2 });
320
- const aliasedColumns = Object.values(table._.columns).map(
321
- (col) => `${alias2}.${col._.name} AS "${alias2}.${col._.name}"`
277
+ this._manualJoins.push({ type: "INNER", table, condition, alias: alias2 });
278
+ const aliasedCols = Object.values(table._.columns).map(
279
+ (col) => `${alias2}.${col._.name} as "${alias2}.${col._.name}"`
322
280
  );
323
- this.selectedColumns.push(...aliasedColumns);
281
+ this._builder = this._builder.innerJoin(`${table._.name} as ${alias2}`, (join) => join.on(condition)).select(aliasedCols);
324
282
  return this;
325
283
  }
326
284
  include(relations2) {
327
- this.includeRelations = { ...this.includeRelations, ...relations2 };
285
+ this._includeRelations = { ...this._includeRelations, ...relations2 };
328
286
  return this;
329
287
  }
330
- buildJoins() {
331
- let sql2 = "";
332
- const params = [];
333
- for (const join of this.joins) {
334
- sql2 += ` ${join.type} JOIN ${join.table._.name} ${join.alias} ON ${join.condition.sql}`;
335
- params.push(...join.condition.params);
336
- }
288
+ applyIncludes() {
337
289
  const processRelations = (parentTable, parentAlias, relations2, depth = 0) => {
338
290
  if (depth > 10) {
339
- console.warn("[Tauri-ORM] Maximum relation depth (10) exceeded. Skipping deeper relations.");
291
+ console.warn("[Tauri-ORM] Maximum relation depth (10) exceeded.");
340
292
  return;
341
293
  }
342
294
  for (const [relationName, include] of Object.entries(relations2)) {
@@ -344,78 +296,43 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
344
296
  const relation = parentTable.relations[relationName];
345
297
  if (!relation) {
346
298
  console.warn(
347
- `[Tauri-ORM] Relation "${relationName}" not found on table "${parentTable._.name}". Skipping include.`
299
+ `[Tauri-ORM] Relation "${relationName}" not found on table "${parentTable._.name}". Skipping.`
348
300
  );
349
301
  continue;
350
302
  }
351
303
  const foreignTable = relation.foreignTable;
352
304
  const foreignAlias = `${parentAlias}_${relationName}`;
353
- const aliasedColumns = Object.values(foreignTable._.columns).map(
354
- (col) => `${foreignAlias}.${col._.name} AS "${foreignAlias}.${col._.name}"`
305
+ const selectedCols = resolveRelationColumns(foreignTable, include);
306
+ const aliasedCols = selectedCols.map(
307
+ (col) => `${foreignAlias}.${col._.name} as "${foreignAlias}.${col._.name}"`
355
308
  );
356
- this.selectedColumns.push(...aliasedColumns);
357
309
  if (relation.type === "one" && relation.fields && relation.references) {
358
- const conditions = relation.fields.map((field, i) => {
359
- const localColumn = `${parentAlias}.${field._.name}`;
360
- const foreignColumn = `${foreignAlias}.${relation.references[i]._.name}`;
361
- return {
362
- sql: `${localColumn} = ${foreignColumn}`,
363
- params: []
364
- };
365
- });
366
- const condition = conditions.length > 1 ? and(...conditions) : conditions[0];
367
- sql2 += ` LEFT JOIN ${foreignTable._.name} ${foreignAlias} ON ${condition.sql}`;
368
- params.push(...condition.params);
310
+ const onCondition = sql`${sql.join(
311
+ relation.fields.map(
312
+ (field, i) => sql`${sql.ref(`${parentAlias}.${field._.name}`)} = ${sql.ref(`${foreignAlias}.${relation.references[i]._.name}`)}`
313
+ ),
314
+ sql` AND `
315
+ )}`;
316
+ this._builder = this._builder.leftJoin(
317
+ `${foreignTable._.name} as ${foreignAlias}`,
318
+ (join) => join.on(onCondition)
319
+ ).select(aliasedCols);
369
320
  } else if (relation.type === "many") {
370
321
  const refRelation = Object.entries(foreignTable.relations).find(
371
- ([_, r]) => r.foreignTable === parentTable
322
+ ([, r]) => r.foreignTable === parentTable
372
323
  );
373
324
  if (refRelation && refRelation[1].fields && refRelation[1].references) {
374
- const [_, relationConfig] = refRelation;
375
- const conditions = relationConfig.fields.map((field, i) => {
376
- const localColumn = `${foreignAlias}.${field._.name}`;
377
- const foreignColumn = `${parentAlias}.${relationConfig.references[i]._.name}`;
378
- return {
379
- sql: `${localColumn} = ${foreignColumn}`,
380
- params: []
381
- };
382
- });
383
- const condition = conditions.length > 1 ? and(...conditions) : conditions[0];
384
- sql2 += ` LEFT JOIN ${foreignTable._.name} ${foreignAlias} ON ${condition.sql}`;
385
- params.push(...condition.params);
386
- }
387
- } else if (relation.type === "manyToMany" && relation.junctionTable && relation.junctionFields && relation.junctionReferences) {
388
- const junctionTable = relation.junctionTable;
389
- const junctionAlias = `${foreignAlias}_junction`;
390
- const parentTablePks = Object.values(parentTable._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
391
- if (parentTablePks.length > 0 && relation.junctionFields.length > 0) {
392
- const junctionConditions = relation.junctionFields.map((field, i) => {
393
- const parentPk = parentTablePks[i] || parentTablePks[0];
394
- const localColumn = `${parentAlias}.${parentPk}`;
395
- const junctionColumn = `${junctionAlias}.${field._.name}`;
396
- return {
397
- sql: `${localColumn} = ${junctionColumn}`,
398
- params: []
399
- };
400
- });
401
- const junctionCondition = junctionConditions.length > 1 ? and(...junctionConditions) : junctionConditions[0];
402
- sql2 += ` LEFT JOIN ${junctionTable._.name} ${junctionAlias} ON ${junctionCondition.sql}`;
403
- params.push(...junctionCondition.params);
404
- const foreignTablePks = Object.values(foreignTable._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
405
- if (foreignTablePks.length > 0 && relation.junctionReferences.length > 0) {
406
- const foreignConditions = relation.junctionReferences.map((field, i) => {
407
- const foreignPk = foreignTablePks[i] || foreignTablePks[0];
408
- const junctionColumn = `${junctionAlias}.${field._.name}`;
409
- const foreignColumn = `${foreignAlias}.${foreignPk}`;
410
- return {
411
- sql: `${junctionColumn} = ${foreignColumn}`,
412
- params: []
413
- };
414
- });
415
- const foreignCondition = foreignConditions.length > 1 ? and(...foreignConditions) : foreignConditions[0];
416
- sql2 += ` LEFT JOIN ${foreignTable._.name} ${foreignAlias} ON ${foreignCondition.sql}`;
417
- params.push(...foreignCondition.params);
418
- }
325
+ const [, relationConfig] = refRelation;
326
+ const onCondition = sql`${sql.join(
327
+ relationConfig.fields.map(
328
+ (field, i) => sql`${sql.ref(`${foreignAlias}.${field._.name}`)} = ${sql.ref(`${parentAlias}.${relationConfig.references[i]._.name}`)}`
329
+ ),
330
+ sql` AND `
331
+ )}`;
332
+ this._builder = this._builder.leftJoin(
333
+ `${foreignTable._.name} as ${foreignAlias}`,
334
+ (join) => join.on(onCondition)
335
+ ).select(aliasedCols);
419
336
  }
420
337
  }
421
338
  if (typeof include === "object" && include.with) {
@@ -423,178 +340,159 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
423
340
  }
424
341
  }
425
342
  };
426
- processRelations(this.table, this.selectedTableAlias, this.includeRelations, 0);
427
- return { sql: sql2, params };
343
+ processRelations(this._table, this._table._.name, this._includeRelations, 0);
428
344
  }
429
- // Enhanced execute method that handles relation data mapping
430
345
  async execute() {
431
- const { sql: joinSql, params: joinParams } = this.buildJoins();
432
- const distinct = this.isDistinct ? "DISTINCT " : "";
433
- this.query = `SELECT ${distinct}${this.selectedColumns.join(", ")} ${this.query}`;
434
- this.query += joinSql;
435
- this.params.push(...joinParams);
436
- const { sql: sql2, params } = this.build();
437
- const rawResults = await this.db.select(sql2, params);
438
- const hasIncludes = Object.values(this.includeRelations).some((i) => i);
346
+ this.applyIncludes();
347
+ const rawResults = await this._builder.execute();
348
+ const hasIncludes = Object.values(this._includeRelations).some((i) => i);
439
349
  if (hasIncludes) {
440
350
  return this.processRelationResults(rawResults);
441
351
  }
442
- const hasJoins = this.joins.length > 0;
443
- if (hasJoins) {
352
+ const hasManualJoins = this._manualJoins.length > 0;
353
+ if (hasManualJoins) {
444
354
  return rawResults;
445
355
  }
446
- const prefix = `${this.selectedTableAlias}.`;
356
+ const prefix = `${this._table._.name}.`;
357
+ const dbNameToTs = getDbNameToTsName(this._table);
447
358
  return rawResults.map((row) => {
448
- const newRow = {};
359
+ const out = {};
449
360
  for (const key in row) {
450
- const columnName = key.startsWith(prefix) ? key.substring(prefix.length) : key;
451
- const column = this.table._.columns[columnName];
452
- if (column) {
453
- newRow[columnName] = deserializeValue(row[key], column);
454
- } else {
455
- newRow[columnName] = row[key];
456
- }
361
+ const normKey = normalizeRowKey(key);
362
+ const dbColName = normKey.startsWith(prefix) ? normKey.slice(prefix.length) : normKey;
363
+ const tsName = dbNameToTs[dbColName] ?? dbColName;
364
+ const column = this._table._.columns[tsName];
365
+ out[tsName] = column ? deserializeValue(row[key], column) : row[key];
457
366
  }
458
- return newRow;
367
+ return out;
459
368
  });
460
369
  }
461
370
  processRelationResults(rawResults) {
462
371
  if (!rawResults.length) return [];
463
- const mainTablePks = Object.values(this.table._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
464
- if (mainTablePks.length === 0) {
465
- return rawResults;
466
- }
372
+ const mainTablePks = Object.values(this._table._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
373
+ if (mainTablePks.length === 0) return rawResults;
467
374
  const groupedResults = /* @__PURE__ */ new Map();
468
375
  const parseRelationPath = (tableAlias, baseAlias) => {
469
- if (!tableAlias.startsWith(baseAlias + "_")) {
470
- return [];
471
- }
472
- const path = tableAlias.substring(baseAlias.length + 1);
473
- return path.split("_");
376
+ if (!tableAlias.startsWith(baseAlias + "_")) return [];
377
+ return tableAlias.slice(baseAlias.length + 1).split("_");
474
378
  };
475
- const setNestedValue = (obj, path, value, columnName) => {
476
- let current = obj;
379
+ const setNestedValue = (obj, path, columnName, value) => {
380
+ let cur = obj;
477
381
  for (let i = 0; i < path.length; i++) {
478
382
  const key = path[i];
479
383
  if (i === path.length - 1) {
480
- if (!current[key]) current[key] = {};
481
- current[key][columnName] = value;
384
+ if (!cur[key]) cur[key] = {};
385
+ cur[key][columnName] = value;
482
386
  } else {
483
- if (!current[key]) current[key] = {};
484
- current = current[key];
387
+ if (!cur[key]) cur[key] = {};
388
+ cur = cur[key];
485
389
  }
486
390
  }
487
391
  };
488
392
  const getNestedRelation = (table, path) => {
489
- let currentTable = table;
490
- let currentRelation = null;
491
- for (const relationName of path) {
492
- currentRelation = currentTable.relations[relationName];
493
- if (!currentRelation) return null;
494
- currentTable = currentRelation.foreignTable;
393
+ let current = table;
394
+ let relation = null;
395
+ for (const name of path) {
396
+ relation = current.relations[name];
397
+ if (!relation) return null;
398
+ current = relation.foreignTable;
495
399
  }
496
- return currentRelation;
400
+ return relation;
497
401
  };
498
402
  for (const row of rawResults) {
499
- const mainTableKey = mainTablePks.map((pk) => row[`${this.selectedTableAlias}.${pk}`] ?? row[pk]).join("_");
403
+ const getVal = (logicalKey) => {
404
+ const quoted = `"${logicalKey}"`;
405
+ return row[quoted] ?? row[logicalKey];
406
+ };
407
+ const mainTableKey = mainTablePks.map((pk) => getVal(`${this._table._.name}.${pk}`) ?? getVal(pk)).join("_");
500
408
  if (!groupedResults.has(mainTableKey)) {
501
409
  groupedResults.set(mainTableKey, {});
502
410
  }
503
411
  const result = groupedResults.get(mainTableKey);
504
412
  const relations2 = {};
505
413
  for (const [key, value] of Object.entries(row)) {
506
- if (key.includes(".")) {
507
- const [tableAlias, columnName] = key.split(".");
508
- if (tableAlias === this.selectedTableAlias) {
509
- const column = this.table._.columns[columnName];
510
- result[columnName] = column ? deserializeValue(value, column) : value;
414
+ const normKey = normalizeRowKey(key);
415
+ if (!normKey.includes(".")) {
416
+ const mainDbToTs = getDbNameToTsName(this._table);
417
+ const tsName = mainDbToTs[normKey] ?? normKey;
418
+ const column = this._table._.columns[tsName];
419
+ result[tsName] = column ? deserializeValue(value, column) : value;
420
+ continue;
421
+ }
422
+ const dotIndex = normKey.indexOf(".");
423
+ const tableAlias = normKey.slice(0, dotIndex);
424
+ const columnName = normKey.slice(dotIndex + 1);
425
+ if (tableAlias === this._table._.name) {
426
+ const mainDbToTs = getDbNameToTsName(this._table);
427
+ const tsName = mainDbToTs[columnName] ?? columnName;
428
+ const column = this._table._.columns[tsName];
429
+ result[tsName] = column ? deserializeValue(value, column) : value;
430
+ } else {
431
+ const path = parseRelationPath(tableAlias, this._table._.name);
432
+ if (path.length > 0) {
433
+ const relationConfig = getNestedRelation(this._table, path);
434
+ const foreignTable = relationConfig?.foreignTable;
435
+ const foreignDbToTs = foreignTable ? getDbNameToTsName(foreignTable) : {};
436
+ const tsName = foreignDbToTs[columnName] ?? columnName;
437
+ const col = foreignTable?._.columns?.[tsName];
438
+ setNestedValue(relations2, path, tsName, col ? deserializeValue(value, col) : value);
511
439
  } else {
512
- const relationPath = parseRelationPath(tableAlias, this.selectedTableAlias);
513
- if (relationPath.length > 0) {
514
- const relationConfig = getNestedRelation(this.table, relationPath);
515
- const column = relationConfig?.foreignTable?._.columns?.[columnName];
516
- const deserializedValue = column ? deserializeValue(value, column) : value;
517
- setNestedValue(relations2, relationPath, deserializedValue, columnName);
518
- } else {
519
- if (!result[tableAlias]) result[tableAlias] = {};
520
- result[tableAlias][columnName] = value;
521
- }
440
+ if (!result[tableAlias]) result[tableAlias] = {};
441
+ result[tableAlias][columnName] = value;
522
442
  }
523
- } else {
524
- const column = this.table._.columns[key];
525
- result[key] = column ? deserializeValue(value, column) : value;
526
443
  }
527
444
  }
528
- const attachRelations = (target, relationsData, table, pathPrefix = []) => {
529
- for (const [relName, relData] of Object.entries(relationsData)) {
530
- const currentPath = [...pathPrefix, relName];
531
- const relationConfig = getNestedRelation(table, currentPath);
445
+ const attachRelations = (target, relData, table) => {
446
+ for (const [relName, data] of Object.entries(relData)) {
447
+ const relationConfig = table.relations[relName];
532
448
  if (!relationConfig) continue;
533
- const hasDirectData = typeof relData === "object" && relData !== null && Object.entries(relData).some(([k, v]) => {
534
- return typeof v !== "object" && v !== null && v !== void 0 && v !== "";
535
- });
536
- if (!hasDirectData && typeof relData === "object" && relData !== null) {
537
- const hasNestedData = Object.values(relData).some(
538
- (v) => typeof v === "object" && v !== null && Object.keys(v).length > 0
539
- );
540
- if (!hasNestedData) continue;
541
- }
542
- if (relationConfig.type === "many" || relationConfig.type === "manyToMany") {
543
- if (!target[relName]) target[relName] = [];
544
- const directData = {};
545
- const nestedData = {};
546
- if (typeof relData === "object" && relData !== null) {
547
- for (const [k, v] of Object.entries(relData)) {
548
- if (typeof v === "object" && v !== null) {
549
- nestedData[k] = v;
550
- } else {
551
- directData[k] = v;
552
- }
449
+ const directData = {};
450
+ const nestedData = {};
451
+ if (typeof data === "object" && data !== null) {
452
+ for (const [k, v] of Object.entries(data)) {
453
+ if (typeof v === "object" && v !== null) {
454
+ nestedData[k] = v;
455
+ } else {
456
+ directData[k] = v;
553
457
  }
554
458
  }
555
- const hasData = Object.values(directData).some(
556
- (v) => v !== null && v !== void 0 && v !== ""
557
- );
459
+ }
460
+ const hasData = Object.values(directData).some(
461
+ (v) => v !== null && v !== void 0 && v !== ""
462
+ );
463
+ if (relationConfig.type === "many") {
464
+ if (!target[relName]) target[relName] = [];
558
465
  if (hasData) {
559
- const relatedPks = Object.values(relationConfig.foreignTable._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
560
- const relDataKey = relatedPks.map((pk) => directData[pk]).join("_");
561
- if (relatedPks.length === 0 || !target[relName].some((r) => relatedPks.map((pk) => r[pk]).join("_") === relDataKey)) {
466
+ const relPks = Object.values(relationConfig.foreignTable._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
467
+ const key = relPks.map((pk) => directData[pk]).join("_");
468
+ if (relPks.length === 0 || !target[relName].some(
469
+ (r) => relPks.map((pk) => r[pk]).join("_") === key
470
+ )) {
562
471
  const newItem = { ...directData };
563
472
  if (Object.keys(nestedData).length > 0) {
564
- attachRelations(newItem, nestedData, relationConfig.foreignTable, []);
473
+ attachRelations(newItem, nestedData, relationConfig.foreignTable);
565
474
  }
566
475
  target[relName].push(newItem);
567
476
  }
568
477
  }
569
478
  } else {
570
- const directData = {};
571
- const nestedData = {};
572
- if (typeof relData === "object" && relData !== null) {
573
- for (const [k, v] of Object.entries(relData)) {
574
- if (typeof v === "object" && v !== null) {
575
- nestedData[k] = v;
576
- } else {
577
- directData[k] = v;
578
- }
579
- }
580
- }
581
- const hasData = Object.values(directData).some(
582
- (v) => v !== null && v !== void 0 && v !== ""
583
- );
584
479
  if (hasData || Object.keys(nestedData).length > 0) {
585
480
  target[relName] = { ...directData };
586
481
  if (Object.keys(nestedData).length > 0) {
587
- attachRelations(target[relName], nestedData, relationConfig.foreignTable, []);
482
+ attachRelations(
483
+ target[relName],
484
+ nestedData,
485
+ relationConfig.foreignTable
486
+ );
588
487
  }
589
488
  }
590
489
  }
591
490
  }
592
491
  };
593
- attachRelations(result, relations2, this.table);
492
+ attachRelations(result, relations2, this._table);
594
493
  }
595
494
  return Array.from(groupedResults.values());
596
495
  }
597
- // Update the return type signatures
598
496
  async all() {
599
497
  return this.execute();
600
498
  }
@@ -603,39 +501,32 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
603
501
  const result = await this.execute();
604
502
  return result[0];
605
503
  }
504
+ async first() {
505
+ return this.get();
506
+ }
606
507
  async exists() {
607
- const originalColumns = this.selectedColumns;
608
- this.selectedColumns = ["1"];
609
- const { sql: joinSql, params: joinParams } = this.buildJoins();
610
- const query = `SELECT 1 ${this.query}${joinSql} LIMIT 1`;
611
- const params = [...this.params, ...joinParams];
612
- this.selectedColumns = originalColumns;
613
- const result = await this.db.select(query, params);
614
- return result.length > 0;
508
+ this.applyIncludes();
509
+ const compiledResult = await this._builder.clearSelect().select(sql.raw("1").as("__exists__")).limit(1).execute();
510
+ return compiledResult.length > 0;
615
511
  }
616
512
  async count() {
617
- const originalColumns = this.selectedColumns;
618
- this.selectedColumns = ["COUNT(*) as count"];
619
- const { sql: joinSql, params: joinParams } = this.buildJoins();
620
- const query = `SELECT COUNT(*) as count ${this.query}${joinSql}`;
621
- const params = [...this.params, ...joinParams];
622
- this.selectedColumns = originalColumns;
623
- const result = await this.db.select(query, params);
624
- return result[0]?.count || 0;
625
- }
626
- async first() {
627
- return this.get();
513
+ this.applyIncludes();
514
+ const result = await this._builder.clearSelect().select(sql`COUNT(*)`.as("count")).execute();
515
+ const row = result[0];
516
+ const val = row ? row['"count"'] ?? row.count : void 0;
517
+ return Number(val ?? 0);
628
518
  }
629
519
  async pluck(column) {
630
- const columnName = this.table._.columns[column]._.name;
631
- const originalColumns = this.selectedColumns;
632
- this.selectedColumns = [`${this.selectedTableAlias}.${columnName} AS "${columnName}"`];
633
- const { sql: joinSql, params: joinParams } = this.buildJoins();
634
- const query = `SELECT ${this.selectedColumns.join(", ")} ${this.query}${joinSql}`;
635
- const params = [...this.params, ...joinParams];
636
- this.selectedColumns = originalColumns;
637
- const results = await this.db.select(query, params);
638
- return results.map((row) => row[columnName]);
520
+ this.applyIncludes();
521
+ const col = this._table._.columns[column];
522
+ const alias2 = col._.name;
523
+ const results = await this._builder.clearSelect().select(
524
+ sql.raw(`${this._table._.name}.${alias2}`).as(alias2)
525
+ ).execute();
526
+ return results.map((row) => {
527
+ const val = row['"' + alias2 + '"'] ?? row[alias2];
528
+ return col ? deserializeValue(val, col) : val;
529
+ });
639
530
  }
640
531
  async paginate(page = 1, pageSize = 10) {
641
532
  if (page < 1) page = 1;
@@ -655,16 +546,19 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
655
546
  };
656
547
  }
657
548
  toSQL() {
658
- const { sql: joinSql, params: joinParams } = this.buildJoins();
659
- const distinct = this.isDistinct ? "DISTINCT " : "";
660
- const finalQuery = `SELECT ${distinct}${this.selectedColumns.join(", ")} ${this.query}${joinSql}`;
661
- return {
662
- sql: finalQuery,
663
- params: [...this.params, ...joinParams]
664
- };
549
+ this.applyIncludes();
550
+ const compiled = this._builder.compile();
551
+ return { sql: compiled.sql, params: [...compiled.parameters] };
552
+ }
553
+ toKyselyExpression() {
554
+ this.applyIncludes();
555
+ return this._builder;
665
556
  }
666
557
  };
667
558
 
559
+ // src/builders/update.ts
560
+ import { sql as sql2 } from "kysely";
561
+
668
562
  // src/errors.ts
669
563
  var TauriORMError = class extends Error {
670
564
  constructor(message) {
@@ -733,414 +627,384 @@ var TableNotFoundError = class extends TauriORMError {
733
627
  };
734
628
 
735
629
  // src/builders/update.ts
736
- var UpdateQueryBuilder = class extends BaseQueryBuilder {
737
- constructor(db, table) {
738
- super(db);
739
- this.table = table;
740
- this.query = `UPDATE ${table._.name}`;
741
- }
742
- updateData = {};
743
- returningColumns = [];
744
- hasWhereClause = false;
745
- allowGlobal = false;
746
- incrementDecrementOps = [];
630
+ var UpdateQueryBuilder = class {
631
+ constructor(kysely, table) {
632
+ this.kysely = kysely;
633
+ this._table = table;
634
+ this._builder = kysely.updateTable(table._.name);
635
+ }
636
+ _builder;
637
+ _table;
638
+ _updateData = {};
639
+ _returningColumns = [];
640
+ _hasWhereClause = false;
641
+ _allowGlobal = false;
642
+ _incrementDecrementOps = [];
747
643
  set(data) {
748
- this.updateData = { ...this.updateData, ...data };
644
+ this._updateData = { ...this._updateData, ...data };
749
645
  return this;
750
646
  }
751
647
  where(condition) {
752
- this.hasWhereClause = true;
753
- return super.where(condition);
648
+ this._hasWhereClause = true;
649
+ this._builder = this._builder.where(condition);
650
+ return this;
754
651
  }
755
652
  increment(column, value = 1) {
756
- const col = this.table._.columns[column];
757
- if (!col) {
758
- throw new ColumnNotFoundError(String(column), this.table._.name);
759
- }
760
- this.incrementDecrementOps.push({ column: col._.name, op: "increment", value });
653
+ const col = this._table._.columns[column];
654
+ if (!col) throw new ColumnNotFoundError(String(column), this._table._.name);
655
+ this._incrementDecrementOps.push({ column: col._.name, op: "increment", value });
761
656
  return this;
762
657
  }
763
658
  decrement(column, value = 1) {
764
- const col = this.table._.columns[column];
765
- if (!col) {
766
- throw new ColumnNotFoundError(String(column), this.table._.name);
767
- }
768
- this.incrementDecrementOps.push({ column: col._.name, op: "decrement", value });
659
+ const col = this._table._.columns[column];
660
+ if (!col) throw new ColumnNotFoundError(String(column), this._table._.name);
661
+ this._incrementDecrementOps.push({ column: col._.name, op: "decrement", value });
769
662
  return this;
770
663
  }
771
664
  allowGlobalOperation() {
772
- this.allowGlobal = true;
665
+ this._allowGlobal = true;
773
666
  return this;
774
667
  }
775
668
  returning(...columns) {
776
- this.returningColumns.push(...columns);
669
+ this._returningColumns.push(...columns);
777
670
  return this;
778
671
  }
779
- buildUpdateClause() {
780
- const finalUpdateData = { ...this.updateData };
781
- for (const [key, column] of Object.entries(this.table._.columns)) {
782
- const typedKey = key;
783
- if (finalUpdateData[typedKey] === void 0 && column.options.$onUpdateFn) {
784
- finalUpdateData[typedKey] = column.options.$onUpdateFn();
785
- }
672
+ mapReturningRows(rows) {
673
+ const dbNameToTs = {};
674
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
675
+ dbNameToTs[col._.name] = tsName;
786
676
  }
787
- const baseQuery = this.query;
788
- const whereParams = this.params;
789
- let tablePart = baseQuery;
790
- let whereClause = "";
791
- const whereIndex = baseQuery.indexOf(" WHERE ");
792
- if (whereIndex !== -1) {
793
- tablePart = baseQuery.substring(0, whereIndex);
794
- whereClause = baseQuery.substring(whereIndex);
677
+ const norm = (k) => k.startsWith('"') && k.endsWith('"') ? k.slice(1, -1) : k;
678
+ return rows.map((row) => {
679
+ const out = {};
680
+ for (const [dbKey, value] of Object.entries(row)) {
681
+ const logicalKey = norm(dbKey);
682
+ const tsName = dbNameToTs[logicalKey] ?? logicalKey;
683
+ const column = this._table._.columns[tsName];
684
+ out[tsName] = column ? deserializeValue(value, column) : value;
685
+ }
686
+ return out;
687
+ });
688
+ }
689
+ buildSetClause() {
690
+ const finalData = { ...this._updateData };
691
+ for (const [key, column] of Object.entries(this._table._.columns)) {
692
+ if (finalData[key] === void 0 && column.options.$onUpdateFn) {
693
+ ;
694
+ finalData[key] = column.options.$onUpdateFn();
695
+ }
795
696
  }
796
- const entries = Object.entries(finalUpdateData);
697
+ const entries = Object.entries(finalData);
797
698
  const hasSetData = entries.length > 0;
798
- const hasIncrementDecrement = this.incrementDecrementOps.length > 0;
799
- if (!hasSetData && !hasIncrementDecrement) {
800
- throw new UpdateValidationError("Cannot execute an update query without a .set(), .increment(), or .decrement() call.");
699
+ const hasOps = this._incrementDecrementOps.length > 0;
700
+ if (!hasSetData && !hasOps) {
701
+ throw new UpdateValidationError(
702
+ "Cannot execute an update query without a .set(), .increment(), or .decrement() call."
703
+ );
801
704
  }
802
- const setClauses = [];
803
- const setParams = [];
804
- if (hasSetData) {
805
- for (const [key, value] of entries) {
806
- const column = this.table._.columns[key];
807
- if (!column) {
808
- throw new ColumnNotFoundError(key, this.table._.name);
809
- }
810
- setClauses.push(`${column._.name} = ?`);
811
- setParams.push(serializeValue(value, column));
812
- }
705
+ const setMap = {};
706
+ for (const [key, value] of entries) {
707
+ const column = this._table._.columns[key];
708
+ if (!column) throw new ColumnNotFoundError(key, this._table._.name);
709
+ setMap[column._.name] = serializeValue(value, column);
813
710
  }
814
- for (const op of this.incrementDecrementOps) {
711
+ for (const op of this._incrementDecrementOps) {
815
712
  const sign = op.op === "increment" ? "+" : "-";
816
- setClauses.push(`${op.column} = ${op.column} ${sign} ?`);
817
- setParams.push(op.value);
713
+ setMap[op.column] = sql2.raw(`${op.column} ${sign} ${op.value}`);
818
714
  }
819
- const setClause = setClauses.join(", ");
820
- const sql2 = `${tablePart} SET ${setClause}${whereClause}`;
821
- const params = [...setParams, ...whereParams];
822
- return { sql: sql2, params };
715
+ return setMap;
823
716
  }
824
717
  async execute() {
825
- if (!this.hasWhereClause && !this.allowGlobal) {
826
- throw new MissingWhereClauseError("UPDATE", this.table._.name);
718
+ if (!this._hasWhereClause && !this._allowGlobal) {
719
+ throw new MissingWhereClauseError("UPDATE", this._table._.name);
827
720
  }
828
- const { sql: updateSql, params } = this.buildUpdateClause();
829
- if (this.returningColumns.length > 0) {
830
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
831
- const sqlWithReturning = `${updateSql} RETURNING ${returningNames}`;
832
- return this.db.select(sqlWithReturning, params);
833
- } else {
834
- const result = await this.db.execute(updateSql, params);
835
- return [{ rowsAffected: result.rowsAffected }];
721
+ const setMap = this.buildSetClause();
722
+ let builder = this._builder.set(setMap);
723
+ if (this._returningColumns.length > 0) {
724
+ const cols = this._returningColumns.map(
725
+ (k) => this._table._.columns[k]._.name
726
+ );
727
+ const rows = await builder.returning(cols).execute();
728
+ return this.mapReturningRows(rows);
836
729
  }
730
+ const result = await builder.executeTakeFirst();
731
+ return [{ rowsAffected: Number(result?.numUpdatedRows ?? 0) }];
837
732
  }
838
733
  async returningAll() {
839
- const allColumns = Object.keys(
840
- this.table._.columns
841
- );
842
- return this.returning(...allColumns).execute();
734
+ const allCols = Object.keys(this._table._.columns);
735
+ return this.returning(...allCols).execute();
843
736
  }
844
737
  async returningFirst() {
845
- const allColumns = Object.keys(
846
- this.table._.columns
847
- );
848
- const results = await this.returning(...allColumns).execute();
738
+ const results = await this.returningAll();
849
739
  return results[0];
850
740
  }
851
741
  toSQL() {
852
- const { sql: updateSql, params } = this.buildUpdateClause();
853
- if (this.returningColumns.length > 0) {
854
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
855
- return {
856
- sql: `${updateSql} RETURNING ${returningNames}`,
857
- params
858
- };
742
+ const setMap = this.buildSetClause();
743
+ let builder = this._builder.set(setMap);
744
+ if (this._returningColumns.length > 0) {
745
+ builder = builder.returning(
746
+ this._returningColumns.map((k) => this._table._.columns[k]._.name)
747
+ );
859
748
  }
860
- return { sql: updateSql, params };
749
+ const compiled = builder.compile();
750
+ return { sql: compiled.sql, params: [...compiled.parameters] };
861
751
  }
862
752
  };
863
753
 
864
754
  // src/builders/insert.ts
865
- var InsertQueryBuilder = class extends BaseQueryBuilder {
866
- constructor(db, table) {
867
- super(db);
868
- this.table = table;
869
- this.query = `INSERT INTO ${table._.name}`;
870
- }
871
- dataSets = [];
872
- returningColumns = [];
873
- onConflictAction = null;
874
- conflictTarget = [];
875
- updateSet = {};
755
+ var InsertQueryBuilder = class {
756
+ constructor(kysely, table) {
757
+ this.kysely = kysely;
758
+ this._table = table;
759
+ this._builder = kysely.insertInto(table._.name);
760
+ }
761
+ _builder;
762
+ _table;
763
+ _dataSets = [];
764
+ _returningColumns = [];
765
+ _onConflictAction = null;
766
+ _conflictTarget = [];
767
+ _updateSet = {};
876
768
  values(data) {
877
- const dataArray = Array.isArray(data) ? data : [data];
878
- this.dataSets.push(...dataArray);
769
+ const arr = Array.isArray(data) ? data : [data];
770
+ this._dataSets.push(...arr);
879
771
  return this;
880
772
  }
881
773
  returning(...columns) {
882
- this.returningColumns.push(...columns);
774
+ this._returningColumns.push(...columns);
883
775
  return this;
884
776
  }
885
777
  onConflictDoNothing(target) {
886
- this.onConflictAction = "nothing";
778
+ this._onConflictAction = "nothing";
887
779
  if (target) {
888
- this.conflictTarget = Array.isArray(target) ? target : [target];
780
+ this._conflictTarget = Array.isArray(target) ? target : [target];
889
781
  }
890
782
  return this;
891
783
  }
892
784
  onConflictDoUpdate(config) {
893
- this.onConflictAction = "update";
894
- this.conflictTarget = Array.isArray(config.target) ? config.target : [config.target];
895
- this.updateSet = config.set;
785
+ this._onConflictAction = "update";
786
+ this._conflictTarget = Array.isArray(config.target) ? config.target : [config.target];
787
+ this._updateSet = config.set;
896
788
  return this;
897
789
  }
898
- processDefaultValues(data) {
899
- const finalData = { ...data };
900
- for (const [key, column] of Object.entries(this.table._.columns)) {
901
- const typedKey = key;
902
- if (finalData[typedKey] === void 0) {
903
- if (column.options.$defaultFn) {
904
- finalData[typedKey] = column.options.$defaultFn();
905
- }
790
+ processDefaults(data) {
791
+ const out = { ...data };
792
+ for (const [key, column] of Object.entries(this._table._.columns)) {
793
+ if (out[key] === void 0 && column.options.$defaultFn) {
794
+ ;
795
+ out[key] = column.options.$defaultFn();
906
796
  }
907
797
  }
908
- return finalData;
909
- }
910
- buildConflictClause() {
911
- if (!this.onConflictAction) return "";
912
- let clause = " ON CONFLICT";
913
- if (this.conflictTarget.length > 0) {
914
- const targetNames = this.conflictTarget.map((col) => col._.name).join(", ");
915
- clause += ` (${targetNames})`;
798
+ return out;
799
+ }
800
+ mapReturningRows(rows) {
801
+ const dbNameToTs = {};
802
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
803
+ dbNameToTs[col._.name] = tsName;
916
804
  }
917
- if (this.onConflictAction === "nothing") {
918
- clause += " DO NOTHING";
919
- } else if (this.onConflictAction === "update") {
920
- const setEntries = Object.entries(this.updateSet);
921
- if (setEntries.length > 0) {
922
- const setClause = setEntries.map(([key]) => `${key} = ?`).join(", ");
923
- clause += ` DO UPDATE SET ${setClause}`;
805
+ const norm = (k) => k.startsWith('"') && k.endsWith('"') ? k.slice(1, -1) : k;
806
+ return rows.map((row) => {
807
+ const out = {};
808
+ for (const [dbKey, value] of Object.entries(row)) {
809
+ const logicalKey = norm(dbKey);
810
+ const tsName = dbNameToTs[logicalKey] ?? logicalKey;
811
+ const column = this._table._.columns[tsName];
812
+ out[tsName] = column ? deserializeValue(value, column) : value;
924
813
  }
814
+ return out;
815
+ });
816
+ }
817
+ serializeDataSet(data) {
818
+ const out = {};
819
+ for (const [key, value] of Object.entries(data)) {
820
+ const column = this._table._.columns[key];
821
+ out[column ? column._.name : key] = column ? serializeValue(value, column) : value;
925
822
  }
926
- return clause;
823
+ return out;
927
824
  }
928
825
  async execute() {
929
- if (this.dataSets.length === 0) {
930
- throw new InsertValidationError("No data provided for insert. Use .values() to provide data.");
931
- }
932
- const processedDataSets = this.dataSets.map(
933
- (data) => this.processDefaultValues(data)
934
- );
935
- const groups = /* @__PURE__ */ new Map();
936
- for (const dataSet of processedDataSets) {
937
- const keys = Object.keys(dataSet).sort().join(",");
938
- if (!groups.has(keys)) {
939
- groups.set(keys, []);
940
- }
941
- groups.get(keys).push(dataSet);
942
- }
943
- let results = [];
944
- let lastInsertId;
945
- let rowsAffected = 0;
946
- for (const [_, dataSets] of groups) {
947
- const columns = Object.keys(dataSets[0]);
948
- const columnNames = columns.map(
949
- (key) => this.table._.columns[key]._.name
826
+ if (this._dataSets.length === 0) {
827
+ throw new InsertValidationError(
828
+ "No data provided for insert. Use .values() to provide data."
950
829
  );
951
- const placeholders = `(${columns.map(() => "?").join(", ")})`;
952
- const valuesSql = dataSets.map(() => placeholders).join(", ");
953
- const conflictClause = this.buildConflictClause();
954
- const finalQuery = `${this.query} (${columnNames.join(
955
- ", "
956
- )}) VALUES ${valuesSql}${conflictClause}`;
957
- const params = dataSets.flatMap(
958
- (data) => columns.map((col) => {
959
- const value = data[col] ?? null;
960
- const column = this.table._.columns[col];
961
- return column ? serializeValue(value, column) : value;
962
- })
963
- );
964
- if (this.onConflictAction === "update") {
965
- const setValues = Object.entries(this.updateSet).map(
966
- ([key, value]) => {
967
- const column = this.table._.columns[key];
968
- return column ? serializeValue(value, column) : value;
969
- }
830
+ }
831
+ const processed = this._dataSets.map((d) => this.serializeDataSet(this.processDefaults(d)));
832
+ let builder = this._builder.values(processed.length === 1 ? processed[0] : processed);
833
+ if (this._onConflictAction === "nothing") {
834
+ if (this._conflictTarget.length > 0) {
835
+ const targetCols = this._conflictTarget.map((c) => c._.name);
836
+ builder = builder.onConflict(
837
+ (oc) => oc.columns(targetCols).doNothing()
970
838
  );
971
- params.push(...setValues);
972
- }
973
- if (this.returningColumns.length > 0) {
974
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
975
- const queryWithReturning = `${finalQuery} RETURNING ${returningNames}`;
976
- const rows = await this.db.select(queryWithReturning, params);
977
- results = results.concat(rows);
978
839
  } else {
979
- const result = await this.db.execute(finalQuery, params);
980
- lastInsertId = result.lastInsertId;
981
- rowsAffected += result.rowsAffected;
840
+ builder = builder.onConflict((oc) => oc.doNothing());
982
841
  }
842
+ } else if (this._onConflictAction === "update") {
843
+ const targetCols = this._conflictTarget.map((c) => c._.name);
844
+ const updateData = this.serializeDataSet(this._updateSet);
845
+ builder = builder.onConflict(
846
+ (oc) => oc.columns(targetCols).doUpdateSet(updateData)
847
+ );
983
848
  }
984
- if (this.returningColumns.length > 0) {
985
- return results;
849
+ if (this._returningColumns.length > 0) {
850
+ const cols = this._returningColumns.map(
851
+ (k) => this._table._.columns[k]._.name
852
+ );
853
+ const rows = await builder.returning(cols).execute();
854
+ return this.mapReturningRows(rows);
986
855
  }
987
- return [{ lastInsertId, rowsAffected }];
856
+ const result = await builder.executeTakeFirst();
857
+ return [
858
+ {
859
+ lastInsertId: Number(result?.insertId ?? 0),
860
+ rowsAffected: Number(result?.numInsertedOrUpdatedRows ?? 0)
861
+ }
862
+ ];
988
863
  }
989
864
  async returningAll() {
990
- const allColumns = Object.keys(
991
- this.table._.columns
992
- );
993
- return this.returning(...allColumns).execute();
865
+ const allCols = Object.keys(this._table._.columns);
866
+ return this.returning(...allCols).execute();
994
867
  }
995
868
  async returningFirst() {
996
- const allColumns = Object.keys(
997
- this.table._.columns
998
- );
999
- const results = await this.returning(...allColumns).execute();
869
+ const results = await this.returningAll();
1000
870
  return results[0];
1001
871
  }
1002
872
  toSQL() {
1003
- if (this.dataSets.length === 0) {
1004
- throw new InsertValidationError("No data provided for insert. Use .values() to provide data.");
873
+ if (this._dataSets.length === 0) {
874
+ throw new InsertValidationError(
875
+ "No data provided for insert. Use .values() to provide data."
876
+ );
1005
877
  }
1006
- const processedDataSets = this.dataSets.map(
1007
- (data) => this.processDefaultValues(data)
1008
- );
1009
- const dataSet = processedDataSets[0];
1010
- const columns = Object.keys(dataSet);
1011
- const columnNames = columns.map(
1012
- (key) => this.table._.columns[key]._.name
1013
- );
1014
- const placeholders = `(${columns.map(() => "?").join(", ")})`;
1015
- const valuesSql = processedDataSets.map(() => placeholders).join(", ");
1016
- const conflictClause = this.buildConflictClause();
1017
- const finalQuery = `${this.query} (${columnNames.join(
1018
- ", "
1019
- )}) VALUES ${valuesSql}${conflictClause}`;
1020
- const params = processedDataSets.flatMap(
1021
- (data) => columns.map((col) => {
1022
- const value = data[col] ?? null;
1023
- const column = this.table._.columns[col];
1024
- return column ? serializeValue(value, column) : value;
1025
- })
1026
- );
1027
- if (this.onConflictAction === "update") {
1028
- const setValues = Object.entries(this.updateSet).map(
1029
- ([key, value]) => {
1030
- const column = this.table._.columns[key];
1031
- return column ? serializeValue(value, column) : value;
1032
- }
878
+ const processed = this._dataSets.map((d) => this.serializeDataSet(this.processDefaults(d)));
879
+ let builder = this._builder.values(processed.length === 1 ? processed[0] : processed);
880
+ if (this._onConflictAction === "nothing") {
881
+ if (this._conflictTarget.length > 0) {
882
+ builder = builder.onConflict(
883
+ (oc) => oc.columns(this._conflictTarget.map((c) => c._.name)).doNothing()
884
+ );
885
+ } else {
886
+ builder = builder.onConflict((oc) => oc.doNothing());
887
+ }
888
+ } else if (this._onConflictAction === "update") {
889
+ const updateData = this.serializeDataSet(this._updateSet);
890
+ builder = builder.onConflict(
891
+ (oc) => oc.columns(this._conflictTarget.map((c) => c._.name)).doUpdateSet(updateData)
1033
892
  );
1034
- params.push(...setValues);
1035
893
  }
1036
- if (this.returningColumns.length > 0) {
1037
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
1038
- return {
1039
- sql: `${finalQuery} RETURNING ${returningNames}`,
1040
- params
1041
- };
894
+ if (this._returningColumns.length > 0) {
895
+ builder = builder.returning(
896
+ this._returningColumns.map((k) => this._table._.columns[k]._.name)
897
+ );
1042
898
  }
1043
- return { sql: finalQuery, params };
899
+ const compiled = builder.compile();
900
+ return { sql: compiled.sql, params: [...compiled.parameters] };
1044
901
  }
1045
902
  };
1046
903
 
1047
904
  // src/builders/delete.ts
1048
- var DeleteQueryBuilder = class extends BaseQueryBuilder {
1049
- constructor(db, table) {
1050
- super(db);
1051
- this.table = table;
1052
- this.query = `DELETE FROM ${table._.name}`;
1053
- }
1054
- returningColumns = [];
1055
- hasWhereClause = false;
1056
- allowGlobal = false;
905
+ var DeleteQueryBuilder = class {
906
+ constructor(kysely, table) {
907
+ this.kysely = kysely;
908
+ this._table = table;
909
+ this._builder = kysely.deleteFrom(table._.name);
910
+ }
911
+ _builder;
912
+ _table;
913
+ _returningColumns = [];
914
+ _hasWhereClause = false;
915
+ _allowGlobal = false;
916
+ mapReturningRows(rows) {
917
+ const dbNameToTs = {};
918
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
919
+ dbNameToTs[col._.name] = tsName;
920
+ }
921
+ const norm = (k) => k.startsWith('"') && k.endsWith('"') ? k.slice(1, -1) : k;
922
+ return rows.map((row) => {
923
+ const out = {};
924
+ for (const [dbKey, value] of Object.entries(row)) {
925
+ const logicalKey = norm(dbKey);
926
+ const tsName = dbNameToTs[logicalKey] ?? logicalKey;
927
+ const column = this._table._.columns[tsName];
928
+ out[tsName] = column ? deserializeValue(value, column) : value;
929
+ }
930
+ return out;
931
+ });
932
+ }
1057
933
  where(condition) {
1058
- this.hasWhereClause = true;
1059
- return super.where(condition);
934
+ this._hasWhereClause = true;
935
+ this._builder = this._builder.where(condition);
936
+ return this;
1060
937
  }
1061
938
  allowGlobalOperation() {
1062
- this.allowGlobal = true;
939
+ this._allowGlobal = true;
1063
940
  return this;
1064
941
  }
1065
942
  returning(...columns) {
1066
- this.returningColumns.push(...columns);
943
+ this._returningColumns.push(...columns);
1067
944
  return this;
1068
945
  }
1069
946
  async execute() {
1070
- if (!this.hasWhereClause && !this.allowGlobal) {
1071
- throw new MissingWhereClauseError("DELETE", this.table._.name);
947
+ if (!this._hasWhereClause && !this._allowGlobal) {
948
+ throw new MissingWhereClauseError("DELETE", this._table._.name);
1072
949
  }
1073
- const { sql: sql2, params } = this.build();
1074
- if (this.returningColumns.length > 0) {
1075
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
1076
- const sqlWithReturning = `${sql2} RETURNING ${returningNames}`;
1077
- return this.db.select(sqlWithReturning, params);
1078
- } else {
1079
- const result = await this.db.execute(sql2, params);
1080
- return [{ rowsAffected: result.rowsAffected }];
950
+ if (this._returningColumns.length > 0) {
951
+ const cols = this._returningColumns.map(
952
+ (k) => this._table._.columns[k]._.name
953
+ );
954
+ const rows = await this._builder.returning(cols).execute();
955
+ return this.mapReturningRows(rows);
1081
956
  }
957
+ const result = await this._builder.executeTakeFirst();
958
+ return [{ rowsAffected: Number(result?.numDeletedRows ?? 0) }];
1082
959
  }
1083
960
  async returningAll() {
1084
- const allColumns = Object.keys(this.table._.columns);
1085
- return this.returning(...allColumns).execute();
961
+ const allCols = Object.keys(this._table._.columns);
962
+ return this.returning(...allCols).execute();
1086
963
  }
1087
964
  async returningFirst() {
1088
- const allColumns = Object.keys(this.table._.columns);
1089
- const results = await this.returning(...allColumns).execute();
965
+ const results = await this.returningAll();
1090
966
  return results[0];
1091
967
  }
1092
968
  toSQL() {
1093
- const { sql: sql2, params } = this.build();
1094
- if (this.returningColumns.length > 0) {
1095
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
1096
- return {
1097
- sql: `${sql2} RETURNING ${returningNames}`,
1098
- params
1099
- };
969
+ let builder = this._builder;
970
+ if (this._returningColumns.length > 0) {
971
+ builder = builder.returning(
972
+ this._returningColumns.map((k) => this._table._.columns[k]._.name)
973
+ );
1100
974
  }
1101
- return { sql: sql2, params };
975
+ const compiled = builder.compile();
976
+ return { sql: compiled.sql, params: [...compiled.parameters] };
1102
977
  }
1103
978
  };
1104
979
 
1105
980
  // src/builders/with.ts
1106
981
  var WithQueryBuilder = class {
1107
- constructor(db) {
1108
- this.db = db;
982
+ constructor(kysely) {
983
+ this.kysely = kysely;
1109
984
  }
1110
- ctes = [];
985
+ _ctes = [];
1111
986
  with(alias2, query) {
1112
- this.ctes.push({ alias: alias2, query: query.sql, params: query.params });
987
+ this._ctes.push({ alias: alias2, query: query.toKyselyExpression() });
1113
988
  return this;
1114
989
  }
990
+ applyWith(builder) {
991
+ let b = builder;
992
+ for (const { alias: alias2, query } of this._ctes) {
993
+ b = b.with(alias2, () => query);
994
+ }
995
+ return b;
996
+ }
1115
997
  select(table, columns) {
1116
- const builder = new SelectQueryBuilder(this.db, table, columns);
1117
- this.applyWithClause(builder);
1118
- return builder;
998
+ return new SelectQueryBuilder(this.kysely, table, columns);
1119
999
  }
1120
1000
  insert(table) {
1121
- const builder = new InsertQueryBuilder(this.db, table);
1122
- this.applyWithClause(builder);
1123
- return builder;
1001
+ return new InsertQueryBuilder(this.kysely, table);
1124
1002
  }
1125
1003
  update(table) {
1126
- const builder = new UpdateQueryBuilder(this.db, table);
1127
- this.applyWithClause(builder);
1128
- return builder;
1004
+ return new UpdateQueryBuilder(this.kysely, table);
1129
1005
  }
1130
1006
  delete(table) {
1131
- const builder = new DeleteQueryBuilder(this.db, table);
1132
- this.applyWithClause(builder);
1133
- return builder;
1134
- }
1135
- applyWithClause(builder) {
1136
- if (this.ctes.length > 0) {
1137
- const cteSql = this.ctes.map((cte) => `${cte.alias} AS (${cte.query})`).join(", ");
1138
- builder["query"] = `WITH ${cteSql} ${builder["query"]}`;
1139
- builder["params"] = [
1140
- ...this.ctes.flatMap((cte) => cte.params),
1141
- ...builder["params"]
1142
- ];
1143
- }
1007
+ return new DeleteQueryBuilder(this.kysely, table);
1144
1008
  }
1145
1009
  };
1146
1010
 
@@ -1183,7 +1047,7 @@ var SQLiteColumn = class _SQLiteColumn {
1183
1047
  unique() {
1184
1048
  return new _SQLiteColumn(this._.name, this.type, { ...this.options, unique: true, mode: this._.mode });
1185
1049
  }
1186
- references(ref, column) {
1050
+ references(ref, column, options) {
1187
1051
  const columnKey = typeof column === "string" ? column : column._.name;
1188
1052
  const columnObj = typeof column === "string" ? ref._.columns[column] : column;
1189
1053
  return new _SQLiteColumn(
@@ -1193,7 +1057,9 @@ var SQLiteColumn = class _SQLiteColumn {
1193
1057
  ...this.options,
1194
1058
  references: {
1195
1059
  table: ref,
1196
- column: columnObj
1060
+ column: columnObj,
1061
+ onDelete: options?.onDelete,
1062
+ onUpdate: options?.onUpdate
1197
1063
  },
1198
1064
  mode: this._.mode
1199
1065
  }
@@ -1222,39 +1088,14 @@ var Table = class {
1222
1088
  var sqliteTable = (tableName, columns) => {
1223
1089
  return new Table(tableName, columns);
1224
1090
  };
1225
- var asc = (column) => ({
1226
- sql: `${column._.name} ASC`,
1227
- params: []
1228
- });
1229
- var desc = (column) => ({
1230
- sql: `${column._.name} DESC`,
1231
- params: []
1232
- });
1233
- var sql = (strings, ...values) => {
1234
- const queryParts = [];
1235
- const params = [];
1236
- strings.forEach((str, i) => {
1237
- queryParts.push(str);
1238
- if (values[i] !== void 0) {
1239
- if (typeof values[i] === "object" && values[i].sql) {
1240
- queryParts.push(values[i].sql);
1241
- params.push(...values[i].params);
1242
- } else {
1243
- queryParts.push("?");
1244
- params.push(values[i]);
1245
- }
1246
- }
1247
- });
1248
- return {
1249
- sql: queryParts.join(""),
1250
- params
1251
- };
1252
- };
1091
+ var asc = (column) => kyselySql`${kyselySql.ref(column._.name)} ASC`;
1092
+ var desc = (column) => kyselySql`${kyselySql.ref(column._.name)} DESC`;
1253
1093
  var TauriORM = class {
1254
1094
  constructor(db, schema = void 0) {
1255
1095
  this.db = db;
1096
+ this.kysely = new Kysely4({ dialect: new TauriDialect(db) });
1256
1097
  if (schema) {
1257
- for (const [key, value] of Object.entries(schema)) {
1098
+ for (const [, value] of Object.entries(schema)) {
1258
1099
  if (value instanceof Table) {
1259
1100
  this.tables.set(value._.name, value);
1260
1101
  }
@@ -1262,24 +1103,31 @@ var TauriORM = class {
1262
1103
  }
1263
1104
  }
1264
1105
  tables = /* @__PURE__ */ new Map();
1106
+ kysely;
1265
1107
  buildColumnDefinition(col, forAlterTable = false) {
1266
- let sql2 = `${col._.name} ${col.type}`;
1108
+ let sql6 = `${col._.name} ${col.type}`;
1267
1109
  if (col.options.primaryKey && !forAlterTable) {
1268
- sql2 += " PRIMARY KEY";
1110
+ sql6 += " PRIMARY KEY";
1269
1111
  if (col._.autoincrement) {
1270
- sql2 += " AUTOINCREMENT";
1112
+ sql6 += " AUTOINCREMENT";
1271
1113
  }
1272
1114
  }
1273
- if (col._.notNull) sql2 += " NOT NULL";
1274
- if (col.options.unique) sql2 += " UNIQUE";
1115
+ if (col._.notNull) sql6 += " NOT NULL";
1116
+ if (col.options.unique) sql6 += " UNIQUE";
1275
1117
  if (col.options.default !== void 0) {
1276
1118
  const value = col.options.default;
1277
- sql2 += ` DEFAULT ${typeof value === "string" ? `'${value.replace(/'/g, "''")}'` : value}`;
1119
+ sql6 += ` DEFAULT ${typeof value === "string" ? `'${value.replace(/'/g, "''")}'` : value}`;
1278
1120
  }
1279
1121
  if (col.options.references) {
1280
- sql2 += ` REFERENCES ${col.options.references.table._.name}(${col.options.references.column._.name})`;
1122
+ sql6 += ` REFERENCES ${col.options.references.table._.name}(${col.options.references.column._.name})`;
1123
+ if (col.options.references.onDelete) {
1124
+ sql6 += ` ON DELETE ${col.options.references.onDelete.toUpperCase()}`;
1125
+ }
1126
+ if (col.options.references.onUpdate) {
1127
+ sql6 += ` ON UPDATE ${col.options.references.onUpdate.toUpperCase()}`;
1128
+ }
1281
1129
  }
1282
- return sql2;
1130
+ return sql6;
1283
1131
  }
1284
1132
  async checkMigration() {
1285
1133
  const dbTables = await this.db.select(
@@ -1321,15 +1169,16 @@ var TauriORM = class {
1321
1169
  const schemaColumns = table._.columns;
1322
1170
  let needsRecreate = false;
1323
1171
  for (const [colName, column] of Object.entries(schemaColumns)) {
1324
- const existing = existingColumns.get(colName);
1172
+ const dbColName = column._.name;
1173
+ const existing = existingColumns.get(dbColName);
1325
1174
  if (!existing) {
1326
1175
  if (!this.canAddColumnWithAlter(column)) {
1327
1176
  needsRecreate = true;
1328
1177
  break;
1329
1178
  }
1330
- changes.columnsToAdd.push({ table: tableName, column: colName });
1179
+ changes.columnsToAdd.push({ table: tableName, column: dbColName });
1331
1180
  } else {
1332
- const hasUniqueInDB = uniqueColumns.has(colName);
1181
+ const hasUniqueInDB = uniqueColumns.has(dbColName);
1333
1182
  const wantsUnique = !!column.options.unique;
1334
1183
  if (hasUniqueInDB !== wantsUnique || this.hasColumnDefinitionChanged(column, existing)) {
1335
1184
  needsRecreate = true;
@@ -1338,7 +1187,8 @@ var TauriORM = class {
1338
1187
  }
1339
1188
  }
1340
1189
  for (const existingCol of existingColumns.keys()) {
1341
- if (!schemaColumns[existingCol]) {
1190
+ const schemaHasCol = Object.values(schemaColumns).some((c) => c._.name === existingCol);
1191
+ if (!schemaHasCol) {
1342
1192
  needsRecreate = true;
1343
1193
  break;
1344
1194
  }
@@ -1390,7 +1240,8 @@ var TauriORM = class {
1390
1240
  let needsRecreate = false;
1391
1241
  const columnsToAdd = [];
1392
1242
  for (const [colName, column] of Object.entries(schemaColumns)) {
1393
- const existing = existingColumns.get(colName);
1243
+ const dbColName = column._.name;
1244
+ const existing = existingColumns.get(dbColName);
1394
1245
  if (!existing) {
1395
1246
  if (this.canAddColumnWithAlter(column)) {
1396
1247
  columnsToAdd.push(column);
@@ -1399,7 +1250,7 @@ var TauriORM = class {
1399
1250
  break;
1400
1251
  }
1401
1252
  } else {
1402
- const hasUniqueInDB = uniqueColumns.has(colName);
1253
+ const hasUniqueInDB = uniqueColumns.has(dbColName);
1403
1254
  const wantsUnique = !!column.options.unique;
1404
1255
  if (hasUniqueInDB !== wantsUnique) {
1405
1256
  needsRecreate = true;
@@ -1413,7 +1264,8 @@ var TauriORM = class {
1413
1264
  }
1414
1265
  if (options?.performDestructiveActions) {
1415
1266
  for (const existingCol of existingColumns.keys()) {
1416
- if (!schemaColumns[existingCol]) {
1267
+ const schemaHasCol = Object.values(schemaColumns).some((c) => c._.name === existingCol);
1268
+ if (!schemaHasCol) {
1417
1269
  needsRecreate = true;
1418
1270
  break;
1419
1271
  }
@@ -1458,7 +1310,7 @@ var TauriORM = class {
1458
1310
  await this.db.execute(`CREATE TABLE ${tempTableName} (${columnsSql})`);
1459
1311
  const oldColumns = await this.db.select(`PRAGMA table_info('${tableName}')`);
1460
1312
  const oldColumnNames = oldColumns.map((c) => c.name);
1461
- const newColumnNames = Object.keys(table._.columns);
1313
+ const newColumnNames = Object.values(table._.columns).map((c) => c._.name);
1462
1314
  const commonColumns = oldColumnNames.filter((name) => newColumnNames.includes(name));
1463
1315
  if (commonColumns.length > 0) {
1464
1316
  const columnsList = commonColumns.join(", ");
@@ -1475,18 +1327,18 @@ var TauriORM = class {
1475
1327
  console.warn(
1476
1328
  `[Tauri-ORM] Table "${table._.name}" was not passed in the schema to the ORM constructor. Relations will not be available.`
1477
1329
  );
1478
- return new SelectQueryBuilder(this.db, table, columns);
1330
+ return new SelectQueryBuilder(this.kysely, table, columns);
1479
1331
  }
1480
- return new SelectQueryBuilder(this.db, internalTable, columns);
1332
+ return new SelectQueryBuilder(this.kysely, internalTable, columns);
1481
1333
  }
1482
1334
  insert(table) {
1483
- return new InsertQueryBuilder(this.db, table);
1335
+ return new InsertQueryBuilder(this.kysely, table);
1484
1336
  }
1485
1337
  update(table) {
1486
- return new UpdateQueryBuilder(this.db, table);
1338
+ return new UpdateQueryBuilder(this.kysely, table);
1487
1339
  }
1488
1340
  delete(table) {
1489
- return new DeleteQueryBuilder(this.db, table);
1341
+ return new DeleteQueryBuilder(this.kysely, table);
1490
1342
  }
1491
1343
  async upsert(table, data, conflictTarget) {
1492
1344
  const columns = conflictTarget.map((col) => table._.columns[col]);
@@ -1496,7 +1348,7 @@ var TauriORM = class {
1496
1348
  }).execute();
1497
1349
  }
1498
1350
  $with(alias2) {
1499
- const withBuilder = new WithQueryBuilder(this.db);
1351
+ const withBuilder = new WithQueryBuilder(this.kysely);
1500
1352
  return {
1501
1353
  as: (query) => {
1502
1354
  withBuilder.with(alias2, query);
@@ -1505,14 +1357,14 @@ var TauriORM = class {
1505
1357
  };
1506
1358
  }
1507
1359
  async transaction(callback) {
1508
- await this.db.execute("BEGIN TRANSACTION");
1360
+ await this.db.execute("BEGIN");
1509
1361
  try {
1510
1362
  const result = await callback(this);
1511
1363
  await this.db.execute("COMMIT");
1512
1364
  return result;
1513
- } catch (error) {
1365
+ } catch (e) {
1514
1366
  await this.db.execute("ROLLBACK");
1515
- throw error;
1367
+ throw e;
1516
1368
  }
1517
1369
  }
1518
1370
  rollback() {
@@ -1564,7 +1416,9 @@ var TauriORM = class {
1564
1416
  unique: !!col.options.unique,
1565
1417
  dv: col.options.default && typeof col.options.default === "object" && col.options.default.raw ? { raw: col.options.default.raw } : col.options.default ?? null,
1566
1418
  hasDefaultFn: col.options.$defaultFn !== void 0,
1567
- hasOnUpdateFn: col.options.$onUpdateFn !== void 0
1419
+ hasOnUpdateFn: col.options.$onUpdateFn !== void 0,
1420
+ onDelete: col.options.references?.onDelete ?? null,
1421
+ onUpdate: col.options.references?.onUpdate ?? null
1568
1422
  };
1569
1423
  }
1570
1424
  computeModelSignature() {
@@ -1632,12 +1486,6 @@ var ManyRelation = class extends Relation {
1632
1486
  super(foreignTable);
1633
1487
  }
1634
1488
  };
1635
- var ManyToManyRelation = class extends Relation {
1636
- constructor(foreignTable, config) {
1637
- super(foreignTable);
1638
- this.config = config;
1639
- }
1640
- };
1641
1489
  var relations = (table, relationsCallback) => {
1642
1490
  const builtRelations = relationsCallback({
1643
1491
  one: (foreignTable, config) => {
@@ -1645,9 +1493,6 @@ var relations = (table, relationsCallback) => {
1645
1493
  },
1646
1494
  many: (foreignTable) => {
1647
1495
  return new ManyRelation(foreignTable);
1648
- },
1649
- manyToMany: (foreignTable, config) => {
1650
- return new ManyToManyRelation(foreignTable, config);
1651
1496
  }
1652
1497
  });
1653
1498
  for (const [name, relation] of Object.entries(builtRelations)) {
@@ -1663,14 +1508,6 @@ var relations = (table, relationsCallback) => {
1663
1508
  type: "many",
1664
1509
  foreignTable: relation.foreignTable
1665
1510
  };
1666
- } else if (relation instanceof ManyToManyRelation) {
1667
- table.relations[name] = {
1668
- type: "manyToMany",
1669
- foreignTable: relation.foreignTable,
1670
- junctionTable: relation.config.junctionTable,
1671
- junctionFields: relation.config.junctionFields,
1672
- junctionReferences: relation.config.junctionReferences
1673
- };
1674
1511
  }
1675
1512
  }
1676
1513
  return builtRelations;
@@ -1682,51 +1519,101 @@ var alias = (table, alias2) => {
1682
1519
  return table;
1683
1520
  };
1684
1521
 
1522
+ // src/operators.ts
1523
+ import { isExpression, sql as sql3 } from "kysely";
1524
+ var eq = (column, value, tableAlias) => {
1525
+ const colRef = tableAlias ? `${tableAlias}.${column._.name}` : column._.name;
1526
+ const serialized = serializeValue(value, column);
1527
+ return sql3`${sql3.ref(colRef)} = ${sql3.val(serialized)}`;
1528
+ };
1529
+ var ne = (column, value, tableAlias) => {
1530
+ const colRef = tableAlias ? `${tableAlias}.${column._.name}` : column._.name;
1531
+ const serialized = serializeValue(value, column);
1532
+ return sql3`${sql3.ref(colRef)} != ${sql3.val(serialized)}`;
1533
+ };
1534
+ var and = (...conditions) => {
1535
+ if (conditions.length === 0) return sql3`1 = 1`;
1536
+ if (conditions.length === 1) return conditions[0];
1537
+ return sql3`(${sql3.join(conditions.map((c) => sql3`(${c})`), sql3` AND `)})`;
1538
+ };
1539
+ var or = (...conditions) => {
1540
+ if (conditions.length === 0) return sql3`1 = 1`;
1541
+ if (conditions.length === 1) return conditions[0];
1542
+ return sql3`(${sql3.join(conditions.map((c) => sql3`(${c})`), sql3` OR `)})`;
1543
+ };
1544
+ var not = (condition) => sql3`NOT (${condition})`;
1545
+ var gt = (column, value) => {
1546
+ const serialized = serializeValue(value, column);
1547
+ return sql3`${sql3.ref(column._.name)} > ${sql3.val(serialized)}`;
1548
+ };
1549
+ var gte = (column, value) => {
1550
+ const serialized = serializeValue(value, column);
1551
+ return sql3`${sql3.ref(column._.name)} >= ${sql3.val(serialized)}`;
1552
+ };
1553
+ var lt = (column, value) => {
1554
+ const serialized = serializeValue(value, column);
1555
+ return sql3`${sql3.ref(column._.name)} < ${sql3.val(serialized)}`;
1556
+ };
1557
+ var lte = (column, value) => {
1558
+ const serialized = serializeValue(value, column);
1559
+ return sql3`${sql3.ref(column._.name)} <= ${sql3.val(serialized)}`;
1560
+ };
1561
+ var like = (column, pattern) => sql3`${sql3.ref(column._.name)} LIKE ${sql3.val(pattern)}`;
1562
+ var ilike = (column, pattern) => sql3`${sql3.ref(column._.name)} LIKE ${sql3.val(pattern)} COLLATE NOCASE`;
1563
+ var startsWith = (column, value) => sql3`${sql3.ref(column._.name)} LIKE ${sql3.val(`${value}%`)}`;
1564
+ var endsWith = (column, value) => sql3`${sql3.ref(column._.name)} LIKE ${sql3.val(`%${value}`)}`;
1565
+ var contains = (column, value) => sql3`${sql3.ref(column._.name)} LIKE ${sql3.val(`%${value}%`)}`;
1566
+ var isNull = (column) => sql3`${sql3.ref(column._.name)} IS NULL`;
1567
+ var isNotNull = (column) => sql3`${sql3.ref(column._.name)} IS NOT NULL`;
1568
+ var exists = (subquery2) => sql3`EXISTS ${subquery2}`;
1569
+ var notExists = (subquery2) => sql3`NOT EXISTS ${subquery2}`;
1570
+ var eqSubquery = (column, subquery2) => sql3`${sql3.ref(column._.name)} = (${subquery2})`;
1571
+ var neSubquery = (column, subquery2) => sql3`${sql3.ref(column._.name)} != (${subquery2})`;
1572
+ var gtSubquery = (column, subquery2) => sql3`${sql3.ref(column._.name)} > (${subquery2})`;
1573
+ var gteSubquery = (column, subquery2) => sql3`${sql3.ref(column._.name)} >= (${subquery2})`;
1574
+ var ltSubquery = (column, subquery2) => sql3`${sql3.ref(column._.name)} < (${subquery2})`;
1575
+ var lteSubquery = (column, subquery2) => sql3`${sql3.ref(column._.name)} <= (${subquery2})`;
1576
+ var inArray = (column, values) => {
1577
+ if (isExpression(values)) {
1578
+ return sql3`${sql3.ref(column._.name)} IN (${values})`;
1579
+ }
1580
+ const arr = values;
1581
+ if (arr.length === 0) return sql3`1 = 0`;
1582
+ const serialized = arr.map((v) => sql3.val(serializeValue(v, column)));
1583
+ return sql3`${sql3.ref(column._.name)} IN (${sql3.join(serialized)})`;
1584
+ };
1585
+ var notIn = (column, values) => {
1586
+ if (isExpression(values)) {
1587
+ return sql3`${sql3.ref(column._.name)} NOT IN (${values})`;
1588
+ }
1589
+ const arr = values;
1590
+ if (arr.length === 0) return sql3`1 = 1`;
1591
+ const serialized = arr.map((v) => sql3.val(serializeValue(v, column)));
1592
+ return sql3`${sql3.ref(column._.name)} NOT IN (${sql3.join(serialized)})`;
1593
+ };
1594
+ var between = (column, min2, max2) => {
1595
+ const serializedMin = serializeValue(min2, column);
1596
+ const serializedMax = serializeValue(max2, column);
1597
+ return sql3`${sql3.ref(column._.name)} BETWEEN ${sql3.val(serializedMin)} AND ${sql3.val(serializedMax)}`;
1598
+ };
1599
+
1685
1600
  // src/aggregates.ts
1686
- var count = (column) => ({
1687
- sql: `COUNT(${column ? column._.name : "*"})`,
1688
- params: []
1689
- });
1690
- var countDistinct = (column) => ({
1691
- sql: `COUNT(DISTINCT ${column._.name})`,
1692
- params: []
1693
- });
1694
- var sum = (column) => ({
1695
- sql: `SUM(${column._.name})`,
1696
- params: []
1697
- });
1698
- var avg = (column) => ({
1699
- sql: `AVG(${column._.name})`,
1700
- params: []
1701
- });
1702
- var max = (column) => ({
1703
- sql: `MAX(${column._.name})`,
1704
- params: []
1705
- });
1706
- var min = (column) => ({
1707
- sql: `MIN(${column._.name})`,
1708
- params: []
1709
- });
1710
- var groupConcat = (column, separator = ",") => ({
1711
- sql: `GROUP_CONCAT(${column._.name}, ?)`,
1712
- params: [separator]
1713
- });
1714
- var as = (aggregate, alias2) => ({
1715
- ...aggregate,
1716
- alias: alias2
1717
- });
1601
+ import { sql as sql4 } from "kysely";
1602
+ var count = (column) => sql4`COUNT(${column ? sql4.ref(column._.name) : sql4.raw("*")})`;
1603
+ var countDistinct = (column) => sql4`COUNT(DISTINCT ${sql4.ref(column._.name)})`;
1604
+ var sum = (column) => sql4`SUM(${sql4.ref(column._.name)})`;
1605
+ var avg = (column) => sql4`AVG(${sql4.ref(column._.name)})`;
1606
+ var max = (column) => sql4`MAX(${sql4.ref(column._.name)})`;
1607
+ var min = (column) => sql4`MIN(${sql4.ref(column._.name)})`;
1608
+ var groupConcat = (column, separator = ",") => sql4`GROUP_CONCAT(${sql4.ref(column._.name)}, ${sql4.val(separator)})`;
1609
+ var as = (aggregate, alias2) => Object.assign(aggregate, { alias: alias2 });
1718
1610
 
1719
1611
  // src/subquery.ts
1720
1612
  var subquery = (query) => {
1721
- const { sql: sql2, params } = query.toSQL();
1722
- return {
1723
- sql: `(${sql2})`,
1724
- params,
1725
- _isSubquery: true
1726
- };
1613
+ return query.toKyselyExpression();
1727
1614
  };
1728
1615
  var scalarSubquery = (query) => {
1729
- return subquery(query);
1616
+ return query.toKyselyExpression();
1730
1617
  };
1731
1618
 
1732
1619
  // src/column-helpers.ts
@@ -1745,14 +1632,15 @@ function numeric(name, config) {
1745
1632
  return new SQLiteColumn(name, "NUMERIC", config);
1746
1633
  }
1747
1634
  var enumType = (name, values) => text(name, { enum: values });
1635
+
1636
+ // src/index.ts
1637
+ import { sql as sql5 } from "kysely";
1748
1638
  export {
1749
- BaseQueryBuilder,
1750
1639
  ColumnNotFoundError,
1751
1640
  DeleteQueryBuilder,
1752
1641
  InsertQueryBuilder,
1753
1642
  InsertValidationError,
1754
1643
  ManyRelation,
1755
- ManyToManyRelation,
1756
1644
  MigrationError,
1757
1645
  MissingWhereClauseError,
1758
1646
  OneRelation,
@@ -1763,6 +1651,7 @@ export {
1763
1651
  SelectQueryBuilder,
1764
1652
  Table,
1765
1653
  TableNotFoundError,
1654
+ TauriDialect,
1766
1655
  TauriORM,
1767
1656
  TauriORMError,
1768
1657
  UpdateQueryBuilder,
@@ -1814,7 +1703,7 @@ export {
1814
1703
  real,
1815
1704
  relations,
1816
1705
  scalarSubquery,
1817
- sql,
1706
+ sql5 as sql,
1818
1707
  sqliteTable,
1819
1708
  startsWith,
1820
1709
  subquery,