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

79.57% Statements 187/235
65.04% Branches 80/123
78.68% Functions 48/61
80.99% Lines 179/221

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 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763                                                                3x       3x       13x       22x 22x   22x 11x       11x 11x     22x       796x       796x       796x       796x       796x       796x       796x                                                                                                             26x     5x       5x   5x 6x     5x             22x 9x     13x 26x   26x   13x 13x                           15x 38x                       22x 10x     12x   12x       22x               22x 19x     3x   3x       22x 3x       3x         23x 11x     12x       12x       23x 23x 22x     1x       1x               22x 22x                 22x             6x       6x 6x 265x 6x                               26x                                     11x 11x 11x 11x 11x 11x 11x           6x                               9x                             26x                                                       15x 15x 15x 15x 15x 15x 15x 15x 15x 15x             22x 17x     5x 5x       5x 5x             5x 5x           5x                                                   22x 22x 22x   46x         22x           22x 22x 46x     22x 22x     5x       22x 22x 11x 5x     6x 6x 6x           22x 22x       22x       22x 22x 22x   22x       52x                   52x                               796x 796x 796x           796x         21x 21x               21x 543x   543x 1088x     543x       543x     21x 5x     21x                 5x   265x           265x   5x                 5x 265x 265x   5x 5x       5x             5x     5x 5x   5x 6x 6x                   6x     5x 5x 6x 266x             266x   266x 2x   264x         5x 5x   5x 265x           265x             265x 265x 2x 2x       263x     265x         1x                 15x             15x 9x     6x       1x   1x                               1x 1x                             14x      
// eslint-disable no-await-in-loop
import {
	aliasedTable,
	aliasedTableColumn,
	mapColumnsInAliasedSQLToAlias,
	mapColumnsInSQLToAlias,
} from 'drizzle-orm/alias'
import { Column } from 'drizzle-orm/column'
import { entityKind, is } from 'drizzle-orm/entity'
import {
	type BuildQueryResult,
	type DBQueryConfig,
	Many,
	One,
	type Relation,
	type TableRelationalConfig,
	type TablesRelationalConfig,
	getOperators,
	getOrderByOperators,
	normalizeRelation,
} from 'drizzle-orm/relations'
import { QueryPromise } from 'drizzle-orm/query-promise'
import { and, eq, inArray, or } from 'drizzle-orm/sql/expressions'
import { type SQL, type SQLWrapper, sql as yql } from 'drizzle-orm/sql/sql'
import { getTableUniqueName } from 'drizzle-orm/table'
import type { KnownKeysOnly, ValueOrArray } from 'drizzle-orm/utils'
import type { YdbDialect } from '../../ydb/dialect.js'
import type { YdbPreparedQueryConfig, YdbSession } from '../session.js'
import type { YdbColumn } from '../columns/common.js'
import type { YdbTable } from '../table.js'
 
function toArray<T>(value: ValueOrArray<T> | undefined): T[] {
	Iif (value === undefined) {
		return []
	}
 
	return Array.isArray(value) ? value : [value]
}
 
function isNumberValue(value: unknown): value is number {
	return typeof value === 'number' && Number.isFinite(value)
}
 
function dedupeColumns(columns: YdbColumn[]): YdbColumn[] {
	let seen = new Set<YdbColumn>()
	let result: YdbColumn[] = []
 
	for (let column of columns) {
		Iif (seen.has(column)) {
			continue
		}
 
		seen.add(column)
		result.push(column)
	}
 
	return result
}
 
function encodeTuplePart(value: unknown): string {
	Iif (typeof value === 'bigint') {
		return `bigint:${value.toString()}`
	}
 
	Iif (value instanceof Date) {
		return `date:${value.toISOString()}`
	}
 
	Iif (value instanceof Uint8Array) {
		return `bytes:${Buffer.from(value).toString('base64')}`
	}
 
	Iif (value === null) {
		return 'null:'
	}
 
	Iif (value === undefined) {
		return 'undefined:'
	}
 
	return `${typeof value}:${String(value)}`
}
 
function getTupleKey(values: unknown[]): string {
	return values.map((value) => encodeTuplePart(value)).join('|')
}
 
