mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge branch 'merge-insert-source-stats' into merge-insert-source-stats-bindings
# Conflicts: # python/python/lancedb/db.py
This commit is contained in:
@@ -15,6 +15,7 @@ renovate.json
|
||||
src
|
||||
lancedb
|
||||
examples
|
||||
scripts
|
||||
nodejs-artifacts
|
||||
Cargo.toml
|
||||
biome.json
|
||||
|
||||
@@ -50,6 +50,19 @@ pnpm install
|
||||
pnpm build
|
||||
```
|
||||
|
||||
Local SQL computed columns and materialized-view creation/refresh are experimental
|
||||
and disabled in published packages. To opt in when building from this directory:
|
||||
|
||||
```shell
|
||||
pnpm build:debug --features experimental-functions
|
||||
pnpm tsc
|
||||
pnpm test --runInBand table.test.ts materialized_view.test.ts
|
||||
```
|
||||
|
||||
Rebuild without `--features experimental-functions` to test the default package.
|
||||
The tests detect the compiled feature; remote operations, metadata protections,
|
||||
and ordinary eager `addColumns` transforms remain available in both builds.
|
||||
|
||||
Lint:
|
||||
|
||||
```shell
|
||||
|
||||
+4
-3
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "lancedb-nodejs"
|
||||
edition.workspace = true
|
||||
version = "0.41.0-beta.9"
|
||||
version = "0.41.0-beta.17"
|
||||
publish = false
|
||||
license.workspace = true
|
||||
description.workspace = true
|
||||
@@ -23,7 +23,7 @@ env_logger.workspace = true
|
||||
futures.workspace = true
|
||||
lancedb.workspace = true
|
||||
lance-namespace.workspace = true
|
||||
napi = { version = "3.8.3", default-features = false, features = [
|
||||
napi = { version = "3.15.0", default-features = false, features = [
|
||||
"napi9",
|
||||
"async",
|
||||
"chrono_date",
|
||||
@@ -31,7 +31,7 @@ napi = { version = "3.8.3", default-features = false, features = [
|
||||
] }
|
||||
chrono.workspace = true
|
||||
serde_json.workspace = true
|
||||
napi-derive = "3.5.2"
|
||||
napi-derive = "3.6.13"
|
||||
# Prevent dynamic linking of lzma, which comes from datafusion
|
||||
lzma-sys = { version = "0.1", features = ["static"] }
|
||||
log.workspace = true
|
||||
@@ -48,3 +48,4 @@ napi-build = "2.3.1"
|
||||
default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel"]
|
||||
fp16kernels = ["lancedb/fp16kernels"]
|
||||
remote = ["lancedb/remote"]
|
||||
experimental-functions = ["lancedb/experimental-functions"]
|
||||
|
||||
@@ -86,7 +86,10 @@ describe("remote catalog", () => {
|
||||
value: "team/search",
|
||||
});
|
||||
expect(names.pageToken()).toBe("next");
|
||||
await catalog.dropDatabase("team/search", { ignoreMissing: true });
|
||||
await catalog.dropDatabase("team/search", {
|
||||
ignoreMissing: true,
|
||||
cascade: true,
|
||||
});
|
||||
expect(requests[0].url).toBe("/v1/namespace/team%2Fsearch/create");
|
||||
expect(requests[0].body).toEqual({ mode: "ExistOk" });
|
||||
expect(requests[5].url).toBe(
|
||||
@@ -94,7 +97,7 @@ describe("remote catalog", () => {
|
||||
);
|
||||
expect(requests[6].body).toEqual({
|
||||
mode: "Skip",
|
||||
behavior: "Restrict",
|
||||
behavior: "Cascade",
|
||||
});
|
||||
for (const [i, request] of requests.entries()) {
|
||||
expect(request.headers["x-lancedb-database"]).toBe(
|
||||
|
||||
@@ -5,15 +5,15 @@ import { mkdirSync, readdirSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { Field, Float64, Schema } from "apache-arrow";
|
||||
import * as tmp from "tmp";
|
||||
import {
|
||||
Connection,
|
||||
ListTablesResponse,
|
||||
Table,
|
||||
connect,
|
||||
connectNamespace,
|
||||
} from "../lancedb";
|
||||
import { Connection, Table, connect, connectNamespace } from "../lancedb";
|
||||
import { LocalTable } from "../lancedb/table";
|
||||
|
||||
async function collectNames(items: AsyncIterable<string>): Promise<string[]> {
|
||||
const names: string[] = [];
|
||||
for await (const name of items) names.push(name);
|
||||
return names;
|
||||
}
|
||||
|
||||
describe("when connecting", () => {
|
||||
let tmpDir: tmp.DirResult;
|
||||
beforeEach(() => {
|
||||
@@ -36,6 +36,87 @@ describe("when connecting", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe.each([
|
||||
[
|
||||
"URI overload",
|
||||
(uri: string, options: { storageOptions?: Record<string, string> }) =>
|
||||
connect(uri, options),
|
||||
],
|
||||
[
|
||||
"object overload",
|
||||
async (
|
||||
uri: string,
|
||||
options: { storageOptions?: Record<string, string> },
|
||||
) => {
|
||||
const input = { uri, ...options };
|
||||
if (Object.isFrozen(options)) {
|
||||
Object.freeze(input);
|
||||
}
|
||||
const db = await connect(input);
|
||||
expect(input).toEqual({ uri, ...options });
|
||||
expect(input.storageOptions).toBe(options.storageOptions);
|
||||
return db;
|
||||
},
|
||||
],
|
||||
[
|
||||
"namespace",
|
||||
(uri: string, options: { storageOptions?: Record<string, string> }) =>
|
||||
connectNamespace("dir", { root: uri }, options),
|
||||
],
|
||||
])("%s connection options", (_name, open) => {
|
||||
let tmpDir: tmp.DirResult;
|
||||
beforeEach(() => {
|
||||
tmpDir = tmp.dirSync({ unsafeCleanup: true });
|
||||
});
|
||||
afterEach(() => tmpDir.removeCallback());
|
||||
|
||||
it("should accept frozen options without storage options", async () => {
|
||||
const options = Object.freeze({});
|
||||
const db = await open(tmpDir.name, options);
|
||||
try {
|
||||
await db.createTable("frozen", [{ id: 1 }]);
|
||||
await expect(db.tableNames()).resolves.toContain("frozen");
|
||||
expect(options).toEqual({});
|
||||
} finally {
|
||||
await db.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("should accept frozen options with storage options", async () => {
|
||||
const storageOptions = Object.freeze({
|
||||
newTableDataStorageVersion: "stable",
|
||||
});
|
||||
const options = Object.freeze({ storageOptions });
|
||||
const db = await open(tmpDir.name, options);
|
||||
try {
|
||||
const table = await db.createTable("frozen", [{ id: 1 }]);
|
||||
await expect(table.countRows()).resolves.toBe(1);
|
||||
expect(options.storageOptions).toBe(storageOptions);
|
||||
expect(storageOptions).toEqual({ newTableDataStorageVersion: "stable" });
|
||||
} finally {
|
||||
await db.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("should preserve reused options and their storage options", async () => {
|
||||
const storageOptions = { newTableDataStorageVersion: "stable" };
|
||||
const options = { storageOptions };
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const db = await open(tmpDir.name, options);
|
||||
try {
|
||||
const table = await db.createTable(`reused_${i}`, [{ id: i }]);
|
||||
await expect(table.countRows()).resolves.toBe(1);
|
||||
expect(options.storageOptions).toBe(storageOptions);
|
||||
expect(storageOptions).toEqual({
|
||||
newTableDataStorageVersion: "stable",
|
||||
});
|
||||
} finally {
|
||||
await db.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("given a connection", () => {
|
||||
let tmpDir: tmp.DirResult;
|
||||
let db: Connection;
|
||||
@@ -54,7 +135,7 @@ describe("given a connection", () => {
|
||||
await db.close();
|
||||
expect(db.isOpen()).toBe(false);
|
||||
await expect(db.tableNames()).rejects.toThrow("Connection is closed");
|
||||
await expect(db.listTables()).rejects.toThrow("Connection is closed");
|
||||
expect(() => db.listTables()).toThrow("Connection is closed");
|
||||
await expect(db.renameTable("a", "b")).rejects.toThrow(
|
||||
"Connection is closed",
|
||||
);
|
||||
@@ -117,6 +198,80 @@ describe("given a connection", () => {
|
||||
await expect(tbl.countRows()).resolves.toBe(1);
|
||||
});
|
||||
|
||||
describe.each([undefined, []])("root namespace %p", (namespacePath) => {
|
||||
it("should preserve createTable options after the namespace", async () => {
|
||||
await db.createTable("test", [{ id: 1 }, { id: 2 }]);
|
||||
|
||||
const table = await db.createTable("test", [{ id: 3 }], namespacePath, {
|
||||
mode: "overwrite",
|
||||
});
|
||||
|
||||
const rows = await table.query().toArray();
|
||||
expect(rows.map((row) => row.id)).toEqual([3]);
|
||||
});
|
||||
|
||||
it("should preserve createEmptyTable overwrite after the namespace", async () => {
|
||||
await db.createTable("test", [{ id: 1 }]);
|
||||
const schema = new Schema([new Field("id", new Float64(), true)]);
|
||||
|
||||
const table = await db.createEmptyTable("test", schema, namespacePath, {
|
||||
mode: "overwrite",
|
||||
});
|
||||
|
||||
await expect(table.countRows()).resolves.toBe(0);
|
||||
});
|
||||
|
||||
it("should preserve createEmptyTable existOk after the namespace", async () => {
|
||||
await db.createTable("test", [{ id: 1 }]);
|
||||
const schema = new Schema([new Field("id", new Float64(), true)]);
|
||||
|
||||
const table = await db.createEmptyTable("test", schema, namespacePath, {
|
||||
existOk: true,
|
||||
});
|
||||
|
||||
await expect(table.countRows()).resolves.toBe(1);
|
||||
});
|
||||
|
||||
it("should preserve tableNames options after the namespace", async () => {
|
||||
for (const name of ["a", "b", "c"]) {
|
||||
await db.createTable(name, [{ id: 1 }]);
|
||||
}
|
||||
|
||||
await expect(
|
||||
db.tableNames(namespacePath, { limit: 1, startAfter: "a" }),
|
||||
).resolves.toEqual(["b"]);
|
||||
});
|
||||
|
||||
it("should preserve listTables options after the namespace", async () => {
|
||||
for (const name of ["a", "b", "c"]) {
|
||||
await db.createTable(name, [{ id: 1 }]);
|
||||
}
|
||||
|
||||
const first = db.listTables(namespacePath, { pageLimit: 1 });
|
||||
expect(await first.next()).toEqual({ done: false, value: "a" });
|
||||
expect(first.pageToken()).toBeDefined();
|
||||
|
||||
const second = db.listTables(namespacePath, {
|
||||
pageLimit: 1,
|
||||
pageToken: first.pageToken(),
|
||||
});
|
||||
expect(await second.next()).toEqual({ done: false, value: "b" });
|
||||
});
|
||||
});
|
||||
it("should keep the existing table when mode is exist_ok", async () => {
|
||||
const created = await db.createTable("test", [{ id: 1 }, { id: 2 }], {
|
||||
mode: "exist_ok",
|
||||
});
|
||||
await expect(created.countRows()).resolves.toBe(2);
|
||||
|
||||
const reopened = await db.createTable("test", [{ id: 9 }], {
|
||||
mode: "exist_ok",
|
||||
});
|
||||
await expect(reopened.countRows()).resolves.toBe(2);
|
||||
const rows = (await reopened.query().toArray()) as { id: number }[];
|
||||
expect(rows.map((row) => row.id).sort()).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("should respect limit and page token when listing tables", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
|
||||
@@ -144,19 +299,18 @@ describe("given a connection", () => {
|
||||
await db.createTable("a", [{ id: 1 }]);
|
||||
await db.createTable("c", [{ id: 1 }]);
|
||||
|
||||
const all = await db.listTables();
|
||||
expect(all.tables).toEqual(["a", "b", "c"]);
|
||||
expect(all.pageToken).toBeUndefined();
|
||||
expect(await collectNames(db.listTables())).toEqual(["a", "b", "c"]);
|
||||
|
||||
const first = await db.listTables({ limit: 1 });
|
||||
expect(first.tables).toEqual(["a"]);
|
||||
expect(first.pageToken).toBeDefined();
|
||||
const first = db.listTables([], { pageLimit: 1 });
|
||||
expect(first.numPageResults()).toBe(0);
|
||||
expect(await first.next()).toEqual({ done: false, value: "a" });
|
||||
expect(first.pageToken()).toBeDefined();
|
||||
|
||||
const second = await db.listTables({
|
||||
limit: 1,
|
||||
pageToken: first.pageToken,
|
||||
const second = db.listTables([], {
|
||||
pageLimit: 1,
|
||||
pageToken: first.pageToken(),
|
||||
});
|
||||
expect(second.tables).toEqual(["b"]);
|
||||
expect(await second.next()).toEqual({ done: false, value: "b" });
|
||||
});
|
||||
|
||||
it("should visit every table exactly once when walking pages", async () => {
|
||||
@@ -167,18 +321,71 @@ describe("given a connection", () => {
|
||||
await db.createTable(name, [{ id: 1 }]);
|
||||
}
|
||||
|
||||
const seen: string[] = [];
|
||||
let pageToken: string | undefined = undefined;
|
||||
do {
|
||||
const page: ListTablesResponse = await db.listTables({
|
||||
limit: 2,
|
||||
pageToken,
|
||||
});
|
||||
seen.push(...page.tables);
|
||||
pageToken = page.pageToken;
|
||||
} while (pageToken);
|
||||
expect(await collectNames(db.listTables([], { pageLimit: 2 }))).toEqual(
|
||||
created,
|
||||
);
|
||||
});
|
||||
|
||||
expect(seen).toEqual(created);
|
||||
it.each([2 ** 32, 2 ** 32 + 1, Number.MAX_SAFE_INTEGER])(
|
||||
"should not wrap a large table listing limit %s",
|
||||
async (limit) => {
|
||||
await db.createTable("a", [{ id: 1 }]);
|
||||
await db.createTable("b", [{ id: 2 }]);
|
||||
for (const names of [
|
||||
db.tableNames({ limit }),
|
||||
db.tableNames([], { limit }),
|
||||
]) {
|
||||
await expect(names).resolves.toEqual(["a", "b"]);
|
||||
}
|
||||
for (const namespacePath of [undefined, []]) {
|
||||
expect(() =>
|
||||
db.listTables(namespacePath, { pageLimit: limit }),
|
||||
).toThrow(/limit/);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
-1,
|
||||
1.5,
|
||||
Number.NaN,
|
||||
Number.POSITIVE_INFINITY,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
Number.MAX_SAFE_INTEGER + 1,
|
||||
])("should reject an invalid table listing limit %s", async (limit) => {
|
||||
await expect(db.tableNames({ limit })).rejects.toThrow(/limit/);
|
||||
await expect(db.tableNames([], { limit })).rejects.toThrow(/limit/);
|
||||
for (const namespacePath of [undefined, []]) {
|
||||
expect(() => db.listTables(namespacePath, { pageLimit: limit })).toThrow(
|
||||
/limit/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("should preserve zero, small and unsigned-32-bit table listing limits", async () => {
|
||||
await db.createTable("a", [{ id: 1 }]);
|
||||
await db.createTable("b", [{ id: 2 }]);
|
||||
for (const [limit, names] of [
|
||||
[0, []],
|
||||
[1, ["a"]],
|
||||
[2 ** 32 - 1, ["a", "b"]],
|
||||
] as const) {
|
||||
await expect(db.tableNames({ limit })).resolves.toEqual(names);
|
||||
}
|
||||
await expect(db.tableNames()).resolves.toEqual(["a", "b"]);
|
||||
for (const namespacePath of [undefined, []]) {
|
||||
for (const pageLimit of [1, 2 ** 31 - 1]) {
|
||||
expect(
|
||||
await collectNames(db.listTables(namespacePath, { pageLimit })),
|
||||
).toEqual(["a", "b"]);
|
||||
}
|
||||
for (const pageLimit of [0, 2 ** 31, 2 ** 32 - 1]) {
|
||||
expect(() => db.listTables(namespacePath, { pageLimit })).toThrow(
|
||||
/limit/,
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(await collectNames(db.listTables())).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("should list all names and use a default page size of 100", async () => {
|
||||
@@ -191,20 +398,17 @@ describe("given a connection", () => {
|
||||
}
|
||||
await expect(db.tableNames()).resolves.toEqual(names);
|
||||
await expect(db.tableNames({ limit: 0 })).resolves.toEqual([]);
|
||||
const first = await db.listTables();
|
||||
expect(first.tables).toEqual(names.slice(0, 100));
|
||||
expect(first.pageToken).toBeDefined();
|
||||
const second = await db.listTables({ pageToken: first.pageToken });
|
||||
expect(second.tables).toEqual(names.slice(100));
|
||||
expect(second.pageToken).toBeUndefined();
|
||||
await expect(db.listTables({ limit: 200 })).resolves.toEqual({
|
||||
tables: names,
|
||||
pageToken: undefined,
|
||||
});
|
||||
await expect(db.listTables({ limit: 0 })).resolves.toEqual({
|
||||
tables: [],
|
||||
pageToken: undefined,
|
||||
});
|
||||
const first = db.listTables();
|
||||
const firstPage: string[] = [];
|
||||
for (let i = 0; i < 100; i++) firstPage.push((await first.next()).value!);
|
||||
expect(firstPage).toEqual(names.slice(0, 100));
|
||||
expect(first.pageToken()).toBeDefined();
|
||||
expect(first.numPageResults()).toBe(0);
|
||||
expect(await collectNames(first)).toEqual(names.slice(100));
|
||||
expect(await collectNames(db.listTables([], { pageLimit: 200 }))).toEqual(
|
||||
names,
|
||||
);
|
||||
expect(() => db.listTables([], { pageLimit: 0 })).toThrow(/limit/);
|
||||
});
|
||||
|
||||
it("should list tables in a namespace", async () => {
|
||||
@@ -215,12 +419,8 @@ describe("given a connection", () => {
|
||||
await db.createNamespace(["child"]);
|
||||
await db.createTable("nested", [{ id: 1 }], ["child"]);
|
||||
|
||||
await expect(db.listTables(["child"])).resolves.toEqual(
|
||||
expect.objectContaining({ tables: ["nested"] }),
|
||||
);
|
||||
await expect(db.listTables()).resolves.toEqual(
|
||||
expect.objectContaining({ tables: [] }),
|
||||
);
|
||||
expect(await collectNames(db.listTables(["child"]))).toEqual(["nested"]);
|
||||
expect(await collectNames(db.listTables())).toEqual([]);
|
||||
});
|
||||
|
||||
it("should create tables in v2 mode", async () => {
|
||||
@@ -293,6 +493,69 @@ describe("given a connection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe.each(["createTable", "createEmptyTable"] as const)(
|
||||
"%s storage options",
|
||||
(method) => {
|
||||
const schema = new Schema([new Field("id", new Float64(), true)]);
|
||||
|
||||
it("should accept frozen creation options without storage options", async () => {
|
||||
const options = Object.freeze({
|
||||
dataStorageVersion: "stable",
|
||||
enableV2ManifestPaths: true,
|
||||
});
|
||||
const table =
|
||||
method === "createTable"
|
||||
? await db.createTable("frozen_options", [{ id: 1 }], options)
|
||||
: await db.createEmptyTable("frozen_options", schema, options);
|
||||
expect(await (table as LocalTable).usesV2ManifestPaths()).toBe(true);
|
||||
expect(options).not.toHaveProperty("storageOptions");
|
||||
});
|
||||
|
||||
it("should accept frozen storage options and preserve override precedence", async () => {
|
||||
const storageOptions = Object.freeze({
|
||||
newTableDataStorageVersion: "legacy",
|
||||
newTableEnableV2ManifestPaths: "false",
|
||||
});
|
||||
const options = Object.freeze({
|
||||
storageOptions,
|
||||
dataStorageVersion: "stable",
|
||||
enableV2ManifestPaths: true,
|
||||
});
|
||||
const table =
|
||||
method === "createTable"
|
||||
? await db.createTable("frozen_storage", [{ id: 1 }], options)
|
||||
: await db.createEmptyTable("frozen_storage", schema, options);
|
||||
expect(await (table as LocalTable).usesV2ManifestPaths()).toBe(true);
|
||||
expect(options.storageOptions).toBe(storageOptions);
|
||||
expect(storageOptions).toEqual({
|
||||
newTableDataStorageVersion: "legacy",
|
||||
newTableEnableV2ManifestPaths: "false",
|
||||
});
|
||||
});
|
||||
|
||||
it("should not retain a previous override when reusing storage options", async () => {
|
||||
const storageOptions = { newTableEnableV2ManifestPaths: "false" };
|
||||
const create = async (name: string, enableV2ManifestPaths?: boolean) =>
|
||||
method === "createTable"
|
||||
? db.createTable(name, [{ id: 1 }], {
|
||||
storageOptions,
|
||||
enableV2ManifestPaths,
|
||||
})
|
||||
: db.createEmptyTable(name, schema, {
|
||||
storageOptions,
|
||||
enableV2ManifestPaths,
|
||||
});
|
||||
const first = await create("override", true);
|
||||
expect(await (first as LocalTable).usesV2ManifestPaths()).toBe(true);
|
||||
const second = await create("without_override");
|
||||
expect(await (second as LocalTable).usesV2ManifestPaths()).toBe(false);
|
||||
expect(storageOptions).toEqual({
|
||||
newTableEnableV2ManifestPaths: "false",
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("should be able to migrate tables to the V2 manifest paths", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const table = (await db.createEmptyTable(
|
||||
@@ -451,22 +714,35 @@ describe("namespaces", () => {
|
||||
it("should list namespaces created at the root", async () => {
|
||||
await db.createNamespace(["alpha"]);
|
||||
await db.createNamespace(["beta"]);
|
||||
const list = await db.listNamespaces();
|
||||
expect(list.namespaces).toEqual(expect.arrayContaining(["alpha", "beta"]));
|
||||
const list = await collectNames(db.listNamespaces());
|
||||
expect(list).toEqual(expect.arrayContaining(["alpha", "beta"]));
|
||||
});
|
||||
|
||||
it("should list child namespaces under a parent", async () => {
|
||||
await db.createNamespace(["parent"]);
|
||||
await db.createNamespace(["parent", "child"]);
|
||||
const list = await db.listNamespaces(["parent"]);
|
||||
expect(list.namespaces).toContain("child");
|
||||
const list = await collectNames(db.listNamespaces(["parent"]));
|
||||
expect(list).toContain("child");
|
||||
});
|
||||
|
||||
it("should resume a namespace listing from its page token", async () => {
|
||||
await db.createNamespace(["alpha"]);
|
||||
await db.createNamespace(["beta"]);
|
||||
const first = db.listNamespaces([], { pageLimit: 1 });
|
||||
expect(first.numPageResults()).toBe(0);
|
||||
expect((await first.next()).value).toBe("alpha");
|
||||
const second = db.listNamespaces([], {
|
||||
pageLimit: 1,
|
||||
pageToken: first.pageToken(),
|
||||
});
|
||||
expect(await collectNames(second)).toEqual(["beta"]);
|
||||
});
|
||||
|
||||
it("should drop a namespace", async () => {
|
||||
await db.createNamespace(["ephemeral"]);
|
||||
await db.dropNamespace(["ephemeral"]);
|
||||
const list = await db.listNamespaces();
|
||||
expect(list.namespaces).not.toContain("ephemeral");
|
||||
const list = await collectNames(db.listNamespaces());
|
||||
expect(list).not.toContain("ephemeral");
|
||||
});
|
||||
|
||||
it("should raise an error on any namespace op after close", async () => {
|
||||
@@ -474,7 +750,7 @@ describe("namespaces", () => {
|
||||
await expect(db.describeNamespace(["foo"])).rejects.toThrow(
|
||||
"Connection is closed",
|
||||
);
|
||||
await expect(db.listNamespaces()).rejects.toThrow("Connection is closed");
|
||||
expect(() => db.listNamespaces()).toThrow("Connection is closed");
|
||||
await expect(db.createNamespace(["foo"])).rejects.toThrow(
|
||||
"Connection is closed",
|
||||
);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { connect } from "../lancedb";
|
||||
import { experimentalFunctionsEnabled } from "../lancedb/native";
|
||||
|
||||
const defaultBuildTest = experimentalFunctionsEnabled() ? it.skip : it;
|
||||
|
||||
defaultBuildTest(
|
||||
"rejects local Functions before mutating the database",
|
||||
async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "lancedb-experimental-"));
|
||||
try {
|
||||
const db = await connect(directory);
|
||||
const table = await db.createTable("source", [{ x: 1 }, { x: 2 }]);
|
||||
const version = await table.version();
|
||||
const operations = [
|
||||
() =>
|
||||
table.addColumns({
|
||||
computed: [{ name: "doubled", valueSql: "x * 2" }],
|
||||
}),
|
||||
() => table.refreshColumn("x"),
|
||||
() => table.refreshColumnAsync("x"),
|
||||
() => db.createMaterializedView("blocked", "source"),
|
||||
() =>
|
||||
db.createMaterializedView("blocked", "source", { withNoData: true }),
|
||||
];
|
||||
for (const operation of operations) {
|
||||
await expect(operation()).rejects.toThrow("experimental-functions");
|
||||
}
|
||||
expect(await table.version()).toBe(version);
|
||||
expect(await db.tableNames()).toEqual(["source"]);
|
||||
await table.addColumns([{ name: "eager", valueSql: "x * 2" }]);
|
||||
expect((await table.query().toArray()).map((row) => row.eager)).toEqual([
|
||||
2, 4,
|
||||
]);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,346 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import * as http from "http";
|
||||
import type { AddressInfo } from "net";
|
||||
import * as tmp from "tmp";
|
||||
|
||||
import { type Table, connect } from "../lancedb";
|
||||
import {
|
||||
Table as ArrowTable,
|
||||
Field,
|
||||
Int64,
|
||||
Schema,
|
||||
Utf8,
|
||||
tableToIPC,
|
||||
} from "../lancedb/arrow";
|
||||
import { Expr, col, func, lit, litBool, litInt } from "../lancedb/expr";
|
||||
|
||||
describe("expr", () => {
|
||||
describe("col", () => {
|
||||
it("returns an Expr instance", () => {
|
||||
const e = col("age");
|
||||
expect(e).toBeInstanceOf(Expr);
|
||||
});
|
||||
|
||||
it("preserves camelCase in toSql()", () => {
|
||||
expect(col("firstName").toSql()).toBe("`firstName`");
|
||||
});
|
||||
|
||||
it("preserves snake_case without quotes", () => {
|
||||
expect(col("first_name").toSql()).toBe("first_name");
|
||||
});
|
||||
|
||||
it("Quotes identifiers with spaces", () => {
|
||||
expect(col("first name").toSql()).toBe("`first name`");
|
||||
});
|
||||
|
||||
it("Quotes identifiers with leading digits", () => {
|
||||
expect(col("2fast").toSql()).toBe("`2fast`");
|
||||
});
|
||||
|
||||
it("Quotes unicode identifiers", () => {
|
||||
expect(col("名前").toSql()).toBe("`名前`");
|
||||
});
|
||||
});
|
||||
|
||||
describe("lit", () => {
|
||||
it("creates a string literal", () => {
|
||||
expect(lit("hello").toSql()).toBe("'hello'");
|
||||
});
|
||||
|
||||
it("creates an integer literal", () => {
|
||||
expect(lit(42).toSql()).toBe("42");
|
||||
});
|
||||
|
||||
it("creates a float literal", () => {
|
||||
expect(lit(3.14).toSql()).toBe("3.14");
|
||||
});
|
||||
});
|
||||
|
||||
describe("numeric literals", () => {
|
||||
it.each([Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER])(
|
||||
"preserves the safe integer boundary %s",
|
||||
(value) => {
|
||||
expect(lit(value).toSql()).toBe(String(value));
|
||||
expect(litInt(value).toSql()).toBe(String(value));
|
||||
},
|
||||
);
|
||||
|
||||
it.each([1e20, -1e20])("preserves the large number %s", (value) => {
|
||||
expect(Number(lit(value).toSql())).toBe(value);
|
||||
expect(col("price").gt(value).toSql()).toBe(
|
||||
col("price").gt(lit(value)).toSql(),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([1.5, 1e20, -1e20, Number.NaN, Number.POSITIVE_INFINITY])(
|
||||
"rejects %s as an explicit integer literal",
|
||||
(value) => expect(() => litInt(value)).toThrow(RangeError),
|
||||
);
|
||||
});
|
||||
|
||||
describe("Expr operators", () => {
|
||||
it("eq", () => {
|
||||
expect(col("x").eq(lit(1)).toSql()).toBe("(x = 1)");
|
||||
});
|
||||
|
||||
it("ne", () => {
|
||||
expect(col("x").ne(lit(1)).toSql()).toBe("(x <> 1)");
|
||||
});
|
||||
|
||||
it("lt", () => {
|
||||
expect(col("age").lt(lit(18)).toSql()).toBe("(age < 18)");
|
||||
});
|
||||
|
||||
it("lte", () => {
|
||||
expect(col("age").lte(lit(18)).toSql()).toBe("(age <= 18)");
|
||||
});
|
||||
|
||||
it("gt", () => {
|
||||
expect(col("age").gt(lit(18)).toSql()).toBe("(age > 18)");
|
||||
});
|
||||
|
||||
it("gte", () => {
|
||||
expect(col("age").gte(lit(18)).toSql()).toBe("(age >= 18)");
|
||||
});
|
||||
|
||||
it("and", () => {
|
||||
const e = col("age")
|
||||
.gt(lit(18))
|
||||
.and(col("status").eq(lit("active")));
|
||||
expect(e.toSql()).toBe("((age > 18) AND (`status` = 'active'))");
|
||||
});
|
||||
|
||||
it("or", () => {
|
||||
const e = col("a")
|
||||
.eq(lit(1))
|
||||
.or(col("b").eq(lit(2)));
|
||||
expect(e.toSql()).toBe("((a = 1) OR (b = 2))");
|
||||
});
|
||||
|
||||
it("not", () => {
|
||||
const e = col("active").eq(litBool(true)).not();
|
||||
expect(e.toSql()).toBe("NOT (active = true)");
|
||||
});
|
||||
|
||||
it("add", () => {
|
||||
expect(col("x").add(lit(1)).toSql()).toBe("(x + 1)");
|
||||
});
|
||||
|
||||
it("sub", () => {
|
||||
expect(col("x").sub(lit(1)).toSql()).toBe("(x - 1)");
|
||||
});
|
||||
|
||||
it("mul", () => {
|
||||
expect(col("price").mul(lit(1.1)).toSql()).toBe("(price * 1.1)");
|
||||
});
|
||||
|
||||
it("div", () => {
|
||||
expect(col("total").div(lit(2)).toSql()).toBe("(total / 2)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Expr string methods", () => {
|
||||
it("lower", () => {
|
||||
expect(col("name").lower().toSql()).toBe("lower(`name`)");
|
||||
});
|
||||
|
||||
it("upper", () => {
|
||||
expect(col("name").upper().toSql()).toBe("upper(`name`)");
|
||||
});
|
||||
|
||||
it("contains", () => {
|
||||
expect(col("text").contains(lit("hello")).toSql()).toBe(
|
||||
"contains(`text`, 'hello')",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("membership and casts", () => {
|
||||
it("accepts scalar list members", () => {
|
||||
expect(col("age").isIn([18, 21]).toSql()).toBe("age IN (18, 21)");
|
||||
});
|
||||
it("casts to an Arrow type", () => {
|
||||
expect(col("age").cast("Int64").toSql()).toBe("arrow_cast(age, 'Int64')");
|
||||
});
|
||||
it("rejects an invalid Arrow type", () => {
|
||||
expect(() => col("age").cast("invalid")).toThrow("Invalid data type");
|
||||
});
|
||||
});
|
||||
|
||||
describe("func", () => {
|
||||
it("lower", () => {
|
||||
expect(func("lower", col("name")).toSql()).toBe("lower(`name`)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("camelCase integration", () => {
|
||||
let db: Awaited<ReturnType<typeof connect>>;
|
||||
let table: Table;
|
||||
let tmpDir: tmp.DirResult;
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = tmp.dirSync({ unsafeCleanup: true });
|
||||
db = await connect(tmpDir.name);
|
||||
table = await db.createTable("test", [
|
||||
{ id: 1, firstName: "Alice", lastName: "Smith" },
|
||||
{ id: 2, firstName: "Bob", lastName: "Jones" },
|
||||
{ id: 3, firstName: "Charlie", lastName: "Brown" },
|
||||
]);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
table.close();
|
||||
db.close();
|
||||
tmpDir.removeCallback();
|
||||
});
|
||||
|
||||
it("filters on camelCase column", async () => {
|
||||
const results = await table
|
||||
.query()
|
||||
.where(col("firstName").eq(lit("Alice")))
|
||||
.toArray();
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].firstName).toBe("Alice");
|
||||
});
|
||||
|
||||
it("filters on multiple camelCase columns", async () => {
|
||||
const results = await table
|
||||
.query()
|
||||
.where(
|
||||
col("firstName")
|
||||
.eq(lit("Bob"))
|
||||
.and(col("lastName").eq(lit("Jones"))),
|
||||
)
|
||||
.toArray();
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].firstName).toBe("Bob");
|
||||
});
|
||||
|
||||
it("preserves an unsafe integer filter threshold", async () => {
|
||||
const prices = await db.createTable("prices", [
|
||||
{ price: 9.5e18 },
|
||||
{ price: 1.1e20 },
|
||||
]);
|
||||
try {
|
||||
const results = await prices
|
||||
.query()
|
||||
.where(col("price").gt(1e20))
|
||||
.toArray();
|
||||
expect(results.map((row) => row.price)).toEqual([1.1e20]);
|
||||
} finally {
|
||||
prices.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("filters with gt on camelCase column", async () => {
|
||||
const results = await table
|
||||
.query()
|
||||
.where(col("id").gt(lit(1)))
|
||||
.toArray();
|
||||
expect(results.length).toBe(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["backslash", "\\"],
|
||||
["quote", "'"],
|
||||
["backslash quote", "\\'"],
|
||||
["OR true payload", "\\') OR true --"],
|
||||
["line comment payload", "\\' -- OR true"],
|
||||
["block comment payload", "\\') /* OR true */ --"],
|
||||
])("filters the exact %s value", async (label, value) => {
|
||||
const escaped = await db.createTable(
|
||||
`escaped_${label.replaceAll(" ", "_")}`,
|
||||
[
|
||||
{ id: 1, tenant: value },
|
||||
{ id: 2, tenant: "different tenant" },
|
||||
],
|
||||
);
|
||||
try {
|
||||
const results = await escaped
|
||||
.query()
|
||||
.where(col("tenant").eq(lit(value)))
|
||||
.toArray();
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].id).toBe(1);
|
||||
expect(results[0].tenant).toBe(value);
|
||||
} finally {
|
||||
escaped.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a quoted expression value to remote as one literal", async () => {
|
||||
const value = "\\') OR true --";
|
||||
const schema = new Schema([
|
||||
new Field("id", new Int64(), false),
|
||||
new Field("tenant", new Utf8(), false),
|
||||
]);
|
||||
const response = Buffer.from(tableToIPC(new ArrowTable(schema), "stream"));
|
||||
let remoteFilter: unknown;
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const path = req.url ?? "";
|
||||
if (path.endsWith("/describe/")) {
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
name: "tenants",
|
||||
version: 1,
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "id", type: { type: "int64" }, nullable: false },
|
||||
{ name: "tenant", type: { type: "string" }, nullable: false },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (path.endsWith("/query/")) {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
req.on("end", () => {
|
||||
remoteFilter = JSON.parse(body).filter;
|
||||
res
|
||||
.writeHead(200, {
|
||||
"Content-Type": "application/vnd.apache.arrow.stream",
|
||||
})
|
||||
.end(response);
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, "127.0.0.1", resolve),
|
||||
);
|
||||
const address = server.address() as AddressInfo;
|
||||
|
||||
try {
|
||||
const db = await connect("db://dev", {
|
||||
apiKey: "fake",
|
||||
hostOverride: `http://127.0.0.1:${address.port}`,
|
||||
});
|
||||
try {
|
||||
const remoteTable = await db.openTable("tenants");
|
||||
await remoteTable
|
||||
.query()
|
||||
.where(col("tenant").eq(lit(value)))
|
||||
.toArrow();
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => {
|
||||
server.closeAllConnections();
|
||||
server.close(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
expect(remoteFilter).toBe("(tenant = '\\'') OR true --')");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const {
|
||||
TransformersEmbeddingFunction,
|
||||
} = require("../../dist/embedding/transformers");
|
||||
const { getRegistry } = require("../../dist/embedding/registry");
|
||||
|
||||
async function main() {
|
||||
const transformers = await import("@huggingface/transformers");
|
||||
// Never fetch a real model, including if a loader mock stops intercepting.
|
||||
transformers.env.allowRemoteModels = false;
|
||||
transformers.env.allowLocalModels = false;
|
||||
const modelCalls = [];
|
||||
const tokenizerCalls = [];
|
||||
const testCase = Number(process.argv[2]);
|
||||
const defaults = "Xenova/all-MiniLM-L6-v2";
|
||||
const cases = [
|
||||
[{}, defaults, defaults],
|
||||
[{ model: "test/model" }, "test/model", "test/model"],
|
||||
[
|
||||
{ model: "test/model", tokenizer: "test/tokenizer" },
|
||||
"test/model",
|
||||
"test/tokenizer",
|
||||
],
|
||||
[
|
||||
{ model: "test/model", tokenizer: "$var:tokenizer" },
|
||||
"test/model",
|
||||
"test/tokenizer",
|
||||
],
|
||||
[
|
||||
{ model: "test/model", tokenizer: "test/tokenizer" },
|
||||
"test/model",
|
||||
"test/tokenizer",
|
||||
],
|
||||
];
|
||||
assert.ok(
|
||||
Number.isInteger(testCase) && testCase >= 0 && testCase < cases.length,
|
||||
);
|
||||
transformers.AutoModel.from_pretrained = async (...args) => {
|
||||
modelCalls.push(args);
|
||||
return {};
|
||||
};
|
||||
transformers.AutoTokenizer.from_pretrained = async (...args) => {
|
||||
tokenizerCalls.push(args);
|
||||
if (testCase === 4) throw new Error("missing tokenizer");
|
||||
return {};
|
||||
};
|
||||
getRegistry().setVar("tokenizer", "test/tokenizer");
|
||||
const [options, model, tokenizer] = cases[testCase];
|
||||
const fn = new TransformersEmbeddingFunction(options);
|
||||
if (testCase === 4) {
|
||||
await assert.rejects(fn.init(), /error loading tokenizer test\/tokenizer/);
|
||||
} else {
|
||||
await fn.init();
|
||||
}
|
||||
assert.deepEqual(modelCalls, [[model, { dtype: "fp32" }]]);
|
||||
assert.deepEqual(tokenizerCalls, [[tokenizer]]);
|
||||
assert.deepEqual(fn.toJSON(), options);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -6,10 +6,13 @@ import * as tmp from "tmp";
|
||||
import { Connection, connect } from "../lancedb";
|
||||
import {
|
||||
DEFINITION_META_KEY,
|
||||
MaterializedView,
|
||||
definitionFromMetadata,
|
||||
} from "../lancedb/materialized_view";
|
||||
import { experimentalFunctionsEnabled } from "../lancedb/native";
|
||||
|
||||
describe("materialized views", () => {
|
||||
const experimentalTest = experimentalFunctionsEnabled() ? it : it.skip;
|
||||
let tmpDir: tmp.DirResult;
|
||||
let db: Connection;
|
||||
|
||||
@@ -69,7 +72,7 @@ describe("materialized views", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("creates, refreshes and queries a view", async () => {
|
||||
experimentalTest("creates, refreshes and queries a view", async () => {
|
||||
const view = await db.createMaterializedView("adults", "people", {
|
||||
select: ["name", ["shout", "upper(name)"]],
|
||||
where: "age >= 18",
|
||||
@@ -81,7 +84,7 @@ describe("materialized views", () => {
|
||||
expect(rows.map((r) => r.shout).sort()).toEqual(["ADA", "GRACE"]);
|
||||
});
|
||||
|
||||
it("round-trips the definition", async () => {
|
||||
experimentalTest("round-trips the definition", async () => {
|
||||
await db.createMaterializedView("adults", "people", {
|
||||
where: "age >= 18",
|
||||
});
|
||||
@@ -92,23 +95,36 @@ describe("materialized views", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("fully refreshes after an append", async () => {
|
||||
const view = await db.createMaterializedView("copy", "people", {
|
||||
withNoData: true,
|
||||
});
|
||||
await view.refresh();
|
||||
experimentalTest.each([false, true])(
|
||||
"fully refreshes after an append (full=%s)",
|
||||
async (full) => {
|
||||
const view = await db.createMaterializedView("copy", "people", {
|
||||
withNoData: true,
|
||||
});
|
||||
await view.refresh();
|
||||
|
||||
const people = await db.openTable("people");
|
||||
await people.add([{ name: "alan", age: 41 }]);
|
||||
const result = await view.refresh();
|
||||
expect(result.mode).toBe("rebuild");
|
||||
expect(Number(result.rowsWritten)).toBe(4);
|
||||
expect(await view.table().countRows()).toBe(4);
|
||||
const people = await db.openTable("people");
|
||||
await people.add([{ name: "alan", age: 41 }]);
|
||||
const result = await view.refresh({ full });
|
||||
expect(result.mode).toBe("rebuild");
|
||||
expect(Number(result.rowsWritten)).toBe(4);
|
||||
expect(await view.table().countRows()).toBe(4);
|
||||
|
||||
expect((await view.refresh()).mode).toBe("rebuild");
|
||||
expect((await view.refresh()).mode).toBe("rebuild");
|
||||
},
|
||||
);
|
||||
|
||||
it("forwards a forced refresh and preserves absent remote metrics", async () => {
|
||||
const view = new MaterializedView(await db.openTable("people"));
|
||||
const remoteResult = { version: 42 };
|
||||
const refresh = jest
|
||||
.spyOn(view.table(), "refreshMaterializedView")
|
||||
.mockResolvedValue(remoteResult);
|
||||
expect(await view.refresh({ full: true })).toEqual(remoteResult);
|
||||
expect(refresh).toHaveBeenCalledWith(undefined, true);
|
||||
});
|
||||
|
||||
it("lists views and rejects non-views", async () => {
|
||||
experimentalTest("lists views and rejects non-views", async () => {
|
||||
await db.createMaterializedView("adults", "people", {
|
||||
where: "age >= 18",
|
||||
});
|
||||
@@ -124,16 +140,20 @@ describe("materialized views", () => {
|
||||
expect(await collect(db.listMaterializedViews())).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns a job when dropping a view asynchronously", async () => {
|
||||
await db.createMaterializedView("adults", "people");
|
||||
experimentalTest(
|
||||
"returns a job when dropping a view asynchronously",
|
||||
async () => {
|
||||
await db.createMaterializedView("adults", "people");
|
||||
|
||||
const job = await db.dropMaterializedViewAsync("adults");
|
||||
expect(job.id).toBeNull();
|
||||
await job.wait();
|
||||
expect(await collect(db.listMaterializedViews())).toEqual([]);
|
||||
});
|
||||
const job = await db.dropMaterializedViewAsync("adults");
|
||||
expect(job.id).toBeNull();
|
||||
expect(job.jobType).toBeNull();
|
||||
await job.wait();
|
||||
expect(await collect(db.listMaterializedViews())).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects an invalid expression at create time", async () => {
|
||||
experimentalTest("rejects an invalid expression at create time", async () => {
|
||||
await expect(
|
||||
db.createMaterializedView("bad", "people", {
|
||||
select: [["x", "missing + 1"]],
|
||||
@@ -148,16 +168,21 @@ describe("materialized views", () => {
|
||||
).rejects.toThrow("non-negative integer");
|
||||
}
|
||||
expect(await collect(db.listMaterializedViews())).toEqual([]);
|
||||
|
||||
const view = await db.createMaterializedView("copy", "people");
|
||||
for (const sourceVersion of [-1, 1.5, Infinity, NaN]) {
|
||||
await expect(view.refresh({ sourceVersion })).rejects.toThrow(
|
||||
"non-negative integer",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("quotes bare select names", async () => {
|
||||
experimentalTest(
|
||||
"rejects invalid source versions before refreshing",
|
||||
async () => {
|
||||
const view = await db.createMaterializedView("copy", "people");
|
||||
for (const sourceVersion of [-1, 1.5, Infinity, NaN]) {
|
||||
await expect(view.refresh({ sourceVersion })).rejects.toThrow(
|
||||
"non-negative integer",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
experimentalTest("quotes bare select names", async () => {
|
||||
await db.createTable("odd_names", [{ "order item": "widget" }]);
|
||||
const view = await db.createMaterializedView("quoted", "odd_names", {
|
||||
select: ["order item"],
|
||||
@@ -167,11 +192,14 @@ describe("materialized views", () => {
|
||||
expect(Number(result.rowsWritten)).toBe(1);
|
||||
});
|
||||
|
||||
it("does not require stable row ids on the source", async () => {
|
||||
await db.createTable("plain", [{ x: 1 }]);
|
||||
const view = await db.createMaterializedView("v", "plain");
|
||||
expect(await view.table().countRows()).toBe(1);
|
||||
});
|
||||
experimentalTest(
|
||||
"does not require stable row ids on the source",
|
||||
async () => {
|
||||
await db.createTable("plain", [{ x: 1 }]);
|
||||
const view = await db.createMaterializedView("v", "plain");
|
||||
expect(await view.table().countRows()).toBe(1);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
async function collect<T>(items: AsyncIterable<T>): Promise<T[]> {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
const {
|
||||
checkNativeBinary,
|
||||
findForbiddenUndefinedSymbols,
|
||||
} = require("../scripts/check-native-symbols.js");
|
||||
|
||||
test("detects the unresolved AVX-512 symbol from broken musl binaries", () => {
|
||||
const output = [
|
||||
" U napi_create_function",
|
||||
" U sum_4bit_dist_table_32bytes_batch_avx512",
|
||||
" U strlen",
|
||||
].join("\n");
|
||||
|
||||
expect(findForbiddenUndefinedSymbols(output)).toEqual([
|
||||
"sum_4bit_dist_table_32bytes_batch_avx512",
|
||||
]);
|
||||
});
|
||||
|
||||
test("accepts native binaries without unresolved internal Lance symbols", () => {
|
||||
const runNm = jest.fn(() => ({
|
||||
status: 0,
|
||||
stdout:
|
||||
" U napi_create_function\n U strlen\n",
|
||||
stderr: "",
|
||||
}));
|
||||
|
||||
expect(() => checkNativeBinary("lancedb.node", runNm)).not.toThrow();
|
||||
expect(runNm).toHaveBeenCalledWith(
|
||||
"nm",
|
||||
["-D", "--undefined-only", "lancedb.node"],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects native binaries with the unresolved AVX-512 symbol", () => {
|
||||
const runNm = jest.fn(() => ({
|
||||
status: 0,
|
||||
stdout: " U sum_4bit_dist_table_32bytes_batch_avx512\n",
|
||||
stderr: "",
|
||||
}));
|
||||
|
||||
expect(() => checkNativeBinary("lancedb.node", runNm)).toThrow(
|
||||
"lancedb.node contains unresolved internal Lance symbols: sum_4bit_dist_table_32bytes_batch_avx512",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import * as tmp from "tmp";
|
||||
import { type Table, blob, connect, isBlobField } from "../lancedb";
|
||||
import {
|
||||
DataType,
|
||||
Field,
|
||||
Int64,
|
||||
List,
|
||||
Schema,
|
||||
Struct,
|
||||
Utf8,
|
||||
} from "../lancedb/arrow";
|
||||
|
||||
describe('nested blobs with blobMode "bytes"', () => {
|
||||
let tmpDir: tmp.DirResult;
|
||||
let table: Table;
|
||||
|
||||
const caption = new Field(
|
||||
"caption",
|
||||
new Utf8(),
|
||||
false,
|
||||
new Map([["label", "caption"]]),
|
||||
);
|
||||
const info = new Field(
|
||||
"info",
|
||||
new Struct([
|
||||
blob("image"),
|
||||
caption,
|
||||
new Field("preview", new Struct([blob("image")]), true),
|
||||
]),
|
||||
true,
|
||||
new Map([["label", "info"]]),
|
||||
);
|
||||
const schema = new Schema(
|
||||
[new Field("id", new Int64(), false), info, blob("cover")],
|
||||
new Map([["source", "nested-blobs"]]),
|
||||
);
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = tmp.dirSync({ unsafeCleanup: true });
|
||||
const db = await connect(tmpDir.name);
|
||||
table = await db.createTable(
|
||||
"nested_blobs",
|
||||
[
|
||||
{
|
||||
id: 1n,
|
||||
info: {
|
||||
image: Buffer.from("hello"),
|
||||
caption: "first",
|
||||
preview: { image: Buffer.from("preview") },
|
||||
},
|
||||
cover: Buffer.from("cover"),
|
||||
},
|
||||
{ id: 2n, info: null, cover: null },
|
||||
{
|
||||
id: 3n,
|
||||
info: { image: null, caption: "third", preview: null },
|
||||
cover: null,
|
||||
},
|
||||
{
|
||||
id: 4n,
|
||||
info: {
|
||||
image: Buffer.alloc(0),
|
||||
caption: "fourth",
|
||||
preview: { image: null },
|
||||
},
|
||||
cover: Buffer.alloc(0),
|
||||
},
|
||||
],
|
||||
{ schema },
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => tmpDir.removeCallback());
|
||||
|
||||
it.each([false, true])(
|
||||
"reads struct leaves across batches (select parent: %s)",
|
||||
async (selectParent) => {
|
||||
const query = table
|
||||
.query()
|
||||
.orderBy({ columnName: "id", ascending: true });
|
||||
if (selectParent) {
|
||||
query.select(["info"]);
|
||||
}
|
||||
const result = await query.toArrow({
|
||||
blobMode: "bytes",
|
||||
maxBatchLength: 1,
|
||||
});
|
||||
expect(result.batches.length).toBeGreaterThan(1);
|
||||
expect(result.schema.fields.map((field) => field.name)).toEqual(
|
||||
selectParent ? ["info"] : ["id", "info", "cover"],
|
||||
);
|
||||
expect(result.schema.metadata).toEqual(schema.metadata);
|
||||
const infoField = result.schema.fields.find(
|
||||
(field) => field.name === "info",
|
||||
)!;
|
||||
expect(infoField.nullable).toBe(true);
|
||||
expect(infoField.metadata).toEqual(info.metadata);
|
||||
const fields = (infoField.type as Struct).children;
|
||||
expect(DataType.isLargeBinary(fields[0].type)).toBe(true);
|
||||
expect(isBlobField(fields[0])).toBe(false);
|
||||
expect(fields[0].metadata.size).toBe(0);
|
||||
expect(fields[1]).toEqual(caption);
|
||||
expect(
|
||||
DataType.isLargeBinary((fields[2].type as Struct).children[0].type),
|
||||
).toBe(true);
|
||||
|
||||
const rows = result.toArray();
|
||||
expect(Buffer.from(rows[0].info.image).toString()).toBe("hello");
|
||||
expect(rows[0].info.caption).toBe("first");
|
||||
expect(Buffer.from(rows[0].info.preview.image).toString()).toBe(
|
||||
"preview",
|
||||
);
|
||||
expect(rows[1].info).toBeNull();
|
||||
expect(rows[2].info.image).toBeNull();
|
||||
expect(rows[2].info.caption).toBe("third");
|
||||
expect(rows[2].info.preview).toBeNull();
|
||||
expect(Buffer.from(rows[3].info.image)).toEqual(Buffer.alloc(0));
|
||||
expect(rows[3].info.preview.image).toBeNull();
|
||||
if (!selectParent) {
|
||||
expect(Buffer.from(rows[0].cover).toString()).toBe("cover");
|
||||
expect(rows[1].cover).toBeNull();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("reads direct leaf and struct aliases", async () => {
|
||||
const rows = await table
|
||||
.query()
|
||||
.orderBy({ columnName: "id", ascending: true })
|
||||
.select({
|
||||
image: "info.image",
|
||||
details: "info",
|
||||
preview: "info.preview",
|
||||
caption: "info.caption",
|
||||
})
|
||||
.toArray({ blobMode: "bytes", maxBatchLength: 1 });
|
||||
expect(Object.keys(rows[0])).toEqual([
|
||||
"image",
|
||||
"details",
|
||||
"preview",
|
||||
"caption",
|
||||
]);
|
||||
expect(Buffer.from(rows[0].image).toString()).toBe("hello");
|
||||
expect(Buffer.from(rows[0].details.image).toString()).toBe("hello");
|
||||
expect(Buffer.from(rows[0].details.preview.image).toString()).toBe(
|
||||
"preview",
|
||||
);
|
||||
expect(Buffer.from(rows[0].preview.image).toString()).toBe("preview");
|
||||
expect(rows[0].caption).toBe("first");
|
||||
expect(rows[1].details).toBeNull();
|
||||
expect(rows[1].image).toBeNull();
|
||||
expect(rows[2].image).toBeNull();
|
||||
expect(Buffer.from(rows[3].image)).toEqual(Buffer.alloc(0));
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"preserves a literal scalar alias matching a nested blob path (reverse: %s)",
|
||||
async (reverse) => {
|
||||
const projection: [string, string][] = [
|
||||
["info", "info"],
|
||||
["info.image", "id"],
|
||||
];
|
||||
if (reverse) {
|
||||
projection.reverse();
|
||||
}
|
||||
const [row] = await table
|
||||
.query()
|
||||
.where("id = 1")
|
||||
.select(new Map(projection))
|
||||
.toArray({ blobMode: "bytes" });
|
||||
expect(row["info.image"]).toBe(1n);
|
||||
expect(Buffer.from(row.info.image).toString()).toBe("hello");
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"materializes every overlapping blob projection (reverse: %s)",
|
||||
async (reverse) => {
|
||||
const columns = ["info.image", "info"];
|
||||
if (reverse) {
|
||||
columns.reverse();
|
||||
}
|
||||
const result = await table
|
||||
.query()
|
||||
.orderBy({ columnName: "id", ascending: true })
|
||||
.select(columns)
|
||||
.toArrow({ blobMode: "bytes", maxBatchLength: 1 });
|
||||
expect(result.schema.fields.map((field) => field.name)).toEqual(columns);
|
||||
expect(DataType.isLargeBinary(result.getChild("info.image")!.type)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
DataType.isLargeBinary(
|
||||
result.getChild("info")!.getChild("image")!.type,
|
||||
),
|
||||
).toBe(true);
|
||||
const rows = result.toArray();
|
||||
expect(Buffer.from(rows[0]["info.image"]).toString()).toBe("hello");
|
||||
expect(Buffer.from(rows[0].info.image).toString()).toBe("hello");
|
||||
expect(rows[0].info.caption).toBe("first");
|
||||
expect(rows[1]["info.image"]).toBeNull();
|
||||
expect(rows[1].info).toBeNull();
|
||||
expect(rows[2]["info.image"]).toBeNull();
|
||||
expect(rows[2].info.image).toBeNull();
|
||||
expect(Buffer.from(rows[3]["info.image"])).toEqual(Buffer.alloc(0));
|
||||
expect(Buffer.from(rows[3].info.image)).toEqual(Buffer.alloc(0));
|
||||
},
|
||||
);
|
||||
|
||||
it("materializes dotted aliases independently of nested fields", async () => {
|
||||
const [row] = await table
|
||||
.query()
|
||||
.where("id = 1")
|
||||
.select({
|
||||
details: "info",
|
||||
"details.image": "info.image",
|
||||
"details.preview": "info.preview",
|
||||
"details.preview.image": "info.preview.image",
|
||||
})
|
||||
.toArray({ blobMode: "bytes" });
|
||||
expect(Buffer.from(row.details.image).toString()).toBe("hello");
|
||||
expect(Buffer.from(row["details.image"]).toString()).toBe("hello");
|
||||
expect(Buffer.from(row.details.preview.image).toString()).toBe("preview");
|
||||
expect(Buffer.from(row["details.preview"].image).toString()).toBe(
|
||||
"preview",
|
||||
);
|
||||
expect(Buffer.from(row["details.preview.image"]).toString()).toBe(
|
||||
"preview",
|
||||
);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"converts the empty result schema (alias: %s)",
|
||||
async (alias) => {
|
||||
const query = table.query().where("id < 0");
|
||||
if (alias) {
|
||||
query.select({ image: "info.image", details: "info" });
|
||||
}
|
||||
const result = await query.toArrow({ blobMode: "bytes" });
|
||||
expect(result.numRows).toBe(0);
|
||||
expect(result.schema.fields.map((field) => field.name)).toEqual(
|
||||
alias ? ["image", "details"] : ["id", "info", "cover"],
|
||||
);
|
||||
const fields = (
|
||||
result.schema.fields.find(
|
||||
(field) => field.name === (alias ? "details" : "info"),
|
||||
)!.type as Struct
|
||||
).children;
|
||||
expect(DataType.isLargeBinary(fields[0].type)).toBe(true);
|
||||
expect(isBlobField(fields[0])).toBe(false);
|
||||
expect(fields[1]).toEqual(caption);
|
||||
expect(
|
||||
DataType.isLargeBinary((fields[2].type as Struct).children[0].type),
|
||||
).toBe(true);
|
||||
if (alias) {
|
||||
expect(DataType.isLargeBinary(result.schema.fields[0].type)).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves requested row IDs and leaves subsequent descriptors intact", async () => {
|
||||
const query = table.query().where("id = 1").select(["info"]);
|
||||
const [bytes] = await query.toArray({ blobMode: "bytes" });
|
||||
expect(Object.keys(bytes)).toEqual(["info"]);
|
||||
const [description] = await query.toArray();
|
||||
expect(Object.keys(description)).toEqual(["info"]);
|
||||
expect(Number(description.info.image.size)).toBe(5);
|
||||
const [withRowId] = await query.withRowId().toArray({ blobMode: "bytes" });
|
||||
expect(typeof withRowId._rowid).toBe("bigint");
|
||||
expect(await table.fetchBlobs("info.image", [withRowId._rowid])).toEqual([
|
||||
Buffer.from(withRowId.info.image),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps descriptors in description mode", async () => {
|
||||
const [description] = await table
|
||||
.query()
|
||||
.where("id = 1")
|
||||
.toArray({ blobMode: "descriptions" });
|
||||
expect(Number(description.info.image.size)).toBe(5);
|
||||
});
|
||||
|
||||
it("keeps list elements as descriptors alongside struct blob bytes", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const table = await db.createTable(
|
||||
"list_blobs",
|
||||
[
|
||||
{
|
||||
info: { image: Buffer.from("hello"), images: [Buffer.from("list")] },
|
||||
},
|
||||
],
|
||||
{
|
||||
schema: new Schema([
|
||||
new Field(
|
||||
"info",
|
||||
new Struct([
|
||||
blob("image"),
|
||||
new Field("images", new List(blob("item")), true),
|
||||
]),
|
||||
true,
|
||||
),
|
||||
]),
|
||||
},
|
||||
);
|
||||
const [bytes] = await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(Buffer.from(bytes.info.image).toString()).toBe("hello");
|
||||
expect(Number(bytes.info.images.get(0).size)).toBe(4);
|
||||
const [row] = await table
|
||||
.query()
|
||||
.select(["info.images"])
|
||||
.toArray({ blobMode: "bytes" });
|
||||
expect(Number(row["info.images"].get(0).size)).toBe(4);
|
||||
expect(Object.keys(row)).toEqual(["info.images"]);
|
||||
const result = await table.query().toArrow({ blobMode: "bytes" });
|
||||
const fields = (result.schema.fields[0].type as Struct).children;
|
||||
const descriptions = await table.query().toArrow();
|
||||
expect(fields[1]).toEqual(
|
||||
(descriptions.schema.fields[0].type as Struct).children[1],
|
||||
);
|
||||
expect(DataType.isStruct((fields[1].type as List).children[0].type)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -538,11 +538,17 @@ describe("IVF search effort", () => {
|
||||
const db = await connect(directory.name);
|
||||
const rows = Array.from({ length: 512 }, (_, id) => ({
|
||||
id,
|
||||
vector: Array.from(
|
||||
{ length: 16 },
|
||||
(_, j) =>
|
||||
(Math.floor(id / 32) === j ? 1 : 0) + Math.sin(id * 17 + j) * 0.001,
|
||||
),
|
||||
// Keep all eight exact neighbors together even if random IVF training
|
||||
// splits the first cluster. This tests effort, not training recall.
|
||||
vector:
|
||||
id < 8
|
||||
? [...vector]
|
||||
: Array.from(
|
||||
{ length: 16 },
|
||||
(_, j) =>
|
||||
(Math.floor(id / 32) === j ? 1 : 0) +
|
||||
Math.sin(id * 17 + j) * 0.001,
|
||||
),
|
||||
}));
|
||||
table = await db.createTable("effort", rows.slice(0, 256));
|
||||
await table.add(rows.slice(256));
|
||||
|
||||
@@ -98,6 +98,57 @@ async function withMockDatabase(
|
||||
}
|
||||
|
||||
describe("remote connection", () => {
|
||||
it.each([
|
||||
{ dataStorageVersion: "2.0" },
|
||||
{ enableV2ManifestPaths: false },
|
||||
{ storageOptions: { bogusOptionXyz: "1" } },
|
||||
])("rejects local create options %j before sending data", async (options) => {
|
||||
const requests: string[] = [];
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
requests.push(req.url ?? "");
|
||||
res.writeHead(200).end();
|
||||
},
|
||||
async (db) => {
|
||||
await expect(
|
||||
db.createTable("test", [{ value: 1 }], {
|
||||
...options,
|
||||
mode: "overwrite",
|
||||
}),
|
||||
).rejects.toThrow(/write_options.*LanceDB Distributed/);
|
||||
await expect(
|
||||
db.createEmptyTable(
|
||||
"test",
|
||||
new Schema([new Field("value", new Int64(), true)]),
|
||||
options,
|
||||
),
|
||||
).rejects.toThrow(/write_options.*LanceDB Distributed/);
|
||||
},
|
||||
);
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([{ indexCacheSize: 5 }, { storageOptions: { x: "y" } }])(
|
||||
"rejects local open options %j before sending a request",
|
||||
async (options) => {
|
||||
const requests: string[] = [];
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
requests.push(req.url ?? "");
|
||||
res.writeHead(200).end();
|
||||
},
|
||||
async (db) => {
|
||||
await expect(
|
||||
db.openTable("test", undefined, options),
|
||||
).rejects.toThrow(
|
||||
/not supported for table access in LanceDB Distributed/,
|
||||
);
|
||||
},
|
||||
);
|
||||
expect(requests).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"normalizes remote blob writes (range target: %s)",
|
||||
async (wide) => {
|
||||
@@ -267,7 +318,7 @@ describe("remote connection", () => {
|
||||
],
|
||||
];
|
||||
for (const [run, operation] of cases) {
|
||||
let message = `LanceDBError: not supported: ${operation} is not supported for remote tables.`;
|
||||
let message = `LanceDBError: not supported: ${operation} is not supported in LanceDB Distributed.`;
|
||||
if (operation === "IVF_HNSW_PQ") {
|
||||
message += " Please use IVF_HNSW_SQ instead.";
|
||||
}
|
||||
@@ -414,7 +465,7 @@ describe("remote connection", () => {
|
||||
table.add([{ id: 1n }], {
|
||||
allowExternalBlobOutsideBases: true,
|
||||
}),
|
||||
).rejects.toThrow("only supported on local tables");
|
||||
).rejects.toThrow("only supported in LanceDB Embedded");
|
||||
expect(insertRequests).toBe(0);
|
||||
|
||||
await expect(table.add([{ id: 2n }])).resolves.toMatchObject({
|
||||
@@ -432,23 +483,6 @@ describe("remote connection", () => {
|
||||
expect(insertRequests).toBe(2);
|
||||
});
|
||||
|
||||
it("lists materialized views through the namespace route", async () => {
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
expect(req.method).toBe("GET");
|
||||
expect(req.url).toBe("/v1/namespace/$/materialized_view/list");
|
||||
res
|
||||
.writeHead(200, { "content-type": "application/json" })
|
||||
.end(JSON.stringify({ views: ["daily_sales"] }));
|
||||
},
|
||||
async (db) => {
|
||||
expect(await collect(db.listMaterializedViews())).toEqual([
|
||||
"daily_sales",
|
||||
]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("creates a view and decodes the schema it resolved to", async () => {
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
@@ -1676,14 +1710,13 @@ async function collect<T>(items: AsyncIterable<T>): Promise<T[]> {
|
||||
}
|
||||
|
||||
describe("lazy resource listings", () => {
|
||||
for (const kind of ["views", "materializedViews", "jobs"] as const) {
|
||||
for (const kind of ["views", "jobs"] as const) {
|
||||
const listing = (
|
||||
db: Connection,
|
||||
options: { pageToken?: string; pageLimit?: number } = {},
|
||||
) => {
|
||||
if (kind === "jobs") return db.listJobs(options);
|
||||
if (kind === "views") return db.listViews(["team"], options);
|
||||
return db.listMaterializedViews(options);
|
||||
return db.listViews(["team"], options);
|
||||
};
|
||||
const page = (names: string[], token?: string) => {
|
||||
const items =
|
||||
@@ -1758,11 +1791,7 @@ describe("lazy resource listings", () => {
|
||||
limit: 2,
|
||||
});
|
||||
} else {
|
||||
expect(url.pathname).toBe(
|
||||
kind === "views"
|
||||
? "/v1/namespace/team/view/list"
|
||||
: "/v1/namespace/$/materialized_view/list",
|
||||
);
|
||||
expect(url.pathname).toBe("/v1/namespace/team/view/list");
|
||||
expect(url.searchParams.get("page_token")).toBe(token);
|
||||
expect(url.searchParams.get("limit")).toBe("2");
|
||||
}
|
||||
|
||||
+260
-54
@@ -47,6 +47,7 @@ import {
|
||||
register,
|
||||
} from "../lancedb/embedding";
|
||||
import { Index } from "../lancedb/indices";
|
||||
import { experimentalFunctionsEnabled } from "../lancedb/native";
|
||||
import {
|
||||
BooleanQuery,
|
||||
Occur,
|
||||
@@ -1716,6 +1717,39 @@ describe("When creating an index", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["IvfPq", Index.ivfPq({ targetPartitionSize: 100 })],
|
||||
["IvfFlat", Index.ivfFlat({ targetPartitionSize: 100 })],
|
||||
["IvfRq", Index.ivfRq({ targetPartitionSize: 100 })],
|
||||
["IvfHnswPq", Index.hnswPq({ targetPartitionSize: 100 })],
|
||||
["IvfHnswSq", Index.hnswSq({ targetPartitionSize: 100 })],
|
||||
])("should create %s with targetPartitionSize", async (indexType, config) => {
|
||||
await tbl.createIndex("vec", { config });
|
||||
|
||||
const indices = await tbl.listIndices();
|
||||
expect(indices).toHaveLength(1);
|
||||
expect(indices[0].indexType).toBe(indexType);
|
||||
expect(
|
||||
(indices[0].indexDetails as Record<string, unknown>)[
|
||||
"target_partition_size"
|
||||
],
|
||||
).toBe(100);
|
||||
});
|
||||
|
||||
it("should prefer numPartitions over targetPartitionSize", async () => {
|
||||
await tbl.createIndex("vec", {
|
||||
config: Index.ivfFlat({ numPartitions: 2, targetPartitionSize: 100 }),
|
||||
});
|
||||
|
||||
// Lance records the target size the partition count implies: 300 rows / 2.
|
||||
const indices = await tbl.listIndices();
|
||||
expect(
|
||||
(indices[0].indexDetails as Record<string, unknown>)[
|
||||
"target_partition_size"
|
||||
],
|
||||
).toBe(150);
|
||||
});
|
||||
|
||||
it("should allow me to replace (or not) an existing index", async () => {
|
||||
await tbl.createIndex("id");
|
||||
// Default is replace=true
|
||||
@@ -3324,51 +3358,64 @@ describe("when dealing with blob columns", () => {
|
||||
).rejects.toThrow(/blobMode must be/);
|
||||
});
|
||||
|
||||
it("reruns the query when the table changes before the version check", async () => {
|
||||
const { table, native, update } = await openVersionedBlobTable();
|
||||
const liveVersion = native.version.bind(native);
|
||||
native.version = async () => {
|
||||
native.version = liveVersion;
|
||||
await update(2n, "new");
|
||||
return liveVersion();
|
||||
};
|
||||
const [row] = await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(row.generation).toBe(2n);
|
||||
expect(Buffer.from(row.image).toString()).toBe("new");
|
||||
});
|
||||
it.each([false, true])(
|
||||
"reruns the query when the table changes before the version check (nested: %s)",
|
||||
async (nested) => {
|
||||
const { table, native, update } = await openVersionedBlobTable(nested);
|
||||
const liveVersion = native.version.bind(native);
|
||||
native.version = async () => {
|
||||
native.version = liveVersion;
|
||||
await update(2n, "new");
|
||||
return liveVersion();
|
||||
};
|
||||
const [row] = await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(row.generation).toBe(2n);
|
||||
expect(Buffer.from(nested ? row.info.image : row.image).toString()).toBe(
|
||||
"new",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("reads bytes from the query's version when a write lands before the fetch", async () => {
|
||||
const { table, native, update } = await openVersionedBlobTable();
|
||||
const liveVersion = native.version.bind(native);
|
||||
native.version = async () => {
|
||||
native.version = liveVersion;
|
||||
const version = await liveVersion();
|
||||
await update(2n, "new");
|
||||
return version;
|
||||
};
|
||||
const [row] = await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(row.generation).toBe(1n);
|
||||
expect(Buffer.from(row.image).toString()).toBe("old");
|
||||
});
|
||||
it.each([false, true])(
|
||||
"reads bytes from the query's version when a write lands before the fetch (nested: %s)",
|
||||
async (nested) => {
|
||||
const { table, native, update } = await openVersionedBlobTable(nested);
|
||||
const liveVersion = native.version.bind(native);
|
||||
native.version = async () => {
|
||||
native.version = liveVersion;
|
||||
const version = await liveVersion();
|
||||
await update(2n, "new");
|
||||
return version;
|
||||
};
|
||||
const [row] = await table.query().toArray({ blobMode: "bytes" });
|
||||
expect(row.generation).toBe(1n);
|
||||
expect(Buffer.from(nested ? row.info.image : row.image).toString()).toBe(
|
||||
"old",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("fails when the table changes during every attempt", async () => {
|
||||
const { table, native, update } = await openVersionedBlobTable();
|
||||
const liveVersion = native.version.bind(native);
|
||||
let generation = 1n;
|
||||
native.version = async () => {
|
||||
generation += 1n;
|
||||
await update(generation, `generation ${generation}`);
|
||||
return liveVersion();
|
||||
};
|
||||
try {
|
||||
await expect(
|
||||
table.query().toArray({ blobMode: "bytes" }),
|
||||
).rejects.toThrow(/changed during each of 3 attempts/);
|
||||
expect(generation).toBe(4n);
|
||||
} finally {
|
||||
native.version = liveVersion;
|
||||
}
|
||||
});
|
||||
it.each([false, true])(
|
||||
"fails when the table changes during every attempt (nested: %s)",
|
||||
async (nested) => {
|
||||
const { table, native, update } = await openVersionedBlobTable(nested);
|
||||
const liveVersion = native.version.bind(native);
|
||||
let generation = 1n;
|
||||
native.version = async () => {
|
||||
generation += 1n;
|
||||
await update(generation, `generation ${generation}`);
|
||||
return liveVersion();
|
||||
};
|
||||
try {
|
||||
await expect(
|
||||
table.query().toArray({ blobMode: "bytes" }),
|
||||
).rejects.toThrow(/changed during each of 3 attempts/);
|
||||
expect(generation).toBe(4n);
|
||||
} finally {
|
||||
native.version = liveVersion;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects fetchBlobs on a non-blob column", async () => {
|
||||
const { table, rowIds } = await openBlobTable();
|
||||
@@ -3395,6 +3442,106 @@ describe("when dealing with blob columns", () => {
|
||||
expect(bytes[0]!.equals(payload)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns bytes for blobs nested in structs", async () => {
|
||||
const { table, alpha, empty } = await openNestedBlobTable();
|
||||
const rows = await table.query().toArray({ blobMode: "bytes" });
|
||||
const byId = new Map(rows.map((row) => [Number(row.id), row]));
|
||||
expect(Buffer.from(byId.get(1)!.info.image)).toEqual(alpha);
|
||||
expect(byId.get(1)!.info.caption).toBe("one");
|
||||
expect(byId.get(2)!.info.image).toBeNull();
|
||||
expect(byId.get(2)!.info.caption).toBe("two");
|
||||
expect(byId.get(3)!.info).toBeNull();
|
||||
expect(Buffer.from(byId.get(4)!.info.image)).toEqual(empty);
|
||||
});
|
||||
|
||||
it("lines up nested rows and bytes across single-row batches", async () => {
|
||||
const { table, alpha, empty } = await openNestedBlobTable();
|
||||
const result = await table
|
||||
.query()
|
||||
.toArrow({ blobMode: "bytes", maxBatchLength: 1 });
|
||||
expect(result.batches.length).toBe(4);
|
||||
const byId = new Map(result.toArray().map((row) => [Number(row.id), row]));
|
||||
expect(Buffer.from(byId.get(1)!.info.image)).toEqual(alpha);
|
||||
expect(byId.get(1)!.info.caption).toBe("one");
|
||||
expect(byId.get(2)!.info.image).toBeNull();
|
||||
expect(byId.get(2)!.info.caption).toBe("two");
|
||||
expect(byId.get(3)!.info).toBeNull();
|
||||
expect(Buffer.from(byId.get(4)!.info.image)).toEqual(empty);
|
||||
});
|
||||
|
||||
it("handles struct fields named like Object prototypes", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const schema = new Schema([
|
||||
new Field("id", new Int64(), true),
|
||||
new Field(
|
||||
"info",
|
||||
new Struct([
|
||||
new Field("constructor", new Struct([blob("image")]), true),
|
||||
]),
|
||||
true,
|
||||
),
|
||||
]);
|
||||
const payload = Buffer.from("proto");
|
||||
const table = await db.createTable(
|
||||
"prototype_named_blobs",
|
||||
[{ id: 1n, info: { constructor: { image: payload } } }],
|
||||
{ schema },
|
||||
);
|
||||
expect(await table.blobColumns()).toEqual(["info.constructor.image"]);
|
||||
const [row] = await table.query().toArray({ blobMode: "bytes" });
|
||||
// Arrow's StructRow shadows the `constructor` property, so read the
|
||||
// field through the JSON form instead of property access.
|
||||
const info = JSON.parse(JSON.stringify(row.info));
|
||||
expect(Buffer.from(Object.values<number>(info.constructor.image))).toEqual(
|
||||
payload,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns nested blob bytes for a struct selection", async () => {
|
||||
const { table, alpha } = await openNestedBlobTable();
|
||||
const [row] = await table
|
||||
.query()
|
||||
.where("id = 1")
|
||||
.select(["info"])
|
||||
.toArray({ blobMode: "bytes" });
|
||||
expect(Object.keys(row)).toEqual(["info"]);
|
||||
expect(Buffer.from(row.info.image)).toEqual(alpha);
|
||||
expect(row.info.caption).toBe("one");
|
||||
});
|
||||
|
||||
it("returns nested blob bytes through aliases", async () => {
|
||||
const { table, alpha } = await openNestedBlobTable();
|
||||
const [row] = await table
|
||||
.query()
|
||||
.where("id = 1")
|
||||
.select(
|
||||
new Map([
|
||||
["picture", "info.image"],
|
||||
["details", "info"],
|
||||
]),
|
||||
)
|
||||
.toArray({ blobMode: "bytes" });
|
||||
expect(Buffer.from(row.picture)).toEqual(alpha);
|
||||
expect(Buffer.from(row.details.image)).toEqual(alpha);
|
||||
expect(row.details.caption).toBe("one");
|
||||
});
|
||||
|
||||
it("returns a nested bytes schema for an empty result", async () => {
|
||||
const { table } = await openNestedBlobTable();
|
||||
const result = await table
|
||||
.query()
|
||||
.where("id > 100")
|
||||
.toArrow({ blobMode: "bytes" });
|
||||
expect(result.numRows).toBe(0);
|
||||
const field = result.schema.fields.find((f) => f.name === "info")!;
|
||||
expect(arrow.DataType.isStruct(field.type)).toBe(true);
|
||||
const image = (field.type as Struct).children.find(
|
||||
(f) => f.name === "image",
|
||||
)!;
|
||||
expect(arrow.DataType.isLargeBinary(image.type)).toBe(true);
|
||||
expect(isBlobField(image)).toBe(false);
|
||||
});
|
||||
|
||||
it("creates list blobs without advertising unfetchable elements", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const schema = new Schema([
|
||||
@@ -3552,18 +3699,28 @@ describe("when dealing with blob columns", () => {
|
||||
).map((value) => (value == null ? null : Number(value.size)));
|
||||
}
|
||||
|
||||
async function openVersionedBlobTable() {
|
||||
async function openVersionedBlobTable(nested = false) {
|
||||
const db = await connect(tmpDir.name, {
|
||||
storageOptions: { newTableEnableStableRowIds: "true" },
|
||||
});
|
||||
const schema = new Schema([
|
||||
new Field("id", new Int64(), false),
|
||||
new Field("generation", new Int64(), true),
|
||||
blob("image"),
|
||||
nested
|
||||
? new Field("info", new Struct([blob("image")]), true)
|
||||
: blob("image"),
|
||||
]);
|
||||
const table = await db.createTable(
|
||||
"versions",
|
||||
[{ id: 1n, generation: 1n, image: Buffer.from("old") }],
|
||||
[
|
||||
{
|
||||
id: 1n,
|
||||
generation: 1n,
|
||||
...(nested
|
||||
? { info: { image: Buffer.from("old") } }
|
||||
: { image: Buffer.from("old") }),
|
||||
},
|
||||
],
|
||||
{ schema },
|
||||
);
|
||||
const native = (
|
||||
@@ -3573,7 +3730,15 @@ describe("when dealing with blob columns", () => {
|
||||
await table
|
||||
.mergeInsert("id")
|
||||
.whenMatchedUpdateAll()
|
||||
.execute([{ id: 1n, generation, image: Buffer.from(image) }]);
|
||||
.execute([
|
||||
{
|
||||
id: 1n,
|
||||
generation,
|
||||
...(nested
|
||||
? { info: { image: Buffer.from(image) } }
|
||||
: { image: Buffer.from(image) }),
|
||||
},
|
||||
]);
|
||||
};
|
||||
return { table, native, update };
|
||||
}
|
||||
@@ -3603,6 +3768,31 @@ describe("when dealing with blob columns", () => {
|
||||
return { table, rowIds, alpha, beta };
|
||||
}
|
||||
|
||||
async function openNestedBlobTable() {
|
||||
const db = await connect(tmpDir.name);
|
||||
const schema = new Schema([
|
||||
new Field("id", new Int64(), true),
|
||||
new Field(
|
||||
"info",
|
||||
new Struct([blob("image"), new Field("caption", new Utf8(), true)]),
|
||||
true,
|
||||
),
|
||||
]);
|
||||
const alpha = Buffer.from("alpha");
|
||||
const empty = Buffer.alloc(0);
|
||||
const table = await db.createTable(
|
||||
"nested_blobs",
|
||||
[{ id: 1n, info: { image: alpha, caption: "one" } }],
|
||||
{ schema },
|
||||
);
|
||||
await table.add([
|
||||
{ id: 2n, info: { image: null, caption: "two" } },
|
||||
{ id: 3n, info: null },
|
||||
{ id: 4n, info: { image: empty, caption: "four" } },
|
||||
]);
|
||||
return { table, alpha, empty };
|
||||
}
|
||||
|
||||
async function openExternalBlobTable() {
|
||||
const db = await connect(path.join(tmpDir.name, "db"));
|
||||
const payload = Buffer.from("external-payload");
|
||||
@@ -3752,6 +3942,21 @@ describe("when optimizing a dataset", () => {
|
||||
expect(stats.prune.oldVersionsRemoved).toBe(2);
|
||||
});
|
||||
|
||||
it("retains tagged versions older than the cleanup cutoff", async () => {
|
||||
await (await table.tags()).create("keep", 1);
|
||||
await table.add([{ id: 3 }]);
|
||||
|
||||
const cutoff = await nextMillisecond();
|
||||
const stats = await table.optimize({ cleanupOlderThan: cutoff });
|
||||
// Versions 2 and 3 are pruned, tagged version 1 is retained
|
||||
expect(stats.prune.oldVersionsRemoved).toBe(2);
|
||||
|
||||
await table.checkout("keep");
|
||||
expect(await table.countRows()).toBe(1);
|
||||
await table.checkoutLatest();
|
||||
expect(await table.countRows()).toBe(3);
|
||||
});
|
||||
|
||||
it("delete unverified", async () => {
|
||||
const version = await table.version();
|
||||
const versionFile = `${tmpDir.name}/${table.name}.lance/_versions/${String(
|
||||
@@ -4364,14 +4569,14 @@ describe.each(arrowVersions)(
|
||||
];
|
||||
const table = await db.createTable("prewarm_data_test", data);
|
||||
|
||||
// prewarmData is only supported on remote tables. We verify the call
|
||||
// prewarmData is only supported in LanceDB Distributed. We verify the call
|
||||
// is wired through napi and surfaces the expected error for both
|
||||
// arg shapes (undefined and string[]).
|
||||
await expect(table.prewarmData()).rejects.toThrow(
|
||||
"prewarm_data is currently only supported on remote tables",
|
||||
"prewarm_data is currently only supported in LanceDB Distributed",
|
||||
);
|
||||
await expect(table.prewarmData(["text"])).rejects.toThrow(
|
||||
"prewarm_data is currently only supported on remote tables",
|
||||
"prewarm_data is currently only supported in LanceDB Distributed",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -5316,13 +5521,14 @@ describe("LSM convergence and stats", () => {
|
||||
});
|
||||
|
||||
describe("computed columns", () => {
|
||||
const experimentalTest = experimentalFunctionsEnabled() ? it : it.skip;
|
||||
let tmpDir: tmp.DirResult;
|
||||
beforeEach(() => {
|
||||
tmpDir = tmp.dirSync({ unsafeCleanup: true });
|
||||
});
|
||||
afterEach(() => tmpDir.removeCallback());
|
||||
|
||||
it("declares a column and fills it on refresh", async () => {
|
||||
experimentalTest("declares a column and fills it on refresh", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const table = await db.createTable("computed", [{ x: 1 }, { x: 2 }]);
|
||||
|
||||
@@ -5343,11 +5549,11 @@ describe("computed columns", () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const table = await db.createTable("errors_local", [{ x: 1 }]);
|
||||
await expect(table.functionErrors()).rejects.toThrow(
|
||||
"LanceDB Cloud and Enterprise",
|
||||
"recorded only in LanceDB Distributed",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns a job handle from refreshColumnAsync", async () => {
|
||||
experimentalTest("returns a job handle from refreshColumnAsync", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const table = await db.createTable("computed_job", [{ x: 1 }, { x: 2 }]);
|
||||
|
||||
@@ -5369,7 +5575,7 @@ describe("computed columns", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("fills rows added since the last refresh", async () => {
|
||||
experimentalTest("fills rows added since the last refresh", async () => {
|
||||
const db = await connect(tmpDir.name);
|
||||
const table = await db.createTable("computed_append", [{ x: 1 }]);
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
describe("Transformers embedding tokenizer selection", () => {
|
||||
// Run init's native ESM import outside Jest's CommonJS sandbox, like a user.
|
||||
// The fixture mocks model loading and forbids local/remote model access.
|
||||
test.each([
|
||||
["default model", 0],
|
||||
["default tokenizer", 1],
|
||||
["custom tokenizer", 2],
|
||||
["tokenizer registry variable", 3],
|
||||
["tokenizer loading error", 4],
|
||||
])("handles %s", (_name, testCase) => {
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
resolve(__dirname, "fixtures", "transformers_tokenizer.cjs"),
|
||||
String(testCase),
|
||||
],
|
||||
{ stdio: "pipe", timeout: 15_000 },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
import { inferSchema } from "./schema";
|
||||
|
||||
export * from "apache-arrow";
|
||||
export type { Data as ArrowData } from "apache-arrow";
|
||||
export type SchemaLike =
|
||||
| Schema
|
||||
| {
|
||||
|
||||
@@ -274,7 +274,7 @@ export class BlobFile {
|
||||
export type BlobReadOptions = {
|
||||
/**
|
||||
* Cancels the read. The call rejects with `signal.reason`, and the native
|
||||
* read stops, including in-flight requests to a remote table.
|
||||
* read stops, including in-flight requests to a LanceDB Distributed table.
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
@@ -82,12 +82,16 @@ export class Catalog {
|
||||
return new LocalConnection(await this.inner.connectDatabase(name));
|
||||
}
|
||||
|
||||
/** Drop an empty database. The server rejects nonempty databases. */
|
||||
/**
|
||||
* Drop a database. A nonempty database is an error unless `cascade` is set,
|
||||
* which drops everything in it first; the name stays taken until the server
|
||||
* finishes cleaning up their storage.
|
||||
*/
|
||||
async dropDatabase(
|
||||
name: string,
|
||||
options: { ignoreMissing?: boolean } = {},
|
||||
options: { ignoreMissing?: boolean; cascade?: boolean } = {},
|
||||
): Promise<void> {
|
||||
await this.inner.dropDatabase(name, options.ignoreMissing);
|
||||
await this.inner.dropDatabase(name, options.ignoreMissing, options.cascade);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+68
-123
@@ -30,16 +30,12 @@ import type {
|
||||
DescribeNamespaceResponse,
|
||||
DropNamespaceResponse,
|
||||
JobInfo,
|
||||
ListNamespacesResponse,
|
||||
ListTablesResponse,
|
||||
} from "./native";
|
||||
import { ViewDescription, viewDescriptionFromNative } from "./view";
|
||||
export type {
|
||||
CreateNamespaceResponse,
|
||||
DescribeNamespaceResponse,
|
||||
DropNamespaceResponse,
|
||||
ListNamespacesResponse,
|
||||
ListTablesResponse,
|
||||
};
|
||||
import { sanitizeTable } from "./sanitize";
|
||||
import { LocalTable, Table } from "./table";
|
||||
@@ -53,8 +49,11 @@ export interface CreateTableOptions {
|
||||
* happen. Any provided data will be ignored.
|
||||
*
|
||||
* If this is set to "overwrite" then any existing table will be replaced.
|
||||
*
|
||||
* If this is set to "exist_ok" then an existing table is opened and any
|
||||
* provided data is ignored.
|
||||
*/
|
||||
mode: "create" | "overwrite";
|
||||
mode: "create" | "overwrite" | "exist_ok";
|
||||
/**
|
||||
* If this is true and the table already exists and the mode is "create"
|
||||
* then no error will be raised.
|
||||
@@ -138,7 +137,7 @@ export interface OpenTableOptions {
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link ListTablesOptions} with {@link Connection.listTables}
|
||||
* @deprecated Use {@link ListingOptions} with {@link Connection.listTables}
|
||||
* instead.
|
||||
*/
|
||||
export interface TableNamesOptions {
|
||||
@@ -154,32 +153,6 @@ export interface TableNamesOptions {
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface ListTablesOptions {
|
||||
/**
|
||||
* Token from a previous response, to resume listing where it left off.
|
||||
*
|
||||
* The token is opaque: it carries whatever the database needs to resume, and
|
||||
* callers should not construct or interpret one.
|
||||
*/
|
||||
pageToken?: string;
|
||||
/**
|
||||
* An upper bound on how many tables to return.
|
||||
* Defaults to 100. Zero returns an empty page without a continuation token.
|
||||
*
|
||||
* A page may hold fewer than this and still not be the last one, so keep
|
||||
* going while the response carries a page token rather than while pages are
|
||||
* full.
|
||||
*/
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface ListNamespacesOptions {
|
||||
/** Token from a previous response for pagination. */
|
||||
pageToken?: string;
|
||||
/** An optional limit to the number of results to return. */
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface CreateNamespaceOptions {
|
||||
/** Creation mode. */
|
||||
mode?: "create" | "exist_ok" | "overwrite";
|
||||
@@ -275,45 +248,18 @@ export abstract class Connection {
|
||||
options?: Partial<TableNamesOptions>,
|
||||
): Promise<string[]>;
|
||||
|
||||
/**
|
||||
* List a page of the tables in this database.
|
||||
*
|
||||
* To retrieve the tables after the page, pass the `pageToken` the response
|
||||
* carries back in. A page can be shorter than `limit` without being the last
|
||||
* one, so walk until a response carries no page token:
|
||||
*
|
||||
/** Lazily list tables in a namespace, requesting 100 per page by default.
|
||||
* @example
|
||||
* ```ts
|
||||
* const names = [];
|
||||
* let pageToken = undefined;
|
||||
* do {
|
||||
* const page = await conn.listTables({ pageToken, limit: 100 });
|
||||
* names.push(...page.tables);
|
||||
* pageToken = page.pageToken;
|
||||
* } while (pageToken);
|
||||
* for await (const name of conn.listTables([], { pageLimit: 20 })) {
|
||||
* console.log(name);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param {Partial<ListTablesOptions>} options - Pagination options
|
||||
* (`pageToken`, `limit`).
|
||||
* @returns {Promise<ListTablesResponse>} A page of table names and an
|
||||
* optional token for the tables after it.
|
||||
*/
|
||||
abstract listTables(
|
||||
options?: Partial<ListTablesOptions>,
|
||||
): Promise<ListTablesResponse>;
|
||||
/**
|
||||
* List a page of the tables in this database.
|
||||
*
|
||||
* @param {string[]} namespacePath - The namespace path to list tables from
|
||||
* (defaults to root namespace)
|
||||
* @param {Partial<ListTablesOptions>} options - Pagination options
|
||||
* (`pageToken`, `limit`).
|
||||
* @returns {Promise<ListTablesResponse>} A page of table names and an
|
||||
* optional token for the tables after it.
|
||||
*/
|
||||
abstract listTables(
|
||||
namespacePath?: string[],
|
||||
options?: Partial<ListTablesOptions>,
|
||||
): Promise<ListTablesResponse>;
|
||||
options?: ListingOptions,
|
||||
): Listing<string>;
|
||||
|
||||
/**
|
||||
* Open a table in the database.
|
||||
@@ -324,6 +270,10 @@ export abstract class Connection {
|
||||
/**
|
||||
* Define a materialized view named `name` over the table `source`.
|
||||
*
|
||||
* LanceDB Embedded creation and refresh require a source build with the
|
||||
* `experimental-functions` Cargo feature, disabled in published packages.
|
||||
* LanceDB Distributed operations do not require this feature.
|
||||
*
|
||||
* The view is populated before creation returns. Set `withNoData` to create
|
||||
* only its definition and empty backing table. The view is a normal table:
|
||||
* it can be queried, indexed and searched, and it appears in `tableNames`.
|
||||
@@ -358,8 +308,8 @@ export abstract class Connection {
|
||||
/**
|
||||
* Drop the materialized view named `name`.
|
||||
*
|
||||
* The view may become unavailable before physical cleanup finishes. Use
|
||||
* {@link dropMaterializedViewAsync} to retain and wait for the cleanup job.
|
||||
* Remote drops wait for the SQL command to remove the catalog binding.
|
||||
* Physical cleanup continues in the background.
|
||||
*
|
||||
* Rejects a table that exists but is not a materialized view.
|
||||
*/
|
||||
@@ -369,8 +319,9 @@ export abstract class Connection {
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Start dropping the materialized view named `name` and return its cleanup
|
||||
* job without waiting for completion.
|
||||
* Start dropping the materialized view named `name` and return its job.
|
||||
* Remote jobs have type `query` and use the SQL query ID as `id`. Waiting
|
||||
* confirms catalog removal; physical cleanup continues in the background.
|
||||
*
|
||||
* Rejects a table that exists but is not a materialized view.
|
||||
*/
|
||||
@@ -539,23 +490,11 @@ export abstract class Connection {
|
||||
namespacePath: string[],
|
||||
): Promise<DescribeNamespaceResponse>;
|
||||
|
||||
/**
|
||||
* List the immediate child namespaces under the given parent.
|
||||
*
|
||||
* Results may be paginated. To retrieve subsequent pages, pass the
|
||||
* `pageToken` returned by a previous call.
|
||||
*
|
||||
* @param {string[]} namespacePath - The parent namespace path. Defaults
|
||||
* to the root namespace if omitted.
|
||||
* @param {Partial<ListNamespacesOptions>} options - Pagination options
|
||||
* (`pageToken`, `limit`).
|
||||
* @returns {Promise<ListNamespacesResponse>} Child namespace names and
|
||||
* an optional token for fetching the next page.
|
||||
*/
|
||||
/** Lazily list immediate child namespaces, 100 per page by default. */
|
||||
abstract listNamespaces(
|
||||
namespacePath?: string[],
|
||||
options?: Partial<ListNamespacesOptions>,
|
||||
): Promise<ListNamespacesResponse>;
|
||||
options?: ListingOptions,
|
||||
): Listing<string>;
|
||||
|
||||
/**
|
||||
* Create a new namespace at the given path.
|
||||
@@ -620,7 +559,7 @@ export abstract class Connection {
|
||||
/**
|
||||
* Rename a table.
|
||||
*
|
||||
* Currently only supported by LanceDB Cloud. Local OSS connections and
|
||||
* Currently only supported in LanceDB Distributed. LanceDB Embedded connections and
|
||||
* namespace-backed connections (via {@link connectNamespace}) reject with
|
||||
* a "not supported" error.
|
||||
*
|
||||
@@ -717,13 +656,13 @@ export class LocalConnection extends Connection {
|
||||
} else {
|
||||
// First argument is options object (backwards compatibility)
|
||||
namespacePath = undefined;
|
||||
tableNamesOptions = namespacePathOrOptions;
|
||||
tableNamesOptions = namespacePathOrOptions ?? options;
|
||||
}
|
||||
|
||||
return this.inner.tableNames(
|
||||
namespacePath ?? [],
|
||||
tableNamesOptions?.startAfter,
|
||||
tableNamesOptions?.limit,
|
||||
normalizeTableListingLimit(tableNamesOptions?.limit),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -818,22 +757,17 @@ export class LocalConnection extends Connection {
|
||||
);
|
||||
}
|
||||
|
||||
async listTables(
|
||||
namespacePathOrOptions?: string[] | Partial<ListTablesOptions>,
|
||||
options?: Partial<ListTablesOptions>,
|
||||
): Promise<ListTablesResponse> {
|
||||
// Detect if first argument is namespacePath array or options object
|
||||
const namespacePath = Array.isArray(namespacePathOrOptions)
|
||||
? namespacePathOrOptions
|
||||
: undefined;
|
||||
const listTablesOptions = Array.isArray(namespacePathOrOptions)
|
||||
? options
|
||||
: namespacePathOrOptions;
|
||||
|
||||
return this.inner.listTables(
|
||||
namespacePath ?? [],
|
||||
listTablesOptions?.pageToken,
|
||||
listTablesOptions?.limit,
|
||||
listTables(
|
||||
namespacePath?: string[],
|
||||
options: ListingOptions = {},
|
||||
): Listing<string> {
|
||||
validateListingOptions(options);
|
||||
return new Listing(
|
||||
this.inner.listTables(
|
||||
namespacePath ?? [],
|
||||
options.pageToken,
|
||||
options.pageLimit,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -890,23 +824,24 @@ export class LocalConnection extends Connection {
|
||||
private getStorageOptions(
|
||||
options?: Partial<CreateTableOptions>,
|
||||
): Record<string, string> | undefined {
|
||||
let storageOptions = options?.storageOptions;
|
||||
if (options?.dataStorageVersion !== undefined) {
|
||||
if (options.storageOptions === undefined) {
|
||||
options.storageOptions = {};
|
||||
}
|
||||
options.storageOptions["newTableDataStorageVersion"] =
|
||||
options.dataStorageVersion;
|
||||
storageOptions = {
|
||||
...storageOptions,
|
||||
newTableDataStorageVersion: options.dataStorageVersion,
|
||||
};
|
||||
}
|
||||
|
||||
if (options?.enableV2ManifestPaths !== undefined) {
|
||||
if (options.storageOptions === undefined) {
|
||||
options.storageOptions = {};
|
||||
}
|
||||
options.storageOptions["newTableEnableV2ManifestPaths"] =
|
||||
options.enableV2ManifestPaths ? "true" : "false";
|
||||
storageOptions = {
|
||||
...storageOptions,
|
||||
newTableEnableV2ManifestPaths: options.enableV2ManifestPaths
|
||||
? "true"
|
||||
: "false",
|
||||
};
|
||||
}
|
||||
|
||||
return cleanseStorageOptions(options?.storageOptions);
|
||||
return cleanseStorageOptions(storageOptions);
|
||||
}
|
||||
|
||||
async createTable(
|
||||
@@ -939,7 +874,7 @@ export class LocalConnection extends Connection {
|
||||
} else {
|
||||
// Third argument is options object (backwards compatibility)
|
||||
namespacePath = undefined;
|
||||
createOptions = namespacePathOrOptions;
|
||||
createOptions = namespacePathOrOptions ?? options;
|
||||
}
|
||||
|
||||
return this._createTableImpl(name, data, namespacePath, createOptions);
|
||||
@@ -986,7 +921,7 @@ export class LocalConnection extends Connection {
|
||||
} else {
|
||||
// Third argument is options object (backwards compatibility)
|
||||
namespacePath = undefined;
|
||||
createOptions = namespacePathOrOptions;
|
||||
createOptions = namespacePathOrOptions ?? options;
|
||||
}
|
||||
|
||||
let mode: string = createOptions?.mode ?? "create";
|
||||
@@ -1035,12 +970,15 @@ export class LocalConnection extends Connection {
|
||||
|
||||
listNamespaces(
|
||||
namespacePath?: string[],
|
||||
options?: Partial<ListNamespacesOptions>,
|
||||
): Promise<ListNamespacesResponse> {
|
||||
return this.inner.listNamespaces(
|
||||
namespacePath ?? [],
|
||||
options?.pageToken,
|
||||
options?.limit,
|
||||
options: ListingOptions = {},
|
||||
): Listing<string> {
|
||||
validateListingOptions(options);
|
||||
return new Listing(
|
||||
this.inner.listNamespaces(
|
||||
namespacePath ?? [],
|
||||
options.pageToken,
|
||||
options.pageLimit,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1103,6 +1041,13 @@ export class LocalConnection extends Connection {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTableListingLimit(limit?: number): number | undefined {
|
||||
validateNonNegativeInteger(limit, "limit");
|
||||
// The native binding takes u32: larger JS numbers otherwise wrap to zero or
|
||||
// a smaller page size. A listing limit is an upper bound, so saturate it.
|
||||
return limit === undefined ? undefined : Math.min(limit, 0xffffffff);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes storage options and makes all the keys snake case.
|
||||
*/
|
||||
|
||||
@@ -38,6 +38,7 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction<
|
||||
#model?: import("@huggingface/transformers").PreTrainedModel;
|
||||
#tokenizer?: import("@huggingface/transformers").PreTrainedTokenizer;
|
||||
#modelName: XenovaTransformerOptions["model"];
|
||||
#tokenizerName: string;
|
||||
#initialized = false;
|
||||
#tokenizerOptions: XenovaTransformerOptions["tokenizerOptions"];
|
||||
#ndims?: number;
|
||||
@@ -58,6 +59,7 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction<
|
||||
|
||||
this.#ndims = options.ndims;
|
||||
this.#modelName = modelName;
|
||||
this.#tokenizerName = options.tokenizer ?? modelName;
|
||||
}
|
||||
|
||||
async init() {
|
||||
@@ -86,11 +88,11 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction<
|
||||
}
|
||||
try {
|
||||
this.#tokenizer = await transformers.AutoTokenizer.from_pretrained(
|
||||
this.#modelName,
|
||||
this.#tokenizerName,
|
||||
);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`error loading tokenizer for ${this.#modelName}. Make sure you are using a wasm compatible model:\nReason: ${e}`,
|
||||
`error loading tokenizer ${this.#tokenizerName}. Make sure you are using a wasm compatible model:\nReason: ${e}`,
|
||||
);
|
||||
}
|
||||
this.#initialized = true;
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import {
|
||||
Expr as NativeExpr,
|
||||
col as nativeCol,
|
||||
func as nativeFunc,
|
||||
lit as nativeLit,
|
||||
litBool as nativeLitBool,
|
||||
litInt as nativeLitInt,
|
||||
} from "./native.js";
|
||||
|
||||
export { Expr as NativeExpr } from "./native";
|
||||
|
||||
/** Values accepted by expression operators. */
|
||||
export type ExprLike = Expr | string | number | boolean;
|
||||
|
||||
function coerce(value: ExprLike): Expr {
|
||||
if (value instanceof Expr) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return lit(value);
|
||||
}
|
||||
if (typeof value === "boolean") {
|
||||
return litBool(value);
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
return lit(value);
|
||||
}
|
||||
throw new TypeError(`Unsupported literal type: ${typeof value}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* A SQL expression backed by the shared LanceDB expression builder.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* table.query().where(col("firstName").eq("Alice")).toArray();
|
||||
* ```
|
||||
*/
|
||||
export class Expr {
|
||||
inner: NativeExpr;
|
||||
|
||||
constructor(inner: NativeExpr) {
|
||||
this.inner = inner;
|
||||
}
|
||||
|
||||
/** Compare for equality. */
|
||||
eq(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.eq(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Compare for inequality. */
|
||||
ne(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.ne(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Compare for less than. */
|
||||
lt(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.lt(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Compare for less than or equal to. */
|
||||
lte(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.lte(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Compare for greater than. */
|
||||
gt(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.gt(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Compare for greater than or equal to. */
|
||||
gte(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.gte(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Combine two predicates with AND. */
|
||||
and(other: Expr): Expr {
|
||||
return new Expr(this.inner.and(other.inner));
|
||||
}
|
||||
|
||||
/** Combine two predicates with OR. */
|
||||
or(other: Expr): Expr {
|
||||
return new Expr(this.inner.or(other.inner));
|
||||
}
|
||||
|
||||
/** Negate this predicate. */
|
||||
not(): Expr {
|
||||
return new Expr(this.inner.not());
|
||||
}
|
||||
|
||||
/** Add a value. */
|
||||
add(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.add(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Subtract a value. */
|
||||
sub(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.sub(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Multiply by a value. */
|
||||
mul(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.mul(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Divide by a value. */
|
||||
div(other: ExprLike): Expr {
|
||||
return new Expr(this.inner.div(coerce(other).inner));
|
||||
}
|
||||
|
||||
/** Convert a string to lowercase. */
|
||||
lower(): Expr {
|
||||
return new Expr(this.inner.lower());
|
||||
}
|
||||
|
||||
/** Convert a string to uppercase. */
|
||||
upper(): Expr {
|
||||
return new Expr(this.inner.upper());
|
||||
}
|
||||
|
||||
/** Test whether a string contains a substring. */
|
||||
contains(substr: ExprLike): Expr {
|
||||
return new Expr(this.inner.contains(coerce(substr).inner));
|
||||
}
|
||||
|
||||
/** Test membership in a list of values. */
|
||||
isIn(values: ExprLike[]): Expr {
|
||||
return new Expr(this.inner.isIn(values.map((v) => coerce(v).inner)));
|
||||
}
|
||||
|
||||
/** Cast to an Arrow data type, such as "Int64". */
|
||||
cast(dataType: string): Expr {
|
||||
return new Expr(this.inner.cast(dataType));
|
||||
}
|
||||
|
||||
/** Serialize with the LanceDB SQL dialect, preserving column case. */
|
||||
toSql(): string {
|
||||
return this.inner.toSql();
|
||||
}
|
||||
}
|
||||
|
||||
/** Reference a column by its exact, case-sensitive name. */
|
||||
export function col(name: string): Expr {
|
||||
return new Expr(nativeCol(name));
|
||||
}
|
||||
|
||||
/** Create a string or numeric literal. Unsafe integers are represented as Float64. */
|
||||
export function lit(value: string | number): Expr {
|
||||
if (typeof value === "string") {
|
||||
return new Expr(nativeLit(value));
|
||||
}
|
||||
if (Number.isSafeInteger(value)) {
|
||||
return new Expr(nativeLitInt(value));
|
||||
}
|
||||
return new Expr(nativeLit(value));
|
||||
}
|
||||
|
||||
/** Create a boolean literal. */
|
||||
export function litBool(value: boolean): Expr {
|
||||
return new Expr(nativeLitBool(value));
|
||||
}
|
||||
|
||||
/** Create an Int64 literal from a JavaScript safe integer. Other numbers throw RangeError. */
|
||||
export function litInt(value: number): Expr {
|
||||
if (!Number.isSafeInteger(value)) {
|
||||
throw new RangeError("Integer literals must be safe integers");
|
||||
}
|
||||
return new Expr(nativeLitInt(value));
|
||||
}
|
||||
|
||||
/** Call a registered SQL function, such as `func("lower", col("firstName"))`. */
|
||||
export function func(name: string, ...args: ExprLike[]): Expr {
|
||||
return new Expr(
|
||||
nativeFunc(
|
||||
name,
|
||||
args.map((a) => coerce(a).inner),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
/**
|
||||
* Header providers for LanceDB remote connections.
|
||||
* Header providers for LanceDB Enterprise connections.
|
||||
*
|
||||
* This module provides a flexible header management framework for LanceDB remote
|
||||
* connections, allowing users to implement custom header strategies for
|
||||
|
||||
+16
-19
@@ -97,13 +97,9 @@ export {
|
||||
Connection,
|
||||
CreateTableOptions,
|
||||
TableNamesOptions,
|
||||
ListTablesOptions,
|
||||
OpenTableOptions,
|
||||
ListNamespacesOptions,
|
||||
CreateNamespaceOptions,
|
||||
DropNamespaceOptions,
|
||||
ListNamespacesResponse,
|
||||
ListTablesResponse,
|
||||
CreateNamespaceResponse,
|
||||
DropNamespaceResponse,
|
||||
DescribeNamespaceResponse,
|
||||
@@ -211,6 +207,8 @@ export {
|
||||
MultiVector,
|
||||
} from "./arrow";
|
||||
export { IntoSql, packBits } from "./util";
|
||||
export { Expr, col, lit, litBool, litInt, func } from "./expr";
|
||||
export type { ExprLike } from "./expr";
|
||||
|
||||
/**
|
||||
* Options for tokenizing a full-text search query without a table index.
|
||||
@@ -290,11 +288,11 @@ export async function tokenize(
|
||||
*
|
||||
* Accepted formats:
|
||||
*
|
||||
* - `/path/to/database` - local database
|
||||
* - `/path/to/database` - database on the local file system
|
||||
* - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
|
||||
* - `db://host:port` - remote database (LanceDB cloud)
|
||||
* - `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database
|
||||
* @param {string} uri - The uri of the database. If the database uri starts
|
||||
* with `db://` then it connects to a remote database.
|
||||
* with `db://` then it connects to LanceDB Enterprise or LanceDB Cloud (legacy).
|
||||
* @see {@link ConnectionOptions} for more details on the URI format.
|
||||
* @param options - The options to use when connecting to the database
|
||||
* @example
|
||||
@@ -335,9 +333,9 @@ export async function connect(
|
||||
*
|
||||
* Accepted formats:
|
||||
*
|
||||
* - `/path/to/database` - local database
|
||||
* - `/path/to/database` - database on the local file system
|
||||
* - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
|
||||
* - `db://host:port` - remote database (LanceDB cloud)
|
||||
* - `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database
|
||||
* @param options - The options to use when connecting to the database
|
||||
* @see {@link ConnectionOptions} for more details on the URI format.
|
||||
* @example
|
||||
@@ -420,10 +418,10 @@ export async function connect(
|
||||
throw new Error("uri is required");
|
||||
}
|
||||
|
||||
finalOptions = (finalOptions as ConnectionOptions) ?? {};
|
||||
(<ConnectionOptions>finalOptions).storageOptions = cleanseStorageOptions(
|
||||
(<ConnectionOptions>finalOptions).storageOptions,
|
||||
);
|
||||
finalOptions = {
|
||||
...finalOptions,
|
||||
storageOptions: cleanseStorageOptions(finalOptions.storageOptions),
|
||||
};
|
||||
|
||||
// Create native header provider if one was provided
|
||||
let nativeProvider: NativeJsHeaderProvider | undefined;
|
||||
@@ -535,7 +533,7 @@ function restConfigToProperties(
|
||||
* Connect to a LanceDB database through a namespace.
|
||||
*
|
||||
* Unlike {@link connect}, which routes by URI scheme (local path vs.
|
||||
* `db://` cloud), `connectNamespace` always returns a namespace-backed
|
||||
* `db://`), `connectNamespace` always returns a namespace-backed
|
||||
* connection. The `implName` selects the namespace implementation:
|
||||
*
|
||||
* - `"dir"` — directory namespace, configured with {@link DirNamespaceConfig}.
|
||||
@@ -630,11 +628,10 @@ export async function connectNamespace(
|
||||
properties = configOrProperties as Record<string, string>;
|
||||
}
|
||||
|
||||
const finalOptions: ConnectNamespaceOptions = (options ??
|
||||
{}) as ConnectNamespaceOptions;
|
||||
finalOptions.storageOptions = cleanseStorageOptions(
|
||||
finalOptions.storageOptions,
|
||||
);
|
||||
const finalOptions: ConnectNamespaceOptions = {
|
||||
...options,
|
||||
storageOptions: cleanseStorageOptions(options?.storageOptions),
|
||||
};
|
||||
|
||||
const nativeConn = await LanceDbConnection.newWithNamespace(
|
||||
implName,
|
||||
|
||||
@@ -11,8 +11,9 @@ export interface IvfPqOptions {
|
||||
* The number of IVF partitions to create.
|
||||
*
|
||||
* This value should generally scale with the number of rows in the dataset.
|
||||
* By default the number of partitions is the square root of the number of
|
||||
* rows.
|
||||
* When set, this takes precedence over `targetPartitionSize`. When omitted,
|
||||
* the partition count is derived from `targetPartitionSize`, which defaults
|
||||
* to 8192 rows for this index type.
|
||||
*
|
||||
* If this value is too large then the first part of the search (picking the
|
||||
* right partition) will be slow. If this value is too small then the second
|
||||
@@ -20,6 +21,21 @@ export interface IvfPqOptions {
|
||||
*/
|
||||
numPartitions?: number;
|
||||
|
||||
/**
|
||||
* The target number of rows in each IVF partition.
|
||||
*
|
||||
* This is an alternative to `numPartitions`. When it is set and
|
||||
* `numPartitions` is not, the number of partitions is derived by dividing
|
||||
* the number of rows by this value. When both are set, `numPartitions` is
|
||||
* used and this value is ignored. When neither is set, the target is
|
||||
* 8192 rows.
|
||||
*
|
||||
* Larger partitions mean fewer of them, which makes the first part of the
|
||||
* search (picking the right partitions) faster and the second part
|
||||
* (searching within a partition) slower.
|
||||
*/
|
||||
targetPartitionSize?: number;
|
||||
|
||||
/**
|
||||
* Number of sub-vectors of PQ.
|
||||
*
|
||||
@@ -117,8 +133,9 @@ export interface IvfRqOptions {
|
||||
* The number of IVF partitions to create.
|
||||
*
|
||||
* This value should generally scale with the number of rows in the dataset.
|
||||
* By default the number of partitions is the square root of the number of
|
||||
* rows.
|
||||
* When set, this takes precedence over `targetPartitionSize`. When omitted,
|
||||
* the partition count is derived from `targetPartitionSize`, which defaults
|
||||
* to 4096 rows for this index type.
|
||||
*
|
||||
* If this value is too large then the first part of the search (picking the
|
||||
* right partition) will be slow. If this value is too small then the second
|
||||
@@ -126,12 +143,28 @@ export interface IvfRqOptions {
|
||||
*/
|
||||
numPartitions?: number;
|
||||
|
||||
/**
|
||||
* The target number of rows in each IVF partition.
|
||||
*
|
||||
* This is an alternative to `numPartitions`. When it is set and
|
||||
* `numPartitions` is not, the number of partitions is derived by dividing
|
||||
* the number of rows by this value. When both are set, `numPartitions` is
|
||||
* used and this value is ignored. When neither is set, the target is
|
||||
* 4096 rows.
|
||||
*
|
||||
* Larger partitions mean fewer of them, which makes the first part of the
|
||||
* search (picking the right partitions) faster and the second part
|
||||
* (searching within a partition) slower.
|
||||
*/
|
||||
targetPartitionSize?: number;
|
||||
|
||||
/**
|
||||
* Number of bits per dimension for residual quantization.
|
||||
*
|
||||
* This value controls how much each residual component is compressed. The more
|
||||
* bits, the more accurate the index will be but the slower search. Typical values
|
||||
* are small integers; the default is 1 bit per dimension.
|
||||
* are small integers. If unset, uses Lance's default (currently 5 bits per
|
||||
* dimension). Set to 1 for maximum compression.
|
||||
*/
|
||||
numBits?: number;
|
||||
|
||||
@@ -214,6 +247,8 @@ export interface HnswPqOptions {
|
||||
/**
|
||||
* The number of IVF partitions to create.
|
||||
*
|
||||
* When set, this takes precedence over `targetPartitionSize`.
|
||||
*
|
||||
* For HNSW, we recommend a small number of partitions. Setting this to 1 works
|
||||
* well for most tables. For very large tables, training just one HNSW graph
|
||||
* will require too much memory. Each partition becomes its own HNSW graph, so
|
||||
@@ -222,6 +257,21 @@ export interface HnswPqOptions {
|
||||
*/
|
||||
numPartitions?: number;
|
||||
|
||||
/**
|
||||
* The target number of rows in each IVF partition.
|
||||
*
|
||||
* This is an alternative to `numPartitions`. When it is set and
|
||||
* `numPartitions` is not, the number of partitions is derived by dividing
|
||||
* the number of rows by this value. When both are set, `numPartitions` is
|
||||
* used and this value is ignored. When neither is set, the target is
|
||||
* 1,048,576 rows.
|
||||
*
|
||||
* Larger partitions mean fewer of them, which makes the first part of the
|
||||
* search (picking the right partitions) faster and the second part
|
||||
* (searching within a partition) slower.
|
||||
*/
|
||||
targetPartitionSize?: number;
|
||||
|
||||
/**
|
||||
* Number of sub-vectors of PQ.
|
||||
*
|
||||
@@ -330,6 +380,8 @@ export interface HnswSqOptions {
|
||||
/**
|
||||
* The number of IVF partitions to create.
|
||||
*
|
||||
* When set, this takes precedence over `targetPartitionSize`.
|
||||
*
|
||||
* For HNSW, we recommend a small number of partitions. Setting this to 1 works
|
||||
* well for most tables. For very large tables, training just one HNSW graph
|
||||
* will require too much memory. Each partition becomes its own HNSW graph, so
|
||||
@@ -338,6 +390,21 @@ export interface HnswSqOptions {
|
||||
*/
|
||||
numPartitions?: number;
|
||||
|
||||
/**
|
||||
* The target number of rows in each IVF partition.
|
||||
*
|
||||
* This is an alternative to `numPartitions`. When it is set and
|
||||
* `numPartitions` is not, the number of partitions is derived by dividing
|
||||
* the number of rows by this value. When both are set, `numPartitions` is
|
||||
* used and this value is ignored. When neither is set, the target is
|
||||
* 1,048,576 rows.
|
||||
*
|
||||
* Larger partitions mean fewer of them, which makes the first part of the
|
||||
* search (picking the right partitions) faster and the second part
|
||||
* (searching within a partition) slower.
|
||||
*/
|
||||
targetPartitionSize?: number;
|
||||
|
||||
/**
|
||||
* Max iterations to train kmeans.
|
||||
*
|
||||
@@ -406,8 +473,9 @@ export interface IvfFlatOptions {
|
||||
* The number of IVF partitions to create.
|
||||
*
|
||||
* This value should generally scale with the number of rows in the dataset.
|
||||
* By default the number of partitions is the square root of the number of
|
||||
* rows.
|
||||
* When set, this takes precedence over `targetPartitionSize`. When omitted,
|
||||
* the partition count is derived from `targetPartitionSize`, which defaults
|
||||
* to 4096 rows for this index type.
|
||||
*
|
||||
* If this value is too large then the first part of the search (picking the
|
||||
* right partition) will be slow. If this value is too small then the second
|
||||
@@ -415,6 +483,21 @@ export interface IvfFlatOptions {
|
||||
*/
|
||||
numPartitions?: number;
|
||||
|
||||
/**
|
||||
* The target number of rows in each IVF partition.
|
||||
*
|
||||
* This is an alternative to `numPartitions`. When it is set and
|
||||
* `numPartitions` is not, the number of partitions is derived by dividing
|
||||
* the number of rows by this value. When both are set, `numPartitions` is
|
||||
* used and this value is ignored. When neither is set, the target is
|
||||
* 4096 rows.
|
||||
*
|
||||
* Larger partitions mean fewer of them, which makes the first part of the
|
||||
* search (picking the right partitions) faster and the second part
|
||||
* (searching within a partition) slower.
|
||||
*/
|
||||
targetPartitionSize?: number;
|
||||
|
||||
/**
|
||||
* Distance type to use to build the index.
|
||||
*
|
||||
@@ -632,6 +715,7 @@ export class Index {
|
||||
options?.numBits,
|
||||
options?.maxIterations,
|
||||
options?.sampleRate,
|
||||
options?.targetPartitionSize,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -660,6 +744,7 @@ export class Index {
|
||||
options?.numBits,
|
||||
options?.maxIterations,
|
||||
options?.sampleRate,
|
||||
options?.targetPartitionSize,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -687,6 +772,7 @@ export class Index {
|
||||
options?.numPartitions,
|
||||
options?.maxIterations,
|
||||
options?.sampleRate,
|
||||
options?.targetPartitionSize,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -797,6 +883,7 @@ export class Index {
|
||||
options?.sampleRate,
|
||||
options?.m,
|
||||
options?.efConstruction,
|
||||
options?.targetPartitionSize,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -819,6 +906,7 @@ export class Index {
|
||||
options?.sampleRate,
|
||||
options?.m,
|
||||
options?.efConstruction,
|
||||
options?.targetPartitionSize,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ export interface JobEventsOptions {
|
||||
* - {@link Job.refresh} and {@link Job.status} fetch the whole record.
|
||||
* - {@link Job.wait} records the terminal state it establishes, but not the
|
||||
* rest of the record.
|
||||
* - Everything is null until one of those runs.
|
||||
* - Registry details are null until one of those runs. Query handles report
|
||||
* jobType "query" immediately.
|
||||
*
|
||||
* @hideconstructor
|
||||
*/
|
||||
@@ -38,8 +39,10 @@ export class Job {
|
||||
/**
|
||||
* Identifies the operation on the server that is running it.
|
||||
*
|
||||
* Operations that run in this process have no server id. The value is
|
||||
* opaque: parsing it or storing it to resume the job later is not supported.
|
||||
* Registry handles expose a registry job ID; query handles expose a
|
||||
* connection-scoped SQL query UUID string. Local handles have no ID.
|
||||
* Query handles report jobType "query". Their IDs are not registry IDs or
|
||||
* durable resume tokens.
|
||||
*/
|
||||
get id(): string | null {
|
||||
return this.inner.id ?? null;
|
||||
@@ -51,8 +54,8 @@ export class Job {
|
||||
}
|
||||
|
||||
/**
|
||||
* The job's type, as the server names it. Null for an in-process job, which
|
||||
* has no server-side record.
|
||||
* "query" immediately for SQL-backed handles; otherwise the cached
|
||||
* server-reported job type. Null for in-process handles.
|
||||
*/
|
||||
get jobType(): string | null {
|
||||
return this.inner.jobType ?? null;
|
||||
|
||||
@@ -186,15 +186,22 @@ export class MaterializedView {
|
||||
|
||||
/**
|
||||
* Recompute the view from its source.
|
||||
* Local refresh requires a source build with `experimental-functions`.
|
||||
*
|
||||
* Every refresh rebuilds the complete view. For local views,
|
||||
* `sourceVersion` refreshes to that source version instead of the latest;
|
||||
* remote SQL refreshes do not support source-version pinning.
|
||||
* `full: true` forces a remote rebuild; otherwise the server chooses the
|
||||
* refresh mode. Local views always rebuild, and `sourceVersion` selects a
|
||||
* source version instead of the latest. Remote SQL refreshes do not support
|
||||
* source-version pinning. Their results leave `mode`, `rowsWritten`, and
|
||||
* `sourceVersion` absent because the SQL job adapter does not expose these metrics.
|
||||
*/
|
||||
async refresh(options?: {
|
||||
full?: boolean;
|
||||
sourceVersion?: number;
|
||||
}): Promise<RefreshMaterializedViewResult> {
|
||||
validateNonNegativeInteger(options?.sourceVersion, "sourceVersion");
|
||||
return await this.inner.refreshMaterializedView(options?.sourceVersion);
|
||||
return await this.inner.refreshMaterializedView(
|
||||
options?.sourceVersion,
|
||||
options?.full,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+123
-40
@@ -1,8 +1,10 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import type { Data as ArrowData } from "apache-arrow";
|
||||
import {
|
||||
Table as ArrowTable,
|
||||
DataType,
|
||||
Field,
|
||||
type IntoVector,
|
||||
LargeBinary,
|
||||
@@ -12,10 +14,10 @@ import {
|
||||
extractVectorBuffer,
|
||||
fromBufferToRecordBatch,
|
||||
fromRecordBatchToBuffer,
|
||||
makeData,
|
||||
tableFromIPC,
|
||||
vectorFromArray,
|
||||
} from "./arrow";
|
||||
import { Expr } from "./expr";
|
||||
import { type IvfPqOptions } from "./indices";
|
||||
import {
|
||||
JsFullTextQuery,
|
||||
@@ -66,20 +68,42 @@ export interface QueryBlobContext {
|
||||
|
||||
const BLOB_BYTES_ATTEMPTS = 3;
|
||||
|
||||
interface BlobSource {
|
||||
// Output names are literal: an alias containing dots is still one field.
|
||||
output: string;
|
||||
path: string[];
|
||||
source: string;
|
||||
}
|
||||
|
||||
function blobSources(
|
||||
blobColumns: string[],
|
||||
projection: [string, string][] | undefined,
|
||||
): Map<string, string> {
|
||||
const columns = new Set(blobColumns);
|
||||
const pairs =
|
||||
projection ??
|
||||
blobColumns.map((column): [string, string] => [column, column]);
|
||||
return new Map(pairs.filter(([, source]) => columns.has(source)));
|
||||
): BlobSource[] {
|
||||
if (projection === undefined) {
|
||||
return blobColumns.map((source) => {
|
||||
const [output, ...path] = source.split(".");
|
||||
return { output, path, source };
|
||||
});
|
||||
}
|
||||
const sources: BlobSource[] = [];
|
||||
for (const [output, source] of projection) {
|
||||
for (const column of blobColumns) {
|
||||
if (column === source || column.startsWith(`${source}.`)) {
|
||||
sources.push({
|
||||
output,
|
||||
path:
|
||||
column === source ? [] : column.slice(source.length + 1).split("."),
|
||||
source: column,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
async function readBlobBytes(
|
||||
table: ArrowTable,
|
||||
sources: Map<string, string>,
|
||||
sources: BlobSource[],
|
||||
snapshot: NativeTable,
|
||||
dropRowId: boolean,
|
||||
): Promise<ArrowTable> {
|
||||
@@ -91,18 +115,25 @@ async function readBlobBytes(
|
||||
rowIdColumn === null
|
||||
? []
|
||||
: Array.from(rowIdColumn.toArray() as BigUint64Array);
|
||||
const replacements = new Map<number, (Buffer | null)[]>();
|
||||
for (const [output, source] of sources) {
|
||||
const index = table.schema.fields.findIndex(
|
||||
(field) => field.name === output,
|
||||
);
|
||||
if (index < 0) {
|
||||
const outputFields = new Map(
|
||||
table.schema.fields.map((field) => [field.name, field]),
|
||||
);
|
||||
const replacements = new Map<Field, (Buffer | null)[]>();
|
||||
for (const { output, path, source } of sources) {
|
||||
let field = outputFields.get(output);
|
||||
for (const name of path) {
|
||||
field =
|
||||
field !== undefined && DataType.isStruct(field.type)
|
||||
? field.type.children.find((child) => child.name === name)
|
||||
: undefined;
|
||||
}
|
||||
if (field === undefined) {
|
||||
continue;
|
||||
}
|
||||
const values =
|
||||
rowIds.length === 0 ? [] : await snapshot.fetchBlobs(source, rowIds);
|
||||
replacements.set(
|
||||
index,
|
||||
field,
|
||||
values.map((value) => value ?? null),
|
||||
);
|
||||
}
|
||||
@@ -117,37 +148,76 @@ async function readBlobBytes(
|
||||
);
|
||||
}
|
||||
|
||||
// A fresh field, not a clone: the descriptor field's metadata must not follow
|
||||
// the bytes.
|
||||
function withBinaryColumns(
|
||||
table: ArrowTable,
|
||||
replacements: Map<number, (Buffer | null)[]>,
|
||||
replacements: Map<Field, (Buffer | null)[]>,
|
||||
): ArrowTable {
|
||||
if (replacements.size === 0) {
|
||||
return table;
|
||||
}
|
||||
const fields = table.schema.fields.map((field, index) =>
|
||||
replacements.has(index)
|
||||
? new Field(field.name, new LargeBinary(), true)
|
||||
: field,
|
||||
);
|
||||
const replaceField = (field: Field): Field => {
|
||||
if (replacements.has(field)) {
|
||||
// The descriptor's extension and encoding metadata must not follow bytes.
|
||||
return new Field(field.name, new LargeBinary(), true);
|
||||
}
|
||||
if (DataType.isStruct(field.type)) {
|
||||
const children = field.type.children.map(replaceField);
|
||||
if (children.some((child, i) => child !== field.type.children[i])) {
|
||||
return field.clone({ type: new Struct(children) });
|
||||
}
|
||||
}
|
||||
return field;
|
||||
};
|
||||
const fields = table.schema.fields.map(replaceField);
|
||||
const schema = new Schema(fields, table.schema.metadata);
|
||||
let offset = 0;
|
||||
const batches = table.batches.map((batch) => {
|
||||
const children = batch.data.children.map((child, index) => {
|
||||
const values = replacements.get(index);
|
||||
if (values === undefined) {
|
||||
return child;
|
||||
const replaceData = (
|
||||
data: ArrowData,
|
||||
field: Field,
|
||||
updated: Field,
|
||||
): ArrowData => {
|
||||
if (field === updated) {
|
||||
return data;
|
||||
}
|
||||
return vectorFromArray(
|
||||
values.slice(offset, offset + batch.numRows),
|
||||
new LargeBinary(),
|
||||
).data[0];
|
||||
});
|
||||
const values = replacements.get(field);
|
||||
if (values !== undefined) {
|
||||
return vectorFromArray(
|
||||
values.slice(offset, offset + batch.numRows),
|
||||
new LargeBinary(),
|
||||
).data[0];
|
||||
}
|
||||
const children = data.children.map((child, index) =>
|
||||
replaceData(
|
||||
child,
|
||||
field.type.children[index],
|
||||
updated.type.children[index],
|
||||
),
|
||||
);
|
||||
// Keep the struct's validity bitmap and offset, including null parents.
|
||||
return data.clone(
|
||||
updated.type,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
children,
|
||||
);
|
||||
};
|
||||
const children = batch.data.children.map((child, index) =>
|
||||
replaceData(child, table.schema.fields[index], fields[index]),
|
||||
);
|
||||
offset += batch.numRows;
|
||||
return new RecordBatch(
|
||||
schema,
|
||||
makeData({ type: new Struct(fields), length: batch.numRows, children }),
|
||||
batch.data.clone(
|
||||
new Struct(fields),
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
children,
|
||||
),
|
||||
);
|
||||
});
|
||||
return new ArrowTable(schema, batches);
|
||||
@@ -175,12 +245,14 @@ export interface QueryExecutionOptions {
|
||||
*
|
||||
* - `"descriptions"` (default): each blob is a descriptor. Read the bytes
|
||||
* with {@link Table.fetchBlobs} or {@link Table.fetchBlobFiles}.
|
||||
* - `"bytes"`: each top-level blob column holds the blob bytes as
|
||||
* `LargeBinary`. The query also reads `_rowid` to fetch the bytes, and
|
||||
* - `"bytes"`: each blob column, including blobs nested in structs, holds
|
||||
* the bytes as `LargeBinary`. The query also reads `_rowid` to fetch them, and
|
||||
* leaves it out of the result unless {@link QueryBase.withRowId} was
|
||||
* called. All the bytes are held in memory.
|
||||
*
|
||||
* Blobs nested in a struct or a list keep their descriptors.
|
||||
* Selecting a parent struct or directly aliasing a blob or struct also returns
|
||||
* bytes. Blobs inside lists keep their descriptors. Arbitrary projection
|
||||
* expressions are not materialized as bytes.
|
||||
*
|
||||
* The rows and the bytes come from the same table version. If the table
|
||||
* changes while the query runs, the query runs again, up to three times.
|
||||
@@ -433,7 +505,7 @@ export class QueryBase<
|
||||
await snapshot.blobColumns(),
|
||||
context.projection,
|
||||
);
|
||||
if (sources.size === 0) {
|
||||
if (sources.length === 0) {
|
||||
return this.collect(options, false);
|
||||
}
|
||||
const addRowId = !context.withRowId;
|
||||
@@ -578,11 +650,16 @@ export class StandardQueryBase<
|
||||
/**
|
||||
* A filter statement to be applied to this query.
|
||||
*
|
||||
* The filter should be supplied as an SQL query string. For example:
|
||||
* The filter may be an SQL query string or an expression built with `col`,
|
||||
* which preserves case-sensitive column names. For example:
|
||||
* @example
|
||||
* x > 10
|
||||
* y > 0 AND y < 100
|
||||
* x > 5 OR y = 'test'
|
||||
* @example
|
||||
* ```ts
|
||||
* table.query().where(col("firstName").eq("Alice"));
|
||||
* ```
|
||||
*
|
||||
* Filtering performance can often be improved by creating a scalar index
|
||||
* on the filter column(s).
|
||||
@@ -590,8 +667,14 @@ export class StandardQueryBase<
|
||||
* Calling this multiple times combines the filters with a logical AND rather
|
||||
* than replacing the previous filter.
|
||||
*/
|
||||
where(predicate: string): this {
|
||||
this.doCall((inner: NativeQueryType) => inner.onlyIf(predicate));
|
||||
where(predicate: string | Expr): this {
|
||||
this.doCall((inner: NativeQueryType) => {
|
||||
if (predicate instanceof Expr) {
|
||||
inner.onlyIf(predicate.toSql());
|
||||
} else {
|
||||
inner.onlyIf(predicate);
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
|
||||
+31
-14
@@ -128,8 +128,8 @@ export interface AddDataOptions {
|
||||
/**
|
||||
* Whether blob URIs outside registered external bases may be written.
|
||||
*
|
||||
* Defaults to `false`. This option is supported only for local/native
|
||||
* tables; remote tables return an error when it is enabled. An enabled write
|
||||
* Defaults to `false`. This option is supported only in LanceDB Embedded;
|
||||
* LanceDB Distributed returns an error when it is enabled. An enabled write
|
||||
* stores the absolute URI reference without registering a base or copying
|
||||
* the external object into the database. The object must remain accessible
|
||||
* when the blob is read later.
|
||||
@@ -381,6 +381,11 @@ export abstract class Table {
|
||||
* }),
|
||||
* });
|
||||
* @example
|
||||
* // Or size the partitions by row count instead of choosing how many.
|
||||
* await table.createIndex("vector", {
|
||||
* config: lancedb.Index.ivfPq({ targetPartitionSize: 4096 }),
|
||||
* });
|
||||
* @example
|
||||
* // Or create a Scalar index
|
||||
* await table.createIndex("my_float_col");
|
||||
*/
|
||||
@@ -438,7 +443,7 @@ export abstract class Table {
|
||||
* Large columns (e.g. high-dimensional vectors or binary data) may not be
|
||||
* practical to prewarm.
|
||||
*
|
||||
* This feature is currently only supported on remote tables.
|
||||
* This feature is currently only supported in LanceDB Distributed.
|
||||
*/
|
||||
abstract prewarmData(columns?: string[]): Promise<void>;
|
||||
|
||||
@@ -594,6 +599,10 @@ export abstract class Table {
|
||||
/**
|
||||
* Add new columns with defined values.
|
||||
*
|
||||
* LanceDB Embedded computed-column declaration and refresh require a source
|
||||
* build with the `experimental-functions` Cargo feature. Published packages
|
||||
* disable it; LanceDB Distributed operations remain available.
|
||||
*
|
||||
* The `{ computed }` form stores the expression rather than evaluating it
|
||||
* now: the column is committed with no values, and rows get them from
|
||||
* {@link Table#refreshColumn}. Declaring one therefore costs the same on a
|
||||
@@ -604,7 +613,7 @@ export abstract class Table {
|
||||
* declaration reads a column, that column cannot be renamed, retyped or
|
||||
* dropped.
|
||||
*
|
||||
* On LanceDB Cloud and Enterprise the expression is planned by the
|
||||
* In LanceDB Distributed the expression is planned by the
|
||||
* server, and the refresh runs as a server job -- see
|
||||
* {@link Table#refreshColumnAsync}.
|
||||
* @param {AddColumnsSql[] | Field | Field[] | Schema} newColumnTransforms Either:
|
||||
@@ -632,11 +641,12 @@ export abstract class Table {
|
||||
|
||||
/**
|
||||
* Fill the rows of a computed column that hold no value yet.
|
||||
* Local refresh requires a source build with `experimental-functions`.
|
||||
*
|
||||
* Rows appended since the last refresh are filled by the next one, and
|
||||
* rows whose inputs changed since they were computed are recomputed;
|
||||
* everything else is left as it is. Local tables only: a remote refresh
|
||||
* runs as a server job, through {@link Table#refreshColumnAsync}.
|
||||
* everything else is left as it is. LanceDB Embedded only: in LanceDB
|
||||
* Distributed a refresh runs as a server job, through {@link Table#refreshColumnAsync}.
|
||||
* @param {string} column The name of the computed column to fill.
|
||||
* @returns {Promise<RefreshColumnResult>} A promise that resolves to the
|
||||
* number of rows filled and the new version number of the table.
|
||||
@@ -646,12 +656,15 @@ export abstract class Table {
|
||||
/**
|
||||
* Like {@link Table#refreshColumn}, but returns a handle to the refresh
|
||||
* job instead of blocking until it completes.
|
||||
* LanceDB Embedded refresh requires a source build with
|
||||
* `experimental-functions`. LanceDB Distributed jobs do not require this
|
||||
* feature.
|
||||
*
|
||||
* The job may already be complete when returned; callers must not assume
|
||||
* the column is filled until {@link Job.wait} resolves. Invalid input --
|
||||
* an unknown column, or one that is not computed -- rejects here rather
|
||||
* than failing the job. On local tables the job runs in-process; on
|
||||
* LanceDB Cloud and Enterprise it is the server's backfill job.
|
||||
* than failing the job. In LanceDB Embedded the job runs in-process; in
|
||||
* LanceDB Distributed it is the server's backfill job.
|
||||
* @param {string} column The name of the computed column to fill.
|
||||
* @example
|
||||
* ```ts
|
||||
@@ -668,7 +681,7 @@ export abstract class Table {
|
||||
* A refresh running under a skip policy records each row it skipped with
|
||||
* the input that failed and the error. This lists those records, newest
|
||||
* job first, plus a summary for any fragment whose per-row detail was
|
||||
* capped. LanceDB Cloud and Enterprise only; reading errors needs read
|
||||
* capped. LanceDB Distributed only; reading errors needs read
|
||||
* access to the table, since a message carries the value that failed.
|
||||
* @param {FunctionErrorsOptions} options Optional filters: `jobId`,
|
||||
* `column`, and `limit` (server default 10000, cap 100000).
|
||||
@@ -692,6 +705,7 @@ export abstract class Table {
|
||||
*/
|
||||
abstract refreshMaterializedView(
|
||||
sourceVersion?: number,
|
||||
full?: boolean,
|
||||
): Promise<RefreshMaterializedViewResult>;
|
||||
|
||||
/** @ignore */
|
||||
@@ -717,8 +731,6 @@ export abstract class Table {
|
||||
* - `lancedb:description`: for a human-readable description of a field.
|
||||
* - `lancedb:tag:<name>`: for a user-defined key-value tag, where the suffix
|
||||
* names the tag category; e.g. `lancedb:tag:model: "clip"`.
|
||||
* - `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and
|
||||
* `feature_v2` might be in the same logical column.
|
||||
* - `lancedb:status`: for status options (`production`, `candidate`,
|
||||
* `deprecated`, `archived`) to designate the current life cycle state of
|
||||
* this column.
|
||||
@@ -988,8 +1000,12 @@ export abstract class Table {
|
||||
* Specify exactly one of `column` or `indexName`.
|
||||
*
|
||||
* Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in
|
||||
* the client process from index metadata. For remote tables, this means the
|
||||
* same tokenizer model files must also exist locally.
|
||||
* the client process from index metadata. In LanceDB Distributed, this means the
|
||||
* same tokenizer model files must also exist locally (under
|
||||
* `LANCE_LANGUAGE_MODEL_HOME`) and must match the files the server uses. A
|
||||
* mismatch cannot be detected: the returned tokens may differ from what the
|
||||
* server's index produces. If the model files are missing, an error naming
|
||||
* the tokenizer is raised.
|
||||
*/
|
||||
abstract tokenize(
|
||||
query: string,
|
||||
@@ -1431,8 +1447,9 @@ export class LocalTable extends Table {
|
||||
|
||||
async refreshMaterializedView(
|
||||
sourceVersion?: number,
|
||||
full?: boolean,
|
||||
): Promise<RefreshMaterializedViewResult> {
|
||||
return await this.inner.refreshMaterializedView(sourceVersion);
|
||||
return await this.inner.refreshMaterializedView(sourceVersion, full);
|
||||
}
|
||||
|
||||
async materializedViewDefinition(): Promise<string> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-darwin-arm64",
|
||||
"version": "0.41.0-beta.9",
|
||||
"version": "0.41.0-beta.17",
|
||||
"os": ["darwin"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.darwin-arm64.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-arm64-gnu",
|
||||
"version": "0.41.0-beta.9",
|
||||
"version": "0.41.0-beta.17",
|
||||
"os": ["linux"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.linux-arm64-gnu.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-arm64-musl",
|
||||
"version": "0.41.0-beta.9",
|
||||
"version": "0.41.0-beta.17",
|
||||
"os": ["linux"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.linux-arm64-musl.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-x64-gnu",
|
||||
"version": "0.41.0-beta.9",
|
||||
"version": "0.41.0-beta.17",
|
||||
"os": ["linux"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.linux-x64-gnu.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-x64-musl",
|
||||
"version": "0.41.0-beta.9",
|
||||
"version": "0.41.0-beta.17",
|
||||
"os": ["linux"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.linux-x64-musl.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-win32-arm64-msvc",
|
||||
"version": "0.41.0-beta.9",
|
||||
"version": "0.41.0-beta.17",
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-win32-x64-msvc",
|
||||
"version": "0.41.0-beta.9",
|
||||
"version": "0.41.0-beta.17",
|
||||
"os": ["win32"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.win32-x64-msvc.node",
|
||||
|
||||
+3
-2
@@ -11,7 +11,7 @@
|
||||
"ann"
|
||||
],
|
||||
"private": false,
|
||||
"version": "0.41.0-beta.9",
|
||||
"version": "0.41.0-beta.17",
|
||||
"main": "dist/index.js",
|
||||
"exports": {
|
||||
".": "./dist/index.js",
|
||||
@@ -90,7 +90,8 @@
|
||||
"postdocs": "node typedoc_post_process.js",
|
||||
"lint": "biome check . && biome format .",
|
||||
"lint-fix": "biome check --write . && biome format --write .",
|
||||
"prepublishOnly": "napi prepublish -t npm",
|
||||
"check:native-symbols": "node scripts/check-native-symbols.js",
|
||||
"prepublishOnly": "pnpm check:native-symbols && napi prepublish -t npm",
|
||||
"test": "jest --verbose",
|
||||
"integration": "S3_TEST=1 pnpm test",
|
||||
"universal": "napi universalize",
|
||||
|
||||
Generated
+29
-29
@@ -13,7 +13,7 @@ importers:
|
||||
dependencies:
|
||||
'@opentelemetry/api':
|
||||
specifier: ^1.9.0
|
||||
version: 1.9.1
|
||||
version: 1.10.0
|
||||
reflect-metadata:
|
||||
specifier: ^0.2.2
|
||||
version: 0.2.2
|
||||
@@ -38,7 +38,7 @@ importers:
|
||||
version: 3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)(@types/node@22.7.4)
|
||||
'@opentelemetry/sdk-metrics':
|
||||
specifier: ^2.10.0
|
||||
version: 2.11.0(@opentelemetry/api@1.9.1)
|
||||
version: 2.12.0(@opentelemetry/api@1.10.0)
|
||||
'@types/axios':
|
||||
specifier: ^0.14.0
|
||||
version: 0.14.4
|
||||
@@ -89,7 +89,7 @@ importers:
|
||||
version: 0.2.7
|
||||
ts-jest:
|
||||
specifier: ^29.1.2
|
||||
version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4)
|
||||
version: 29.4.15(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4)
|
||||
typedoc:
|
||||
specifier: 0.26.4
|
||||
version: 0.26.4(typescript@5.5.4)
|
||||
@@ -1399,24 +1399,24 @@ packages:
|
||||
'@octokit/types@16.0.0':
|
||||
resolution: {integrity: sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==}
|
||||
|
||||
'@opentelemetry/api@1.9.1':
|
||||
resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}
|
||||
'@opentelemetry/api@1.10.0':
|
||||
resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==}
|
||||
engines: {node: '>=8.0.0'}
|
||||
|
||||
'@opentelemetry/core@2.11.0':
|
||||
resolution: {integrity: sha512-7YP44XH0tV6+Mb54x2YGf84i7yi+31MBZlE8JwvozkxyTvXbSp10X7cI7YE49ChJ3shMJoBmCJF3+1QFBJctGA==}
|
||||
'@opentelemetry/core@2.12.0':
|
||||
resolution: {integrity: sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.0.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/resources@2.11.0':
|
||||
resolution: {integrity: sha512-Ie7+8q8MDF4FAEQCKVMTx3ReUvxiIAgIiiW3c9JdmP8+HMcDy20puT+AHjexnExgnbvBxjQ9fjkFDWrikJ2jQA==}
|
||||
'@opentelemetry/resources@2.12.0':
|
||||
resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.3.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/sdk-metrics@2.11.0':
|
||||
resolution: {integrity: sha512-7GXXcObyHyDUUSG+L+kJoquty01bzm7ivE7+SSgXXJcHuPzGviptxwARmI2c+bnnxjexGQbJnyNlN8HxBP/Y7A==}
|
||||
'@opentelemetry/sdk-metrics@2.12.0':
|
||||
resolution: {integrity: sha512-mVMaEHwCUJuY3S4Esn+nT0yQA3qCEGh+SOPJsXygU0Gl453WcsDNjtEa8EfdewMwoLyr1tlofB4fXytVpiXuow==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.9.0 <1.10.0'
|
||||
@@ -2434,8 +2434,8 @@ packages:
|
||||
guid-typescript@1.0.9:
|
||||
resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==}
|
||||
|
||||
handlebars@4.7.9:
|
||||
resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==}
|
||||
handlebars@4.7.10:
|
||||
resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==}
|
||||
engines: {node: '>=0.4.7'}
|
||||
hasBin: true
|
||||
|
||||
@@ -3280,12 +3280,12 @@ packages:
|
||||
peerDependencies:
|
||||
typescript: '>=4.2.0'
|
||||
|
||||
ts-jest@29.4.12:
|
||||
resolution: {integrity: sha512-Ov6ClY53Fflh6BGAnY2DlTq1hYDrTycz2PVTXBWFW2CU+9zrEqAp9fWdGXl42EXO5RLSFAcAZ2JFKbP+zBTFfw==}
|
||||
ts-jest@29.4.15:
|
||||
resolution: {integrity: sha512-s2qmEUYFRqbjz1wv0EmccNPVOb45HOFpFuhzQJLKShYVisuTbCFPIIAIV2EuK5rIxb4BejLDbH7dnBZfYjybUQ==}
|
||||
engines: {node: ^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@babel/core': '>=7.0.0-beta.0 <8'
|
||||
'@babel/core': '>=7.0.0-beta.0 <9'
|
||||
'@jest/transform': ^29.0.0 || ^30.0.0
|
||||
'@jest/types': ^29.0.0 || ^30.0.0
|
||||
babel-jest: ^29.0.0 || ^30.0.0
|
||||
@@ -5153,24 +5153,24 @@ snapshots:
|
||||
dependencies:
|
||||
'@octokit/openapi-types': 27.0.0
|
||||
|
||||
'@opentelemetry/api@1.9.1': {}
|
||||
'@opentelemetry/api@1.10.0': {}
|
||||
|
||||
'@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1)':
|
||||
'@opentelemetry/core@2.12.0(@opentelemetry/api@1.10.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.1
|
||||
'@opentelemetry/api': 1.10.0
|
||||
'@opentelemetry/semantic-conventions': 1.43.0
|
||||
|
||||
'@opentelemetry/resources@2.11.0(@opentelemetry/api@1.9.1)':
|
||||
'@opentelemetry/resources@2.12.0(@opentelemetry/api@1.10.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.1
|
||||
'@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1)
|
||||
'@opentelemetry/api': 1.10.0
|
||||
'@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0)
|
||||
'@opentelemetry/semantic-conventions': 1.43.0
|
||||
|
||||
'@opentelemetry/sdk-metrics@2.11.0(@opentelemetry/api@1.9.1)':
|
||||
'@opentelemetry/sdk-metrics@2.12.0(@opentelemetry/api@1.10.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.1
|
||||
'@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1)
|
||||
'@opentelemetry/resources': 2.11.0(@opentelemetry/api@1.9.1)
|
||||
'@opentelemetry/api': 1.10.0
|
||||
'@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0)
|
||||
'@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0)
|
||||
|
||||
'@opentelemetry/semantic-conventions@1.43.0': {}
|
||||
|
||||
@@ -6376,7 +6376,7 @@ snapshots:
|
||||
guid-typescript@1.0.9:
|
||||
optional: true
|
||||
|
||||
handlebars@4.7.9:
|
||||
handlebars@4.7.10:
|
||||
dependencies:
|
||||
minimist: 1.2.8
|
||||
neo-async: 2.6.2
|
||||
@@ -7409,11 +7409,11 @@ snapshots:
|
||||
dependencies:
|
||||
typescript: 5.5.4
|
||||
|
||||
ts-jest@29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4):
|
||||
ts-jest@29.4.15(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4):
|
||||
dependencies:
|
||||
bs-logger: 0.2.6
|
||||
fast-json-stable-stringify: 2.1.0
|
||||
handlebars: 4.7.9
|
||||
handlebars: 4.7.10
|
||||
jest: 29.7.0(@types/node@22.7.4)
|
||||
json5: 2.2.3
|
||||
lodash.memoize: 4.1.2
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const { existsSync } = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const FORBIDDEN_UNDEFINED_SYMBOLS = new Set([
|
||||
"sum_4bit_dist_table_32bytes_batch_avx512",
|
||||
]);
|
||||
|
||||
function findForbiddenUndefinedSymbols(output) {
|
||||
const found = new Set();
|
||||
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
const columns = line.trim().split(/\s+/);
|
||||
const symbol = columns.at(-1)?.split("@")[0];
|
||||
if (symbol && FORBIDDEN_UNDEFINED_SYMBOLS.has(symbol)) {
|
||||
found.add(symbol);
|
||||
}
|
||||
}
|
||||
|
||||
return [...found].sort();
|
||||
}
|
||||
|
||||
function checkNativeBinary(binaryPath, runNm = spawnSync) {
|
||||
const result = runNm("nm", ["-D", "--undefined-only", binaryPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(`Unable to inspect ${binaryPath}: ${result.error.message}`);
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
throw new Error(
|
||||
`Unable to inspect ${binaryPath}: nm exited with status ${result.status}\n${result.stderr}`,
|
||||
);
|
||||
}
|
||||
|
||||
const forbidden = findForbiddenUndefinedSymbols(result.stdout);
|
||||
if (forbidden.length > 0) {
|
||||
throw new Error(
|
||||
`${binaryPath} contains unresolved internal Lance symbols: ${forbidden.join(
|
||||
", ",
|
||||
)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const binaryPath = path.resolve(
|
||||
__dirname,
|
||||
"..",
|
||||
"npm",
|
||||
"linux-x64-musl",
|
||||
"lancedb.linux-x64-musl.node",
|
||||
);
|
||||
|
||||
if (!existsSync(binaryPath)) {
|
||||
throw new Error(
|
||||
`Missing ${binaryPath}; assemble the native artifacts before publishing`,
|
||||
);
|
||||
}
|
||||
|
||||
checkNativeBinary(binaryPath);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { checkNativeBinary, findForbiddenUndefinedSymbols };
|
||||
@@ -124,10 +124,17 @@ impl Catalog {
|
||||
.default_error()
|
||||
}
|
||||
#[napi]
|
||||
pub async fn drop_database(&self, name: String, ignore_missing: Option<bool>) -> Result<()> {
|
||||
pub async fn drop_database(
|
||||
&self,
|
||||
name: String,
|
||||
ignore_missing: Option<bool>,
|
||||
cascade: Option<bool>,
|
||||
) -> Result<()> {
|
||||
self.inner
|
||||
.drop_database(
|
||||
DropDatabaseRequest::new(name).ignore_missing(ignore_missing.unwrap_or(false)),
|
||||
DropDatabaseRequest::new(name)
|
||||
.ignore_missing(ignore_missing.unwrap_or(false))
|
||||
.cascade(cascade.unwrap_or(false)),
|
||||
)
|
||||
.await
|
||||
.default_error()
|
||||
|
||||
+19
-52
@@ -16,8 +16,7 @@ use crate::table::Table;
|
||||
use lancedb::connection::{ConnectBuilder, Connection as LanceDBConnection, connect_namespace};
|
||||
|
||||
use lance_namespace::models::{
|
||||
CreateNamespaceRequest, DescribeNamespaceRequest, DropNamespaceRequest, ListNamespacesRequest,
|
||||
ListTablesRequest,
|
||||
CreateNamespaceRequest, DescribeNamespaceRequest, DropNamespaceRequest,
|
||||
};
|
||||
use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema};
|
||||
|
||||
@@ -31,18 +30,6 @@ pub struct DescribeNamespaceResponse {
|
||||
pub properties: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct ListNamespacesResponse {
|
||||
pub namespaces: Vec<String>,
|
||||
pub page_token: Option<String>,
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct ListTablesResponse {
|
||||
pub tables: Vec<String>,
|
||||
pub page_token: Option<String>,
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct CreateNamespaceResponse {
|
||||
pub properties: Option<HashMap<String, String>>,
|
||||
@@ -239,31 +226,20 @@ impl Connection {
|
||||
op.execute().await.default_error()
|
||||
}
|
||||
|
||||
/// List a page of tables in the database.
|
||||
/// Lazily list tables in the database.
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn list_tables(
|
||||
pub fn list_tables(
|
||||
&self,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
page_token: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> napi::Result<ListTablesResponse> {
|
||||
let request = ListTablesRequest {
|
||||
// The root namespace is an empty path, not an absent one: a namespace-backed
|
||||
// database rejects a request that names no namespace.
|
||||
id: Some(namespace_path.unwrap_or_default()),
|
||||
page_token,
|
||||
limit: limit.map(|limit| i32::try_from(limit).unwrap_or(i32::MAX)),
|
||||
..Default::default()
|
||||
};
|
||||
let response = self
|
||||
.get_inner()?
|
||||
.list_tables(request)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(ListTablesResponse {
|
||||
tables: response.tables,
|
||||
page_token: response.page_token,
|
||||
})
|
||||
) -> napi::Result<crate::listing::NameListing> {
|
||||
Ok(crate::listing::NameListing::new(
|
||||
self.get_inner()?.list_tables(
|
||||
&namespace_path.unwrap_or_default(),
|
||||
crate::listing::options(page_token, limit),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
/// Create table from a Apache Arrow IPC (file) buffer.
|
||||
@@ -663,28 +639,19 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
/// List child namespaces under the given namespace path
|
||||
pub async fn list_namespaces(
|
||||
/// Lazily list child namespaces under the given namespace path
|
||||
pub fn list_namespaces(
|
||||
&self,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
page_token: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> napi::Result<ListNamespacesResponse> {
|
||||
let req = ListNamespacesRequest {
|
||||
id: namespace_path,
|
||||
page_token,
|
||||
limit: limit.map(|l| l as i32),
|
||||
..Default::default()
|
||||
};
|
||||
let resp = self
|
||||
.get_inner()?
|
||||
.list_namespaces(req)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(ListNamespacesResponse {
|
||||
namespaces: resp.namespaces,
|
||||
page_token: resp.page_token,
|
||||
})
|
||||
) -> napi::Result<crate::listing::NameListing> {
|
||||
Ok(crate::listing::NameListing::new(
|
||||
self.get_inner()?.list_namespaces(
|
||||
&namespace_path.unwrap_or_default(),
|
||||
crate::listing::options(page_token, limit),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! Napi bindings for the LanceDB expression builder API.
|
||||
|
||||
use std::ops::{Add, Div, Mul, Not, Sub};
|
||||
|
||||
use lancedb::expr::{
|
||||
DfExpr, col as ldb_col, contains, expr_cast, is_in, lit as df_lit, lower, upper,
|
||||
};
|
||||
use napi::bindgen_prelude::*;
|
||||
use napi_derive::napi;
|
||||
|
||||
#[napi]
|
||||
#[derive(Clone)]
|
||||
pub struct Expr {
|
||||
pub(crate) inner: DfExpr,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl Expr {
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn eq(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().eq(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn ne(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().not_eq(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn lt(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().lt(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn lte(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().lt_eq(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn gt(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().gt(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn gte(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().gt_eq(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn and(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().and(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn or(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().or(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn not(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().not(),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn add(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().add(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn sub(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().sub(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn mul(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().mul(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn div(&self, other: &Expr) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone().div(other.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn lower(&self) -> Self {
|
||||
Self {
|
||||
inner: lower(self.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn upper(&self) -> Self {
|
||||
Self {
|
||||
inner: upper(self.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn contains(&self, substr: &Expr) -> Self {
|
||||
Self {
|
||||
inner: contains(self.inner.clone(), substr.inner.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it
|
||||
pub fn is_in(&self, list: Vec<&Expr>) -> Self {
|
||||
let items: Vec<DfExpr> = list.into_iter().map(|e| e.inner.clone()).collect();
|
||||
Self {
|
||||
inner: is_in(self.inner.clone(), items),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn cast(&self, data_type: String) -> napi::Result<Self> {
|
||||
let arrow_type = data_type
|
||||
.parse::<arrow_schema::DataType>()
|
||||
.map_err(|e| napi::Error::from_reason(format!("Invalid data type: {}", e)))?;
|
||||
Ok(Self {
|
||||
inner: expr_cast(self.inner.clone(), arrow_type),
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn to_sql(&self) -> napi::Result<String> {
|
||||
lancedb::expr::expr_to_sql_string(&self.inner)
|
||||
.map_err(|e| napi::Error::from_reason(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a column reference expression.
|
||||
///
|
||||
/// The column name is preserved exactly as given (case-sensitive), so
|
||||
/// `col("firstName")` correctly references a field named `firstName`.
|
||||
#[napi]
|
||||
#[allow(dead_code)]
|
||||
pub fn col(name: String) -> Expr {
|
||||
Expr {
|
||||
inner: ldb_col(name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a literal (constant) value expression.
|
||||
#[napi]
|
||||
#[allow(dead_code)]
|
||||
pub fn lit(value: napi::bindgen_prelude::Either<String, f64>) -> napi::Result<Expr> {
|
||||
match value {
|
||||
Either::A(s) => Ok(Expr { inner: df_lit(s) }),
|
||||
Either::B(f) => Ok(Expr { inner: df_lit(f) }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a literal boolean value expression.
|
||||
#[napi]
|
||||
#[allow(dead_code)]
|
||||
pub fn lit_bool(value: bool) -> Expr {
|
||||
Expr {
|
||||
inner: df_lit(value),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a literal integer value expression.
|
||||
#[napi]
|
||||
#[allow(dead_code)]
|
||||
pub fn lit_int(value: i64) -> Expr {
|
||||
Expr {
|
||||
inner: df_lit(value),
|
||||
}
|
||||
}
|
||||
|
||||
/// Call an arbitrary registered SQL function by name.
|
||||
#[napi]
|
||||
#[allow(dead_code)]
|
||||
pub fn func(name: String, args: Vec<&Expr>) -> napi::Result<Expr> {
|
||||
let df_args: Vec<DfExpr> = args.into_iter().map(|e| e.inner.clone()).collect();
|
||||
lancedb::expr::func(&name, df_args)
|
||||
.map(|inner| Expr { inner })
|
||||
.map_err(|e| napi::Error::from_reason(e.to_string()))
|
||||
}
|
||||
@@ -104,6 +104,7 @@ impl Index {
|
||||
num_bits: Option<u32>,
|
||||
max_iterations: Option<u32>,
|
||||
sample_rate: Option<u32>,
|
||||
target_partition_size: Option<u32>,
|
||||
) -> napi::Result<Self> {
|
||||
let mut ivf_pq_builder = IvfPqIndexBuilder::default();
|
||||
if let Some(distance_type) = distance_type {
|
||||
@@ -113,6 +114,9 @@ impl Index {
|
||||
if let Some(num_partitions) = num_partitions {
|
||||
ivf_pq_builder = ivf_pq_builder.num_partitions(num_partitions);
|
||||
}
|
||||
if let Some(target_partition_size) = target_partition_size {
|
||||
ivf_pq_builder = ivf_pq_builder.target_partition_size(target_partition_size);
|
||||
}
|
||||
if let Some(num_sub_vectors) = num_sub_vectors {
|
||||
ivf_pq_builder = ivf_pq_builder.num_sub_vectors(num_sub_vectors);
|
||||
}
|
||||
@@ -137,6 +141,7 @@ impl Index {
|
||||
num_bits: Option<u32>,
|
||||
max_iterations: Option<u32>,
|
||||
sample_rate: Option<u32>,
|
||||
target_partition_size: Option<u32>,
|
||||
) -> napi::Result<Self> {
|
||||
let mut ivf_rq_builder = IvfRqIndexBuilder::default();
|
||||
if let Some(distance_type) = distance_type {
|
||||
@@ -146,6 +151,9 @@ impl Index {
|
||||
if let Some(num_partitions) = num_partitions {
|
||||
ivf_rq_builder = ivf_rq_builder.num_partitions(num_partitions);
|
||||
}
|
||||
if let Some(target_partition_size) = target_partition_size {
|
||||
ivf_rq_builder = ivf_rq_builder.target_partition_size(target_partition_size);
|
||||
}
|
||||
if let Some(num_bits) = num_bits {
|
||||
ivf_rq_builder = ivf_rq_builder.num_bits(num_bits);
|
||||
}
|
||||
@@ -166,6 +174,7 @@ impl Index {
|
||||
num_partitions: Option<u32>,
|
||||
max_iterations: Option<u32>,
|
||||
sample_rate: Option<u32>,
|
||||
target_partition_size: Option<u32>,
|
||||
) -> napi::Result<Self> {
|
||||
let mut ivf_flat_builder = IvfFlatIndexBuilder::default();
|
||||
if let Some(distance_type) = distance_type {
|
||||
@@ -175,6 +184,9 @@ impl Index {
|
||||
if let Some(num_partitions) = num_partitions {
|
||||
ivf_flat_builder = ivf_flat_builder.num_partitions(num_partitions);
|
||||
}
|
||||
if let Some(target_partition_size) = target_partition_size {
|
||||
ivf_flat_builder = ivf_flat_builder.target_partition_size(target_partition_size);
|
||||
}
|
||||
if let Some(max_iterations) = max_iterations {
|
||||
ivf_flat_builder = ivf_flat_builder.max_iterations(max_iterations);
|
||||
}
|
||||
@@ -283,6 +295,7 @@ impl Index {
|
||||
}
|
||||
|
||||
#[napi(factory)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn hnsw_pq(
|
||||
distance_type: Option<String>,
|
||||
num_partitions: Option<u32>,
|
||||
@@ -291,6 +304,7 @@ impl Index {
|
||||
sample_rate: Option<u32>,
|
||||
m: Option<u32>,
|
||||
ef_construction: Option<u32>,
|
||||
target_partition_size: Option<u32>,
|
||||
) -> napi::Result<Self> {
|
||||
let mut hnsw_pq_builder = IvfHnswPqIndexBuilder::default();
|
||||
if let Some(distance_type) = distance_type {
|
||||
@@ -300,6 +314,9 @@ impl Index {
|
||||
if let Some(num_partitions) = num_partitions {
|
||||
hnsw_pq_builder = hnsw_pq_builder.num_partitions(num_partitions);
|
||||
}
|
||||
if let Some(target_partition_size) = target_partition_size {
|
||||
hnsw_pq_builder = hnsw_pq_builder.target_partition_size(target_partition_size);
|
||||
}
|
||||
if let Some(num_sub_vectors) = num_sub_vectors {
|
||||
hnsw_pq_builder = hnsw_pq_builder.num_sub_vectors(num_sub_vectors);
|
||||
}
|
||||
@@ -328,6 +345,7 @@ impl Index {
|
||||
sample_rate: Option<u32>,
|
||||
m: Option<u32>,
|
||||
ef_construction: Option<u32>,
|
||||
target_partition_size: Option<u32>,
|
||||
) -> napi::Result<Self> {
|
||||
let mut hnsw_sq_builder = IvfHnswSqIndexBuilder::default();
|
||||
if let Some(distance_type) = distance_type {
|
||||
@@ -337,6 +355,9 @@ impl Index {
|
||||
if let Some(num_partitions) = num_partitions {
|
||||
hnsw_sq_builder = hnsw_sq_builder.num_partitions(num_partitions);
|
||||
}
|
||||
if let Some(target_partition_size) = target_partition_size {
|
||||
hnsw_sq_builder = hnsw_sq_builder.target_partition_size(target_partition_size);
|
||||
}
|
||||
if let Some(max_iterations) = max_iterations {
|
||||
hnsw_sq_builder = hnsw_sq_builder.max_iterations(max_iterations);
|
||||
}
|
||||
|
||||
+6
-6
@@ -29,8 +29,8 @@ impl Job {
|
||||
|
||||
#[napi]
|
||||
impl Job {
|
||||
/// Identifies the operation on the server that is running it. Operations
|
||||
/// that run in this process have no server id. The value is opaque.
|
||||
/// The operation's opaque ID. Interpret registry and query IDs using job_type().
|
||||
/// Local handles have no ID.
|
||||
#[napi(getter)]
|
||||
pub fn id(&self) -> Option<String> {
|
||||
self.inner.id().map(str::to_string)
|
||||
@@ -62,8 +62,8 @@ impl Job {
|
||||
/// Ask the backend for this job's current state, and for a server-side job
|
||||
/// its full record, then cache it for the getters below.
|
||||
///
|
||||
/// They are all null until this runs, because submitting an operation
|
||||
/// returns only a job id. {@link Job.status} fetches the whole record too;
|
||||
/// Registry details are null until this runs; query handles already expose
|
||||
/// job_type "query". {@link Job.status} fetches the whole registry record too;
|
||||
/// {@link Job.wait} records only the terminal state it establishes.
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn refresh(&self) -> napi::Result<()> {
|
||||
@@ -76,8 +76,8 @@ impl Job {
|
||||
self.inner.state()
|
||||
}
|
||||
|
||||
/// The job's type, as the server names it. Null for an in-process job,
|
||||
/// which has no server-side record.
|
||||
/// "query" immediately for SQL-backed handles; otherwise the cached
|
||||
/// server-reported job type. Null for in-process handles.
|
||||
#[napi(getter)]
|
||||
pub fn job_type(&self) -> Option<String> {
|
||||
self.inner.job_type()
|
||||
|
||||
+17
-10
@@ -14,6 +14,7 @@ mod blob;
|
||||
mod catalog;
|
||||
mod connection;
|
||||
mod error;
|
||||
mod expr;
|
||||
mod header;
|
||||
mod index;
|
||||
mod iterator;
|
||||
@@ -30,6 +31,12 @@ mod session;
|
||||
mod table;
|
||||
mod util;
|
||||
|
||||
/// Whether this native binding was built with local experimental Functions.
|
||||
#[napi]
|
||||
pub fn experimental_functions_enabled() -> bool {
|
||||
cfg!(feature = "experimental-functions")
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
#[derive(Debug)]
|
||||
pub struct ConnectionOptions {
|
||||
@@ -47,34 +54,34 @@ pub struct ConnectionOptions {
|
||||
/// often each read pays the cost of checking for updates against object
|
||||
/// storage, raising per-read latency and cost.
|
||||
pub read_consistency_interval: Option<f64>,
|
||||
/// (For LanceDB OSS only): configuration for object storage.
|
||||
/// (For LanceDB Embedded only): configuration for object storage.
|
||||
///
|
||||
/// The available options are described at https://docs.lancedb.com/storage/
|
||||
pub storage_options: Option<HashMap<String, String>>,
|
||||
/// (For LanceDB OSS only): use directory namespace manifests as the source
|
||||
/// (For LanceDB Embedded only): use directory namespace manifests as the source
|
||||
/// of truth for table metadata. Existing directory-listed root tables are
|
||||
/// migrated into the manifest on access.
|
||||
pub manifest_enabled: Option<bool>,
|
||||
/// (For LanceDB OSS only): extra properties for the backing namespace
|
||||
/// (For LanceDB Embedded only): extra properties for the backing namespace
|
||||
/// client used by manifest-enabled native connections.
|
||||
pub namespace_client_properties: Option<HashMap<String, String>>,
|
||||
/// (For LanceDB OSS only): the session to use for this connection. Holds
|
||||
/// (For LanceDB Embedded only): the session to use for this connection. Holds
|
||||
/// shared caches and other session-specific state.
|
||||
pub session: Option<session::Session>,
|
||||
|
||||
/// (For LanceDB cloud only): configuration for the remote HTTP client.
|
||||
/// (For LanceDB Enterprise or LanceDB Cloud only): configuration for the HTTP client.
|
||||
pub client_config: Option<remote::ClientConfig>,
|
||||
/// (For LanceDB cloud only): the API key to use with LanceDB Cloud.
|
||||
/// (For LanceDB Enterprise or LanceDB Cloud only): the API key to use.
|
||||
///
|
||||
/// Can also be set via the environment variable `LANCEDB_API_KEY`.
|
||||
pub api_key: Option<String>,
|
||||
/// (For LanceDB cloud only): the region to use for LanceDB cloud.
|
||||
/// (For LanceDB Cloud only): the region to use for LanceDB Cloud (legacy).
|
||||
/// Defaults to 'us-east-1'.
|
||||
pub region: Option<String>,
|
||||
/// (For LanceDB cloud only): the host to use for LanceDB cloud. Used
|
||||
/// for testing purposes.
|
||||
/// (For LanceDB Enterprise only): the host of the LanceDB Enterprise
|
||||
/// deployment to connect to.
|
||||
pub host_override: Option<String>,
|
||||
/// (For LanceDB cloud only): OAuth configuration for IdP-based
|
||||
/// (For LanceDB Enterprise only): OAuth configuration for IdP-based
|
||||
/// authentication (e.g., Azure Entra ID). When set, token acquisition
|
||||
/// and refresh are handled entirely in Rust. TypeScript users should pass
|
||||
/// the public `OAuthConfig` type exported from `@lancedb/lancedb`.
|
||||
|
||||
@@ -25,6 +25,10 @@ pub struct TimeoutConfig {
|
||||
/// The timeout for reading data from the server in seconds. Default is 300
|
||||
/// seconds (5 minutes). This can also be set via the environment variable
|
||||
/// `LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds.
|
||||
///
|
||||
/// This also applies while waiting for response headers during an upload.
|
||||
/// A large or slowly produced request body (for example, when creating a
|
||||
/// table) may need a longer timeout even if data is still being uploaded.
|
||||
pub read_timeout: Option<f64>,
|
||||
/// The timeout for keeping idle connections in the connection pool in seconds.
|
||||
/// Default is 300 seconds (5 minutes). This can also be set via the
|
||||
@@ -65,7 +69,7 @@ pub struct RetryConfig {
|
||||
/// `LANCE_CLIENT_RETRY_BACKOFF_JITTER`.
|
||||
pub backoff_jitter: Option<f64>,
|
||||
/// The HTTP status codes for which to retry the request. Default is
|
||||
/// [429, 500, 502, 503].
|
||||
/// [409, 429, 500, 502, 503, 504].
|
||||
///
|
||||
/// You can also set this via the environment variable
|
||||
/// `LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers.
|
||||
@@ -104,7 +108,7 @@ pub struct ClientConfig {
|
||||
pub tls_config: Option<TlsConfig>,
|
||||
/// User identifier for tracking purposes.
|
||||
///
|
||||
/// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise.
|
||||
/// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Enterprise.
|
||||
/// It can be set directly, or via the `LANCEDB_USER_ID` environment variable.
|
||||
/// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment
|
||||
/// variable that contains the user ID value.
|
||||
|
||||
+26
-22
@@ -470,11 +470,12 @@ impl Table {
|
||||
pub async fn refresh_materialized_view(
|
||||
&self,
|
||||
source_version: Option<i64>,
|
||||
full: Option<bool>,
|
||||
) -> napi::Result<RefreshMaterializedViewResult> {
|
||||
let view = lancedb::MaterializedView::from_table(self.inner_ref()?.clone())
|
||||
.await
|
||||
.default_error()?;
|
||||
let mut builder = view.refresh();
|
||||
let mut builder = view.refresh().full(full.unwrap_or(false));
|
||||
if let Some(version) = source_version {
|
||||
let version = u64::try_from(version).map_err(|_| {
|
||||
napi::Error::from_reason("sourceVersion must be a non-negative integer")
|
||||
@@ -830,7 +831,7 @@ impl Table {
|
||||
self.inner_ref()?
|
||||
.as_native()
|
||||
.ok_or_else(|| lancedb::Error::NotSupported {
|
||||
message: "uses_v2_manifest_paths is not supported for remote tables.".into(),
|
||||
message: "uses_v2_manifest_paths is not supported in LanceDB Distributed.".into(),
|
||||
})
|
||||
.default_error()?
|
||||
.uses_v2_manifest_paths()
|
||||
@@ -843,7 +844,8 @@ impl Table {
|
||||
self.inner_ref()?
|
||||
.as_native()
|
||||
.ok_or_else(|| lancedb::Error::NotSupported {
|
||||
message: "migrate_manifest_paths_v2 is not supported for remote tables.".into(),
|
||||
message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed."
|
||||
.into(),
|
||||
})
|
||||
.default_error()?
|
||||
.migrate_manifest_paths_v2()
|
||||
@@ -866,40 +868,40 @@ pub struct IndexConfig {
|
||||
pub columns: Vec<String>,
|
||||
/// The UUID of the first segment of the index.
|
||||
///
|
||||
/// `undefined` for remote tables, which do not yet surface this.
|
||||
/// `undefined` in LanceDB Distributed, which does not yet surface this.
|
||||
pub index_uuid: Option<String>,
|
||||
/// The protobuf type URL, a precise type identifier for the index.
|
||||
///
|
||||
/// `undefined` for remote tables.
|
||||
/// `undefined` in LanceDB Distributed.
|
||||
pub type_url: Option<String>,
|
||||
/// When the index was created.
|
||||
///
|
||||
/// `undefined` for remote tables or indices created before timestamps were tracked.
|
||||
/// `undefined` in LanceDB Distributed or indices created before timestamps were tracked.
|
||||
pub created_at: Option<DateTime<Utc>>,
|
||||
/// The number of rows indexed, across all segments.
|
||||
///
|
||||
/// `undefined` for remote tables.
|
||||
/// May be `undefined` in LanceDB Distributed if the server does not report it.
|
||||
pub num_indexed_rows: Option<i64>,
|
||||
/// The number of rows not yet covered by this index.
|
||||
///
|
||||
/// `undefined` for remote tables.
|
||||
/// May be `undefined` in LanceDB Distributed if the server does not report it.
|
||||
pub num_unindexed_rows: Option<i64>,
|
||||
/// The total size in bytes of all index files across all segments.
|
||||
///
|
||||
/// `undefined` for remote tables or indices without size tracking.
|
||||
/// `undefined` in LanceDB Distributed or indices without size tracking.
|
||||
pub size_bytes: Option<i64>,
|
||||
/// The number of segments that make up the index.
|
||||
///
|
||||
/// `undefined` for remote tables.
|
||||
/// `undefined` in LanceDB Distributed.
|
||||
pub num_segments: Option<i32>,
|
||||
/// The on-disk index format version.
|
||||
///
|
||||
/// `undefined` for remote tables.
|
||||
/// `undefined` in LanceDB Distributed.
|
||||
pub index_version: Option<i32>,
|
||||
/// Index-type-specific details parsed as a JavaScript object.
|
||||
///
|
||||
/// Falls back to a raw string if JSON parsing fails. `undefined` for
|
||||
/// remote tables or when details are unavailable.
|
||||
/// Falls back to a raw string if JSON parsing fails. `undefined` in
|
||||
/// LanceDB Distributed or when details are unavailable.
|
||||
pub index_details: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
@@ -1615,22 +1617,24 @@ impl From<lancedb::function::FunctionErrors> for FunctionErrors {
|
||||
|
||||
#[napi(object)]
|
||||
pub struct RefreshMaterializedViewResult {
|
||||
/// How the view was brought up to date: "rebuild".
|
||||
pub mode: String,
|
||||
pub rows_written: i64,
|
||||
pub source_version: i64,
|
||||
/// How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes.
|
||||
pub mode: Option<String>,
|
||||
/// Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes.
|
||||
pub rows_written: Option<i64>,
|
||||
/// Source version refreshed to, or absent for LanceDB Distributed SQL refreshes.
|
||||
pub source_version: Option<i64>,
|
||||
pub version: i64,
|
||||
}
|
||||
|
||||
impl From<lancedb::RefreshMaterializedViewResult> for RefreshMaterializedViewResult {
|
||||
fn from(value: lancedb::RefreshMaterializedViewResult) -> Self {
|
||||
let mode = match value.mode {
|
||||
let mode = value.mode.map(|mode| match mode {
|
||||
lancedb::RefreshMode::Rebuild => "rebuild",
|
||||
};
|
||||
});
|
||||
Self {
|
||||
mode: mode.to_string(),
|
||||
rows_written: value.rows_written as i64,
|
||||
source_version: value.source_version as i64,
|
||||
mode: mode.map(str::to_string),
|
||||
rows_written: value.rows_written.map(|rows| rows as i64),
|
||||
source_version: value.source_version.map(|version| version as i64),
|
||||
version: value.version as i64,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"intentionallyNotExported": [
|
||||
"lancedb/native.d.ts:Query",
|
||||
"lancedb/native.d.ts:Expr",
|
||||
"lancedb/native.d.ts:VectorQuery",
|
||||
"lancedb/native.d.ts:TakeQuery",
|
||||
"lancedb/native.d.ts:RecordBatchIterator",
|
||||
|
||||
Reference in New Issue
Block a user