turbine-orm 0.9.1 → 0.10.0

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