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

88.95% Statements 153/172
81.92% Branches 145/177
97.77% Functions 44/45
88.88% Lines 152/171

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                                32x       2x       2x               16x 22x 15x     7x               7x     16x                 15x               15x 5x   5x       5x     10x       42x                 11x 16x 11x   11x 1x     10x     5x 5x   15x                   136x       136x 308x   308x         308x 7x         301x 301x                   136x       2x 2x           20x       20x 37x       37x 1x     36x 36x           20x       268x 3x   3x 2x     1x     265x 25x     240x       138x 126x     12x 12x 12x   12x       12x     12x       160x 131x     29x 41x           136x 134x     2x 3x           155x       155x       136x 134x     2x       2x       2x 2x           136x 132x     4x 2x       2x       136x       136x 135x     1x       136x 134x     2x 2x                         136x       136x     136x 136x   136x   13x       136x 136x 136x 136x 136x 136x 136x       136x     136x 136x 136x 136x   136x       136x               4x       4x 4x 4x   5x           4x                                       4x               4x 8x     4x   4x       4x                       6x 6x 6x 6x 6x   6x       6x 6x 6x 6x 6x   6x 6x   6x         6x       6x       6x                 13x   13x                 13x 7x 7x     6x                                 9x   11x           136x 136x   136x                                                         136x 129x     7x              
import { Column } from 'drizzle-orm/column'
import { is } from 'drizzle-orm/entity'
import { SQL, type SQLChunk, type SQLWrapper, sql as yql } from 'drizzle-orm/sql/sql'
import { Subquery } from 'drizzle-orm/subquery'
import { Table } from 'drizzle-orm/table'
import { type YdbSelectedFieldsOrdered, orderSelectedFields } from '../ydb-core/result-mapping.js'
import type { YdbJoinConfig, YdbSelectConfig, YdbSetOperatorConfig } from './dialect.types.js'
import {
	type YdbFlattenConfig,
	type YdbSampleConfig,
	type YdbWindowClause,
	matchRecognize as buildMatchRecognizeClause,
	renderUniqueDistinctHints,
} from '../ydb-core/query-builders/select-syntax.js'
 
