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

83.7% Statements 262/313
76.28% Branches 193/253
86.3% Functions 63/73
83.49% Lines 258/309

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 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090                                                                                                                                                                                              3x       17x                                                                                     32x 32x 32x 32x         18x             2x                           52x 20x     32x 52x         13x   13x                             6x       54x           18x   18x                                       3x 3x 3x 2x     1x 1x                                     3x       3x 1x     2x 2x                   3x 3x             8x       8x             17x   17x 17x 17x                                           18x           18x 18x     18x 24x   24x 24x   24x     24x 24x   24x 8x     16x                       16x         24x   16x 16x 16x                                                 16x   16x     36x               16x 16x                             8x 8x 2x     6x     2x             32x       155x       2199x       900x       1x         752x         752x 8x     744x 1x     743x 4x     739x           10x     729x 4x     725x       332x 324x     8x 8x 8x     8x       23x                 3x       2x       20x       133x       2x       3x       2x       2x                 2x                 2x       136x 136x 136x       65x 65x 65x       65x 65x 65x 212x     65x 65x       65x 6x     6x     59x       59x       59x 73x     59x   73x   230x           59x       17x 17x 68x 68x 30x     38x     17x       17x       19x 19x     19x   19x       19x 3x     16x       16x 16x 16x   19x       106x 106x     106x   106x             106x 3x       3x     103x 2x 2x 2x 2x 2x   2x       2x 2x     2x 2x 2x       2x 2x   2x         101x   106x                     2x     2x 2x   2x 6x           2x     2x   2x     2x     2x 2x 2x 4x       4x 4x 2x   4x       2x 2x 4x                 2x                             2x     2x 1x     2x 1x       1x     2x 2x     2x     2x 2x 1x     1x       2x                           2x           2x   4x 4x                                       2x     4x                                 2x                       19x 19x         19x 19x 18x 18x     17x   17x                           17x 17x 17x 13x   17x 13x     17x 29x 10x     19x 19x 19x 3x     17x   29x 29x 22x 22x 29x 29x   29x                                   17x 17x 21x 21x 19x 19x                                     15x 15x                                     15x 15x                       2x 2x 2x                                       2x             6x   19x 16x 16x             19x 6x     13x           674x                    
/* oxlint-disable no-await-in-loop -- migrate() applies statements sequentially and polls the lock with backoff */
import * as crypto from 'node:crypto'
import {
	aliasedTable,
	aliasedTableColumn,
	mapColumnsInAliasedSQLToAlias,
	mapColumnsInSQLToAlias,
} from 'drizzle-orm/alias'
import { CasingCache } from 'drizzle-orm/casing'
import { Column } from 'drizzle-orm/column'
import { entityKind, is } from 'drizzle-orm/entity'
import { DrizzleError } from 'drizzle-orm/errors'
import { getOperators, getOrderByOperators } from 'drizzle-orm/relations'
import {
	type DriverValueEncoder,
	type QueryTypingsValue,
	type QueryWithTypings,
	SQL,
	sql as yql,
} from 'drizzle-orm/sql/sql'
import { and } from 'drizzle-orm/sql/expressions'
import type { Casing } from 'drizzle-orm/utils'
import type { YdbSession } from '../ydb-core/session.js'
import type { YdbSelectedFieldsOrdered } from '../ydb-core/result-mapping.js'
import type { YdbColumn } from '../ydb-core/columns/common.js'
import {
	type YdbMigrationStatus,
	buildMigrationHistoryInsertSql,
	buildMigrationHistoryMetadataColumnSql,
	buildMigrationHistoryMetadataProbeSql,
	buildMigrationHistorySelectSql,
	buildMigrationLockRefreshSql,
	buildMigrationLockReleaseSql,
	buildMigrationLockSelectSql,
	buildMigrationLockTableBootstrapSql,
	buildMigrationLockUpsertSql,
	buildMigrationTableBootstrapSql,
	buildStableMigrationName,
} from './migration-ddl.js'
import {
	buildFromTable,
	buildJoins,
	buildLimit,
	buildOffset,
	buildOrderBy,
	buildReturningSelection,
	buildSelectQuery,
	buildSelection,
	buildSetOperationQuery,
	buildSetOperations,
	getSelectionAliases,
	mapExpressionsToSelectionAliases,
} from './dialect.select.js'
import type {
	YdbDeleteConfig,
	YdbDialectMigration,
	YdbDialectMigrationConfig,
	YdbInsertConfig,
	YdbJoinConfig,
	YdbRelationalQueryConfig,
	YdbRelationalQueryResult,
	YdbSelectConfig,
	YdbSetOperatorConfig,
	YdbUpdateConfig,
} from './dialect.types.js'
import {
	getInsertColumnEntries,
	getPrimaryColumnKeys,
	getTableColumns,
	resolveInsertValue,
	resolveUpdateValue,
	validateTableColumnKeys,
} from '../ydb-core/query-builders/utils.js'
 
