mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat: register blob bases during table creation (#5117)
## Summary `create_table` / `create_empty_table` now accept registered storage bases and the embedded opt-in for blob URIs outside them. A create with data registers `initial_bases` in the same commit, so external Blob v2 references no longer need an empty create followed by `add`. - Rust `CreateTableBuilder::initial_bases` / `allow_external_blob_outside_bases`, with `BasePath` re-exported. - PyO3 and Python sync/async create paths accept lightweight `BasePath`, dicts, and duck-typed `lance.DatasetBasePath`; `id=None` lets Lance assign an ID and explicit `0` or duplicate explicit IDs are rejected. - `blob_uri_array` builds the standard four-field `lance.blob.v2` array without pylance and keeps field metadata such as `lancedb:logical_type=mp4`. - Enterprise create rejects non-empty `initial_bases` and the true opt-in before normalization, input iteration, or HTTP; empty/false defaults remain an ordinary create. - Native namespace create merges namespace and connection storage options into the caller's store parameters instead of replacing them. This is reconciled with #5114's refresh layering, so caller-scoped options survive create, refresh, and reopen while namespace-vended values keep their precedence. - The outside-base opt-in applies to one write: setting it on create does not carry over to a later `add()`. ## Validation - `cargo fmt --all -- --check`, `cargo check --quiet --features remote --tests --examples`, `cargo clippy --quiet --features remote --tests --examples`. - Rust: `blob_integration` 66 passed, `database::namespace` 23, `connection::create_table` 16, `remote::db` 128. - Python: `test_blob.py` 263 passed / 1 skipped, `test_blob_array.py` 4, remote create 12, `test_db.py -k "pickle or create_table"` 15, `test_namespace.py -k "pickle or refresh or create"` 29, `test_table.py -k pickle` 8; ruff 0.9.9 and pyright from `python/`. - `test_blob.py` also passes with pylance and pandas removed (177 passed / 87 skipped), matching the CI no-pylance suite. The lightweight and dict create cases keep version, schema, reopen, and exact-range assertions there; only the pylance-only manifest introspection moved into the `DatasetBasePath` case. - Rust and sync Python two-base probes assert that base 1's scoped option fails its read while base 2 still returns exact bytes after reopen. A separate async namespace test covers create and reopen with exact ranges. - `test_namespace_refresh_layers_caller_scoped_options` covers the expired namespace seed: create-time `base_1.caller_scoped` survives refresh, vended `timeout` is replaced (7s to 8s), fresh namespace values appear, and reopen with the caller option returns exact blob range bytes through the registered base. - Updated `main` through #5127 (including #5114) is merged; `rust/lancedb/src/database/namespace.rs` and `rust/lancedb/src/table.rs` match `main`, and no #5114 code was stacked before it merged. ## Dependency note The Lance dependency stays pinned at the `v15.0.0-beta.25` release on `main`. With that pin, mixing an automatic base ID (`id=0`) and an explicit non-zero ID may still collide; the approved upstream fix is https://github.com/lance-format/lance/pull/11307. Use distinct explicit non-zero IDs for multi-base creates, or automatic IDs for every base, until a Lance release containing that fix is pinned. A failed mixed create can leave the table name listed but unopenable; retrying with distinct explicit IDs succeeds. Multi-base validation here uses explicit IDs and bootstrap uses a single automatic ID, so the mixed-ID case is not claimed as verified until a Lance release containing that fix is pinned.
This commit is contained in:
@@ -948,9 +948,42 @@ PyArrow's `RecordBatch.from_pylist(..., schema=...)` cannot convert raw bytes
|
||||
into the blob extension type; use `blob_array` and `RecordBatch.from_arrays`
|
||||
when constructing batches explicitly.
|
||||
|
||||
For external blob references, construct the descriptor struct described by
|
||||
[blob][lancedb.schema.blob], then wrap it with `pa.ExtensionArray.from_storage`.
|
||||
Inline `data` and external `uri` representations are mutually exclusive.
|
||||
For external blob references, use [blob_uri_array][lancedb.blob_uri_array]. It builds the
|
||||
same extension type from URI strings and optional `(position, size)` byte
|
||||
ranges without requiring pylance. Inline `data` and external `uri` representations
|
||||
are mutually exclusive.
|
||||
|
||||
Register the object prefix with [BasePath][lancedb.BasePath] on
|
||||
`create_table(..., initial_bases=[...])` to store a matched absolute blob URI
|
||||
relative to a base and to scope credentials with `base_<id>.<option>` storage
|
||||
options. A create with data stays a single atomic request; without a matching
|
||||
base, pass `allow_external_blob_outside_bases=True` to keep the absolute URI
|
||||
instead. That opt-in still expects a valid absolute URI and applies to one
|
||||
write; a later `add()` needs its own opt-in. When registering several bases,
|
||||
supply distinct explicit non-zero IDs: the pinned Lance release can collide
|
||||
when automatic and explicit IDs are mixed, leaving a listed but unopenable name
|
||||
after a failed create; retrying with distinct explicit IDs succeeds.
|
||||
|
||||
```python
|
||||
from lancedb import BasePath, blob, blob_uri_array
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
blob("video").with_metadata({"lancedb:logical_type": "mp4"}),
|
||||
]
|
||||
)
|
||||
videos = blob_uri_array(
|
||||
["s3://bucket/clip-0.mp4", "s3://bucket/clip-1.mp4"],
|
||||
positions=[0, 0],
|
||||
sizes=[1 << 20, 1 << 20],
|
||||
)
|
||||
db.create_table(
|
||||
"videos",
|
||||
data=pa.RecordBatch.from_arrays([pa.array([0, 1]), videos], schema=schema),
|
||||
initial_bases=[BasePath("s3://bucket")],
|
||||
)
|
||||
```
|
||||
|
||||
LanceDB Enterprise SQL returns blob bytes by default. Select `blob_descriptor(video)` to
|
||||
return an openable reference instead, then use
|
||||
@@ -1012,6 +1045,10 @@ so the fetch APIs cannot read their bytes yet.
|
||||
|
||||
::: lancedb.schema.blob_array
|
||||
|
||||
::: lancedb.blob_uri_array
|
||||
|
||||
::: lancedb.BasePath
|
||||
|
||||
::: lancedb._blob.BlobFile
|
||||
options:
|
||||
show_root_full_path: false
|
||||
|
||||
@@ -38,7 +38,7 @@ from .db import AsyncConnection, DBConnection, LanceDBConnection
|
||||
from .remote import ClientConfig
|
||||
from .remote.db import RemoteDBConnection
|
||||
from .expr import Expr, col, lit, func
|
||||
from .schema import blob, vector
|
||||
from .schema import BasePath, blob, blob_uri_array, vector
|
||||
from ._blob_reader import BlobReader as BlobReader
|
||||
from .job import AsyncJob, Job
|
||||
from .sql import AsyncQuery as AsyncSqlQuery
|
||||
@@ -696,6 +696,8 @@ __all__ = [
|
||||
"sanitize_uri",
|
||||
"blob",
|
||||
"BlobType",
|
||||
"BasePath",
|
||||
"blob_uri_array",
|
||||
"vector",
|
||||
"DBConnection",
|
||||
"Job",
|
||||
|
||||
@@ -334,6 +334,9 @@ class Connection(object):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table: ...
|
||||
async def create_empty_table(
|
||||
self,
|
||||
@@ -343,6 +346,8 @@ class Connection(object):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
) -> Table: ...
|
||||
async def open_table(
|
||||
self,
|
||||
|
||||
@@ -507,6 +507,8 @@ class DBConnection(EnforceOverrides):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
"""Create a [Table][lancedb.table.Table] in the database.
|
||||
|
||||
@@ -570,6 +572,23 @@ class DBConnection(EnforceOverrides):
|
||||
enable_v2_manifest_paths: optional, bool, default False
|
||||
Deprecated. Set `storage_options` when connecting to the database and set
|
||||
`new_table_enable_v2_manifest_paths` in the options.
|
||||
initial_bases: list, optional
|
||||
Storage bases to register in the table's manifest in the same
|
||||
commit that creates it, so a create with data stays atomic. Each
|
||||
entry can be a [BasePath][lancedb.schema.BasePath], a dict with
|
||||
`path`, `name`, `is_dataset_root`, and `id` keys, or a
|
||||
`lance.DatasetBasePath`. Blob URIs that fall under a registered
|
||||
base are stored relative to it; other URIs need
|
||||
`allow_external_blob_outside_bases=True`. `None` and an empty
|
||||
list are equivalent. When supplying IDs for multiple bases, use
|
||||
distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
|
||||
describes the pinned-Lance limitation.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Store blob URIs that do not fall under a registered base. The row
|
||||
keeps a reference, so the objects have to stay readable. Set
|
||||
`initial_bases` instead when the URIs share a registered prefix.
|
||||
Defaults to rejecting such URIs. The opt-in applies only to the
|
||||
initial data; a later `add()` must enable it again.
|
||||
Returns
|
||||
-------
|
||||
LanceTable
|
||||
@@ -2156,6 +2175,8 @@ class LanceDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> LanceTable:
|
||||
"""Create a table in the database.
|
||||
|
||||
@@ -2186,6 +2207,8 @@ class LanceDBConnection(DBConnection):
|
||||
storage_options=storage_options,
|
||||
data_storage_version=data_storage_version,
|
||||
enable_v2_manifest_paths=enable_v2_manifest_paths,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
return tbl
|
||||
|
||||
@@ -3296,6 +3319,8 @@ class AsyncConnection(object):
|
||||
embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> AsyncTable:
|
||||
"""Create an [AsyncTable][lancedb.table.AsyncTable] in the database.
|
||||
|
||||
@@ -3353,6 +3378,23 @@ class AsyncConnection(object):
|
||||
To enable stable row IDs (row IDs remain stable after compaction,
|
||||
update, delete, and merges), set `new_table_enable_stable_row_ids`
|
||||
to `"true"` in storage_options when connecting to the database.
|
||||
initial_bases: list, optional
|
||||
Storage bases to register in the table's manifest in the same
|
||||
commit that creates it, so a create with data stays atomic. Each
|
||||
entry can be a [BasePath][lancedb.schema.BasePath], a dict with
|
||||
`path`, `name`, `is_dataset_root`, and `id` keys, or a
|
||||
`lance.DatasetBasePath`. Blob URIs that fall under a registered
|
||||
base are stored relative to it; other URIs need
|
||||
`allow_external_blob_outside_bases=True`. `None` and an empty
|
||||
list are equivalent. When supplying IDs for multiple bases, use
|
||||
distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
|
||||
describes the pinned-Lance limitation.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Store blob URIs that do not fall under a registered base. The row
|
||||
keeps a reference, so the objects have to stay readable. Requires
|
||||
initial `data`; the opt-in applies only to that initial write, and
|
||||
a later `add()` must enable it again. Defaults to rejecting such
|
||||
URIs.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -3464,6 +3506,25 @@ class AsyncConnection(object):
|
||||
"""
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
if get_uri_scheme(self.uri) == "db":
|
||||
# The Enterprise create endpoint has no way to express either
|
||||
# option. Reject before sanitizing or reading `data`, and do not
|
||||
# point at a local-only or remote `add` path.
|
||||
if initial_bases:
|
||||
raise NotImplementedError(
|
||||
"initial_bases is not supported for table creation in "
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if allow_external_blob_outside_bases:
|
||||
raise NotImplementedError(
|
||||
"allow_external_blob_outside_bases is not supported for table "
|
||||
"creation in LanceDB Enterprise"
|
||||
)
|
||||
if data is None and allow_external_blob_outside_bases:
|
||||
raise ValueError(
|
||||
"allow_external_blob_outside_bases requires initial data; "
|
||||
"pass it to add() for later writes"
|
||||
)
|
||||
metadata = None
|
||||
|
||||
if embedding_functions is not None:
|
||||
@@ -3510,6 +3571,7 @@ class AsyncConnection(object):
|
||||
storage_options=storage_options,
|
||||
location=location,
|
||||
namespace_client=namespace_client,
|
||||
initial_bases=initial_bases,
|
||||
)
|
||||
else:
|
||||
data = data_to_reader(data, schema)
|
||||
@@ -3521,6 +3583,8 @@ class AsyncConnection(object):
|
||||
storage_options=storage_options,
|
||||
location=location,
|
||||
namespace_client=namespace_client,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
|
||||
return AsyncTable(new_table)
|
||||
|
||||
@@ -642,6 +642,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
@@ -663,6 +665,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
embedding_functions=embedding_functions,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1309,6 +1313,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> AsyncTable:
|
||||
"""Create a new table in the namespace."""
|
||||
if namespace_path is None:
|
||||
@@ -1330,6 +1336,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
namespace_path=namespace_path,
|
||||
embedding_functions=embedding_functions,
|
||||
storage_options=storage_options,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
return table._set_namespace_context(
|
||||
namespace_path=namespace_path,
|
||||
|
||||
@@ -641,6 +641,8 @@ class RemoteDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
"""Create a [Table][lancedb.table.Table] in the database.
|
||||
|
||||
@@ -686,6 +688,10 @@ class RemoteDBConnection(DBConnection):
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
enable_v2_manifest_paths: bool, optional
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
initial_bases: list, optional
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -761,6 +767,16 @@ class RemoteDBConnection(DBConnection):
|
||||
f"{option} is not supported for table creation in "
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if initial_bases:
|
||||
raise NotImplementedError(
|
||||
"initial_bases is not supported for table creation in "
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if allow_external_blob_outside_bases:
|
||||
raise NotImplementedError(
|
||||
"allow_external_blob_outside_bases is not supported for table "
|
||||
"creation in LanceDB Enterprise"
|
||||
)
|
||||
if exist_ok:
|
||||
if mode == "create":
|
||||
mode = "exist_ok"
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import ctypes
|
||||
import importlib
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Iterable, Optional
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -27,6 +28,78 @@ _BLOB_V2_STORAGE_TYPE = pa.struct(
|
||||
]
|
||||
)
|
||||
_resolved_blob_type = None
|
||||
_UINT32_MAX = 0xFFFF_FFFF
|
||||
_UINT64_MAX = 0xFFFF_FFFF_FFFF_FFFF
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BasePath:
|
||||
"""A storage base registered on a table at creation time.
|
||||
|
||||
Use with the ``initial_bases`` argument of
|
||||
[create_table][lancedb.db.DBConnection.create_table] to make
|
||||
external blob URIs resolve under a shared prefix: descriptors that fall
|
||||
under ``path`` are stored relative to it instead of as absolute URIs.
|
||||
|
||||
This is a lightweight stand-in for ``lance.DatasetBasePath`` that does
|
||||
not require pylance. Both classes, and equivalent dictionaries, are
|
||||
accepted by the create APIs.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
path:
|
||||
Full URI of the base (for example ``s3://bucket/prefix`` or a
|
||||
``file://`` URI). A blob URI under this prefix is stored relative to
|
||||
it.
|
||||
name:
|
||||
Optional human-readable name for the base.
|
||||
is_dataset_root:
|
||||
Whether the base uses the dataset-root layout. Defaults to ``False``.
|
||||
Bases registered here must leave this ``False``: Lance only resolves
|
||||
external blob URIs against non-root bases.
|
||||
id:
|
||||
Base ID used by scoped storage options such as ``base_<id>.region``.
|
||||
``None`` lets Lance assign a non-zero ID. ``0`` is reserved for
|
||||
absolute (unregistered) URIs and is rejected.
|
||||
|
||||
When supplying IDs for multiple bases, use distinct explicit non-zero
|
||||
IDs. The pinned Lance release can collide when one base uses automatic
|
||||
allocation and another supplies an explicit ID; the create fails, the
|
||||
table name can remain listed but unopenable, and retrying with distinct
|
||||
explicit IDs succeeds. Automatic allocation for every base is
|
||||
supported.
|
||||
"""
|
||||
|
||||
path: str
|
||||
name: Optional[str] = None
|
||||
is_dataset_root: bool = False
|
||||
id: Optional[int] = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.path, str):
|
||||
raise TypeError(f"path must be a string, got {type(self.path).__name__}")
|
||||
if not self.path:
|
||||
raise ValueError("path must not be empty")
|
||||
if self.name is not None and not isinstance(self.name, str):
|
||||
raise TypeError(f"name must be a string, got {type(self.name).__name__}")
|
||||
if not isinstance(self.is_dataset_root, bool):
|
||||
raise TypeError(
|
||||
"is_dataset_root must be a bool, got "
|
||||
f"{type(self.is_dataset_root).__name__}"
|
||||
)
|
||||
if self.id is None:
|
||||
return
|
||||
if isinstance(self.id, bool) or not isinstance(self.id, int):
|
||||
raise TypeError(f"id must be an int or None, got {type(self.id).__name__}")
|
||||
if self.id == 0:
|
||||
raise ValueError(
|
||||
"id=0 is reserved for unregistered blob URIs; "
|
||||
"pass id=None to let Lance assign an ID"
|
||||
)
|
||||
if self.id < 0:
|
||||
raise ValueError("id must be a positive integer")
|
||||
if self.id > _UINT32_MAX:
|
||||
raise ValueError("id must fit in a 32-bit unsigned integer")
|
||||
|
||||
|
||||
class _FallbackBlobType(pa.ExtensionType):
|
||||
@@ -344,6 +417,132 @@ def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray:
|
||||
return pa.ExtensionArray.from_storage(blob_type, storage)
|
||||
|
||||
|
||||
def _blob_uint64(value: object, what: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise TypeError(f"{what} must be an int, got {type(value).__name__}")
|
||||
if value < 0:
|
||||
raise ValueError(f"{what} must be non-negative")
|
||||
if value > _UINT64_MAX:
|
||||
raise OverflowError(f"{what} must fit in a uint64")
|
||||
return value
|
||||
|
||||
|
||||
def blob_uri_array(
|
||||
uris: Iterable[Optional[str]],
|
||||
*,
|
||||
positions: Optional[Iterable[Optional[int]]] = None,
|
||||
sizes: Optional[Iterable[Optional[int]]] = None,
|
||||
) -> pa.ExtensionArray:
|
||||
"""Build a Lance blob v2 extension array from external URIs.
|
||||
|
||||
Produces the standard four-field blob v2 storage (``data=None``, ``uri``,
|
||||
nullable ``position`` and ``size``) without requiring pylance, so the
|
||||
result can be used directly in Arrow record batches and combined with
|
||||
field metadata such as ``lancedb:logical_type="mp4"``.
|
||||
|
||||
A row without ``position`` and ``size`` references the whole object; a
|
||||
row with both reads exactly that byte range. Register the object prefix
|
||||
with [BasePath][lancedb.schema.BasePath] at table creation to store a
|
||||
matched URI relative to a base, or enable
|
||||
``allow_external_blob_outside_bases`` on the write that inserts the row to
|
||||
keep the absolute URI when no base matches. The opt-in covers that one
|
||||
write; a later ``add()`` must enable it again.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
uris:
|
||||
An iterable of absolute URI strings or ``None`` for a null blob. A
|
||||
URI under a registered base is matched and stored in the descriptor
|
||||
relative to that base. An unmatched URI requires the write that
|
||||
inserts the row to opt in with
|
||||
``allow_external_blob_outside_bases``, and must always be a valid
|
||||
absolute URI.
|
||||
positions:
|
||||
Optional byte offsets, one per URI. Provide together with ``sizes``;
|
||||
each entry is an ``int`` or ``None``. A range requires both fields.
|
||||
sizes:
|
||||
Optional range lengths in bytes, one per URI. Must be positive when
|
||||
``position`` is set.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pa.ExtensionArray
|
||||
external blob values ready to use in Arrow tables or record batches.
|
||||
|
||||
Raises
|
||||
------
|
||||
TypeError
|
||||
If a URI, position, or size has the wrong type.
|
||||
ValueError
|
||||
If lengths differ, only one of ``positions``/``sizes`` is given, a
|
||||
range is incomplete, a size is not positive, or a range is given for
|
||||
a null URI.
|
||||
OverflowError
|
||||
If a position or size does not fit in a uint64.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import pyarrow as pa
|
||||
>>> from lancedb.schema import blob, blob_uri_array
|
||||
>>> schema = pa.schema([blob("video")])
|
||||
>>> videos = blob_uri_array(
|
||||
... ["s3://bucket/a.mp4", "hf://datasets/org/repo@abc/b.mp4"],
|
||||
... positions=[0, 8],
|
||||
... sizes=[4, 4],
|
||||
... )
|
||||
>>> batch = pa.RecordBatch.from_arrays([videos], schema=schema)
|
||||
>>> batch.num_rows
|
||||
2
|
||||
"""
|
||||
uri_list = list(uris)
|
||||
if positions is None and sizes is None:
|
||||
ranges = [(None, None)] * len(uri_list)
|
||||
elif positions is None or sizes is None:
|
||||
raise ValueError("positions and sizes must be provided together")
|
||||
else:
|
||||
position_list = list(positions)
|
||||
size_list = list(sizes)
|
||||
if len(position_list) != len(uri_list):
|
||||
raise ValueError(
|
||||
"positions must have the same length as uris, got "
|
||||
f"{len(position_list)} and {len(uri_list)}"
|
||||
)
|
||||
if len(size_list) != len(uri_list):
|
||||
raise ValueError(
|
||||
"sizes must have the same length as uris, got "
|
||||
f"{len(size_list)} and {len(uri_list)}"
|
||||
)
|
||||
ranges = list(zip(position_list, size_list, strict=True))
|
||||
|
||||
descriptors = []
|
||||
for index, (uri, (position, size)) in enumerate(zip(uri_list, ranges, strict=True)):
|
||||
if uri is None:
|
||||
if position is not None or size is not None:
|
||||
raise ValueError(
|
||||
f"uris[{index}] is None but a position or size was provided"
|
||||
)
|
||||
descriptors.append(None)
|
||||
continue
|
||||
if not isinstance(uri, str):
|
||||
raise TypeError(f"uris[{index}] must be a string, got {type(uri).__name__}")
|
||||
if position is None and size is None:
|
||||
descriptors.append({"uri": uri})
|
||||
continue
|
||||
if position is None or size is None:
|
||||
raise ValueError(
|
||||
f"uris[{index}] must set both position and size or neither"
|
||||
)
|
||||
position = _blob_uint64(position, f"positions[{index}]")
|
||||
size = _blob_uint64(size, f"sizes[{index}]")
|
||||
if size == 0:
|
||||
raise ValueError(f"sizes[{index}] must be positive to read a byte range")
|
||||
descriptors.append({"uri": uri, "position": position, "size": size})
|
||||
|
||||
blob_type = _resolve_blob_type()()
|
||||
storage = pa.array(descriptors, type=blob_type.storage_type)
|
||||
return pa.ExtensionArray.from_storage(blob_type, storage)
|
||||
|
||||
|
||||
def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType:
|
||||
"""A help function to create a vector type.
|
||||
|
||||
|
||||
@@ -5766,6 +5766,8 @@ class LanceTable(Table):
|
||||
namespace_client: Optional[Any] = None,
|
||||
pushdown_operations: Optional[set] = None,
|
||||
route_pushdown_to_rust: bool = False,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
):
|
||||
"""
|
||||
Create a new table.
|
||||
@@ -5819,6 +5821,20 @@ class LanceTable(Table):
|
||||
enable_v2_manifest_paths: optional, bool, default False
|
||||
Deprecated. Set `storage_options` when connecting to the database and set
|
||||
`new_table_enable_v2_manifest_paths` in the options.
|
||||
initial_bases: list, optional
|
||||
Storage bases to register in the table's manifest in the same
|
||||
commit that creates it. Each entry can be a
|
||||
[BasePath][lancedb.schema.BasePath], a dict with `path`, `name`,
|
||||
`is_dataset_root`, and `id` keys, or a `lance.DatasetBasePath`.
|
||||
Blob URIs under a registered base are stored relative to it. When
|
||||
supplying IDs for multiple bases, use distinct explicit non-zero
|
||||
IDs; [BasePath][lancedb.schema.BasePath] describes the pinned-Lance
|
||||
limitation.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Store blob URIs that do not fall under a registered base. The row
|
||||
keeps a reference, so the objects have to stay readable. The
|
||||
opt-in applies only to the initial data; a later `add()` must
|
||||
enable it again.
|
||||
"""
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
@@ -5870,6 +5886,8 @@ class LanceTable(Table):
|
||||
storage_options=storage_options,
|
||||
location=location,
|
||||
namespace_client=namespace_client,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
)
|
||||
self._branch = self._table.current_branch()
|
||||
|
||||
@@ -3176,3 +3176,393 @@ async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path):
|
||||
with file:
|
||||
actual.append(await file.aread())
|
||||
assert actual == [None, b"alpha", b"alpha"]
|
||||
|
||||
|
||||
def _initial_base_payloads(tmp_path):
|
||||
base_dir = tmp_path / "videos"
|
||||
base_dir.mkdir(exist_ok=True)
|
||||
payload = b"0123456789abcdef"
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
return base_dir, clip, payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("base_spec", ["lightweight", "dict", "dataset_base_path"])
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_initial_bases_store_relative_blob_ranges(
|
||||
tmp_path, base_spec, use_async
|
||||
):
|
||||
lance = None
|
||||
if base_spec == "dataset_base_path":
|
||||
lance = pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
field = lancedb.blob("video").with_metadata({"lancedb:logical_type": "mp4"})
|
||||
schema = pa.schema([pa.field("id", pa.int64()), field])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
base_kwargs = {"path": base_dir.as_uri(), "name": "source", "id": 1}
|
||||
if base_spec == "lightweight":
|
||||
bases = [lancedb.BasePath(**base_kwargs)]
|
||||
elif base_spec == "dict":
|
||||
bases = [base_kwargs]
|
||||
else:
|
||||
bases = [lance.DatasetBasePath(**base_kwargs)]
|
||||
|
||||
if use_async:
|
||||
db = await lancedb.connect_async(tmp_path / "db")
|
||||
table = await db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert await table.version() == 1
|
||||
created_schema = await table.schema()
|
||||
reopened = await db.open_table("videos")
|
||||
hits = await reopened.query().with_row_id().to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload[:6]]
|
||||
assert (
|
||||
await reopened.fetch_blob_ranges("video", [(row_id, 1, 3)])
|
||||
).to_pylist() == [payload[1:4]]
|
||||
else:
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
table = db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert table.version == 1
|
||||
created_schema = table.schema
|
||||
# Manifest introspection needs pylance; the lightweight and dict
|
||||
# variants must still prove registration through the reopen and bytes.
|
||||
if lance is not None:
|
||||
registered = table.to_lance().base_paths()[1]
|
||||
assert registered.path == base_dir.as_uri()
|
||||
assert registered.is_dataset_root is False
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
|
||||
payload[1:4]
|
||||
]
|
||||
assert created_schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
|
||||
|
||||
|
||||
def test_create_table_initial_bases_bootstrap_empty_table_with_auto_id(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source")],
|
||||
)
|
||||
assert table.version == 1
|
||||
registered = list(table.to_lance().base_paths().values())
|
||||
assert len(registered) == 1
|
||||
assert registered[0].id > 0
|
||||
assert registered[0].path == base_dir.as_uri()
|
||||
assert registered[0].is_dataset_root is False
|
||||
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
table.add(rows)
|
||||
reopened = db.open_table("videos")
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
assert reopened.fetch_blobs("video", [by_id[1]]).to_pylist() == [payload]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_reject_bad_input(tmp_path):
|
||||
base_dir, _, _ = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
db = lancedb.connect("memory:///")
|
||||
path = base_dir.as_uri()
|
||||
|
||||
with pytest.raises(ValueError, match="id=0"):
|
||||
lancedb.BasePath(path=path, id=0)
|
||||
with pytest.raises(ValueError, match="id=0"):
|
||||
db.create_table("zero", schema=schema, initial_bases=[{"path": path, "id": 0}])
|
||||
with pytest.raises(ValueError, match="unique"):
|
||||
db.create_table(
|
||||
"duplicates",
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=path, id=1),
|
||||
lancedb.BasePath(path=f"{path}/other", id=1),
|
||||
],
|
||||
)
|
||||
with pytest.raises(ValueError, match="missing 'path'"):
|
||||
db.create_table("missing_path", schema=schema, initial_bases=[{"id": 1}])
|
||||
with pytest.raises(TypeError, match="must be a BasePath, dict, or DatasetBasePath"):
|
||||
db.create_table("not_a_base", schema=schema, initial_bases=[object()])
|
||||
|
||||
|
||||
def test_create_table_allow_external_blob_outside_bases_is_atomic(tmp_path):
|
||||
payload = b"0123456789abcdef"
|
||||
clip = tmp_path / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
with pytest.raises(ValueError, match="allow_external_blob_outside_bases"):
|
||||
db.create_table("rejected", data=rows, schema=schema)
|
||||
with pytest.raises(ValueError, match="requires initial data"):
|
||||
db.create_table(
|
||||
"empty_opt_in", schema=schema, allow_external_blob_outside_bases=True
|
||||
)
|
||||
|
||||
table = db.create_table(
|
||||
"videos", data=rows, schema=schema, allow_external_blob_outside_bases=True
|
||||
)
|
||||
assert table.version == 1
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 0, 6)]).to_pylist() == [
|
||||
payload[:6]
|
||||
]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_keep_scoped_options_on_reopen(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
payload = b"scoped-payload"
|
||||
dir_a = tmp_path / "base-a"
|
||||
dir_b = tmp_path / "base-b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
clip_a = dir_a / "clip.mp4"
|
||||
clip_b = dir_b / "clip.mp4"
|
||||
clip_a.write_bytes(payload)
|
||||
clip_b.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1, 2], pa.int64()), videos], schema=schema
|
||||
)
|
||||
storage_options = {
|
||||
"timeout": "7s",
|
||||
"base_1.region": "base-one",
|
||||
"base_2.region": "base-two",
|
||||
}
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
|
||||
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
|
||||
],
|
||||
storage_options=storage_options,
|
||||
)
|
||||
assert table.version == 1
|
||||
assert {base.id for base in table.to_lance().base_paths().values()} == {1, 2}
|
||||
|
||||
reopened = db.open_table("videos", storage_options=storage_options)
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
assert reopened.fetch_blobs("video", [by_id[1], by_id[2]]).to_pylist() == [
|
||||
payload,
|
||||
payload,
|
||||
]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_through_namespace(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "ns")})
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
|
||||
)
|
||||
assert table.version == 1
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
|
||||
payload[1:4]
|
||||
]
|
||||
|
||||
|
||||
def test_namespace_create_keeps_scoped_options_over_connection_defaults(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, _ = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
{"root": str(tmp_path / "ns")},
|
||||
storage_options={"timeout": "7s"},
|
||||
)
|
||||
|
||||
# The invalid scoped option belongs to base 1. It must survive the merge
|
||||
# with connection defaults instead of being replaced by them.
|
||||
with pytest.raises(ValueError, match="scheduler_error_mode"):
|
||||
db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)
|
||||
],
|
||||
storage_options={"base_1.scheduler_error_mode": "invalid"},
|
||||
)
|
||||
|
||||
|
||||
def test_namespace_reopen_applies_scoped_options_per_base(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
payload_a = b"namespace-base-a"
|
||||
payload_b = b"namespace-base-b"
|
||||
dir_a = tmp_path / "base-a"
|
||||
dir_b = tmp_path / "base-b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
clip_a = dir_a / "clip.mp4"
|
||||
clip_b = dir_b / "clip.mp4"
|
||||
clip_a.write_bytes(payload_a)
|
||||
clip_b.write_bytes(payload_b)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1, 2], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
{"root": str(tmp_path / "ns")},
|
||||
storage_options={"timeout": "7s"},
|
||||
)
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
|
||||
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
|
||||
],
|
||||
)
|
||||
assert table.version == 1
|
||||
|
||||
reopened = db.open_table(
|
||||
"videos", storage_options={"base_1.scheduler_error_mode": "invalid"}
|
||||
)
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
with pytest.raises(ValueError, match="scheduler_error_mode"):
|
||||
reopened.fetch_blobs("video", [by_id[1]])
|
||||
assert reopened.fetch_blobs("video", [by_id[2]]).to_pylist() == [payload_b]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_initial_bases_through_async_namespace(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path / "ns")})
|
||||
|
||||
table = await db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
|
||||
)
|
||||
assert await table.version() == 1
|
||||
reopened = await db.open_table("videos")
|
||||
hits = await reopened.query().with_row_id().to_arrow()
|
||||
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload]
|
||||
|
||||
|
||||
def test_namespace_refresh_layers_caller_scoped_options(tmp_path):
|
||||
from lance_namespace import (
|
||||
DeclareTableResponse,
|
||||
DescribeTableResponse,
|
||||
LanceNamespace,
|
||||
)
|
||||
from lancedb.namespace import LanceNamespaceDBConnection
|
||||
|
||||
class RefreshingNamespace(LanceNamespace):
|
||||
def __init__(self, location):
|
||||
self.location = location
|
||||
self.refreshes = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return self.location
|
||||
|
||||
def declare_table(self, request):
|
||||
return DeclareTableResponse(
|
||||
location=self.location,
|
||||
storage_options={
|
||||
"timeout": "7s",
|
||||
# Expired immediately so the next read must refresh.
|
||||
"expires_at_millis": "1",
|
||||
},
|
||||
)
|
||||
|
||||
def describe_table(self, request):
|
||||
self.refreshes += 1
|
||||
return DescribeTableResponse(
|
||||
location=self.location,
|
||||
storage_options={"timeout": "8s", "namespace_vended": "fresh"},
|
||||
)
|
||||
|
||||
payload = b"0123456789abcdef"
|
||||
base_dir = tmp_path / "base"
|
||||
base_dir.mkdir()
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
namespace = RefreshingNamespace((tmp_path / "table.lance").as_uri())
|
||||
db = LanceNamespaceDBConnection(namespace)
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(base_dir.as_uri(), name="base", id=1)],
|
||||
storage_options={"base_1.caller_scoped": "keep-me"},
|
||||
)
|
||||
initial = table.initial_storage_options()
|
||||
assert initial["base_1.caller_scoped"] == "keep-me"
|
||||
assert initial["timeout"] == "7s"
|
||||
|
||||
latest = table.latest_storage_options()
|
||||
assert namespace.refreshes > 0, "expired seed did not trigger a refresh"
|
||||
assert latest["base_1.caller_scoped"] == "keep-me"
|
||||
assert latest["timeout"] == "8s"
|
||||
assert latest["namespace_vended"] == "fresh"
|
||||
assert table.version == 1
|
||||
|
||||
reopened = db.open_table(
|
||||
"videos", storage_options={"base_1.caller_scoped": "keep-me"}
|
||||
)
|
||||
assert reopened.latest_storage_options()["base_1.caller_scoped"] == "keep-me"
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", [row_id]).to_pylist() == [payload]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 4, 6)]).to_pylist() == [
|
||||
payload[4:10]
|
||||
]
|
||||
|
||||
@@ -85,3 +85,133 @@ def test_blob_array(with_pylance):
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_pylance", [False, True])
|
||||
def test_blob_uri_array(with_pylance):
|
||||
if with_pylance:
|
||||
pytest.importorskip("lance")
|
||||
# Use fresh processes so each extension class can own Arrow's registry.
|
||||
script = textwrap.dedent(
|
||||
"""\
|
||||
import importlib.abc
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
if sys.argv[1] == "False":
|
||||
class MissingLance(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
if fullname == "lance" or fullname.startswith("lance."):
|
||||
raise ModuleNotFoundError(fullname, name="lance")
|
||||
sys.meta_path.insert(0, MissingLance())
|
||||
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
from lancedb import BasePath, blob_uri_array
|
||||
from lancedb.schema import blob
|
||||
|
||||
if sys.argv[1] == "True":
|
||||
from lance import DatasetBasePath
|
||||
from lance.blob import BlobType
|
||||
else:
|
||||
from lancedb.schema import _FallbackBlobType as BlobType
|
||||
DatasetBasePath = None
|
||||
|
||||
schema = pa.schema([blob("video")])
|
||||
array = blob_uri_array(
|
||||
["s3://bucket/a.mp4", None, "b.mp4"],
|
||||
positions=[0, None, None],
|
||||
sizes=[4, None, None],
|
||||
)
|
||||
assert isinstance(array, pa.ExtensionArray)
|
||||
assert type(array.type) is BlobType
|
||||
assert array.type == schema.field("video").type
|
||||
assert array.storage.to_pylist() == [
|
||||
{"data": None, "uri": "s3://bucket/a.mp4", "position": 0, "size": 4},
|
||||
None,
|
||||
{"data": None, "uri": "b.mp4", "position": None, "size": None},
|
||||
]
|
||||
whole = blob_uri_array(iter(["s3://bucket/a.mp4"]))
|
||||
assert whole.storage.to_pylist() == [
|
||||
{"data": None, "uri": "s3://bucket/a.mp4", "position": None, "size": None}
|
||||
]
|
||||
|
||||
checks = [
|
||||
(lambda: blob_uri_array(["u"], positions=[0]), "provided together"),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], positions=[0, 0], sizes=[1, 1]),
|
||||
"same length",
|
||||
),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], sizes=[1, 1], positions=[0, 0]),
|
||||
"same length",
|
||||
),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], positions=[0], sizes=[None]),
|
||||
"both position and size",
|
||||
),
|
||||
(lambda: blob_uri_array(["u"], positions=[0], sizes=[0]), "positive"),
|
||||
(lambda: blob_uri_array(["u"], positions=[-1], sizes=[1]), "non-negative"),
|
||||
(lambda: blob_uri_array([None], positions=[0], sizes=[1]), "None but"),
|
||||
(lambda: blob_uri_array(["u"], positions=[0], sizes=[2**64]), "uint64"),
|
||||
(lambda: blob_uri_array([b"u"]), "must be a string"),
|
||||
]
|
||||
for call, fragment in checks:
|
||||
try:
|
||||
call()
|
||||
except (TypeError, ValueError, OverflowError) as error:
|
||||
assert fragment in str(error), (fragment, error)
|
||||
else:
|
||||
raise AssertionError(f"accepted invalid input: {fragment}")
|
||||
|
||||
try:
|
||||
BasePath("s3://bucket", id=0)
|
||||
except ValueError as error:
|
||||
assert "id=None" in str(error)
|
||||
else:
|
||||
raise AssertionError("accepted explicit id=0")
|
||||
|
||||
# The public create route must accept the helper and register the base
|
||||
# in the same commit as the data, with or without pylance.
|
||||
root = pathlib.Path(tempfile.mkdtemp())
|
||||
base_dir = root / "videos"
|
||||
base_dir.mkdir()
|
||||
payload = b"0123456789abcdef"
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
db = lancedb.connect(root / "db")
|
||||
field = blob("video").with_metadata({"lancedb:logical_type": "mp4"})
|
||||
table_schema = pa.schema([pa.field("id", pa.int64()), field])
|
||||
videos = blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=table_schema
|
||||
)
|
||||
if DatasetBasePath is not None:
|
||||
bases = [DatasetBasePath(path=base_dir.as_uri(), name="source")]
|
||||
else:
|
||||
bases = [BasePath(path=base_dir.as_uri(), name="source")]
|
||||
table = db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert table.version == 1
|
||||
assert (
|
||||
table.schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
|
||||
)
|
||||
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
|
||||
assert table.fetch_blobs("video", row_ids).to_pylist() == [payload[:6]]
|
||||
assert table.fetch_blob_ranges(
|
||||
"video", [(row_ids[0].as_py(), 1, 3)]
|
||||
).to_pylist() == [payload[1:4]]
|
||||
if DatasetBasePath is not None:
|
||||
base_paths = table.to_lance().base_paths()
|
||||
assert base_paths[1].path == base_dir.as_uri()
|
||||
assert base_paths[1].is_dataset_root is False
|
||||
if sys.argv[1] == "False":
|
||||
assert "lance" not in sys.modules
|
||||
"""
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script, str(with_pylance)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
@@ -1530,6 +1530,126 @@ def test_create_table_positional_parameters_match_base_contract():
|
||||
assert actual == expected
|
||||
|
||||
|
||||
def _unconsumed_create_input():
|
||||
raise AssertionError("create_table consumed input before rejecting the option")
|
||||
yield # pragma: no cover
|
||||
|
||||
|
||||
def _assert_enterprise_rejection(error):
|
||||
message = str(error)
|
||||
assert "not supported for table creation in LanceDB Enterprise" in message
|
||||
assert "Embedded" not in message
|
||||
assert "add(" not in message
|
||||
|
||||
|
||||
def test_create_table_rejects_blob_base_options_before_request():
|
||||
def handler(request):
|
||||
raise AssertionError(f"unexpected request: {request.path}")
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
with pytest.raises(NotImplementedError, match="initial_bases") as error:
|
||||
db.create_table(
|
||||
"test",
|
||||
data=_unconsumed_create_input(),
|
||||
initial_bases=[{"path": "s3://bucket/prefix"}],
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
) as error:
|
||||
db.create_table(
|
||||
"test",
|
||||
data=_unconsumed_create_input(),
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
) as error:
|
||||
db.create_table(
|
||||
"test",
|
||||
schema=schema,
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
|
||||
|
||||
def test_create_table_accepts_empty_blob_base_options():
|
||||
def handler(request):
|
||||
assert request.path == "/v1/table/test/create/?mode=create"
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(b"{}")
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = db.create_table(
|
||||
"test",
|
||||
schema=schema,
|
||||
initial_bases=[],
|
||||
allow_external_blob_outside_bases=False,
|
||||
)
|
||||
assert table is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_rejects_blob_base_options_before_request_async():
|
||||
def handler(request):
|
||||
raise AssertionError(f"unexpected request: {request.path}")
|
||||
|
||||
def reader():
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
return pa.RecordBatchReader.from_batches(schema, [])
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
async with mock_lancedb_connection_async(handler) as db:
|
||||
with pytest.raises(NotImplementedError, match="initial_bases") as error:
|
||||
await db.create_table(
|
||||
"test",
|
||||
data=_unconsumed_create_input(),
|
||||
initial_bases=[{"path": "s3://bucket/prefix"}],
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
) as error:
|
||||
await db.create_table(
|
||||
"test",
|
||||
data=_unconsumed_create_input(),
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
) as error:
|
||||
await db.create_table(
|
||||
"test",
|
||||
schema=schema,
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
# The lower-layer guard still maps Error::NotSupported for direct native
|
||||
# calls that bypass the Python entrypoint.
|
||||
with pytest.raises(NotImplementedError, match="initial_bases"):
|
||||
await db._inner.create_table(
|
||||
"test",
|
||||
"create",
|
||||
reader(),
|
||||
initial_bases=[{"path": "s3://bucket/prefix"}],
|
||||
)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
):
|
||||
await db._inner.create_table(
|
||||
"test",
|
||||
"create",
|
||||
reader(),
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
|
||||
|
||||
def test_create_table_exist_ok():
|
||||
def handler(request):
|
||||
if request.path == "/v1/table/test/create/?mode=exist_ok":
|
||||
|
||||
+152
-4
@@ -20,6 +20,7 @@ use arrow::{
|
||||
pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
|
||||
};
|
||||
use lancedb::{
|
||||
BasePath,
|
||||
connection::Connection as LanceConnection,
|
||||
connection::NamespaceClientPushdownOperation,
|
||||
database::namespace::LanceNamespaceDatabase,
|
||||
@@ -30,9 +31,9 @@ use lancedb::{
|
||||
};
|
||||
use pyo3::{
|
||||
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
|
||||
exceptions::{PyRuntimeError, PyValueError},
|
||||
exceptions::{PyRuntimeError, PyTypeError, PyValueError},
|
||||
pyclass, pyfunction, pymethods,
|
||||
types::{PyAnyMethods, PyDict, PyDictMethods, PyList},
|
||||
types::{PyAnyMethods, PyBool, PyDict, PyDictMethods, PyList},
|
||||
};
|
||||
|
||||
fn materialized_view_builder(
|
||||
@@ -56,6 +57,139 @@ fn materialized_view_builder(
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `initial_bases` into Lance base paths.
|
||||
///
|
||||
/// Accepts LanceDB's lightweight `BasePath`, a mapping with the same keys, or
|
||||
/// a duck-typed `lance.DatasetBasePath`. `None` maps to no bases. Object
|
||||
/// attributes follow `DatasetBasePath`: a reported `id` of `0` means
|
||||
/// automatic assignment, while a mapping that sets `id=0` explicitly is
|
||||
/// rejected because `0` is reserved for unregistered blob URIs. Explicit
|
||||
/// non-zero ids must be unique.
|
||||
fn parse_initial_bases(initial_bases: Option<Bound<'_, PyAny>>) -> PyResult<Option<Vec<BasePath>>> {
|
||||
let Some(value) = initial_bases else {
|
||||
return Ok(None);
|
||||
};
|
||||
if value.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut bases = Vec::new();
|
||||
let mut explicit_ids: HashSet<u32> = HashSet::new();
|
||||
for (index, item) in value.try_iter()?.enumerate() {
|
||||
let item = item?;
|
||||
let base = parse_base_path(&item, index)?;
|
||||
if base.id != 0 && !explicit_ids.insert(base.id) {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] reuses base id {}; explicit ids must be unique",
|
||||
base.id
|
||||
)));
|
||||
}
|
||||
bases.push(base);
|
||||
}
|
||||
Ok(Some(bases))
|
||||
}
|
||||
|
||||
fn parse_base_path(item: &Bound<'_, PyAny>, index: usize) -> PyResult<BasePath> {
|
||||
let (path, name, is_dataset_root, id) = if let Ok(dict) = item.cast::<PyDict>() {
|
||||
let path = required_string(dict.get_item("path")?, index, "path")?;
|
||||
let name = optional_string(dict.get_item("name")?, index, "name")?;
|
||||
let is_dataset_root =
|
||||
optional_bool(dict.get_item("is_dataset_root")?, index, "is_dataset_root")?;
|
||||
let id = match dict.get_item("id")? {
|
||||
None => 0,
|
||||
Some(value) if value.is_none() => 0,
|
||||
Some(value) => {
|
||||
let id = base_id(&value, index)?;
|
||||
if id == 0 {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] sets id=0, which is reserved for unregistered \
|
||||
blob URIs; pass id=None to let Lance assign an ID"
|
||||
)));
|
||||
}
|
||||
id
|
||||
}
|
||||
};
|
||||
(path, name, is_dataset_root, id)
|
||||
} else {
|
||||
let path = item.getattr("path").map_err(|_| {
|
||||
PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}] must be a BasePath, dict, or DatasetBasePath"
|
||||
))
|
||||
})?;
|
||||
let path = required_string(Some(path), index, "path")?;
|
||||
let name = item.getattr("name").ok().filter(|value| !value.is_none());
|
||||
let name = optional_string(name, index, "name")?;
|
||||
let is_dataset_root = match item.getattr("is_dataset_root") {
|
||||
Ok(value) if !value.is_none() => value.extract::<bool>().map_err(|_| {
|
||||
PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}].is_dataset_root must be a bool"
|
||||
))
|
||||
})?,
|
||||
_ => false,
|
||||
};
|
||||
let id = match item.getattr("id") {
|
||||
Ok(value) if !value.is_none() => base_id(&value, index)?,
|
||||
_ => 0,
|
||||
};
|
||||
(path, name, is_dataset_root, id)
|
||||
};
|
||||
|
||||
if path.is_empty() {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}].path must not be empty"
|
||||
)));
|
||||
}
|
||||
Ok(BasePath::new(id, path, name, is_dataset_root))
|
||||
}
|
||||
|
||||
fn required_string(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<String> {
|
||||
let Some(value) = value else {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] is missing '{field}'"
|
||||
)));
|
||||
};
|
||||
value.extract::<String>().map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
|
||||
})
|
||||
}
|
||||
|
||||
fn optional_string(
|
||||
value: Option<Bound<'_, PyAny>>,
|
||||
index: usize,
|
||||
field: &str,
|
||||
) -> PyResult<Option<String>> {
|
||||
match value {
|
||||
None => Ok(None),
|
||||
Some(value) if value.is_none() => Ok(None),
|
||||
Some(value) => value.extract::<String>().map(Some).map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_bool(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<bool> {
|
||||
match value {
|
||||
None => Ok(false),
|
||||
Some(value) if value.is_none() => Ok(false),
|
||||
Some(value) => value.extract::<bool>().map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a bool"))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn base_id(value: &Bound<'_, PyAny>, index: usize) -> PyResult<u32> {
|
||||
if value.is_instance_of::<PyBool>() {
|
||||
return Err(PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}].id must be a positive integer, not a bool"
|
||||
)));
|
||||
}
|
||||
value.extract::<u32>().map_err(|_| {
|
||||
PyValueError::new_err(format!(
|
||||
"initial_bases[{index}].id must be a positive integer that fits in a u32"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[pyclass]
|
||||
pub struct Connection {
|
||||
inner: Option<LanceConnection>,
|
||||
@@ -311,7 +445,7 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
|
||||
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None, allow_external_blob_outside_bases=false))]
|
||||
pub fn create_table<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
name: String,
|
||||
@@ -321,11 +455,14 @@ impl Connection {
|
||||
storage_options: Option<HashMap<String, String>>,
|
||||
location: Option<String>,
|
||||
namespace_client: Option<Py<PyAny>>,
|
||||
initial_bases: Option<Bound<'_, PyAny>>,
|
||||
allow_external_blob_outside_bases: bool,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let py = self_.py();
|
||||
|
||||
let mode = Self::parse_create_mode_str(mode)?;
|
||||
let initial_bases = parse_initial_bases(initial_bases)?;
|
||||
|
||||
let batches: Box<dyn arrow::array::RecordBatchReader + Send> =
|
||||
Box::new(ArrowArrayStreamReader::from_pyarrow_bound(&data)?);
|
||||
@@ -333,6 +470,12 @@ impl Connection {
|
||||
let ns_path = namespace_path.clone().unwrap_or_default();
|
||||
let mut builder = inner.create_table(name.clone(), batches).mode(mode);
|
||||
|
||||
if let Some(bases) = initial_bases {
|
||||
builder = builder.initial_bases(bases);
|
||||
}
|
||||
if allow_external_blob_outside_bases {
|
||||
builder = builder.allow_external_blob_outside_bases(true);
|
||||
}
|
||||
builder = builder.namespace(ns_path.clone());
|
||||
if let Some(storage_options) = storage_options {
|
||||
builder = builder.storage_options(storage_options);
|
||||
@@ -359,7 +502,7 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
|
||||
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None))]
|
||||
pub fn create_empty_table<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
name: String,
|
||||
@@ -369,11 +512,13 @@ impl Connection {
|
||||
storage_options: Option<HashMap<String, String>>,
|
||||
location: Option<String>,
|
||||
namespace_client: Option<Py<PyAny>>,
|
||||
initial_bases: Option<Bound<'_, PyAny>>,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let py = self_.py();
|
||||
|
||||
let mode = Self::parse_create_mode_str(mode)?;
|
||||
let initial_bases = parse_initial_bases(initial_bases)?;
|
||||
|
||||
let schema = Schema::from_pyarrow_bound(&schema)?;
|
||||
|
||||
@@ -382,6 +527,9 @@ impl Connection {
|
||||
.create_empty_table(name.clone(), Arc::new(schema))
|
||||
.mode(mode);
|
||||
|
||||
if let Some(bases) = initial_bases {
|
||||
builder = builder.initial_bases(bases);
|
||||
}
|
||||
builder = builder.namespace(ns_path.clone());
|
||||
if let Some(storage_options) = storage_options {
|
||||
builder = builder.storage_options(storage_options);
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use lance::dataset::WriteParams;
|
||||
use lance::table::format::BasePath;
|
||||
use lance_io::object_store::StorageOptionsProvider;
|
||||
|
||||
use crate::{
|
||||
@@ -53,6 +55,67 @@ impl CreateTableBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Register additional base paths in the new table's manifest.
|
||||
///
|
||||
/// The bases are written in the same commit that creates the table, so a
|
||||
/// create with data stays a single atomic operation. Blob URIs that fall
|
||||
/// under a registered base are stored relative to it instead of as absolute
|
||||
/// URIs; see [`Table::fetch_blobs`].
|
||||
///
|
||||
/// Set [`BasePath::id`] to `0` to let Lance assign an ID, or to a unique
|
||||
/// non-zero value. Pass an empty list to leave the request unchanged.
|
||||
///
|
||||
/// When supplying IDs for multiple bases, use distinct explicit non-zero
|
||||
/// IDs. The pinned Lance release can collide when one base asks for
|
||||
/// automatic allocation (`0`) and another supplies an explicit ID: the
|
||||
/// create fails, the table name can remain listed but unopenable, and
|
||||
/// retrying with distinct explicit IDs succeeds. Automatic allocation for
|
||||
/// every base is supported.
|
||||
///
|
||||
/// LanceDB Embedded only.
|
||||
///
|
||||
/// [`Table::fetch_blobs`]: crate::table::Table::fetch_blobs
|
||||
pub fn initial_bases(mut self, bases: Vec<BasePath>) -> Self {
|
||||
let empty = bases.is_empty();
|
||||
self.update_lance_write_params(!empty, |params| {
|
||||
params.initial_bases = (!empty).then_some(bases);
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// Store blob URIs that sit outside registered blob bases.
|
||||
///
|
||||
/// The row keeps a reference, so the object has to stay readable.
|
||||
/// [`Table::fetch_blobs`] reads from that location. Defaults to `false`.
|
||||
///
|
||||
/// The opt-in covers only the rows written by this create. A later `add`
|
||||
/// must enable it again.
|
||||
///
|
||||
/// LanceDB Embedded only.
|
||||
///
|
||||
/// [`Table::fetch_blobs`]: crate::table::Table::fetch_blobs
|
||||
pub fn allow_external_blob_outside_bases(mut self, allow: bool) -> Self {
|
||||
self.update_lance_write_params(allow, |params| {
|
||||
params.allow_external_blob_outside_bases = allow;
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// Apply `update` to the Lance write parameters, creating them only when
|
||||
/// `create` is set. A no-op call on a request that has no write parameters
|
||||
/// leaves it that way, so default creation does not look customized.
|
||||
fn update_lance_write_params(&mut self, create: bool, update: impl FnOnce(&mut WriteParams)) {
|
||||
if !create && self.request.write_options.lance_write_params.is_none() {
|
||||
return;
|
||||
}
|
||||
update(
|
||||
self.request
|
||||
.write_options
|
||||
.lance_write_params
|
||||
.get_or_insert_default(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Set an option for the storage layer.
|
||||
///
|
||||
/// Options already set on the connection will be inherited by the table,
|
||||
@@ -218,6 +281,24 @@ mod tests {
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_table_with_default_blob_base_options() {
|
||||
// Explicit empty bases and opt-out follow the ordinary create path: no
|
||||
// write parameters are attached just because the fluent methods ran.
|
||||
let db = connect("memory://").execute().await.unwrap();
|
||||
let batch = record_batch!(("id", Int64, [1, 2, 3])).unwrap();
|
||||
|
||||
let table = db
|
||||
.create_table("no_bases", batch)
|
||||
.initial_bases(Vec::new())
|
||||
.allow_external_blob_outside_bases(false)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 3);
|
||||
}
|
||||
|
||||
async fn test_create_table_with_data<T>(data: T)
|
||||
where
|
||||
T: Scannable + 'static,
|
||||
|
||||
@@ -238,6 +238,7 @@ pub use connection::{ConnectNamespaceBuilder, Connection};
|
||||
pub use error::{Error, JobFailure, Result};
|
||||
pub use function::FunctionVersion;
|
||||
pub use job::Job;
|
||||
pub use lance::table::format::BasePath;
|
||||
use lance_index::vector::ApproxMode as LanceApproxMode;
|
||||
use lance_linalg::distance::DistanceType as LanceDistanceType;
|
||||
pub use materialized_view::{
|
||||
|
||||
@@ -1552,6 +1552,30 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
|
||||
// The remote create endpoint does not transmit Lance write parameters.
|
||||
// Reject them before consuming data or issuing a request, especially
|
||||
// for overwrite: silently using the server's format can lose intent.
|
||||
//
|
||||
// Name the blob-base options specifically: they carry data placement
|
||||
// and URI-resolution semantics the server cannot honor, and a generic
|
||||
// "write_options" message would not tell the caller which input to drop.
|
||||
if let Some(params) = request.write_options.lance_write_params.as_ref() {
|
||||
let unsupported = if params
|
||||
.initial_bases
|
||||
.as_ref()
|
||||
.is_some_and(|bases| !bases.is_empty())
|
||||
{
|
||||
Some("initial_bases")
|
||||
} else if params.allow_external_blob_outside_bases {
|
||||
Some("allow_external_blob_outside_bases")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(option) = unsupported {
|
||||
return Err(Error::NotSupported {
|
||||
message: format!(
|
||||
"{option} is not supported for table creation in LanceDB Enterprise"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (option, provided) in [
|
||||
(
|
||||
"write_options (including storage_options)",
|
||||
@@ -2913,6 +2937,89 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_rejects_blob_base_options_before_reading_input() {
|
||||
let conn = Connection::new_with_handler(|_| -> http::Response<&'static str> {
|
||||
panic!("must not send a create request")
|
||||
});
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
|
||||
let base = crate::BasePath::new(1, "s3://bucket/prefix".to_string(), None, false);
|
||||
|
||||
let reads = Arc::new(AtomicUsize::new(0));
|
||||
let data: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new(CountingReader {
|
||||
schema: schema.clone(),
|
||||
reads: reads.clone(),
|
||||
});
|
||||
let err = conn
|
||||
.create_table("table1", data)
|
||||
.initial_bases(vec![base])
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, Error::NotSupported { ref message } if message.contains("initial_bases")),
|
||||
"got {err:?}"
|
||||
);
|
||||
assert_eq!(reads.load(Ordering::SeqCst), 0);
|
||||
|
||||
let err = conn
|
||||
.create_empty_table("table1", schema)
|
||||
.allow_external_blob_outside_bases(true)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, Error::NotSupported { ref message } if message.contains("allow_external_blob_outside_bases")),
|
||||
"got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_accepts_empty_blob_base_options() {
|
||||
// Empty bases and the explicit opt-out are not customization: the remote
|
||||
// create must stay an ordinary request.
|
||||
let conn = Connection::new_with_handler(|request| {
|
||||
assert_eq!(request.url().path(), "/v1/table/table1/create/");
|
||||
http::Response::builder().status(200).body("").unwrap()
|
||||
});
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
|
||||
let data = RecordBatch::try_new(
|
||||
schema.clone(),
|
||||
vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
|
||||
)
|
||||
.unwrap();
|
||||
for builder in [
|
||||
conn.create_table("table1", data)
|
||||
.initial_bases(Vec::new())
|
||||
.allow_external_blob_outside_bases(false),
|
||||
conn.create_empty_table("table1", schema)
|
||||
.initial_bases(Vec::new())
|
||||
.allow_external_blob_outside_bases(false),
|
||||
] {
|
||||
assert!(builder.execute().await.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
struct CountingReader {
|
||||
schema: Arc<Schema>,
|
||||
reads: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Iterator for CountingReader {
|
||||
type Item = Result<RecordBatch, arrow_schema::ArrowError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.reads.fetch_add(1, Ordering::SeqCst);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl arrow_array::RecordBatchReader for CountingReader {
|
||||
fn schema(&self) -> arrow_schema::SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_open_rejects_local_options_even_when_cached(#[values(false, true)] cached: bool) {
|
||||
|
||||
@@ -2085,3 +2085,377 @@ async fn blob_layout_rte_merge_normalizes_before_writing() -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One-row blob v2 batch carrying an external URI with an explicit byte range.
|
||||
fn range_uri_batch(
|
||||
ids: &[i64],
|
||||
uris: &[&str],
|
||||
positions: &[Option<u64>],
|
||||
sizes: &[Option<u64>],
|
||||
) -> RecordBatch {
|
||||
let image_field = lancedb::blob("image", true);
|
||||
let DataType::Struct(children) = image_field.data_type().clone() else {
|
||||
unreachable!("blob field is a struct");
|
||||
};
|
||||
let values = StructArray::new(
|
||||
children,
|
||||
vec![
|
||||
new_null_array(&DataType::LargeBinary, ids.len()),
|
||||
Arc::new(StringArray::from_iter_values(uris.iter().copied())),
|
||||
Arc::new(UInt64Array::from(positions.to_vec())),
|
||||
Arc::new(UInt64Array::from(sizes.to_vec())),
|
||||
],
|
||||
None,
|
||||
);
|
||||
RecordBatch::try_new(
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
image_field,
|
||||
])),
|
||||
vec![Arc::new(Int64Array::from(ids.to_vec())), Arc::new(values)],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn wide_blob_table_schema() -> Arc<Schema> {
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
lancedb::blob("image", true),
|
||||
]))
|
||||
}
|
||||
|
||||
fn local_base(id: u32, path: String) -> BasePath {
|
||||
BasePath {
|
||||
id,
|
||||
name: Some(format!("base{id}")),
|
||||
path,
|
||||
is_dataset_root: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_local_payload(dir: &std::path::Path, name: &str, payload: &[u8]) -> (String, String) {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, payload).unwrap();
|
||||
(
|
||||
url::Url::from_file_path(&path).unwrap().to_string(),
|
||||
url::Url::from_directory_path(dir).unwrap().to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A create with data and `initial_bases` must commit once. Registering the
|
||||
/// base in a later commit, or creating empty first, would bump the version and
|
||||
/// leave an intermediate table without its storage.
|
||||
#[tokio::test]
|
||||
async fn create_table_with_data_registers_initial_base_atomically() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload = b"0123456789abcdef";
|
||||
let (clip_uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", payload);
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let table = db
|
||||
.create_table(
|
||||
"videos",
|
||||
range_uri_batch(&[1], &[clip_uri.as_str()], &[Some(0)], &[Some(6)]),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_uri.clone())])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
assert_eq!(table.version().await?, 1);
|
||||
let manifest = table.as_native().unwrap().manifest().await?;
|
||||
let registered = manifest.base_paths.get(&1).expect("base 1 registered");
|
||||
assert_eq!(registered.path, base_uri);
|
||||
assert!(!registered.is_dataset_root);
|
||||
|
||||
let reopened = db.open_table("videos").execute().await?;
|
||||
let ids = collect_row_ids(&reopened).await?;
|
||||
let files = reopened.fetch_blob_files("image", &ids).await?;
|
||||
let file = files[0].as_ref().unwrap();
|
||||
assert_eq!(file.uri(), Some("clip.mp4"));
|
||||
assert_eq!(file.position(), Some(0));
|
||||
assert_eq!(file.size(), 6);
|
||||
let bytes = reopened.fetch_blobs("image", &ids).await?;
|
||||
assert_eq!(bytes.value(0), &payload[..6]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_table_with_data_accepts_unregistered_uri_only_with_opt_in() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload = b"0123456789abcdef";
|
||||
let (clip_uri, _) = write_local_payload(tmp.path(), "clip.mp4", payload);
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
let batch = range_uri_batch(&[1], &[clip_uri.as_str()], &[Some(0)], &[Some(6)]);
|
||||
|
||||
let err = db
|
||||
.create_table("videos", batch.clone())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("allow_external_blob_outside_bases"),
|
||||
"got: {err}"
|
||||
);
|
||||
assert!(db.open_table("videos").execute().await.is_err());
|
||||
|
||||
let table = db
|
||||
.create_table("videos", batch)
|
||||
.allow_external_blob_outside_bases(true)
|
||||
.execute()
|
||||
.await?;
|
||||
assert_eq!(table.version().await?, 1);
|
||||
let reopened = db.open_table("videos").execute().await?;
|
||||
let ids = collect_row_ids(&reopened).await?;
|
||||
let bytes = reopened.fetch_blobs("image", &ids).await?;
|
||||
assert_eq!(bytes.value(0), &payload[..6]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An explicit `id=0` asks Lance to assign the base ID in the create commit.
|
||||
#[tokio::test]
|
||||
async fn create_empty_table_with_initial_bases_bootstraps_base_with_auto_id() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload = b"payload-bytes";
|
||||
let (clip_uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", payload);
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let table = db
|
||||
.create_empty_table("videos", wide_blob_table_schema())
|
||||
.initial_bases(vec![local_base(0, base_uri.clone())])
|
||||
.execute()
|
||||
.await?;
|
||||
let manifest = table.as_native().unwrap().manifest().await?;
|
||||
let registered = manifest
|
||||
.base_paths
|
||||
.values()
|
||||
.find(|base| base.path == base_uri)
|
||||
.expect("base registered with the empty create");
|
||||
assert!(registered.id > 0);
|
||||
assert!(!registered.is_dataset_root);
|
||||
|
||||
table
|
||||
.add(range_uri_batch(
|
||||
&[1],
|
||||
&[clip_uri.as_str()],
|
||||
&[None],
|
||||
&[None],
|
||||
))
|
||||
.execute()
|
||||
.await?;
|
||||
let reopened = db.open_table("videos").execute().await?;
|
||||
let ids = collect_row_ids(&reopened).await?;
|
||||
let files = reopened.fetch_blob_files("image", &ids).await?;
|
||||
assert_eq!(files[0].as_ref().unwrap().uri(), Some("clip.mp4"));
|
||||
let bytes = reopened.fetch_blobs("image", &ids).await?;
|
||||
assert_eq!(bytes.value(0), payload);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scoped `base_<id>.<key>` options travel with the table and keep each base
|
||||
/// readable after reopen. Unscoped options stay shared defaults.
|
||||
#[tokio::test]
|
||||
async fn created_bases_read_back_with_scoped_storage_options() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload_a = b"base-a-payload";
|
||||
let payload_b = b"base-b-payload";
|
||||
let dir_a = tmp.path().join("base-a");
|
||||
let dir_b = tmp.path().join("base-b");
|
||||
std::fs::create_dir_all(&dir_a).unwrap();
|
||||
std::fs::create_dir_all(&dir_b).unwrap();
|
||||
let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a);
|
||||
let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b);
|
||||
let storage_options = [
|
||||
("timeout", "7s"),
|
||||
("base_1.region", "base-one"),
|
||||
("base_2.region", "base-two"),
|
||||
];
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let table = db
|
||||
.create_table(
|
||||
"videos",
|
||||
range_uri_batch(
|
||||
&[1, 2],
|
||||
&[uri_a.as_str(), uri_b.as_str()],
|
||||
&[None, None],
|
||||
&[None, None],
|
||||
),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_a), local_base(2, base_b)])
|
||||
.storage_options(storage_options)
|
||||
.execute()
|
||||
.await?;
|
||||
assert_eq!(table.version().await?, 1);
|
||||
|
||||
let reopened = db
|
||||
.open_table("videos")
|
||||
.storage_options(storage_options)
|
||||
.execute()
|
||||
.await?;
|
||||
let ids = collect_row_ids(&reopened).await?;
|
||||
let files = reopened.fetch_blob_files("image", &ids).await?;
|
||||
assert_eq!(files[0].as_ref().unwrap().uri(), Some("clip.mp4"));
|
||||
assert_eq!(files[1].as_ref().unwrap().uri(), Some("clip.mp4"));
|
||||
let bytes = reopened.fetch_blobs("image", &ids).await?;
|
||||
assert_eq!(bytes.value(0), payload_a);
|
||||
assert_eq!(bytes.value(1), payload_b);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scoped `base_<id>.<key>` options belong to exactly one base. An option
|
||||
/// that only base 1 can reject must not change what base 2 reads on reopen.
|
||||
#[tokio::test]
|
||||
async fn scoped_storage_options_do_not_leak_between_bases_on_reopen() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload_a = b"base-a-payload";
|
||||
let payload_b = b"base-b-payload";
|
||||
let dir_a = tmp.path().join("base-a");
|
||||
let dir_b = tmp.path().join("base-b");
|
||||
std::fs::create_dir_all(&dir_a).unwrap();
|
||||
std::fs::create_dir_all(&dir_b).unwrap();
|
||||
let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a);
|
||||
let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b);
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
db.create_table(
|
||||
"videos",
|
||||
range_uri_batch(
|
||||
&[1, 2],
|
||||
&[uri_a.as_str(), uri_b.as_str()],
|
||||
&[None, None],
|
||||
&[None, None],
|
||||
),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_a), local_base(2, base_b)])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let reopened = db
|
||||
.open_table("videos")
|
||||
.storage_options([("base_1.scheduler_error_mode", "invalid")])
|
||||
.execute()
|
||||
.await?;
|
||||
let pairs = sorted_id_rowid(&reopened).await?;
|
||||
let row_for = |id: i64| {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(row_id, _)| *row_id == id)
|
||||
.map(|(_, row_id)| *row_id)
|
||||
.expect("row present")
|
||||
};
|
||||
|
||||
let err = reopened
|
||||
.fetch_blobs("image", &[row_for(1)])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("scheduler_error_mode"),
|
||||
"base 1 should carry its scoped option, got: {err}"
|
||||
);
|
||||
let bytes = reopened.fetch_blobs("image", &[row_for(2)]).await?;
|
||||
assert_eq!(bytes.value(0), payload_b);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn namespace_properties(root: &std::path::Path) -> std::collections::HashMap<String, String> {
|
||||
std::collections::HashMap::from([("root".to_string(), root.to_str().unwrap().to_string())])
|
||||
}
|
||||
|
||||
/// Connection-level storage options must be merged under the request's
|
||||
/// storage options on the namespace create path. Replacing the request
|
||||
/// accessor drops `base_<id>.<key>` settings and silently accepts options the
|
||||
/// selected base cannot use.
|
||||
#[tokio::test]
|
||||
async fn namespace_create_keeps_caller_scoped_storage_options() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let (uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", b"namespace-scoped");
|
||||
let db = connect_namespace("dir", namespace_properties(&tmp.path().join("ns")))
|
||||
.storage_options([("timeout", "7s")])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let err = db
|
||||
.create_table(
|
||||
"videos",
|
||||
range_uri_batch(&[1], &[uri.as_str()], &[None], &[None]),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_uri)])
|
||||
.storage_option("base_1.scheduler_error_mode", "invalid")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("scheduler_error_mode"),
|
||||
"request-scoped option was dropped, got: {err}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A namespace reopen keeps scoped options attached to their own base: base
|
||||
/// 1's invalid option fails its read while base 2 still returns exact bytes.
|
||||
#[tokio::test]
|
||||
async fn namespace_reopen_applies_scoped_options_to_their_own_base() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload_a = b"namespace-base-a";
|
||||
let payload_b = b"namespace-base-b";
|
||||
let dir_a = tmp.path().join("base-a");
|
||||
let dir_b = tmp.path().join("base-b");
|
||||
std::fs::create_dir_all(&dir_a).unwrap();
|
||||
std::fs::create_dir_all(&dir_b).unwrap();
|
||||
let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a);
|
||||
let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b);
|
||||
let db = connect_namespace("dir", namespace_properties(&tmp.path().join("ns")))
|
||||
.storage_options([("timeout", "7s")])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
db.create_table(
|
||||
"videos",
|
||||
range_uri_batch(
|
||||
&[1, 2],
|
||||
&[uri_a.as_str(), uri_b.as_str()],
|
||||
&[None, None],
|
||||
&[None, None],
|
||||
),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_a), local_base(2, base_b)])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let reopened = db
|
||||
.open_table("videos")
|
||||
.storage_options([("base_1.scheduler_error_mode", "invalid")])
|
||||
.execute()
|
||||
.await?;
|
||||
let pairs = sorted_id_rowid(&reopened).await?;
|
||||
let row_for = |id: i64| {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(row_id, _)| *row_id == id)
|
||||
.map(|(_, row_id)| *row_id)
|
||||
.expect("row present")
|
||||
};
|
||||
|
||||
let err = reopened
|
||||
.fetch_blobs("image", &[row_for(1)])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("scheduler_error_mode"),
|
||||
"base 1 should carry its scoped option, got: {err}"
|
||||
);
|
||||
let bytes = reopened.fetch_blobs("image", &[row_for(2)]).await?;
|
||||
assert_eq!(bytes.value(0), payload_b);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user