All files / third-parties/drizzle-adapter/src/ydb-core session.ts

90.81% Statements 89/98
78.43% Branches 40/51
100% Functions 28/28
90.62% Lines 87/96

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                                                                                        516x       321x                     31x       516x       516x       3x   3x 6x 3x     3x             494x                                   494x       19x                                           516x 516x 516x 516x 516x 516x       2x       1x       421x       421x 43x 48x   43x     378x 368x     10x           516x     516x 220x     516x 516x 516x           494x   22x         430x 409x       5x 5x       6x 6x 6x       75x 74x         19x                   81x 81x 81x                         516x                     236x 6x     230x           230x     230x       3x 2x     1x           1x     1x       4x 3x     1x                 74x 2x     72x                     2x   2x 4x         4x 4x 4x           2x       3x 3x 3x                                                 31x 1x     30x 30x 30x 30x         30x     3x 3x 3x              
/* oxlint-disable no-await-in-loop -- batch() runs queries sequentially by contract */
import { entityKind } from 'drizzle-orm/entity'
import { TransactionRollbackError } from 'drizzle-orm/errors'
import { type Logger, NoopLogger } from 'drizzle-orm/logger'
import type { RelationalSchemaConfig, TablesRelationalConfig } from 'drizzle-orm/relations'
import type { QueryWithTypings, SQL, SQLWrapper } from 'drizzle-orm/sql/sql'
import type { YdbDialect } from '../ydb/dialect.js'
import { mapYdbQueryError } from '../ydb/errors.js'
import type {
	YdbExecuteOptions,
	YdbExecutor,
	YdbQueryResult,
	YdbTransactionalExecutor,
} from '../ydb/driver.js'
import type { YdbTransactionConfig } from '../ydb/driver.js'
import { type YdbSelectedFieldsOrdered, mapResultRow, rowToArray } from './result-mapping.js'
import type {
	YdbSchemaDefinition,
	YdbSchemaRelations,
	YdbSchemaWithoutTables,
} from './schema.types.js'
import { YdbTransaction } from './transaction.js'
 
export interface YdbPreparedQueryConfig {
	execute: unknown
	all: unknown
	get: unknown
	values: unknown
}
 
export interface YdbSessionOptions {
	logger?: Logger | undefined
}
 
type SelectedFieldsOrdered = YdbSelectedFieldsOrdered
 
export type YdbQuerySource = SQL | SQLWrapper | QueryWithTypings
export type YdbBatchQuery = YdbQuerySource | YdbPreparedQuery | YdbRunnablePreparedQuery
 
type YdbRunnablePreparedQuery = {
	prepare(name?: string): Pick<YdbPreparedQuery, 'execute' | 'all' | 'get' | 'values'>
}
 
function isQueryWithTypings(query: YdbQuerySource): query is QueryWithTypings {
	return 'sql' in query && 'params' in query && Array.isArray(query.params)
}
 
function isRunnablePreparedQuery(query: unknown): query is SQLWrapper & YdbRunnablePreparedQuery {
	return (
		!!query &&
		typeof query === 'object' &&
		'prepare' in query &&
		typeof query.prepare === 'function'
	)
}
 
function supportsTransactions(
	client: YdbExecutor | YdbTransactionalExecutor
): client is YdbTransactionalExecutor {
	return 'transaction' in client && typeof client.transaction === 'function'
}
 
function normalizeQuery(query: YdbQuerySource, dialect: YdbDialect): QueryWithTypings {
	Iif (isQueryWithTypings(query)) {
		return query as QueryWithTypings
	}
 
	return dialect.sqlToQuery(query.getSQL())
}
 
function findTransactionRollbackError(error: unknown): TransactionRollbackError | undefined {
	let current = error
 
	while (current instanceof Error) {
		if (current instanceof TransactionRollbackError) {
			return current
		}
 
		current = current.cause
	}
 
	return undefined
}
 
function attachResultMeta(rows: unknown[], result: YdbQueryResult): unknown[] {
	Object.defineProperties(rows, {
		rowCount: {
			configurable: true,
			enumerable: false,
			value: result.rowCount,
		},
		command: {
			configurable: true,
			enumerable: false,
			value: result.command,
		},
		meta: {
			configurable: true,
			enumerable: false,
			value: result.meta,
		},
	})
 
	return rows
}
 
