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:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user