type YdbRelationalManyConfig<
	TSchema extends TablesRelationalConfig,
	TFields extends TableRelationalConfig,
> = DBQueryConfig<'many', true, TSchema, TFields>
 
type YdbRelationalFirstConfig<
	TSchema extends TablesRelationalConfig,
	TFields extends TableRelationalConfig,
> = Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>
 
type YdbRelationalAnyConfig = DBQueryConfig<'many', boolean>
 
type YdbVisibleSelectionEntry = {
	tsKey: string
	alias: string
	field: SQLWrapper
}
 
type YdbSelectedRelation = {
	tsKey: string
	relation: Relation
	relationTableTsName: string
	queryConfig: true | DBQueryConfig<'many', false>
	normalizedRelation: ReturnType<typeof normalizeRelation>
}
 
type YdbFlatQueryPlan = {
	sql: SQL
	tableAlias: string
	columnEntries: YdbVisibleSelectionEntry[]
	extraEntries: YdbVisibleSelectionEntry[]
	hiddenColumnAliases: Map<YdbColumn, string>
	selectedRelations: YdbSelectedRelation[]
}
 
type YdbExecutedLevel = {
	plan: YdbFlatQueryPlan
	rows: Array<Record<string, unknown>>
	values: Array<Record<string, unknown>>
}
 
type YdbExecuteLevelOptions = {
	table: YdbTable
	tableConfig: TableRelationalConfig
	config: YdbRelationalAnyConfig
	tableAlias: string
	requiredColumns?: YdbColumn[]
	extraWhere?: SQL
	applyLimit?: boolean
	applyOffset?: boolean
}
 
let relationalRelationParameterBudget = 256
 
function chunkRelationTuples(tuples: unknown[][], columnCount: number): unknown[][][] {
	let chunkSize = Math.max(
		1,
		Math.floor(relationalRelationParameterBudget / Math.max(1, columnCount))
	)
	let chunks: unknown[][][] = []
 
	for (let index = 0; index < tuples.length; index += chunkSize) {
		chunks.push(tuples.slice(index, index + chunkSize))
	}
 
	return chunks
}
 
function getSelectedColumnKeys(
	tableConfig: TableRelationalConfig,
	config: YdbRelationalAnyConfig
): string[] {
	if (!config.columns) {
		return Object.keys(tableConfig.columns)
	}
 
	let explicitEntries = Object.entries(config.columns).filter(
		([key, include]) => key in tableConfig.columns && include !== undefined
	)
	let includeKeys = explicitEntries.filter(([, include]) => include === true).map(([key]) => key)
 
	Eif (includeKeys.length > 0) {
		return includeKeys
	}
 
	let excludeKeys = new Set(
		explicitEntries.filter(([, include]) => include === false).map(([key]) => key)
	)
 
	return Object.keys(tableConfig.columns).filter((key) => !excludeKeys.has(key))
}
 
function getAliasedColumns(
	tableConfig: TableRelationalConfig,
	tableAlias: string
): Record<string, Column> {
	return Object.fromEntries(
		Object.entries(tableConfig.columns).map(([key, value]) => [
			key,
			aliasedTableColumn(value, tableAlias),
		])
	) as Record<string, Column>
}
 
function getWhereClause(
	tableConfig: TableRelationalConfig,
	config: YdbRelationalAnyConfig,
	tableAlias: string
): SQL | undefined {
	if (config.where === undefined) {
		return undefined
	}
 
	let aliasedColumns = getAliasedColumns(tableConfig, tableAlias)
	let whereSql =
		typeof config.where === 'function'
			? config.where(aliasedColumns as Record<string, YdbColumn>, getOperators())
			: config.where
 
	return whereSql ? mapColumnsInSQLToAlias(whereSql, tableAlias) : undefined
}
 
function getOrderByClause(
	tableConfig: TableRelationalConfig,
	config: YdbRelationalAnyConfig,
	tableAlias: string
): SQL[] {
	if (config.orderBy === undefined) {
		return []
	}
 
	let aliasedColumns = getAliasedColumns(tableConfig, tableAlias)
	let orderBy =
		typeof config.orderBy === 'function'
			? config.orderBy(aliasedColumns as Record<string, YdbColumn>, getOrderByOperators())
			: config.orderBy
 
	return toArray(orderBy).map((field) => {
		Iif (is(field, Column)) {
			return aliasedTableColumn(field, tableAlias) as unknown as SQL
		}
 
		return mapColumnsInSQLToAlias(field as SQL, tableAlias)
	})
}
 
