| 1 | // Copyright 2023 LanceDB Developers. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | import { |
| 16 | type EmbeddingFunction, |
| 17 | type Table, |
| 18 | type VectorIndexParams, |
| 19 | type Connection, |
| 20 | type ConnectionOptions, |
| 21 | type CreateTableOptions, |
| 22 | type VectorIndex, |
| 23 | type WriteOptions, |
| 24 | type IndexStats, |
| 25 | type UpdateArgs, |
| 26 | type UpdateSqlArgs, |
| 27 | makeArrowTable, |
| 28 | type MergeInsertArgs, |
| 29 | type ColumnAlteration |
| 30 | } from '../index' |
| 31 | import { Query } from '../query' |
| 32 | |
| 33 | import { Vector, Table as ArrowTable } from 'apache-arrow' |
| 34 | import { HttpLancedbClient } from './client' |
| 35 | import { isEmbeddingFunction } from '../embedding/embedding_function' |
| 36 | import { |
| 37 | createEmptyTable, |
| 38 | fromRecordsToStreamBuffer, |
| 39 | fromTableToStreamBuffer |
| 40 | } from '../arrow' |
| 41 | import { toSQL, TTLCache } from '../util' |
| 42 | import { type HttpMiddleware } from '../middleware' |
| 43 | |
| 44 | /** |
| 45 | * Remote connection. |
| 46 | */ |
| 47 | export class RemoteConnection implements Connection { |
| 48 | private _client: HttpLancedbClient |
| 49 | private readonly _dbName: string |
| 50 | private readonly _tableCache = new TTLCache(300_000) |
| 51 | |
| 52 | constructor (opts: ConnectionOptions) { |
| 53 | if (!opts.uri.startsWith('db://')) { |
| 54 | throw new Error(`Invalid remote DB URI: ${opts.uri}`) |
| 55 | } |
| 56 | if (opts.apiKey == null || opts.apiKey === '') { |
| 57 | opts = Object.assign({}, opts, { apiKey: process.env.LANCEDB_API_KEY }) |
| 58 | } |
| 59 | if (opts.apiKey === undefined || opts.region === undefined) { |
| 60 | throw new Error( |
| 61 | 'API key and region are must be passed for remote connections. ' + |
| 62 | 'API key can also be set through LANCEDB_API_KEY env variable.') |
| 63 | } |
| 64 | |
| 65 | this._dbName = opts.uri.slice('db://'.length) |
| 66 | let server: string |
| 67 | if (opts.hostOverride === undefined) { |
| 68 | server = `https://${this._dbName}.${opts.region}.api.lancedb.com` |
| 69 | } else { |
| 70 | server = opts.hostOverride |
| 71 | } |
| 72 | this._client = new HttpLancedbClient( |
| 73 | server, |
| 74 | opts.apiKey, |
| 75 | opts.timeout, |
| 76 | opts.hostOverride === undefined ? undefined : this._dbName |
| 77 | ) |
| 78 | } |
| 79 | |
| 80 | get uri (): string { |
| 81 | // add the lancedb+ prefix back |
| 82 | return 'db://' + this._client.uri |
| 83 | } |
| 84 | |
| 85 | async tableNames ( |
| 86 | pageToken: string = '', |
| 87 | limit: number = 10 |
| 88 | ): Promise<string[]> { |
| 89 | const response = await this._client.get('/v1/table/', { |
| 90 | limit: `${limit}`, |
| 91 | page_token: pageToken |
| 92 | }) |
| 93 | const body = await response.body() |
| 94 | for (const table of body.tables) { |
| 95 | this._tableCache.set(table, true) |
| 96 | } |
| 97 | return body.tables |
| 98 | } |
| 99 | |
| 100 | async openTable (name: string): Promise<Table> |
| 101 | async openTable<T>( |
| 102 | name: string, |
| 103 | embeddings: EmbeddingFunction<T> |
| 104 | ): Promise<Table<T>> |
| 105 | async openTable<T>( |
| 106 | name: string, |
| 107 | embeddings?: EmbeddingFunction<T> |
| 108 | ): Promise<Table<T>> { |
| 109 | // check if the table exists |
| 110 | if (this._tableCache.get(name) === undefined) { |
| 111 | await this._client.post(`/v1/table/${encodeURIComponent(name)}/describe/`) |
| 112 | this._tableCache.set(name, true) |
| 113 | } |
| 114 | |
| 115 | if (embeddings !== undefined) { |
| 116 | return new RemoteTable(this._client, name, embeddings) |
| 117 | } else { |
| 118 | return new RemoteTable(this._client, name) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | async createTable<T>( |
| 123 | nameOrOpts: string | CreateTableOptions<T>, |
| 124 | data?: Array<Record<string, unknown>> | ArrowTable, |
| 125 | optsOrEmbedding?: WriteOptions | EmbeddingFunction<T>, |
| 126 | opt?: WriteOptions |
| 127 | ): Promise<Table<T>> { |
| 128 | // Logic copied from LocatlConnection, refactor these to a base class + connectionImpl pattern |
| 129 | let schema |
| 130 | let embeddings: undefined | EmbeddingFunction<T> |
| 131 | let tableName: string |
| 132 | if (typeof nameOrOpts === 'string') { |
| 133 | if ( |
| 134 | optsOrEmbedding !== undefined && |
| 135 | isEmbeddingFunction(optsOrEmbedding) |
| 136 | ) { |
| 137 | embeddings = optsOrEmbedding |
| 138 | } |
| 139 | tableName = nameOrOpts |
| 140 | } else { |
| 141 | schema = nameOrOpts.schema |
| 142 | embeddings = nameOrOpts.embeddingFunction |
| 143 | tableName = nameOrOpts.name |
| 144 | if (data === undefined) { |
| 145 | data = nameOrOpts.data |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | let buffer: Buffer |
| 150 | |
| 151 | function isEmpty ( |
| 152 | data: Array<Record<string, unknown>> | ArrowTable<any> |
| 153 | ): boolean { |
| 154 | if (data instanceof ArrowTable) { |
| 155 | return data.numRows === 0 |
| 156 | } |
| 157 | return data.length === 0 |
| 158 | } |
| 159 | |
| 160 | if (data === undefined || isEmpty(data)) { |
| 161 | if (schema === undefined) { |
| 162 | throw new Error('Either data or schema needs to defined') |
| 163 | } |
| 164 | buffer = await fromTableToStreamBuffer(createEmptyTable(schema)) |
| 165 | } else if (data instanceof ArrowTable) { |
| 166 | buffer = await fromTableToStreamBuffer(data, embeddings) |
| 167 | } else { |
| 168 | // data is Array<Record<...>> |
| 169 | buffer = await fromRecordsToStreamBuffer(data, embeddings) |
| 170 | } |
| 171 | |
| 172 | const res = await this._client.post( |
| 173 | `/v1/table/${encodeURIComponent(tableName)}/create/`, |
| 174 | buffer, |
| 175 | undefined, |
| 176 | 'application/vnd.apache.arrow.stream' |
| 177 | ) |
| 178 | if (res.status !== 200) { |
| 179 | throw new Error( |
| 180 | `Server Error, status: ${res.status}, ` + |
| 181 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 182 | `message: ${res.statusText}: ${await res.body()}` |
| 183 | ) |
| 184 | } |
| 185 | |
| 186 | this._tableCache.set(tableName, true) |
| 187 | if (embeddings === undefined) { |
| 188 | return new RemoteTable(this._client, tableName) |
| 189 | } else { |
| 190 | return new RemoteTable(this._client, tableName, embeddings) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | async dropTable (name: string): Promise<void> { |
| 195 | await this._client.post(`/v1/table/${encodeURIComponent(name)}/drop/`) |
| 196 | this._tableCache.delete(name) |
| 197 | } |
| 198 | |
| 199 | withMiddleware (middleware: HttpMiddleware): Connection { |
| 200 | const wrapped = this.clone() |
| 201 | wrapped._client = wrapped._client.withMiddleware(middleware) |
| 202 | return wrapped |
| 203 | } |
| 204 | |
| 205 | private clone (): RemoteConnection { |
| 206 | const clone: RemoteConnection = Object.create(RemoteConnection.prototype) |
| 207 | return Object.assign(clone, this) |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | export class RemoteQuery<T = number[]> extends Query<T> { |
| 212 | constructor ( |
| 213 | query: T, |
| 214 | private readonly _client: HttpLancedbClient, |
| 215 | private readonly _name: string, |
| 216 | embeddings?: EmbeddingFunction<T> |
| 217 | ) { |
| 218 | super(query, undefined, embeddings) |
| 219 | } |
| 220 | |
| 221 | // TODO: refactor this to a base class + queryImpl pattern |
| 222 | async execute<T = Record<string, unknown>>(): Promise<T[]> { |
| 223 | const embeddings = this._embeddings |
| 224 | const query = (this as any)._query |
| 225 | let queryVector: number[] |
| 226 | |
| 227 | if (embeddings !== undefined) { |
| 228 | queryVector = (await embeddings.embed([query]))[0] |
| 229 | } else { |
| 230 | queryVector = query as number[] |
| 231 | } |
| 232 | |
| 233 | const data = await this._client.search( |
| 234 | this._name, |
| 235 | queryVector, |
| 236 | (this as any)._limit, |
| 237 | (this as any)._nprobes, |
| 238 | (this as any)._prefilter, |
| 239 | (this as any)._refineFactor, |
| 240 | (this as any)._select, |
| 241 | (this as any)._filter, |
| 242 | (this as any)._metricType, |
| 243 | (this as any)._fastSearch |
| 244 | ) |
| 245 | |
| 246 | return data.toArray().map((entry: Record<string, unknown>) => { |
| 247 | const newObject: Record<string, unknown> = {} |
| 248 | Object.keys(entry).forEach((key: string) => { |
| 249 | if (entry[key] instanceof Vector) { |
| 250 | newObject[key] = (entry[key] as any).toArray() |
| 251 | } else { |
| 252 | newObject[key] = entry[key] as any |
| 253 | } |
| 254 | }) |
| 255 | return newObject as unknown as T |
| 256 | }) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | // we are using extend until we have next next version release |
| 261 | // Table and Connection has both been refactored to interfaces |
| 262 | export class RemoteTable<T = number[]> implements Table<T> { |
| 263 | private _client: HttpLancedbClient |
| 264 | private readonly _embeddings?: EmbeddingFunction<T> |
| 265 | private readonly _name: string |
| 266 | |
| 267 | constructor (client: HttpLancedbClient, name: string) |
| 268 | constructor ( |
| 269 | client: HttpLancedbClient, |
| 270 | name: string, |
| 271 | embeddings: EmbeddingFunction<T> |
| 272 | ) |
| 273 | constructor ( |
| 274 | client: HttpLancedbClient, |
| 275 | name: string, |
| 276 | embeddings?: EmbeddingFunction<T> |
| 277 | ) { |
| 278 | this._client = client |
| 279 | this._name = name |
| 280 | this._embeddings = embeddings |
| 281 | } |
| 282 | |
| 283 | get name (): string { |
| 284 | return this._name |
| 285 | } |
| 286 | |
| 287 | get schema (): Promise<any> { |
| 288 | return this._client |
| 289 | .post(`/v1/table/${encodeURIComponent(this._name)}/describe/`) |
| 290 | .then(async (res) => { |
| 291 | if (res.status !== 200) { |
| 292 | throw new Error( |
| 293 | `Server Error, status: ${res.status}, ` + |
| 294 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 295 | `message: ${res.statusText}: ${await res.body()}` |
| 296 | ) |
| 297 | } |
| 298 | return (await res.body())?.schema |
| 299 | }) |
| 300 | } |
| 301 | |
| 302 | search (query: T): Query<T> { |
| 303 | return new RemoteQuery(query, this._client, encodeURIComponent(this._name)) //, this._embeddings_new) |
| 304 | } |
| 305 | |
| 306 | filter (where: string): Query<T> { |
| 307 | throw new Error('Not implemented') |
| 308 | } |
| 309 | |
| 310 | async mergeInsert (on: string, data: Array<Record<string, unknown>> | ArrowTable, args: MergeInsertArgs): Promise<void> { |
| 311 | let tbl: ArrowTable |
| 312 | if (data instanceof ArrowTable) { |
| 313 | tbl = data |
| 314 | } else { |
| 315 | tbl = makeArrowTable(data, await this.schema) |
| 316 | } |
| 317 | |
| 318 | const queryParams: any = { |
| 319 | on |
| 320 | } |
| 321 | if (args.whenMatchedUpdateAll !== false && args.whenMatchedUpdateAll !== null && args.whenMatchedUpdateAll !== undefined) { |
| 322 | queryParams.when_matched_update_all = 'true' |
| 323 | if (typeof args.whenMatchedUpdateAll === 'string') { |
| 324 | queryParams.when_matched_update_all_filt = args.whenMatchedUpdateAll |
| 325 | } |
| 326 | } else { |
| 327 | queryParams.when_matched_update_all = 'false' |
| 328 | } |
| 329 | if (args.whenNotMatchedInsertAll ?? false) { |
| 330 | queryParams.when_not_matched_insert_all = 'true' |
| 331 | } else { |
| 332 | queryParams.when_not_matched_insert_all = 'false' |
| 333 | } |
| 334 | if (args.whenNotMatchedBySourceDelete !== false && args.whenNotMatchedBySourceDelete !== null && args.whenNotMatchedBySourceDelete !== undefined) { |
| 335 | queryParams.when_not_matched_by_source_delete = 'true' |
| 336 | if (typeof args.whenNotMatchedBySourceDelete === 'string') { |
| 337 | queryParams.when_not_matched_by_source_delete_filt = args.whenNotMatchedBySourceDelete |
| 338 | } |
| 339 | } else { |
| 340 | queryParams.when_not_matched_by_source_delete = 'false' |
| 341 | } |
| 342 | |
| 343 | const buffer = await fromTableToStreamBuffer(tbl, this._embeddings) |
| 344 | const res = await this._client.post( |
| 345 | `/v1/table/${encodeURIComponent(this._name)}/merge_insert/`, |
| 346 | buffer, |
| 347 | queryParams, |
| 348 | 'application/vnd.apache.arrow.stream' |
| 349 | ) |
| 350 | if (res.status !== 200) { |
| 351 | throw new Error( |
| 352 | `Server Error, status: ${res.status}, ` + |
| 353 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 354 | `message: ${res.statusText}: ${await res.body()}` |
| 355 | ) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | async add (data: Array<Record<string, unknown>> | ArrowTable): Promise<number> { |
| 360 | let tbl: ArrowTable |
| 361 | if (data instanceof ArrowTable) { |
| 362 | tbl = data |
| 363 | } else { |
| 364 | tbl = makeArrowTable(data, await this.schema) |
| 365 | } |
| 366 | |
| 367 | const buffer = await fromTableToStreamBuffer(tbl, this._embeddings) |
| 368 | const res = await this._client.post( |
| 369 | `/v1/table/${encodeURIComponent(this._name)}/insert/`, |
| 370 | buffer, |
| 371 | { |
| 372 | mode: 'append' |
| 373 | }, |
| 374 | 'application/vnd.apache.arrow.stream' |
| 375 | ) |
| 376 | if (res.status !== 200) { |
| 377 | throw new Error( |
| 378 | `Server Error, status: ${res.status}, ` + |
| 379 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 380 | `message: ${res.statusText}: ${await res.body()}` |
| 381 | ) |
| 382 | } |
| 383 | return tbl.numRows |
| 384 | } |
| 385 | |
| 386 | async overwrite (data: Array<Record<string, unknown>> | ArrowTable): Promise<number> { |
| 387 | let tbl: ArrowTable |
| 388 | if (data instanceof ArrowTable) { |
| 389 | tbl = data |
| 390 | } else { |
| 391 | tbl = makeArrowTable(data) |
| 392 | } |
| 393 | const buffer = await fromTableToStreamBuffer(tbl, this._embeddings) |
| 394 | const res = await this._client.post( |
| 395 | `/v1/table/${encodeURIComponent(this._name)}/insert/`, |
| 396 | buffer, |
| 397 | { |
| 398 | mode: 'overwrite' |
| 399 | }, |
| 400 | 'application/vnd.apache.arrow.stream' |
| 401 | ) |
| 402 | if (res.status !== 200) { |
| 403 | throw new Error( |
| 404 | `Server Error, status: ${res.status}, ` + |
| 405 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 406 | `message: ${res.statusText}: ${await res.body()}` |
| 407 | ) |
| 408 | } |
| 409 | return tbl.numRows |
| 410 | } |
| 411 | |
| 412 | async createIndex (indexParams: VectorIndexParams): Promise<void> { |
| 413 | const unsupportedParams = [ |
| 414 | 'index_name', |
| 415 | 'num_partitions', |
| 416 | 'max_iters', |
| 417 | 'use_opq', |
| 418 | 'num_sub_vectors', |
| 419 | 'num_bits', |
| 420 | 'max_opq_iters', |
| 421 | 'replace' |
| 422 | ] |
| 423 | for (const param of unsupportedParams) { |
| 424 | // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions |
| 425 | if (indexParams[param as keyof VectorIndexParams]) { |
| 426 | throw new Error(`${param} is not supported for remote connections`) |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | const column = indexParams.column ?? 'vector' |
| 431 | const indexType = 'vector' |
| 432 | const metricType = indexParams.metric_type ?? 'L2' |
| 433 | const indexCacheSize = indexParams.index_cache_size ?? null |
| 434 | |
| 435 | const data = { |
| 436 | column, |
| 437 | index_type: indexType, |
| 438 | metric_type: metricType, |
| 439 | index_cache_size: indexCacheSize |
| 440 | } |
| 441 | const res = await this._client.post( |
| 442 | `/v1/table/${encodeURIComponent(this._name)}/create_index/`, |
| 443 | data |
| 444 | ) |
| 445 | if (res.status !== 200) { |
| 446 | throw new Error( |
| 447 | `Server Error, status: ${res.status}, ` + |
| 448 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 449 | `message: ${res.statusText}: ${await res.body()}` |
| 450 | ) |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | async createScalarIndex (column: string): Promise<void> { |
| 455 | const indexType = 'scalar' |
| 456 | |
| 457 | const data = { |
| 458 | column, |
| 459 | index_type: indexType, |
| 460 | replace: true |
| 461 | } |
| 462 | const res = await this._client.post( |
| 463 | `/v1/table/${encodeURIComponent(this._name)}/create_scalar_index/`, |
| 464 | data |
| 465 | ) |
| 466 | if (res.status !== 200) { |
| 467 | throw new Error( |
| 468 | `Server Error, status: ${res.status}, ` + |
| 469 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 470 | `message: ${res.statusText}: ${await res.body()}` |
| 471 | ) |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | async countRows (filter?: string): Promise<number> { |
| 476 | const result = await this._client.post(`/v1/table/${encodeURIComponent(this._name)}/count_rows/`, { |
| 477 | predicate: filter |
| 478 | }) |
| 479 | return (await result.body()) |
| 480 | } |
| 481 | |
| 482 | async delete (filter: string): Promise<void> { |
| 483 | await this._client.post(`/v1/table/${encodeURIComponent(this._name)}/delete/`, { |
| 484 | predicate: filter |
| 485 | }) |
| 486 | } |
| 487 | |
| 488 | async update (args: UpdateArgs | UpdateSqlArgs): Promise<void> { |
| 489 | let filter: string | null |
| 490 | let updates: Record<string, string> |
| 491 | |
| 492 | if ('valuesSql' in args) { |
| 493 | filter = args.where ?? null |
| 494 | updates = args.valuesSql |
| 495 | } else { |
| 496 | filter = args.where ?? null |
| 497 | updates = {} |
| 498 | for (const [key, value] of Object.entries(args.values)) { |
| 499 | updates[key] = toSQL(value) |
| 500 | } |
| 501 | } |
| 502 | await this._client.post(`/v1/table/${encodeURIComponent(this._name)}/update/`, { |
| 503 | predicate: filter, |
| 504 | updates: Object.entries(updates).map(([key, value]) => [key, value]) |
| 505 | }) |
| 506 | } |
| 507 | |
| 508 | async listIndices (): Promise<VectorIndex[]> { |
| 509 | const results = await this._client.post( |
| 510 | `/v1/table/${encodeURIComponent(this._name)}/index/list/` |
| 511 | ) |
| 512 | return (await results.body()).indexes?.map((index: any) => ({ |
| 513 | columns: index.columns, |
| 514 | name: index.index_name, |
| 515 | uuid: index.index_uuid, |
| 516 | status: index.status |
| 517 | })) |
| 518 | } |
| 519 | |
| 520 | async indexStats (indexName: string): Promise<IndexStats> { |
| 521 | const results = await this._client.post( |
| 522 | `/v1/table/${encodeURIComponent(this._name)}/index/${indexName}/stats/` |
| 523 | ) |
| 524 | const body = await results.body() |
| 525 | return { |
| 526 | numIndexedRows: body?.num_indexed_rows, |
| 527 | numUnindexedRows: body?.num_unindexed_rows, |
| 528 | indexType: body?.index_type, |
| 529 | distanceType: body?.distance_type |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | async addColumns (newColumnTransforms: Array<{ name: string, valueSql: string }>): Promise<void> { |
| 534 | throw new Error('Add columns is not yet supported in LanceDB Cloud.') |
| 535 | } |
| 536 | |
| 537 | async alterColumns (columnAlterations: ColumnAlteration[]): Promise<void> { |
| 538 | throw new Error('Alter columns is not yet supported in LanceDB Cloud.') |
| 539 | } |
| 540 | |
| 541 | async dropColumns (columnNames: string[]): Promise<void> { |
| 542 | throw new Error('Drop columns is not yet supported in LanceDB Cloud.') |
| 543 | } |
| 544 | |
| 545 | withMiddleware(middleware: HttpMiddleware): Table<T> { |
| 546 | const wrapped = this.clone() |
| 547 | wrapped._client = wrapped._client.withMiddleware(middleware) |
| 548 | return wrapped |
| 549 | } |
| 550 | |
| 551 | private clone (): RemoteTable<T> { |
| 552 | const clone: RemoteTable<T> = Object.create(RemoteTable.prototype) |
| 553 | return Object.assign(clone, this) |
| 554 | } |
| 555 | } |