turbine-orm 0.92.0-next.b95bea3 → 0.93.0-next.90d9a6c

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.
@@ -48,6 +48,7 @@ const stream_idle_js_1 = require("./query/stream-idle.js");
48
48
  const table_client_js_1 = require("./query/table-client.js");
49
49
  const utils_js_1 = require("./query/utils.js");
50
50
  const warn_registry_js_1 = require("./query/warn-registry.js");
51
+ const query_channel_js_1 = require("./query-channel.js");
51
52
  const query_events_js_1 = require("./query-events.js");
52
53
  const realtime_js_1 = require("./realtime.js");
53
54
  const supplied_pool_types_js_1 = require("./supplied-pool-types.js");
@@ -367,12 +368,14 @@ const ISOLATION_LEVELS = Object.assign(Object.create(null), {
367
368
  * that are the main reason to run SERIALIZABLE at all.
368
369
  */
369
370
  async function runTxControl(client, sql, params) {
370
- try {
371
- await client.query(sql, params);
372
- }
373
- catch (err) {
374
- throw (0, errors_js_1.wrapPgError)(err);
375
- }
371
+ await (0, query_channel_js_1.traceStatement)(query_channel_js_1.TRANSACTION_CONTROL_OPERATION, sql, params?.length ?? 0, async () => {
372
+ try {
373
+ await client.query(sql, params);
374
+ }
375
+ catch (err) {
376
+ throw (0, errors_js_1.wrapPgError)(err);
377
+ }
378
+ });
376
379
  }
377
380
  /**
378
381
  * Refuse anything in a batch that is not a deferred query, before any of it
@@ -543,6 +546,9 @@ const SESSION_SETTING_REFUSALS = Object.assign(Object.create(null), {
543
546
  * own message (which may contain the value) stays on `cause`.
544
547
  */
545
548
  async function applySessionSetting(client, setting) {
549
+ await (0, query_channel_js_1.traceStatement)(query_channel_js_1.TRANSACTION_CONTROL_OPERATION, setting.sql, setting.params.length, () => sendSessionSetting(client, setting));
550
+ }
551
+ async function sendSessionSetting(client, setting) {
546
552
  try {
547
553
  await client.query(setting.sql, setting.params);
548
554
  }
@@ -627,7 +633,8 @@ async function rollbackOnServer(client, state, dialect) {
627
633
  return false;
628
634
  }
629
635
  let failed = false;
630
- const rollback = client.query(dialect.rollbackStatement()).catch(() => {
636
+ const sql = dialect.rollbackStatement();
637
+ const rollback = (0, query_channel_js_1.traceStatement)(query_channel_js_1.TRANSACTION_CONTROL_OPERATION, sql, 0, () => client.query(sql)).catch(() => {
631
638
  failed = true;
632
639
  });
633
640
  return (await settlesWithin(rollback, TX_ABORT_GRACE_MS)) && !failed;
@@ -2249,7 +2256,7 @@ class TurbineClient {
2249
2256
  const comments = this.statementComments(queries);
2250
2257
  const sent = comments ? queries.map((q, i) => (0, sql_comment_js_1.commentDeferred)(q, comments[i])) : queries;
2251
2258
  const sink = this.queryListeners.size > 0 ? this.queryOptions._onQuery : undefined;
2252
- if (!sink)
2259
+ if (!sink && !(0, query_channel_js_1.queryChannelActive)())
2253
2260
  return this.withErrorMode(() => (0, pipeline_js_1.executePipeline)(this.queryPool, sent, options));
2254
2261
  return this.withErrorMode(() => this.reportedPipeline(sink, queries, options, sent, comments));
2255
2262
  }
@@ -2284,6 +2291,10 @@ class TurbineClient {
2284
2291
  return q.transform(raw);
2285
2292
  },
2286
2293
  }));
2294
+ const traces = queries.map((q) => {
2295
+ const { model, action } = (0, query_events_js_1.deferredIdentity)(q.tag);
2296
+ return (0, query_channel_js_1.startQueryTrace)(model, action, q.sql, q.params.length, 'pipeline');
2297
+ });
2287
2298
  const start = performance.now();
2288
2299
  let failure;
2289
2300
  try {
@@ -2304,6 +2315,10 @@ class TurbineClient {
2304
2315
  : rowCounts.indexOf(undefined);
2305
2316
  queries.forEach((q, i) => {
2306
2317
  const failed = i === failedIndex;
2318
+ const error = failure === undefined ? undefined : failure instanceof Error ? failure : new Error(String(failure));
2319
+ // A traced slot is always settled, so every channel start has its end: one that never ran
2320
+ // (or rolled back unseen) settles with the batch's error.
2321
+ (0, query_channel_js_1.settleQueryTrace)(traces[i], rowCounts[i] ?? 0, duration, failed || rowCounts[i] === undefined ? error : undefined);
2307
2322
  // A slot that never ran (or rolled back unseen) is not reported.
2308
2323
  if (failed || rowCounts[i] !== undefined) {
2309
2324
  (0, query_events_js_1.emitStatementEvent)(sink, {
@@ -2314,7 +2329,7 @@ class TurbineClient {
2314
2329
  rows: rowCounts[i] ?? 0,
2315
2330
  batch: 'pipeline',
2316
2331
  ...(comments?.[i] === undefined ? {} : { comment: comments[i] }),
2317
- ...(failed ? { error: failure instanceof Error ? failure : new Error(String(failure)) } : {}),
2332
+ ...(failed ? { error } : {}),
2318
2333
  });
2319
2334
  }
2320
2335
  });
@@ -2879,12 +2894,15 @@ class TurbineClient {
2879
2894
  if (this.logging) {
2880
2895
  (0, logger_js_1.logTo)(this.logger, 'debug', `NOTIFY ${channel}`, { code: 'notify', channel });
2881
2896
  }
2882
- try {
2883
- await this.pool.query('SELECT pg_notify($1, $2)', [channel, payload ?? '']);
2884
- }
2885
- catch (err) {
2886
- throw (0, errors_js_1.wrapPgError)(err);
2887
- }
2897
+ const sql = 'SELECT pg_notify($1, $2)';
2898
+ await (0, query_channel_js_1.traceStatement)('$notify', sql, 2, async () => {
2899
+ try {
2900
+ return await this.pool.query(sql, [channel, payload ?? '']);
2901
+ }
2902
+ catch (err) {
2903
+ throw (0, errors_js_1.wrapPgError)(err);
2904
+ }
2905
+ });
2888
2906
  }
2889
2907
  // -------------------------------------------------------------------------
2890
2908
  // Retry, automatic retry for retryable errors (deadlock, serialization)
@@ -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/cjs/index.js CHANGED
@@ -35,7 +35,7 @@
35
35
  */
36
36
  Object.defineProperty(exports, "__esModule", { value: true });
37
37
  exports.AUTO_JOIN_PENALTY_MS_PER_ROW = exports.AUTO_COUNT_BATCH_MIN_PARENT_ROWS = exports.AUTO_ASSUMED_ROUND_TRIP_MS = exports.expr = exports.fingerprintPrismaSchema = exports.pipelineSupported = exports.executePipeline = exports.PgMetricsSink = exports.HttpJsonSink = exports.hasRelationFields = exports.executeNestedUpdate = exports.executeNestedCreate = exports.introspect = exports.generate = exports.wrapPgError = exports.ValidationError = exports.UnsupportedFeatureError = exports.UniqueConstraintError = exports.TurbineErrorCode = exports.TurbineError = exports.TransactionRolledBackError = exports.TimeoutError = exports.setErrorMessageMode = exports.SerializationFailureError = exports.RelationError = exports.ReadOnlyError = exports.REDACTED_DETAIL = exports.PipelineError = exports.OptimisticLockError = exports.NotNullViolationError = exports.NotFoundError = exports.MigrationError = exports.LockNotAvailableError = exports.InvariantError = exports.getErrorMessageMode = exports.ForeignKeyError = exports.ExclusionConstraintError = exports.DeadlockError = exports.ConnectionError = exports.CircularRelationError = exports.CheckConstraintError = exports.postgresDialect = exports.withRetry = exports.TurbineClient = exports.TransactionClient = exports.yugabytedb = exports.timescale = exports.postgresql = exports.cockroachdb = exports.alloydb = void 0;
38
- exports.TypedSqlQuery = exports.buildTypedSql = exports.turbineHttp = exports.defineSeed = exports.schemaToSQLString = exports.schemaToSQL = exports.schemaPush = exports.schemaDiff = exports.DestructivePushRefusal = exports.schemaDefToMetadata = exports.table = exports.isDocFieldIndexDef = exports.defineSchema = exports.column = exports.ColumnBuilder = exports.applyManyToManyRelations = exports.withDbFieldNames = exports.snakeToPascal = exports.snakeToCamel = exports.singularize = exports.pgTypeToTs = exports.pgArrayType = exports.normalizeKeyColumns = exports.isDateType = exports.camelToSnake = exports.validateChannel = exports.RAW_QUERY_MODEL = exports.MAX_QUERY_TAG_LENGTH = exports.UNSAFE = exports.QueryInterface = exports.jsonValue = exports.col = exports.AUTO_TO_ONE_JOIN_ROWS_MIN = exports.AUTO_TO_ONE_JOIN_ROWS_MAX = exports.AUTO_TO_ONE_JOIN_MAX_ROWS = void 0;
38
+ exports.TypedSqlQuery = exports.buildTypedSql = exports.turbineHttp = exports.defineSeed = exports.schemaToSQLString = exports.schemaToSQL = exports.schemaPush = exports.schemaDiff = exports.DestructivePushRefusal = exports.schemaDefToMetadata = exports.table = exports.isDocFieldIndexDef = exports.defineSchema = exports.column = exports.ColumnBuilder = exports.applyManyToManyRelations = exports.withDbFieldNames = exports.snakeToPascal = exports.snakeToCamel = exports.singularize = exports.pgTypeToTs = exports.pgArrayType = exports.normalizeKeyColumns = exports.isDateType = exports.camelToSnake = exports.validateChannel = exports.RAW_QUERY_MODEL = exports.MAX_QUERY_TAG_LENGTH = exports.QUERY_CHANNEL = exports.UNSAFE = exports.QueryInterface = exports.jsonValue = exports.col = exports.AUTO_TO_ONE_JOIN_ROWS_MIN = exports.AUTO_TO_ONE_JOIN_ROWS_MAX = exports.AUTO_TO_ONE_JOIN_MAX_ROWS = void 0;
39
39
  var index_js_1 = require("./adapters/index.js");
40
40
  Object.defineProperty(exports, "alloydb", { enumerable: true, get: function () { return index_js_1.alloydb; } });
41
41
  Object.defineProperty(exports, "cockroachdb", { enumerable: true, get: function () { return index_js_1.cockroachdb; } });
@@ -118,6 +118,9 @@ Object.defineProperty(exports, "col", { enumerable: true, get: function () { ret
118
118
  Object.defineProperty(exports, "jsonValue", { enumerable: true, get: function () { return index_js_2.jsonValue; } });
119
119
  Object.defineProperty(exports, "QueryInterface", { enumerable: true, get: function () { return index_js_2.QueryInterface; } });
120
120
  Object.defineProperty(exports, "UNSAFE", { enumerable: true, get: function () { return index_js_2.UNSAFE; } });
121
+ // diagnostics_channel tracing channel every statement is published on
122
+ var query_channel_js_1 = require("./query-channel.js");
123
+ Object.defineProperty(exports, "QUERY_CHANNEL", { enumerable: true, get: function () { return query_channel_js_1.QUERY_CHANNEL; } });
121
124
  // $on('query') event metadata: raw-statement model name, $tag() label limit
122
125
  var query_events_js_1 = require("./query-events.js");
123
126
  Object.defineProperty(exports, "MAX_QUERY_TAG_LENGTH", { enumerable: true, get: function () { return query_events_js_1.MAX_QUERY_TAG_LENGTH; } });
@@ -27,6 +27,7 @@ const connection_guard_js_1 = require("./connection-guard.js");
27
27
  const dialect_js_1 = require("./dialect.js");
28
28
  const errors_js_1 = require("./errors.js");
29
29
  const pipeline_submittable_js_1 = require("./pipeline-submittable.js");
30
+ const query_channel_js_1 = require("./query-channel.js");
30
31
  const transaction_state_js_1 = require("./transaction-state.js");
31
32
  /**
32
33
  * Run one deferred query on the batch's connection. An engine without
@@ -56,12 +57,15 @@ async function runSequential(client, queries, dialect, options = {}) {
56
57
  // TurbineError, and a caller branching on `err.code` saw neither
57
58
  // `TURBINE_E004` nor a retryable flag for the one failure that is most
58
59
  // worth retrying.
59
- try {
60
- await client.query(dialect.beginStatement());
61
- }
62
- catch (err) {
63
- throw (0, errors_js_1.wrapPgError)(err);
64
- }
60
+ const begin = dialect.beginStatement();
61
+ await (0, query_channel_js_1.traceStatement)(query_channel_js_1.TRANSACTION_CONTROL_OPERATION, begin, 0, async () => {
62
+ try {
63
+ await client.query(begin);
64
+ }
65
+ catch (err) {
66
+ throw (0, errors_js_1.wrapPgError)(err);
67
+ }
68
+ });
65
69
  const results = [];
66
70
  for (const q of queries) {
67
71
  let raw;
@@ -80,7 +84,8 @@ async function runSequential(client, queries, dialect, options = {}) {
80
84
  }
81
85
  catch (err) {
82
86
  try {
83
- await client.query(dialect.rollbackStatement());
87
+ const rollback = dialect.rollbackStatement();
88
+ await (0, query_channel_js_1.traceStatement)(query_channel_js_1.TRANSACTION_CONTROL_OPERATION, rollback, 0, () => client.query(rollback));
84
89
  }
85
90
  catch {
86
91
  // Best-effort rollback
package/dist/cjs/powql.js CHANGED
@@ -65,6 +65,7 @@ const warn_registry_js_1 = require("./query/warn-registry.js");
65
65
  const where_js_1 = require("./query/where.js");
66
66
  const where_compile_js_1 = require("./query/where-compile.js");
67
67
  const writes_js_1 = require("./query/writes.js");
68
+ const query_channel_js_1 = require("./query-channel.js");
68
69
  const schema_js_1 = require("./schema.js");
69
70
  const transaction_client_slot_js_1 = require("./transaction-client-slot.js");
70
71
  /**
@@ -2208,6 +2209,7 @@ class PowqlInterface {
2208
2209
  if (this.pool.readonly === true && POWQL_WRITE_ACTIONS.has(action)) {
2209
2210
  throw this.readOnlyError(action);
2210
2211
  }
2212
+ const trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, powql, params.length);
2211
2213
  const start = performance.now();
2212
2214
  const run = this.pool.query(powql, params);
2213
2215
  try {
@@ -2217,7 +2219,9 @@ class PowqlInterface {
2217
2219
  new Promise((_, reject) => setTimeout(() => reject(new errors_js_1.TimeoutError(timeout)), timeout)),
2218
2220
  ])
2219
2221
  : await run;
2220
- this.emit(action, powql, params, performance.now() - start, result.rowCount ?? result.rows.length);
2222
+ const duration = performance.now() - start;
2223
+ (0, query_channel_js_1.settleQueryTrace)(trace, result.rowCount ?? result.rows.length, duration);
2224
+ this.emit(action, powql, params, duration, result.rowCount ?? result.rows.length);
2221
2225
  // The pool tags each result with the wire that actually served it
2222
2226
  // (adaptResult → false, adaptNativeResult → true). A heterogeneous
2223
2227
  // injected pool can fall back to the legacy wire per call, so read the
@@ -2228,12 +2232,16 @@ class PowqlInterface {
2228
2232
  return { rows: result.rows, rowCount: result.rowCount ?? result.rows.length, native };
2229
2233
  }
2230
2234
  catch (err) {
2235
+ const duration = performance.now() - start;
2231
2236
  if (!isRetry && this.shouldRetryStaleRead(err, action)) {
2232
2237
  // Transparent single replay on a fresh connection; the first (swallowed)
2233
- // failure is not emitted, only the retried outcome is observed.
2238
+ // failure is not emitted, only the retried outcome is observed. Its
2239
+ // channel trace is still settled, marked retried.
2240
+ (0, query_channel_js_1.settleQueryTrace)(trace, 0, duration, err instanceof Error ? err : new Error(String(err)), true);
2234
2241
  return this.execOnce(powql, params, timeout, action, true);
2235
2242
  }
2236
- this.emit(action, powql, params, performance.now() - start, 0, err);
2243
+ (0, query_channel_js_1.settleQueryTrace)(trace, 0, duration, err instanceof Error ? err : new Error(String(err)));
2244
+ this.emit(action, powql, params, duration, 0, err);
2237
2245
  throw err;
2238
2246
  }
2239
2247
  }
@@ -56,6 +56,7 @@ const errors_js_1 = require("../errors.js");
56
56
  const index_advisor_js_1 = require("../index-advisor.js");
57
57
  const logger_js_1 = require("../logger.js");
58
58
  const nested_write_js_1 = require("../nested-write.js");
59
+ const query_channel_js_1 = require("../query-channel.js");
59
60
  const schema_js_1 = require("../schema.js");
60
61
  const transaction_client_slot_js_1 = require("../transaction-client-slot.js");
61
62
  const transaction_state_js_1 = require("../transaction-state.js");
@@ -2473,7 +2474,8 @@ class QueryInterface {
2473
2474
  resetUnlimitedWarnings() {
2474
2475
  (0, warn_registry_js_1.resetWarnOnce)(warn_registry_js_1.WARN_NS.unlimitedFindMany);
2475
2476
  }
2476
- emitQueryEvent(out, params, duration, action, rows, error, retried) {
2477
+ emitQueryEvent(out, params, duration, action, rows, error, retried, trace) {
2478
+ (0, query_channel_js_1.settleQueryTrace)(trace, rows, duration, error, retried);
2477
2479
  const onQuery = this.options?._onQuery;
2478
2480
  if (!onQuery)
2479
2481
  return;
@@ -2625,6 +2627,7 @@ class QueryInterface {
2625
2627
  return this.queryCancellableInTransaction(out, params, timeout, state, action);
2626
2628
  }
2627
2629
  }
2630
+ let trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2628
2631
  let start = performance.now();
2629
2632
  // Build the query argument, use object form with `name` for prepared
2630
2633
  // statements, or the plain (text, values) form otherwise.
@@ -2653,10 +2656,11 @@ class QueryInterface {
2653
2656
  // so a listener counting errors sees it and one alerting on failed
2654
2657
  // CALLS can skip it. The final event below times the retry alone.
2655
2658
  const wrapped = (0, errors_js_1.wrapPgError)(err);
2656
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, true);
2659
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, true, trace);
2657
2660
  await (0, connection_guard_js_1.settleEventLoop)();
2658
2661
  if (abandoned)
2659
2662
  throw err;
2663
+ trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2660
2664
  start = performance.now();
2661
2665
  return send();
2662
2666
  });
@@ -2664,12 +2668,12 @@ class QueryInterface {
2664
2668
  if (!timeout) {
2665
2669
  try {
2666
2670
  const result = await exec;
2667
- this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0);
2671
+ this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0, undefined, undefined, trace);
2668
2672
  return result;
2669
2673
  }
2670
2674
  catch (err) {
2671
2675
  const wrapped = (0, errors_js_1.wrapPgError)(err);
2672
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined);
2676
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, undefined, trace);
2673
2677
  throw wrapped;
2674
2678
  }
2675
2679
  }
@@ -2686,12 +2690,12 @@ class QueryInterface {
2686
2690
  });
2687
2691
  try {
2688
2692
  const result = await Promise.race([exec, timeoutPromise]);
2689
- this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0);
2693
+ this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0, undefined, undefined, trace);
2690
2694
  return result;
2691
2695
  }
2692
2696
  catch (err) {
2693
2697
  const wrapped = (0, errors_js_1.wrapPgError)(err);
2694
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined);
2698
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, undefined, trace);
2695
2699
  throw wrapped;
2696
2700
  }
2697
2701
  finally {
@@ -2725,12 +2729,13 @@ class QueryInterface {
2725
2729
  * once its backend is idle, so timed-out statements cannot hold the pool.
2726
2730
  */
2727
2731
  async queryCancellable(out, params, timeout, retryIfStale, action) {
2732
+ let trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2728
2733
  let start = performance.now();
2729
2734
  const config = out.name && this.preparedStatementsEnabled ? { name: out.name, text: out.text, values: params } : null;
2730
2735
  const report = (err, retried) => {
2731
2736
  const wrapped = err instanceof errors_js_1.TimeoutError ? err : (0, errors_js_1.wrapPgError)(err);
2732
2737
  const error = wrapped instanceof Error ? wrapped : undefined;
2733
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, retried);
2738
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, retried, trace);
2734
2739
  return wrapped;
2735
2740
  };
2736
2741
  let expired = false;
@@ -2769,7 +2774,8 @@ class QueryInterface {
2769
2774
  if ('result' in settled) {
2770
2775
  if (first !== TIMED_OUT)
2771
2776
  checkout.release();
2772
- this.emitQueryEvent(out, params, performance.now() - start, action, settled.result.rowCount ?? 0);
2777
+ const rows = settled.result.rowCount ?? 0;
2778
+ this.emitQueryEvent(out, params, performance.now() - start, action, rows, undefined, undefined, trace);
2773
2779
  return settled.result;
2774
2780
  }
2775
2781
  if ('timeout' in settled)
@@ -2784,6 +2790,7 @@ class QueryInterface {
2784
2790
  await (0, connection_guard_js_1.settleEventLoop)();
2785
2791
  if (expired)
2786
2792
  throw report(neverSent());
2793
+ trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2787
2794
  start = performance.now();
2788
2795
  }
2789
2796
  }
@@ -2803,6 +2810,7 @@ class QueryInterface {
2803
2810
  * A statement that finishes before the deadline is returned as usual.
2804
2811
  */
2805
2812
  async queryCancellableInTransaction(out, params, timeout, state, action) {
2813
+ const trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2806
2814
  const start = performance.now();
2807
2815
  const running = (out.name && this.preparedStatementsEnabled
2808
2816
  ? this.pool.query({
@@ -2824,11 +2832,13 @@ class QueryInterface {
2824
2832
  clearTimeout(timer);
2825
2833
  }
2826
2834
  if ('result' in settled) {
2827
- this.emitQueryEvent(out, params, performance.now() - start, action, settled.result.rowCount ?? 0);
2835
+ const rows = settled.result.rowCount ?? 0;
2836
+ this.emitQueryEvent(out, params, performance.now() - start, action, rows, undefined, undefined, trace);
2828
2837
  return settled.result;
2829
2838
  }
2830
2839
  const err = 'timeout' in settled ? settled.timeout : (0, errors_js_1.wrapPgError)(settled.error);
2831
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, err instanceof Error ? err : undefined);
2840
+ const error = err instanceof Error ? err : undefined;
2841
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, undefined, trace);
2832
2842
  throw err;
2833
2843
  }
2834
2844
  /** Cancel a timed-out statement in a transaction and end the transaction. See {@link queryCancellableInTransaction}. */
@@ -0,0 +1,86 @@
1
+ /**
2
+ * turbine-orm, the `turbine:query` tracing channel.
3
+ *
4
+ * Every statement that emits a `$on('query')` event, and the transaction
5
+ * control and `$notify` statements Turbine sends on its own (which emit none),
6
+ * is published on the Node `diagnostics_channel` tracing channel named
7
+ * {@link QUERY_CHANNEL}, so a tracer or APM agent can turn Turbine queries
8
+ * into spans without any setup in the application: it subscribes to the
9
+ * channel, and the application never passes it a client.
10
+ *
11
+ * The events follow the TracingChannel lifecycle for an async call: `start`
12
+ * and `end` when the statement is handed to the driver, then `error` (on
13
+ * failure), `asyncStart` and `asyncEnd` when it settles. All five carry the
14
+ * same context object, so a subscriber can key its own state on it. `start`
15
+ * runs in the caller's async context, so the active span there is the
16
+ * statement's parent.
17
+ *
18
+ * The context never carries a bound parameter value: `sql` is the
19
+ * parametrized text Turbine built (`$1`, `$2`, ...), without the `sqlComment`,
20
+ * and `paramCount` is how many values were bound. Result rows are not
21
+ * attached either. That is why the events are published directly rather than
22
+ * through `tracePromise`, which would put the driver result on the context.
23
+ * A consequence: stores bound with `bindStore` are not entered, so read the
24
+ * caller's async context in the `start` subscriber instead.
25
+ *
26
+ * Cost without a subscriber: one `hasSubscribers` read per statement, and no
27
+ * object is built. The channel is looked up once, through
28
+ * `process.getBuiltinModule`, so no Node builtin is imported statically and
29
+ * the edge entry stays builtin-free. Where that function is missing (Node
30
+ * before 20.16 or 22.3, edge runtimes) nothing is published.
31
+ */
32
+ /** The tracing channel name. Subscribe with `diagnostics_channel.tracingChannel('turbine:query')`. */
33
+ export declare const QUERY_CHANNEL = "turbine:query";
34
+ /**
35
+ * The `operation` of a transaction-control statement Turbine sends on its own:
36
+ * `BEGIN`, `COMMIT`, `ROLLBACK`, savepoints and `sessionContext` settings. Its
37
+ * `model` is `'$raw'`, the `RAW_QUERY_MODEL` of query-events.ts (not imported:
38
+ * query-events.ts imports this module).
39
+ */
40
+ export declare const TRANSACTION_CONTROL_OPERATION = "$transaction";
41
+ /**
42
+ * The context object published on every `turbine:query` event. `rowCount` and
43
+ * `durationMs` are set before `asyncStart`, and `error` before the `error`
44
+ * event; the start events see only the identity fields.
45
+ */
46
+ export interface QueryChannelContext {
47
+ /** The table, or `'$raw'` for raw SQL and transaction control. */
48
+ model: string;
49
+ /** The entry point: `findMany`, `create`, `raw`, `$queryRaw` ..., or `'$transaction'` for transaction control. */
50
+ operation: string;
51
+ /** The parametrized statement, never its values, and without the `sqlComment`. */
52
+ sql: string;
53
+ /** How many values were bound to `sql`. */
54
+ paramCount: number;
55
+ /** Rows returned or affected. 0 for a failed statement. */
56
+ rowCount?: number;
57
+ /** Wall time of the statement, in ms. In a pipeline, the batch's time split evenly across its statements. */
58
+ durationMs?: number;
59
+ /** The error the caller receives, on failure. */
60
+ error?: Error;
61
+ /** `'pipeline'` or `'transaction'` for a statement sent as part of a batch. */
62
+ batch?: 'pipeline' | 'transaction';
63
+ /** Set on a failed first attempt of a read that Turbine sent once more on a fresh connection. */
64
+ retried?: true;
65
+ }
66
+ /** True when something subscribes to `turbine:query`. */
67
+ export declare function queryChannelActive(): boolean;
68
+ /**
69
+ * Publish `start` and `end` for a statement about to be sent, and return the
70
+ * context to settle with {@link settleQueryTrace}. Undefined, and nothing
71
+ * built, when nobody subscribes. Never throws.
72
+ */
73
+ export declare function startQueryTrace(model: string, operation: string, sql: string, paramCount: number, batch?: 'pipeline' | 'transaction'): QueryChannelContext | undefined;
74
+ /**
75
+ * Publish `error` (on failure), `asyncStart` and `asyncEnd` for a statement
76
+ * started with {@link startQueryTrace}. A no-op for an undefined context.
77
+ * Never throws.
78
+ */
79
+ export declare function settleQueryTrace(context: QueryChannelContext | undefined, rowCount: number, durationMs: number, error?: Error, retried?: boolean): void;
80
+ /**
81
+ * Run a statement Turbine sends on its own (transaction control, `$notify`)
82
+ * with a `turbine:query` trace around it. `run` should throw the error the
83
+ * caller receives, so the trace carries that one. Without a subscriber it is
84
+ * `run()` and nothing else.
85
+ */
86
+ export declare function traceStatement<R>(operation: string, sql: string, paramCount: number, run: () => Promise<R>): Promise<R>;
@@ -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
  });