turbine-orm 0.65.0 → 0.67.0-next.c353473

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 (142) hide show
  1. package/README.md +34 -32
  2. package/dist/adapters/cockroachdb.js +21 -3
  3. package/dist/adapters/index.d.ts +15 -0
  4. package/dist/adapters/yugabytedb.js +20 -3
  5. package/dist/cjs/adapters/cockroachdb.js +21 -3
  6. package/dist/cjs/adapters/index.d.ts +15 -0
  7. package/dist/cjs/adapters/yugabytedb.js +20 -3
  8. package/dist/cjs/cli/destructive.d.ts +18 -4
  9. package/dist/cjs/cli/destructive.js +230 -122
  10. package/dist/cjs/cli/index.d.ts +21 -4
  11. package/dist/cjs/cli/index.js +119 -22
  12. package/dist/cjs/cli/mcp.d.ts +28 -8
  13. package/dist/cjs/cli/mcp.js +170 -127
  14. package/dist/cjs/cli/migrate.d.ts +134 -13
  15. package/dist/cjs/cli/migrate.js +349 -241
  16. package/dist/cjs/cli/pii-predicate-guard.d.ts +112 -0
  17. package/dist/cjs/cli/pii-predicate-guard.js +390 -0
  18. package/dist/cjs/cli/prisma-resolve.js +75 -4
  19. package/dist/cjs/cli/prisma-schema.d.ts +17 -1
  20. package/dist/cjs/cli/prisma-schema.js +83 -17
  21. package/dist/cjs/cli/sql-statements.d.ts +125 -0
  22. package/dist/cjs/cli/sql-statements.js +378 -0
  23. package/dist/cjs/cli/studio.js +49 -118
  24. package/dist/cjs/cli/ui.d.ts +1 -1
  25. package/dist/cjs/client.d.ts +43 -0
  26. package/dist/cjs/client.js +125 -6
  27. package/dist/cjs/dialect.d.ts +123 -0
  28. package/dist/cjs/dialect.js +33 -0
  29. package/dist/cjs/errors.d.ts +74 -1
  30. package/dist/cjs/errors.js +239 -25
  31. package/dist/cjs/index-advisor.d.ts +33 -1
  32. package/dist/cjs/index-advisor.js +32 -1
  33. package/dist/cjs/introspect.d.ts +48 -0
  34. package/dist/cjs/introspect.js +222 -91
  35. package/dist/cjs/mssql.js +43 -1
  36. package/dist/cjs/mysql.d.ts +5 -2
  37. package/dist/cjs/mysql.js +202 -17
  38. package/dist/cjs/nested-write.js +6 -1
  39. package/dist/cjs/pipeline-submittable.js +17 -3
  40. package/dist/cjs/pipeline.js +75 -9
  41. package/dist/cjs/powdb.d.ts +23 -0
  42. package/dist/cjs/powdb.js +33 -1
  43. package/dist/cjs/powql.d.ts +61 -9
  44. package/dist/cjs/powql.js +186 -49
  45. package/dist/cjs/prisma-compat.js +160 -41
  46. package/dist/cjs/query/aggregates.d.ts +1 -1
  47. package/dist/cjs/query/aggregates.js +80 -18
  48. package/dist/cjs/query/batched-loader.d.ts +10 -0
  49. package/dist/cjs/query/batched-loader.js +268 -7
  50. package/dist/cjs/query/builder.d.ts +112 -0
  51. package/dist/cjs/query/builder.js +410 -98
  52. package/dist/cjs/query/filters.d.ts +162 -0
  53. package/dist/cjs/query/filters.js +250 -1
  54. package/dist/cjs/query/relations.d.ts +10 -10
  55. package/dist/cjs/query/relations.js +93 -12
  56. package/dist/cjs/query/types.d.ts +14 -1
  57. package/dist/cjs/query/utils.d.ts +146 -2
  58. package/dist/cjs/query/utils.js +210 -4
  59. package/dist/cjs/query/warn-registry.d.ts +10 -0
  60. package/dist/cjs/query/warn-registry.js +10 -0
  61. package/dist/cjs/query/where-compile.d.ts +30 -0
  62. package/dist/cjs/query/where-compile.js +41 -0
  63. package/dist/cjs/query/where.d.ts +128 -13
  64. package/dist/cjs/query/where.js +215 -77
  65. package/dist/cjs/query/writes.d.ts +1 -1
  66. package/dist/cjs/query/writes.js +39 -15
  67. package/dist/cjs/schema-builder.d.ts +2 -1
  68. package/dist/cjs/schema-sql.d.ts +94 -4
  69. package/dist/cjs/schema-sql.js +506 -30
  70. package/dist/cjs/schema.d.ts +3 -1
  71. package/dist/cjs/sqlite.d.ts +6 -0
  72. package/dist/cjs/sqlite.js +151 -10
  73. package/dist/cjs/typed-sql.d.ts +29 -1
  74. package/dist/cjs/typed-sql.js +30 -12
  75. package/dist/cli/destructive.d.ts +18 -4
  76. package/dist/cli/destructive.js +229 -121
  77. package/dist/cli/index.d.ts +21 -4
  78. package/dist/cli/index.js +120 -24
  79. package/dist/cli/mcp.d.ts +28 -8
  80. package/dist/cli/mcp.js +172 -129
  81. package/dist/cli/migrate.d.ts +134 -13
  82. package/dist/cli/migrate.js +347 -238
  83. package/dist/cli/pii-predicate-guard.d.ts +112 -0
  84. package/dist/cli/pii-predicate-guard.js +386 -0
  85. package/dist/cli/prisma-resolve.js +75 -4
  86. package/dist/cli/prisma-schema.d.ts +17 -1
  87. package/dist/cli/prisma-schema.js +83 -17
  88. package/dist/cli/sql-statements.d.ts +125 -0
  89. package/dist/cli/sql-statements.js +373 -0
  90. package/dist/cli/studio.js +49 -118
  91. package/dist/cli/ui.d.ts +1 -1
  92. package/dist/client.d.ts +43 -0
  93. package/dist/client.js +126 -7
  94. package/dist/dialect.d.ts +123 -0
  95. package/dist/dialect.js +33 -0
  96. package/dist/errors.d.ts +74 -1
  97. package/dist/errors.js +228 -19
  98. package/dist/index-advisor.d.ts +33 -1
  99. package/dist/index-advisor.js +31 -1
  100. package/dist/introspect.d.ts +48 -0
  101. package/dist/introspect.js +221 -91
  102. package/dist/mssql.js +44 -2
  103. package/dist/mysql.d.ts +5 -2
  104. package/dist/mysql.js +203 -18
  105. package/dist/nested-write.js +7 -2
  106. package/dist/pipeline-submittable.js +18 -4
  107. package/dist/pipeline.js +76 -10
  108. package/dist/powdb.d.ts +23 -0
  109. package/dist/powdb.js +33 -2
  110. package/dist/powql.d.ts +61 -9
  111. package/dist/powql.js +187 -50
  112. package/dist/prisma-compat.js +160 -41
  113. package/dist/query/aggregates.d.ts +1 -1
  114. package/dist/query/aggregates.js +82 -20
  115. package/dist/query/batched-loader.d.ts +10 -0
  116. package/dist/query/batched-loader.js +270 -9
  117. package/dist/query/builder.d.ts +112 -0
  118. package/dist/query/builder.js +411 -100
  119. package/dist/query/filters.d.ts +162 -0
  120. package/dist/query/filters.js +246 -1
  121. package/dist/query/relations.d.ts +10 -10
  122. package/dist/query/relations.js +94 -14
  123. package/dist/query/types.d.ts +14 -1
  124. package/dist/query/utils.d.ts +146 -2
  125. package/dist/query/utils.js +204 -3
  126. package/dist/query/warn-registry.d.ts +10 -0
  127. package/dist/query/warn-registry.js +10 -0
  128. package/dist/query/where-compile.d.ts +30 -0
  129. package/dist/query/where-compile.js +40 -1
  130. package/dist/query/where.d.ts +128 -13
  131. package/dist/query/where.js +216 -80
  132. package/dist/query/writes.d.ts +1 -1
  133. package/dist/query/writes.js +40 -16
  134. package/dist/schema-builder.d.ts +2 -1
  135. package/dist/schema-sql.d.ts +94 -4
  136. package/dist/schema-sql.js +505 -30
  137. package/dist/schema.d.ts +3 -1
  138. package/dist/sqlite.d.ts +6 -0
  139. package/dist/sqlite.js +151 -10
  140. package/dist/typed-sql.d.ts +29 -1
  141. package/dist/typed-sql.js +30 -12
  142. package/package.json +6 -4
