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

93.54% Statements 116/124
79.45% Branches 58/73
100% Functions 37/37
93.44% Lines 114/122

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                                                              12x       4x       4x       1x               8x 8x 8x       8x 9x 9x 1x       7x 26x       68x                     44x 44x 58x 58x 169x       44x 187x     44x 58x 186x               44x               7x 7x           7x 7x 7x 18x 1x         17x             16x                                               68x 68x 68x 68x 68x 68x 68x       59x 59x 59x 59x         7x   7x 7x     7x 7x       7x 7x       7x 7x       66x 2x     64x 66x 2x     62x 77x     61x       67x 5x                     62x   62x           67x                     17x       5x 5x       45x                 36x                         54x       4x       5x 5x 5x       5x 1x     4x 4x       4x 4x 4x 4x 4x   4x       4x 4x     4x     8x               4x 4x   8x 4x     4x 4x                           4x   4x       4x 8x     4x       4x       5x           55x 5x 1x     4x 4x     50x                     8x       3x                     6x       1x      
import { is } from 'drizzle-orm/entity'
import { QueryPromise } from 'drizzle-orm/query-promise'
import { Param, SQL, type SQL as SQLType, sql as yql } from 'drizzle-orm/sql/sql'
import type { Subquery } from 'drizzle-orm/subquery'
import { Table } from 'drizzle-orm/table'
import { haveSameKeys } from 'drizzle-orm/utils'
import type { YdbPreparedQueryConfig, YdbSession } from '../session.js'
import type { YdbTable } from '../table.js'
import type { YdbColumn } from '../columns/common.js'
import { type YdbSelectedFieldsOrdered, orderSelectedFields } from '../result-mapping.js'
import { YdbDialect } from '../../ydb/dialect.js'
import {
	getInsertColumnEntries,
	getPrimaryColumnKeys,
	getTableColumns,
	resolveInsertValue,
	validateTableColumnKeys,
} from './utils.js'
import { YdbQueryBuilder } from './query-builder.js'
 
type InsertValues = Record<string, unknown>
type OnDuplicateKeyUpdateConfig = { set: InsertValues }
type InsertCommand = 'insert' | 'upsert' | 'replace'
type InsertSelectQuery =
	| SQLType
	| {
			getSQL(): SQLType
			getSelectedFields(): Record<string, unknown> | undefined
	  }
 
function qualifyAlias(alias: string, columnName: string): SQLType {
	return yql`${yql.identifier(alias)}.${yql.identifier(columnName)}`
}
 
function resolveOnDuplicateValue(column: YdbColumn, value: unknown): unknown {
	return is(value, SQL) || is(value, Param) ? value : yql.param(value, column)
}
 
function capitalize(value: string): string {
	return value.charAt(0).toUpperCase() + value.slice(1)
}
 
function getAllReturningFields(table: YdbTable): Record<string, unknown> {
	return (table as any)[(Table as any).Symbol.Columns] ?? {}
}
 
function getProvidedColumnEntries(
	table: YdbTable,
	rows: InsertValues[],
	command: InsertCommand
): Array<[string, YdbColumn]> {
	let firstRow = rows[0] ?? {}
	let firstKeys = Object.keys(firstRow)
	Iif (firstKeys.length === 0) {
		throw new Error(`YDB ${command} values must include at least one column`)
	}
 
	for (let row of rows) {
		validateTableColumnKeys(table, row, command)
		if (!haveSameKeys(firstRow, row)) {
			throw new Error(`YDB ${command} values must provide the same columns for every row`)
		}
	}
 
	let keys = new Set(firstKeys)
	return getInsertColumnEntries(table).filter(([key]) => keys.has(key))
}
 
function hasRuntimeInsertValue(column: YdbColumn): boolean {
	return (
		column.defaultFn !== undefined ||
		column.default !== undefined ||
		column.onUpdateFn !== undefined
	)
}
 
function getDefaultAwareInsertColumnEntries(
	table: YdbTable,
	rows: InsertValues[]
): Array<[string, YdbColumn]> {
	let explicitKeys = new Set<string>()
	for (let row of rows) {
		validateTableColumnKeys(table, row, 'insert')
		for (let key of Object.keys(row)) {
			explicitKeys.add(key)
		}
	}
 
	let entries = getInsertColumnEntries(table).filter(
		([key, column]) => explicitKeys.has(key) || hasRuntimeInsertValue(column)
	)
 
	for (let row of rows) {
		for (let [key, column] of entries) {
			Iif (!(key in row) && !hasRuntimeInsertValue(column)) {
				throw new Error(
					'YDB insert values must provide the same non-default columns for every row'
				)
			}
		}
	}
 
	return entries
}
 
