turbine-orm 0.92.0 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ /**
3
+ * turbine-orm, the `turbine:query` tracing channel.
4
+ *
5
+ * Every statement that emits a `$on('query')` event, and the transaction
6
+ * control and `$notify` statements Turbine sends on its own (which emit none),
7
+ * is published on the Node `diagnostics_channel` tracing channel named
8
+ * {@link QUERY_CHANNEL}, so a tracer or APM agent can turn Turbine queries
9
+ * into spans without any setup in the application: it subscribes to the
10
+ * channel, and the application never passes it a client.
11
+ *
12
+ * The events follow the TracingChannel lifecycle for an async call: `start`
13
+ * and `end` when the statement is handed to the driver, then `error` (on
14
+ * failure), `asyncStart` and `asyncEnd` when it settles. All five carry the
15
+ * same context object, so a subscriber can key its own state on it. `start`
16
+ * runs in the caller's async context, so the active span there is the
17
+ * statement's parent.
18
+ *
19
+ * The context never carries a bound parameter value: `sql` is the
20
+ * parametrized text Turbine built (`$1`, `$2`, ...), without the `sqlComment`,
21
+ * and `paramCount` is how many values were bound. Result rows are not
22
+ * attached either. That is why the events are published directly rather than
23
+ * through `tracePromise`, which would put the driver result on the context.
24
+ * A consequence: stores bound with `bindStore` are not entered, so read the
25
+ * caller's async context in the `start` subscriber instead.
26
+ *
27
+ * Cost without a subscriber: one `hasSubscribers` read per statement, and no
28
+ * object is built. The channel is looked up once, through
29
+ * `process.getBuiltinModule`, so no Node builtin is imported statically and
30
+ * the edge entry stays builtin-free. Where that function is missing (Node
31
+ * before 20.16 or 22.3, edge runtimes) nothing is published.
32
+ */
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.TRANSACTION_CONTROL_OPERATION = exports.QUERY_CHANNEL = void 0;
35
+ exports.queryChannelActive = queryChannelActive;
36
+ exports.startQueryTrace = startQueryTrace;
37
+ exports.settleQueryTrace = settleQueryTrace;
38
+ exports.traceStatement = traceStatement;
39
+ /** The tracing channel name. Subscribe with `diagnostics_channel.tracingChannel('turbine:query')`. */
40
+ exports.QUERY_CHANNEL = 'turbine:query';
41
+ /**
42
+ * The `operation` of a transaction-control statement Turbine sends on its own:
43
+ * `BEGIN`, `COMMIT`, `ROLLBACK`, savepoints and `sessionContext` settings. Its
44
+ * `model` is `'$raw'`, the `RAW_QUERY_MODEL` of query-events.ts (not imported:
45
+ * query-events.ts imports this module).
46
+ */
47
+ exports.TRANSACTION_CONTROL_OPERATION = '$transaction';
48
+ let channel;
49
+ function queryChannel() {
50
+ if (channel !== undefined)
51
+ return channel;
52
+ channel = null;
53
+ try {
54
+ const proc = globalThis.process;
55
+ const dc = proc?.getBuiltinModule?.('node:diagnostics_channel');
56
+ channel = dc?.tracingChannel?.(exports.QUERY_CHANNEL) ?? null;
57
+ }
58
+ catch {
59
+ channel = null;
60
+ }
61
+ return channel;
62
+ }
63
+ function subscribed(c) {
64
+ // TracingChannel#hasSubscribers is Node 22+ and 20.13+; older ones check each channel.
65
+ if (typeof c.hasSubscribers === 'boolean')
66
+ return c.hasSubscribers;
67
+ return (c.start.hasSubscribers ||
68
+ c.end.hasSubscribers ||
69
+ c.asyncStart.hasSubscribers ||
70
+ c.asyncEnd.hasSubscribers ||
71
+ c.error.hasSubscribers);
72
+ }
73
+ /** True when something subscribes to `turbine:query`. */
74
+ function queryChannelActive() {
75
+ const c = queryChannel();
76
+ return c !== null && subscribed(c);
77
+ }
78
+ /**
79
+ * Publish `start` and `end` for a statement about to be sent, and return the
80
+ * context to settle with {@link settleQueryTrace}. Undefined, and nothing
81
+ * built, when nobody subscribes. Never throws.
82
+ */
83
+ function startQueryTrace(model, operation, sql, paramCount, batch) {
84
+ const c = queryChannel();
85
+ if (c === null || !subscribed(c))
86
+ return undefined;
87
+ const context = { model, operation, sql, paramCount };
88
+ if (batch !== undefined)
89
+ context.batch = batch;
90
+ try {
91
+ c.start.publish(context);
92
+ c.end.publish(context);
93
+ }
94
+ catch {
95
+ // A subscriber problem must not fail the statement.
96
+ }
97
+ return context;
98
+ }
99
+ /**
100
+ * Publish `error` (on failure), `asyncStart` and `asyncEnd` for a statement
101
+ * started with {@link startQueryTrace}. A no-op for an undefined context.
102
+ * Never throws.
103
+ */
104
+ function settleQueryTrace(context, rowCount, durationMs, error, retried) {
105
+ if (context === undefined)
106
+ return;
107
+ const c = queryChannel();
108
+ if (c === null)
109
+ return;
110
+ context.rowCount = rowCount;
111
+ context.durationMs = durationMs;
112
+ if (retried)
113
+ context.retried = true;
114
+ try {
115
+ if (error !== undefined) {
116
+ context.error = error;
117
+ c.error.publish(context);
118
+ }
119
+ c.asyncStart.publish(context);
120
+ c.asyncEnd.publish(context);
121
+ }
122
+ catch {
123
+ // A subscriber problem must not fail the statement.
124
+ }
125
+ }
126
+ /**
127
+ * Run a statement Turbine sends on its own (transaction control, `$notify`)
128
+ * with a `turbine:query` trace around it. `run` should throw the error the
129
+ * caller receives, so the trace carries that one. Without a subscriber it is
130
+ * `run()` and nothing else.
131
+ */
132
+ function traceStatement(operation, sql, paramCount, run) {
133
+ const trace = startQueryTrace('$raw', operation, sql, paramCount);
134
+ if (trace === undefined)
135
+ return run();
136
+ return settleAround(trace, run);
137
+ }
138
+ async function settleAround(trace, run) {
139
+ const start = performance.now();
140
+ try {
141
+ const result = await run();
142
+ const rows = result?.rowCount;
143
+ settleQueryTrace(trace, typeof rows === 'number' ? rows : 0, performance.now() - start);
144
+ return result;
145
+ }
146
+ catch (err) {
147
+ settleQueryTrace(trace, 0, performance.now() - start, err instanceof Error ? err : new Error(String(err)));
148
+ throw err;
149
+ }
150
+ }
@@ -39,6 +39,7 @@ exports.deferredIdentity = deferredIdentity;
39
39
  exports.runReportedStatement = runReportedStatement;
