Merge main into gatekeeper/fix-5007-1

This commit is contained in:
Gatefixer
2026-11-14 04:27:06 +00:00
57 changed files with 1902 additions and 598 deletions
+17 -2
View File
@@ -188,7 +188,11 @@ class Connection(object):
async def server_info(self) -> str: ...
async def list_gpu_classes(self) -> list[GpuClass]: ...
async def create_function_async(
self, request_json: str, namespace_path: Optional[List[str]] = None
self,
request_json: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> Job: ...
async def get_function(
self,
@@ -253,7 +257,12 @@ class Connection(object):
self, name: str, namespace_path: Optional[List[str]] = None
) -> Tuple[str, int, int]: ...
async def create_view(
self, name: str, query: str, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ...
async def describe_view(
self, name: str, namespace_path: Optional[List[str]] = None
@@ -338,6 +347,8 @@ class Connection(object):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
*,
exist_ok: bool = False,
) -> Table: ...
async def rename_table(
self,
@@ -358,6 +369,7 @@ class Connection(object):
auto_refresh_interval_seconds: Optional[float] = None,
*,
query: Optional[str] = None,
exist_ok: bool = False,
) -> Table: ...
async def create_materialized_view_async(
self,
@@ -371,6 +383,7 @@ class Connection(object):
auto_refresh_interval_seconds: Optional[float] = None,
*,
query: Optional[str] = None,
exist_ok: bool = False,
) -> Job: ...
def list_materialized_views(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
@@ -578,6 +591,7 @@ class Table:
*,
name: Optional[str],
train: Optional[bool],
exist_ok: bool = False,
): ...
async def create_index_async(
self,
@@ -602,6 +616,7 @@ class Table:
*,
name: Optional[str],
train: Optional[bool],
exist_ok: bool = False,
) -> Job: ...
async def list_versions(self) -> List[Dict[str, Any]]: ...
async def version(self) -> int: ...
+96 -11
View File
@@ -432,8 +432,12 @@ class DBConnection(EnforceOverrides):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
"""Register storage access, preserving existing configuration with
``exist_ok=True``. Existing names are errors by default.
"""
raise NotImplementedError
def describe_storage_integration(
@@ -706,11 +710,15 @@ class DBConnection(EnforceOverrides):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
``exist_ok=True`` preserves an existing view's definition, data and
refresh settings without refreshing it. Existing names error by default.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Enterprise operations remain available.
@@ -776,11 +784,15 @@ class DBConnection(EnforceOverrides):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
"""Submit materialized-view creation and return its job.
``exist_ok=True`` preserves an existing view without refreshing it.
A skipped creation returns a completed job without a registry job ID.
The job may already be complete in LanceDB Embedded. In LanceDB
Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL
server and the returned ``id`` is the registry job ID. That ID can be
@@ -1004,10 +1016,14 @@ class DBConnection(EnforceOverrides):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
"""Build and register a scalar Python function, then return its version.
``exist_ok=True`` returns the existing named Function version unchanged.
By default, registration retains its existing version-creation behavior.
The server builds the OCI image and registers the completed artifact.
This is the blocking counterpart of :meth:`create_function_async`.
LanceDB Embedded connections raise ``NotImplementedError``.
@@ -1040,7 +1056,10 @@ class DBConnection(EnforceOverrides):
```
"""
return self.create_function_async(
definition, secrets=secrets, namespace_path=namespace_path
definition,
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
).wait()
def create_function_async(
@@ -1048,10 +1067,14 @@ class DBConnection(EnforceOverrides):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> Job[FunctionVersion]:
"""Submit a scalar Python function for building and registration.
``exist_ok=True`` preserves an existing named version and its metadata.
The default retains the existing version-creation behavior.
The server-side job builds the OCI image, then registers the completed
artifact. The returned job has type ``query`` and the SQL query UUID as
its ID. Waiting on it returns the immutable Function version.
@@ -1273,7 +1296,12 @@ class DBConnection(EnforceOverrides):
)
def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
"""Create a view: a named query the database plans on every read.
@@ -1281,9 +1309,10 @@ class DBConnection(EnforceOverrides):
is refused now rather than at the first read. A view holds no rows, and
its readers see its sources as they are at read time.
There is no replace: a name already taken is an error, and changing a
view is a drop followed by a create. LanceDB Embedded connections raise
``NotImplementedError``.
A name already taken is an error unless ``exist_ok=True``, which returns
the existing view's stored query and schema without changing them.
Changing a view is a drop followed by a create. LanceDB Embedded
connections raise ``NotImplementedError``.
>>> import lancedb
>>> db = lancedb.connect("db://my_database") # doctest: +SKIP
@@ -2129,11 +2158,15 @@ class LanceDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
``exist_ok=True`` preserves an existing view's definition, data and
refresh settings without refreshing it. Existing names error by default.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Enterprise operations remain available.
@@ -2164,6 +2197,7 @@ class LanceDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -2181,6 +2215,7 @@ class LanceDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
@@ -2193,6 +2228,7 @@ class LanceDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -2250,6 +2286,7 @@ class LanceDBConnection(DBConnection):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
exist_ok: bool = False,
) -> LanceTable:
"""Clone a table from a source table.
@@ -2274,6 +2311,8 @@ class LanceDBConnection(DBConnection):
is_shallow: bool, default True
Whether to perform a shallow clone (True) or deep clone (False).
Currently only shallow clone is supported.
exist_ok: bool, default False
Return the existing target unchanged instead of cloning over it.
Returns
-------
@@ -2289,6 +2328,7 @@ class LanceDBConnection(DBConnection):
source_version=source_version,
source_tag=source_tag,
is_shallow=is_shallow,
exist_ok=exist_ok,
)
)
return LanceTable.open(
@@ -2390,11 +2430,15 @@ class LanceDBConnection(DBConnection):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> Job[FunctionVersion]:
job = LOOP.run(
self._conn.create_function_async(
definition, secrets=secrets, namespace_path=namespace_path
definition,
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
return Job(job)
@@ -2482,6 +2526,7 @@ class LanceDBConnection(DBConnection):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
return LOOP.run(
@@ -2499,6 +2544,7 @@ class LanceDBConnection(DBConnection):
azure_client_secret_secret=azure_client_secret_secret,
gcp_credentials_json_secret=gcp_credentials_json_secret,
huggingface_token_secret=huggingface_token_secret,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
@@ -2592,10 +2638,17 @@ class LanceDBConnection(DBConnection):
@override
def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
return LOOP.run(
self._conn.create_view(name, query, namespace_path=namespace_path)
self._conn.create_view(
name, query, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
@@ -3415,11 +3468,15 @@ class AsyncConnection(object):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> AsyncMaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
``exist_ok=True`` preserves an existing view's definition, data and
refresh settings without refreshing it. Existing names error by default.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Enterprise operations remain available.
@@ -3442,6 +3499,7 @@ class AsyncConnection(object):
filter=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
**native_options,
@@ -3458,11 +3516,15 @@ class AsyncConnection(object):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> AsyncJob[None]:
"""Submit materialized-view creation and return its job.
``exist_ok=True`` preserves an existing view without refreshing it.
A skipped creation returns a completed job without a registry job ID.
Wait for the returned job before opening or querying the view. In LanceDB
Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id``
identifies that query on this connection.
@@ -3483,6 +3545,7 @@ class AsyncConnection(object):
filter=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
**native_options,
@@ -3561,6 +3624,7 @@ class AsyncConnection(object):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
exist_ok: bool = False,
) -> AsyncTable:
"""Clone a table from a source table.
@@ -3585,6 +3649,8 @@ class AsyncConnection(object):
is_shallow: bool, default True
Whether to perform a shallow clone (True) or deep clone (False).
Currently only shallow clone is supported.
exist_ok: bool, default False
Return the existing target unchanged instead of cloning over it.
Returns
-------
@@ -3599,6 +3665,7 @@ class AsyncConnection(object):
source_version=source_version,
source_tag=source_tag,
is_shallow=is_shallow,
exist_ok=exist_ok,
)
return AsyncTable(table)
@@ -3719,10 +3786,14 @@ class AsyncConnection(object):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> AsyncJob[FunctionVersion]:
"""Submit a scalar Python function for building and registration.
``exist_ok=True`` preserves an existing named version and its metadata.
The default retains the existing version-creation behavior.
The server-side job builds the OCI image, then registers the completed
artifact. The returned job has type ``query`` and the SQL query UUID as
its ID. Waiting on it returns the immutable Function version.
@@ -3736,7 +3807,7 @@ class AsyncConnection(object):
raise TypeError("create_function_async requires a @function definition")
request = definition.bind_secrets(secrets)
inner = await self._inner.create_function_async(
request.to_canonical_json(), namespace_path
request.to_canonical_json(), namespace_path, exist_ok=exist_ok
)
return _typed_job(inner, FunctionVersion.from_json)
@@ -3856,6 +3927,7 @@ class AsyncConnection(object):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
"""Register cloud storage access using database-owned credential Secrets.
@@ -3870,6 +3942,10 @@ class AsyncConnection(object):
optionally set ``huggingface_token_secret`` to a Secret containing the
token; omitting it selects anonymous access at the default rate limits.
Registration returns setup instructions without verifying storage access.
``exist_ok=True`` returns the stored configuration unchanged when the
integration exists, preserving its provider, prefix and credential
bindings. Existing names are errors by default.
"""
azure_options = (
azure_tenant_id_secret,
@@ -3978,6 +4054,8 @@ class AsyncConnection(object):
"aws_access_key_id_secret": reference(aws_access_key_id_secret),
"aws_secret_access_key_secret": reference(aws_secret_access_key_secret),
}
if exist_ok:
request["exist_ok"] = True
info = await self._inner.create_storage_integration(
validate_secret_name(name),
json.dumps(request),
@@ -4107,7 +4185,12 @@ class AsyncConnection(object):
)
async def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
"""Create a view: a named query the database plans on every read.
@@ -4115,7 +4198,9 @@ class AsyncConnection(object):
[DBConnection.create_view][lancedb.DBConnection.create_view].
"""
return _view_description(
await self._inner.create_view(name, query, list(namespace_path or []))
await self._inner.create_view(
name, query, list(namespace_path or []), exist_ok=exist_ok
)
)
async def describe_view(
+8
View File
@@ -705,6 +705,7 @@ class LanceNamespaceDBConnection(DBConnection):
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
exist_ok: bool = False,
) -> "MaterializedView":
"""Define a materialized view over a table in the root namespace.
See
@@ -723,6 +724,7 @@ class LanceNamespaceDBConnection(DBConnection):
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
).name
)
@@ -741,6 +743,7 @@ class LanceNamespaceDBConnection(DBConnection):
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
exist_ok: bool = False,
) -> Job[None]:
job = LOOP.run(
self._inner.create_materialized_view_async(
@@ -753,6 +756,7 @@ class LanceNamespaceDBConnection(DBConnection):
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
)
return Job(job)
@@ -1352,6 +1356,7 @@ class AsyncLanceNamespaceDBConnection:
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
exist_ok: bool = False,
) -> "AsyncMaterializedView":
"""Define a materialized view over a table in the root namespace."""
view = await self._inner.create_materialized_view(
@@ -1364,6 +1369,7 @@ class AsyncLanceNamespaceDBConnection:
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
# Reopen through the namespace so the view's table carries the
# namespace client and pushdown configuration a bare inner table lacks.
@@ -1381,6 +1387,7 @@ class AsyncLanceNamespaceDBConnection:
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
exist_ok: bool = False,
) -> AsyncJob[None]:
"""Submit materialized-view creation and return its job."""
return await self._inner.create_materialized_view_async(
@@ -1393,6 +1400,7 @@ class AsyncLanceNamespaceDBConnection:
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
async def open_materialized_view(self, name: str) -> "AsyncMaterializedView":
+24 -3
View File
@@ -576,6 +576,7 @@ class RemoteDBConnection(DBConnection):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
exist_ok: bool = False,
) -> Table:
"""Clone a table from a source table.
@@ -595,6 +596,8 @@ class RemoteDBConnection(DBConnection):
is_shallow: bool, default True
Whether to perform a shallow clone (True) or deep clone (False).
Currently only shallow clone is supported.
exist_ok: bool, default False
Return the existing target unchanged instead of cloning over it.
Returns
-------
@@ -612,6 +615,7 @@ class RemoteDBConnection(DBConnection):
source_version=source_version,
source_tag=source_tag,
is_shallow=is_shallow,
exist_ok=exist_ok,
)
)
return RemoteTable(
@@ -799,6 +803,7 @@ class RemoteDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
@@ -813,6 +818,7 @@ class RemoteDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -837,6 +843,7 @@ class RemoteDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
@@ -849,6 +856,7 @@ class RemoteDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -992,11 +1000,15 @@ class RemoteDBConnection(DBConnection):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> Job[FunctionVersion]:
job = LOOP.run(
self._conn.create_function_async(
definition, secrets=secrets, namespace_path=namespace_path
definition,
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
return Job(job)
@@ -1087,6 +1099,7 @@ class RemoteDBConnection(DBConnection):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
return LOOP.run(
@@ -1104,6 +1117,7 @@ class RemoteDBConnection(DBConnection):
azure_client_secret_secret=azure_client_secret_secret,
gcp_credentials_json_secret=gcp_credentials_json_secret,
huggingface_token_secret=huggingface_token_secret,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
@@ -1197,10 +1211,17 @@ class RemoteDBConnection(DBConnection):
@override
def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
return LOOP.run(
self._conn.create_view(name, query, namespace_path=namespace_path)
self._conn.create_view(
name, query, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
+10
View File
@@ -369,6 +369,7 @@ class RemoteTable(Table):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -395,6 +396,7 @@ class RemoteTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -433,6 +435,7 @@ class RemoteTable(Table):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on a column.
@@ -492,6 +495,7 @@ class RemoteTable(Table):
self._table.create_index(
field_names,
replace=replace,
exist_ok=exist_ok,
config=config,
name=name,
wait_timeout=wait_timeout,
@@ -516,6 +520,7 @@ class RemoteTable(Table):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -541,6 +546,7 @@ class RemoteTable(Table):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -572,6 +578,7 @@ class RemoteTable(Table):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -675,6 +682,7 @@ class RemoteTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -690,6 +698,7 @@ class RemoteTable(Table):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -702,6 +711,7 @@ class RemoteTable(Table):
self._table.create_index_async(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
+67 -4
View File
@@ -168,6 +168,36 @@ def _validate_index_accelerator(accelerator: Any) -> None:
raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err
def _create_accelerated_index(dataset, *, exist_ok=False, name=None, **options):
if exist_ok:
parts = _parse_field_path(options["column"])
default_name = ".".join(parts)
if any("." in part for part in parts):
default_name = ".".join(
"`" + part.replace("`", "``") + "`"
if any(
not character.isalnum() and character != "_" for character in part
)
else part
for part in parts
)
name = name or f"{default_name}_idx"
dataset.checkout_latest()
if any(index["name"] == name for index in dataset.list_indices()):
return
options["replace"] = False
options["name"] = name
_validate_index_accelerator(options.get("accelerator"))
try:
dataset.create_index(**options)
except Exception:
if exist_ok:
dataset.checkout_latest()
if any(index["name"] == name for index in dataset.list_indices()):
return
raise
def _polars_predicate_pushdown_barrier(frame: Any) -> Any:
"""Return a Polars frame unchanged while blocking predicate pushdown."""
return frame
@@ -1834,6 +1864,7 @@ class Table(ABC):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -1859,6 +1890,7 @@ class Table(ABC):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -1890,6 +1922,7 @@ class Table(ABC):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -1913,6 +1946,9 @@ class Table(ABC):
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
Preserve the existing index with the requested or derived name.
Takes precedence over replace and keeps its definition and build.
wait_timeout : timedelta, optional
LanceDB Enterprise only: how long to wait for the index build to finish.
If not set, the call returns once the build is scheduled.
@@ -1970,6 +2006,7 @@ class Table(ABC):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -2067,6 +2104,7 @@ class Table(ABC):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -2153,6 +2191,7 @@ class Table(ABC):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on the table.
@@ -4329,6 +4368,7 @@ class LanceTable(Table):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -4354,6 +4394,7 @@ class LanceTable(Table):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -4385,6 +4426,7 @@ class LanceTable(Table):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -4408,6 +4450,9 @@ class LanceTable(Table):
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
Preserve the existing index with the requested or derived name.
Takes precedence over replace and keeps its definition and build.
wait_timeout : timedelta, optional
Timeout to wait for async indexing to complete.
name : str, optional
@@ -4478,8 +4523,10 @@ class LanceTable(Table):
# Handle accelerator through pylance
if accelerator is not None:
dataset = self.to_lance()
_validate_index_accelerator(accelerator)
dataset.create_index(
_create_accelerated_index(
dataset,
exist_ok=exist_ok,
name=name,
column=column,
index_type=index_type,
metric=metric,
@@ -4505,7 +4552,6 @@ class LanceTable(Table):
if acc is not None:
# Dispatch to pylance for GPU acceleration
dataset = self.to_lance()
_validate_index_accelerator(acc)
index_type_map = {
"IvfFlat": "IVF_FLAT",
"IvfSq": "IVF_SQ",
@@ -4522,7 +4568,10 @@ class LanceTable(Table):
if num_bits is not None:
quantization_kwargs["num_bits"] = num_bits
dataset.create_index(
_create_accelerated_index(
dataset,
exist_ok=exist_ok,
name=name,
column=column,
index_type=lance_index_type,
metric=getattr(config, "distance_type", "l2"),
@@ -4544,6 +4593,7 @@ class LanceTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4559,6 +4609,7 @@ class LanceTable(Table):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -4577,6 +4628,7 @@ class LanceTable(Table):
self._table.create_index_async(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4697,6 +4749,7 @@ class LanceTable(Table):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -4723,6 +4776,7 @@ class LanceTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4760,6 +4814,7 @@ class LanceTable(Table):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on a column.
@@ -4821,6 +4876,7 @@ class LanceTable(Table):
self._table.create_index(
field_names,
replace=replace,
exist_ok=exist_ok,
config=config,
name=name,
wait_timeout=wait_timeout,
@@ -6819,6 +6875,7 @@ class AsyncTable:
] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
):
"""Create an index to speed up queries
@@ -6851,6 +6908,9 @@ class AsyncTable:
The name of the index. If not provided, a default name will be generated.
Custom names must contain 1–128 ASCII letters, digits, dashes,
underscores, or periods, excluding ``.`` and ``..``.
exist_ok: bool, default False
Preserve an existing index with the requested or derived name. This
takes precedence over replace and keeps its definition and build.
train: bool, default True
Whether to train the index with existing data. Vector indices always train
with existing data.
@@ -6906,6 +6966,7 @@ class AsyncTable:
column,
index=config,
replace=replace,
exist_ok=exist_ok,
wait_timeout=wait_timeout,
name=name,
train=train,
@@ -6943,6 +7004,7 @@ class AsyncTable:
] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> AsyncJob:
"""Create an index, returning a handle to the indexing job.
@@ -6961,6 +7023,7 @@ class AsyncTable:
column,
index=config,
replace=replace,
exist_ok=exist_ok,
wait_timeout=wait_timeout,
name=name,
train=train,
@@ -0,0 +1,36 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
import lancedb
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous):
source_uri = str(tmp_path / "source.lance")
if asynchronous:
db = await lancedb.connect_async(tmp_path)
await db.create_table("source", [{"id": 1}])
table = await db.clone_table("target", source_uri, exist_ok=True)
assert (await table.to_arrow()).to_pylist() == [{"id": 1}]
await table.add([{"id": 2}])
version = await table.version()
with pytest.raises(ValueError, match="already exists"):
await db.clone_table("target", source_uri)
kept = await db.clone_table("target", "missing.lance", exist_ok=True)
assert await kept.version() == version
assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}]
else:
db = lancedb.connect(tmp_path)
db.create_table("source", [{"id": 1}])
table = db.clone_table("target", source_uri, exist_ok=True)
assert table.to_arrow().to_pylist() == [{"id": 1}]
table.add([{"id": 2}])
version = table.version
with pytest.raises(ValueError, match="already exists"):
db.clone_table("target", source_uri)
kept = db.clone_table("target", "missing.lance", exist_ok=True)
assert kept.version == version
assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}]
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
from pathlib import Path
import pyarrow as pa
import pytest
import lancedb
from lancedb.functions import function
@pytest.mark.asyncio
@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"])
@pytest.mark.parametrize("exist_ok", [None, False, True])
async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok):
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
/ "remote_function_version.canonical.json"
)
stored = json.loads(fixture.read_text())
result = pa.table({"definition": [json.dumps(stored)]})
@function(name=stored["name"])
def replacement(value: float) -> float:
return value * 2
class FunctionServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(result)
with FunctionServer() as server:
options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
kwargs["namespace_path"] = ["team"]
if entry == "async_job":
db = await lancedb.connect_async("db://analytics", **options)
job = await db.create_function_async(replacement, **kwargs)
version = await job.wait()
else:
db = lancedb.connect("db://analytics", **options)
if entry == "sync_job":
version = db.create_function_async(replacement, **kwargs).wait()
else:
version = db.create_function(replacement, **kwargs)
(request,) = server.requests
prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION"
assert f'{prefix} "{stored["name"]}" FROM '.encode() in request
assert b'"exist_ok"' not in request
assert json.loads(version.to_canonical_json()) == stored
+42
View File
@@ -621,3 +621,45 @@ def test_index_statistics_index_type_lists_all_supported_values():
set(get_args(get_type_hints(IndexStatistics)["index_type"]))
== expected_index_types
)
@pytest.mark.asyncio
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize(
"column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))]
)
async def test_index_exist_ok_preserves_existing_index(
some_table, background, column, config
):
await some_table.create_index(column, config=config, exist_ok=True)
version = await some_table.version()
original = await some_table.list_indices()
if background:
job = await some_table.create_index_async(
column, config=config, replace=True, exist_ok=True
)
await job.wait()
else:
await some_table.create_index(
column, config=config, replace=True, exist_ok=True
)
assert await some_table.version() == version
assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [
(i.name, i.index_type) for i in original
]
@pytest.mark.asyncio
@pytest.mark.parametrize("background", [False, True])
async def test_named_index_exist_ok_checks_before_column_validation(
some_table, background
):
await some_table.create_index("id", config=BTree(), name="kept")
version = await some_table.version()
method = some_table.create_index_async if background else some_table.create_index
result = await method("missing", config=BTree(), name="kept", exist_ok=True)
if background:
assert result.id is None
await result.wait()
assert await some_table.version() == version
assert [index.name for index in await some_table.list_indices()] == ["kept"]
@@ -0,0 +1,84 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
import lancedb
@pytest.mark.experimental_functions
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize("namespace", [False, True])
@pytest.mark.parametrize("defining_query", [False, True])
async def test_exist_ok_preserves_materialized_data(
tmp_path, asynchronous, background, namespace, defining_query
):
source_args = (
{"query": "SELECT * FROM source"} if defining_query else {"source": "source"}
)
replacement_args = {
**(
{"query": "SELECT * FROM missing"}
if defining_query
else {"source": "missing"}
),
"auto_refresh_enabled": True,
"auto_refresh_interval_seconds": 1,
}
options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}}
if asynchronous:
db = (
lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options)
if namespace
else await lancedb.connect_async(tmp_path, **options)
)
source = await db.create_table("source", [{"id": 1}])
original = await db.create_materialized_view(
"saved", **source_args, exist_ok=True
)
definition = await original.definition()
version = await original.table.version()
await source.add([{"id": 2}])
if background:
job = await db.create_materialized_view_async(
"saved", **replacement_args, exist_ok=True
)
await job.wait()
kept = await db.open_materialized_view("saved")
else:
kept = await db.create_materialized_view(
"saved", **replacement_args, exist_ok=True
)
assert (await kept.definition()).query == definition.query
assert await kept.table.version() == version
assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}]
with pytest.raises(ValueError, match="already exists"):
await db.create_materialized_view("saved", **source_args)
else:
db = (
lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options)
if namespace
else lancedb.connect(tmp_path, **options)
)
source = db.create_table("source", [{"id": 1}])
original = db.create_materialized_view("saved", **source_args, exist_ok=True)
definition = original.definition
version = original.table.version
source.add([{"id": 2}])
if background:
job = db.create_materialized_view_async(
"saved", **replacement_args, exist_ok=True
)
job.wait()
kept = db.open_materialized_view("saved")
else:
kept = db.create_materialized_view(
"saved", **replacement_args, exist_ok=True
)
assert kept.definition.query == definition.query
assert kept.table.version == version
assert kept.table.to_arrow().to_pylist() == [{"id": 1}]
with pytest.raises(ValueError, match="already exists"):
db.create_materialized_view("saved", **source_args)
@@ -197,6 +197,7 @@ def test_sync_remote_create_uses_public_async_connection(query):
where=None,
limit=None,
with_no_data=False,
exist_ok=False,
auto_refresh_enabled=None,
auto_refresh_interval_seconds=None,
):
@@ -729,6 +730,7 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
"filter": None,
"limit": None,
"with_no_data": False,
"exist_ok": False,
"auto_refresh_enabled": options.get("auto_refresh_enabled"),
"auto_refresh_interval_seconds": options.get(
"auto_refresh_interval_seconds"
+52
View File
@@ -45,6 +45,7 @@ from lancedb.query import (
LanceVectorQueryBuilder,
MatchQuery,
)
from lancedb.index import BTree
from lancedb.remote import ClientConfig
from lancedb.remote.errors import (
AlreadyExistsError,
@@ -7420,3 +7421,54 @@ async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnati
if use_async:
await result
assert not any(path == "fetch_blobs" for path, _ in requests)
@pytest.mark.asyncio
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize("kwargs", [{}, {"exist_ok": False}, {"exist_ok": True}])
async def test_remote_index_exist_ok_wire(is_async, background, kwargs):
received = []
def handler(request):
parsed = urlparse(request.path)
body = request.rfile.read(int(request.headers.get("Content-Length", 0)))
if parsed.path.endswith("/create_index/"):
received.append((parse_qs(parsed.query), json.loads(body)))
payload = {}
elif parsed.path.endswith("/describe/"):
payload = dict(
version=1,
schema=dict(
fields=[dict(name="id", type={"type": "int64"}, nullable=False)]
),
)
elif parsed.path.endswith("/create/"):
payload = {}
else:
raise AssertionError(request.path)
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(payload).encode())
method = "create_index_async" if background else "create_index"
if is_async:
async with mock_lancedb_connection_async(handler) as db:
table = await db.create_table("test", [{"id": 1}])
result = await getattr(table, method)("id", config=BTree(), **kwargs)
if background:
await result.wait()
else:
with mock_lancedb_connection(handler) as db:
table = db.create_table("test", [{"id": 1}])
result = getattr(table, method)("id", config=BTree(), **kwargs)
if background:
result.wait()
query, body = received[0]
assert query == ({"exist_ok": ["true"]} if kwargs.get("exist_ok") else {})
assert "exist_ok" not in body
if kwargs.get("exist_ok"):
assert body["replace"] is False
else:
assert "replace" not in body
@@ -0,0 +1,85 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
from pathlib import Path
import pyarrow as pa
import pytest
import lancedb
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
("exist_ok", "existing"),
[(None, False), (False, False), (True, False), (True, True)],
)
async def test_storage_integration_exist_ok_preserves_server_metadata(
asynchronous, exist_ok, existing
):
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/storage_integration.json"
)
stored = json.loads(fixture.read_text())
stored["namespace_path"] = ["team"]
columns = {}
for key, value in stored.items():
if isinstance(value, (dict, list)):
value = json.dumps(value)
columns[key] = pa.array([None], type=pa.string()) if value is None else [value]
result = pa.table(columns)
prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"]
role = (
"arn:aws:iam::999999999999:role/replacement"
if existing
else stored["aws_role_arn"]
)
class IntegrationServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(result)
with IntegrationServer() as server:
connection_options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
kwargs.update(
storage_provider="S3",
storage_prefix=prefix,
aws_role_arn=role,
namespace_path=["team"],
)
uri = f"db://{stored['database']}"
if asynchronous:
db = await lancedb.connect_async(uri, **connection_options)
info = await db.create_storage_integration(stored["name"], **kwargs)
else:
db = lancedb.connect(uri, **connection_options)
info = db.create_storage_integration(stored["name"], **kwargs)
(request,) = server.requests
command = (
"CREATE STORAGE INTEGRATION IF NOT EXISTS"
if exist_ok
else "CREATE STORAGE INTEGRATION"
)
assert f'{command} "raw"'.encode() in request
assert prefix.encode() in request
assert role.encode() in request
assert info.storage_prefix == stored["storage_prefix"]
assert info.aws_role_arn == stored["aws_role_arn"]
assert info.aws_external_id == stored["aws_external_id"]
assert info.created_at_millis == stored["created_at_millis"]
assert info.namespace_path == ["team"]
+96
View File
@@ -1837,6 +1837,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
# Test with target_partition_size
@@ -1862,6 +1863,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
# target_partition_size has a default value,
@@ -1886,6 +1888,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
table.create_index(
@@ -1902,6 +1905,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
table.create_index(
@@ -1922,6 +1926,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
table.create_index(
@@ -1942,6 +1947,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
@@ -2073,6 +2079,7 @@ def test_create_index_name_and_train_parameters(
wait_timeout=None,
name="my_custom_index",
train=True,
exist_ok=False,
)
# Test with train=False
@@ -2084,6 +2091,7 @@ def test_create_index_name_and_train_parameters(
wait_timeout=None,
name=None,
train=False,
exist_ok=False,
)
# Test with both name and train
@@ -2095,6 +2103,7 @@ def test_create_index_name_and_train_parameters(
wait_timeout=None,
name="my_index_name",
train=True,
exist_ok=False,
)
@@ -2132,6 +2141,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
# Scalar index via new API
@@ -2143,6 +2153,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
# FTS index via new API
@@ -2154,6 +2165,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
@@ -6292,3 +6304,87 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
metadata = (await table.schema()).field("doubled").metadata
assert metadata[b"computed_column.auto_refresh_enabled"] == b"true"
assert b"computed_column.auto_refresh_interval_seconds" not in metadata
@pytest.mark.parametrize(
"method",
["create_index", "create_index_async", "create_scalar_index", "create_fts_index"],
)
@pytest.mark.parametrize("name", [None, "kept_index"])
def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name):
table = mem_db.create_table(
"keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)]
)
column = "text" if method == "create_fts_index" else "id"
config = FTS() if column == "text" else BTree()
table.create_index(column, config=config, name=name, exist_ok=True)
before = table.version
original = table.list_indices()
kwargs = dict(name=name, exist_ok=True)
if method in ("create_index", "create_index_async"):
kwargs["config"] = config
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
result = getattr(table, method)(column, **kwargs)
if method == "create_index_async":
result.wait()
assert table.version == before
assert [(index.name, index.index_type) for index in table.list_indices()] == [
(index.name, index.index_type) for index in original
]
with pytest.raises((ValueError, RuntimeError), match="already exists"):
table.create_index(column, config=config, name=name, replace=False)
table.create_index(column, config=config, name=name)
assert table.version > before
@pytest.mark.parametrize(
"column,name,existing",
[
("vector", "kept", "kept"),
("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"),
],
)
def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing):
dataset = MagicMock()
dataset.list_indices.return_value = [{"name": existing}]
with patch("lancedb.table._validate_index_accelerator") as validate:
table_module._create_accelerated_index(
dataset, column=column, accelerator="cuda", name=name, exist_ok=True
)
validate.assert_not_called()
dataset.create_index.assert_not_called()
def test_accelerated_index_exist_ok_preserves_concurrent_winner():
dataset = MagicMock()
dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]]
dataset.create_index.side_effect = RuntimeError("concurrent create")
with patch("lancedb.table._validate_index_accelerator"):
table_module._create_accelerated_index(
dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True
)
assert dataset.create_index.call_args.kwargs["replace"] is False
assert dataset.create_index.call_args.kwargs["name"] == "vector_idx"
@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"])
def test_index_exist_ok_matches_lance_default_name(mem_db, column):
table = mem_db.create_table(
"quoted_index",
[{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}],
)
table.create_index(column, config=BTree())
before = table.version
table.create_index(column, config=BTree(), exist_ok=True)
assert table.version == before
assert len(table.list_indices()) == 1
def test_fts_exist_ok_matches_quoted_default_name(mem_db):
table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}])
table.create_index("`body-text`", config=FTS())
before = table.version
table.create_index("`body-text`", config=FTS(), exist_ok=True)
assert table.version == before
assert len(table.list_indices()) == 1
+5 -1
View File
@@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table):
}.items():
assert getattr(config, name) == value
assert kwargs == dict(
wait_timeout=timeout, name="custom_idx", replace=False, train=False
wait_timeout=timeout,
name="custom_idx",
replace=False,
train=False,
exist_ok=False,
)
+71
View File
@@ -0,0 +1,71 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import pyarrow as pa
import pytest
import lancedb
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
("exist_ok", "existing"),
[(None, False), (False, False), (True, False), (True, True)],
)
async def test_create_view_exist_ok_preserves_server_metadata(
asynchronous, exist_ok, existing
):
flight = pytest.importorskip("pyarrow.flight")
original_query = "SELECT 'original' AS original"
submitted_query = (
"SELECT 'replacement' AS replacement" if existing else original_query
)
schema = {
"fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}],
"metadata": {
"lancedb::view::default_db": "analytics",
"lancedb::view::default_namespace": "team",
},
}
result = pa.table(
{"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]}
)
class ViewServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(result)
with ViewServer() as server:
connection_options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
if asynchronous:
db = await lancedb.connect_async("db://analytics", **connection_options)
view = await db.create_view(
"saved", submitted_query, namespace_path=["team"], **kwargs
)
else:
db = lancedb.connect("db://analytics", **connection_options)
view = db.create_view(
"saved", submitted_query, namespace_path=["team"], **kwargs
)
(request,) = server.requests
prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW"
assert f'{prefix} "saved" AS {submitted_query}'.encode() in request
assert view.name == "saved"
assert view.namespace_path == ["team"]
assert view.default_namespace_path == ["team"]
assert view.query == original_query
assert view.schema.names == ["original"]
+17 -9
View File
@@ -457,7 +457,8 @@ impl Connection {
})
}
#[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true, *, exist_ok=false))]
pub fn clone_table(
self_: PyRef<'_, Self>,
target_table_name: String,
@@ -466,6 +467,7 @@ impl Connection {
source_version: Option<u64>,
source_tag: Option<String>,
is_shallow: bool,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
@@ -477,7 +479,7 @@ impl Connection {
if let Some(tag) = source_tag {
builder = builder.source_tag(tag);
}
builder = builder.is_shallow(is_shallow);
builder = builder.is_shallow(is_shallow).exist_ok(exist_ok);
future_into_py(self_.py(), async move {
let table = builder.execute().await.infer_error()?;
@@ -505,7 +507,7 @@ impl Connection {
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))]
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))]
pub fn create_materialized_view(
self_: PyRef<'_, Self>,
name: String,
@@ -517,6 +519,7 @@ impl Connection {
auto_refresh_enabled: Option<bool>,
auto_refresh_interval_seconds: Option<f64>,
query: Option<String>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let builder = materialized_view_builder(
@@ -527,7 +530,7 @@ impl Connection {
projections.is_some() || filter.is_some() || limit.is_some(),
)?;
future_into_py(self_.py(), async move {
let mut builder = builder;
let mut builder = builder.exist_ok(exist_ok);
if let Some(enabled) = auto_refresh_enabled {
builder = builder.auto_refresh_enabled(enabled);
}
@@ -550,7 +553,7 @@ impl Connection {
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))]
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))]
pub fn create_materialized_view_async(
self_: PyRef<'_, Self>,
name: String,
@@ -562,6 +565,7 @@ impl Connection {
auto_refresh_enabled: Option<bool>,
auto_refresh_interval_seconds: Option<f64>,
query: Option<String>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let builder = materialized_view_builder(
@@ -572,7 +576,7 @@ impl Connection {
projections.is_some() || filter.is_some() || limit.is_some(),
)?;
future_into_py(self_.py(), async move {
let mut builder = builder;
let mut builder = builder.exist_ok(exist_ok);
if let Some(enabled) = auto_refresh_enabled {
builder = builder.auto_refresh_enabled(enabled);
}
@@ -903,15 +907,17 @@ impl Connection {
})
}
#[pyo3(signature = (request_json, namespace_path=None))]
#[pyo3(signature = (request_json, namespace_path=None, *, exist_ok=false))]
pub fn create_function_async(
self_: PyRef<'_, Self>,
request_json: String,
namespace_path: Option<Vec<String>>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json)
let mut request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json)
.infer_error()?;
request.exist_ok = exist_ok;
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
@@ -1158,18 +1164,20 @@ impl Connection {
})
}
#[pyo3(signature = (name, query, namespace_path=None))]
#[pyo3(signature = (name, query, namespace_path=None, *, exist_ok=false))]
pub fn create_view(
self_: PyRef<'_, Self>,
name: String,
query: String,
namespace_path: Option<Vec<String>>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
let view = inner
.create_view(name, query, &namespace_path)
.exist_ok(exist_ok)
.await
.infer_error()?;
view_description_to_py(view)
+8 -2
View File
@@ -1628,7 +1628,8 @@ impl Table {
})
}
#[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))]
pub fn create_index<'a>(
self_: PyRef<'a, Self>,
column: String,
@@ -1637,6 +1638,7 @@ impl Table {
wait_timeout: Option<Bound<'_, PyAny>>,
name: Option<String>,
train: Option<bool>,
exist_ok: bool,
) -> PyResult<Bound<'a, PyAny>> {
let index = extract_index_params(&index)?;
let timeout = wait_timeout
@@ -1645,6 +1647,7 @@ impl Table {
let mut op = self_
.inner_ref()?
.create_index_with_timeout(&[column], index, timeout);
op = op.exist_ok(exist_ok);
if let Some(replace) = replace {
op = op.replace(replace);
}
@@ -1661,7 +1664,8 @@ impl Table {
})
}
#[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))]
pub fn create_index_async<'a>(
self_: PyRef<'a, Self>,
column: String,
@@ -1670,6 +1674,7 @@ impl Table {
wait_timeout: Option<Bound<'_, PyAny>>,
name: Option<String>,
train: Option<bool>,
exist_ok: bool,
) -> PyResult<Bound<'a, PyAny>> {
let index = extract_index_params(&index)?;
let timeout = wait_timeout
@@ -1678,6 +1683,7 @@ impl Table {
let mut op = self_
.inner_ref()?
.create_index_with_timeout(&[column], index, timeout);
op = op.exist_ok(exist_ok);
if let Some(replace) = replace {
op = op.replace(replace);
}