bun-query-builder 0.1.24 → 0.1.25

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/bin/cli.js CHANGED
@@ -12010,18 +12010,11 @@ function getBunSql() {
12010
12010
  }
12011
12011
  return sql;
12012
12012
  } catch (error) {
12013
- if (config5.verbose) {
12014
- console.warn(`[query-builder] Failed to create connection: ${error.message}`);
12015
- }
12016
- try {
12013
+ console.error(`[query-builder] Failed to create database connection for dialect '${dialect}': ${error.message}`);
12014
+ if (dialect === "sqlite") {
12017
12015
  return createSQLiteSQL(":memory:");
12018
- } catch {
12019
- return {
12020
- query: () => Promise.resolve([]),
12021
- execute: () => Promise.resolve([]),
12022
- close: () => Promise.resolve()
12023
- };
12024
12016
  }
12017
+ throw error;
12025
12018
  }
12026
12019
  }
12027
12020
  function getOrCreateBunSql(forceNew = false) {
@@ -23273,6 +23266,10 @@ var init_src = __esm(() => {
23273
23266
 
23274
23267
  // src/orm.ts
23275
23268
  import { Database as Database2 } from "bun:sqlite";
23269
+ function formatNow() {
23270
+ const iso = new Date().toISOString();
23271
+ return config5.dialect === "mysql" ? iso.slice(0, 19).replace("T", " ") : iso;
23272
+ }
23276
23273
  function assertValidIdentifier(name, context) {
23277
23274
  if (typeof name !== "string" || name.length === 0)
23278
23275
  throw new TypeError(`[bun-query-builder] ${context}: identifier must be a non-empty string, got ${typeof name}`);
@@ -23293,19 +23290,130 @@ function getModelFromRegistry(name) {
23293
23290
  }
23294
23291
  return _getModel(name);
23295
23292
  }
23293
+ function toPostgresPlaceholders(sql2) {
23294
+ let i2 = 0;
23295
+ return sql2.replace(/\?/g, () => `$${++i2}`);
23296
+ }
23297
+ function extractChanges(res) {
23298
+ if (res == null)
23299
+ return 0;
23300
+ if (typeof res.affectedRows === "number")
23301
+ return res.affectedRows;
23302
+ if (typeof res.count === "number")
23303
+ return res.count;
23304
+ if (Array.isArray(res))
23305
+ return res.length;
23306
+ return 0;
23307
+ }
23308
+ function extractInsertId(res) {
23309
+ if (res == null || typeof res !== "object")
23310
+ return null;
23311
+ if ("insertId" in res && res.insertId != null)
23312
+ return res.insertId;
23313
+ if ("lastInsertRowid" in res && res.lastInsertRowid != null)
23314
+ return res.lastInsertRowid;
23315
+ return null;
23316
+ }
23317
+
23318
+ class SqliteExecutor {
23319
+ sqliteDb;
23320
+ dialect = "sqlite";
23321
+ constructor(sqliteDb) {
23322
+ this.sqliteDb = sqliteDb;
23323
+ }
23324
+ all(sql2, params) {
23325
+ return Promise.resolve(this.sqliteDb.query(sql2).all(...params));
23326
+ }
23327
+ get(sql2, params) {
23328
+ return Promise.resolve(this.sqliteDb.query(sql2).get(...params) ?? undefined);
23329
+ }
23330
+ run(sql2, params) {
23331
+ const r2 = this.sqliteDb.run(sql2, params);
23332
+ return Promise.resolve({ changes: r2.changes, lastInsertId: r2.lastInsertRowid });
23333
+ }
23334
+ insert(sql2, params) {
23335
+ return this.run(sql2, params);
23336
+ }
23337
+ }
23338
+
23339
+ class DriverExecutor {
23340
+ dialect;
23341
+ constructor(dialect) {
23342
+ this.dialect = dialect;
23343
+ }
23344
+ conn() {
23345
+ return getOrCreateBunSql();
23346
+ }
23347
+ text(sql2) {
23348
+ return this.dialect === "postgres" ? toPostgresPlaceholders(sql2) : sql2;
23349
+ }
23350
+ async all(sql2, params) {
23351
+ const rows = await this.conn().unsafe(this.text(sql2), params);
23352
+ return Array.isArray(rows) ? rows : [];
23353
+ }
23354
+ async get(sql2, params) {
23355
+ const rows = await this.conn().unsafe(this.text(sql2), params);
23356
+ if (Array.isArray(rows))
23357
+ return rows[0] ?? undefined;
23358
+ return rows ?? undefined;
23359
+ }
23360
+ async run(sql2, params) {
23361
+ const res = await this.conn().unsafe(this.text(sql2), params);
23362
+ return { changes: extractChanges(res), lastInsertId: extractInsertId(res) };
23363
+ }
23364
+ async insert(sql2, params, primaryKey) {
23365
+ if (this.dialect === "postgres") {
23366
+ const rows = await this.conn().unsafe(`${toPostgresPlaceholders(sql2)} RETURNING ${primaryKey}`, params);
23367
+ const row = Array.isArray(rows) ? rows[0] : rows;
23368
+ return { changes: 1, lastInsertId: row ? row[primaryKey] ?? null : null };
23369
+ }
23370
+ const res = await this.conn().unsafe(sql2, params);
23371
+ let id = extractInsertId(res);
23372
+ if (id == null) {
23373
+ const rows = await this.conn().unsafe("SELECT LAST_INSERT_ID() as id", []);
23374
+ const row = Array.isArray(rows) ? rows[0] : rows;
23375
+ id = row?.id ?? null;
23376
+ }
23377
+ return { changes: extractChanges(res) || 1, lastInsertId: id };
23378
+ }
23379
+ }
23296
23380
  function configureOrm(options) {
23297
23381
  if (options.database instanceof Database2) {
23298
23382
  globalDb = options.database;
23299
23383
  } else {
23300
23384
  globalDb = new Database2(options.database || ":memory:", { create: true });
23301
23385
  }
23302
- preparedStatementCache.clear();
23386
+ _executor = null;
23387
+ _executorForDb = null;
23303
23388
  }
23304
- function getDatabase() {
23305
- if (!globalDb) {
23306
- globalDb = new Database2(":memory:", { create: true });
23389
+ function getExecutor() {
23390
+ if (globalDb) {
23391
+ if (!_executor || _executorForDb !== globalDb) {
23392
+ _executor = new SqliteExecutor(globalDb);
23393
+ _executorForDb = globalDb;
23394
+ _executorDialect = "sqlite";
23395
+ _executorDatabase = null;
23396
+ }
23397
+ return _executor;
23307
23398
  }
23308
- return globalDb;
23399
+ const dialect = config5.dialect;
23400
+ const database = config5.database?.database ?? null;
23401
+ if (_executor && _executorForDb === null && _executorDialect === dialect && _executorDatabase === database)
23402
+ return _executor;
23403
+ _executorForDb = null;
23404
+ _executorDialect = dialect;
23405
+ _executorDatabase = database;
23406
+ if (dialect === "sqlite")
23407
+ _executor = new SqliteExecutor(new Database2(database || ":memory:", { create: true }));
23408
+ else
23409
+ _executor = new DriverExecutor(dialect);
23410
+ return _executor;
23411
+ }
23412
+ function getDatabase() {
23413
+ const exec = getExecutor();
23414
+ if (exec.sqliteDb)
23415
+ return exec.sqliteDb;
23416
+ throw new Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; ` + `the configured dialect is '${exec.dialect}'. Use the async model API instead.`);
23309
23417
  }
23310
23418
  function collectBelongsToManyKeys(definition) {
23311
23419
  const keys = new Set;
@@ -23459,8 +23567,8 @@ class ModelInstance {
23459
23567
  Object.assign(this._attributes, data);
23460
23568
  return this;
23461
23569
  }
23462
- save() {
23463
- const db = getDatabase();
23570
+ async save() {
23571
+ const exec = getExecutor();
23464
23572
  const pk = this._definition.primaryKey || "id";
23465
23573
  const hooks = this._definition.hooks;
23466
23574
  const setters = this._definition.set || {};
@@ -23470,20 +23578,20 @@ class ModelInstance {
23470
23578
  }
23471
23579
  }
23472
23580
  if (this._attributes[pk]) {
23473
- hooks?.beforeUpdate?.(this, this.getChanges());
23581
+ await hooks?.beforeUpdate?.(this, this.getChanges());
23474
23582
  const changes = this.getChanges();
23475
23583
  const changeKeys = Object.keys(changes);
23476
23584
  if (changeKeys.length > 0) {
23477
23585
  const sets = changeKeys.map((k2) => `${k2} = ?`).join(", ");
23478
23586
  const values = [...Object.values(changes), this._attributes[pk]];
23479
23587
  if (this._definition.traits?.useTimestamps) {
23480
- const now = new Date().toISOString();
23481
- db.run(`UPDATE ${this._definition.table} SET ${sets}, updated_at = ? WHERE ${pk} = ?`, [...Object.values(changes), now, this._attributes[pk]]);
23588
+ const now = formatNow();
23589
+ await exec.run(`UPDATE ${this._definition.table} SET ${sets}, updated_at = ? WHERE ${pk} = ?`, [...Object.values(changes), now, this._attributes[pk]]);
23482
23590
  } else {
23483
- db.run(`UPDATE ${this._definition.table} SET ${sets} WHERE ${pk} = ?`, values);
23591
+ await exec.run(`UPDATE ${this._definition.table} SET ${sets} WHERE ${pk} = ?`, values);
23484
23592
  }
23485
23593
  }
23486
- hooks?.afterUpdate?.(this);
23594
+ await hooks?.afterUpdate?.(this);
23487
23595
  } else {
23488
23596
  const attrs = this._definition.attributes;
23489
23597
  const data = {};
@@ -23493,65 +23601,66 @@ class ModelInstance {
23493
23601
  }
23494
23602
  }
23495
23603
  if (this._definition.traits?.useTimestamps) {
23496
- const now = new Date().toISOString();
23604
+ const now = formatNow();
23497
23605
  data.created_at = now;
23498
23606
  data.updated_at = now;
23499
23607
  }
23500
23608
  if (this._definition.traits?.useUuid && !data.uuid) {
23501
23609
  data.uuid = crypto.randomUUID();
23502
23610
  }
23503
- hooks?.beforeCreate?.(data);
23611
+ await hooks?.beforeCreate?.(data);
23504
23612
  const columns = Object.keys(data);
23505
23613
  const placeholders = columns.map(() => "?").join(", ");
23506
- const result = db.run(`INSERT INTO ${this._definition.table} (${columns.join(", ")}) VALUES (${placeholders})`, Object.values(data));
23614
+ const result = await exec.insert(`INSERT INTO ${this._definition.table} (${columns.join(", ")}) VALUES (${placeholders})`, Object.values(data), pk);
23507
23615
  for (const [key, value] of Object.entries(data)) {
23508
23616
  this._attributes[key] = value;
23509
23617
  }
23510
- this._attributes[pk] = result.lastInsertRowid;
23511
- hooks?.afterCreate?.(this);
23618
+ if (result.lastInsertId != null)
23619
+ this._attributes[pk] = result.lastInsertId;
23620
+ await hooks?.afterCreate?.(this);
23512
23621
  }
23513
23622
  this._original = { ...this._attributes };
23514
23623
  this._hasSaved = true;
23515
23624
  return this;
23516
23625
  }
23517
- update(data) {
23626
+ async update(data) {
23518
23627
  this.fill(data);
23519
23628
  return this.save();
23520
23629
  }
23521
- fresh() {
23522
- const db = getDatabase();
23630
+ async fresh() {
23631
+ const exec = getExecutor();
23523
23632
  const pk = this._definition.primaryKey || "id";
23524
23633
  const id = this._attributes[pk];
23525
23634
  if (id == null)
23526
23635
  return null;
23527
- const row = db.query(`SELECT * FROM ${this._definition.table} WHERE ${pk} = ?`).get(id);
23636
+ const row = await exec.get(`SELECT * FROM ${this._definition.table} WHERE ${pk} = ?`, [id]);
23528
23637
  if (!row)
23529
23638
  return null;
23530
23639
  return new ModelInstance(this._definition, row);
23531
23640
  }
23532
- delete() {
23533
- const db = getDatabase();
23641
+ async delete() {
23642
+ const exec = getExecutor();
23534
23643
  const pk = this._definition.primaryKey || "id";
23535
23644
  const pkValue = this._attributes[pk];
23536
23645
  const hooks = this._definition.hooks;
23537
23646
  if (!pkValue)
23538
23647
  throw new Error("Cannot delete a model without a primary key");
23539
- hooks?.beforeDelete?.(this);
23648
+ await hooks?.beforeDelete?.(this);
23540
23649
  if (this._definition.traits?.useSoftDeletes) {
23541
- db.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${pk} = ?`, [new Date().toISOString(), pkValue]);
23650
+ await exec.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${pk} = ?`, [formatNow(), pkValue]);
23542
23651
  } else {
23543
- db.run(`DELETE FROM ${this._definition.table} WHERE ${pk} = ?`, [pkValue]);
23652
+ await exec.run(`DELETE FROM ${this._definition.table} WHERE ${pk} = ?`, [pkValue]);
23544
23653
  }
23545
- hooks?.afterDelete?.(this);
23654
+ await hooks?.afterDelete?.(this);
23546
23655
  return true;
23547
23656
  }
23548
- refresh() {
23549
- const db = getDatabase();
23657
+ async refresh() {
23658
+ const exec = getExecutor();
23550
23659
  const pk = this._definition.primaryKey || "id";
23551
23660
  const pkValue = this._attributes[pk];
23552
23661
  if (!pkValue)
23553
23662
  throw new Error("Cannot refresh a model without a primary key");
23554
- const row = db.query(`SELECT * FROM ${this._definition.table} WHERE ${pk} = ?`).get(pkValue);
23663
+ const row = await exec.get(`SELECT * FROM ${this._definition.table} WHERE ${pk} = ?`, [pkValue]);
23555
23664
  if (!row)
23556
23665
  return null;
23557
23666
  this._attributes = row;
@@ -23896,34 +24005,35 @@ class BelongsToManyRelationBuilder {
23896
24005
  return inst;
23897
24006
  });
23898
24007
  }
23899
- get() {
23900
- const db = getDatabase();
24008
+ async get() {
24009
+ const exec = getExecutor();
23901
24010
  const { sql: sql2, params } = this.buildSelect();
23902
- const rows = db.query(sql2).all(...params);
24011
+ const rows = await exec.all(sql2, params);
23903
24012
  return this.hydrateRows(rows);
23904
24013
  }
23905
- first() {
24014
+ async first() {
23906
24015
  this._limit = 1;
23907
- return this.get()[0];
24016
+ return (await this.get())[0];
23908
24017
  }
23909
- count() {
23910
- const db = getDatabase();
24018
+ async count() {
24019
+ const exec = getExecutor();
23911
24020
  let sql2 = `SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`;
23912
24021
  const params = [this.parentId];
23913
24022
  for (const w of this._pivotWheres) {
23914
24023
  sql2 += ` AND ${w.sql}`;
23915
24024
  params.push(...w.params);
23916
24025
  }
23917
- return db.query(sql2).get(...params).count;
24026
+ const row = await exec.get(sql2, params);
24027
+ return Number(row?.count ?? 0);
23918
24028
  }
23919
- exists() {
23920
- return this.count() > 0;
24029
+ async exists() {
24030
+ return await this.count() > 0;
23921
24031
  }
23922
24032
  now() {
23923
- return new Date().toISOString();
24033
+ return formatNow();
23924
24034
  }
23925
- attach(idOrIds, extras = {}) {
23926
- const db = getDatabase();
24035
+ async attach(idOrIds, extras = {}) {
24036
+ const exec = getExecutor();
23927
24037
  const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
23928
24038
  if (ids.length === 0)
23929
24039
  return 0;
@@ -23945,13 +24055,13 @@ class BelongsToManyRelationBuilder {
23945
24055
  const placeholders = cols.map(() => "?").join(", ");
23946
24056
  const sql2 = `INSERT INTO ${this.pivotTable} (${cols.join(", ")}) VALUES (${placeholders})`;
23947
24057
  const params = cols.map((c2) => row[c2]);
23948
- db.run(sql2, params);
24058
+ await exec.run(sql2, params);
23949
24059
  inserted++;
23950
24060
  }
23951
24061
  return inserted;
23952
24062
  }
23953
- detach(idOrIds) {
23954
- const db = getDatabase();
24063
+ async detach(idOrIds) {
24064
+ const exec = getExecutor();
23955
24065
  let sql2 = `DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`;
23956
24066
  const params = [this.parentId];
23957
24067
  if (idOrIds !== undefined && idOrIds !== null) {
@@ -23962,10 +24072,10 @@ class BelongsToManyRelationBuilder {
23962
24072
  sql2 += ` AND ${this.fkRelated} IN (${placeholders})`;
23963
24073
  params.push(...ids);
23964
24074
  }
23965
- return db.run(sql2, params).changes;
24075
+ return (await exec.run(sql2, params)).changes;
23966
24076
  }
23967
- updateExistingPivot(relatedId, extras) {
23968
- const db = getDatabase();
24077
+ async updateExistingPivot(relatedId, extras) {
24078
+ const exec = getExecutor();
23969
24079
  const updates = { ...extras };
23970
24080
  if (this._resolved.pivotTimestamps && updates.updated_at === undefined) {
23971
24081
  updates.updated_at = this.now();
@@ -23976,10 +24086,10 @@ class BelongsToManyRelationBuilder {
23976
24086
  const setClause = cols.map((c2) => `${c2} = ?`).join(", ");
23977
24087
  const sql2 = `UPDATE ${this.pivotTable} SET ${setClause} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`;
23978
24088
  const params = [...cols.map((c2) => updates[c2]), this.parentId, relatedId];
23979
- return db.run(sql2, params).changes;
24089
+ return (await exec.run(sql2, params)).changes;
23980
24090
  }
23981
- sync(items) {
23982
- const db = getDatabase();
24091
+ async sync(items) {
24092
+ const exec = getExecutor();
23983
24093
  const desired = new Map;
23984
24094
  for (const item of items) {
23985
24095
  if (item != null && typeof item === "object" && "id" in item) {
@@ -23989,41 +24099,41 @@ class BelongsToManyRelationBuilder {
23989
24099
  desired.set(item, {});
23990
24100
  }
23991
24101
  }
23992
- const current = db.query(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`).all(this.parentId);
24102
+ const current = await exec.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`, [this.parentId]);
23993
24103
  const currentIds = new Set(current.map((r2) => r2[this.fkRelated]));
23994
24104
  const attached = [];
23995
24105
  const detached = [];
23996
24106
  const updated = [];
23997
24107
  const toDetach = [...currentIds].filter((id) => !desired.has(id));
23998
24108
  if (toDetach.length > 0) {
23999
- this.detach(toDetach);
24109
+ await this.detach(toDetach);
24000
24110
  detached.push(...toDetach);
24001
24111
  }
24002
24112
  for (const [id, extras] of desired) {
24003
24113
  if (!currentIds.has(id)) {
24004
- this.attach(id, extras);
24114
+ await this.attach(id, extras);
24005
24115
  attached.push(id);
24006
24116
  } else if (Object.keys(extras).length > 0) {
24007
- this.updateExistingPivot(id, extras);
24117
+ await this.updateExistingPivot(id, extras);
24008
24118
  updated.push(id);
24009
24119
  }
24010
24120
  }
24011
24121
  return { attached, detached, updated };
24012
24122
  }
24013
- toggle(idOrIds) {
24014
- const db = getDatabase();
24123
+ async toggle(idOrIds) {
24124
+ const exec = getExecutor();
24015
24125
  const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
24016
24126
  if (ids.length === 0)
24017
24127
  return { attached: [], detached: [] };
24018
24128
  const placeholders = ids.map(() => "?").join(", ");
24019
- const present = db.query(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${placeholders})`).all(this.parentId, ...ids);
24129
+ const present = await exec.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${placeholders})`, [this.parentId, ...ids]);
24020
24130
  const presentIds = new Set(present.map((r2) => r2[this.fkRelated]));
24021
24131
  const toAttach = ids.filter((id) => !presentIds.has(id));
24022
24132
  const toDetach = ids.filter((id) => presentIds.has(id));
24023
24133
  if (toAttach.length > 0)
24024
- this.attach(toAttach);
24134
+ await this.attach(toAttach);
24025
24135
  if (toDetach.length > 0)
24026
- this.detach(toDetach);
24136
+ await this.detach(toDetach);
24027
24137
  return { attached: toAttach, detached: toDetach };
24028
24138
  }
24029
24139
  }
@@ -24234,10 +24344,10 @@ class ModelQueryBuilder {
24234
24344
  toSql() {
24235
24345
  return this.buildQuery();
24236
24346
  }
24237
- eagerLoadRelations(instances) {
24347
+ async eagerLoadRelations(instances) {
24238
24348
  if (instances.length === 0 || this._withRelations.length === 0)
24239
24349
  return;
24240
- const db = getDatabase();
24350
+ const exec = getExecutor();
24241
24351
  const pk = this._definition.primaryKey || "id";
24242
24352
  for (const relationName of this._withRelations) {
24243
24353
  const cacheKey = `${this._definition.name}:${relationName}`;
@@ -24253,7 +24363,7 @@ class ModelQueryBuilder {
24253
24363
  if (parentIds.length === 0)
24254
24364
  continue;
24255
24365
  const placeholders = parentIds.map(() => "?").join(", ");
24256
- const rows = db.query(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.foreignKey} IN (${placeholders})`).all(...parentIds);
24366
+ const rows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.foreignKey} IN (${placeholders})`, parentIds);
24257
24367
  const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
24258
24368
  const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
24259
24369
  if (rel.type === "hasMany") {
@@ -24285,7 +24395,7 @@ class ModelQueryBuilder {
24285
24395
  if (uniqueFkValues.length === 0)
24286
24396
  continue;
24287
24397
  const placeholders = uniqueFkValues.map(() => "?").join(", ");
24288
- const rows = db.query(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.localKey} IN (${placeholders})`).all(...uniqueFkValues);
24398
+ const rows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.localKey} IN (${placeholders})`, uniqueFkValues);
24289
24399
  const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
24290
24400
  const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
24291
24401
  const byPk = new Map;
@@ -24305,7 +24415,7 @@ class ModelQueryBuilder {
24305
24415
  if (!rel.pivotTable || !rel.pivotFkParent || !rel.pivotFkRelated)
24306
24416
  continue;
24307
24417
  const pivotPlaceholders = parentIds.map(() => "?").join(", ");
24308
- const pivotRows = db.query(`SELECT * FROM ${rel.pivotTable} WHERE ${rel.pivotFkParent} IN (${pivotPlaceholders})`).all(...parentIds);
24418
+ const pivotRows = await exec.all(`SELECT * FROM ${rel.pivotTable} WHERE ${rel.pivotFkParent} IN (${pivotPlaceholders})`, parentIds);
24309
24419
  if (pivotRows.length === 0) {
24310
24420
  for (const instance of instances)
24311
24421
  instance.setRelation(relationName, []);
@@ -24318,7 +24428,7 @@ class ModelQueryBuilder {
24318
24428
  let relatedRows = [];
24319
24429
  if (relatedIds.length > 0) {
24320
24430
  const relPlaceholders = relatedIds.map(() => "?").join(", ");
24321
- relatedRows = db.query(`SELECT * FROM ${rel.relatedTable} WHERE ${relatedPk} IN (${relPlaceholders})`).all(...relatedIds);
24431
+ relatedRows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${relatedPk} IN (${relPlaceholders})`, relatedIds);
24322
24432
  }