function getLimitClause(config: YdbRelationalAnyConfig): number | undefined {
	if (config.limit === undefined) {
		return undefined
	}
 
	Iif (!isNumberValue(config.limit)) {
		throw new Error('YDB relational query limit must be a finite number')
	}
 
	return config.limit
}
 
function getOffsetClause(config: YdbRelationalAnyConfig): number | undefined {
	let offset = 'offset' in config ? config.offset : undefined
	if (offset === undefined) {
		return undefined
	}
 
	Iif (!isNumberValue(offset)) {
		throw new Error('YDB relational query offset must be a finite number')
	}
 
	return offset
}
 
function getExtrasSelection(
	tableConfig: TableRelationalConfig,
	config: YdbRelationalAnyConfig,
	tableAlias: string
): Array<{ tsKey: string; field: SQL.Aliased }> {
	Eif (!config.extras) {
		return []
	}
 
	let aliasedColumns = getAliasedColumns(tableConfig, tableAlias)
	let extras =
		typeof config.extras === 'function'
			? config.extras(aliasedColumns as Record<string, YdbColumn>, { sql: yql })
			: config.extras
 
	return Object.entries(extras).map(([tsKey, value]) => ({
		tsKey,
		field: mapColumnsInAliasedSQLToAlias(value, tableAlias) as SQL.Aliased,
	}))
}
 
function buildRelationFilter(columns: YdbColumn[], tuples: unknown[][]): SQL {
	Iif (columns.length === 0) {
		throw new Error('YDB relational relation filter requires at least one column')
	}
 
	Eif (columns.length === 1) {
		let column = columns[0]!
		let values = tuples.map(([value]) => value)
		return values.length === 1 ? eq(column, values[0]) : inArray(column, values)
	}
 
	if (tuples.length === 1) {
		return and(...columns.map((column, index) => eq(column, tuples[0]![index])))!
	}
 
	return or(
		...tuples.map((tuple) => and(...columns.map((column, index) => eq(column, tuple[index]))))
	)!
}
 
export class YdbRelationalQueryBuilder<
	TSchema extends TablesRelationalConfig,
	TFields extends TableRelationalConfig,
> {
	static readonly [entityKind] = 'YdbRelationalQueryBuilder'
 
	readonly #fullSchema: Record<string, unknown>
	readonly #schema: TSchema
	readonly #tableNamesMap: Record<string, string>
	readonly #table: YdbTable
	readonly #tableConfig: TFields
	readonly #dialect: YdbDialect
	readonly #session: YdbSession
 
	constructor(
		fullSchema: Record<string, unknown>,
		schema: TSchema,
		tableNamesMap: Record<string, string>,
		table: YdbTable,
		tableConfig: TFields,
		dialect: YdbDialect,
		session: YdbSession
	) {
		this.#fullSchema = fullSchema
		this.#schema = schema
		this.#tableNamesMap = tableNamesMap
		this.#table = table
		this.#tableConfig = tableConfig
		this.#dialect = dialect
		this.#session = session
	}
 
	findMany<TConfig extends YdbRelationalManyConfig<TSchema, TFields>>(
		config?: KnownKeysOnly<TConfig, YdbRelationalManyConfig<TSchema, TFields>>
	): YdbRelationalQuery<BuildQueryResult<TSchema, TFields, TConfig>[]> {
		return new YdbRelationalQuery(
			this.#fullSchema,
			this.#schema,
			this.#tableNamesMap,
			this.#table,
			this.#tableConfig,
			this.#dialect,
			this.#session,
			(config ?? {}) as YdbRelationalAnyConfig,
			'many'
		)
	}
 
	findFirst<TConfig extends YdbRelationalFirstConfig<TSchema, TFields>>(
		config?: KnownKeysOnly<TConfig, YdbRelationalFirstConfig<TSchema, TFields>>
	): YdbRelationalQuery<BuildQueryResult<TSchema, TFields, TConfig> | undefined> {
		return new YdbRelationalQuery(
			this.#fullSchema,
			this.#schema,
			this.#tableNamesMap,
			this.#table,
			this.#tableConfig,
			this.#dialect,
			this.#session,
			{ ...((config ?? {}) as YdbRelationalAnyConfig), limit: 1 },
			'first'
		)
	}
}
 