@@ -46,6 +46,7 @@ var __importStar = (this && this.__importStar) || (function () {
46
46
  })();
47
47
  Object.defineProperty(exports, "__esModule", { value: true });
48
48
  exports.QueryInterface = exports.AUTO_COUNT_BATCH_MIN_PARENT_ROWS = exports.AUTO_TO_ONE_JOIN_ROWS_MAX = exports.AUTO_TO_ONE_JOIN_ROWS_MIN = exports.AUTO_TO_ONE_JOIN_MAX_ROWS = exports.AUTO_ASSUMED_ROUND_TRIP_MS = exports.AUTO_JOIN_PENALTY_MS_PER_ROW = void 0;
49
+ exports.resetCacheCrossCheckEnv = resetCacheCrossCheckEnv;
49
50
  exports.unlockNestedWriteTx = unlockNestedWriteTx;
50
51
  const dialect_js_1 = require("../dialect.js");
51
52
  const errors_js_1 = require("../errors.js");
@@ -87,18 +88,55 @@ const writesMod = __importStar(require("./writes.js"));
87
88
  * throws, same as dev. `0`, unset, or an unparseable value means never check.
88
89
  */
89
90
  function cacheCrossCheckMode() {
91
+ const env = crossCheckEnv ?? readCrossCheckEnv();
92
+ if (env.mode !== 'sampled')
93
+ return env.mode;
94
+ // The SAMPLING decision, and only it, is genuinely per hit.
95
+ return env.rate >= 1 || Math.random() < env.rate ? 'sampled' : 'off';
96
+ }
97
+ /**
98
+ * The env-derived half of {@link cacheCrossCheckMode}, resolved ONCE per
99
+ * process and memoized.
100
+ *
101
+ * `process.env` is not a plain object: every property read crosses a C++
102
+ * interceptor. Measured at 112.7 ns per read against 3.6 ns for a module-level
103
+ * constant, and this function ran TWO reads on every cache hit, which put it
104
+ * at the top of the SQL-build CPU profile (12.53% self time, with a further
105
+ * ~12% inside the interceptor) for a value that does not change.
106
+ *
107
+ * It is memoized rather than hoisted to a `const` because the toggle IS
108
+ * observed at runtime, contrary to what a quick look suggests: the
109
+ * cross-check and sampling suites flip `NODE_ENV` /
110
+ * `TURBINE_DISABLE_CACHE_CHECK` / `TURBINE_CACHE_CHECK_SAMPLE` around a
111
+ * synchronous block in-process, not at spawn. So the read is deferred to first
112
+ * use and {@link resetCacheCrossCheckEnv} re-arms it; that is the entire
113
+ * contract, and the only thing lost versus reading every time is that a
114
+ * process which mutates these variables mid-run must say so.
115
+ */
116
+ let crossCheckEnv;
117
+ function readCrossCheckEnv() {
118
+ let resolved;
90
119
  if (process.env.NODE_ENV !== 'production') {
91
- return process.env.TURBINE_DISABLE_CACHE_CHECK === '1' ? 'off' : 'dev';
92
- }
93
- const raw = process.env.TURBINE_CACHE_CHECK_SAMPLE;
94
- if (raw === undefined)
95
- return 'off';
96
- const rate = Number.parseFloat(raw);
97
- if (!Number.isFinite(rate) || rate <= 0)
98
- return 'off';
99
- if (rate >= 1)
100
- return 'sampled';
101
- return Math.random() < rate ? 'sampled' : 'off';
120
+ resolved = { mode: process.env.TURBINE_DISABLE_CACHE_CHECK === '1' ? 'off' : 'dev' };
121
+ }
122
+ else {
123
+ const raw = process.env.TURBINE_CACHE_CHECK_SAMPLE;
124
+ const rate = raw === undefined ? Number.NaN : Number.parseFloat(raw);
125
+ resolved = !Number.isFinite(rate) || rate <= 0 ? { mode: 'off' } : { mode: 'sampled', rate };
126
+ }
127
+ crossCheckEnv = resolved;
128
+ return resolved;
129
+ }
130
+ /**
131
+ * Discard the memoized cross-check environment so the next cache hit re-reads
132
+ * `process.env`.
133
+ *
134
+ * @internal Exposed for the tests that toggle these variables in-process (see
135
+ * {@link crossCheckEnv}). Production code sets them before the first query and
136
+ * never again.
137
+ */
138
+ function resetCacheCrossCheckEnv() {
139
+ crossCheckEnv = undefined;
102
140
  }