export interface YdbDialectConfig {
	casing?: Casing | undefined
}
 
export {
	type YdbDeleteConfig,
	type YdbDialectMigration,
	type YdbDialectMigrationConfig,
	type YdbFlatRelationalQueryConfig,
	type YdbInsertConfig,
	type YdbJoinConfig,
	type YdbJoinType,
	type YdbRelationalQueryConfig,
	type YdbRelationalQueryResult,
	type YdbSelectConfig,
	type YdbSetOperatorConfig,
	type YdbSetOperatorSource,
	type YdbUpdateConfig,
} from './dialect.types.js'
 
function isNumberValue(value: unknown): value is number {
	return typeof value === 'number' && Number.isFinite(value)
}
 
function deriveMigrationName(migration: YdbDialectMigration): string {
	return buildStableMigrationName(migration)
}
 
type MigrationSession = Pick<YdbSession, 'execute' | 'values'>
 
type MigrationTransactionalSession = MigrationSession & {
	transaction<T>(
		callback: (tx: MigrationSession) => Promise<T>,
		config?: { accessMode?: 'read only' | 'read write'; idempotent?: boolean }
	): Promise<T>
}
 
type MigrationSessionInput = MigrationSession & {
	transaction?: MigrationTransactionalSession['transaction']
}
 
interface NormalizedMigrationHistoryRow {
	hash: string
	folderMillis: number
	name: string
	status: YdbMigrationStatus
	startedAt?: number | undefined
	finishedAt?: number | undefined
	error?: string | undefined
	ownerId?: string | undefined
	statementsTotal?: number | undefined
	statementsApplied?: number | undefined
}
 
interface NormalizedMigrationLockConfig {
	key: string
	ownerId: string
	leaseMs: number
	acquireTimeoutMs: number
	retryIntervalMs: number
}
 
interface MigrationLockHandle {
	ownerId: string
	assertHealthy(): void
	release(): Promise<void>
}
 
let defaultMigrationLockLeaseMs = 10 * 60 * 1000
let defaultMigrationLockAcquireTimeoutMs = 60 * 1000
let defaultMigrationLockRetryIntervalMs = 1000
let defaultMigrationStaleRunningAfterMs = 60 * 60 * 1000
 
function isMigrationTransactionalSession(
	session: MigrationSession
): session is MigrationTransactionalSession {
	return (
		'transaction' in session &&
		typeof (session as MigrationTransactionalSession).transaction === 'function'
	)
}
 
function getErrorMessage(error: unknown): string {
	return error instanceof Error ? error.message : String(error)
}
 
function isMissingMigrationMetadataError(error: unknown): boolean {
	return /column|member|unknown|not found|does not exist|no such|type annotation/i.test(
		getErrorMessage(error)
	)
}
 
function isAlreadyExistsError(error: unknown): boolean {
	return /already|exists|duplicate/i.test(getErrorMessage(error))
}
 
function toOptionalNumber(value: unknown): number | undefined {
	if (value === undefined || value === null) {
		return undefined
	}
 
	let numberValue = typeof value === 'bigint' ? Number(value) : Number(value)
	return Number.isFinite(numberValue) ? numberValue : undefined
}
 
function normalizeMigrationHistoryRow(row: unknown[]): NormalizedMigrationHistoryRow {
	let status: YdbMigrationStatus =
		row[3] === 'running' || row[3] === 'failed' || row[3] === 'applied' ? row[3] : 'applied'
 
	return {
		hash: String(row[0]),
		folderMillis: Number(row[1]),
		name: String(row[2]),
		status,
		startedAt: toOptionalNumber(row[4]),
		finishedAt: toOptionalNumber(row[5]),
		error: row[6] === undefined || row[6] === null ? undefined : String(row[6]),
		ownerId: row[7] === undefined || row[7] === null ? undefined : String(row[7]),
		statementsTotal: toOptionalNumber(row[8]),
		statementsApplied: toOptionalNumber(row[9]),
	}
}
 
function sleep(ms: number): Promise<void> {
	return new Promise((resolve) => setTimeout(resolve, ms))
}
 
