@type32/tauri-sqlite-orm 0.2.13 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,
@@ -54,6 +53,8 @@ __export(index_exports, {
54
53
  contains: () => contains,
55
54
  count: () => count,
56
55
  countDistinct: () => countDistinct,
56
+ defineRelations: () => defineRelations,
57
+ defineRelationsPart: () => defineRelationsPart,
57
58
  desc: () => desc,
58
59
  endsWith: () => endsWith,
59
60
  enumType: () => enumType,
@@ -88,186 +89,92 @@ __export(index_exports, {
88
89
  real: () => real,
89
90
  relations: () => relations,
90
91
  scalarSubquery: () => scalarSubquery,
91
- sql: () => sql,
92
+ sql: () => import_kysely7.sql,
92
93
  sqliteTable: () => sqliteTable,
93
94
  startsWith: () => startsWith,
94
95
  subquery: () => subquery,
95
96
  sum: () => sum,
96
- text: () => text
97
+ text: () => text,
98
+ through: () => through
97
99
  });
98
100
  module.exports = __toCommonJS(index_exports);
99
101
 
100
- // src/builders/query-base.ts
101
- var BaseQueryBuilder = class {
102
+ // src/orm.ts
103
+ var import_kysely5 = require("kysely");
104
+
105
+ // src/dialect.ts
106
+ var import_kysely = require("kysely");
107
+ var TauriConnection = class {
102
108
  constructor(db) {
103
109
  this.db = db;
104
110
  }
105
- query = "";
106
- params = [];
107
- where(condition) {
108
- this.query += ` WHERE ${condition.sql}`;
109
- this.params.push(...condition.params);
110
- return this;
111
+ async executeQuery(compiledQuery) {
112
+ const { sql: sql6, parameters } = compiledQuery;
113
+ const params = parameters;
114
+ const trimmed = sql6.trimStart();
115
+ const isSelect = /^\s*(SELECT|WITH|PRAGMA)/i.test(trimmed);
116
+ const hasReturning = /\bRETURNING\b/i.test(sql6);
117
+ if (isSelect || hasReturning) {
118
+ const rows = await this.db.select(sql6, params);
119
+ return { rows };
120
+ }
121
+ const result = await this.db.execute(sql6, params);
122
+ return {
123
+ rows: [],
124
+ insertId: BigInt(Math.round(result.lastInsertId ?? 0)),
125
+ numAffectedRows: BigInt(result.rowsAffected ?? 0)
126
+ };
111
127
  }
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;
128
+ async *streamQuery(_compiledQuery) {
129
+ throw new Error("Streaming queries are not supported by @tauri-apps/plugin-sql");
120
130
  }
121
- limit(count2) {
122
- this.query += ` LIMIT ${count2}`;
123
- return this;
131
+ };
132
+ var TauriDriver = class {
133
+ constructor(db) {
134
+ this.db = db;
124
135
  }
125
- offset(count2) {
126
- this.query += ` OFFSET ${count2}`;
127
- return this;
136
+ async init() {
128
137
  }
129
- build() {
130
- return {
131
- sql: this.query,
132
- params: this.params
133
- };
138
+ async acquireConnection() {
139
+ return new TauriConnection(this.db);
134
140
  }
135
- toSQL() {
136
- return this.build();
141
+ async beginTransaction(conn, _settings) {
142
+ await conn.executeQuery(import_kysely.CompiledQuery.raw("BEGIN"));
137
143
  }
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
- };
144
+ async commitTransaction(conn) {
145
+ await conn.executeQuery(import_kysely.CompiledQuery.raw("COMMIT"));
146
+ }
147
+ async rollbackTransaction(conn) {
148
+ await conn.executeQuery(import_kysely.CompiledQuery.raw("ROLLBACK"));
149
+ }
150
+ async releaseConnection(_conn) {
151
+ }
152
+ async destroy() {
249
153
  }
250
- return {
251
- sql: `${column._.name} IN (${values.map(() => "?").join(",")})`,
252
- params: values
253
- };
254
154
  };
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
- };
155
+ var TauriDialect = class {
156
+ constructor(db) {
157
+ this.db = db;
158
+ }
159
+ createAdapter() {
160
+ return new import_kysely.SqliteAdapter();
161
+ }
162
+ createDriver() {
163
+ return new TauriDriver(this.db);
164
+ }
165
+ createIntrospector(db) {
166
+ return new import_kysely.SqliteIntrospector(db);
167
+ }
168
+ createQueryCompiler() {
169
+ return new import_kysely.SqliteQueryCompiler();
261
170
  }
262
- return {
263
- sql: `${column._.name} NOT IN (${values.map(() => "?").join(",")})`,
264
- params: values
265
- };
266
171
  };
267
- var between = (column, min2, max2) => ({
268
- sql: `${column._.name} BETWEEN ? AND ?`,
269
- params: [min2, max2]
270
- });
172
+
173
+ // src/builders/select.ts
174
+ var import_kysely3 = require("kysely");
175
+
176
+ // src/operators.ts
177
+ var import_kysely2 = require("kysely");
271
178
 
272
179
  // src/serialization.ts
273
180
  function serializeValue(value, column) {
@@ -370,72 +277,194 @@ function deserializeValue(value, column) {
370
277
  return value;
371
278
  }
372
279
 
280
+ // src/operators.ts
281
+ var eq = (column, value, tableAlias) => {
282
+ const colRef = tableAlias ? `${tableAlias}.${column._.name}` : column._.name;
283
+ const serialized = serializeValue(value, column);
284
+ return import_kysely2.sql`${import_kysely2.sql.ref(colRef)} = ${import_kysely2.sql.val(serialized)}`;
285
+ };
286
+ var ne = (column, value, tableAlias) => {
287
+ const colRef = tableAlias ? `${tableAlias}.${column._.name}` : column._.name;
288
+ const serialized = serializeValue(value, column);
289
+ return import_kysely2.sql`${import_kysely2.sql.ref(colRef)} != ${import_kysely2.sql.val(serialized)}`;
290
+ };
291
+ var and = (...conditions) => {
292
+ if (conditions.length === 0) return import_kysely2.sql`1 = 1`;
293
+ if (conditions.length === 1) return conditions[0];
294
+ return import_kysely2.sql`(${import_kysely2.sql.join(conditions.map((c) => import_kysely2.sql`(${c})`), import_kysely2.sql` AND `)})`;
295
+ };
296
+ var or = (...conditions) => {
297
+ if (conditions.length === 0) return import_kysely2.sql`1 = 1`;
298
+ if (conditions.length === 1) return conditions[0];
299
+ return import_kysely2.sql`(${import_kysely2.sql.join(conditions.map((c) => import_kysely2.sql`(${c})`), import_kysely2.sql` OR `)})`;
300
+ };
301
+ var not = (condition) => import_kysely2.sql`NOT (${condition})`;
302
+ var gt = (column, value) => {
303
+ const serialized = serializeValue(value, column);
304
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} > ${import_kysely2.sql.val(serialized)}`;
305
+ };
306
+ var gte = (column, value) => {
307
+ const serialized = serializeValue(value, column);
308
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} >= ${import_kysely2.sql.val(serialized)}`;
309
+ };
310
+ var lt = (column, value) => {
311
+ const serialized = serializeValue(value, column);
312
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} < ${import_kysely2.sql.val(serialized)}`;
313
+ };
314
+ var lte = (column, value) => {
315
+ const serialized = serializeValue(value, column);
316
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} <= ${import_kysely2.sql.val(serialized)}`;
317
+ };
318
+ var like = (column, pattern) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} LIKE ${import_kysely2.sql.val(pattern)}`;
319
+ var ilike = (column, pattern) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} LIKE ${import_kysely2.sql.val(pattern)} COLLATE NOCASE`;
320
+ var startsWith = (column, value) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} LIKE ${import_kysely2.sql.val(`${value}%`)}`;
321
+ var endsWith = (column, value) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} LIKE ${import_kysely2.sql.val(`%${value}`)}`;
322
+ var contains = (column, value) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} LIKE ${import_kysely2.sql.val(`%${value}%`)}`;
323
+ var isNull = (column) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} IS NULL`;
324
+ var isNotNull = (column) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} IS NOT NULL`;
325
+ var exists = (subquery2) => import_kysely2.sql`EXISTS ${subquery2}`;
326
+ var notExists = (subquery2) => import_kysely2.sql`NOT EXISTS ${subquery2}`;
327
+ var eqSubquery = (column, subquery2) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} = (${subquery2})`;
328
+ var neSubquery = (column, subquery2) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} != (${subquery2})`;
329
+ var gtSubquery = (column, subquery2) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} > (${subquery2})`;
330
+ var gteSubquery = (column, subquery2) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} >= (${subquery2})`;
331
+ var ltSubquery = (column, subquery2) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} < (${subquery2})`;
332
+ var lteSubquery = (column, subquery2) => import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} <= (${subquery2})`;
333
+ var inArray = (column, values) => {
334
+ if ((0, import_kysely2.isExpression)(values)) {
335
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} IN (${values})`;
336
+ }
337
+ const arr = values;
338
+ if (arr.length === 0) return import_kysely2.sql`1 = 0`;
339
+ const serialized = arr.map((v) => import_kysely2.sql.val(serializeValue(v, column)));
340
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} IN (${import_kysely2.sql.join(serialized)})`;
341
+ };
342
+ var notIn = (column, values) => {
343
+ if ((0, import_kysely2.isExpression)(values)) {
344
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} NOT IN (${values})`;
345
+ }
346
+ const arr = values;
347
+ if (arr.length === 0) return import_kysely2.sql`1 = 1`;
348
+ const serialized = arr.map((v) => import_kysely2.sql.val(serializeValue(v, column)));
349
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} NOT IN (${import_kysely2.sql.join(serialized)})`;
350
+ };
351
+ var between = (column, min2, max2) => {
352
+ const serializedMin = serializeValue(min2, column);
353
+ const serializedMax = serializeValue(max2, column);
354
+ return import_kysely2.sql`${import_kysely2.sql.ref(column._.name)} BETWEEN ${import_kysely2.sql.val(serializedMin)} AND ${import_kysely2.sql.val(serializedMax)}`;
355
+ };
356
+
373
357
  // 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}"`