40
40
  const node_async_hooks_1 = require("node:async_hooks");
41
41
  const errors_js_1 = require("./errors.js");
42
+ const query_channel_js_1 = require("./query-channel.js");
42
43
  /**
43
44
  * The `model` reported for statements that are not tied to one table: `raw`,
44
45
  * `sql`, the transaction-scoped `raw` / `rawQuery`, and prisma-compat's
@@ -114,15 +115,18 @@ function deferredIdentity(tag) {
114
115
  * success. `minified-events.test.ts` runs this module through that minifier.
115
116
  */
116
117
  async function runReportedStatement(sink, identity, sql, params, run, wrap) {
118
+ const trace = (0, query_channel_js_1.startQueryTrace)(identity.model, identity.action, sql, params.length, identity.batch);
117
119
  const start = performance.now();
118
120
  const report = (rows, error) => {
121
+ const duration = performance.now() - start;
122
+ (0, query_channel_js_1.settleQueryTrace)(trace, rows, duration, error);
119
123
  if (!sink)
120
124
  return;
121
125
  emitStatementEvent(sink, {
122
126
  ...identity,
123
127
  sql,
124
128
  params,
125
- duration: performance.now() - start,
129
+ duration,
126
130
  rows,
127
131
  ...(error === undefined ? {} : { error }),
128
132
  });
@@ -48,6 +48,7 @@ exports.closedTransactionError = closedTransactionError;
48
48
  exports.unawaitedWorkError = unawaitedWorkError;
49
49
  const node_async_hooks_1 = require("node:async_hooks");
50
50
  const errors_js_1 = require("./errors.js");
51
+ const query_channel_js_1 = require("./query-channel.js");
51
52
  const transaction_control_js_1 = require("./transaction-control.js");
52
53
  /** The key a transaction-scoped pool carries its {@link TransactionState} under. */
53
54
  exports.TRANSACTION_STATE = Symbol.for('turbine-orm.transactionState');
@@ -502,14 +503,14 @@ class TransactionState {
502
503
  */
503
504
  async control(sql) {
504
505
  this.assertOpen();
505
- await this.send(async () => {
506
+ await this.send(() => (0, query_channel_js_1.traceStatement)(query_channel_js_1.TRANSACTION_CONTROL_OPERATION, sql, 0, async () => {
506
507
  try {
507
508
  await this.client.query(sql);
508
509
  }
509
510
  catch (err) {
510
511
  throw (0, errors_js_1.wrapPgError)(err);
511
512
  }
512
- });
513
+ }));
513
514
  }
514
515
  }
515
516
  exports.TransactionState = TransactionState;
@@ -547,15 +548,18 @@ function withSavepoint(pool, operation) {
547
548
  * result, so the check is inert for them.
548
549
  */
549
550
  async function commitTransaction(client, commitSql, firstFailure, api = '$transaction') {
550
- let result;
551
- try {
552
- result = await client.query(commitSql);
553
- }
554
- catch (err) {
555
- throw (0, errors_js_1.wrapPgError)(err);
556
- }
557
- if (commitWasRolledBack(result))
558
- throw rolledBackError(firstFailure, 'transaction', api);
551
+ // The rolled-back check is inside the trace: a COMMIT answered with ROLLBACK is a failed COMMIT.
552
+ await (0, query_channel_js_1.traceStatement)(query_channel_js_1.TRANSACTION_CONTROL_OPERATION, commitSql, 0, async () => {
553
+ let result;
554
+ try {
555
+ result = await client.query(commitSql);
556
+ }
557
+ catch (err) {
558
+ throw (0, errors_js_1.wrapPgError)(err);
559
+ }
560
+ if (commitWasRolledBack(result))
561
+ throw rolledBackError(firstFailure, 'transaction', api);
562
+ });
559
563
  }
560
564
  /** Whether a COMMIT result reports that the server rolled the transaction back. */
561
565
  function commitWasRolledBack(result) {
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/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
  }
@@ -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';
@@ -2435,7 +2436,8 @@ export class QueryInterface {
2435
2436
  resetUnlimitedWarnings() {
2436
2437
  resetWarnOnce(WARN_NS.unlimitedFindMany);
2437
2438
  }
2438
- 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);
2439
2441
  const onQuery = this.options?._onQuery;
2440
2442
  if (!onQuery)
2441
2443
  return;
@@ -2587,6 +2589,7 @@ export class QueryInterface {
2587
2589
  return this.queryCancellableInTransaction(out, params, timeout, state, action);
2588
2590
  }
2589
2591
  }
2592
+ let trace = startQueryTrace(this.table, action, out.sql, params.length);
2590
2593
  let start = performance.now();
2591
2594
  // Build the query argument, use object form with `name` for prepared
2592
2595
  // statements, or the plain (text, values) form otherwise.
@@ -2615,10 +2618,11 @@ export class QueryInterface {
2615
2618
  // so a listener counting errors sees it and one alerting on failed
2616
2619
  // CALLS can skip it. The final event below times the retry alone.
2617
2620
  const wrapped = wrapPgError(err);
2618
- 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);
2619
2622
  await settleEventLoop();
2620
2623
  if (abandoned)
2621
2624
  throw err;
2625
+ trace = startQueryTrace(this.table, action, out.sql, params.length);
2622
2626
  start = performance.now();
2623
2627
  return send();
2624
2628
  });
