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

81.3% Statements 100/123
65.45% Branches 72/110
87.23% Functions 41/47
81.3% Lines 100/123

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                                                                                                                              23x           8x       3x 3x       3x       12x             3x       3x 2x 2x       2x   4x       4x 8x             1x 1x       1x 2x     1x     2x       2x 2x   4x         2x 2x 4x                   1x           4x               8x 10x           5x       1x 1x       2x 2x 2x   2x       4x 4x         2x   2x       2x 2x             3x       3x 1x     2x 2x       1x         1x             1x   1x         1x     1x 1x         1x 1x     1x   1x     2x 2x           1x       2x 2x       2x 2x       2x       2x 4x 4x 4x     2x       4x 2x     2x 2x 1x   2x 2x   2x 1x     2x       2x 2x       1x       1x       1x       1x       1x 2x           1x       1x                                     2x                   2x       2x                 1x       1x       1x                               1x                               1x            
import { SQL, type SQLWrapper, sql as yql } from 'drizzle-orm/sql/sql'
 
export type YdbOrderDirection = 'asc' | 'desc'
 
export type YdbValuesPrimitive = string | number | boolean | bigint | null | Uint8Array | Date
export type YdbValuesRow =
	| readonly YdbValuesPrimitive[]
	| Readonly<Record<string, YdbValuesPrimitive>>
 
export interface YdbValuesOptions {
	alias?: string | undefined
	columns?: readonly string[] | undefined
}
 
export type YdbFlattenMode = 'by' | 'list by' | 'dict by' | 'optional by' | 'columns'
 
export interface YdbFlattenConfig {
	mode: YdbFlattenMode
	expressions?: SQLWrapper[] | undefined
}
 
export type YdbSampleConfig =
	| { kind: 'sample'; ratio: number | SQLWrapper }
	| {
			kind: 'tablesample'
			method: string
			size: number | SQLWrapper
			repeatable?: number | SQLWrapper | undefined
	  }
 
export interface YdbMatchRecognizeConfig {
	partitionBy?: SQLWrapper[] | undefined
	orderBy?: SQLWrapper[] | undefined
	measures?: Readonly<Record<string, SQLWrapper>> | undefined
	rowsPerMatch?: 'ONE ROW PER MATCH' | 'ALL ROWS PER MATCH' | undefined
	afterMatchSkip?: string | undefined
	pattern: string | SQLWrapper
	define?: Readonly<Record<string, SQLWrapper>> | undefined
}
 
export interface YdbUniqueDistinctHint {
	kind: 'unique' | 'distinct'
	columns?: readonly string[] | undefined
}
 
export interface YdbWindowClause {
	name: string
	definition: SQLWrapper
}
 
export interface YdbWindowDefinitionConfig {
	partitionBy?: readonly SQLWrapper[] | undefined
	orderBy?: readonly SQLWrapper[] | undefined
	frame?: string | SQLWrapper | undefined
}
 
export type YdbGroupingSet = readonly SQLWrapper[]
 
export type YdbKnnDistanceFunction = 'CosineDistance' | 'EuclideanDistance' | 'ManhattanDistance'
 
export type YdbKnnSimilarityFunction = 'CosineSimilarity' | 'InnerProductSimilarity'
 
function assertIdentifier(name: string, context: string): void {
	Iif (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)) {
		throw new Error(`YDB ${context} must be a simple identifier`)
	}
}
 
function assertHintColumn(name: string): void {
	assertIdentifier(name, 'UNIQUE DISTINCT hint column')
}
 
function renderBindingName(name: string): SQL {
	let binding = name.startsWith('$') ? name : `$${name}`
	Iif (!/^\$[A-Za-z_][A-Za-z0-9_]*$/u.test(binding)) {
		throw new Error('YDB AS_TABLE binding must look like $name')
	}
 
	return yql.raw(binding)
}
 
function renderValue(value: YdbValuesPrimitive): SQL {
	return value === null ? yql`NULL` : yql`${value}`
}
 
