@type32/tauri-sqlite-orm 0.2.13 → 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;
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 };
117
+ }
118
+ const result = await this.db.execute(sql6, params);
119
+ return {
120
+ rows: [],
121
+ insertId: BigInt(Math.round(result.lastInsertId ?? 0)),
122
+ numAffectedRows: BigInt(result.rowsAffected ?? 0)
123
+ };
111
124
  }
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}`;
118
- }
119
- return this;
125
+ async *streamQuery(_compiledQuery) {
126
+ throw new Error("Streaming queries are not supported by @tauri-apps/plugin-sql");
120
127
  }
121
- limit(count2) {
122
- this.query += ` LIMIT ${count2}`;
123
- return this;
128
+ };
129
+ var TauriDriver = class {
130
+ constructor(db) {
131
+ this.db = db;
124
132
  }
125
- offset(count2) {
126
- this.query += ` OFFSET ${count2}`;
127
- return this;
133
+ async init() {
128
134
  }
129
- build() {
130
- return {
131
- sql: this.query,
132
- params: this.params
133
- };
135
+ async acquireConnection() {
136
+ return new TauriConnection(this.db);
134
137
  }
135
- toSQL() {
136
- return this.build();
138
+ async beginTransaction(conn, _settings) {
139
+ await conn.executeQuery(import_kysely.CompiledQuery.raw("BEGIN"));
137
140
  }
138
- };
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
- };
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,184 +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
- const whereIndex = this.query.indexOf(" WHERE ");
533
- let fromPart = this.query;
534
- let wherePart = "";
535
- if (whereIndex !== -1) {
536
- fromPart = this.query.substring(0, whereIndex);
537
- wherePart = this.query.substring(whereIndex);
538
- }
539
- this.query = `SELECT ${distinct}${this.selectedColumns.join(", ")} ${fromPart}${joinSql}${wherePart}`;
540
- this.params = [...joinParams, ...this.params];
541
- const { sql: sql2, params } = this.build();
542
- const rawResults = await this.db.select(sql2, params);
543
- 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);
544
442
  if (hasIncludes) {
545
443
  return this.processRelationResults(rawResults);
546
444
  }
547
- const hasJoins = this.joins.length > 0;
548
- if (hasJoins) {
445
+ const hasManualJoins = this._manualJoins.length > 0;
446
+ if (hasManualJoins) {
549
447
  return rawResults;
550
448
  }
551
- const prefix = `${this.selectedTableAlias}.`;
449
+ const prefix = `${this._table._.name}.`;
450
+ const dbNameToTs = getDbNameToTsName(this._table);
552
451
  return rawResults.map((row) => {
553
- const newRow = {};
452
+ const out = {};
554
453
  for (const key in row) {
555
- const columnName = key.startsWith(prefix) ? key.substring(prefix.length) : key;
556
- const column = this.table._.columns[columnName];
557
- if (column) {
558
- newRow[columnName] = deserializeValue(row[key], column);
559
- } else {
560
- newRow[columnName] = row[key];
561
- }
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];
562
459
  }
563
- return newRow;
460
+ return out;
564
461
  });
565
462
  }
566
463
  processRelationResults(rawResults) {
567
464
  if (!rawResults.length) return [];
568
- const mainTablePks = Object.values(this.table._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
569
- if (mainTablePks.length === 0) {
570
- return rawResults;
571
- }
465
+ const mainTablePks = Object.values(this._table._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
466
+ if (mainTablePks.length === 0) return rawResults;
572
467
  const groupedResults = /* @__PURE__ */ new Map();
573
468
  const parseRelationPath = (tableAlias, baseAlias) => {
574
- if (!tableAlias.startsWith(baseAlias + "_")) {
575
- return [];
576
- }
577
- const path = tableAlias.substring(baseAlias.length + 1);
578
- return path.split("_");
469
+ if (!tableAlias.startsWith(baseAlias + "_")) return [];
470
+ return tableAlias.slice(baseAlias.length + 1).split("_");
579
471
  };
580
- const setNestedValue = (obj, path, value, columnName) => {
581
- let current = obj;
472
+ const setNestedValue = (obj, path, columnName, value) => {
473
+ let cur = obj;
582
474
  for (let i = 0; i < path.length; i++) {
583
475
  const key = path[i];
584
476
  if (i === path.length - 1) {
585
- if (!current[key]) current[key] = {};
586
- current[key][columnName] = value;
477
+ if (!cur[key]) cur[key] = {};
478
+ cur[key][columnName] = value;
587
479
  } else {
588
- if (!current[key]) current[key] = {};
589
- current = current[key];
480
+ if (!cur[key]) cur[key] = {};
481
+ cur = cur[key];
590
482
  }
591
483
  }
592
484
  };
593
485
  const getNestedRelation = (table, path) => {
594
- let currentTable = table;
595
- let currentRelation = null;
596
- for (const relationName of path) {
597
- currentRelation = currentTable.relations[relationName];
598
- if (!currentRelation) return null;
599
- 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;
600
492
  }
601
- return currentRelation;
493
+ return relation;
602
494
  };
603
495
  for (const row of rawResults) {
604
- 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("_");
605
501
  if (!groupedResults.has(mainTableKey)) {
606
502
  groupedResults.set(mainTableKey, {});
607
503
  }
608
504
  const result = groupedResults.get(mainTableKey);
609
505
  const relations2 = {};
610
506
  for (const [key, value] of Object.entries(row)) {
611
- if (key.includes(".")) {
612
- const [tableAlias, columnName] = key.split(".");
613
- if (tableAlias === this.selectedTableAlias) {
614
- const column = this.table._.columns[columnName];
615
- 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);
616
532
  } else {
617
- const relationPath = parseRelationPath(tableAlias, this.selectedTableAlias);
618
- if (relationPath.length > 0) {
619
- const relationConfig = getNestedRelation(this.table, relationPath);
620
- const column = relationConfig?.foreignTable?._.columns?.[columnName];
621
- const deserializedValue = column ? deserializeValue(value, column) : value;
622
- setNestedValue(relations2, relationPath, deserializedValue, columnName);
623
- } else {
624
- if (!result[tableAlias]) result[tableAlias] = {};
625
- result[tableAlias][columnName] = value;
626
- }
533
+ if (!result[tableAlias]) result[tableAlias] = {};
534
+ result[tableAlias][columnName] = value;
627
535
  }
628
- } else {
629
- const column = this.table._.columns[key];
630
- result[key] = column ? deserializeValue(value, column) : value;
631
536
  }
632
537
  }
633
- const attachRelations = (target, relationsData, table, pathPrefix = []) => {
634
- for (const [relName, relData] of Object.entries(relationsData)) {
635
- const currentPath = [...pathPrefix, relName];
636
- 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];
637
541
  if (!relationConfig) continue;
638
- const hasDirectData = typeof relData === "object" && relData !== null && Object.entries(relData).some(([k, v]) => {
639
- return typeof v !== "object" && v !== null && v !== void 0 && v !== "";
640
- });
641
- if (!hasDirectData && typeof relData === "object" && relData !== null) {
642
- const hasNestedData = Object.values(relData).some(
643
- (v) => typeof v === "object" && v !== null && Object.keys(v).length > 0
644
- );
645
- if (!hasNestedData) continue;
646
- }
647
- if (relationConfig.type === "many" || relationConfig.type === "manyToMany") {
648
- if (!target[relName]) target[relName] = [];
649
- const directData = {};
650
- const nestedData = {};
651
- if (typeof relData === "object" && relData !== null) {
652
- for (const [k, v] of Object.entries(relData)) {
653
- if (typeof v === "object" && v !== null) {
654
- nestedData[k] = v;
655
- } else {
656
- directData[k] = v;
657
- }
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;
658
550
  }
659
551
  }
660
- const hasData = Object.values(directData).some(
661
- (v) => v !== null && v !== void 0 && v !== ""
662
- );
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] = [];
663
558
  if (hasData) {
664
- const relatedPks = Object.values(relationConfig.foreignTable._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
665
- const relDataKey = relatedPks.map((pk) => directData[pk]).join("_");
666
- 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
+ )) {
667
564
  const newItem = { ...directData };
668
565
  if (Object.keys(nestedData).length > 0) {
669
- attachRelations(newItem, nestedData, relationConfig.foreignTable, []);
566
+ attachRelations(newItem, nestedData, relationConfig.foreignTable);
670
567
  }
671
568
  target[relName].push(newItem);
672
569
  }
673
570
  }
674
571
  } else {
675
- const directData = {};
676
- const nestedData = {};
677
- if (typeof relData === "object" && relData !== null) {
678
- for (const [k, v] of Object.entries(relData)) {
679
- if (typeof v === "object" && v !== null) {
680
- nestedData[k] = v;
681
- } else {
682
- directData[k] = v;
683
- }
684
- }
685
- }
686
- const hasData = Object.values(directData).some(
687
- (v) => v !== null && v !== void 0 && v !== ""
688
- );
689
572
  if (hasData || Object.keys(nestedData).length > 0) {
690
573
  target[relName] = { ...directData };
691
574
  if (Object.keys(nestedData).length > 0) {
692
- attachRelations(target[relName], nestedData, relationConfig.foreignTable, []);
575
+ attachRelations(
576
+ target[relName],
577
+ nestedData,
578
+ relationConfig.foreignTable
579
+ );
693
580
  }
694
581
  }
695
582
  }
696
583
  }
697
584
  };
698
- attachRelations(result, relations2, this.table);
585
+ attachRelations(result, relations2, this._table);
699
586
  }
700
587
  return Array.from(groupedResults.values());
701
588
  }
702
- // Update the return type signatures
703
589
  async all() {
704
590
  return this.execute();
705
591
  }
@@ -708,61 +594,32 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
708
594
  const result = await this.execute();
709
595
  return result[0];
710
596
  }
597
+ async first() {
598
+ return this.get();
599
+ }
711
600
  async exists() {
712
- const originalColumns = this.selectedColumns;
713
- this.selectedColumns = ["1"];
714
- const { sql: joinSql, params: joinParams } = this.buildJoins();
715
- const whereIndex = this.query.indexOf(" WHERE ");
716
- let fromPart = this.query;
717
- let wherePart = "";
718
- if (whereIndex !== -1) {
719
- fromPart = this.query.substring(0, whereIndex);
720
- wherePart = this.query.substring(whereIndex);
721
- }
722
- const query = `SELECT 1 ${fromPart}${joinSql}${wherePart} LIMIT 1`;
723
- const params = [...joinParams, ...this.params];
724
- this.selectedColumns = originalColumns;
725
- const result = await this.db.select(query, params);
726
- 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;
727
604
  }
728
605
  async count() {
729
- const originalColumns = this.selectedColumns;
730
- this.selectedColumns = ["COUNT(*) as count"];
731
- const { sql: joinSql, params: joinParams } = this.buildJoins();
732
- const whereIndex = this.query.indexOf(" WHERE ");
733
- let fromPart = this.query;
734
- let wherePart = "";
735
- if (whereIndex !== -1) {
736
- fromPart = this.query.substring(0, whereIndex);
737
- wherePart = this.query.substring(whereIndex);
738
- }
739
- const query = `SELECT COUNT(*) as count ${fromPart}${joinSql}${wherePart}`;
740
- const params = [...joinParams, ...this.params];
741
- this.selectedColumns = originalColumns;
742
- const result = await this.db.select(query, params);
743
- return result[0]?.count || 0;
744
- }
745
- async first() {
746
- 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);
747
611
  }
748
612
  async pluck(column) {
749
- const columnName = this.table._.columns[column]._.name;
750
- const originalColumns = this.selectedColumns;
751
- this.selectedColumns = [`${this.selectedTableAlias}.${columnName} AS "${columnName}"`];
752
- const { sql: joinSql, params: joinParams } = this.buildJoins();
753
- const whereIndex = this.query.indexOf(" WHERE ");
754
- let fromPart = this.query;
755
- let wherePart = "";
756
- if (whereIndex !== -1) {
757
- fromPart = this.query.substring(0, whereIndex);
758
- wherePart = this.query.substring(whereIndex);
759
- }
760
- const query = `SELECT ${this.selectedColumns.join(", ")} ${fromPart}${joinSql}${wherePart}`;
761
- const params = [...joinParams, ...this.params];
762
- this.selectedColumns = originalColumns;
763
- const results = await this.db.select(query, params);
764
- const col = this.table._.columns[column];
765
- return results.map((row) => col ? deserializeValue(row[columnName], col) : 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
+ });
766
623
  }
767
624
  async paginate(page = 1, pageSize = 10) {
768
625
  if (page < 1) page = 1;
@@ -782,16 +639,19 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
782
639
  };
783
640
  }
784
641
  toSQL() {
785
- const { sql: joinSql, params: joinParams } = this.buildJoins();
786
- const distinct = this.isDistinct ? "DISTINCT " : "";
787
- const finalQuery = `SELECT ${distinct}${this.selectedColumns.join(", ")} ${this.query}${joinSql}`;
788
- return {
789
- sql: finalQuery,
790
- params: [...this.params, ...joinParams]
791
- };
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;
792
649
  }
793
650
  };
794
651
 
652
+ // src/builders/update.ts
653
+ var import_kysely3 = require("kysely");
654
+
795
655
  // src/errors.ts
796
656
  var TauriORMError = class extends Error {
797
657
  constructor(message) {
@@ -860,414 +720,384 @@ var TableNotFoundError = class extends TauriORMError {
860
720
  };
861
721
 
862
722
  // src/builders/update.ts
863
- var UpdateQueryBuilder = class extends BaseQueryBuilder {
864
- constructor(db, table) {
865
- super(db);
866
- this.table = table;
867
- this.query = `UPDATE ${table._.name}`;
868
- }
869
- updateData = {};
870
- returningColumns = [];
871
- hasWhereClause = false;
872
- allowGlobal = false;
873
- 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 = [];
874
736
  set(data) {
875
- this.updateData = { ...this.updateData, ...data };
737
+ this._updateData = { ...this._updateData, ...data };
876
738
  return this;
877
739
  }
878
740
  where(condition) {
879
- this.hasWhereClause = true;
880
- return super.where(condition);
741
+ this._hasWhereClause = true;
742
+ this._builder = this._builder.where(condition);
743
+ return this;
881
744
  }
882
745
  increment(column, value = 1) {
883
- const col = this.table._.columns[column];
884
- if (!col) {
885
- throw new ColumnNotFoundError(String(column), this.table._.name);
886
- }
887
- 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 });
888
749
  return this;
889
750
  }
890
751
  decrement(column, value = 1) {
891
- const col = this.table._.columns[column];
892
- if (!col) {
893
- throw new ColumnNotFoundError(String(column), this.table._.name);
894
- }
895
- 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 });
896
755
  return this;
897
756
  }
898
757
  allowGlobalOperation() {
899
- this.allowGlobal = true;
758
+ this._allowGlobal = true;
900
759
  return this;
901
760
  }
902
761
  returning(...columns) {
903
- this.returningColumns.push(...columns);
762
+ this._returningColumns.push(...columns);
904
763
  return this;
905
764
  }
906
- buildUpdateClause() {
907
- const finalUpdateData = { ...this.updateData };
908
- for (const [key, column] of Object.entries(this.table._.columns)) {
909
- const typedKey = key;
910
- if (finalUpdateData[typedKey] === void 0 && column.options.$onUpdateFn) {
911
- finalUpdateData[typedKey] = column.options.$onUpdateFn();
765
+ mapReturningRows(rows) {
766
+ const dbNameToTs = {};
767
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
768
+ dbNameToTs[col._.name] = tsName;
769
+ }
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();
912
788
  }
913
789
  }
914
- const baseQuery = this.query;
915
- const whereParams = this.params;
916
- let tablePart = baseQuery;
917
- let whereClause = "";
918
- const whereIndex = baseQuery.indexOf(" WHERE ");
919
- if (whereIndex !== -1) {
920
- tablePart = baseQuery.substring(0, whereIndex);
921
- whereClause = baseQuery.substring(whereIndex);
922
- }
923
- const entries = Object.entries(finalUpdateData);
790
+ const entries = Object.entries(finalData);
924
791
  const hasSetData = entries.length > 0;
925
- const hasIncrementDecrement = this.incrementDecrementOps.length > 0;
926
- if (!hasSetData && !hasIncrementDecrement) {
927
- 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
+ );
928
797
  }
929
- const setClauses = [];
930
- const setParams = [];
931
- if (hasSetData) {
932
- for (const [key, value] of entries) {
933
- const column = this.table._.columns[key];
934
- if (!column) {
935
- throw new ColumnNotFoundError(key, this.table._.name);
936
- }
937
- setClauses.push(`${column._.name} = ?`);
938
- setParams.push(serializeValue(value, column));
939
- }
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);
940
803
  }
941
- for (const op of this.incrementDecrementOps) {
804
+ for (const op of this._incrementDecrementOps) {
942
805
  const sign = op.op === "increment" ? "+" : "-";
943
- setClauses.push(`${op.column} = ${op.column} ${sign} ?`);
944
- setParams.push(op.value);
806
+ setMap[op.column] = import_kysely3.sql.raw(`${op.column} ${sign} ${op.value}`);
945
807
  }
946
- const setClause = setClauses.join(", ");
947
- const sql2 = `${tablePart} SET ${setClause}${whereClause}`;
948
- const params = [...setParams, ...whereParams];
949
- return { sql: sql2, params };
808
+ return setMap;
950
809
  }
951
810
  async execute() {
952
- if (!this.hasWhereClause && !this.allowGlobal) {
953
- throw new MissingWhereClauseError("UPDATE", this.table._.name);
954
- }
955
- const { sql: updateSql, params } = this.buildUpdateClause();
956
- if (this.returningColumns.length > 0) {
957
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
958
- const sqlWithReturning = `${updateSql} RETURNING ${returningNames}`;
959
- return this.db.select(sqlWithReturning, params);
960
- } else {
961
- const result = await this.db.execute(updateSql, params);
962
- return [{ rowsAffected: result.rowsAffected }];
811
+ if (!this._hasWhereClause && !this._allowGlobal) {
812
+ throw new MissingWhereClauseError("UPDATE", this._table._.name);
813
+ }
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);
963
822
  }
823
+ const result = await builder.executeTakeFirst();
824
+ return [{ rowsAffected: Number(result?.numUpdatedRows ?? 0) }];
964
825
  }
965
826
  async returningAll() {
966
- const allColumns = Object.keys(
967
- this.table._.columns
968
- );
969
- return this.returning(...allColumns).execute();
827
+ const allCols = Object.keys(this._table._.columns);
828
+ return this.returning(...allCols).execute();
970
829
  }
971
830
  async returningFirst() {
972
- const allColumns = Object.keys(
973
- this.table._.columns
974
- );
975
- const results = await this.returning(...allColumns).execute();
831
+ const results = await this.returningAll();
976
832
  return results[0];
977
833
  }
978
834
  toSQL() {
979
- const { sql: updateSql, params } = this.buildUpdateClause();
980
- if (this.returningColumns.length > 0) {
981
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
982
- return {
983
- sql: `${updateSql} RETURNING ${returningNames}`,
984
- params
985
- };
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
+ );
986
841
  }
987
- return { sql: updateSql, params };
842
+ const compiled = builder.compile();
843
+ return { sql: compiled.sql, params: [...compiled.parameters] };
988
844
  }
989
845
  };
990
846
 
991
847
  // src/builders/insert.ts
992
- var InsertQueryBuilder = class extends BaseQueryBuilder {
993
- constructor(db, table) {
994
- super(db);
995
- this.table = table;
996
- this.query = `INSERT INTO ${table._.name}`;
997
- }
998
- dataSets = [];
999
- returningColumns = [];
1000
- onConflictAction = null;
1001
- conflictTarget = [];
1002
- 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 = {};
1003
861
  values(data) {
1004
- const dataArray = Array.isArray(data) ? data : [data];
1005
- this.dataSets.push(...dataArray);
862
+ const arr = Array.isArray(data) ? data : [data];
863
+ this._dataSets.push(...arr);
1006
864
  return this;
1007
865
  }
1008
866
  returning(...columns) {
1009
- this.returningColumns.push(...columns);
867
+ this._returningColumns.push(...columns);
1010
868
  return this;
1011
869
  }
1012
870
  onConflictDoNothing(target) {
1013
- this.onConflictAction = "nothing";
871
+ this._onConflictAction = "nothing";
1014
872
  if (target) {
1015
- this.conflictTarget = Array.isArray(target) ? target : [target];
873
+ this._conflictTarget = Array.isArray(target) ? target : [target];
1016
874
  }
1017
875
  return this;
1018
876
  }
1019
877
  onConflictDoUpdate(config) {
1020
- this.onConflictAction = "update";
1021
- this.conflictTarget = Array.isArray(config.target) ? config.target : [config.target];
1022
- this.updateSet = config.set;
878
+ this._onConflictAction = "update";
879
+ this._conflictTarget = Array.isArray(config.target) ? config.target : [config.target];
880
+ this._updateSet = config.set;
1023
881
  return this;
1024
882
  }
1025
- processDefaultValues(data) {
1026
- const finalData = { ...data };
1027
- for (const [key, column] of Object.entries(this.table._.columns)) {
1028
- const typedKey = key;
1029
- if (finalData[typedKey] === void 0) {
1030
- if (column.options.$defaultFn) {
1031
- finalData[typedKey] = column.options.$defaultFn();
1032
- }
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();
1033
889
  }
1034
890
  }
1035
- return finalData;
1036
- }
1037
- buildConflictClause() {
1038
- if (!this.onConflictAction) return "";
1039
- let clause = " ON CONFLICT";
1040
- if (this.conflictTarget.length > 0) {
1041
- const targetNames = this.conflictTarget.map((col) => col._.name).join(", ");
1042
- clause += ` (${targetNames})`;
1043
- }
1044
- if (this.onConflictAction === "nothing") {
1045
- clause += " DO NOTHING";
1046
- } else if (this.onConflictAction === "update") {
1047
- const setEntries = Object.entries(this.updateSet);
1048
- if (setEntries.length > 0) {
1049
- const setClause = setEntries.map(([key]) => `${key} = ?`).join(", ");
1050
- clause += ` DO UPDATE SET ${setClause}`;
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;
897
+ }
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;
1051
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;
1052
915
  }
1053
- return clause;
916
+ return out;
1054
917
  }
1055
918
  async execute() {
1056
- if (this.dataSets.length === 0) {
1057
- throw new InsertValidationError("No data provided for insert. Use .values() to provide data.");
1058
- }
1059
- const processedDataSets = this.dataSets.map(
1060
- (data) => this.processDefaultValues(data)
1061
- );
1062
- const groups = /* @__PURE__ */ new Map();
1063
- for (const dataSet of processedDataSets) {
1064
- const keys = Object.keys(dataSet).sort().join(",");
1065
- if (!groups.has(keys)) {
1066
- groups.set(keys, []);
1067
- }
1068
- groups.get(keys).push(dataSet);
1069
- }
1070
- let results = [];
1071
- let lastInsertId;
1072
- let rowsAffected = 0;
1073
- for (const [_, dataSets] of groups) {
1074
- const columns = Object.keys(dataSets[0]);
1075
- const columnNames = columns.map(
1076
- (key) => this.table._.columns[key]._.name
1077
- );
1078
- const placeholders = `(${columns.map(() => "?").join(", ")})`;
1079
- const valuesSql = dataSets.map(() => placeholders).join(", ");
1080
- const conflictClause = this.buildConflictClause();
1081
- const finalQuery = `${this.query} (${columnNames.join(
1082
- ", "
1083
- )}) VALUES ${valuesSql}${conflictClause}`;
1084
- const params = dataSets.flatMap(
1085
- (data) => columns.map((col) => {
1086
- const value = data[col] ?? null;
1087
- const column = this.table._.columns[col];
1088
- return column ? serializeValue(value, column) : value;
1089
- })
919
+ if (this._dataSets.length === 0) {
920
+ throw new InsertValidationError(
921
+ "No data provided for insert. Use .values() to provide data."
1090
922
  );
1091
- if (this.onConflictAction === "update") {
1092
- const setValues = Object.entries(this.updateSet).map(
1093
- ([key, value]) => {
1094
- const column = this.table._.columns[key];
1095
- return column ? serializeValue(value, column) : value;
1096
- }
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()
1097
931
  );
1098
- params.push(...setValues);
1099
- }
1100
- if (this.returningColumns.length > 0) {
1101
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
1102
- const queryWithReturning = `${finalQuery} RETURNING ${returningNames}`;
1103
- const rows = await this.db.select(queryWithReturning, params);
1104
- results = results.concat(rows);
1105
932
  } else {
1106
- const result = await this.db.execute(finalQuery, params);
1107
- lastInsertId = result.lastInsertId;
1108
- rowsAffected += result.rowsAffected;
933
+ builder = builder.onConflict((oc) => oc.doNothing());
1109
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
+ );
1110
941
  }
1111
- if (this.returningColumns.length > 0) {
1112
- 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);
1113
948
  }
1114
- 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
+ ];
1115
956
  }
1116
957
  async returningAll() {
1117
- const allColumns = Object.keys(
1118
- this.table._.columns
1119
- );
1120
- return this.returning(...allColumns).execute();
958
+ const allCols = Object.keys(this._table._.columns);
959
+ return this.returning(...allCols).execute();
1121
960
  }
1122
961
  async returningFirst() {
1123
- const allColumns = Object.keys(
1124
- this.table._.columns
1125
- );
1126
- const results = await this.returning(...allColumns).execute();
962
+ const results = await this.returningAll();
1127
963
  return results[0];
1128
964
  }
1129
965
  toSQL() {
1130
- if (this.dataSets.length === 0) {
1131
- 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
+ );
1132
970
  }
1133
- const processedDataSets = this.dataSets.map(
1134
- (data) => this.processDefaultValues(data)
1135
- );
1136
- const dataSet = processedDataSets[0];
1137
- const columns = Object.keys(dataSet);
1138
- const columnNames = columns.map(
1139
- (key) => this.table._.columns[key]._.name
1140
- );
1141
- const placeholders = `(${columns.map(() => "?").join(", ")})`;
1142
- const valuesSql = processedDataSets.map(() => placeholders).join(", ");
1143
- const conflictClause = this.buildConflictClause();
1144
- const finalQuery = `${this.query} (${columnNames.join(
1145
- ", "
1146
- )}) VALUES ${valuesSql}${conflictClause}`;
1147
- const params = processedDataSets.flatMap(
1148
- (data) => columns.map((col) => {
1149
- const value = data[col] ?? null;
1150
- const column = this.table._.columns[col];
1151
- return column ? serializeValue(value, column) : value;
1152
- })
1153
- );
1154
- if (this.onConflictAction === "update") {
1155
- const setValues = Object.entries(this.updateSet).map(
1156
- ([key, value]) => {
1157
- const column = this.table._.columns[key];
1158
- return column ? serializeValue(value, column) : value;
1159
- }
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)
1160
985
  );
1161
- params.push(...setValues);
1162
986
  }
1163
- if (this.returningColumns.length > 0) {
1164
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
1165
- return {
1166
- sql: `${finalQuery} RETURNING ${returningNames}`,
1167
- params
1168
- };
987
+ if (this._returningColumns.length > 0) {
988
+ builder = builder.returning(
989
+ this._returningColumns.map((k) => this._table._.columns[k]._.name)
990
+ );
1169
991
  }
1170
- return { sql: finalQuery, params };
992
+ const compiled = builder.compile();
993
+ return { sql: compiled.sql, params: [...compiled.parameters] };
1171
994
  }
1172
995
  };
1173
996
 
1174
997
  // src/builders/delete.ts
1175
- var DeleteQueryBuilder = class extends BaseQueryBuilder {
1176
- constructor(db, table) {
1177
- super(db);
1178
- this.table = table;
1179
- this.query = `DELETE FROM ${table._.name}`;
1180
- }
1181
- returningColumns = [];
1182
- hasWhereClause = false;
1183
- 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
+ }
1184
1026
  where(condition) {
1185
- this.hasWhereClause = true;
1186
- return super.where(condition);
1027
+ this._hasWhereClause = true;
1028
+ this._builder = this._builder.where(condition);
1029
+ return this;
1187
1030
  }
1188
1031
  allowGlobalOperation() {
1189
- this.allowGlobal = true;
1032
+ this._allowGlobal = true;
1190
1033
  return this;
1191
1034
  }
1192
1035
  returning(...columns) {
1193
- this.returningColumns.push(...columns);
1036
+ this._returningColumns.push(...columns);
1194
1037
  return this;
1195
1038
  }
1196
1039
  async execute() {
1197
- if (!this.hasWhereClause && !this.allowGlobal) {
1198
- throw new MissingWhereClauseError("DELETE", this.table._.name);
1040
+ if (!this._hasWhereClause && !this._allowGlobal) {
1041
+ throw new MissingWhereClauseError("DELETE", this._table._.name);
1199
1042
  }
1200
- const { sql: sql2, params } = this.build();
1201
- if (this.returningColumns.length > 0) {
1202
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
1203
- const sqlWithReturning = `${sql2} RETURNING ${returningNames}`;
1204
- return this.db.select(sqlWithReturning, params);
1205
- } else {
1206
- const result = await this.db.execute(sql2, params);
1207
- 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);
1208
1049
  }
1050
+ const result = await this._builder.executeTakeFirst();
1051
+ return [{ rowsAffected: Number(result?.numDeletedRows ?? 0) }];
1209
1052
  }
1210
1053
  async returningAll() {
1211
- const allColumns = Object.keys(this.table._.columns);
1212
- return this.returning(...allColumns).execute();
1054
+ const allCols = Object.keys(this._table._.columns);
1055
+ return this.returning(...allCols).execute();
1213
1056
  }
1214
1057
  async returningFirst() {
1215
- const allColumns = Object.keys(this.table._.columns);
1216
- const results = await this.returning(...allColumns).execute();
1058
+ const results = await this.returningAll();
1217
1059
  return results[0];
1218
1060
  }
1219
1061
  toSQL() {
1220
- const { sql: sql2, params } = this.build();
1221
- if (this.returningColumns.length > 0) {
1222
- const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
1223
- return {
1224
- sql: `${sql2} RETURNING ${returningNames}`,
1225
- params
1226
- };
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
+ );
1227
1067
  }
1228
- return { sql: sql2, params };
1068
+ const compiled = builder.compile();
1069
+ return { sql: compiled.sql, params: [...compiled.parameters] };
1229
1070
  }
1230
1071
  };
1231
1072
 
1232
1073
  // src/builders/with.ts
1233
1074
  var WithQueryBuilder = class {
1234
- constructor(db) {
1235
- this.db = db;
1075
+ constructor(kysely) {
1076
+ this.kysely = kysely;
1236
1077
  }
1237
- ctes = [];
1078
+ _ctes = [];
1238
1079
  with(alias2, query) {
1239
- this.ctes.push({ alias: alias2, query: query.sql, params: query.params });
1080
+ this._ctes.push({ alias: alias2, query: query.toKyselyExpression() });
1240
1081
  return this;
1241
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
+ }
1242
1090
  select(table, columns) {
1243
- const builder = new SelectQueryBuilder(this.db, table, columns);
1244
- this.applyWithClause(builder);
1245
- return builder;
1091
+ return new SelectQueryBuilder(this.kysely, table, columns);
1246
1092
  }
1247
1093
  insert(table) {
1248
- const builder = new InsertQueryBuilder(this.db, table);
1249
- this.applyWithClause(builder);
1250
- return builder;
1094
+ return new InsertQueryBuilder(this.kysely, table);
1251
1095
  }
1252
1096
  update(table) {
1253
- const builder = new UpdateQueryBuilder(this.db, table);
1254
- this.applyWithClause(builder);
1255
- return builder;
1097
+ return new UpdateQueryBuilder(this.kysely, table);
1256
1098
  }
1257
1099
  delete(table) {
1258
- const builder = new DeleteQueryBuilder(this.db, table);
1259
- this.applyWithClause(builder);
1260
- return builder;
1261
- }
1262
- applyWithClause(builder) {
1263
- if (this.ctes.length > 0) {
1264
- const cteSql = this.ctes.map((cte) => `${cte.alias} AS (${cte.query})`).join(", ");
1265
- builder["query"] = `WITH ${cteSql} ${builder["query"]}`;
1266
- builder["params"] = [
1267
- ...this.ctes.flatMap((cte) => cte.params),
1268
- ...builder["params"]
1269
- ];
1270
- }
1100
+ return new DeleteQueryBuilder(this.kysely, table);
1271
1101
  }
1272
1102
  };
1273
1103
 
@@ -1310,7 +1140,7 @@ var SQLiteColumn = class _SQLiteColumn {
1310
1140
  unique() {
1311
1141
  return new _SQLiteColumn(this._.name, this.type, { ...this.options, unique: true, mode: this._.mode });
1312
1142
  }
1313
- references(ref, column) {
1143
+ references(ref, column, options) {
1314
1144
  const columnKey = typeof column === "string" ? column : column._.name;
1315
1145
  const columnObj = typeof column === "string" ? ref._.columns[column] : column;
1316
1146
  return new _SQLiteColumn(
@@ -1320,7 +1150,9 @@ var SQLiteColumn = class _SQLiteColumn {
1320
1150
  ...this.options,
1321
1151
  references: {
1322
1152
  table: ref,
1323
- column: columnObj
1153
+ column: columnObj,
1154
+ onDelete: options?.onDelete,
1155
+ onUpdate: options?.onUpdate
1324
1156
  },
1325
1157
  mode: this._.mode
1326
1158
  }
@@ -1349,39 +1181,14 @@ var Table = class {
1349
1181
  var sqliteTable = (tableName, columns) => {
1350
1182
  return new Table(tableName, columns);
1351
1183
  };
1352
- var asc = (column) => ({
1353
- sql: `${column._.name} ASC`,
1354
- params: []
1355
- });
1356
- var desc = (column) => ({
1357
- sql: `${column._.name} DESC`,
1358
- params: []
1359
- });
1360
- var sql = (strings, ...values) => {
1361
- const queryParts = [];
1362
- const params = [];
1363
- strings.forEach((str, i) => {
1364
- queryParts.push(str);
1365
- if (values[i] !== void 0) {
1366
- if (typeof values[i] === "object" && values[i].sql) {
1367
- queryParts.push(values[i].sql);
1368
- params.push(...values[i].params);
1369
- } else {
1370
- queryParts.push("?");
1371
- params.push(values[i]);
1372
- }
1373
- }
1374
- });
1375
- return {
1376
- sql: queryParts.join(""),
1377
- params
1378
- };
1379
- };
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`;
1380
1186
  var TauriORM = class {
1381
1187
  constructor(db, schema = void 0) {
1382
1188
  this.db = db;
1189
+ this.kysely = new import_kysely4.Kysely({ dialect: new TauriDialect(db) });
1383
1190
  if (schema) {
1384
- for (const [key, value] of Object.entries(schema)) {
1191
+ for (const [, value] of Object.entries(schema)) {
1385
1192
  if (value instanceof Table) {
1386
1193
  this.tables.set(value._.name, value);
1387
1194
  }
@@ -1389,24 +1196,31 @@ var TauriORM = class {
1389
1196
  }
1390
1197
  }
1391
1198
  tables = /* @__PURE__ */ new Map();
1199
+ kysely;
1392
1200
  buildColumnDefinition(col, forAlterTable = false) {
1393
- let sql2 = `${col._.name} ${col.type}`;
1201
+ let sql6 = `${col._.name} ${col.type}`;
1394
1202
  if (col.options.primaryKey && !forAlterTable) {
1395
- sql2 += " PRIMARY KEY";
1203
+ sql6 += " PRIMARY KEY";
1396
1204
  if (col._.autoincrement) {
1397
- sql2 += " AUTOINCREMENT";
1205
+ sql6 += " AUTOINCREMENT";
1398
1206
  }
1399
1207
  }
1400
- if (col._.notNull) sql2 += " NOT NULL";
1401
- if (col.options.unique) sql2 += " UNIQUE";
1208
+ if (col._.notNull) sql6 += " NOT NULL";
1209
+ if (col.options.unique) sql6 += " UNIQUE";
1402
1210
  if (col.options.default !== void 0) {
1403
1211
  const value = col.options.default;
1404
- sql2 += ` DEFAULT ${typeof value === "string" ? `'${value.replace(/'/g, "''")}'` : value}`;
1212
+ sql6 += ` DEFAULT ${typeof value === "string" ? `'${value.replace(/'/g, "''")}'` : value}`;
1405
1213
  }
1406
1214
  if (col.options.references) {
1407
- 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
+ }
1408
1222
  }
