turbine-orm 0.91.0 → 0.92.0-next.4df06d4

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 (54) hide show
  1. package/README.md +23 -24
  2. package/dist/cjs/cli/config.d.ts +5 -0
  3. package/dist/cjs/cli/config.js +1 -0
  4. package/dist/cjs/cli/index.d.ts +17 -17
  5. package/dist/cjs/cli/index.js +34 -27
  6. package/dist/cjs/cli/observe-ui.d.ts +1 -1
  7. package/dist/cjs/cli/observe-ui.js +1 -1
  8. package/dist/cjs/cli/studio-ui.generated.js +1 -1
  9. package/dist/cjs/client.js +33 -15
  10. package/dist/cjs/index.d.ts +1 -0
  11. package/dist/cjs/index.js +4 -1
  12. package/dist/cjs/pipeline.js +12 -7
  13. package/dist/cjs/powdb.d.ts +10 -6
  14. package/dist/cjs/powdb.js +4 -2
  15. package/dist/cjs/powql.js +11 -3
  16. package/dist/cjs/query/builder.d.ts +8 -0
  17. package/dist/cjs/query/builder.js +51 -33
  18. package/dist/cjs/query/relations.d.ts +21 -3
  19. package/dist/cjs/query/relations.js +331 -68
  20. package/dist/cjs/query/utils.d.ts +13 -0
  21. package/dist/cjs/query/utils.js +44 -1
  22. package/dist/cjs/query/where.d.ts +15 -0
  23. package/dist/cjs/query-channel.d.ts +86 -0
  24. package/dist/cjs/query-channel.js +150 -0
  25. package/dist/cjs/query-events.js +5 -1
  26. package/dist/cjs/schema-builder.d.ts +8 -5
  27. package/dist/cjs/transaction-state.js +15 -11
  28. package/dist/cli/config.d.ts +5 -0
  29. package/dist/cli/config.js +1 -0
  30. package/dist/cli/index.d.ts +17 -17
  31. package/dist/cli/index.js +35 -28
  32. package/dist/cli/observe-ui.d.ts +1 -1
  33. package/dist/cli/observe-ui.js +1 -1
  34. package/dist/cli/studio-ui.generated.js +1 -1
  35. package/dist/client.js +33 -15
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.js +2 -0
  38. package/dist/pipeline.js +12 -7
  39. package/dist/powdb.d.ts +10 -6
  40. package/dist/powdb.js +4 -2
  41. package/dist/powql.js +11 -3
  42. package/dist/query/builder.d.ts +8 -0
  43. package/dist/query/builder.js +38 -20
  44. package/dist/query/relations.d.ts +21 -3
  45. package/dist/query/relations.js +330 -69
  46. package/dist/query/utils.d.ts +13 -0
  47. package/dist/query/utils.js +43 -0
  48. package/dist/query/where.d.ts +15 -0
  49. package/dist/query-channel.d.ts +86 -0
  50. package/dist/query-channel.js +143 -0
  51. package/dist/query-events.js +5 -1
  52. package/dist/schema-builder.d.ts +8 -5
  53. package/dist/transaction-state.js +15 -11
  54. package/package.json +2 -1
package/dist/client.js CHANGED
@@ -41,6 +41,7 @@ import { resolveStreamIdleTimeout } from './query/stream-idle.js';
41
41
  import { asQueryInterface, TABLE_METHODS } from './query/table-client.js';
42
42
  import { ownLookup, quoteIdent, registerUtcTemporalParsers, sendCancelRequest, suggestKey, warnParserOverwrite, } from './query/utils.js';
43
43
  import { shouldWarnOnce, WARN_NS } from './query/warn-registry.js';
44
+ import { queryChannelActive, settleQueryTrace, startQueryTrace, TRANSACTION_CONTROL_OPERATION, traceStatement, } from './query-channel.js';
44
45
  import { currentQueryTag, deferredIdentity, emitStatementEvent, rawIdentity, resultRowCount, runReportedStatement, runWithQueryTag, } from './query-events.js';
45
46
  import { createSubscription, validateChannel, } from './realtime.js';
46
47
  import { parseInt8, rawClientOf, typedQueryPool } from './supplied-pool-types.js';