@@ -2626,12 +2630,12 @@ export class QueryInterface {
2626
2630
  if (!timeout) {
2627
2631
  try {
2628
2632
  const result = await exec;
2629
- 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);
2630
2634
  return result;
2631
2635
  }
2632
2636
  catch (err) {
2633
2637
  const wrapped = wrapPgError(err);
2634
- 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);
2635
2639
  throw wrapped;
2636
2640
  }
2637
2641
  }
@@ -2648,12 +2652,12 @@ export class QueryInterface {
2648
2652
  });
2649
2653
  try {
2650
2654
  const result = await Promise.race([exec, timeoutPromise]);
2651
- 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);
2652
2656
  return result;
2653
2657
  }
2654
2658
  catch (err) {
2655
2659
  const wrapped = wrapPgError(err);
2656
- 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);
2657
2661
  throw wrapped;
2658
2662
  }
2659
2663
  finally {
@@ -2687,12 +2691,13 @@ export class QueryInterface {
2687
2691
  * once its backend is idle, so timed-out statements cannot hold the pool.
2688
2692
  */
2689
2693
  async queryCancellable(out, params, timeout, retryIfStale, action) {
2694
+ let trace = startQueryTrace(this.table, action, out.sql, params.length);
2690
2695
  let start = performance.now();
2691
2696
  const config = out.name && this.preparedStatementsEnabled ? { name: out.name, text: out.text, values: params } : null;
2692
2697
  const report = (err, retried) => {
2693
2698
  const wrapped = err instanceof TimeoutError ? err : wrapPgError(err);
2694
2699
  const error = wrapped instanceof Error ? wrapped : undefined;
2695
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, retried);
2700
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, retried, trace);
2696
2701
  return wrapped;
2697
2702
  };
2698
2703
  let expired = false;
@@ -2731,7 +2736,8 @@ export class QueryInterface {
2731
2736
  if ('result' in settled) {
2732
2737
  if (first !== TIMED_OUT)
2733
2738
  checkout.release();
2734
- 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);
2735
2741
  return settled.result;
2736
2742
  }
2737
2743
  if ('timeout' in settled)
@@ -2746,6 +2752,7 @@ export class QueryInterface {
2746
2752
  await settleEventLoop();
2747
2753
  if (expired)
2748
2754
  throw report(neverSent());
2755
+ trace = startQueryTrace(this.table, action, out.sql, params.length);
2749
2756
  start = performance.now();
2750
2757
  }
2751
2758
  }
@@ -2765,6 +2772,7 @@ export class QueryInterface {
2765
2772
  * A statement that finishes before the deadline is returned as usual.
2766
2773
  */
2767
2774
  async queryCancellableInTransaction(out, params, timeout, state, action) {
2775
+ const trace = startQueryTrace(this.table, action, out.sql, params.length);
2768
2776
  const start = performance.now();
2769
2777
  const running = (out.name && this.preparedStatementsEnabled
2770
2778
  ? this.pool.query({
@@ -2786,11 +2794,13 @@ export class QueryInterface {
2786
2794
  clearTimeout(timer);
2787
2795
  }
2788
2796
  if ('result' in settled) {
2789
- 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);
2790
2799
  return settled.result;
2791
2800
  }
2792
2801
  const err = 'timeout' in settled ? settled.timeout : wrapPgError(settled.error);
2793
- 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);
2794
2804
  throw err;
2795
2805
  }
2796
2806
  /** Cancel a timed-out statement in a transaction and end the transaction. See {@link queryCancellableInTransaction}. */