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.
- package/README.md +34 -32
- package/dist/adapters/cockroachdb.js +21 -3
- package/dist/adapters/index.d.ts +15 -0
- package/dist/adapters/yugabytedb.js +20 -3
- package/dist/cjs/adapters/cockroachdb.js +21 -3
- package/dist/cjs/adapters/index.d.ts +15 -0
- package/dist/cjs/adapters/yugabytedb.js +20 -3
- package/dist/cjs/cli/destructive.d.ts +18 -4
- package/dist/cjs/cli/destructive.js +230 -122
- package/dist/cjs/cli/index.d.ts +21 -4
- package/dist/cjs/cli/index.js +119 -22
- package/dist/cjs/cli/mcp.d.ts +28 -8
- package/dist/cjs/cli/mcp.js +170 -127
- package/dist/cjs/cli/migrate.d.ts +134 -13
- package/dist/cjs/cli/migrate.js +349 -241
- package/dist/cjs/cli/pii-predicate-guard.d.ts +112 -0
- package/dist/cjs/cli/pii-predicate-guard.js +390 -0
- package/dist/cjs/cli/prisma-resolve.js +75 -4
- package/dist/cjs/cli/prisma-schema.d.ts +17 -1
- package/dist/cjs/cli/prisma-schema.js +83 -17
- package/dist/cjs/cli/sql-statements.d.ts +125 -0
- package/dist/cjs/cli/sql-statements.js +378 -0
- package/dist/cjs/cli/studio.js +49 -118
- package/dist/cjs/cli/ui.d.ts +1 -1
- package/dist/cjs/client.d.ts +43 -0
- package/dist/cjs/client.js +125 -6
- package/dist/cjs/dialect.d.ts +123 -0
- package/dist/cjs/dialect.js +33 -0
- package/dist/cjs/errors.d.ts +74 -1
- package/dist/cjs/errors.js +239 -25
- package/dist/cjs/index-advisor.d.ts +33 -1
- package/dist/cjs/index-advisor.js +32 -1
- package/dist/cjs/introspect.d.ts +48 -0
- package/dist/cjs/introspect.js +222 -91
- package/dist/cjs/mssql.js +43 -1
- package/dist/cjs/mysql.d.ts +5 -2
- package/dist/cjs/mysql.js +202 -17
- package/dist/cjs/nested-write.js +6 -1
- package/dist/cjs/pipeline-submittable.js +17 -3
- package/dist/cjs/pipeline.js +75 -9
- package/dist/cjs/powdb.d.ts +23 -0
- package/dist/cjs/powdb.js +33 -1
- package/dist/cjs/powql.d.ts +61 -9
- package/dist/cjs/powql.js +186 -49
- package/dist/cjs/prisma-compat.js +160 -41
- package/dist/cjs/query/aggregates.d.ts +1 -1
- package/dist/cjs/query/aggregates.js +80 -18
- package/dist/cjs/query/batched-loader.d.ts +10 -0
- package/dist/cjs/query/batched-loader.js +268 -7
- package/dist/cjs/query/builder.d.ts +112 -0
- package/dist/cjs/query/builder.js +410 -98
- package/dist/cjs/query/filters.d.ts +162 -0
- package/dist/cjs/query/filters.js +250 -1
- package/dist/cjs/query/relations.d.ts +10 -10
- package/dist/cjs/query/relations.js +93 -12
- package/dist/cjs/query/types.d.ts +14 -1
- package/dist/cjs/query/utils.d.ts +146 -2
- package/dist/cjs/query/utils.js +210 -4
- package/dist/cjs/query/warn-registry.d.ts +10 -0
- package/dist/cjs/query/warn-registry.js +10 -0
- package/dist/cjs/query/where-compile.d.ts +30 -0
- package/dist/cjs/query/where-compile.js +41 -0
- package/dist/cjs/query/where.d.ts +128 -13
- package/dist/cjs/query/where.js +215 -77
- package/dist/cjs/query/writes.d.ts +1 -1
- package/dist/cjs/query/writes.js +39 -15
- package/dist/cjs/schema-builder.d.ts +2 -1
- package/dist/cjs/schema-sql.d.ts +94 -4
- package/dist/cjs/schema-sql.js +506 -30
- package/dist/cjs/schema.d.ts +3 -1
- package/dist/cjs/sqlite.d.ts +6 -0
- package/dist/cjs/sqlite.js +151 -10
- package/dist/cjs/typed-sql.d.ts +29 -1
- package/dist/cjs/typed-sql.js +30 -12
- package/dist/cli/destructive.d.ts +18 -4
- package/dist/cli/destructive.js +229 -121
- package/dist/cli/index.d.ts +21 -4
- package/dist/cli/index.js +120 -24
- package/dist/cli/mcp.d.ts +28 -8
- package/dist/cli/mcp.js +172 -129
- package/dist/cli/migrate.d.ts +134 -13
- package/dist/cli/migrate.js +347 -238
- package/dist/cli/pii-predicate-guard.d.ts +112 -0
- package/dist/cli/pii-predicate-guard.js +386 -0
- package/dist/cli/prisma-resolve.js +75 -4
- package/dist/cli/prisma-schema.d.ts +17 -1
- package/dist/cli/prisma-schema.js +83 -17
- package/dist/cli/sql-statements.d.ts +125 -0
- package/dist/cli/sql-statements.js +373 -0
- package/dist/cli/studio.js +49 -118
- package/dist/cli/ui.d.ts +1 -1
- package/dist/client.d.ts +43 -0
- package/dist/client.js +126 -7
- package/dist/dialect.d.ts +123 -0
- package/dist/dialect.js +33 -0
- package/dist/errors.d.ts +74 -1
- package/dist/errors.js +228 -19
- package/dist/index-advisor.d.ts +33 -1
- package/dist/index-advisor.js +31 -1
- package/dist/introspect.d.ts +48 -0
- package/dist/introspect.js +221 -91
- package/dist/mssql.js +44 -2
- package/dist/mysql.d.ts +5 -2
- package/dist/mysql.js +203 -18
- package/dist/nested-write.js +7 -2
- package/dist/pipeline-submittable.js +18 -4
- package/dist/pipeline.js +76 -10
- package/dist/powdb.d.ts +23 -0
- package/dist/powdb.js +33 -2
- package/dist/powql.d.ts +61 -9
- package/dist/powql.js +187 -50
- package/dist/prisma-compat.js +160 -41
- package/dist/query/aggregates.d.ts +1 -1
- package/dist/query/aggregates.js +82 -20
- package/dist/query/batched-loader.d.ts +10 -0
- package/dist/query/batched-loader.js +270 -9
- package/dist/query/builder.d.ts +112 -0
- package/dist/query/builder.js +411 -100
- package/dist/query/filters.d.ts +162 -0
- package/dist/query/filters.js +246 -1
- package/dist/query/relations.d.ts +10 -10
- package/dist/query/relations.js +94 -14
- package/dist/query/types.d.ts +14 -1
- package/dist/query/utils.d.ts +146 -2
- package/dist/query/utils.js +204 -3
- package/dist/query/warn-registry.d.ts +10 -0
- package/dist/query/warn-registry.js +10 -0
- package/dist/query/where-compile.d.ts +30 -0
- package/dist/query/where-compile.js +40 -1
- package/dist/query/where.d.ts +128 -13
- package/dist/query/where.js +216 -80
- package/dist/query/writes.d.ts +1 -1
- package/dist/query/writes.js +40 -16
- package/dist/schema-builder.d.ts +2 -1
- package/dist/schema-sql.d.ts +94 -4
- package/dist/schema-sql.js +505 -30
- package/dist/schema.d.ts +3 -1
- package/dist/sqlite.d.ts +6 -0
- package/dist/sqlite.js +151 -10
- package/dist/typed-sql.d.ts +29 -1
- package/dist/typed-sql.js +30 -12
- package/package.json +6 -4
package/dist/query/builder.js
CHANGED
|
@@ -18,10 +18,10 @@ import { normalizeKeyColumns, snakeToCamel } from '../schema.js';
|
|
|
18
18
|
import * as aggMod from './aggregates.js';
|
|
19
19
|
import { assertProjectionShape, defaultProjectionFields, includeKeysForBatching, loadRelationsBatched, neededParentKeyFields, rejectNestedPickOrder, resolveCountRelations, stripFields, } from './batched-loader.js';
|
|
20
20
|
import { expandCompoundUniqueWhere } from './compound-unique.js';
|
|
21
|
-
import { isJsonPathOrderBy, isOrderBySpec, isRelationPickOrderBy, isVectorOrderBy, isWhereOperator, orderByEntries, sortedEntries, } from './filters.js';
|
|
21
|
+
import { dedupeColumnList, dedupeOrderEntries, isJsonPathOrderBy, isOrderBySpec, isRelationPickOrderBy, isVectorOrderBy, isWhereOperator, orderByEntries, sortedEntries, } from './filters.js';
|
|
22
22
|
import * as relationsMod from './relations.js';
|
|
23
23
|
import { resolveSkipGlobalFilters, resolveUnsafeFlag, UNSAFE } from './types.js';
|
|
24
|
-
import { isTemporalInfinity, LRUCache, ownLookup, parseDbDate, resolveColumnName, sqlToPreparedName, unknownFieldMessage, } from './utils.js';
|
|
24
|
+
import { isTemporalInfinity, LRUCache, ownLookup, parseDbDate, resolveColumnName, sqlToPreparedName, unknownFieldMessage, warnRedundantSortTerm, } from './utils.js';
|
|
25
25
|
import { shouldWarnOnce, WARN_NS } from './warn-registry.js';
|
|
26
26
|
import * as whereMod from './where.js';
|
|
27
27
|
import * as writesMod from './writes.js';
|
|
@@ -50,18 +50,55 @@ import * as writesMod from './writes.js';
|
|
|
50
50
|
* throws, same as dev. `0`, unset, or an unparseable value means never check.
|
|
51
51
|
*/
|
|
52
52
|
function cacheCrossCheckMode() {
|
|
53
|
+
const env = crossCheckEnv ?? readCrossCheckEnv();
|
|
54
|
+
if (env.mode !== 'sampled')
|
|
55
|
+
return env.mode;
|
|
56
|
+
// The SAMPLING decision, and only it, is genuinely per hit.
|
|
57
|
+
return env.rate >= 1 || Math.random() < env.rate ? 'sampled' : 'off';
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The env-derived half of {@link cacheCrossCheckMode}, resolved ONCE per
|
|
61
|
+
* process and memoized.
|
|
62
|
+
*
|
|
63
|
+
* `process.env` is not a plain object: every property read crosses a C++
|
|
64
|
+
* interceptor. Measured at 112.7 ns per read against 3.6 ns for a module-level
|
|
65
|
+
* constant, and this function ran TWO reads on every cache hit, which put it
|
|
66
|
+
* at the top of the SQL-build CPU profile (12.53% self time, with a further
|
|
67
|
+
* ~12% inside the interceptor) for a value that does not change.
|
|
68
|
+
*
|
|
69
|
+
* It is memoized rather than hoisted to a `const` because the toggle IS
|
|
70
|
+
* observed at runtime, contrary to what a quick look suggests: the
|
|
71
|
+
* cross-check and sampling suites flip `NODE_ENV` /
|
|
72
|
+
* `TURBINE_DISABLE_CACHE_CHECK` / `TURBINE_CACHE_CHECK_SAMPLE` around a
|
|
73
|
+
* synchronous block in-process, not at spawn. So the read is deferred to first
|
|
74
|
+
* use and {@link resetCacheCrossCheckEnv} re-arms it; that is the entire
|
|
75
|
+
* contract, and the only thing lost versus reading every time is that a
|
|
76
|
+
* process which mutates these variables mid-run must say so.
|
|
77
|
+
*/
|
|
78
|
+
let crossCheckEnv;
|
|
79
|
+
function readCrossCheckEnv() {
|
|
80
|
+
let resolved;
|
|
53
81
|
if (process.env.NODE_ENV !== 'production') {
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
82
|
+
resolved = { mode: process.env.TURBINE_DISABLE_CACHE_CHECK === '1' ? 'off' : 'dev' };
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
const raw = process.env.TURBINE_CACHE_CHECK_SAMPLE;
|
|
86
|
+
const rate = raw === undefined ? Number.NaN : Number.parseFloat(raw);
|
|
87
|
+
resolved = !Number.isFinite(rate) || rate <= 0 ? { mode: 'off' } : { mode: 'sampled', rate };
|
|
88
|
+
}
|
|
89
|
+
crossCheckEnv = resolved;
|
|
90
|
+
return resolved;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Discard the memoized cross-check environment so the next cache hit re-reads
|
|
94
|
+
* `process.env`.
|
|
95
|
+
*
|
|
96
|
+
* @internal Exposed for the tests that toggle these variables in-process (see
|
|
97
|
+
* {@link crossCheckEnv}). Production code sets them before the first query and
|
|
98
|
+
* never again.
|
|
99
|
+
*/
|
|
100
|
+
export function resetCacheCrossCheckEnv() {
|
|
101
|
+
crossCheckEnv = undefined;
|
|
65
102
|
}
|
|
66
103
|
/**
|
|
67
104
|
* Distinct cache-mismatch fingerprints already logged by the sampled production
|
|
@@ -211,6 +248,22 @@ export const AUTO_TO_ONE_JOIN_ROWS_MAX = 100_000;
|
|
|
211
248
|
* it.
|
|
212
249
|
*/
|
|
213
250
|
export const AUTO_COUNT_BATCH_MIN_PARENT_ROWS = 2;
|
|
251
|
+
/**
|
|
252
|
+
* How many distinct `parseRow` column shapes one QueryInterface remembers.
|
|
253
|
+
* Deliberately far smaller than the 1,000-entry SQL template cache: a shape is
|
|
254
|
+
* a `select` / `omit` projection rather than a where-clause fingerprint, so the
|
|
255
|
+
* realistic population is single digits per table, and the cost of a miss is
|
|
256
|
+
* one rebuild rather than a re-parse on the server.
|
|
257
|
+
*/
|
|
258
|
+
const ROW_PLAN_CACHE_SIZE = 128;
|
|
259
|
+
/**
|
|
260
|
+
* The largest `findManyStream` batch size for which the speculative first fetch
|
|
261
|
+
* is still worth attempting. Equal to the default batch size, so the default
|
|
262
|
+
* and everything below it behaves exactly as it always has. See the comment at
|
|
263
|
+
* the speculation itself for why the bound is on `batchSize` rather than on the
|
|
264
|
+
* probe's own limit.
|
|
265
|
+
*/
|
|
266
|
+
const STREAM_SPECULATION_MAX_BATCH = 1000;
|
|
214
267
|
/**
|
|
215
268
|
* Strict structural equality for a single SQL parameter value. Handles the
|
|
216
269
|
* value shapes Turbine binds: primitives (incl. `NaN` and `bigint`), `null`/
|
|
@@ -380,6 +433,16 @@ export class QueryInterface {
|
|
|
380
433
|
* inline, not through the top-level cache).
|
|
381
434
|
*/
|
|
382
435
|
lastCacheHit = false;
|
|
436
|
+
/**
|
|
437
|
+
* Set while a build closure runs when the statement's WHERE (or HAVING)
|
|
438
|
+
* carries a caller-written `AND`/`OR` combinator array, i.e. when its SQL text
|
|
439
|
+
* is a function of an arity the caller chose. Read (and reset) by
|
|
440
|
+
* {@link acquireSql}, which brackets the single `build()` call, so the flag
|
|
441
|
+
* has no lifetime outside that synchronous window and cannot leak between
|
|
442
|
+
* queries. See {@link BuilderCtx.markVariableArity} for the unbounded
|
|
443
|
+
* server-side prepared-statement growth this exists to stop.
|
|
444
|
+
*/
|
|
445
|
+
variableArityShape = false;
|
|
383
446
|
middlewares;
|
|
384
447
|
defaultLimit;
|
|
385
448
|
warnOnUnlimited;
|
|
@@ -430,6 +493,20 @@ export class QueryInterface {
|
|
|
430
493
|
autoRoundTripMs;
|
|
431
494
|
/** Nested-relation JSON encoding: 'object' (default) or 'positional'. */
|
|
432
495
|
jsonEncoding;
|
|
496
|
+
/**
|
|
497
|
+
* `parseRow` decode plans, keyed by table plus the exact column list. Bounded
|
|
498
|
+
* like the SQL template cache and for the same reason: the shapes come from
|
|
499
|
+
* `select` / `omit`, which is usually a handful of literals in the caller's
|
|
500
|
+
* source but can be assembled per request from user input, so the key space
|
|
501
|
+
* is not provably finite. Eviction only ever costs a rebuild.
|
|
502
|
+
*/
|
|
503
|
+
rowPlanCache = new LRUCache(ROW_PLAN_CACHE_SIZE);
|
|
504
|
+
/**
|
|
505
|
+
* The most recent plan per table, which is the entry `parseRow` actually
|
|
506
|
+
* probes. One result set is one shape, so this hits for every row after the
|
|
507
|
+
* first without hashing a cache key per row.
|
|
508
|
+
*/
|
|
509
|
+
rowPlanLast = new Map();
|
|
433
510
|
/**
|
|
434
511
|
* Client-level automatic WHERE filters keyed by table accessor (soft-delete /
|
|
435
512
|
* multi-tenancy). AND-merged into every query on the keyed table and every
|
|
@@ -466,6 +543,17 @@ export class QueryInterface {
|
|
|
466
543
|
* to Date as well (otherwise nested dates leak through as strings).
|
|
467
544
|
*/
|
|
468
545
|
camelDateFieldCache = new Map();
|
|
546
|
+
/**
|
|
547
|
+
* Per-table memo of `Object.entries(meta.relations)`, consumed by the nested
|
|
548
|
+
* row parser (see `getRelationEntries` in relations.ts). Same rationale and
|
|
549
|
+
* same lifetime as {@link camelDateFieldCache}: the metadata is immutable, and
|
|
550
|
+
* the parser reads it once per row.
|
|
551
|
+
*/
|
|
552
|
+
relationEntryCache = new Map();
|
|
553
|
+
/** Per-table memo of batched-loader child readers (see {@link batchedChild}). */
|
|
554
|
+
batchedChildCache = new Map();
|
|
555
|
+
/** The (option-invariant) options every batched child is built with. */
|
|
556
|
+
batchedChildOptions;
|
|
469
557
|
/** True when this QI runs inside an active transaction (set via _txScoped option). */
|
|
470
558
|
txScoped;
|
|
471
559
|
/** Original options reference, forwarded to child QIs in nested writes. */
|
|
@@ -662,6 +750,9 @@ export class QueryInterface {
|
|
|
662
750
|
set currentSkip(v) {
|
|
663
751
|
self.currentSkip = v;
|
|
664
752
|
},
|
|
753
|
+
markVariableArity: () => {
|
|
754
|
+
this.variableArityShape = true;
|
|
755
|
+
},
|
|
665
756
|
q: (name) => this.q(name),
|
|
666
757
|
p: (index) => this.p(index),
|
|
667
758
|
inParam: (values) => this.inParam(values),
|
|
@@ -679,6 +770,7 @@ export class QueryInterface {
|
|
|
679
770
|
crossCheckCache: (op, cacheKey, entry, build, collectedParams) => this.crossCheckCache(op, cacheKey, entry, build, collectedParams),
|
|
680
771
|
jsonEncoding: this.jsonEncoding,
|
|
681
772
|
camelDateFieldCache: this.camelDateFieldCache,
|
|
773
|
+
relationEntryCache: this.relationEntryCache,
|
|
682
774
|
limitOneClause: () => this.limitOneClause(),
|
|
683
775
|
buildPagination: (limitPh, offsetPh, hasOrderBy) => this.buildPagination(limitPh, offsetPh, hasOrderBy),
|
|
684
776
|
paginationRef: (value, params, arg) => this.paginationRef(value, params, arg),
|
|
@@ -1441,15 +1533,10 @@ export class QueryInterface {
|
|
|
1441
1533
|
includePii, forceCustomPlan = false) {
|
|
1442
1534
|
// The loader's own global-filter callback below needs the RESOLVED form.
|
|
1443
1535
|
const resolvedSkip = resolveSkipGlobalFilters(skip);
|
|
1444
|
-
const childOptions = {
|
|
1445
|
-
...this.options,
|
|
1446
|
-
defaultLimit: undefined,
|
|
1447
|
-
warnOnUnlimited: false,
|
|
1448
|
-
};
|
|
1449
1536
|
return {
|
|
1450
1537
|
parentMeta: this.tableMeta,
|
|
1451
1538
|
schema: this.schema,
|
|
1452
|
-
makeChild: (table) =>
|
|
1539
|
+
makeChild: (table) => this.batchedChild(table),
|
|
1453
1540
|
// The per-query `forceCustomPlan` opt-in covers the relation follow-ups
|
|
1454
1541
|
// too: a batched load re-issues the SAME tenant-shaped predicate one
|
|
1455
1542
|
// level down, so leaving those named would keep exactly the plan-cache
|
|
@@ -1459,6 +1546,23 @@ export class QueryInterface {
|
|
|
1459
1546
|
buildInClause: (expr, paramRef, negated) => this.inClause(expr, paramRef, negated),
|
|
1460
1547
|
inClauseParam: (values) => this.inParam(values),
|
|
1461
1548
|
paramPlaceholder: (index) => this.p(index),
|
|
1549
|
+
// Bound each relation follow-up per correlation key when the engine can
|
|
1550
|
+
// express it; absent leaves the loader on its client-side slice. Bound as
|
|
1551
|
+
// a closure rather than passing `this.dialect` so the loader keeps
|
|
1552
|
+
// needing nothing else from the dialect.
|
|
1553
|
+
//
|
|
1554
|
+
// The `dialect.name` test is NOT redundant with the hook's presence, and
|
|
1555
|
+
// this is the same trap the `distinct` gate documents: every engine
|
|
1556
|
+
// dialect is built by SPREADING `postgresDialect`, so an optional hook
|
|
1557
|
+
// added there is INHERITED by sqlite / mysql / mssql, whose "absent"
|
|
1558
|
+
// fallback would then never be taken. The wrapper is not portable as
|
|
1559
|
+
// written either (T-SQL rejects an ORDER BY inside a derived table
|
|
1560
|
+
// without TOP/OFFSET, and the compiled child query carries one), so the
|
|
1561
|
+
// pushdown stays with the dialect that owns the implementation until
|
|
1562
|
+
// another engine ships its own and asserts it.
|
|
1563
|
+
buildPartitionLimit: this.dialect.name === 'postgresql' && this.dialect.buildPartitionLimit
|
|
1564
|
+
? (input) => this.dialect.buildPartitionLimit(input)
|
|
1565
|
+
: undefined,
|
|
1462
1566
|
skipGlobalFilters: skip,
|
|
1463
1567
|
// Query-level opt-in threaded onto every follow-up child `buildFindMany`,
|
|
1464
1568
|
// so a batched load excludes/includes PII exactly as the join strategy.
|
|
@@ -1480,6 +1584,36 @@ export class QueryInterface {
|
|
|
1480
1584
|
},
|
|
1481
1585
|
};
|
|
1482
1586
|
}
|
|
1587
|
+
/**
|
|
1588
|
+
* The child {@link QueryInterface} the batched loader uses for `table`,
|
|
1589
|
+
* memoized per table for the lifetime of this accessor.
|
|
1590
|
+
*
|
|
1591
|
+
* It used to be constructed fresh for every relation of every query, which
|
|
1592
|
+
* threw away that child's SQL template cache each time: a relation follow-up
|
|
1593
|
+
* therefore MISSED the cache on every single request and rebuilt its SQL,
|
|
1594
|
+
* which is the one thing the template cache exists to avoid, and it allocated
|
|
1595
|
+
* a whole QueryInterface (column type maps, camel-date memo, the ctx literal)
|
|
1596
|
+
* per relation per query. `childOptions` was likewise a fresh spread per
|
|
1597
|
+
* query although it is a pure function of this instance's options.
|
|
1598
|
+
*
|
|
1599
|
+
* Safe to share across queries: a QueryInterface holds no per-query state
|
|
1600
|
+
* beyond the transient build fields, which live and die inside one
|
|
1601
|
+
* synchronous `build*` call, and every child is bound to THIS instance's pool
|
|
1602
|
+
* (so it still joins an active transaction) with `defaultLimit` cleared and
|
|
1603
|
+
* unlimited-warnings silenced, because a relation load must fetch every
|
|
1604
|
+
* matching child. Per-query values (`skipGlobalFilters`, `includePii`,
|
|
1605
|
+
* `timeout`, `forceCustomPlan`) are passed as ARGUMENTS by the loader, never
|
|
1606
|
+
* baked into the child, which is what makes the memo sound.
|
|
1607
|
+
*/
|
|
1608
|
+
batchedChild(table) {
|
|
1609
|
+
let child = this.batchedChildCache.get(table);
|
|
1610
|
+
if (!child) {
|
|
1611
|
+
this.batchedChildOptions ??= { ...this.options, defaultLimit: undefined, warnOnUnlimited: false };
|
|
1612
|
+
child = new QueryInterface(this.pool, table, this.schema, [], this.batchedChildOptions);
|
|
1613
|
+
this.batchedChildCache.set(table, child);
|
|
1614
|
+
}
|
|
1615
|
+
return child;
|
|
1616
|
+
}
|
|
1483
1617
|
/**
|
|
1484
1618
|
* Run a findMany with the batched strategy: execute the base query WITHOUT
|
|
1485
1619
|
* relation subqueries (all other clauses intact), then load each relation via
|
|
@@ -1564,9 +1698,7 @@ export class QueryInterface {
|
|
|
1564
1698
|
acquireSql(cacheKey, build) {
|
|
1565
1699
|
if (!this.sqlCacheEnabled) {
|
|
1566
1700
|
this.lastCacheHit = false;
|
|
1567
|
-
|
|
1568
|
-
this.cacheMisses++;
|
|
1569
|
-
return { sql, name: sqlToPreparedName(sql) };
|
|
1701
|
+
return this.buildCacheEntry(build);
|
|
1570
1702
|
}
|
|
1571
1703
|
const cached = this.sqlTemplateCache.get(cacheKey);
|
|
1572
1704
|
if (cached) {
|
|
@@ -1575,12 +1707,38 @@ export class QueryInterface {
|
|
|
1575
1707
|
return cached;
|
|
1576
1708
|
}
|
|
1577
1709
|
this.lastCacheHit = false;
|
|
1578
|
-
const
|
|
1579
|
-
const entry = { sql, name: sqlToPreparedName(sql) };
|
|
1710
|
+
const entry = this.buildCacheEntry(build);
|
|
1580
1711
|
this.sqlTemplateCache.set(cacheKey, entry);
|
|
1581
|
-
this.cacheMisses++;
|
|
1582
1712
|
return entry;
|
|
1583
1713
|
}
|
|
1714
|
+
/**
|
|
1715
|
+
* Run one build closure and pair its SQL with the prepared-statement name it
|
|
1716
|
+
* should execute under.
|
|
1717
|
+
*
|
|
1718
|
+
* The `variableArityShape` flag is reset immediately BEFORE the build and read
|
|
1719
|
+
* immediately AFTER it, so this method is the flag's entire lifetime: the
|
|
1720
|
+
* build walk (`buildWhereClause` / `buildScopedWhere` / the HAVING combinator)
|
|
1721
|
+
* is the only thing that can set it, nothing can observe a stale value, and a
|
|
1722
|
+
* throw out of `build()` leaves nothing behind to affect the next query.
|
|
1723
|
+
*
|
|
1724
|
+
* An EMPTY name is how "send this unnamed" travels: `queryWithTimeout` tests
|
|
1725
|
+
* the name for truthiness, so `''` takes the plain `(text, values)` form the
|
|
1726
|
+
* driver never registers a named statement for. Doing it HERE rather than at
|
|
1727
|
+
* the execute seam is what makes it survive the cache: the entry is created
|
|
1728
|
+
* once, on the miss, and a later HIT reuses the same (empty) name, so a
|
|
1729
|
+
* variable-arity shape can never acquire a name from a warmed template.
|
|
1730
|
+
*
|
|
1731
|
+
* See {@link BuilderCtx.markVariableArity} for what makes a shape
|
|
1732
|
+
* variable-arity and the measured reason it must not be named.
|
|
1733
|
+
*/
|
|
1734
|
+
buildCacheEntry(build) {
|
|
1735
|
+
this.variableArityShape = false;
|
|
1736
|
+
const sql = build([]);
|
|
1737
|
+
const variableArity = this.variableArityShape;
|
|
1738
|
+
this.variableArityShape = false;
|
|
1739
|
+
this.cacheMisses++;
|
|
1740
|
+
return { sql, name: variableArity ? '' : sqlToPreparedName(sql) };
|
|
1741
|
+
}
|
|
1584
1742
|
/**
|
|
1585
1743
|
* Dev-mode SQL-cache lockstep cross-check (see {@link cacheCrossCheckEnabled}).
|
|
1586
1744
|
*
|
|
@@ -1910,7 +2068,6 @@ export class QueryInterface {
|
|
|
1910
2068
|
stripFields([entity], proj.strip);
|
|
1911
2069
|
return entity;
|
|
1912
2070
|
}
|
|
1913
|
-
// biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
|
|
1914
2071
|
buildFindUnique(args) {
|
|
1915
2072
|
this.currentSkip = resolveSkipGlobalFilters(args.skipGlobalFilters);
|
|
1916
2073
|
// Prisma compound-unique selector expansion (before global-filter merge and
|
|
@@ -2249,7 +2406,6 @@ export class QueryInterface {
|
|
|
2249
2406
|
}
|
|
2250
2407
|
return maxDepth;
|
|
2251
2408
|
}
|
|
2252
|
-
// biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
|
|
2253
2409
|
buildFindMany(args) {
|
|
2254
2410
|
this.currentSkip = resolveSkipGlobalFilters(args?.skipGlobalFilters);
|
|
2255
2411
|
// Stable relation order (opt-in): fill PK-asc orderBy into unordered to-many
|
|
@@ -2270,6 +2426,32 @@ export class QueryInterface {
|
|
|
2270
2426
|
if (args?.orderBy !== undefined && isEmptyOrderBy(args.orderBy)) {
|
|
2271
2427
|
args = { ...args, orderBy: undefined };
|
|
2272
2428
|
}
|
|
2429
|
+
// Drop `orderBy` terms that sort by an expression an earlier term already
|
|
2430
|
+
// sorted by, and `distinct` columns named twice. HERE, before the
|
|
2431
|
+
// fingerprint, for the reason every other normalization in this method is
|
|
2432
|
+
// here: the fingerprint, the SQL build and the param collect must all see
|
|
2433
|
+
// ONE list, or the cache key and the statement it caches describe different
|
|
2434
|
+
// queries. Rewritten into the array form, which flattens through
|
|
2435
|
+
// `orderByEntries` to the identical entry list the object form does, so a
|
|
2436
|
+
// caller who wrote no duplicate is untouched down to the cache key (the
|
|
2437
|
+
// helpers return null unless something was actually dropped).
|
|
2438
|
+
if (args?.orderBy !== undefined) {
|
|
2439
|
+
const deduped = dedupeOrderEntries(this.tableMeta, orderByEntries(args.orderBy), this.table);
|
|
2440
|
+
if (deduped) {
|
|
2441
|
+
warnRedundantSortTerm(this.table, 'orderBy', deduped.dropped);
|
|
2442
|
+
args = {
|
|
2443
|
+
...args,
|
|
2444
|
+
orderBy: deduped.entries.map(([k, v]) => ({ [k]: v })),
|
|
2445
|
+
};
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
if (args?.distinct && args.distinct.length > 0) {
|
|
2449
|
+
const deduped = dedupeColumnList(this.tableMeta, args.distinct);
|
|
2450
|
+
if (deduped) {
|
|
2451
|
+
warnRedundantSortTerm(this.table, 'distinct', deduped.dropped);
|
|
2452
|
+
args = { ...args, distinct: deduped.columns };
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2273
2455
|
// Deterministic pagination (opt-in): fill a PK-asc orderBy into a paginating
|
|
2274
2456
|
// query that declares none, BEFORE fingerprinting so the ordered and
|
|
2275
2457
|
// unordered shapes get distinct cache entries. No-op unless
|
|
@@ -2277,6 +2459,29 @@ export class QueryInterface {
|
|
|
2277
2459
|
const implicitOrder = this.implicitPkOrderBy(args);
|
|
2278
2460
|
if (implicitOrder)
|
|
2279
2461
|
args = { ...args, orderBy: implicitOrder };
|
|
2462
|
+
// `distinct` compiles to `SELECT DISTINCT ON (...)`, which is PostgreSQL
|
|
2463
|
+
// syntax and nothing else's. Every other engine parsed it as far as the
|
|
2464
|
+
// word `ON` and answered with a RAW driver error carrying no TURBINE_ code
|
|
2465
|
+
// (SQLite: `near "ON": syntax error`; MySQL: ER_PARSE_ERROR), i.e. the one
|
|
2466
|
+
// shape the typed-error surface exists to prevent. Refused with the same
|
|
2467
|
+
// E017 the OTHER spelling of this feature already used, `groupBy({
|
|
2468
|
+
// distinctOn })` in aggregates.ts, which was gated correctly all along.
|
|
2469
|
+
//
|
|
2470
|
+
// `dialect.name` rather than a new capability flag, deliberately, and this
|
|
2471
|
+
// is the exception to the "capability flags, not engine names" rule the
|
|
2472
|
+
// rest of the dialect follows: every engine dialect is built by SPREADING
|
|
2473
|
+
// `postgresDialect`, so a flag defaulting to `true` would be inherited by
|
|
2474
|
+
// all of them (which is the bug) and one defaulting to `false` would have
|
|
2475
|
+
// to be re-declared on Postgres-compatible dialects that already work.
|
|
2476
|
+
// The established precedent for exactly this feature is the `dialect.name`
|
|
2477
|
+
// test in `buildDistinctOnSource`.
|
|
2478
|
+
//
|
|
2479
|
+
// Before the cache, like the two guards below, so a warmed template cannot
|
|
2480
|
+
// serve the query the cold path refuses.
|
|
2481
|
+
if (args?.distinct && args.distinct.length > 0 && this.dialect.name !== 'postgresql') {
|
|
2482
|
+
throw new UnsupportedFeatureError('DISTINCT ON (findMany distinct)', this.dialect.name, 'findMany({ distinct }) requires PostgreSQL: SELECT DISTINCT ON is not portable. Group in ' +
|
|
2483
|
+
'application code, or use groupBy({ by }) for one row per combination.');
|
|
2484
|
+
}
|
|
2280
2485
|
// `distinct` + relation orderBy is refused up front (E003): the distinct
|
|
2281
2486
|
// path re-orders in an outer wrapper (`... AS "<table>_distinct" ORDER BY
|
|
2282
2487
|
// <userOrder>`) where a correlated relation subquery (pick-row, `_count`,
|
|
@@ -2367,6 +2572,30 @@ export class QueryInterface {
|
|
|
2367
2572
|
if (args?.distinct && args.distinct.length > 0) {
|
|
2368
2573
|
distinctCols = args.distinct.map((k) => this.toSqlColumn(k));
|
|
2369
2574
|
distinctPrefix = `DISTINCT ON (${distinctCols.join(', ')}) `;
|
|
2575
|
+
// A MULTI-column `distinct` gives up its server-side prepared-statement
|
|
2576
|
+
// name, for the same reason a caller-written `OR` array does and by the
|
|
2577
|
+
// same mechanism (see markVariableArity). The channel here is ORDER, not
|
|
2578
|
+
// arity: the column list is written into the SQL text one term at a
|
|
2579
|
+
// time, so the reachable statement set is the ORDERED subsets of the
|
|
2580
|
+
// table's columns. Measured on PostgreSQL 16, a seven-column table:
|
|
2581
|
+
// 5,040 `distinct` permutations left 5,040 further permanent statements
|
|
2582
|
+
// and took CachedPlanSource from 39.4 MB to 59.1 MB on ONE connection.
|
|
2583
|
+
//
|
|
2584
|
+
// UNNAMED rather than canonicalized, which is what `select` and the
|
|
2585
|
+
// write `data` list do, and the asymmetry is the point. This list is
|
|
2586
|
+
// re-emitted as the leading terms of the inner ORDER BY a few lines
|
|
2587
|
+
// below, and with no `orderBy` at all PostgreSQL's choice of
|
|
2588
|
+
// representative row per group is explicitly unpredictable, so
|
|
2589
|
+
// reordering it could hand a caller a different row. Withholding the
|
|
2590
|
+
// name changes no SQL text and therefore cannot. The cost is one extra
|
|
2591
|
+
// server-side parse per execution on an already-rare query shape.
|
|
2592
|
+
//
|
|
2593
|
+
// `length > 1` because a single column has exactly one ordering and so
|
|
2594
|
+
// no permutation space: the common `distinct: ['tenantId']` keeps its
|
|
2595
|
+
// name. Repeats are already dropped upstream (dedupeColumnList), so the
|
|
2596
|
+
// list here is distinct columns and nothing else.
|
|
2597
|
+
if (args.distinct.length > 1)
|
|
2598
|
+
this.ctx.markVariableArity();
|
|
2370
2599
|
}
|
|
2371
2600
|
// Join-sink for `relationLoadStrategy: 'flatten'`. Filled while the SELECT
|
|
2372
2601
|
// list is built (so the flattened relations' ON-clause params interleave
|
|
@@ -2555,27 +2784,57 @@ export class QueryInterface {
|
|
|
2555
2784
|
const parseWith = hasRelations
|
|
2556
2785
|
? this.makeNestedParser(args.with, streamPii, streamFlattenPlan)
|
|
2557
2786
|
: null;
|
|
2558
|
-
// --- Speculative first fetch: try to satisfy the entire drain in one RTT ---
|
|
2559
|
-
const speculativeDeferred = this.buildFindMany({
|
|
2560
|
-
...args,
|
|
2561
|
-
limit: batchSize + 1,
|
|
2562
|
-
});
|
|
2563
2787
|
this.currentAction = 'findManyStream';
|
|
2564
2788
|
// Streaming is ALREADY immune to the generic-plan cliff: the speculative
|
|
2565
2789
|
// fetch has never passed a prepared name, and the cursor path runs through
|
|
2566
2790
|
// DECLARE, so neither statement enters the plan cache. `preparedNameFor` is
|
|
2567
|
-
// still called with no name so that `forceCustomPlan: true` is VALIDATED on
|
|
2791
|
+
// still called, with no name, so that `forceCustomPlan: true` is VALIDATED on
|
|
2568
2792
|
// an engine that cannot honour it here either, rather than being quietly
|
|
2569
|
-
// satisfied by an accident of this code path.
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2793
|
+
// satisfied by an accident of this code path. It is called OUTSIDE the
|
|
2794
|
+
// speculation branch below: it used to be the speculative fetch's own
|
|
2795
|
+
// argument, which would have made that validation conditional on a batch
|
|
2796
|
+
// size the moment the speculation became conditional.
|
|
2797
|
+
const streamPreparedName = this.preparedNameFor(args, undefined);
|
|
2798
|
+
// --- Speculative first fetch: try to satisfy the entire drain in one RTT ---
|
|
2799
|
+
//
|
|
2800
|
+
// A drain that fits in one batch needs no cursor, and skipping it saves the
|
|
2801
|
+
// four extra round trips BEGIN / DECLARE / CLOSE / COMMIT cost. That is the
|
|
2802
|
+
// whole point of this fetch, and it is a good trade while the statement is
|
|
2803
|
+
// cheap to throw away.
|
|
2804
|
+
//
|
|
2805
|
+
// On OVERFLOW it is thrown away: these rows were read outside the cursor's
|
|
2806
|
+
// transaction, so yielding them and then continuing from the cursor would
|
|
2807
|
+
// splice two snapshots together, and resuming past them would need an
|
|
2808
|
+
// ORDER BY the caller never asked for. Both are unsound, so the cursor
|
|
2809
|
+
// re-reads from row one and this fetch cost `batchSize + 1` rows for
|
|
2810
|
+
// nothing.
|
|
2811
|
+
//
|
|
2812
|
+
// That waste is proportional to `batchSize`, which is the one number the
|
|
2813
|
+
// caller raises when they expect MORE rows, so the optimization used to get
|
|
2814
|
+
// most expensive exactly where it was least likely to pay off: raising
|
|
2815
|
+
// `batchSize` for throughput made every large drain slower, and the stream
|
|
2816
|
+
// was the only thing here that got slower as `batchSize` went up. So the
|
|
2817
|
+
// speculation is now bounded BY `batchSize` rather than scaled by it. At or
|
|
2818
|
+
// below the default it is unchanged; above it, a caller asking for large
|
|
2819
|
+
// batches has told us not to expect a one-batch result, and we go straight
|
|
2820
|
+
// to the cursor and waste nothing. The cost of being wrong about that is
|
|
2821
|
+
// four round trips on a drain that would have fit, never any transferred
|
|
2822
|
+
// rows.
|
|
2823
|
+
if (batchSize <= STREAM_SPECULATION_MAX_BATCH) {
|
|
2824
|
+
const speculativeDeferred = this.buildFindMany({
|
|
2825
|
+
...args,
|
|
2826
|
+
limit: batchSize + 1,
|
|
2827
|
+
});
|
|
2828
|
+
const speculativeResult = await this.queryWithTimeout(speculativeDeferred.sql, speculativeDeferred.params, args?.timeout, streamPreparedName);
|
|
2829
|
+
if (speculativeResult.rows.length <= batchSize) {
|
|
2830
|
+
// Small drain, yield all rows and return, no cursor needed
|
|
2831
|
+
for (const row of speculativeResult.rows) {
|
|
2832
|
+
yield (parseWith ? parseWith(row) : this.parseRow(row, this.table));
|
|
2833
|
+
}
|
|
2834
|
+
return;
|
|
2575
2835
|
}
|
|
2576
|
-
return;
|
|
2577
2836
|
}
|
|
2578
|
-
// --- Overflow
|
|
2837
|
+
// --- Overflow, or speculation declined: cursor path from scratch ---
|
|
2579
2838
|
const deferred = this.buildFindMany(args);
|
|
2580
2839
|
// Acquire a dedicated connection: cursors require a single connection in a
|
|
2581
2840
|
// transaction. The dialect owns the streaming SQL (Postgres: BEGIN → DECLARE
|
|
@@ -2634,7 +2893,6 @@ export class QueryInterface {
|
|
|
2634
2893
|
return deferred.transform(result);
|
|
2635
2894
|
});
|
|
2636
2895
|
}
|
|
2637
|
-
// biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
|
|
2638
2896
|
buildFindFirst(args) {
|
|
2639
2897
|
// Reuse findMany's SQL builder but force LIMIT 1
|
|
2640
2898
|
const findManyArgs = { ...args, limit: 1 };
|
|
@@ -2659,7 +2917,6 @@ export class QueryInterface {
|
|
|
2659
2917
|
return deferred.transform(result);
|
|
2660
2918
|
});
|
|
2661
2919
|
}
|
|
2662
|
-
// biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
|
|
2663
2920
|
buildFindFirstOrThrow(args) {
|
|
2664
2921
|
const inner = this.buildFindFirst(args);
|
|
2665
2922
|
return {
|
|
@@ -2689,7 +2946,6 @@ export class QueryInterface {
|
|
|
2689
2946
|
return deferred.transform(result);
|
|
2690
2947
|
});
|
|
2691
2948
|
}
|
|
2692
|
-
// biome-ignore lint/complexity/noBannedTypes: {} means "no with clause", matches TypedWithClause default
|
|
2693
2949
|
buildFindUniqueOrThrow(args) {
|
|
2694
2950
|
const inner = this.buildFindUnique(args);
|
|
2695
2951
|
return {
|
|
@@ -3330,68 +3586,123 @@ export class QueryInterface {
|
|
|
3330
3586
|
return value;
|
|
3331
3587
|
return value === '-infinity' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
|
|
3332
3588
|
}
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3589
|
+
/**
|
|
3590
|
+
* The decode work for ONE cell of a date-bearing column, extracted so the
|
|
3591
|
+
* planned and unplanned row paths cannot drift apart. `null` and an
|
|
3592
|
+
* already-parsed `Date` are returned untouched, which is the same guard the
|
|
3593
|
+
* pre-plan code spelled inline.
|
|
3594
|
+
*/
|
|
3595
|
+
decodeTemporalCell(value, table, field) {
|
|
3596
|
+
if (value === null || value instanceof Date)
|
|
3597
|
+
return value;
|
|
3598
|
+
if (isTemporalInfinity(value)) {
|
|
3599
|
+
// Postgres `infinity` / `-infinity`. No JS Date means either, so both
|
|
3600
|
+
// readings cost something and the default is the one that is not lossy.
|
|
3601
|
+
// `'preserve'` hands back the JS number, which breaks the declared `Date`
|
|
3602
|
+
// type at runtime (`.toISOString()` throws) and still serializes as null
|
|
3603
|
+
// because JSON has no infinity literal, but binds straight back, so a
|
|
3604
|
+
// read-modify-write stores `infinity` again. `'null'` reads nicer and
|
|
3605
|
+
// DESTROYS the value on that same write, because a stored infinity and a
|
|
3606
|
+
// stored NULL become indistinguishable. Whichever is configured, it is
|
|
3607
|
+
// the SAME on every read strategy: the driver hands back the number,
|
|
3608
|
+
// `json_build_object` hands back the string "infinity", and both land
|
|
3609
|
+
// here (see `isTemporalInfinity`).
|
|
3610
|
+
//
|
|
3611
|
+
// The warning fires once per column when the option was left unset, on a
|
|
3612
|
+
// row that actually held an infinity, and describes the reading in force
|
|
3613
|
+
// rather than gating on which one it is.
|
|
3614
|
+
this.warnTemporalInfinity(table, field);
|
|
3615
|
+
return this.readTemporalInfinity(value);
|
|
3616
|
+
}
|
|
3617
|
+
if (Array.isArray(value)) {
|
|
3618
|
+
// `dateColumns` includes array-of-date columns (`date[]`, `timestamp[]`,
|
|
3619
|
+
// `timestamptz[]`), for which the driver already hands back a `Date[]`.
|
|
3620
|
+
// Coercing the array itself ran `new Date(String(theArray))` and replaced
|
|
3621
|
+
// the whole column with one Invalid Date. Its ELEMENTS get the same
|
|
3622
|
+
// infinity mapping as a scalar (same declared element type, same JSON
|
|
3623
|
+
// rendering); everything else is passed through by identity.
|
|
3624
|
+
return this.mapArrayTemporalInfinity(value, table, field);
|
|
3625
|
+
}
|
|
3626
|
+
// Any other number on a date column is left alone rather than run through
|
|
3627
|
+
// `parseDbDate(String(n))`, which would produce an Invalid Date.
|
|
3628
|
+
if (typeof value === 'number')
|
|
3629
|
+
return value;
|
|
3630
|
+
// Offset-less strings (Postgres `timestamp`, json_agg output) are pinned to
|
|
3631
|
+
// UTC so results don't depend on the server's time zone.
|
|
3632
|
+
return this.utcTimestamps ? parseDbDate(String(value)) : new Date(value);
|
|
3633
|
+
}
|
|
3634
|
+
/**
|
|
3635
|
+
* Build the decode plan for one exact column list, and remember it as this
|
|
3636
|
+
* table's most recent shape so the next row of the same result set hits the
|
|
3637
|
+
* fast path in {@link parseRow}.
|
|
3638
|
+
*/
|
|
3639
|
+
buildRowDecodePlan(table, meta, keys) {
|
|
3640
|
+
const shapeKey = `${table}${keys.join('')}`;
|
|
3641
|
+
let plan = this.rowPlanCache.get(shapeKey);
|
|
3642
|
+
if (plan === undefined) {
|
|
3338
3643
|
const reverseMap = meta.reverseColumnMap;
|
|
3339
3644
|
const dateCols = meta.dateColumns;
|
|
3340
3645
|
// camelCase-keyed date fields, so nested json_build_object rows (whose
|
|
3341
3646
|
// keys are already camelCase) get the same Date coercion as top-level rows.
|
|
3342
3647
|
const camelDateFields = this.getCamelDateFields(table, meta);
|
|
3343
|
-
const
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3648
|
+
const cols = keys.slice();
|
|
3649
|
+
const fields = [];
|
|
3650
|
+
const dates = [];
|
|
3651
|
+
for (const col of cols) {
|
|
3347
3652
|
const field = reverseMap[col] ?? col; // fall back to raw col name, not regex
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3653
|
+
fields.push(field);
|
|
3654
|
+
// Top-level rows are snake_case (dateCols); nested rows are camelCase.
|
|
3655
|
+
dates.push(dateCols.has(col) || camelDateFields.has(field));
|
|
3656
|
+
}
|
|
3657
|
+
plan = { cols, fields, dates };
|
|
3658
|
+
this.rowPlanCache.set(shapeKey, plan);
|
|
3659
|
+
}
|
|
3660
|
+
this.rowPlanLast.set(table, plan);
|
|
3661
|
+
return plan;
|
|
3662
|
+
}
|
|
3663
|
+
/**
|
|
3664
|
+
* Whether a cached plan describes exactly this row's column list, in order.
|
|
3665
|
+
* A pointer compare per column: both sides are the driver's own interned
|
|
3666
|
+
* column-name strings, so this is far cheaper than the reverse-map lookup and
|
|
3667
|
+
* two Set probes per column that it replaces, and unlike a length check or a
|
|
3668
|
+
* fingerprint it CANNOT accept a different projection that happens to look
|
|
3669
|
+
* similar. That matters more than the speed: a positional plan applied to the
|
|
3670
|
+
* wrong column list would silently write each value under a neighbouring
|
|
3671
|
+
* field's name, which is the one failure mode worth paying a full comparison
|
|
3672
|
+
* to make impossible.
|
|
3673
|
+
*/
|
|
3674
|
+
static rowPlanMatches(plan, keys) {
|
|
3675
|
+
const cols = plan.cols;
|
|
3676
|
+
if (cols.length !== keys.length)
|
|
3677
|
+
return false;
|
|
3678
|
+
for (let i = 0; i < keys.length; i++) {
|
|
3679
|
+
if (cols[i] !== keys[i])
|
|
3680
|
+
return false;
|
|
3681
|
+
}
|
|
3682
|
+
return true;
|
|
3683
|
+
}
|
|
3684
|
+
parseRow(row, table) {
|
|
3685
|
+
const parsed = {};
|
|
3686
|
+
const meta = this.schema.tables[table];
|
|
3687
|
+
if (meta) {
|
|
3688
|
+
// Every row of one result set has the same columns in the same order (a
|
|
3689
|
+
// SQL result set has fixed field descriptors, and a nested row decoded
|
|
3690
|
+
// from `json_build_object` has a fixed key list), so the per-column
|
|
3691
|
+
// name resolution and date-column membership tests are the same answer
|
|
3692
|
+
// recomputed for every row. Resolve them ONCE per column shape and keep
|
|
3693
|
+
// the plan; the shape is verified against each row rather than assumed,
|
|
3694
|
+
// so a caller that does hand this function heterogeneous rows gets a
|
|
3695
|
+
// rebuilt plan instead of a mis-mapped one.
|
|
3696
|
+
const keys = Object.keys(row);
|
|
3697
|
+
const last = this.rowPlanLast.get(table);
|
|
3698
|
+
const plan = last !== undefined && QueryInterface.rowPlanMatches(last, keys)
|
|
3699
|
+
? last
|
|
3700
|
+
: this.buildRowDecodePlan(table, meta, keys);
|
|
3701
|
+
const { cols, fields, dates } = plan;
|
|
3702
|
+
for (let i = 0; i < cols.length; i++) {
|
|
3703
|
+
const field = fields[i];
|
|
3704
|
+
const value = row[cols[i]];
|
|
3705
|
+
parsed[field] = dates[i] ? this.decodeTemporalCell(value, table, field) : value;
|
|
3395
3706
|
}
|
|
3396
3707
|
}
|
|
3397
3708
|
else {
|