function getSelectColumnEntries(
	table: YdbTable,
	fields: Record<string, unknown> | undefined,
	command: InsertCommand
): Array<[string, YdbColumn]> {
	let selectedKeys = Object.keys(fields ?? {})
	Iif (selectedKeys.length === 0) {
		throw new Error(
			'Insert select error: selected fields must include at least one table column'
		)
	}
 
	let columns = getTableColumns(table)
	let insertableColumns = new Map(getInsertColumnEntries(table))
	for (let key of selectedKeys) {
		if (!(key in columns)) {
			throw new Error(
				`Insert select error: selected field "${key}" is not a column of the target table`
			)
		}
 
		Iif (!insertableColumns.has(key)) {
			throw new Error(
				`Insert select error: selected field "${key}" is not insertable in ${command}()`
			)
		}
	}
 
	return selectedKeys.map((key) => [key, insertableColumns.get(key)!])
}
 
abstract class YdbInsertLikeBuilder<TResult = unknown> extends QueryPromise<TResult> {
	protected valuesData: InsertValues | InsertValues[] | undefined
	protected selectQuery: InsertSelectQuery | undefined
	protected selectColumnEntries: Array<[string, YdbColumn]> | undefined
	protected returningFields: YdbSelectedFieldsOrdered | undefined
 
	protected readonly table: YdbTable
	protected readonly session: YdbSession
	protected readonly dialect: YdbDialect
	protected readonly withList: Subquery[]
	protected readonly command: InsertCommand
	readonly #valuesColumnMode: 'all' | 'provided' | 'default-aware'
 
	constructor(
		table: YdbTable,
		session: YdbSession,
		dialect: YdbDialect,
		withList: Subquery[],
		command: InsertCommand,
		valuesColumnMode: 'all' | 'provided' | 'default-aware'
	) {
		super()
		this.table = table
		this.session = session
		this.dialect = dialect
		this.withList = withList
		this.command = command
		this.#valuesColumnMode = valuesColumnMode
	}
 
	values(values: InsertValues | InsertValues[]): this {
		this.valuesData = values
		this.selectQuery = undefined
		this.selectColumnEntries = undefined
		return this
	}
 
	select(query: InsertSelectQuery | ((qb: YdbQueryBuilder) => InsertSelectQuery)): this {
		let resolved =
			typeof query === 'function' ? query(new YdbQueryBuilder(this.dialect)) : query
 
		this.selectQuery = resolved
		this.selectColumnEntries = is(resolved, SQL)
			? undefined
			: getSelectColumnEntries(this.table, resolved.getSelectedFields(), this.command)
		this.valuesData = undefined
		return this
	}
 
	protected setReturning(fields: Record<string, unknown>): this {
		let orderedFields = orderSelectedFields(fields)
		Iif (orderedFields.length === 0) {
			throw new Error('YDB returning() requires at least one field')
		}
 
		this.returningFields = orderedFields
		return this
	}
 
	protected getRows(): InsertValues[] {
		if (!this.valuesData) {
			throw new Error(`${capitalize(this.command)} values are missing`)
		}
 
		let rows = Array.isArray(this.valuesData) ? this.valuesData : [this.valuesData]
		if (rows.length === 0) {
			throw new Error(`${capitalize(this.command)} values are empty`)
		}
 
		for (let row of rows) {
			validateTableColumnKeys(this.table, row, this.command)
		}
 
		return rows
	}
 
	protected buildStandardQuery(): SQLType {
		if (this.selectQuery) {
			return this.dialect.buildInsertQuery({
				table: this.table,
				values: this.selectQuery,
				select: true,
				withList: this.withList,
				command: this.command,
				columnEntries: this.selectColumnEntries,
				returning: this.returningFields,
			})
		}
 
		let rows = this.getRows()
		let columnEntries =
			this.#valuesColumnMode === 'all'
				? getInsertColumnEntries(this.table)
				: this.#valuesColumnMode === 'default-aware'
					? getDefaultAwareInsertColumnEntries(this.table, rows)
					: getProvidedColumnEntries(this.table, rows, this.command)
 
		return this.dialect.buildInsertQuery({
			table: this.table,
			values: rows,
			withList: this.withList,
			command: this.command,
			columnEntries,
			returning: this.returningFields,
		})
	}
 
	getSQL(): SQLType {
		return this.buildStandardQuery()
	}
 
	toSQL() {
		let { typings: _typings, ...query } = this.dialect.sqlToQuery(this.getSQL())
		return query
	}
 
	prepare(name?: string) {
		return this.session.prepareQuery<YdbPreparedQueryConfig & { execute: TResult }>(
			this.getSQL(),
			this.returningFields,
			name,
			this.returningFields !== undefined
		)
	}
 
	override execute(): Promise<TResult> {
		return this.prepare().execute() as Promise<TResult>
	}
}
 
export class YdbInsertBuilder<TResult = unknown> extends YdbInsertLikeBuilder<TResult> {
	#onDuplicateSet: InsertValues | undefined
 
