turbine-orm 0.9.0 → 0.9.2

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