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