1409
- return sql2;
1223
+ return sql6;
1410
1224
  }
1411
1225
  async checkMigration() {
1412
1226
  const dbTables = await this.db.select(
@@ -1448,15 +1262,16 @@ var TauriORM = class {
1448
1262
  const schemaColumns = table._.columns;
1449
1263
  let needsRecreate = false;
1450
1264
  for (const [colName, column] of Object.entries(schemaColumns)) {
1451
- const existing = existingColumns.get(colName);
1265
+ const dbColName = column._.name;
1266
+ const existing = existingColumns.get(dbColName);
1452
1267
  if (!existing) {
1453
1268
  if (!this.canAddColumnWithAlter(column)) {
1454
1269
  needsRecreate = true;
1455
1270
  break;
1456
1271
  }
1457
- changes.columnsToAdd.push({ table: tableName, column: colName });
1272
+ changes.columnsToAdd.push({ table: tableName, column: dbColName });
1458
1273
  } else {
1459
- const hasUniqueInDB = uniqueColumns.has(colName);
1274
+ const hasUniqueInDB = uniqueColumns.has(dbColName);
1460
1275
  const wantsUnique = !!column.options.unique;
1461
1276
  if (hasUniqueInDB !== wantsUnique || this.hasColumnDefinitionChanged(column, existing)) {
1462
1277
  needsRecreate = true;
@@ -1465,7 +1280,8 @@ var TauriORM = class {
1465
1280
  }
1466
1281
  }
1467
1282
  for (const existingCol of existingColumns.keys()) {
1468
- if (!schemaColumns[existingCol]) {
1283
+ const schemaHasCol = Object.values(schemaColumns).some((c) => c._.name === existingCol);
1284
+ if (!schemaHasCol) {
1469
1285
  needsRecreate = true;
1470
1286
  break;
1471
1287
  }
@@ -1517,7 +1333,8 @@ var TauriORM = class {
1517
1333
  let needsRecreate = false;
1518
1334
  const columnsToAdd = [];
1519
1335
  for (const [colName, column] of Object.entries(schemaColumns)) {
1520
- const existing = existingColumns.get(colName);
1336
+ const dbColName = column._.name;
1337
+ const existing = existingColumns.get(dbColName);
1521
1338
  if (!existing) {
1522
1339
  if (this.canAddColumnWithAlter(column)) {
1523
1340
  columnsToAdd.push(column);
@@ -1526,7 +1343,7 @@ var TauriORM = class {
1526
1343
  break;
1527
1344
  }
1528
1345
  } else {
1529
- const hasUniqueInDB = uniqueColumns.has(colName);
1346
+ const hasUniqueInDB = uniqueColumns.has(dbColName);
1530
1347
  const wantsUnique = !!column.options.unique;
1531
1348
  if (hasUniqueInDB !== wantsUnique) {
1532
1349
  needsRecreate = true;
@@ -1540,7 +1357,8 @@ var TauriORM = class {
1540
1357
  }
1541
1358
  if (options?.performDestructiveActions) {
1542
1359
  for (const existingCol of existingColumns.keys()) {
1543
- if (!schemaColumns[existingCol]) {
1360
+ const schemaHasCol = Object.values(schemaColumns).some((c) => c._.name === existingCol);
1361
+ if (!schemaHasCol) {
1544
1362
  needsRecreate = true;
1545
1363
  break;
1546
1364
  }
@@ -1585,7 +1403,7 @@ var TauriORM = class {
1585
1403
  await this.db.execute(`CREATE TABLE ${tempTableName} (${columnsSql})`);
1586
1404
  const oldColumns = await this.db.select(`PRAGMA table_info('${tableName}')`);
1587
1405
  const oldColumnNames = oldColumns.map((c) => c.name);
1588
- const newColumnNames = Object.keys(table._.columns);
1406
+ const newColumnNames = Object.values(table._.columns).map((c) => c._.name);
1589
1407
  const commonColumns = oldColumnNames.filter((name) => newColumnNames.includes(name));
1590
1408
  if (commonColumns.length > 0) {
1591
1409
  const columnsList = commonColumns.join(", ");
@@ -1602,18 +1420,18 @@ var TauriORM = class {
1602
1420
  console.warn(
1603
1421
  `[Tauri-ORM] Table "${table._.name}" was not passed in the schema to the ORM constructor. Relations will not be available.`
1604
1422
  );
1605
- return new SelectQueryBuilder(this.db, table, columns);
1423
+ return new SelectQueryBuilder(this.kysely, table, columns);
1606
1424
  }
1607
- return new SelectQueryBuilder(this.db, internalTable, columns);
1425
+ return new SelectQueryBuilder(this.kysely, internalTable, columns);
1608
1426
  }
1609
1427
  insert(table) {
1610
- return new InsertQueryBuilder(this.db, table);
1428
+ return new InsertQueryBuilder(this.kysely, table);
1611
1429
  }
1612
1430
  update(table) {
1613
- return new UpdateQueryBuilder(this.db, table);
1431
+ return new UpdateQueryBuilder(this.kysely, table);
1614
1432
  }
1615
1433
  delete(table) {
1616
- return new DeleteQueryBuilder(this.db, table);
1434
+ return new DeleteQueryBuilder(this.kysely, table);
1617
1435
  }
1618
1436
  async upsert(table, data, conflictTarget) {
1619
1437
  const columns = conflictTarget.map((col) => table._.columns[col]);
@@ -1623,7 +1441,7 @@ var TauriORM = class {
1623
1441
  }).execute();
1624
1442
  }
1625
1443
  $with(alias2) {
1626
- const withBuilder = new WithQueryBuilder(this.db);
1444
+ const withBuilder = new WithQueryBuilder(this.kysely);
1627
1445
  return {
1628
1446
  as: (query) => {
1629
1447
  withBuilder.with(alias2, query);
@@ -1632,14 +1450,14 @@ var TauriORM = class {
1632
1450
  };
1633
1451
  }
1634
1452
  async transaction(callback) {
1635
- await this.db.execute("BEGIN TRANSACTION");
1453
+ await this.db.execute("BEGIN");
1636
1454
  try {
1637
1455
  const result = await callback(this);
1638
1456
  await this.db.execute("COMMIT");
1639
1457
  return result;
1640
- } catch (error) {
1458
+ } catch (e) {
1641
1459
  await this.db.execute("ROLLBACK");
1642
- throw error;
1460
+ throw e;
1643
1461
  }
1644
1462
  }
1645
1463
  rollback() {
@@ -1691,7 +1509,9 @@ var TauriORM = class {
1691
1509
  unique: !!col.options.unique,
1692
1510
  dv: col.options.default && typeof col.options.default === "object" && col.options.default.raw ? { raw: col.options.default.raw } : col.options.default ?? null,
1693
1511
  hasDefaultFn: col.options.$defaultFn !== void 0,
1694
- 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
1695
1515
  };
1696
1516
  }
1697
1517
  computeModelSignature() {
@@ -1759,12 +1579,6 @@ var ManyRelation = class extends Relation {
1759
1579
  super(foreignTable);
1760
1580
  }
1761
1581
  };
1762
- var ManyToManyRelation = class extends Relation {
1763
- constructor(foreignTable, config) {
1764
- super(foreignTable);
1765
- this.config = config;
1766
- }
1767
- };
1768
1582
  var relations = (table, relationsCallback) => {
1769
1583
  const builtRelations = relationsCallback({
1770
1584
  one: (foreignTable, config) => {
@@ -1772,9 +1586,6 @@ var relations = (table, relationsCallback) => {
1772
1586
  },
1773
1587
  many: (foreignTable) => {
1774
1588
  return new ManyRelation(foreignTable);
1775
- },
1776
- manyToMany: (foreignTable, config) => {
1777
- return new ManyToManyRelation(foreignTable, config);
1778
1589
  }
1779
1590
  });
1780
1591
  for (const [name, relation] of Object.entries(builtRelations)) {
@@ -1790,14 +1601,6 @@ var relations = (table, relationsCallback) => {
1790
1601
  type: "many",
1791
1602
  foreignTable: relation.foreignTable
1792
1603
  };
1793
- } else if (relation instanceof ManyToManyRelation) {
1794
- table.relations[name] = {
1795
- type: "manyToMany",
1796
- foreignTable: relation.foreignTable,
1797
- junctionTable: relation.config.junctionTable,
1798
- junctionFields: relation.config.junctionFields,
1799
- junctionReferences: relation.config.junctionReferences
1800
- };
1801
1604
  }
1802
1605
  }
1803
1606
  return builtRelations;
@@ -1809,51 +1612,101 @@ var alias = (table, alias2) => {
1809
1612
  return table;
1810
1613
  };
1811
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
+
1812
1693
  // src/aggregates.ts
1813
- var count = (column) => ({
1814
- sql: `COUNT(${column ? column._.name : "*"})`,
1815
- params: []
1816
- });
1817
- var countDistinct = (column) => ({
1818
- sql: `COUNT(DISTINCT ${column._.name})`,
1819
- params: []
1820
- });
1821
- var sum = (column) => ({
1822
- sql: `SUM(${column._.name})`,
1823
- params: []
1824
- });
1825
- var avg = (column) => ({
1826
- sql: `AVG(${column._.name})`,
1827
- params: []
1828
- });
1829
- var max = (column) => ({
1830
- sql: `MAX(${column._.name})`,
1831
- params: []
1832
- });
1833
- var min = (column) => ({
1834
- sql: `MIN(${column._.name})`,
1835
- params: []
1836
- });
1837
- var groupConcat = (column, separator = ",") => ({
1838
- sql: `GROUP_CONCAT(${column._.name}, ?)`,
1839
- params: [separator]
1840
- });
1841
- var as = (aggregate, alias2) => ({
1842
- ...aggregate,
1843
- alias: alias2
1844
- });
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 });
1845
1703
 
1846
1704
  // src/subquery.ts
1847
1705
  var subquery = (query) => {
1848
- const { sql: sql2, params } = query.toSQL();
1849
- return {
1850
- sql: `(${sql2})`,
1851
- params,
1852
- _isSubquery: true
1853
- };
1706
+ return query.toKyselyExpression();
1854
1707
  };
1855
1708
  var scalarSubquery = (query) => {
1856
- return subquery(query);
1709
+ return query.toKyselyExpression();
1857
1710
  };
1858
1711
 
1859
1712
  // src/column-helpers.ts
@@ -1872,15 +1725,16 @@ function numeric(name, config) {
1872
1725
  return new SQLiteColumn(name, "NUMERIC", config);
1873
1726
  }
1874
1727
  var enumType = (name, values) => text(name, { enum: values });
1728
+
1729
+ // src/index.ts
1730
+ var import_kysely7 = require("kysely");
1875
1731
  // Annotate the CommonJS export names for ESM import in node:
1876
1732
  0 && (module.exports = {
1877
- BaseQueryBuilder,
1878
1733
  ColumnNotFoundError,
1879
1734
  DeleteQueryBuilder,
1880
1735
  InsertQueryBuilder,
1881
1736
  InsertValidationError,
1882
1737
  ManyRelation,
1883
- ManyToManyRelation,
1884
1738
  MigrationError,
1885
1739
  MissingWhereClauseError,
1886
1740
  OneRelation,
@@ -1891,6 +1745,7 @@ var enumType = (name, values) => text(name, { enum: values });
1891
1745
  SelectQueryBuilder,
1892
1746
  Table,
1893
1747
  TableNotFoundError,
1748
+ TauriDialect,
1894
1749
  TauriORM,
1895
1750
  TauriORMError,
1896
1751
  UpdateQueryBuilder,