rev-dal 0.0.0-stage → 0.2.1
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/AGENTS.md +234 -0
- package/CONTRIBUTING.md +83 -0
- package/LICENSE +121 -0
- package/README.md +67 -2
- package/dist/index.d.ts +48 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +26 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/clone.d.ts +24 -0
- package/dist/lib/clone.d.ts.map +1 -0
- package/dist/lib/clone.js +83 -0
- package/dist/lib/clone.js.map +1 -0
- package/dist/lib/create-model.d.ts +207 -0
- package/dist/lib/create-model.d.ts.map +1 -0
- package/dist/lib/create-model.js +230 -0
- package/dist/lib/create-model.js.map +1 -0
- package/dist/lib/data-access-layer.d.ts +140 -0
- package/dist/lib/data-access-layer.d.ts.map +1 -0
- package/dist/lib/data-access-layer.js +389 -0
- package/dist/lib/data-access-layer.js.map +1 -0
- package/dist/lib/errors.d.ts +139 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +206 -0
- package/dist/lib/errors.js.map +1 -0
- package/dist/lib/filter-where.d.ts +199 -0
- package/dist/lib/filter-where.d.ts.map +1 -0
- package/dist/lib/filter-where.js +563 -0
- package/dist/lib/filter-where.js.map +1 -0
- package/dist/lib/ml-string.d.ts +63 -0
- package/dist/lib/ml-string.d.ts.map +1 -0
- package/dist/lib/ml-string.js +331 -0
- package/dist/lib/ml-string.js.map +1 -0
- package/dist/lib/model-factory.d.ts +25 -0
- package/dist/lib/model-factory.d.ts.map +1 -0
- package/dist/lib/model-factory.js +57 -0
- package/dist/lib/model-factory.js.map +1 -0
- package/dist/lib/model-handle.d.ts +67 -0
- package/dist/lib/model-handle.d.ts.map +1 -0
- package/dist/lib/model-handle.js +182 -0
- package/dist/lib/model-handle.js.map +1 -0
- package/dist/lib/model-initializer.d.ts +96 -0
- package/dist/lib/model-initializer.d.ts.map +1 -0
- package/dist/lib/model-initializer.js +182 -0
- package/dist/lib/model-initializer.js.map +1 -0
- package/dist/lib/model-manifest.d.ts +112 -0
- package/dist/lib/model-manifest.d.ts.map +1 -0
- package/dist/lib/model-manifest.js +2 -0
- package/dist/lib/model-manifest.js.map +1 -0
- package/dist/lib/model-registry.d.ts +81 -0
- package/dist/lib/model-registry.d.ts.map +1 -0
- package/dist/lib/model-registry.js +139 -0
- package/dist/lib/model-registry.js.map +1 -0
- package/dist/lib/model-types.d.ts +380 -0
- package/dist/lib/model-types.d.ts.map +1 -0
- package/dist/lib/model-types.js +2 -0
- package/dist/lib/model-types.js.map +1 -0
- package/dist/lib/model.d.ts +503 -0
- package/dist/lib/model.d.ts.map +1 -0
- package/dist/lib/model.js +1423 -0
- package/dist/lib/model.js.map +1 -0
- package/dist/lib/postgres-config.d.ts +3 -0
- package/dist/lib/postgres-config.d.ts.map +1 -0
- package/dist/lib/postgres-config.js +2 -0
- package/dist/lib/postgres-config.js.map +1 -0
- package/dist/lib/query-builder.d.ts +607 -0
- package/dist/lib/query-builder.d.ts.map +1 -0
- package/dist/lib/query-builder.js +1734 -0
- package/dist/lib/query-builder.js.map +1 -0
- package/dist/lib/revision.d.ts +55 -0
- package/dist/lib/revision.d.ts.map +1 -0
- package/dist/lib/revision.js +307 -0
- package/dist/lib/revision.js.map +1 -0
- package/dist/lib/runtime.d.ts +18 -0
- package/dist/lib/runtime.d.ts.map +1 -0
- package/dist/lib/runtime.js +134 -0
- package/dist/lib/runtime.js.map +1 -0
- package/dist/lib/transaction.d.ts +17 -0
- package/dist/lib/transaction.d.ts.map +1 -0
- package/dist/lib/transaction.js +30 -0
- package/dist/lib/transaction.js.map +1 -0
- package/dist/lib/type.d.ts +130 -0
- package/dist/lib/type.d.ts.map +1 -0
- package/dist/lib/type.js +376 -0
- package/dist/lib/type.js.map +1 -0
- package/docs/models.md +406 -0
- package/docs/multilingual-text.md +142 -0
- package/docs/queries.md +374 -0
- package/docs/revisions.md +61 -0
- package/package.json +60 -4
- package/releases/0.2.0.md +18 -0
- package/releases/0.2.1.md +22 -0
- package/releases/README.md +7 -0
- package/setup-db-grants.sql +51 -0
|
@@ -0,0 +1,1734 @@
|
|
|
1
|
+
import { cloneRowValue } from './clone.js';
|
|
2
|
+
import { convertPostgreSQLError } from './errors.js';
|
|
3
|
+
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 = '.';
|
|
11
|
+
/**
|
|
12
|
+
* Validate a LIMIT/OFFSET value. Anything other than a non-negative safe
|
|
13
|
+
* integer is rejected rather than coerced; callers should parse and clamp
|
|
14
|
+
* untrusted input (e.g. query strings) before passing it in.
|
|
15
|
+
*
|
|
16
|
+
* @param value Candidate row count
|
|
17
|
+
* @param clause Clause name used in the error message
|
|
18
|
+
* @returns The validated count
|
|
19
|
+
*/
|
|
20
|
+
function assertRowCount(value, clause) {
|
|
21
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
|
|
22
|
+
throw new TypeError(`QueryBuilder ${clause} must be a non-negative integer; received ${JSON.stringify(value) ?? String(value)}.`);
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Validate and normalize a sort direction. Directions are interpolated into
|
|
28
|
+
* SQL, so only `ASC` and `DESC` (case-insensitive) are accepted.
|
|
29
|
+
*
|
|
30
|
+
* @param direction Candidate sort direction
|
|
31
|
+
* @returns Upper-cased direction
|
|
32
|
+
*/
|
|
33
|
+
function normalizeSortDirection(direction) {
|
|
34
|
+
if (typeof direction === 'string') {
|
|
35
|
+
const upper = direction.toUpperCase();
|
|
36
|
+
if (upper === 'ASC' || upper === 'DESC') {
|
|
37
|
+
return upper;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
throw new TypeError(`QueryBuilder sort direction must be 'ASC' or 'DESC'; received ${JSON.stringify(direction) ?? String(direction)}.`);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Convert a database row with snake_case keys to the model's camelCase schema keys.
|
|
44
|
+
*
|
|
45
|
+
* @param row Database row to normalize
|
|
46
|
+
* @param fieldMappings Camel-to-snake mapping registered on the model
|
|
47
|
+
* @returns Row keyed by camelCase field names
|
|
48
|
+
*/
|
|
49
|
+
function remapRowToCamelCase(row, fieldMappings) {
|
|
50
|
+
if (!(fieldMappings instanceof Map) || fieldMappings.size === 0) {
|
|
51
|
+
return row;
|
|
52
|
+
}
|
|
53
|
+
const reverseMapping = new Map();
|
|
54
|
+
for (const [camel, snake] of fieldMappings.entries()) {
|
|
55
|
+
reverseMapping.set(snake, camel);
|
|
56
|
+
}
|
|
57
|
+
const remapped = {};
|
|
58
|
+
for (const [key, value] of Object.entries(row)) {
|
|
59
|
+
const camelKey = reverseMapping.get(key) ?? key;
|
|
60
|
+
remapped[camelKey] = value;
|
|
61
|
+
}
|
|
62
|
+
return remapped;
|
|
63
|
+
}
|
|
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';
|
|
68
|
+
/**
|
|
69
|
+
* Whether a value can be compared with `=` (or `= ANY` for arrays) in a
|
|
70
|
+
* batch-join filter.
|
|
71
|
+
*/
|
|
72
|
+
function isJoinFilterValue(value) {
|
|
73
|
+
if (value === null || value instanceof Date)
|
|
74
|
+
return true;
|
|
75
|
+
if (Array.isArray(value))
|
|
76
|
+
return value.every(item => item === null || isJoinFilterValue(item));
|
|
77
|
+
return ['string', 'number', 'boolean', 'bigint'].includes(typeof value);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Run an `_apply` callback against a builder that records each call, so the
|
|
81
|
+
* batch query can be built from the actual arguments (including variables
|
|
82
|
+
* the callback closes over).
|
|
83
|
+
*
|
|
84
|
+
* @param applyFn The `_apply` callback from a join specification
|
|
85
|
+
* @returns The recorded specification, or null when there is no callback
|
|
86
|
+
*/
|
|
87
|
+
function recordJoinApply(applyFn) {
|
|
88
|
+
if (typeof applyFn !== 'function') {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const spec = { filters: [], without: [], order: [], limit: null };
|
|
92
|
+
const addFilter = (literal) => {
|
|
93
|
+
if (!literal || typeof literal !== 'object' || Array.isArray(literal)) {
|
|
94
|
+
throw new TypeError('_apply filterWhere() expects an object of field values.');
|
|
95
|
+
}
|
|
96
|
+
for (const [field, value] of Object.entries(literal)) {
|
|
97
|
+
if (value === undefined)
|
|
98
|
+
continue;
|
|
99
|
+
if (!isJoinFilterValue(value)) {
|
|
100
|
+
throw new TypeError(`_apply filterWhere() supports plain values, null and arrays; '${field}' has an ` +
|
|
101
|
+
'unsupported value (operator helpers are not supported in joins).');
|
|
102
|
+
}
|
|
103
|
+
spec.filters.push({ field, value });
|
|
104
|
+
}
|
|
105
|
+
return builder;
|
|
106
|
+
};
|
|
107
|
+
const builder = {
|
|
108
|
+
filterWhere: addFilter,
|
|
109
|
+
filter: addFilter,
|
|
110
|
+
without(fields) {
|
|
111
|
+
spec.without.push(...(Array.isArray(fields) ? fields : [fields]));
|
|
112
|
+
return builder;
|
|
113
|
+
},
|
|
114
|
+
limit(count) {
|
|
115
|
+
spec.limit = assertRowCount(count, 'LIMIT');
|
|
116
|
+
return builder;
|
|
117
|
+
},
|
|
118
|
+
orderBy(field, direction = 'ASC') {
|
|
119
|
+
spec.order.push({ field, direction: normalizeSortDirection(direction) });
|
|
120
|
+
return builder;
|
|
121
|
+
},
|
|
122
|
+
asc(field) {
|
|
123
|
+
return builder.orderBy(field, 'ASC');
|
|
124
|
+
},
|
|
125
|
+
desc(field) {
|
|
126
|
+
return builder.orderBy(field, 'DESC');
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
applyFn(builder);
|
|
130
|
+
return spec;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Query Builder for PostgreSQL DAL
|
|
134
|
+
*
|
|
135
|
+
* Provides a fluent interface for building and executing database queries.
|
|
136
|
+
*/
|
|
137
|
+
/**
|
|
138
|
+
* Fluent query builder for the PostgreSQL DAL.
|
|
139
|
+
*
|
|
140
|
+
* Produces parameterized SQL for SELECT/COUNT/DELETE with support for
|
|
141
|
+
* predicates, ordering, pagination, and both simple and complex joins.
|
|
142
|
+
* Instances are model-aware (leveraging table/column metadata) and implement
|
|
143
|
+
* Promise-like behavior so they can be awaited directly.
|
|
144
|
+
*/
|
|
145
|
+
class QueryBuilder {
|
|
146
|
+
modelClass;
|
|
147
|
+
dal;
|
|
148
|
+
tableName;
|
|
149
|
+
_select;
|
|
150
|
+
_where;
|
|
151
|
+
_joins;
|
|
152
|
+
_orderBy;
|
|
153
|
+
_limit;
|
|
154
|
+
_offset;
|
|
155
|
+
_params;
|
|
156
|
+
_paramIndex;
|
|
157
|
+
_includeSensitive;
|
|
158
|
+
_groupBy;
|
|
159
|
+
_joinSpecs;
|
|
160
|
+
_simpleJoins;
|
|
161
|
+
_complexJoins;
|
|
162
|
+
constructor(modelClass, dal) {
|
|
163
|
+
this.modelClass = modelClass;
|
|
164
|
+
this.dal = dal;
|
|
165
|
+
this.tableName = modelClass.tableName;
|
|
166
|
+
// Query components
|
|
167
|
+
this._select = ['*'];
|
|
168
|
+
this._where = [];
|
|
169
|
+
this._joins = [];
|
|
170
|
+
this._orderBy = [];
|
|
171
|
+
this._groupBy = [];
|
|
172
|
+
this._limit = null;
|
|
173
|
+
this._offset = null;
|
|
174
|
+
this._params = [];
|
|
175
|
+
this._paramIndex = 1;
|
|
176
|
+
this._includeSensitive = [];
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Include sensitive fields in query results
|
|
180
|
+
* @param fields - Array of sensitive field names to include
|
|
181
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
182
|
+
*/
|
|
183
|
+
includeSensitive(fields) {
|
|
184
|
+
this._includeSensitive = Array.isArray(fields) ? fields : [fields];
|
|
185
|
+
return this;
|
|
186
|
+
}
|
|
187
|
+
/** Compile an independent, terminal projection without model hydration. */
|
|
188
|
+
_project(fields) {
|
|
189
|
+
if (!fields.length)
|
|
190
|
+
throw new TypeError('select() requires at least one field.');
|
|
191
|
+
if (this._joins.length ||
|
|
192
|
+
Object.keys(this._complexJoins ?? {}).length ||
|
|
193
|
+
this._groupBy.length) {
|
|
194
|
+
throw new TypeError('select() cannot be combined with getJoin() or groupBy().');
|
|
195
|
+
}
|
|
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}'.`);
|
|
204
|
+
}
|
|
205
|
+
if (definition.isSensitive && !this._includeSensitive.includes(field)) {
|
|
206
|
+
throw new TypeError(`select('${field}') requires includeSensitive('${field}').`);
|
|
207
|
+
}
|
|
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)}`;
|
|
212
|
+
});
|
|
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);
|
|
216
|
+
snapshot._select = columns;
|
|
217
|
+
const all = snapshot._buildSelectQuery();
|
|
218
|
+
snapshot._limit = this._limit === 0 ? 0 : 1;
|
|
219
|
+
const first = snapshot._buildSelectQuery();
|
|
220
|
+
all.params = cloneRowValue(all.params);
|
|
221
|
+
first.params = cloneRowValue(first.params);
|
|
222
|
+
const dal = this.dal;
|
|
223
|
+
const execute = async ({ sql, params }) => {
|
|
224
|
+
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]]))));
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
throw convertPostgreSQLError(error);
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
const run = () => execute(all);
|
|
233
|
+
return Object.freeze({
|
|
234
|
+
run,
|
|
235
|
+
first: async () => (await execute(first))[0] ?? null,
|
|
236
|
+
then: (onfulfilled, onrejected) => run().then(onfulfilled, onrejected),
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Resolve a logical field reference to a database column.
|
|
241
|
+
*
|
|
242
|
+
* @private
|
|
243
|
+
* @param fieldName - Field identifier from legacy code
|
|
244
|
+
* @returns {string} Database column name
|
|
245
|
+
*/
|
|
246
|
+
_resolveFieldName(fieldName) {
|
|
247
|
+
if (typeof fieldName !== 'string') {
|
|
248
|
+
return fieldName;
|
|
249
|
+
}
|
|
250
|
+
if (this.modelClass &&
|
|
251
|
+
typeof this.modelClass._getDbFieldName === 'function') {
|
|
252
|
+
return this.modelClass._getDbFieldName(fieldName);
|
|
253
|
+
}
|
|
254
|
+
return fieldName;
|
|
255
|
+
}
|
|
256
|
+
_assertResolvedField(field) {
|
|
257
|
+
if (typeof field !== 'string') {
|
|
258
|
+
return field;
|
|
259
|
+
}
|
|
260
|
+
if (field.includes('.') || field.includes('(')) {
|
|
261
|
+
return field;
|
|
262
|
+
}
|
|
263
|
+
const resolved = this._resolveFieldName(field);
|
|
264
|
+
if (resolved !== field) {
|
|
265
|
+
throw new Error(`QueryBuilder expected a resolved database column name but received "${field}".`);
|
|
266
|
+
}
|
|
267
|
+
return field;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Filter by revision user
|
|
271
|
+
* @param userId - User ID who created the revision
|
|
272
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
273
|
+
*/
|
|
274
|
+
filterByRevisionUser(userId) {
|
|
275
|
+
this._addWhereCondition('_rev_user', '=', userId);
|
|
276
|
+
return this;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Filter by revision tags
|
|
280
|
+
* @param tags - Tag or array of tags to filter by
|
|
281
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
282
|
+
*/
|
|
283
|
+
filterByRevisionTags(tags) {
|
|
284
|
+
const tagArray = Array.isArray(tags) ? tags : [tags];
|
|
285
|
+
// Use PostgreSQL array overlap operator
|
|
286
|
+
this._addWhereCondition('_rev_tags', '&&', tagArray);
|
|
287
|
+
return this;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Filter by revision date range
|
|
291
|
+
* @param startDate - Start date (inclusive)
|
|
292
|
+
* @param endDate - End date (inclusive)
|
|
293
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
294
|
+
*/
|
|
295
|
+
filterByRevisionDateRange(startDate, endDate) {
|
|
296
|
+
if (startDate) {
|
|
297
|
+
this._addWhereCondition('_rev_date', '>=', startDate);
|
|
298
|
+
}
|
|
299
|
+
if (endDate) {
|
|
300
|
+
this._addWhereCondition('_rev_date', '<=', endDate);
|
|
301
|
+
}
|
|
302
|
+
return this;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Filter by date range
|
|
306
|
+
* @param startDate - Start date
|
|
307
|
+
* @param endDate - End date
|
|
308
|
+
* @param options - Options (leftBound, rightBound)
|
|
309
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
310
|
+
*/
|
|
311
|
+
between(startDate, endDate, options = {}) {
|
|
312
|
+
const leftOp = options.leftBound === 'open' ? '>' : '>=';
|
|
313
|
+
const rightOp = options.rightBound === 'open' ? '<' : '<=';
|
|
314
|
+
this._addWhereCondition('created_on', leftOp, startDate);
|
|
315
|
+
this._addWhereCondition('created_on', rightOp, endDate);
|
|
316
|
+
return this;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Filter by array contains (for PostgreSQL arrays)
|
|
320
|
+
* @param field - Field name
|
|
321
|
+
* @param value - Value to check for
|
|
322
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
323
|
+
*/
|
|
324
|
+
contains(field, value) {
|
|
325
|
+
const values = Array.isArray(value) ? value : [value];
|
|
326
|
+
this._addWhereCondition(field, '@>', values, {
|
|
327
|
+
cast: 'text[]',
|
|
328
|
+
});
|
|
329
|
+
return this;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Filter by JSONB field contains
|
|
333
|
+
* @param field - JSONB field name
|
|
334
|
+
* @param value - Value to check for
|
|
335
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
336
|
+
*/
|
|
337
|
+
containsJsonb(field, value) {
|
|
338
|
+
this._addWhereCondition(field, '@>', value, {
|
|
339
|
+
cast: 'jsonb',
|
|
340
|
+
serializeValue: JSON.stringify,
|
|
341
|
+
});
|
|
342
|
+
return this;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Filter by field existence in JSONB
|
|
346
|
+
* @param field - JSONB field name
|
|
347
|
+
* @param key - Key to check for existence
|
|
348
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
349
|
+
*/
|
|
350
|
+
hasFields(field, key) {
|
|
351
|
+
this._addWhereCondition(field, '?', key);
|
|
352
|
+
return this;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Filter by membership in a list of values using PostgreSQL ANY
|
|
356
|
+
* @param field - Field name
|
|
357
|
+
* @param values - Values to match
|
|
358
|
+
* @param [options] - Additional options
|
|
359
|
+
* @param [options.cast] - Optional cast to apply to the parameter (e.g., 'uuid[]')
|
|
360
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
361
|
+
*/
|
|
362
|
+
whereIn(field, values, { cast } = {}) {
|
|
363
|
+
if (!Array.isArray(values)) {
|
|
364
|
+
throw new TypeError('QueryBuilder.whereIn requires an array of values.');
|
|
365
|
+
}
|
|
366
|
+
// Membership in an empty set is always false, so match no rows rather
|
|
367
|
+
// than silently dropping the filter.
|
|
368
|
+
if (values.length === 0) {
|
|
369
|
+
this._where.push(this._createMatchNothingPredicate());
|
|
370
|
+
return this;
|
|
371
|
+
}
|
|
372
|
+
const valueTransform = placeholder => `(${placeholder}${cast ? `::${cast}` : ''})`;
|
|
373
|
+
this._addWhereCondition(field, '= ANY', values, { valueTransform });
|
|
374
|
+
return this;
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Get all revisions of a specific document (including old and deleted)
|
|
378
|
+
* @param documentId - The document ID to get revisions for
|
|
379
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
380
|
+
*/
|
|
381
|
+
getAllRevisions(documentId) {
|
|
382
|
+
// Clear any existing revision filters
|
|
383
|
+
this._where = this._where.filter(predicate => !this._isRevisionFilterPredicate(predicate));
|
|
384
|
+
// Add condition to get all revisions of the document
|
|
385
|
+
const idPredicate = this._createPredicate('id', '=', documentId);
|
|
386
|
+
const oldRevPredicate = this._createPredicate('_old_rev_of', '=', documentId);
|
|
387
|
+
const groupPredicate = {
|
|
388
|
+
type: 'group',
|
|
389
|
+
conjunction: 'OR',
|
|
390
|
+
predicates: [idPredicate, oldRevPredicate],
|
|
391
|
+
};
|
|
392
|
+
this._where.push(groupPredicate);
|
|
393
|
+
return this;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Add ORDER BY clause
|
|
397
|
+
* @param field - Field to order by
|
|
398
|
+
* @param direction - Sort direction (ASC/DESC)
|
|
399
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
400
|
+
*/
|
|
401
|
+
orderBy(field, direction = 'ASC') {
|
|
402
|
+
const normalizedDirection = normalizeSortDirection(direction);
|
|
403
|
+
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}`;
|
|
409
|
+
}
|
|
410
|
+
else {
|
|
411
|
+
expression = resolvedColumn;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
this._orderBy.push(`${expression} ${normalizedDirection}`);
|
|
415
|
+
return this;
|
|
416
|
+
}
|
|
417
|
+
orderByRelation(relationName, field, direction = 'ASC') {
|
|
418
|
+
const normalizedDirection = normalizeSortDirection(direction);
|
|
419
|
+
const joinInfo = this._getJoinInfo(relationName);
|
|
420
|
+
if (!joinInfo) {
|
|
421
|
+
debug.db(`Warning: Unknown relation '${relationName}' for table '${this.tableName}'`);
|
|
422
|
+
return this;
|
|
423
|
+
}
|
|
424
|
+
if (!this._simpleJoins || !this._simpleJoins[relationName]) {
|
|
425
|
+
this._addSimpleJoin(relationName);
|
|
426
|
+
}
|
|
427
|
+
const targetTable = joinInfo.joinTable || joinInfo.table;
|
|
428
|
+
if (!targetTable) {
|
|
429
|
+
debug.db(`Warning: Relation '${relationName}' missing table metadata for ordering`);
|
|
430
|
+
return this;
|
|
431
|
+
}
|
|
432
|
+
const column = this._normalizeColumnName(field);
|
|
433
|
+
this._orderBy.push(`${targetTable}.${column} ${normalizedDirection}`);
|
|
434
|
+
return this;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Add LIMIT clause
|
|
438
|
+
* @param count - Limit count (non-negative integer), or `null` to clear it
|
|
439
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
440
|
+
*/
|
|
441
|
+
limit(count) {
|
|
442
|
+
this._limit = count === null ? null : assertRowCount(count, 'LIMIT');
|
|
443
|
+
return this;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Add OFFSET clause
|
|
447
|
+
* @param count - Offset count (non-negative integer), or `null` to clear it
|
|
448
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
449
|
+
*/
|
|
450
|
+
offset(count) {
|
|
451
|
+
this._offset = count === null ? null : assertRowCount(count, 'OFFSET');
|
|
452
|
+
return this;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Add GROUP BY clause
|
|
456
|
+
* @param fields - Field or fields to group by
|
|
457
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
458
|
+
*/
|
|
459
|
+
groupBy(fields) {
|
|
460
|
+
const fieldArray = Array.isArray(fields) ? fields : [fields];
|
|
461
|
+
for (const field of fieldArray) {
|
|
462
|
+
let expression = field;
|
|
463
|
+
if (typeof field === 'string' && !field.includes('(') && !field.includes('.')) {
|
|
464
|
+
const resolvedColumn = this._resolvePredicateColumn(null, field);
|
|
465
|
+
expression = `${this.tableName}.${resolvedColumn}`;
|
|
466
|
+
}
|
|
467
|
+
this._groupBy.push(expression);
|
|
468
|
+
}
|
|
469
|
+
return this;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Add JOIN clauses with support for complex joins
|
|
473
|
+
* @param joinSpec - Join specification
|
|
474
|
+
* @returns {QueryBuilder} This instance for chaining
|
|
475
|
+
*/
|
|
476
|
+
getJoin(joinSpec) {
|
|
477
|
+
if (!joinSpec || Object.keys(joinSpec).length === 0) {
|
|
478
|
+
return this;
|
|
479
|
+
}
|
|
480
|
+
// Store join specification for processing during query execution
|
|
481
|
+
if (!this._joinSpecs) {
|
|
482
|
+
this._joinSpecs = [];
|
|
483
|
+
}
|
|
484
|
+
this._joinSpecs.push(joinSpec);
|
|
485
|
+
// Process joins and add to query
|
|
486
|
+
for (const [relationName, relationSpec] of Object.entries(joinSpec)) {
|
|
487
|
+
this._processJoin(relationName, relationSpec);
|
|
488
|
+
}
|
|
489
|
+
return this;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Process a single join specification
|
|
493
|
+
* @param relationName - Name of the relation
|
|
494
|
+
* @param relationSpec - Join specification
|
|
495
|
+
* @private
|
|
496
|
+
*/
|
|
497
|
+
_processJoin(relationName, relationSpec) {
|
|
498
|
+
// Handle simple boolean joins (e.g., { teams: true })
|
|
499
|
+
if (relationSpec === true) {
|
|
500
|
+
// Check cardinality to auto-select optimal strategy:
|
|
501
|
+
// - 'one' → inline join (single query)
|
|
502
|
+
// - 'many' → batch loader (follow-up query, avoids row multiplication)
|
|
503
|
+
const joinInfo = this._getJoinInfo(relationName);
|
|
504
|
+
if (joinInfo && (joinInfo.cardinality === 'many' || this._inlineJoinConflict(joinInfo))) {
|
|
505
|
+
// Use the batch loader for many relations, and for relations whose
|
|
506
|
+
// table can't be joined inline again (joined tables aren't aliased)
|
|
507
|
+
this._addComplexJoin(relationName, {});
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
this._addSimpleJoin(relationName);
|
|
511
|
+
}
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
// Handle complex join specifications
|
|
515
|
+
if (typeof relationSpec === 'object' && relationSpec !== null) {
|
|
516
|
+
this._addComplexJoin(relationName, relationSpec);
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Add a simple join for a relation
|
|
522
|
+
* @param relationName - Name of the relation
|
|
523
|
+
* @private
|
|
524
|
+
*/
|
|
525
|
+
_addSimpleJoin(relationName) {
|
|
526
|
+
if (this._simpleJoins?.[relationName]) {
|
|
527
|
+
return; // Already joined (e.g. by whereRelated)
|
|
528
|
+
}
|
|
529
|
+
const joinInfo = this._getJoinInfo(relationName);
|
|
530
|
+
if (!joinInfo) {
|
|
531
|
+
debug.db(`Warning: Unknown relation '${relationName}' for table '${this.tableName}'`);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
const conflict = this._inlineJoinConflict(joinInfo);
|
|
535
|
+
if (conflict) {
|
|
536
|
+
throw new Error(`Cannot join relation '${relationName}' inline: ${conflict}. ` +
|
|
537
|
+
'Load it with getJoin() instead, which falls back to a separate query.');
|
|
538
|
+
}
|
|
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
|
+
}
|
|
556
|
+
// Mark this relation for result processing
|
|
557
|
+
if (!this._simpleJoins) {
|
|
558
|
+
this._simpleJoins = {};
|
|
559
|
+
}
|
|
560
|
+
this._simpleJoins[relationName] = joinInfo;
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Explain why a relation's tables can't be joined inline into this query,
|
|
564
|
+
* or return null if they can. Joined tables are referenced by name rather
|
|
565
|
+
* than by alias, so each table may appear only once.
|
|
566
|
+
* @private
|
|
567
|
+
*/
|
|
568
|
+
_inlineJoinConflict(joinInfo) {
|
|
569
|
+
const joined = new Set([this.tableName]);
|
|
570
|
+
for (const info of Object.values(this._simpleJoins ?? {})) {
|
|
571
|
+
joined.add(info.table);
|
|
572
|
+
if (info.joinTable)
|
|
573
|
+
joined.add(info.joinTable);
|
|
574
|
+
}
|
|
575
|
+
for (const table of [joinInfo.table, joinInfo.joinTable]) {
|
|
576
|
+
if (!table || !joined.has(table))
|
|
577
|
+
continue;
|
|
578
|
+
return table === this.tableName
|
|
579
|
+
? `it refers back to '${table}', the table being queried`
|
|
580
|
+
: `'${table}' is already joined by another relation`;
|
|
581
|
+
}
|
|
582
|
+
return null;
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Add a complex join with filters and transformations
|
|
586
|
+
* @param relationName - Name of the relation
|
|
587
|
+
* @param relationSpec - Join specification with _apply, filters, etc.
|
|
588
|
+
* @private
|
|
589
|
+
*/
|
|
590
|
+
_addComplexJoin(relationName, relationSpec) {
|
|
591
|
+
const joinInfo = this._getJoinInfo(relationName);
|
|
592
|
+
if (!joinInfo) {
|
|
593
|
+
debug.db(`Warning: Unknown relation '${relationName}' for table '${this.tableName}'`);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
// For complex joins, we'll need to handle them during result processing
|
|
597
|
+
// Store the specification for later use
|
|
598
|
+
if (!this._complexJoins) {
|
|
599
|
+
this._complexJoins = {};
|
|
600
|
+
}
|
|
601
|
+
this._complexJoins[relationName] = {
|
|
602
|
+
...relationSpec,
|
|
603
|
+
joinInfo,
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Get join information for a relation name
|
|
608
|
+
* @param relationName - Name of the relation
|
|
609
|
+
* @returns {Object|null} Join information
|
|
610
|
+
* @private
|
|
611
|
+
*/
|
|
612
|
+
_getJoinInfo(relationName) {
|
|
613
|
+
if (!this.modelClass || typeof this.modelClass.getRelation !== 'function') {
|
|
614
|
+
return null;
|
|
615
|
+
}
|
|
616
|
+
const relationConfig = this.modelClass.getRelation(relationName);
|
|
617
|
+
if (!relationConfig) {
|
|
618
|
+
return null;
|
|
619
|
+
}
|
|
620
|
+
const baseTargetTable = relationConfig.targetTable || relationConfig.table;
|
|
621
|
+
const targetTableName = this._resolveTableReference(baseTargetTable);
|
|
622
|
+
if (!targetTableName) {
|
|
623
|
+
debug.db(`Warning: Relation '${relationName}' on '${this.tableName}' is missing a target table definition`);
|
|
624
|
+
return null;
|
|
625
|
+
}
|
|
626
|
+
const hasRevisions = Boolean(relationConfig.hasRevisions);
|
|
627
|
+
const sourceColumn = relationConfig.sourceColumn || relationConfig.sourceKey || 'id';
|
|
628
|
+
const targetColumn = relationConfig.targetColumn || relationConfig.targetKey || 'id';
|
|
629
|
+
const cardinality = relationConfig.cardinality || (relationConfig.isArray ? 'many' : 'one');
|
|
630
|
+
const targetModelKey = relationConfig.targetModelKey || relationConfig.targetModel || baseTargetTable;
|
|
631
|
+
if (relationConfig.through && typeof relationConfig.through === 'object') {
|
|
632
|
+
const joinTableName = this._resolveTableReference(relationConfig.through.table || relationConfig.joinTable);
|
|
633
|
+
if (!joinTableName) {
|
|
634
|
+
debug.db(`Warning: Relation '${relationName}' on '${this.tableName}' is missing a join table definition`);
|
|
635
|
+
return null;
|
|
636
|
+
}
|
|
637
|
+
const throughSourceKey = relationConfig.through.sourceColumn ||
|
|
638
|
+
relationConfig.through.sourceForeignKey ||
|
|
639
|
+
relationConfig.through.sourceKey;
|
|
640
|
+
const throughTargetKey = relationConfig.through.targetColumn ||
|
|
641
|
+
relationConfig.through.targetForeignKey ||
|
|
642
|
+
relationConfig.through.targetKey;
|
|
643
|
+
if (!throughSourceKey || !throughTargetKey) {
|
|
644
|
+
debug.db(`Warning: Relation '${relationName}' on '${this.tableName}' is missing join column metadata`);
|
|
645
|
+
return null;
|
|
646
|
+
}
|
|
647
|
+
const joinTableOn = relationConfig.through.sourceCondition ||
|
|
648
|
+
`${this.tableName}.${sourceColumn} = ${joinTableName}.${throughSourceKey}`;
|
|
649
|
+
const targetCondition = relationConfig.condition ||
|
|
650
|
+
relationConfig.through.targetCondition ||
|
|
651
|
+
`${joinTableName}.${throughTargetKey} = ${targetTableName}.${targetColumn}`;
|
|
652
|
+
return {
|
|
653
|
+
type: 'through',
|
|
654
|
+
table: targetTableName,
|
|
655
|
+
baseTable: baseTargetTable,
|
|
656
|
+
hasRevisions,
|
|
657
|
+
joinTable: joinTableName,
|
|
658
|
+
joinTableOn,
|
|
659
|
+
condition: targetCondition,
|
|
660
|
+
sourceColumn,
|
|
661
|
+
targetColumn,
|
|
662
|
+
joinTableSourceColumn: throughSourceKey,
|
|
663
|
+
joinTableTargetColumn: throughTargetKey,
|
|
664
|
+
cardinality,
|
|
665
|
+
isArray: cardinality !== 'one',
|
|
666
|
+
targetModelKey,
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
const directCondition = relationConfig.condition ||
|
|
670
|
+
`${this.tableName}.${sourceColumn} = ${targetTableName}.${targetColumn}`;
|
|
671
|
+
return {
|
|
672
|
+
type: 'direct',
|
|
673
|
+
table: targetTableName,
|
|
674
|
+
baseTable: baseTargetTable,
|
|
675
|
+
hasRevisions,
|
|
676
|
+
condition: directCondition,
|
|
677
|
+
sourceColumn,
|
|
678
|
+
targetColumn,
|
|
679
|
+
cardinality,
|
|
680
|
+
isArray: cardinality !== 'one',
|
|
681
|
+
targetModelKey,
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
_resolveTableReference(tableRef) {
|
|
685
|
+
if (!tableRef || typeof tableRef !== 'string') {
|
|
686
|
+
return null;
|
|
687
|
+
}
|
|
688
|
+
if (tableRef.includes('.')) {
|
|
689
|
+
return tableRef;
|
|
690
|
+
}
|
|
691
|
+
return this._getTableName(tableRef);
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Get table name with optional schema namespace
|
|
695
|
+
* @param baseName - Base table name
|
|
696
|
+
* @returns {string} Full table name
|
|
697
|
+
* @private
|
|
698
|
+
*/
|
|
699
|
+
_getTableName(baseName) {
|
|
700
|
+
const namespace = this.dal.schemaNamespace || '';
|
|
701
|
+
return namespace + baseName;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Execute query and return all results
|
|
705
|
+
* @returns {Promise<Array>} Query results
|
|
706
|
+
*/
|
|
707
|
+
async run() {
|
|
708
|
+
try {
|
|
709
|
+
// Handle complex joins that require separate queries
|
|
710
|
+
if (this._complexJoins && Object.keys(this._complexJoins).length > 0) {
|
|
711
|
+
return await this._runWithComplexJoins();
|
|
712
|
+
}
|
|
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);
|
|
717
|
+
}
|
|
718
|
+
catch (error) {
|
|
719
|
+
throw convertPostgreSQLError(error);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Allow QueryBuilder to behave like a Promise (basic thenable)
|
|
724
|
+
* @param onFulfilled - Success handler
|
|
725
|
+
* @param onRejected - Error handler
|
|
726
|
+
* @returns {Promise} Promise resolving to query results
|
|
727
|
+
*/
|
|
728
|
+
then(onFulfilled, onRejected) {
|
|
729
|
+
return this.run().then(onFulfilled, onRejected);
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Catch handler for Promise-like usage
|
|
733
|
+
* @param onRejected - Error handler
|
|
734
|
+
* @returns {Promise} Promise resolving to query results
|
|
735
|
+
*/
|
|
736
|
+
catch(onRejected) {
|
|
737
|
+
return this.run().catch(onRejected);
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Finally handler for Promise-like usage
|
|
741
|
+
* @param onFinally - Finally handler
|
|
742
|
+
* @returns {Promise} Promise resolving to query results
|
|
743
|
+
*/
|
|
744
|
+
finally(onFinally) {
|
|
745
|
+
return this.run().finally(onFinally ?? undefined);
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Execute query with complex joins that require separate queries
|
|
749
|
+
* @returns {Promise<Array>} Query results with joined data
|
|
750
|
+
* @private
|
|
751
|
+
*/
|
|
752
|
+
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);
|
|
760
|
+
}
|
|
761
|
+
return mainRows;
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Process a complex join by executing separate queries
|
|
765
|
+
* @param mainRows - Main query results
|
|
766
|
+
* @param relationName - Name of the relation
|
|
767
|
+
* @param joinSpec - Join specification
|
|
768
|
+
* @private
|
|
769
|
+
*/
|
|
770
|
+
async _processComplexJoin(mainRows, relationName, joinSpec) {
|
|
771
|
+
if (!Array.isArray(mainRows) || mainRows.length === 0) {
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
const { joinInfo } = joinSpec;
|
|
775
|
+
if (!joinInfo) {
|
|
776
|
+
debug.db(`Warning: Missing join metadata for relation '${relationName}' on '${this.tableName}'`);
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
const sourceValues = this._extractJoinSourceValues(mainRows, joinInfo.sourceColumn);
|
|
780
|
+
if (sourceValues.length === 0) {
|
|
781
|
+
this._assignJoinResults(mainRows, relationName, joinInfo, new Map());
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
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);
|
|
792
|
+
this._assignJoinResults(mainRows, relationName, joinInfo, groupedRows);
|
|
793
|
+
}
|
|
794
|
+
_extractJoinSourceValues(mainRows, sourceColumn) {
|
|
795
|
+
if (!sourceColumn) {
|
|
796
|
+
return [];
|
|
797
|
+
}
|
|
798
|
+
const values = [];
|
|
799
|
+
const seen = new Set();
|
|
800
|
+
for (const row of mainRows) {
|
|
801
|
+
const value = this._getRowValue(row, sourceColumn);
|
|
802
|
+
if (value === undefined || value === null) {
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
const key = value instanceof Date ? String(value.getTime()) : `${value}`;
|
|
806
|
+
if (seen.has(key)) {
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
seen.add(key);
|
|
810
|
+
values.push(value);
|
|
811
|
+
}
|
|
812
|
+
return values;
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Resolve a field named in an `_apply` callback to a column of the related
|
|
816
|
+
* table, using the related model's field mappings when available.
|
|
817
|
+
* @private
|
|
818
|
+
*/
|
|
819
|
+
_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)) {
|
|
825
|
+
throw new Error(`Invalid field '${String(field)}' in _apply for relation '${relationName}'.`);
|
|
826
|
+
}
|
|
827
|
+
return column;
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Build the batch query that loads a relation for a set of parent rows.
|
|
831
|
+
*
|
|
832
|
+
* Selects the related model's safe (non-sensitive) columns, applies the
|
|
833
|
+
* recorded `_apply` filters/order as parameters, and limits per parent with
|
|
834
|
+
* a window function.
|
|
835
|
+
* @private
|
|
836
|
+
*/
|
|
837
|
+
_buildComplexJoinQuery(relationName, joinInfo, sourceValues, spec = null) {
|
|
838
|
+
const params = [sourceValues];
|
|
839
|
+
const nextParam = (value) => {
|
|
840
|
+
params.push(value);
|
|
841
|
+
return `$${params.length}`;
|
|
842
|
+
};
|
|
843
|
+
const targetAlias = `${relationName}_target`;
|
|
844
|
+
const throughAlias = `${relationName}_through`;
|
|
845
|
+
const joinSourceAlias = '_join_source_id';
|
|
846
|
+
const relatedModel = this._getRelatedModel(relationName, joinInfo);
|
|
847
|
+
const resolve = (field) => this._resolveJoinColumn(relatedModel, relationName, field);
|
|
848
|
+
// Columns: the related model's safe columns minus `without`; fall back to
|
|
849
|
+
// all columns (and omit after the query) when no model is registered.
|
|
850
|
+
const safeColumns = typeof relatedModel?.getSafeColumnNames === 'function'
|
|
851
|
+
? relatedModel.getSafeColumnNames()
|
|
852
|
+
: [];
|
|
853
|
+
let selectList;
|
|
854
|
+
let omitAfterQuery = [];
|
|
855
|
+
if (safeColumns.length > 0) {
|
|
856
|
+
const omitted = new Set((spec?.without ?? []).map(resolve));
|
|
857
|
+
selectList = safeColumns
|
|
858
|
+
.filter(column => !omitted.has(column))
|
|
859
|
+
.map(column => `${targetAlias}.${column}`);
|
|
860
|
+
}
|
|
861
|
+
else {
|
|
862
|
+
selectList = [`${targetAlias}.*`];
|
|
863
|
+
omitAfterQuery = spec?.without ?? [];
|
|
864
|
+
}
|
|
865
|
+
const isThrough = joinInfo.type === 'through';
|
|
866
|
+
const sourceExpr = isThrough
|
|
867
|
+
? `${throughAlias}.${joinInfo.joinTableSourceColumn}`
|
|
868
|
+
: `${targetAlias}.${joinInfo.targetColumn}`;
|
|
869
|
+
let from = `FROM ${joinInfo.table} ${targetAlias}`;
|
|
870
|
+
if (isThrough) {
|
|
871
|
+
from += ` JOIN ${joinInfo.joinTable} ${throughAlias} ON ${throughAlias}.${joinInfo.joinTableTargetColumn} = ${targetAlias}.${joinInfo.targetColumn}`;
|
|
872
|
+
}
|
|
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)`);
|
|
882
|
+
}
|
|
883
|
+
else if (value === null) {
|
|
884
|
+
whereClauses.push(`${column} IS NULL`);
|
|
885
|
+
}
|
|
886
|
+
else if (Array.isArray(value)) {
|
|
887
|
+
whereClauses.push(`${column} = ANY(${nextParam(value)})`);
|
|
888
|
+
}
|
|
889
|
+
else {
|
|
890
|
+
whereClauses.push(`${column} = ${nextParam(value)}`);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const orderSql = (spec?.order ?? [])
|
|
894
|
+
.map(({ field, direction }) => `${targetAlias}.${resolve(field)} ${direction}`)
|
|
895
|
+
.join(', ');
|
|
896
|
+
const columns = [...selectList, `${sourceExpr} AS ${joinSourceAlias}`];
|
|
897
|
+
const where = ` WHERE ${whereClauses.join(' AND ')}`;
|
|
898
|
+
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}`;
|
|
902
|
+
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}`;
|
|
905
|
+
}
|
|
906
|
+
else {
|
|
907
|
+
query = `SELECT ${columns.join(', ')} ${from}${where}${orderSql ? ` ORDER BY ${orderSql}` : ''}`;
|
|
908
|
+
}
|
|
909
|
+
return { query, params, joinSourceAlias, omitAfterQuery };
|
|
910
|
+
}
|
|
911
|
+
_groupRelatedRows(rows, joinSourceAlias = '_join_source_id') {
|
|
912
|
+
const grouped = new Map();
|
|
913
|
+
if (!Array.isArray(rows)) {
|
|
914
|
+
return grouped;
|
|
915
|
+
}
|
|
916
|
+
for (const row of rows) {
|
|
917
|
+
if (!row ||
|
|
918
|
+
typeof row !== 'object' ||
|
|
919
|
+
!Object.prototype.hasOwnProperty.call(row, joinSourceAlias)) {
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
922
|
+
const key = row[joinSourceAlias];
|
|
923
|
+
if (key === undefined || key === null) {
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
const cloned = { ...row };
|
|
927
|
+
delete cloned[joinSourceAlias];
|
|
928
|
+
delete cloned[JOIN_RANK_ALIAS];
|
|
929
|
+
const existing = grouped.get(key) || [];
|
|
930
|
+
existing.push(cloned);
|
|
931
|
+
grouped.set(key, existing);
|
|
932
|
+
}
|
|
933
|
+
return grouped;
|
|
934
|
+
}
|
|
935
|
+
_assignJoinResults(mainRows, relationName, joinInfo, groupedRows) {
|
|
936
|
+
const RelatedModel = this._getRelatedModel(relationName, joinInfo);
|
|
937
|
+
const expectsArray = joinInfo.isArray !== false && joinInfo.cardinality !== 'one';
|
|
938
|
+
const sourceColumn = joinInfo.sourceColumn || 'id';
|
|
939
|
+
for (const mainRow of mainRows) {
|
|
940
|
+
const joinKey = this._getRowValue(mainRow, sourceColumn);
|
|
941
|
+
const related = joinKey === undefined || joinKey === null ? [] : groupedRows.get(joinKey) || [];
|
|
942
|
+
if (expectsArray) {
|
|
943
|
+
mainRow[relationName] = related.map(row => this._instantiateRelated(RelatedModel, row));
|
|
944
|
+
}
|
|
945
|
+
else {
|
|
946
|
+
const match = related[0] || null;
|
|
947
|
+
mainRow[relationName] = match ? this._instantiateRelated(RelatedModel, match) : null;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
_instantiateRelated(RelatedModel, data) {
|
|
952
|
+
if (!RelatedModel) {
|
|
953
|
+
return data;
|
|
954
|
+
}
|
|
955
|
+
const runtime = RelatedModel;
|
|
956
|
+
if (typeof runtime._createInstance === 'function') {
|
|
957
|
+
return runtime._createInstance(data);
|
|
958
|
+
}
|
|
959
|
+
return new RelatedModel(data);
|
|
960
|
+
}
|
|
961
|
+
_getRowValue(row, column) {
|
|
962
|
+
if (!row || !column) {
|
|
963
|
+
return undefined;
|
|
964
|
+
}
|
|
965
|
+
if (typeof row.getValue === 'function') {
|
|
966
|
+
return row.getValue(column);
|
|
967
|
+
}
|
|
968
|
+
return row[column];
|
|
969
|
+
}
|
|
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
|
+
_normalizeColumnName(field) {
|
|
988
|
+
if (!field) {
|
|
989
|
+
return field;
|
|
990
|
+
}
|
|
991
|
+
if (field.startsWith('_')) {
|
|
992
|
+
return `_${this._normalizeColumnName(field.slice(1))}`;
|
|
993
|
+
}
|
|
994
|
+
const withUnderscores = field.replace(/([a-z0-9])([A-Z])/g, '$1_$2').replace(/[\s-]+/g, '_');
|
|
995
|
+
return withUnderscores.toLowerCase();
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* Get the model class for a relation
|
|
999
|
+
* @param relationName - Name of the relation
|
|
1000
|
+
* @returns {Function|null} Model class
|
|
1001
|
+
* @private
|
|
1002
|
+
*/
|
|
1003
|
+
_getRelatedModel(relationName, joinInfo = null) {
|
|
1004
|
+
const registry = this._getModelRegistry();
|
|
1005
|
+
if (!registry || typeof registry.get !== 'function') {
|
|
1006
|
+
return null;
|
|
1007
|
+
}
|
|
1008
|
+
const metadata = joinInfo ??
|
|
1009
|
+
this._simpleJoins?.[relationName] ??
|
|
1010
|
+
this._complexJoins?.[relationName]?.joinInfo ??
|
|
1011
|
+
{};
|
|
1012
|
+
const identifiers = [metadata.targetModelKey, metadata.baseTable, metadata.table, relationName];
|
|
1013
|
+
for (const identifier of identifiers) {
|
|
1014
|
+
if (!identifier)
|
|
1015
|
+
continue;
|
|
1016
|
+
const model = registry.get(identifier);
|
|
1017
|
+
if (model) {
|
|
1018
|
+
return model;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
return null;
|
|
1022
|
+
}
|
|
1023
|
+
_getModelRegistry() {
|
|
1024
|
+
if (!this.dal) {
|
|
1025
|
+
return null;
|
|
1026
|
+
}
|
|
1027
|
+
let registry = null;
|
|
1028
|
+
if (typeof this.dal.getModelRegistry === 'function') {
|
|
1029
|
+
registry = this.dal.getModelRegistry();
|
|
1030
|
+
}
|
|
1031
|
+
else {
|
|
1032
|
+
registry = this.dal.modelRegistry ?? null;
|
|
1033
|
+
}
|
|
1034
|
+
if (!registry || typeof registry.get !== 'function') {
|
|
1035
|
+
return null;
|
|
1036
|
+
}
|
|
1037
|
+
return registry;
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Process query results, handling simple joins
|
|
1041
|
+
* @param rows - Raw database rows
|
|
1042
|
+
* @returns {Promise<Array>} Processed model instances
|
|
1043
|
+
* @private
|
|
1044
|
+
*/
|
|
1045
|
+
async _processResults(rows) {
|
|
1046
|
+
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
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
processedRows.push(instance);
|
|
1090
|
+
}
|
|
1091
|
+
return processedRows;
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Execute query and return first result
|
|
1095
|
+
* @returns {Promise<Model|null>} First result or null
|
|
1096
|
+
*/
|
|
1097
|
+
async first() {
|
|
1098
|
+
this.limit(1);
|
|
1099
|
+
const results = await this.run();
|
|
1100
|
+
return results.length > 0 ? results[0] : null;
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Execute query and return count
|
|
1104
|
+
* @returns {Promise<number>} Result count
|
|
1105
|
+
*/
|
|
1106
|
+
async count() {
|
|
1107
|
+
try {
|
|
1108
|
+
const { sql, params } = this._buildCountQuery();
|
|
1109
|
+
const result = await this.dal.query(sql, params);
|
|
1110
|
+
const [row] = result.rows;
|
|
1111
|
+
return Number.parseInt(String(row?.count ?? '0'), 10);
|
|
1112
|
+
}
|
|
1113
|
+
catch (error) {
|
|
1114
|
+
throw convertPostgreSQLError(error);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* Calculate the average for a column.
|
|
1119
|
+
*
|
|
1120
|
+
* @param field - Column to aggregate.
|
|
1121
|
+
* @returns Numeric average or `null` when no rows satisfy the predicates.
|
|
1122
|
+
*/
|
|
1123
|
+
async average(field) {
|
|
1124
|
+
return this._aggregateFunction('AVG', field);
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
* Compute an aggregate for the active query.
|
|
1128
|
+
*
|
|
1129
|
+
* @param func - SQL aggregate function identifier (e.g., `AVG`).
|
|
1130
|
+
* @param field - Resolved field/column name to aggregate.
|
|
1131
|
+
* @returns Numeric aggregate result or `null` when no rows match.
|
|
1132
|
+
*/
|
|
1133
|
+
async _aggregateFunction(func, field) {
|
|
1134
|
+
try {
|
|
1135
|
+
const column = typeof field === 'string' && (field.includes('.') || field.includes('('))
|
|
1136
|
+
? field
|
|
1137
|
+
: `${this.tableName}.${field}`;
|
|
1138
|
+
const { sql, params } = this._buildAggregateQuery(func, column);
|
|
1139
|
+
const result = await this.dal.query(sql, params);
|
|
1140
|
+
const value = result.rows[0]?.value;
|
|
1141
|
+
if (value === null || value === undefined) {
|
|
1142
|
+
return null;
|
|
1143
|
+
}
|
|
1144
|
+
const numeric = typeof value === 'number' ? value : Number(value);
|
|
1145
|
+
return Number.isNaN(numeric) ? null : numeric;
|
|
1146
|
+
}
|
|
1147
|
+
catch (error) {
|
|
1148
|
+
throw convertPostgreSQLError(error);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Perform grouped aggregations with GROUP BY.
|
|
1153
|
+
* Returns a map from the grouping key to the aggregate value.
|
|
1154
|
+
*
|
|
1155
|
+
* @param func - SQL aggregate function (e.g., 'COUNT', 'AVG')
|
|
1156
|
+
* @param options - Configuration options
|
|
1157
|
+
* @param options.aggregateField - Field to aggregate (required for AVG, SUM, etc.; omit for COUNT)
|
|
1158
|
+
* @returns Map from group key to aggregate value
|
|
1159
|
+
*
|
|
1160
|
+
* @example
|
|
1161
|
+
* // Count reviews per thing
|
|
1162
|
+
* const counts = await Review.filterWhere({})
|
|
1163
|
+
* .whereIn('thingID', thingIds)
|
|
1164
|
+
* .groupBy('thingID')
|
|
1165
|
+
* .aggregateGrouped('COUNT');
|
|
1166
|
+
* // Returns: Map { 'thing-id-1' => 5, 'thing-id-2' => 3, ... }
|
|
1167
|
+
*/
|
|
1168
|
+
async aggregateGrouped(func, options = {}) {
|
|
1169
|
+
try {
|
|
1170
|
+
if (this._groupBy.length === 0) {
|
|
1171
|
+
throw new Error('aggregateGrouped requires groupBy() to be called first');
|
|
1172
|
+
}
|
|
1173
|
+
let aggregateColumn = '*';
|
|
1174
|
+
if (options.aggregateField) {
|
|
1175
|
+
if (options.aggregateField.includes('.') || options.aggregateField.includes('(')) {
|
|
1176
|
+
aggregateColumn = options.aggregateField;
|
|
1177
|
+
}
|
|
1178
|
+
else {
|
|
1179
|
+
const resolved = this._resolveFieldName(options.aggregateField);
|
|
1180
|
+
if (typeof resolved !== 'string') {
|
|
1181
|
+
throw new TypeError('aggregateGrouped requires a string field name');
|
|
1182
|
+
}
|
|
1183
|
+
aggregateColumn = `${this.tableName}.${resolved}`;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
const aggregateExpr = func === 'COUNT' ? `COUNT(${aggregateColumn})` : `${func}(${aggregateColumn})`;
|
|
1187
|
+
const { sql, params } = this._buildGroupedAggregateQuery(aggregateExpr);
|
|
1188
|
+
const result = await this.dal.query(sql, params);
|
|
1189
|
+
const resultMap = new Map();
|
|
1190
|
+
for (const row of result.rows) {
|
|
1191
|
+
const key = String(row.group_key);
|
|
1192
|
+
const value = typeof row.aggregate_value === 'number'
|
|
1193
|
+
? row.aggregate_value
|
|
1194
|
+
: Number(row.aggregate_value);
|
|
1195
|
+
resultMap.set(key, Number.isNaN(value) ? 0 : value);
|
|
1196
|
+
}
|
|
1197
|
+
return resultMap;
|
|
1198
|
+
}
|
|
1199
|
+
catch (error) {
|
|
1200
|
+
throw convertPostgreSQLError(error);
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Delete records matching the query.
|
|
1205
|
+
*
|
|
1206
|
+
* Requires at least one predicate, so an unfiltered builder cannot wipe the
|
|
1207
|
+
* table. On models with revision tracking this is a permanent hard delete and
|
|
1208
|
+
* must be requested explicitly with `{ purge: true }`; matching documents are
|
|
1209
|
+
* removed together with their archived revisions. Use `deleteAllRevisions()`
|
|
1210
|
+
* for the usual soft delete.
|
|
1211
|
+
*
|
|
1212
|
+
* @param options - Delete options
|
|
1213
|
+
* @returns Number of rows deleted
|
|
1214
|
+
*/
|
|
1215
|
+
async delete(options = {}) {
|
|
1216
|
+
const { sql, params } = this._buildDeleteQuery(options);
|
|
1217
|
+
try {
|
|
1218
|
+
const result = await this.dal.query(sql, params);
|
|
1219
|
+
return typeof result.rowCount === 'number' ? result.rowCount : 0;
|
|
1220
|
+
}
|
|
1221
|
+
catch (error) {
|
|
1222
|
+
throw convertPostgreSQLError(error);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
/**
|
|
1226
|
+
* Delete a record by ID, ignoring any predicates on this builder.
|
|
1227
|
+
*
|
|
1228
|
+
* On models with revision tracking this requires `{ purge: true }` and also
|
|
1229
|
+
* removes the document's archived revisions.
|
|
1230
|
+
*
|
|
1231
|
+
* @param id - Record ID
|
|
1232
|
+
* @param options - Delete options
|
|
1233
|
+
* @returns Number of rows deleted
|
|
1234
|
+
*/
|
|
1235
|
+
async deleteById(id, options = {}) {
|
|
1236
|
+
const hasRevisions = this._hasRevisionFields();
|
|
1237
|
+
if (hasRevisions) {
|
|
1238
|
+
this._assertPurgeAllowed(options, 'deleteById');
|
|
1239
|
+
}
|
|
1240
|
+
const query = hasRevisions
|
|
1241
|
+
? `DELETE FROM ${this.tableName} WHERE id = $1 OR _old_rev_of = $1`
|
|
1242
|
+
: `DELETE FROM ${this.tableName} WHERE id = $1`;
|
|
1243
|
+
try {
|
|
1244
|
+
const result = await this.dal.query(query, [id]);
|
|
1245
|
+
return typeof result.rowCount === 'number' ? result.rowCount : 0;
|
|
1246
|
+
}
|
|
1247
|
+
catch (error) {
|
|
1248
|
+
throw convertPostgreSQLError(error);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
/**
|
|
1252
|
+
* Whether the model backing this builder carries revision fields.
|
|
1253
|
+
* @private
|
|
1254
|
+
*/
|
|
1255
|
+
_hasRevisionFields() {
|
|
1256
|
+
const schema = this.modelClass?.schema;
|
|
1257
|
+
return Boolean(schema && Object.prototype.hasOwnProperty.call(schema, '_revID'));
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Throw unless a hard delete on a revision-tracked table was requested explicitly.
|
|
1261
|
+
* @private
|
|
1262
|
+
*/
|
|
1263
|
+
_assertPurgeAllowed(options, method) {
|
|
1264
|
+
if (options?.purge === true) {
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
throw new Error(`QueryBuilder.${method} refused to hard-delete from '${this.tableName}', which uses ` +
|
|
1268
|
+
'revision tracking; this would permanently erase revision history. Use ' +
|
|
1269
|
+
'deleteAllRevisions(user) to soft-delete, or pass { purge: true } to permanently ' +
|
|
1270
|
+
'remove the matching documents and all of their revisions.');
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Add a WHERE condition
|
|
1274
|
+
* @param field - Field name
|
|
1275
|
+
* @param operator - Comparison operator
|
|
1276
|
+
* @param value - Comparison value
|
|
1277
|
+
* @param [options] - Predicate options
|
|
1278
|
+
* @returns {Object} Predicate descriptor
|
|
1279
|
+
* @private
|
|
1280
|
+
*/
|
|
1281
|
+
_addWhereCondition(field, operator, value, options = {}) {
|
|
1282
|
+
const predicate = this._createPredicate(field, operator, value, options);
|
|
1283
|
+
this._where.push(predicate);
|
|
1284
|
+
return predicate;
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* Add a predicate against a column on a joined relation. This will ensure the
|
|
1288
|
+
* relation is joined and apply a WHERE clause to the related table using
|
|
1289
|
+
* camelCase field names.
|
|
1290
|
+
*
|
|
1291
|
+
* @param relationName - Relation key from the manifest
|
|
1292
|
+
* @param field - CamelCase field on the related model
|
|
1293
|
+
* @param operator - Comparison operator (defaults to '=')
|
|
1294
|
+
* @param value - Comparison value
|
|
1295
|
+
*/
|
|
1296
|
+
whereRelated(relationName, field, operator, value) {
|
|
1297
|
+
const joinInfo = this._getJoinInfo(relationName);
|
|
1298
|
+
if (!joinInfo) {
|
|
1299
|
+
debug.db(`Warning: Unknown relation '${relationName}' for table '${this.tableName}'`);
|
|
1300
|
+
return this;
|
|
1301
|
+
}
|
|
1302
|
+
if (!this._simpleJoins || !this._simpleJoins[relationName]) {
|
|
1303
|
+
this._addSimpleJoin(relationName);
|
|
1304
|
+
}
|
|
1305
|
+
const column = `${joinInfo.table}.${this._normalizeColumnName(field)}`;
|
|
1306
|
+
this._addWhereCondition(column, operator, value);
|
|
1307
|
+
return this;
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* Create a predicate descriptor without mutating the WHERE clause
|
|
1311
|
+
* @param field - Field reference (optionally qualified)
|
|
1312
|
+
* @param operator - Comparison operator
|
|
1313
|
+
* @param value - Comparison value
|
|
1314
|
+
* @param options - Predicate options
|
|
1315
|
+
* @param [options.serializeValue] - Serializer for stored value
|
|
1316
|
+
* @param [options.cast] - Cast to append to placeholder (e.g., 'jsonb')
|
|
1317
|
+
* @param [options.valueTransform] - Custom placeholder transformer
|
|
1318
|
+
* @returns {Object} Predicate descriptor
|
|
1319
|
+
* @private
|
|
1320
|
+
*/
|
|
1321
|
+
_createPredicate(field, operator, value, options = {}) {
|
|
1322
|
+
let effectiveOperator = operator;
|
|
1323
|
+
if (value === null) {
|
|
1324
|
+
if (operator === '=') {
|
|
1325
|
+
effectiveOperator = 'IS';
|
|
1326
|
+
}
|
|
1327
|
+
else if (operator === '!=') {
|
|
1328
|
+
effectiveOperator = 'IS NOT';
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
const { table: explicitTable, column } = this._splitFieldReference(field);
|
|
1332
|
+
const tableReference = options.table || explicitTable || null;
|
|
1333
|
+
const resolvedColumn = this._resolvePredicateColumn(tableReference, column);
|
|
1334
|
+
const predicate = {
|
|
1335
|
+
type: 'basic',
|
|
1336
|
+
column: resolvedColumn,
|
|
1337
|
+
operator: effectiveOperator,
|
|
1338
|
+
};
|
|
1339
|
+
if (tableReference) {
|
|
1340
|
+
predicate.table = tableReference;
|
|
1341
|
+
}
|
|
1342
|
+
const serializer = typeof options.serializeValue === 'function' ? options.serializeValue : null;
|
|
1343
|
+
const storedValue = serializer ? serializer(value) : value;
|
|
1344
|
+
if ((operator === 'IS' || operator === 'IS NOT') && storedValue === null) {
|
|
1345
|
+
predicate.value = null;
|
|
1346
|
+
return predicate;
|
|
1347
|
+
}
|
|
1348
|
+
if (storedValue !== undefined) {
|
|
1349
|
+
predicate.value = storedValue;
|
|
1350
|
+
if (typeof options.valueTransform === 'function') {
|
|
1351
|
+
predicate.valueTransform = options.valueTransform;
|
|
1352
|
+
}
|
|
1353
|
+
else if (options.cast) {
|
|
1354
|
+
predicate.valueTransform = placeholder => `${placeholder}::${options.cast}`;
|
|
1355
|
+
}
|
|
1356
|
+
else {
|
|
1357
|
+
predicate.valueTransform = placeholder => placeholder;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
return predicate;
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* Predicate that matches no rows (e.g. membership in an empty set).
|
|
1364
|
+
* @private
|
|
1365
|
+
*/
|
|
1366
|
+
_createMatchNothingPredicate() {
|
|
1367
|
+
return { type: 'raw', sql: 'FALSE' };
|
|
1368
|
+
}
|
|
1369
|
+
_resolvePredicateColumn(tableReference, column) {
|
|
1370
|
+
if (typeof column !== 'string' || column === '*' || /[()\s]/.test(column)) {
|
|
1371
|
+
return column;
|
|
1372
|
+
}
|
|
1373
|
+
const normalizedTable = tableReference || null;
|
|
1374
|
+
const schemaNamespace = this.dal && typeof this.dal.schemaNamespace === 'string' ? this.dal.schemaNamespace : '';
|
|
1375
|
+
const unprefixedTableName = schemaNamespace && this.tableName.startsWith(schemaNamespace)
|
|
1376
|
+
? this.tableName.slice(schemaNamespace.length)
|
|
1377
|
+
: this.tableName;
|
|
1378
|
+
const isBaseTable = normalizedTable === null ||
|
|
1379
|
+
normalizedTable === this.tableName ||
|
|
1380
|
+
normalizedTable === unprefixedTableName;
|
|
1381
|
+
if (isBaseTable) {
|
|
1382
|
+
return this._resolveFieldName(column);
|
|
1383
|
+
}
|
|
1384
|
+
return column;
|
|
1385
|
+
}
|
|
1386
|
+
_splitFieldReference(field) {
|
|
1387
|
+
if (typeof field !== 'string') {
|
|
1388
|
+
return { table: null, column: field };
|
|
1389
|
+
}
|
|
1390
|
+
const dotIndex = field.indexOf('.');
|
|
1391
|
+
if (dotIndex === -1) {
|
|
1392
|
+
return { table: null, column: field };
|
|
1393
|
+
}
|
|
1394
|
+
const table = field.slice(0, dotIndex);
|
|
1395
|
+
const column = field.slice(dotIndex + 1);
|
|
1396
|
+
return { table, column };
|
|
1397
|
+
}
|
|
1398
|
+
_buildWhereClause({ qualifyColumns = false } = {}) {
|
|
1399
|
+
if (!Array.isArray(this._where) || this._where.length === 0) {
|
|
1400
|
+
this._params = [];
|
|
1401
|
+
this._paramIndex = 1;
|
|
1402
|
+
return { sql: '', params: [] };
|
|
1403
|
+
}
|
|
1404
|
+
const params = [];
|
|
1405
|
+
let nextIndex = 1;
|
|
1406
|
+
const context = {
|
|
1407
|
+
qualifyColumns,
|
|
1408
|
+
defaultTable: this.tableName,
|
|
1409
|
+
getNextPlaceholder: () => `$${nextIndex++}`,
|
|
1410
|
+
params,
|
|
1411
|
+
};
|
|
1412
|
+
const fragments = [];
|
|
1413
|
+
for (const predicate of this._where) {
|
|
1414
|
+
const fragment = this._renderPredicate(predicate, context);
|
|
1415
|
+
if (fragment) {
|
|
1416
|
+
fragments.push(fragment);
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
this._params = params;
|
|
1420
|
+
this._paramIndex = nextIndex;
|
|
1421
|
+
return {
|
|
1422
|
+
sql: fragments.join(' AND '),
|
|
1423
|
+
params,
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
_renderPredicate(predicate, context) {
|
|
1427
|
+
if (!predicate) {
|
|
1428
|
+
return '';
|
|
1429
|
+
}
|
|
1430
|
+
if (predicate.type === 'group') {
|
|
1431
|
+
const conjunction = predicate.conjunction || 'AND';
|
|
1432
|
+
const inner = [];
|
|
1433
|
+
for (const child of predicate.predicates || []) {
|
|
1434
|
+
const rendered = this._renderPredicate(child, context);
|
|
1435
|
+
if (rendered) {
|
|
1436
|
+
inner.push(rendered);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
if (inner.length === 0) {
|
|
1440
|
+
return '';
|
|
1441
|
+
}
|
|
1442
|
+
return `(${inner.join(` ${conjunction} `)})`;
|
|
1443
|
+
}
|
|
1444
|
+
if (predicate.type === 'raw' && predicate.sql) {
|
|
1445
|
+
// Raw predicates may contribute their own parameters
|
|
1446
|
+
if (Array.isArray(predicate.values)) {
|
|
1447
|
+
for (const value of predicate.values) {
|
|
1448
|
+
context.params.push(value);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
return predicate.sql;
|
|
1452
|
+
}
|
|
1453
|
+
return this._renderBasicPredicate(predicate, context);
|
|
1454
|
+
}
|
|
1455
|
+
_renderBasicPredicate(predicate, context) {
|
|
1456
|
+
const columnSql = this._qualifyColumn(predicate, context);
|
|
1457
|
+
const { operator } = predicate;
|
|
1458
|
+
if ((operator === 'IS' || operator === 'IS NOT') && predicate.value === null) {
|
|
1459
|
+
return `${columnSql} ${operator} NULL`;
|
|
1460
|
+
}
|
|
1461
|
+
// PostgreSQL IS predicates require boolean keywords, not placeholders.
|
|
1462
|
+
if ((operator === 'IS' || operator === 'IS NOT') && typeof predicate.value === 'boolean') {
|
|
1463
|
+
return `${columnSql} ${operator} ${predicate.value ? 'TRUE' : 'FALSE'}`;
|
|
1464
|
+
}
|
|
1465
|
+
if (predicate.value === undefined) {
|
|
1466
|
+
return `${columnSql} ${operator}`;
|
|
1467
|
+
}
|
|
1468
|
+
const placeholder = context.getNextPlaceholder();
|
|
1469
|
+
context.params.push(predicate.value);
|
|
1470
|
+
const transform = typeof predicate.valueTransform === 'function' ? predicate.valueTransform : value => value;
|
|
1471
|
+
const valueSql = transform(placeholder);
|
|
1472
|
+
return `${columnSql} ${operator} ${valueSql}`;
|
|
1473
|
+
}
|
|
1474
|
+
_qualifyColumn(predicate, context) {
|
|
1475
|
+
const { column } = predicate;
|
|
1476
|
+
if (!column || typeof column !== 'string') {
|
|
1477
|
+
return column;
|
|
1478
|
+
}
|
|
1479
|
+
if (predicate.table) {
|
|
1480
|
+
return `${predicate.table}.${column}`;
|
|
1481
|
+
}
|
|
1482
|
+
if (!context.qualifyColumns) {
|
|
1483
|
+
return column;
|
|
1484
|
+
}
|
|
1485
|
+
if (column.includes('.') || column.includes('(')) {
|
|
1486
|
+
return column;
|
|
1487
|
+
}
|
|
1488
|
+
return `${context.defaultTable}.${column}`;
|
|
1489
|
+
}
|
|
1490
|
+
_isRevisionFilterPredicate(predicate) {
|
|
1491
|
+
if (!predicate) {
|
|
1492
|
+
return false;
|
|
1493
|
+
}
|
|
1494
|
+
if (predicate.type === 'basic') {
|
|
1495
|
+
return predicate.column === '_old_rev_of' || predicate.column === '_rev_deleted';
|
|
1496
|
+
}
|
|
1497
|
+
return false;
|
|
1498
|
+
}
|
|
1499
|
+
/**
|
|
1500
|
+
* Build SELECT query
|
|
1501
|
+
* @returns {{ sql: string, params: Array }} SQL query and parameters
|
|
1502
|
+
* @private
|
|
1503
|
+
*/
|
|
1504
|
+
_buildSelectQuery() {
|
|
1505
|
+
let selectClause = this._select.join(', ');
|
|
1506
|
+
// Replace SELECT * with explicit column list to exclude sensitive fields
|
|
1507
|
+
// (e.g., passwords). For models without sensitive fields, getColumnNames()
|
|
1508
|
+
// returns all columns, equivalent to SELECT *.
|
|
1509
|
+
if (this._select.includes('*')) {
|
|
1510
|
+
const columns = this.modelClass.getColumnNames(this._includeSensitive);
|
|
1511
|
+
const mainTableColumns = columns.map(col => `${this.tableName}.${col}`);
|
|
1512
|
+
if (this._joins.length > 0) {
|
|
1513
|
+
selectClause = mainTableColumns.join(', ');
|
|
1514
|
+
// Add columns from simple joins with prefixed aliases
|
|
1515
|
+
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(', ');
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
else {
|
|
1537
|
+
// No joins, just list the columns
|
|
1538
|
+
selectClause = mainTableColumns.join(', ');
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
let query = `SELECT ${selectClause} FROM ${this.tableName}`;
|
|
1542
|
+
if (this._joins.length > 0) {
|
|
1543
|
+
query += ' ' + this._joins.join(' ');
|
|
1544
|
+
}
|
|
1545
|
+
const where = this._buildWhereClause({ qualifyColumns: true });
|
|
1546
|
+
if (where.sql) {
|
|
1547
|
+
query += ' WHERE ' + where.sql;
|
|
1548
|
+
}
|
|
1549
|
+
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(', ');
|
|
1557
|
+
}
|
|
1558
|
+
// LIMIT/OFFSET are bound as parameters rather than interpolated.
|
|
1559
|
+
const params = [...where.params];
|
|
1560
|
+
if (this._limit !== null) {
|
|
1561
|
+
params.push(this._limit);
|
|
1562
|
+
query += ` LIMIT $${params.length}`;
|
|
1563
|
+
}
|
|
1564
|
+
if (this._offset !== null) {
|
|
1565
|
+
params.push(this._offset);
|
|
1566
|
+
query += ` OFFSET $${params.length}`;
|
|
1567
|
+
}
|
|
1568
|
+
return { sql: query, params };
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Build COUNT query
|
|
1572
|
+
* @returns {{ sql: string, params: Array }} SQL query and parameters
|
|
1573
|
+
* @private
|
|
1574
|
+
*/
|
|
1575
|
+
_buildCountQuery() {
|
|
1576
|
+
let query = `SELECT COUNT(*) as count FROM ${this.tableName}`;
|
|
1577
|
+
if (this._joins.length > 0) {
|
|
1578
|
+
query += ` ${this._joins.join(' ')}`;
|
|
1579
|
+
}
|
|
1580
|
+
const where = this._buildWhereClause({ qualifyColumns: this._joins.length > 0 });
|
|
1581
|
+
if (where.sql) {
|
|
1582
|
+
query += ' WHERE ' + where.sql;
|
|
1583
|
+
}
|
|
1584
|
+
return { sql: query, params: where.params };
|
|
1585
|
+
}
|
|
1586
|
+
/**
|
|
1587
|
+
* Build an aggregate query (`AVG`, `COUNT`, etc.) for the current predicates.
|
|
1588
|
+
*
|
|
1589
|
+
* @param func - Aggregate function keyword.
|
|
1590
|
+
* @param column - Fully qualified column expression.
|
|
1591
|
+
* @returns SQL fragment plus bound params.
|
|
1592
|
+
*/
|
|
1593
|
+
_buildAggregateQuery(func, column) {
|
|
1594
|
+
let query = `SELECT ${func}(${column}) as value FROM ${this.tableName}`;
|
|
1595
|
+
const where = this._buildWhereClause({ qualifyColumns: true });
|
|
1596
|
+
if (where.sql) {
|
|
1597
|
+
query += ' WHERE ' + where.sql;
|
|
1598
|
+
}
|
|
1599
|
+
return { sql: query, params: where.params };
|
|
1600
|
+
}
|
|
1601
|
+
/**
|
|
1602
|
+
* Build a grouped aggregate query with GROUP BY clause.
|
|
1603
|
+
*
|
|
1604
|
+
* @param aggregateExpr - Full aggregate expression (e.g., 'COUNT(*)', 'AVG(star_rating)')
|
|
1605
|
+
* @returns SQL fragment plus bound params
|
|
1606
|
+
* @private
|
|
1607
|
+
*/
|
|
1608
|
+
_buildGroupedAggregateQuery(aggregateExpr) {
|
|
1609
|
+
if (this._groupBy.length === 0) {
|
|
1610
|
+
throw new Error('_buildGroupedAggregateQuery requires _groupBy to be set');
|
|
1611
|
+
}
|
|
1612
|
+
// Use the first GROUP BY field as the group key in the result
|
|
1613
|
+
const groupByField = this._groupBy[0];
|
|
1614
|
+
let query = `SELECT ${groupByField} as group_key, ${aggregateExpr} as aggregate_value FROM ${this.tableName}`;
|
|
1615
|
+
const where = this._buildWhereClause({ qualifyColumns: true });
|
|
1616
|
+
if (where.sql) {
|
|
1617
|
+
query += ' WHERE ' + where.sql;
|
|
1618
|
+
}
|
|
1619
|
+
query += ' GROUP BY ' + this._groupBy.join(', ');
|
|
1620
|
+
return { sql: query, params: where.params };
|
|
1621
|
+
}
|
|
1622
|
+
/**
|
|
1623
|
+
* Build DELETE query
|
|
1624
|
+
* @returns {{ sql: string, params: Array }} SQL query and parameters
|
|
1625
|
+
* @private
|
|
1626
|
+
*/
|
|
1627
|
+
_buildDeleteQuery(options = {}) {
|
|
1628
|
+
const where = this._buildWhereClause();
|
|
1629
|
+
if (!where.sql) {
|
|
1630
|
+
throw new Error('QueryBuilder.delete requires a WHERE clause to avoid deleting every row in the table.');
|
|
1631
|
+
}
|
|
1632
|
+
if (this._hasRevisionFields()) {
|
|
1633
|
+
this._assertPurgeAllowed(options, 'delete');
|
|
1634
|
+
// Purge the matched documents together with their archived revisions so
|
|
1635
|
+
// no orphaned history rows are left behind.
|
|
1636
|
+
const query = `WITH purged AS (SELECT id FROM ${this.tableName} WHERE ${where.sql}) ` +
|
|
1637
|
+
`DELETE FROM ${this.tableName} ` +
|
|
1638
|
+
'WHERE id IN (SELECT id FROM purged) OR _old_rev_of IN (SELECT id FROM purged)';
|
|
1639
|
+
return { sql: query, params: where.params };
|
|
1640
|
+
}
|
|
1641
|
+
return { sql: `DELETE FROM ${this.tableName} WHERE ${where.sql}`, params: where.params };
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* Atomically increment a numeric column on rows matching the current predicate.
|
|
1645
|
+
*
|
|
1646
|
+
* @param field Model field (resolved to a DB column) to increment
|
|
1647
|
+
* @param amount Increment step (default: 1)
|
|
1648
|
+
* @param options Optional returning clause
|
|
1649
|
+
* @returns Rows matched/returned plus affected row count.
|
|
1650
|
+
*/
|
|
1651
|
+
async increment(field, amount = 1, options = {}) {
|
|
1652
|
+
if (!Number.isFinite(amount)) {
|
|
1653
|
+
throw new TypeError('QueryBuilder.increment amount must be a finite number.');
|
|
1654
|
+
}
|
|
1655
|
+
if (this._joins.length > 0) {
|
|
1656
|
+
throw new Error('QueryBuilder.increment does not support joined queries.');
|
|
1657
|
+
}
|
|
1658
|
+
const dbField = this._resolveFieldName(field);
|
|
1659
|
+
this._assertResolvedField(dbField);
|
|
1660
|
+
if (typeof dbField !== 'string') {
|
|
1661
|
+
throw new TypeError('QueryBuilder.increment requires a string column reference.');
|
|
1662
|
+
}
|
|
1663
|
+
const schema = this.modelClass.schema;
|
|
1664
|
+
const fieldMappings = this.modelClass
|
|
1665
|
+
._fieldMappings;
|
|
1666
|
+
let schemaFieldName = null;
|
|
1667
|
+
if (typeof field === 'string') {
|
|
1668
|
+
if (schema && field in schema) {
|
|
1669
|
+
schemaFieldName = field;
|
|
1670
|
+
}
|
|
1671
|
+
if (!schemaFieldName && fieldMappings instanceof Map) {
|
|
1672
|
+
for (const [schemaKey, dbKey] of fieldMappings.entries()) {
|
|
1673
|
+
if (dbKey === dbField || dbKey === field) {
|
|
1674
|
+
schemaFieldName = schemaKey;
|
|
1675
|
+
break;
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
if (schema && schemaFieldName) {
|
|
1681
|
+
const columnDef = schema[schemaFieldName];
|
|
1682
|
+
if (!(columnDef instanceof NumberType)) {
|
|
1683
|
+
throw new TypeError(`QueryBuilder.increment requires a numeric schema field; '${schemaFieldName}' is not numeric.`);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
else {
|
|
1687
|
+
throw new TypeError(`QueryBuilder.increment could not resolve schema metadata for field '${field}'.`);
|
|
1688
|
+
}
|
|
1689
|
+
const where = this._buildWhereClause();
|
|
1690
|
+
if (!where.sql) {
|
|
1691
|
+
throw new Error('QueryBuilder.increment requires a WHERE clause to avoid full-table updates.');
|
|
1692
|
+
}
|
|
1693
|
+
const params = [...where.params];
|
|
1694
|
+
const amountPlaceholder = `$${params.length + 1}`;
|
|
1695
|
+
params.push(amount);
|
|
1696
|
+
let query = `UPDATE ${this.tableName} SET ${dbField} = ${dbField} + ${amountPlaceholder} WHERE ${where.sql}`;
|
|
1697
|
+
const returningColumns = Array.isArray(options.returning) ? options.returning : [];
|
|
1698
|
+
if (returningColumns.length > 0) {
|
|
1699
|
+
const resolvedColumns = returningColumns.map(column => {
|
|
1700
|
+
const resolved = this._resolveFieldName(column);
|
|
1701
|
+
this._assertResolvedField(resolved);
|
|
1702
|
+
if (typeof resolved !== 'string') {
|
|
1703
|
+
throw new TypeError('QueryBuilder.increment RETURNING requires string column references.');
|
|
1704
|
+
}
|
|
1705
|
+
return resolved;
|
|
1706
|
+
});
|
|
1707
|
+
query += ` RETURNING ${resolvedColumns.join(', ')}`;
|
|
1708
|
+
}
|
|
1709
|
+
const result = await this.dal.query(query, params);
|
|
1710
|
+
const rows = returningColumns.length > 0
|
|
1711
|
+
? result.rows.map(row => remapRowToCamelCase(row, fieldMappings))
|
|
1712
|
+
: [];
|
|
1713
|
+
return {
|
|
1714
|
+
rowCount: result.rowCount ?? result.rows.length,
|
|
1715
|
+
rows,
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
/**
|
|
1719
|
+
* Get a random sample of records
|
|
1720
|
+
*
|
|
1721
|
+
* @param count - Number of records to sample
|
|
1722
|
+
* @returns {Promise<Array>} Array of sampled records
|
|
1723
|
+
*/
|
|
1724
|
+
async sample(count = 1) {
|
|
1725
|
+
// Add ORDER BY RANDOM() and LIMIT to get random sample
|
|
1726
|
+
this._orderBy = ['RANDOM()'];
|
|
1727
|
+
this._limit = assertRowCount(count, 'LIMIT');
|
|
1728
|
+
const results = await this.run();
|
|
1729
|
+
return results;
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
export { QueryBuilder, normalizeSortDirection };
|
|
1733
|
+
export default QueryBuilder;
|
|
1734
|
+
//# sourceMappingURL=query-builder.js.map
|