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