mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(nodejs): add table delta streams
Expose the Embedded Table.delta contract through NAPI and the TypeScript wrapper. Accept exact bigint, safe-number, or same-branch tag refs; return bigint endpoints and transaction read versions; stream four row readers with schemas and reusable Arrow iterators; preserve remote unsupported and keep the abstract Table default for custom subclasses.
This commit is contained in:
@@ -552,6 +552,41 @@ containing the new version number of the table
|
||||
|
||||
***
|
||||
|
||||
### delta()
|
||||
|
||||
```ts
|
||||
delta(fromVersion, toVersion?): Promise<TableDelta>
|
||||
```
|
||||
|
||||
Compare two persisted versions or same-branch tags on an Embedded table.
|
||||
|
||||
`fromVersion` is exclusive and `toVersion` is inclusive. Omitting
|
||||
`toVersion` uses the version currently visible through this handle,
|
||||
including a checked-out version. The endpoints are fixed when the delta is
|
||||
created.
|
||||
|
||||
Row readers require stable row IDs at both endpoints. Create the table with
|
||||
`storageOptions: { new_table_enable_stable_row_ids: "true" }` to enable
|
||||
them. `listTransactions()` works without stable row IDs.
|
||||
|
||||
Row readers reject ranges containing a Restore, or ranges whose transaction
|
||||
history cannot prove they are restore-free. Recompute the checkpoint with a
|
||||
full rescan and reinitialize it at the range end version.
|
||||
|
||||
LanceDB Enterprise tables reject this operation.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **fromVersion**: [`DeltaVersion`](../type-aliases/DeltaVersion.md)
|
||||
|
||||
* **toVersion?**: [`DeltaVersion`](../type-aliases/DeltaVersion.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`TableDelta`](TableDelta.md)>
|
||||
|
||||
***
|
||||
|
||||
### disableRTE()
|
||||
|
||||
```ts
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / TableDelta
|
||||
|
||||
# Class: TableDelta
|
||||
|
||||
A handle for reading changes between two pinned table versions.
|
||||
|
||||
Created by [Table.delta](Table.md#delta). Endpoints are fixed at creation; later writes
|
||||
or tag moves do not change this delta.
|
||||
|
||||
## Accessors
|
||||
|
||||
### beginVersion
|
||||
|
||||
```ts
|
||||
get beginVersion(): bigint
|
||||
```
|
||||
|
||||
The exclusive start version, as an exact u64 bigint.
|
||||
|
||||
#### Returns
|
||||
|
||||
`bigint`
|
||||
|
||||
***
|
||||
|
||||
### endVersion
|
||||
|
||||
```ts
|
||||
get endVersion(): bigint
|
||||
```
|
||||
|
||||
The inclusive end version, as an exact u64 bigint.
|
||||
|
||||
#### Returns
|
||||
|
||||
`bigint`
|
||||
|
||||
## Methods
|
||||
|
||||
### deletedRowIds()
|
||||
|
||||
```ts
|
||||
deletedRowIds(): TableDeltaReader
|
||||
```
|
||||
|
||||
Stream deleted row IDs. Each batch has one `_rowid: uint64` column.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`TableDeltaReader`](../interfaces/TableDeltaReader.md)
|
||||
|
||||
***
|
||||
|
||||
### insertedRows()
|
||||
|
||||
```ts
|
||||
insertedRows(): TableDeltaReader
|
||||
```
|
||||
|
||||
Stream rows inserted in `(beginVersion, endVersion]`.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`TableDeltaReader`](../interfaces/TableDeltaReader.md)
|
||||
|
||||
***
|
||||
|
||||
### listTransactions()
|
||||
|
||||
```ts
|
||||
listTransactions(): Promise<TableDeltaTransaction[]>
|
||||
```
|
||||
|
||||
List readable transactions committed in `(beginVersion, endVersion]`.
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`TableDeltaTransaction`](../interfaces/TableDeltaTransaction.md)[]>
|
||||
|
||||
***
|
||||
|
||||
### updatedRows()
|
||||
|
||||
```ts
|
||||
updatedRows(): TableDeltaReader
|
||||
```
|
||||
|
||||
Stream rows updated in `(beginVersion, endVersion]`.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`TableDeltaReader`](../interfaces/TableDeltaReader.md)
|
||||
|
||||
***
|
||||
|
||||
### upsertedRows()
|
||||
|
||||
```ts
|
||||
upsertedRows(): TableDeltaReader
|
||||
```
|
||||
|
||||
Stream inserted and updated rows in `(beginVersion, endVersion]`.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`TableDeltaReader`](../interfaces/TableDeltaReader.md)
|
||||
@@ -49,6 +49,7 @@
|
||||
- [Session](classes/Session.md)
|
||||
- [StaticHeaderProvider](classes/StaticHeaderProvider.md)
|
||||
- [Table](classes/Table.md)
|
||||
- [TableDelta](classes/TableDelta.md)
|
||||
- [TagContents](classes/TagContents.md)
|
||||
- [Tags](classes/Tags.md)
|
||||
- [TakeQuery](classes/TakeQuery.md)
|
||||
@@ -158,6 +159,8 @@
|
||||
- [SplitRandomOptions](interfaces/SplitRandomOptions.md)
|
||||
- [SplitSequentialOptions](interfaces/SplitSequentialOptions.md)
|
||||
- [SsTableStats](interfaces/SsTableStats.md)
|
||||
- [TableDeltaReader](interfaces/TableDeltaReader.md)
|
||||
- [TableDeltaTransaction](interfaces/TableDeltaTransaction.md)
|
||||
- [TableNamesOptions](interfaces/TableNamesOptions.md)
|
||||
- [TableShardStats](interfaces/TableShardStats.md)
|
||||
- [TableStatistics](interfaces/TableStatistics.md)
|
||||
@@ -189,6 +192,7 @@
|
||||
- [Data](type-aliases/Data.md)
|
||||
- [DataLike](type-aliases/DataLike.md)
|
||||
- [DataTypeLike](type-aliases/DataTypeLike.md)
|
||||
- [DeltaVersion](type-aliases/DeltaVersion.md)
|
||||
- [ExprLike](type-aliases/ExprLike.md)
|
||||
- [FieldLike](type-aliases/FieldLike.md)
|
||||
- [IntoSql](type-aliases/IntoSql.md)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / TableDeltaReader
|
||||
|
||||
# Interface: TableDeltaReader
|
||||
|
||||
A streaming table-delta reader.
|
||||
|
||||
`schema()` is available before consuming the stream, including when the
|
||||
range is empty. The stream yields Arrow record batches without
|
||||
materializing the full result.
|
||||
|
||||
## Extends
|
||||
|
||||
- `AsyncIterable`<`RecordBatch`>
|
||||
|
||||
## Methods
|
||||
|
||||
### \[asyncIterator\]()
|
||||
|
||||
```ts
|
||||
asyncIterator: AsyncIterator<RecordBatch<any>, any, undefined>
|
||||
```
|
||||
|
||||
#### Returns
|
||||
|
||||
`AsyncIterator`<`RecordBatch`<`any`>, `any`, `undefined`>
|
||||
|
||||
#### Inherited from
|
||||
|
||||
`AsyncIterable.[asyncIterator]`
|
||||
|
||||
***
|
||||
|
||||
### schema()
|
||||
|
||||
```ts
|
||||
schema(): Promise<Schema<any>>
|
||||
```
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`Schema`<`any`>>
|
||||
@@ -0,0 +1,51 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / TableDeltaTransaction
|
||||
|
||||
# Interface: TableDeltaTransaction
|
||||
|
||||
A committed transaction in a table delta range.
|
||||
|
||||
## Properties
|
||||
|
||||
### operation
|
||||
|
||||
```ts
|
||||
operation: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### readVersion
|
||||
|
||||
```ts
|
||||
readVersion: bigint;
|
||||
```
|
||||
|
||||
The version the transaction was based on. Exact u64 value.
|
||||
|
||||
***
|
||||
|
||||
### tag?
|
||||
|
||||
```ts
|
||||
optional tag: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### transactionProperties?
|
||||
|
||||
```ts
|
||||
optional transactionProperties: Record<string, string>;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### uuid
|
||||
|
||||
```ts
|
||||
uuid: string;
|
||||
```
|
||||
@@ -0,0 +1,17 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / DeltaVersion
|
||||
|
||||
# Type Alias: DeltaVersion
|
||||
|
||||
```ts
|
||||
type DeltaVersion: number | bigint | string;
|
||||
```
|
||||
|
||||
One endpoint of a table delta: a positive version number/bigint or a tag on
|
||||
the table handle's current branch.
|
||||
|
||||
Use a `bigint` when the version may exceed `Number.MAX_SAFE_INTEGER`.
|
||||
Strings are always tags.
|
||||
@@ -309,6 +309,9 @@ describe("remote connection", () => {
|
||||
},
|
||||
async (db) => {
|
||||
const table = (await db.openTable("test")) as LocalTable;
|
||||
await expect(table.delta(1)).rejects.toThrow(
|
||||
"table.delta is only supported on LanceDB Embedded tables",
|
||||
);
|
||||
const cases: [() => Promise<unknown>, string][] = [
|
||||
[() => table.usesV2ManifestPaths(), "uses_v2_manifest_paths"],
|
||||
[() => table.migrateManifestPathsV2(), "migrate_manifest_paths_v2"],
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
PhraseQuery,
|
||||
Query,
|
||||
Table,
|
||||
TableDeltaReader,
|
||||
VectorQuery,
|
||||
blob,
|
||||
connect,
|
||||
@@ -4139,6 +4140,180 @@ describe("when dealing with branches", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when dealing with table delta", () => {
|
||||
let tmpDir: tmp.DirResult;
|
||||
// biome-ignore lint/style/useNamingConvention: storage option wire format
|
||||
const stableRowIds = { new_table_enable_stable_row_ids: "true" };
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = tmp.dirSync({ unsafeCleanup: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
tmpDir.removeCallback();
|
||||
});
|
||||
|
||||
async function readDelta(
|
||||
reader: TableDeltaReader,
|
||||
): Promise<arrow.RecordBatch[]> {
|
||||
const batches: arrow.RecordBatch[] = [];
|
||||
for await (const batch of reader) {
|
||||
batches.push(batch);
|
||||
}
|
||||
return batches;
|
||||
}
|
||||
|
||||
function deltaColumn(batches: arrow.RecordBatch[], name: string): unknown[] {
|
||||
return batches.flatMap((batch) => batch.getChild(name)?.toJSON() ?? []);
|
||||
}
|
||||
|
||||
it("streams rows, transactions, and empty schemas", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await conn.createTable(
|
||||
"delta_rows",
|
||||
[
|
||||
{ id: 1, value: 0 },
|
||||
{ id: 2, value: 0 },
|
||||
],
|
||||
{ mode: "overwrite", storageOptions: stableRowIds },
|
||||
);
|
||||
const tags = await table.tags();
|
||||
await tags.create("baseline", await table.version());
|
||||
await table.add([{ id: 3, value: 0 }]);
|
||||
await table.update({ where: "id = 1", values: { value: 10 } });
|
||||
await table.delete("id = 2");
|
||||
|
||||
const delta = await table.delta("baseline", 4n);
|
||||
expect(delta.beginVersion).toBe(1n);
|
||||
expect(delta.endVersion).toBe(4n);
|
||||
|
||||
const insertedReader = delta.insertedRows();
|
||||
expect(
|
||||
(await insertedReader.schema()).fields.map((field) => field.name),
|
||||
).toEqual([
|
||||
"id",
|
||||
"value",
|
||||
"_rowid",
|
||||
"_row_created_at_version",
|
||||
"_row_last_updated_at_version",
|
||||
]);
|
||||
const inserted = await readDelta(insertedReader);
|
||||
expect(deltaColumn(inserted, "id")).toEqual([3]);
|
||||
|
||||
const updated = await readDelta(delta.updatedRows());
|
||||
expect(deltaColumn(updated, "id")).toEqual([1]);
|
||||
const upserted = await readDelta(delta.upsertedRows());
|
||||
expect((deltaColumn(upserted, "id") as number[]).sort()).toEqual([1, 3]);
|
||||
|
||||
const deleted = await readDelta(delta.deletedRowIds());
|
||||
expect(deleted).toHaveLength(1);
|
||||
expect(deleted[0].schema.fields.map((field) => field.name)).toEqual([
|
||||
"_rowid",
|
||||
]);
|
||||
const deletedIds = deltaColumn(deleted, "_rowid");
|
||||
expect(deletedIds).toHaveLength(1);
|
||||
expect(typeof deletedIds[0]).toBe("bigint");
|
||||
|
||||
const transactions = await delta.listTransactions();
|
||||
expect(transactions.map((tx) => tx.operation)).toEqual([
|
||||
"Append",
|
||||
"Update",
|
||||
"Delete",
|
||||
]);
|
||||
expect(transactions.map((tx) => tx.readVersion)).toEqual([1n, 2n, 3n]);
|
||||
expect(transactions.every((tx) => typeof tx.readVersion === "bigint")).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// Early drop after the first batch must not throw or force the rest of the
|
||||
// stream to materialize.
|
||||
let batchesSeen = 0;
|
||||
for await (const _batch of delta.upsertedRows()) {
|
||||
batchesSeen += 1;
|
||||
break;
|
||||
}
|
||||
expect(batchesSeen).toBe(1);
|
||||
|
||||
const equal = await table.delta(2, 2);
|
||||
const equalReader = equal.insertedRows();
|
||||
expect(
|
||||
(await equalReader.schema()).fields.map((field) => field.name),
|
||||
).toEqual([
|
||||
"id",
|
||||
"value",
|
||||
"_rowid",
|
||||
"_row_created_at_version",
|
||||
"_row_last_updated_at_version",
|
||||
]);
|
||||
expect(await readDelta(equalReader)).toEqual([]);
|
||||
expect(
|
||||
(await equal.deletedRowIds().schema()).fields.map((field) => field.name),
|
||||
).toEqual(["_rowid"]);
|
||||
expect(await equal.listTransactions()).toEqual([]);
|
||||
});
|
||||
|
||||
it("pins the visible target without moving checkout state", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await conn.createTable("delta_pinned", [{ id: 1 }], {
|
||||
storageOptions: stableRowIds,
|
||||
});
|
||||
await table.add([{ id: 2 }]);
|
||||
await table.update({ where: "id = 1", values: { id: 10 } });
|
||||
|
||||
await table.checkout(2);
|
||||
const pinned = await table.delta(1n);
|
||||
expect(pinned.beginVersion).toBe(1n);
|
||||
expect(pinned.endVersion).toBe(2n);
|
||||
expect(deltaColumn(await readDelta(pinned.insertedRows()), "id")).toEqual([
|
||||
2,
|
||||
]);
|
||||
expect(await table.version()).toBe(2);
|
||||
|
||||
const explicit = await table.delta(1n, 3n);
|
||||
expect(deltaColumn(await readDelta(explicit.updatedRows()), "id")).toEqual([
|
||||
10,
|
||||
]);
|
||||
expect(await table.version()).toBe(2);
|
||||
await table.checkoutLatest();
|
||||
});
|
||||
|
||||
it("rejects invalid endpoints and cross-branch tags", async () => {
|
||||
const conn = await connect(tmpDir.name, { readConsistencyInterval: 0 });
|
||||
const table = await conn.createTable("delta_errors", [{ id: 0 }], {
|
||||
storageOptions: stableRowIds,
|
||||
});
|
||||
await table.add([{ id: 1 }]);
|
||||
const forkVersion = await table.version();
|
||||
|
||||
await expect(table.delta(0)).rejects.toThrow(/positive/);
|
||||
await expect(table.delta(0n)).rejects.toThrow(/positive u64/);
|
||||
await expect(table.delta(1n << 64n)).rejects.toThrow(/u64 bigint/);
|
||||
await expect(table.delta(-1)).rejects.toThrow(/positive/);
|
||||
await expect(table.delta("")).rejects.toThrow(/non-empty/);
|
||||
await expect(table.delta(1.5)).rejects.toThrow(/safe integer/);
|
||||
await expect(table.delta(Number.MAX_SAFE_INTEGER + 1)).rejects.toThrow(
|
||||
/safe integer/,
|
||||
);
|
||||
await expect(table.delta(2, 1)).rejects.toThrow(/newer than/);
|
||||
await expect(table.delta(999)).rejects.toThrow(/does not exist/);
|
||||
await expect(table.delta("missing-tag")).rejects.toThrow(/does not exist/);
|
||||
|
||||
const branch = await (await table.branches()).create("exp");
|
||||
await branch.add([{ id: 2 }]);
|
||||
await table.add([{ id: 100 }]);
|
||||
expect(await branch.version()).toBe(await table.version());
|
||||
await (await table.tags()).create("main-tag", await table.version());
|
||||
await (await branch.tags()).create("exp-tag", await branch.version());
|
||||
|
||||
const sameBranch = await branch.delta(BigInt(forkVersion), "exp-tag");
|
||||
expect(sameBranch.endVersion).toBe(3n);
|
||||
expect(
|
||||
deltaColumn(await readDelta(sameBranch.insertedRows()), "id"),
|
||||
).toEqual([2]);
|
||||
await expect(branch.delta("main-tag")).rejects.toThrow(/branch/i);
|
||||
await expect(table.delta("exp-tag")).rejects.toThrow(/branch/i);
|
||||
});
|
||||
});
|
||||
|
||||
/** Returns a Date strictly later than every instant observed before the call. */
|
||||
async function nextMillisecond(): Promise<Date> {
|
||||
const start = Date.now();
|
||||
@@ -6142,6 +6317,9 @@ describe("Enterprise table overrides", () => {
|
||||
class LegacyTable extends Table {}
|
||||
|
||||
const table = new LegacyTable();
|
||||
await expect(table.delta(1)).rejects.toThrow(
|
||||
"table.delta is only supported on LanceDB Embedded tables",
|
||||
);
|
||||
await expect(table.getTableOverrides()).rejects.toThrow(
|
||||
"getTableOverrides is not supported on this table type",
|
||||
);
|
||||
|
||||
@@ -164,6 +164,10 @@ export {
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableDelta,
|
||||
TableDeltaReader,
|
||||
TableDeltaTransaction,
|
||||
DeltaVersion,
|
||||
FunctionColumnAutoRefreshStatus,
|
||||
FunctionColumnLastRefreshJob,
|
||||
FunctionColumnStatus,
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
Field,
|
||||
IntoVector,
|
||||
MultiVector,
|
||||
RecordBatch,
|
||||
Schema,
|
||||
dataTypeToJson,
|
||||
fromDataToBuffer,
|
||||
@@ -57,7 +58,10 @@ import {
|
||||
IndexConfig,
|
||||
IndexStatistics,
|
||||
JobFailureInfo,
|
||||
RecordBatchIterator as NativeBatchIterator,
|
||||
Branches as NativeBranches,
|
||||
DeltaRef as NativeDeltaRef,
|
||||
TableDelta as NativeTableDelta,
|
||||
OptimizeStats,
|
||||
RTEStats,
|
||||
RefreshColumnOptions,
|
||||
@@ -73,6 +77,7 @@ import {
|
||||
AutoQuery,
|
||||
FullTextQuery,
|
||||
Query,
|
||||
RecordBatchIterator,
|
||||
TakeQuery,
|
||||
VectorQuery,
|
||||
createAutoQuery,
|
||||
@@ -253,6 +258,36 @@ export interface Version {
|
||||
metadata: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One endpoint of a table delta: a positive version number/bigint or a tag on
|
||||
* the table handle's current branch.
|
||||
*
|
||||
* Use a `bigint` when the version may exceed `Number.MAX_SAFE_INTEGER`.
|
||||
* Strings are always tags.
|
||||
*/
|
||||
export type DeltaVersion = number | bigint | string;
|
||||
|
||||
/** A committed transaction in a table delta range. */
|
||||
export interface TableDeltaTransaction {
|
||||
/** The version the transaction was based on. Exact u64 value. */
|
||||
readVersion: bigint;
|
||||
uuid: string;
|
||||
operation: string;
|
||||
tag?: string;
|
||||
transactionProperties?: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A streaming table-delta reader.
|
||||
*
|
||||
* `schema()` is available before consuming the stream, including when the
|
||||
* range is empty. The stream yields Arrow record batches without
|
||||
* materializing the full result.
|
||||
*/
|
||||
export interface TableDeltaReader extends AsyncIterable<RecordBatch> {
|
||||
schema(): Promise<Schema>;
|
||||
}
|
||||
|
||||
/** Token produced by the tokenizer configured on a full-text search index. */
|
||||
export interface FtsToken {
|
||||
/** Token text after tokenizer filters have been applied. */
|
||||
@@ -1349,6 +1384,34 @@ export abstract class Table {
|
||||
* out state and the read_consistency_interval, if any, will apply.
|
||||
*/
|
||||
abstract restore(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Compare two persisted versions or same-branch tags on an Embedded table.
|
||||
*
|
||||
* `fromVersion` is exclusive and `toVersion` is inclusive. Omitting
|
||||
* `toVersion` uses the version currently visible through this handle,
|
||||
* including a checked-out version. The endpoints are fixed when the delta is
|
||||
* created.
|
||||
*
|
||||
* Row readers require stable row IDs at both endpoints. Create the table with
|
||||
* `storageOptions: { new_table_enable_stable_row_ids: "true" }` to enable
|
||||
* them. `listTransactions()` works without stable row IDs.
|
||||
*
|
||||
* Row readers reject ranges containing a Restore, or ranges whose transaction
|
||||
* history cannot prove they are restore-free. Recompute the checkpoint with a
|
||||
* full rescan and reinitialize it at the range end version.
|
||||
*
|
||||
* LanceDB Enterprise tables reject this operation.
|
||||
*/
|
||||
async delta(
|
||||
// biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs
|
||||
fromVersion: DeltaVersion,
|
||||
// biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs
|
||||
toVersion?: DeltaVersion,
|
||||
): Promise<TableDelta> {
|
||||
throw new Error("table.delta is only supported on LanceDB Embedded tables");
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit durable remote cleanup through SQL VACUUM and return after acceptance.
|
||||
* Requires table Ownership and parent Usage. Retention inherits from the table
|
||||
@@ -2087,6 +2150,18 @@ export class LocalTable extends Table {
|
||||
await this.inner.checkoutLatest();
|
||||
}
|
||||
|
||||
async delta(
|
||||
fromVersion: DeltaVersion,
|
||||
toVersion?: DeltaVersion,
|
||||
): Promise<TableDelta> {
|
||||
return new TableDelta(
|
||||
await this.inner.delta(
|
||||
toNativeDeltaRef(fromVersion),
|
||||
toVersion === undefined ? undefined : toNativeDeltaRef(toVersion),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async listVersions(): Promise<Version[]> {
|
||||
return (await this.inner.listVersions()).map((version) => ({
|
||||
version: version.version,
|
||||
@@ -2353,6 +2428,98 @@ export interface CreateBranchOptions {
|
||||
fromTag: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A handle for reading changes between two pinned table versions.
|
||||
*
|
||||
* Created by {@link Table.delta}. Endpoints are fixed at creation; later writes
|
||||
* or tag moves do not change this delta.
|
||||
*/
|
||||
export class TableDelta {
|
||||
readonly #inner: NativeTableDelta;
|
||||
|
||||
/**
|
||||
* Construct a table-delta handle. Internal use only.
|
||||
* @hidden
|
||||
*/
|
||||
constructor(inner: NativeTableDelta) {
|
||||
this.#inner = inner;
|
||||
}
|
||||
|
||||
/** The exclusive start version, as an exact u64 bigint. */
|
||||
get beginVersion(): bigint {
|
||||
return this.#inner.beginVersion();
|
||||
}
|
||||
|
||||
/** The inclusive end version, as an exact u64 bigint. */
|
||||
get endVersion(): bigint {
|
||||
return this.#inner.endVersion();
|
||||
}
|
||||
|
||||
/** Stream rows inserted in `(beginVersion, endVersion]`. */
|
||||
insertedRows(): TableDeltaReader {
|
||||
return tableDeltaReader(this.#inner.insertedRows());
|
||||
}
|
||||
|
||||
/** Stream rows updated in `(beginVersion, endVersion]`. */
|
||||
updatedRows(): TableDeltaReader {
|
||||
return tableDeltaReader(this.#inner.updatedRows());
|
||||
}
|
||||
|
||||
/** Stream inserted and updated rows in `(beginVersion, endVersion]`. */
|
||||
upsertedRows(): TableDeltaReader {
|
||||
return tableDeltaReader(this.#inner.upsertedRows());
|
||||
}
|
||||
|
||||
/** Stream deleted row IDs. Each batch has one `_rowid: uint64` column. */
|
||||
deletedRowIds(): TableDeltaReader {
|
||||
return tableDeltaReader(this.#inner.deletedRowIds());
|
||||
}
|
||||
|
||||
/** List readable transactions committed in `(beginVersion, endVersion]`. */
|
||||
async listTransactions(): Promise<TableDeltaTransaction[]> {
|
||||
const transactions = await this.#inner.listTransactions();
|
||||
return transactions.map((transaction) => ({
|
||||
readVersion: transaction.readVersion,
|
||||
uuid: transaction.uuid,
|
||||
operation: transaction.operation,
|
||||
tag: transaction.tag ?? undefined,
|
||||
transactionProperties: transaction.transactionProperties ?? undefined,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function toNativeDeltaRef(value: DeltaVersion): NativeDeltaRef {
|
||||
if (typeof value === "string") {
|
||||
if (value.length === 0) {
|
||||
throw new Error("delta tag must be a non-empty string");
|
||||
}
|
||||
return { tag: value };
|
||||
}
|
||||
if (typeof value === "bigint") {
|
||||
if (value <= 0n) {
|
||||
throw new Error("delta version must be a positive u64 bigint");
|
||||
}
|
||||
return { version: value };
|
||||
}
|
||||
if (!Number.isSafeInteger(value) || value <= 0) {
|
||||
throw new Error(
|
||||
"delta version must be a positive safe integer; use bigint for larger versions",
|
||||
);
|
||||
}
|
||||
return { version: BigInt(value) };
|
||||
}
|
||||
|
||||
function tableDeltaReader(
|
||||
promisedInner: Promise<NativeBatchIterator>,
|
||||
): TableDeltaReader {
|
||||
return {
|
||||
schema: async () => tableFromIPC((await promisedInner).schema()).schema,
|
||||
[Symbol.asyncIterator](): AsyncIterator<RecordBatch> {
|
||||
return RecordBatchIterator(promisedInner);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Branch manager for a {@link Table}.
|
||||
*
|
||||
|
||||
+137
-2
@@ -2,17 +2,18 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema};
|
||||
use lancedb::table::{
|
||||
AddDataMode, ColumnAlteration as LanceColumnAlteration,
|
||||
AddDataMode, ColumnAlteration as LanceColumnAlteration, DeltaRef as LanceDbDeltaRef,
|
||||
FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken,
|
||||
FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig,
|
||||
FunctionRefreshPodResources as LanceFunctionRefreshPodResources,
|
||||
FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref,
|
||||
Table as LanceDbTable,
|
||||
Table as LanceDbTable, TableDelta as LanceDbTableDelta,
|
||||
};
|
||||
use napi::Env;
|
||||
use napi::bindgen_prelude::*;
|
||||
@@ -22,6 +23,7 @@ use napi_derive::napi;
|
||||
use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable};
|
||||
use crate::error::{NapiErrorExt, convert_error};
|
||||
use crate::index::Index;
|
||||
use crate::iterator::RecordBatchIterator;
|
||||
use crate::job::JobFailureInfo;
|
||||
use crate::merge::NativeMergeInsertBuilder;
|
||||
use crate::query::{Query, TakeQuery, VectorQuery};
|
||||
@@ -126,6 +128,57 @@ impl CompactionOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// One endpoint of a table delta: a positive version or a same-branch tag.
|
||||
#[napi(object)]
|
||||
pub struct DeltaRef {
|
||||
/// A persisted version, expressed as a positive lossless u64 bigint.
|
||||
pub version: Option<BigInt>,
|
||||
/// A tag on the table handle's current branch.
|
||||
pub tag: Option<String>,
|
||||
}
|
||||
|
||||
impl DeltaRef {
|
||||
fn into_delta_ref(self) -> napi::Result<LanceDbDeltaRef> {
|
||||
match (self.version, self.tag) {
|
||||
(Some(version), None) => {
|
||||
let (negative, value, lossless) = version.get_u64();
|
||||
if negative || !lossless {
|
||||
return Err(napi::Error::from_reason(
|
||||
"delta version must be a positive lossless u64 bigint",
|
||||
));
|
||||
}
|
||||
if value == 0 {
|
||||
return Err(napi::Error::from_reason(
|
||||
"delta version must be greater than zero",
|
||||
));
|
||||
}
|
||||
Ok(LanceDbDeltaRef::Version(value))
|
||||
}
|
||||
(None, Some(tag)) => {
|
||||
if tag.is_empty() {
|
||||
return Err(napi::Error::from_reason(
|
||||
"delta tag must be a non-empty string",
|
||||
));
|
||||
}
|
||||
Ok(LanceDbDeltaRef::Tag(tag))
|
||||
}
|
||||
_ => Err(napi::Error::from_reason(
|
||||
"delta reference must contain exactly one of version or tag",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A committed transaction in a table delta range.
|
||||
#[napi(object)]
|
||||
pub struct TableDeltaTransaction {
|
||||
pub read_version: BigInt,
|
||||
pub uuid: String,
|
||||
pub operation: String,
|
||||
pub tag: Option<String>,
|
||||
pub transaction_properties: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub struct Table {
|
||||
// We keep a duplicate of the table name so we can use it for error
|
||||
@@ -955,6 +1008,19 @@ impl Table {
|
||||
self.inner_ref()?.checkout_latest().await.default_error()
|
||||
}
|
||||
|
||||
/// Compare two persisted versions or same-branch tags.
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn delta(
|
||||
&self,
|
||||
from_version: DeltaRef,
|
||||
to_version: Option<DeltaRef>,
|
||||
) -> napi::Result<TableDelta> {
|
||||
let from = from_version.into_delta_ref()?;
|
||||
let to = to_version.map(DeltaRef::into_delta_ref).transpose()?;
|
||||
let delta = self.inner_ref()?.delta(from, to).await.default_error()?;
|
||||
Ok(TableDelta::new(delta))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn list_versions(&self) -> napi::Result<Vec<Version>> {
|
||||
self.inner_ref()?
|
||||
@@ -2434,6 +2500,75 @@ fn from_tag_hint(name: &str, tag: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// A pinned version range with streaming row changes.
|
||||
#[napi]
|
||||
pub struct TableDelta {
|
||||
inner: Arc<LanceDbTableDelta>,
|
||||
}
|
||||
|
||||
impl TableDelta {
|
||||
fn new(inner: LanceDbTableDelta) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(inner),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl TableDelta {
|
||||
#[napi]
|
||||
pub fn begin_version(&self) -> BigInt {
|
||||
BigInt::from(self.inner.begin_version())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn end_version(&self) -> BigInt {
|
||||
BigInt::from(self.inner.end_version())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn inserted_rows(&self) -> napi::Result<RecordBatchIterator> {
|
||||
let stream = self.inner.inserted_rows().await.default_error()?;
|
||||
Ok(RecordBatchIterator::new(stream.into()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn updated_rows(&self) -> napi::Result<RecordBatchIterator> {
|
||||
let stream = self.inner.updated_rows().await.default_error()?;
|
||||
Ok(RecordBatchIterator::new(stream.into()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn upserted_rows(&self) -> napi::Result<RecordBatchIterator> {
|
||||
let stream = self.inner.upserted_rows().await.default_error()?;
|
||||
Ok(RecordBatchIterator::new(stream.into()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn deleted_row_ids(&self) -> napi::Result<RecordBatchIterator> {
|
||||
let stream = self.inner.deleted_row_ids().await.default_error()?;
|
||||
Ok(RecordBatchIterator::new(stream.into()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn list_transactions(&self) -> napi::Result<Vec<TableDeltaTransaction>> {
|
||||
let transactions = self.inner.list_transactions().await.default_error()?;
|
||||
Ok(transactions
|
||||
.into_iter()
|
||||
.map(|transaction| TableDeltaTransaction {
|
||||
read_version: BigInt::from(transaction.read_version),
|
||||
uuid: transaction.uuid,
|
||||
operation: transaction.operation.name().to_string(),
|
||||
tag: transaction.tag,
|
||||
transaction_properties: transaction
|
||||
.transaction_properties
|
||||
.as_ref()
|
||||
.map(|properties| (**properties).clone()),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Tags label table versions with human-readable names.
|
||||
#[napi]
|
||||
pub struct Tags {
|
||||
|
||||
Reference in New Issue
Block a user