rev-dal 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/AGENTS.md +47 -78
  2. package/CONTRIBUTING.md +2 -2
  3. package/dist/lib/create-model.d.ts +12 -4
  4. package/dist/lib/create-model.d.ts.map +1 -1
  5. package/dist/lib/create-model.js +3 -2
  6. package/dist/lib/create-model.js.map +1 -1
  7. package/dist/lib/data-access-layer.d.ts.map +1 -1
  8. package/dist/lib/data-access-layer.js +1 -26
  9. package/dist/lib/data-access-layer.js.map +1 -1
  10. package/dist/lib/filter-operator.d.ts +26 -0
  11. package/dist/lib/filter-operator.d.ts.map +1 -0
  12. package/dist/lib/filter-operator.js +167 -0
  13. package/dist/lib/filter-operator.js.map +1 -0
  14. package/dist/lib/filter-where.d.ts +13 -40
  15. package/dist/lib/filter-where.d.ts.map +1 -1
  16. package/dist/lib/filter-where.js +24 -190
  17. package/dist/lib/filter-where.js.map +1 -1
  18. package/dist/lib/model-initializer.d.ts.map +1 -1
  19. package/dist/lib/model-initializer.js +6 -4
  20. package/dist/lib/model-initializer.js.map +1 -1
  21. package/dist/lib/model-manifest.d.ts +24 -2
  22. package/dist/lib/model-manifest.d.ts.map +1 -1
  23. package/dist/lib/model-registry.d.ts +5 -0
  24. package/dist/lib/model-registry.d.ts.map +1 -1
  25. package/dist/lib/model-registry.js +25 -0
  26. package/dist/lib/model-registry.js.map +1 -1
  27. package/dist/lib/model-types.d.ts +114 -29
  28. package/dist/lib/model-types.d.ts.map +1 -1
  29. package/dist/lib/model.d.ts +6 -7
  30. package/dist/lib/model.d.ts.map +1 -1
  31. package/dist/lib/model.js +123 -57
  32. package/dist/lib/model.js.map +1 -1
  33. package/dist/lib/query-builder.d.ts +178 -17
  34. package/dist/lib/query-builder.d.ts.map +1 -1
  35. package/dist/lib/query-builder.js +708 -234
  36. package/dist/lib/query-builder.js.map +1 -1
  37. package/dist/lib/sql-identifiers.d.ts +14 -0
  38. package/dist/lib/sql-identifiers.d.ts.map +1 -0
  39. package/dist/lib/sql-identifiers.js +40 -0
  40. package/dist/lib/sql-identifiers.js.map +1 -0
  41. package/dist/lib/sql-results.d.ts +11 -0
  42. package/dist/lib/sql-results.d.ts.map +1 -0
  43. package/dist/lib/sql-results.js +27 -0
  44. package/dist/lib/sql-results.js.map +1 -0
  45. package/dist/lib/transaction.d.ts +2 -0
  46. package/dist/lib/transaction.d.ts.map +1 -1
  47. package/dist/lib/transaction.js +14 -0
  48. package/dist/lib/transaction.js.map +1 -1
  49. package/dist/lib/type.d.ts +1 -0
  50. package/dist/lib/type.d.ts.map +1 -1
  51. package/dist/lib/type.js.map +1 -1
  52. package/docs/models.md +33 -1
  53. package/docs/queries.md +197 -1
  54. package/package.json +1 -1
  55. package/releases/0.2.2.md +11 -0
  56. package/releases/0.3.0.md +29 -0
@@ -1,13 +1,53 @@
1
1
  import { cloneRowValue } from './clone.js';
2
2
  import { convertPostgreSQLError } from './errors.js';
3
+ import { createOperators, isOperatorToken } from './filter-operator.js';
4
+ import { resolveModelLookupName } from './model-registry.js';
3
5
  import { debug } from './runtime.js';
4
- import { NumberType } from './type.js';
5
- /**
6
- * Separates relation and column in the aliases of inline-joined columns
7
- * (`"thing.id"`). Column and relation names are plain identifiers, which can't
8
- * contain it, so a joined column can never be mistaken for a main-table column.
9
- */
10
- const JOIN_ALIAS_SEPARATOR = '.';
6
+ import { columnReference, effectivePostgresIdentifier, isConfiguredIdentifier, postgresIdentifierParts, quoteIdentifier, renderParameterCast, } from './sql-identifiers.js';
7
+ import { SqlResultColumns } from './sql-results.js';
8
+ import { assertActiveTransaction, assertTransactionClient, } from './transaction.js';
9
+ import { ArrayType, NumberType } from './type.js';
10
+ function sqlTableReference(sql) {
11
+ return { sql, qualify: columnSql => `${sql}.${columnSql}` };
12
+ }
13
+ function tableReferencesConflict(left, right) {
14
+ const leftParts = postgresIdentifierParts(left);
15
+ const rightParts = postgresIdentifierParts(right);
16
+ return (leftParts.at(-1) === rightParts.at(-1) &&
17
+ (leftParts.length === 1 ||
18
+ rightParts.length === 1 ||
19
+ JSON.stringify(leftParts) === JSON.stringify(rightParts)));
20
+ }
21
+ class SqlAliases {
22
+ reserved;
23
+ generated = new Set();
24
+ constructor(references = []) {
25
+ this.reserved = new Set(references.map(effectivePostgresIdentifier));
26
+ }
27
+ reserve(reference) {
28
+ if (reference)
29
+ this.reserved.add(effectivePostgresIdentifier(reference));
30
+ }
31
+ allocate(preferred) {
32
+ let name = preferred;
33
+ while (this.reserved.has(effectivePostgresIdentifier(name)))
34
+ name += '_';
35
+ this.reserve(name);
36
+ this.generated.add(effectivePostgresIdentifier(name));
37
+ return quoteIdentifier(name);
38
+ }
39
+ isGenerated(reference) {
40
+ return this.generated.has(effectivePostgresIdentifier(reference));
41
+ }
42
+ copy() {
43
+ const copy = new SqlAliases();
44
+ for (const name of this.reserved)
45
+ copy.reserved.add(name);
46
+ for (const name of this.generated)
47
+ copy.generated.add(name);
48
+ return copy;
49
+ }
50
+ }
11
51
  /**
12
52
  * Validate a LIMIT/OFFSET value. Anything other than a non-negative safe
13
53
  * integer is rejected rather than coerced; callers should parse and clamp
@@ -61,10 +101,7 @@ function remapRowToCamelCase(row, fieldMappings) {
61
101
  }
62
102
  return remapped;
63
103
  }
64
- /** Column names that are safe to interpolate into SQL. */
65
- const SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
66
- /** Column added to batch-join rows to rank them per parent for `limit()`. */
67
- const JOIN_RANK_ALIAS = '_join_rank';
104
+ const correlationOperators = ['=', '<>', '<', '<=', '>', '>=', 'IS NOT DISTINCT FROM'];
68
105
  /**
69
106
  * Whether a value can be compared with `=` (or `= ANY` for arrays) in a
70
107
  * batch-join filter.
@@ -74,6 +111,10 @@ function isJoinFilterValue(value) {
74
111
  return true;
75
112
  if (Array.isArray(value))
76
113
  return value.every(item => item === null || isJoinFilterValue(item));
114
+ if (value !== null && typeof value === 'object') {
115
+ const prototype = Object.getPrototypeOf(value);
116
+ return prototype === Object.prototype || prototype === null;
117
+ }
77
118
  return ['string', 'number', 'boolean', 'bigint'].includes(typeof value);
78
119
  }
79
120
  /**
@@ -84,35 +125,88 @@ function isJoinFilterValue(value) {
84
125
  * @param applyFn The `_apply` callback from a join specification
85
126
  * @returns The recorded specification, or null when there is no callback
86
127
  */
