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

87.64% Statements 78/89
82.5% Branches 33/40
86.36% Functions 19/22
87.64% Lines 78/89

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                                                                                    34x 34x 34x 34x             30x   30x 19x                 21x 1x                 11x               7x 7x 7x 7x   7x 1x     5x 5x 4x 4x   1x 1x     5x       5x       5x 5x 5x 5x 5x       34x             15x 15x 15x       15x   15x 4x     15x 4x     15x         34x   15x 15x   15x 15x             15x 15x 15x                 1x 1x                 1x 1x       5x 5x       1x       2x 2x       5x 5x       15x 15x   15x 5x       5x 1x     4x 1x       13x                             34x   13x       11x                         6x 6x   6x       6x             2x 2x 2x       1x    
import { entityKind } from 'drizzle-orm/entity'
import { type SQL, sql as yql } from 'drizzle-orm/sql/sql'
import { getTableName } from 'drizzle-orm/table'
import type { YdbColumn } from './columns/common.js'
import type { YdbTable } from './table.js'
 
export type YdbIndexLocality = 'GLOBAL' | 'LOCAL'
export type YdbIndexSyncMode = 'SYNC' | 'ASYNC'
export type YdbVectorType = 'float' | 'uint8' | 'int8'
export type YdbVectorDistance = 'cosine' | 'manhattan' | 'euclidean'
export type YdbVectorSimilarity = 'inner_product' | 'cosine'
 
export interface YdbIndexWithOptions {
	[key: string]: string | number | boolean
}
 
export interface YdbVectorKMeansTreeOptions {
	vectorDimension: number
	vectorType: YdbVectorType
	distance?: YdbVectorDistance
	similarity?: YdbVectorSimilarity
	clusters: number
	levels: number
}
 
export interface YdbIndexConfig {
	readonly name?: string | undefined
	readonly table: YdbTable
	readonly columns: readonly YdbColumn[]
	readonly unique: boolean
	readonly locality: YdbIndexLocality
	readonly sync: YdbIndexSyncMode
	readonly indexType?: string | undefined
	readonly cover: readonly YdbColumn[]
	readonly withOptions: Readonly<Record<string, string | number | boolean>>
}
 
interface YdbIndexBuilderDefaults {
	readonly indexType?: string | undefined
	readonly withOptions?: YdbIndexWithOptions | undefined
}
 
let vectorKMeansTreeIndexType = 'vector_kmeans_tree'
let vectorTypes: readonly YdbVectorType[] = ['float', 'uint8', 'int8']
let vectorDistances: readonly YdbVectorDistance[] = ['cosine', 'manhattan', 'euclidean']
let vectorSimilarities: readonly YdbVectorSimilarity[] = ['inner_product', 'cosine']
 
function assertColumnsBelongToTable(
	table: YdbTable,
	columns: readonly YdbColumn[],
	kind: string
): void {
	let tableName = getTableName(table)
 
	for (let column of columns) {
		Iif (column.table !== table) {
			throw new Error(
				`${kind} column "${column.name}" does not belong to table "${tableName}"`
			)
		}
	}
}
 
function assertIntegerRange(name: string, value: number, min: number, max: number): void {
	if (!Number.isInteger(value) || value < min || value > max) {
		throw new Error(`YDB vector index ${name} must be an integer between ${min} and ${max}`)
	}
}
 
function assertOneOf<T extends string>(
	name: string,
	value: string,
	allowed: readonly T[]
): asserts value is T {
	Iif (!(allowed as readonly string[]).includes(value)) {
		throw new Error(`YDB vector index ${name} must be one of: ${allowed.join(', ')}`)
	}
}
 
function normalizeVectorKMeansTreeOptions(
	options: YdbVectorKMeansTreeOptions
): YdbIndexWithOptions {
	assertIntegerRange('vectorDimension', options.vectorDimension, 1, 16_384)
	assertIntegerRange('clusters', options.clusters, 2, 2_048)
	assertIntegerRange('levels', options.levels, 1, 16)
	assertOneOf('vectorType', options.vectorType, vectorTypes)
 
	if ((options.distance === undefined) === (options.similarity === undefined)) {
		throw new Error('YDB vector index requires exactly one of distance or similarity')
	}
 
	let result: YdbIndexWithOptions = {}
	if (options.distance !== undefined) {
		assertOneOf('distance', options.distance, vectorDistances)
		result['distance'] = options.distance
	} else {
		assertOneOf('similarity', options.similarity!, vectorSimilarities)
		result['similarity'] = options.similarity!
	}
 
	Iif (options.clusters ** options.levels > 1_073_741_824) {
		throw new Error('YDB vector index clusters ** levels must be no more than 1073741824')
	}
 
	Iif (options.vectorDimension * options.clusters > 4_194_304) {
		throw new Error('YDB vector index vectorDimension * clusters must be no more than 4194304')
	}
 
	result['vector_type'] = options.vectorType
	result['vector_dimension'] = options.vectorDimension
	result['clusters'] = options.clusters
	result['levels'] = options.levels
	return result
}
 
export class YdbIndexBuilderOn {
	static readonly [entityKind] = 'YdbIndexBuilderOn'
 
