Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | 23x 23x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 120x 120x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 11x 11x 11x 1x 1x 564x 564x 565x 526x 526x 565x 565x 565x 565x 565x 565x 526x 564x 564x 564x 564x 473x 564x 38x 526x 564x 564x 564x 564x 564x 564x 564x 567x 567x 11x 11x 556x 556x 380x 176x 176x 176x 232x 232x 667x 667x 667x 242x 242x 425x 232x 12x 1x 12x 552x 552x 564x 552x 552x 552x 12x 12x 564x 564x 564x 564x 564x 1692x 1692x 1692x 1418x 1418x 1692x 352x 352x 352x 352x 85x 85x | import { EventEmitter } from 'node:events'
import { tracingChannel } from 'node:diagnostics_channel'
import { create } from '@bufbuild/protobuf'
import { StatusIds_StatusCode } from '@ydbjs/api/operation'
import {
ExecMode,
QueryServiceDefinition,
type QueryStats,
StatsMode,
Syntax,
type TransactionControl,
TransactionControlSchema,
} from '@ydbjs/api/query'
import { type TypedValue, TypedValueSchema } from '@ydbjs/api/value'
import type { Driver, DriverIdentity } from '@ydbjs/core'
import { loggers } from '@ydbjs/debug'
import { YDBError } from '@ydbjs/error'
import {
type RetryConfig,
type RetryContext,
defaultRetryConfig,
isRetryableError,
retry,
} from '@ydbjs/retry'
import { type Value, fromYdb, toJs } from '@ydbjs/value'
import { typeToString } from '@ydbjs/value/print'
import type { Metadata } from 'nice-grpc'
import { ctx } from './ctx.js'
import { linkSignals } from '@ydbjs/abortable'
import { type SessionPool, sessionAcquireCh } from './session-pool.js'
type QueryExecuteContext = {
driver: DriverIdentity
text: string
sessionId: string
nodeId: bigint
idempotent: boolean
isolation: string
}
let executeQueryCh = tracingChannel<QueryExecuteContext, QueryExecuteContext>(
'tracing:ydb:query.execute'
)
let dbg = loggers.query
// Utility type to convert a tuple of types to a tuple of arrays of those types
type ArrayifyTuple<T extends any[]> = {
[K in keyof T]: T[K][]
}
export type QueryEventMap = {
done: [ArrayifyTuple<any>]
retry: [RetryContext]
error: [unknown]
stats: [QueryStats]
cancel: []
metadata: [Metadata]
}
export class Query<T extends any[] = unknown[]>
extends EventEmitter<QueryEventMap>
implements PromiseLike<ArrayifyTuple<T>>, AsyncDisposable
{
#driver: Driver
#sessionPool: SessionPool
#promise: Promise<ArrayifyTuple<T>> | null = null
#text: string
#parameters: Record<string, Value>
#idempotent: boolean = false
#active: boolean = false
#disposed: boolean = false
#cancelled: boolean = false
#controller: AbortController = new AbortController()
#signal: AbortSignal | undefined
#timeout: number | undefined
#syntax: Syntax = Syntax.YQL_V1
#poolId: string | undefined
#stats: QueryStats | undefined
#statsMode: StatsMode = StatsMode.UNSPECIFIED
#isolation:
| 'implicit'
| 'serializableReadWrite'
| 'snapshotReadOnly'
| 'snapshotReadWrite'
| 'onlineReadOnly'
| 'staleReadOnly' = 'implicit'
#isolationSettings: { allowInconsistentReads: boolean } | {} = {}
#raw: boolean = false
#values: boolean = false
constructor(
driver: Driver,
text: string,
params: Record<string, Value>,
sessionPool: SessionPool
) {
super()
this.#text = text
this.#driver = driver
this.#sessionPool = sessionPool
this.#parameters = {}
for (let key in params) {
// oxlint-disable no-unused-expressions
key.startsWith('$') || (key = '$' + key)
this.#parameters[key] = params[key]!
}
}
static get [Symbol.species]() {
return Promise
}
async #execute(): Promise<ArrayifyTuple<T>> {
let store = ctx.getStore() || {}
// `txSession` is set only when we run inside a transaction — the tx
// body owns the session. Outside a transaction it stays undefined and
// every retry attempt grabs a fresh lease from the pool. Treating
// this as closure-local (vs mutating per attempt) prevents a released
// session from being reused across retries by a different caller.
let txSession = store.session
let transactionId = store.transactionId
let txSignal = store.signal
Iif (this.#disposed) {
dbg.log('query disposed, aborting execution')
throw new Error('Query has been disposed.')
}
// If we already have a promise, return it without executing the query again
Iif (this.#promise) {
dbg.log('query already has a promise, returning cached result')
return this.#promise
}
Iif (this.#active) {
dbg.log('query is already executing, aborting')
throw new Error('Query is already executing.')
}
dbg.log('starting query execution: %s', this.text)
this.#active = true
let signals: AbortSignal[] = [this.#controller.signal]
if (txSignal) signals.push(txSignal)
Iif (this.#signal) signals.push(this.#signal)
Iif (this.#timeout) signals.push(AbortSignal.timeout(this.#timeout))
let linkedSignal = linkSignals(...signals)
let sessionDiedLastAttempt = false
let retryConfig: RetryConfig = {
...defaultRetryConfig,
signal: linkedSignal.signal,
idempotent: this.#idempotent,
retry: (error, idempotent) => {
let sessionDied = sessionDiedLastAttempt
sessionDiedLastAttempt = false
// A session abort mid-call is only a safe reason to retry if
// the operation itself is idempotent — otherwise we can't tell
// whether the server applied it before the stream dropped.
return isRetryableError(error, idempotent) || (sessionDied && idempotent)
},
onRetry: (retryCtx) => {
dbg.log('retrying query, attempt %d, error: %O', retryCtx.attempt, retryCtx.error)
this.emit('retry', retryCtx)
},
}
await this.#driver.ready(linkedSignal.signal)
let runAttempt = async (retrySignal: AbortSignal) => {
// Transaction-owned session stays pinned; out-of-transaction
// attempts always get a fresh lease — no cross-attempt reuse.
using sessionLease = txSession
? undefined
: await sessionAcquireCh.tracePromise(
() => this.#sessionPool.acquire(retrySignal),
{ driver: this.#driver.identity }
)
let session = txSession ?? sessionLease!.session
let attemptSessionId = session.id
let attemptNodeId = session.nodeId
// Single-threaded session guard. YDB processes RPCs on a session
// sequentially, so concurrent statements on the same session
// (e.g. `Promise.all([tx`a`, tx`b`])`) hang on a server-side lock
// and confuse retry semantics. `claim()` throws SessionBusyError
// (non-retryable) and is released on scope exit via `using`.
using _claim = session.claim()
// linkSignals cleans up listeners on dispose — no accumulation
// on the long-lived session signal across many queries. We link to
// `session.signal` directly: in a tx body there's no lease (the tx
// owns the session), so the lease-mirrored signal isn't available.
using linked = linkSignals(retrySignal, session.signal)
let signal = linked.signal
if (sessionLease) {
dbg.log('acquired session %s from pool', sessionLease.id)
}
dbg.log('creating query client for nodeId: %s', attemptNodeId)
let client = this.#driver.createClient(QueryServiceDefinition, attemptNodeId)
let parameters: Record<string, TypedValue> = {}
for (let key in this.#parameters) {
parameters[key] = create(TypedValueSchema, {
type: this.#parameters[key]!.type.encode(),
value: this.#parameters[key]!.encode(),
})
}
// If we have a transactionId, we should use it
// If we have an isolation level, we should use it
let txControl: TransactionControl | undefined
if (transactionId) {
txControl = create(TransactionControlSchema, {
txSelector: {
case: 'txId',
value: transactionId,
},
})
} else Iif (this.#isolation !== 'implicit') {
txControl = create(TransactionControlSchema, {
commitTx: true,
txSelector: {
case: 'beginTx',
value: {
txMode: {
case: this.#isolation,
value: this.#isolationSettings as {},
},
},
},
})
}
let executeCtx: QueryExecuteContext = {
driver: this.#driver.identity,
text: this.text,
sessionId: attemptSessionId,
nodeId: attemptNodeId,
idempotent: this.#idempotent,
isolation: this.#isolation,
}
return await executeQueryCh.tracePromise(async () => {
let stream = client.executeQuery(
{
sessionId: attemptSessionId,
execMode: ExecMode.EXECUTE,
query: {
case: 'queryContent',
value: {
syntax: this.#syntax,
text: this.text,
},
},
parameters,
statsMode: this.#statsMode,
...(this.#poolId && { poolId: this.#poolId }),
...(txControl && { txControl }),
},
{
signal,
onTrailer: (trailer) => {
this.emit('metadata', trailer)
},
}
)
let results = [] as ArrayifyTuple<T>
try {
for await (let part of stream) {
signal.throwIfAborted()
if (part.status !== StatusIds_StatusCode.SUCCESS) {
dbg.log('query part failed, status: %d', part.status)
throw new YDBError(part.status, part.issues)
}
Iif (part.execStats) {
dbg.log('received query stats')
this.#stats = part.execStats
}
if (!part.resultSet) {
continue
}
while (part.resultSetIndex >= results.length) {
results.push([])
}
for (let i = 0; i < part.resultSet.rows.length; i++) {
let result: any = this.#values ? [] : {}
for (let j = 0; j < part.resultSet.columns.length; j++) {
let column = part.resultSet.columns[j]!
let value = part.resultSet.rows[i]!.items[j]!
if (this.#values) {
result.push(
this.#raw ? value : toJs(fromYdb(value, column.type!))
)
continue
}
result[column.name] = this.#raw
? value
: toJs(fromYdb(value, column.type!))
}
results[Number(part.resultSetIndex)]!.push(result)
}
}
} catch (err) {
// Record whether this attempt failed because the session died.
// The retry callback uses this to decide — together with the
// idempotent flag — whether to retry against a fresh session.
if (session.signal.aborted) {
sessionDiedLastAttempt = true
}
throw err
}
dbg.log('query executed successfully')
return results
}, executeCtx)
}
// Inside a transaction body, the txn callback (`sql.begin()`) owns the
// retry loop — retrying a single statement against the same
// `transactionId` after a server-side abort cannot recover the
// transaction. Skip the retry wrapper entirely; the tx retries the
// whole body if it needs to.
this.#promise = (
txSession ? runAttempt(linkedSignal.signal) : retry(retryConfig, runAttempt)
)
.then((results) => {
Iif (this.#stats) {
this.emit('stats', this.#stats)
}
this.emit('done', results)
return results
})
.catch((err) => {
this.emit('error', err)
throw err
})
.finally(async () => {
this.#active = false
this.#controller.abort('Query completed.')
linkedSignal[Symbol.dispose]()
})
return this.#promise
}
/** Returns the result of the query */
then<TResult1 = ArrayifyTuple<T>, TResult2 = never>(
onfulfilled?: (value: ArrayifyTuple<T>) => TResult1 | PromiseLike<TResult1>,
onrejected?: (reason: unknown) => TResult2 | PromiseLike<TResult2>
): Promise<TResult1 | TResult2> {
return this.#execute().then(onfulfilled, onrejected)
}
/** Indicates if the query is currently executing */
get active(): boolean {
return this.#active
}
/** Indicates if the query has been cancelled */
get cancelled(): boolean {
return this.#cancelled
}
get text(): string {
let queryText = this.#text
Eif (this.#parameters) {
for (let [name, value] of Object.entries(this.#parameters)) {
// oxlint-disable no-unused-expressions
name.startsWith('$') || (name = '$' + name)
queryText = `DECLARE ${name} AS ${typeToString(value.type)};\n` + queryText
}
}
return queryText
}
get parameters(): Record<string, Value> {
return this.#parameters
}
syntax(syntax: Exclude<Syntax, Syntax.UNSPECIFIED>): Query<T> {
this.#syntax = syntax
return this
}
pool(poolId: string): Query<T> {
this.#poolId = poolId
return this
}
/** Adds a parameter to the query */
parameter(name: string, parameter: Value | undefined): Query<T> {
name.startsWith('$') || (name = '$' + name)
Iif (parameter === undefined) {
delete this.#parameters[name]
return this
}
this.#parameters[name] = parameter
return this
}
/** Adds a parameter to the query */
param(name: string, parameter: Value | undefined): Query<T> {
return this.parameter(name, parameter)
}
/**
* Sets the idempotent flag for the query.
*
* ONLY FOR SINGLE EXECUTE CALLS.
* DO NOTHING IN TRANSACTION CONTEXT (sql.begin or sql.transaction).
*
* Idempotent queries may be retried without side effects.
*/
idempotent(idempotent: boolean = true): Query<T> {
this.#idempotent = idempotent
return this
}
/**
* Sets the transaction isolation level for a single execute call.
*
* ONLY FOR SINGLE EXECUTE CALLS.
* DO NOTHING IN TRANSACTION CONTEXT (sql.begin or sql.transaction).
*
* A transaction is always used. If `mode` is 'implicit', the database decides the isolation level.
* If a specific isolation `mode` is provided, the query will be executed within a single transaction (with inline begin and commit)
* using the specified isolation level.
*
* @param mode Transaction isolation level:
* - 'serializableReadWrite' — serializable read/write
* - 'snapshotReadOnly' — snapshot read-only
* - 'snapshotReadWrite' — snapshot read/write
* - 'onlineReadOnly' — online read-only
* - 'staleReadOnly' — stale read-only
* - 'implicit' — isolation is not set, server decides
* - 'implicit' is the default value
* @param settings Additional options, e.g., allowInconsistentReads — allow inconsistent reads only with 'onlineReadOnly'
* @returns The current instance for chaining
*/
isolation(
mode:
| 'implicit'
| 'serializableReadWrite'
| 'snapshotReadOnly'
| 'snapshotReadWrite'
| 'onlineReadOnly'
| 'staleReadOnly',
settings: { allowInconsistentReads: boolean } | {} | undefined = {}
) {
this.#isolation = mode
this.#isolationSettings = settings
return this
}
/** Returns the query execution statistics */
// TODO: Return user-friendly stats report
stats(): QueryStats | undefined {
return this.#stats
}
/** Returns a query with statistics enabled */
withStats(mode: Exclude<StatsMode, StatsMode.UNSPECIFIED>): Query<T> {
this.#statsMode = mode
return this as Query<T>
}
/** Sets the query timeout */
timeout(timeout: number): Query<T> {
this.#timeout = timeout
return this
}
/** Cancels the executing query */
cancel(): Query<T> {
this.#controller.abort('Query cancelled by user.')
this.#cancelled = true
this.emit('cancel')
return this
}
signal(signal: AbortSignal): Query<T> {
this.#signal = signal
return this
}
/** Executes the query */
execute(): Query<T> {
void this.#execute()
return this
}
/** Returns only the values from the query result */
values(): Query<[unknown][]> {
this.#values = true
return this
}
/** Returns raw values */
raw(): Query<T> {
this.#raw = true
return this
}
/**
* Disposes the query and releases all resources.
* This method is called automatically when the query is done.
* It is recommended to call this method explicitly when the query is no longer needed.
*/
async dispose(): Promise<void> {
if (this.#disposed) {
return
}
this.#controller.abort('Query disposed.')
this.#promise = null
this.#disposed = true
}
[Symbol.dispose](): void {
this.dispose()
}
async [Symbol.asyncDispose](): Promise<void> {
await this.dispose()
}
}
|