@lancedb/lancedb 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/arrow.d.ts +2 -3
  2. package/dist/arrow.js +2 -27
  3. package/dist/connection.d.ts +9 -0
  4. package/dist/connection.js +16 -2
  5. package/dist/embedding/embedding_function.d.ts +11 -0
  6. package/dist/embedding/embedding_function.js +28 -7
  7. package/dist/embedding/index.d.ts +2 -1
  8. package/dist/embedding/index.js +7 -6
  9. package/dist/embedding/openai.d.ts +1 -1
  10. package/dist/embedding/registry.d.ts +9 -7
  11. package/dist/embedding/registry.js +24 -6
  12. package/dist/embedding/transformers.d.ts +37 -0
  13. package/dist/embedding/transformers.js +147 -0
  14. package/dist/index.d.ts +1 -1
  15. package/dist/query.js +15 -9
  16. package/dist/remote/client.d.ts +1 -1
  17. package/dist/remote/client.js +6 -8
  18. package/dist/remote/connection.d.ts +2 -3
  19. package/dist/remote/connection.js +2 -2
  20. package/dist/sanitize.js +4 -2
  21. package/dist/table.d.ts +3 -0
  22. package/dist/table.js +1 -1
  23. package/package.json +17 -13
  24. package/Cargo.toml +0 -28
  25. package/biome.json +0 -158
  26. package/build.rs +0 -5
  27. package/dist/native.d.ts +0 -208
  28. package/examples/ann_indexes.ts +0 -49
  29. package/examples/basic.ts +0 -149
  30. package/examples/embedding.ts +0 -83
  31. package/examples/filtering.ts +0 -34
  32. package/examples/jsconfig.json +0 -27
  33. package/examples/package-lock.json +0 -79
  34. package/examples/package.json +0 -18
  35. package/examples/search.ts +0 -37
  36. package/jest.config.js +0 -7
  37. package/lancedb/arrow.ts +0 -947
  38. package/lancedb/connection.ts +0 -333
  39. package/lancedb/embedding/embedding_function.ts +0 -194
  40. package/lancedb/embedding/index.ts +0 -113
  41. package/lancedb/embedding/openai.ts +0 -113
  42. package/lancedb/embedding/registry.ts +0 -188
  43. package/lancedb/index.ts +0 -142
  44. package/lancedb/indices.ts +0 -203
  45. package/lancedb/merge.ts +0 -70
  46. package/lancedb/query.ts +0 -507
  47. package/lancedb/remote/client.ts +0 -221
  48. package/lancedb/remote/connection.ts +0 -201
  49. package/lancedb/remote/index.ts +0 -3
  50. package/lancedb/remote/table.ts +0 -226
  51. package/lancedb/sanitize.ts +0 -588
  52. package/lancedb/table.ts +0 -669
  53. package/lancedb/util.ts +0 -69
  54. package/native.d.ts +0 -208
  55. package/nodejs-artifacts/arrow.d.ts +0 -250
  56. package/nodejs-artifacts/arrow.js +0 -768
  57. package/nodejs-artifacts/connection.d.ts +0 -171
  58. package/nodejs-artifacts/connection.js +0 -135
  59. package/nodejs-artifacts/embedding/embedding_function.d.ts +0 -79
  60. package/nodejs-artifacts/embedding/embedding_function.js +0 -112
  61. package/nodejs-artifacts/embedding/index.d.ts +0 -28
  62. package/nodejs-artifacts/embedding/index.js +0 -114
  63. package/nodejs-artifacts/embedding/openai.d.ts +0 -18
  64. package/nodejs-artifacts/embedding/openai.js +0 -105
  65. package/nodejs-artifacts/embedding/registry.d.ts +0 -53
  66. package/nodejs-artifacts/embedding/registry.js +0 -127
  67. package/nodejs-artifacts/index.d.ts +0 -55
  68. package/nodejs-artifacts/index.js +0 -57
  69. package/nodejs-artifacts/indices.d.ts +0 -165
  70. package/nodejs-artifacts/indices.js +0 -71
  71. package/nodejs-artifacts/merge.d.ts +0 -54
  72. package/nodejs-artifacts/merge.js +0 -64
  73. package/nodejs-artifacts/native.d.ts +0 -208
  74. package/nodejs-artifacts/native.js +0 -330
  75. package/nodejs-artifacts/query.d.ts +0 -283
  76. package/nodejs-artifacts/query.js +0 -448
  77. package/nodejs-artifacts/remote/client.d.ts +0 -28
  78. package/nodejs-artifacts/remote/client.js +0 -172
  79. package/nodejs-artifacts/remote/connection.d.ts +0 -25
  80. package/nodejs-artifacts/remote/connection.js +0 -110
  81. package/nodejs-artifacts/remote/index.d.ts +0 -3
  82. package/nodejs-artifacts/remote/index.js +0 -9
  83. package/nodejs-artifacts/remote/table.d.ts +0 -42
  84. package/nodejs-artifacts/remote/table.js +0 -179
  85. package/nodejs-artifacts/sanitize.d.ts +0 -31
  86. package/nodejs-artifacts/sanitize.js +0 -436
  87. package/nodejs-artifacts/table.d.ts +0 -395
  88. package/nodejs-artifacts/table.js +0 -230
  89. package/nodejs-artifacts/util.d.ts +0 -14
  90. package/nodejs-artifacts/util.js +0 -65
  91. package/tsconfig.json +0 -25
  92. package/typedoc.json +0 -10
