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