358
+ function getDbNameToTsName(table) {
359
+ const map = {};
360
+ for (const [tsName, col] of Object.entries(table._.columns)) {
361
+ map[col._.name] = tsName;
362
+ }
363
+ return map;
364
+ }
365
+ function normalizeRowKey(key) {
366
+ if (key.startsWith('"') && key.endsWith('"')) {
367
+ return key.slice(1, -1);
368
+ }
369
+ return key;
370
+ }
371
+ function resolveRelationColumns(table, include) {
372
+ const allEntries = Object.entries(table._.columns);
373
+ if (include === true || typeof include !== "object") {
374
+ return allEntries.map(([, col]) => col);
375
+ }
376
+ const cols = include.columns;
377
+ if (!cols) {
378
+ return allEntries.map(([, col]) => col);
379
+ }
380
+ const names = Array.isArray(cols) ? cols : Object.entries(cols).filter(([, v]) => v).map(([k]) => k);
381
+ const pkNames = allEntries.filter(([, c]) => c.options.primaryKey).map(([k]) => k);
382
+ const combined = /* @__PURE__ */ new Set([...names, ...pkNames]);
383
+ return allEntries.filter(([tsName]) => combined.has(tsName)).map(([, col]) => col);
384
+ }
385
+ var SelectQueryBuilder = class {
386
+ constructor(kysely, table, columns) {
387
+ this.kysely = kysely;
388
+ this._table = table;
389
+ this._columns = columns;
390
+ const selected = columns ? columns.map((c) => table._.columns[c]) : Object.values(table._.columns);
391
+ const colSelections = selected.map(
392
+ (col) => `${table._.name}.${col._.name} as "${table._.name}.${col._.name}"`
383
393
  );
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 = [];
394
+ this._includedColumnAliases = colSelections;
395
+ this._builder = kysely.selectFrom(table._.name).select(colSelections);
396
+ }
397
+ _builder;
398
+ _table;
399
+ _columns;
400
+ _includeRelations = {};
401
+ _manualJoins = [];
402
+ _isDistinct = false;
403
+ _includedColumnAliases = [];
393
404
  distinct() {
394
- this.isDistinct = true;
405
+ this._isDistinct = true;
406
+ this._builder = this._builder.distinct();
407
+ return this;
408
+ }
409
+ where(condition) {
410
+ this._builder = this._builder.where(condition);
411
+ return this;
412
+ }
413
+ orderBy(column, direction = "asc") {
414
+ if ("toOperationNode" in column) {
415
+ this._builder = this._builder.orderBy(column, direction);
416
+ } else {
417
+ this._builder = this._builder.orderBy(
418
+ import_kysely3.sql.ref(column._.name),
419
+ direction
420
+ );
421
+ }
422
+ return this;
423
+ }
424
+ limit(count2) {
425
+ this._builder = this._builder.limit(count2);
426
+ return this;
427
+ }
428
+ offset(count2) {
429
+ this._builder = this._builder.offset(count2);
395
430
  return this;
396
431
  }
397
432
  groupBy(...columns) {
398
- this.groupByColumns.push(...columns);
399
- const columnNames = columns.map((col) => `${this.selectedTableAlias}.${col._.name}`).join(", ");
400
- this.query += ` GROUP BY ${columnNames}`;
433
+ for (const col of columns) {
434
+ this._builder = this._builder.groupBy(
435
+ import_kysely3.sql`${import_kysely3.sql.ref(this._table._.name)}.${import_kysely3.sql.ref(col._.name)}`
436
+ );
437
+ }
401
438
  return this;
402
439
  }
403
440
  having(condition) {
404
- this.havingCondition = condition;
405
- this.query += ` HAVING ${condition.sql}`;
406
- this.params.push(...condition.params);
441
+ this._builder = this._builder.having(condition);
407
442
  return this;
408
443
  }
409
444
  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}"`
445
+ this._manualJoins.push({ type: "LEFT", table, condition, alias: alias2 });
446
+ const aliasedCols = Object.values(table._.columns).map(
447
+ (col) => `${alias2}.${col._.name} as "${alias2}.${col._.name}"`
413
448
  );
414
- this.selectedColumns.push(...aliasedColumns);
449
+ this._builder = this._builder.leftJoin(`${table._.name} as ${alias2}`, (join) => join.on(condition)).select(aliasedCols);
415
450
  return this;
416
451
  }
417
452
  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}"`
453
+ this._manualJoins.push({ type: "INNER", table, condition, alias: alias2 });
454
+ const aliasedCols = Object.values(table._.columns).map(
455
+ (col) => `${alias2}.${col._.name} as "${alias2}.${col._.name}"`
421
456
  );
422
- this.selectedColumns.push(...aliasedColumns);
457
+ this._builder = this._builder.innerJoin(`${table._.name} as ${alias2}`, (join) => join.on(condition)).select(aliasedCols);
423
458
  return this;
424
459
  }
425
460
  include(relations2) {
426
- this.includeRelations = { ...this.includeRelations, ...relations2 };
461
+ this._includeRelations = { ...this._includeRelations, ...relations2 };
427
462
  return this;
428
463
  }
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
- }
464
+ applyIncludes() {
436
465
  const processRelations = (parentTable, parentAlias, relations2, depth = 0) => {
437
466
  if (depth > 10) {
438
- console.warn("[Tauri-ORM] Maximum relation depth (10) exceeded. Skipping deeper relations.");
467
+ console.warn("[Tauri-ORM] Maximum relation depth (10) exceeded.");
439
468
  return;
440
469
  }
441
470
  for (const [relationName, include] of Object.entries(relations2)) {
@@ -443,77 +472,72 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
443
472
  const relation = parentTable.relations[relationName];
444
473
  if (!relation) {
445
474
  console.warn(
446
- `[Tauri-ORM] Relation "${relationName}" not found on table "${parentTable._.name}". Skipping include.`
475
+ `[Tauri-ORM] Relation "${relationName}" not found on table "${parentTable._.name}". Skipping.`
447
476
  );
448
477
  continue;
449
478
  }
450
479
  const foreignTable = relation.foreignTable;
451
480
  const foreignAlias = `${parentAlias}_${relationName}`;
452
- const aliasedColumns = Object.values(foreignTable._.columns).map(
453
- (col) => `${foreignAlias}.${col._.name} AS "${foreignAlias}.${col._.name}"`
481
+ const selectedCols = resolveRelationColumns(foreignTable, include);
482
+ const aliasedCols = selectedCols.map(
483
+ (col) => `${foreignAlias}.${col._.name} as "${foreignAlias}.${col._.name}"`
454
484
  );
455
- this.selectedColumns.push(...aliasedColumns);
456
485
  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);
486
+ const onCondition = import_kysely3.sql`${import_kysely3.sql.join(
487
+ relation.fields.map(
488
+ (field, i) => import_kysely3.sql`${import_kysely3.sql.ref(`${parentAlias}.${field._.name}`)} = ${import_kysely3.sql.ref(`${foreignAlias}.${relation.references[i]._.name}`)}`
489
+ ),
490
+ import_kysely3.sql` AND `
491
+ )}`;
492
+ this._builder = this._builder.leftJoin(
493
+ `${foreignTable._.name} as ${foreignAlias}`,
494
+ (join) => join.on(onCondition)
495
+ ).select(aliasedCols);
468
496
  } else if (relation.type === "many") {
469
- const refRelation = Object.entries(foreignTable.relations).find(
470
- ([_, r]) => r.foreignTable === parentTable
471
- );
472
- 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);
497
+ if (relation.junctionTable && relation.fromJunction && relation.toJunction) {
498
+ const junctionTable = relation.junctionTable;
499
+ const junctionAlias = `${foreignAlias}_jn`;
500
+ const fromJ = relation.fromJunction;
501
+ const toJ = relation.toJunction;
502
+ const join1 = import_kysely3.sql`${import_kysely3.sql.ref(`${parentAlias}.${fromJ.column._.name}`)} = ${import_kysely3.sql.ref(`${junctionAlias}.${fromJ.junctionColumn._.name}`)}`;
503
+ let join2 = import_kysely3.sql`${import_kysely3.sql.ref(`${junctionAlias}.${toJ.junctionColumn._.name}`)} = ${import_kysely3.sql.ref(`${foreignAlias}.${toJ.column._.name}`)}`;
504
+ if (relation.where) {
505
+ join2 = and(join2, relation.where(foreignAlias));
506
+ }
507
+ this._builder = this._builder.leftJoin(
508
+ `${junctionTable._.name} as ${junctionAlias}`,
509
+ (join) => join.on(join1)
510
+ ).leftJoin(
511
+ `${foreignTable._.name} as ${foreignAlias}`,
512
+ (join) => join.on(join2)
513
+ ).select(aliasedCols);
514
+ } else {
515
+ let fields = relation.fields;
516
+ let references = relation.references;
517
+ if (!fields || !references) {
518
+ const refRelation = Object.entries(foreignTable.relations).find(
519
+ ([, r]) => r.foreignTable === parentTable
520
+ );
521
+ if (refRelation && refRelation[1].fields && refRelation[1].references) {
522
+ const [, relationConfig] = refRelation;
523
+ fields = relationConfig.fields;
524
+ references = relationConfig.references;
525
+ }
526
+ }
527
+ if (fields && references) {
528
+ let onCondition = import_kysely3.sql`${import_kysely3.sql.join(
529
+ fields.map(
530
+ (field, i) => import_kysely3.sql`${import_kysely3.sql.ref(`${foreignAlias}.${field._.name}`)} = ${import_kysely3.sql.ref(`${parentAlias}.${references[i]._.name}`)}`
531
+ ),
532
+ import_kysely3.sql` AND `
533
+ )}`;
534
+ if (relation.where) {
535
+ onCondition = and(onCondition, relation.where(foreignAlias));
536
+ }
537
+ this._builder = this._builder.leftJoin(
538
+ `${foreignTable._.name} as ${foreignAlias}`,
539
+ (join) => join.on(onCondition)
540
+ ).select(aliasedCols);
517
541
  }
518
542
  }
519
543
  }
@@ -522,184 +546,160 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
522
546
  }