@@ -1,448 +0,0 @@
1
- "use strict";
2
- // Copyright 2024 Lance Developers.
3
- //
4
- // Licensed under the Apache License, Version 2.0 (the "License");
5
- // you may not use this file except in compliance with the License.
6
- // You may obtain a copy of the License at
7
- //
8
- // http://www.apache.org/licenses/LICENSE-2.0
9
- //
10
- // Unless required by applicable law or agreed to in writing, software
11
- // distributed under the License is distributed on an "AS IS" BASIS,
12
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- // See the License for the specific language governing permissions and
14
- // limitations under the License.
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.Query = exports.VectorQuery = exports.QueryBase = exports.RecordBatchIterator = void 0;
17
- const arrow_1 = require("./arrow");
18
- class RecordBatchIterator {
19
- promisedInner;
20
- inner;
21
- constructor(promise) {
22
- // TODO: check promise reliably so we dont need to pass two arguments.
23
- this.promisedInner = promise;
24
- }
25
- // biome-ignore lint/suspicious/noExplicitAny: skip
26
- async next() {
27
- if (this.inner === undefined) {
28
- this.inner = await this.promisedInner;
29
- }
30
- if (this.inner === undefined) {
31
- throw new Error("Invalid iterator state state");
32
- }
33
- const n = await this.inner.next();
34
- if (n == null) {
35
- return Promise.resolve({ done: true, value: null });
36
- }
37
- const tbl = (0, arrow_1.tableFromIPC)(n);
38
- if (tbl.batches.length != 1) {
39
- throw new Error("Expected only one batch");
40
- }
41
- return Promise.resolve({ done: false, value: tbl.batches[0] });
42
- }
43
- }
44
- exports.RecordBatchIterator = RecordBatchIterator;
45
- /* eslint-enable */
46
- class RecordBatchIterable {
47
- inner;
48
- options;
49
- constructor(inner, options) {
50
- this.inner = inner;
51
- this.options = options;
52
- }
53
- // biome-ignore lint/suspicious/noExplicitAny: skip
54
- [Symbol.asyncIterator]() {
55
- return new RecordBatchIterator(this.inner.execute(this.options?.maxBatchLength));
56
- }
57
- }
58
- /** Common methods supported by all query types */
59
- class QueryBase {
60
- inner;
61
- constructor(inner) {
62
- this.inner = inner;
63
- // intentionally empty
64
- }
65
- // call a function on the inner (either a promise or the actual object)
66
- doCall(fn) {
67
- if (this.inner instanceof Promise) {
68
- this.inner = this.inner.then((inner) => {
69
- fn(inner);
70
- return inner;
71
- });
72
- }
73
- else {
74
- fn(this.inner);
75
- }
76
- }
77
- /**
78
- * A filter statement to be applied to this query.
79
- *
80
- * The filter should be supplied as an SQL query string. For example:
81
- * @example
82
- * x > 10
83
- * y > 0 AND y < 100
84
- * x > 5 OR y = 'test'
85
- *
86
- * Filtering performance can often be improved by creating a scalar index
87
- * on the filter column(s).
88
- */
89
- where(predicate) {
90
- this.doCall((inner) => inner.onlyIf(predicate));
91
- return this;
92
- }
93
- /**
94
- * A filter statement to be applied to this query.
95
- * @alias where
96
- * @deprecated Use `where` instead
97
- */
98
- filter(predicate) {
99
- return this.where(predicate);
100
- }
101
- /**
102
- * Return only the specified columns.
103
- *
104
- * By default a query will return all columns from the table. However, this can have
105
- * a very significant impact on latency. LanceDb stores data in a columnar fashion. This
106
- * means we can finely tune our I/O to select exactly the columns we need.
107
- *
108
- * As a best practice you should always limit queries to the columns that you need. If you
109
- * pass in an array of column names then only those columns will be returned.
110
- *
111
- * You can also use this method to create new "dynamic" columns based on your existing columns.
112
- * For example, you may not care about "a" or "b" but instead simply want "a + b". This is often
113
- * seen in the SELECT clause of an SQL query (e.g. `SELECT a+b FROM my_table`).
114
- *
115
- * To create dynamic columns you can pass in a Map<string, string>. A column will be returned
116
- * for each entry in the map. The key provides the name of the column. The value is
117
- * an SQL string used to specify how the column is calculated.
118
- *
119
- * For example, an SQL query might state `SELECT a + b AS combined, c`. The equivalent
120
- * input to this method would be:
121
- * @example
122
- * new Map([["combined", "a + b"], ["c", "c"]])
123
- *
124
- * Columns will always be returned in the order given, even if that order is different than
125
- * the order used when adding the data.
126
- *
127
- * Note that you can pass in a `Record<string, string>` (e.g. an object literal). This method
128
- * uses `Object.entries` which should preserve the insertion order of the object. However,
129
- * object insertion order is easy to get wrong and `Map` is more foolproof.
130
- */
131
- select(columns) {
132
- let columnTuples;
133
- if (typeof columns === "string") {
134
- columns = [columns];
135
- }
136
- if (Array.isArray(columns)) {
137
- columnTuples = columns.map((c) => [c, c]);
138
- }
139
- else if (columns instanceof Map) {
140
- columnTuples = Array.from(columns.entries());
141
- }
142
- else {
143
- columnTuples = Object.entries(columns);
144
- }
145
- this.doCall((inner) => {
146
- inner.select(columnTuples);
147
- });
148
- return this;
149
- }
150
- /**
151
- * Set the maximum number of results to return.
152
- *
153
- * By default, a plain search has no limit. If this method is not
154
- * called then every valid row from the table will be returned.
155
- */
156
- limit(limit) {
157
- this.doCall((inner) => inner.limit(limit));
158
- return this;
159
- }
160
- nativeExecute(options) {
161
- if (this.inner instanceof Promise) {
162
- return this.inner.then((inner) => inner.execute(options?.maxBatchLength));
163
- }
164
- else {
165
- return this.inner.execute(options?.maxBatchLength);
166
- }
167
- }
168
- /**
169
- * Execute the query and return the results as an @see {@link AsyncIterator}
170
- * of @see {@link RecordBatch}.
171
- *
172
- * By default, LanceDb will use many threads to calculate results and, when
173
- * the result set is large, multiple batches will be processed at one time.
174
- * This readahead is limited however and backpressure will be applied if this
175
- * stream is consumed slowly (this constrains the maximum memory used by a
176
- * single query)
177
- *
178
- */
179
- execute(options) {
180
- return new RecordBatchIterator(this.nativeExecute(options));
181
- }
182
- // biome-ignore lint/suspicious/noExplicitAny: skip
183
- [Symbol.asyncIterator]() {
184
- const promise = this.nativeExecute();
185
- return new RecordBatchIterator(promise);
186
- }
187
- /** Collect the results as an Arrow @see {@link ArrowTable}. */
188
- async toArrow(options) {
189
- const batches = [];
190
- let inner;
191
- if (this.inner instanceof Promise) {
192
- inner = await this.inner;
193
- }
194
- else {
195
- inner = this.inner;
196
- }
197
- for await (const batch of new RecordBatchIterable(inner, options)) {
198
- batches.push(batch);
199
- }
200
- return new arrow_1.Table(batches);
201
- }
202
- /** Collect the results as an array of objects. */
203
- // biome-ignore lint/suspicious/noExplicitAny: arrow.toArrow() returns any[]
204
- async toArray(options) {
205
- const tbl = await this.toArrow(options);
206
- return tbl.toArray();
207
- }
208
- /**
209
- * Generates an explanation of the query execution plan.
210
- *
211
- * @example
212
- * import * as lancedb from "@lancedb/lancedb"
213
- * const db = await lancedb.connect("./.lancedb");
214
- * const table = await db.createTable("my_table", [
215
- * { vector: [1.1, 0.9], id: "1" },
216
- * ]);
217
- * const plan = await table.query().nearestTo([0.5, 0.2]).explainPlan();
218
- *
219
- * @param verbose - If true, provides a more detailed explanation. Defaults to false.
220
- * @returns A Promise that resolves to a string containing the query execution plan explanation.
221
- */
222
- async explainPlan(verbose = false) {
223
- if (this.inner instanceof Promise) {
224
- return this.inner.then((inner) => inner.explainPlan(verbose));
225
- }
226
- else {
227
- return this.inner.explainPlan(verbose);
228
- }
229
- }
230
- }
231
- exports.QueryBase = QueryBase;
232
- /**
233
- * A builder used to construct a vector search
234
- *
235
- * This builder can be reused to execute the query many times.
236
- */
237
- class VectorQuery extends QueryBase {
238
- constructor(inner) {
239
- super(inner);
240
- }
241
- /**
242
- * Set the number of partitions to search (probe)
243
- *
244
- * This argument is only used when the vector column has an IVF PQ index.
245
- * If there is no index then this value is ignored.
246
- *
247
- * The IVF stage of IVF PQ divides the input into partitions (clusters) of
248
- * related values.
249
- *
250
- * The partition whose centroids are closest to the query vector will be
251
- * exhaustiely searched to find matches. This parameter controls how many
252
- * partitions should be searched.
253
- *
254
- * Increasing this value will increase the recall of your query but will
255
- * also increase the latency of your query. The default value is 20. This
256
- * default is good for many cases but the best value to use will depend on
257
- * your data and the recall that you need to achieve.
258
- *
259
- * For best results we recommend tuning this parameter with a benchmark against
260
- * your actual data to find the smallest possible value that will still give
261
- * you the desired recall.
262
- */
263
- nprobes(nprobes) {
264
- super.doCall((inner) => inner.nprobes(nprobes));
265
- return this;
266
- }
267
- /**
268
- * Set the vector column to query
269
- *
270
- * This controls which column is compared to the query vector supplied in
271
- * the call to @see {@link Query#nearestTo}
272
- *
273
- * This parameter must be specified if the table has more than one column
274
- * whose data type is a fixed-size-list of floats.
275
- */
276
- column(column) {
277
- super.doCall((inner) => inner.column(column));
278
- return this;
279
- }
280
- /**
281
- * Set the distance metric to use
282
- *
283
- * When performing a vector search we try and find the "nearest" vectors according
284
- * to some kind of distance metric. This parameter controls which distance metric to
285
- * use. See @see {@link IvfPqOptions.distanceType} for more details on the different
286
- * distance metrics available.
287
- *
288
- * Note: if there is a vector index then the distance type used MUST match the distance
289
- * type used to train the vector index. If this is not done then the results will be
290
- * invalid.
291
- *
292
- * By default "l2" is used.
293
- */
294
- distanceType(distanceType) {
295
- super.doCall((inner) => inner.distanceType(distanceType));
296
- return this;
297
- }
298
- /**
299
- * A multiplier to control how many additional rows are taken during the refine step
300
- *
301
- * This argument is only used when the vector column has an IVF PQ index.
302
- * If there is no index then this value is ignored.
303
- *
304
- * An IVF PQ index stores compressed (quantized) values. They query vector is compared
305
- * against these values and, since they are compressed, the comparison is inaccurate.
306
- *
307
- * This parameter can be used to refine the results. It can improve both improve recall
308
- * and correct the ordering of the nearest results.
309
- *
310
- * To refine results LanceDb will first perform an ANN search to find the nearest
311
- * `limit` * `refine_factor` results. In other words, if `refine_factor` is 3 and
312
- * `limit` is the default (10) then the first 30 results will be selected. LanceDb
313
- * then fetches the full, uncompressed, values for these 30 results. The results are
314
- * then reordered by the true distance and only the nearest 10 are kept.
315
- *
316
- * Note: there is a difference between calling this method with a value of 1 and never
317
- * calling this method at all. Calling this method with any value will have an impact
318
- * on your search latency. When you call this method with a `refine_factor` of 1 then
319
- * LanceDb still needs to fetch the full, uncompressed, values so that it can potentially
320
- * reorder the results.
321
- *
322
- * Note: if this method is NOT called then the distances returned in the _distance column
323
- * will be approximate distances based on the comparison of the quantized query vector
324
- * and the quantized result vectors. This can be considerably different than the true
325
- * distance between the query vector and the actual uncompressed vector.
326
- */
327
- refineFactor(refineFactor) {
328
- super.doCall((inner) => inner.refineFactor(refineFactor));
329
- return this;
330
- }
331
- /**
332
- * If this is called then filtering will happen after the vector search instead of
333
- * before.
334
- *
335
- * By default filtering will be performed before the vector search. This is how
336
- * filtering is typically understood to work. This prefilter step does add some
337
- * additional latency. Creating a scalar index on the filter column(s) can
338
- * often improve this latency. However, sometimes a filter is too complex or scalar
339
- * indices cannot be applied to the column. In these cases postfiltering can be
340
- * used instead of prefiltering to improve latency.
341
- *
342
- * Post filtering applies the filter to the results of the vector search. This means
343
- * we only run the filter on a much smaller set of data. However, it can cause the
344
- * query to return fewer than `limit` results (or even no results) if none of the nearest
345
- * results match the filter.
346
- *
347
- * Post filtering happens during the "refine stage" (described in more detail in
348
- * @see {@link VectorQuery#refineFactor}). This means that setting a higher refine
349
- * factor can often help restore some of the results lost by post filtering.
350
- */
351
- postfilter() {
352
- super.doCall((inner) => inner.postfilter());
353
- return this;
354
- }
355
- /**
356
- * If this is called then any vector index is skipped
357
- *
358
- * An exhaustive (flat) search will be performed. The query vector will
359
- * be compared to every vector in the table. At high scales this can be
360
- * expensive. However, this is often still useful. For example, skipping
361
- * the vector index can give you ground truth results which you can use to
362
- * calculate your recall to select an appropriate value for nprobes.
363
- */
364
- bypassVectorIndex() {
365
- super.doCall((inner) => inner.bypassVectorIndex());
366
- return this;
367
- }
368
- }
369
- exports.VectorQuery = VectorQuery;
370
- /** A builder for LanceDB queries. */
371
- class Query extends QueryBase {
372
- constructor(tbl) {
373
- super(tbl.query());
374
- }
375
- /**
376
- * Find the nearest vectors to the given query vector.
377
- *
378
- * This converts the query from a plain query to a vector query.
379
- *
380
- * This method will attempt to convert the input to the query vector
381
- * expected by the embedding model. If the input cannot be converted
382
- * then an error will be thrown.
383
- *
384
- * By default, there is no embedding model, and the input should be
385
- * an array-like object of numbers (something that can be used as input
386
- * to Float32Array.from)
387
- *
388
- * If there is only one vector column (a column whose data type is a
389
- * fixed size list of floats) then the column does not need to be specified.
390
- * If there is more than one vector column you must use
391
- * @see {@link VectorQuery#column} to specify which column you would like
392
- * to compare with.
393
- *
394
- * If no index has been created on the vector column then a vector query
395
- * will perform a distance comparison between the query vector and every
396
- * vector in the database and then sort the results. This is sometimes
397
- * called a "flat search"
398
- *
399
- * For small databases, with a few hundred thousand vectors or less, this can
400
- * be reasonably fast. In larger databases you should create a vector index
401
- * on the column. If there is a vector index then an "approximate" nearest
402
- * neighbor search (frequently called an ANN search) will be performed. This
403
- * search is much faster, but the results will be approximate.
404
- *
405
- * The query can be further parameterized using the returned builder. There
406
- * are various ANN search parameters that will let you fine tune your recall
407
- * accuracy vs search latency.
408
- *
409
- * Vector searches always have a `limit`. If `limit` has not been called then
410
- * a default `limit` of 10 will be used. @see {@link Query#limit}
411
- */
412
- nearestTo(vector) {
413
- if (this.inner instanceof Promise) {
414
- const nativeQuery = this.inner.then(async (inner) => {
415
- if (vector instanceof Promise) {
416
- const arr = await vector.then((v) => Float32Array.from(v));
417
- return inner.nearestTo(arr);
418
- }
419
- else {
420
- return inner.nearestTo(Float32Array.from(vector));
421
- }
422
- });
423
- return new VectorQuery(nativeQuery);
424
- }
425
- if (vector instanceof Promise) {
426
- const res = (async () => {
427
- try {
428
- const v = await vector;
429
- const arr = Float32Array.from(v);
430
- //
431
- // biome-ignore lint/suspicious/noExplicitAny: we need to get the `inner`, but js has no package scoping
432
- const value = this.nearestTo(arr);
433
- const inner = value.inner;
434
- return inner;
435
- }
436
- catch (e) {
437
- return Promise.reject(e);
438
- }
439
- })();
440
- return new VectorQuery(res);
441
- }
442
- else {
443
- const vectorQuery = this.inner.nearestTo(Float32Array.from(vector));
444
- return new VectorQuery(vectorQuery);
445
- }
446
- }
447
- }
448
- exports.Query = Query;
@@ -1,28 +0,0 @@
1
- /// <reference types="node" />
2
- import { type AxiosResponse } from "axios";
3
- import { Table as ArrowTable } from "../arrow";
4
- import { VectorQuery } from "../query";
5
- export declare class RestfulLanceDBClient {
6
- #private;
7
- constructor(dbName: string, apiKey: string, region: string, hostOverride?: string, connectionTimeout?: number, readTimeout?: number);
8
- get session(): import("axios").AxiosInstance;
9
- get url(): string;
10
- get headers(): {
11
- [key: string]: string;
12
- };
13
- isOpen(): boolean;
14
- private checkNotClosed;
15
- close(): void;
16
- get(uri: string, params?: Record<string, any>): Promise<any>;
17
- post(uri: string, body?: any): Promise<any>;
18
- post(uri: string, body: any, additional: {
19
- config?: {
20
- responseType: "arraybuffer";
21
- };
22
- headers?: Record<string, string>;
23
- params?: Record<string, string>;
24
- }): Promise<Buffer>;
25
- listTables(limit?: number, pageToken?: string): Promise<string[]>;
26
- query(tableName: string, query: VectorQuery): Promise<ArrowTable>;
27
- static checkStatus(response: AxiosResponse): void;
28
- }
@@ -1,172 +0,0 @@
1
- "use strict";
2
- // Copyright 2023 LanceDB Developers.
3
- //
4
- // Licensed under the Apache License, Version 2.0 (the "License");
5
- // you may not use this file except in compliance with the License.
6
- // You may obtain a copy of the License at
7
- //
8
- // http://www.apache.org/licenses/LICENSE-2.0
9
- //
10
- // Unless required by applicable law or agreed to in writing, software
11
- // distributed under the License is distributed on an "AS IS" BASIS,
12
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- // See the License for the specific language governing permissions and
14
- // limitations under the License.
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.RestfulLanceDBClient = void 0;
17
- const axios_1 = require("axios");
18
- const arrow_1 = require("../arrow");
19
- class RestfulLanceDBClient {
20
- #dbName;
21
- #region;
22
- #apiKey;
23
- #hostOverride;
24
- #closed = false;
25
- #connectionTimeout = 12 * 1000; // 12 seconds;
26
- #readTimeout = 30 * 1000; // 30 seconds;
27
- #session;
28
- constructor(dbName, apiKey, region, hostOverride, connectionTimeout, readTimeout) {
29
- this.#dbName = dbName;
30
- this.#apiKey = apiKey;
31
- this.#region = region;
32
- this.#hostOverride = hostOverride ?? this.#hostOverride;
33
- this.#connectionTimeout = connectionTimeout ?? this.#connectionTimeout;
34
- this.#readTimeout = readTimeout ?? this.#readTimeout;
35
- }
36
- // todo: cache the session.
37
- get session() {
38
- if (this.#session !== undefined) {
39
- return this.#session;
40
- }
41
- else {
42
- return axios_1.default.create({
43
- baseURL: this.url,
44
- headers: {
45
- // biome-ignore lint: external API
46
- Authorization: `Bearer ${this.#apiKey}`,
47
- },
48
- transformResponse: decodeErrorData,
49
- timeout: this.#connectionTimeout,
50
- });
51
- }
52
- }
53
- get url() {
54
- return (this.#hostOverride ??
55
- `https://${this.#dbName}.${this.#region}.api.lancedb.com`);
56
- }
57
- get headers() {
58
- const headers = {
59
- "x-api-key": this.#apiKey,
60
- "x-request-id": "na",
61
- };
62
- if (this.#region == "local") {
63
- headers["Host"] = `${this.#dbName}.${this.#region}.api.lancedb.com`;
64
- }
65
- if (this.#hostOverride) {
66
- headers["x-lancedb-database"] = this.#dbName;
67
- }
68
- return headers;
69
- }
70
- isOpen() {
71
- return !this.#closed;
72
- }
73
- checkNotClosed() {
74
- if (this.#closed) {
75
- throw new Error("Connection is closed");
76
- }
77
- }
78
- close() {
79
- this.#session = undefined;
80
- this.#closed = true;
81
- }
82
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
83
- async get(uri, params) {
84
- this.checkNotClosed();
85
- uri = new URL(uri, this.url).toString();
86
- let response;
87
- try {
88
- response = await this.session.get(uri, {
89
- headers: this.headers,
90
- params,
91
- });
92
- }
93
- catch (e) {
94
- if (e instanceof axios_1.AxiosError) {
95
- response = e.response;
96
- }
97
- else {
98
- throw e;
99
- }
100
- }
101
- RestfulLanceDBClient.checkStatus(response);
102
- return response.data;
103
- }
104
- async post(uri,
105
- // biome-ignore lint/suspicious/noExplicitAny: api request
106
- body, additional) {
107
- this.checkNotClosed();
108
- uri = new URL(uri, this.url).toString();
109
- additional = Object.assign({ config: { responseType: "json" } }, additional);
110
- const headers = { ...this.headers, ...additional.headers };
111
- if (!headers["Content-Type"]) {
112
- headers["Content-Type"] = "application/json";
113
- }
114
- let response;
115
- try {
116
- response = await this.session.post(uri, body, {
117
- headers,
118
- responseType: additional.config.responseType,
119
- params: new Map(Object.entries(additional.params ?? {})),
120
- });
121
- }
122
- catch (e) {
123
- if (e instanceof axios_1.AxiosError) {
124
- response = e.response;
125
- }
126
- else {
127
- throw e;
128
- }
129
- }
130
- RestfulLanceDBClient.checkStatus(response);
131
- if (additional.config.responseType === "arraybuffer") {
132
- return response.data;
133
- }
134
- else {
135
- return JSON.parse(response.data);
136
- }
137
- }
138
- async listTables(limit = 10, pageToken = "") {
139
- const json = await this.get("/v1/table", { limit, pageToken });
140
- return json.tables;
141
- }
142
- async query(tableName, query) {
143
- const tbl = await this.post(`/v1/table/${tableName}/query`, query, {
144
- config: {
145
- responseType: "arraybuffer",
146
- },
147
- });
148
- return (0, arrow_1.tableFromIPC)(tbl);
149
- }
150
- static checkStatus(response) {
151
- if (response.status === 404) {
152
- throw new Error(`Not found: ${response.data}`);
153
- }
154
- else if (response.status >= 400 && response.status < 500) {
155
- throw new Error(`Bad Request: ${response.status}, error: ${response.data}`);
156
- }
157
- else if (response.status >= 500 && response.status < 600) {
158
- throw new Error(`Internal Server Error: ${response.status}, error: ${response.data}`);
159
- }
160
- else if (response.status !== 200) {
161
- throw new Error(`Unknown Error: ${response.status}, error: ${response.data}`);
162
- }
163
- }
164
- }
165
- exports.RestfulLanceDBClient = RestfulLanceDBClient;
166
- function decodeErrorData(data) {
167
- if (Buffer.isBuffer(data)) {
168
- const decoded = data.toString("utf-8");
169
- return decoded;
170
- }
171
- return data;
172
- }
@@ -1,25 +0,0 @@
1
- import { Data, SchemaLike } from "../arrow";
2
- import { Connection, CreateTableOptions, OpenTableOptions, TableNamesOptions } from "../connection";
3
- import { Table } from "../table";
4
- export interface RemoteConnectionOptions {
5
- apiKey?: string;
6
- region?: string;
7
- hostOverride?: string;
8
- connectionTimeout?: number;
9
- readTimeout?: number;
10
- }
11
- export declare class RemoteConnection extends Connection {
12
- #private;
13
- constructor(url: string, { apiKey, region, hostOverride, connectionTimeout, readTimeout, }: RemoteConnectionOptions);
14
- isOpen(): boolean;
15
- close(): void;
16
- display(): string;
17
- tableNames(options?: Partial<TableNamesOptions>): Promise<string[]>;
18
- openTable(name: string, _options?: Partial<OpenTableOptions> | undefined): Promise<Table>;
19
- createTable(nameOrOptions: string | ({
20
- name: string;
21
- data: Data;
22
- } & Partial<CreateTableOptions>), data?: Data, options?: Partial<CreateTableOptions> | undefined): Promise<Table>;
23
- createEmptyTable(name: string, schema: SchemaLike, options?: Partial<CreateTableOptions> | undefined): Promise<Table>;
24
- dropTable(name: string): Promise<void>;
25
- }