bun-query-builder 0.1.59 → 0.1.61

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
@@ -11704,6 +11704,7 @@ var init_config = __esm(() => {
11704
11704
  init_dist();
11705
11705
  defaultConfig4 = {
11706
11706
  verbose: true,
11707
+ snapshotDir: ".qb",
11707
11708
  dialect: "postgres",
11708
11709
  database: {
11709
11710
  database: "test_db",
@@ -12062,6 +12063,13 @@ function createSQLiteSQL(filename) {
12062
12063
  sqlFunction._wrapper = wrapper;
12063
12064
  return sqlFunction;
12064
12065
  }
12066
+ function sqliteFileFromUrl(url) {
12067
+ const stripped = url.replace(/^(?:sqlite|sqlite3|file):/i, "");
12068
+ if (stripped === url)
12069
+ return url;
12070
+ const path = stripped.startsWith("///") ? stripped.slice(2) : stripped.startsWith("//") ? stripped.slice(2) : stripped;
12071
+ return path || ":memory:";
12072
+ }
12065
12073
  function createConnectionString(dialect, dbConfig) {
12066
12074
  if ((dialect === "postgres" || dialect === "mysql" || dialect === "singlestore") && process19.env.DB_CONNECTION === dialect) {
12067
12075
  const e = process19.env;
@@ -12075,7 +12083,7 @@ function createConnectionString(dialect, dbConfig) {
12075
12083
  return `${scheme}://${envUser}:${envPass}@${envHost}${envPort ? `:${envPort}` : ""}/${envDb}${ssl2}`;
12076
12084
  }
12077
12085
  if (dbConfig.url) {
12078
- return dbConfig.url;
12086
+ return dialect === "sqlite" ? sqliteFileFromUrl(dbConfig.url) : dbConfig.url;
12079
12087
  }
12080
12088
  const { database, username, password, host = "localhost", port, ssl } = dbConfig;
12081
12089
  const sslQ = ssl || process19.env.DB_SSL === "true" || process19.env.DB_SSL === "1" ? "?ssl=true" : "";
@@ -12351,9 +12359,37 @@ var init_benchmark = __esm(() => {
12351
12359
  init_src2();
12352
12360
  });
12353
12361
 
12362
+ // src/inflect.ts
12363
+ function stripTrailingS(name) {
12364
+ return name.endsWith("s") ? name.slice(0, -1) : name;
12365
+ }
12366
+ function inflectSingular(name) {
12367
+ if (name.endsWith("ies") && name.length > 3) {
12368
+ const stem = name.slice(0, -3);
12369
+ const prev = stem[stem.length - 1];
12370
+ if (prev && !"aeiou".includes(prev))
12371
+ return `${stem}y`;
12372
+ }
12373
+ if (name.endsWith("es") && name.length > 2) {
12374
+ const stem = name.slice(0, -2);
12375
+ if (stem.endsWith("s") || stem.endsWith("x") || stem.endsWith("ch") || stem.endsWith("sh"))
12376
+ return stem;
12377
+ }
12378
+ if (name.endsWith("s") && !name.endsWith("ss") && !name.endsWith("us") && !name.endsWith("is"))
12379
+ return name.slice(0, -1);
12380
+ return name;
12381
+ }
12382
+ function singularizerFor(strategy) {
12383
+ if (strategy === "none")
12384
+ return (name) => name;
12385
+ if (strategy === "inflect")
12386
+ return inflectSingular;
12387
+ return stripTrailingS;
12388
+ }
12389
+
12354
12390
  // src/pivot.ts
12355
12391
  function defaultSingularize(name) {
12356
- return name.endsWith("s") ? name.slice(0, -1) : name;
12392
+ return singularizerFor(config5.relations?.singularizeStrategy)(name);
12357
12393
  }
12358
12394
  function resolvePivot(meta, parentTable, relationKey, options = {}) {
12359
12395
  const singularize = options.singularize ?? defaultSingularize;
@@ -12430,6 +12466,9 @@ function* iterateAllPivots(meta, options = {}) {
12430
12466
  }
12431
12467
  }
12432
12468
  }
12469
+ var init_pivot = __esm(() => {
12470
+ init_config();
12471
+ });
12433
12472
 
12434
12473
  // src/client.ts
12435
12474
  function isRawExpression(expr) {
@@ -12610,7 +12649,13 @@ class QueryCache {
12610
12649
  this.cache.clear();
12611
12650
  }
12612
12651
  setMaxSize(size) {
12613
- this.maxSize = size;
12652
+ this.maxSize = Math.max(0, Math.floor(size));
12653
+ while (this.cache.size > this.maxSize) {
12654
+ const lruKey = this.cache.keys().next().value;
12655
+ if (lruKey === undefined)
12656
+ break;
12657
+ this.cache.delete(lruKey);
12658
+ }
12614
12659
  }
12615
12660
  }
12616
12661
  function isRetriableTxError(err) {
@@ -12715,8 +12760,7 @@ function computeBackoffMs(attempt, cfg) {
12715
12760
  const max = Math.max(base, cfg?.maxMs ?? 2000);
12716
12761
  let ms = Math.min(max, base * factor ** Math.max(0, attempt - 1));
12717
12762
  if (cfg?.jitter) {
12718
- const jitter = Math.random() * ms * 0.2;
12719
- ms = ms - jitter / 2;
12763
+ ms = Math.min(max, ms * (0.9 + Math.random() * 0.2));
12720
12764
  }
12721
12765
  return Math.floor(ms);
12722
12766
  }
@@ -12968,11 +13012,7 @@ function createQueryBuilder(state) {
12968
13012
  const pivotColumns = new Map;
12969
13013
  const pivotConfigRelations = new Set;
12970
13014
  let cacheTtl = 60000;
12971
- const singularize = (name) => {
12972
- if (config5.relations.singularizeStrategy === "none")
12973
- return name;
12974
- return name.endsWith("s") ? name.slice(0, -1) : name;
12975
- };
13015
+ const singularize = (name) => singularizerFor(config5.relations.singularizeStrategy)(name);
12976
13016
  const resolvePivotLocal = (relationKey) => {
12977
13017
  if (!meta)
12978
13018
  return null;
@@ -15448,6 +15488,7 @@ function createQueryBuilder(state) {
15448
15488
  const colCount = keys.length;
15449
15489
  const totalParams = rowCount * colCount;
15450
15490
  params.length = totalParams;
15491
+ const columnList = isPostgres ? keys.map((k) => quoteId(k)).join(",") : keys.join(",");
15451
15492
  if (rowCount === 1) {
15452
15493
  if (!isPostgres) {
15453
15494
  let cols = quoteId(keys[0]);
@@ -15460,7 +15501,6 @@ function createQueryBuilder(state) {
15460
15501
  }
15461
15502
  sqlText = `INSERT INTO ${quoteId(table)}(${cols})VALUES(${placeholders})`;
15462
15503
  } else {
15463
- const columnList = keys.map((k) => quoteId(k)).join(",");
15464
15504
  sqlText = `INSERT INTO ${quoteId(table)}(${columnList})VALUES(`;
15465
15505
  for (let c = 0;c < colCount; c++) {
15466
15506
  if (c > 0)
@@ -15471,8 +15511,8 @@ function createQueryBuilder(state) {
15471
15511
  sqlText += ")";
15472
15512
  }
15473
15513
  } else {
15474
- const columnList = keys.map((k) => quoteId(k)).join(",");
15475
- sqlText = `INSERT INTO ${quoteId(table)}(${columnList})VALUES`;
15514
+ const columnList2 = keys.map((k) => quoteId(k)).join(",");
15515
+ sqlText = `INSERT INTO ${quoteId(table)}(${columnList2})VALUES`;
15476
15516
  let pidx = 0;
15477
15517
  for (let r = 0;r < rowCount; r++) {
15478
15518
  const row = rows[r];
@@ -16028,11 +16068,13 @@ function createQueryBuilder(state) {
16028
16068
  }
16029
16069
  },
16030
16070
  async savepoint(fn) {
16071
+ if (state?.inTransaction !== true)
16072
+ throw new Error("savepoint() must be called inside a transaction");
16031
16073
  const s = _sql;
16032
16074
  if (!s || typeof s.savepoint !== "function")
16033
- throw new Error("savepoint() must be called inside a transaction");
16075
+ throw new Error("savepoint() is not supported by the active connection");
16034
16076
  return await s.savepoint(async (sp) => {
16035
- const qb = createQueryBuilder({ sql: sp, meta, schema });
16077
+ const qb = createQueryBuilder({ sql: sp, meta, schema, inTransaction: true });
16036
16078
  return await fn(qb);
16037
16079
  });
16038
16080
  },
@@ -16449,6 +16491,7 @@ var SQL_PATTERNS, SAFE_WHERE_OPERATORS, warnedSqlFragmentContexts, queryCache, r
16449
16491
  var init_client = __esm(() => {
16450
16492
  init_config();
16451
16493
  init_db();
16494
+ init_pivot();
16452
16495
  SQL_PATTERNS = {
16453
16496
  SELECT_STAR: /^SELECT\s+\*/i,
16454
16497
  SELECT: /^SELECT\s+/i,
@@ -17049,7 +17092,7 @@ var init_db_info = __esm(() => {
17049
17092
  // src/actions/db-optimize.ts
17050
17093
  import process22 from "process";
17051
17094
  async function dbOptimize(options = {}) {
17052
- const dialect = options.dialect || process22.env.DB_DIALECT || "postgres";
17095
+ const dialect = options.dialect || process22.env.DB_DIALECT || config5.dialect || "postgres";
17053
17096
  const aggressive = options.aggressive || false;
17054
17097
  if (options.verbose) {
17055
17098
  console.log(`Optimizing ${dialect} database${aggressive ? " (aggressive mode)" : ""}...`);
@@ -17144,7 +17187,7 @@ var init_db_optimize = __esm(() => {
17144
17187
  // src/actions/db-wipe.ts
17145
17188
  import process23 from "process";
17146
17189
  async function dbWipe(options = {}) {
17147
- const dialect = options.dialect || process23.env.DB_DIALECT || "postgres";
17190
+ const dialect = options.dialect || process23.env.DB_DIALECT || config5.dialect || "postgres";
17148
17191
  if (options.verbose) {
17149
17192
  console.log(`Wiping all tables from ${dialect} database...`);
17150
17193
  }
@@ -18556,9 +18599,11 @@ function info(message) {
18556
18599
  if (config5.verbose)
18557
18600
  console.log(message);
18558
18601
  }
18602
+ function getSnapshotDir(workspaceRoot) {
18603
+ return join9(workspaceRoot, config5.snapshotDir || ".qb");
18604
+ }
18559
18605
  function getSnapshotPath(workspaceRoot, dialect) {
18560
- const snapshotDir = join9(workspaceRoot, ".qb");
18561
- return join9(snapshotDir, `model-snapshot.${dialect}.json`);
18606
+ return join9(getSnapshotDir(workspaceRoot), `model-snapshot.${dialect}.json`);
18562
18607
  }
18563
18608
  function loadPlanSnapshot(workspaceRoot, dialect) {
18564
18609
  const snapshotPath = getSnapshotPath(workspaceRoot, dialect);
@@ -18583,7 +18628,7 @@ function loadPlanSnapshot(workspaceRoot, dialect) {
18583
18628
  }
18584
18629
  function savePlanSnapshot(workspaceRoot, dialect, plan) {
18585
18630
  const snapshotPath = getSnapshotPath(workspaceRoot, dialect);
18586
- const snapshotDir = join9(workspaceRoot, ".qb");
18631
+ const snapshotDir = getSnapshotDir(workspaceRoot);
18587
18632
  const hash = hashMigrationPlan(plan);
18588
18633
  if (existsSync16(snapshotPath)) {
18589
18634
  try {
@@ -18762,7 +18807,7 @@ async function resetDatabase(dir, opts = {}) {
18762
18807
  if (!dir) {
18763
18808
  dir = join9(process25.cwd(), "app/Models");
18764
18809
  }
18765
- const dialect = opts.dialect || "postgres";
18810
+ const dialect = opts.dialect || config5.dialect || "postgres";
18766
18811
  const driver = getDialectDriver(dialect);
18767
18812
  const workspaceRoot = getWorkspaceRoot();
18768
18813
  try {
@@ -18862,7 +18907,7 @@ async function deleteMigrationFiles(dir, workspaceRoot, opts = {}) {
18862
18907
  if (!workspaceRoot) {
18863
18908
  workspaceRoot = getWorkspaceRoot();
18864
18909
  }
18865
- const dialect = String(opts.dialect || "postgres");
18910
+ const dialect = String(opts.dialect || config5.dialect || "postgres");
18866
18911
  const snapshotPath = getSnapshotPath(workspaceRoot, dialect);
18867
18912
  if (existsSync16(snapshotPath)) {
18868
18913
  unlinkSync(snapshotPath);
@@ -24693,6 +24738,13 @@ function normalizeAttributeKeys(data) {
24693
24738
  }
24694
24739
  return result;
24695
24740
  }
24741
+ function normalizeAttributeKeysInPlace(data) {
24742
+ for (const key in data) {
24743
+ if (toSnakeCase(key) !== key)
24744
+ return normalizeAttributeKeys(data);
24745
+ }
24746
+ return data;
24747
+ }
24696
24748
  function findAttributeDef(attrs, key) {
24697
24749
  if (attrs[key])
24698
24750
  return attrs[key];
@@ -24714,7 +24766,7 @@ class ModelInstance {
24714
24766
  _relations = {};
24715
24767
  constructor(definition, attributes = {}) {
24716
24768
  this._definition = definition;
24717
- this._attributes = normalizeAttributeKeys({ ...attributes });
24769
+ this._attributes = normalizeAttributeKeysInPlace({ ...attributes });
24718
24770
  this._original = null;
24719
24771
  const btmKeys = collectBelongsToManyKeys(definition);
24720
24772
  if (btmKeys.size === 0)
@@ -25015,6 +25067,9 @@ class ModelInstance {
25015
25067
  return json;
25016
25068
  }
25017
25069
  }
25070
+ function sqlColumn(name) {
25071
+ return toSnakeCase(name);
25072
+ }
25018
25073
  function toSnakeCase(str) {
25019
25074
  let cached = snakeCaseCache.get(str);
25020
25075
  if (cached !== undefined)
@@ -25158,12 +25213,12 @@ function resolveRelation(definition, relationName) {
25158
25213
  }
25159
25214
  pivotTable = throughModel.getTable?.() || throughModel.getDefinition?.()?.table || toTableName(config6.through);
25160
25215
  } else {
25161
- const a2 = parentTable.endsWith("s") ? parentTable.slice(0, -1) : parentTable;
25162
- const b2 = relatedTable.endsWith("s") ? relatedTable.slice(0, -1) : relatedTable;
25216
+ const a2 = singularizeWord(parentTable);
25217
+ const b2 = singularizeWord(relatedTable);
25163
25218
  pivotTable = [a2, b2].sort().join("_");
25164
25219
  }
25165
- const pivotFkParent = config6?.foreignKey || `${parentTable.endsWith("s") ? parentTable.slice(0, -1) : parentTable}_id`;
25166
- const pivotFkRelated = config6?.relatedKey || `${relatedTable.endsWith("s") ? relatedTable.slice(0, -1) : relatedTable}_id`;
25220
+ const pivotFkParent = config6?.foreignKey || `${singularizeWord(parentTable)}_id`;
25221
+ const pivotFkRelated = config6?.relatedKey || `${singularizeWord(relatedTable)}_id`;
25167
25222
  const pivotColumns = [];
25168
25223
  if (config6?.pivot?.columns) {
25169
25224
  for (const k2 of Object.keys(config6.pivot.columns))
@@ -25231,8 +25286,17 @@ function resolveRelation(definition, relationName) {
25231
25286
  return hot;
25232
25287
  return null;
25233
25288
  }
25289
+ function distinctParentIds(instances, pk) {
25290
+ const seen = new Set;
25291
+ for (const i2 of instances) {
25292
+ const v2 = i2.get(pk);
25293
+ if (v2 != null)
25294
+ seen.add(v2);
25295
+ }
25296
+ return [...seen];
25297
+ }
25234
25298
  function singularizeWord(table) {
25235
- return table.endsWith("s") ? table.slice(0, -1) : table;
25299
+ return singularizerFor(config5.relations?.singularizeStrategy)(table);
25236
25300
  }
25237
25301
 
25238
25302
  class BelongsToManyRelationBuilder {
@@ -25635,7 +25699,7 @@ class ModelQueryBuilder {
25635
25699
  }
25636
25700
  whereNotBetween(column, range) {
25637
25701
  assertValidIdentifier(column, "whereNotBetween(column)");
25638
- const col = column;
25702
+ const col = sqlColumn(column);
25639
25703
  this._wheres.push({
25640
25704
  raw: `(${col} < ? OR ${col} > ?)`,
25641
25705
  rawParams: [range[0], range[1]],
@@ -25700,13 +25764,14 @@ class ModelQueryBuilder {
25700
25764
  if (w.rawParams && w.rawParams.length > 0)
25701
25765
  params.push(...w.rawParams);
25702
25766
  } else if (w.value === null) {
25703
- clause = w.operator === "=" ? `${w.column} IS NULL` : `${w.column} IS NOT NULL`;
25767
+ const col = sqlColumn(w.column);
25768
+ clause = w.operator === "=" ? `${col} IS NULL` : `${col} IS NOT NULL`;
25704
25769
  } else if (w.operator === "in" || w.operator === "not in") {
25705
25770
  const arr = w.value;
25706
- clause = `${w.column} ${w.operator.toUpperCase()} (${arr.map(() => "?").join(", ")})`;
25771
+ clause = `${sqlColumn(w.column)} ${w.operator.toUpperCase()} (${arr.map(() => "?").join(", ")})`;
25707
25772
  params.push(...arr);
25708
25773
  } else {
25709
- clause = `${w.column} ${w.operator} ?`;
25774
+ clause = `${sqlColumn(w.column)} ${w.operator} ?`;
25710
25775
  params.push(w.value);
25711
25776
  }
25712
25777
  clauses.push(i2 === 0 ? clause : `${w.boolean.toUpperCase()} ${clause}`);
@@ -25727,13 +25792,14 @@ class ModelQueryBuilder {
25727
25792
  }
25728
25793
  buildQuery() {
25729
25794
  const params = [];
25730
- let sql2 = `SELECT ${this._select.join(", ")} FROM ${this._definition.table}`;
25795
+ const cols = this._select.map((c2) => c2 === "*" ? c2 : sqlColumn(c2));
25796
+ let sql2 = `SELECT ${cols.join(", ")} FROM ${this._definition.table}`;
25731
25797
  const whereBody = this.composeWhere(params);
25732
25798
  if (whereBody) {
25733
25799
  sql2 += ` WHERE ${whereBody}`;
25734
25800
  }
25735
25801
  if (this._orderBy.length > 0) {
25736
- sql2 += ` ORDER BY ${this._orderBy.map((o2) => `${o2.column} ${o2.direction.toUpperCase()}`).join(", ")}`;
25802
+ sql2 += ` ORDER BY ${this._orderBy.map((o2) => `${sqlColumn(o2.column)} ${o2.direction.toUpperCase()}`).join(", ")}`;
25737
25803
  }
25738
25804
  if (this._limit !== undefined)
25739
25805
  sql2 += ` LIMIT ${this._limit}`;
@@ -25747,165 +25813,168 @@ class ModelQueryBuilder {
25747
25813
  async eagerLoadRelations(instances) {
25748
25814
  if (instances.length === 0 || this._withRelations.length === 0)
25749
25815
  return;
25816
+ await Promise.all(this._withRelations.map((r2) => this.eagerLoadRelation(r2, instances)));
25817
+ }
25818
+ async eagerLoadRelation(relationName, instances) {
25750
25819
  const exec = getExecutor();
25751
25820
  const pk = this._definition.primaryKey || "id";
25752
- for (const relationName of this._withRelations) {
25753
- const cacheKey = `${this._definition.name}:${relationName}`;
25754
- let rel = relationCache.get(cacheKey);
25755
- if (rel === undefined) {
25756
- rel = resolveRelation(this._definition, relationName);
25757
- if (relationCache.size >= RELATION_CACHE_MAX)
25758
- relationCache.clear();
25759
- relationCache.set(cacheKey, rel);
25760
- }
25761
- if (!rel)
25762
- continue;
25763
- if (rel.type === "hasMany" || rel.type === "hasOne") {
25764
- const parentIds = instances.map((i2) => i2.get(pk)).filter((id) => id != null);
25765
- if (parentIds.length === 0)
25766
- continue;
25767
- const placeholders = parentIds.map(() => "?").join(", ");
25768
- const rows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.foreignKey} IN (${placeholders})`, parentIds);
25769
- const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
25770
- const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
25771
- if (rel.type === "hasMany") {
25772
- const grouped = new Map;
25773
- for (const row of rows) {
25774
- const fkVal = row[rel.foreignKey];
25775
- if (!grouped.has(fkVal))
25776
- grouped.set(fkVal, []);
25777
- grouped.get(fkVal).push(row);
25778
- }
25779
- for (const instance of instances) {
25780
- const related = grouped.get(instance.get(pk)) || [];
25781
- instance.setRelation(relationName, related.map((r2) => new ModelInstance(relDef, r2)));
25782
- }
25783
- } else {
25784
- const byFk = new Map;
25785
- for (const row of rows) {
25786
- byFk.set(row[rel.foreignKey], row);
25787
- }
25788
- for (const instance of instances) {
25789
- const row = byFk.get(instance.get(pk));
25790
- instance.setRelation(relationName, row ? new ModelInstance(relDef, row) : null);
25791
- }
25821
+ const cacheKey = `${this._definition.name}:${relationName}`;
25822
+ let rel = relationCache.get(cacheKey);
25823
+ if (rel === undefined) {
25824
+ rel = resolveRelation(this._definition, relationName);
25825
+ if (relationCache.size >= RELATION_CACHE_MAX)
25826
+ relationCache.clear();
25827
+ relationCache.set(cacheKey, rel);
25828
+ }
25829
+ if (!rel)
25830
+ return;
25831
+ if (rel.type === "hasMany" || rel.type === "hasOne") {
25832
+ const parentIds = distinctParentIds(instances, pk);
25833
+ if (parentIds.length === 0)
25834
+ return;
25835
+ const placeholders = parentIds.map(() => "?").join(", ");
25836
+ const rows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.foreignKey} IN (${placeholders})`, parentIds);
25837
+ const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
25838
+ const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
25839
+ if (rel.type === "hasMany") {
25840
+ const grouped = new Map;
25841
+ for (const row of rows) {
25842
+ const fkVal = row[rel.foreignKey];
25843
+ if (!grouped.has(fkVal))
25844
+ grouped.set(fkVal, []);
25845
+ grouped.get(fkVal).push(row);
25792
25846
  }
25793
- }
25794
- if (rel.type === "belongsTo") {
25795
- const fkSet = new Set;
25796
- for (const i2 of instances) {
25797
- const v2 = i2._attributes[rel.foreignKey];
25798
- if (v2 != null)
25799
- fkSet.add(v2);
25847
+ for (const instance of instances) {
25848
+ const related = grouped.get(instance.get(pk)) || [];
25849
+ instance.setRelation(relationName, related.map((r2) => new ModelInstance(relDef, r2)));
25800
25850
  }
25801
- const uniqueFkValues = [...fkSet];
25802
- if (uniqueFkValues.length === 0)
25803
- continue;
25804
- const placeholders = uniqueFkValues.map(() => "?").join(", ");
25805
- const rows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.localKey} IN (${placeholders})`, uniqueFkValues);
25806
- const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
25807
- const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
25808
- const byPk = new Map;
25851
+ } else {
25852
+ const byFk = new Map;
25809
25853
  for (const row of rows) {
25810
- byPk.set(row[rel.localKey], row);
25854
+ const k2 = row[rel.foreignKey];
25855
+ if (!byFk.has(k2))
25856
+ byFk.set(k2, row);
25811
25857
  }
25812
25858
  for (const instance of instances) {
25813
- const fkVal = instance._attributes[rel.foreignKey];
25814
- const row = byPk.get(fkVal);
25859
+ const row = byFk.get(instance.get(pk));
25815
25860
  instance.setRelation(relationName, row ? new ModelInstance(relDef, row) : null);
25816
25861
  }
25817
25862
  }
25818
- if (rel.type === "belongsToMany") {
25819
- const parentIds = instances.map((i2) => i2.get(pk)).filter((id) => id != null);
25820
- if (parentIds.length === 0)
25821
- continue;
25822
- if (!rel.pivotTable || !rel.pivotFkParent || !rel.pivotFkRelated)
25823
- continue;
25824
- const pivotPlaceholders = parentIds.map(() => "?").join(", ");
25825
- const pivotRows = await exec.all(`SELECT * FROM ${rel.pivotTable} WHERE ${rel.pivotFkParent} IN (${pivotPlaceholders})`, parentIds);
25826
- if (pivotRows.length === 0) {
25827
- for (const instance of instances)
25828
- instance.setRelation(relationName, []);
25829
- continue;
25830
- }
25831
- const relatedIdSet = new Set;
25832
- for (const p2 of pivotRows) {
25833
- const v2 = p2[rel.pivotFkRelated];
25834
- if (v2 != null)
25835
- relatedIdSet.add(v2);
25836
- }
25837
- const relatedIds = [...relatedIdSet];
25838
- const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
25839
- const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
25840
- const relatedPk = relDef?.primaryKey || "id";
25841
- let relatedRows = [];
25842
- if (relatedIds.length > 0) {
25843
- const relPlaceholders = relatedIds.map(() => "?").join(", ");
25844
- relatedRows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${relatedPk} IN (${relPlaceholders})`, relatedIds);
25845
- }
25846
- const relatedByPk = new Map;
25847
- for (const r2 of relatedRows)
25848
- relatedByPk.set(r2[relatedPk], r2);
25849
- const pivotByParent = new Map;
25850
- for (const p2 of pivotRows) {
25851
- const key = p2[rel.pivotFkParent];
25852
- if (!pivotByParent.has(key))
25853
- pivotByParent.set(key, []);
25854
- pivotByParent.get(key).push(p2);
25855
- }
25856
- const pivotKnownKeys = new Set([rel.pivotFkParent, rel.pivotFkRelated]);
25857
- for (const instance of instances) {
25858
- const parentVal = instance.get(pk);
25859
- const myPivots = pivotByParent.get(parentVal) || [];
25860
- const relatedInstances = myPivots.map((p2) => {
25861
- const relRow = relatedByPk.get(p2[rel.pivotFkRelated]);
25862
- if (!relRow)
25863
- return null;
25864
- const inst = new ModelInstance(relDef, relRow);
25865
- const extras = {};
25866
- for (const [k2, v2] of Object.entries(p2)) {
25867
- if (!pivotKnownKeys.has(k2))
25868
- extras[k2] = v2;
25869
- }
25870
- inst.pivot = extras;
25871
- return inst;
25872
- }).filter((x2) => x2 !== null);
25873
- instance.setRelation(relationName, relatedInstances);
25874
- }
25863
+ }
25864
+ if (rel.type === "belongsTo") {
25865
+ const fkSet = new Set;
25866
+ for (const i2 of instances) {
25867
+ const v2 = i2._attributes[rel.foreignKey];
25868
+ if (v2 != null)
25869
+ fkSet.add(v2);
25875
25870
  }
25876
- if (rel.type === "hasManyThrough" || rel.type === "hasOneThrough") {
25877
- const parentIds = instances.map((i2) => i2.get(pk)).filter((id) => id != null);
25878
- if (parentIds.length === 0)
25879
- continue;
25880
- const throughPk = rel.throughLocalKey || "id";
25881
- const throughPh = parentIds.map(() => "?").join(", ");
25882
- const throughRows = await exec.all(`SELECT ${throughPk}, ${rel.throughForeignKey} FROM ${rel.throughTable} WHERE ${rel.throughForeignKey} IN (${throughPh})`, parentIds);
25883
- if (throughRows.length === 0) {
25884
- for (const instance of instances)
25885
- instance.setRelation(relationName, rel.type === "hasManyThrough" ? [] : null);
25871
+ const uniqueFkValues = [...fkSet];
25872
+ if (uniqueFkValues.length === 0)
25873
+ return;
25874
+ const placeholders = uniqueFkValues.map(() => "?").join(", ");
25875
+ const rows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.localKey} IN (${placeholders})`, uniqueFkValues);
25876
+ const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
25877
+ const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
25878
+ const byPk = new Map;
25879
+ for (const row of rows) {
25880
+ byPk.set(row[rel.localKey], row);
25881
+ }
25882
+ for (const instance of instances) {
25883
+ const fkVal = instance._attributes[rel.foreignKey];
25884
+ const row = byPk.get(fkVal);
25885
+ instance.setRelation(relationName, row ? new ModelInstance(relDef, row) : null);
25886
+ }
25887
+ }
25888
+ if (rel.type === "belongsToMany") {
25889
+ const parentIds = distinctParentIds(instances, pk);
25890
+ if (parentIds.length === 0)
25891
+ return;
25892
+ if (!rel.pivotTable || !rel.pivotFkParent || !rel.pivotFkRelated)
25893
+ return;
25894
+ const pivotPlaceholders = parentIds.map(() => "?").join(", ");
25895
+ const pivotRows = await exec.all(`SELECT * FROM ${rel.pivotTable} WHERE ${rel.pivotFkParent} IN (${pivotPlaceholders})`, parentIds);
25896
+ if (pivotRows.length === 0) {
25897
+ for (const instance of instances)
25898
+ instance.setRelation(relationName, []);
25899
+ return;
25900
+ }
25901
+ const relatedIdSet = new Set;
25902
+ for (const p2 of pivotRows) {
25903
+ const v2 = p2[rel.pivotFkRelated];
25904
+ if (v2 != null)
25905
+ relatedIdSet.add(v2);
25906
+ }
25907
+ const relatedIds = [...relatedIdSet];
25908
+ const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
25909
+ const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
25910
+ const relatedPk = relDef?.primaryKey || "id";
25911
+ let relatedRows = [];
25912
+ if (relatedIds.length > 0) {
25913
+ const relPlaceholders = relatedIds.map(() => "?").join(", ");
25914
+ relatedRows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${relatedPk} IN (${relPlaceholders})`, relatedIds);
25915
+ }
25916
+ const relatedByPk = new Map;
25917
+ for (const r2 of relatedRows)
25918
+ relatedByPk.set(r2[relatedPk], r2);
25919
+ const pivotByParent = new Map;
25920
+ for (const p2 of pivotRows) {
25921
+ const key = p2[rel.pivotFkParent];
25922
+ if (!pivotByParent.has(key))
25923
+ pivotByParent.set(key, []);
25924
+ pivotByParent.get(key).push(p2);
25925
+ }
25926
+ const pivotKnownKeys = new Set([rel.pivotFkParent, rel.pivotFkRelated]);
25927
+ for (const instance of instances) {
25928
+ const parentVal = instance.get(pk);
25929
+ const myPivots = pivotByParent.get(parentVal) || [];
25930
+ const relatedInstances = myPivots.map((p2) => {
25931
+ const relRow = relatedByPk.get(p2[rel.pivotFkRelated]);
25932
+ if (!relRow)
25933
+ return null;
25934
+ const inst = new ModelInstance(relDef, relRow);
25935
+ const extras = {};
25936
+ for (const [k2, v2] of Object.entries(p2)) {
25937
+ if (!pivotKnownKeys.has(k2))
25938
+ extras[k2] = v2;
25939
+ }
25940
+ inst.pivot = extras;
25941
+ return inst;
25942
+ }).filter((x2) => x2 !== null);
25943
+ instance.setRelation(relationName, relatedInstances);
25944
+ }
25945
+ }
25946
+ if (rel.type === "hasManyThrough" || rel.type === "hasOneThrough") {
25947
+ const parentIds = distinctParentIds(instances, pk);
25948
+ if (parentIds.length === 0)
25949
+ return;
25950
+ const throughPk = rel.throughLocalKey || "id";
25951
+ const throughPh = parentIds.map(() => "?").join(", ");
25952
+ const throughRows = await exec.all(`SELECT ${throughPk}, ${rel.throughForeignKey} FROM ${rel.throughTable} WHERE ${rel.throughForeignKey} IN (${throughPh})`, parentIds);
25953
+ if (throughRows.length === 0) {
25954
+ for (const instance of instances)
25955
+ instance.setRelation(relationName, rel.type === "hasManyThrough" ? [] : null);
25956
+ return;
25957
+ }
25958
+ const throughToParent = new Map;
25959
+ for (const t2 of throughRows)
25960
+ throughToParent.set(t2[throughPk], t2[rel.throughForeignKey]);
25961
+ const throughIds = [...new Set(throughRows.map((t2) => t2[throughPk]))];
25962
+ const targetPh = throughIds.map(() => "?").join(", ");
25963
+ const targetRows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.targetForeignKey} IN (${targetPh})`, throughIds);
25964
+ const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
25965
+ const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
25966
+ const byParent = new Map;
25967
+ for (const row of targetRows) {
25968
+ const parentVal = throughToParent.get(row[rel.targetForeignKey]);
25969
+ if (parentVal == null)
25886
25970
  continue;
25887
- }
25888
- const throughToParent = new Map;
25889
- for (const t2 of throughRows)
25890
- throughToParent.set(t2[throughPk], t2[rel.throughForeignKey]);
25891
- const throughIds = [...new Set(throughRows.map((t2) => t2[throughPk]))];
25892
- const targetPh = throughIds.map(() => "?").join(", ");
25893
- const targetRows = await exec.all(`SELECT * FROM ${rel.relatedTable} WHERE ${rel.targetForeignKey} IN (${targetPh})`, throughIds);
25894
- const relatedModelDef = getModelFromRegistry(rel.relatedModelName);
25895
- const relDef = relatedModelDef?.getDefinition?.() || relatedModelDef?.definition || this._definition;
25896
- const byParent = new Map;
25897
- for (const row of targetRows) {
25898
- const parentVal = throughToParent.get(row[rel.targetForeignKey]);
25899
- if (parentVal == null)
25900
- continue;
25901
- if (!byParent.has(parentVal))
25902
- byParent.set(parentVal, []);
25903
- byParent.get(parentVal).push(new ModelInstance(relDef, row));
25904
- }
25905
- for (const instance of instances) {
25906
- const group = byParent.get(instance.get(pk)) || [];
25907
- instance.setRelation(relationName, rel.type === "hasManyThrough" ? group : group[0] ?? null);
25908
- }
25971
+ if (!byParent.has(parentVal))
25972
+ byParent.set(parentVal, []);
25973
+ byParent.get(parentVal).push(new ModelInstance(relDef, row));
25974
+ }
25975
+ for (const instance of instances) {
25976
+ const group = byParent.get(instance.get(pk)) || [];
25977
+ instance.setRelation(relationName, rel.type === "hasManyThrough" ? group : group[0] ?? null);
25909
25978
  }
25910
25979
  }
25911
25980
  }
@@ -25965,7 +26034,8 @@ class ModelQueryBuilder {
25965
26034
  assertValidIdentifier(column, "increment(column)");
25966
26035
  const exec = getExecutor();
25967
26036
  const params = [amount];
25968
- let sql2 = `UPDATE ${this._definition.table} SET ${column} = ${column} + ?`;
26037
+ const incCol = sqlColumn(column);
26038
+ let sql2 = `UPDATE ${this._definition.table} SET ${incCol} = ${incCol} + ?`;
25969
26039
  if (timestampsEnabled(this._definition)) {
25970
26040
  sql2 += `, updated_at = ?`;
25971
26041
  params.push(formatNow());
@@ -26023,26 +26093,27 @@ class ModelQueryBuilder {
26023
26093
  assertValidIdentifier(column, "pluck(column)");
26024
26094
  const exec = getExecutor();
26025
26095
  const params = [];
26026
- let sql2 = `SELECT ${column} FROM ${this._definition.table}`;
26096
+ const pluckCol = sqlColumn(column);
26097
+ let sql2 = `SELECT ${pluckCol} FROM ${this._definition.table}`;
26027
26098
  const whereBody = this.composeWhere(params);
26028
26099
  if (whereBody) {
26029
26100
  sql2 += ` WHERE ${whereBody}`;
26030
26101
  }
26031
26102
  if (this._orderBy.length > 0) {
26032
- sql2 += ` ORDER BY ${this._orderBy.map((o2) => `${o2.column} ${o2.direction.toUpperCase()}`).join(", ")}`;
26103
+ sql2 += ` ORDER BY ${this._orderBy.map((o2) => `${sqlColumn(o2.column)} ${o2.direction.toUpperCase()}`).join(", ")}`;
26033
26104
  }
26034
26105
  if (this._limit !== undefined)
26035
26106
  sql2 += ` LIMIT ${this._limit}`;
26036
26107
  if (this._offset !== undefined)
26037
26108
  sql2 += ` OFFSET ${this._offset}`;
26038
26109
  const rows = await exec.all(sql2, params);
26039
- return rows.map((r2) => r2[column]);
26110
+ return rows.map((r2) => r2[pluckCol]);
26040
26111
  }
26041
26112
  async aggregate(fn, column) {
26042
26113
  assertValidIdentifier(column, `${fn}(column)`);
26043
26114
  const exec = getExecutor();
26044
26115
  const params = [];
26045
- let sql2 = `SELECT ${fn}(${column}) as v FROM ${this._definition.table}`;
26116
+ let sql2 = `SELECT ${fn}(${sqlColumn(column)}) as v FROM ${this._definition.table}`;
26046
26117
  const whereBody = this.composeWhere(params);
26047
26118
  if (whereBody) {
26048
26119
  sql2 += ` WHERE ${whereBody}`;
@@ -26081,7 +26152,7 @@ class ModelQueryBuilder {
26081
26152
  async update(data) {
26082
26153
  const exec = getExecutor();
26083
26154
  const entries = Object.entries(data);
26084
- const sets = entries.map(([k2]) => `${k2} = ?`).join(", ");
26155
+ const sets = entries.map(([k2]) => `${sqlColumn(k2)} = ?`).join(", ");
26085
26156
  const params = entries.map(([, v2]) => v2);
26086
26157
  if (timestampsEnabled(this._definition)) {
26087
26158
  params.push(formatNow());
@@ -27930,6 +28001,9 @@ function info2(message) {
27930
28001
  function snakeCase(str) {
27931
28002
  return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z\d])([A-Z])/g, "$1_$2").replace(/(\d)([A-Z])/gi, "$1_$2").toLowerCase();
27932
28003
  }
28004
+ function singularizeTable(table) {
28005
+ return singularizerFor(config5.relations?.singularizeStrategy)(table);
28006
+ }
27933
28007
  function findWorkspaceRoot6(startPath) {
27934
28008
  let currentPath = startPath;
27935
28009
  while (currentPath !== dirname12(currentPath)) {
@@ -28318,7 +28392,7 @@ function buildMigrationPlan2(models, options) {
28318
28392
  const model = models[modelName];
28319
28393
  const traits = model?.traits ?? {};
28320
28394
  const modelTable = model.table || `${String(model.name).toLowerCase()}s`;
28321
- const singular = modelTable.replace(/s$/, "");
28395
+ const singular = singularizeTable(modelTable);
28322
28396
  if (traits.likeable) {
28323
28397
  const opts = typeof traits.likeable === "object" ? traits.likeable : {};
28324
28398
  const likeTable = opts.table || `${modelTable}_likes`;
@@ -28385,7 +28459,7 @@ function buildMigrationPlan2(models, options) {
28385
28459
  if (!btm || typeof btm !== "object" || Array.isArray(btm))
28386
28460
  continue;
28387
28461
  const parentTable = model.table || `${String(model.name).toLowerCase()}s`;
28388
- const parentSingular = parentTable.replace(/s$/, "");
28462
+ const parentSingular = singularizeTable(parentTable);
28389
28463
  for (const [relKey, value] of Object.entries(btm)) {
28390
28464
  const cfg = value;
28391
28465
  if (!cfg || typeof cfg !== "object")
@@ -28398,7 +28472,7 @@ function buildMigrationPlan2(models, options) {
28398
28472
  const relatedModelName = cfg.model;
28399
28473
  const relatedRaw = models[relatedModelName];
28400
28474
  const relatedTable = relatedRaw?.table || `${String(relatedModelName).toLowerCase()}s`;
28401
- const relatedSingular = relatedTable.replace(/s$/, "");
28475
+ const relatedSingular = singularizeTable(relatedTable);
28402
28476
  const pivotTable = cfg.table || [parentSingular, relatedSingular].sort().join("_");
28403
28477
  const fkParent = cfg.foreignKey || `${parentSingular}_id`;
28404
28478
  const fkRelated = cfg.relatedKey || `${relatedSingular}_id`;
@@ -29032,6 +29106,7 @@ var init_src2 = __esm(() => {
29032
29106
  init_loader();
29033
29107
  init_meta();
29034
29108
  init_migrations();
29109
+ init_pivot();
29035
29110
  init_orm();
29036
29111
  init_sqlite_pragmas();
29037
29112
  });
@@ -31075,7 +31150,7 @@ function getPrefix() {
31075
31150
  }
31076
31151
  var prefix = getPrefix();
31077
31152
  // package.json
31078
- var version2 = "0.1.59";
31153
+ var version2 = "0.1.61";
31079
31154
 
31080
31155
  // bin/cli.ts
31081
31156
  init_actions();