mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
feat(nodejs): add tag-based branch creation and default tag versions
This commit is contained in:
@@ -1382,6 +1382,111 @@ describe("remote connection", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("forks Enterprise branches from tags and defaults tag versions", async () => {
|
||||
const requests: { path: string; body: Record<string, unknown> }[] = [];
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
const path = req.url ?? "";
|
||||
if (path.endsWith("/branches/list/")) {
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
branches: {
|
||||
exp: { parentVersion: 1, createAt: 1, manifestSize: 1 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (path.endsWith("/describe/")) {
|
||||
res.writeHead(200, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
name: "t",
|
||||
version: 2,
|
||||
schema: { fields: [] },
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let raw = "";
|
||||
req.on("data", (chunk) => {
|
||||
raw += chunk;
|
||||
});
|
||||
req.on("end", () => {
|
||||
const body = raw ? JSON.parse(raw) : {};
|
||||
requests.push({ path, body });
|
||||
if (path.endsWith("/tags/version/")) {
|
||||
res
|
||||
.writeHead(200, { "Content-Type": "application/json" })
|
||||
.end(JSON.stringify({ version: 3, branch: "base" }));
|
||||
return;
|
||||
}
|
||||
if (path.endsWith("/tags/create/")) {
|
||||
res
|
||||
.writeHead(200, { "Content-Type": "application/json" })
|
||||
.end("{}");
|
||||
return;
|
||||
}
|
||||
if (path.endsWith("/branches/create/")) {
|
||||
if (body["name"] === "missing") {
|
||||
res
|
||||
.writeHead(404, { "Content-Type": "application/json" })
|
||||
.end(JSON.stringify({ message: "not found" }));
|
||||
return;
|
||||
}
|
||||
res
|
||||
.writeHead(200, { "Content-Type": "application/json" })
|
||||
.end("{}");
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
});
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("t", undefined, { branch: "exp" });
|
||||
await (await table.tags()).create("baseline");
|
||||
|
||||
const branches = await table.branches();
|
||||
const fromTag = await branches.create("from-tag", {
|
||||
fromTag: "baseline",
|
||||
});
|
||||
expect(fromTag.currentBranch()).toBe("from-tag");
|
||||
|
||||
// An Enterprise 404 is an ambiguous table-or-source failure, so the
|
||||
// Embedded branch hint must not be appended based on its message.
|
||||
const missing = await branches
|
||||
.create("missing", { fromTag: "baseline" })
|
||||
.then(
|
||||
() => undefined,
|
||||
(error: Error) => error,
|
||||
);
|
||||
expect(missing).toBeDefined();
|
||||
expect(missing?.message).not.toContain("fromTag");
|
||||
},
|
||||
);
|
||||
|
||||
// Omitting the tag version resolves the handle's visible branch version.
|
||||
expect(requests).toContainEqual({
|
||||
path: "/v1/table/t/tags/create/",
|
||||
body: {
|
||||
tag: "baseline",
|
||||
version: 2,
|
||||
branch: "exp",
|
||||
},
|
||||
});
|
||||
// A tag source uses the existing coordinate lookup and the normal
|
||||
// branches/create body; there is no from_tag field on the wire.
|
||||
expect(requests).toContainEqual({
|
||||
path: "/v1/table/t/tags/version/",
|
||||
body: { tag: "baseline" },
|
||||
});
|
||||
expect(requests).toContainEqual({
|
||||
path: "/v1/table/t/branches/create/",
|
||||
// biome-ignore lint/style/useNamingConvention: snake_case is the server wire format
|
||||
body: { name: "from-tag", from_branch: "base", from_version: 3 },
|
||||
});
|
||||
});
|
||||
|
||||
it("sends FTS options to remote tables", async () => {
|
||||
let createIndexBody: Record<string, unknown> | undefined;
|
||||
|
||||
|
||||
@@ -4020,6 +4020,123 @@ describe("when dealing with tags", () => {
|
||||
await table.add([{ id: 3n, vector: [0.5, 0.6] }]);
|
||||
expect(await table.countRows()).toBe(2);
|
||||
});
|
||||
|
||||
it("defaults create version to the handle's visible version", async () => {
|
||||
const conn = await connect(tmpDir.name, {
|
||||
readConsistencyInterval: 0,
|
||||
});
|
||||
const table = await conn.createTable("my_table", [{ id: 1 }]);
|
||||
await table.add([{ id: 2 }]);
|
||||
const tags = await table.tags();
|
||||
|
||||
await tags.create("live");
|
||||
expect(await tags.getVersion("live")).toBe(2);
|
||||
|
||||
await table.checkout(1);
|
||||
await tags.create("pinned");
|
||||
expect(await tags.getVersion("pinned")).toBe(1);
|
||||
|
||||
// An explicit version is independent of the version this handle shows.
|
||||
await tags.create("explicit", 2);
|
||||
expect(await tags.getVersion("explicit")).toBe(2);
|
||||
|
||||
// A tag checkout is still a visible version, not "latest".
|
||||
await table.checkoutLatest();
|
||||
await table.add([{ id: 3 }]);
|
||||
expect(await table.version()).toBe(3);
|
||||
await table.checkout("live");
|
||||
await tags.create("tag-checkout");
|
||||
expect(await tags.getVersion("tag-checkout")).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when dealing with branches", () => {
|
||||
let tmpDir: tmp.DirResult;
|
||||
beforeEach(() => {
|
||||
tmpDir = tmp.dirSync({ unsafeCleanup: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
tmpDir.removeCallback();
|
||||
});
|
||||
|
||||
it("forks from a tag on a branch with the same version as main", async () => {
|
||||
const conn = await connect(tmpDir.name, {
|
||||
readConsistencyInterval: 0,
|
||||
});
|
||||
const table = await conn.createTable("my_table", [{ i: 0 }]);
|
||||
const branches = await table.branches();
|
||||
|
||||
const exp = await branches.create("exp");
|
||||
await exp.add([{ i: 10 }]);
|
||||
const expVersion = await exp.version();
|
||||
await (await exp.tags()).create("exp-v2", expVersion);
|
||||
|
||||
// main reaches the same numeric version with different rows.
|
||||
await table.add([{ i: 100 }]);
|
||||
expect(await table.version()).toBe(expVersion);
|
||||
|
||||
const fromTag = await branches.create("from-tag", {
|
||||
fromTag: "exp-v2",
|
||||
});
|
||||
expect(fromTag.currentBranch()).toBe("from-tag");
|
||||
expect(await fromTag.countRows("i = 10")).toBe(1);
|
||||
expect(await fromTag.countRows("i = 100")).toBe(0);
|
||||
|
||||
// The existing positional branch/version path keeps its ordering.
|
||||
const positional = await branches.create("from-exp", "exp", expVersion);
|
||||
expect(positional.currentBranch()).toBe("from-exp");
|
||||
expect(await positional.countRows("i = 10")).toBe(1);
|
||||
expect(await positional.countRows("i = 100")).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects fromTag combined with another source before main normalization", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await conn.createTable("my_table", [{ i: 0 }]);
|
||||
await (await table.tags()).create("baseline");
|
||||
const branches = await table.branches();
|
||||
|
||||
// fromRef="main" must not normalize the conflict away.
|
||||
const mixedSources = { fromTag: "baseline", fromRef: "main" };
|
||||
await expect(branches.create("conflict", mixedSources)).rejects.toThrow(
|
||||
"fromTag cannot be combined",
|
||||
);
|
||||
|
||||
// JavaScript callers can still pass the legacy version position.
|
||||
const createWithLegacyVersion = branches.create.bind(branches) as (
|
||||
name: string,
|
||||
options: { fromTag: string },
|
||||
fromVersion: number,
|
||||
) => Promise<Table>;
|
||||
await expect(
|
||||
createWithLegacyVersion("conflict", { fromTag: "baseline" }, 1),
|
||||
).rejects.toThrow("fromTag cannot be combined");
|
||||
expect(await branches.list()).not.toHaveProperty("conflict");
|
||||
});
|
||||
|
||||
it("hints at fromTag only for a missing Embedded branch", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await conn.createTable("my_table", [{ i: 0 }]);
|
||||
const branches = await table.branches();
|
||||
const base = await branches.create("base");
|
||||
await base.add([{ i: 1 }]);
|
||||
await (await table.tags()).create("baseline");
|
||||
|
||||
// A tag passed through fromRef keeps the original failure and gains a
|
||||
// static hint without probing the ref again.
|
||||
await expect(branches.create("missing", "baseline")).rejects.toThrow(
|
||||
'branches.create("missing", { fromTag: "baseline" })',
|
||||
);
|
||||
|
||||
// A missing version is not an unresolved branch, so it gets no hint.
|
||||
const missingVersion = await branches
|
||||
.create("missing-version", "base", 9999)
|
||||
.then(
|
||||
() => undefined,
|
||||
(error: Error) => error,
|
||||
);
|
||||
expect(missingVersion?.message).toContain("9999");
|
||||
expect(missingVersion?.message).not.toContain("fromTag");
|
||||
});
|
||||
});
|
||||
|
||||
/** Returns a Date strictly later than every instant observed before the call. */
|
||||
|
||||
@@ -164,6 +164,7 @@ export {
|
||||
FunctionColumnStatus,
|
||||
FunctionColumnVersionStatus,
|
||||
Branches,
|
||||
CreateBranchOptions,
|
||||
BranchColumnSummary,
|
||||
BranchColumnChange,
|
||||
BranchIndexSummary,
|
||||
|
||||
+51
-1
@@ -2297,6 +2297,17 @@ export interface CherryPickResult {
|
||||
mainVersionAfter?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for creating a branch from a named source.
|
||||
*/
|
||||
export interface CreateBranchOptions {
|
||||
/**
|
||||
* Tag to fork from. The tag keeps the branch and version it points to.
|
||||
* Cannot be combined with `fromRef` or `fromVersion`.
|
||||
*/
|
||||
fromTag: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Branch manager for a {@link Table}.
|
||||
*
|
||||
@@ -2319,6 +2330,18 @@ export class Branches {
|
||||
return await this.#inner.list();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a branch from a tag and return a handle scoped to it.
|
||||
*
|
||||
* @param name Name of the new branch.
|
||||
* @param options Named source. `fromTag` keeps the tag's branch and version.
|
||||
* @example
|
||||
* ```typescript
|
||||
* const branches = await table.branches();
|
||||
* const branch = await branches.create("exp", { fromTag: "baseline" });
|
||||
* ```
|
||||
*/
|
||||
async create(name: string, options: CreateBranchOptions): Promise<Table>;
|
||||
/**
|
||||
* Create a branch and return a handle scoped to it.
|
||||
*
|
||||
@@ -2330,8 +2353,35 @@ export class Branches {
|
||||
name: string,
|
||||
fromRef?: string,
|
||||
fromVersion?: number,
|
||||
): Promise<Table>;
|
||||
async create(
|
||||
name: string,
|
||||
fromRefOrOptions?: string | CreateBranchOptions,
|
||||
fromVersion?: number,
|
||||
): Promise<Table> {
|
||||
return new LocalTable(await this.#inner.create(name, fromRef, fromVersion));
|
||||
if (typeof fromRefOrOptions === "object" && fromRefOrOptions !== null) {
|
||||
// The public options shape only adds `fromTag`. Forward any runtime
|
||||
// `fromRef`/`fromVersion` fields so the native check remains the single
|
||||
// authority for rejecting mixed sources before `main` normalization.
|
||||
const options = fromRefOrOptions as CreateBranchOptions & {
|
||||
fromRef?: string;
|
||||
fromVersion?: number;
|
||||
};
|
||||
if (typeof options.fromTag !== "string") {
|
||||
throw new Error("branch source options must include fromTag");
|
||||
}
|
||||
return new LocalTable(
|
||||
await this.#inner.create(
|
||||
name,
|
||||
options.fromRef,
|
||||
fromVersion ?? options.fromVersion,
|
||||
options.fromTag,
|
||||
),
|
||||
);
|
||||
}
|
||||
return new LocalTable(
|
||||
await this.#inner.create(name, fromRefOrOptions, fromVersion),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+69
-10
@@ -20,7 +20,7 @@ use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
|
||||
use napi_derive::napi;
|
||||
|
||||
use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable};
|
||||
use crate::error::NapiErrorExt;
|
||||
use crate::error::{NapiErrorExt, convert_error};
|
||||
use crate::index::Index;
|
||||
use crate::job::JobFailureInfo;
|
||||
use crate::merge::NativeMergeInsertBuilder;
|
||||
@@ -2393,6 +2393,15 @@ pub struct BranchContents {
|
||||
pub manifest_size: i64,
|
||||
}
|
||||
|
||||
fn from_tag_hint(name: &str, tag: &str) -> String {
|
||||
let name_literal = serde_json::Value::String(name.to_string()).to_string();
|
||||
let tag_literal = serde_json::Value::String(tag.to_string()).to_string();
|
||||
format!(
|
||||
"If {tag_literal} is a tag, use branches.create({name_literal}, {{ fromTag: {tag_literal} }}) instead of fromRef."
|
||||
)
|
||||
}
|
||||
|
||||
/// Tags label table versions with human-readable names.
|
||||
#[napi]
|
||||
pub struct Tags {
|
||||
inner: LanceDbTable,
|
||||
@@ -2431,12 +2440,20 @@ impl Tags {
|
||||
.default_error()
|
||||
}
|
||||
|
||||
/// Create a tag for a table version.
|
||||
///
|
||||
/// Omit `version` to tag the version this handle currently shows,
|
||||
/// including a checked-out version.
|
||||
#[napi]
|
||||
pub async unsafe fn create(&mut self, tag: String, version: i64) -> napi::Result<()> {
|
||||
pub async unsafe fn create(&mut self, tag: String, version: Option<i64>) -> napi::Result<()> {
|
||||
let version = match version {
|
||||
Some(version) => version as u64,
|
||||
None => self.inner.version().await.default_error()?,
|
||||
};
|
||||
let mut rust_tags = self.inner.tags().await.default_error()?;
|
||||
rust_tags
|
||||
.as_mut()
|
||||
.create(tag.as_str(), version as u64)
|
||||
.create(tag.as_str(), version)
|
||||
.await
|
||||
.default_error()
|
||||
}
|
||||
@@ -2494,7 +2511,18 @@ impl Branches {
|
||||
name: String,
|
||||
from_ref: Option<String>,
|
||||
from_version: Option<i64>,
|
||||
from_tag: Option<String>,
|
||||
) -> napi::Result<Table> {
|
||||
if from_tag.is_some() && (from_ref.is_some() || from_version.is_some()) {
|
||||
return Err(napi::Error::from_reason(
|
||||
"fromTag cannot be combined with fromRef or fromVersion; pass only one source",
|
||||
));
|
||||
}
|
||||
let from_branch = if from_tag.is_none() {
|
||||
from_ref.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let from_ref = from_ref.filter(|b| b != "main");
|
||||
let from_version = from_version
|
||||
.map(|v| {
|
||||
@@ -2503,13 +2531,27 @@ impl Branches {
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let from = Ref::Version(from_ref, from_version);
|
||||
let table = self
|
||||
.inner
|
||||
.create_branch(&name, from)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(Table::new(table))
|
||||
let from = match from_tag {
|
||||
Some(tag) => Ref::Tag(tag),
|
||||
None => Ref::Version(from_ref, from_version),
|
||||
};
|
||||
match self.inner.create_branch(&name, from).await {
|
||||
Ok(table) => Ok(Table::new(table)),
|
||||
Err(error) => {
|
||||
// A missing branch is a native NotFound. A missing version is
|
||||
// VersionNotFound, and an Enterprise 404 is an ambiguous
|
||||
// TableNotFound, so only the native branch case gets the hint.
|
||||
let missing_branch = matches!(
|
||||
&error,
|
||||
lancedb::Error::Lance { source } if source.is_not_found()
|
||||
);
|
||||
let mut error = convert_error(&error);
|
||||
if missing_branch && let Some(branch) = from_branch.as_deref() {
|
||||
error.reason = format!("{}\n{}", error.reason, from_tag_hint(&name, branch));
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
@@ -2557,3 +2599,20 @@ impl Branches {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::from_tag_hint;
|
||||
|
||||
#[test]
|
||||
fn from_tag_hint_uses_escaped_javascript_string_literals() {
|
||||
assert_eq!(
|
||||
from_tag_hint("exp", "baseline"),
|
||||
r#"If "baseline" is a tag, use branches.create("exp", { fromTag: "baseline" }) instead of fromRef."#
|
||||
);
|
||||
assert_eq!(
|
||||
from_tag_hint("branch\"name\\path", "tag\"name\\path"),
|
||||
r#"If "tag\"name\\path" is a tag, use branches.create("branch\"name\\path", { fromTag: "tag\"name\\path" }) instead of fromRef."#
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user