function normalizePositiveNumber(value: unknown, fallback: number): number {
	return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
}
 
function normalizeMigrationLockConfig(
	config: YdbDialectMigrationConfig
): NormalizedMigrationLockConfig {
	let lockConfig = typeof config.migrationLock === 'object' ? config.migrationLock : {}
 
	return {
		key: lockConfig.key ?? 'migrate',
		ownerId: lockConfig.ownerId ?? `ydb-drizzle-${process.pid}-${crypto.randomUUID()}`,
		leaseMs: normalizePositiveNumber(lockConfig.leaseMs, defaultMigrationLockLeaseMs),
		acquireTimeoutMs: normalizePositiveNumber(
			lockConfig.acquireTimeoutMs,
			defaultMigrationLockAcquireTimeoutMs
		),
		retryIntervalMs: normalizePositiveNumber(
			lockConfig.retryIntervalMs,
			defaultMigrationLockRetryIntervalMs
		),
	}
}
 
function shouldRetryMigration(
	row: NormalizedMigrationHistoryRow,
	now: number,
	config: YdbDialectMigrationConfig
): boolean {
	let recovery = config.migrationRecovery ?? {}
	let mode = recovery.mode ?? 'fail'
	if (mode !== 'retry') {
		return false
	}
 
	Eif (row.status === 'failed') {
		return true
	}
 
	let staleAfterMs = normalizePositiveNumber(
		recovery.staleRunningAfterMs,
		defaultMigrationStaleRunningAfterMs
	)
	return (
		row.status === 'running' &&
		row.startedAt !== undefined &&
		now - row.startedAt > staleAfterMs
	)
}
 
function assertMigrationRecoverable(
	row: NormalizedMigrationHistoryRow,
	now: number,
	config: YdbDialectMigrationConfig
): void {
	Iif (row.status === 'applied') {
		return
	}
 
	if (shouldRetryMigration(row, now, config)) {
		return
	}
 
	Eif (row.status === 'failed') {
		throw new Error(
			`YDB migration "${row.name}" (${row.hash}) is marked as failed after ${row.statementsApplied ?? 0}/${row.statementsTotal ?? 0} statements. ` +
				'Fix the migration manually or rerun with migrationRecovery.mode = "retry".'
		)
	}
 
	let staleAfterMs = normalizePositiveNumber(
		config.migrationRecovery?.staleRunningAfterMs,
		defaultMigrationStaleRunningAfterMs
	)
	let age = row.startedAt === undefined ? 'unknown' : `${now - row.startedAt}ms`
	throw new Error(
		`YDB migration "${row.name}" (${row.hash}) is still marked as running (age: ${age}, owner: ${row.ownerId ?? 'unknown'}). ` +
			`It is treated as active until it is older than ${staleAfterMs}ms; use migrationRecovery.mode = "retry" only after verifying the previous run is dead.`
	)
}
 
function yqlBindingName(alias: string): string {
	Iif (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(alias)) {
		throw new Error(`YDB CTE alias "${alias}" cannot be used as a YQL binding name`)
	}
 
	return `$${alias}`
}
 
async function ensureMigrationHistoryTable(
	session: MigrationSession,
	config: YdbDialectMigrationConfig
): Promise<void> {
	await session.execute(yql.raw(buildMigrationTableBootstrapSql(config)))
 
	try {
		await session.values(yql.raw(buildMigrationHistoryMetadataProbeSql(config)))
		return
	} catch (error) {
		if (!isMissingMigrationMetadataError(error)) {
			throw error
		}
	}
 
	for (let statement of buildMigrationHistoryMetadataColumnSql(config)) {
		try {
			await session.execute(yql.raw(statement))
		} catch (error) {
			if (!isAlreadyExistsError(error)) {
				throw error
			}
		}
	}
}
 