	constructor(
		table: YdbTable,
		session: YdbSession,
		dialect = new YdbDialect(),
		withList: Subquery[] = []
	) {
		super(table, session, dialect, withList, 'insert', 'default-aware')
	}
 
	returning(fields: Record<string, unknown> = getAllReturningFields(this.table)): this {
		return this.setReturning(fields)
	}
 
	onDuplicateKeyUpdate(config: OnDuplicateKeyUpdateConfig): this {
		validateTableColumnKeys(this.table, config.set, 'update')
		this.#onDuplicateSet = { ...config.set }
		return this
	}
 
	#buildOnDuplicateKeyUpdateQuery(rows: InsertValues[]): SQLType {
		if (this.selectQuery) {
			throw new Error('YDB onDuplicateKeyUpdate() does not support insert().select(...)')
		}
 
		let columnEntries = getInsertColumnEntries(this.table)
		Iif (columnEntries.length === 0) {
			throw new Error('Insertable columns are missing')
		}
 
		let columnsByKey = new Map(columnEntries)
		let primaryColumns = getPrimaryColumnKeys(this.table)
			.map((key) => columnsByKey.get(key))
			.filter((column): column is YdbColumn => column !== undefined)
		let primaryColumnSet = new Set(primaryColumns)
 
		Iif (primaryColumns.length === 0) {
			throw new Error('YDB onDuplicateKeyUpdate() requires at least one primary key column')
		}
 
		let incomingAlias = '__ydb_incoming'
		let incomingSql = yql.join(
			rows.map(
				(row) =>
					yql`select ${yql.join(
						columnEntries.map(
							([key, column]) =>
								yql`${resolveInsertValue(column, row[key])} as ${yql.identifier(column.name)}`
						),
						yql`, `
					)}`
			),
			yql` union all `
		)
 
		let conflictDetectedSql = yql`${this.table}.${yql.identifier(primaryColumns[0]!.name)}`
		let mergedSelections = yql.join(
			columnEntries.map(([key, column]) => {
				if (primaryColumnSet.has(column)) {
					return yql`${qualifyAlias(incomingAlias, column.name)} as ${yql.identifier(column.name)}`
				}
 
				Eif (this.#onDuplicateSet && key in this.#onDuplicateSet) {
					return yql`case when ${conflictDetectedSql} is null then ${qualifyAlias(
						incomingAlias,
						column.name
					)} else ${resolveOnDuplicateValue(column, this.#onDuplicateSet[key])} end as ${yql.identifier(column.name)}`
				}
 
				return yql`case when ${conflictDetectedSql} is null then ${qualifyAlias(
					incomingAlias,
					column.name
				)} else ${column} end as ${yql.identifier(column.name)}`
			}),
			yql`, `
		)
 
		let joinSql = yql.join(
			primaryColumns.map(
				(column) => yql`${column} = ${qualifyAlias(incomingAlias, column.name)}`
			),
			yql` and `
		)
		let columnList = yql.join(
			columnEntries.map(([, column]) => yql.identifier(column.name)),
			yql`, `
		)
		let withSql = this.dialect.buildWithCTE([
			...this.withList,
			{ _: { alias: incomingAlias, sql: incomingSql } } as any,
		])
		let returningSql = this.returningFields
			? yql` returning ${this.dialect.buildReturningSelection(this.returningFields)}`
			: undefined
 
		return yql`${withSql}upsert into ${this.table} (${columnList}) select ${mergedSelections} from ${yql.raw(
			`$${incomingAlias}`
		)} as ${yql.identifier(incomingAlias)} left join ${this.table} on ${joinSql}${returningSql}`
	}
 
	override getSQL(): SQLType {
		if (this.#onDuplicateSet) {
			if (this.selectQuery) {
				return this.#buildOnDuplicateKeyUpdateQuery([])
			}
 
			let rows = this.getRows()
			return this.#buildOnDuplicateKeyUpdateQuery(rows)
		}
 
		return this.buildStandardQuery()
	}
}
 
export class YdbUpsertBuilder<TResult = unknown> extends YdbInsertLikeBuilder<TResult> {
	constructor(
		table: YdbTable,
		session: YdbSession,
		dialect = new YdbDialect(),
		withList: Subquery[] = []
	) {
		super(table, session, dialect, withList, 'upsert', 'provided')
	}
 
	returning(fields: Record<string, unknown> = getAllReturningFields(this.table)): this {
		return this.setReturning(fields)
	}
}
 
export class YdbReplaceBuilder<TResult = unknown> extends YdbInsertLikeBuilder<TResult> {
	constructor(
		table: YdbTable,
		session: YdbSession,
		dialect = new YdbDialect(),
		withList: Subquery[] = []
	) {
		super(table, session, dialect, withList, 'replace', 'all')
	}
 
	returning(): never {
		throw new Error('YDB replace().returning() is not documented or supported')
	}
}