@type32/tauri-sqlite-orm 0.1.18-4 → 0.1.18-6

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
@@ -7,11 +7,11 @@ var __export = (target, all) => {
7
7
  for (var name in all)
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
- var __copyProps = (to, from, except, desc) => {
10
+ var __copyProps = (to, from, except, desc2) => {
11
11
  if (from && typeof from === "object" || typeof from === "function") {
12
12
  for (let key of __getOwnPropNames(from))
13
13
  if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });
15
15
  }
16
16
  return to;
17
17
  };
@@ -27,10 +27,18 @@ __export(index_exports, {
27
27
  Table: () => Table,
28
28
  TauriORM: () => TauriORM,
29
29
  UpdateQueryBuilder: () => UpdateQueryBuilder,
30
+ WithQueryBuilder: () => WithQueryBuilder,
31
+ alias: () => alias,
30
32
  and: () => and,
33
+ asc: () => asc,
34
+ avg: () => avg,
31
35
  blob: () => blob,
32
36
  boolean: () => boolean,
37
+ count: () => count,
38
+ countDistinct: () => countDistinct,
39
+ desc: () => desc,
33
40
  eq: () => eq,
41
+ getTableColumns: () => getTableColumns,
34
42
  gt: () => gt,
35
43
  gte: () => gte,
36
44
  inArray: () => inArray,
@@ -40,10 +48,15 @@ __export(index_exports, {
40
48
  like: () => like,
41
49
  lt: () => lt,
42
50
  lte: () => lte,
51
+ max: () => max,
52
+ min: () => min,
53
+ not: () => not,
43
54
  or: () => or,
44
55
  real: () => real,
45
56
  relations: () => relations,
57
+ sql: () => sql,
46
58
  sqliteTable: () => sqliteTable,
59
+ sum: () => sum,
47
60
  text: () => text
48
61
  });
49
62
  module.exports = __toCommonJS(index_exports);
@@ -133,6 +146,9 @@ var SQLiteColumn = class _SQLiteColumn {
133
146
  this._.mode
134
147
  );
135
148
  }
149
+ as(alias2) {
150
+ return this;
151
+ }
136
152
  };
137
153
  var text = (name) => new SQLiteColumn(name, "TEXT");
138
154
  var integer = (name, config) => new SQLiteColumn(name, "INTEGER", {}, config?.mode || "default");
@@ -163,6 +179,10 @@ var or = (...conditions) => ({
163
179
  sql: conditions.map((c) => `(${c.sql})`).join(" OR "),
164
180
  params: conditions.flatMap((c) => c.params)
165
181
  });