@@ -360,12 +361,14 @@ const ISOLATION_LEVELS = Object.assign(Object.create(null), {
360
361
  * that are the main reason to run SERIALIZABLE at all.
361
362
  */
362
363
  async function runTxControl(client, sql, params) {
363
- try {
364
- await client.query(sql, params);
365
- }
366
- catch (err) {
367
- throw wrapPgError(err);
368
- }
364
+ await traceStatement(TRANSACTION_CONTROL_OPERATION, sql, params?.length ?? 0, async () => {
365
+ try {
366
+ await client.query(sql, params);
367
+ }
368
+ catch (err) {
369
+ throw wrapPgError(err);
370
+ }
371
+ });
369
372
  }
370
373
  /**
371
374
  * Refuse anything in a batch that is not a deferred query, before any of it
@@ -536,6 +539,9 @@ const SESSION_SETTING_REFUSALS = Object.assign(Object.create(null), {
536
539
  * own message (which may contain the value) stays on `cause`.
537
540
  */
538
541
  async function applySessionSetting(client, setting) {
542
+ await traceStatement(TRANSACTION_CONTROL_OPERATION, setting.sql, setting.params.length, () => sendSessionSetting(client, setting));
543
+ }
544
+ async function sendSessionSetting(client, setting) {
539
545
  try {
540
546
  await client.query(setting.sql, setting.params);
541
547
  }
@@ -620,7 +626,8 @@ async function rollbackOnServer(client, state, dialect) {
620
626
  return false;
621
627
  }
622
628
  let failed = false;
623
- const rollback = client.query(dialect.rollbackStatement()).catch(() => {
629
+ const sql = dialect.rollbackStatement();
630
+ const rollback = traceStatement(TRANSACTION_CONTROL_OPERATION, sql, 0, () => client.query(sql)).catch(() => {
624
631
  failed = true;
625
632
  });
626
633
  return (await settlesWithin(rollback, TX_ABORT_GRACE_MS)) && !failed;
@@ -2241,7 +2248,7 @@ export class TurbineClient {
2241
2248
  const comments = this.statementComments(queries);
2242
2249
  const sent = comments ? queries.map((q, i) => commentDeferred(q, comments[i])) : queries;
2243
2250
  const sink = this.queryListeners.size > 0 ? this.queryOptions._onQuery : undefined;
2244
- if (!sink)
2251
+ if (!sink && !queryChannelActive())
2245
2252
  return this.withErrorMode(() => executePipeline(this.queryPool, sent, options));
2246
2253
  return this.withErrorMode(() => this.reportedPipeline(sink, queries, options, sent, comments));
2247
2254
  }
@@ -2276,6 +2283,10 @@ export class TurbineClient {
2276
2283
  return q.transform(raw);
2277
2284
  },
2278
2285
  }));
2286
+ const traces = queries.map((q) => {
2287
+ const { model, action } = deferredIdentity(q.tag);
2288
+ return startQueryTrace(model, action, q.sql, q.params.length, 'pipeline');
2289
+ });
2279
2290
  const start = performance.now();
2280
2291
  let failure;
2281
2292
  try {
@@ -2296,6 +2307,10 @@ export class TurbineClient {
2296
2307
  : rowCounts.indexOf(undefined);
2297
2308
  queries.forEach((q, i) => {
2298
2309
  const failed = i === failedIndex;
2310
+ const error = failure === undefined ? undefined : failure instanceof Error ? failure : new Error(String(failure));
2311
+ // A traced slot is always settled, so every channel start has its end: one that never ran
2312
+ // (or rolled back unseen) settles with the batch's error.
2313
+ settleQueryTrace(traces[i], rowCounts[i] ?? 0, duration, failed || rowCounts[i] === undefined ? error : undefined);
2299
2314
  // A slot that never ran (or rolled back unseen) is not reported.
2300
2315
  if (failed || rowCounts[i] !== undefined) {
2301
2316
  emitStatementEvent(sink, {
@@ -2306,7 +2321,7 @@ export class TurbineClient {
2306
2321
  rows: rowCounts[i] ?? 0,
2307
2322
  batch: 'pipeline',
2308
2323
  ...(comments?.[i] === undefined ? {} : { comment: comments[i] }),
2309
- ...(failed ? { error: failure instanceof Error ? failure : new Error(String(failure)) } : {}),
2324
+ ...(failed ? { error } : {}),
2310
2325
  });
2311
2326
  }
2312
2327
  });
@@ -2871,12 +2886,15 @@ export class TurbineClient {
2871
2886
  if (this.logging) {
2872
2887
  logTo(this.logger, 'debug', `NOTIFY ${channel}`, { code: 'notify', channel });
2873
2888
  }
2874
- try {
2875
- await this.pool.query('SELECT pg_notify($1, $2)', [channel, payload ?? '']);
2876
- }
2877
- catch (err) {
2878
- throw wrapPgError(err);
2879
- }
2889
+ const sql = 'SELECT pg_notify($1, $2)';
2890
+ await traceStatement('$notify', sql, 2, async () => {
2891
+ try {
2892
+ return await this.pool.query(sql, [channel, payload ?? '']);
2893
+ }
2894
+ catch (err) {
2895
+ throw wrapPgError(err);
2896
+ }
2897
+ });
2880
2898
  }
2881
2899
  // -------------------------------------------------------------------------
2882
2900
  // Retry, automatic retry for retryable errors (deadlock, serialization)
package/dist/index.d.ts CHANGED
@@ -50,6 +50,7 @@ export { type CaseArm, type ExprOperand, expr, type NumericOperand } from './que
50
50
  export { type AggregateArgs, type AggregateResult, type ArrayFilter, AUTO_ASSUMED_ROUND_TRIP_MS, AUTO_COUNT_BATCH_MIN_PARENT_ROWS, AUTO_JOIN_PENALTY_MS_PER_ROW, AUTO_TO_ONE_JOIN_MAX_ROWS, AUTO_TO_ONE_JOIN_ROWS_MAX, AUTO_TO_ONE_JOIN_ROWS_MIN, type ColumnRef, type ConnectOrCreateOp, type CountArgs, type CreateArgs, type CreateDataInput, type CreateManyArgs, type CreateManyCount, type CreateManyResult, col, type DeferredQuery, type DeleteArgs, type DeleteManyArgs, type FieldResult, type FindManyArgs, type FindManyStreamArgs, type FindUniqueArgs, type GlobalFilters, type GroupByAggregateSpec, type GroupByArgs, type GroupByDistinctOn, type GroupByResult, type HavingClause, type JsonEncoding, type JsonFilter, type JsonPathAggregateTarget, type JsonPathGroupKey, type JsonPathOrderBy, type JsonValue, jsonValue, type MiddlewareFn, type NestedCreateOp, type NestedUpdateOp, type NestedUpdateOpItem, type NestedUpsertOpItem, type OmitResult, type OrderByClause, type OrderByObject, type OrderBySpec, type OrderDirection, type PrivilegeOption, type QueryEvent, type QueryEventListener, QueryInterface, type QueryResult, type RelationDescriptor, type RelationFilter, type RelationLoadStrategy, type RelationOrderBy, type RelationOrderByChain, type RelationPickBy, type RelationPickOrderBy, type SelectResult, type SkipGlobalFilters, type TemporalInfinityReading, type TextSearchFilter, type TypedWithClause, UNSAFE, type Unsafe, type UpdateArgs, type UpdateDataInput, type UpdateInput, type UpdateManyArgs, type UpdateOperatorInput, type UpsertArgs, type VectorDistanceFilter, type VectorFilter, type VectorMetric, type VectorOrderBy, type VectorOrderByDistance, type WhereClause, type WhereOperator, type WhereValue, type WithClause, type WithOptions, type WithOrderByObject, type WithResult, } from './query/index.js';
51
51
  export type { SqlCommentOptions } from './query/sql-comment.js';
52
52
  export type { AggregateResultOf, ConflictTarget, ConflictUpdateData, CreateManyOnConflict, DefaultInputTypes, ExcludedRef, FieldPercentiles, GlobalFilter, NestedToOneCreateOp, NestedToOneUpdateOp, OptionalInput, PercentileArgs, PercentileExprSpec, PercentileKeysChecked, PercentileMethod, PercentileSpec, RelationKind, RowLock, RowLockMode, SqlExpr, SqlExprKind, TableInputTypes, } from './query/types.js';
53
+ export { QUERY_CHANNEL, type QueryChannelContext } from './query-channel.js';
53
54
  export { MAX_QUERY_TAG_LENGTH, RAW_QUERY_MODEL } from './query-events.js';
54
55
  export { type ActiveSubscription, type ListenOptions, type ListenReconnectOptions, type NotificationHandler, type Subscription, validateChannel, } from './realtime.js';
55
56
  export type { CheckMetadata, ColumnMetadata, IndexMetadata, PrismaCompatMap, PrismaModelMap, PrismaRelationMap, PrismaSchemaSource, ReferentialAction, RelationDef, SchemaMetadata, TableMetadata, } from './schema.js';
package/dist/index.js CHANGED
@@ -57,6 +57,8 @@ export { expr } from './query/expr.js';
57
57
  // `allowFullTableScan` are unlocked by THIS VALUE and nothing else, so a
58
58
  // request body spread into query args cannot enable them (JSON has no symbols).
59
59
  export { AUTO_ASSUMED_ROUND_TRIP_MS, AUTO_COUNT_BATCH_MIN_PARENT_ROWS, AUTO_JOIN_PENALTY_MS_PER_ROW, AUTO_TO_ONE_JOIN_MAX_ROWS, AUTO_TO_ONE_JOIN_ROWS_MAX, AUTO_TO_ONE_JOIN_ROWS_MIN, col, jsonValue, QueryInterface, UNSAFE, } from './query/index.js';
60
+ // diagnostics_channel tracing channel every statement is published on
61
+ export { QUERY_CHANNEL } from './query-channel.js';
60
62
  // $on('query') event metadata: raw-statement model name, $tag() label limit
61
63
  export { MAX_QUERY_TAG_LENGTH, RAW_QUERY_MODEL } from './query-events.js';
62
64
  // Realtime, LISTEN/NOTIFY pub/sub
package/dist/pipeline.js CHANGED
@@ -23,6 +23,7 @@ import { guardCheckout } from './connection-guard.js';
23
23
  import { postgresDialect } from './dialect.js';
24
24
  import { explainConnectionLoss, PipelineError, TurbineError, wrapPgError } from './errors.js';
25
25
  import { pipelineClientNeedsDiscard, runPipelined, supportsExtendedPipeline, } from './pipeline-submittable.js';
26
+ import { TRANSACTION_CONTROL_OPERATION, traceStatement } from './query-channel.js';
26
27
  import { commitTransaction } from './transaction-state.js';
27
28
  /**
28
29
  * Run one deferred query on the batch's connection. An engine without
@@ -52,12 +53,15 @@ async function runSequential(client, queries, dialect, options = {}) {
52
53
  // TurbineError, and a caller branching on `err.code` saw neither
53
54
  // `TURBINE_E004` nor a retryable flag for the one failure that is most
54
55
  // worth retrying.
55
- try {
56
- await client.query(dialect.beginStatement());
57
- }
58
- catch (err) {
59
- throw wrapPgError(err);
60
- }
56
+ const begin = dialect.beginStatement();
57
+ await traceStatement(TRANSACTION_CONTROL_OPERATION, begin, 0, async () => {
58
+ try {
59
+ await client.query(begin);
60
+ }
61
+ catch (err) {
62
+ throw wrapPgError(err);
63
+ }
64
+ });
61
65
  const results = [];
62
66
  for (const q of queries) {
63
67
  let raw;
@@ -76,7 +80,8 @@ async function runSequential(client, queries, dialect, options = {}) {
76
80
  }
77
81
  catch (err) {
78
82
  try {
79
- await client.query(dialect.rollbackStatement());
83
+ const rollback = dialect.rollbackStatement();
84
+ await traceStatement(TRANSACTION_CONTROL_OPERATION, rollback, 0, () => client.query(rollback));
80
85
  }
81
86
  catch {
82
87
  // Best-effort rollback
package/dist/powdb.d.ts CHANGED
@@ -21,7 +21,9 @@
21
21
  * writable types (`str`/`int`/`float`/`bool`); `Date` → `int` epoch micros;
22
22
  * `string` PKs hold UUID strings.
23
23
  * - **No JSON aggregation / link navigation**, single-query nested `with` is
24
- * impossible → it degrades to batched N+1 loaders (Phase B).
24
+ * not available → on PowDB 0.18+ an eligible `with` compiles to nested
25
+ * projections inside the parent statement; older engines and ineligible
26
+ * relations use batched loaders.
25
27
  * - **Single global write lock; no savepoints/isolation**, nested
26
28
  * transactions / isolation / vector / LISTEN-NOTIFY / RLS throw.
27
29
  * Independent concurrent `db.$transaction` calls do NOT throw: they queue
@@ -667,8 +669,10 @@ export { PowqlInterface } from './powql.js';
667
669
  */
668
670
  export interface TurbinePowdbOptions extends EngineClientConfig {
669
671
  /**
670
- * Client-level default `with`-relation load strategy. On PowDB the default is
671
- * the batched N+1 loaders; setting `'join'` opts INTO native PowQL server-side
672
+ * Client-level default `with`-relation load strategy. On PowDB 0.18+ the default
673
+ * compiles eligible relations to nested projections in one statement (older
674
+ * engines and ineligible relations use the batched loaders); `'batched'` forces
675
+ * the loaders, and setting `'join'` opts INTO native PowQL server-side
672
676
  * joins for eligible top-level relations (ineligible ones, e.g. a paged parent
673
677
  * or a nested `with`, fall back to the loaders per-relation and silently). A
674
678
  * per-query `relationLoadStrategy` arg still overrides this. Requires an engine
@@ -743,9 +747,9 @@ export interface TurbinePowdbOptions extends EngineClientConfig {
743
747
  /**
744
748
  * Selects the **embedded** transport, an in-process `@zvndev/powdb-embedded`
745
749
  * database at the given data directory (no server, no socket). The value is the
746
- * data dir path. Preview: Full-durability checkpoint-bound; built binaries ship
747
- * for macOS (arm64/x64) and Unix-glibc only (Intel-mac/musl/Windows fall back to
748
- * a from-source `npm run build`).
750
+ * data dir path. Preview: Full-durability checkpoint-bound; prebuilt binaries ship
751
+ * for macOS arm64 and Linux glibc x64/arm64 only (Intel macOS, musl and Windows
752
+ * fall back to a from-source `npm run build`).
749
753
  *
750
754
  * @example
751
755
  * ```ts
package/dist/powdb.js CHANGED
@@ -21,7 +21,9 @@
21
21
  * writable types (`str`/`int`/`float`/`bool`); `Date` → `int` epoch micros;
22
22
  * `string` PKs hold UUID strings.
23
23
  * - **No JSON aggregation / link navigation**, single-query nested `with` is
24
- * impossible → it degrades to batched N+1 loaders (Phase B).
24
+ * not available → on PowDB 0.18+ an eligible `with` compiles to nested
25
+ * projections inside the parent statement; older engines and ineligible
26
+ * relations use batched loaders.
25
27
  * - **Single global write lock; no savepoints/isolation**, nested
26
28
  * transactions / isolation / vector / LISTEN-NOTIFY / RLS throw.
27
29
  * Independent concurrent `db.$transaction` calls do NOT throw: they queue
@@ -1832,7 +1834,7 @@ async function loadPowdbEmbedded() {
1832
1834
  catch (err) {
1833
1835
  throw new ConnectionError("turbine-orm/powdb embedded mode requires the optional peer '@zvndev/powdb-embedded'. " +
1834
1836
  'Install it: npm i @zvndev/powdb-embedded. If install succeeded but loading failed, your platform has no ' +
1835
- 'prebuilt binary (prebuilts ship for macOS arm64/x64 and Linux glibc x64/arm64; Intel-mac/musl/Windows ' +
1837
+ 'prebuilt binary (prebuilts ship for macOS arm64 and Linux glibc x64/arm64; Intel macOS, musl and Windows ' +
1836
1838
  'build from source), build it with `npm run build` in the addon, then retry. You can also construct the ' +
1837
1839
  'pool yourself and inject it: turbinePowDB(pool, schema). ' +
1838
1840
  `(${err.message})`);
package/dist/powql.js CHANGED
@@ -62,6 +62,7 @@ import { shouldWarnOnce, WARN_NS } from './query/warn-registry.js';
62
62
  import { assertJsonFilterKeys, emptyMutationWhereMessage, jsonStringEntries, normalizeRelationFilter, resolveGlobalFilterFrom, } from './query/where.js';
63
63
  import { combinatorBranches, foldWhereFor, relationCardinalityProblem, relationFilterValueProblem, } from './query/where-compile.js';
64
64
  import { assertNoBulkWritePaging, assertNoOptimisticLock } from './query/writes.js';
65
+ import { settleQueryTrace, startQueryTrace } from './query-channel.js';
65
66
  import { normalizeKeyColumns, snakeToCamel, } from './schema.js';
66
67
  import { transactionClientFor } from './transaction-client-slot.js';
67
68
  /**
@@ -2205,6 +2206,7 @@ export class PowqlInterface {
2205
2206
  if (this.pool.readonly === true && POWQL_WRITE_ACTIONS.has(action)) {
2206
2207
  throw this.readOnlyError(action);
2207
2208
  }
2209
+ const trace = startQueryTrace(this.table, action, powql, params.length);
2208
2210
  const start = performance.now();
2209
2211
  const run = this.pool.query(powql, params);
2210
2212
  try {
@@ -2214,7 +2216,9 @@ export class PowqlInterface {
2214
2216
  new Promise((_, reject) => setTimeout(() => reject(new TimeoutError(timeout)), timeout)),
2215
2217
  ])
2216
2218
  : await run;
2217
- this.emit(action, powql, params, performance.now() - start, result.rowCount ?? result.rows.length);
2219
+ const duration = performance.now() - start;
2220
+ settleQueryTrace(trace, result.rowCount ?? result.rows.length, duration);
2221
+ this.emit(action, powql, params, duration, result.rowCount ?? result.rows.length);
2218
2222
  // The pool tags each result with the wire that actually served it
2219
2223
  // (adaptResult → false, adaptNativeResult → true). A heterogeneous
2220
2224
  // injected pool can fall back to the legacy wire per call, so read the
@@ -2225,12 +2229,16 @@ export class PowqlInterface {
2225
2229
  return { rows: result.rows, rowCount: result.rowCount ?? result.rows.length, native };
2226
2230
  }
2227
2231
  catch (err) {
2232
+ const duration = performance.now() - start;
2228
2233
  if (!isRetry && this.shouldRetryStaleRead(err, action)) {
2229
2234
  // Transparent single replay on a fresh connection; the first (swallowed)
2230
- // failure is not emitted, only the retried outcome is observed.
2235
+ // failure is not emitted, only the retried outcome is observed. Its
2236
+ // channel trace is still settled, marked retried.
2237
+ settleQueryTrace(trace, 0, duration, err instanceof Error ? err : new Error(String(err)), true);
2231
2238
  return this.execOnce(powql, params, timeout, action, true);
2232
2239
  }
2233
- this.emit(action, powql, params, performance.now() - start, 0, err);
2240
+ settleQueryTrace(trace, 0, duration, err instanceof Error ? err : new Error(String(err)));
2241
+ this.emit(action, powql, params, duration, 0, err);
2234
2242
  throw err;
2235
2243
  }
2236
2244
  }
@@ -1702,6 +1702,14 @@ export declare class QueryInterface<T extends object, R extends object = {}, M e
1702
1702
  * search down the wrong path.
1703
1703
  */
1704
1704
  private buildRowDecodePlan;
1705
+ /**
1706
+ * The cached decode plan for one exact column list, without touching the
1707
+ * per-table most-recent slot. {@link buildRowDecodePlan} is the per-row entry;
1708
+ * this is also what the positional nested-row plan in relations.ts reads
1709
+ * (through the ctx) when it is built, so a nested row decodes by exactly the
1710
+ * field names and cell kinds {@link parseRow} would give the same keys.
1711
+ */
1712
+ private rowDecodePlanFor;
1705
1713
  /**
1706
1714
  * Whether a cached plan describes exactly this row's column list, in order.
1707
1715
  * A pointer compare per column: both sides are the driver's own interned
@@ -18,6 +18,7 @@ import { explainConnectionLoss, INVARIANT_REPORT_HINT, InvariantError, isStaleCo
18
18
  import { missingIndexForRelation, schemaHasIndexInfo } from '../index-advisor.js';
19
19
  import { consoleLogger, logTo } from '../logger.js';
20
20
  import { executeNestedCreate, executeNestedUpdate, extractRelationFields, hasRelationFields, } from '../nested-write.js';
21
+ import { settleQueryTrace, startQueryTrace } from '../query-channel.js';
21
22
  import { normalizeKeyColumns, snakeToCamel } from '../schema.js';
22
23
  import { transactionClientFor } from '../transaction-client-slot.js';
23
24
  import { transactionStateOf, withSavepoint } from '../transaction-state.js';
@@ -34,7 +35,7 @@ import { lockOnStreamMessage, lockOutsideTransactionMessage, lockWithDistinctMes
34
35
  import { resolveSqlComment } from './sql-comment.js';
35
36
  import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, newStreamIdleState, resolveStreamIdleTimeout, StreamIdleGuard, streamBackstopStatement, streamIdleExpiredError, watchStreamConnection, } from './stream-idle.js';
36
37
  import { resolveSkipGlobalFilters, resolveUnsafeFlag, UNSAFE } from './types.js';
37
- import { assertMiddlewareArgsKept, availableClause, boundedPreparedName, canCancelBackend, isNodePostgresPool, isTemporalInfinity, LRUCache, normalizePagination, ownLookup, parseDbDate, readJsonFloat, readJsonFloatArray, readOnlyMiddlewareParams, readTextArray, resolveColumnName, resolveRelation, resolveRelationDef, sendCancelRequest, sqlToPreparedName, unknownFieldMessage, warnRedundantSortTerm, } from './utils.js';
38
+ import { assertMiddlewareArgsKept, availableClause, boundedPreparedName, CELL_DIALECT, CELL_FLOAT, CELL_FLOAT_ARRAY, CELL_PLAIN, CELL_TEMPORAL, CELL_TEXT_ARRAY, canCancelBackend, isNodePostgresPool, isTemporalInfinity, LRUCache, normalizePagination, ownLookup, parseDbDate, readJsonFloat, readJsonFloatArray, readOnlyMiddlewareParams, readTextArray, resolveColumnName, resolveRelation, resolveRelationDef, sendCancelRequest, sqlToPreparedName, unknownFieldMessage, warnRedundantSortTerm, } from './utils.js';
38
39
  import { resetWarnOnce, shouldWarnOnce, WARN_NS } from './warn-registry.js';
39
40
  import * as whereMod from './where.js';
40
41
  import * as writesMod from './writes.js';
@@ -239,14 +240,6 @@ const ROW_PLAN_CACHE_SIZE = 128;
239
240
  * probe's own limit.
240
241
  */
241
242
  const STREAM_SPECULATION_MAX_BATCH = 1000;
242
- /** Per-cell decode work in a {@link RowDecodePlan}. */
243
- const CELL_PLAIN = 0;
244
- const CELL_TEMPORAL = 1;
245
- const CELL_FLOAT = 2;
246
- const CELL_FLOAT_ARRAY = 3;
247
- const CELL_TEXT_ARRAY = 4;
248
- /** The dialect's own decode for a type whose storage differs (see `Dialect.decodeColumnValue`). */
249
- const CELL_DIALECT = 5;
250
243
  const FLOAT_TYPES = new Set(['float4', 'float8', 'real', 'double precision']);
251
244
  const FLOAT_ARRAY_TYPES = new Set(['_float4', '_float8', 'float4[]', 'float8[]', 'real[]', 'double precision[]']);
252
245
  /**
@@ -982,6 +975,11 @@ export class QueryInterface {
982
975
  toColumn: (field) => this.toColumn(field),
983
976
  castAgg: (expr, target) => this.castAgg(expr, target),
984
977
  parseRow: (row, table) => this.parseRow(row, table),
978
+ rowDecodePlan: (table, keys) => {
979
+ const meta = this.schema.tables[table];
980
+ return meta ? this.rowDecodePlanFor(table, meta, keys) : undefined;
981
+ },
982
+ decodeCell: (kind, value, table, field) => this.decodeCell(kind, value, table, field),
985
983
  nullsSuffix: (nulls) => this.nullsSuffix(nulls),
986
984
  isRelationOrderByValue: (value) => this.isRelationOrderByValue(value),
987
985
  resolveOrderByColumn: (table, meta, key) => this.resolveOrderByColumn(table, meta, key),
@@ -2438,7 +2436,8 @@ export class QueryInterface {
2438
2436
  resetUnlimitedWarnings() {
2439
2437
  resetWarnOnce(WARN_NS.unlimitedFindMany);
2440
2438
  }
2441
- emitQueryEvent(out, params, duration, action, rows, error, retried) {
2439
+ emitQueryEvent(out, params, duration, action, rows, error, retried, trace) {
2440
+ settleQueryTrace(trace, rows, duration, error, retried);
2442
2441
  const onQuery = this.options?._onQuery;
2443
2442
  if (!onQuery)
2444
2443
  return;
@@ -2590,6 +2589,7 @@ export class QueryInterface {
2590
2589
  return this.queryCancellableInTransaction(out, params, timeout, state, action);
2591
2590
  }
2592
2591
  }
2592
+ let trace = startQueryTrace(this.table, action, out.sql, params.length);
2593
2593
  let start = performance.now();
2594
2594
  // Build the query argument, use object form with `name` for prepared
2595
2595
  // statements, or the plain (text, values) form otherwise.
@@ -2618,10 +2618,11 @@ export class QueryInterface {
2618
2618
  // so a listener counting errors sees it and one alerting on failed
2619
2619
  // CALLS can skip it. The final event below times the retry alone.
2620
2620
  const wrapped = wrapPgError(err);
2621
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, true);
2621
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, true, trace);
2622
2622
  await settleEventLoop();
2623
2623
  if (abandoned)
2624
2624
  throw err;
2625
+ trace = startQueryTrace(this.table, action, out.sql, params.length);
2625
2626
  start = performance.now();
2626
2627
  return send();
2627
2628
  });
@@ -2629,12 +2630,12 @@ export class QueryInterface {
2629
2630
  if (!timeout) {
2630
2631
  try {
2631
2632
  const result = await exec;
2632
- this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0);
2633
+ this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0, undefined, undefined, trace);
2633
2634
  return result;
2634
2635
  }
2635
2636
  catch (err) {
2636
2637
  const wrapped = wrapPgError(err);
2637
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined);
2638
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, undefined, trace);
2638
2639
  throw wrapped;
2639
2640
  }
2640
2641
  }
@@ -2651,12 +2652,12 @@ export class QueryInterface {
2651
2652
  });
2652
2653
  try {
2653
2654
  const result = await Promise.race([exec, timeoutPromise]);
2654
- this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0);
2655
+ this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0, undefined, undefined, trace);
2655
2656
  return result;
2656
2657
  }
2657
2658
  catch (err) {
2658
2659
  const wrapped = wrapPgError(err);
2659
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined);
2660
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, undefined, trace);
2660
2661
  throw wrapped;
2661
2662
  }
2662
2663
  finally {
@@ -2690,12 +2691,13 @@ export class QueryInterface {
2690
2691
  * once its backend is idle, so timed-out statements cannot hold the pool.
2691
2692
  */
2692
2693
  async queryCancellable(out, params, timeout, retryIfStale, action) {
2694
+ let trace = startQueryTrace(this.table, action, out.sql, params.length);
2693
2695
  let start = performance.now();
2694
2696
  const config = out.name && this.preparedStatementsEnabled ? { name: out.name, text: out.text, values: params } : null;
2695
2697
  const report = (err, retried) => {
2696
2698
  const wrapped = err instanceof TimeoutError ? err : wrapPgError(err);
2697
2699
  const error = wrapped instanceof Error ? wrapped : undefined;
2698
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, retried);
2700
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, retried, trace);
2699
2701
  return wrapped;
2700
2702
  };
2701
2703
  let expired = false;
@@ -2734,7 +2736,8 @@ export class QueryInterface {
2734
2736
  if ('result' in settled) {
2735
2737
  if (first !== TIMED_OUT)
2736
2738
  checkout.release();
2737
- this.emitQueryEvent(out, params, performance.now() - start, action, settled.result.rowCount ?? 0);
2739
+ const rows = settled.result.rowCount ?? 0;
2740
+ this.emitQueryEvent(out, params, performance.now() - start, action, rows, undefined, undefined, trace);
2738
2741
  return settled.result;
2739
2742
  }
2740
2743
  if ('timeout' in settled)
@@ -2749,6 +2752,7 @@ export class QueryInterface {
2749
2752
  await settleEventLoop();
2750
2753
  if (expired)
2751
2754
  throw report(neverSent());
2755
+ trace = startQueryTrace(this.table, action, out.sql, params.length);
2752
2756
  start = performance.now();
2753
2757
  }
2754
2758
  }
@@ -2768,6 +2772,7 @@ export class QueryInterface {
2768
2772
  * A statement that finishes before the deadline is returned as usual.
2769
2773
  */
2770
2774
  async queryCancellableInTransaction(out, params, timeout, state, action) {
2775
+ const trace = startQueryTrace(this.table, action, out.sql, params.length);
2771
2776
  const start = performance.now();
2772
2777
  const running = (out.name && this.preparedStatementsEnabled
2773
2778
  ? this.pool.query({
@@ -2789,11 +2794,13 @@ export class QueryInterface {
2789
2794
  clearTimeout(timer);
2790
2795
  }
2791
2796
  if ('result' in settled) {
2792
- this.emitQueryEvent(out, params, performance.now() - start, action, settled.result.rowCount ?? 0);
2797
+ const rows = settled.result.rowCount ?? 0;
2798
+ this.emitQueryEvent(out, params, performance.now() - start, action, rows, undefined, undefined, trace);
2793
2799
  return settled.result;
2794
2800
  }
2795
2801
  const err = 'timeout' in settled ? settled.timeout : wrapPgError(settled.error);
2796
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, err instanceof Error ? err : undefined);
2802
+ const error = err instanceof Error ? err : undefined;
2803
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, undefined, trace);
2797
2804
  throw err;
2798
2805
  }
2799
2806
  /** Cancel a timed-out statement in a transaction and end the transaction. See {@link queryCancellableInTransaction}. */
@@ -5290,6 +5297,18 @@ export class QueryInterface {
5290
5297
  * search down the wrong path.
5291
5298
  */
5292
5299
  buildRowDecodePlan(table, meta, keys) {
5300
+ const plan = this.rowDecodePlanFor(table, meta, keys);
5301
+ this.rowPlanLast.set(table, plan);
5302
+ return plan;
5303
+ }
5304
+ /**
5305
+ * The cached decode plan for one exact column list, without touching the
5306
+ * per-table most-recent slot. {@link buildRowDecodePlan} is the per-row entry;
5307
+ * this is also what the positional nested-row plan in relations.ts reads
5308
+ * (through the ctx) when it is built, so a nested row decodes by exactly the
5309
+ * field names and cell kinds {@link parseRow} would give the same keys.
5310
+ */
5311
+ rowDecodePlanFor(table, meta, keys) {
5293
5312
  const shapeKey = `${table}\u0000${keys.join('\u0000')}`;
5294
5313
  let plan = this.rowPlanCache.get(shapeKey);
5295
5314
  if (plan === undefined) {
@@ -5313,7 +5332,6 @@ export class QueryInterface {
5313
5332
  plan = { cols, fields, kinds };
5314
5333
  this.rowPlanCache.set(shapeKey, plan);
5315
5334
  }
5316
- this.rowPlanLast.set(table, plan);
5317
5335
  return plan;
5318
5336
  }
5319
5337
  /**
@@ -353,11 +353,22 @@ export declare function buildRelationShapes(qi: BuilderCtx, table: string, withC
353
353
  export declare function buildRelationShape(qi: BuilderCtx, relDef: RelationDef, spec: true | WithOptions, parentMeta: TableMetadata, includePii?: boolean): RelationShape;
354
354
  /**
355
355
  * Build the row parser for a `with` clause. In object mode this is just
356
- * {@link parseNestedRow}. In positional mode it decodes each relation's
357
- * positional arrays into the object form first (shapes built once, not per
358
- * row), then delegates to parseNestedRow for date/snake-camel coercion.
356
+ * {@link parseNestedRow}. In positional mode the relation shapes are built
357
+ * once (not per row) and compiled into a decode plan
358
+ * ({@link makePositionalRowParser}) that turns each positional array straight
359
+ * into its parsed row. A query whose shapes the plan declines takes the
360
+ * reference path instead, which decodes each positional array into the object
361
+ * form and hands it to parseNestedRow.
359
362
  */
360
363
  export declare function makeNestedParser(qi: BuilderCtx, withClause: WithClause, includePii?: boolean, flattenPlan?: FlattenPlan | null): (row: Record<string, unknown>) => Record<string, unknown>;
364
+ /**
365
+ * The positional parser the plan in {@link makePositionalRowParser} is held to:
366
+ * decode each relation's arrays into the object representation, then parse
367
+ * that exactly as an object-encoded row is parsed. It is the path for every
368
+ * query the plan declines, and is exported so the differential tests can
369
+ * compare the two.
370
+ */
371
+ export declare function makeReferencePositionalParser(qi: BuilderCtx, shapes: Record<string, RelationShape>): (row: Record<string, unknown>) => Record<string, unknown>;
361
372
  /**
362
373
  * Return a shallow copy of a top-level row with each relation column decoded
363
374
  * from its positional array(s) into the object representation. Only relation
@@ -374,6 +385,13 @@ export declare function decodePositionalRelations(qi: BuilderCtx, row: Record<st
374
385
  export declare function decodePositionalValue(qi: BuilderCtx, raw: unknown, shape: RelationShape): unknown;
375
386
  /** Map one positional array back to a keyed object using the shape's key order. */
376
387
  export declare function decodePositionalObject(qi: BuilderCtx, arr: unknown, shape: RelationShape): unknown;
388
+ /**
389
+ * Compile a top-level positional parser for `shapes`, or `undefined` when any
390
+ * part of it is a shape the plan does not take (the caller then uses
391
+ * {@link makeReferencePositionalParser}). Rows are identical to the
392
+ * reference's on every shape it does take.
393
+ */
394
+ export declare function makePositionalRowParser(qi: BuilderCtx, table: string, shapes: Record<string, RelationShape>): ((row: Record<string, unknown>) => Record<string, unknown>) | undefined;
377
395
  /** One relation `'flatten'` declined, with the reason, for the dev warning. */
378
396
  export interface FlattenReject {
379
397
  /** Dotted path from the root table's `with`, e.g. `order.customer`. */