87
- function recordJoinApply(applyFn) {
128
+ function recordJoinApply(applyFn, schema) {
88
129
  if (typeof applyFn !== 'function') {
89
130
  return null;
90
131
  }
91
- const spec = { filters: [], without: [], order: [], limit: null };
92
- const addFilter = (literal) => {
132
+ const spec = {
133
+ filters: [],
134
+ revisionFilters: [],
135
+ without: [],
136
+ order: [],
137
+ limit: null,
138
+ limitStrategy: 'window',
139
+ includeStale: false,
140
+ includeDeleted: false,
141
+ correlations: [],
142
+ };
143
+ const recordFilters = (literal, destination) => {
93
144
  if (!literal || typeof literal !== 'object' || Array.isArray(literal)) {
94
145
  throw new TypeError('_apply filterWhere() expects an object of field values.');
95
146
  }
96
147
  for (const [field, value] of Object.entries(literal)) {
97
148
  if (value === undefined)
98
149
  continue;
99
- if (!isJoinFilterValue(value)) {
150
+ if (!isJoinFilterValue(value) && !isOperatorToken(value)) {
100
151
  throw new TypeError(`_apply filterWhere() supports plain values, null and arrays; '${field}' has an ` +
101
- 'unsupported value (operator helpers are not supported in joins).');
152
+ 'unsupported value.');
153
+ }
154
+ if (schema &&
155
+ value !== null &&
156
+ typeof value === 'object' &&
157
+ !Array.isArray(value) &&
158
+ !(value instanceof Date) &&
159
+ !isOperatorToken(value)) {
160
+ try {
161
+ const definition = schema[field];
162
+ if (!definition)
163
+ throw new TypeError('Unknown batch filter field.');
164
+ definition.validate(value, field);
165
+ }
166
+ catch {
167
+ throw new TypeError(`_apply filterWhere() has an object value incompatible with '${field}'.`);
168
+ }
102
169
  }
103
- spec.filters.push({ field, value });
170
+ destination.push({ field, value });
104
171
  }
172
+ };
173
+ const addFilter = literal => {
174
+ recordFilters(literal, spec.filters);
105
175
  return builder;
106
176
  };
107
177
  const builder = {
178
+ ops: createOperators(),
108
179
  filterWhere: addFilter,
109
180
  filter: addFilter,
181
+ revisionData(literal) {
182
+ recordFilters(literal, spec.revisionFilters);
183
+ return this;
184
+ },
185
+ includeStale() {
186
+ spec.includeStale = true;
187
+ return this;
188
+ },
189
+ includeDeleted() {
190
+ spec.includeDeleted = true;
191
+ return this;
192
+ },
193
+ whereExists(model, options) {
194
+ spec.correlations.push({
195
+ model,
196
+ options: options,
197
+ });
198
+ return this;
199
+ },
110
200
  without(fields) {
111
201
  spec.without.push(...(Array.isArray(fields) ? fields : [fields]));
112
202
  return builder;
113
203
  },
114
- limit(count) {
204
+ limit(count, { strategy = 'window' } = {}) {
205
+ if (strategy !== 'window' && strategy !== 'lateral') {
206
+ throw new TypeError('Batch limit strategy must be window or lateral.');
207
+ }
115
208
  spec.limit = assertRowCount(count, 'LIMIT');
209
+ spec.limitStrategy = strategy;
116
210
  return builder;
117
211
  },
118
212
  orderBy(field, direction = 'ASC') {
@@ -158,7 +252,11 @@ class QueryBuilder {
158
252
  _groupBy;
159
253
  _joinSpecs;
160
254
  _simpleJoins;
255
+ _joinedTargets;
256
+ _aliases;
161
257
  _complexJoins;
258
+ _transaction;
259
+ _forUpdate = false;
162
260
  constructor(modelClass, dal) {
163
261
  this.modelClass = modelClass;
164
262
  this.dal = dal;
@@ -184,6 +282,24 @@ class QueryBuilder {
184
282
  this._includeSensitive = Array.isArray(fields) ? fields : [fields];
185
283
  return this;
186
284
  }
285
+ withTransaction(transaction) {
286
+ assertTransactionClient(transaction);
287
+ if (!transaction)
288
+ throw new TypeError('withTransaction() requires a transaction client.');
289
+ this._transaction = transaction;
290
+ return this;
291
+ }
292
+ forUpdate() {
293
+ this._forUpdate = true;
294
+ return this;
295
+ }
296
+ whereExists(model, options) {
297
+ this._where.push({
298
+ type: 'exists',
299
+ correlation: { model, options: options },
300
+ });
301
+ return this;
302
+ }
187
303
  /** Compile an independent, terminal projection without model hydration. */
188
304
  _project(fields) {
189
305
  if (!fields.length)
@@ -193,37 +309,164 @@ class QueryBuilder {
193
309
  this._groupBy.length) {
194
310
  throw new TypeError('select() cannot be combined with getJoin() or groupBy().');
195
311
  }
196
- const quote = (identifier) => `"${identifier.replaceAll('"', '""')}"`;
197
- const selected = [...new Set(fields)];
198
- const columns = selected.map(field => {
199
- const definition = Object.hasOwn(this.modelClass.schema, field)
200
- ? this.modelClass.schema[field]
201
- : undefined;
202
- if (!definition || definition.isVirtual) {
203
- throw new TypeError(`select() requires a persisted model field; received '${field}'.`);
312
+ const results = new SqlResultColumns();
313
+ const read = results.select(fields, field => `${this.tableName}.${this._readableColumn(field, 'select')}`);
314
+ const snapshot = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
315
+ return snapshot._compileProjection(results.sql, read);
316
+ }
317
+ _projectRelations(fields, relations) {
318
+ if (this._groupBy.length ||
319
+ Object.keys(this._complexJoins ?? {}).length ||
320
+ Object.values(this._simpleJoins ?? {}).some(join => join.cardinality !== 'one')) {
321
+ throw new TypeError('selectRelated() requires a root query with only to-one joins.');
322
+ }
323
+ const snapshot = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
324
+ snapshot._joins = [...this._joins];
325
+ snapshot._joinedTargets = { ...this._joinedTargets };
326
+ snapshot._aliases = this._aliasAllocator().copy();
327
+ snapshot._simpleJoins = Object.assign(Object.create(null), this._simpleJoins);
328
+ const rootFields = [...new Set(fields)];
329
+ const results = new SqlResultColumns();
330
+ const readRoot = results.select(rootFields, field => `${this.tableName}.${this._readableColumn(field, 'selectRelated')}`);
331
+ const requested = Object.entries(relations).flatMap(([name, selection]) => selection === undefined ? [] : [{ name, selection, join: snapshot._getJoinInfo(name) }]);
332
+ const readers = requested.map(({ name, selection, join }, index) => {
333
+ if (rootFields.includes(name))
334
+ throw new TypeError(`Projection field '${name}' clashes with a relation.`);
335
+ if (!join || join.cardinality !== 'one') {
336
+ throw new TypeError(`selectRelated() requires a declared to-one relation; received '${name}'.`);
204
337
  }
205
- if (definition.isSensitive && !this._includeSensitive.includes(field)) {
206
- throw new TypeError(`select('${field}') requires includeSensitive('${field}').`);
338
+ if (!selection.fields.length)
339
+ throw new TypeError(`Select at least one field on '${name}'.`);
340
+ const target = snapshot._getRelatedModel(name, join);
341
+ if (!target)
342
+ throw new Error(`Related model not found for relation '${name}'.`);
343
+ let joined = snapshot._joinedTargets?.[name];
344
+ if (!Object.hasOwn(snapshot._simpleJoins ?? {}, name)) {
345
+ joined = snapshot._inlineJoinConflict(join)
346
+ ? snapshot._addInlineJoin(join, { name, index })
347
+ : snapshot._addSimpleJoin(name);
207
348
  }
208
- const column = this._resolveFieldName(field);
209
- if (typeof column !== 'string')
210
- throw new TypeError('Invalid selected column.');
211
- return `${this.tableName.split('.').map(quote).join('.')}.${quote(column)} AS ${quote(field)}`;
349
+ const { reference, present } = joined;
350
+ const marker = results.add(`(${present})`);
351
+ const readFields = results.select(selection.fields, field => {
352
+ const definition = Object.hasOwn(target.schema, field) ? target.schema[field] : undefined;
353
+ if (!definition || definition.isVirtual) {
354
+ throw new TypeError(`selectRelated() requires a persisted field on '${name}'; received '${field}'.`);
355
+ }
356
+ if (definition.isSensitive && !selection.includeSensitive?.includes(field)) {
357
+ throw new TypeError(`Selecting '${name}.${field}' requires the relation's includeSensitive option.`);
358
+ }
359
+ return columnReference(target._getDbFieldName(field), 'configured-identifier', reference);
360
+ });
361
+ return {
362
+ name,
363
+ read: (row) => (row[marker] ? Object.freeze(readFields(row)) : null),
364
+ };
212
365
  });
213
- // Compile SQL now: later builder mutations, including nested predicate values,
214
- // cannot affect this query. The original SELECT list and limit stay intact.
215
- const snapshot = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
366
+ if (!results.sql.length)
367
+ throw new TypeError('selectRelated() requires at least one field.');
368
+ return snapshot._compileProjection(results.sql, row => Object.fromEntries([
369
+ ...Object.entries(readRoot(row)),
370
+ ...readers.map(({ name, read }) => [name, read(row)]),
371
+ ]));
372
+ }
373
+ _aliasAllocator() {
374
+ return (this._aliases ??= new SqlAliases([this.tableName]));
375
+ }
376
+ _reserveDeclaredJoinTables(aliases) {
377
+ const declared = this.modelClass
378
+ .getRelations()
379
+ .flatMap(({ name }) => this._getJoinInfo(name) ?? []);
380
+ for (const join of declared) {
381
+ aliases.reserve(join.table);
382
+ aliases.reserve(join.joinTable);
383
+ }
384
+ return declared;
385
+ }
386
+ _buildJoinedTarget(join, reference = join.table) {
387
+ const source = reference === join.table ? join.table : `${join.table} AS ${reference}`;
388
+ if (join.targetConditionKind === 'equality') {
389
+ return {
390
+ source,
391
+ reference,
392
+ present: `${columnReference(join.targetColumn, 'configured-sql', reference)} IS NOT NULL`,
393
+ };
394
+ }
395
+ // Reserve identifiers used by ON as well as modeled columns: custom SQL can
396
+ // reference database columns that are absent from the model schema.
397
+ const aliases = this._aliasAllocator();
398
+ const declared = this._reserveDeclaredJoinTables(aliases);
399
+ const conditions = [
400
+ join.condition,
401
+ ...declared.flatMap(info => [
402
+ info.condition,
403
+ ...(info.joinTableOn ? [info.joinTableOn] : []),
404
+ ]),
405
+ ];
406
+ const marker = aliases.allocate('__rev_dal_marker');
407
+ const columnNames = new SqlAliases([
408
+ ...this.modelClass.getColumnNames(this.modelClass.getSensitiveFieldNames()),
409
+ ...conditions.flatMap(condition => condition.match(/"(?:[^"]|"")*"|[a-zA-Z_][a-zA-Z_0-9$]*/g) ?? []),
410
+ ]);
411
+ const markerColumn = columnNames.allocate('__rev_dal_present');
412
+ return {
413
+ source: `${source} CROSS JOIN (SELECT TRUE AS ${markerColumn}) AS ${marker}`,
414
+ reference,
415
+ present: `${marker}.${markerColumn} IS TRUE`,
416
+ };
417
+ }
418
+ _addInlineJoin(join, alias) {
419
+ const aliases = this._aliasAllocator();
420
+ aliases.reserve(join.table);
421
+ aliases.reserve(join.joinTable);
422
+ let targetReference = join.table;
423
+ let junctionSource = join.joinTable;
424
+ let junctionCondition = join.joinTableOn;
425
+ let condition = join.condition;
426
+ if (alias) {
427
+ if (join.joinTable && join.junctionConditionKind !== 'equality') {
428
+ throw new Error(`Cannot alias relation '${alias.name}' with a custom junction condition.`);
429
+ }
430
+ if (join.targetConditionKind !== 'equality') {
431
+ throw new Error(`Cannot alias relation '${alias.name}' with a custom join condition.`);
432
+ }
433
+ this._reserveDeclaredJoinTables(aliases);
434
+ targetReference = aliases.allocate(`__rev_dal_relation_${alias.index}`);
435
+ const column = (reference, field) => columnReference(field, 'configured-sql', reference);
436
+ let source = column(this.tableName, join.sourceColumn);
437
+ if (join.joinTable && join.joinTableSourceColumn && join.joinTableTargetColumn) {
438
+ const junctionReference = aliases.allocate(`__rev_dal_junction_${alias.index}`);
439
+ junctionSource = `${join.joinTable} AS ${junctionReference}`;
440
+ junctionCondition = `${source} = ${column(junctionReference, join.joinTableSourceColumn)}`;
441
+ source = column(junctionReference, join.joinTableTargetColumn);
442
+ }
443
+ condition = `${source} = ${column(targetReference, join.targetColumn)}`;
444
+ }
445
+ const target = this._buildJoinedTarget(join, targetReference);
446
+ if (junctionSource && junctionCondition) {
447
+ this._joins.push(`LEFT JOIN ${junctionSource} ON ${junctionCondition}`);
448
+ }
449
+ if (join.hasRevisions) {
450
+ if (join.targetConditionKind === 'custom')
451
+ condition = `(${condition})`;
452
+ condition += ` AND ${target.reference}._old_rev_of IS NULL AND (${target.reference}._rev_deleted IS NULL OR ${target.reference}._rev_deleted = false)`;
453
+ }
454
+ this._joins.push(`LEFT JOIN ${target.source} ON ${condition}`);
455
+ return target;
456
+ }
457
+ _compileProjection(columns, read) {
458
+ // Compile now so later mutations of the originating builder cannot alter the projection.
459
+ const snapshot = this;
216
460
  snapshot._select = columns;
217
461
  const all = snapshot._buildSelectQuery();
218
462
  snapshot._limit = this._limit === 0 ? 0 : 1;
219
463
  const first = snapshot._buildSelectQuery();
220
464
  all.params = cloneRowValue(all.params);
221
465
  first.params = cloneRowValue(first.params);
222
- const dal = this.dal;
223
466
  const execute = async ({ sql, params }) => {
224
467
  try {
225
- const result = await dal.query(sql, cloneRowValue(params));
226
- return result.rows.map(row => Object.freeze(Object.fromEntries(selected.map(field => [field, row[field]]))));
468
+ const result = await snapshot._query(sql, cloneRowValue(params));
469
+ return result.rows.map(row => Object.freeze(read(row)));
227
470
  }
228
471
  catch (error) {
229
472
  throw convertPostgreSQLError(error);
@@ -236,6 +479,25 @@ class QueryBuilder {
236
479
  then: (onfulfilled, onrejected) => run().then(onfulfilled, onrejected),
237
480
  });
238
481
  }
482
+ _persistedField(field, operation) {
483
+ const definition = Object.hasOwn(this.modelClass.schema, field)
484
+ ? this.modelClass.schema[field]
485
+ : undefined;
486
+ if (!definition || definition.isVirtual) {
487
+ throw new TypeError(`${operation}() requires a persisted model field; received '${field}'.`);
488
+ }
489
+ const column = this._resolveFieldName(field);
490
+ if (typeof column !== 'string')
491
+ throw new TypeError('Invalid persisted column.');
492
+ return { definition, column };
493
+ }
494
+ _readableColumn(field, operation) {
495
+ const { definition, column } = this._persistedField(field, operation);
496
+ if (definition.isSensitive && !this._includeSensitive.includes(field)) {
497
+ throw new TypeError(`${operation}('${field}') requires includeSensitive('${field}').`);
498
+ }
499
+ return columnReference(column, 'configured-identifier');
500
+ }
239
501
  /**
240
502
  * Resolve a logical field reference to a database column.
241
503
  *
@@ -369,7 +631,7 @@ class QueryBuilder {
369
631
  this._where.push(this._createMatchNothingPredicate());
370
632
  return this;
371
633
  }
372
- const valueTransform = placeholder => `(${placeholder}${cast ? `::${cast}` : ''})`;
634
+ const valueTransform = placeholder => `(${renderParameterCast(placeholder, cast)})`;
373
635
  this._addWhereCondition(field, '= ANY', values, { valueTransform });
374
636
  return this;
375
637
  }
@@ -401,14 +663,15 @@ class QueryBuilder {
401
663
  orderBy(field, direction = 'ASC') {
402
664
  const normalizedDirection = normalizeSortDirection(direction);
403
665
  let expression = field;
404
- if (typeof field === 'string' && !field.includes('(')) {
405
- const { table, column } = this._splitFieldReference(field);
406
- const resolvedColumn = this._resolvePredicateColumn(table || null, column);
407
- if (table) {
408
- expression = `${table}.${resolvedColumn}`;
666
+ if (typeof field === 'string') {
667
+ if (isConfiguredIdentifier(field)) {
668
+ const column = this._resolveFieldName(field);
669
+ expression = columnReference(String(column), 'configured-sql', this._rootTableReference().sql);
409
670
  }
410
- else {
411
- expression = resolvedColumn;
671
+ else if (!field.includes('(')) {
672
+ const { table, column } = this._splitFieldReference(field);
673
+ const resolvedColumn = this._resolvePredicateColumn(table || null, column);
674
+ expression = table ? `${table}.${resolvedColumn}` : resolvedColumn;
412
675
  }
413
676
  }
414
677
  this._orderBy.push(`${expression} ${normalizedDirection}`);
@@ -524,7 +787,7 @@ class QueryBuilder {
524
787
  */
525
788
  _addSimpleJoin(relationName) {
526
789
  if (this._simpleJoins?.[relationName]) {
527
- return; // Already joined (e.g. by whereRelated)
790
+ return this._joinedTargets?.[relationName]; // Already joined (e.g. by whereRelated)
528
791
  }
529
792
  const joinInfo = this._getJoinInfo(relationName);
530
793
  if (!joinInfo) {
@@ -536,28 +799,14 @@ class QueryBuilder {
536
799
  throw new Error(`Cannot join relation '${relationName}' inline: ${conflict}. ` +
537
800
  'Load it with getJoin() instead, which falls back to a separate query.');
538
801
  }
539
- if (joinInfo.joinTable && joinInfo.joinTableOn) {
540
- this._joins.push(`LEFT JOIN ${joinInfo.joinTable} ON ${joinInfo.joinTableOn}`);
541
- let targetJoin = `LEFT JOIN ${joinInfo.table} ON ${joinInfo.condition}`;
542
- if (joinInfo.hasRevisions) {
543
- targetJoin += ` AND ${joinInfo.table}._old_rev_of IS NULL AND (${joinInfo.table}._rev_deleted IS NULL OR ${joinInfo.table}._rev_deleted = false)`;
544
- }
545
- this._joins.push(targetJoin);
546
- }
547
- else {
548
- // Direct join
549
- let joinClause = `LEFT JOIN ${joinInfo.table} ON ${joinInfo.condition}`;
550
- // Add revision filtering for joined table if it has revision fields
551
- if (joinInfo.hasRevisions) {
552
- joinClause += ` AND ${joinInfo.table}._old_rev_of IS NULL AND (${joinInfo.table}._rev_deleted IS NULL OR ${joinInfo.table}._rev_deleted = false)`;
553
- }
554
- this._joins.push(joinClause);
555
- }
802
+ const target = this._addInlineJoin(joinInfo);
803
+ (this._joinedTargets ??= {})[relationName] = target;
556
804
  // Mark this relation for result processing
557
805
  if (!this._simpleJoins) {
558
806
  this._simpleJoins = {};
559
807
  }
560
808
  this._simpleJoins[relationName] = joinInfo;
809
+ return target;
561
810
  }
562
811
  /**
563
812
  * Explain why a relation's tables can't be joined inline into this query,
@@ -566,18 +815,23 @@ class QueryBuilder {
566
815
  * @private
567
816
  */
568
817
  _inlineJoinConflict(joinInfo) {
569
- const joined = new Set([this.tableName]);
818
+ const joined = [this.tableName];
570
819
  for (const info of Object.values(this._simpleJoins ?? {})) {
571
- joined.add(info.table);
820
+ joined.push(info.table);
572
821
  if (info.joinTable)
573
- joined.add(info.joinTable);
822
+ joined.push(info.joinTable);
574
823
  }
575
824
  for (const table of [joinInfo.table, joinInfo.joinTable]) {
576
- if (!table || !joined.has(table))
825
+ if (!table)
577
826
  continue;
578
- return table === this.tableName
579
- ? `it refers back to '${table}', the table being queried`
580
- : `'${table}' is already joined by another relation`;
827
+ if (this._aliases?.isGenerated(table))
828
+ return `'${table}' conflicts with a generated join alias`;
829
+ if (joined.some(reference => tableReferencesConflict(reference, table))) {
830
+ return tableReferencesConflict(table, this.tableName)
831
+ ? `it refers back to '${table}', the table being queried`
832
+ : `'${table}' is already joined by another relation`;
833
+ }
834
+ joined.push(table);
581
835
  }
582
836
  return null;
583
837
  }
@@ -657,6 +911,13 @@ class QueryBuilder {
657
911
  joinTable: joinTableName,
658
912
  joinTableOn,
659
913
  condition: targetCondition,
914
+ targetConditionKind: targetCondition ===
915
+ `${joinTableName}.${throughTargetKey} = ${targetTableName}.${targetColumn}`
916
+ ? 'equality'
917
+ : 'custom',
918
+ junctionConditionKind: joinTableOn === `${this.tableName}.${sourceColumn} = ${joinTableName}.${throughSourceKey}`
919
+ ? 'equality'
920
+ : 'custom',
660
921
  sourceColumn,
661
922
  targetColumn,
662
923
  joinTableSourceColumn: throughSourceKey,
@@ -674,6 +935,9 @@ class QueryBuilder {
674
935
  baseTable: baseTargetTable,
675
936
  hasRevisions,
676
937
  condition: directCondition,
938
+ targetConditionKind: directCondition === `${this.tableName}.${sourceColumn} = ${targetTableName}.${targetColumn}`
939
+ ? 'equality'
940
+ : 'custom',
677
941
  sourceColumn,
678
942
  targetColumn,
679
943
  cardinality,
@@ -705,15 +969,34 @@ class QueryBuilder {
705
969
  * @returns {Promise<Array>} Query results
706
970
  */
707
971
  async run() {
972
+ return (await this._runRows()).rows;
973
+ }
974
+ _rootTableReference() {
975
+ return sqlTableReference(this.tableName);
976
+ }
977
+ async _query(sql, params, transaction = this._transaction) {
978
+ if (this._forUpdate)
979
+ await assertActiveTransaction(transaction ?? undefined);
980
+ return this.dal.query(sql, params, transaction);
981
+ }
982
+ async _runRows(extraColumns = {}) {
708
983
  try {
709
- // Handle complex joins that require separate queries
710
- if (this._complexJoins && Object.keys(this._complexJoins).length > 0) {
711
- return await this._runWithComplexJoins();
984
+ const { sql, params, inlineResults } = this._buildSelectQuery(extraColumns);
985
+ const result = await this._query(sql, params);
986
+ const aliases = Object.keys(extraColumns);
987
+ const metadata = aliases.length
988
+ ? result.rows.map(row => {
989
+ const extra = Object.fromEntries(aliases.map(alias => [alias, row[alias]]));
990
+ for (const alias of aliases)
991
+ delete row[alias];
992
+ return extra;
993
+ })
994
+ : [];
995
+ const rows = await this._processResults(result.rows, inlineResults);
996
+ for (const [name, spec] of Object.entries(this._complexJoins ?? {})) {
997
+ await this._processComplexJoin(rows, name, spec);
712
998
  }
713
- const { sql, params } = this._buildSelectQuery();
714
- const result = await this.dal.query(sql, params);
715
- // Process results with simple joins
716
- return await this._processResults(result.rows);
999
+ return { rows, metadata };
717
1000
  }
718
1001
  catch (error) {
719
1002
  throw convertPostgreSQLError(error);
@@ -750,15 +1033,60 @@ class QueryBuilder {
750
1033
  * @private
751
1034
  */
752
1035
  async _runWithComplexJoins() {
753
- // First get the main results
754
- const mainQuery = this._buildSelectQuery();
755
- const mainResult = await this.dal.query(mainQuery.sql, mainQuery.params);
756
- const mainRows = await this._processResults(mainResult.rows);
757
- // Process each complex join
758
- for (const [relationName, joinSpec] of Object.entries(this._complexJoins ?? {})) {
759
- await this._processComplexJoin(mainRows, relationName, joinSpec);
1036
+ return (await this._runRows()).rows;
1037
+ }
1038
+ async _runCompositeFeed(cursorField, tieBreaker, direction, limit, cursor) {
1039
+ if (cursorField === tieBreaker)
1040
+ throw new TypeError('The tie-breaker must be a different field.');
1041
+ if (this._offset !== null)
1042
+ throw new TypeError('Composite cursor pagination cannot use offset().');
1043
+ if (this._joins.length) {
1044
+ throw new TypeError('Composite cursor pagination cannot use inline joins; use whereExists() to filter roots and batch joins to load relations.');
760
1045
  }
761
- return mainRows;
1046
+ const snapshot = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
1047
+ snapshot._where = [...this._where];
1048
+ const table = this._rootTableReference();
1049
+ const timestamp = table.qualify(this._readableColumn(cursorField, 'chronologicalFeed'));
1050
+ const tie = table.qualify(this._readableColumn(tieBreaker, 'chronologicalFeed'));
1051
+ // Inspect the database type: a model's string/number declaration cannot
1052
+ // establish whether PostgreSQL's text output preserves the cursor boundary.
1053
+ const description = await this._query(`SELECT ${tie} FROM ${table.sql} LIMIT 0`);
1054
+ const typeId = description.fields[0]?.dataTypeID;
1055
+ // bool, int8, int2, int4, text, bpchar, varchar, numeric, uuid.
1056
+ const exactTextTypes = new Set([16, 20, 21, 23, 25, 1042, 1043, 1700, 2950]);
1057
+ if (!exactTextTypes.has(typeId)) {
1058
+ throw new TypeError('Composite tie-breaker has an unsupported database type; use text, UUID, integer, numeric, or boolean.');
1059
+ }
1060
+ snapshot._where.push({ type: 'raw', sql: `${timestamp} IS NOT NULL AND ${tie} IS NOT NULL` });
1061
+ if (cursor != null) {
1062
+ if (typeof cursor.timestamp !== 'string' || typeof cursor.tieBreaker !== 'string') {
1063
+ throw new TypeError('A composite cursor requires timestamp and tieBreaker strings.');
1064
+ }
1065
+ snapshot._where.push({
1066
+ type: 'tuple',
1067
+ columns: [timestamp, tie],
1068
+ operator: direction === 'ASC' ? '>' : '<',
1069
+ values: [cursor.timestamp, cursor.tieBreaker],
1070
+ });
1071
+ }
1072
+ snapshot._orderBy = [`${timestamp} ${direction}`, `${tie} ${direction}`];
1073
+ snapshot.limit(limit + 1);
1074
+ const results = new SqlResultColumns(this.modelClass.getColumnNames(this._includeSensitive));
1075
+ const timestampAlias = results.add(`to_json(${timestamp}) #>> '{}'`);
1076
+ const tieAlias = results.add(`${tie}::text`);
1077
+ const { rows, metadata } = await snapshot._runRows(results.expressions);
1078
+ const hasMore = rows.length > limit;
1079
+ const last = metadata[limit - 1];
1080
+ return {
1081
+ rows: hasMore ? rows.slice(0, limit) : rows,
1082
+ hasMore,
1083
+ nextCursor: hasMore
1084
+ ? {
1085
+ timestamp: String(last[timestampAlias]),
1086
+ tieBreaker: String(last[tieAlias]),
1087
+ }
1088
+ : undefined,
1089
+ };
762
1090
  }
763
1091
  /**
764
1092
  * Process a complex join by executing separate queries
@@ -781,14 +1109,16 @@ class QueryBuilder {
781
1109
  this._assignJoinResults(mainRows, relationName, joinInfo, new Map());
782
1110
  return;
783
1111
  }
784
- const spec = recordJoinApply(joinSpec._apply);
785
- const { query, params, joinSourceAlias, omitAfterQuery } = this._buildComplexJoinQuery(relationName, joinInfo, sourceValues, spec);
786
- const relatedResult = await this.dal.query(query, params);
787
- let relatedRows = (relatedResult.rows || []);
788
- if (omitAfterQuery.length) {
789
- relatedRows = this._applyJoinFieldOmissions(relatedRows, omitAfterQuery);
790
- }
791
- const groupedRows = this._groupRelatedRows(relatedRows, joinSourceAlias);
1112
+ const relatedModel = this._getRelatedModel(relationName, joinInfo);
1113
+ const spec = recordJoinApply(joinSpec._apply, relatedModel?.schema);
1114
+ // A wildcard fallback needs PostgreSQL's actual result names before metadata
1115
+ // aliases can be reserved. Registered models normally supply these names.
1116
+ const wildcardColumns = !relatedModel?.getSafeColumnNames().length
1117
+ ? (await this._query(`SELECT * FROM ${joinInfo.table} LIMIT 0`)).fields.map(field => quoteIdentifier(field.name))
1118
+ : [];
1119
+ const { query, params, joinSourceAlias, joinRankAlias, omitAfterQuery } = this._buildComplexJoinQuery(relationName, joinInfo, sourceValues, spec, wildcardColumns);
1120
+ const relatedResult = await this._query(query, params);
1121
+ const groupedRows = this._groupRelatedRows(relatedResult.rows, joinSourceAlias, joinRankAlias, omitAfterQuery);
792
1122
  this._assignJoinResults(mainRows, relationName, joinInfo, groupedRows);
793
1123
  }
794
1124
  _extractJoinSourceValues(mainRows, sourceColumn) {
@@ -817,15 +1147,113 @@ class QueryBuilder {
817
1147
  * @private
818
1148
  */
819
1149
  _resolveJoinColumn(relatedModel, relationName, field) {
820
- const mapped = relatedModel && typeof relatedModel._getDbFieldName === 'function'
821
- ? relatedModel._getDbFieldName(field)
822
- : field;
823
- const column = mapped !== field ? mapped : this._normalizeColumnName(field);
824
- if (typeof column !== 'string' || !SAFE_IDENTIFIER.test(column)) {
1150
+ const mapped = relatedModel?._getDbFieldName?.(field) ?? field;
1151
+ const schema = relatedModel?.schema;
1152
+ const persisted = schema && Object.hasOwn(schema, field) && !schema[field].isVirtual;
1153
+ const column = persisted || mapped !== field ? mapped : this._normalizeColumnName(field);
1154
+ if (typeof column !== 'string' || !isConfiguredIdentifier(column)) {
825
1155
  throw new Error(`Invalid field '${String(field)}' in _apply for relation '${relationName}'.`);
826
1156
  }
827
1157
  return column;
828
1158
  }
1159
+ _batchRevisionGuards(alias, revisioned, options) {
1160
+ if (!revisioned)
1161
+ return [];
1162
+ const guards = [];
1163
+ if (!options.includeStale)
1164
+ guards.push(`${alias}._old_rev_of IS NULL`);
1165
+ if (!options.includeDeleted)
1166
+ guards.push(`${alias}._rev_deleted IS NOT TRUE`);
1167
+ return guards;
1168
+ }
1169
+ _batchFilterSql(entries, alias, resolve, params, semantics, arrayColumns) {
1170
+ const getNextPlaceholder = () => `$${params.length + 1}`;
1171
+ return entries.flatMap(({ field, value }) => {
1172
+ if (value === undefined)
1173
+ return [];
1174
+ const column = resolve(field);
1175
+ const reference = columnReference(column, semantics === 'batch' ? 'configured-sql' : 'configured-identifier', alias);
1176
+ if (isOperatorToken(value)) {
1177
+ const predicate = value.build({
1178
+ builder: this,
1179
+ field: reference,
1180
+ mutate: false,
1181
+ });
1182
+ const sql = this._renderPredicate(predicate, {
1183
+ qualifyColumns: true,
1184
+ defaultTable: alias,
1185
+ getNextPlaceholder,
1186
+ params,
1187
+ });
1188
+ return sql ? [sql] : [];
1189
+ }
1190
+ if (semantics === 'batch' && column === '_rev_deleted' && value === false) {
1191
+ return [`${reference} IS NOT TRUE`];
1192
+ }
1193
+ if (value === null)
1194
+ return [`${reference} IS NULL`];
1195
+ const placeholder = getNextPlaceholder();
1196
+ params.push(value);
1197
+ return [
1198
+ semantics === 'batch' &&
1199
+ Array.isArray(value) &&
1200
+ !arrayColumns?.has(effectivePostgresIdentifier(column))
1201
+ ? `${reference} = ANY(${placeholder})`
1202
+ : `${reference} = ${placeholder}`,
1203
+ ];
1204
+ });
1205
+ }
1206
+ _correlationColumn(model, field) {
1207
+ if (!Object.hasOwn(model.schema, field) || model.schema[field].isVirtual) {
1208
+ throw new TypeError(`Correlation requires a persisted field on '${model.tableName}'; received '${field}'.`);
1209
+ }
1210
+ return model._getDbFieldName(field);
1211
+ }
1212
+ _correlationExpression(model, alias, field) {
1213
+ const column = (name) => columnReference(this._correlationColumn(model, name), 'configured-identifier', alias);
1214
+ if (typeof field === 'string')
1215
+ return column(field);
1216
+ if (!field || !Array.isArray(field.coalesce) || field.coalesce.length < 2) {
1217
+ throw new TypeError('Correlation coalesce requires at least two field names.');
1218
+ }
1219
+ return `COALESCE(${field.coalesce.map(column).join(', ')})`;
1220
+ }
1221
+ _existenceSql(correlation, outerModel, outerAlias, index, params) {
1222
+ const { model, options } = correlation;
1223
+ const innerModel = this._getModelRegistry()?.get(resolveModelLookupName(model));
1224
+ if (!outerModel || !innerModel)
1225
+ throw new TypeError('Correlated queries require registered models.');
1226
+ if (!Array.isArray(options.correlate) || options.correlate.length === 0) {
1227
+ throw new TypeError('Correlated queries require at least one field comparison.');
1228
+ }
1229
+ const innerAlias = new SqlAliases([outerAlias]).allocate(`_correlated_${index}`);
1230
+ const resolve = (field) => this._correlationColumn(innerModel, field);
1231
+ const clauses = options.correlate.map(([inner, operator, outer]) => {
1232
+ if (!correlationOperators.includes(operator))
1233
+ throw new TypeError('Invalid correlation operator.');
1234
+ return [
1235
+ this._correlationExpression(innerModel, innerAlias, inner),
1236
+ operator,
1237
+ this._correlationExpression(outerModel, outerAlias, outer),
1238
+ ].join(' ');
1239
+ });
1240
+ const revisioned = Object.hasOwn(innerModel.schema, '_revID');
1241
+ if (!revisioned && options.revisionData)
1242
+ throw new TypeError('revisionData() requires revision tracking.');
1243
+ if (revisioned) {
1244
+ if (!options.includeStale)
1245
+ clauses.push(`${innerAlias}._old_rev_of IS NULL`);
1246
+ if (!options.includeDeleted)
1247
+ clauses.push(`${innerAlias}._rev_deleted = false`);
1248
+ }
1249
+ const filters = [
1250
+ ...Object.entries(options.filterWhere ?? {}),
1251
+ ...Object.entries(options.revisionData ?? {}),
1252
+ ];
1253
+ clauses.push(...this._batchFilterSql(filters.map(([field, value]) => ({ field, value })), innerAlias, resolve, params, 'correlated'));
1254
+ const table = sqlTableReference(innerModel.tableName);
1255
+ return `${options.not ? 'NOT ' : ''}EXISTS (SELECT 1 FROM ${table.sql} ${innerAlias} WHERE ${clauses.join(' AND ')})`;
1256
+ }
829
1257
  /**
830
1258
  * Build the batch query that loads a relation for a set of parent rows.
831
1259
  *
@@ -834,15 +1262,14 @@ class QueryBuilder {
834
1262
  * a window function.
835
1263
  * @private
836
1264
  */
837
- _buildComplexJoinQuery(relationName, joinInfo, sourceValues, spec = null) {
1265
+ _buildComplexJoinQuery(relationName, joinInfo, sourceValues, spec = null, wildcardColumns = []) {
838
1266
  const params = [sourceValues];
839
1267
  const nextParam = (value) => {
840
1268
  params.push(value);
841
1269
  return `$${params.length}`;
842
1270
  };
843
- const targetAlias = `${relationName}_target`;
844
- const throughAlias = `${relationName}_through`;
845
- const joinSourceAlias = '_join_source_id';
1271
+ const targetAlias = '_join_target';
1272
+ const throughAlias = '_join_through';
846
1273
  const relatedModel = this._getRelatedModel(relationName, joinInfo);
847
1274
  const resolve = (field) => this._resolveJoinColumn(relatedModel, relationName, field);
848
1275
  // Columns: the related model's safe columns minus `without`; fall back to
@@ -856,12 +1283,13 @@ class QueryBuilder {
856
1283
  const omitted = new Set((spec?.without ?? []).map(resolve));
857
1284
  selectList = safeColumns
858
1285
  .filter(column => !omitted.has(column))
859
- .map(column => `${targetAlias}.${column}`);
1286
+ .map(column => columnReference(column, 'configured-sql', targetAlias));
860
1287
  }
861
1288
  else {
862
1289
  selectList = [`${targetAlias}.*`];
863
1290
  omitAfterQuery = spec?.without ?? [];
864
1291
  }
1292
+ const metadata = new SqlResultColumns([...safeColumns, ...wildcardColumns]);
865
1293
  const isThrough = joinInfo.type === 'through';
866
1294
  const sourceExpr = isThrough
867
1295
  ? `${throughAlias}.${joinInfo.joinTableSourceColumn}`
@@ -870,45 +1298,59 @@ class QueryBuilder {
870
1298
  if (isThrough) {
871
1299
  from += ` JOIN ${joinInfo.joinTable} ${throughAlias} ON ${throughAlias}.${joinInfo.joinTableTargetColumn} = ${targetAlias}.${joinInfo.targetColumn}`;
872
1300
  }
873
- const whereClauses = [`${sourceExpr} = ANY($1)`];
874
- if (joinInfo.hasRevisions) {
875
- whereClauses.push(`${targetAlias}._old_rev_of IS NULL`);
876
- whereClauses.push(`(${targetAlias}._rev_deleted IS NULL OR ${targetAlias}._rev_deleted = false)`);
877
- }
878
- for (const { field, value } of spec?.filters ?? []) {
879
- const column = `${targetAlias}.${resolve(field)}`;
880
- if (resolve(field) === '_rev_deleted' && value === false) {
881
- whereClauses.push(`(${column} IS NULL OR ${column} = false)`);
1301
+ const whereClauses = this._batchRevisionGuards(targetAlias, joinInfo.hasRevisions, spec ?? {});
1302
+ if (spec) {
1303
+ if (spec.revisionFilters.length && !joinInfo.hasRevisions) {
1304
+ throw new TypeError('revisionData() requires a revisioned relation.');
882
1305
  }
883
- else if (value === null) {
884
- whereClauses.push(`${column} IS NULL`);
1306
+ const filters = [...spec.filters, ...spec.revisionFilters];
1307
+ const arrayColumns = new Set();
1308
+ if (relatedModel && filters.some(({ value }) => Array.isArray(value))) {
1309
+ for (const [field, definition] of Object.entries(relatedModel.schema)) {
1310
+ if (definition instanceof ArrayType) {
1311
+ arrayColumns.add(effectivePostgresIdentifier(relatedModel._getDbFieldName(field)));
1312
+ }
1313
+ }
885
1314
  }
886
- else if (Array.isArray(value)) {
887
- whereClauses.push(`${column} = ANY(${nextParam(value)})`);
888
- }
889
- else {
890
- whereClauses.push(`${column} = ${nextParam(value)}`);
1315
+ whereClauses.push(...this._batchFilterSql(filters, targetAlias, resolve, params, 'batch', arrayColumns));
1316
+ for (const [index, correlation] of spec.correlations.entries()) {
1317
+ whereClauses.push(this._existenceSql(correlation, relatedModel, targetAlias, index, params));
891
1318
  }
892
1319
  }
893
1320
  const orderSql = (spec?.order ?? [])
894
1321
  .map(({ field, direction }) => `${targetAlias}.${resolve(field)} ${direction}`)
895
1322
  .join(', ');
896
- const columns = [...selectList, `${sourceExpr} AS ${joinSourceAlias}`];
897
- const where = ` WHERE ${whereClauses.join(' AND ')}`;
1323
+ const joinSourceAlias = metadata.add(sourceExpr);
1324
+ let joinRankAlias;
1325
+ const columns = [...selectList, ...metadata.sql];
1326
+ const order = orderSql ? ` ORDER BY ${orderSql}` : '';
1327
+ const where = (sourceFilter) => ` WHERE ${[sourceFilter, ...whereClauses].join(' AND ')}`;
898
1328
  let query;
899
- if (spec?.limit !== null && spec?.limit !== undefined) {
900
- // Limit per parent: rank each parent's related rows, keep the first n
901
- const rank = `ROW_NUMBER() OVER (PARTITION BY ${sourceExpr}${orderSql ? ` ORDER BY ${orderSql}` : ''}) AS ${JOIN_RANK_ALIAS}`;
1329
+ if (spec?.limit != null && spec.limitStrategy === 'lateral') {
1330
+ // The empty array supplies the source column's PostgreSQL type without reading any rows.
1331
+ const sources = `unnest(COALESCE($1, ARRAY(SELECT ${sourceExpr} ${from} WHERE FALSE)))`;
1332
+ joinRankAlias = metadata.add(`ROW_NUMBER() OVER (${order.trimStart()})`);
1333
+ const rank = `${metadata.expressions[joinRankAlias]} AS ${quoteIdentifier(joinRankAlias)}`;
1334
+ query =
1335
+ `SELECT _batch.* FROM ${sources} WITH ORDINALITY AS _parents(source, ordinal) ` +
1336
+ `CROSS JOIN LATERAL (SELECT ${[...columns, rank].join(', ')} ${from}` +
1337
+ `${where(`${sourceExpr} = _parents.source`)}${order} LIMIT ${nextParam(spec.limit)}) AS _batch ` +
1338
+ `ORDER BY _parents.ordinal, _batch.${joinRankAlias}`;
1339
+ }
1340
+ else if (spec?.limit != null) {
1341
+ joinRankAlias = metadata.add(`ROW_NUMBER() OVER (PARTITION BY ${sourceExpr}${order})`);
1342
+ const rank = `${metadata.expressions[joinRankAlias]} AS ${quoteIdentifier(joinRankAlias)}`;
902
1343
  query =
903
- `SELECT * FROM (SELECT ${[...columns, rank].join(', ')} ${from}${where}) AS _join_ranked ` +
904
- `WHERE ${JOIN_RANK_ALIAS} <= ${nextParam(spec.limit)} ORDER BY ${JOIN_RANK_ALIAS}`;
1344
+ `SELECT * FROM (SELECT ${[...columns, rank].join(', ')} ${from}` +
1345
+ `${where(`${sourceExpr} = ANY($1)`)}) AS _join_ranked ` +
1346
+ `WHERE ${joinRankAlias} <= ${nextParam(spec.limit)} ORDER BY ${joinRankAlias}`;
905
1347
  }
906
1348
  else {
907
- query = `SELECT ${columns.join(', ')} ${from}${where}${orderSql ? ` ORDER BY ${orderSql}` : ''}`;
1349
+ query = `SELECT ${columns.join(', ')} ${from}${where(`${sourceExpr} = ANY($1)`)}${order}`;
908
1350
  }
909
- return { query, params, joinSourceAlias, omitAfterQuery };
1351
+ return { query, params, joinSourceAlias, joinRankAlias, omitAfterQuery };
910
1352
  }
911
- _groupRelatedRows(rows, joinSourceAlias = '_join_source_id') {
1353
+ _groupRelatedRows(rows, joinSourceAlias, joinRankAlias, omitFields = []) {
912
1354
  const grouped = new Map();
913
1355
  if (!Array.isArray(rows)) {
914
1356
  return grouped;
@@ -925,7 +1367,12 @@ class QueryBuilder {
925
1367
  }
926
1368
  const cloned = { ...row };
927
1369
  delete cloned[joinSourceAlias];
928
- delete cloned[JOIN_RANK_ALIAS];
1370
+ if (joinRankAlias)
1371
+ delete cloned[joinRankAlias];
1372
+ for (const field of omitFields) {
1373
+ if (field)
1374
+ delete cloned[field];
1375
+ }
929
1376
  const existing = grouped.get(key) || [];
930
1377
  existing.push(cloned);
931
1378
  grouped.set(key, existing);
@@ -967,23 +1414,6 @@ class QueryBuilder {
967
1414
  }
968
1415
  return row[column];
969
1416
  }
970
- _applyJoinFieldOmissions(rows, fields) {
971
- if (!Array.isArray(rows) || !Array.isArray(fields) || fields.length === 0) {
972
- return rows;
973
- }
974
- return rows.map(row => {
975
- if (!row || typeof row !== 'object') {
976
- return row;
977
- }
978
- const cloned = { ...row };
979
- for (const field of fields) {
980
- if (!field)
981
- continue;
982
- delete cloned[field];
983
- }
984
- return cloned;
985
- });
986
- }
987
1417
  _normalizeColumnName(field) {
988
1418
  if (!field) {
989
1419
  return field;
@@ -1042,53 +1472,22 @@ class QueryBuilder {
1042
1472
  * @returns {Promise<Array>} Processed model instances
1043
1473
  * @private
1044
1474
  */
1045
- async _processResults(rows) {
1475
+ async _processResults(rows, inlineResults) {
1046
1476
  const BaseModel = this.modelClass;
1047
- if (!this._simpleJoins || Object.keys(this._simpleJoins).length === 0) {
1048
- // No joins, just create model instances
1049
- return rows.map(row => this._instantiateRelated(BaseModel, row));
1050
- }
1051
- // Process rows with joined data
1052
- const processedRows = [];
1053
- for (const row of rows) {
1054
- const mainData = {};
1055
- const joinedData = {};
1056
- // Separate main data from joined data: only joined columns carry the
1057
- // separator in their alias ("relation.column")
1058
- for (const [key, value] of Object.entries(row)) {
1059
- const separatorIndex = key.indexOf(JOIN_ALIAS_SEPARATOR);
1060
- const relationName = separatorIndex > 0 ? key.slice(0, separatorIndex) : null;
1061
- if (relationName && Object.hasOwn(this._simpleJoins, relationName)) {
1062
- if (!joinedData[relationName]) {
1063
- joinedData[relationName] = {};
1064
- }
1065
- joinedData[relationName][key.slice(separatorIndex + 1)] = value;
1066
- }
1067
- else {
1068
- mainData[key] = value;
1069
- }
1070
- }
1071
- // Create main model instance
1072
- const instance = this._instantiateRelated(BaseModel, mainData);
1073
- // Attach joined data
1074
- for (const [relationName, data] of Object.entries(joinedData)) {
1075
- // When a LEFT JOIN finds no matching row, all joined columns are NULL
1076
- // Only create a model instance if at least one field has a non-null value
1077
- const hasMatchingRow = data && typeof data === 'object' && Object.keys(data).some(key => data[key] !== null);
1078
- if (hasMatchingRow) {
1079
- // Create model instance for joined data
1080
- const joinInfo = this._simpleJoins ? this._simpleJoins[relationName] : null;
1081
- const RelatedModel = this._getRelatedModel(relationName, joinInfo);
1082
- instance[relationName] = this._instantiateRelated(RelatedModel, data);
1083
- }
1084
- else {
1085
- // No matching row found in join
1086
- instance[relationName] = null;
1087
- }
1477
+ return rows.map(row => {
1478
+ const main = { ...row };
1479
+ for (const alias of Object.keys(inlineResults?.columns.expressions ?? {}))
1480
+ delete main[alias];
1481
+ const instance = this._instantiateRelated(BaseModel, main);
1482
+ for (const relation of inlineResults?.relations ?? []) {
1483
+ const model = this._getRelatedModel(relation.name, this._simpleJoins?.[relation.name]);
1484
+ instance[relation.name] =
1485
+ row[relation.present] === true
1486
+ ? this._instantiateRelated(model, relation.read(row))
1487
+ : null;
1088
1488
  }
1089
- processedRows.push(instance);
1090
- }
1091
- return processedRows;
1489
+ return instance;
1490
+ });
1092
1491
  }
1093
1492
  /**
1094
1493
  * Execute query and return first result
@@ -1104,9 +1503,11 @@ class QueryBuilder {
1104
1503
  * @returns {Promise<number>} Result count
1105
1504
  */
1106
1505
  async count() {
1506
+ if (this._forUpdate)
1507
+ throw new TypeError('forUpdate() requires a row query.');
1107
1508
  try {
1108
1509
  const { sql, params } = this._buildCountQuery();
1109
- const result = await this.dal.query(sql, params);
1510
+ const result = await this._query(sql, params);
1110
1511
  const [row] = result.rows;
1111
1512
  return Number.parseInt(String(row?.count ?? '0'), 10);
1112
1513
  }
@@ -1131,12 +1532,14 @@ class QueryBuilder {
1131
1532
  * @returns Numeric aggregate result or `null` when no rows match.
1132
1533
  */
1133
1534
  async _aggregateFunction(func, field) {
1535
+ if (this._forUpdate)
1536
+ throw new TypeError('forUpdate() requires a row query.');
1134
1537
  try {
1135
1538
  const column = typeof field === 'string' && (field.includes('.') || field.includes('('))
1136
1539
  ? field
1137
1540
  : `${this.tableName}.${field}`;
1138
1541
  const { sql, params } = this._buildAggregateQuery(func, column);
1139
- const result = await this.dal.query(sql, params);
1542
+ const result = await this._query(sql, params);
1140
1543
  const value = result.rows[0]?.value;
1141
1544
  if (value === null || value === undefined) {
1142
1545
  return null;
@@ -1166,10 +1569,15 @@ class QueryBuilder {
1166
1569
  * // Returns: Map { 'thing-id-1' => 5, 'thing-id-2' => 3, ... }
1167
1570
  */
1168
1571
  async aggregateGrouped(func, options = {}) {
1572
+ if (this._forUpdate)
1573
+ throw new TypeError('forUpdate() requires a row query.');
1169
1574
  try {
1170
1575
  if (this._groupBy.length === 0) {
1171
1576
  throw new Error('aggregateGrouped requires groupBy() to be called first');
1172
1577
  }
1578
+ if (this._groupBy.length > 1) {
1579
+ throw new Error('aggregateGrouped requires exactly one grouping column');
1580
+ }
1173
1581
  let aggregateColumn = '*';
1174
1582
  if (options.aggregateField) {
1175
1583
  if (options.aggregateField.includes('.') || options.aggregateField.includes('(')) {
@@ -1185,7 +1593,7 @@ class QueryBuilder {
1185
1593
  }
1186
1594
  const aggregateExpr = func === 'COUNT' ? `COUNT(${aggregateColumn})` : `${func}(${aggregateColumn})`;
1187
1595
  const { sql, params } = this._buildGroupedAggregateQuery(aggregateExpr);
1188
- const result = await this.dal.query(sql, params);
1596
+ const result = await this._query(sql, params);
1189
1597
  const resultMap = new Map();
1190
1598
  for (const row of result.rows) {
1191
1599
  const key = String(row.group_key);
@@ -1213,9 +1621,11 @@ class QueryBuilder {
1213
1621
  * @returns Number of rows deleted
1214
1622
  */
1215
1623
  async delete(options = {}) {
1624
+ const transaction = options.transaction ?? this._transaction;
1625
+ assertTransactionClient(transaction);
1216
1626
  const { sql, params } = this._buildDeleteQuery(options);
1217
1627
  try {
1218
- const result = await this.dal.query(sql, params);
1628
+ const result = await this._query(sql, params, transaction);
1219
1629
  return typeof result.rowCount === 'number' ? result.rowCount : 0;
1220
1630
  }
1221
1631
  catch (error) {
@@ -1233,6 +1643,8 @@ class QueryBuilder {
1233
1643
  * @returns Number of rows deleted
1234
1644
  */
1235
1645
  async deleteById(id, options = {}) {
1646
+ const transaction = options.transaction ?? this._transaction;
1647
+ assertTransactionClient(transaction);
1236
1648
  const hasRevisions = this._hasRevisionFields();
1237
1649
  if (hasRevisions) {
1238
1650
  this._assertPurgeAllowed(options, 'deleteById');
@@ -1241,7 +1653,7 @@ class QueryBuilder {
1241
1653
  ? `DELETE FROM ${this.tableName} WHERE id = $1 OR _old_rev_of = $1`
1242
1654
  : `DELETE FROM ${this.tableName} WHERE id = $1`;
1243
1655
  try {
1244
- const result = await this.dal.query(query, [id]);
1656
+ const result = await this._query(query, [id], transaction);
1245
1657
  return typeof result.rowCount === 'number' ? result.rowCount : 0;
1246
1658
  }
1247
1659
  catch (error) {
@@ -1351,7 +1763,7 @@ class QueryBuilder {
1351
1763
  predicate.valueTransform = options.valueTransform;
1352
1764
  }
1353
1765
  else if (options.cast) {
1354
- predicate.valueTransform = placeholder => `${placeholder}::${options.cast}`;
1766
+ predicate.valueTransform = placeholder => renderParameterCast(placeholder, options.cast);
1355
1767
  }
1356
1768
  else {
1357
1769
  predicate.valueTransform = placeholder => placeholder;
@@ -1402,11 +1814,10 @@ class QueryBuilder {
1402
1814
  return { sql: '', params: [] };
1403
1815
  }
1404
1816
  const params = [];
1405
- let nextIndex = 1;
1406
1817
  const context = {
1407
1818
  qualifyColumns,
1408
1819
  defaultTable: this.tableName,
1409
- getNextPlaceholder: () => `$${nextIndex++}`,
1820
+ getNextPlaceholder: () => `$${params.length + 1}`,
1410
1821
  params,
1411
1822
  };
1412
1823
  const fragments = [];
@@ -1417,7 +1828,7 @@ class QueryBuilder {
1417
1828
  }
1418
1829
  }
1419
1830
  this._params = params;
1420
- this._paramIndex = nextIndex;
1831
+ this._paramIndex = params.length + 1;
1421
1832
  return {
1422
1833
  sql: fragments.join(' AND '),
1423
1834
  params,
@@ -1441,6 +1852,19 @@ class QueryBuilder {
1441
1852
  }
1442
1853
  return `(${inner.join(` ${conjunction} `)})`;
1443
1854
  }
1855
+ if (predicate.type === 'tuple') {
1856
+ const placeholders = predicate.values.map(value => {
1857
+ const placeholder = context.getNextPlaceholder();
1858
+ context.params.push(value);
1859
+ return placeholder;
1860
+ });
1861
+ return `(${predicate.columns.join(', ')}) ${predicate.operator} (${placeholders.join(', ')})`;
1862
+ }
1863
+ if (predicate.type === 'exists') {
1864
+ const outerModel = this._getModelRegistry()?.get(this.tableName) ?? null;
1865
+ const outer = this._rootTableReference().sql;
1866
+ return this._existenceSql(predicate.correlation, outerModel, outer, 0, context.params);
1867
+ }
1444
1868
  if (predicate.type === 'raw' && predicate.sql) {
1445
1869
  // Raw predicates may contribute their own parameters
1446
1870
  if (Array.isArray(predicate.values)) {
@@ -1477,7 +1901,7 @@ class QueryBuilder {
1477
1901
  return column;
1478
1902
  }
1479
1903
  if (predicate.table) {
1480
- return `${predicate.table}.${column}`;
1904
+ return columnReference(column, 'configured-sql', predicate.table);
1481
1905
  }
1482
1906
  if (!context.qualifyColumns) {
1483
1907
  return column;
@@ -1485,7 +1909,7 @@ class QueryBuilder {
1485
1909
  if (column.includes('.') || column.includes('(')) {
1486
1910
  return column;
1487
1911
  }
1488
- return `${context.defaultTable}.${column}`;
1912
+ return columnReference(column, 'configured-sql', context.defaultTable);
1489
1913
  }
1490
1914
  _isRevisionFilterPredicate(predicate) {
1491
1915
  if (!predicate) {
@@ -1501,36 +1925,36 @@ class QueryBuilder {
1501
1925
  * @returns {{ sql: string, params: Array }} SQL query and parameters
1502
1926
  * @private
1503
1927
  */
1504
- _buildSelectQuery() {
1928
+ _buildSelectQuery(extraColumns = {}) {
1929
+ const rootTable = this._rootTableReference();
1505
1930
  let selectClause = this._select.join(', ');
1931
+ let inlineResults;
1506
1932
  // Replace SELECT * with explicit column list to exclude sensitive fields
1507
1933
  // (e.g., passwords). For models without sensitive fields, getColumnNames()
1508
1934
  // returns all columns, equivalent to SELECT *.
1509
1935
  if (this._select.includes('*')) {
1510
1936
  const columns = this.modelClass.getColumnNames(this._includeSensitive);
1511
- const mainTableColumns = columns.map(col => `${this.tableName}.${col}`);
1937
+ const mainTableColumns = columns.map(col => columnReference(col, 'configured-sql', rootTable.sql));
1512
1938
  if (this._joins.length > 0) {
1513
1939
  selectClause = mainTableColumns.join(', ');
1514
1940
  // Add columns from simple joins with prefixed aliases
1515
1941
  if (this._simpleJoins) {
1516
- const joinSelects = [];
1517
- for (const [relationName, joinInfo] of Object.entries(this._simpleJoins)) {
1518
- if (joinInfo && joinInfo.table) {
1519
- // Get the related model to get safe (non-sensitive) column names
1520
- const RelatedModel = this._getRelatedModel(relationName, joinInfo);
1521
- if (!RelatedModel) {
1522
- throw new Error(`Related model not found for relation '${relationName}'.`);
1523
- }
1524
- const safeColumns = RelatedModel.getSafeColumnNames();
1525
- // Select each safe column with a prefixed alias (e.g., creator_id, creator_display_name)
1526
- for (const col of safeColumns) {
1527
- joinSelects.push(`${joinInfo.table}.${col} AS "${relationName}${JOIN_ALIAS_SEPARATOR}${col}"`);
1528
- }
1529
- }
1530
- }
1531
- if (joinSelects.length > 0) {
1532
- selectClause += ', ' + joinSelects.join(', ');
1942
+ const results = new SqlResultColumns([...columns, ...Object.keys(extraColumns)]);
1943
+ inlineResults = { columns: results, relations: [] };
1944
+ for (const [name, join] of Object.entries(this._simpleJoins)) {
1945
+ const model = this._getRelatedModel(name, join);
1946
+ if (!model)
1947
+ throw new Error(`Related model not found for relation '${name}'.`);
1948
+ const safe = model.getSafeColumnNames();
1949
+ // Model constructors consume configured storage keys; PostgreSQL
1950
+ // result-name folding applies only to SQL references, not these keys.
1951
+ const target = this._joinedTargets[name];
1952
+ const read = results.select(safe, column => columnReference(column, 'configured-sql', target.reference));
1953
+ const present = results.add(target.present);
1954
+ inlineResults.relations.push({ name, read, present });
1533
1955
  }
1956
+ if (results.sql.length)
1957
+ selectClause += ', ' + results.sql.join(', ');
1534
1958
  }
1535
1959
  }
1536
1960
  else {
@@ -1538,7 +1962,8 @@ class QueryBuilder {
1538
1962
  selectClause = mainTableColumns.join(', ');
1539
1963
  }
1540
1964
  }
1541
- let query = `SELECT ${selectClause} FROM ${this.tableName}`;
1965
+ const extras = Object.entries(extraColumns).map(([alias, expression]) => `${expression} AS ${quoteIdentifier(alias)}`);
1966
+ let query = `SELECT ${[selectClause, ...extras].join(', ')} FROM ${rootTable.sql}`;
1542
1967
  if (this._joins.length > 0) {
1543
1968
  query += ' ' + this._joins.join(' ');
1544
1969
  }
@@ -1547,13 +1972,7 @@ class QueryBuilder {
1547
1972
  query += ' WHERE ' + where.sql;
1548
1973
  }
1549
1974
  if (this._orderBy.length > 0) {
1550
- const qualifiedOrderBy = this._orderBy.map(orderClause => {
1551
- if (orderClause.includes('.') || orderClause.includes('(')) {
1552
- return orderClause;
1553
- }
1554
- return orderClause.replace(/^(\w+)/, `${this.tableName}.$1`);
1555
- });
1556
- query += ' ORDER BY ' + qualifiedOrderBy.join(', ');
1975
+ query += ' ORDER BY ' + this._orderBy.join(', ');
1557
1976
  }
1558
1977
  // LIMIT/OFFSET are bound as parameters rather than interpolated.
1559
1978
  const params = [...where.params];
@@ -1565,7 +1984,13 @@ class QueryBuilder {
1565
1984
  params.push(this._offset);
1566
1985
  query += ` OFFSET $${params.length}`;
1567
1986
  }
1568
- return { sql: query, params };
1987
+ if (this._forUpdate) {
1988
+ if (!this._transaction)
1989
+ throw new TypeError('forUpdate() requires a transaction client.');
1990
+ const relation = quoteIdentifier(effectivePostgresIdentifier(this.tableName));
1991
+ query += ` FOR UPDATE OF ${relation}`;
1992
+ }
1993
+ return { sql: query, params, inlineResults };
1569
1994
  }
1570
1995
  /**
1571
1996
  * Build COUNT query
@@ -1640,6 +2065,54 @@ class QueryBuilder {
1640
2065
  }
1641
2066
  return { sql: `DELETE FROM ${this.tableName} WHERE ${where.sql}`, params: where.params };
1642
2067
  }
2068
+ async updateMatching(data, options = {}) {
2069
+ if (this._hasRevisionFields()) {
2070
+ throw new Error('Filtered updates are not supported for revisioned models.');
2071
+ }
2072
+ if (this._joins.length ||
2073
+ Object.keys(this._complexJoins ?? {}).length ||
2074
+ this._orderBy.length ||
2075
+ this._groupBy.length ||
2076
+ this._limit !== null ||
2077
+ this._offset !== null ||
2078
+ this._forUpdate) {
2079
+ throw new Error('Filtered updates require an unpaginated root query without joins or locks.');
2080
+ }
2081
+ const where = this._buildWhereClause();
2082
+ if (!where.sql)
2083
+ throw new Error('Filtered updates require an explicit WHERE predicate.');
2084
+ const entries = Object.entries(data);
2085
+ if (!entries.length)
2086
+ throw new TypeError('Filtered updates require at least one assignment.');
2087
+ const transaction = options.transaction ?? this._transaction;
2088
+ assertTransactionClient(transaction);
2089
+ const params = [...where.params];
2090
+ const assignments = entries.map(([field, value]) => {
2091
+ const { definition, column } = this._persistedField(field, 'update');
2092
+ if (definition.isSensitive && !options.updateSensitive?.includes(field)) {
2093
+ throw new TypeError(`Updating sensitive field '${field}' requires updateSensitive.`);
2094
+ }
2095
+ if (value === undefined)
2096
+ throw new TypeError(`Assignment for '${field}' must be defined.`);
2097
+ params.push(definition.validate(value, field));
2098
+ return `${columnReference(column, 'configured-identifier')} = $${params.length}`;
2099
+ });
2100
+ const results = new SqlResultColumns();
2101
+ const read = results.select(options.returning ?? [], field => this._readableColumn(field, 'returning'));
2102
+ const returning = results.sql;
2103
+ const sql = `UPDATE ${this.tableName} SET ${assignments.join(', ')} WHERE ${where.sql}` +
2104
+ (returning.length ? ` RETURNING ${returning.join(', ')}` : '');
2105
+ try {
2106
+ const result = await this._query(sql, params, transaction);
2107
+ return {
2108
+ rowCount: result.rowCount ?? 0,
2109
+ rows: result.rows.map(row => Object.freeze(read(row))),
2110
+ };
2111
+ }
2112
+ catch (error) {
2113
+ throw convertPostgreSQLError(error);
2114
+ }
2115
+ }
1643
2116
  /**
1644
2117
  * Atomically increment a numeric column on rows matching the current predicate.
1645
2118
  *
@@ -1693,7 +2166,8 @@ class QueryBuilder {
1693
2166
  const params = [...where.params];
1694
2167
  const amountPlaceholder = `$${params.length + 1}`;
1695
2168
  params.push(amount);
1696
- let query = `UPDATE ${this.tableName} SET ${dbField} = ${dbField} + ${amountPlaceholder} WHERE ${where.sql}`;
2169
+ const counter = columnReference(dbField, 'configured-sql');
2170
+ let query = `UPDATE ${this.tableName} SET ${counter} = ${counter} + ${amountPlaceholder} WHERE ${where.sql}`;
1697
2171
  const returningColumns = Array.isArray(options.returning) ? options.returning : [];
1698
2172
  if (returningColumns.length > 0) {
1699
2173
  const resolvedColumns = returningColumns.map(column => {
@@ -1706,7 +2180,7 @@ class QueryBuilder {
1706
2180
  });
1707
2181
  query += ` RETURNING ${resolvedColumns.join(', ')}`;
1708
2182
  }
1709
- const result = await this.dal.query(query, params);
2183
+ const result = await this._query(query, params);
1710
2184
  const rows = returningColumns.length > 0
1711
2185
  ? result.rows.map(row => remapRowToCamelCase(row, fieldMappings))
1712
2186
  : [];