function qualifyIdentifier(tableAlias: string, columnName: string): SQL {
	return yql`${yql.identifier(tableAlias)}.${yql.identifier(columnName)}`
}
 
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}`
}
 
function findSelectionAlias(
	value: unknown,
	fields: YdbSelectedFieldsOrdered,
	selectionAliases: string[]
): string | undefined {
	let foundIndex = fields.findIndex(({ path, field }) => {
		if (field === value) {
			return true
		}
 
		Iif (is(value, SQL.Aliased)) {
			if (is(field, SQL.Aliased) && field.fieldAlias === value.fieldAlias) {
				return true
			}
 
			return path[path.length - 1] === value.fieldAlias
		}
 
		return false
	})
 
	return foundIndex >= 0 ? selectionAliases[foundIndex] : undefined
}
 
function mapChunkToSelectionAlias(
	chunk: SQLChunk,
	fields: YdbSelectedFieldsOrdered,
	selectionAliases: string[],
	context: string
): SQLChunk {
	Iif (is(chunk, SQL)) {
		return new SQL(
			chunk.queryChunks.map((value) =>
				mapChunkToSelectionAlias(value, fields, selectionAliases, context)
			)
		)
	}
 
	if (is(chunk, Column) || is(chunk, SQL.Aliased)) {
		let alias = findSelectionAlias(chunk, fields, selectionAliases)
 
		Iif (!alias) {
			throw new Error(`YDB ${context} can only reference selected fields`)
		}
 
		return yql.identifier(alias)
	}
 
	return chunk
}
 
export function getSelectionAliases(fields: YdbSelectedFieldsOrdered): string[] {
	return fields.map((_, index) => `__ydb_f${index}`)
}
 
export function mapExpressionsToSelectionAliases(
	expressions: SQLWrapper[],
	fields: YdbSelectedFieldsOrdered,
	selectionAliases: string[],
	context: string
): SQLWrapper[] {
	return expressions.map((expression) => {
		if (is(expression, Column) || is(expression, SQL.Aliased)) {
			let alias = findSelectionAlias(expression, fields, selectionAliases)
 
			if (!alias) {
				throw new Error(`YDB ${context} can only reference selected fields`)
			}
 
			return yql.identifier(alias)
		}
 
		Eif (is(expression, SQL)) {
			return new SQL(
				expression.queryChunks.map((chunk) =>
					mapChunkToSelectionAlias(chunk, fields, selectionAliases, context)
				)
			)
		}
 
		return expression
	})
}
 
export function buildSelection(fields: YdbSelectedFieldsOrdered, aliases?: string[]): SQL {
	Iif (fields.length === 0) {
		return yql.raw('*')
	}
 
	let selection = fields.map(({ field }, index) => {
		let alias = aliases?.[index]
 
		Iif (is(field, SQL.Aliased) && (field as any).isSelectionField) {
			let base = yql.identifier(field.fieldAlias)
			return alias ? yql`${base} as ${yql.identifier(alias)}` : base
		}
 
		if (is(field, SQL.Aliased)) {
			return alias
				? yql`${field.sql} as ${yql.identifier(alias)}`
				: yql`${field.sql} as ${yql.identifier(field.fieldAlias)}`
		}
 
		Eif (is(field, Column) || is(field, SQL) || is(field, Subquery)) {
			return alias
				? yql`${field as SQLWrapper} as ${yql.identifier(alias)}`
				: yql`${field as SQLWrapper}`
		}
 
		return alias
			? yql`${field as SQLWrapper} as ${yql.identifier(alias)}`
			: yql`${field as SQLWrapper}`
	})
 
	return yql.join(selection, yql`, `)
}
 
function buildSelectionWithout(without: SQLWrapper[]): SQL {
	return yql`* WITHOUT ${yql.join(
		without.map((value) => yql`${value}`),
		yql`, `
	)}`
}
 
export function buildReturningSelection(fields: YdbSelectedFieldsOrdered): SQL {
	Iif (fields.length === 0) {
		return yql.raw('*')
	}
 
	let selection = fields.map(({ field }) => {
		Iif (is(field, SQL.Aliased) && (field as any).isSelectionField) {
			return yql.identifier(field.fieldAlias)
		}
 
		if (is(field, SQL.Aliased)) {
			return yql`${field.sql} as ${yql.identifier(field.fieldAlias)}`
		}
 
		Eif (is(field, Column)) {
			return yql.identifier(field.name)
		}
 
		return yql`${field as SQLWrapper}`
	})
 
	return yql.join(selection, yql`, `)
}
 
export function buildFromTable(table: unknown): SQLWrapper {
	if (is(table, Subquery)) {
		let alias = table._.alias
 
		if (table._.isWith) {
			return yql`${yql.raw(yqlBindingName(alias))} as ${yql.identifier(alias)}`
		}
 
		return yql`(${table._.sql}) as ${yql.identifier(alias)}`
	}
 
	if (is(table, Table) && (table as any)[(Table as any).Symbol.IsAlias]) {
		return yql`${yql.identifier((table as any)[(Table as any).Symbol.OriginalName])} ${yql.identifier((table as any)[(Table as any).Symbol.Name])}`
	}
 
	return table as SQLWrapper
}
 
export function buildJoins(joins: YdbJoinConfig[] | undefined): SQL | undefined {
	if (!joins || joins.length === 0) {
		return undefined
	}
 
	let joinsSql = joins.map((join) => {
		let onSql = join.on ? yql` on ${join.on}` : undefined
		let joinKeyword = yql.raw(`${join.joinType} join`)
 
		Iif (is(join.table, Table) && (join.table as any)[(Table as any).Symbol.IsAlias]) {
			return yql`${joinKeyword} ${yql.identifier((join.table as any)[(Table as any).Symbol.OriginalName])} ${yql.identifier((join.table as any)[(Table as any).Symbol.Name])}${onSql}`
		}
 
		return yql`${joinKeyword} ${join.table as SQLWrapper}${onSql}`
	})
 
	return yql` ${yql.join(joinsSql, yql` `)}`
}
 
export function buildOrderBy(orderBy: SQLWrapper[] | undefined): SQL | undefined {
	if (!orderBy || orderBy.length === 0) {
		return undefined
	}
 
	return yql` order by ${yql.join(
		orderBy.map((value) => yql`${value}`),
		yql`, `
	)}`
}
 
export function buildAssumeOrderBy(assumeOrderBy: SQLWrapper[] | undefined): SQL | undefined {
	if (!assumeOrderBy || assumeOrderBy.length === 0) {
		return undefined
	}
 
	return yql` assume order by ${yql.join(
		assumeOrderBy.map((value) => yql`${value}`),
		yql`, `
	)}`
}
 
export function buildLimit(limit: number | undefined): SQL | undefined {
	return limit !== undefined ? yql` limit ${limit}` : undefined
}
 
export function buildOffset(offset: number | undefined): SQL | undefined {
	return offset !== undefined ? yql` offset ${offset}` : undefined
}
 
function buildFlatten(flatten: YdbFlattenConfig | undefined): SQL | undefined {
	if (!flatten) {
		return undefined
	}
 
	Iif (flatten.mode === 'columns') {
		return yql` flatten columns`
	}
 
	Iif (!flatten.expressions || flatten.expressions.length === 0) {
		throw new Error('YDB flatten requires at least one expression')
	}
 
	return yql` flatten ${yql.raw(flatten.mode)} ${yql.join(
		flatten.expressions.map((value) => yql`${value}`),
		yql`, `
	)}`
}
 
function buildSample(sample: YdbSampleConfig | undefined): SQL | undefined {
	if (!sample) {
		return undefined
	}
 
	if (sample.kind === 'sample') {
		return yql` sample ${typeof sample.ratio === 'number' ? yql`${sample.ratio}` : sample.ratio}`
	}
 
	let repeatable =
		sample.repeatable === undefined
			? undefined
			: yql` repeatable(${typeof sample.repeatable === 'number' ? yql`${sample.repeatable}` : sample.repeatable})`
 
	return yql` tablesample ${yql.raw(sample.method)}(${typeof sample.size === 'number' ? yql`${sample.size}` : sample.size})${repeatable}`
}
 
function buildMatchRecognize(matchRecognize: YdbSelectConfig['matchRecognize']): SQL | undefined {
	if (!matchRecognize) {
		return undefined
	}
 
	return yql` match_recognize ${buildMatchRecognizeClause(matchRecognize)}`
}
 
function buildWindows(windows: YdbWindowClause[] | undefined): SQL | undefined {
	if (!windows || windows.length === 0) {
		return undefined
	}
 
	return yql` window ${yql.join(
		windows.map((window) => yql`${yql.identifier(window.name)} AS ${window.definition}`),
		yql`, `
	)}`
}
 
function buildSimpleSelectQuery(
	config: Omit<YdbSelectConfig, 'table' | 'fields' | 'fieldsFlat' | 'setOperators'> & {
		table?: unknown
		fieldsFlat: YdbSelectedFieldsOrdered
		extraSelections?: SQL[]
	}
): SQL {
	let selection =
		config.without && config.without.length > 0
			? buildSelectionWithout(config.without)
			: buildSelection(config.fieldsFlat, config.selectionAliases)
	let allSelections =
		config.extraSelections && config.extraSelections.length > 0
			? yql`${selection}, ${yql.join(config.extraSelections, yql`, `)}`
			: selection
	let joinsSql = buildJoins(config.joins)
	let whereSql = config.where ? yql` where ${config.where}` : undefined
	let groupBySql =
		config.groupBy && config.groupBy.length > 0
			? yql` ${yql.raw(config.groupByCompact ? 'group compact by' : 'group by')} ${yql.join(
					config.groupBy.map((value) => yql`${value}`),
					yql`, `
				)}`
			: undefined
	let havingSql = config.having ? yql` having ${config.having}` : undefined
	let windowSql = buildWindows(config.windows)
	let orderBySql = buildOrderBy(config.orderBy)
	let assumeOrderBySql = buildAssumeOrderBy(config.assumeOrderBy)
	let limitSql = buildLimit(config.limit)
	let offsetSql = buildOffset(config.offset)
	let intoResultSql = config.intoResult
		? yql` into result ${yql.identifier(config.intoResult)}`
		: undefined
	let uniqueDistinctSql =
		config.uniqueDistinctHints && config.uniqueDistinctHints.length > 0
			? yql` ${renderUniqueDistinctHints(config.uniqueDistinctHints)}`
			: undefined
	let distinctSql = config.distinct ? yql` distinct` : undefined
	let sampleSql = buildSample(config.sample)
	let matchRecognizeSql = buildMatchRecognize(config.matchRecognize)
	let flattenSql = buildFlatten(config.flatten)
	let fromSql =
		config.table === undefined
			? undefined
			: yql` from ${buildFromTable(config.table)}${sampleSql}${matchRecognizeSql}${flattenSql}`
 
	return yql`select${uniqueDistinctSql}${distinctSql} ${allSelections}${fromSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${windowSql}${orderBySql}${assumeOrderBySql}${limitSql}${offsetSql}${intoResultSql}`
}
 
function buildDistinctOnQuery(
	config: YdbSelectConfig,
	fieldsFlat: YdbSelectedFieldsOrdered,
	selectionAliases: string[]
): SQL {
	Iif (!config.distinctOn || config.distinctOn.length === 0) {
		throw new Error('YDB distinctOn() requires at least one expression')
	}
 
	let distinctAlias = '__ydb_distinct_on'
	let rowNumberAlias = '__ydb_row_number'
	let rowNumberSelection = yql`row_number() over (
      partition by ${yql.join(
			config.distinctOn.map((value) => yql`${value}`),
			yql`, `
		)}
      ${buildOrderBy(config.orderBy)}
    ) as ${yql.identifier(rowNumberAlias)}`
 
	let innerQuery = buildSimpleSelectQuery({
		table: config.table,
		fieldsFlat,
		joins: config.joins,
		where: config.where,
		groupBy: config.groupBy,
		groupByCompact: config.groupByCompact,
		having: config.having,
		windows: config.windows,
		distinct: false,
		without: config.without,
		flatten: config.flatten,
		sample: config.sample,
		matchRecognize: config.matchRecognize,
		uniqueDistinctHints: config.uniqueDistinctHints,
		selectionAliases,
		extraSelections: [rowNumberSelection],
	})
 
	let outerOrderBy =
		config.orderBy && config.orderBy.length > 0
			? mapExpressionsToSelectionAliases(
					config.orderBy,
					fieldsFlat,
					selectionAliases,
					'distinctOn() orderBy()'
				)
			: undefined
	let selection = yql.join(
		selectionAliases.map((alias) => yql.identifier(alias)),
		yql`, `
	)
	let rowNumberFilter = yql`${qualifyIdentifier(distinctAlias, rowNumberAlias)} = 1`
 
	let intoResultSql = config.intoResult
		? yql` into result ${yql.identifier(config.intoResult)}`
		: undefined
 
	return yql`select ${selection} from (${innerQuery}) as ${yql.identifier(distinctAlias)} where ${rowNumberFilter}${buildOrderBy(outerOrderBy)}${buildLimit(config.limit)}${buildOffset(config.offset)}${intoResultSql}`
}
 
function buildEmulatedSetOperationQuery(
	type: 'intersect' | 'except',
	leftSelect: SQL,
	rightSelect: SQL,
	selectionAliases: string[],
	orderBy: SQLWrapper[] | undefined,
	limit: number | undefined,
	offset: number | undefined
): SQL {
	let leftAlias = '__ydb_left'
	let rightAlias = '__ydb_right'
	let matchAlias = '__ydb_match'
	let rightInputAlias = '__ydb_right_input'
	let rightSelection = yql.join(
		selectionAliases.map(
			(alias) => yql`${qualifyIdentifier(rightInputAlias, alias)} as ${yql.identifier(alias)}`
		),
		yql`, `
	)
	let rightComparable = yql`select ${rightSelection}, 1 as ${yql.identifier(matchAlias)} from (${rightSelect}) as ${yql.identifier(rightInputAlias)}`
	let joinConditions = selectionAliases.map((alias) => {
		let leftValue = qualifyIdentifier(leftAlias, alias)
		let rightValue = qualifyIdentifier(rightAlias, alias)
		return yql`${leftValue} = ${rightValue}`
	})
	let onSql = yql.join(joinConditions, yql` and `)
	let selection = yql.join(
		selectionAliases.map(
			(alias) => yql`${qualifyIdentifier(leftAlias, alias)} as ${yql.identifier(alias)}`
		),
		yql`, `
	)
	let joinSql =
		type === 'intersect'
			? yql`inner join (${rightComparable}) as ${yql.identifier(rightAlias)} on ${onSql}`
			: yql`left join (${rightComparable}) as ${yql.identifier(rightAlias)} on ${onSql}`
	let whereSql =
		type === 'except'
			? yql` where ${qualifyIdentifier(rightAlias, matchAlias)} is null`
			: undefined
 
	return yql`select distinct ${selection} from (${leftSelect}) as ${yql.identifier(leftAlias)} ${joinSql}${whereSql}${buildOrderBy(orderBy)}${buildLimit(limit)}${buildOffset(offset)}`
}
 
export function buildSetOperationQuery(
	leftSelect: SQL,
	fields: YdbSelectedFieldsOrdered,
	selectionAliases: string[],
	setOperator: YdbSetOperatorConfig
): SQL {
	let rightSelect = setOperator.rightSelect.getSQL(selectionAliases)
	let mappedOrderBy =
		setOperator.orderBy && setOperator.orderBy.length > 0
			? mapExpressionsToSelectionAliases(
					setOperator.orderBy,
					fields,
					selectionAliases,
					`${setOperator.type}() orderBy()`
				)
			: undefined
 
	if (setOperator.type === 'union') {
		let operator = yql.raw(`union${setOperator.isAll ? ' all' : ''}`)
		return yql`${leftSelect} ${operator} ${rightSelect}${buildOrderBy(mappedOrderBy)}${buildLimit(setOperator.limit)}${buildOffset(setOperator.offset)}`
	}
 
	return buildEmulatedSetOperationQuery(
		setOperator.type,
		leftSelect,
		rightSelect,
		selectionAliases,
		mappedOrderBy,
		setOperator.limit,
		setOperator.offset
	)
}
 
export function buildSetOperations(
	leftSelect: SQL,
	fields: YdbSelectedFieldsOrdered,
	selectionAliases: string[],
	setOperators: YdbSetOperatorConfig[]
): SQL {
	return setOperators.reduce(
		(current, setOperator) =>
			buildSetOperationQuery(current, fields, selectionAliases, setOperator),
		leftSelect
	)
}
 
export function buildSelectQuery(config: YdbSelectConfig): SQL {
	let fieldsFlat = config.fieldsFlat ?? orderSelectedFields(config.fields)
	let selectionAliases = config.selectionAliases
	let baseQuery =
		config.distinctOn && config.distinctOn.length > 0
			? buildDistinctOnQuery(
					config,
					fieldsFlat,
					selectionAliases ?? getSelectionAliases(fieldsFlat)
				)
			: buildSimpleSelectQuery({
					table: config.table,
					fieldsFlat,
					joins: config.joins,
					where: config.where,
					groupBy: config.groupBy,
					groupByCompact: config.groupByCompact,
					having: config.having,
					windows: config.windows,
					orderBy: config.orderBy,
					assumeOrderBy: config.assumeOrderBy,
					limit: config.limit,
					offset: config.offset,
					intoResult: config.intoResult,
					without: config.without,
					flatten: config.flatten,
					sample: config.sample,
					matchRecognize: config.matchRecognize,
					uniqueDistinctHints: config.uniqueDistinctHints,
					distinct: config.distinct,
					selectionAliases,
				})
 
	if (config.setOperators.length === 0) {
		return baseQuery
	}
 
	return buildSetOperations(
		baseQuery,
		fieldsFlat,
		selectionAliases ?? getSelectionAliases(fieldsFlat),
		config.setOperators
	)
}