24323
24433
  const relatedByPk = new Map;
24324
24434
  for (const r2 of relatedRows)
@@ -24352,75 +24462,76 @@ class ModelQueryBuilder {
24352
24462
  }
24353
24463
  }
24354
24464
  }
24355
- get() {
24356
- const db = getDatabase();
24465
+ async get() {
24466
+ const exec = getExecutor();
24357
24467
  const { sql: sql2, params } = this.buildQuery();
24358
- const rows = db.query(sql2).all(...params);
24468
+ const rows = await exec.all(sql2, params);
24359
24469
  const instances = rows.map((row) => new ModelInstance(this._definition, row));
24360
24470
  if (this._withRelations.length > 0) {
24361
- this.eagerLoadRelations(instances);
24471
+ await this.eagerLoadRelations(instances);
24362
24472
  }
24363
24473
  return instances;
24364
24474
  }
24365
- first() {
24475
+ async first() {
24366
24476
  this._limit = 1;
24367
- return this.get()[0];
24477
+ return (await this.get())[0];
24368
24478
  }
24369
- firstOrFail() {
24370
- const result = this.first();
24479
+ async firstOrFail() {
24480
+ const result = await this.first();
24371
24481
  if (!result)
24372
24482
  throw new Error(`No ${this._definition.name} found`);
24373
24483
  return result;
24374
24484
  }
24375
- last() {
24485
+ async last() {
24376
24486
  const pk = this._definition.primaryKey || "id";
24377
24487
  this._orderBy = [{ column: pk, direction: "desc" }];
24378
24488
  this._limit = 1;
24379
- return this.get()[0];
24489
+ return (await this.get())[0];
24380
24490
  }
24381
- count() {
24382
- const db = getDatabase();
24491
+ async count() {
24492
+ const exec = getExecutor();
24383
24493
  const params = [];
24384
24494
  let sql2 = `SELECT COUNT(*) as count FROM ${this._definition.table}`;
24385
24495
  if (this._wheres.length > 0) {
24386
24496
  sql2 += ` WHERE ${this.buildWhereClauses(params)}`;
24387
24497
  }
24388
- return db.query(sql2).get(...params).count;
24498
+ const row = await exec.get(sql2, params);
24499
+ return Number(row?.count ?? 0);
24389
24500
  }
24390
- exists() {
24391
- return this.count() > 0;
24501
+ async exists() {
24502
+ return await this.count() > 0;
24392
24503
  }
24393
- doesntExist() {
24394
- return this.count() === 0;
24504
+ async doesntExist() {
24505
+ return await this.count() === 0;
24395
24506
  }
24396
- sole() {
24507
+ async sole() {
24397
24508
  this._limit = 2;
24398
- const results = this.get();
24509
+ const results = await this.get();
24399
24510
  if (results.length === 0)
24400
24511
  throw new Error(`No ${this._definition.name} found`);
24401
24512
  if (results.length > 1)
24402
24513
  throw new Error(`Expected one ${this._definition.name}, found multiple`);
24403
24514
  return results[0];
24404
24515
  }
24405
- increment(column, amount = 1) {
24516
+ async increment(column, amount = 1) {
24406
24517
  assertValidIdentifier(column, "increment(column)");
24407
- const db = getDatabase();
24518
+ const exec = getExecutor();
24408
24519
  const params = [amount];
24409
24520
  let sql2 = `UPDATE ${this._definition.table} SET ${column} = ${column} + ?`;
24410
24521
  if (this._definition.traits?.useTimestamps) {
24411
24522
  sql2 += `, updated_at = ?`;
24412
- params.push(new Date().toISOString());
24523
+ params.push(formatNow());
24413
24524
  }
24414
24525
  if (this._wheres.length > 0) {
24415
24526
  const clauses = this.buildWhereClauses(params);
24416
24527
  sql2 += ` WHERE ${clauses}`;
24417
24528
  }
24418
- return db.run(sql2, params).changes;
24529
+ return (await exec.run(sql2, params)).changes;
24419
24530
  }
24420
24531
  decrement(column, amount = 1) {
24421
24532
  return this.increment(column, -amount);
24422
24533
  }
24423
- chunk(size, callback) {
24534
+ async chunk(size, callback) {
24424
24535
  let page = 0;
24425
24536
  while (true) {
24426
24537
  const builder = new ModelQueryBuilder(this._definition);
@@ -24430,10 +24541,10 @@ class ModelQueryBuilder {
24430
24541
  builder._withRelations = [...this._withRelations];
24431
24542
  builder._limit = size;
24432
24543
  builder._offset = page * size;
24433
- const results = builder.get();
24544
+ const results = await builder.get();
24434
24545
  if (results.length === 0)
24435
24546
  break;
24436
- const result = callback(results);
24547
+ const result = await callback(results);
24437
24548
  if (result === false)
24438
24549
  break;
24439
24550
  if (results.length < size)
@@ -24441,12 +24552,12 @@ class ModelQueryBuilder {
24441
24552
  page++;
24442
24553
  }
24443
24554
  }
24444
- paginate(page = 1, perPage = 15) {
24445
- const total = this.count();
24555
+ async paginate(page = 1, perPage = 15) {
24556
+ const total = await this.count();
24446
24557
  const lastPage = Math.ceil(total / perPage);
24447
24558
  this._limit = perPage;
24448
24559
  this._offset = (page - 1) * perPage;
24449
- const data = this.get();
24560
+ const data = await this.get();
24450
24561
  return {
24451
24562
  data,
24452
24563
  total,
@@ -24459,9 +24570,9 @@ class ModelQueryBuilder {
24459
24570
  to: data.length > 0 ? (page - 1) * perPage + data.length : null
24460
24571
  };
24461
24572
  }
24462
- pluck(column) {
24573
+ async pluck(column) {
24463
24574
  assertValidIdentifier(column, "pluck(column)");
24464
- const db = getDatabase();
24575
+ const exec = getExecutor();
24465
24576
  const params = [];
24466
24577
  let sql2 = `SELECT ${column} FROM ${this._definition.table}`;
24467
24578
  if (this._wheres.length > 0) {
@@ -24474,19 +24585,19 @@ class ModelQueryBuilder {
24474
24585
  sql2 += ` LIMIT ${this._limit}`;
24475
24586
  if (this._offset !== undefined)
24476
24587
  sql2 += ` OFFSET ${this._offset}`;
24477
- const rows = db.query(sql2).all(...params);
24588
+ const rows = await exec.all(sql2, params);
24478
24589
  return rows.map((r2) => r2[column]);
24479
24590
  }
24480
- aggregate(fn, column) {
24591
+ async aggregate(fn, column) {
24481
24592
  assertValidIdentifier(column, `${fn}(column)`);
24482
- const db = getDatabase();
24593
+ const exec = getExecutor();
24483
24594
  const params = [];
24484
24595
  let sql2 = `SELECT ${fn}(${column}) as v FROM ${this._definition.table}`;
24485
24596
  if (this._wheres.length > 0) {
24486
24597
  sql2 += ` WHERE ${this.buildWhereClauses(params)}`;
24487
24598
  }
24488
- const row = db.query(sql2).get(...params);
24489
- return row?.v ?? null;
24599
+ const row = await exec.get(sql2, params);
24600
+ return row?.v == null ? null : Number(row.v);
24490
24601
  }
24491
24602
  max(column) {
24492
24603
  return this.aggregate("MAX", column);
@@ -24494,34 +24605,34 @@ class ModelQueryBuilder {
24494
24605
  min(column) {
24495
24606
  return this.aggregate("MIN", column);
24496
24607
  }
24497
- avg(column) {
24498
- return this.aggregate("AVG", column) || 0;
24608
+ async avg(column) {
24609
+ return await this.aggregate("AVG", column) || 0;
24499
24610
  }
24500
- sum(column) {
24501
- return this.aggregate("SUM", column) || 0;
24611
+ async sum(column) {
24612
+ return await this.aggregate("SUM", column) || 0;
24502
24613
  }
24503
- delete() {
24504
- const db = getDatabase();
24614
+ async delete() {
24615
+ const exec = getExecutor();
24505
24616
  const params = [];
24506
24617
  let sql2 = `DELETE FROM ${this._definition.table}`;
24507
24618
  if (this._wheres.length > 0) {
24508
24619
  sql2 += ` WHERE ${this.buildWhereClauses(params)}`;
24509
24620
  }
24510
- return db.run(sql2, params).changes;
24621
+ return (await exec.run(sql2, params)).changes;
24511
24622
  }
24512
- update(data) {
24513
- const db = getDatabase();
24623
+ async update(data) {
24624
+ const exec = getExecutor();
24514
24625
  const entries = Object.entries(data);
24515
24626
  const sets = entries.map(([k2]) => `${k2} = ?`).join(", ");
24516
24627
  const params = entries.map(([, v2]) => v2);
24517
24628
  if (this._definition.traits?.useTimestamps) {
24518
- params.push(new Date().toISOString());
24629
+ params.push(formatNow());
24519
24630
  }
24520
24631
  let sql2 = `UPDATE ${this._definition.table} SET ${sets}${this._definition.traits?.useTimestamps ? ", updated_at = ?" : ""}`;
24521
24632
  if (this._wheres.length > 0) {
24522
24633
  sql2 += ` WHERE ${this.buildWhereClauses(params)}`;
24523
24634
  }
24524
- return db.run(sql2, params).changes;
24635
+ return (await exec.run(sql2, params)).changes;
24525
24636
  }
24526
24637
  }
24527
24638
  function createModel(definition) {
@@ -24563,28 +24674,22 @@ function createModel(definition) {
24563
24674
  limit: (count) => new ModelQueryBuilder(definition).limit(count),
24564
24675
  take: (count) => new ModelQueryBuilder(definition).take(count),
24565
24676
  skip: (count) => new ModelQueryBuilder(definition).skip(count),
24566
- find(id) {
24567
- const db = getDatabase();
24677
+ async find(id) {
24678
+ const exec = getExecutor();
24568
24679
  const pk = definition.primaryKey || "id";
24569
- const sql2 = `SELECT * FROM ${definition.table} WHERE ${pk} = ?`;
24570
- let stmt = preparedStatementCache.get(sql2);
24571
- if (!stmt) {
24572
- stmt = db.prepare(sql2);
24573
- preparedStatementCache.set(sql2, stmt);
24574
- }
24575
- const row = stmt.get(id);
24680
+ const row = await exec.get(`SELECT * FROM ${definition.table} WHERE ${pk} = ?`, [id]);
24576
24681
  return row ? new ModelInstance(definition, row) : undefined;
24577
24682
  },
24578
- findOrFail(id) {
24579
- const result = model.find(id);
24683
+ async findOrFail(id) {
24684
+ const result = await model.find(id);
24580
24685
  if (!result)
24581
24686
  throw new Error(`${definition.name} with id ${id} not found`);
24582
24687
  return result;
24583
24688
  },
24584
- findMany(ids) {
24585
- const db = getDatabase();
24689
+ async findMany(ids) {
24690
+ const exec = getExecutor();
24586
24691
  const pk = definition.primaryKey || "id";
24587
- const rows = db.query(`SELECT * FROM ${definition.table} WHERE ${pk} IN (${ids.map(() => "?").join(", ")})`).all(...ids);
24692
+ const rows = await exec.all(`SELECT * FROM ${definition.table} WHERE ${pk} IN (${ids.map(() => "?").join(", ")})`, ids);
24588
24693
  return rows.map((row) => new ModelInstance(definition, row));
24589
24694
  },
24590
24695
  all: () => new ModelQueryBuilder(definition).get(),
@@ -24601,44 +24706,47 @@ function createModel(definition) {
24601
24706
  whereNotBetween(column, range) {
24602
24707
  return new ModelQueryBuilder(definition).whereNotBetween(column, range);
24603
24708
  },
24604
- create(data) {
24709
+ async create(data) {
24605
24710
  const instance = new ModelInstance(definition, data);
24606
- instance.save();
24711
+ await instance.save();
24607
24712
  return instance;
24608
24713
  },
24609
- createMany(items) {
24610
- return items.map((data) => this.create(data));
24714
+ async createMany(items) {
24715
+ const out = [];
24716
+ for (const data of items)
24717
+ out.push(await this.create(data));
24718
+ return out;
24611
24719
  },
24612
- updateOrCreate(search, data) {
24720
+ async updateOrCreate(search, data) {
24613
24721
  let query = new ModelQueryBuilder(definition);
24614
24722
  for (const [key, value] of Object.entries(search)) {
24615
24723
  query = query.where(key, value);
24616
24724
  }
24617
- const existing = query.first();
24725
+ const existing = await query.first();
24618
24726
  if (existing) {
24619
- existing.update(data);
24727
+ await existing.update(data);
24620
24728
  return existing;
24621
24729
  }
24622
24730
  return this.create({ ...search, ...data });
24623
24731
  },
24624
- firstOrCreate(search, data) {
24732
+ async firstOrCreate(search, data) {
24625
24733
  let query = new ModelQueryBuilder(definition);
24626
24734
  for (const [key, value] of Object.entries(search)) {
24627
24735
  query = query.where(key, value);
24628
24736
  }
24629
- const existing = query.first();
24737
+ const existing = await query.first();
24630
24738
  return existing || this.create({ ...search, ...data });
24631
24739
  },
24632
- destroy(id) {
24633
- const db = getDatabase();
24740
+ async destroy(id) {
24741
+ const exec = getExecutor();
24634
24742
  const pk = definition.primaryKey || "id";
24635
- return db.run(`DELETE FROM ${definition.table} WHERE ${pk} = ?`, [id]).changes > 0;
24743
+ return (await exec.run(`DELETE FROM ${definition.table} WHERE ${pk} = ?`, [id])).changes > 0;
24636
24744
  },
24637
24745
  remove(id) {
24638
24746
  return this.destroy(id);
24639
24747
  },
24640
- truncate() {
24641
- getDatabase().run(`DELETE FROM ${definition.table}`);
24748
+ async truncate() {
24749
+ await getExecutor().run(`DELETE FROM ${definition.table}`, []);
24642
24750
  },
24643
24751
  getDefinition: () => definition,
24644
24752
  getTable: () => definition.table,
@@ -24668,8 +24776,8 @@ function createModel(definition) {
24668
24776
  }
24669
24777
  });
24670
24778
  }
24671
- function createTableFromModel(definition) {
24672
- const db = getDatabase();
24779
+ async function createTableFromModel(definition) {
24780
+ const exec = getExecutor();
24673
24781
  const pk = definition.primaryKey || "id";
24674
24782
  const columns = [];
24675
24783
  columns.push(definition.autoIncrement !== false ? `${pk} INTEGER PRIMARY KEY AUTOINCREMENT` : `${pk} INTEGER PRIMARY KEY`);
@@ -24702,7 +24810,7 @@ function createTableFromModel(definition) {
24702
24810
  if (definition.traits?.useSoftDeletes) {
24703
24811
  columns.push("deleted_at TEXT");
24704
24812
  }
24705
- db.run(`CREATE TABLE IF NOT EXISTS ${definition.table} (${columns.join(", ")})`);
24813
+ await exec.run(`CREATE TABLE IF NOT EXISTS ${definition.table} (${columns.join(", ")})`, []);
24706
24814
  }
24707
24815
  function createFakerCompatLayer(underlying) {
24708
24816
  return new Proxy(underlying, {
@@ -24726,7 +24834,7 @@ function createFakerCompatLayer(underlying) {
24726
24834
  });
24727
24835
  }
24728
24836
  async function seedModel(definition, count, faker) {
24729
- const db = getDatabase();
24837
+ const exec = getExecutor();
24730
24838
  const seeder = definition.traits?.useSeeder;
24731
24839
  const seedCount = count ?? (typeof seeder === "object" && seeder ? seeder.count : 10);
24732
24840
  if (!faker) {
@@ -24745,23 +24853,24 @@ async function seedModel(definition, count, faker) {
24745
24853
  data[name] = attr.factory(faker);
24746
24854
  }
24747
24855
  if (definition.traits?.useTimestamps) {
24748
- const now = new Date().toISOString();
24856
+ const now = formatNow();
24749
24857
  data.created_at = now;
24750
24858
  data.updated_at = now;
24751
24859
  }
24752
24860
  if (definition.traits?.useUuid)
24753
24861
  data.uuid = crypto.randomUUID();
24754
24862
  const columns = Object.keys(data);
24755
- db.run(`INSERT INTO ${definition.table} (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`, Object.values(data));
24863
+ await exec.run(`INSERT INTO ${definition.table} (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`, Object.values(data));
24756
24864
  }
24757
24865
  }
24758
- var SAFE_SQL_IDENTIFIER, _getModel = null, globalDb = null, snakeCaseCache, tableNameCache, relationCache, preparedStatementCache;
24866
+ var SAFE_SQL_IDENTIFIER, _getModel = null, globalDb = null, _executor = null, _executorForDb = null, _executorDialect = null, _executorDatabase = null, snakeCaseCache, tableNameCache, relationCache;
24759
24867
  var init_orm = __esm(() => {
24868
+ init_config();
24869
+ init_db();
24760
24870
  SAFE_SQL_IDENTIFIER = /^[A-Z_][A-Z0-9_]*$/i;
24761
24871
  snakeCaseCache = new Map;
24762
24872
  tableNameCache = new Map;
24763
24873
  relationCache = new Map;
24764
- preparedStatementCache = new Map;
24765
24874
  });
24766
24875
 
24767
24876
  // src/model.ts
@@ -29174,7 +29283,7 @@ function getPrefix() {
29174
29283
  }
29175
29284
  var prefix = getPrefix();
29176
29285
  // package.json
29177
- var version2 = "0.1.24";
29286
+ var version2 = "0.1.25";
29178
29287
 
29179
29288
  // bin/cli.ts
29180
29289
  init_actions();