All files / third-parties/drizzle-adapter/src/ydb-core/query-builders select.builder.ts

82.99% Statements 205/247
67.77% Branches 122/180
89.47% Functions 51/57
83.26% Lines 204/245

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 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671                                                                                                26x           115x   115x                                 115x 115x   115x 66x 66x 66x               66x     49x 49x 49x                     113x 1x     112x       113x   113x       112x             49x           49x       14x       97x               49x       97x           28x       1150x 10x       10x 10x   10x             10x 2x       2x         2x 2x         10x   10x 10x     10x             10x 10x   3x 3x   1x 1x   1x 1x   1x 1x   1x 1x     2x 2x       10x         2x       2x 2x 2x   2x 2x           2x 2x       2x   6x       6x           2x       2x 2x       2x 2x               2x       2x       2x             2x       2x 3x 2x     1x       1x         460x           4x       4x           4x 4x 4x     4x           4x         111x 111x   111x 30x 30x         111x   111x       2x       2x       85x       61x       61x       2x       2x       5x             5x 5x 5x       2x             2x 2x 2x       17x   17x       17x 3x 3x         3x     14x 14x       2x       2x     2x 2x       8x 8x       8x       3x 3x       3x       2x       2x       2x       2x       2x     2x 2x 2x               2x                               2x 2x     2x 2x       2x     2x 2x   2x 1x     2x 2x       1x 1x       2x       2x 2x       2x 2x       1x 1x       2x     2x       2x       2x       3x 1x     2x 2x       5x 1x     4x     5x       4x 4x     115x 115x 115x 115x 115x 115x 115x 115x 115x 115x   115x 115x 115x 115x     3x   3x 3x 3x       3x 3x       113x 113x 113x   113x               3x 3x       49x 49x   49x     49x 49x   49x                   37x      
import { entityKind, is } from 'drizzle-orm/entity'
import { Column } from 'drizzle-orm/column'
import { QueryPromise } from 'drizzle-orm/query-promise'
import { SQL, type SQLWrapper, sql as yql } from 'drizzle-orm/sql/sql'
import type { Subquery } from 'drizzle-orm/subquery'
import { haveSameKeys } from 'drizzle-orm/utils'
import { mapResultRow, orderSelectedFields } from '../result-mapping.js'
import type { YdbPreparedQueryConfig, YdbSession } from '../session.js'
import { YdbDialect } from '../../ydb/dialect.js'
import type {
	YdbJoinType,
	YdbSelectConfig,
	YdbSetOperatorConfig,
	YdbSetOperatorSource,
} from '../../ydb/dialect.types.js'
import { getSetOperatorHelpers } from './select.set-operators.js'
import type {
	SelectConfigWithTable,
	SelectFields,
	YdbSelectBuilderOptions,
} from './select.types.js'
import {
	createSelectionProxy,
	getSourceSelection,
	getTableLikeName,
	normalizeCountValue,
	normalizeSqlWrapperArray,
} from './select.utils.js'
import {
	type YdbFlattenMode,
	type YdbMatchRecognizeConfig,
	type YdbUniqueDistinctHint,
	type YdbValuesOptions,
	type YdbValuesRow,
	type YdbWindowClause,
	type YdbWindowDefinitionConfig,
	asTable,
	valuesTable,
	windowDefinition,
} from './select-syntax.js'
 
type SelectionCallback = (fields: any) => SQLWrapper | SQLWrapper[]
type InternalSelectConfig = Omit<YdbSelectConfig, 'table'> & { table?: unknown }
 
