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