523
547
  }
524
548
  };
525
- processRelations(this.table, this.selectedTableAlias, this.includeRelations, 0);
526
- return { sql: sql2, params };
549
+ processRelations(this._table, this._table._.name, this._includeRelations, 0);
527
550
  }
528
- // Enhanced execute method that handles relation data mapping
529
551
  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);
552
+ this.applyIncludes();
553
+ const rawResults = await this._builder.execute();
554
+ const hasIncludes = Object.values(this._includeRelations).some((i) => i);
544
555
  if (hasIncludes) {
545
556
  return this.processRelationResults(rawResults);
546
557
  }
547
- const hasJoins = this.joins.length > 0;
548
- if (hasJoins) {
558
+ const hasManualJoins = this._manualJoins.length > 0;
559
+ if (hasManualJoins) {
549
560
  return rawResults;
550
561
  }
551
- const prefix = `${this.selectedTableAlias}.`;
562
+ const prefix = `${this._table._.name}.`;
563
+ const dbNameToTs = getDbNameToTsName(this._table);
552
564
  return rawResults.map((row) => {
553
- const newRow = {};
565
+ const out = {};
554
566
  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
- }
567
+ const normKey = normalizeRowKey(key);
568
+ const dbColName = normKey.startsWith(prefix) ? normKey.slice(prefix.length) : normKey;
569
+ const tsName = dbNameToTs[dbColName] ?? dbColName;
570
+ const column = this._table._.columns[tsName];
571
+ out[tsName] = column ? deserializeValue(row[key], column) : row[key];
562
572
  }
563
- return newRow;
573
+ return out;
564
574
  });
565
575
  }
566
576
  processRelationResults(rawResults) {
567
577
  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
- }
578
+ const mainTablePks = Object.values(this._table._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
579
+ if (mainTablePks.length === 0) return rawResults;
572
580
  const groupedResults = /* @__PURE__ */ new Map();
573
581
  const parseRelationPath = (tableAlias, baseAlias) => {
574
- if (!tableAlias.startsWith(baseAlias + "_")) {
575
- return [];
576
- }
577
- const path = tableAlias.substring(baseAlias.length + 1);
578
- return path.split("_");
582
+ if (!tableAlias.startsWith(baseAlias + "_")) return [];
583
+ return tableAlias.slice(baseAlias.length + 1).split("_");
579
584
  };
580
- const setNestedValue = (obj, path, value, columnName) => {
581
- let current = obj;
585
+ const setNestedValue = (obj, path, columnName, value) => {
586
+ let cur = obj;
582
587
  for (let i = 0; i < path.length; i++) {
583
588
  const key = path[i];
584
589
  if (i === path.length - 1) {
585
- if (!current[key]) current[key] = {};
586
- current[key][columnName] = value;
590
+ if (!cur[key]) cur[key] = {};
591
+ cur[key][columnName] = value;
587
592
  } else {
588
- if (!current[key]) current[key] = {};
589
- current = current[key];
593
+ if (!cur[key]) cur[key] = {};
594
+ cur = cur[key];
590
595
  }
591
596
  }
592
597
  };
593
598
  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;
599
+ let current = table;
600
+ let relation = null;
601
+ for (const name of path) {
602
+ relation = current.relations[name];
603
+ if (!relation) return null;
604
+ current = relation.foreignTable;
600
605
  }
601
- return currentRelation;
606
+ return relation;
602
607
  };
603
608
  for (const row of rawResults) {
604
- const mainTableKey = mainTablePks.map((pk) => row[`${this.selectedTableAlias}.${pk}`] ?? row[pk]).join("_");
609
+ const getVal = (logicalKey) => {
610
+ const quoted = `"${logicalKey}"`;
611
+ return row[quoted] ?? row[logicalKey];
612
+ };
613
+ const mainTableKey = mainTablePks.map((pk) => getVal(`${this._table._.name}.${pk}`) ?? getVal(pk)).join("_");
605
614
  if (!groupedResults.has(mainTableKey)) {
606
615
  groupedResults.set(mainTableKey, {});
607
616
  }
608
617
  const result = groupedResults.get(mainTableKey);
609
618
  const relations2 = {};
610
619
  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;
620
+ const normKey = normalizeRowKey(key);
621
+ if (!normKey.includes(".")) {
622
+ const mainDbToTs = getDbNameToTsName(this._table);
623
+ const tsName = mainDbToTs[normKey] ?? normKey;
624
+ const column = this._table._.columns[tsName];
625
+ result[tsName] = column ? deserializeValue(value, column) : value;
626
+ continue;
627
+ }
628
+ const dotIndex = normKey.indexOf(".");
629
+ const tableAlias = normKey.slice(0, dotIndex);
630
+ const columnName = normKey.slice(dotIndex + 1);
631
+ if (tableAlias === this._table._.name) {
632
+ const mainDbToTs = getDbNameToTsName(this._table);
633
+ const tsName = mainDbToTs[columnName] ?? columnName;
634
+ const column = this._table._.columns[tsName];
635
+ result[tsName] = column ? deserializeValue(value, column) : value;
636
+ } else {
637
+ if (tableAlias.endsWith("_jn")) continue;
638
+ const path = parseRelationPath(tableAlias, this._table._.name);
639
+ if (path.length > 0) {
640
+ const relationConfig = getNestedRelation(this._table, path);
641
+ const foreignTable = relationConfig?.foreignTable;
642
+ const foreignDbToTs = foreignTable ? getDbNameToTsName(foreignTable) : {};
643
+ const tsName = foreignDbToTs[columnName] ?? columnName;
644
+ const col = foreignTable?._.columns?.[tsName];
645
+ setNestedValue(relations2, path, tsName, col ? deserializeValue(value, col) : value);
616
646
  } 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
- }
647
+ if (!result[tableAlias]) result[tableAlias] = {};
648
+ result[tableAlias][columnName] = value;
627
649
  }
628
- } else {
629
- const column = this.table._.columns[key];
630
- result[key] = column ? deserializeValue(value, column) : value;
631
650
  }