	readonly #name: string | undefined
	readonly #unique: boolean
	readonly #defaults: YdbIndexBuilderDefaults
 
	constructor(name: string | undefined, unique: boolean, defaults: YdbIndexBuilderDefaults = {}) {
		this.#name = name
		this.#unique = unique
		this.#defaults = defaults
	}
 
	on(...columns: [YdbColumn, ...YdbColumn[]]): YdbIndexBuilder {
		let builder = new YdbIndexBuilder(this.#name, columns, this.#unique)
 
		if (this.#defaults.indexType) {
			builder.using(this.#defaults.indexType)
		}
 
		if (this.#defaults.withOptions) {
			builder.with(this.#defaults.withOptions)
		}
 
		return builder
	}
}
 
export class YdbIndexBuilder {
	static readonly [entityKind] = 'YdbIndexBuilder'
 
	#locality: YdbIndexLocality = 'GLOBAL'
	#syncMode: YdbIndexSyncMode = 'SYNC'
	#indexType?: string
	#coverColumns: YdbColumn[] = []
	#withOptions: YdbIndexWithOptions = {}
 
	readonly #name: string | undefined
	readonly #columns: [YdbColumn, ...YdbColumn[]]
	readonly #unique: boolean
 
	constructor(name: string | undefined, columns: [YdbColumn, ...YdbColumn[]], unique: boolean) {
		this.#name = name
		this.#columns = columns
		this.#unique = unique
	}
 
	global(): this {
		this.#locality = 'GLOBAL'
		return this
	}
 
	local(): this {
		this.#locality = 'LOCAL'
		return this
	}
 
	sync(): this {
		this.#syncMode = 'SYNC'
		return this
	}
 
	async(): this {
		this.#syncMode = 'ASYNC'
		return this
	}
 
	using(indexType: string): this {
		this.#indexType = indexType
		return this
	}
 
	vectorKMeansTree(options: YdbVectorKMeansTreeOptions): this {
		return this.using(vectorKMeansTreeIndexType).with(normalizeVectorKMeansTreeOptions(options))
	}
 
	cover(...columns: YdbColumn[]): this {
		this.#coverColumns = [...columns]
		return this
	}
 
	with(options: YdbIndexWithOptions): this {
		this.#withOptions = { ...this.#withOptions, ...options }
		return this
	}
 
	build(table: YdbTable): YdbIndex {
		assertColumnsBelongToTable(table, this.#columns, 'Index')
		assertColumnsBelongToTable(table, this.#coverColumns, 'Index cover')
 
		if (this.#indexType === vectorKMeansTreeIndexType) {
			Iif (this.#unique) {
				throw new Error('YDB vector indexes cannot be UNIQUE')
			}
 
			if (this.#locality !== 'GLOBAL') {
				throw new Error('YDB vector indexes support only GLOBAL locality')
			}
 
			if (this.#syncMode !== 'SYNC') {
				throw new Error('YDB vector indexes support only SYNC mode')
			}
		}
 
		return new YdbIndex({
			name: this.#name,
			table,
			columns: [...this.#columns],
			unique: this.#unique,
			locality: this.#locality,
			sync: this.#syncMode,
			indexType: this.#indexType,
			cover: [...this.#coverColumns],
			withOptions: { ...this.#withOptions },
		})
	}
}
 
export class YdbIndex {
	static readonly [entityKind] = 'YdbIndex'
 
	constructor(readonly config: YdbIndexConfig) {}
}
 
export function index(name?: string): YdbIndexBuilderOn {
	return new YdbIndexBuilderOn(name, false)
}
 
export function uniqueIndex(name?: string): YdbIndexBuilderOn {
	return new YdbIndexBuilderOn(name, true)
}
 
export function vectorIndex(name: string, options: YdbVectorKMeansTreeOptions): YdbIndexBuilderOn
export function vectorIndex(options: YdbVectorKMeansTreeOptions): YdbIndexBuilderOn
export function vectorIndex(
	nameOrOptions: string | YdbVectorKMeansTreeOptions,
	options?: YdbVectorKMeansTreeOptions
): YdbIndexBuilderOn {
	let name = typeof nameOrOptions === 'string' ? nameOrOptions : undefined
	let vectorOptions = typeof nameOrOptions === 'string' ? options : nameOrOptions
 
	Iif (!vectorOptions) {
		throw new Error('YDB vectorIndex() requires vector index options')
	}
 
	return new YdbIndexBuilderOn(name, false, {
		indexType: vectorKMeansTreeIndexType,
		withOptions: normalizeVectorKMeansTreeOptions(vectorOptions),
	})
}
 
export function indexView(table: YdbTable | string, indexName: string, alias?: string): SQL {
	let tableSql = typeof table === 'string' ? yql.identifier(table) : yql`${table}`
	let aliasSql = alias ? yql` as ${yql.identifier(alias)}` : undefined
	return yql`${tableSql} view ${yql.identifier(indexName)}${aliasSql}`
}
 
export function vectorIndexView(table: YdbTable | string, indexName: string, alias?: string): SQL {
	return indexView(table, indexName, alias)
}