mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat: add table.delta for version-to-version row changes (#5135)
Adds native `Table::delta(from_version, to_version=None)` and Python
sync/async `table.delta(...)` for version-to-version row changes.
`TableDelta` exposes streaming `inserted_rows()`, `updated_rows()`,
`upserted_rows()`, `deleted_row_ids()`, and `list_transactions()`.
Endpoints are resolved once on independent dataset handles.
`to_version=None` uses the table handle's visible snapshot, and the
handle's checkout is not changed. Only versions `>= 1` and tags on the
current branch are accepted; cross-branch tags, reversed ranges, version
0, and missing endpoints are rejected. Equal valid endpoints return
empty readers with the same schemas.
Row-level readers require stable row ids at both endpoints and report
the `storage_options={"new_table_enable_stable_row_ids": "true"}`
creation guidance when they are absent. `list_transactions()` does not
require stable row ids.
Row-level readers also fail closed when the range contains a `Restore`,
or when transaction history cannot prove the range is restore-free,
because restored rows can retain older row-version metadata that the
delta readers omit. The error directs consumers to a full rescan and
reinitializing the checkpoint at the range end version.
`list_transactions()` remains available for readable history. The
Versioning guide includes Python and Rust checkpoint-delta examples with
stable-row-ID setup and this Embedded limitation.
Embedded `branches.diff()` remains a separate API.
Refs OSS-2860
This commit is contained in:
@@ -649,6 +649,11 @@ class Table:
|
||||
) -> Job: ...
|
||||
async def list_versions(self) -> List[Dict[str, Any]]: ...
|
||||
async def version(self) -> int: ...
|
||||
async def delta(
|
||||
self,
|
||||
from_version: Union[int, str],
|
||||
to_version: Optional[Union[int, str]] = None,
|
||||
) -> TableDelta: ...
|
||||
async def checkout(self, version: Union[int, str]): ...
|
||||
async def checkout_latest(self): ...
|
||||
async def _checkout_current(self) -> Table: ...
|
||||
@@ -966,6 +971,15 @@ class ColumnOrdering(TypedDict):
|
||||
ascending: bool
|
||||
nulls_first: bool
|
||||
|
||||
class TableDelta:
|
||||
def begin_version(self) -> int: ...
|
||||
def end_version(self) -> int: ...
|
||||
async def inserted_rows(self) -> RecordBatchStream: ...
|
||||
async def updated_rows(self) -> RecordBatchStream: ...
|
||||
async def upserted_rows(self) -> RecordBatchStream: ...
|
||||
async def deleted_row_ids(self) -> RecordBatchStream: ...
|
||||
async def list_transactions(self) -> List[Dict[str, Any]]: ...
|
||||
|
||||
class Query:
|
||||
def where(self, filter: str): ...
|
||||
def where_expr(self, expr: PyExpr): ...
|
||||
|
||||
@@ -85,6 +85,7 @@ from ..table import (
|
||||
IndexStatistics,
|
||||
Query,
|
||||
Table,
|
||||
TableDelta,
|
||||
Tags,
|
||||
)
|
||||
from ..types import BaseTokenizerType, ScalarIndexType
|
||||
@@ -287,6 +288,19 @@ class RemoteTable(Table):
|
||||
"""List all versions of the table"""
|
||||
return LOOP.run(self._table.list_versions())
|
||||
|
||||
def delta(
|
||||
self,
|
||||
from_version: int | str,
|
||||
to_version: Optional[int | str] = None,
|
||||
) -> TableDelta:
|
||||
"""Compare two versions or tags.
|
||||
|
||||
Streamed version deltas are not supported by LanceDB Enterprise tables;
|
||||
this raises ``NotImplementedError``.
|
||||
"""
|
||||
async_delta = LOOP.run(self._table.delta(from_version, to_version))
|
||||
return TableDelta(async_delta._inner)
|
||||
|
||||
def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table:
|
||||
"""to_arrow() is not supported in LanceDB Enterprise."""
|
||||
validate_blob_mode(blob_mode)
|
||||
|
||||
@@ -46,7 +46,7 @@ from ._blob import (
|
||||
validate_blob_mode,
|
||||
)
|
||||
from .types import BlobMode
|
||||
from lancedb.arrow import peek_reader
|
||||
from lancedb.arrow import AsyncRecordBatchReader, peek_reader
|
||||
from lancedb.sql import QueryParameters, to_parameter_batch
|
||||
from lancedb.background_loop import LOOP, embedding_executor
|
||||
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
|
||||
@@ -1598,6 +1598,63 @@ class Table(ABC):
|
||||
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
|
||||
raise NotImplementedError("current_branch is not supported for this table type")
|
||||
|
||||
def delta(
|
||||
self,
|
||||
from_version: int | str,
|
||||
to_version: Optional[int | str] = None,
|
||||
) -> "TableDelta":
|
||||
"""Compare two persisted versions of this table on its current branch.
|
||||
|
||||
``from_version`` is exclusive and ``to_version`` is inclusive. Both
|
||||
accept a version number (starting at 1) or a tag on the current branch.
|
||||
Omitting ``to_version`` uses the version this handle currently sees,
|
||||
including a time-travel checkout. Endpoints are resolved once when this
|
||||
method is called, so moving a tag or advancing the table later does not
|
||||
change the delta, and this table's checkout state is left untouched.
|
||||
|
||||
The returned [TableDelta][lancedb.table.TableDelta] streams inserted,
|
||||
updated, upserted, and deleted rows. Those row-level readers require
|
||||
stable row ids at both endpoints; create the table with
|
||||
``storage_options={"new_table_enable_stable_row_ids": "true"}`` to
|
||||
enable them. ``list_transactions()`` works without stable row ids.
|
||||
Equal valid versions produce empty readers with the same schemas.
|
||||
|
||||
Reversed ranges, version 0, missing versions or tags, and tags from a
|
||||
different branch are rejected. A row-level range that contains a
|
||||
``Restore``, or whose transaction history is incomplete, is rejected
|
||||
because the restored snapshot can retain older row-version metadata that
|
||||
the delta readers would omit; recompute the checkpoint with a full
|
||||
rescan and reinitialize it at the end version. Remote tables raise
|
||||
``NotImplementedError``.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
from_version: int | str
|
||||
The version or tag to compare from (exclusive).
|
||||
to_version: int | str, optional
|
||||
The version or tag to compare to (inclusive). Defaults to the
|
||||
currently visible version.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import lancedb
|
||||
>>> db = lancedb.connect("memory://")
|
||||
>>> table = db.create_table(
|
||||
... "delta_example",
|
||||
... [{"id": 1}, {"id": 2}],
|
||||
... storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
... )
|
||||
>>> table.tags.create("baseline", table.version)
|
||||
>>> _ = table.add([{"id": 3}])
|
||||
>>> delta = table.delta("baseline")
|
||||
>>> inserted = delta.inserted_rows().read_all()
|
||||
>>> inserted["id"].to_pylist()
|
||||
[3]
|
||||
>>> [transaction["operation"] for transaction in delta.list_transactions()]
|
||||
['Append']
|
||||
"""
|
||||
raise NotImplementedError("delta is not supported for this table type")
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""The number of rows in this Table"""
|
||||
return self.count_rows(None)
|
||||
@@ -4618,6 +4675,18 @@ class LanceTable(Table):
|
||||
"""List all versions of the table"""
|
||||
return LOOP.run(self._table.list_versions())
|
||||
|
||||
def delta(
|
||||
self,
|
||||
from_version: int | str,
|
||||
to_version: Optional[int | str] = None,
|
||||
) -> "TableDelta":
|
||||
"""Compare two versions or tags.
|
||||
|
||||
See [Table.delta][lancedb.table.Table.delta].
|
||||
"""
|
||||
async_delta = LOOP.run(self._table.delta(from_version, to_version))
|
||||
return TableDelta(async_delta._inner)
|
||||
|
||||
@property
|
||||
def version(self) -> int:
|
||||
"""Get the current version of the table"""
|
||||
@@ -9764,6 +9833,20 @@ class AsyncTable:
|
||||
|
||||
return versions
|
||||
|
||||
async def delta(
|
||||
self,
|
||||
from_version: int | str,
|
||||
to_version: Optional[int | str] = None,
|
||||
) -> "AsyncTableDelta":
|
||||
"""Compare two versions or tags.
|
||||
|
||||
See [Table.delta][lancedb.table.Table.delta] for endpoint, stable-row-id,
|
||||
and branch-tag semantics. The returned
|
||||
[AsyncTableDelta][lancedb.table.AsyncTableDelta] streams
|
||||
``AsyncRecordBatchReader`` values.
|
||||
"""
|
||||
return AsyncTableDelta(await self._inner.delta(from_version, to_version))
|
||||
|
||||
async def checkout(self, version: int | str):
|
||||
"""
|
||||
Checks out a specific version of the Table
|
||||
@@ -10569,6 +10652,128 @@ class Branches:
|
||||
return self._parent._wrap_branch_handle(async_table, version)
|
||||
|
||||
|
||||
class TableDelta:
|
||||
"""Streaming row changes between two table versions.
|
||||
|
||||
Created by [Table.delta][lancedb.table.Table.delta]. The endpoints are
|
||||
fixed when the delta is created.
|
||||
|
||||
Row-level readers require stable row ids at both endpoints. Create the
|
||||
table with ``storage_options={"new_table_enable_stable_row_ids": "true"}``
|
||||
to enable them. [list_transactions][lancedb.table.TableDelta.list_transactions]
|
||||
works without stable row ids.
|
||||
|
||||
A nonempty range that contains a ``Restore``, or whose transaction history
|
||||
is incomplete, rejects the row-level readers. Recompute the checkpoint with
|
||||
a full rescan and reinitialize it at the end version; transaction history
|
||||
remains available.
|
||||
"""
|
||||
|
||||
def __init__(self, inner: Any):
|
||||
self._inner = inner
|
||||
self._async = AsyncTableDelta(inner)
|
||||
|
||||
@property
|
||||
def begin_version(self) -> int:
|
||||
"""The version this delta starts from (exclusive)."""
|
||||
return self._inner.begin_version()
|
||||
|
||||
@property
|
||||
def end_version(self) -> int:
|
||||
"""The version this delta ends at (inclusive)."""
|
||||
return self._inner.end_version()
|
||||
|
||||
def inserted_rows(self) -> pa.RecordBatchReader:
|
||||
"""Stream rows inserted in ``(begin_version, end_version]``.
|
||||
|
||||
Each batch carries the table columns plus ``_rowid``,
|
||||
``_row_created_at_version``, and ``_row_last_updated_at_version``.
|
||||
"""
|
||||
return _record_batch_reader(LOOP.run(self._async.inserted_rows()))
|
||||
|
||||
def updated_rows(self) -> pa.RecordBatchReader:
|
||||
"""Stream rows updated in ``(begin_version, end_version]``.
|
||||
|
||||
Newly inserted rows are excluded; use
|
||||
[upserted_rows][lancedb.table.TableDelta.upserted_rows] for both.
|
||||
"""
|
||||
return _record_batch_reader(LOOP.run(self._async.updated_rows()))
|
||||
|
||||
def upserted_rows(self) -> pa.RecordBatchReader:
|
||||
"""Stream inserted and updated rows in ``(begin_version, end_version]``."""
|
||||
return _record_batch_reader(LOOP.run(self._async.upserted_rows()))
|
||||
|
||||
def deleted_row_ids(self) -> pa.RecordBatchReader:
|
||||
"""Stream the ``_rowid`` values of rows deleted in the range.
|
||||
|
||||
Each batch carries one ``_rowid`` column of type ``uint64``. Deleted
|
||||
rows are not reconstructed from earlier versions.
|
||||
"""
|
||||
return _record_batch_reader(LOOP.run(self._async.deleted_row_ids()))
|
||||
|
||||
def list_transactions(self) -> List[Dict[str, Any]]:
|
||||
"""List transactions committed in ``(begin_version, end_version]``.
|
||||
|
||||
Each item has ``read_version``, ``uuid``, ``operation``, ``tag``, and
|
||||
``transaction_properties``. Unlike row readers, this works without
|
||||
stable row ids.
|
||||
"""
|
||||
return LOOP.run(self._async.list_transactions())
|
||||
|
||||
|
||||
class AsyncTableDelta:
|
||||
"""Async streaming row changes between two table versions.
|
||||
|
||||
Created by [AsyncTable.delta][lancedb.table.AsyncTable.delta]. See
|
||||
[TableDelta][lancedb.table.TableDelta] for the endpoint and stable-row-id
|
||||
contract.
|
||||
"""
|
||||
|
||||
def __init__(self, inner: Any):
|
||||
self._inner = inner
|
||||
|
||||
@property
|
||||
def begin_version(self) -> int:
|
||||
"""The version this delta starts from (exclusive)."""
|
||||
return self._inner.begin_version()
|
||||
|
||||
@property
|
||||
def end_version(self) -> int:
|
||||
"""The version this delta ends at (inclusive)."""
|
||||
return self._inner.end_version()
|
||||
|
||||
async def inserted_rows(self) -> AsyncRecordBatchReader:
|
||||
"""Stream rows inserted in ``(begin_version, end_version]``."""
|
||||
return AsyncRecordBatchReader(await self._inner.inserted_rows())
|
||||
|
||||
async def updated_rows(self) -> AsyncRecordBatchReader:
|
||||
"""Stream rows updated in ``(begin_version, end_version]``."""
|
||||
return AsyncRecordBatchReader(await self._inner.updated_rows())
|
||||
|
||||
async def upserted_rows(self) -> AsyncRecordBatchReader:
|
||||
"""Stream inserted and updated rows in ``(begin_version, end_version]``."""
|
||||
return AsyncRecordBatchReader(await self._inner.upserted_rows())
|
||||
|
||||
async def deleted_row_ids(self) -> AsyncRecordBatchReader:
|
||||
"""Stream the ``_rowid`` values of rows deleted in the range."""
|
||||
return AsyncRecordBatchReader(await self._inner.deleted_row_ids())
|
||||
|
||||
async def list_transactions(self) -> List[Dict[str, Any]]:
|
||||
"""List transactions committed in ``(begin_version, end_version]``."""
|
||||
return await self._inner.list_transactions()
|
||||
|
||||
|
||||
def _record_batch_reader(stream) -> pa.RecordBatchReader:
|
||||
def iter_sync():
|
||||
try:
|
||||
while True:
|
||||
yield LOOP.run(stream.__anext__())
|
||||
except StopAsyncIteration:
|
||||
return
|
||||
|
||||
return pa.RecordBatchReader.from_batches(stream.schema, iter_sync())
|
||||
|
||||
|
||||
class AsyncTags:
|
||||
"""
|
||||
Async table tag manager.
|
||||
|
||||
@@ -1373,6 +1373,270 @@ def test_versioning(mem_db: DBConnection):
|
||||
assert len(table) == 2
|
||||
|
||||
|
||||
def test_delta_streams_and_pins_endpoints(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"delta",
|
||||
data=[
|
||||
{"id": 1, "value": 0},
|
||||
{"id": 2, "value": 0},
|
||||
],
|
||||
storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
)
|
||||
|
||||
table.add([{"id": 3, "value": 0}])
|
||||
table.tags.create("baseline", 2)
|
||||
table.update(where="id = 1", values_sql={"value": "value + 10"})
|
||||
table.delete("id = 2")
|
||||
assert table.version == 4
|
||||
|
||||
delta = table.delta(1)
|
||||
assert delta.begin_version == 1
|
||||
assert delta.end_version == 4
|
||||
|
||||
inserted = delta.inserted_rows().read_all()
|
||||
assert inserted["id"].to_pylist() == [3]
|
||||
assert inserted.schema.names == [
|
||||
"id",
|
||||
"value",
|
||||
"_rowid",
|
||||
"_row_created_at_version",
|
||||
"_row_last_updated_at_version",
|
||||
]
|
||||
|
||||
updated = delta.updated_rows().read_all()
|
||||
assert updated["id"].to_pylist() == [1]
|
||||
assert updated["value"].to_pylist() == [10]
|
||||
|
||||
upserted = delta.upserted_rows().read_all()
|
||||
assert sorted(upserted["id"].to_pylist()) == [1, 3]
|
||||
|
||||
deleted = delta.deleted_row_ids().read_all()
|
||||
assert deleted.schema.names == ["_rowid"]
|
||||
assert deleted.schema.field("_rowid").type == pa.uint64()
|
||||
assert deleted.num_rows == 1
|
||||
|
||||
transactions = delta.list_transactions()
|
||||
assert [transaction["operation"] for transaction in transactions] == [
|
||||
"Append",
|
||||
"Update",
|
||||
"Delete",
|
||||
]
|
||||
assert transactions[0]["read_version"] == 1
|
||||
|
||||
# Tags are resolved on the current branch and can be either endpoint.
|
||||
from_tag = table.delta("baseline")
|
||||
assert from_tag.begin_version == 2
|
||||
assert from_tag.end_version == 4
|
||||
assert from_tag.updated_rows().read_all()["id"].to_pylist() == [1]
|
||||
|
||||
to_tag = table.delta(1, "baseline")
|
||||
assert to_tag.end_version == 2
|
||||
assert to_tag.inserted_rows().read_all()["id"].to_pylist() == [3]
|
||||
|
||||
# Equal valid versions keep the reader schemas even when no rows change.
|
||||
equal = table.delta(2, 2)
|
||||
empty_inserted = equal.inserted_rows().read_all()
|
||||
assert empty_inserted.num_rows == 0
|
||||
assert empty_inserted.schema == inserted.schema
|
||||
empty_deleted = equal.deleted_row_ids().read_all()
|
||||
assert empty_deleted.num_rows == 0
|
||||
assert empty_deleted.schema.names == ["_rowid"]
|
||||
|
||||
# Reversed, zero, missing, and missing-tag endpoints are input errors.
|
||||
with pytest.raises(ValueError, match="newer than"):
|
||||
table.delta(4, 2)
|
||||
with pytest.raises(ValueError, match="start at 1"):
|
||||
table.delta(0)
|
||||
with pytest.raises(ValueError, match="does not exist"):
|
||||
table.delta(999)
|
||||
with pytest.raises(ValueError, match="does not exist"):
|
||||
table.delta("missing-tag")
|
||||
|
||||
# An omitted target follows the visible checkout and leaves the shared
|
||||
# checkout in place.
|
||||
table.checkout(2)
|
||||
checked_out = table.delta(1)
|
||||
assert checked_out.end_version == 2
|
||||
assert checked_out.inserted_rows().read_all()["id"].to_pylist() == [3]
|
||||
assert table.version == 2
|
||||
|
||||
# An explicit target works from a pinned handle without moving it.
|
||||
explicit = table.delta(1, 3)
|
||||
assert explicit.updated_rows().read_all()["id"].to_pylist() == [1]
|
||||
assert table.version == 2
|
||||
table.checkout_latest()
|
||||
assert table.version == 4
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", ["update", "delete"])
|
||||
def test_delta_rejects_restore_ranges(tmp_path, mutation):
|
||||
table = lancedb.connect(tmp_path).create_table(
|
||||
"restore_delta",
|
||||
[{"id": 1, "value": 0}],
|
||||
storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
)
|
||||
if mutation == "update":
|
||||
table.update(values={"value": 10})
|
||||
else:
|
||||
table.delete("id = 1")
|
||||
assert table.version == 2
|
||||
|
||||
table.restore(1)
|
||||
assert table.version == 3
|
||||
assert table.to_arrow().to_pylist() == [{"id": 1, "value": 0}]
|
||||
|
||||
restore_range = table.delta(2, 3)
|
||||
assert [tx["operation"] for tx in restore_range.list_transactions()] == ["Restore"]
|
||||
for reader in (
|
||||
restore_range.inserted_rows,
|
||||
restore_range.updated_rows,
|
||||
restore_range.upserted_rows,
|
||||
restore_range.deleted_row_ids,
|
||||
):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
reader()
|
||||
message = str(exc_info.value)
|
||||
assert "Restore" in message
|
||||
assert "full rescan" in message
|
||||
assert "reinitialize" in message
|
||||
|
||||
# A restore in the middle of the range is still unverifiable.
|
||||
table.add([{"id": 2, "value": 0}])
|
||||
assert table.version == 4
|
||||
with pytest.raises(ValueError, match="Restore"):
|
||||
table.delta(2, 4).upserted_rows()
|
||||
|
||||
# A restore at the exclusive boundary is the base snapshot, so later
|
||||
# changes remain usable.
|
||||
after_restore = table.delta(3, 4)
|
||||
assert after_restore.inserted_rows().read_all()["id"].to_pylist() == [2]
|
||||
assert [tx["operation"] for tx in after_restore.list_transactions()] == ["Append"]
|
||||
|
||||
# Equal endpoints remain empty and do not run the restore guard.
|
||||
equal = table.delta(3, 3)
|
||||
assert equal.inserted_rows().read_all().num_rows == 0
|
||||
|
||||
|
||||
def test_delta_rejects_restore_after_same_uri_recreate(tmp_path):
|
||||
stable = {"new_table_enable_stable_row_ids": "true"}
|
||||
old_db = lancedb.connect(tmp_path)
|
||||
old = old_db.create_table("t", [{"id": 1, "value": 0}], storage_options=stable)
|
||||
old.add([{"id": 2, "value": 0}])
|
||||
old.add([{"id": 3, "value": 0}])
|
||||
assert [tx["operation"] for tx in old.delta(2, 3).list_transactions()] == ["Append"]
|
||||
|
||||
writer_db = lancedb.connect(tmp_path)
|
||||
writer_db.drop_table("t")
|
||||
schema = pa.schema(
|
||||
[("id", pa.int32()), ("value", pa.int32())],
|
||||
metadata={"padding": "x" * (256 * 1024)},
|
||||
)
|
||||
recreated = writer_db.create_table(
|
||||
"t",
|
||||
pa.Table.from_pylist([{"id": 1, "value": 0}], schema=schema),
|
||||
storage_options=stable,
|
||||
)
|
||||
recreated.update(values={"value": 10})
|
||||
recreated.restore(1)
|
||||
assert [tx["operation"] for tx in recreated.delta(2, 3).list_transactions()] == [
|
||||
"Restore"
|
||||
]
|
||||
|
||||
delta = old_db.open_table("t").delta(2, 3)
|
||||
assert [tx["operation"] for tx in delta.list_transactions()] == ["Restore"]
|
||||
with pytest.raises(ValueError, match="Restore"):
|
||||
delta.upserted_rows()
|
||||
|
||||
|
||||
def test_delta_requires_stable_row_ids(mem_db: DBConnection):
|
||||
table = mem_db.create_table("delta_no_stable", data=[{"id": 1}])
|
||||
table.add([{"id": 2}])
|
||||
delta = table.delta(1)
|
||||
|
||||
for reader in (
|
||||
delta.inserted_rows,
|
||||
delta.updated_rows,
|
||||
delta.upserted_rows,
|
||||
delta.deleted_row_ids,
|
||||
):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
reader()
|
||||
message = str(exc_info.value)
|
||||
assert "new_table_enable_stable_row_ids" in message
|
||||
assert "list_transactions" in message
|
||||
|
||||
# Transactions remain available without stable row ids.
|
||||
transactions = delta.list_transactions()
|
||||
assert [transaction["operation"] for transaction in transactions] == ["Append"]
|
||||
|
||||
# Equal endpoints need no row lineage, so they are empty rather than
|
||||
# rejected.
|
||||
version = table.version
|
||||
equal = table.delta(version, version)
|
||||
assert equal.inserted_rows().read_all().num_rows == 0
|
||||
assert equal.deleted_row_ids().read_all().num_rows == 0
|
||||
|
||||
|
||||
def test_delta_rejects_cross_branch_tags(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
table = db.create_table(
|
||||
"delta_branches",
|
||||
data=[{"id": 0}],
|
||||
storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
)
|
||||
branch = table.branches.create("exp")
|
||||
branch.add([{"id": 1}])
|
||||
table.add([{"id": 100}, {"id": 101}, {"id": 102}])
|
||||
assert branch.version == table.version
|
||||
|
||||
table.tags.create("main_tag", table.version)
|
||||
branch.tags.create("exp_tag", branch.version)
|
||||
|
||||
# The same-branch tag resolves through the branch, not main's data at the
|
||||
# same version number.
|
||||
delta = branch.delta(1, "exp_tag")
|
||||
assert delta.inserted_rows().read_all()["id"].to_pylist() == [1]
|
||||
|
||||
# Cross-branch tags are rejected even though the version number exists on
|
||||
# both branches.
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
branch.delta("main_tag")
|
||||
message = str(exc_info.value)
|
||||
assert "main_tag" in message
|
||||
assert "main" in message
|
||||
assert "exp" in message
|
||||
|
||||
with pytest.raises(ValueError, match="exp_tag"):
|
||||
table.delta("exp_tag")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_delta(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"async_delta",
|
||||
data=[{"id": 1}],
|
||||
storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
)
|
||||
await table.add([{"id": 2}])
|
||||
|
||||
delta = await table.delta(1)
|
||||
assert delta.begin_version == 1
|
||||
assert delta.end_version == 2
|
||||
|
||||
reader = await delta.inserted_rows()
|
||||
inserted = await reader.read_all()
|
||||
assert inserted[0]["id"].to_pylist() == [2]
|
||||
|
||||
transactions = await delta.list_transactions()
|
||||
assert [transaction["operation"] for transaction in transactions] == ["Append"]
|
||||
|
||||
equal = await table.delta(2, 2)
|
||||
reader = await equal.inserted_rows()
|
||||
assert await reader.read_all() == []
|
||||
|
||||
|
||||
def test_tags(mem_db: DBConnection):
|
||||
table = mem_db.create_table(
|
||||
"test",
|
||||
|
||||
@@ -98,6 +98,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(catalog::connect_catalog, m)?)?;
|
||||
m.add_class::<Session>()?;
|
||||
m.add_class::<Table>()?;
|
||||
m.add_class::<table::TableDelta>()?;
|
||||
m.add_class::<crate::oauth::PyOAuthSession>()?;
|
||||
m.add_class::<crate::oauth::PySessionStatus>()?;
|
||||
m.add_class::<crate::oauth::PySessionLogout>()?;
|
||||
|
||||
+115
-2
@@ -29,10 +29,10 @@ use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest};
|
||||
use lancedb::connection::LanceFileVersion;
|
||||
use lancedb::index::scalar::FtsIndexBuilder;
|
||||
use lancedb::table::{
|
||||
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
|
||||
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, DeltaRef, Duration,
|
||||
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig,
|
||||
FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform,
|
||||
Ref, RefreshColumnOptions, Table as LanceDbTable,
|
||||
Ref, RefreshColumnOptions, Table as LanceDbTable, TableDelta as LanceDbTableDelta,
|
||||
};
|
||||
use lancedb::tokenize as lancedb_tokenize;
|
||||
use pyo3::{
|
||||
@@ -2075,6 +2075,22 @@ impl Table {
|
||||
)
|
||||
}
|
||||
|
||||
#[pyo3(signature = (from_version, to_version=None))]
|
||||
pub fn delta(
|
||||
self_: PyRef<'_, Self>,
|
||||
from_version: LanceVersion,
|
||||
to_version: Option<LanceVersion>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let delta = inner
|
||||
.delta(from_version, to_version.map(Into::into))
|
||||
.await
|
||||
.infer_error()?;
|
||||
Ok(TableDelta::new(delta))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn list_versions(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -3244,6 +3260,103 @@ pub enum LanceVersion {
|
||||
Tag(String),
|
||||
}
|
||||
|
||||
impl From<LanceVersion> for DeltaRef {
|
||||
fn from(version: LanceVersion) -> Self {
|
||||
match version {
|
||||
LanceVersion::Version(version) => DeltaRef::Version(version),
|
||||
LanceVersion::Tag(tag) => DeltaRef::Tag(tag),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming row changes between two table versions.
|
||||
#[pyclass]
|
||||
pub struct TableDelta {
|
||||
inner: Arc<LanceDbTableDelta>,
|
||||
}
|
||||
|
||||
impl TableDelta {
|
||||
fn new(inner: LanceDbTableDelta) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(inner),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl TableDelta {
|
||||
/// The version this delta starts from (exclusive).
|
||||
pub fn begin_version(&self) -> u64 {
|
||||
self.inner.begin_version()
|
||||
}
|
||||
|
||||
/// The version this delta ends at (inclusive).
|
||||
pub fn end_version(&self) -> u64 {
|
||||
self.inner.end_version()
|
||||
}
|
||||
|
||||
pub fn inserted_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let stream = inner.inserted_rows().await.infer_error()?;
|
||||
Ok(crate::arrow::RecordBatchStream::new(stream.into()))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn updated_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let stream = inner.updated_rows().await.infer_error()?;
|
||||
Ok(crate::arrow::RecordBatchStream::new(stream.into()))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn upserted_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let stream = inner.upserted_rows().await.infer_error()?;
|
||||
Ok(crate::arrow::RecordBatchStream::new(stream.into()))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn deleted_row_ids(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let stream = inner.deleted_row_ids().await.infer_error()?;
|
||||
Ok(crate::arrow::RecordBatchStream::new(stream.into()))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn list_transactions(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let transactions = inner.list_transactions().await.infer_error()?;
|
||||
Python::attach(|py| {
|
||||
let output = PyList::empty(py);
|
||||
for transaction in transactions {
|
||||
let item = PyDict::new(py);
|
||||
item.set_item("read_version", transaction.read_version)?;
|
||||
item.set_item("uuid", transaction.uuid)?;
|
||||
item.set_item("operation", transaction.operation.name())?;
|
||||
item.set_item("tag", transaction.tag)?;
|
||||
match transaction.transaction_properties {
|
||||
Some(properties) => {
|
||||
let py_properties = PyDict::new(py);
|
||||
for (key, value) in properties.iter() {
|
||||
py_properties.set_item(key, value)?;
|
||||
}
|
||||
item.set_item("transaction_properties", py_properties)?;
|
||||
}
|
||||
None => item.set_item("transaction_properties", py.None())?,
|
||||
}
|
||||
output.append(item)?;
|
||||
}
|
||||
Ok(output.unbind())
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(FromPyObject)]
|
||||
#[pyo3(from_item_all)]
|
||||
pub struct MergeInsertParams {
|
||||
|
||||
Reference in New Issue
Block a user