export class YdbRelationalQuery<TResult> extends QueryPromise<TResult> {
	static override readonly [entityKind] = 'YdbRelationalQuery'
 
	declare readonly _: {
		readonly dialect: 'ydb'
		readonly result: TResult
	}
 
	readonly #fullSchema: Record<string, unknown>
	readonly #schema: TablesRelationalConfig
	readonly #tableNamesMap: Record<string, string>
	readonly #table: YdbTable
	readonly #tableConfig: TableRelationalConfig
	readonly #dialect: YdbDialect
	readonly #session: YdbSession
	readonly #config: YdbRelationalAnyConfig
	readonly #mode: 'many' | 'first'
 
	constructor(
		fullSchema: Record<string, unknown>,
		schema: TablesRelationalConfig,
		tableNamesMap: Record<string, string>,
		table: YdbTable,
		tableConfig: TableRelationalConfig,
		dialect: YdbDialect,
		session: YdbSession,
		config: YdbRelationalAnyConfig,
		mode: 'many' | 'first'
	) {
		super()
		this.#fullSchema = fullSchema
		this.#schema = schema
		this.#tableNamesMap = tableNamesMap
		this.#table = table
		this.#tableConfig = tableConfig
		this.#dialect = dialect
		this.#session = session
		this.#config = config
		this.#mode = mode
	}
 