async function acquireMigrationLock(
	session: MigrationSession,
	config: YdbDialectMigrationConfig
): Promise<MigrationLockHandle> {
	Iif (!isMigrationTransactionalSession(session)) {
		throw new Error(
			'YDB migrate() migrationLock requires a transactional YDB session. Pass migrationLock: false to opt out.'
		)
	}
 
	let lockConfig = normalizeMigrationLockConfig(config)
	let deadline = Date.now() + lockConfig.acquireTimeoutMs
	let lastError: unknown
 
	while (Date.now() <= deadline) {
		let now = Date.now()
 
		try {
			let acquired = await session.transaction(
				async (tx) => {
					let rows = await tx.values<[string, number | string]>(
						yql.raw(buildMigrationLockSelectSql(config, lockConfig.key))
					)
					let [ownerId, expiresAtRaw] = rows[0] ?? []
					let expiresAt = Number(expiresAtRaw ?? 0)
 
					if (ownerId && ownerId !== lockConfig.ownerId && expiresAt > now) {
						return false
					}
 
					await tx.execute(
						yql.raw(
							buildMigrationLockUpsertSql(config, {
								key: lockConfig.key,
								ownerId: lockConfig.ownerId,
								acquiredAt: now,
								heartbeatAt: now,
								expiresAt: now + lockConfig.leaseMs,
							})
						)
					)
 
					return true
				},
				{ accessMode: 'read write', idempotent: false }
			)
 
			if (acquired) {
				let heartbeatError: unknown
				let heartbeatInFlight = false
				let heartbeatEveryMs = Math.max(1000, Math.floor(lockConfig.leaseMs / 3))
				let heartbeat = setInterval(() => {
					if (heartbeatInFlight) {
						return
					}
 
					heartbeatInFlight = true
					let heartbeatAt = Date.now()
					void session
						.execute(
							yql.raw(
								buildMigrationLockRefreshSql(config, {
									key: lockConfig.key,
									ownerId: lockConfig.ownerId,
									heartbeatAt,
									expiresAt: heartbeatAt + lockConfig.leaseMs,
								})
							)
						)
						.catch((error) => {
							heartbeatError = error
						})
						.finally(() => {
							heartbeatInFlight = false
						})
				}, heartbeatEveryMs)
				heartbeat.unref?.()
 
				return {
					ownerId: lockConfig.ownerId,
					assertHealthy() {
						Iif (heartbeatError) {
							throw new Error(
								`YDB migrate() lock heartbeat failed: ${getErrorMessage(heartbeatError)}`,
								{ cause: heartbeatError }
							)
						}
					},
					async release() {
						clearInterval(heartbeat)
						await session.execute(
							yql.raw(
								buildMigrationLockReleaseSql(config, {
									key: lockConfig.key,
									ownerId: lockConfig.ownerId,
								})
							)
						)
					},
				}
			}
		} catch (error) {
			lastError = error
		}
 
		let remainingMs = deadline - Date.now()
		if (remainingMs <= 0) {
			break
		}
 
		await sleep(Math.min(lockConfig.retryIntervalMs, remainingMs))
	}
 
	throw new Error(
		`YDB migrate() could not acquire migration lock "${lockConfig.key}" within ${lockConfig.acquireTimeoutMs}ms.`,
		{ cause: lastError }
	)
}
 
export class YdbDialect {
	static readonly [entityKind] = 'YdbDialect'
	readonly #casing: CasingCache
 
	constructor(config: YdbDialectConfig = {}) {
		this.#casing = new CasingCache(config.casing)
	}
 
