turbine-orm 0.18.0 → 0.19.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/dist/cjs/query.js DELETED
@@ -1,2711 +0,0 @@
1
- "use strict";
2
- /**
3
- * turbine-orm — Query builder
4
- *
5
- * Each table accessor (db.users, db.posts, etc.) returns a QueryInterface<T>
6
- * that builds parameterized SQL and executes it through the connection pool.
7
- *
8
- * Nested relations use json_build_object + json_agg subqueries for single-query
9
- * resolution — a PostgreSQL-native approach that eliminates N+1 query patterns.
10
- *
11
- * Schema-driven: all column names, types, and relations come from introspected
12
- * metadata — nothing is hardcoded.
13
- */
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.QueryInterface = void 0;
16
- exports.quoteIdent = quoteIdent;
17
- exports.fnv1a64Hex = fnv1a64Hex;
18
- exports.sqlToPreparedName = sqlToPreparedName;
19
- const errors_js_1 = require("./errors.js");
20
- const schema_js_1 = require("./schema.js");
21
- // ---------------------------------------------------------------------------
22
- // Identifier quoting — prevents SQL injection via table/column names
23
- // ---------------------------------------------------------------------------
24
- /**
25
- * Quote a SQL identifier (table name, column name) using Postgres double-quote
26
- * rules: wrap in double quotes, escape internal double quotes by doubling them.
27
- *
28
- * @example
29
- * quoteIdent('users') → '"users"'
30
- * quoteIdent('my"table') → '"my""table"'
31
- * quoteIdent('user name') → '"user name"'
32
- */
33
- function quoteIdent(name) {
34
- return `"${name.replace(/"/g, '""')}"`;
35
- }
36
- /**
37
- * Escape single quotes for use as string keys in json_build_object().
38
- * Doubles single quotes per SQL quoting rules.
39
- */
40
- function escSingleQuote(s) {
41
- return s.replace(/'/g, "''");
42
- }
43
- /**
44
- * Escape LIKE pattern metacharacters: %, _, and \.
45
- * Must be used with `ESCAPE '\'` in the LIKE clause.
46
- */
47
- function escapeLike(value) {
48
- return value.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_');
49
- }
50
- /** Known operator keys — used to detect operator objects vs plain values */
51
- const OPERATOR_KEYS = new Set([
52
- 'gt',
53
- 'gte',
54
- 'lt',
55
- 'lte',
56
- 'not',
57
- 'in',
58
- 'notIn',
59
- 'contains',
60
- 'startsWith',
61
- 'endsWith',
62
- 'mode',
63
- ]);
64
- /** Check if a value is a where operator object (has at least one known operator key) */
65
- function isWhereOperator(value) {
66
- if (value === null ||
67
- value === undefined ||
68
- typeof value !== 'object' ||
69
- Array.isArray(value) ||
70
- value instanceof Date) {
71
- return false;
72
- }
73
- const keys = Object.keys(value);
74
- return keys.length > 0 && keys.every((k) => OPERATOR_KEYS.has(k));
75
- }
76
- /** Known atomic-update operator keys — used to detect operator objects vs plain JSON values */
77
- const UPDATE_OPERATOR_KEYS = new Set(['set', 'increment', 'decrement', 'multiply', 'divide']);
78
- /** Known JSONB operator keys */
79
- const JSONB_OPERATOR_KEYS = new Set(['path', 'equals', 'contains', 'hasKey']);
80
- /**
81
- * JSONB operator keys that are *unique* to {@link JsonFilter} — they cannot
82
- * appear in any other where-filter shape, so the presence of one of these is
83
- * an unambiguous signal that the user meant a JSON filter. Used by the
84
- * strict-validation path so that `{ contains: 'foo' }` (which is also a valid
85
- * `WhereOperator` for LIKE) is not misclassified.
86
- */
87
- const JSONB_UNIQUE_KEYS = new Set(['path', 'equals', 'hasKey']);
88
- /** Check if a value is a JSONB filter object */
89
- function isJsonFilter(value) {
90
- if (value === null ||
91
- value === undefined ||
92
- typeof value !== 'object' ||
93
- Array.isArray(value) ||
94
- value instanceof Date) {
95
- return false;
96
- }
97
- const keys = Object.keys(value);
98
- return keys.length > 0 && keys.some((k) => JSONB_OPERATOR_KEYS.has(k));
99
- }
100
- /**
101
- * Returns the first JSON-unique key found in `value`, or `null` if none.
102
- * Used to drive the strict-validation error message.
103
- */
104
- function findJsonUniqueKey(value) {
105
- for (const k of Object.keys(value)) {
106
- if (JSONB_UNIQUE_KEYS.has(k))
107
- return k;
108
- }
109
- return null;
110
- }
111
- /** Known Array operator keys */
112
- const ARRAY_OPERATOR_KEYS = new Set(['has', 'hasEvery', 'hasSome', 'isEmpty']);
113
- /**
114
- * Array operator keys that are *unique* to {@link ArrayFilter}. None of the
115
- * array operators currently overlap with `WhereOperator` or `JsonFilter`, so
116
- * this set equals {@link ARRAY_OPERATOR_KEYS}; it is kept as a separate
117
- * constant so a future overlap (e.g. a `contains` for arrays) is easy to
118
- * carve out.
119
- */
120
- const ARRAY_UNIQUE_KEYS = new Set(['has', 'hasEvery', 'hasSome', 'isEmpty']);
121
- /** Check if a value is an Array filter object */
122
- function isArrayFilter(value) {
123
- if (value === null ||
124
- value === undefined ||
125
- typeof value !== 'object' ||
126
- Array.isArray(value) ||
127
- value instanceof Date) {
128
- return false;
129
- }
130
- const keys = Object.keys(value);
131
- return keys.length > 0 && keys.some((k) => ARRAY_OPERATOR_KEYS.has(k));
132
- }
133
- /**
134
- * Returns the first array-unique key found in `value`, or `null` if none.
135
- * Used to drive the strict-validation error message.
136
- */
137
- function findArrayUniqueKey(value) {
138
- for (const k of Object.keys(value)) {
139
- if (ARRAY_UNIQUE_KEYS.has(k))
140
- return k;
141
- }
142
- return null;
143
- }
144
- // ---------------------------------------------------------------------------
145
- // LRU cache — bounded SQL template cache to prevent memory leaks
146
- // ---------------------------------------------------------------------------
147
- /**
148
- * Simple LRU (Least Recently Used) cache with a fixed maximum size.
149
- * When the cache exceeds maxSize, the oldest (least recently used) entry is evicted.
150
- * Uses Map insertion order for O(1) eviction.
151
- */
152
- class LRUCache {
153
- maxSize;
154
- cache = new Map();
155
- constructor(maxSize) {
156
- this.maxSize = maxSize;
157
- }
158
- get(key) {
159
- const value = this.cache.get(key);
160
- if (value !== undefined) {
161
- // Move to end (most recently used)
162
- this.cache.delete(key);
163
- this.cache.set(key, value);
164
- }
165
- return value;
166
- }
167
- set(key, value) {
168
- if (this.cache.has(key)) {
169
- this.cache.delete(key);
170
- }
171
- else if (this.cache.size >= this.maxSize) {
172
- // Delete oldest (first) entry
173
- const firstKey = this.cache.keys().next().value;
174
- if (firstKey !== undefined)
175
- this.cache.delete(firstKey);
176
- }
177
- this.cache.set(key, value);
178
- }
179
- get size() {
180
- return this.cache.size;
181
- }
182
- }
183
- /**
184
- * FNV-1a 64-bit hash returning 16 lowercase hex chars.
185
- * Single-loop string iteration. Uses BigInt for 64-bit math.
186
- *
187
- * @internal Exported for testing only.
188
- */
189
- function fnv1a64Hex(s) {
190
- // FNV-1a offset basis and prime for 64-bit
191
- let hash = 0xcbf29ce484222325n;
192
- const prime = 0x100000001b3n;
193
- const mask = 0xffffffffffffffffn; // 64-bit mask
194
- for (let i = 0; i < s.length; i++) {
195
- hash ^= BigInt(s.charCodeAt(i));
196
- hash = (hash * prime) & mask;
197
- }
198
- return hash.toString(16).padStart(16, '0');
199
- }
200
- /**
201
- * Derive a prepared-statement name from a SQL string.
202
- * Format: `t_<16hex>` — always 18 chars, well under NAMEDATALEN (63).
203
- *
204
- * @internal Exported for testing only.
205
- */
206
- function sqlToPreparedName(sql) {
207
- return `t_${fnv1a64Hex(sql)}`;
208
- }
209
- class QueryInterface {
210
- pool;
211
- table;
212
- schema;
213
- tableMeta;
214
- /** SQL template cache: cacheKey → SqlCacheEntry (sql + prepared statement name) */
215
- sqlTemplateCache = new LRUCache(1000);
216
- middlewares;
217
- defaultLimit;
218
- warnOnUnlimited;
219
- preparedStatementsEnabled;
220
- sqlCacheEnabled;
221
- /**
222
- * Tracks tables that have already triggered an unlimited-query warning so
223
- * the user is not spammed once per row. Per-instance state — each
224
- * QueryInterface is bound to a single table, so this set will only ever
225
- * contain at most one entry, but using a Set keeps the API consistent with
226
- * the audit's "Set<string>" guidance and leaves room for future
227
- * cross-table sharing.
228
- */
229
- warnedTables = new Set();
230
- /** Cache hit/miss counters for diagnostics */
231
- cacheHits = 0;
232
- cacheMisses = 0;
233
- /** Pre-computed column type lookups (avoids linear scans per query) */
234
- columnPgTypeMap;
235
- columnArrayTypeMap;
236
- constructor(pool, table, schema, middlewares, options) {
237
- this.pool = pool;
238
- this.table = table;
239
- this.schema = schema;
240
- const meta = schema.tables[table];
241
- if (!meta) {
242
- throw new errors_js_1.ValidationError(`[turbine] Unknown table "${table}". Available: ${Object.keys(schema.tables).join(', ')}`);
243
- }
244
- this.tableMeta = meta;
245
- this.middlewares = middlewares ?? [];
246
- this.defaultLimit = options?.defaultLimit;
247
- // Default to ON: surfacing accidental full-table scans is more valuable
248
- // than the (small) risk of noisy logs. Callers explicitly opt out with
249
- // `warnOnUnlimited: false`.
250
- this.warnOnUnlimited = options?.warnOnUnlimited !== false;
251
- this.preparedStatementsEnabled = options?.preparedStatements ?? true;
252
- this.sqlCacheEnabled = options?.sqlCache !== false;
253
- // Pre-compute column type lookup maps (TASK-26)
254
- this.columnPgTypeMap = new Map();
255
- this.columnArrayTypeMap = new Map();
256
- for (const col of this.tableMeta.columns) {
257
- this.columnPgTypeMap.set(col.name, col.pgType);
258
- this.columnArrayTypeMap.set(col.name, col.pgArrayType);
259
- }
260
- }
261
- /**
262
- * Return cache hit/miss statistics for this QueryInterface instance.
263
- * Useful for monitoring and benchmarking.
264
- */
265
- cacheStats() {
266
- const total = this.cacheHits + this.cacheMisses;
267
- return {
268
- hits: this.cacheHits,
269
- misses: this.cacheMisses,
270
- hitRate: total > 0 ? this.cacheHits / total : 0,
271
- size: this.sqlTemplateCache.size,
272
- };
273
- }
274
- /**
275
- * Look up or build a SQL template in the cache.
276
- * On miss, calls `build()` to generate the SQL, stores the entry, and returns it.
277
- * On hit, increments counters and returns the cached entry.
278
- *
279
- * When `sqlCache` is disabled, always calls `build()` without caching.
280
- */
281
- acquireSql(cacheKey, build) {
282
- if (!this.sqlCacheEnabled) {
283
- const sql = build();
284
- this.cacheMisses++;
285
- return { sql, name: sqlToPreparedName(sql) };
286
- }
287
- const cached = this.sqlTemplateCache.get(cacheKey);
288
- if (cached) {
289
- this.cacheHits++;
290
- return cached;
291
- }
292
- const sql = build();
293
- const entry = { sql, name: sqlToPreparedName(sql) };
294
- this.sqlTemplateCache.set(cacheKey, entry);
295
- this.cacheMisses++;
296
- return entry;
297
- }
298
- /**
299
- * Reset the per-instance unlimited-query warning dedupe set.
300
- * Exposed for tests so a single test process can verify the warning fires
301
- * exactly once per table without bleeding state between assertions.
302
- */
303
- resetUnlimitedWarnings() {
304
- this.warnedTables.clear();
305
- }
306
- /**
307
- * Execute a pool.query with an optional timeout.
308
- * If timeout is set, races the query against a timer and rejects on expiry.
309
- * pg driver errors are translated to typed Turbine errors via wrapPgError.
310
- */
311
- async queryWithTimeout(sql, params, timeout, preparedName) {
312
- // Build the query argument — use object form with `name` for prepared
313
- // statements, or the plain (text, values) form otherwise.
314
- const usePrepared = preparedName && this.preparedStatementsEnabled;
315
- const exec = usePrepared
316
- ? this.pool.query({ name: preparedName, text: sql, values: params })
317
- : this.pool.query(sql, params);
318
- if (!timeout) {
319
- try {
320
- return await exec;
321
- }
322
- catch (err) {
323
- throw (0, errors_js_1.wrapPgError)(err);
324
- }
325
- }
326
- let timer;
327
- const timeoutPromise = new Promise((_, reject) => {
328
- timer = setTimeout(() => reject(new errors_js_1.TimeoutError(timeout)), timeout);
329
- });
330
- try {
331
- return await Promise.race([exec, timeoutPromise]);
332
- }
333
- catch (err) {
334
- throw (0, errors_js_1.wrapPgError)(err);
335
- }
336
- finally {
337
- clearTimeout(timer);
338
- }
339
- }
340
- /**
341
- * Execute a query through the middleware chain.
342
- * If no middlewares are registered, executes directly.
343
- *
344
- * Middleware can inspect and log query parameters, modify results after execution,
345
- * and measure timing. Note: query SQL is generated before middleware runs, so
346
- * modifying params.args in middleware will NOT affect the executed SQL.
347
- * To intercept queries before SQL generation, use the raw() method instead.
348
- */
349
- async executeWithMiddleware(action, args, executor) {
350
- if (this.middlewares.length === 0) {
351
- return executor();
352
- }
353
- const params = { model: this.table, action, args: { ...args } };
354
- // Build middleware chain
355
- let index = 0;
356
- const next = async (p) => {
357
- if (index < this.middlewares.length) {
358
- const mw = this.middlewares[index++];
359
- return mw(p, next);
360
- }
361
- // End of chain — execute the actual query
362
- return executor();
363
- };
364
- return next(params);
365
- }
366
- // -------------------------------------------------------------------------
367
- // findUnique
368
- // -------------------------------------------------------------------------
369
- async findUnique(args) {
370
- return this.executeWithMiddleware('findUnique', args, async () => {
371
- const deferred = this.buildFindUnique(args);
372
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
373
- return deferred.transform(result);
374
- });
375
- }
376
- buildFindUnique(args) {
377
- const columnsList = this.resolveColumns(args.select, args.omit);
378
- const whereObj = args.where;
379
- const colKey = columnsList ? columnsList.join(',') : '*';
380
- const whereFingerprint = this.fingerprintWhere(whereObj);
381
- const withFp = args.with ? this.withFingerprint(args.with) : '';
382
- const ck = `fu:${whereFingerprint}|c=${colKey}|w=${withFp}`;
383
- const params = [];
384
- // Check if all where values are simple (plain equality, no operators/null/OR)
385
- const whereKeys = Object.keys(whereObj).filter((k) => whereObj[k] !== undefined);
386
- const isSimpleWhere = !whereObj.OR &&
387
- !whereObj.AND &&
388
- !whereObj.NOT &&
389
- whereKeys.every((k) => {
390
- const v = whereObj[k];
391
- return v !== null && !isWhereOperator(v) && !this.tableMeta.relations[k];
392
- });
393
- // Simple path: plain equality, no operators/null/OR
394
- if (!args.with && isSimpleWhere) {
395
- const entry = this.acquireSql(ck, () => {
396
- const qt = quoteIdent(this.table);
397
- const tempParams = whereKeys.map((k) => whereObj[k]);
398
- const whereClauses = whereKeys.map((k, i) => `${this.toSqlColumn(k)} = $${i + 1}`);
399
- const whereSql = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
400
- const selectExpr = columnsList ? columnsList.map((c) => `${qt}.${quoteIdent(c)}`).join(', ') : `${qt}.*`;
401
- void tempParams; // params are positional, SQL is value-invariant
402
- return `SELECT ${selectExpr} FROM ${qt}${whereSql} LIMIT 1`;
403
- });
404
- // Collect params (same order as build)
405
- for (const k of whereKeys) {
406
- params.push(whereObj[k]);
407
- }
408
- return {
409
- sql: entry.sql,
410
- params,
411
- transform: (result) => {
412
- const row = result.rows[0];
413
- return row ? this.parseRow(row, this.table) : null;
414
- },
415
- tag: `${this.table}.findUnique`,
416
- preparedName: entry.name,
417
- };
418
- }
419
- // General path (with operators, null, OR, with clause)
420
- if (!args.with) {
421
- const entry = this.acquireSql(ck, () => {
422
- const freshParams = [];
423
- const clause = this.buildWhereClause(whereObj, freshParams);
424
- const whereSql = clause ? ` WHERE ${clause}` : '';
425
- const qt = quoteIdent(this.table);
426
- const selectExpr = columnsList ? columnsList.map((c) => `${qt}.${quoteIdent(c)}`).join(', ') : `${qt}.*`;
427
- return `SELECT ${selectExpr} FROM ${qt}${whereSql} LIMIT 1`;
428
- });
429
- // Collect params
430
- this.collectWhereParams(whereObj, params);
431
- return {
432
- sql: entry.sql,
433
- params,
434
- transform: (result) => {
435
- const row = result.rows[0];
436
- return row ? this.parseRow(row, this.table) : null;
437
- },
438
- tag: `${this.table}.findUnique`,
439
- preparedName: entry.name,
440
- };
441
- }
442
- // Nested queries with `with` clause.
443
- // The param order in the original code is:
444
- // 1. buildWhere pushes where params
445
- // 2. buildSelectWithRelations pushes relation params to same array
446
- // We must preserve this exact order.
447
- const entry = this.acquireSql(ck, () => {
448
- const freshParams = [];
449
- const clause = this.buildWhereClause(whereObj, freshParams);
450
- const whereSql = clause ? ` WHERE ${clause}` : '';
451
- const selectClause = this.buildSelectWithRelations(this.table, args.with, freshParams, columnsList);
452
- return `SELECT ${selectClause} FROM ${quoteIdent(this.table)}${whereSql} LIMIT 1`;
453
- });
454
- // Collect params in exact build order: where first, then with-clause relations
455
- this.collectWhereParams(whereObj, params);
456
- this.collectWithParams(args.with, params);
457
- return {
458
- sql: entry.sql,
459
- params,
460
- transform: (result) => {
461
- const row = result.rows[0];
462
- return row ? this.parseNestedRow(row, this.table) : null;
463
- },
464
- tag: `${this.table}.findUnique`,
465
- preparedName: entry.name,
466
- };
467
- }
468
- // -------------------------------------------------------------------------
469
- // findMany
470
- // -------------------------------------------------------------------------
471
- async findMany(args) {
472
- this.maybeWarnUnlimited(args);
473
- return this.executeWithMiddleware('findMany', (args ?? {}), async () => {
474
- const deferred = this.buildFindMany(args);
475
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args?.timeout, deferred.preparedName);
476
- return deferred.transform(result);
477
- });
478
- }
479
- /**
480
- * Emit a one-time `console.warn` when {@link findMany} is called without an
481
- * explicit `limit`/`take` and `warnOnUnlimited` has not been disabled.
482
- *
483
- * Deduped per QueryInterface instance via {@link warnedTables} so a busy
484
- * loop calling `db.users.findMany()` thousands of times only logs once.
485
- * Suppressed when `defaultLimit` is configured (the caller has already
486
- * opted in to a bounded query) and when the user passed an explicit
487
- * `limit`, `take`, or `cursor`.
488
- */
489
- maybeWarnUnlimited(args) {
490
- if (!this.warnOnUnlimited)
491
- return;
492
- if (this.defaultLimit !== undefined)
493
- return;
494
- const hasExplicitLimit = args?.limit !== undefined || args?.take !== undefined || args?.cursor !== undefined;
495
- if (hasExplicitLimit)
496
- return;
497
- if (this.warnedTables.has(this.table))
498
- return;
499
- this.warnedTables.add(this.table);
500
- console.warn(`[turbine] warning: findMany on "${this.table}" has no limit — this will fetch every row. ` +
501
- 'Pass `limit` or set `warnOnUnlimited: false` in config to silence.');
502
- }
503
- buildFindMany(args) {
504
- const columnsList = this.resolveColumns(args?.select, args?.omit);
505
- const colKey = columnsList ? columnsList.join(',') : '*';
506
- const whereObj = (args?.where ?? {});
507
- // Build fingerprint for cache lookup
508
- const whereFp = args?.where ? this.fingerprintWhere(whereObj) : '';
509
- const withFp = args?.with ? this.withFingerprint(args.with) : '';
510
- const orderFp = args?.orderBy
511
- ? Object.entries(args.orderBy)
512
- .map(([k, d]) => `${k}:${d}`)
513
- .join(',')
514
- : '';
515
- const cursorFp = args?.cursor
516
- ? Object.keys(args.cursor)
517
- .filter((k) => args.cursor[k] !== undefined)
518
- .sort()
519
- .join(',')
520
- : '';
521
- const distinctFp = args?.distinct ? args.distinct.slice().sort().join(',') : '';
522
- const effectiveLimit = args?.take ?? args?.limit ?? this.defaultLimit;
523
- const limitFp = effectiveLimit !== undefined ? '1' : '0';
524
- const offsetFp = args?.offset !== undefined ? '1' : '0';
525
- const ck = `fm:${whereFp}|c=${colKey}|o=${orderFp}|l=${limitFp}|off=${offsetFp}|cur=${cursorFp}|d=${distinctFp}|w=${withFp}`;
526
- const params = [];
527
- const entry = this.acquireSql(ck, () => {
528
- // Fresh build — generates SQL and populates freshParams
529
- const freshParams = [];
530
- const { sql: freshWhereSql } = args?.where
531
- ? (() => {
532
- const clause = this.buildWhereClause(whereObj, freshParams);
533
- return { sql: clause ? ` WHERE ${clause}` : '' };
534
- })()
535
- : { sql: '' };
536
- const qt = quoteIdent(this.table);
537
- let distinctPrefix = '';
538
- if (args?.distinct && args.distinct.length > 0) {
539
- const distinctCols = args.distinct.map((k) => this.toSqlColumn(k));
540
- distinctPrefix = `DISTINCT ON (${distinctCols.join(', ')}) `;
541
- }
542
- let selectClause;
543
- if (args?.with) {
544
- selectClause = this.buildSelectWithRelations(this.table, args.with, freshParams, columnsList);
545
- }
546
- else if (columnsList) {
547
- selectClause = columnsList.map((c) => `${qt}.${quoteIdent(c)}`).join(', ');
548
- }
549
- else {
550
- selectClause = `${qt}.*`;
551
- }
552
- let sql = `SELECT ${distinctPrefix}${selectClause} FROM ${qt}${freshWhereSql}`;
553
- if (args?.cursor) {
554
- const cursorEntries = Object.entries(args.cursor).filter(([, v]) => v !== undefined);
555
- if (cursorEntries.length > 0) {
556
- const cursorConditions = cursorEntries.map(([k, v]) => {
557
- const col = this.toSqlColumn(k);
558
- const dir = args.orderBy?.[k] ?? 'asc';
559
- const op = dir === 'desc' ? '<' : '>';
560
- freshParams.push(v);
561
- return `${qt}.${col} ${op} $${freshParams.length}`;
562
- });
563
- if (freshWhereSql) {
564
- sql += ` AND ${cursorConditions.join(' AND ')}`;
565
- }
566
- else {
567
- sql += ` WHERE ${cursorConditions.join(' AND ')}`;
568
- }
569
- }
570
- }
571
- if (args?.orderBy) {
572
- sql += ` ORDER BY ${this.buildOrderBy(args.orderBy)}`;
573
- }
574
- if (effectiveLimit !== undefined) {
575
- freshParams.push(Number(effectiveLimit));
576
- sql += ` LIMIT $${freshParams.length}`;
577
- }
578
- if (args?.offset !== undefined) {
579
- freshParams.push(Number(args.offset));
580
- sql += ` OFFSET $${freshParams.length}`;
581
- }
582
- return sql;
583
- });
584
- // Collect params in exact build order:
585
- // 1. WHERE params
586
- if (args?.where) {
587
- this.collectWhereParams(whereObj, params);
588
- }
589
- // 2. WITH relation params
590
- if (args?.with) {
591
- this.collectWithParams(args.with, params);
592
- }
593
- // 3. Cursor params
594
- if (args?.cursor) {
595
- const cursorEntries = Object.entries(args.cursor).filter(([, v]) => v !== undefined);
596
- for (const [, v] of cursorEntries) {
597
- params.push(v);
598
- }
599
- }
600
- // 4. LIMIT param
601
- if (effectiveLimit !== undefined) {
602
- params.push(Number(effectiveLimit));
603
- }
604
- // 5. OFFSET param
605
- if (args?.offset !== undefined) {
606
- params.push(Number(args.offset));
607
- }
608
- return {
609
- sql: entry.sql,
610
- params,
611
- transform: (result) => result.rows.map((row) => args?.with ? this.parseNestedRow(row, this.table) : this.parseRow(row, this.table)),
612
- tag: `${this.table}.findMany`,
613
- preparedName: entry.name,
614
- };
615
- }
616
- // -------------------------------------------------------------------------
617
- // findManyStream — async iterable using PostgreSQL cursors
618
- // -------------------------------------------------------------------------
619
- /**
620
- * Stream rows from a findMany query using PostgreSQL cursors.
621
- * Returns an AsyncIterable that yields individual rows, fetching in batches internally.
622
- *
623
- * **Speculative fast-path:** Before opening a cursor, issues a single
624
- * `SELECT ... LIMIT batchSize+1`. If the result fits within `batchSize`,
625
- * all rows are yielded immediately with zero cursor overhead (no BEGIN /
626
- * DECLARE / CLOSE / COMMIT). Only when the result overflows does the
627
- * method fall back to the full cursor path.
628
- *
629
- * **Cursor path:** Uses DECLARE CURSOR within a dedicated transaction on a
630
- * single pooled connection. The cursor is automatically closed and the
631
- * connection released when iteration completes or is terminated early
632
- * (e.g. `break` from `for await`).
633
- *
634
- * **Snapshot semantics note:** The speculative fast-path runs outside a
635
- * transaction. If the result overflows and the cursor path is opened, the
636
- * cursor runs in its own transaction — spanning two separate snapshots.
637
- * For strict single-snapshot semantics, wrap the call in `$transaction`.
638
- *
639
- * @example
640
- * ```ts
641
- * for await (const user of db.users.findManyStream({ where: { orgId: 1 }, batchSize: 500 })) {
642
- * process.stdout.write(`${user.email}\n`);
643
- * }
644
- * ```
645
- */
646
- async *findManyStream(args) {
647
- const batchSize = Math.max(1, Math.floor(Number(args?.batchSize ?? 1000)));
648
- const hasRelations = !!args?.with;
649
- // --- Speculative first fetch: try to satisfy the entire drain in one RTT ---
650
- const speculativeDeferred = this.buildFindMany({
651
- ...args,
652
- limit: batchSize + 1,
653
- });
654
- const speculativeResult = await this.queryWithTimeout(speculativeDeferred.sql, speculativeDeferred.params, args?.timeout);
655
- if (speculativeResult.rows.length <= batchSize) {
656
- // Small drain — yield all rows and return, no cursor needed
657
- for (const row of speculativeResult.rows) {
658
- yield (hasRelations ? this.parseNestedRow(row, this.table) : this.parseRow(row, this.table));
659
- }
660
- return;
661
- }
662
- // --- Overflow: fall back to cursor path from scratch ---
663
- const deferred = this.buildFindMany(args);
664
- // Acquire a dedicated connection — cursors require a single connection in a transaction
665
- const client = await this.pool.connect();
666
- const cursorName = `turbine_cursor_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
667
- const quotedCursor = quoteIdent(cursorName);
668
- try {
669
- await client.query('BEGIN');
670
- await client.query(`DECLARE ${quotedCursor} NO SCROLL CURSOR FOR ${deferred.sql}`, deferred.params);
671
- while (true) {
672
- const batch = await client.query(`FETCH ${batchSize} FROM ${quotedCursor}`);
673
- if (batch.rows.length === 0)
674
- break;
675
- for (const row of batch.rows) {
676
- yield (hasRelations ? this.parseNestedRow(row, this.table) : this.parseRow(row, this.table));
677
- }
678
- if (batch.rows.length < batchSize)
679
- break;
680
- }
681
- await client.query(`CLOSE ${quotedCursor}`);
682
- await client.query('COMMIT');
683
- }
684
- catch (err) {
685
- // Rollback on error (also closes cursor implicitly)
686
- try {
687
- await client.query('ROLLBACK');
688
- }
689
- catch {
690
- // Connection may already be broken — ignore rollback error
691
- }
692
- // Wrap pg constraint errors so streaming surfaces typed errors like the rest of the API
693
- throw (0, errors_js_1.wrapPgError)(err);
694
- }
695
- finally {
696
- client.release();
697
- }
698
- }
699
- // -------------------------------------------------------------------------
700
- // findFirst — like findMany but returns a single row or null
701
- // -------------------------------------------------------------------------
702
- async findFirst(args) {
703
- return this.executeWithMiddleware('findFirst', (args ?? {}), async () => {
704
- const deferred = this.buildFindFirst(args);
705
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args?.timeout, deferred.preparedName);
706
- return deferred.transform(result);
707
- });
708
- }
709
- buildFindFirst(args) {
710
- // Reuse findMany's SQL builder but force LIMIT 1
711
- const findManyArgs = { ...args, limit: 1 };
712
- const deferred = this.buildFindMany(findManyArgs);
713
- return {
714
- sql: deferred.sql,
715
- params: deferred.params,
716
- transform: (result) => {
717
- const rows = deferred.transform(result);
718
- return rows.length > 0 ? rows[0] : null;
719
- },
720
- tag: `${this.table}.findFirst`,
721
- };
722
- }
723
- // -------------------------------------------------------------------------
724
- // findFirstOrThrow — like findFirst but throws if no record found
725
- // -------------------------------------------------------------------------
726
- async findFirstOrThrow(args) {
727
- return this.executeWithMiddleware('findFirstOrThrow', (args ?? {}), async () => {
728
- const deferred = this.buildFindFirstOrThrow(args);
729
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args?.timeout, deferred.preparedName);
730
- return deferred.transform(result);
731
- });
732
- }
733
- buildFindFirstOrThrow(args) {
734
- const inner = this.buildFindFirst(args);
735
- return {
736
- sql: inner.sql,
737
- params: inner.params,
738
- transform: (result) => {
739
- const row = inner.transform(result);
740
- if (row === null) {
741
- throw new errors_js_1.NotFoundError({
742
- table: this.table,
743
- where: args?.where,
744
- operation: 'findFirstOrThrow',
745
- });
746
- }
747
- return row;
748
- },
749
- tag: `${this.table}.findFirstOrThrow`,
750
- };
751
- }
752
- // -------------------------------------------------------------------------
753
- // findUniqueOrThrow — like findUnique but throws if no record found
754
- // -------------------------------------------------------------------------
755
- async findUniqueOrThrow(args) {
756
- return this.executeWithMiddleware('findUniqueOrThrow', args, async () => {
757
- const deferred = this.buildFindUniqueOrThrow(args);
758
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
759
- return deferred.transform(result);
760
- });
761
- }
762
- buildFindUniqueOrThrow(args) {
763
- const inner = this.buildFindUnique(args);
764
- return {
765
- sql: inner.sql,
766
- params: inner.params,
767
- transform: (result) => {
768
- const row = inner.transform(result);
769
- if (row === null) {
770
- throw new errors_js_1.NotFoundError({
771
- table: this.table,
772
- where: args.where,
773
- operation: 'findUniqueOrThrow',
774
- });
775
- }
776
- return row;
777
- },
778
- tag: `${this.table}.findUniqueOrThrow`,
779
- };
780
- }
781
- // -------------------------------------------------------------------------
782
- // create
783
- // -------------------------------------------------------------------------
784
- async create(args) {
785
- return this.executeWithMiddleware('create', args, async () => {
786
- const deferred = this.buildCreate(args);
787
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
788
- return deferred.transform(result);
789
- });
790
- }
791
- buildCreate(args) {
792
- const entries = Object.entries(args.data).filter(([, v]) => v !== undefined);
793
- const columns = entries.map(([k]) => this.toSqlColumn(k));
794
- const params = entries.map(([, v]) => v);
795
- const placeholders = entries.map((_, i) => `$${i + 1}`);
796
- const sql = `INSERT INTO ${quoteIdent(this.table)} (${columns.join(', ')}) VALUES (${placeholders.join(', ')}) RETURNING *`;
797
- return {
798
- sql,
799
- params,
800
- transform: (result) => {
801
- const row = result.rows[0];
802
- if (!row) {
803
- throw new errors_js_1.NotFoundError({
804
- table: this.table,
805
- operation: 'create',
806
- message: `[turbine] create on "${this.table}" returned no row from RETURNING * — this should never happen.`,
807
- });
808
- }
809
- return this.parseRow(row, this.table);
810
- },
811
- tag: `${this.table}.create`,
812
- };
813
- }
814
- // -------------------------------------------------------------------------
815
- // createMany — uses UNNEST for performance
816
- // -------------------------------------------------------------------------
817
- async createMany(args) {
818
- return this.executeWithMiddleware('createMany', args, async () => {
819
- const deferred = this.buildCreateMany(args);
820
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
821
- return deferred.transform(result);
822
- });
823
- }
824
- buildCreateMany(args) {
825
- const qt = quoteIdent(this.table);
826
- if (args.data.length === 0) {
827
- return {
828
- sql: `SELECT * FROM ${qt} WHERE false`,
829
- params: [],
830
- transform: () => [],
831
- tag: `${this.table}.createMany`,
832
- };
833
- }
834
- const keys = Object.keys(args.data[0]).filter((k) => args.data[0][k] !== undefined);
835
- const columns = keys.map((k) => this.toColumn(k));
836
- // Build column arrays for UNNEST
837
- const columnArrays = keys.map(() => []);
838
- for (const row of args.data) {
839
- const record = row;
840
- keys.forEach((key, i) => {
841
- columnArrays[i].push(record[key]);
842
- });
843
- }
844
- // Use actual Postgres types for array casts
845
- const typeCasts = columns.map((col) => this.getColumnArrayType(col));
846
- const unnestArgs = columnArrays.map((_, i) => `$${i + 1}::${typeCasts[i]}`);
847
- const quotedColumns = columns.map((c) => quoteIdent(c));
848
- let sql = `INSERT INTO ${qt} (${quotedColumns.join(', ')}) SELECT * FROM UNNEST(${unnestArgs.join(', ')})`;
849
- // skipDuplicates: add ON CONFLICT DO NOTHING
850
- if (args.skipDuplicates) {
851
- sql += ` ON CONFLICT DO NOTHING`;
852
- }
853
- sql += ` RETURNING *`;
854
- return {
855
- sql,
856
- params: columnArrays,
857
- transform: (result) => result.rows.map((row) => this.parseRow(row, this.table)),
858
- tag: `${this.table}.createMany`,
859
- };
860
- }
861
- // -------------------------------------------------------------------------
862
- // update
863
- // -------------------------------------------------------------------------
864
- async update(args) {
865
- return this.executeWithMiddleware('update', args, async () => {
866
- const deferred = this.buildUpdate(args);
867
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
868
- return deferred.transform(result);
869
- });
870
- }
871
- buildUpdate(args) {
872
- const dataObj = args.data;
873
- const whereObj = args.where;
874
- const setFp = this.fingerprintSet(dataObj);
875
- const whereFp = this.fingerprintWhere(whereObj);
876
- const ck = `u:${setFp}|${whereFp}`;
877
- const params = [];
878
- const entry = this.acquireSql(ck, () => {
879
- const freshParams = [];
880
- const setEntries = Object.entries(dataObj).filter(([, v]) => v !== undefined);
881
- const setClauses = setEntries.map(([k, v]) => this.buildSetClause(k, v, freshParams));
882
- const whereClause = this.buildWhereClause(whereObj, freshParams);
883
- const whereSql = whereClause ? ` WHERE ${whereClause}` : '';
884
- this.assertMutationHasPredicate('update', whereSql, args.allowFullTableScan);
885
- return `UPDATE ${quoteIdent(this.table)} SET ${setClauses.join(', ')}${whereSql} RETURNING *`;
886
- });
887
- // On cache hit, validate predicate
888
- if (whereFp === '') {
889
- this.assertMutationHasPredicate('update', '', args.allowFullTableScan);
890
- }
891
- // Collect params: SET first, then WHERE (same order as fresh build)
892
- this.collectSetParams(dataObj, params);
893
- this.collectWhereParams(whereObj, params);
894
- return {
895
- sql: entry.sql,
896
- params,
897
- transform: (result) => {
898
- const row = result.rows[0];
899
- if (!row) {
900
- throw new errors_js_1.NotFoundError({
901
- table: this.table,
902
- where: args.where,
903
- operation: 'update',
904
- });
905
- }
906
- return this.parseRow(row, this.table);
907
- },
908
- tag: `${this.table}.update`,
909
- preparedName: entry.name,
910
- };
911
- }
912
- // -------------------------------------------------------------------------
913
- // delete
914
- // -------------------------------------------------------------------------
915
- async delete(args) {
916
- return this.executeWithMiddleware('delete', args, async () => {
917
- const deferred = this.buildDelete(args);
918
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
919
- return deferred.transform(result);
920
- });
921
- }
922
- buildDelete(args) {
923
- const whereObj = args.where;
924
- const whereFp = this.fingerprintWhere(whereObj);
925
- const ck = `d:${whereFp}`;
926
- const params = [];
927
- // We need to check the mutation predicate. Build the whereSql to test it.
928
- // On cache hit we still need to validate (the shape may be empty).
929
- const entry = this.acquireSql(ck, () => {
930
- const freshParams = [];
931
- const clause = this.buildWhereClause(whereObj, freshParams);
932
- const whereSql = clause ? ` WHERE ${clause}` : '';
933
- this.assertMutationHasPredicate('delete', whereSql, args.allowFullTableScan);
934
- return `DELETE FROM ${quoteIdent(this.table)}${whereSql} RETURNING *`;
935
- });
936
- // On cache hit, still validate the predicate
937
- if (whereFp === '') {
938
- this.assertMutationHasPredicate('delete', '', args.allowFullTableScan);
939
- }
940
- this.collectWhereParams(whereObj, params);
941
- return {
942
- sql: entry.sql,
943
- params,
944
- transform: (result) => {
945
- const row = result.rows[0];
946
- if (!row) {
947
- throw new errors_js_1.NotFoundError({
948
- table: this.table,
949
- where: args.where,
950
- operation: 'delete',
951
- });
952
- }
953
- return this.parseRow(row, this.table);
954
- },
955
- tag: `${this.table}.delete`,
956
- preparedName: entry.name,
957
- };
958
- }
959
- // -------------------------------------------------------------------------
960
- // upsert — INSERT ... ON CONFLICT ... DO UPDATE
961
- // -------------------------------------------------------------------------
962
- async upsert(args) {
963
- return this.executeWithMiddleware('upsert', args, async () => {
964
- const deferred = this.buildUpsert(args);
965
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
966
- return deferred.transform(result);
967
- });
968
- }
969
- buildUpsert(args) {
970
- // Build the INSERT part from create data
971
- const createEntries = Object.entries(args.create).filter(([, v]) => v !== undefined);
972
- const columns = createEntries.map(([k]) => this.toSqlColumn(k));
973
- const createParams = createEntries.map(([, v]) => v);
974
- const placeholders = createEntries.map((_, i) => `$${i + 1}`);
975
- // The conflict target comes from `where` keys — must be unique/PK columns
976
- const conflictKeys = Object.keys(args.where).filter((k) => args.where[k] !== undefined);
977
- const conflictColumns = conflictKeys.map((k) => this.toSqlColumn(k));
978
- // Build the UPDATE SET part
979
- const updateEntries = Object.entries(args.update).filter(([, v]) => v !== undefined);
980
- let paramIdx = createParams.length + 1;
981
- const setClauses = updateEntries.map(([k]) => {
982
- const clause = `${this.toSqlColumn(k)} = $${paramIdx}`;
983
- paramIdx++;
984
- return clause;
985
- });
986
- const updateParams = updateEntries.map(([, v]) => v);
987
- const params = [...createParams, ...updateParams];
988
- const sql = `INSERT INTO ${quoteIdent(this.table)} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})` +
989
- ` ON CONFLICT (${conflictColumns.join(', ')}) DO UPDATE SET ${setClauses.join(', ')}` +
990
- ` RETURNING *`;
991
- return {
992
- sql,
993
- params,
994
- transform: (result) => {
995
- const row = result.rows[0];
996
- if (!row) {
997
- throw new errors_js_1.NotFoundError({
998
- table: this.table,
999
- where: args.where,
1000
- operation: 'upsert',
1001
- message: `[turbine] upsert on "${this.table}" returned no row from RETURNING * — this should never happen.`,
1002
- });
1003
- }
1004
- return this.parseRow(row, this.table);
1005
- },
1006
- tag: `${this.table}.upsert`,
1007
- };
1008
- }
1009
- // -------------------------------------------------------------------------
1010
- // updateMany — UPDATE ... WHERE ... returning count
1011
- // -------------------------------------------------------------------------
1012
- async updateMany(args) {
1013
- return this.executeWithMiddleware('updateMany', args, async () => {
1014
- const deferred = this.buildUpdateMany(args);
1015
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
1016
- return deferred.transform(result);
1017
- });
1018
- }
1019
- buildUpdateMany(args) {
1020
- const dataObj = args.data;
1021
- const whereObj = args.where;
1022
- const setFp = this.fingerprintSet(dataObj);
1023
- const whereFp = this.fingerprintWhere(whereObj);
1024
- const ck = `um:${setFp}|${whereFp}`;
1025
- const params = [];
1026
- const entry = this.acquireSql(ck, () => {
1027
- const freshParams = [];
1028
- const setEntries = Object.entries(dataObj).filter(([, v]) => v !== undefined);
1029
- const setClauses = setEntries.map(([k, v]) => this.buildSetClause(k, v, freshParams));
1030
- const whereClause = this.buildWhereClause(whereObj, freshParams);
1031
- const whereSql = whereClause ? ` WHERE ${whereClause}` : '';
1032
- this.assertMutationHasPredicate('updateMany', whereSql, args.allowFullTableScan);
1033
- return `UPDATE ${quoteIdent(this.table)} SET ${setClauses.join(', ')}${whereSql}`;
1034
- });
1035
- if (whereFp === '') {
1036
- this.assertMutationHasPredicate('updateMany', '', args.allowFullTableScan);
1037
- }
1038
- this.collectSetParams(dataObj, params);
1039
- this.collectWhereParams(whereObj, params);
1040
- return {
1041
- sql: entry.sql,
1042
- params,
1043
- transform: (result) => ({ count: result.rowCount ?? 0 }),
1044
- tag: `${this.table}.updateMany`,
1045
- preparedName: entry.name,
1046
- };
1047
- }
1048
- // -------------------------------------------------------------------------
1049
- // deleteMany — DELETE ... WHERE ... returning count
1050
- // -------------------------------------------------------------------------
1051
- async deleteMany(args) {
1052
- return this.executeWithMiddleware('deleteMany', args, async () => {
1053
- const deferred = this.buildDeleteMany(args);
1054
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
1055
- return deferred.transform(result);
1056
- });
1057
- }
1058
- buildDeleteMany(args) {
1059
- const whereObj = args.where;
1060
- const whereFp = this.fingerprintWhere(whereObj);
1061
- const ck = `dm:${whereFp}`;
1062
- const params = [];
1063
- const entry = this.acquireSql(ck, () => {
1064
- const freshParams = [];
1065
- const clause = this.buildWhereClause(whereObj, freshParams);
1066
- const whereSql = clause ? ` WHERE ${clause}` : '';
1067
- this.assertMutationHasPredicate('deleteMany', whereSql, args.allowFullTableScan);
1068
- return `DELETE FROM ${quoteIdent(this.table)}${whereSql}`;
1069
- });
1070
- if (whereFp === '') {
1071
- this.assertMutationHasPredicate('deleteMany', '', args.allowFullTableScan);
1072
- }
1073
- this.collectWhereParams(whereObj, params);
1074
- return {
1075
- sql: entry.sql,
1076
- params,
1077
- transform: (result) => ({ count: result.rowCount ?? 0 }),
1078
- tag: `${this.table}.deleteMany`,
1079
- preparedName: entry.name,
1080
- };
1081
- }
1082
- // -------------------------------------------------------------------------
1083
- // count
1084
- // -------------------------------------------------------------------------
1085
- async count(args) {
1086
- return this.executeWithMiddleware('count', (args ?? {}), async () => {
1087
- const deferred = this.buildCount(args);
1088
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args?.timeout, deferred.preparedName);
1089
- return deferred.transform(result);
1090
- });
1091
- }
1092
- buildCount(args) {
1093
- const whereObj = (args?.where ?? {});
1094
- const whereFp = args?.where ? this.fingerprintWhere(whereObj) : '';
1095
- const ck = `cnt:${whereFp}`;
1096
- const params = [];
1097
- const entry = this.acquireSql(ck, () => {
1098
- const freshParams = [];
1099
- const clause = args?.where ? this.buildWhereClause(whereObj, freshParams) : null;
1100
- const whereSql = clause ? ` WHERE ${clause}` : '';
1101
- return `SELECT COUNT(*)::int AS count FROM ${quoteIdent(this.table)}${whereSql}`;
1102
- });
1103
- if (args?.where) {
1104
- this.collectWhereParams(whereObj, params);
1105
- }
1106
- return {
1107
- sql: entry.sql,
1108
- params,
1109
- transform: (result) => result.rows[0].count,
1110
- tag: `${this.table}.count`,
1111
- preparedName: entry.name,
1112
- };
1113
- }
1114
- // -------------------------------------------------------------------------
1115
- // groupBy (with aggregate functions)
1116
- // -------------------------------------------------------------------------
1117
- async groupBy(args) {
1118
- return this.executeWithMiddleware('groupBy', args, async () => {
1119
- const deferred = this.buildGroupBy(args);
1120
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
1121
- return deferred.transform(result);
1122
- });
1123
- }
1124
- buildGroupBy(args) {
1125
- const meta = this.schema.tables[this.table];
1126
- if (meta) {
1127
- for (const key of args.by) {
1128
- if (!(key in meta.columnMap)) {
1129
- throw new errors_js_1.ValidationError(`Unknown column "${key}" in groupBy for table "${this.table}"`);
1130
- }
1131
- }
1132
- }
1133
- const groupColsRaw = args.by.map((k) => this.toColumn(k));
1134
- const groupCols = groupColsRaw.map((c) => quoteIdent(c));
1135
- const { sql: whereSql, params } = args.where ? this.buildWhere(args.where) : { sql: '', params: [] };
1136
- // Build SELECT expressions: group-by columns + aggregate functions
1137
- const selectExprs = [...groupCols];
1138
- // _count
1139
- if (args._count === true || args._count === undefined) {
1140
- // default: always include count
1141
- selectExprs.push('COUNT(*)::int AS _count');
1142
- }
1143
- // _sum
1144
- if (args._sum) {
1145
- for (const [field, enabled] of Object.entries(args._sum)) {
1146
- if (enabled) {
1147
- const col = this.toColumn(field);
1148
- selectExprs.push(`SUM(${quoteIdent(col)}) AS ${quoteIdent(`_sum_${col}`)}`);
1149
- }
1150
- }
1151
- }
1152
- // _avg
1153
- if (args._avg) {
1154
- for (const [field, enabled] of Object.entries(args._avg)) {
1155
- if (enabled) {
1156
- const col = this.toColumn(field);
1157
- selectExprs.push(`AVG(${quoteIdent(col)})::float AS ${quoteIdent(`_avg_${col}`)}`);
1158
- }
1159
- }
1160
- }
1161
- // _min
1162
- if (args._min) {
1163
- for (const [field, enabled] of Object.entries(args._min)) {
1164
- if (enabled) {
1165
- const col = this.toColumn(field);
1166
- selectExprs.push(`MIN(${quoteIdent(col)}) AS ${quoteIdent(`_min_${col}`)}`);
1167
- }
1168
- }
1169
- }
1170
- // _max
1171
- if (args._max) {
1172
- for (const [field, enabled] of Object.entries(args._max)) {
1173
- if (enabled) {
1174
- const col = this.toColumn(field);
1175
- selectExprs.push(`MAX(${quoteIdent(col)}) AS ${quoteIdent(`_max_${col}`)}`);
1176
- }
1177
- }
1178
- }
1179
- let sql = `SELECT ${selectExprs.join(', ')} FROM ${quoteIdent(this.table)}${whereSql} GROUP BY ${groupCols.join(', ')}`;
1180
- // ORDER BY
1181
- if (args.orderBy) {
1182
- sql += ` ORDER BY ${this.buildOrderBy(args.orderBy)}`;
1183
- }
1184
- return {
1185
- sql,
1186
- params,
1187
- transform: (result) => result.rows.map((row) => {
1188
- const parsed = this.parseRow(row, this.table);
1189
- // Restructure aggregate results into nested objects (Prisma-style)
1190
- const restructured = {};
1191
- // Copy group-by fields
1192
- for (const field of args.by) {
1193
- restructured[field] = parsed[field];
1194
- }
1195
- // _count
1196
- if ('_count' in row) {
1197
- restructured._count = row._count;
1198
- }
1199
- else if ('count' in row) {
1200
- restructured._count = row.count;
1201
- }
1202
- // Collect aggregates into nested objects
1203
- const sumObj = {};
1204
- const avgObj = {};
1205
- const minObj = {};
1206
- const maxObj = {};
1207
- let hasSums = false, hasAvgs = false, hasMins = false, hasMaxs = false;
1208
- for (const [rawKey, rawValue] of Object.entries(row)) {
1209
- if (rawKey.startsWith('_sum_')) {
1210
- const col = rawKey.slice(5);
1211
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1212
- sumObj[field] = rawValue !== null ? Number(rawValue) : null;
1213
- hasSums = true;
1214
- }
1215
- else if (rawKey.startsWith('_avg_')) {
1216
- const col = rawKey.slice(5);
1217
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1218
- avgObj[field] = rawValue !== null ? Number(rawValue) : null;
1219
- hasAvgs = true;
1220
- }
1221
- else if (rawKey.startsWith('_min_')) {
1222
- const col = rawKey.slice(5);
1223
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1224
- minObj[field] = rawValue;
1225
- hasMins = true;
1226
- }
1227
- else if (rawKey.startsWith('_max_')) {
1228
- const col = rawKey.slice(5);
1229
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1230
- maxObj[field] = rawValue;
1231
- hasMaxs = true;
1232
- }
1233
- }
1234
- if (hasSums)
1235
- restructured._sum = sumObj;
1236
- if (hasAvgs)
1237
- restructured._avg = avgObj;
1238
- if (hasMins)
1239
- restructured._min = minObj;
1240
- if (hasMaxs)
1241
- restructured._max = maxObj;
1242
- return restructured;
1243
- }),
1244
- tag: `${this.table}.groupBy`,
1245
- };
1246
- }
1247
- // -------------------------------------------------------------------------
1248
- // aggregate — standalone aggregation without groupBy
1249
- // -------------------------------------------------------------------------
1250
- async aggregate(args) {
1251
- return this.executeWithMiddleware('aggregate', args, async () => {
1252
- const deferred = this.buildAggregate(args);
1253
- const result = await this.queryWithTimeout(deferred.sql, deferred.params, args.timeout, deferred.preparedName);
1254
- return deferred.transform(result);
1255
- });
1256
- }
1257
- buildAggregate(args) {
1258
- const { sql: whereSql, params } = args.where ? this.buildWhere(args.where) : { sql: '', params: [] };
1259
- const meta = this.schema.tables[this.table];
1260
- if (meta) {
1261
- for (const group of [args._sum, args._avg, args._min, args._max]) {
1262
- if (group && typeof group === 'object') {
1263
- for (const key of Object.keys(group)) {
1264
- if (!(key in meta.columnMap)) {
1265
- throw new errors_js_1.ValidationError(`Unknown column "${key}" in aggregate for table "${this.table}"`);
1266
- }
1267
- }
1268
- }
1269
- }
1270
- if (args._count && typeof args._count === 'object') {
1271
- for (const key of Object.keys(args._count)) {
1272
- if (!(key in meta.columnMap)) {
1273
- throw new errors_js_1.ValidationError(`Unknown column "${key}" in aggregate for table "${this.table}"`);
1274
- }
1275
- }
1276
- }
1277
- }
1278
- const selectExprs = [];
1279
- // _count
1280
- if (args._count === true) {
1281
- selectExprs.push('COUNT(*)::int AS _count');
1282
- }
1283
- else if (args._count && typeof args._count === 'object') {
1284
- for (const [field, enabled] of Object.entries(args._count)) {
1285
- if (enabled) {
1286
- const col = this.toColumn(field);
1287
- selectExprs.push(`COUNT(${quoteIdent(col)})::int AS ${quoteIdent(`_count_${col}`)}`);
1288
- }
1289
- }
1290
- }
1291
- // _sum
1292
- if (args._sum) {
1293
- for (const [field, enabled] of Object.entries(args._sum)) {
1294
- if (enabled) {
1295
- const col = this.toColumn(field);
1296
- selectExprs.push(`SUM(${quoteIdent(col)}) AS ${quoteIdent(`_sum_${col}`)}`);
1297
- }
1298
- }
1299
- }
1300
- // _avg
1301
- if (args._avg) {
1302
- for (const [field, enabled] of Object.entries(args._avg)) {
1303
- if (enabled) {
1304
- const col = this.toColumn(field);
1305
- selectExprs.push(`AVG(${quoteIdent(col)})::float AS ${quoteIdent(`_avg_${col}`)}`);
1306
- }
1307
- }
1308
- }
1309
- // _min
1310
- if (args._min) {
1311
- for (const [field, enabled] of Object.entries(args._min)) {
1312
- if (enabled) {
1313
- const col = this.toColumn(field);
1314
- selectExprs.push(`MIN(${quoteIdent(col)}) AS ${quoteIdent(`_min_${col}`)}`);
1315
- }
1316
- }
1317
- }
1318
- // _max
1319
- if (args._max) {
1320
- for (const [field, enabled] of Object.entries(args._max)) {
1321
- if (enabled) {
1322
- const col = this.toColumn(field);
1323
- selectExprs.push(`MAX(${quoteIdent(col)}) AS ${quoteIdent(`_max_${col}`)}`);
1324
- }
1325
- }
1326
- }
1327
- if (selectExprs.length === 0) {
1328
- selectExprs.push('COUNT(*)::int AS _count');
1329
- }
1330
- const sql = `SELECT ${selectExprs.join(', ')} FROM ${quoteIdent(this.table)}${whereSql}`;
1331
- return {
1332
- sql,
1333
- params,
1334
- transform: (result) => {
1335
- const row = result.rows[0];
1336
- const aggResult = {};
1337
- // _count
1338
- if (row._count !== undefined) {
1339
- aggResult._count = row._count;
1340
- }
1341
- else {
1342
- // Check for per-column counts
1343
- const countObj = {};
1344
- let hasCountFields = false;
1345
- for (const [key, val] of Object.entries(row)) {
1346
- if (key.startsWith('_count_')) {
1347
- const col = key.slice(7);
1348
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1349
- countObj[field] = val;
1350
- hasCountFields = true;
1351
- }
1352
- }
1353
- if (hasCountFields)
1354
- aggResult._count = countObj;
1355
- }
1356
- // Build nested aggregate objects
1357
- const sumObj = {};
1358
- const avgObj = {};
1359
- const minObj = {};
1360
- const maxObj = {};
1361
- let hasSums = false, hasAvgs = false, hasMins = false, hasMaxs = false;
1362
- for (const [key, val] of Object.entries(row)) {
1363
- if (key.startsWith('_sum_')) {
1364
- const col = key.slice(5);
1365
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1366
- sumObj[field] = val !== null ? Number(val) : null;
1367
- hasSums = true;
1368
- }
1369
- else if (key.startsWith('_avg_')) {
1370
- const col = key.slice(5);
1371
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1372
- avgObj[field] = val !== null ? Number(val) : null;
1373
- hasAvgs = true;
1374
- }
1375
- else if (key.startsWith('_min_')) {
1376
- const col = key.slice(5);
1377
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1378
- minObj[field] = val;
1379
- hasMins = true;
1380
- }
1381
- else if (key.startsWith('_max_')) {
1382
- const col = key.slice(5);
1383
- const field = this.tableMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col);
1384
- maxObj[field] = val;
1385
- hasMaxs = true;
1386
- }
1387
- }
1388
- if (hasSums)
1389
- aggResult._sum = sumObj;
1390
- if (hasAvgs)
1391
- aggResult._avg = avgObj;
1392
- if (hasMins)
1393
- aggResult._min = minObj;
1394
- if (hasMaxs)
1395
- aggResult._max = maxObj;
1396
- return aggResult;
1397
- },
1398
- tag: `${this.table}.aggregate`,
1399
- };
1400
- }
1401
- // =========================================================================
1402
- // Internal helpers
1403
- // =========================================================================
1404
- /**
1405
- * Resolve select/omit options into a list of snake_case column names.
1406
- * Returns null if neither is provided (meaning all columns).
1407
- */
1408
- resolveColumns(select, omit) {
1409
- if (select) {
1410
- // Only include columns where value is true
1411
- return Object.entries(select)
1412
- .filter(([, v]) => v)
1413
- .map(([k]) => this.toColumn(k));
1414
- }
1415
- if (omit) {
1416
- // Include all columns except those where value is true
1417
- const omitCols = new Set(Object.entries(omit)
1418
- .filter(([, v]) => v)
1419
- .map(([k]) => this.toColumn(k)));
1420
- return this.tableMeta.allColumns.filter((col) => !omitCols.has(col));
1421
- }
1422
- return null;
1423
- }
1424
- /** Convert camelCase field name to snake_case column name (unquoted, for non-SQL uses) */
1425
- toColumn(field) {
1426
- const mapped = this.tableMeta.columnMap[field];
1427
- if (mapped)
1428
- return mapped;
1429
- // Fall back to camelToSnake ONLY if that snake_cased name also exists as a
1430
- // real column on the table. This preserves the convenience of writing
1431
- // `userId` when the schema exposes `user_id` under an unusual field name,
1432
- // but rejects arbitrary strings — closing the defense-in-depth gap for
1433
- // SQL injection and catching typos like `where: { emial: 'x' }` with a
1434
- // clear error instead of a cryptic Postgres "column does not exist".
1435
- const snake = (0, schema_js_1.camelToSnake)(field);
1436
- if (this.tableMeta.reverseColumnMap?.[snake]) {
1437
- return snake;
1438
- }
1439
- if (this.tableMeta.allColumns?.includes(snake)) {
1440
- return snake;
1441
- }
1442
- throw new errors_js_1.ValidationError(`[turbine] Unknown field "${field}" on table "${this.table}". ` +
1443
- `Known fields: ${Object.keys(this.tableMeta.columnMap).join(', ') || '(none)'}.`);
1444
- }
1445
- /** Convert camelCase field name to a double-quoted SQL identifier */
1446
- toSqlColumn(field) {
1447
- return quoteIdent(this.toColumn(field));
1448
- }
1449
- /**
1450
- * Build a single SET clause entry for update/updateMany.
1451
- *
1452
- * Supports plain values and atomic operator objects ({ set, increment,
1453
- * decrement, multiply, divide }). An operator object is detected ONLY when
1454
- * it has EXACTLY one key that is one of the 5 operator keys — this avoids
1455
- * misinterpreting JSON column values like `{ set: 'x' }` as operators
1456
- * (real operator objects always have exactly one key, and a plain JSON
1457
- * payload that happens to have a single `set` key is extremely unusual).
1458
- * Multi-key objects are always treated as plain (JSON) values.
1459
- *
1460
- * Returns the SQL fragment (e.g., `"view_count" = "view_count" + $3`) and
1461
- * pushes any required params onto the shared params array so that WHERE
1462
- * clause numbering continues correctly afterward.
1463
- */
1464
- buildSetClause(key, value, params) {
1465
- const col = this.toSqlColumn(key);
1466
- // Detect atomic-operator object: plain object (not null, not array, not
1467
- // Date, not Buffer) with EXACTLY one key matching an operator name.
1468
- if (value !== null &&
1469
- typeof value === 'object' &&
1470
- !Array.isArray(value) &&
1471
- !(value instanceof Date) &&
1472
- !Buffer.isBuffer(value)) {
1473
- const v = value;
1474
- const keys = Object.keys(v);
1475
- if (keys.length === 1 && UPDATE_OPERATOR_KEYS.has(keys[0])) {
1476
- const op = keys[0];
1477
- const opValue = v[op];
1478
- if (op === 'set') {
1479
- params.push(opValue);
1480
- return `${col} = $${params.length}`;
1481
- }
1482
- // Arithmetic operators: must be finite numbers
1483
- if (typeof opValue !== 'number' || !Number.isFinite(opValue)) {
1484
- throw new errors_js_1.ValidationError(`[turbine] update operator "${op}" on "${this.table}.${key}" requires a finite number, got ${typeof opValue}`);
1485
- }
1486
- if (op === 'increment') {
1487
- params.push(opValue);
1488
- return `${col} = ${col} + $${params.length}`;
1489
- }
1490
- if (op === 'decrement') {
1491
- params.push(opValue);
1492
- return `${col} = ${col} - $${params.length}`;
1493
- }
1494
- if (op === 'multiply') {
1495
- params.push(opValue);
1496
- return `${col} = ${col} * $${params.length}`;
1497
- }
1498
- if (op === 'divide') {
1499
- params.push(opValue);
1500
- return `${col} = ${col} / $${params.length}`;
1501
- }
1502
- }
1503
- // Fall through: multi-key objects or non-operator single-key objects
1504
- // are treated as plain values (e.g., JSONB column payloads).
1505
- }
1506
- // Plain value (including null, Date, Buffer, arrays, JSON objects)
1507
- params.push(value);
1508
- return `${col} = $${params.length}`;
1509
- }
1510
- // =========================================================================
1511
- // Fingerprinting — value-invariant shape keys for SQL cache lookup
1512
- // =========================================================================
1513
- /**
1514
- * Produce a value-invariant fingerprint of a where clause.
1515
- * Same keys + same operator shapes + same combinator structure => same string.
1516
- * Different values (e.g. id=1 vs id=999) => identical fingerprint.
1517
- *
1518
- * @internal Exposed as package-private for testing via class access.
1519
- */
1520
- fingerprintWhere(where) {
1521
- const keys = Object.keys(where)
1522
- .filter((k) => where[k] !== undefined)
1523
- .sort();
1524
- if (keys.length === 0)
1525
- return '';
1526
- const parts = [];
1527
- for (const key of keys) {
1528
- const value = where[key];
1529
- if (value === undefined)
1530
- continue;
1531
- if (key === 'OR') {
1532
- const orArr = value;
1533
- if (!Array.isArray(orArr) || orArr.length === 0)
1534
- continue;
1535
- const orParts = orArr.map((cond) => this.fingerprintWhere(cond));
1536
- parts.push(`OR[${orParts.join(',')}]`);
1537
- continue;
1538
- }
1539
- if (key === 'AND') {
1540
- const andArr = value;
1541
- if (!Array.isArray(andArr) || andArr.length === 0)
1542
- continue;
1543
- const andParts = andArr.map((cond) => this.fingerprintWhere(cond));
1544
- parts.push(`AND[${andParts.join(',')}]`);
1545
- continue;
1546
- }
1547
- if (key === 'NOT') {
1548
- const notCond = value;
1549
- parts.push(`NOT(${this.fingerprintWhere(notCond)})`);
1550
- continue;
1551
- }
1552
- // Relation filters: { posts: { some: { published: true } } }
1553
- const relDef = this.tableMeta.relations[key];
1554
- if (relDef && typeof value === 'object' && value !== null && !Array.isArray(value)) {
1555
- const filterObj = value;
1556
- if ('some' in filterObj || 'every' in filterObj || 'none' in filterObj) {
1557
- const relParts = [];
1558
- if (filterObj.some !== undefined)
1559
- relParts.push(`some(${this.fingerprintRelFilter(relDef.to, filterObj.some)})`);
1560
- if (filterObj.every !== undefined)
1561
- relParts.push(`every(${this.fingerprintRelFilter(relDef.to, filterObj.every)})`);
1562
- if (filterObj.none !== undefined)
1563
- relParts.push(`none(${this.fingerprintRelFilter(relDef.to, filterObj.none)})`);
1564
- parts.push(`${key}:{${relParts.join(',')}}`);
1565
- continue;
1566
- }
1567
- }
1568
- // null → distinct from value
1569
- if (value === null) {
1570
- parts.push(`${key}:null`);
1571
- continue;
1572
- }
1573
- // Operator objects
1574
- if (isWhereOperator(value)) {
1575
- const opKeys = Object.keys(value)
1576
- .filter((k) => k !== 'mode')
1577
- .sort();
1578
- const mode = value.mode;
1579
- const modeStr = mode === 'insensitive' ? ':i' : '';
1580
- parts.push(`${key}:op(${opKeys.join(',')}${modeStr})`);
1581
- continue;
1582
- }
1583
- // JSON filter
1584
- if (typeof value === 'object' && !Array.isArray(value) && isJsonFilter(value)) {
1585
- const jKeys = Object.keys(value).sort();
1586
- parts.push(`${key}:json(${jKeys.join(',')})`);
1587
- continue;
1588
- }
1589
- // Array filter
1590
- if (typeof value === 'object' && !Array.isArray(value) && isArrayFilter(value)) {
1591
- const aKeys = Object.keys(value).sort();
1592
- parts.push(`${key}:arr(${aKeys.join(',')})`);
1593
- continue;
1594
- }
1595
- // Plain equality
1596
- parts.push(`${key}:eq`);
1597
- }
1598
- return parts.join('&');
1599
- }
1600
- /**
1601
- * Fingerprint a relation filter sub-where for some/every/none.
1602
- */
1603
- fingerprintRelFilter(_targetTable, subWhere) {
1604
- const keys = Object.keys(subWhere)
1605
- .filter((k) => subWhere[k] !== undefined)
1606
- .sort();
1607
- if (keys.length === 0)
1608
- return '';
1609
- const parts = [];
1610
- for (const key of keys) {
1611
- const value = subWhere[key];
1612
- if (value === undefined)
1613
- continue;
1614
- if (value === null) {
1615
- parts.push(`${key}:null`);
1616
- }
1617
- else if (isWhereOperator(value)) {
1618
- const opKeys = Object.keys(value)
1619
- .filter((k) => k !== 'mode')
1620
- .sort();
1621
- const mode = value.mode;
1622
- const modeStr = mode === 'insensitive' ? ':i' : '';
1623
- parts.push(`${key}:op(${opKeys.join(',')}${modeStr})`);
1624
- }
1625
- else {
1626
- parts.push(`${key}:eq`);
1627
- }
1628
- }
1629
- return parts.join('&');
1630
- }
1631
- /**
1632
- * Walk a where clause and push ONLY values into `params`, in the EXACT same
1633
- * order that `buildWhereClause` pushes them. Used on cache hit to fill params
1634
- * without rebuilding SQL.
1635
- *
1636
- * @internal Exposed as package-private for testing.
1637
- */
1638
- collectWhereParams(where, params) {
1639
- const keys = Object.keys(where);
1640
- for (const key of keys) {
1641
- const value = where[key];
1642
- if (value === undefined)
1643
- continue;
1644
- if (key === 'OR') {
1645
- const orConditions = value;
1646
- if (!Array.isArray(orConditions) || orConditions.length === 0)
1647
- continue;
1648
- for (const orCond of orConditions) {
1649
- this.collectWhereParams(orCond, params);
1650
- }
1651
- continue;
1652
- }
1653
- if (key === 'AND') {
1654
- const andConditions = value;
1655
- if (!Array.isArray(andConditions) || andConditions.length === 0)
1656
- continue;
1657
- for (const andCond of andConditions) {
1658
- this.collectWhereParams(andCond, params);
1659
- }
1660
- continue;
1661
- }
1662
- if (key === 'NOT') {
1663
- const notCond = value;
1664
- this.collectWhereParams(notCond, params);
1665
- continue;
1666
- }
1667
- // Relation filters
1668
- const relationDef = this.tableMeta.relations[key];
1669
- if (relationDef && typeof value === 'object' && value !== null && !Array.isArray(value)) {
1670
- const filterObj = value;
1671
- if ('some' in filterObj || 'every' in filterObj || 'none' in filterObj) {
1672
- if (filterObj.some !== undefined)
1673
- this.collectRelFilterParams(relationDef.to, filterObj.some, params);
1674
- if (filterObj.none !== undefined)
1675
- this.collectRelFilterParams(relationDef.to, filterObj.none, params);
1676
- if (filterObj.every !== undefined)
1677
- this.collectRelFilterParams(relationDef.to, filterObj.every, params);
1678
- continue;
1679
- }
1680
- }
1681
- // null → no param pushed (IS NULL is parameterless)
1682
- if (value === null)
1683
- continue;
1684
- const rawColumn = this.toColumn(key);
1685
- // JSONB filter
1686
- if (typeof value === 'object' && !Array.isArray(value) && isJsonFilter(value)) {
1687
- const colType = this.getColumnPgType(rawColumn);
1688
- if (colType === 'json' || colType === 'jsonb') {
1689
- this.collectJsonFilterParams(value, params);
1690
- continue;
1691
- }
1692
- }
1693
- // Array filter
1694
- if (typeof value === 'object' && !Array.isArray(value) && isArrayFilter(value)) {
1695
- const colType = this.getColumnPgType(rawColumn);
1696
- if (colType.startsWith('_')) {
1697
- this.collectArrayFilterParams(value, params);
1698
- continue;
1699
- }
1700
- }
1701
- // Operator objects
1702
- if (isWhereOperator(value)) {
1703
- this.collectOperatorParams(value, params);
1704
- continue;
1705
- }
1706
- // Plain equality
1707
- params.push(value);
1708
- }
1709
- }
1710
- /** Collect params from a relation filter sub-where. Mirrors buildSubWhereForRelation. */
1711
- collectRelFilterParams(targetTable, subWhere, params) {
1712
- const meta = this.schema.tables[targetTable];
1713
- if (!meta)
1714
- return;
1715
- for (const [_field, value] of Object.entries(subWhere)) {
1716
- if (value === undefined)
1717
- continue;
1718
- if (value === null)
1719
- continue;
1720
- if (isWhereOperator(value)) {
1721
- this.collectOperatorParams(value, params);
1722
- continue;
1723
- }
1724
- params.push(value);
1725
- }
1726
- }
1727
- /** Collect params from operator clauses. Mirrors buildOperatorClauses. */
1728
- collectOperatorParams(op, params) {
1729
- if (op.gt !== undefined)
1730
- params.push(op.gt);
1731
- if (op.gte !== undefined)
1732
- params.push(op.gte);
1733
- if (op.lt !== undefined)
1734
- params.push(op.lt);
1735
- if (op.lte !== undefined)
1736
- params.push(op.lte);
1737
- if (op.not !== undefined && op.not !== null)
1738
- params.push(op.not);
1739
- if (op.in !== undefined)
1740
- params.push(op.in);
1741
- if (op.notIn !== undefined)
1742
- params.push(op.notIn);
1743
- if (op.contains !== undefined)
1744
- params.push(`%${escapeLike(op.contains)}%`);
1745
- if (op.startsWith !== undefined)
1746
- params.push(`${escapeLike(op.startsWith)}%`);
1747
- if (op.endsWith !== undefined)
1748
- params.push(`%${escapeLike(op.endsWith)}`);
1749
- }
1750
- /** Collect params from JSON filter. Mirrors buildJsonFilterClauses. */
1751
- collectJsonFilterParams(filter, params) {
1752
- if (filter.path !== undefined && filter.equals !== undefined) {
1753
- params.push(filter.path);
1754
- params.push(String(filter.equals));
1755
- }
1756
- else if (filter.equals !== undefined) {
1757
- params.push(JSON.stringify(filter.equals));
1758
- }
1759
- if (filter.contains !== undefined) {
1760
- params.push(JSON.stringify(filter.contains));
1761
- }
1762
- if (filter.hasKey !== undefined) {
1763
- params.push(filter.hasKey);
1764
- }
1765
- }
1766
- /** Collect params from array filter. Mirrors buildArrayFilterClauses. */
1767
- collectArrayFilterParams(filter, params) {
1768
- if (filter.has !== undefined)
1769
- params.push(filter.has);
1770
- if (filter.hasEvery !== undefined)
1771
- params.push(filter.hasEvery);
1772
- if (filter.hasSome !== undefined)
1773
- params.push(filter.hasSome);
1774
- // isEmpty has no params (IS NULL / IS NOT NULL)
1775
- }
1776
- /**
1777
- * Produce a fingerprint for a `with` clause tree. Recursion mirrors
1778
- * buildSelectWithRelations / buildRelationSubquery.
1779
- *
1780
- * @internal Exposed as package-private for testing.
1781
- */
1782
- withFingerprint(withClause, table, depth = 0) {
1783
- if (!withClause)
1784
- return '';
1785
- const meta = this.schema.tables[table ?? this.table];
1786
- if (!meta)
1787
- return '';
1788
- const relNames = Object.keys(withClause).sort();
1789
- const parts = [];
1790
- for (const relName of relNames) {
1791
- const spec = withClause[relName];
1792
- if (!spec)
1793
- continue;
1794
- const relDef = meta.relations[relName];
1795
- if (!relDef)
1796
- continue;
1797
- if (spec === true) {
1798
- parts.push(relName);
1799
- continue;
1800
- }
1801
- const opts = spec;
1802
- const subParts = [];
1803
- // select/omit shape
1804
- if (opts.select) {
1805
- const selKeys = Object.entries(opts.select)
1806
- .filter(([, v]) => v)
1807
- .map(([k]) => k)
1808
- .sort();
1809
- subParts.push(`sl=${selKeys.join(',')}`);
1810
- }
1811
- if (opts.omit) {
1812
- const omKeys = Object.entries(opts.omit)
1813
- .filter(([, v]) => v)
1814
- .map(([k]) => k)
1815
- .sort();
1816
- subParts.push(`om=${omKeys.join(',')}`);
1817
- }
1818
- // where shape (value-invariant)
1819
- if (opts.where) {
1820
- // Use a target-table QI if possible, or a simplified fingerprint
1821
- const wKeys = Object.keys(opts.where)
1822
- .filter((k) => opts.where[k] !== undefined)
1823
- .sort();
1824
- subParts.push(`w=${wKeys.join(',')}`);
1825
- }
1826
- // orderBy shape
1827
- if (opts.orderBy) {
1828
- const oEntries = Object.entries(opts.orderBy).map(([k, d]) => `${k}:${d}`);
1829
- subParts.push(`o=${oEntries.join(',')}`);
1830
- }
1831
- // limit presence
1832
- if (opts.limit !== undefined) {
1833
- subParts.push('l=1');
1834
- }
1835
- // nested with (recurse)
1836
- if (opts.with) {
1837
- const nested = this.withFingerprint(opts.with, relDef.to, depth + 1);
1838
- if (nested)
1839
- subParts.push(`W=(${nested})`);
1840
- }
1841
- parts.push(subParts.length > 0 ? `${relName}/{${subParts.join('/')}}` : relName);
1842
- }
1843
- return parts.join('|');
1844
- }
1845
- /**
1846
- * Collect params from a `with` clause tree. Mirrors buildSelectWithRelations +
1847
- * buildRelationSubquery param-push order.
1848
- */
1849
- collectWithParams(withClause, params, table) {
1850
- const meta = this.schema.tables[table ?? this.table];
1851
- if (!meta)
1852
- return;
1853
- for (const [relName, relSpec] of Object.entries(withClause)) {
1854
- const relDef = meta.relations[relName];
1855
- if (!relDef)
1856
- continue;
1857
- this.collectRelationSubqueryParams(relDef, relSpec, params, table ?? this.table);
1858
- }
1859
- }
1860
- /**
1861
- * Collect params from a single relation subquery. Mirrors buildRelationSubquery.
1862
- */
1863
- collectRelationSubqueryParams(relDef, spec, params, _parentRef, depth = 0) {
1864
- if (spec === true)
1865
- return; // No params for default include
1866
- const targetTable = relDef.to;
1867
- const targetMeta = this.schema.tables[targetTable];
1868
- if (!targetMeta)
1869
- return;
1870
- const willWrap = relDef.type === 'hasMany' && (spec.limit !== undefined || spec.orderBy !== undefined);
1871
- // Non-wrapped path: nested relations BEFORE where/limit
1872
- if (!willWrap && spec.with) {
1873
- for (const [nestedRelName, nestedSpec] of Object.entries(spec.with)) {
1874
- const nestedRelDef = targetMeta.relations[nestedRelName];
1875
- if (!nestedRelDef)
1876
- continue;
1877
- this.collectRelationSubqueryParams(nestedRelDef, nestedSpec, params, 'alias', depth + 1);
1878
- }
1879
- }
1880
- // where params
1881
- if (spec.where) {
1882
- for (const [, v] of Object.entries(spec.where)) {
1883
- params.push(v);
1884
- }
1885
- }
1886
- // limit param
1887
- if (spec.limit) {
1888
- params.push(Number(spec.limit));
1889
- }
1890
- // Wrapped path: nested relations AFTER where/limit (inside inner subquery)
1891
- if (willWrap && spec.with) {
1892
- for (const [nestedRelName, nestedSpec] of Object.entries(spec.with)) {
1893
- const nestedRelDef = targetMeta.relations[nestedRelName];
1894
- if (!nestedRelDef)
1895
- continue;
1896
- this.collectRelationSubqueryParams(nestedRelDef, nestedSpec, params, 'innerAlias', depth + 1);
1897
- }
1898
- }
1899
- }
1900
- /**
1901
- * Fingerprint SET clauses for update/updateMany.
1902
- * Captures key names + operator types (set/increment/etc) but not values.
1903
- */
1904
- fingerprintSet(data) {
1905
- const entries = Object.entries(data).filter(([, v]) => v !== undefined);
1906
- const parts = [];
1907
- for (const [k, v] of entries) {
1908
- if (v !== null &&
1909
- typeof v === 'object' &&
1910
- !Array.isArray(v) &&
1911
- !(v instanceof Date) &&
1912
- !(typeof Buffer !== 'undefined' && Buffer.isBuffer(v))) {
1913
- const keys = Object.keys(v);
1914
- if (keys.length === 1 && UPDATE_OPERATOR_KEYS.has(keys[0])) {
1915
- parts.push(`${k}:${keys[0]}`);
1916
- continue;
1917
- }
1918
- }
1919
- parts.push(`${k}:eq`);
1920
- }
1921
- return parts.join(',');
1922
- }
1923
- /**
1924
- * Collect SET params for update/updateMany. Mirrors buildSetClause param order.
1925
- */
1926
- collectSetParams(data, params) {
1927
- const entries = Object.entries(data).filter(([, v]) => v !== undefined);
1928
- for (const [, v] of entries) {
1929
- if (v !== null &&
1930
- typeof v === 'object' &&
1931
- !Array.isArray(v) &&
1932
- !(v instanceof Date) &&
1933
- !(typeof Buffer !== 'undefined' && Buffer.isBuffer(v))) {
1934
- const obj = v;
1935
- const keys = Object.keys(obj);
1936
- if (keys.length === 1 && UPDATE_OPERATOR_KEYS.has(keys[0])) {
1937
- params.push(obj[keys[0]]);
1938
- continue;
1939
- }
1940
- }
1941
- params.push(v);
1942
- }
1943
- }
1944
- /** Build WHERE clause from a where object (supports operators, NULL, OR) */
1945
- buildWhere(where) {
1946
- const params = [];
1947
- const clause = this.buildWhereClause(where, params);
1948
- if (!clause)
1949
- return { sql: '', params: [] };
1950
- return { sql: ` WHERE ${clause}`, params };
1951
- }
1952
- /**
1953
- * Refuse mutations with an empty predicate unless explicitly opted in.
1954
- *
1955
- * An empty `where` (e.g. `{}` or `{ id: undefined }`) resolves to a
1956
- * mutation with no filter — a common footgun when a caller's filter
1957
- * value accidentally resolves to `undefined`. This guard throws
1958
- * `ValidationError` in that case unless `allowFullTableScan: true`.
1959
- */
1960
- assertMutationHasPredicate(operation, whereSql, allowFullTableScan) {
1961
- if (whereSql.length > 0)
1962
- return;
1963
- if (allowFullTableScan === true)
1964
- return;
1965
- throw new errors_js_1.ValidationError(`[turbine] ${operation} on "${this.table}" refused: the \`where\` clause is empty. ` +
1966
- `Pass \`allowFullTableScan: true\` to opt in, or check that your filter values are defined.`);
1967
- }
1968
- /**
1969
- * Build the inner WHERE expression (without the WHERE keyword).
1970
- * Returns null if no conditions exist.
1971
- * Supports: equality, operators, NULL, OR, AND, NOT, relation filters (some/every/none).
1972
- */
1973
- buildWhereClause(where, params) {
1974
- const keys = Object.keys(where);
1975
- if (keys.length === 0)
1976
- return null;
1977
- const andClauses = [];
1978
- for (const key of keys) {
1979
- const value = where[key];
1980
- if (value === undefined)
1981
- continue;
1982
- // Handle OR special key
1983
- if (key === 'OR') {
1984
- const orConditions = value;
1985
- if (!Array.isArray(orConditions) || orConditions.length === 0)
1986
- continue;
1987
- const orClauses = [];
1988
- for (const orCond of orConditions) {
1989
- const sub = this.buildWhereClause(orCond, params);
1990
- if (sub)
1991
- orClauses.push(sub);
1992
- }
1993
- if (orClauses.length > 0) {
1994
- andClauses.push(`(${orClauses.join(' OR ')})`);
1995
- }
1996
- continue;
1997
- }
1998
- // Handle AND special key
1999
- if (key === 'AND') {
2000
- const andConditions = value;
2001
- if (!Array.isArray(andConditions) || andConditions.length === 0)
2002
- continue;
2003
- for (const andCond of andConditions) {
2004
- const sub = this.buildWhereClause(andCond, params);
2005
- if (sub)
2006
- andClauses.push(sub);
2007
- }
2008
- continue;
2009
- }
2010
- // Handle NOT special key
2011
- if (key === 'NOT') {
2012
- const notCond = value;
2013
- const sub = this.buildWhereClause(notCond, params);
2014
- if (sub)
2015
- andClauses.push(`NOT (${sub})`);
2016
- continue;
2017
- }
2018
- // Handle relation filters: { posts: { some: { published: true } } }
2019
- const relationDef = this.tableMeta.relations[key];
2020
- if (relationDef && typeof value === 'object' && value !== null && !Array.isArray(value)) {
2021
- const filterObj = value;
2022
- // Check if this is a relation filter (has some/every/none keys)
2023
- if ('some' in filterObj || 'every' in filterObj || 'none' in filterObj) {
2024
- const relClause = this.buildRelationFilter(key, relationDef, filterObj, params);
2025
- if (relClause)
2026
- andClauses.push(relClause);
2027
- continue;
2028
- }
2029
- }
2030
- const rawColumn = this.toColumn(key);
2031
- const column = quoteIdent(rawColumn);
2032
- // Handle null → IS NULL
2033
- if (value === null) {
2034
- andClauses.push(`${column} IS NULL`);
2035
- continue;
2036
- }
2037
- // Handle JSONB filter operators (for json/jsonb columns)
2038
- if (typeof value === 'object' && !Array.isArray(value) && isJsonFilter(value)) {
2039
- const colType = this.getColumnPgType(rawColumn);
2040
- if (colType === 'json' || colType === 'jsonb') {
2041
- const jsonClauses = this.buildJsonFilterClauses(column, value, params);
2042
- andClauses.push(...jsonClauses);
2043
- continue;
2044
- }
2045
- // Strict validation: a JSON-only operator on a non-JSON column was almost
2046
- // certainly a typo or schema mismatch. Silently falling through to plain
2047
- // equality (the previous behaviour) wasted hours of debugging time. Only
2048
- // throw when the operator is unambiguously JSON-specific — `contains` is
2049
- // shared with WhereOperator's LIKE so it must continue to fall through.
2050
- const jsonKey = findJsonUniqueKey(value);
2051
- if (jsonKey) {
2052
- throw new errors_js_1.ValidationError(`[turbine] Column "${rawColumn}" on table "${this.table}" is not a JSON column ` +
2053
- `(actual type: ${colType}); cannot apply JSON operator '${jsonKey}'.`);
2054
- }
2055
- }
2056
- // Handle Array filter operators (for array columns)
2057
- if (typeof value === 'object' && !Array.isArray(value) && isArrayFilter(value)) {
2058
- const colType = this.getColumnPgType(rawColumn);
2059
- if (colType.startsWith('_')) {
2060
- const arrayClauses = this.buildArrayFilterClauses(column, value, params, colType);
2061
- andClauses.push(...arrayClauses);
2062
- continue;
2063
- }
2064
- // Strict validation: array operators (`has`, `hasEvery`, ...) on a
2065
- // non-array column always indicate a mistake. None of these keys
2066
- // overlap with other filter shapes so we can throw unconditionally.
2067
- const arrayKey = findArrayUniqueKey(value);
2068
- if (arrayKey) {
2069
- throw new errors_js_1.ValidationError(`[turbine] Column "${rawColumn}" on table "${this.table}" is not an array column ` +
2070
- `(actual type: ${colType}); cannot apply array operator '${arrayKey}'.`);
2071
- }
2072
- }
2073
- // Handle operator objects
2074
- if (isWhereOperator(value)) {
2075
- const opClauses = this.buildOperatorClauses(column, value, params);
2076
- andClauses.push(...opClauses);
2077
- continue;
2078
- }
2079
- // Plain equality
2080
- params.push(value);
2081
- andClauses.push(`${column} = $${params.length}`);
2082
- }
2083
- if (andClauses.length === 0)
2084
- return null;
2085
- return andClauses.join(' AND ');
2086
- }
2087
- /**
2088
- * Build relation filter SQL: WHERE EXISTS / NOT EXISTS subquery
2089
- * Supports: some (EXISTS), every (NOT EXISTS ... NOT), none (NOT EXISTS)
2090
- */
2091
- buildRelationFilter(_relName, relDef, filterObj, params) {
2092
- const targetTable = relDef.to;
2093
- const targetMeta = this.schema.tables[targetTable];
2094
- if (!targetMeta)
2095
- return null;
2096
- const qt = quoteIdent(targetTable);
2097
- const qSelf = quoteIdent(this.table);
2098
- const clauses = [];
2099
- // Correlation: link child table to parent table
2100
- let correlation;
2101
- if (relDef.type === 'hasMany' || relDef.type === 'hasOne') {
2102
- // parent.pk = child.fk
2103
- correlation = `${qt}.${quoteIdent(relDef.foreignKey)} = ${qSelf}.${quoteIdent(relDef.referenceKey)}`;
2104
- }
2105
- else {
2106
- // belongsTo: parent.fk = child.pk
2107
- correlation = `${qt}.${quoteIdent(relDef.referenceKey)} = ${qSelf}.${quoteIdent(relDef.foreignKey)}`;
2108
- }
2109
- // "some": EXISTS (SELECT 1 FROM target WHERE correlation AND filter)
2110
- if (filterObj.some !== undefined) {
2111
- const subWhere = filterObj.some;
2112
- const filterClause = this.buildSubWhereForRelation(targetTable, subWhere, params);
2113
- const fullWhere = filterClause ? `${correlation} AND ${filterClause}` : correlation;
2114
- clauses.push(`EXISTS (SELECT 1 FROM ${qt} WHERE ${fullWhere})`);
2115
- }
2116
- // "none": NOT EXISTS (SELECT 1 FROM target WHERE correlation AND filter)
2117
- if (filterObj.none !== undefined) {
2118
- const subWhere = filterObj.none;
2119
- const filterClause = this.buildSubWhereForRelation(targetTable, subWhere, params);
2120
- const fullWhere = filterClause ? `${correlation} AND ${filterClause}` : correlation;
2121
- clauses.push(`NOT EXISTS (SELECT 1 FROM ${qt} WHERE ${fullWhere})`);
2122
- }
2123
- // "every": NOT EXISTS (SELECT 1 FROM target WHERE correlation AND NOT (filter))
2124
- if (filterObj.every !== undefined) {
2125
- const subWhere = filterObj.every;
2126
- const filterClause = this.buildSubWhereForRelation(targetTable, subWhere, params);
2127
- if (filterClause) {
2128
- clauses.push(`NOT EXISTS (SELECT 1 FROM ${qt} WHERE ${correlation} AND NOT (${filterClause}))`);
2129
- }
2130
- else {
2131
- // "every" with empty filter = true (all match trivially)
2132
- }
2133
- }
2134
- return clauses.length > 0 ? clauses.join(' AND ') : null;
2135
- }
2136
- /**
2137
- * Build WHERE clause conditions for a relation filter subquery.
2138
- * Uses the target table's column mapping to resolve field names.
2139
- */
2140
- buildSubWhereForRelation(targetTable, subWhere, params) {
2141
- const meta = this.schema.tables[targetTable];
2142
- if (!meta)
2143
- return null;
2144
- const qt = quoteIdent(targetTable);
2145
- const conditions = [];
2146
- for (const [field, value] of Object.entries(subWhere)) {
2147
- if (value === undefined)
2148
- continue;
2149
- const col = meta.columnMap[field] ?? (0, schema_js_1.camelToSnake)(field);
2150
- const qCol = `${qt}.${quoteIdent(col)}`;
2151
- if (value === null) {
2152
- conditions.push(`${qCol} IS NULL`);
2153
- continue;
2154
- }
2155
- if (isWhereOperator(value)) {
2156
- const opClauses = this.buildOperatorClauses(qCol, value, params);
2157
- conditions.push(...opClauses);
2158
- continue;
2159
- }
2160
- params.push(value);
2161
- conditions.push(`${qCol} = $${params.length}`);
2162
- }
2163
- return conditions.length > 0 ? conditions.join(' AND ') : null;
2164
- }
2165
- /**
2166
- * Build SQL clauses for a single operator object on a column.
2167
- * Each operator key becomes its own clause, all ANDed together.
2168
- */
2169
- buildOperatorClauses(column, op, params) {
2170
- const clauses = [];
2171
- if (op.gt !== undefined) {
2172
- params.push(op.gt);
2173
- clauses.push(`${column} > $${params.length}`);
2174
- }
2175
- if (op.gte !== undefined) {
2176
- params.push(op.gte);
2177
- clauses.push(`${column} >= $${params.length}`);
2178
- }
2179
- if (op.lt !== undefined) {
2180
- params.push(op.lt);
2181
- clauses.push(`${column} < $${params.length}`);
2182
- }
2183
- if (op.lte !== undefined) {
2184
- params.push(op.lte);
2185
- clauses.push(`${column} <= $${params.length}`);
2186
- }
2187
- if (op.not !== undefined) {
2188
- if (op.not === null) {
2189
- clauses.push(`${column} IS NOT NULL`);
2190
- }
2191
- else {
2192
- params.push(op.not);
2193
- clauses.push(`${column} != $${params.length}`);
2194
- }
2195
- }
2196
- if (op.in !== undefined) {
2197
- params.push(op.in);
2198
- clauses.push(`${column} = ANY($${params.length})`);
2199
- }
2200
- if (op.notIn !== undefined) {
2201
- params.push(op.notIn);
2202
- clauses.push(`${column} != ALL($${params.length})`);
2203
- }
2204
- // Use ILIKE for case-insensitive mode, LIKE otherwise
2205
- const likeOp = op.mode === 'insensitive' ? 'ILIKE' : 'LIKE';
2206
- if (op.contains !== undefined) {
2207
- params.push(`%${escapeLike(op.contains)}%`);
2208
- clauses.push(`${column} ${likeOp} $${params.length} ESCAPE '\\'`);
2209
- }
2210
- if (op.startsWith !== undefined) {
2211
- params.push(`${escapeLike(op.startsWith)}%`);
2212
- clauses.push(`${column} ${likeOp} $${params.length} ESCAPE '\\'`);
2213
- }
2214
- if (op.endsWith !== undefined) {
2215
- params.push(`%${escapeLike(op.endsWith)}`);
2216
- clauses.push(`${column} ${likeOp} $${params.length} ESCAPE '\\'`);
2217
- }
2218
- return clauses;
2219
- }
2220
- /** Build ORDER BY clause from an object */
2221
- buildOrderBy(orderBy) {
2222
- const meta = this.schema.tables[this.table];
2223
- return Object.entries(orderBy)
2224
- .map(([key, dir]) => {
2225
- if (meta && !(key in meta.columnMap)) {
2226
- throw new errors_js_1.ValidationError(`Unknown column "${key}" in orderBy for table "${this.table}"`);
2227
- }
2228
- const safeDir = dir.toLowerCase() === 'desc' ? 'DESC' : 'ASC';
2229
- return `${this.toSqlColumn(key)} ${safeDir}`;
2230
- })
2231
- .join(', ');
2232
- }
2233
- /** Parse a flat row: convert snake_case to camelCase + Date coercion */
2234
- parseRow(row, table) {
2235
- const parsed = {};
2236
- const meta = this.schema.tables[table];
2237
- if (meta) {
2238
- // Fast path: use pre-computed maps (avoids regex per column per row)
2239
- const reverseMap = meta.reverseColumnMap;
2240
- const dateCols = meta.dateColumns;
2241
- const keys = Object.keys(row);
2242
- for (let i = 0; i < keys.length; i++) {
2243
- const col = keys[i];
2244
- const value = row[col];
2245
- const field = reverseMap[col] ?? col; // fall back to raw col name, not regex
2246
- if (dateCols.has(col) && value !== null && !(value instanceof Date)) {
2247
- parsed[field] = new Date(value);
2248
- }
2249
- else {
2250
- parsed[field] = value;
2251
- }
2252
- }
2253
- }
2254
- else {
2255
- // Fallback: no metadata, use regex conversion
2256
- for (const [col, value] of Object.entries(row)) {
2257
- parsed[(0, schema_js_1.snakeToCamel)(col)] = value;
2258
- }
2259
- }
2260
- return parsed;
2261
- }
2262
- /** Parse a row that may contain JSON nested relation columns */
2263
- parseNestedRow(row, table) {
2264
- const parsed = this.parseRow(row, table);
2265
- const meta = this.schema.tables[table];
2266
- if (!meta)
2267
- return parsed;
2268
- for (const [relName, relDef] of Object.entries(meta.relations)) {
2269
- const rawValue = row[relName];
2270
- if (rawValue === undefined)
2271
- continue;
2272
- // --- Short-circuit: skip JSON.parse for common empty/null cases ---
2273
- // hasMany returns '[]' (from COALESCE(..., '[]'::json)); belongsTo/hasOne returns null
2274
- if (rawValue === null || rawValue === 'null') {
2275
- parsed[relName] = null;
2276
- continue;
2277
- }
2278
- if (rawValue === '[]') {
2279
- parsed[relName] = [];
2280
- continue;
2281
- }
2282
- if (Array.isArray(rawValue) && rawValue.length === 0) {
2283
- parsed[relName] = [];
2284
- continue;
2285
- }
2286
- // --- Non-empty values: full parse path ---
2287
- if (typeof rawValue === 'string') {
2288
- try {
2289
- const jsonVal = JSON.parse(rawValue);
2290
- // After parsing, apply parseRow to each item for snake→camel + date coercion
2291
- if (Array.isArray(jsonVal)) {
2292
- parsed[relName] = jsonVal.map((item) => typeof item === 'object' && item !== null
2293
- ? this.parseRow(item, relDef.to)
2294
- : item);
2295
- }
2296
- else if (typeof jsonVal === 'object' && jsonVal !== null) {
2297
- parsed[relName] = this.parseRow(jsonVal, relDef.to);
2298
- }
2299
- else {
2300
- parsed[relName] = jsonVal;
2301
- }
2302
- }
2303
- catch {
2304
- console.warn(`[turbine] Warning: Failed to parse JSON for relation "${relName}" on table "${this.table}". Using raw value.`);
2305
- parsed[relName] = rawValue;
2306
- }
2307
- }
2308
- else if (Array.isArray(rawValue)) {
2309
- parsed[relName] = rawValue.map((item) => typeof item === 'object' && item !== null ? this.parseRow(item, relDef.to) : item);
2310
- }
2311
- else if (typeof rawValue === 'object' && rawValue !== null) {
2312
- parsed[relName] = this.parseRow(rawValue, relDef.to);
2313
- }
2314
- else {
2315
- parsed[relName] = rawValue;
2316
- }
2317
- }
2318
- return parsed;
2319
- }
2320
- /**
2321
- * Build a SELECT clause that includes both base columns and nested relation subqueries.
2322
- *
2323
- * For each relation specified in the `with` clause, this method generates a correlated
2324
- * subquery using PostgreSQL's `json_agg(json_build_object(...))` pattern. The result
2325
- * is a single SQL SELECT clause that resolves the full object tree in one query --
2326
- * no N+1 problem.
2327
- *
2328
- * **How it works:**
2329
- * 1. Resolves the base columns for the root table (all columns, or a subset via `columnsList`).
2330
- * 2. Iterates over each key in the `with` clause, looking up the relation definition.
2331
- * 3. For each relation, delegates to {@link buildRelationSubquery} to generate a
2332
- * correlated subquery that returns JSON (array for hasMany, object for belongsTo/hasOne).
2333
- * 4. Each subquery is aliased as the relation name in the final SELECT.
2334
- *
2335
- * **aliasCounter:** A shared `{ n: number }` object is passed through all nesting levels.
2336
- * Each call to `buildRelationSubquery` increments it to produce unique table aliases
2337
- * (`t0`, `t1`, `t2`, ...) across arbitrarily deep relation trees, preventing alias
2338
- * collisions in the generated SQL.
2339
- *
2340
- * **Example output:**
2341
- * ```sql
2342
- * "users"."id", "users"."name", "users"."email",
2343
- * (SELECT COALESCE(json_agg(json_build_object('id', t0."id", 'title', t0."title")), '[]'::json)
2344
- * FROM "posts" t0 WHERE t0."user_id" = "users"."id") AS "posts"
2345
- * ```
2346
- *
2347
- * @param table - The root table name (e.g. `"users"`).
2348
- * @param withClause - An object mapping relation names to their include specs
2349
- * (`true` for default inclusion, or `WithOptions` for select/omit/where/orderBy/limit).
2350
- * @param params - Shared parameter array for parameterized values (`$1`, `$2`, ...).
2351
- * Nested where/limit values are pushed here to prevent SQL injection.
2352
- * @param columnsList - Optional subset of columns to include in the SELECT. When `null`
2353
- * or omitted, all columns from the table's schema metadata are used.
2354
- * @param depth - Current nesting depth, passed through to {@link buildRelationSubquery}
2355
- * for circular-relation detection. Defaults to `0` at the top level.
2356
- * @param path - Breadcrumb trail of relation names traversed so far, used in error
2357
- * messages when circular or too-deep nesting is detected.
2358
- * @returns A complete SELECT clause string (without the `SELECT` keyword) containing
2359
- * base columns and relation subqueries.
2360
- */
2361
- buildSelectWithRelations(table, withClause, params, columnsList, depth, path) {
2362
- const meta = this.schema.tables[table];
2363
- if (!meta)
2364
- throw new errors_js_1.ValidationError(`[turbine] Unknown table "${table}"`);
2365
- const cols = columnsList ?? meta.allColumns;
2366
- const qtbl = quoteIdent(table);
2367
- const baseCols = cols.map((col) => `${qtbl}.${quoteIdent(col)}`).join(', ');
2368
- const relationSelects = [];
2369
- const aliasCounter = { n: 0 };
2370
- for (const [relName, relSpec] of Object.entries(withClause)) {
2371
- const relDef = meta.relations[relName];
2372
- if (!relDef) {
2373
- throw new errors_js_1.RelationError(`[turbine] Unknown relation "${relName}" on table "${table}". ` +
2374
- `Available: ${Object.keys(meta.relations).join(', ')}`);
2375
- }
2376
- // The main table is not aliased, so pass table name as parentRef
2377
- const subquery = this.buildRelationSubquery(relDef, relSpec, params, table, aliasCounter, depth, path);
2378
- relationSelects.push(`(${subquery}) AS ${quoteIdent(relName)}`);
2379
- }
2380
- return [baseCols, ...relationSelects].join(', ');
2381
- }
2382
- /**
2383
- * Generate a correlated subquery that returns JSON for a single relation.
2384
- *
2385
- * This is the core of Turbine's single-query nested relation strategy. For a given
2386
- * relation (e.g. `posts` on a `users` query), it produces a self-contained SQL subquery
2387
- * that PostgreSQL evaluates per parent row, returning either a JSON array (hasMany) or
2388
- * a single JSON object (belongsTo / hasOne).
2389
- *
2390
- * ### Algorithm overview
2391
- *
2392
- * 1. **Alias generation:** Allocates a unique alias (`t0`, `t1`, ...) from the shared
2393
- * `aliasCounter` so that deeply nested subqueries never collide.
2394
- *
2395
- * 2. **Column resolution:** Honors `select` / `omit` options to control which columns
2396
- * appear in the output JSON.
2397
- *
2398
- * 3. **`json_build_object`:** Builds a JSON object for each row by mapping camelCase
2399
- * field names to their column values:
2400
- * ```sql
2401
- * json_build_object('id', t0."id", 'title', t0."title", 'createdAt', t0."created_at")
2402
- * ```
2403
- *
2404
- * 4. **`json_agg` wrapping (hasMany):** For one-to-many relations, wraps the
2405
- * `json_build_object` call in `json_agg(...)` to aggregate all matching child rows
2406
- * into a JSON array. Uses `COALESCE(..., '[]'::json)` so the result is never NULL.
2407
- * For belongsTo / hasOne, no aggregation is used -- just the single JSON object
2408
- * with `LIMIT 1`.
2409
- *
2410
- * 5. **Correlation (WHERE clause):** Links the subquery to the parent row:
2411
- * - **hasMany:** `alias.foreignKey = parentRef.referenceKey`
2412
- * (e.g. `t0."user_id" = "users"."id"` -- child FK points to parent PK)
2413
- * - **belongsTo / hasOne:** `alias.referenceKey = parentRef.foreignKey`
2414
- * (e.g. `t0."id" = "posts"."author_id"` -- parent FK points to child PK)
2415
- *
2416
- * 6. **Recursion:** If the spec includes a nested `with` clause, this method calls
2417
- * itself recursively for each nested relation, passing the current alias as
2418
- * `parentRef`. The nested subquery appears as an additional key in the
2419
- * `json_build_object` call, wrapped in `COALESCE(..., '[]'::json)`.
2420
- * Depth is incremented and capped at 10 to guard against circular relations.
2421
- *
2422
- * 7. **LIMIT / ORDER BY wrapping:** For hasMany relations with `limit` or `orderBy`,
2423
- * the query is restructured into a two-level form:
2424
- * ```sql
2425
- * SELECT COALESCE(json_agg(json_build_object(...)), '[]'::json)
2426
- * FROM (
2427
- * SELECT t0.* FROM "posts" t0
2428
- * WHERE t0."user_id" = "users"."id"
2429
- * ORDER BY t0."created_at" DESC
2430
- * LIMIT $1
2431
- * ) t0i
2432
- * ```
2433
- * This ensures LIMIT and ORDER BY apply to the raw rows *before* `json_agg`
2434
- * aggregation. Without the inner subquery, LIMIT would be meaningless because
2435
- * `json_agg` produces a single aggregated row.
2436
- *
2437
- * 8. **Parameter threading:** All user-supplied values (where filters, limit) are
2438
- * pushed to the shared `params` array with `$N` placeholders. No string
2439
- * interpolation of user data ever occurs -- all identifiers go through
2440
- * `quoteIdent()` and all values are parameterized.
2441
- *
2442
- * ### Example output (hasMany with nested relation)
2443
- * ```sql
2444
- * SELECT COALESCE(json_agg(json_build_object(
2445
- * 'id', t0."id",
2446
- * 'title', t0."title",
2447
- * 'comments', COALESCE((
2448
- * SELECT COALESCE(json_agg(json_build_object('id', t1."id", 'body', t1."body")), '[]'::json)
2449
- * FROM "comments" t1 WHERE t1."post_id" = t0."id"
2450
- * ), '[]'::json)
2451
- * )), '[]'::json) FROM "posts" t0 WHERE t0."user_id" = "users"."id"
2452
- * ```
2453
- *
2454
- * @param relDef - The relation definition from schema metadata (contains `to`, `type`,
2455
- * `foreignKey`, `referenceKey`).
2456
- * @param spec - Either `true` (include with defaults) or a `WithOptions` object that
2457
- * can specify `select`, `omit`, `where`, `orderBy`, `limit`, and nested `with`.
2458
- * @param params - Shared parameter array. User-supplied values are pushed here and
2459
- * referenced as `$1`, `$2`, etc. in the generated SQL.
2460
- * @param parentRef - The alias (e.g. `"t0"`) or table name (e.g. `"users"`) of the
2461
- * parent query. Used to build the correlated WHERE clause that ties
2462
- * child rows to their parent row.
2463
- * @param aliasCounter - Shared mutable counter (`{ n: number }`) for generating unique
2464
- * table aliases (`t0`, `t1`, `t2`, ...) across all nesting levels.
2465
- * Each call increments `n` by 1.
2466
- * @param depth - Current nesting depth (starts at `0`). Incremented on each recursive
2467
- * call. If it reaches 10, a {@link CircularRelationError} is thrown.
2468
- * @param path - Breadcrumb trail of relation/table names traversed so far
2469
- * (e.g. `["users", "posts", "comments"]`). Used in the error message
2470
- * when circular or too-deep nesting is detected.
2471
- * @returns A complete SQL subquery string (without surrounding parentheses) that
2472
- * evaluates to a JSON array (hasMany) or a JSON object (belongsTo/hasOne).
2473
- */
2474
- buildRelationSubquery(relDef, spec, params, parentRef, aliasCounter, depth, path) {
2475
- const currentDepth = depth ?? 0;
2476
- const currentPath = path ?? [this.table];
2477
- const targetTable = relDef.to;
2478
- // Hard depth cap — the `with` clause is a finite JSON structure so users can't
2479
- // create true infinite recursion, but extremely deep nesting (10+ levels) produces
2480
- // unmanageably large SQL. Back-references (e.g. posts → user → posts) are allowed
2481
- // since they are legitimate queries (Prisma supports the same pattern).
2482
- if (currentDepth >= 10) {
2483
- throw new errors_js_1.CircularRelationError([...currentPath, targetTable]);
2484
- }
2485
- const targetMeta = this.schema.tables[targetTable];
2486
- if (!targetMeta)
2487
- throw new errors_js_1.RelationError(`[turbine] Unknown relation target "${targetTable}"`);
2488
- // Generate a unique alias: t0, t1, t2, ...
2489
- const alias = `t${aliasCounter.n++}`;
2490
- // Resolve which columns to include based on select/omit
2491
- let targetColumns = targetMeta.allColumns;
2492
- if (spec !== true && spec.select) {
2493
- const selectedFields = Object.entries(spec.select)
2494
- .filter(([, v]) => v)
2495
- .map(([k]) => targetMeta.columnMap[k] ?? (0, schema_js_1.camelToSnake)(k));
2496
- targetColumns = selectedFields.filter((col) => targetMeta.allColumns.includes(col));
2497
- }
2498
- else if (spec !== true && spec.omit) {
2499
- const omittedFields = new Set(Object.entries(spec.omit)
2500
- .filter(([, v]) => v)
2501
- .map(([k]) => targetMeta.columnMap[k] ?? (0, schema_js_1.camelToSnake)(k)));
2502
- targetColumns = targetMeta.allColumns.filter((col) => !omittedFields.has(col));
2503
- }
2504
- // Build json_build_object pairs for resolved columns
2505
- const jsonPairs = targetColumns.map((col) => `'${escSingleQuote(targetMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col))}', ${alias}.${quoteIdent(col)}`);
2506
- // Determine if this hasMany will take the wrapped subquery path (LIMIT or ORDER BY).
2507
- // When wrapping, nested relations are built in the wrapped path referencing innerAlias,
2508
- // so we must NOT build them here (they would push orphaned params).
2509
- const willWrap = relDef.type === 'hasMany' && spec !== true && (spec.limit !== undefined || spec.orderBy !== undefined);
2510
- // Nested relations — only in the non-wrapped path (wrapped path builds them separately)
2511
- if (!willWrap && spec !== true && spec.with) {
2512
- for (const [nestedRelName, nestedSpec] of Object.entries(spec.with)) {
2513
- const nestedRelDef = targetMeta.relations[nestedRelName];
2514
- if (!nestedRelDef) {
2515
- throw new errors_js_1.RelationError(`[turbine] Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
2516
- `Available: ${Object.keys(targetMeta.relations).join(', ')}`);
2517
- }
2518
- // Recursively build nested subquery, passing THIS alias as the parent reference
2519
- const nestedSubquery = this.buildRelationSubquery(nestedRelDef, nestedSpec, params, alias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name]);
2520
- // Use '[]'::json for hasMany (empty array), NULL for belongsTo/hasOne (no object)
2521
- const fallback = nestedRelDef.type === 'hasMany' ? "'[]'::json" : 'NULL';
2522
- jsonPairs.push(`'${escSingleQuote(nestedRelName)}', COALESCE((${nestedSubquery}), ${fallback})`);
2523
- }
2524
- }
2525
- const jsonObj = `json_build_object(${jsonPairs.join(', ')})`;
2526
- // Quote parent ref — can be a table name or auto-generated alias
2527
- const qParent = quoteIdent(parentRef);
2528
- const qTarget = quoteIdent(targetTable);
2529
- // Build ORDER BY for json_agg
2530
- let orderClause = '';
2531
- if (spec !== true && spec.orderBy) {
2532
- const orders = Object.entries(spec.orderBy)
2533
- .map(([k, dir]) => {
2534
- const col = (0, schema_js_1.camelToSnake)(k);
2535
- if (!targetMeta.allColumns.includes(col)) {
2536
- throw new errors_js_1.ValidationError(`[turbine] Unknown column "${k}" in orderBy for table "${targetTable}"`);
2537
- }
2538
- const safeDir = dir.toLowerCase() === 'desc' ? 'DESC' : 'ASC';
2539
- return `${alias}.${quoteIdent(col)} ${safeDir}`;
2540
- })
2541
- .join(', ');
2542
- orderClause = ` ORDER BY ${orders}`;
2543
- }
2544
- // Build WHERE — correlate to parent via parentRef (alias or table name).
2545
- // For hasMany: target has FK, so alias.fk = parentRef.pk
2546
- // For belongsTo: source has FK, so alias.pk = parentRef.fk (reversed)
2547
- let whereClause;
2548
- if (relDef.type === 'belongsTo' || relDef.type === 'hasOne') {
2549
- whereClause = `${alias}.${quoteIdent(relDef.referenceKey)} = ${qParent}.${quoteIdent(relDef.foreignKey)}`;
2550
- }
2551
- else {
2552
- whereClause = `${alias}.${quoteIdent(relDef.foreignKey)} = ${qParent}.${quoteIdent(relDef.referenceKey)}`;
2553
- }
2554
- // Additional filters — properly parameterized
2555
- if (spec !== true && spec.where) {
2556
- for (const [k, v] of Object.entries(spec.where)) {
2557
- const col = (0, schema_js_1.camelToSnake)(k);
2558
- if (!targetMeta.allColumns.includes(col)) {
2559
- throw new errors_js_1.ValidationError(`[turbine] Unknown column "${k}" in where for table "${targetTable}"`);
2560
- }
2561
- params.push(v);
2562
- whereClause += ` AND ${alias}.${quoteIdent(col)} = $${params.length}`;
2563
- }
2564
- }
2565
- // LIMIT
2566
- let limitClause = '';
2567
- if (spec !== true && spec.limit) {
2568
- params.push(Number(spec.limit));
2569
- limitClause = ` LIMIT $${params.length}`;
2570
- }
2571
- if (relDef.type === 'hasMany') {
2572
- // When LIMIT or ORDER BY is used, wrap in a subquery so LIMIT applies to rows
2573
- // BEFORE json_agg aggregation (otherwise LIMIT on aggregated result is meaningless)
2574
- if (limitClause || orderClause) {
2575
- const innerAlias = `${alias}i`;
2576
- // Rewrite: SELECT json_agg(json_build_object(...)) FROM (SELECT * FROM table WHERE ... ORDER BY ... LIMIT N) AS alias
2577
- // Inner SELECT always needs all columns for WHERE/ORDER to work; json_build_object filters later
2578
- const innerSql = `SELECT ${targetMeta.allColumns.map((c) => `${alias}.${quoteIdent(c)}`).join(', ')} FROM ${qTarget} ${alias} WHERE ${whereClause}${orderClause}${limitClause}`;
2579
- // For the json_build_object, reference the inner alias — only include resolved columns
2580
- const innerJsonPairs = targetColumns.map((col) => `'${escSingleQuote(targetMeta.reverseColumnMap[col] ?? (0, schema_js_1.snakeToCamel)(col))}', ${innerAlias}.${quoteIdent(col)}`);
2581
- // Build nested relation subqueries referencing innerAlias
2582
- if (spec !== true && spec.with) {
2583
- for (const [nestedRelName, nestedSpec] of Object.entries(spec.with)) {
2584
- const nestedRelDef = targetMeta.relations[nestedRelName];
2585
- if (!nestedRelDef) {
2586
- throw new errors_js_1.RelationError(`[turbine] Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
2587
- `Available: ${Object.keys(targetMeta.relations).join(', ')}`);
2588
- }
2589
- const nestedSub = this.buildRelationSubquery(nestedRelDef, nestedSpec, params, innerAlias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name]);
2590
- const fallback = nestedRelDef.type === 'hasMany' ? "'[]'::json" : 'NULL';
2591
- innerJsonPairs.push(`'${escSingleQuote(nestedRelName)}', COALESCE((${nestedSub}), ${fallback})`);
2592
- }
2593
- }
2594
- const innerJsonObj = `json_build_object(${innerJsonPairs.join(', ')})`;
2595
- return `SELECT COALESCE(json_agg(${innerJsonObj}), '[]'::json) FROM (${innerSql}) ${innerAlias}`;
2596
- }
2597
- return `SELECT COALESCE(json_agg(${jsonObj}${orderClause}), '[]'::json) FROM ${qTarget} ${alias} WHERE ${whereClause}`;
2598
- }
2599
- // belongsTo / hasOne — return single object
2600
- return `SELECT ${jsonObj} FROM ${qTarget} ${alias} WHERE ${whereClause} LIMIT 1`;
2601
- }
2602
- /**
2603
- * Get the Postgres type for a column (e.g. 'jsonb', 'text', '_int4').
2604
- * Used to detect JSONB/array columns for specialized operators.
2605
- * Uses pre-computed Map for O(1) lookup instead of linear scan.
2606
- */
2607
- getColumnPgType(column) {
2608
- return this.columnPgTypeMap.get(column) ?? 'text';
2609
- }
2610
- /**
2611
- * Get the Postgres base element type for an array column.
2612
- * E.g. '_text' → 'text', '_int4' → 'integer'
2613
- */
2614
- getArrayElementType(pgType) {
2615
- const baseType = pgType.startsWith('_') ? pgType.slice(1) : pgType;
2616
- const typeMap = {
2617
- int2: 'smallint',
2618
- int4: 'integer',
2619
- int8: 'bigint',
2620
- float4: 'real',
2621
- float8: 'double precision',
2622
- bool: 'boolean',
2623
- text: 'text',
2624
- varchar: 'text',
2625
- uuid: 'uuid',
2626
- timestamptz: 'timestamptz',
2627
- timestamp: 'timestamp',
2628
- jsonb: 'jsonb',
2629
- json: 'json',
2630
- };
2631
- return typeMap[baseType] ?? 'text';
2632
- }
2633
- /**
2634
- * Build SQL clauses for JSONB filter operators on a column.
2635
- * Supports: path, equals, contains, hasKey.
2636
- */
2637
- buildJsonFilterClauses(column, filter, params) {
2638
- const clauses = [];
2639
- if (filter.path !== undefined && filter.equals !== undefined) {
2640
- // Path access + equals: column #>> $N::text[] = $M
2641
- params.push(filter.path);
2642
- const pathParam = params.length;
2643
- params.push(String(filter.equals));
2644
- clauses.push(`${column} #>> $${pathParam}::text[] = $${params.length}`);
2645
- }
2646
- else if (filter.equals !== undefined) {
2647
- // Containment equality: column @> $N::jsonb
2648
- params.push(JSON.stringify(filter.equals));
2649
- clauses.push(`${column} @> $${params.length}::jsonb`);
2650
- }
2651
- if (filter.contains !== undefined) {
2652
- // Containment: column @> $N::jsonb
2653
- params.push(JSON.stringify(filter.contains));
2654
- clauses.push(`${column} @> $${params.length}::jsonb`);
2655
- }
2656
- if (filter.hasKey !== undefined) {
2657
- // Key existence: column ? $N
2658
- params.push(filter.hasKey);
2659
- clauses.push(`${column} ? $${params.length}`);
2660
- }
2661
- return clauses;
2662
- }
2663
- /**
2664
- * Build SQL clauses for Array filter operators on a column.
2665
- * Supports: has, hasEvery, hasSome, isEmpty.
2666
- */
2667
- buildArrayFilterClauses(column, filter, params, pgType) {
2668
- const clauses = [];
2669
- const elementType = this.getArrayElementType(pgType);
2670
- if (filter.has !== undefined) {
2671
- // value = ANY(column)
2672
- params.push(filter.has);
2673
- clauses.push(`$${params.length} = ANY(${column})`);
2674
- }
2675
- if (filter.hasEvery !== undefined) {
2676
- // column @> ARRAY[...]::type[]
2677
- params.push(filter.hasEvery);
2678
- clauses.push(`${column} @> $${params.length}::${elementType}[]`);
2679
- }
2680
- if (filter.hasSome !== undefined) {
2681
- // column && ARRAY[...]::type[]
2682
- params.push(filter.hasSome);
2683
- clauses.push(`${column} && $${params.length}::${elementType}[]`);
2684
- }
2685
- if (filter.isEmpty === true) {
2686
- // array_length(column, 1) IS NULL
2687
- clauses.push(`array_length(${column}, 1) IS NULL`);
2688
- }
2689
- else if (filter.isEmpty === false) {
2690
- // array_length(column, 1) IS NOT NULL
2691
- clauses.push(`array_length(${column}, 1) IS NOT NULL`);
2692
- }
2693
- return clauses;
2694
- }
2695
- /**
2696
- * Get the Postgres array type for a column (used by UNNEST in createMany).
2697
- * Uses pre-computed Map for O(1) lookup instead of linear scan.
2698
- */
2699
- getColumnArrayType(column) {
2700
- const arrayType = this.columnArrayTypeMap.get(column);
2701
- if (arrayType)
2702
- return arrayType;
2703
- // Fallback heuristic for unknown columns
2704
- if (column === 'id' || column.endsWith('_id'))
2705
- return 'bigint[]';
2706
- if (column.endsWith('_at'))
2707
- return 'timestamptz[]';
2708
- return 'text[]';
2709
- }
2710
- }
2711
- exports.QueryInterface = QueryInterface;