diff --git a/docs/src/js/classes/Branches.md b/docs/src/js/classes/Branches.md
index 6680fbfee..4e154e30f 100644
--- a/docs/src/js/classes/Branches.md
+++ b/docs/src/js/classes/Branches.md
@@ -64,6 +64,35 @@ with `status: "failed"` instead of throwing.
### create()
+#### create(name, options)
+
+```ts
+create(name, options): Promise
+```
+
+Create a branch from a tag and return a handle scoped to it.
+
+##### Parameters
+
+* **name**: `string`
+ Name of the new branch.
+
+* **options**: [`CreateBranchOptions`](../interfaces/CreateBranchOptions.md)
+ Named source. `fromTag` keeps the tag's branch and version.
+
+##### Returns
+
+`Promise`<[`Table`](Table.md)>
+
+##### Example
+
+```typescript
+const branches = await table.branches();
+const branch = await branches.create("exp", { fromTag: "baseline" });
+```
+
+#### create(name, fromRef, fromVersion)
+
```ts
create(
name,
@@ -73,7 +102,7 @@ create(
Create a branch and return a handle scoped to it.
-#### Parameters
+##### Parameters
* **name**: `string`
Name of the new branch.
@@ -84,7 +113,7 @@ Create a branch and return a handle scoped to it.
* **fromVersion?**: `number`
A specific version on `fromRef`. Defaults to latest.
-#### Returns
+##### Returns
`Promise`<[`Table`](Table.md)>
diff --git a/docs/src/js/classes/Tags.md b/docs/src/js/classes/Tags.md
index 341673b37..dff91dd70 100644
--- a/docs/src/js/classes/Tags.md
+++ b/docs/src/js/classes/Tags.md
@@ -6,6 +6,8 @@
# Class: Tags
+Tags label table versions with human-readable names.
+
## Constructors
### new Tags()
@@ -23,14 +25,19 @@ new Tags(): Tags
### create()
```ts
-create(tag, version): Promise
+create(tag, version?): Promise
```
+Create a tag for a table version.
+
+Omit `version` to tag the version this handle currently shows,
+including a checked-out version.
+
#### Parameters
* **tag**: `string`
-* **version**: `number`
+* **version?**: `null` \| `number`
#### Returns
diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md
index 2aab45c12..83b78f12d 100644
--- a/docs/src/js/globals.md
+++ b/docs/src/js/globals.md
@@ -79,6 +79,7 @@
- [CompactionStats](interfaces/CompactionStats.md)
- [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md)
- [ConnectionOptions](interfaces/ConnectionOptions.md)
+- [CreateBranchOptions](interfaces/CreateBranchOptions.md)
- [CreateNamespaceOptions](interfaces/CreateNamespaceOptions.md)
- [CreateNamespaceResponse](interfaces/CreateNamespaceResponse.md)
- [CreateTableOptions](interfaces/CreateTableOptions.md)
diff --git a/docs/src/js/interfaces/CreateBranchOptions.md b/docs/src/js/interfaces/CreateBranchOptions.md
new file mode 100644
index 000000000..2cfb3406d
--- /dev/null
+++ b/docs/src/js/interfaces/CreateBranchOptions.md
@@ -0,0 +1,20 @@
+[**@lancedb/lancedb**](../README.md) • **Docs**
+
+***
+
+[@lancedb/lancedb](../globals.md) / CreateBranchOptions
+
+# Interface: CreateBranchOptions
+
+Options for creating a branch from a named source.
+
+## Properties
+
+### fromTag
+
+```ts
+fromTag: string;
+```
+
+Tag to fork from. The tag keeps the branch and version it points to.
+Cannot be combined with `fromRef` or `fromVersion`.
diff --git a/docs/web-tests/ts/tables.test.ts b/docs/web-tests/ts/tables.test.ts
index 16fa4545c..c4a81189d 100644
--- a/docs/web-tests/ts/tables.test.ts
+++ b/docs/web-tests/ts/tables.test.ts
@@ -853,7 +853,8 @@ test("versioning snippets (async)", async () => {
// Create a tag pointing at a specific version
await tags.create("baseline", 1);
- await tags.create("with-edits", await tagsTable.version());
+ // Omit version to tag the version this handle currently shows.
+ await tags.create("with-edits");
// List all tags on this table
console.log(await tags.list());
@@ -868,12 +869,16 @@ test("versioning snippets (async)", async () => {
await tagsTable.checkout("baseline");
console.log(await tagsTable.version());
+ // A checked-out handle tags the older version it shows, not the latest.
+ await tags.create("baseline-checkout");
+
// Delete a tag (does not delete the underlying version)
await tags.delete("with-edits");
// Return to the latest version
await tagsTable.checkoutLatest();
// --8<-- [end:versioning_tags]
+ expect(await tags.getVersion("baseline-checkout")).toBe(2);
expect(await tagsTable.version()).toBe(3);
const remainingTags = await tags.list();
expect(remainingTags).toHaveProperty("baseline");
@@ -900,8 +905,18 @@ test("branch snippets (async)", async () => {
// Fork an isolated, writable branch from main's latest version.
// `create` returns a table handle scoped to the new branch.
const branch = await branches.create("exp");
+
+ // Fork from a tag. Pass `{ fromTag }` as the second argument; it cannot be
+ // combined with `fromRef` or `fromVersion`.
+ await (await table.tags()).create("baseline", 1);
+ const tagBranch = await branches.create("exp-from-tag", {
+ fromTag: "baseline",
+ });
// --8<-- [end:branch_create]
+ expect(tagBranch.currentBranch()).toBe("exp-from-tag");
+ expect(await tagBranch.countRows()).toBe(3);
+
// --8<-- [start:branch_write]
// Writes land on the branch handle only; main is left untouched.
await branch.add([{ id: 4, author: "Lancelot", quote: "For the realm!" }]);
@@ -928,6 +943,7 @@ test("branch snippets (async)", async () => {
// Delete the branch and its branch-local history. Data on main is safe.
await branches.delete("exp");
// --8<-- [end:branch_delete]
+ await branches.delete("exp-from-tag");
expect(await table.countRows()).toBe(3);
expect(await branches.list()).not.toHaveProperty("exp");
diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx
index 14c1a9fc2..45f94846a 100644
--- a/docs/web/management/table.mdx
+++ b/docs/web/management/table.mdx
@@ -1742,10 +1742,10 @@ page).
The tags API supports the standard CRUD operations (create, list, update, delete),
plus checking out by tag name.
-In Python, `tags.create()` accepts an optional `version`. If you omit it, the
-tag uses the version the table handle currently shows. That includes a handle
-checked out to an older version, so pass `version` explicitly when the tag must
-not depend on the handle's checkout state.
+In Python and TypeScript, `tags.create()` accepts an optional `version`. If you
+omit it, the tag uses the version the table handle currently shows. That includes
+a handle checked out to an older version, so pass `version` explicitly when the
+tag must not depend on the handle's checkout state.
diff --git a/docs/web/snippets/tables.mdx b/docs/web/snippets/tables.mdx
index ecbdc71c9..c68c2a414 100644
--- a/docs/web/snippets/tables.mdx
+++ b/docs/web/snippets/tables.mdx
@@ -162,7 +162,7 @@ export const TsAlterColumnsWithExpression = "// For custom transforms, create a
export const TsAlterVectorColumn = "const oldDim = 384;\nconst newDim = 1024;\nconst vectorSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\n \"embedding\",\n new arrow.FixedSizeList(\n oldDim,\n new arrow.Field(\"item\", new arrow.Float16(), true),\n ),\n true,\n ),\n]);\nconst vectorData = lancedb.makeArrowTable(\n [{ id: 1, embedding: Array.from({ length: oldDim }, () => Math.random()) }],\n { schema: vectorSchema },\n);\nconst vectorTable = await db.createTable(\"vector_alter_example\", vectorData, {\n mode: \"overwrite\",\n});\n\n// Changing FixedSizeList dimensions (384 -> 1024) is not supported via alterColumns.\n// Use addColumns + dropColumns + alterColumns(rename) to replace the column.\nawait vectorTable.addColumns([\n {\n name: \"embedding_v2\",\n valueSql: `arrow_cast(NULL, 'FixedSizeList(${newDim}, Float16)')`,\n },\n]);\nawait vectorTable.dropColumns([\"embedding\"]);\nawait vectorTable.alterColumns([{ path: \"embedding_v2\", rename: \"embedding\" }]);\n";
-export const TsBranchCreate = "// Fork an isolated, writable branch from main's latest version.\n// `create` returns a table handle scoped to the new branch.\nconst branch = await branches.create(\"exp\");\n";
+export const TsBranchCreate = "// Fork an isolated, writable branch from main's latest version.\n// `create` returns a table handle scoped to the new branch.\nconst branch = await branches.create(\"exp\");\n\n// Fork from a tag. Pass `{ fromTag }` as the second argument; it cannot be\n// combined with `fromRef` or `fromVersion`.\nawait (await table.tags()).create(\"baseline\", 1);\nconst tagBranch = await branches.create(\"exp-from-tag\", {\n fromTag: \"baseline\",\n});\n";
export const TsBranchDelete = "// Delete the branch and its branch-local history. Data on main is safe.\nawait branches.delete(\"exp\");\n";
@@ -250,7 +250,7 @@ export const TsVersioningListAllVersions = "const allVersions = await table.list
export const TsVersioningRollback = "await table.checkout(versionAfterMod);\nawait table.restore();\nconst versionsAfterRollback = await table.listVersions();\nconst versionCountAfterRollback = versionsAfterRollback.length;\nconsole.log(\n `Total number of versions after rollback: ${versionCountAfterRollback}`,\n);\n";
-export const TsVersioningTags = "const tags = await tagsTable.tags();\n\n// Create a tag pointing at a specific version\nawait tags.create(\"baseline\", 1);\nawait tags.create(\"with-edits\", await tagsTable.version());\n\n// List all tags on this table\nconsole.log(await tags.list());\n\n// Look up the version a tag points at\nconsole.log(await tags.getVersion(\"baseline\"));\n\n// Move an existing tag to a different version\nawait tags.update(\"baseline\", 2);\n\n// Check out a version by tag name\nawait tagsTable.checkout(\"baseline\");\nconsole.log(await tagsTable.version());\n\n// Delete a tag (does not delete the underlying version)\nawait tags.delete(\"with-edits\");\n\n// Return to the latest version\nawait tagsTable.checkoutLatest();\n";
+export const TsVersioningTags = "const tags = await tagsTable.tags();\n\n// Create a tag pointing at a specific version\nawait tags.create(\"baseline\", 1);\n// Omit version to tag the version this handle currently shows.\nawait tags.create(\"with-edits\");\n\n// List all tags on this table\nconsole.log(await tags.list());\n\n// Look up the version a tag points at\nconsole.log(await tags.getVersion(\"baseline\"));\n\n// Move an existing tag to a different version\nawait tags.update(\"baseline\", 2);\n\n// Check out a version by tag name\nawait tagsTable.checkout(\"baseline\");\nconsole.log(await tagsTable.version());\n\n// A checked-out handle tags the older version it shows, not the latest.\nawait tags.create(\"baseline-checkout\");\n\n// Delete a tag (does not delete the underlying version)\nawait tags.delete(\"with-edits\");\n\n// Return to the latest version\nawait tagsTable.checkoutLatest();\n";
export const TsVersioningUpdateData = "await table.update({\n where: \"author = 'Richard'\",\n values: { author: \"Richard Daniel Sanchez\" },\n});\nconst rowsAfterUpdate = await table.countRows(\n \"author = 'Richard Daniel Sanchez'\",\n);\nconsole.log(`Rows updated to Richard Daniel Sanchez: ${rowsAfterUpdate}`);\n";
diff --git a/docs/web/tables/branching.mdx b/docs/web/tables/branching.mdx
index 9edd7c669..dea021bab 100644
--- a/docs/web/tables/branching.mdx
+++ b/docs/web/tables/branching.mdx
@@ -130,9 +130,10 @@ Forking from `main` returns a table handle scoped to the new branch. `main` is
the reserved default source, so `create` needs only a name. To fork from another
branch, pass `from_ref`, optionally with `from_version`. In Python, use
keyword-only `from_tag` to fork from a tag; it cannot be combined with
-`from_ref` or `from_version`. In Rust, pass `Ref::Tag` to `create_branch`. A
-tag carries its own branch and version, so the tag source forks from that exact
-snapshot.
+`from_ref` or `from_version`. In TypeScript, pass `{ fromTag }` as the second
+argument to `create`; it cannot be combined with `fromRef` or `fromVersion`. In
+Rust, pass `Ref::Tag` to `create_branch`. A tag carries its own branch and
+version, so the tag source forks from that exact snapshot.
diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts
index eccfb9ffd..0ae189b0a 100644
--- a/nodejs/__test__/remote.test.ts
+++ b/nodejs/__test__/remote.test.ts
@@ -1382,6 +1382,111 @@ describe("remote connection", () => {
);
});
+ it("forks Enterprise branches from tags and defaults tag versions", async () => {
+ const requests: { path: string; body: Record }[] = [];
+ 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 | undefined;
diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts
index 7aac3864c..a8bec5c98 100644
--- a/nodejs/__test__/table.test.ts
+++ b/nodejs/__test__/table.test.ts
@@ -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;
+ 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. */
diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts
index aa51c2b56..ac138aa1e 100644
--- a/nodejs/lancedb/index.ts
+++ b/nodejs/lancedb/index.ts
@@ -164,6 +164,7 @@ export {
FunctionColumnStatus,
FunctionColumnVersionStatus,
Branches,
+ CreateBranchOptions,
BranchColumnSummary,
BranchColumnChange,
BranchIndexSummary,
diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts
index eecb83fb6..f328a844f 100644
--- a/nodejs/lancedb/table.ts
+++ b/nodejs/lancedb/table.ts
@@ -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;
/**
* Create a branch and return a handle scoped to it.
*
@@ -2330,8 +2353,35 @@ export class Branches {
name: string,
fromRef?: string,
fromVersion?: number,
+ ): Promise;
+ async create(
+ name: string,
+ fromRefOrOptions?: string | CreateBranchOptions,
+ fromVersion?: number,
): Promise {
- 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),
+ );
}
/**
diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs
index 1a4c3e91c..6eff43c5a 100644
--- a/nodejs/src/table.rs
+++ b/nodejs/src/table.rs
@@ -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) -> 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,
from_version: Option,
+ from_tag: Option,
) -> napi::Result {
+ 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."#
+ );
+ }
+}