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.
- package/README.md +16 -16
- package/dist/cjs/client.js +33 -15
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.js +4 -1
- package/dist/cjs/pipeline.js +12 -7
- package/dist/cjs/powql.js +11 -3
- package/dist/cjs/query/builder.js +20 -10
- package/dist/cjs/query-channel.d.ts +86 -0
- package/dist/cjs/query-channel.js +150 -0
- package/dist/cjs/query-events.js +5 -1
- package/dist/cjs/transaction-state.js +15 -11
- package/dist/client.js +33 -15
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/pipeline.js +12 -7
- package/dist/powql.js +11 -3
- package/dist/query/builder.js +20 -10
- package/dist/query-channel.d.ts +86 -0
- package/dist/query-channel.js +143 -0
- package/dist/query-events.js +5 -1
- package/dist/transaction-state.js +15 -11
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -21,36 +21,36 @@ Six reasons, each with the mechanism that makes it true:
|
|
|
21
21
|
1. **One dependency.** `dependencies` is `{ "pg": "^8.15.0" }`. No engine binary, no WASM compiler, no adapter packages in lockstep. The optional engines (SQLite, MySQL, SQL Server, PowDB, all tiered Experimental in [STABILITY.md](STABILITY.md)) are peer dependencies or Node builtins you install only if you use them.
|
|
22
22
|
2. **Written from scratch.** Turbine is not a layer over Knex or a query-builder library. Query compilation is plain string building with an FNV-1a shape fingerprint into a bounded LRU of SQL templates, so there is no plan cache to size and no compiler running on your event loop.
|
|
23
23
|
3. **Nested relations in one statement.** A `with` clause compiles to correlated `json_agg` subqueries, so users with posts with comments is one round trip, typed end to end: `users[0].posts[0].comments[0].author.name` autocompletes with no annotation.
|
|
24
|
-
4. **Faster than Drizzle and Prisma.** In the 0.
|
|
24
|
+
4. **Faster than Drizzle and Prisma.** In the 0.92.0 run Drizzle took 1.5x as long as Turbine and Prisma 2.1x, by geometric mean, on a dedicated benchmark machine. The table is below; the losses are stated with the wins.
|
|
25
25
|
5. **Agents get a skill and typed tools, not a SQL prompt.** `npx turbine skill` installs a query-writing skill whose every claim is executed against a live database before release; `npx turbine mcp` exposes eleven read-only MCP tools, including a relation graph and a join-path finder that returns the `with` clause to write. Every tool runs inside `BEGIN READ ONLY`, and PII-tagged columns are redacted before rows reach a model.
|
|
26
26
|
6. **The dangerous operations ask first.** Destructive migration statements refuse to run without typed consent. `update`/`delete` with an empty `where` throws. Columns tagged `pii: true` are excluded from the emitted SQL's projections. `turbine doctor` reports missing FK indexes offline, no account, no telemetry.
|
|
27
27
|
|
|
28
28
|
## Benchmarks
|
|
29
29
|
|
|
30
|
-
Measured **2026-10-15 against turbine-orm 0.
|
|
30
|
+
Measured **2026-10-15 against turbine-orm 0.92.0**, versus **Drizzle 0.45.3** (relational queries) and **Prisma 7.10.0** (`@prisma/adapter-pg`, `relationJoins` on), with a hand-written `pg` control arm. Run by the repository's [`benchmarks.yml`](.github/workflows/benchmarks.yml) workflow on a dedicated machine: AMD Ryzen 9 7950X host, 4-vCPU 16 GB Firecracker VM, client and PostgreSQL 17 (Docker) on the same VM over a Unix socket. PostgreSQL 17.11, Node v24.18.0, `pg` 8.23.1 under every arm. Same schema, same data (1K users, 10K posts, 50K comments), same pool config. Each figure is the median over 200 rounds with arm order rotated per round, taken as the median of 3 full runs.
|
|
31
31
|
|
|
32
|
-
| Scenario | Turbine 0.
|
|
32
|
+
| Scenario | Turbine 0.92.0 | Drizzle 0.45.3 | Prisma 7.10.0 | raw pg |
|
|
33
33
|
|---|---|---|---|---|
|
|
34
|
-
| findMany, 100 users | **0.
|
|
35
|
-
| findMany, 50 users + posts
|
|
36
|
-
| findMany, 10 users + posts + comments | **0.
|
|
37
|
-
| findUnique by primary key | **0.090 ms** | 0.
|
|
38
|
-
| findUnique, user + posts + comments | **0.
|
|
39
|
-
| count, all users | **0.
|
|
40
|
-
| stream 50,000 comments, per row *(tie)* | 55.
|
|
41
|
-
| atomic increment | **0.
|
|
42
|
-
| pipeline, 5-query batch | **0.
|
|
43
|
-
| hot findUnique, rotating ids | **0.078 ms** | 0.
|
|
34
|
+
| findMany, 100 users | **0.208 ms** | 0.310 ms | 0.352 ms | 0.201 ms |
|
|
35
|
+
| findMany, 50 users + posts | **1.075 ms** | 1.485 ms | 2.955 ms | 0.854 ms |
|
|
36
|
+
| findMany, 10 users + posts + comments | **0.620 ms** | 0.884 ms | 2.270 ms | n/a |
|
|
37
|
+
| findUnique by primary key | **0.090 ms** | 0.149 ms | 0.179 ms | 0.075 ms |
|
|
38
|
+
| findUnique, user + posts + comments | **0.246 ms** | 0.460 ms | 0.599 ms | n/a |
|
|
39
|
+
| count, all users | **0.079 ms** | 0.114 ms | 0.169 ms | 0.078 ms |
|
|
40
|
+
| stream 50,000 comments, per row *(tie)* | 55.02 ms | 55.13 ms | 82.84 ms | 57.03 ms |
|
|
41
|
+
| atomic increment | **0.164 ms** | 0.182 ms | 0.259 ms | 0.135 ms |
|
|
42
|
+
| pipeline, 5-query batch | **0.343 ms** | 0.701 ms | 0.784 ms | 0.360 ms |
|
|
43
|
+
| hot findUnique, rotating ids | **0.078 ms** | 0.145 ms | 0.158 ms | 0.070 ms |
|
|
44
44
|
|
|
45
45
|
What that run says:
|
|
46
46
|
|
|
47
|
-
- **Across all ten scenarios Drizzle took 1.
|
|
48
|
-
- **Against hand-written `pg`, Turbine ran at 1.
|
|
47
|
+
- **Across all ten scenarios Drizzle took 1.49x as long as Turbine and Prisma 2.13x**, by geometric mean. Turbine won or tied every one against both (1 tie with Drizzle), and won or tied all 14 extra scenarios too.
|
|
48
|
+
- **Against hand-written `pg`, Turbine ran at 1.09x, Drizzle at 1.59x and Prisma at 2.13x** (geometric mean over the 8 scenarios with a control). Where a query returns nested rows, the control decodes them into objects with `Date` timestamps as the ORMs do. The nested read with posts is 1.26x the control, down from 1.86x in 0.91.0, because relation rows now decode in one pass.
|
|
49
49
|
- **Pipelining is the clearest win over a network**: five dashboard queries 25 ms from the database take 25 ms as one batch against 171 ms as a transaction.
|
|
50
50
|
- **Where Turbine loses:** deep `OFFSET` pagination unless `forceCustomPlan` is set, and per-row streaming against the Drizzle 1.0 release candidate (`findManyStreamBatches` ties it).
|
|
51
51
|
- Figures under 0.15 ms carry roughly one third uncertainty in their absolute values. Orderings held across runs; those margins should not be quoted.
|
|
52
52
|
|
|
53
|
-
Full method, the extra scenarios, streaming, latency and the losses: [`benchmarks/RESULTS-0.
|
|
53
|
+
Full method, the extra scenarios, streaming, latency and the losses: [`benchmarks/RESULTS-0.92.0.md`](https://github.com/zvndev/turbine-orm/blob/main/benchmarks/RESULTS-0.92.0.md), or the charts at [turbineorm.dev/benchmarks](https://turbineorm.dev/benchmarks).
|
|
54
54
|
|
|
55
55
|
Reproduce it on a fresh machine with `gh workflow run benchmarks.yml`, or locally with `benchmarks/run-round.sh` (see [`benchmarks/README.md`](benchmarks/README.md)).
|
|
56
56
|
|
package/dist/cjs/client.js
CHANGED
|
@@ -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
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
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)
|
package/dist/cjs/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/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; } });
|
package/dist/cjs/pipeline.js
CHANGED
|
@@ -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
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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>;
|