	escapeName(name: string): string {
		return `\`${name.replace(/`/g, '``')}\``
	}
 
	escapeParam(num: number): string {
		return `$p${num}`
	}
 
	escapeString(str: string): string {
		return `'${str.replace(/'/g, "''")}'`
	}
 
	prepareTyping(encoder?: DriverValueEncoder<unknown, unknown>): QueryTypingsValue {
		let sqlType =
			typeof (encoder as unknown as { getSQLType?: () => string } | undefined)?.getSQLType ===
			'function'
				? (encoder as unknown as { getSQLType(): string }).getSQLType()
				: undefined
 
		if (sqlType === 'Json' || sqlType === 'JsonDocument') {
			return 'json'
		}
 
		if (sqlType?.startsWith('Decimal(')) {
			return 'decimal'
		}
 
		if (sqlType === 'Date' || sqlType === 'Date32') {
			return 'date'
		}
 
		if (
			sqlType === 'Datetime' ||
			sqlType === 'Timestamp' ||
			sqlType === 'Datetime64' ||
			sqlType === 'Timestamp64'
		) {
			return 'timestamp'
		}
 
		if (sqlType === 'Uuid') {
			return 'uuid'
		}
 
		return 'none'
	}
 
	buildWithCTE(queries: { _: { alias: string; sql: SQL } }[] | undefined): SQL | undefined {
		if (!queries || queries.length === 0) {
			return undefined
		}
 
		let withSqlChunks: SQL[] = []
		for (let query of queries) {
			withSqlChunks.push(yql`${yql.raw(yqlBindingName(query._.alias))} = (${query._.sql}); `)
		}
 
		return yql.join(withSqlChunks)
	}
 
	getSelectionAliases(fields: YdbSelectedFieldsOrdered): string[] {
		return getSelectionAliases(fields)
	}
 
	mapExpressionsToSelectionAliases(
		expressions: Parameters<typeof mapExpressionsToSelectionAliases>[0],
		fields: Parameters<typeof mapExpressionsToSelectionAliases>[1],
		selectionAliases: Parameters<typeof mapExpressionsToSelectionAliases>[2],
		context: Parameters<typeof mapExpressionsToSelectionAliases>[3]
	) {
		return mapExpressionsToSelectionAliases(expressions, fields, selectionAliases, context)
	}
 
	buildSelection(fields: YdbSelectedFieldsOrdered, aliases?: string[]) {
		return buildSelection(fields, aliases)
	}
 
	buildReturningSelection(fields: YdbSelectedFieldsOrdered) {
		return buildReturningSelection(fields)
	}
 
	buildFromTable(table: unknown) {
		return buildFromTable(table)
	}
 
	buildJoins(joins: YdbJoinConfig[] | undefined) {
		return buildJoins(joins)
	}
 
	buildOrderBy(orderBy: Parameters<typeof buildOrderBy>[0]) {
		return buildOrderBy(orderBy)
	}
 
	buildLimit(limit: number | undefined) {
		return buildLimit(limit)
	}
 
	buildOffset(offset: number | undefined) {
		return buildOffset(offset)
	}
 
	buildSetOperationQuery(
		leftSelect: SQL,
		fields: YdbSelectedFieldsOrdered,
		selectionAliases: string[],
		setOperator: YdbSetOperatorConfig
	) {
		return buildSetOperationQuery(leftSelect, fields, selectionAliases, setOperator)
	}
 
	buildSetOperations(
		leftSelect: SQL,
		fields: YdbSelectedFieldsOrdered,
		selectionAliases: string[],
		setOperators: YdbSetOperatorConfig[]
	) {
		return buildSetOperations(leftSelect, fields, selectionAliases, setOperators)
	}
 
	buildSelectQuery(config: YdbSelectConfig) {
		let withSql = this.buildWithCTE(config.withList)
		let query = buildSelectQuery(config)
		return withSql ? yql`${withSql}${query}` : query
	}
 
	buildInsertQuery(config: YdbInsertConfig): SQL {
		let withSql = this.buildWithCTE(config.withList)
		let columnEntries = config.columnEntries ?? getInsertColumnEntries(config.table)
		Iif (columnEntries.length === 0) {
			throw new Error('Insertable columns are missing')
		}
 
		let commandName = config.command ?? 'insert'
		let commandLabel = commandName.charAt(0).toUpperCase() + commandName.slice(1)
		let insertOrder = yql`(${yql.join(
			columnEntries.map(([, column]) => yql.identifier(column.name)),
			yql`, `
		)})`
		let command = yql.raw(commandName)
		let returningSql = config.returning
			? yql` returning ${this.buildReturningSelection(config.returning)}`
			: undefined
 
		if (config.select) {
			let selectQuery = is(config.values, SQL)
				? config.values
				: (config.values as { getSQL(): SQL }).getSQL()
			return yql`${withSql}${command} into ${config.table} ${insertOrder} ${selectQuery}${returningSql}`
		}
 
		Iif (!Array.isArray(config.values)) {
			throw new Error(`YDB ${commandName} values must be an array when select is not used`)
		}
 
		Iif (config.values.length === 0) {
			throw new Error(`${commandLabel} values are empty`)
		}
 
		for (let row of config.values) {
			validateTableColumnKeys(config.table, row, commandName)
		}
 
		let valuesSql = config.values.map(
			(row) =>
				yql`(${yql.join(
					columnEntries.map(
						([key, column]) => yql`${resolveInsertValue(column, row[key])}`
					),
					yql`, `
				)})`
		)
 
		return yql`${withSql}${command} into ${config.table} ${insertOrder} values ${yql.join(valuesSql, yql`, `)}${returningSql}`
	}
 
	buildUpdateSet(table: YdbUpdateConfig['table'], set: NonNullable<YdbUpdateConfig['set']>): SQL {
		let columns = getTableColumns(table)
		let setEntries = Object.entries(columns).flatMap(([key, column]) => {
			let value = resolveUpdateValue(column, set[key])
			if (value === undefined) {
				return []
			}
 
			return [yql`${yql.identifier(column.name)} = ${value}`]
		})
 
		Iif (setEntries.length === 0) {
			throw new Error('Update values are empty')
		}
 
		return yql.join(setEntries, yql`, `)
	}
 
	buildUpdateQuery(config: YdbUpdateConfig): SQL {
		let withSql = this.buildWithCTE(config.withList)
		let returningSql = config.returning
			? yql` returning ${this.buildReturningSelection(config.returning)}`
			: undefined
		let updateKeyword = config.batch ? yql`batch update` : yql`update`
 
		Iif (config.batch && (config.on || returningSql || withSql)) {
			throw new Error('YDB BATCH UPDATE cannot use WITH, ON, or RETURNING')
		}
 
		if (config.on) {
			return yql`${withSql}update ${this.buildFromTable(config.table)} on ${config.on}${returningSql}`
		}
 
		Iif (!config.set) {
			throw new Error('Update values are missing')
		}
 
		let set = config.set
		let setSql = this.buildUpdateSet(config.table, set)
		let whereSql = config.where ? yql` where ${config.where}` : undefined
 
		return yql`${withSql}${updateKeyword} ${this.buildFromTable(config.table)} set ${setSql}${whereSql}${returningSql}`
	}
 
	buildDeleteQuery(config: YdbDeleteConfig): SQL {
		let withSql = this.buildWithCTE(config.withList)
		let returningSql = config.returning
			? yql` returning ${this.buildReturningSelection(config.returning)}`
			: undefined
		let deleteKeyword = config.batch ? yql`batch delete from` : yql`delete from`
 
		Iif (
			config.batch &&
			(config.on || returningSql || withSql || (config.using && config.using.length > 0))
		) {
			throw new Error('YDB BATCH DELETE cannot use WITH, ON, USING, or RETURNING')
		}
 
		if (config.on) {
			Iif (config.where || (config.using && config.using.length > 0)) {
				throw new Error('YDB delete().on() cannot be combined with where() or using()')
			}
 
			return yql`${withSql}delete from ${this.buildFromTable(config.table)} on ${config.on}${returningSql}`
		}
 
		if (config.using && config.using.length > 0) {
			let targetTable = config.table as Parameters<typeof getTableColumns>[0]
			let columns = getTableColumns(targetTable)
			let primaryColumns = getPrimaryColumnKeys(targetTable)
				.map((key) => columns[key])
				.filter((column): column is NonNullable<typeof column> => column !== undefined)
 
			Iif (primaryColumns.length === 0) {
				throw new Error('YDB delete().using() requires at least one primary key column')
			}
 
			let usingJoinsSql = yql.join(
				config.using.map((table) => yql` cross join ${this.buildFromTable(table)}`),
				yql``
			)
			let innerWhereSql = config.where ? yql` where ${config.where}` : undefined
			let keySelection = yql.join(
				primaryColumns.map((column) => yql`${column}`),
				yql`, `
			)
			let outerKey =
				primaryColumns.length === 1 ? yql`${primaryColumns[0]!}` : yql`(${keySelection})`
			let innerKey = primaryColumns.length === 1 ? yql`${primaryColumns[0]!}` : keySelection
 
			return yql`${withSql}delete from ${this.buildFromTable(config.table)} where ${outerKey} in (select ${innerKey} from ${this.buildFromTable(
				config.table
			)}${usingJoinsSql}${innerWhereSql})${returningSql}`
		}
 
		let whereSql = config.where ? yql` where ${config.where}` : undefined
 
		return yql`${withSql}${deleteKeyword} ${this.buildFromTable(config.table)}${whereSql}${returningSql}`
	}
 
	buildRelationalQueryWithoutPK({
		table,
		tableConfig,
		queryConfig: config,
		tableAlias,
		joinOn,
	}: YdbRelationalQueryConfig): YdbRelationalQueryResult {
		let where: SQL | undefined
		let orderBy: SQL[] = []
		let limit: number | undefined
		let offset: number | undefined
		let selectedColumns: string[] = []
		let selectedExtras: Array<{ tsKey: string; field: SQL.Aliased }> = []
 
		let aliasedColumns = Object.fromEntries(
			Object.entries(tableConfig.columns).map(([key, value]) => [
				key,
				aliasedTableColumn(value, tableAlias),
			])
		) as Record<string, Column>
 
		Iif (config === true) {
			selectedColumns = Object.keys(tableConfig.columns)
		} else {
			Eif (config.where) {
				let whereSql =
					typeof config.where === 'function'
						? config.where(aliasedColumns, getOperators())
						: config.where
				where = whereSql ? mapColumnsInSQLToAlias(whereSql, tableAlias) : undefined
			}
 
			if (config.columns) {
				let isIncludeMode = false
				for (let [field, value] of Object.entries(config.columns)) {
					Iif (value === undefined) {
						continue
					}
 
					Eif (field in tableConfig.columns) {
						if (!isIncludeMode && value === true) {
							isIncludeMode = true
						}
						selectedColumns.push(field)
					}
				}
 
				Eif (selectedColumns.length > 0) {
					selectedColumns = isIncludeMode
						? selectedColumns.filter((column) => config.columns?.[column] === true)
						: Object.keys(tableConfig.columns).filter(
								(column) => !selectedColumns.includes(column)
							)
				}
			} else E{
				selectedColumns = Object.keys(tableConfig.columns)
			}
 
			Iif (config.extras) {
				let extras =
					typeof config.extras === 'function'
						? config.extras(aliasedColumns as Record<string, Column>, { sql: yql })
						: config.extras
 
				for (let [tsKey, value] of Object.entries(extras)) {
					selectedExtras.push({
						tsKey,
						field: mapColumnsInAliasedSQLToAlias(value, tableAlias) as SQL.Aliased,
					})
				}
			}
 
			let orderByOrig =
				typeof config.orderBy === 'function'
					? config.orderBy(aliasedColumns, getOrderByOperators())
					: (config.orderBy ?? [])
			if (!Array.isArray(orderByOrig)) {
				orderByOrig = [orderByOrig]
			}
 
			orderBy = orderByOrig.map((orderByValue) => {
				Iif (is(orderByValue, Column)) {
					return aliasedTableColumn(orderByValue, tableAlias) as unknown as SQL
				}
 
				return mapColumnsInSQLToAlias(orderByValue, tableAlias)
			})
 
			Eif (config.limit !== undefined) {
				Iif (!isNumberValue(config.limit)) {
					throw new Error('YDB relational query limit must be a finite number')
				}
				limit = config.limit
			}
 
			let offsetValue = 'offset' in config ? config.offset : undefined
			if (offsetValue !== undefined) {
				Iif (!isNumberValue(offsetValue)) {
					throw new Error('YDB relational query offset must be a finite number')
				}
				offset = offsetValue
			}
		}
 
		Iif (selectedColumns.length === 0 && selectedExtras.length === 0) {
			selectedColumns =
				tableConfig.primaryKey.length > 0
					? tableConfig.primaryKey
							.map(
								(column) =>
									Object.entries(tableConfig.columns).find(
										([, value]) => value === column
									)?.[0]
							)
							.filter((value): value is string => !!value)
					: Object.keys(tableConfig.columns).slice(0, 1)
		}
 
		Iif (selectedColumns.length === 0 && selectedExtras.length === 0) {
			throw new DrizzleError({
				message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`,
			})
		}
 
		let selection = [
			...selectedColumns.map((field) => {
				let column = tableConfig.columns[field]!
				return {
					dbKey: column.name,
					tsKey: field,
					field: aliasedTableColumn(column, tableAlias) as unknown as YdbColumn,
					relationTableTsKey: undefined,
					isJson: false,
					selection: [],
				}
			}),
			...selectedExtras.map(({ tsKey, field }) => ({
				dbKey: field.fieldAlias,
				tsKey,
				field,
				relationTableTsKey: undefined,
				isJson: false,
				isExtra: true,
				selection: [],
			})),
		]
 
		let result = this.buildSelectQuery({
			table: aliasedTable(table, tableAlias),
			fields: {},
			fieldsFlat: selection.map(({ field }) => ({
				path: [],
				field,
			})) as YdbSelectedFieldsOrdered,
			where: and(joinOn, where),
			joins: undefined,
			orderBy,
			groupBy: undefined,
			having: undefined,
			limit,
			offset,
			distinct: false,
			distinctOn: undefined,
			selectionAliases: undefined,
			setOperators: [],
		})
 
		return {
			tableTsKey: tableConfig.tsName,
			sql: result,
			selection,
		}
	}
 
	async migrate(
		migrations: readonly YdbDialectMigration[],
		session: MigrationSessionInput,
		config: string | YdbDialectMigrationConfig = {}
	): Promise<void> {
		let migrationConfig = typeof config === 'string' ? { migrationsTable: config } : config
		let lockEnabled = migrationConfig.migrationLock !== false
		let lock: MigrationLockHandle | undefined
		let primaryError: unknown
		let releaseError: unknown
 
		try {
			if (lockEnabled) {
				await session.execute(yql.raw(buildMigrationLockTableBootstrapSql(migrationConfig)))
				lock = await acquireMigrationLock(session, migrationConfig)
			}
 
			await ensureMigrationHistoryTable(session, migrationConfig)
 
			let appliedRows = await session.values<
				[
					string,
					number | string,
					string,
					YdbMigrationStatus | null,
					number | string | null,
					number | string | null,
					string | null,
					string | null,
					number | string | null,
					number | string | null,
				]
			>(yql.raw(buildMigrationHistorySelectSql(migrationConfig)))
			let historyRows = appliedRows.map((row) => normalizeMigrationHistoryRow(row))
			let historyByHash = new Map(historyRows.map((row) => [row.hash, row]))
			let appliedHashes = new Set(
				historyRows.filter((row) => row.status === 'applied').map((row) => row.hash)
			)
			let orderedMigrations = [...migrations].sort(
				(left, right) => left.folderMillis - right.folderMillis
			)
 
			for (let migration of orderedMigrations) {
				if (appliedHashes.has(migration.hash)) {
					continue
				}
 
				let now = Date.now()
				let existingRow = historyByHash.get(migration.hash)
				if (existingRow) {
					assertMigrationRecoverable(existingRow, now, migrationConfig)
				}
 
				lock?.assertHealthy()
 
				let migrationName = deriveMigrationName(migration)
				let statements = migration.sql
					.map((statement) => statement.trim())
					.filter((statement) => statement !== '')
				let startedAt = Date.now()
				let statementsApplied = 0
 
				await session.execute(
					yql.raw(
						buildMigrationHistoryInsertSql(
							{
								hash: migration.hash,
								folderMillis: migration.folderMillis,
								name: migrationName,
								status: 'running',
								startedAt,
								ownerId: lock?.ownerId,
								statementsTotal: statements.length,
								statementsApplied,
							},
							migrationConfig
						)
					)
				)
 
				try {
					for (let statement of statements) {
						lock?.assertHealthy()
						await session.execute(yql.raw(statement))
						statementsApplied += 1
						await session.execute(
							yql.raw(
								buildMigrationHistoryInsertSql(
									{
										hash: migration.hash,
										folderMillis: migration.folderMillis,
										name: migrationName,
										status: 'running',
										startedAt,
										ownerId: lock?.ownerId,
										statementsTotal: statements.length,
										statementsApplied,
									},
									migrationConfig
								)
							)
						)
					}
 
					let finishedAt = Date.now()
					await session.execute(
						yql.raw(
							buildMigrationHistoryInsertSql(
								{
									hash: migration.hash,
									folderMillis: migration.folderMillis,
									name: migrationName,
									status: 'applied',
									startedAt,
									finishedAt,
									ownerId: lock?.ownerId,
									statementsTotal: statements.length,
									statementsApplied,
								},
								migrationConfig
							)
						)
					)
 
					appliedHashes.add(migration.hash)
					historyByHash.set(migration.hash, {
						hash: migration.hash,
						folderMillis: migration.folderMillis,
						name: migrationName,
						status: 'applied',
						startedAt,
						finishedAt,
						ownerId: lock?.ownerId,
						statementsTotal: statements.length,
						statementsApplied,
					})
				} catch (error) {
					let finishedAt = Date.now()
					let message = getErrorMessage(error)
					await session.execute(
						yql.raw(
							buildMigrationHistoryInsertSql(
								{
									hash: migration.hash,
									folderMillis: migration.folderMillis,
									name: migrationName,
									status: 'failed',
									startedAt,
									finishedAt,
									error: message.slice(0, 4096),
									ownerId: lock?.ownerId,
									statementsTotal: statements.length,
									statementsApplied,
								},
								migrationConfig
							)
						)
					)
 
					throw new Error(
						`YDB migration "${migrationName}" failed after ${statementsApplied}/${statements.length} statements: ${message}`,
						{ cause: error }
					)
				}
			}
		} catch (error) {
			primaryError = error
		} finally {
			if (lock) {
				try {
					await lock.release()
				} catch (error) {
					releaseError = error
				}
			}
		}
 
		if (primaryError) {
			throw primaryError
		}
 
		Iif (releaseError) {
			throw releaseError
		}
	}
 
	sqlToQuery(sqlValue: SQL, invokeSource?: 'indexes'): QueryWithTypings {
		return sqlValue.toQuery({
			casing: this.#casing,
			escapeName: this.escapeName,
			escapeParam: this.escapeParam,
			escapeString: this.escapeString,
			prepareTyping: this.prepareTyping,
			invokeSource,
		})
	}
}