103
141
  /**
104
142
  * Distinct cache-mismatch fingerprints already logged by the sampled production
@@ -248,6 +286,22 @@ exports.AUTO_TO_ONE_JOIN_ROWS_MAX = 100_000;
248
286
  * it.
249
287
  */
250
288
  exports.AUTO_COUNT_BATCH_MIN_PARENT_ROWS = 2;
289
+ /**
290
+ * How many distinct `parseRow` column shapes one QueryInterface remembers.
291
+ * Deliberately far smaller than the 1,000-entry SQL template cache: a shape is
292
+ * a `select` / `omit` projection rather than a where-clause fingerprint, so the
293
+ * realistic population is single digits per table, and the cost of a miss is
294
+ * one rebuild rather than a re-parse on the server.
295
+ */
296
+ const ROW_PLAN_CACHE_SIZE = 128;
297
+ /**
298
+ * The largest `findManyStream` batch size for which the speculative first fetch
299
+ * is still worth attempting. Equal to the default batch size, so the default
300
+ * and everything below it behaves exactly as it always has. See the comment at
301
+ * the speculation itself for why the bound is on `batchSize` rather than on the
302
+ * probe's own limit.
303
+ */
304
+ const STREAM_SPECULATION_MAX_BATCH = 1000;
251
305
  /**
252
306
  * Strict structural equality for a single SQL parameter value. Handles the
253
307
  * value shapes Turbine binds: primitives (incl. `NaN` and `bigint`), `null`/
@@ -417,6 +471,16 @@ class QueryInterface {
417
471
  * inline, not through the top-level cache).
418
472
  */
419
473
  lastCacheHit = false;
474
+ /**
475
+ * Set while a build closure runs when the statement's WHERE (or HAVING)
476
+ * carries a caller-written `AND`/`OR` combinator array, i.e. when its SQL text
477
+ * is a function of an arity the caller chose. Read (and reset) by
478
+ * {@link acquireSql}, which brackets the single `build()` call, so the flag
479
+ * has no lifetime outside that synchronous window and cannot leak between
480
+ * queries. See {@link BuilderCtx.markVariableArity} for the unbounded
481
+ * server-side prepared-statement growth this exists to stop.
482
+ */
483
+ variableArityShape = false;
420
484
  middlewares;
421
485
  defaultLimit;
422
486
  warnOnUnlimited;