	#getSelectedRelations(
		tableConfig: TableRelationalConfig,
		config: YdbRelationalAnyConfig
	): YdbSelectedRelation[] {
		if (!config.with) {
			return []
		}
 
		return Object.entries(config.with).flatMap(([tsKey, queryConfig]) => {
			Iif (!queryConfig) {
				return []
			}
 
			let relation = tableConfig.relations[tsKey]
			Iif (!relation) {
				throw new Error(
					`YDB relational query relation "${tableConfig.tsName}.${tsKey}" is missing`
				)
			}
 
			let relationTableTsName =
				this.#tableNamesMap[getTableUniqueName(relation.referencedTable)]
			Iif (!relationTableTsName) {
				throw new Error(
					`YDB relational query table metadata for "${relation.referencedTableName}" is missing`
				)
			}
 
			return [
				{
					tsKey,
					relation,
					relationTableTsName,
					queryConfig: queryConfig as true | DBQueryConfig<'many', false>,
					normalizedRelation: normalizeRelation(
						this.#schema,
						this.#tableNamesMap,
						relation
					),
				},
			]
		})
	}
 
	#buildFlatQueryPlan({
		table,
		tableConfig,
		config,
		tableAlias,
		requiredColumns = [],
		extraWhere,
		applyLimit = true,
		applyOffset = true,
	}: YdbExecuteLevelOptions): YdbFlatQueryPlan {
		let selectedRelations = this.#getSelectedRelations(tableConfig, config)
		let selectedColumnKeys = getSelectedColumnKeys(tableConfig, config)
		let selectedExtras = getExtrasSelection(tableConfig, config, tableAlias)
 
		let columnEntries = selectedColumnKeys.map((tsKey, index) => ({
			tsKey,
			alias: `__ydb_c${index}`,
			field: aliasedTableColumn(tableConfig.columns[tsKey]!, tableAlias),
		}))
		let extraEntries = selectedExtras.map(({ tsKey, field }, index) => ({
			tsKey,
			alias: `__ydb_e${index}`,
			field,
		}))
 
		let hiddenColumnAliases = new Map<YdbColumn, string>()
		for (let entry of columnEntries) {
			hiddenColumnAliases.set(tableConfig.columns[entry.tsKey] as YdbColumn, entry.alias)
		}
 
		let hiddenFields: Array<{ alias: string; field: SQLWrapper }> = []
		let hiddenColumns = dedupeColumns([
			...requiredColumns,
			...selectedRelations.flatMap(
				({ normalizedRelation }) => normalizedRelation.fields as YdbColumn[]
			),
		])
 
		let hiddenIndex = 0
		for (let column of hiddenColumns) {
			if (hiddenColumnAliases.has(column)) {
				continue
			}
 
			let alias = `__ydb_h${hiddenIndex++}`
			hiddenColumnAliases.set(column, alias)
			hiddenFields.push({
				alias,
				field: aliasedTableColumn(column, tableAlias),
			})
		}
 
		let fields = [...columnEntries, ...extraEntries, ...hiddenFields]
		Iif (fields.length === 0) {
			throw new Error(`YDB relational query selected zero fields for "${tableConfig.tsName}"`)
		}
 
		let where = and(
			extraWhere ? mapColumnsInSQLToAlias(extraWhere, tableAlias) : undefined,
			getWhereClause(tableConfig, config, tableAlias)
		)
		let orderBy = getOrderByClause(tableConfig, config, tableAlias)
		let limit = applyLimit ? getLimitClause(config) : undefined
		let offset = applyOffset ? getOffsetClause(config) : undefined
 
		return {
			sql: this.#dialect.buildSelectQuery({
				table: aliasedTable(table, tableAlias),
				fields: {},
				fieldsFlat: fields.map(({ field }) => ({ path: [], field })),
				where,
				joins: undefined,
				orderBy,
				groupBy: undefined,
				having: undefined,
				limit,
				offset,
				distinct: false,
				distinctOn: undefined,
				selectionAliases: fields.map(({ alias }) => alias),
				setOperators: [],
			}),
			tableAlias,
			columnEntries,
			extraEntries,
			hiddenColumnAliases,
			selectedRelations,
		}
	}
 
	#getColumnTuple(
		row: Record<string, unknown>,
		columns: YdbColumn[],
		aliases: Map<YdbColumn, string>
	): unknown[] {
		return columns.map((column) => {
			let alias = aliases.get(column)
			Iif (!alias) {
				throw new Error(
					`YDB relational query hidden alias for column "${column.name}" is missing`
				)
			}
 
			return row[alias]
		})
	}
 
	async #executeLevel(options: YdbExecuteLevelOptions): Promise<YdbExecutedLevel> {
		let plan = this.#buildFlatQueryPlan(options)
		let rows = await this.#session
			.prepareQuery<YdbPreparedQueryConfig & { execute: Array<Record<string, unknown>> }>(
				plan.sql,
				undefined,
				undefined,
				false
			)
			.execute()
		let values = rows.map((row) => {
			let result: Record<string, unknown> = {}
 
			for (let entry of plan.columnEntries) {
				result[entry.tsKey] = row[entry.alias]
			}
 
			for (let entry of plan.extraEntries) {
				result[entry.tsKey] = row[entry.alias]
			}
 
			return result
		})
 
		for (let relation of plan.selectedRelations) {
			await this.#hydrateRelation(plan, rows, values, relation)
		}
 
		return { plan, rows, values }
	}
 
	async #hydrateRelation(
		parentPlan: YdbFlatQueryPlan,
		parentRows: Array<Record<string, unknown>>,
		parentValues: Array<Record<string, unknown>>,
		relationSelection: YdbSelectedRelation
	): Promise<void> {
		let parentTuples = parentRows
			.map((row) =>
				this.#getColumnTuple(
					row,
					relationSelection.normalizedRelation.fields as YdbColumn[],
					parentPlan.hiddenColumnAliases
				)
			)
			.filter((tuple) => tuple.every((value) => value !== null && value !== undefined))
 
		Iif (parentTuples.length === 0) {
			for (let parentValue of parentValues) {
				parentValue[relationSelection.tsKey] = is(relationSelection.relation, One)
					? null
					: []
			}
			return
		}
 
		let uniqueParentTuples = Array.from(
			new Map(parentTuples.map((tuple) => [getTupleKey(tuple), tuple])),
			([, tuple]) => tuple
		)
		let relationTableConfig = this.#schema[relationSelection.relationTableTsName]
		let relationTable = this.#fullSchema[relationSelection.relationTableTsName] as
			| YdbTable
			| undefined
 
		Iif (!relationTableConfig || !relationTable) {
			throw new Error(
				`YDB relational query table "${relationSelection.relationTableTsName}" is missing`
			)
		}
 
		let relationConfig =
			relationSelection.queryConfig === true
				? ({} as YdbRelationalAnyConfig)
				: (relationSelection.queryConfig as YdbRelationalAnyConfig)
		let referenceColumns = relationSelection.normalizedRelation.references as YdbColumn[]
		let relationResults: YdbExecutedLevel[] = []
 
		for (let tupleChunk of chunkRelationTuples(uniqueParentTuples, referenceColumns.length)) {
			let relationFilter = buildRelationFilter(referenceColumns, tupleChunk)
			let relationResult = await this.#executeLevel({
				table: relationTable,
				tableConfig: relationTableConfig,
				config: relationConfig,
				tableAlias: `${parentPlan.tableAlias}_${relationSelection.tsKey}`,
				requiredColumns: referenceColumns,
				extraWhere: relationFilter,
				applyLimit: !is(relationSelection.relation, Many),
				applyOffset: !is(relationSelection.relation, Many),
			})
			relationResults.push(relationResult)
		}
 
		let groupedValues = new Map<string, Array<Record<string, unknown>>>()
		for (let relationResult of relationResults) {
			for (let [index, row] of relationResult.rows.entries()) {
				let key = getTupleKey(
					this.#getColumnTuple(
						row,
						referenceColumns,
						relationResult.plan.hiddenColumnAliases
					)
				)
				let existing = groupedValues.get(key)
 
				if (existing) {
					existing.push(relationResult.values[index]!)
				} else {
					groupedValues.set(key, [relationResult.values[index]!])
				}
			}
		}
 
		let relationOffset = getOffsetClause(relationConfig) ?? 0
		let relationLimit = getLimitClause(relationConfig)
 
		for (let [index, parentValue] of parentValues.entries()) {
			let tuple = this.#getColumnTuple(
				parentRows[index]!,
				relationSelection.normalizedRelation.fields as YdbColumn[],
				parentPlan.hiddenColumnAliases
			)
 
			Iif (tuple.some((value) => value === null || value === undefined)) {
				parentValue[relationSelection.tsKey] = is(relationSelection.relation, One)
					? null
					: []
				continue
			}
 
			let relatedValues = groupedValues.get(getTupleKey(tuple)) ?? []
			if (is(relationSelection.relation, One)) {
				parentValue[relationSelection.tsKey] = relatedValues[0] ?? null
				continue
			}
 
			let sliced =
				relationLimit === undefined
					? relatedValues.slice(relationOffset)
					: relatedValues.slice(relationOffset, relationOffset + relationLimit)
			parentValue[relationSelection.tsKey] = sliced
		}
	}
 
	getSQL(): SQL {
		return this.#buildFlatQueryPlan({
			table: this.#table,
			tableConfig: this.#tableConfig,
			config: this.#config,
			tableAlias: this.#tableConfig.tsName,
		}).sql
	}
 
	async #run(): Promise<TResult> {
		let result = await this.#executeLevel({
			table: this.#table,
			tableConfig: this.#tableConfig,
			config: this.#config,
			tableAlias: this.#tableConfig.tsName,
		})
 
		if (this.#mode === 'first') {
			return result.values[0] as TResult | undefined as TResult
		}
 
		return result.values as TResult
	}
 
	prepare(name?: string) {
		let flatPrepared = this.#session.prepareQuery(this.getSQL(), undefined, name, false)
 
		return {
			getQuery: () => {
				return flatPrepared.getQuery()
			},
			execute: async () => {
				return this.#run()
			},
			all: async () => {
				let result = await this.#run()
				if (Array.isArray(result)) {
					return result
				}
 
				return result === undefined ? [] : [result]
			},
			get: async () => {
				let result = await this.#run()
				return Array.isArray(result) ? result[0] : result
			},
			values: async () => {
				return flatPrepared.values()
			},
		}
	}
 
	toSQL() {
		let prepared = this.prepare()
		let { typings: _typings, ...query } = prepared.getQuery()
		return query
	}
 
	override execute(): Promise<TResult> {
		return this.#run()
	}
}