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
@@ -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
@@ -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/cjs/powdb.js CHANGED
@@ -22,7 +22,9 @@
22
22
  * writable types (`str`/`int`/`float`/`bool`); `Date` → `int` epoch micros;
23
23
  * `string` PKs hold UUID strings.
24
24
  * - **No JSON aggregation / link navigation**, single-query nested `with` is
25
- * impossible → it degrades to batched N+1 loaders (Phase B).
25
+ * not available → on PowDB 0.18+ an eligible `with` compiles to nested
26
+ * projections inside the parent statement; older engines and ineligible
27
+ * relations use batched loaders.
26
28
  * - **Single global write lock; no savepoints/isolation**, nested
27
29
  * transactions / isolation / vector / LISTEN-NOTIFY / RLS throw.
28
30
  * Independent concurrent `db.$transaction` calls do NOT throw: they queue
@@ -1867,7 +1869,7 @@ async function loadPowdbEmbedded() {
1867
1869
  catch (err) {
1868
1870
  throw new errors_js_1.ConnectionError("turbine-orm/powdb embedded mode requires the optional peer '@zvndev/powdb-embedded'. " +
1869
1871
  'Install it: npm i @zvndev/powdb-embedded. If install succeeded but loading failed, your platform has no ' +
1870
- 'prebuilt binary (prebuilts ship for macOS arm64/x64 and Linux glibc x64/arm64; Intel-mac/musl/Windows ' +
1872
+ 'prebuilt binary (prebuilts ship for macOS arm64 and Linux glibc x64/arm64; Intel macOS, musl and Windows ' +
1871
1873
  'build from source), build it with `npm run build` in the addon, then retry. You can also construct the ' +
1872
1874
  'pool yourself and inject it: turbinePowDB(pool, schema). ' +
1873
1875
  `(${err.message})`);
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
  }
@@ -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
@@ -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");
@@ -277,14 +278,6 @@ const ROW_PLAN_CACHE_SIZE = 128;
277
278
  * probe's own limit.
278
279
  */
279
280
  const STREAM_SPECULATION_MAX_BATCH = 1000;
280
- /** Per-cell decode work in a {@link RowDecodePlan}. */
281
- const CELL_PLAIN = 0;
282
- const CELL_TEMPORAL = 1;
283
- const CELL_FLOAT = 2;
284
- const CELL_FLOAT_ARRAY = 3;
285
- const CELL_TEXT_ARRAY = 4;
286
- /** The dialect's own decode for a type whose storage differs (see `Dialect.decodeColumnValue`). */
287
- const CELL_DIALECT = 5;
288
281
  const FLOAT_TYPES = new Set(['float4', 'float8', 'real', 'double precision']);
289
282
  const FLOAT_ARRAY_TYPES = new Set(['_float4', '_float8', 'float4[]', 'float8[]', 'real[]', 'double precision[]']);
290
283
  /**
@@ -294,11 +287,11 @@ const FLOAT_ARRAY_TYPES = new Set(['_float4', '_float8', 'float4[]', 'float8[]',
294
287
  */
295
288
  function cellKindOf(pgType, enums) {
296
289
  if (FLOAT_TYPES.has(pgType))
297
- return CELL_FLOAT;
290
+ return utils_js_1.CELL_FLOAT;
298
291
  if (FLOAT_ARRAY_TYPES.has(pgType))
299
- return CELL_FLOAT_ARRAY;
292
+ return utils_js_1.CELL_FLOAT_ARRAY;
300
293
  const element = pgType.startsWith('_') ? pgType.slice(1) : pgType.endsWith('[]') ? pgType.slice(0, -2) : undefined;
301
- return element !== undefined && enums !== undefined && Object.hasOwn(enums, element) ? CELL_TEXT_ARRAY : CELL_PLAIN;
294
+ return element !== undefined && enums !== undefined && Object.hasOwn(enums, element) ? utils_js_1.CELL_TEXT_ARRAY : utils_js_1.CELL_PLAIN;
302
295
  }
303
296
  /**
304
297
  * Strict structural equality for a single SQL parameter value. Handles the
@@ -1020,6 +1013,11 @@ class QueryInterface {
1020
1013
  toColumn: (field) => this.toColumn(field),
1021
1014
  castAgg: (expr, target) => this.castAgg(expr, target),
1022
1015
  parseRow: (row, table) => this.parseRow(row, table),
1016
+ rowDecodePlan: (table, keys) => {
1017
+ const meta = this.schema.tables[table];
1018
+ return meta ? this.rowDecodePlanFor(table, meta, keys) : undefined;
1019
+ },
1020
+ decodeCell: (kind, value, table, field) => this.decodeCell(kind, value, table, field),
1023
1021
  nullsSuffix: (nulls) => this.nullsSuffix(nulls),
1024
1022
  isRelationOrderByValue: (value) => this.isRelationOrderByValue(value),
1025
1023
  resolveOrderByColumn: (table, meta, key) => this.resolveOrderByColumn(table, meta, key),
@@ -2476,7 +2474,8 @@ class QueryInterface {
2476
2474
  resetUnlimitedWarnings() {
2477
2475
  (0, warn_registry_js_1.resetWarnOnce)(warn_registry_js_1.WARN_NS.unlimitedFindMany);
2478
2476
  }
2479
- 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);
2480
2479
  const onQuery = this.options?._onQuery;
2481
2480
  if (!onQuery)
2482
2481
  return;
@@ -2628,6 +2627,7 @@ class QueryInterface {
2628
2627
  return this.queryCancellableInTransaction(out, params, timeout, state, action);
2629
2628
  }
2630
2629
  }
2630
+ let trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2631
2631
  let start = performance.now();
2632
2632
  // Build the query argument, use object form with `name` for prepared
2633
2633
  // statements, or the plain (text, values) form otherwise.
@@ -2656,10 +2656,11 @@ class QueryInterface {
2656
2656
  // so a listener counting errors sees it and one alerting on failed
2657
2657
  // CALLS can skip it. The final event below times the retry alone.
2658
2658
  const wrapped = (0, errors_js_1.wrapPgError)(err);
2659
- 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);
2660
2660
  await (0, connection_guard_js_1.settleEventLoop)();
2661
2661
  if (abandoned)
2662
2662
  throw err;
2663
+ trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2663
2664
  start = performance.now();
2664
2665
  return send();
2665
2666
  });
@@ -2667,12 +2668,12 @@ class QueryInterface {
2667
2668
  if (!timeout) {
2668
2669
  try {
2669
2670
  const result = await exec;
2670
- 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);
2671
2672
  return result;
2672
2673
  }
2673
2674
  catch (err) {
2674
2675
  const wrapped = (0, errors_js_1.wrapPgError)(err);
2675
- 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);
2676
2677
  throw wrapped;
2677
2678
  }
2678
2679
  }
@@ -2689,12 +2690,12 @@ class QueryInterface {
2689
2690
  });
2690
2691
  try {
2691
2692
  const result = await Promise.race([exec, timeoutPromise]);
2692
- 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);
2693
2694
  return result;
2694
2695
  }
2695
2696
  catch (err) {
2696
2697
  const wrapped = (0, errors_js_1.wrapPgError)(err);
2697
- 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);
2698
2699
  throw wrapped;
2699
2700
  }
2700
2701
  finally {
@@ -2728,12 +2729,13 @@ class QueryInterface {
2728
2729
  * once its backend is idle, so timed-out statements cannot hold the pool.
2729
2730
  */
2730
2731
  async queryCancellable(out, params, timeout, retryIfStale, action) {
2732
+ let trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2731
2733
  let start = performance.now();
2732
2734
  const config = out.name && this.preparedStatementsEnabled ? { name: out.name, text: out.text, values: params } : null;
2733
2735
  const report = (err, retried) => {
2734
2736
  const wrapped = err instanceof errors_js_1.TimeoutError ? err : (0, errors_js_1.wrapPgError)(err);
2735
2737
  const error = wrapped instanceof Error ? wrapped : undefined;
2736
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, retried);
2738
+ this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, retried, trace);
2737
2739
  return wrapped;
2738
2740
  };