182
+ var not = (condition) => ({
183
+ sql: `NOT (${condition.sql})`,
184
+ params: condition.params
185
+ });
166
186
  var gt = (column, value) => ({
167
187
  sql: `${column._.name} > ?`,
168
188
  params: [value]
@@ -195,6 +215,58 @@ var inArray = (column, values) => ({
195
215
  sql: `${column._.name} IN (${values.map(() => "?").join(",")})`,
196
216
  params: values
197
217
  });
218
+ var asc = (column) => ({
219
+ sql: `${column._.name} ASC`,
220
+ params: []
221
+ });
222
+ var desc = (column) => ({
223
+ sql: `${column._.name} DESC`,
224
+ params: []
225
+ });
226
+ var count = (column) => ({
227
+ sql: `COUNT(${column ? column._.name : "*"})`,
228
+ params: []
229
+ });
230
+ var countDistinct = (column) => ({
231
+ sql: `COUNT(DISTINCT ${column._.name})`,
232
+ params: []
233
+ });
234
+ var sum = (column) => ({
235
+ sql: `SUM(${column._.name})`,
236
+ params: []
237
+ });
238
+ var avg = (column) => ({
239
+ sql: `AVG(${column._.name})`,
240
+ params: []
241
+ });
242
+ var max = (column) => ({
243
+ sql: `MAX(${column._.name})`,
244
+ params: []
245
+ });
246
+ var min = (column) => ({
247
+ sql: `MIN(${column._.name})`,
248
+ params: []
249
+ });
250
+ var sql = (strings, ...values) => {
251
+ const queryParts = [];
252
+ const params = [];
253
+ strings.forEach((str, i) => {
254
+ queryParts.push(str);
255
+ if (values[i] !== void 0) {
256
+ if (typeof values[i] === "object" && values[i].sql) {
257
+ queryParts.push(values[i].sql);
258
+ params.push(...values[i].params);
259
+ } else {
260
+ queryParts.push("?");
261
+ params.push(values[i]);
262
+ }
263
+ }
264
+ });
265
+ return {
266
+ sql: queryParts.join(""),
267
+ params
268
+ };
269
+ };
198
270
  var BaseQueryBuilder = class {
199
271
  constructor(db) {
200
272
  this.db = db;
@@ -207,15 +279,20 @@ var BaseQueryBuilder = class {
207
279
  return this;
208
280
  }
209
281
  orderBy(column, direction = "ASC") {
210
- this.query += ` ORDER BY ${column._.name} ${direction}`;
282
+ if ("sql" in column) {
283
+ this.query += ` ORDER BY ${column.sql} ${direction}`;
284
+ this.params.push(...column.params);
285
+ } else {
286
+ this.query += ` ORDER BY ${column._.name} ${direction}`;
287
+ }
211
288
  return this;
212
289
  }
213
- limit(count) {
214
- this.query += ` LIMIT ${count}`;
290
+ limit(count2) {
291
+ this.query += ` LIMIT ${count2}`;
215
292
  return this;
216
293
  }
217
- offset(count) {
218
- this.query += ` OFFSET ${count}`;
294
+ offset(count2) {
295
+ this.query += ` OFFSET ${count2}`;
219
296
  return this;
220
297
  }
221
298
  build() {
@@ -233,9 +310,37 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
233
310
  const columnNames = columns ? columns.map((c) => table._.columns[c]._.name) : ["*"];
234
311
  this.query = `SELECT ${columnNames.join(", ")} FROM ${table._.name}`;
235
312
  }
313
+ isDistinct = false;
314
+ groupByColumns = [];
315
+ havingCondition = null;
316
+ distinct() {
317
+ this.isDistinct = true;
318
+ this.query = this.query.replace("SELECT", "SELECT DISTINCT");
319
+ return this;
320
+ }
321
+ groupBy(...columns) {
322
+ this.groupByColumns.push(...columns);
323
+ const columnNames = columns.map((col) => col._.name).join(", ");
324
+ this.query += ` GROUP BY ${columnNames}`;
325
+ return this;
326
+ }
327
+ having(condition) {
328
+ this.havingCondition = condition;
329
+ this.query += ` HAVING ${condition.sql}`;
330
+ this.params.push(...condition.params);
331
+ return this;
332
+ }
236
333
  async execute() {
237
- const { sql, params } = this.build();
238
- return this.db.select(sql, params);
334
+ const { sql: sql2, params } = this.build();
335
+ return this.db.select(sql2, params);
336
+ }
337
+ async all() {
338
+ return this.execute();
339
+ }
340
+ async get() {
341
+ this.limit(1);
342
+ const result = await this.execute();
343
+ return result[0];
239
344
  }
240
345
  };
241
346
  var InsertQueryBuilder = class extends BaseQueryBuilder {
@@ -245,46 +350,121 @@ var InsertQueryBuilder = class extends BaseQueryBuilder {
245
350
  this.query = `INSERT INTO ${table._.name}`;
246
351
  }
247
352
  dataSets = [];
353
+ returningColumns = [];
354
+ onConflictAction = null;
355
+ conflictTarget = [];
356
+ updateSet = {};
248
357
  values(data) {
249
358
  const dataArray = Array.isArray(data) ? data : [data];
250
359
  this.dataSets.push(...dataArray);
251
360
  return this;
252
361
  }
362
+ returning(...columns) {
363
+ this.returningColumns = columns;
364
+ return this;
365
+ }
366
+ onConflictDoNothing(target) {
367
+ this.onConflictAction = "nothing";
368
+ if (target) {
369
+ this.conflictTarget = Array.isArray(target) ? target : [target];
370
+ }
371
+ return this;
372
+ }
373
+ onConflictDoUpdate(config) {
374
+ this.onConflictAction = "update";
375
+ this.conflictTarget = Array.isArray(config.target) ? config.target : [config.target];
376
+ this.updateSet = config.set;
377
+ return this;
378
+ }
379
+ processDefaultValues(data) {
380
+ const finalData = { ...data };
381
+ for (const [key, column] of Object.entries(this.table._.columns)) {
382
+ const typedKey = key;
383
+ if (finalData[typedKey] === void 0) {
384
+ if (column.options.$defaultFn) {
385
+ finalData[typedKey] = column.options.$defaultFn();
386
+ }
387
+ }
388
+ }
389
+ return finalData;
390
+ }
391
+ buildConflictClause() {
392
+ if (!this.onConflictAction) return "";
393
+ let clause = " ON CONFLICT";
394
+ if (this.conflictTarget.length > 0) {
395
+ const targetNames = this.conflictTarget.map((col) => col._.name).join(", ");
396
+ clause += ` (${targetNames})`;
397
+ }
398
+ if (this.onConflictAction === "nothing") {
399
+ clause += " DO NOTHING";
400
+ } else if (this.onConflictAction === "update") {
401
+ const setEntries = Object.entries(this.updateSet);
402
+ if (setEntries.length > 0) {
403
+ const setClause = setEntries.map(([key]) => `${key} = ?`).join(", ");
404
+ clause += ` DO UPDATE SET ${setClause}`;
405
+ }
406
+ }
407
+ return clause;
408
+ }
253
409
  async execute() {
254
410
  if (this.dataSets.length === 0) {
255
411
  throw new Error("No data provided for insert");
256
412
  }
257
- const processedDataSets = this.dataSets.map((dataSet) => {
258
- const finalData = { ...dataSet };
259
- for (const [key, column] of Object.entries(this.table._.columns)) {
260
- if (finalData[key] === void 0) {
261
- if (column.options.$defaultFn) {
262
- finalData[key] = column.options.$defaultFn();
263
- }
264
- }
265
- }
266
- return finalData;
267
- });
268
- const allKeys = /* @__PURE__ */ new Set();
413
+ const processedDataSets = this.dataSets.map(
414
+ (data) => this.processDefaultValues(data)
415
+ );
416
+ const groups = /* @__PURE__ */ new Map();
269
417
  for (const dataSet of processedDataSets) {
270
- for (const key of Object.keys(dataSet)) {
271
- allKeys.add(key);
418
+ const keys = Object.keys(dataSet).sort().join(",");
419
+ if (!groups.has(keys)) {
420
+ groups.set(keys, []);
272
421
  }
422
+ groups.get(keys).push(dataSet);
273
423
  }
274
- const columns = Array.from(allKeys);
275
- const columnNames = columns.map(
276
- (key) => this.table._.columns[key]._.name
277
- );
278
- const placeholders = `(${columns.map(() => "?").join(", ")})`;
279
- const valuesSql = processedDataSets.map(() => placeholders).join(", ");
280
- const finalQuery = `${this.query} (${columnNames.join(
281
- ", "
282
- )}) VALUES ${valuesSql}`;
283
- const params = processedDataSets.flatMap(
284
- (data) => columns.map((col) => data[col] ?? null)
424
+ let results = [];
425
+ let lastInsertId;
426
+ let rowsAffected = 0;
427
+ for (const [_, dataSets] of groups) {
428
+ const columns = Object.keys(dataSets[0]);
429
+ const columnNames = columns.map(
430
+ (key) => this.table._.columns[key]._.name
431
+ );
432
+ const placeholders = `(${columns.map(() => "?").join(", ")})`;
433
+ const valuesSql = dataSets.map(() => placeholders).join(", ");
434
+ const conflictClause = this.buildConflictClause();
435
+ const finalQuery = `${this.query} (${columnNames.join(
436
+ ", "
437
+ )}) VALUES ${valuesSql}${conflictClause}`;
438
+ const params = dataSets.flatMap(
439
+ (data) => columns.map((col) => data[col] ?? null)
440
+ );
441
+ if (this.onConflictAction === "update") {
442
+ const setValues = Object.entries(this.updateSet).map(
443
+ ([, value]) => value
444
+ );
445
+ params.push(...setValues);
446
+ }
447
+ if (this.returningColumns.length > 0) {
448
+ const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
449
+ const queryWithReturning = `${finalQuery} RETURNING ${returningNames}`;
450
+ const rows = await this.db.select(queryWithReturning, params);
451
+ results = results.concat(rows);
452
+ } else {
453
+ const result = await this.db.execute(finalQuery, params);
454
+ lastInsertId = result.lastInsertId;
455
+ rowsAffected += result.rowsAffected;
456
+ }
457
+ }
458
+ if (this.returningColumns.length > 0) {
459
+ return results;
460
+ }
461
+ return [{ lastInsertId, rowsAffected }];
462
+ }
463
+ async returningAll() {
464
+ const allColumns = Object.keys(
465
+ this.table._.columns
285
466
  );
286
- const result = await this.db.execute(finalQuery, params);
287
- return result.lastInsertId ?? 0;
467
+ return this.returning(...allColumns).execute();
288
468
  }
289
469
  };
290
470
  var UpdateQueryBuilder = class extends BaseQueryBuilder {
@@ -294,15 +474,21 @@ var UpdateQueryBuilder = class extends BaseQueryBuilder {
294
474
  this.query = `UPDATE ${table._.name}`;
295
475
  }
296
476
  updateData = {};
477
+ returningColumns = [];
297
478
  set(data) {
298
479
  this.updateData = { ...this.updateData, ...data };
299
480
  return this;
300
481
  }
301
- build() {
482
+ returning(...columns) {
483
+ this.returningColumns = columns;
484
+ return this;
485
+ }
486
+ buildUpdateClause() {
302
487
  const finalUpdateData = { ...this.updateData };
303
488
  for (const [key, column] of Object.entries(this.table._.columns)) {
304
- if (finalUpdateData[key] === void 0 && column.options.$onUpdateFn) {
305
- finalUpdateData[key] = column.options.$onUpdateFn();
489
+ const typedKey = key;
490
+ if (finalUpdateData[typedKey] === void 0 && column.options.$onUpdateFn) {
491
+ finalUpdateData[typedKey] = column.options.$onUpdateFn();
306
492
  }
307
493
  }
308
494
  const baseQuery = this.query;
@@ -328,14 +514,26 @@ var UpdateQueryBuilder = class extends BaseQueryBuilder {
328
514
  return `${column._.name} = ?`;
329
515
  }).join(", ");
330
516
  const setParams = entries.map(([, value]) => value);
331
- const sql = `${tablePart} SET ${setClause}${whereClause}`;
517
+ const sql2 = `${tablePart} SET ${setClause}${whereClause}`;
332
518
  const params = [...setParams, ...whereParams];
333
- return { sql, params };
519
+ return { sql: sql2, params };
334
520
  }
335
521
  async execute() {
336
- const { sql, params } = this.build();
337
- const result = await this.db.execute(sql, params);
338
- return result.rowsAffected;
522
+ const { sql: updateSql, params } = this.buildUpdateClause();
523
+ if (this.returningColumns.length > 0) {
524
+ const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
525
+ const sqlWithReturning = `${updateSql} RETURNING ${returningNames}`;
526
+ return this.db.select(sqlWithReturning, params);
527
+ } else {
528
+ const result = await this.db.execute(updateSql, params);
529
+ return [{ rowsAffected: result.rowsAffected }];
530
+ }
531
+ }
532
+ async returningAll() {
533
+ const allColumns = Object.keys(
534
+ this.table._.columns
535
+ );
536
+ return this.returning(...allColumns).execute();
339
537
  }
340
538
  };
341
539
  var DeleteQueryBuilder = class extends BaseQueryBuilder {
@@ -344,10 +542,67 @@ var DeleteQueryBuilder = class extends BaseQueryBuilder {
344
542
  this.table = table;
345
543
  this.query = `DELETE FROM ${table._.name}`;
346
544
  }
545
+ returningColumns = [];
546
+ returning(...columns) {
547
+ this.returningColumns = columns;
548
+ return this;
549
+ }
347
550
  async execute() {
348
- const { sql, params } = this.build();
349
- const result = await this.db.execute(sql, params);
350
- return result.rowsAffected;
551
+ const { sql: sql2, params } = this.build();
552
+ if (this.returningColumns.length > 0) {
553
+ const returningNames = this.returningColumns.map((col) => this.table._.columns[col]._.name).join(", ");
554
+ const sqlWithReturning = `${sql2} RETURNING ${returningNames}`;
555
+ return this.db.select(sqlWithReturning, params);
556
+ } else {
557
+ const result = await this.db.execute(sql2, params);
558
+ return [{ rowsAffected: result.rowsAffected }];
559
+ }
560
+ }
561
+ async returningAll() {
562
+ const allColumns = Object.keys(
563
+ this.table._.columns
564
+ );
565
+ return this.returning(...allColumns).execute();
566
+ }
567
+ };
568
+ var WithQueryBuilder = class {
569
+ constructor(db) {
570
+ this.db = db;
571
+ }
572
+ ctes = [];
573
+ with(alias2, query) {
574
+ this.ctes.push({ alias: alias2, query: query.sql, params: query.params });
575
+ return this;
576
+ }
577
+ select(table, columns) {
578
+ const builder = new SelectQueryBuilder(this.db, table, columns);
579
+ this.applyWithClause(builder);
580
+ return builder;
581
+ }
582
+ insert(table) {
583
+ const builder = new InsertQueryBuilder(this.db, table);
584
+ this.applyWithClause(builder);
585
+ return builder;
586
+ }
587
+ update(table) {
588
+ const builder = new UpdateQueryBuilder(this.db, table);
589
+ this.applyWithClause(builder);
590
+ return builder;
591
+ }
592
+ delete(table) {
593
+ const builder = new DeleteQueryBuilder(this.db, table);
594
+ this.applyWithClause(builder);
595
+ return builder;
596
+ }
597
+ applyWithClause(builder) {
598
+ if (this.ctes.length > 0) {
599
+ const cteSql = this.ctes.map((cte) => `${cte.alias} AS (${cte.query})`).join(", ");
600
+ builder["query"] = `WITH ${cteSql} ${builder["query"]}`;
601
+ builder["params"] = [
602
+ ...this.ctes.flatMap((cte) => cte.params),
603
+ ...builder["params"]
604
+ ];
605
+ }
351
606
  }
352
607
  };
353
608
  var TauriORM = class {
@@ -361,23 +616,23 @@ var TauriORM = class {
361
616
  }
362
617
  tables = /* @__PURE__ */ new Map();
363
618
  buildColumnDefinition(col, forAlterTable = false) {
364
- let sql = `${col._.name} ${col.type}`;
619
+ let sql2 = `${col._.name} ${col.type}`;
365
620
  if (col.options.primaryKey && !forAlterTable) {
366
- sql += " PRIMARY KEY";
621
+ sql2 += " PRIMARY KEY";
367
622
  if (col._.autoincrement) {
368
- sql += " AUTOINCREMENT";
623
+ sql2 += " AUTOINCREMENT";
369
624
  }
370
625
  }
371
- if (col._.notNull) sql += " NOT NULL";
372
- if (col.options.unique) sql += " UNIQUE";
626
+ if (col._.notNull) sql2 += " NOT NULL";
627
+ if (col.options.unique) sql2 += " UNIQUE";
373
628
  if (col.options.default !== void 0) {
374
629
  const value = col.options.default;
375
- sql += ` DEFAULT ${typeof value === "string" ? `'${value.replace(/'/g, "''")}'` : value}`;
630
+ sql2 += ` DEFAULT ${typeof value === "string" ? `'${value.replace(/'/g, "''")}'` : value}`;
376
631
  }
377
632
  if (col.options.references) {
378
- sql += ` REFERENCES ${col.options.references.table._.name}(${col.options.references.column._.name})`;
633
+ sql2 += ` REFERENCES ${col.options.references.table._.name}(${col.options.references.column._.name})`;
379
634
  }
380
- return sql;
635
+ return sql2;
381
636
  }
382
637
  async migrate() {
383
638
  for (const table of this.tables.values()) {
@@ -414,6 +669,15 @@ var TauriORM = class {
414
669
  delete(table) {
415
670
  return new DeleteQueryBuilder(this.db, table);
416
671
  }
672
+ $with(alias2) {
673
+ const withBuilder = new WithQueryBuilder(this.db);
674
+ return {
675
+ as: (query) => {
676
+ withBuilder.with(alias2, query);
677
+ return withBuilder;
678
+ }
679
+ };
680
+ }
417
681
  async transaction(callback) {
418
682
  await this.db.execute("BEGIN TRANSACTION");
419
683
  try {
@@ -425,6 +689,9 @@ var TauriORM = class {
425
689
  throw error;
426
690
  }
427
691
  }
692
+ rollback() {
693
+ throw new Error("Transaction rolled back");
694
+ }
428
695
  // --- Schema detection / signature ---
429
696
  async ensureSchemaMeta() {
430
697
  await this.db.execute(
@@ -502,6 +769,12 @@ var relations = (table, relationsCallback) => {
502
769
  })
503
770
  });
504
771
  };
772
+ var getTableColumns = (table) => {
773
+ return table._.columns;
774
+ };
775
+ var alias = (table, alias2) => {
776
+ return table;
777
+ };
505
778
  // Annotate the CommonJS export names for ESM import in node:
506
779
  0 && (module.exports = {
507
780
  DeleteQueryBuilder,
@@ -511,10 +784,18 @@ var relations = (table, relationsCallback) => {
511
784
  Table,
512
785
  TauriORM,
513
786
  UpdateQueryBuilder,
787
+ WithQueryBuilder,
788
+ alias,
514
789
  and,
790
+ asc,
791
+ avg,
515
792
  blob,
516
793
  boolean,
794
+ count,
795
+ countDistinct,
796
+ desc,
517
797
  eq,
798
+ getTableColumns,
518
799
  gt,
519
800
  gte,
520
801
  inArray,
@@ -524,9 +805,14 @@ var relations = (table, relationsCallback) => {
524
805
  like,
525
806
  lt,
526
807
  lte,
808
+ max,
809
+ min,
810
+ not,
527
811
  or,
528
812
  real,
529
813
  relations,
814
+ sql,
530
815
  sqliteTable,
816
+ sum,
531
817
  text
532
818
  });