function normalizeRows(rows: readonly YdbValuesRow[]): {
	rows: readonly SQL[]
	columns?: string[]
} {
	Iif (rows.length === 0) {
		throw new Error('YDB VALUES requires at least one row')
	}
 
	if (Array.isArray(rows[0])) {
		let expectedLength = (rows[0] as readonly unknown[]).length
		Iif (expectedLength === 0) {
			throw new Error('YDB VALUES rows require at least one value')
		}
 
		return {
			rows: rows.map((row) => {
				Iif (!Array.isArray(row) || row.length !== expectedLength) {
					throw new Error('YDB VALUES array rows must have the same length')
				}
 
				return yql`(${yql.join(
					row.map((value) => renderValue(value)),
					yql`, `
				)})`
			}),
		}
	}
 
	let columns = Object.keys(rows[0] as Record<string, YdbValuesPrimitive>)
	Iif (columns.length === 0) {
		throw new Error('YDB VALUES object rows require at least one key')
	}
 
	for (let column of columns) {
		assertIdentifier(column, 'VALUES column')
	}
 
	return {
		columns,
		rows: rows.map((row) => {
			Iif (Array.isArray(row)) {
				throw new Error('YDB VALUES cannot mix object and array rows')
			}
 
			let keys = Object.keys(row)
			Iif (
				keys.length !== columns.length ||
				keys.some((key, index) => key !== columns[index])
			) {
				throw new Error('YDB VALUES object rows must have identical key order')
			}
 
			let objectRow = row as Record<string, YdbValuesPrimitive>
			return yql`(${yql.join(
				columns.map((column) => renderValue(objectRow[column] ?? null)),
				yql`, `
			)})`
		}),
	}
}
 
function isMatchRecognizeConfig(
	value: YdbMatchRecognizeConfig | SQLWrapper
): value is YdbMatchRecognizeConfig {
	return typeof value === 'object' && value !== null && 'pattern' in value
}
 
function isWindowDefinitionConfig(
	value: YdbWindowDefinitionConfig | SQLWrapper
): value is YdbWindowDefinitionConfig {
	return (
		typeof value === 'object' &&
		value !== null &&
		('partitionBy' in value || 'orderBy' in value || 'frame' in value)
	)
}
 
function renderExpressionList(expressions: readonly SQLWrapper[]): SQL {
	return yql.join(
		expressions.map((value) => yql`${value}`),
		yql`, `
	)
}
 
function renderIntervalLiteral(value: string | SQLWrapper): SQLWrapper {
	return typeof value === 'string' ? yql`${value}` : value
}
 
export function values(rows: readonly YdbValuesRow[]): SQL {
	let normalized = normalizeRows(rows)
	return yql`VALUES ${yql.join([...normalized.rows], yql`, `)}`
}
 