export class YdbPreparedQuery<T extends YdbPreparedQueryConfig = YdbPreparedQueryConfig> {
	static readonly [entityKind] = 'YdbPreparedQuery'
 
	readonly #client: YdbExecutor
	readonly #query: QueryWithTypings
	readonly #logger: Logger
	readonly #fields: SelectedFieldsOrdered | undefined
	readonly #responseInArrayMode: boolean
	readonly #customResultMapper:
		| ((rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => T['execute'])
		| undefined
 
	constructor(
		client: YdbExecutor,
		query: QueryWithTypings,
		logger: Logger,
		fields: SelectedFieldsOrdered | undefined,
		responseInArrayMode: boolean,
		customResultMapper?: (
			rows: unknown[][],
			mapColumnValue?: (value: unknown) => unknown
		) => T['execute']
	) {
		this.#client = client
		this.#query = query
		this.#logger = logger
		this.#fields = fields
		this.#responseInArrayMode = responseInArrayMode
		this.#customResultMapper = customResultMapper
	}
 
	getQuery(): QueryWithTypings {
		return this.#query
	}
 
	isResponseInArrayMode(): boolean {
		return this.#responseInArrayMode
	}
 
	mapResult(response: unknown, _isFromBatch?: boolean): unknown {
		Iif (!Array.isArray(response)) {
			return response
		}
 
		if (this.#customResultMapper) {
			let rows = this.#fields
				? response.map((row) => rowToArray(this.#fields as any, row as any))
				: (response as unknown[][])
			return this.#customResultMapper(rows as unknown[][], (value) => value)
		}
 
		if (!this.#fields) {
			return response
		}
 
		return (response as Array<unknown[] | Record<string, unknown>>).map((row) =>
			mapResultRow(this.#fields as any, row, undefined)
		)
	}
 
	async #run(method: 'execute' | 'all', arrayMode: boolean): Promise<unknown[]> {
		let options: YdbExecuteOptions = {
			arrayMode,
		}
		if (this.#query.typings !== undefined) {
			options.typings = this.#query.typings
		}
 
		this.#logger.logQuery(this.#query.sql, this.#query.params)
		try {
			let result = await this.#client.execute(
				this.#query.sql,
				this.#query.params,
				method,
				options
			)
			return attachResultMeta(result.rows, result)
		} catch (error) {
			throw mapYdbQueryError(this.#query.sql, this.#query.params, error)
		}
	}
 
	async execute(): Promise<T['execute']> {
		let rows = await this.#run('execute', this.#responseInArrayMode)
		return this.mapResult(rows) as T['execute']
	}
 
	async all(): Promise<T['all']> {
		let rows = await this.#run('all', this.#responseInArrayMode)
		return this.mapResult(rows) as T['all']
	}
 
	async get(): Promise<T['get']> {
		let rows = await this.#run('all', this.#responseInArrayMode)
		let result = this.mapResult(rows)
		return (Array.isArray(result) ? result[0] : result) as T['get']
	}
 
	async values(): Promise<T['values']> {
		let rows = await this.#run('all', true)
		return rows as T['values']
	}
}
 
export class YdbSession {
	static readonly [entityKind] = 'YdbSession'
	readonly #logger: Logger
	readonly #client: YdbExecutor | YdbTransactionalExecutor
	readonly #dialect: YdbDialect
 
	constructor(
		client: YdbExecutor | YdbTransactionalExecutor,
		dialect: YdbDialect,
		options: YdbSessionOptions = {}
	) {
		this.#client = client
		this.#dialect = dialect
		this.#logger = options.logger ?? new NoopLogger()
	}
 
	prepareQuery<T extends YdbPreparedQueryConfig = YdbPreparedQueryConfig>(
		query: YdbQuerySource,
		fields?: SelectedFieldsOrdered,
		_name?: string,
		isResponseInArrayMode = false,
		customResultMapper?: (
			rows: unknown[][],
			mapColumnValue?: (value: unknown) => unknown
		) => T['execute']
	): YdbPreparedQuery<T> {
		return new YdbPreparedQuery<T>(
			this.#client,
			normalizeQuery(query, this.#dialect),
			this.#logger,
			fields,
			isResponseInArrayMode,
			customResultMapper
		)
	}
 
	async execute<T = unknown>(query: YdbQuerySource, options?: YdbExecuteOptions): Promise<T> {
		if (isRunnablePreparedQuery(query)) {
			return query.prepare().execute() as Promise<T>
		}
 
		let prepared = this.prepareQuery<YdbPreparedQueryConfig & { execute: T }>(
			query,
			undefined,
			undefined,
			false
		)
		Iif (options?.arrayMode === true) {
			return prepared.values() as Promise<T>
		}
		return prepared.execute() as Promise<T>
	}
 
	async all<T = unknown>(query: YdbQuerySource, options?: YdbExecuteOptions): Promise<T[]> {
		if (isRunnablePreparedQuery(query)) {
			return query.prepare().all() as Promise<T[]>
		}
 
		let prepared = this.prepareQuery<YdbPreparedQueryConfig & { all: T[] }>(
			query,
			undefined,
			undefined,
			false
		)
		Iif (options?.arrayMode === true) {
			return prepared.values() as Promise<T[]>
		}
		return prepared.all() as Promise<T[]>
	}
 
	async get<T = unknown>(query: YdbQuerySource): Promise<T> {
		if (isRunnablePreparedQuery(query)) {
			return query.prepare().get() as Promise<T>
		}
 
		return this.prepareQuery<YdbPreparedQueryConfig & { get: T }>(
			query,
			undefined,
			undefined,
			false
		).get()
	}
 
	async values<T extends unknown[] = unknown[]>(query: YdbQuerySource): Promise<T[]> {
		if (isRunnablePreparedQuery(query)) {
			return query.prepare().values() as Promise<T[]>
		}
 
		return this.prepareQuery<YdbPreparedQueryConfig & { values: T[] }>(
			query,
			undefined,
			undefined,
			true
		).values()
	}
 
	async batch<T extends readonly YdbBatchQuery[]>(
		queries: T
	): Promise<{ [K in keyof T]: unknown }> {
		let results: unknown[] = []
 
		for (let query of queries) {
			Iif (query instanceof YdbPreparedQuery) {
				results.push(await query.execute())
				continue
			}
 
			Eif (isRunnablePreparedQuery(query)) {
				results.push(await query.prepare().execute())
				continue
			}
 
			results.push(await this.execute(query as YdbQuerySource))
		}
 
		return results as { [K in keyof T]: unknown }
	}
 
	async count(query: YdbQuerySource): Promise<number> {
		let rows = await this.values<[number | bigint | string]>(query)
		let value = rows[0]?.[0]
		return Number(value ?? 0)
	}
 
	async transaction<T>(
		transaction: (tx: YdbTransaction) => Promise<T>,
		config?: YdbTransactionConfig
	): Promise<T>
	async transaction<
		T,
		TSchemaDefinition extends YdbSchemaDefinition = YdbSchemaWithoutTables,
		TSchemaRelations extends TablesRelationalConfig = YdbSchemaRelations<TSchemaDefinition>,
	>(
		transaction: (tx: YdbTransaction<TSchemaDefinition, TSchemaRelations>) => Promise<T>,
		config: YdbTransactionConfig | undefined,
		schema: RelationalSchemaConfig<TSchemaRelations> | undefined
	): Promise<T>
	async transaction<
		T,
		TSchemaDefinition extends YdbSchemaDefinition = YdbSchemaWithoutTables,
		TSchemaRelations extends TablesRelationalConfig = YdbSchemaRelations<TSchemaDefinition>,
	>(
		transaction: (tx: YdbTransaction<TSchemaDefinition, TSchemaRelations>) => Promise<T>,
		config?: YdbTransactionConfig,
		schema?: RelationalSchemaConfig<TSchemaRelations>
	): Promise<T> {
		if (!supportsTransactions(this.#client)) {
			throw new Error('Transactions are not supported')
		}
 
		try {
			return await this.#client.transaction(async (txClient) => {
				let session = new YdbSession(txClient, this.#dialect, { logger: this.#logger })
				let tx = new YdbTransaction<TSchemaDefinition, TSchemaRelations>(
					this.#dialect,
					session,
					schema
				)
				return transaction(tx)
			}, config)
		} catch (error) {
			let rollbackError = findTransactionRollbackError(error)
			Eif (rollbackError) {
				throw rollbackError
			}
 
			throw error
		}
	}
}