export class YdbSelectBuilder<TResult = unknown[]>
	extends QueryPromise<TResult>
	implements YdbSetOperatorSource
{
	static override readonly [entityKind] = 'YdbSelectBuilder'
 
	readonly #session: YdbSession | undefined
	readonly #dialect: YdbDialect
	readonly #config: InternalSelectConfig
	readonly #isPartialSelect: boolean
	#joinsNotNullableMap: Record<string, boolean> = {}
	#tableName: string | undefined
	#usedInSetOperation = false
 
	constructor(session: YdbSession | undefined, fields?: SelectFields)
	constructor(
		session: YdbSession | undefined,
		dialect: YdbDialect,
		fields?: SelectFields,
		options?: YdbSelectBuilderOptions,
		withList?: Subquery[]
	)
	constructor(
		session: YdbSession | undefined,
		dialectOrFields?: YdbDialect | SelectFields,
		fieldsOrUndefined?: SelectFields,
		options: YdbSelectBuilderOptions = {},
		withList: Subquery[] = []
	) {
		super()
		this.#session = session
 
		if (dialectOrFields instanceof YdbDialect) {
			this.#dialect = dialectOrFields
			this.#isPartialSelect = fieldsOrUndefined !== undefined
			this.#config = {
				table: undefined,
				fields: fieldsOrUndefined ? { ...fieldsOrUndefined } : {},
				withList,
				distinct: options.distinct,
				distinctOn: options.distinctOn,
				setOperators: [],
			}
			return
		}
 
		this.#dialect = new YdbDialect()
		this.#isPartialSelect = dialectOrFields !== undefined
		this.#config = {
			table: undefined,
			fields: dialectOrFields ? { ...(dialectOrFields as SelectFields) } : {},
			withList,
			distinct: false,
			distinctOn: undefined,
			setOperators: [],
		}
	}
 
	#requireTable(): unknown | undefined {
		if (this.#config.table === undefined && Object.keys(this.#config.fields).length === 0) {
			throw new Error('Missing table in select().from()')
		}
 
		return this.#config.table
	}
 
	#requireConfigWithTable(): SelectConfigWithTable {
		let table = this.#requireTable()
 
		Iif (Object.keys(this.#config.fields).length === 0) {
			throw new Error('YDB select() selected zero columns')
		}
 
		return {
			...this.#config,
			table,
		}
	}
 
	#requireSession(): YdbSession {
		Iif (!this.#session) {
			throw new Error(
				'Cannot execute a query on a query builder. Please use a database instance instead.'
			)
		}
 
		return this.#session
	}
 
	#markUsedInSetOperation(): void {
		this.#usedInSetOperation = true
	}
 
	#shouldUseSelectionAliases(): boolean {
		return (
			this.#usedInSetOperation ||
			(this.#config.joins?.length ?? 0) > 0 ||
			(this.#config.distinctOn?.length ?? 0) > 0
		)
	}
 
	#getOrderedFields() {
		return orderSelectedFields(this.getSelectedFields())
	}
 
	#getSelectionAliases(fields = this.#getOrderedFields()): string[] | undefined {
		return this.#shouldUseSelectionAliases()
			? this.#dialect.getSelectionAliases(fields)
			: undefined
	}
 
	#getTargetConfigForTailClauses(): YdbSetOperatorConfig | InternalSelectConfig {
		return this.#config.setOperators[this.#config.setOperators.length - 1] ?? this.#config
	}
 
	#createJoin(joinType: YdbJoinType) {
		return (table: unknown, on?: SQL | ((fields: SelectFields) => SQL)) => {
			Iif (this.#config.without && this.#config.without.length > 0) {
				throw new Error('YDB without() cannot be combined with joins')
			}
 
			let baseTableName = this.#tableName
			let tableName = getTableLikeName(table)
 
			Iif (
				typeof tableName === 'string' &&
				this.#config.joins?.some((join) => join.alias === tableName)
			) {
				throw new Error(`Alias "${tableName}" is already used in this query`)
			}
 
			if (!this.#isPartialSelect) {
				Eif (
					Object.keys(this.#joinsNotNullableMap).length === 1 &&
					typeof baseTableName === 'string'
				) {
					this.#config.fields = {
						[baseTableName]: this.#config.fields,
					}
				}
 
				Eif (typeof tableName === 'string' && !is(table, SQL)) {
					this.#config.fields[tableName] = getSourceSelection(table)
				}
			}
 
			let resolvedOn =
				typeof on === 'function' ? on(createSelectionProxy(this.#config.fields, 'sql')) : on
 
			Eif (!this.#config.joins) {
				this.#config.joins = []
			}
 
			this.#config.joins.push({
				table,
				joinType,
				alias: tableName,
				on: resolvedOn,
			})
 
			Eif (typeof tableName === 'string') {
				switch (joinType) {
					case 'left':
						this.#joinsNotNullableMap[tableName] = false
						break
					case 'right':
						this.#joinsNotNullableMap = Object.fromEntries(
							Object.keys(this.#joinsNotNullableMap).map((key) => [key, false])
						)
						this.#joinsNotNullableMap[tableName] = true
						break
					case 'full':
						this.#joinsNotNullableMap = Object.fromEntries(
							Object.keys(this.#joinsNotNullableMap).map((key) => [key, false])
						)
						this.#joinsNotNullableMap[tableName] = false
						break
					case 'inner':
					case 'cross':
						this.#joinsNotNullableMap[tableName] = true
						break
				}
			}
 
			return this
		}
	}
 
	#applyWithoutToFields(values: readonly (string | SQLWrapper)[]): void {
		Iif (Object.keys(this.#config.fields).length === 0) {
			return
		}
 
		let fieldEntries = Object.entries(this.#config.fields)
		let removedKeys = new Set<string>()
		let removedColumnNames = new Set<string>()
 
		for (let value of values) {
			Iif (typeof value === 'string') {
				removedKeys.add(value)
				removedColumnNames.add(value)
				continue
			}
 
			Eif (is(value, Column)) {
				removedColumnNames.add(value.name)
			}
		}
 
		this.#config.fields = Object.fromEntries(
			fieldEntries.filter(([key, field]) => {
				Iif (removedKeys.has(key)) {
					return false
				}
 
				return !(is(field, Column) && removedColumnNames.has(field.name))
			})
		)
	}
 
	#normalizeWithout(values: readonly (string | SQLWrapper)[]): SQLWrapper[] {
		Iif (values.length === 0) {
			throw new Error('YDB without() requires at least one column')
		}
 
		return values.map((value) => {
			Iif (typeof value === 'string') {
				return yql.identifier(value)
			}
 
			Eif (is(value, Column)) {
				return yql.identifier(value.name)
			}
 
			return value
		})
	}
 
	#setFlatten(mode: YdbFlattenMode, expressions: readonly SQLWrapper[] = []): this {
		Iif (mode !== 'columns' && expressions.length === 0) {
			throw new Error('YDB flatten requires at least one expression')
		}
 
		this.#config.flatten = {
			mode,
			expressions: expressions.length > 0 ? [...expressions] : undefined,
		}
		return this
	}
 
	#normalizeColumnExpressions(
		values: readonly (string | SQLWrapper)[],
		context: string
	): SQLWrapper[] {
		Iif (values.length === 0) {
			throw new Error(`YDB ${context} requires at least one column`)
		}
 
		return values.map((value) => {
			if (typeof value === 'string') {
				return yql.identifier(value)
			}
 
			Iif (is(value, Column)) {
				return yql.identifier(value.name)
			}
 
			return value
		})
	}
 
	#createSetOperator(type: 'union' | 'intersect' | 'except', isAll: boolean) {
		return (
			rightSelection:
				| YdbSetOperatorSource
				| ((operators: ReturnType<typeof getSetOperatorHelpers>) => YdbSetOperatorSource)
		) => {
			let rightSelect =
				typeof rightSelection === 'function'
					? rightSelection(getSetOperatorHelpers())
					: rightSelection
 
			Iif (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
				throw new Error(
					'Set operator error (union / intersect / except): selected fields are not the same or are in a different order'
				)
			}
 
			this.#markUsedInSetOperation()
			Eif (rightSelect instanceof YdbSelectBuilder) {
				rightSelect.#markUsedInSetOperation()
			}
 
			this.#config.setOperators.push({
				type,
				isAll,
				rightSelect,
			})
 
			return this
		}
	}
 
	from(source: unknown): this {
		this.#config.table = source
		this.#tableName = getTableLikeName(source)
 
		if (!this.#isPartialSelect) {
			this.#config.fields = getSourceSelection(source)
			Iif (this.#config.without && this.#config.without.length > 0) {
				this.#applyWithoutToFields(this.#config.without)
			}
		}
 
		this.#joinsNotNullableMap =
			typeof this.#tableName === 'string' ? { [this.#tableName]: true } : {}
		return this
	}
 
	fromAsTable(binding: string | SQLWrapper, alias?: string): this {
		return this.from(asTable(binding, alias))
	}
 
	fromValues(rows: readonly YdbValuesRow[], options?: YdbValuesOptions): this {
		return this.from(valuesTable(rows, options))
	}
 
	getSelectedFields(): SelectFields {
		return this.#config.fields
	}
 
	where(where: SQL | ((fields: SelectFields) => SQL) | undefined): this {
		this.#config.where =
			typeof where === 'function'
				? where(createSelectionProxy(this.#config.fields, 'sql'))
				: (where ?? undefined)
		return this
	}
 
	having(having: SQL | ((fields: SelectFields) => SQL) | undefined): this {
		this.#config.having =
			typeof having === 'function'
				? having(createSelectionProxy(this.#config.fields, 'sql'))
				: (having ?? undefined)
		return this
	}
 
	groupBy(...columns: SQLWrapper[] | [SelectionCallback]): this {
		Iif (typeof columns[0] === 'function') {
			let groupBy = columns[0](createSelectionProxy(this.#config.fields, 'alias'))
			this.#config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]
			this.#config.groupByCompact = false
			return this
		}
 
		this.#config.groupBy = columns as SQLWrapper[]
		this.#config.groupByCompact = false
		return this
	}
 
	groupCompactBy(...columns: SQLWrapper[] | [SelectionCallback]): this {
		Iif (typeof columns[0] === 'function') {
			let groupBy = columns[0](createSelectionProxy(this.#config.fields, 'alias'))
			this.#config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]
			this.#config.groupByCompact = true
			return this
		}
 
		this.#config.groupBy = columns as SQLWrapper[]
		this.#config.groupByCompact = true
		return this
	}
 
	orderBy(...columns: SQLWrapper[] | [SelectionCallback]): this {
		let target = this.#getTargetConfigForTailClauses()
 
		Iif (target === this.#config && this.#config.assumeOrderBy?.length) {
			throw new Error('YDB orderBy() cannot be combined with assumeOrderBy()')
		}
 
		if (typeof columns[0] === 'function') {
			let orderBy = columns[0](createSelectionProxy(this.#config.fields, 'alias'))
			;(target as YdbSetOperatorConfig | InternalSelectConfig).orderBy = Array.isArray(
				orderBy
			)
				? orderBy
				: [orderBy]
			return this
		}
 
		;(target as YdbSetOperatorConfig | InternalSelectConfig).orderBy = columns as SQLWrapper[]
		return this
	}
 
	assumeOrderBy(...columns: (string | SQLWrapper)[] | [(string | SQLWrapper)[]]): this {
		Iif (this.#config.orderBy && this.#config.orderBy.length > 0) {
			throw new Error('YDB assumeOrderBy() cannot be combined with orderBy()')
		}
 
		let resolved = Array.isArray(columns[0])
			? (columns[0] as (string | SQLWrapper)[])
			: (columns as (string | SQLWrapper)[])
		this.#config.assumeOrderBy = this.#normalizeColumnExpressions(resolved, 'assumeOrderBy()')
		return this
	}
 
	limit(limit: number): this {
		let target = this.#getTargetConfigForTailClauses()
		;(target as YdbSetOperatorConfig | InternalSelectConfig).limit = normalizeCountValue(
			limit,
			'limit'
		)
		return this
	}
 
	offset(offset: number): this {
		let target = this.#getTargetConfigForTailClauses()
		;(target as YdbSetOperatorConfig | InternalSelectConfig).offset = normalizeCountValue(
			offset,
			'offset'
		)
		return this
	}
 
	without(...columns: (string | SQLWrapper)[] | [(string | SQLWrapper)[]]): this {
		Iif (this.#config.table === undefined) {
			throw new Error('YDB without() must be called after from()')
		}
 
		Iif (this.#config.joins && this.#config.joins.length > 0) {
			throw new Error('YDB without() cannot be combined with joins')
		}
 
		Iif (this.#isPartialSelect) {
			throw new Error('YDB without() is only supported for whole-source select() queries')
		}
 
		Iif (this.#config.distinctOn && this.#config.distinctOn.length > 0) {
			throw new Error('YDB without() cannot be combined with distinctOn()')
		}
 
		let resolved = Array.isArray(columns[0])
			? (columns[0] as (string | SQLWrapper)[])
			: (columns as (string | SQLWrapper)[])
		this.#config.without = this.#normalizeWithout(resolved)
		this.#applyWithoutToFields(resolved)
		return this
	}
 
	flattenBy(...expressions: SQLWrapper[]): this {
		return this.#setFlatten('by', expressions)
	}
 
	flattenListBy(...expressions: SQLWrapper[]): this {
		return this.#setFlatten('list by', expressions)
	}
 
	flattenDictBy(...expressions: SQLWrapper[]): this {
		return this.#setFlatten('dict by', expressions)
	}
 
	flattenOptionalBy(...expressions: SQLWrapper[]): this {
		return this.#setFlatten('optional by', expressions)
	}
 
	flattenColumns(): this {
		return this.#setFlatten('columns')
	}
 
	sample(ratio: number | SQLWrapper): this {
		Eif (typeof ratio === 'number') {
			normalizeCountValue(ratio, 'sample')
		}
 
		this.#config.sample = { kind: 'sample', ratio }
		return this
	}
 
	tableSample(method: string, size: number | SQLWrapper, repeatable?: number | SQLWrapper): this {
		Iif (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(method)) {
			throw new Error('YDB tableSample() method must be a simple identifier')
		}
		Eif (typeof size === 'number') {
			normalizeCountValue(size, 'tableSample')
		}
		if (typeof repeatable === 'number') {
			normalizeCountValue(repeatable, 'tableSample repeatable')
		}
 
		this.#config.sample = { kind: 'tablesample', method, size, repeatable }
		return this
	}
 
	matchRecognize(config: YdbMatchRecognizeConfig | SQLWrapper): this {
		this.#config.matchRecognize = config
		return this
	}
 
	window(name: string, definition: YdbWindowDefinitionConfig | SQLWrapper): this {
		Iif (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)) {
			throw new Error('YDB window() name must be a simple identifier')
		}
 
		let windows = this.#config.windows ?? []
		Iif (windows.some((value: YdbWindowClause) => value.name === name)) {
			throw new Error(`YDB window() duplicate window name "${name}"`)
		}
 
		this.#config.windows = [...windows, { name, definition: windowDefinition(definition) }]
		return this
	}
 
	intoResult(name: string): this {
		this.#config.intoResult = name
		return this
	}
 
	uniqueDistinct(...hints: YdbUniqueDistinctHint[] | [YdbUniqueDistinctHint[]]): this {
		let resolved = Array.isArray(hints[0])
			? (hints[0] as YdbUniqueDistinctHint[])
			: (hints as YdbUniqueDistinctHint[])
		Iif (resolved.length === 0) {
			throw new Error('YDB uniqueDistinct() requires at least one hint')
		}
 
		this.#config.uniqueDistinctHints = [
			...(this.#config.uniqueDistinctHints ?? []),
			...resolved,
		]
		return this
	}
 
	distinct(): this {
		if (this.#config.distinctOn && this.#config.distinctOn.length > 0) {
			throw new Error('YDB select() cannot combine distinct() and distinctOn()')
		}
 
		this.#config.distinct = true
		return this
	}
 
	distinctOn(...values: SQLWrapper[] | [SQLWrapper[]]): this {
		if (this.#config.distinct) {
			throw new Error('YDB select() cannot combine distinct() and distinctOn()')
		}
 
		let resolved = Array.isArray(values[0])
			? normalizeSqlWrapperArray(values[0] as SQLWrapper[])
			: normalizeSqlWrapperArray(values as SQLWrapper[])
		Iif (!resolved || resolved.length === 0) {
			throw new Error('YDB distinctOn() requires at least one expression')
		}
 
		this.#config.distinctOn = resolved
		return this
	}
 
	innerJoin = this.#createJoin('inner')
	leftJoin = this.#createJoin('left')
	rightJoin = this.#createJoin('right')
	fullJoin = this.#createJoin('full')
	crossJoin = this.#createJoin('cross')
	leftSemiJoin = this.#createJoin('left semi')
	rightSemiJoin = this.#createJoin('right semi')
	leftOnlyJoin = this.#createJoin('left only')
	rightOnlyJoin = this.#createJoin('right only')
	exclusionJoin = this.#createJoin('exclusion')
 
	union = this.#createSetOperator('union', false)
	unionAll = this.#createSetOperator('union', true)
	intersect = this.#createSetOperator('intersect', false)
	except = this.#createSetOperator('except', false)
 
	addSetOperators(setOperators: YdbSetOperatorConfig[]): this {
		this.#markUsedInSetOperation()
 
		for (let setOperator of setOperators) {
			Eif (setOperator.rightSelect instanceof YdbSelectBuilder) {
				setOperator.rightSelect.#markUsedInSetOperation()
			}
		}
 
		this.#config.setOperators.push(...setOperators)
		return this
	}
 
	getSQL(selectionAliases?: string[]): SQL {
		let config = this.#requireConfigWithTable()
		let fieldsFlat = orderSelectedFields(config.fields)
		let aliases = selectionAliases ?? this.#getSelectionAliases(fieldsFlat)
 
		return this.#dialect.buildSelectQuery({
			...config,
			fieldsFlat,
			selectionAliases: aliases,
		})
	}
 
	toSQL() {
		let { typings: _typings, ...query } = this.#dialect.sqlToQuery(this.getSQL())
		return query
	}
 
	prepare(name?: string) {
		let session = this.#requireSession()
		let orderedFields = this.#getOrderedFields()
		let joinsNotNullableMap =
			Object.keys(this.#joinsNotNullableMap).length > 0
				? this.#joinsNotNullableMap
				: undefined
		let resultMapper = (rows: unknown[][]) =>
			rows.map((row) => mapResultRow(orderedFields, row, joinsNotNullableMap))
 
		return session.prepareQuery<YdbPreparedQueryConfig & { execute: TResult; all: TResult }>(
			this.getSQL(),
			orderedFields,
			name,
			true,
			resultMapper as any
		)
	}
 
	override execute(): Promise<TResult> {
		return this.prepare().execute() as Promise<TResult>
	}
}