@@ -467,6 +531,20 @@ class QueryInterface {
467
531
  autoRoundTripMs;
468
532
  /** Nested-relation JSON encoding: 'object' (default) or 'positional'. */
469
533
  jsonEncoding;
534
+ /**
535
+ * `parseRow` decode plans, keyed by table plus the exact column list. Bounded
536
+ * like the SQL template cache and for the same reason: the shapes come from
537
+ * `select` / `omit`, which is usually a handful of literals in the caller's
538
+ * source but can be assembled per request from user input, so the key space
539
+ * is not provably finite. Eviction only ever costs a rebuild.
540
+ */
541
+ rowPlanCache = new utils_js_1.LRUCache(ROW_PLAN_CACHE_SIZE);
542
+ /**
543
+ * The most recent plan per table, which is the entry `parseRow` actually
544
+ * probes. One result set is one shape, so this hits for every row after the
545
+ * first without hashing a cache key per row.
546
+ */
547
+ rowPlanLast = new Map();
470
548
  /**
471
549
  * Client-level automatic WHERE filters keyed by table accessor (soft-delete /
472
550
  * multi-tenancy). AND-merged into every query on the keyed table and every
@@ -503,6 +581,17 @@ class QueryInterface {
503
581
  * to Date as well (otherwise nested dates leak through as strings).
504
582
  */
505
583
  camelDateFieldCache = new Map();
584
+ /**
585
+ * Per-table memo of `Object.entries(meta.relations)`, consumed by the nested
586
+ * row parser (see `getRelationEntries` in relations.ts). Same rationale and
587
+ * same lifetime as {@link camelDateFieldCache}: the metadata is immutable, and
588
+ * the parser reads it once per row.
589
+ */
590
+ relationEntryCache = new Map();
591
+ /** Per-table memo of batched-loader child readers (see {@link batchedChild}). */
592
+ batchedChildCache = new Map();
593
+ /** The (option-invariant) options every batched child is built with. */
594
+ batchedChildOptions;
506
595
  /** True when this QI runs inside an active transaction (set via _txScoped option). */
507
596
  txScoped;
508
597
  /** Original options reference, forwarded to child QIs in nested writes. */
@@ -699,6 +788,9 @@ class QueryInterface {
699
788
  set currentSkip(v) {
700
789
  self.currentSkip = v;
701
790
  },
791
+ markVariableArity: () => {
792
+ this.variableArityShape = true;
793
+ },
702
794
  q: (name) => this.q(name),
703
795
  p: (index) => this.p(index),
704
796
  inParam: (values) => this.inParam(values),
@@ -716,6 +808,7 @@ class QueryInterface {
716
808
  crossCheckCache: (op, cacheKey, entry, build, collectedParams) => this.crossCheckCache(op, cacheKey, entry, build, collectedParams),
717
809
  jsonEncoding: this.jsonEncoding,
718
810
  camelDateFieldCache: this.camelDateFieldCache,
811
+ relationEntryCache: this.relationEntryCache,
719
812
  limitOneClause: () => this.limitOneClause(),
720
813
  buildPagination: (limitPh, offsetPh, hasOrderBy) => this.buildPagination(limitPh, offsetPh, hasOrderBy),
721
814
  paginationRef: (value, params, arg) => this.paginationRef(value, params, arg),
@@ -1478,15 +1571,10 @@ class QueryInterface {
1478
1571
  includePii, forceCustomPlan = false) {
1479
1572
  // The loader's own global-filter callback below needs the RESOLVED form.
1480
1573
  const resolvedSkip = (0, types_js_1.resolveSkipGlobalFilters)(skip);
1481
- const childOptions = {
1482
- ...this.options,
1483
- defaultLimit: undefined,
1484
- warnOnUnlimited: false,
1485
- };
1486
1574
  return {
1487
1575
  parentMeta: this.tableMeta,
1488
1576
  schema: this.schema,
1489
- makeChild: (table) => new QueryInterface(this.pool, table, this.schema, [], childOptions),
1577
+ makeChild: (table) => this.batchedChild(table),
1490
1578
  // The per-query `forceCustomPlan` opt-in covers the relation follow-ups
1491
1579
  // too: a batched load re-issues the SAME tenant-shaped predicate one
1492
1580
  // level down, so leaving those named would keep exactly the plan-cache
@@ -1496,6 +1584,23 @@ class QueryInterface {
1496
1584
  buildInClause: (expr, paramRef, negated) => this.inClause(expr, paramRef, negated),
1497
1585
  inClauseParam: (values) => this.inParam(values),
1498
1586
  paramPlaceholder: (index) => this.p(index),
1587
+ // Bound each relation follow-up per correlation key when the engine can
1588
+ // express it; absent leaves the loader on its client-side slice. Bound as
1589
+ // a closure rather than passing `this.dialect` so the loader keeps
1590
+ // needing nothing else from the dialect.
1591
+ //
1592
+ // The `dialect.name` test is NOT redundant with the hook's presence, and
1593
+ // this is the same trap the `distinct` gate documents: every engine
1594
+ // dialect is built by SPREADING `postgresDialect`, so an optional hook
1595
+ // added there is INHERITED by sqlite / mysql / mssql, whose "absent"
1596
+ // fallback would then never be taken. The wrapper is not portable as
1597
+ // written either (T-SQL rejects an ORDER BY inside a derived table
1598
+ // without TOP/OFFSET, and the compiled child query carries one), so the
1599
+ // pushdown stays with the dialect that owns the implementation until
1600
+ // another engine ships its own and asserts it.
1601
+ buildPartitionLimit: this.dialect.name === 'postgresql' && this.dialect.buildPartitionLimit
1602
+ ? (input) => this.dialect.buildPartitionLimit(input)
1603
+ : undefined,
1499
1604
  skipGlobalFilters: skip,
1500
1605
  // Query-level opt-in threaded onto every follow-up child `buildFindMany`,
1501
1606
  // so a batched load excludes/includes PII exactly as the join strategy.
@@ -1517,6 +1622,36 @@ class QueryInterface {
1517
1622
  },
1518
1623
  };
1519
1624
  }
1625
+ /**
1626
+ * The child {@link QueryInterface} the batched loader uses for `table`,
1627
+ * memoized per table for the lifetime of this accessor.
1628
+ *
1629
+ * It used to be constructed fresh for every relation of every query, which
1630
+ * threw away that child's SQL template cache each time: a relation follow-up
1631
+ * therefore MISSED the cache on every single request and rebuilt its SQL,
1632
+ * which is the one thing the template cache exists to avoid, and it allocated
1633
+ * a whole QueryInterface (column type maps, camel-date memo, the ctx literal)
1634
+ * per relation per query. `childOptions` was likewise a fresh spread per
1635
+ * query although it is a pure function of this instance's options.
1636
+ *
1637
+ * Safe to share across queries: a QueryInterface holds no per-query state
1638
+ * beyond the transient build fields, which live and die inside one
1639
+ * synchronous `build*` call, and every child is bound to THIS instance's pool
1640
+ * (so it still joins an active transaction) with `defaultLimit` cleared and
1641
+ * unlimited-warnings silenced, because a relation load must fetch every
1642
+ * matching child. Per-query values (`skipGlobalFilters`, `includePii`,
1643
+ * `timeout`, `forceCustomPlan`) are passed as ARGUMENTS by the loader, never
1644
+ * baked into the child, which is what makes the memo sound.
1645
+ */
1646
+ batchedChild(table) {
1647
+ let child = this.batchedChildCache.get(table);
1648
+ if (!child) {
1649
+ this.batchedChildOptions ??= { ...this.options, defaultLimit: undefined, warnOnUnlimited: false };
1650
+ child = new QueryInterface(this.pool, table, this.schema, [], this.batchedChildOptions);
1651
+ this.batchedChildCache.set(table, child);
1652
+ }
1653
+ return child;
1654
+ }
1520
1655
  /**
1521
1656
  * Run a findMany with the batched strategy: execute the base query WITHOUT
1522
1657
  * relation subqueries (all other clauses intact), then load each relation via
@@ -1601,9 +1736,7 @@ class QueryInterface {
1601
1736
  acquireSql(cacheKey, build) {
1602
1737
  if (!this.sqlCacheEnabled) {
1603
1738
  this.lastCacheHit = false;
1604
- const sql = build([]);
1605
- this.cacheMisses++;
1606
- return { sql, name: (0, utils_js_1.sqlToPreparedName)(sql) };
1739
+ return this.buildCacheEntry(build);
1607
1740
  }
1608
1741
  const cached = this.sqlTemplateCache.get(cacheKey);
1609
1742
  if (cached) {
@@ -1612,12 +1745,38 @@ class QueryInterface {
1612
1745
  return cached;
1613
1746
  }
1614
1747
  this.lastCacheHit = false;
1615
- const sql = build([]);
1616
- const entry = { sql, name: (0, utils_js_1.sqlToPreparedName)(sql) };
1748
+ const entry = this.buildCacheEntry(build);
1617
1749
  this.sqlTemplateCache.set(cacheKey, entry);
1618
- this.cacheMisses++;
1619
1750
  return entry;
1620
1751
  }
1752
+ /**
1753
+ * Run one build closure and pair its SQL with the prepared-statement name it
1754
+ * should execute under.
1755
+ *
1756
+ * The `variableArityShape` flag is reset immediately BEFORE the build and read
1757
+ * immediately AFTER it, so this method is the flag's entire lifetime: the
1758
+ * build walk (`buildWhereClause` / `buildScopedWhere` / the HAVING combinator)
1759
+ * is the only thing that can set it, nothing can observe a stale value, and a
1760
+ * throw out of `build()` leaves nothing behind to affect the next query.
1761
+ *
1762
+ * An EMPTY name is how "send this unnamed" travels: `queryWithTimeout` tests
1763
+ * the name for truthiness, so `''` takes the plain `(text, values)` form the
1764
+ * driver never registers a named statement for. Doing it HERE rather than at
1765
+ * the execute seam is what makes it survive the cache: the entry is created
1766
+ * once, on the miss, and a later HIT reuses the same (empty) name, so a
1767
+ * variable-arity shape can never acquire a name from a warmed template.
1768
+ *
1769
+ * See {@link BuilderCtx.markVariableArity} for what makes a shape
1770
+ * variable-arity and the measured reason it must not be named.
1771
+ */
1772
+ buildCacheEntry(build) {
1773
+ this.variableArityShape = false;
1774
+ const sql = build([]);
1775
+ const variableArity = this.variableArityShape;
1776
+ this.variableArityShape = false;
1777
+ this.cacheMisses++;
1778
+ return { sql, name: variableArity ? '' : (0, utils_js_1.sqlToPreparedName)(sql) };
1779
+ }
1621
1780
  /**
1622
1781
  * Dev-mode SQL-cache lockstep cross-check (see {@link cacheCrossCheckEnabled}).
1623
1782
  *
@@ -1947,7 +2106,6 @@ class QueryInterface {
1947
2106
  (0, batched_loader_js_1.stripFields)([entity], proj.strip);
1948
2107
  return entity;
1949
2108
  }
1950
- // biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
1951
2109
  buildFindUnique(args) {
1952
2110
  this.currentSkip = (0, types_js_1.resolveSkipGlobalFilters)(args.skipGlobalFilters);
1953
2111
  // Prisma compound-unique selector expansion (before global-filter merge and
@@ -2286,7 +2444,6 @@ class QueryInterface {
2286
2444
  }
2287
2445
  return maxDepth;
2288
2446
  }
2289
- // biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
2290
2447
  buildFindMany(args) {
2291
2448
  this.currentSkip = (0, types_js_1.resolveSkipGlobalFilters)(args?.skipGlobalFilters);
2292
2449
  // Stable relation order (opt-in): fill PK-asc orderBy into unordered to-many
@@ -2307,6 +2464,32 @@ class QueryInterface {
2307
2464
  if (args?.orderBy !== undefined && isEmptyOrderBy(args.orderBy)) {
2308
2465
  args = { ...args, orderBy: undefined };
2309
2466
  }
2467
+ // Drop `orderBy` terms that sort by an expression an earlier term already
2468
+ // sorted by, and `distinct` columns named twice. HERE, before the
2469
+ // fingerprint, for the reason every other normalization in this method is
2470
+ // here: the fingerprint, the SQL build and the param collect must all see
2471
+ // ONE list, or the cache key and the statement it caches describe different
2472
+ // queries. Rewritten into the array form, which flattens through
2473
+ // `orderByEntries` to the identical entry list the object form does, so a
2474
+ // caller who wrote no duplicate is untouched down to the cache key (the
2475
+ // helpers return null unless something was actually dropped).
2476
+ if (args?.orderBy !== undefined) {
2477
+ const deduped = (0, filters_js_1.dedupeOrderEntries)(this.tableMeta, (0, filters_js_1.orderByEntries)(args.orderBy), this.table);
2478
+ if (deduped) {
2479
+ (0, utils_js_1.warnRedundantSortTerm)(this.table, 'orderBy', deduped.dropped);
2480
+ args = {
2481
+ ...args,
2482
+ orderBy: deduped.entries.map(([k, v]) => ({ [k]: v })),
2483
+ };
2484
+ }
2485
+ }
2486
+ if (args?.distinct && args.distinct.length > 0) {
2487
+ const deduped = (0, filters_js_1.dedupeColumnList)(this.tableMeta, args.distinct);
2488
+ if (deduped) {
2489
+ (0, utils_js_1.warnRedundantSortTerm)(this.table, 'distinct', deduped.dropped);
2490
+ args = { ...args, distinct: deduped.columns };
2491
+ }
2492
+ }
2310
2493
  // Deterministic pagination (opt-in): fill a PK-asc orderBy into a paginating
2311
2494
  // query that declares none, BEFORE fingerprinting so the ordered and
2312
2495
  // unordered shapes get distinct cache entries. No-op unless
@@ -2314,6 +2497,29 @@ class QueryInterface {
2314
2497
  const implicitOrder = this.implicitPkOrderBy(args);
2315
2498
  if (implicitOrder)
2316
2499
  args = { ...args, orderBy: implicitOrder };
2500
+ // `distinct` compiles to `SELECT DISTINCT ON (...)`, which is PostgreSQL
2501
+ // syntax and nothing else's. Every other engine parsed it as far as the
2502
+ // word `ON` and answered with a RAW driver error carrying no TURBINE_ code
2503
+ // (SQLite: `near "ON": syntax error`; MySQL: ER_PARSE_ERROR), i.e. the one
2504
+ // shape the typed-error surface exists to prevent. Refused with the same
2505
+ // E017 the OTHER spelling of this feature already used, `groupBy({
2506
+ // distinctOn })` in aggregates.ts, which was gated correctly all along.
2507
+ //
2508
+ // `dialect.name` rather than a new capability flag, deliberately, and this
2509
+ // is the exception to the "capability flags, not engine names" rule the
2510
+ // rest of the dialect follows: every engine dialect is built by SPREADING
2511
+ // `postgresDialect`, so a flag defaulting to `true` would be inherited by
2512
+ // all of them (which is the bug) and one defaulting to `false` would have
2513
+ // to be re-declared on Postgres-compatible dialects that already work.
2514
+ // The established precedent for exactly this feature is the `dialect.name`
2515
+ // test in `buildDistinctOnSource`.
2516
+ //
2517
+ // Before the cache, like the two guards below, so a warmed template cannot
2518
+ // serve the query the cold path refuses.
2519
+ if (args?.distinct && args.distinct.length > 0 && this.dialect.name !== 'postgresql') {
2520
+ throw new errors_js_1.UnsupportedFeatureError('DISTINCT ON (findMany distinct)', this.dialect.name, 'findMany({ distinct }) requires PostgreSQL: SELECT DISTINCT ON is not portable. Group in ' +
2521
+ 'application code, or use groupBy({ by }) for one row per combination.');
2522
+ }
2317
2523
  // `distinct` + relation orderBy is refused up front (E003): the distinct
2318
2524
  // path re-orders in an outer wrapper (`... AS "<table>_distinct" ORDER BY
2319
2525
  // <userOrder>`) where a correlated relation subquery (pick-row, `_count`,
@@ -2404,6 +2610,30 @@ class QueryInterface {
2404
2610
  if (args?.distinct && args.distinct.length > 0) {
2405
2611
  distinctCols = args.distinct.map((k) => this.toSqlColumn(k));
2406
2612
  distinctPrefix = `DISTINCT ON (${distinctCols.join(', ')}) `;
2613
+ // A MULTI-column `distinct` gives up its server-side prepared-statement
2614
+ // name, for the same reason a caller-written `OR` array does and by the
2615
+ // same mechanism (see markVariableArity). The channel here is ORDER, not
2616
+ // arity: the column list is written into the SQL text one term at a
2617
+ // time, so the reachable statement set is the ORDERED subsets of the
2618
+ // table's columns. Measured on PostgreSQL 16, a seven-column table:
2619
+ // 5,040 `distinct` permutations left 5,040 further permanent statements
2620
+ // and took CachedPlanSource from 39.4 MB to 59.1 MB on ONE connection.
2621
+ //
2622
+ // UNNAMED rather than canonicalized, which is what `select` and the
2623
+ // write `data` list do, and the asymmetry is the point. This list is
2624
+ // re-emitted as the leading terms of the inner ORDER BY a few lines
2625
+ // below, and with no `orderBy` at all PostgreSQL's choice of
2626
+ // representative row per group is explicitly unpredictable, so
2627
+ // reordering it could hand a caller a different row. Withholding the
2628
+ // name changes no SQL text and therefore cannot. The cost is one extra
2629
+ // server-side parse per execution on an already-rare query shape.
2630
+ //
2631
+ // `length > 1` because a single column has exactly one ordering and so
2632
+ // no permutation space: the common `distinct: ['tenantId']` keeps its
2633
+ // name. Repeats are already dropped upstream (dedupeColumnList), so the
2634
+ // list here is distinct columns and nothing else.
2635
+ if (args.distinct.length > 1)
2636
+ this.ctx.markVariableArity();
2407
2637
  }
2408
2638
  // Join-sink for `relationLoadStrategy: 'flatten'`. Filled while the SELECT
2409
2639
  // list is built (so the flattened relations' ON-clause params interleave
@@ -2592,27 +2822,57 @@ class QueryInterface {
2592
2822
  const parseWith = hasRelations
2593
2823
  ? this.makeNestedParser(args.with, streamPii, streamFlattenPlan)
2594
2824
  : null;
2595
- // --- Speculative first fetch: try to satisfy the entire drain in one RTT ---
2596
- const speculativeDeferred = this.buildFindMany({
2597
- ...args,
2598
- limit: batchSize + 1,
2599
- });
2600
2825
  this.currentAction = 'findManyStream';
2601
2826
  // Streaming is ALREADY immune to the generic-plan cliff: the speculative
2602
2827
  // fetch has never passed a prepared name, and the cursor path runs through
2603
2828
  // DECLARE, so neither statement enters the plan cache. `preparedNameFor` is
2604
- // still called with no name so that `forceCustomPlan: true` is VALIDATED on
2829
+ // still called, with no name, so that `forceCustomPlan: true` is VALIDATED on
2605
2830
  // an engine that cannot honour it here either, rather than being quietly
2606
- // satisfied by an accident of this code path.
2607
- const speculativeResult = await this.queryWithTimeout(speculativeDeferred.sql, speculativeDeferred.params, args?.timeout, this.preparedNameFor(args, undefined));
2608
- if (speculativeResult.rows.length <= batchSize) {
2609
- // Small drain, yield all rows and return, no cursor needed
2610
- for (const row of speculativeResult.rows) {
2611
- yield (parseWith ? parseWith(row) : this.parseRow(row, this.table));
2831
+ // satisfied by an accident of this code path. It is called OUTSIDE the
2832
+ // speculation branch below: it used to be the speculative fetch's own
2833
+ // argument, which would have made that validation conditional on a batch
2834
+ // size the moment the speculation became conditional.
2835
+ const streamPreparedName = this.preparedNameFor(args, undefined);
2836
+ // --- Speculative first fetch: try to satisfy the entire drain in one RTT ---
2837
+ //
2838
+ // A drain that fits in one batch needs no cursor, and skipping it saves the
2839
+ // four extra round trips BEGIN / DECLARE / CLOSE / COMMIT cost. That is the
2840
+ // whole point of this fetch, and it is a good trade while the statement is
2841
+ // cheap to throw away.
2842
+ //
2843
+ // On OVERFLOW it is thrown away: these rows were read outside the cursor's
2844
+ // transaction, so yielding them and then continuing from the cursor would
2845
+ // splice two snapshots together, and resuming past them would need an
2846
+ // ORDER BY the caller never asked for. Both are unsound, so the cursor
2847
+ // re-reads from row one and this fetch cost `batchSize + 1` rows for
2848
+ // nothing.
2849
+ //
2850
+ // That waste is proportional to `batchSize`, which is the one number the
2851
+ // caller raises when they expect MORE rows, so the optimization used to get
2852
+ // most expensive exactly where it was least likely to pay off: raising
2853
+ // `batchSize` for throughput made every large drain slower, and the stream
2854
+ // was the only thing here that got slower as `batchSize` went up. So the
2855
+ // speculation is now bounded BY `batchSize` rather than scaled by it. At or
2856
+ // below the default it is unchanged; above it, a caller asking for large
2857
+ // batches has told us not to expect a one-batch result, and we go straight
2858
+ // to the cursor and waste nothing. The cost of being wrong about that is
2859
+ // four round trips on a drain that would have fit, never any transferred
2860
+ // rows.
2861
+ if (batchSize <= STREAM_SPECULATION_MAX_BATCH) {
2862
+ const speculativeDeferred = this.buildFindMany({
2863
+ ...args,
2864
+ limit: batchSize + 1,
2865
+ });
2866
+ const speculativeResult = await this.queryWithTimeout(speculativeDeferred.sql, speculativeDeferred.params, args?.timeout, streamPreparedName);
2867
+ if (speculativeResult.rows.length <= batchSize) {
2868
+ // Small drain, yield all rows and return, no cursor needed
2869
+ for (const row of speculativeResult.rows) {
2870
+ yield (parseWith ? parseWith(row) : this.parseRow(row, this.table));
2871
+ }
2872
+ return;
2612
2873
  }
2613
- return;
2614
2874
  }
2615
- // --- Overflow: fall back to cursor path from scratch ---
2875
+ // --- Overflow, or speculation declined: cursor path from scratch ---
2616
2876
  const deferred = this.buildFindMany(args);
2617
2877
  // Acquire a dedicated connection: cursors require a single connection in a
2618
2878
  // transaction. The dialect owns the streaming SQL (Postgres: BEGIN → DECLARE
@@ -2671,7 +2931,6 @@ class QueryInterface {
2671
2931
  return deferred.transform(result);
2672
2932
  });
2673
2933
  }
2674
- // biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
2675
2934
  buildFindFirst(args) {
2676
2935
  // Reuse findMany's SQL builder but force LIMIT 1
2677
2936
  const findManyArgs = { ...args, limit: 1 };
@@ -2696,7 +2955,6 @@ class QueryInterface {
2696
2955
  return deferred.transform(result);
2697
2956
  });
2698
2957
  }
2699
- // biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
2700
2958
  buildFindFirstOrThrow(args) {
2701
2959
  const inner = this.buildFindFirst(args);
2702
2960
  return {
@@ -2726,7 +2984,6 @@ class QueryInterface {
2726
2984
  return deferred.transform(result);
2727
2985
  });
2728
2986
  }
2729
- // biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
2730
2987
  buildFindUniqueOrThrow(args) {
2731
2988
  const inner = this.buildFindUnique(args);
2732
2989
  return {
@@ -3367,68 +3624,123 @@ class QueryInterface {
3367
3624
  return value;
3368
3625
  return value === '-infinity' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
3369
3626
  }
3370
- parseRow(row, table) {
3371
- const parsed = {};
3372
- const meta = this.schema.tables[table];
3373
- if (meta) {
3374
- // Fast path: use pre-computed maps (avoids regex per column per row)
3627
+ /**
3628
+ * The decode work for ONE cell of a date-bearing column, extracted so the
3629
+ * planned and unplanned row paths cannot drift apart. `null` and an
3630
+ * already-parsed `Date` are returned untouched, which is the same guard the
3631
+ * pre-plan code spelled inline.
3632
+ */
3633
+ decodeTemporalCell(value, table, field) {
3634
+ if (value === null || value instanceof Date)
3635
+ return value;
3636
+ if ((0, utils_js_1.isTemporalInfinity)(value)) {
3637
+ // Postgres `infinity` / `-infinity`. No JS Date means either, so both
3638
+ // readings cost something and the default is the one that is not lossy.
3639
+ // `'preserve'` hands back the JS number, which breaks the declared `Date`
3640
+ // type at runtime (`.toISOString()` throws) and still serializes as null
3641
+ // because JSON has no infinity literal, but binds straight back, so a
3642
+ // read-modify-write stores `infinity` again. `'null'` reads nicer and
3643
+ // DESTROYS the value on that same write, because a stored infinity and a
3644
+ // stored NULL become indistinguishable. Whichever is configured, it is
3645
+ // the SAME on every read strategy: the driver hands back the number,
3646
+ // `json_build_object` hands back the string "infinity", and both land
3647
+ // here (see `isTemporalInfinity`).
3648
+ //
3649
+ // The warning fires once per column when the option was left unset, on a
3650
+ // row that actually held an infinity, and describes the reading in force
3651
+ // rather than gating on which one it is.
3652
+ this.warnTemporalInfinity(table, field);
3653
+ return this.readTemporalInfinity(value);
3654
+ }
3655
+ if (Array.isArray(value)) {
3656
+ // `dateColumns` includes array-of-date columns (`date[]`, `timestamp[]`,
3657
+ // `timestamptz[]`), for which the driver already hands back a `Date[]`.
3658
+ // Coercing the array itself ran `new Date(String(theArray))` and replaced
3659
+ // the whole column with one Invalid Date. Its ELEMENTS get the same
3660
+ // infinity mapping as a scalar (same declared element type, same JSON
3661
+ // rendering); everything else is passed through by identity.
3662
+ return this.mapArrayTemporalInfinity(value, table, field);
3663
+ }
3664
+ // Any other number on a date column is left alone rather than run through
3665
+ // `parseDbDate(String(n))`, which would produce an Invalid Date.
3666
+ if (typeof value === 'number')
3667
+ return value;
3668
+ // Offset-less strings (Postgres `timestamp`, json_agg output) are pinned to
3669
+ // UTC so results don't depend on the server's time zone.
3670
+ return this.utcTimestamps ? (0, utils_js_1.parseDbDate)(String(value)) : new Date(value);
3671
+ }
3672
+ /**
3673
+ * Build the decode plan for one exact column list, and remember it as this
3674
+ * table's most recent shape so the next row of the same result set hits the
3675
+ * fast path in {@link parseRow}.
3676
+ */
3677
+ buildRowDecodePlan(table, meta, keys) {
3678
+ const shapeKey = `${table}${keys.join('')}`;
3679
+ let plan = this.rowPlanCache.get(shapeKey);
3680
+ if (plan === undefined) {
3375
3681
  const reverseMap = meta.reverseColumnMap;
3376
3682
  const dateCols = meta.dateColumns;
3377
3683
  // camelCase-keyed date fields, so nested json_build_object rows (whose
3378
3684
  // keys are already camelCase) get the same Date coercion as top-level rows.
3379
3685
  const camelDateFields = this.getCamelDateFields(table, meta);
3380
- const keys = Object.keys(row);
3381
- for (let i = 0; i < keys.length; i++) {
3382
- const col = keys[i];
3383
- const value = row[col];
3686
+ const cols = keys.slice();
3687
+ const fields = [];
3688
+ const dates = [];
3689
+ for (const col of cols) {
3384
3690
  const field = reverseMap[col] ?? col; // fall back to raw col name, not regex
3385
- // Top-level rows are snake_case (dateCols); nested rows are camelCase (camelDateFields).
3386
- if ((dateCols.has(col) || camelDateFields.has(field)) && value !== null && !(value instanceof Date)) {
3387
- if ((0, utils_js_1.isTemporalInfinity)(value)) {
3388
- // Postgres `infinity` / `-infinity`. No JS Date means either, so
3389
- // both readings cost something and the default is the one that is
3390
- // not lossy. `'preserve'` hands back the JS number, which breaks
3391
- // the declared `Date` type at runtime (`.toISOString()` throws) and
3392
- // still serializes as null because JSON has no infinity literal,
3393
- // but binds straight back, so a read-modify-write stores `infinity`
3394
- // again. `'null'` reads nicer and DESTROYS the value on that same
3395
- // write, because a stored infinity and a stored NULL become
3396
- // indistinguishable. Whichever is configured, it is the SAME on
3397
- // every read strategy: the driver hands back the number,
3398
- // `json_build_object` hands back the string "infinity", and both
3399
- // land here (see `isTemporalInfinity`).
3400
- //
3401
- // The warning below fires once per column when the option was left
3402
- // unset, on a row that actually held an infinity, and describes the
3403
- // reading in force rather than gating on which one it is.
3404
- this.warnTemporalInfinity(table, field);
3405
- parsed[field] = this.readTemporalInfinity(value);
3406
- }
3407
- else if (Array.isArray(value)) {
3408
- // `dateColumns` includes array-of-date columns (`date[]`,
3409
- // `timestamp[]`, `timestamptz[]`), for which the driver already
3410
- // hands back a `Date[]`. Coercing the array itself ran
3411
- // `new Date(String(theArray))` and replaced the whole column with
3412
- // one Invalid Date. Its ELEMENTS get the same infinity mapping as a
3413
- // scalar (same declared element type, same JSON rendering);
3414
- // everything else is passed through by identity.
3415
- parsed[field] = this.mapArrayTemporalInfinity(value, table, field);
3416
- }
3417
- else if (typeof value === 'number') {
3418
- // Any other number on a date column is left alone rather than run
3419
- // through `parseDbDate(String(n))`, which would produce an Invalid
3420
- // Date.
3421
- parsed[field] = value;
3422
- }
3423
- else {
3424
- // Offset-less strings (Postgres `timestamp`, json_agg output) are
3425
- // pinned to UTC so results don't depend on the server's time zone.
3426
- parsed[field] = this.utcTimestamps ? (0, utils_js_1.parseDbDate)(String(value)) : new Date(value);
3427
- }
3428
- }
3429
- else {
3430
- parsed[field] = value;
3431
- }
3691
+ fields.push(field);
3692
+ // Top-level rows are snake_case (dateCols); nested rows are camelCase.
3693
+ dates.push(dateCols.has(col) || camelDateFields.has(field));
3694
+ }
3695
+ plan = { cols, fields, dates };
3696
+ this.rowPlanCache.set(shapeKey, plan);
3697
+ }
3698
+ this.rowPlanLast.set(table, plan);
3699
+ return plan;
3700
+ }
3701
+ /**
3702
+ * Whether a cached plan describes exactly this row's column list, in order.
3703
+ * A pointer compare per column: both sides are the driver's own interned
3704
+ * column-name strings, so this is far cheaper than the reverse-map lookup and
3705
+ * two Set probes per column that it replaces, and unlike a length check or a
3706
+ * fingerprint it CANNOT accept a different projection that happens to look
3707
+ * similar. That matters more than the speed: a positional plan applied to the
3708
+ * wrong column list would silently write each value under a neighbouring
3709
+ * field's name, which is the one failure mode worth paying a full comparison
3710
+ * to make impossible.
3711
+ */
3712
+ static rowPlanMatches(plan, keys) {
3713
+ const cols = plan.cols;
3714
+ if (cols.length !== keys.length)
3715
+ return false;
3716
+ for (let i = 0; i < keys.length; i++) {
3717
+ if (cols[i] !== keys[i])
3718
+ return false;
3719
+ }
3720
+ return true;
3721
+ }
3722
+ parseRow(row, table) {
3723
+ const parsed = {};
3724
+ const meta = this.schema.tables[table];
3725
+ if (meta) {
3726
+ // Every row of one result set has the same columns in the same order (a
3727
+ // SQL result set has fixed field descriptors, and a nested row decoded
3728
+ // from `json_build_object` has a fixed key list), so the per-column
3729
+ // name resolution and date-column membership tests are the same answer
3730
+ // recomputed for every row. Resolve them ONCE per column shape and keep
3731
+ // the plan; the shape is verified against each row rather than assumed,
3732
+ // so a caller that does hand this function heterogeneous rows gets a
3733
+ // rebuilt plan instead of a mis-mapped one.
3734
+ const keys = Object.keys(row);
3735
+ const last = this.rowPlanLast.get(table);
3736
+ const plan = last !== undefined && QueryInterface.rowPlanMatches(last, keys)
3737
+ ? last
3738
+ : this.buildRowDecodePlan(table, meta, keys);
3739
+ const { cols, fields, dates } = plan;
3740
+ for (let i = 0; i < cols.length; i++) {
3741
+ const field = fields[i];
3742
+ const value = row[cols[i]];
3743
+ parsed[field] = dates[i] ? this.decodeTemporalCell(value, table, field) : value;
3432
3744
  }
3433
3745
  }
3434
3746
  else {