export function valuesTable(rows: readonly YdbValuesRow[], options: YdbValuesOptions = {}): SQL {
	let normalized = normalizeRows(rows)
	let alias = options.alias
	let columns = options.columns ?? normalized.columns
	let columnSql =
		columns && columns.length > 0
			? yql.raw(
					`(${columns
						.map((column) => {
							assertIdentifier(column, 'VALUES column')
							return `\`${column.replace(/`/g, '``')}\``
						})
						.join(', ')})`
				)
			: undefined
	let source = yql`(${yql.raw('VALUES')} ${yql.join([...normalized.rows], yql`, `)})`
 
	Iif (!alias) {
		return source
	}
 
	assertIdentifier(alias, 'VALUES alias')
	return columnSql
		? yql`${source} as ${yql.identifier(alias)}${columnSql}`
		: yql`${source} as ${yql.identifier(alias)}`
}
 
export function asTable(binding: string | SQLWrapper, alias?: string): SQL {
	let source =
		typeof binding === 'string'
			? yql`AS_TABLE(${renderBindingName(binding)})`
			: yql`AS_TABLE(${binding})`
 
	if (!alias) {
		return source
	}
 
	assertIdentifier(alias, 'AS_TABLE alias')
	return yql`${source} as ${yql.identifier(alias)}`
}
 
export function matchRecognize(config: YdbMatchRecognizeConfig | SQLWrapper): SQL {
	Iif (!isMatchRecognizeConfig(config)) {
		return yql`${config}`
	}
 
	let partitionBy =
		config.partitionBy && config.partitionBy.length > 0
			? yql`PARTITION BY ${yql.join(
					config.partitionBy.map((value) => yql`${value}`),
					yql`, `
				)} `
			: undefined
	let orderBy =
		config.orderBy && config.orderBy.length > 0
			? yql`ORDER BY ${yql.join(
					config.orderBy.map((value) => yql`${value}`),
					yql`, `
				)} `
			: undefined
	let measures =
		config.measures && Object.keys(config.measures).length > 0
			? yql`MEASURES ${yql.join(
					Object.entries(config.measures).map(([alias, expression]) => {
						assertIdentifier(alias, 'MATCH_RECOGNIZE measure alias')
						return yql`${expression} AS ${yql.identifier(alias)}`
					}),
					yql`, `
				)} `
			: undefined
	let rowsPerMatch = config.rowsPerMatch ? yql.raw(`${config.rowsPerMatch} `) : undefined
	let afterMatchSkip = config.afterMatchSkip
		? yql.raw(`AFTER MATCH SKIP ${config.afterMatchSkip} `)
		: undefined
	let pattern = typeof config.pattern === 'string' ? yql.raw(config.pattern) : config.pattern
	let define =
		config.define && Object.keys(config.define).length > 0
			? yql` DEFINE ${yql.join(
					Object.entries(config.define).map(([name, expression]) => {
						assertIdentifier(name, 'MATCH_RECOGNIZE variable')
						return yql`${yql.raw(name)} AS ${expression}`
					}),
					yql`, `
				)}`
			: undefined
 
	return yql`(${partitionBy}${orderBy}${measures}${rowsPerMatch}${afterMatchSkip}PATTERN ${pattern}${define})`
}
 
export function uniqueHint(...columns: string[]): YdbUniqueDistinctHint {
	columns.forEach(assertHintColumn)
	return { kind: 'unique', columns }
}
 
export function distinctHint(...columns: string[]): YdbUniqueDistinctHint {
	columns.forEach(assertHintColumn)
	return { kind: 'distinct', columns }
}
 
export function renderUniqueDistinctHints(hints: readonly YdbUniqueDistinctHint[]): SQL {
	Iif (hints.length === 0) {
		throw new Error('YDB UNIQUE DISTINCT hints require at least one hint')
	}
 
	let rendered = hints.map((hint) => {
		let columns = hint.columns ?? []
		columns.forEach(assertHintColumn)
		return `${hint.kind}(${columns.join(' ')})`
	})
 
	return yql.raw(`/*+ ${rendered.join(' ')} */`)
}
 
export function windowDefinition(config: YdbWindowDefinitionConfig | SQLWrapper): SQL {
	if (!isWindowDefinitionConfig(config)) {
		return yql`${config}`
	}
 
	let parts: SQL[] = []
	if (config.partitionBy && config.partitionBy.length > 0) {
		parts.push(yql`PARTITION BY ${renderExpressionList(config.partitionBy)}`)
	}
	Eif (config.orderBy && config.orderBy.length > 0) {
		parts.push(yql`ORDER BY ${renderExpressionList(config.orderBy)}`)
	}
	if (config.frame) {
		parts.push(typeof config.frame === 'string' ? yql.raw(config.frame) : yql`${config.frame}`)
	}
 
	return yql`(${yql.join(parts, yql` `)})`
}
 
export function groupKey(expression: SQLWrapper, alias: string): SQL {
	assertIdentifier(alias, 'GROUP BY alias')
	return yql`${expression} AS ${yql.identifier(alias)}`
}
 
export function rollup(...expressions: SQLWrapper[]): SQL {
	Iif (expressions.length === 0) {
		throw new Error('YDB ROLLUP requires at least one expression')
	}
 
	return yql`ROLLUP(${renderExpressionList(expressions)})`
}
 
export function cube(...expressions: SQLWrapper[]): SQL {
	Iif (expressions.length === 0) {
		throw new Error('YDB CUBE requires at least one expression')
	}
 
	return yql`CUBE(${renderExpressionList(expressions)})`
}
 
export function groupingSets(...sets: [YdbGroupingSet, ...YdbGroupingSet[]]): SQL {
	return yql`GROUPING SETS(${yql.join(
		sets.map((set) => yql`(${renderExpressionList(set)})`),
		yql`, `
	)})`
}
 
export function grouping(...expressions: SQLWrapper[]): SQL {
	Iif (expressions.length === 0) {
		throw new Error('YDB GROUPING requires at least one expression')
	}
 
	return yql`GROUPING(${renderExpressionList(expressions)})`
}
 
export function sessionWindow(
	orderExpression: SQLWrapper,
	timeoutExpression: string | SQLWrapper
): SQL
export function sessionWindow(
	orderExpression: SQLWrapper,
	initLambda: SQLWrapper,
	updateLambda: SQLWrapper,
	calculateLambda: SQLWrapper
): SQL
export function sessionWindow(
	orderExpression: SQLWrapper,
	second: string | SQLWrapper,
	updateLambda?: SQLWrapper,
	calculateLambda?: SQLWrapper
): SQL {
	Iif (updateLambda || calculateLambda) {
		if (!updateLambda || !calculateLambda || typeof second === 'string') {
			throw new Error(
				'YDB SessionWindow extended form requires init, update, and calculate lambdas'
			)
		}
 
		return yql`SessionWindow(${orderExpression}, ${second}, ${updateLambda}, ${calculateLambda})`
	}
 
	return yql`SessionWindow(${orderExpression}, ${renderIntervalLiteral(second)})`
}
 
export function sessionStart(): SQL {
	return yql.raw('SessionStart()')
}
 
export function hop(
	timeExtractor: SQLWrapper,
	hopInterval: string | SQLWrapper,
	windowInterval: string | SQLWrapper,
	delay: string | SQLWrapper
): SQL {
	return yql`HOP(${timeExtractor}, ${renderIntervalLiteral(hopInterval)}, ${renderIntervalLiteral(windowInterval)}, ${renderIntervalLiteral(delay)})`
}
 
export function hopStart(): SQL {
	return yql.raw('HOP_START()')
}
 
export function hopEnd(): SQL {
	return yql.raw('HOP_END()')
}
 
export function knnDistance(
	fn: YdbKnnDistanceFunction,
	vector: SQLWrapper,
	target: SQLWrapper
): SQL {
	return yql`${yql.raw(`Knn::${fn}`)}(${vector}, ${target})`
}
 
export function knnSimilarity(
	fn: YdbKnnSimilarityFunction,
	vector: SQLWrapper,
	target: SQLWrapper
): SQL {
	return yql`${yql.raw(`Knn::${fn}`)}(${vector}, ${target})`
}
 
export function knnCosineDistance(vector: SQLWrapper, target: SQLWrapper): SQL {
	return knnDistance('CosineDistance', vector, target)
}
 
export function knnEuclideanDistance(vector: SQLWrapper, target: SQLWrapper): SQL {
	return knnDistance('EuclideanDistance', vector, target)
}
 
export function knnManhattanDistance(vector: SQLWrapper, target: SQLWrapper): SQL {
	return knnDistance('ManhattanDistance', vector, target)
}
 
export function knnCosineSimilarity(vector: SQLWrapper, target: SQLWrapper): SQL {
	return knnSimilarity('CosineSimilarity', vector, target)
}
 
export function knnInnerProductSimilarity(vector: SQLWrapper, target: SQLWrapper): SQL {
	return knnSimilarity('InnerProductSimilarity', vector, target)
}