632
651
  }
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);
652
+ const attachRelations = (target, relData, table) => {
653
+ for (const [relName, data] of Object.entries(relData)) {
654
+ const relationConfig = table.relations[relName];
637
655
  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
- }
656
+ const directData = {};
657
+ const nestedData = {};
658
+ if (typeof data === "object" && data !== null) {
659
+ for (const [k, v] of Object.entries(data)) {
660
+ if (typeof v === "object" && v !== null) {
661
+ nestedData[k] = v;
662
+ } else {
663
+ directData[k] = v;
658
664
  }
659
665
  }
660
- const hasData = Object.values(directData).some(
661
- (v) => v !== null && v !== void 0 && v !== ""
662
- );
666
+ }
667
+ const hasData = Object.values(directData).some(
668
+ (v) => v !== null && v !== void 0 && v !== ""
669
+ );
670
+ if (relationConfig.type === "many") {
671
+ if (!target[relName]) target[relName] = [];
663
672
  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)) {
673
+ const relPks = Object.values(relationConfig.foreignTable._.columns).filter((c) => c.options.primaryKey).map((c) => c._.name);
674
+ const key = relPks.map((pk) => directData[pk]).join("_");
675
+ if (relPks.length === 0 || !target[relName].some(
676
+ (r) => relPks.map((pk) => r[pk]).join("_") === key
677
+ )) {
667
678
  const newItem = { ...directData };
668
679
  if (Object.keys(nestedData).length > 0) {
669
- attachRelations(newItem, nestedData, relationConfig.foreignTable, []);
680
+ attachRelations(newItem, nestedData, relationConfig.foreignTable);
670
681
  }
671
682
  target[relName].push(newItem);
672
683
  }
673
684
  }
674
685
  } 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
686
  if (hasData || Object.keys(nestedData).length > 0) {
690
687
  target[relName] = { ...directData };
691
688
  if (Object.keys(nestedData).length > 0) {
692
- attachRelations(target[relName], nestedData, relationConfig.foreignTable, []);
689
+ attachRelations(
690
+ target[relName],
691
+ nestedData,
692
+ relationConfig.foreignTable
693
+ );
693
694
  }
694
695
  }
695
696
  }
696
697
  }
697
698
  };
698
- attachRelations(result, relations2, this.table);
699
+ attachRelations(result, relations2, this._table);
699
700
  }
700
701
  return Array.from(groupedResults.values());
701
702
  }
702
- // Update the return type signatures
703
703
  async all() {
704
704
  return this.execute();
705
705
  }
@@ -708,61 +708,32 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
708
708
  const result = await this.execute();
709
709
  return result[0];
710
710
  }
711
+ async first() {
712
+ return this.get();
713
+ }
711
714
  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;
715
+ this.applyIncludes();
716
+ const compiledResult = await this._builder.clearSelect().select(import_kysely3.sql.raw("1").as("__exists__")).limit(1).execute();
717
+ return compiledResult.length > 0;
727
718
  }
728
719
  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();
720
+ this.applyIncludes();
721
+ const result = await this._builder.clearSelect().select(import_kysely3.sql`COUNT(*)`.as("count")).execute();
722
+ const row = result[0];
723
+ const val = row ? row['"count"'] ?? row.count : void 0;
724
+ return Number(val ?? 0);
747
725
  }
748
726
  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]);
727
+ this.applyIncludes();
728
+ const col = this._table._.columns[column];
729
+ const alias2 = col._.name;
730
+ const results = await this._builder.clearSelect().select(
731
+ import_kysely3.sql.raw(`${this._table._.name}.${alias2}`).as(alias2)
732
+ ).execute();
733
+ return results.map((row) => {
734
+ const val = row['"' + alias2 + '"'] ?? row[alias2];
735
+ return col ? deserializeValue(val, col) : val;
736
+ });
766
737
  }
767
738
  async paginate(page = 1, pageSize = 10) {
768
739
  if (page < 1) page = 1;
@@ -782,16 +753,19 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
782
753
  };
783
754
  }
784
755
  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
- };
756
+ this.applyIncludes();
757
+ const compiled = this._builder.compile();
758
+ return { sql: compiled.sql, params: [...compiled.parameters] };
759
+ }
760
+ toKyselyExpression() {
761
+ this.applyIncludes();
762
+ return this._builder;
792
763
  }
793
764
  };
794
765
 
766
+ // src/builders/update.ts
767
+ var import_kysely4 = require("kysely");
768
+
795
769
  // src/errors.ts
796
770
  var TauriORMError = class extends Error {
797
771
  constructor(message) {
@@ -860,414 +834,384 @@ var TableNotFoundError = class extends TauriORMError {
860
834
  };
861
835
 
862
836
  // 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 = [];
837
+ var UpdateQueryBuilder = class {
838
+ constructor(kysely, table) {
839
+ this.kysely = kysely;
840
+ this._table = table;
841
+ this._builder = kysely.updateTable(table._.name);
842
+ }
843
+ _builder;
844
+ _table;
845
+ _updateData = {};
846
+ _returningColumns = [];
847
+ _hasWhereClause = false;
848
+ _allowGlobal = false;
849
+ _incrementDecrementOps = [];
874
850
  set(data) {
875
- this.updateData = { ...this.updateData, ...data };
851
+ this._updateData = { ...this._updateData, ...data };
876
852
  return this;
877
853
  }
878
854
  where(condition) {
879
- this.hasWhereClause = true;
880
- return super.where(condition);
855
+ this._hasWhereClause = true;
856
+ this._builder = this._builder.where(condition);
857
+ return this;
881
858
  }
882
859
  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 });
860
+ const col = this._table._.columns[column];
861
+ if (!col) throw new ColumnNotFoundError(String(column), this._table._.name);
862
+ this._incrementDecrementOps.push({ column: col._.name, op: "increment", value });
888
863
  return this;
889
864
  }
890
865
  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 });
866
+ const col = this._table._.columns[column];
867
+ if (!col) throw new ColumnNotFoundError(String(column), this._table._.name);
868
+ this._incrementDecrementOps.push({ column: col._.name, op: "decrement", value });
896
869
  return this;
897
870
  }
898
871
  allowGlobalOperation() {
899
- this.allowGlobal = true;
872
+ this._allowGlobal = true;
900
873
  return this;
901
874
  }
902
875
  returning(...columns) {
903
- this.returningColumns.push(...columns);
876
+ this._returningColumns.push(...columns);
904
877
  return this;
905
878
  }
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();
879
+ mapReturningRows(rows) {
880
+ const dbNameToTs = {};
881
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
882
+ dbNameToTs[col._.name] = tsName;
883
+ }
884
+ const norm = (k) => k.startsWith('"') && k.endsWith('"') ? k.slice(1, -1) : k;
885
+ return rows.map((row) => {
886
+ const out = {};
887
+ for (const [dbKey, value] of Object.entries(row)) {
888
+ const logicalKey = norm(dbKey);
889
+ const tsName = dbNameToTs[logicalKey] ?? logicalKey;
890
+ const column = this._table._.columns[tsName];
891
+ out[tsName] = column ? deserializeValue(value, column) : value;
892
+ }
893
+ return out;
894
+ });
895
+ }
896
+ buildSetClause() {
897
+ const finalData = { ...this._updateData };
898
+ for (const [key, column] of Object.entries(this._table._.columns)) {
899
+ if (finalData[key] === void 0 && column.options.$onUpdateFn) {
900
+ ;
901
+ finalData[key] = column.options.$onUpdateFn();
912
902
  }
913
903
  }
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);
904
+ const entries = Object.entries(finalData);
924
905
  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.");
906
+ const hasOps = this._incrementDecrementOps.length > 0;
907
+ if (!hasSetData && !hasOps) {
908
+ throw new UpdateValidationError(
909
+ "Cannot execute an update query without a .set(), .increment(), or .decrement() call."
910
+ );
928
911
  }
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
- }
912
+ const setMap = {};
913
+ for (const [key, value] of entries) {
914
+ const column = this._table._.columns[key];
915
+ if (!column) throw new ColumnNotFoundError(key, this._table._.name);
916
+ setMap[column._.name] = serializeValue(value, column);
940
917
  }
941
- for (const op of this.incrementDecrementOps) {
918
+ for (const op of this._incrementDecrementOps) {
942
919
  const sign = op.op === "increment" ? "+" : "-";
943
- setClauses.push(`${op.column} = ${op.column} ${sign} ?`);
944
- setParams.push(op.value);
920
+ setMap[op.column] = import_kysely4.sql.raw(`${op.column} ${sign} ${op.value}`);
945
921
  }
946
- const setClause = setClauses.join(", ");
947
- const sql2 = `${tablePart} SET ${setClause}${whereClause}`;
948
- const params = [...setParams, ...whereParams];
949
- return { sql: sql2, params };
922
+ return setMap;
950
923
  }
951
924
  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 }];
925
+ if (!this._hasWhereClause && !this._allowGlobal) {
926
+ throw new MissingWhereClauseError("UPDATE", this._table._.name);
927
+ }
928
+ const setMap = this.buildSetClause();
929
+ let builder = this._builder.set(setMap);
930
+ if (this._returningColumns.length > 0) {
931
+ const cols = this._returningColumns.map(
932
+ (k) => this._table._.columns[k]._.name
933
+ );
934
+ const rows = await builder.returning(cols).execute();
935
+ return this.mapReturningRows(rows);
963
936
  }
937
+ const result = await builder.executeTakeFirst();
938
+ return [{ rowsAffected: Number(result?.numUpdatedRows ?? 0) }];
964
939
  }