2739
2741
  let expired = false;
@@ -2772,7 +2774,8 @@ class QueryInterface {
2772
2774
  if ('result' in settled) {
2773
2775
  if (first !== TIMED_OUT)
2774
2776
  checkout.release();
2775
- 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);
2776
2779
  return settled.result;
2777
2780
  }
2778
2781
  if ('timeout' in settled)
@@ -2787,6 +2790,7 @@ class QueryInterface {
2787
2790
  await (0, connection_guard_js_1.settleEventLoop)();
2788
2791
  if (expired)
2789
2792
  throw report(neverSent());
2793
+ trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2790
2794
  start = performance.now();
2791
2795
  }
2792
2796
  }
@@ -2806,6 +2810,7 @@ class QueryInterface {
2806
2810
  * A statement that finishes before the deadline is returned as usual.
2807
2811
  */
2808
2812
  async queryCancellableInTransaction(out, params, timeout, state, action) {
2813
+ const trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2809
2814
  const start = performance.now();
2810
2815
  const running = (out.name && this.preparedStatementsEnabled
2811
2816
  ? this.pool.query({
@@ -2827,11 +2832,13 @@ class QueryInterface {
2827
2832
  clearTimeout(timer);
2828
2833
  }
2829
2834
  if ('result' in settled) {
2830
- 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);
2831
2837
  return settled.result;
2832
2838
  }
2833
2839
  const err = 'timeout' in settled ? settled.timeout : (0, errors_js_1.wrapPgError)(settled.error);
2834
- 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);
2835
2842
  throw err;
2836
2843
  }
2837
2844
  /** Cancel a timed-out statement in a transaction and end the transaction. See {@link queryCancellableInTransaction}. */
@@ -5266,9 +5273,9 @@ class QueryInterface {
5266
5273
  if (typeof pgType !== 'string')
5267
5274
  continue;
5268
5275
  let kind = cellKindOf(pgType, this.schema.enums);
5269
- const decode = kind === CELL_PLAIN ? this.dialect.decodeColumnValue?.(pgType) : undefined;
5276
+ const decode = kind === utils_js_1.CELL_PLAIN ? this.dialect.decodeColumnValue?.(pgType) : undefined;
5270
5277
  if (decode !== undefined) {
5271
- kind = CELL_DIALECT;
5278
+ kind = utils_js_1.CELL_DIALECT;
5272
5279
  let decoders = this.dialectDecodeCache.get(table);
5273
5280
  if (!decoders) {
5274
5281
  decoders = new Map();
@@ -5277,7 +5284,7 @@ class QueryInterface {
5277
5284
  decoders.set(column.name, decode);
5278
5285
  decoders.set(column.field, decode);
5279
5286
  }
5280
- if (kind === CELL_PLAIN)
5287
+ if (kind === utils_js_1.CELL_PLAIN)
5281
5288
  continue;
5282
5289
  kinds.set(column.name, kind);
5283
5290
  kinds.set(column.field, kind);
@@ -5289,15 +5296,15 @@ class QueryInterface {
5289
5296
  /** One cell's decode, for every kind but {@link CELL_PLAIN}. */
5290
5297
  decodeCell(kind, value, table, field) {
5291
5298
  switch (kind) {
5292
- case CELL_TEMPORAL:
5299
+ case utils_js_1.CELL_TEMPORAL:
5293
5300
  return this.decodeTemporalCell(value, table, field);
5294
- case CELL_FLOAT:
5301
+ case utils_js_1.CELL_FLOAT:
5295
5302
  return (0, utils_js_1.readJsonFloat)(value);
5296
- case CELL_FLOAT_ARRAY:
5303
+ case utils_js_1.CELL_FLOAT_ARRAY:
5297
5304
  return (0, utils_js_1.readJsonFloatArray)(value);
5298
- case CELL_TEXT_ARRAY:
5305
+ case utils_js_1.CELL_TEXT_ARRAY:
5299
5306
  return (0, utils_js_1.readTextArray)(value);
5300
- case CELL_DIALECT:
5307
+ case utils_js_1.CELL_DIALECT:
5301
5308
  return this.decodeDialectCell(value, table, field);
5302
5309
  default:
5303
5310
  return value;
@@ -5328,6 +5335,18 @@ class QueryInterface {
5328
5335
  * search down the wrong path.
5329
5336
  */
5330
5337
  buildRowDecodePlan(table, meta, keys) {
5338
+ const plan = this.rowDecodePlanFor(table, meta, keys);
5339
+ this.rowPlanLast.set(table, plan);
5340
+ return plan;
5341
+ }
5342
+ /**
5343
+ * The cached decode plan for one exact column list, without touching the
5344
+ * per-table most-recent slot. {@link buildRowDecodePlan} is the per-row entry;
5345
+ * this is also what the positional nested-row plan in relations.ts reads
5346
+ * (through the ctx) when it is built, so a nested row decodes by exactly the
5347
+ * field names and cell kinds {@link parseRow} would give the same keys.
5348
+ */
5349
+ rowDecodePlanFor(table, meta, keys) {
5331
5350
  const shapeKey = `${table}\u0000${keys.join('\u0000')}`;
5332
5351
  let plan = this.rowPlanCache.get(shapeKey);
5333
5352
  if (plan === undefined) {
@@ -5345,13 +5364,12 @@ class QueryInterface {
5345
5364
  fields.push(field);
5346
5365
  // Top-level rows are snake_case (dateCols); nested rows are camelCase.
5347
5366
  kinds.push(dateCols.has(col) || camelDateFields.has(field)
5348
- ? CELL_TEMPORAL
5349
- : (cellKinds.get(col) ?? cellKinds.get(field) ?? CELL_PLAIN));
5367
+ ? utils_js_1.CELL_TEMPORAL
5368
+ : (cellKinds.get(col) ?? cellKinds.get(field) ?? utils_js_1.CELL_PLAIN));
5350
5369
  }
5351
5370
  plan = { cols, fields, kinds };
5352
5371
  this.rowPlanCache.set(shapeKey, plan);
5353
5372
  }
5354
- this.rowPlanLast.set(table, plan);
5355
5373
  return plan;
5356
5374
  }
5357
5375
  /**
@@ -5399,7 +5417,7 @@ class QueryInterface {
5399
5417
  const kind = kinds[i];
5400
5418
  // A float from the driver is already a number; only JSON's strings need reading.
5401
5419
  parsed[field] =
5402
- kind === CELL_PLAIN || (kind === CELL_FLOAT && typeof value !== 'string')
5420
+ kind === utils_js_1.CELL_PLAIN || (kind === utils_js_1.CELL_FLOAT && typeof value !== 'string')
5403
5421
  ? value
5404
5422
  : this.decodeCell(kind, value, table, field);
5405
5423
  }
@@ -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`. */