965
940
  async returningAll() {
966
- const allColumns = Object.keys(
967
- this.table._.columns
968
- );
969
- return this.returning(...allColumns).execute();
941
+ const allCols = Object.keys(this._table._.columns);
942
+ return this.returning(...allCols).execute();
970
943
  }
971
944
  async returningFirst() {
972
- const allColumns = Object.keys(
973
- this.table._.columns
974
- );
975
- const results = await this.returning(...allColumns).execute();
945
+ const results = await this.returningAll();
976
946
  return results[0];
977
947
  }
978
948
  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
- };
949
+ const setMap = this.buildSetClause();
950
+ let builder = this._builder.set(setMap);
951
+ if (this._returningColumns.length > 0) {
952
+ builder = builder.returning(
953
+ this._returningColumns.map((k) => this._table._.columns[k]._.name)
954
+ );
986
955
  }
987
- return { sql: updateSql, params };
956
+ const compiled = builder.compile();
957
+ return { sql: compiled.sql, params: [...compiled.parameters] };
988
958
  }
989
959
  };
990
960
 
991
961
  // 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 = {};
962
+ var InsertQueryBuilder = class {
963
+ constructor(kysely, table) {
964
+ this.kysely = kysely;
965
+ this._table = table;
966
+ this._builder = kysely.insertInto(table._.name);
967
+ }
968
+ _builder;
969
+ _table;
970
+ _dataSets = [];
971
+ _returningColumns = [];
972
+ _onConflictAction = null;
973
+ _conflictTarget = [];
974
+ _updateSet = {};
1003
975
  values(data) {
1004
- const dataArray = Array.isArray(data) ? data : [data];
1005
- this.dataSets.push(...dataArray);
976
+ const arr = Array.isArray(data) ? data : [data];
977
+ this._dataSets.push(...arr);
1006
978
  return this;
1007
979
  }
1008
980
  returning(...columns) {
1009
- this.returningColumns.push(...columns);
981
+ this._returningColumns.push(...columns);
1010
982
  return this;
1011
983
  }
1012
984
  onConflictDoNothing(target) {
1013
- this.onConflictAction = "nothing";
985
+ this._onConflictAction = "nothing";
1014
986
  if (target) {
1015
- this.conflictTarget = Array.isArray(target) ? target : [target];
987
+ this._conflictTarget = Array.isArray(target) ? target : [target];
1016
988
  }
1017
989
  return this;
1018
990
  }
1019
991
  onConflictDoUpdate(config) {
1020
- this.onConflictAction = "update";
1021
- this.conflictTarget = Array.isArray(config.target) ? config.target : [config.target];
1022
- this.updateSet = config.set;
992
+ this._onConflictAction = "update";
993
+ this._conflictTarget = Array.isArray(config.target) ? config.target : [config.target];
994
+ this._updateSet = config.set;
1023
995
  return this;
1024
996
  }
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
- }
997
+ processDefaults(data) {
998
+ const out = { ...data };
999
+ for (const [key, column] of Object.entries(this._table._.columns)) {
1000
+ if (out[key] === void 0 && column.options.$defaultFn) {
1001
+ ;
1002
+ out[key] = column.options.$defaultFn();
1033
1003
  }
1034
1004
  }
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}`;
1005
+ return out;
1006
+ }
1007
+ mapReturningRows(rows) {
1008
+ const dbNameToTs = {};
1009
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
1010
+ dbNameToTs[col._.name] = tsName;
1011
+ }
1012
+ const norm = (k) => k.startsWith('"') && k.endsWith('"') ? k.slice(1, -1) : k;
1013
+ return rows.map((row) => {
1014
+ const out = {};
1015
+ for (const [dbKey, value] of Object.entries(row)) {
1016
+ const logicalKey = norm(dbKey);
1017
+ const tsName = dbNameToTs[logicalKey] ?? logicalKey;
1018
+ const column = this._table._.columns[tsName];
1019
+ out[tsName] = column ? deserializeValue(value, column) : value;
1051
1020
  }
1021
+ return out;
1022
+ });
1023
+ }
1024
+ serializeDataSet(data) {
1025
+ const out = {};
1026
+ for (const [key, value] of Object.entries(data)) {
1027
+ const column = this._table._.columns[key];
1028
+ out[column ? column._.name : key] = column ? serializeValue(value, column) : value;
1052
1029
  }
1053
- return clause;
1030
+ return out;
1054
1031
  }
1055
1032
  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
1033
+ if (this._dataSets.length === 0) {
1034
+ throw new InsertValidationError(
1035
+ "No data provided for insert. Use .values() to provide data."
1077
1036
  );
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
- })
1090
- );
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
- }
1037
+ }
1038
+ const processed = this._dataSets.map((d) => this.serializeDataSet(this.processDefaults(d)));
1039
+ let builder = this._builder.values(processed.length === 1 ? processed[0] : processed);
1040
+ if (this._onConflictAction === "nothing") {
1041
+ if (this._conflictTarget.length > 0) {
1042
+ const targetCols = this._conflictTarget.map((c) => c._.name);
1043
+ builder = builder.onConflict(
1044
+ (oc) => oc.columns(targetCols).doNothing()
1097
1045
  );
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
1046
  } else {
1106
- const result = await this.db.execute(finalQuery, params);
1107
- lastInsertId = result.lastInsertId;
1108
- rowsAffected += result.rowsAffected;
1047
+ builder = builder.onConflict((oc) => oc.doNothing());
1109
1048
  }
1049
+ } else if (this._onConflictAction === "update") {
1050
+ const targetCols = this._conflictTarget.map((c) => c._.name);
1051
+ const updateData = this.serializeDataSet(this._updateSet);
1052
+ builder = builder.onConflict(
1053
+ (oc) => oc.columns(targetCols).doUpdateSet(updateData)
1054
+ );
1110
1055
  }
1111
- if (this.returningColumns.length > 0) {
1112
- return results;
1056
+ if (this._returningColumns.length > 0) {
1057
+ const cols = this._returningColumns.map(
1058
+ (k) => this._table._.columns[k]._.name
1059
+ );
1060
+ const rows = await builder.returning(cols).execute();
1061
+ return this.mapReturningRows(rows);
1113
1062
  }
1114
- return [{ lastInsertId, rowsAffected }];
1063
+ const result = await builder.executeTakeFirst();
1064
+ return [
1065
+ {
1066
+ lastInsertId: Number(result?.insertId ?? 0),
1067
+ rowsAffected: Number(result?.numInsertedOrUpdatedRows ?? 0)
1068
+ }
1069
+ ];
1115
1070
  }
1116
1071
  async returningAll() {
1117
- const allColumns = Object.keys(
1118
- this.table._.columns
1119
- );
1120
- return this.returning(...allColumns).execute();
1072
+ const allCols = Object.keys(this._table._.columns);
1073
+ return this.returning(...allCols).execute();
1121
1074
  }
1122
1075
  async returningFirst() {
1123
- const allColumns = Object.keys(
1124
- this.table._.columns
1125
- );
1126
- const results = await this.returning(...allColumns).execute();
1076
+ const results = await this.returningAll();
1127
1077
  return results[0];
1128
1078
  }
1129
1079
  toSQL() {
1130
- if (this.dataSets.length === 0) {
1131
- throw new InsertValidationError("No data provided for insert. Use .values() to provide data.");
1080
+ if (this._dataSets.length === 0) {
1081
+ throw new InsertValidationError(
1082
+ "No data provided for insert. Use .values() to provide data."
1083
+ );
1132
1084
  }
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
- }
1085
+ const processed = this._dataSets.map((d) => this.serializeDataSet(this.processDefaults(d)));
1086
+ let builder = this._builder.values(processed.length === 1 ? processed[0] : processed);
1087
+ if (this._onConflictAction === "nothing") {
1088
+ if (this._conflictTarget.length > 0) {
1089
+ builder = builder.onConflict(
1090
+ (oc) => oc.columns(this._conflictTarget.map((c) => c._.name)).doNothing()
1091
+ );
1092
+ } else {
1093
+ builder = builder.onConflict((oc) => oc.doNothing());
1094
+ }
1095
+ } else if (this._onConflictAction === "update") {
1096
+ const updateData = this.serializeDataSet(this._updateSet);
1097
+ builder = builder.onConflict(
1098
+ (oc) => oc.columns(this._conflictTarget.map((c) => c._.name)).doUpdateSet(updateData)
1160
1099
  );
1161
- params.push(...setValues);
1162
1100
  }
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
- };
1101
+ if (this._returningColumns.length > 0) {
1102
+ builder = builder.returning(
1103
+ this._returningColumns.map((k) => this._table._.columns[k]._.name)
1104
+ );
1169
1105
  }
1170
- return { sql: finalQuery, params };
1106
+ const compiled = builder.compile();
1107
+ return { sql: compiled.sql, params: [...compiled.parameters] };
1171
1108
  }
1172
1109
  };
1173
1110
 
1174
1111
  // 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;
1112
+ var DeleteQueryBuilder = class {
1113
+ constructor(kysely, table) {
1114
+ this.kysely = kysely;
1115
+ this._table = table;
1116
+ this._builder = kysely.deleteFrom(table._.name);
1117
+ }
1118
+ _builder;
1119
+ _table;
1120
+ _returningColumns = [];
1121
+ _hasWhereClause = false;
1122
+ _allowGlobal = false;
1123
+ mapReturningRows(rows) {
1124
+ const dbNameToTs = {};
1125
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
1126
+ dbNameToTs[col._.name] = tsName;
1127
+ }
1128
+ const norm = (k) => k.startsWith('"') && k.endsWith('"') ? k.slice(1, -1) : k;
1129
+ return rows.map((row) => {
1130
+ const out = {};
1131
+ for (const [dbKey, value] of Object.entries(row)) {
1132
+ const logicalKey = norm(dbKey);
1133
+ const tsName = dbNameToTs[logicalKey] ?? logicalKey;
1134
+ const column = this._table._.columns[tsName];
1135
+ out[tsName] = column ? deserializeValue(value, column) : value;
1136
+ }
1137
+ return out;
1138
+ });
1139
+ }
1184
1140
  where(condition) {
1185
- this.hasWhereClause = true;
1186
- return super.where(condition);
1141
+ this._hasWhereClause = true;
1142
+ this._builder = this._builder.where(condition);
1143
+ return this;
1187
1144
  }
1188
1145
  allowGlobalOperation() {
1189
- this.allowGlobal = true;
1146
+ this._allowGlobal = true;
1190
1147
  return this;
1191
1148
  }
1192
1149
  returning(...columns) {
1193
- this.returningColumns.push(...columns);
1150
+ this._returningColumns.push(...columns);
1194
1151
  return this;
1195
1152
  }
1196
1153
  async execute() {
1197
- if (!this.hasWhereClause && !this.allowGlobal) {
1198
- throw new MissingWhereClauseError("DELETE", this.table._.name);
1154
+ if (!this._hasWhereClause && !this._allowGlobal) {
1155
+ throw new MissingWhereClauseError("DELETE", this._table._.name);
1199
1156
  }
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 }];
1157
+ if (this._returningColumns.length > 0) {
1158
+ const cols = this._returningColumns.map(
1159
+ (k) => this._table._.columns[k]._.name
1160
+ );
1161
+ const rows = await this._builder.returning(cols).execute();
1162
+ return this.mapReturningRows(rows);
1208
1163
  }
1164
+ const result = await this._builder.executeTakeFirst();
1165
+ return [{ rowsAffected: Number(result?.numDeletedRows ?? 0) }];
1209
1166
  }
1210
1167
  async returningAll() {
1211
- const allColumns = Object.keys(this.table._.columns);
1212
- return this.returning(...allColumns).execute();
1168
+ const allCols = Object.keys(this._table._.columns);
1169
+ return this.returning(...allCols).execute();
1213
1170
  }
1214
1171
  async returningFirst() {
1215
- const allColumns = Object.keys(this.table._.columns);
1216
- const results = await this.returning(...allColumns).execute();
1172
+ const results = await this.returningAll();
1217
1173
  return results[0];
1218
1174
  }
1219
1175
  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
- };
1176
+ let builder = this._builder;
1177
+ if (this._returningColumns.length > 0) {
1178
+ builder = builder.returning(
1179
+ this._returningColumns.map((k) => this._table._.columns[k]._.name)
1180
+ );
1227
1181
  }
1228
- return { sql: sql2, params };
1182
+ const compiled = builder.compile();
1183
+ return { sql: compiled.sql, params: [...compiled.parameters] };
1229
1184
  }
1230
1185
  };
1231
1186
 
1232
1187
  // src/builders/with.ts
1233
1188
  var WithQueryBuilder = class {
1234
- constructor(db) {
1235
- this.db = db;
1189
+ constructor(kysely) {
1190
+ this.kysely = kysely;
1236
1191
  }
1237
- ctes = [];
1192
+ _ctes = [];
1238
1193
  with(alias2, query) {
1239
- this.ctes.push({ alias: alias2, query: query.sql, params: query.params });
1194
+ this._ctes.push({ alias: alias2, query: query.toKyselyExpression() });
1240
1195
  return this;
1241
1196
  }
1197
+ applyWith(builder) {
1198
+ let b = builder;
1199
+ for (const { alias: alias2, query } of this._ctes) {
1200
+ b = b.with(alias2, () => query);
1201
+ }
1202
+ return b;
1203
+ }
1242
1204
  select(table, columns) {
1243
- const builder = new SelectQueryBuilder(this.db, table, columns);
1244
- this.applyWithClause(builder);
1245
- return builder;
1205
+ return new SelectQueryBuilder(this.kysely, table, columns);
1246
1206
  }
1247
1207
  insert(table) {
1248
- const builder = new InsertQueryBuilder(this.db, table);
1249
- this.applyWithClause(builder);
1250
- return builder;
1208
+ return new InsertQueryBuilder(this.kysely, table);
1251
1209
  }
1252
1210
  update(table) {
1253
- const builder = new UpdateQueryBuilder(this.db, table);
1254
- this.applyWithClause(builder);
1255
- return builder;
1211
+ return new UpdateQueryBuilder(this.kysely, table);
1256
1212
  }
1257
1213
  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
- }
1214
+ return new DeleteQueryBuilder(this.kysely, table);
1271
1215
  }
1272
1216
  };
1273
1217
 
@@ -1310,7 +1254,7 @@ var SQLiteColumn = class _SQLiteColumn {
1310
1254
  unique() {
1311
1255
  return new _SQLiteColumn(this._.name, this.type, { ...this.options, unique: true, mode: this._.mode });
1312
1256
  }
1313
- references(ref, column) {
1257
+ references(ref, column, options) {
1314
1258
  const columnKey = typeof column === "string" ? column : column._.name;
1315
1259
  const columnObj = typeof column === "string" ? ref._.columns[column] : column;
1316
1260
  return new _SQLiteColumn(
@@ -1320,7 +1264,9 @@ var SQLiteColumn = class _SQLiteColumn {
1320
1264
  ...this.options,
1321
1265
  references: {
1322
1266
  table: ref,
1323
- column: columnObj
1267
+ column: columnObj,
1268
+ onDelete: options?.onDelete,
1269
+ onUpdate: options?.onUpdate
1324
1270
  },
1325
1271
  mode: this._.mode
1326
1272
  }
@@ -1349,39 +1295,14 @@ var Table = class {
1349
1295
  var sqliteTable = (tableName, columns) => {
1350
1296
  return new Table(tableName, columns);
1351
1297
  };
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
- };
1298
+ var asc = (column) => import_kysely5.sql`${import_kysely5.sql.ref(column._.name)} ASC`;
1299
+ var desc = (column) => import_kysely5.sql`${import_kysely5.sql.ref(column._.name)} DESC`;
1380
1300
  var TauriORM = class {
1381
1301
  constructor(db, schema = void 0) {
1382
1302
  this.db = db;
1303
+ this.kysely = new import_kysely5.Kysely({ dialect: new TauriDialect(db) });
1383
1304
  if (schema) {
1384
- for (const [key, value] of Object.entries(schema)) {
1305
+ for (const [, value] of Object.entries(schema)) {
1385
1306
  if (value instanceof Table) {
1386
1307
  this.tables.set(value._.name, value);
1387
1308
  }
@@ -1389,24 +1310,31 @@ var TauriORM = class {
1389
1310
  }
1390
1311
  }
1391
1312
  tables = /* @__PURE__ */ new Map();
1313
+ kysely;
1392
1314
  buildColumnDefinition(col, forAlterTable = false) {
1393
- let sql2 = `${col._.name} ${col.type}`;
1315
+ let sql6 = `${col._.name} ${col.type}`;
1394
1316
  if (col.options.primaryKey && !forAlterTable) {
1395
- sql2 += " PRIMARY KEY";
1317
+ sql6 += " PRIMARY KEY";
1396
1318
  if (col._.autoincrement) {
1397
- sql2 += " AUTOINCREMENT";
1319
+ sql6 += " AUTOINCREMENT";
1398
1320
  }
1399
1321
  }
1400
- if (col._.notNull) sql2 += " NOT NULL";
1401
- if (col.options.unique) sql2 += " UNIQUE";
1322
+ if (col._.notNull) sql6 += " NOT NULL";
1323
+ if (col.options.unique) sql6 += " UNIQUE";
1402
1324
  if (col.options.default !== void 0) {
1403
1325
  const value = col.options.default;
1404
- sql2 += ` DEFAULT ${typeof value === "string" ? `'${value.replace(/'/g, "''")}'` : value}`;
1326
+ sql6 += ` DEFAULT ${typeof value === "string" ? `'${value.replace(/'/g, "''")}'` : value}`;
1405
1327
  }
1406
1328
  if (col.options.references) {
1407
- sql2 += ` REFERENCES ${col.options.references.table._.name}(${col.options.references.column._.name})`;
1329
+ sql6 += ` REFERENCES ${col.options.references.table._.name}(${col.options.references.column._.name})`;
1330
+ if (col.options.references.onDelete) {
1331
+ sql6 += ` ON DELETE ${col.options.references.onDelete.toUpperCase()}`;
1332
+ }
1333
+ if (col.options.references.onUpdate) {
1334
+ sql6 += ` ON UPDATE ${col.options.references.onUpdate.toUpperCase()}`;
1335
+ }
1408
1336
  }
1409
- return sql2;
1337
+ return sql6;
1410
1338
  }
1411
1339
  async checkMigration() {
1412
1340
  const dbTables = await this.db.select(
@@ -1448,15 +1376,16 @@ var TauriORM = class {
1448
1376
  const schemaColumns = table._.columns;
1449
1377
  let needsRecreate = false;
1450
1378
  for (const [colName, column] of Object.entries(schemaColumns)) {
1451
- const existing = existingColumns.get(colName);
1379
+ const dbColName = column._.name;
1380
+ const existing = existingColumns.get(dbColName);
1452
1381
  if (!existing) {
1453
1382
  if (!this.canAddColumnWithAlter(column)) {
1454
1383
  needsRecreate = true;
1455
1384
  break;
1456
1385
  }
1457
- changes.columnsToAdd.push({ table: tableName, column: colName });
1386
+ changes.columnsToAdd.push({ table: tableName, column: dbColName });
1458
1387
  } else {
1459
- const hasUniqueInDB = uniqueColumns.has(colName);
1388
+ const hasUniqueInDB = uniqueColumns.has(dbColName);
1460
1389
  const wantsUnique = !!column.options.unique;
1461
1390
  if (hasUniqueInDB !== wantsUnique || this.hasColumnDefinitionChanged(column, existing)) {
1462
1391
  needsRecreate = true;
@@ -1465,7 +1394,8 @@ var TauriORM = class {
1465
1394
  }
1466
1395
  }
1467
1396
  for (const existingCol of existingColumns.keys()) {
1468
- if (!schemaColumns[existingCol]) {
1397
+ const schemaHasCol = Object.values(schemaColumns).some((c) => c._.name === existingCol);
1398
+ if (!schemaHasCol) {
1469
1399
  needsRecreate = true;
1470
1400
  break;
1471
1401
  }
@@ -1517,7 +1447,8 @@ var TauriORM = class {
1517
1447
  let needsRecreate = false;
1518
1448
  const columnsToAdd = [];
1519
1449
  for (const [colName, column] of Object.entries(schemaColumns)) {
1520
- const existing = existingColumns.get(colName);
1450
+ const dbColName = column._.name;
1451
+ const existing = existingColumns.get(dbColName);
1521
1452
  if (!existing) {
1522
1453
  if (this.canAddColumnWithAlter(column)) {
1523
1454
  columnsToAdd.push(column);
@@ -1526,7 +1457,7 @@ var TauriORM = class {
1526
1457
  break;
1527
1458
  }
1528
1459
  } else {
1529
- const hasUniqueInDB = uniqueColumns.has(colName);
1460
+ const hasUniqueInDB = uniqueColumns.has(dbColName);
1530
1461
  const wantsUnique = !!column.options.unique;
1531
1462
  if (hasUniqueInDB !== wantsUnique) {
1532
1463
  needsRecreate = true;
@@ -1540,7 +1471,8 @@ var TauriORM = class {
1540
1471
  }
1541
1472
  if (options?.performDestructiveActions) {
1542
1473
  for (const existingCol of existingColumns.keys()) {
1543
- if (!schemaColumns[existingCol]) {
1474
+ const schemaHasCol = Object.values(schemaColumns).some((c) => c._.name === existingCol);
1475
+ if (!schemaHasCol) {
1544
1476
  needsRecreate = true;
1545
1477
  break;
1546
1478
  }
@@ -1585,7 +1517,7 @@ var TauriORM = class {
1585
1517
  await this.db.execute(`CREATE TABLE ${tempTableName} (${columnsSql})`);
1586
1518
  const oldColumns = await this.db.select(`PRAGMA table_info('${tableName}')`);
1587
1519
  const oldColumnNames = oldColumns.map((c) => c.name);
1588
- const newColumnNames = Object.keys(table._.columns);
1520
+ const newColumnNames = Object.values(table._.columns).map((c) => c._.name);
1589
1521
  const commonColumns = oldColumnNames.filter((name) => newColumnNames.includes(name));
1590
1522
  if (commonColumns.length > 0) {
1591
1523
  const columnsList = commonColumns.join(", ");
@@ -1602,18 +1534,18 @@ var TauriORM = class {
1602
1534
  console.warn(
1603
1535
  `[Tauri-ORM] Table "${table._.name}" was not passed in the schema to the ORM constructor. Relations will not be available.`
1604
1536
  );
1605
- return new SelectQueryBuilder(this.db, table, columns);
1537
+ return new SelectQueryBuilder(this.kysely, table, columns);
1606
1538
  }
1607
- return new SelectQueryBuilder(this.db, internalTable, columns);
1539
+ return new SelectQueryBuilder(this.kysely, internalTable, columns);
1608
1540
  }
1609
1541
  insert(table) {
1610
- return new InsertQueryBuilder(this.db, table);
1542
+ return new InsertQueryBuilder(this.kysely, table);
1611
1543
  }
1612
1544
  update(table) {
1613
- return new UpdateQueryBuilder(this.db, table);
1545
+ return new UpdateQueryBuilder(this.kysely, table);
1614
1546
  }
1615
1547
  delete(table) {
1616
- return new DeleteQueryBuilder(this.db, table);
1548
+ return new DeleteQueryBuilder(this.kysely, table);
1617
1549
  }
1618
1550
  async upsert(table, data, conflictTarget) {
1619
1551
  const columns = conflictTarget.map((col) => table._.columns[col]);
@@ -1623,7 +1555,7 @@ var TauriORM = class {
1623
1555
  }).execute();
1624
1556
  }
1625
1557
  $with(alias2) {
1626
- const withBuilder = new WithQueryBuilder(this.db);
1558
+ const withBuilder = new WithQueryBuilder(this.kysely);
1627
1559
  return {
1628
1560
  as: (query) => {
1629
1561
  withBuilder.with(alias2, query);
@@ -1632,14 +1564,14 @@ var TauriORM = class {
1632
1564
  };
1633
1565
  }
1634
1566
  async transaction(callback) {
1635
- await this.db.execute("BEGIN TRANSACTION");
1567
+ await this.db.execute("BEGIN");
1636
1568
  try {
1637
1569
  const result = await callback(this);
1638
1570
  await this.db.execute("COMMIT");
1639
1571
  return result;
1640
- } catch (error) {
1572
+ } catch (e) {
1641
1573
  await this.db.execute("ROLLBACK");
1642
- throw error;
1574
+ throw e;
1643
1575
  }
1644
1576
  }
1645
1577
  rollback() {
@@ -1691,7 +1623,9 @@ var TauriORM = class {
1691
1623
  unique: !!col.options.unique,
1692
1624
  dv: col.options.default && typeof col.options.default === "object" && col.options.default.raw ? { raw: col.options.default.raw } : col.options.default ?? null,
1693
1625
  hasDefaultFn: col.options.$defaultFn !== void 0,
1694
- hasOnUpdateFn: col.options.$onUpdateFn !== void 0
1626
+ hasOnUpdateFn: col.options.$onUpdateFn !== void 0,
1627
+ onDelete: col.options.references?.onDelete ?? null,
1628
+ onUpdate: col.options.references?.onUpdate ?? null
1695
1629
  };
1696
1630
  }
1697
1631
  computeModelSignature() {
@@ -1755,11 +1689,6 @@ var OneRelation = class extends Relation {
1755
1689
  }
1756
1690
  };
1757
1691
  var ManyRelation = class extends Relation {
1758
- constructor(foreignTable) {
1759
- super(foreignTable);
1760
- }
1761
- };
1762
- var ManyToManyRelation = class extends Relation {
1763
1692
  constructor(foreignTable, config) {
1764
1693
  super(foreignTable);
1765
1694
  this.config = config;
@@ -1772,9 +1701,6 @@ var relations = (table, relationsCallback) => {
1772
1701
  },
1773
1702
  many: (foreignTable) => {
1774
1703
  return new ManyRelation(foreignTable);
1775
- },
1776
- manyToMany: (foreignTable, config) => {
1777
- return new ManyToManyRelation(foreignTable, config);
1778
1704
  }
1779
1705
  });
1780
1706
  for (const [name, relation] of Object.entries(builtRelations)) {
@@ -1783,21 +1709,15 @@ var relations = (table, relationsCallback) => {
1783
1709
  type: "one",
1784
1710
  foreignTable: relation.foreignTable,
1785
1711
  fields: relation.config?.fields,
1786
- references: relation.config?.references
1712
+ references: relation.config?.references,
1713
+ optional: relation.config?.optional,
1714
+ alias: relation.config?.alias
1787
1715
  };
1788
1716
  } else if (relation instanceof ManyRelation) {
1789
1717
  table.relations[name] = {
1790
1718
  type: "many",
1791
1719
  foreignTable: relation.foreignTable
1792
1720
  };
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
1721
  }
1802
1722
  }
1803
1723
  return builtRelations;
@@ -1810,50 +1730,22 @@ var alias = (table, alias2) => {
1810
1730
  };
1811
1731
 
1812
1732
  // 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
- });
1733
+ var import_kysely6 = require("kysely");
1734
+ var count = (column) => import_kysely6.sql`COUNT(${column ? import_kysely6.sql.ref(column._.name) : import_kysely6.sql.raw("*")})`;
1735
+ var countDistinct = (column) => import_kysely6.sql`COUNT(DISTINCT ${import_kysely6.sql.ref(column._.name)})`;
1736
+ var sum = (column) => import_kysely6.sql`SUM(${import_kysely6.sql.ref(column._.name)})`;
1737
+ var avg = (column) => import_kysely6.sql`AVG(${import_kysely6.sql.ref(column._.name)})`;
1738
+ var max = (column) => import_kysely6.sql`MAX(${import_kysely6.sql.ref(column._.name)})`;
1739
+ var min = (column) => import_kysely6.sql`MIN(${import_kysely6.sql.ref(column._.name)})`;
1740
+ var groupConcat = (column, separator = ",") => import_kysely6.sql`GROUP_CONCAT(${import_kysely6.sql.ref(column._.name)}, ${import_kysely6.sql.val(separator)})`;
1741
+ var as = (aggregate, alias2) => Object.assign(aggregate, { alias: alias2 });
1845
1742
 
1846
1743
  // src/subquery.ts
1847
1744
  var subquery = (query) => {
1848
- const { sql: sql2, params } = query.toSQL();
1849
- return {
1850
- sql: `(${sql2})`,
1851
- params,
1852
- _isSubquery: true
1853
- };
1745
+ return query.toKyselyExpression();
1854
1746
  };
1855
1747
  var scalarSubquery = (query) => {
1856
- return subquery(query);
1748
+ return query.toKyselyExpression();
1857
1749
  };
1858
1750
 
1859
1751
  // src/column-helpers.ts
@@ -1872,15 +1764,136 @@ function numeric(name, config) {
1872
1764
  return new SQLiteColumn(name, "NUMERIC", config);
1873
1765
  }
1874
1766
  var enumType = (name, values) => text(name, { enum: values });
1767
+
1768
+ // src/relations-v2.ts
1769
+ function extractTables(schema) {
1770
+ const tables = {};
1771
+ for (const [key, value] of Object.entries(schema)) {
1772
+ const v = value;
1773
+ if (v && typeof v === "object" && v._?.name && v._?.columns && typeof v.relations === "object") {
1774
+ tables[key] = v;
1775
+ }
1776
+ }
1777
+ return tables;
1778
+ }
1779
+ function through(column, junctionColumn, junctionTable) {
1780
+ return { column, junctionColumn, junctionTable };
1781
+ }
1782
+ function toArray(col) {
1783
+ return Array.isArray(col) ? col : [col];
1784
+ }
1785
+ function isThroughRef(v) {
1786
+ return v && typeof v === "object" && "column" in v && "junctionColumn" in v && "junctionTable" in v;
1787
+ }
1788
+ function buildTableRef(table) {
1789
+ return { ...table._.columns };
1790
+ }
1791
+ function buildR(tables) {
1792
+ const tableRefs = {};
1793
+ const oneFns = {};
1794
+ const manyFns = {};
1795
+ for (const [tableKey, table] of Object.entries(tables)) {
1796
+ tableRefs[tableKey] = buildTableRef(table);
1797
+ const foreignTable = table;
1798
+ oneFns[tableKey] = (opts) => {
1799
+ return new OneRelation(foreignTable, {
1800
+ fields: toArray(opts.from),
1801
+ references: toArray(opts.to),
1802
+ optional: opts.optional,
1803
+ alias: opts.alias
1804
+ });
1805
+ };
1806
+ manyFns[tableKey] = (opts) => {
1807
+ if (!opts?.from || !opts?.to) return new ManyRelation(foreignTable);
1808
+ if (isThroughRef(opts.from) && isThroughRef(opts.to)) {
1809
+ return new ManyRelation(foreignTable, {
1810
+ through: {
1811
+ junctionTable: opts.from.junctionTable,
1812
+ fromRef: { column: opts.from.column, junctionColumn: opts.from.junctionColumn },
1813
+ toRef: { column: opts.to.column, junctionColumn: opts.to.junctionColumn }
1814
+ },
1815
+ optional: opts.optional,
1816
+ alias: opts.alias,
1817
+ where: opts.where
1818
+ });
1819
+ }
1820
+ return new ManyRelation(foreignTable, {
1821
+ from: toArray(opts.from),
1822
+ to: toArray(opts.to),
1823
+ optional: opts.optional,
1824
+ alias: opts.alias,
1825
+ where: opts.where
1826
+ });
1827
+ };
1828
+ }
1829
+ return {
1830
+ ...tableRefs,
1831
+ one: oneFns,
1832
+ many: manyFns
1833
+ };
1834
+ }
1835
+ function applyRelationsToTables(tables, relationsResult) {
1836
+ for (const [tableKey, rels] of Object.entries(relationsResult)) {
1837
+ const table = tables[tableKey];
1838
+ if (!table) continue;
1839
+ for (const [relName, relation] of Object.entries(rels)) {
1840
+ if (relation instanceof OneRelation) {
1841
+ table.relations[relName] = {
1842
+ type: "one",
1843
+ foreignTable: relation.foreignTable,
1844
+ fields: relation.config?.fields,
1845
+ references: relation.config?.references,
1846
+ optional: relation.config?.optional,
1847
+ alias: relation.config?.alias
1848
+ };
1849
+ } else if (relation instanceof ManyRelation) {
1850
+ const config = relation.config;
1851
+ if (config?.through) {
1852
+ table.relations[relName] = {
1853
+ type: "many",
1854
+ foreignTable: relation.foreignTable,
1855
+ junctionTable: config.through.junctionTable,
1856
+ fromJunction: config.through.fromRef,
1857
+ toJunction: config.through.toRef,
1858
+ optional: config.optional,
1859
+ alias: config.alias,
1860
+ where: config.where
1861
+ };
1862
+ } else {
1863
+ table.relations[relName] = {
1864
+ type: "many",
1865
+ foreignTable: relation.foreignTable,
1866
+ fields: config ? config.to : void 0,
1867
+ references: config ? config.from : void 0,
1868
+ optional: config?.optional,
1869
+ alias: config?.alias,
1870
+ where: config?.where
1871
+ };
1872
+ }
1873
+ }
1874
+ }
1875
+ }
1876
+ }
1877
+ function defineRelations(schema, callback) {
1878
+ const tables = extractTables(schema);
1879
+ const r = buildR(tables);
1880
+ const result = callback(r);
1881
+ applyRelationsToTables(tables, result);
1882
+ return result;
1883
+ }
1884
+ function defineRelationsPart(schema, callback) {
1885
+ return defineRelations(schema, callback);
1886
+ }
1887
+
1888
+ // src/index.ts
1889
+ var import_kysely7 = require("kysely");
1875
1890
  // Annotate the CommonJS export names for ESM import in node:
1876
1891
  0 && (module.exports = {
1877
- BaseQueryBuilder,
1878
1892
  ColumnNotFoundError,
1879
1893
  DeleteQueryBuilder,
1880
1894
  InsertQueryBuilder,
1881
1895
  InsertValidationError,
1882
1896
  ManyRelation,
1883
- ManyToManyRelation,
1884
1897
  MigrationError,
1885
1898
  MissingWhereClauseError,
1886
1899
  OneRelation,
@@ -1891,6 +1904,7 @@ var enumType = (name, values) => text(name, { enum: values });
1891
1904
  SelectQueryBuilder,
1892
1905
  Table,
1893
1906
  TableNotFoundError,
1907
+ TauriDialect,
1894
1908
  TauriORM,
1895
1909
  TauriORMError,
1896
1910
  UpdateQueryBuilder,
@@ -1908,6 +1922,8 @@ var enumType = (name, values) => text(name, { enum: values });
1908
1922
  contains,
1909
1923
  count,
1910
1924
  countDistinct,
1925
+ defineRelations,
1926
+ defineRelationsPart,
1911
1927
  desc,
1912
1928
  endsWith,
1913
1929
  enumType,
@@ -1947,5 +1963,6 @@ var enumType = (name, values) => text(name, { enum: values });
1947
1963
  startsWith,
1948
1964
  subquery,
1949
1965
  sum,
1950
- text
1966
+ text,
1967
+ through
1951
1968
  });