diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 18c1deb3b..d46d414d3 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -180,13 +180,13 @@ abstract createMaterializedView( Define a materialized view named `name` over the table `source`. -The view is created empty, with the query recorded in its schema -metadata; `view.refresh()` computes the rows. The view is a normal -table: it can be queried, indexed and searched, and it appears in -`tableNames`. The source table must have stable row ids (create it with +The view is populated before creation returns. Set `withNoData` to create +only its definition and empty backing table. The view is a normal table: +it can be queried, indexed and searched, and it appears in `tableNames`. +The source table must have stable row ids (create it with the `newTableEnableStableRowIds` storage option); they keep the view's provenance valid across source compactions and cannot be enabled after -a table exists. Local databases only. +a table exists. #### Parameters @@ -202,6 +202,8 @@ a table exists. Local databases only. * **options.where?**: `string` +* **options.withNoData?**: `boolean` + #### Returns `Promise`<[`MaterializedView`](MaterializedView.md)> @@ -373,6 +375,54 @@ Drop all tables in the database. *** +### dropMaterializedView() + +```ts +abstract dropMaterializedView(name, namespacePath?): Promise +``` + +Drop the materialized view named `name`. + +The view may become unavailable before physical cleanup finishes. Use +[dropMaterializedViewAsync](Connection.md#dropmaterializedviewasync) to retain and wait for the cleanup job. + +Rejects a table that exists but is not a materialized view. + +#### Parameters + +* **name**: `string` + +* **namespacePath?**: `string`[] + +#### Returns + +`Promise`<`void`> + +*** + +### dropMaterializedViewAsync() + +```ts +abstract dropMaterializedViewAsync(name, namespacePath?): Promise +``` + +Start dropping the materialized view named `name` and return its cleanup +job without waiting for completion. + +Rejects a table that exists but is not a materialized view. + +#### Parameters + +* **name**: `string` + +* **namespacePath?**: `string`[] + +#### Returns + +`Promise`<[`Job`](Job.md)> + +*** + ### dropNamespace() ```ts diff --git a/docs/src/js/classes/MaterializedView.md b/docs/src/js/classes/MaterializedView.md index e6ff66142..58eaa3c13 100644 --- a/docs/src/js/classes/MaterializedView.md +++ b/docs/src/js/classes/MaterializedView.md @@ -49,7 +49,7 @@ get name(): string definition(): Promise ``` -The query that defines the view, read from its stored schema. +The query that defines the view. #### Returns diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts index b9d8ec911..7d0e5ebb3 100644 --- a/nodejs/__test__/materialized_view.test.ts +++ b/nodejs/__test__/materialized_view.test.ts @@ -76,11 +76,7 @@ describe("materialized views", () => { where: "age >= 18", }); expect(view.name).toBe("adults"); - expect(await view.table().countRows()).toBe(0); - - const result = await view.refresh(); - expect(result.mode).toBe("rebuild"); - expect(Number(result.rowsWritten)).toBe(2); + expect(await view.table().countRows()).toBe(2); const rows = await view.table().query().toArray(); expect(rows.map((r) => r.shout).sort()).toEqual(["ADA", "GRACE"]); @@ -102,7 +98,9 @@ describe("materialized views", () => { }); it("refreshes incrementally after an append", async () => { - const view = await db.createMaterializedView("copy", "people"); + const view = await db.createMaterializedView("copy", "people", { + withNoData: true, + }); await view.refresh(); const people = await db.openTable("people"); @@ -123,6 +121,21 @@ describe("materialized views", () => { await expect(db.openMaterializedView("people")).rejects.toThrow( "not a materialized view", ); + await expect(db.dropMaterializedView("people")).rejects.toThrow( + "not a materialized view", + ); + + await db.dropMaterializedView("adults"); + expect(await db.listMaterializedViews()).toEqual([]); + }); + + it("returns a job when dropping a view asynchronously", async () => { + await db.createMaterializedView("adults", "people"); + + const job = await db.dropMaterializedViewAsync("adults"); + expect(job.id).toBeNull(); + await job.wait(); + expect(await db.listMaterializedViews()).toEqual([]); }); it("rejects an invalid expression at create time", async () => { @@ -155,6 +168,7 @@ describe("materialized views", () => { }); const view = await db.createMaterializedView("quoted", "odd_names", { select: ["order item"], + withNoData: true, }); const result = await view.refresh(); expect(Number(result.rowsWritten)).toBe(1); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 519f0eb5f..5da0bf724 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -82,21 +82,17 @@ async function withMockDatabase( } describe("remote connection", () => { - it("refuses materialized views before issuing any request", async () => { - const paths: string[] = []; + it("lists materialized views through the namespace route", async () => { await withMockDatabase( (req, res) => { - paths.push(req.url ?? ""); - res.writeHead(404).end(); + expect(req.method).toBe("GET"); + expect(req.url).toBe("/v1/namespace/$/materialized_view/list"); + res + .writeHead(200, { "content-type": "application/json" }) + .end(JSON.stringify({ views: ["daily_sales"] })); }, async (db) => { - await expect(db.openMaterializedView("secret_table")).rejects.toThrow( - /only on local databases/, - ); - await expect(db.listMaterializedViews()).rejects.toThrow( - /only on local databases/, - ); - expect(paths).toEqual([]); + expect(await db.listMaterializedViews()).toEqual(["daily_sales"]); }, ); }); diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 094819ec1..f5a6679cf 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -320,13 +320,13 @@ export abstract class Connection { /** * Define a materialized view named `name` over the table `source`. * - * The view is created empty, with the query recorded in its schema - * metadata; `view.refresh()` computes the rows. The view is a normal - * table: it can be queried, indexed and searched, and it appears in - * `tableNames`. The source table must have stable row ids (create it with + * The view is populated before creation returns. Set `withNoData` to create + * only its definition and empty backing table. The view is a normal table: + * it can be queried, indexed and searched, and it appears in `tableNames`. + * The source table must have stable row ids (create it with * the `newTableEnableStableRowIds` storage option); they keep the view's * provenance valid across source compactions and cannot be enabled after - * a table exists. Local databases only. + * a table exists. */ abstract createMaterializedView( name: string, @@ -335,6 +335,7 @@ export abstract class Connection { select?: MaterializedViewSelect; where?: string; limit?: number; + withNoData?: boolean; }, ): Promise; @@ -352,6 +353,30 @@ export abstract class Connection { */ abstract listMaterializedViews(): Promise; + /** + * Drop the materialized view named `name`. + * + * The view may become unavailable before physical cleanup finishes. Use + * {@link dropMaterializedViewAsync} to retain and wait for the cleanup job. + * + * Rejects a table that exists but is not a materialized view. + */ + abstract dropMaterializedView( + name: string, + namespacePath?: string[], + ): Promise; + + /** + * Start dropping the materialized view named `name` and return its cleanup + * job without waiting for completion. + * + * Rejects a table that exists but is not a materialized view. + */ + abstract dropMaterializedViewAsync( + name: string, + namespacePath?: string[], + ): Promise; + abstract openTable( name: string, namespacePath?: string[], @@ -631,6 +656,7 @@ export class LocalConnection extends Connection { select?: MaterializedViewSelect; where?: string; limit?: number; + withNoData?: boolean; }, ): Promise { validateNonNegativeInteger(options?.limit, "limit"); @@ -640,6 +666,7 @@ export class LocalConnection extends Connection { normalizeSelect(options?.select), options?.where, options?.limit, + options?.withNoData ?? false, ); return new MaterializedView(new LocalTable(innerTable)); } @@ -653,6 +680,22 @@ export class LocalConnection extends Connection { return await this.inner.listMaterializedViews(); } + async dropMaterializedView( + name: string, + namespacePath?: string[], + ): Promise { + return this.inner.dropMaterializedView(name, namespacePath ?? []); + } + + async dropMaterializedViewAsync( + name: string, + namespacePath?: string[], + ): Promise { + return new Job( + await this.inner.dropMaterializedViewAsync(name, namespacePath ?? []), + ); + } + async listTables( namespacePathOrOptions?: string[] | Partial, options?: Partial, diff --git a/nodejs/lancedb/materialized_view.ts b/nodejs/lancedb/materialized_view.ts index 1d47b640a..e729c960b 100644 --- a/nodejs/lancedb/materialized_view.ts +++ b/nodejs/lancedb/materialized_view.ts @@ -78,10 +78,22 @@ export function definitionFromMetadata( if (raw === undefined) { throw new Error(`Table '${name}' is not a materialized view`); } + return definitionFromJson(raw, name); +} + +/** @internal Parse the backend-independent definition returned by native code. */ +export function definitionFromJson( + raw: string, + name: string, +): MaterializedViewDefinition { // biome-ignore lint/suspicious/noExplicitAny: raw JSON const value: any = JSON.parse(raw); // "namespaced_select" keeps older readers from resolving the source at root. - if (value.kind !== "select" && value.kind !== "namespaced_select") { + if ( + value.kind !== undefined && + value.kind !== "select" && + value.kind !== "namespaced_select" + ) { throw new Error( `materialized view '${name}' is defined by '${value.kind}', which this ` + "version of lancedb cannot refresh", @@ -134,10 +146,12 @@ export class MaterializedView { return this.inner; } - /** The query that defines the view, read from its stored schema. */ + /** The query that defines the view. */ async definition(): Promise { - const schema = await this.inner.schema(); - return definitionFromMetadata(schema.metadata, this.name); + return definitionFromJson( + await this.inner.materializedViewDefinition(), + this.name, + ); } /** diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index a70243402..0280ac7f8 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -640,7 +640,7 @@ export abstract class Table { * Recompute this table's contents from its materialized-view definition. * * Plumbing for {@link MaterializedView.refresh}, which is the way to call - * it: rejects tables that carry no view definition. Local tables only. + * it: rejects tables that carry no view definition. * @ignore */ abstract refreshMaterializedView( @@ -648,6 +648,9 @@ export abstract class Table { sourceVersion?: number, ): Promise; + /** @ignore */ + abstract materializedViewDefinition(): Promise; + /** * Alter the name or nullability of columns. * @param {ColumnAlteration[]} columnAlterations One or more alterations to @@ -1367,6 +1370,10 @@ export class LocalTable extends Table { return await this.inner.refreshMaterializedView(full, sourceVersion); } + async materializedViewDefinition(): Promise { + return await this.inner.materializedViewDefinition(); + } + async alterColumns( columnAlterations: ColumnAlteration[], ): Promise { diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 586238359..0c07ffd50 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -308,6 +308,7 @@ impl Connection { projections: Option>>, filter: Option, limit: Option, + with_no_data: bool, ) -> napi::Result { let mut builder = self.get_inner()?.create_materialized_view(name, source); if let Some(projections) = projections { @@ -328,6 +329,7 @@ impl Connection { .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer"))?; builder = builder.limit(limit); } + builder = builder.with_no_data(with_no_data); let view = builder.execute().await.default_error()?; Ok(Table::new(view.table().clone())) } @@ -349,7 +351,37 @@ impl Connection { .list_materialized_views() .await .default_error()?; - Ok(views.into_iter().map(|v| v.name).collect()) + Ok(views) + } + + /// Drop a materialized view. + #[napi(catch_unwind)] + pub async fn drop_materialized_view( + &self, + name: String, + namespace_path: Option>, + ) -> napi::Result<()> { + let ns = namespace_path.unwrap_or_default(); + self.get_inner()? + .drop_materialized_view(&name, &ns) + .await + .default_error() + } + + /// Start dropping a materialized view and return its cleanup job. + #[napi(catch_unwind)] + pub async fn drop_materialized_view_async( + &self, + name: String, + namespace_path: Option>, + ) -> napi::Result { + let ns = namespace_path.unwrap_or_default(); + let job = self + .get_inner()? + .drop_materialized_view_async(&name, &ns) + .await + .default_error()?; + Ok(crate::job::Job::new(job)) } #[napi(catch_unwind)] diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index cf7ec4020..344017d08 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -447,6 +447,19 @@ impl Table { Ok(result.into()) } + #[napi(catch_unwind)] + pub async fn materialized_view_definition(&self) -> napi::Result { + let inner = self.inner_ref()?.clone(); + let view = lancedb::MaterializedView::from_table(inner) + .await + .default_error()?; + serde_json::to_string(view.definition()).map_err(|err| { + napi::Error::from_reason(format!( + "failed to serialize materialized-view definition: {err}" + )) + }) + } + #[napi(catch_unwind)] pub async fn add_columns_with_schema( &self, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 08d81bfd3..32159dd5a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -211,8 +211,24 @@ class Connection(object): projections: Optional[List[Tuple[str, str]]] = None, filter: Optional[str] = None, limit: Optional[int] = None, + with_no_data: bool = False, ) -> Table: ... + async def create_materialized_view_async( + self, + name: str, + source: str, + projections: Optional[List[Tuple[str, str]]] = None, + filter: Optional[str] = None, + limit: Optional[int] = None, + with_no_data: bool = False, + ) -> Job: ... async def list_materialized_views(self) -> List[str]: ... + async def drop_materialized_view( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> None: ... + async def drop_materialized_view_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job: ... async def drop_table( self, name: str, namespace_path: Optional[List[str]] = None ) -> None: ... @@ -429,6 +445,10 @@ class Table: async def refresh_materialized_view( self, full: bool = False, source_version: Optional[int] = None ) -> RefreshMaterializedViewResult: ... + async def refresh_materialized_view_async( + self, full: bool = False, source_version: Optional[int] = None + ) -> Job: ... + async def materialized_view_definition(self) -> str: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... async def alter_columns( self, columns: list[dict[str, Any]] @@ -782,6 +802,8 @@ class RefreshColumnResult: version: int class RefreshMaterializedViewResult: + @staticmethod + def from_json(value: str) -> RefreshMaterializedViewResult: ... mode: str rows_written: int source_version: int diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 88718e968..d09db80c3 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -529,13 +529,14 @@ class DBConnection(EnforceOverrides): select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, + with_no_data: bool = False, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. - The view is created empty, with the query recorded in its schema - metadata; ``view.refresh()`` computes the rows. The view is a normal - table: it can be queried, indexed and searched, and it appears in - ``table_names``. Local databases only. + The view is populated before creation returns. Pass + ``with_no_data=True`` to create only its definition and empty backing + table. The view is a normal table: it can be queried, indexed and + searched, and it appears in ``table_names``. The source table must have stable row ids (create it with the ``new_table_enable_stable_row_ids`` storage option): they keep the @@ -556,6 +557,8 @@ class DBConnection(EnforceOverrides): SQL predicate; only matching source rows appear in the view. limit: int, optional Cap the view at this many rows, in materialization order. + with_no_data: bool, default False + Skip the initial refresh and leave the backing table empty. Returns ------- @@ -565,6 +568,27 @@ class DBConnection(EnforceOverrides): "materialized views are not supported on this connection type" ) + def create_materialized_view_async( + self, + name: str, + source: str, + *, + select: SelectArg = None, + where: Optional[str] = None, + limit: Optional[int] = None, + with_no_data: bool = False, + ) -> Job[None]: + """Submit materialized-view creation and return its job. + + The job may already be complete for a local database. On LanceDB + Cloud and Enterprise, its ``id`` is the server job identifier from + the ``202 Accepted`` create response. Wait for the job before opening + or querying the view. + """ + raise NotImplementedError( + "materialized views are not supported on this connection type" + ) + def open_materialized_view(self, name: str) -> MaterializedView: """Open the materialized view named ``name``. @@ -585,6 +609,32 @@ class DBConnection(EnforceOverrides): "materialized views are not supported on this connection type" ) + def drop_materialized_view( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> None: + """Drop a materialized view. + + The view may become unavailable before physical cleanup finishes. Use + :meth:`drop_materialized_view_async` to retain and wait for the cleanup + job. + """ + raise NotImplementedError( + "materialized views are not supported on this connection type" + ) + + def drop_materialized_view_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job[None]: + """Start dropping a materialized view and return its cleanup job. + + The job may already be complete for a local database. On LanceDB Cloud + and Enterprise, its ``id`` is the server job identifier from the + ``202 Accepted`` drop response. + """ + raise NotImplementedError( + "materialized views are not supported on this connection type" + ) + def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): """Drop a table from the database. @@ -1270,6 +1320,7 @@ class LanceDBConnection(DBConnection): select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, + with_no_data: bool = False, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. See @@ -1290,17 +1341,44 @@ class LanceDBConnection(DBConnection): ... select=["name", ("shout", "upper(name)")], ... where="age >= 18", ... ) - >>> result = view.refresh() - >>> result.rows_written + >>> view.table.count_rows() 1 """ LOOP.run( self._conn.create_materialized_view( - name, source, select=select, where=where, limit=limit + name, + source, + select=select, + where=where, + limit=limit, + with_no_data=with_no_data, ) ) return MaterializedView(self.open_table(name)) + @override + def create_materialized_view_async( + self, + name: str, + source: str, + *, + select: SelectArg = None, + where: Optional[str] = None, + limit: Optional[int] = None, + with_no_data: bool = False, + ) -> Job[None]: + job = LOOP.run( + self._conn.create_materialized_view_async( + name, + source, + select=select, + where=where, + limit=limit, + with_no_data=with_no_data, + ) + ) + return Job(job) + @override def open_materialized_view(self, name: str) -> MaterializedView: """Open the materialized view named ``name``.""" @@ -1313,6 +1391,25 @@ class LanceDBConnection(DBConnection): """The names of the materialized views in this database.""" return LOOP.run(self._conn.list_materialized_views()) + @override + def drop_materialized_view( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> None: + if namespace_path is None: + namespace_path = [] + LOOP.run(self._conn.drop_materialized_view(name, namespace_path=namespace_path)) + + @override + def drop_materialized_view_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job[None]: + if namespace_path is None: + namespace_path = [] + job = LOOP.run( + self._conn.drop_materialized_view_async(name, namespace_path=namespace_path) + ) + return Job(job) + def clone_table( self, target_table_name: str, @@ -2080,6 +2177,7 @@ class AsyncConnection(object): select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, + with_no_data: bool = False, ) -> AsyncMaterializedView: """Define a materialized view named ``name`` over the table ``source``. See @@ -2091,19 +2189,40 @@ class AsyncConnection(object): projections=normalize_select(select), filter=where, limit=limit, + with_no_data=with_no_data, ) return AsyncMaterializedView(AsyncTable(inner)) + async def create_materialized_view_async( + self, + name: str, + source: str, + *, + select: SelectArg = None, + where: Optional[str] = None, + limit: Optional[int] = None, + with_no_data: bool = False, + ) -> AsyncJob[None]: + """Submit materialized-view creation and return its job. + + Wait for the returned job before opening or querying the view. + """ + inner = await self._inner.create_materialized_view_async( + name, + source, + projections=normalize_select(select), + filter=where, + limit=limit, + with_no_data=with_no_data, + ) + return AsyncJob(inner) + async def open_materialized_view(self, name: str) -> AsyncMaterializedView: """Open the materialized view named ``name``. Raises ``ValueError`` if the table exists but is not a materialized view. """ - if self.uri.startswith("db://"): - raise NotImplementedError( - "materialized views are supported only on local databases" - ) view = AsyncMaterializedView(await self.open_table(name)) await view.definition() return view @@ -2116,6 +2235,41 @@ class AsyncConnection(object): """ return await self._inner.list_materialized_views() + async def drop_materialized_view( + self, + name: str, + *, + namespace_path: Optional[List[str]] = None, + ) -> None: + """Drop a materialized view. + + The view may become unavailable before physical cleanup finishes. Use + :meth:`drop_materialized_view_async` to retain and wait for the cleanup + job. + """ + if namespace_path is None: + namespace_path = [] + await self._inner.drop_materialized_view(name, namespace_path=namespace_path) + + async def drop_materialized_view_async( + self, + name: str, + *, + namespace_path: Optional[List[str]] = None, + ) -> AsyncJob[None]: + """Start dropping a materialized view and return its cleanup job. + + Await :meth:`AsyncJob.wait` before assuming physical cleanup has + finished. + """ + if namespace_path is None: + namespace_path = [] + return AsyncJob( + await self._inner.drop_materialized_view_async( + name, namespace_path=namespace_path + ) + ) + async def clone_table( self, target_table_name: str, diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index c52a2d7a9..384683c9f 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -11,6 +11,7 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union from .background_loop import LOOP +from .job import AsyncJob, Job, _typed_job if TYPE_CHECKING: import pyarrow as pa @@ -73,6 +74,20 @@ def _definition_from_schema( ) +def _definition_from_json(raw: str) -> MaterializedViewDefinition: + value = json.loads(raw) + return MaterializedViewDefinition( + source_table=value["source_table"], + projections=[ + (p["output"], p["expression"]) for p in value.get("projections", []) + ], + filter=value.get("filter"), + limit=value.get("limit"), + inputs=value.get("inputs", []), + source_namespace=value.get("source_namespace", []), + ) + + def _quote_identifier(name: str) -> str: """Quote a column name as a Lance SQL identifier (backticks).""" escaped = name.replace("`", "``") @@ -126,8 +141,9 @@ class AsyncMaterializedView: return self._table async def definition(self) -> MaterializedViewDefinition: - """The query that defines the view, read from its stored schema.""" - return _definition_from_schema(await self._table.schema(), self.name) + """The query that defines the view.""" + raw = await self._table._inner.materialized_view_definition() + return _definition_from_json(raw) async def refresh( self, *, full: bool = False, source_version: Optional[int] = None @@ -148,6 +164,24 @@ class AsyncMaterializedView: full=full, source_version=source_version ) + async def refresh_async( + self, *, full: bool = False, source_version: Optional[int] = None + ) -> "AsyncJob[RefreshMaterializedViewResult]": + """Submit a refresh and return its job without waiting. + + The job may already be complete for a local view. On LanceDB Cloud + and Enterprise, its ``id`` is the server job identifier returned by + the refresh endpoint. + """ + from ._lancedb import RefreshMaterializedViewResult + + return _typed_job( + await self._table._inner.refresh_materialized_view_async( + full=full, source_version=source_version + ), + RefreshMaterializedViewResult.from_json, + ) + class MaterializedView: """Synchronous variant of @@ -171,8 +205,8 @@ class MaterializedView: @property def definition(self) -> MaterializedViewDefinition: - """The query that defines the view, read from its stored schema.""" - return _definition_from_schema(self._table.schema, self.name) + """The query that defines the view.""" + return LOOP.run(self._async.definition()) def refresh( self, *, full: bool = False, source_version: Optional[int] = None @@ -180,3 +214,17 @@ class MaterializedView: """Recompute the view from its source. See [AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].""" return LOOP.run(self._async.refresh(full=full, source_version=source_version)) + + def refresh_async( + self, *, full: bool = False, source_version: Optional[int] = None + ) -> "Job[RefreshMaterializedViewResult]": + """Submit a refresh and return its job without waiting. + + See + [AsyncMaterializedView.refresh_async][lancedb.materialized_view.AsyncMaterializedView.refresh_async]. + """ + return Job( + LOOP.run( + self._async.refresh_async(full=full, source_version=source_version) + ) + ) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 61d2122f3..fe38a47c7 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -637,6 +637,7 @@ class LanceNamespaceDBConnection(DBConnection): select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, + with_no_data: bool = False, ) -> "MaterializedView": """Define a materialized view over a table in the root namespace. See @@ -646,12 +647,40 @@ class LanceNamespaceDBConnection(DBConnection): self.open_table( LOOP.run( self._inner.create_materialized_view( - name, source, select=select, where=where, limit=limit + name, + source, + select=select, + where=where, + limit=limit, + with_no_data=with_no_data, ) ).name ) ) + @override + def create_materialized_view_async( + self, + name: str, + source: str, + *, + select: "SelectArg" = None, + where: Optional[str] = None, + limit: Optional[int] = None, + with_no_data: bool = False, + ) -> Job[None]: + job = LOOP.run( + self._inner.create_materialized_view_async( + name, + source, + select=select, + where=where, + limit=limit, + with_no_data=with_no_data, + ) + ) + return Job(job) + @override def open_materialized_view(self, name: str) -> "MaterializedView": """Open the materialized view named ``name``.""" @@ -664,6 +693,30 @@ class LanceNamespaceDBConnection(DBConnection): """The names of the materialized views in the root namespace.""" return LOOP.run(self._inner.list_materialized_views()) + @override + def drop_materialized_view( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> None: + if namespace_path is None: + namespace_path = [] + LOOP.run( + self._inner.drop_materialized_view(name, namespace_path=namespace_path) + ) + + @override + def drop_materialized_view_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job[None]: + if namespace_path is None: + namespace_path = [] + return Job( + LOOP.run( + self._inner.drop_materialized_view_async( + name, namespace_path=namespace_path + ) + ) + ) + @override def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): if namespace_path is None: @@ -1194,15 +1247,41 @@ class AsyncLanceNamespaceDBConnection: select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, + with_no_data: bool = False, ) -> "AsyncMaterializedView": """Define a materialized view over a table in the root namespace.""" view = await self._inner.create_materialized_view( - name, source, select=select, where=where, limit=limit + name, + source, + select=select, + where=where, + limit=limit, + with_no_data=with_no_data, ) # Reopen through the namespace so the view's table carries the # namespace client and pushdown configuration a bare inner table lacks. return AsyncMaterializedView(await self.open_table(view.name)) + async def create_materialized_view_async( + self, + name: str, + source: str, + *, + select: "SelectArg" = None, + where: Optional[str] = None, + limit: Optional[int] = None, + with_no_data: bool = False, + ) -> AsyncJob[None]: + """Submit materialized-view creation and return its job.""" + return await self._inner.create_materialized_view_async( + name, + source, + select=select, + where=where, + limit=limit, + with_no_data=with_no_data, + ) + async def open_materialized_view(self, name: str) -> "AsyncMaterializedView": """Open the materialized view named ``name``.""" view = AsyncMaterializedView(await self.open_table(name)) @@ -1213,6 +1292,24 @@ class AsyncLanceNamespaceDBConnection: """The names of the materialized views in the root namespace.""" return await self._inner.list_materialized_views() + async def drop_materialized_view( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> None: + """Drop a materialized view from the namespace.""" + if namespace_path is None: + namespace_path = [] + await self._inner.drop_materialized_view(name, namespace_path=namespace_path) + + async def drop_materialized_view_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> AsyncJob[None]: + """Start dropping a materialized view and return its cleanup job.""" + if namespace_path is None: + namespace_path = [] + return await self._inner.drop_materialized_view_async( + name, namespace_path=namespace_path + ) + async def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): """Drop a table from the namespace.""" if namespace_path is None: diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 5b6828b04..fb4e30fdf 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -665,22 +665,80 @@ class RemoteDBConnection(DBConnection): select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, + with_no_data: bool = False, ) -> MaterializedView: - raise NotImplementedError( - "materialized views are supported only on local databases" + from .table import RemoteTable + + view = LOOP.run( + self._conn.create_materialized_view( + name, + source, + select=select, + where=where, + limit=limit, + with_no_data=with_no_data, + ) ) + return MaterializedView( + RemoteTable( + view.table, + self.db_name, + connection_state=self.serialize, + namespace_path=[], + ) + ) + + @override + def create_materialized_view_async( + self, + name: str, + source: str, + *, + select: SelectArg = None, + where: Optional[str] = None, + limit: Optional[int] = None, + with_no_data: bool = False, + ) -> Job[None]: + job = LOOP.run( + self._conn.create_materialized_view_async( + name, + source, + select=select, + where=where, + limit=limit, + with_no_data=with_no_data, + ) + ) + return Job(job) @override def open_materialized_view(self, name: str) -> MaterializedView: - raise NotImplementedError( - "materialized views are supported only on local databases" - ) + view = MaterializedView(self.open_table(name)) + view.definition + return view @override def list_materialized_views(self) -> List[str]: - raise NotImplementedError( - "materialized views are supported only on local databases" + return LOOP.run(self._conn.list_materialized_views()) + + @override + def drop_materialized_view( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> None: + if namespace_path is None: + namespace_path = [] + LOOP.run(self._conn.drop_materialized_view(name, namespace_path=namespace_path)) + + @override + def drop_materialized_view_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job[None]: + if namespace_path is None: + namespace_path = [] + job = LOOP.run( + self._conn.drop_materialized_view_async(name, namespace_path=namespace_path) ) + return Job(job) @override def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 5cd7b23d6..695ef142a 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -1,9 +1,15 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import contextlib +import http.server +import json +import threading + import lancedb import pytest from lancedb.materialized_view import MaterializedViewDefinition +from lancedb.remote.db import RemoteDBConnection STABLE_ROW_IDS = {"new_table_enable_stable_row_ids": "true"} @@ -22,6 +28,152 @@ def make_db(tmp_path): return db +@contextlib.contextmanager +def mock_remote_materialized_views(): + requests = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + requests.append(self.path) + encoded = json.dumps({"views": ["daily_sales"]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + with http.server.HTTPServer(("localhost", 0), Handler) as server: + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"http://localhost:{server.server_address[1]}", requests + finally: + server.shutdown() + thread.join() + + +@contextlib.contextmanager +def mock_remote_materialized_view_create(): + requests = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length", 0)) + body = json.loads(self.rfile.read(length) or b"{}") + requests.append((self.path, body)) + job_id = "mv-drop-123" if self.path.endswith("/drop") else "mv-create-123" + encoded = json.dumps({"job_id": job_id}).encode() + self.send_response(202) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + with http.server.HTTPServer(("localhost", 0), Handler) as server: + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"http://localhost:{server.server_address[1]}", requests + finally: + server.shutdown() + thread.join() + + +def test_remote_list_uses_namespace_route(): + with mock_remote_materialized_views() as (host, requests): + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + assert db.list_materialized_views() == ["daily_sales"] + assert requests == ["/v1/namespace/$/materialized_view/list"] + + +def test_remote_create_async_returns_server_job(): + with mock_remote_materialized_view_create() as (host, requests): + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + job = db.create_materialized_view_async("adults", "people", where="age >= 18") + assert job.id == "mv-create-123" + assert requests == [ + ( + "/v1/materialized_view/adults/create", + {"query": 'SELECT * FROM "people" WHERE age >= 18', "with_no_data": False}, + ) + ] + + +def test_remote_drop_async_returns_server_job(): + with mock_remote_materialized_view_create() as (host, requests): + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + job = db.drop_materialized_view_async("adults") + assert job.id == "mv-drop-123" + assert requests == [("/v1/materialized_view/adults/drop", {})] + + +def test_sync_remote_create_uses_public_async_connection(): + calls = [] + + class StubAsyncTable: + name = "adults" + + class StubAsyncMaterializedView: + table = StubAsyncTable() + + class StrictAsyncConnection: + async def create_materialized_view( + self, + name, + source, + *, + select=None, + where=None, + limit=None, + with_no_data=False, + ): + calls.append((name, source, select, where, limit, with_no_data)) + return StubAsyncMaterializedView() + + async def drop_materialized_view(self, name, *, namespace_path=None): + calls.append(("drop", name, namespace_path)) + + db = RemoteDBConnection.__new__(RemoteDBConnection) + db._conn = StrictAsyncConnection() + db.db_name = "example" + db.serialize = lambda: "{}" + + view = db.create_materialized_view( + "adults", + "people", + select=["name"], + where="age >= 18", + limit=10, + with_no_data=True, + ) + assert view.name == "adults" + assert calls == [("adults", "people", ["name"], "age >= 18", 10, True)] + + db.drop_materialized_view("adults", namespace_path=["analytics"]) + assert calls[-1] == ("drop", "adults", ["analytics"]) + + def test_create_refresh_and_query(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view( @@ -31,16 +183,34 @@ def test_create_refresh_and_query(tmp_path): where="age >= 18", ) assert view.name == "adults" - assert view.table.count_rows() == 0 - - result = view.refresh() - assert result.mode == "rebuild" - assert result.rows_written == 2 + assert view.table.count_rows() == 2 rows = view.table.search().to_list() assert sorted(row["shout"] for row in rows) == ["ADA", "GRACE"] +def test_create_and_refresh_jobs(tmp_path): + db = make_db(tmp_path) + create_job = db.create_materialized_view_async( + "adults", "people", where="age >= 18", with_no_data=True + ) + assert create_job.id is None + assert create_job.wait() is None + + view = db.open_materialized_view("adults") + refresh_job = view.refresh_async() + assert refresh_job.id is None + result = refresh_job.wait() + assert result.mode == "rebuild" + assert result.rows_written == 2 + assert view.table.count_rows() == 2 + + drop_job = db.drop_materialized_view_async("adults") + assert drop_job.id is None + assert drop_job.wait() is None + assert "adults" not in db.list_materialized_views() + + def test_definition_round_trips(tmp_path): db = make_db(tmp_path) db.create_materialized_view("adults", "people", where="age >= 18") @@ -56,7 +226,7 @@ def test_definition_round_trips(tmp_path): def test_incremental_refresh_after_append(tmp_path): db = make_db(tmp_path) - view = db.create_materialized_view("copy", "people") + view = db.create_materialized_view("copy", "people", with_no_data=True) view.refresh() db.open_table("people").add([{"name": "alan", "age": 41}]) @@ -70,7 +240,7 @@ def test_incremental_refresh_after_append(tmp_path): def test_incremental_refresh_after_update(tmp_path): db = make_db(tmp_path) - view = db.create_materialized_view("copy", "people") + view = db.create_materialized_view("copy", "people", with_no_data=True) view.refresh() db.open_table("people").update(where="name = 'kid'", values={"age": 8}) @@ -87,7 +257,7 @@ def test_legacy_storage_source_update_rebuilds(tmp_path): storage_options={**STABLE_ROW_IDS, "new_table_data_storage_version": "legacy"}, ) db.create_table("people", [{"name": "ada", "age": 36}, {"name": "kid", "age": 7}]) - view = db.create_materialized_view("copy", "people") + view = db.create_materialized_view("copy", "people", with_no_data=True) view.refresh() db.open_table("people").update(where="name = 'kid'", values={"age": 8}) @@ -104,6 +274,11 @@ def test_list_and_not_a_view(tmp_path): assert db.list_materialized_views() == ["adults"] with pytest.raises(ValueError, match="not a materialized view"): db.open_materialized_view("people") + with pytest.raises(ValueError, match="not a materialized view"): + db.drop_materialized_view("people") + + db.drop_materialized_view("adults") + assert db.list_materialized_views() == [] def test_invalid_expression_fails_at_create(tmp_path): @@ -119,7 +294,10 @@ async def test_async_create_refresh_and_open(tmp_path): await db.create_table("people", [{"name": "ada", "age": 36}]) view = await db.create_materialized_view( - "shouts", "people", select=[("shout", "upper(name)")] + "shouts", + "people", + select=[("shout", "upper(name)")], + with_no_data=True, ) result = await view.refresh() assert result.mode == "rebuild" @@ -131,11 +309,35 @@ async def test_async_create_refresh_and_open(tmp_path): assert await db.list_materialized_views() == ["shouts"] +@pytest.mark.asyncio +async def test_async_create_and_refresh_jobs(tmp_path): + db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) + await db.create_table("people", [{"name": "ada", "age": 36}]) + + create_job = await db.create_materialized_view_async( + "adults", "people", with_no_data=True + ) + assert create_job.id is None + assert await create_job.wait() is None + + view = await db.open_materialized_view("adults") + refresh_job = await view.refresh_async() + assert refresh_job.id is None + result = await refresh_job.wait() + assert result.mode == "rebuild" + assert result.rows_written == 1 + + drop_job = await db.drop_materialized_view_async("adults") + assert drop_job.id is None + assert await drop_job.wait() is None + assert "adults" not in await db.list_materialized_views() + + @pytest.mark.asyncio async def test_async_incremental(tmp_path): db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) await db.create_table("people", [{"name": "ada", "age": 36}]) - view = await db.create_materialized_view("copy", "people") + view = await db.create_materialized_view("copy", "people", with_no_data=True) await view.refresh() table = await db.open_table("people") @@ -157,7 +359,10 @@ def test_bare_select_names_are_quoted(tmp_path): db.create_table("odd_names", [{"order item": "widget", "select": 2}]) view = db.create_materialized_view( - "quoted", "odd_names", select=["order item", "select"] + "quoted", + "odd_names", + select=["order item", "select"], + with_no_data=True, ) result = view.refresh() assert result.rows_written == 1 @@ -166,19 +371,6 @@ def test_bare_select_names_are_quoted(tmp_path): assert rows[0]["select"] == 2 -@pytest.mark.asyncio -async def test_async_remote_is_refused_without_network(): - db = await lancedb.connect_async( - "db://nowhere", api_key="sk_test", region="us-east-1" - ) - with pytest.raises(NotImplementedError, match="local"): - await db.create_materialized_view("v", "src") - with pytest.raises(NotImplementedError, match="local"): - await db.open_materialized_view("v") - with pytest.raises(NotImplementedError, match="local"): - await db.list_materialized_views() - - def test_scalar_select_is_one_column(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("just_name", "people", select="name") @@ -235,6 +427,17 @@ def test_namespace_connection_materialized_views(tmp_path): with pytest.raises(ValueError, match="not a materialized view"): db.open_materialized_view("people") + create_job = db.create_materialized_view_async( + "job_view", "people", with_no_data=True + ) + assert create_job.wait() is None + refresh_job = db.open_materialized_view("job_view").refresh_async() + assert refresh_job.wait().rows_written == 2 + + assert db.drop_materialized_view_async("job_view").wait() is None + db.drop_materialized_view("adults") + assert db.list_materialized_views() == [] + @pytest.mark.asyncio async def test_async_namespace_connection_materialized_views(tmp_path): @@ -267,6 +470,19 @@ async def test_async_namespace_connection_materialized_views(tmp_path): ) assert handle._namespace_path == through_namespace._namespace_path + create_job = await db.create_materialized_view_async( + "job_view", "people", with_no_data=True + ) + assert await create_job.wait() is None + job_view = await db.open_materialized_view("job_view") + refresh_job = await job_view.refresh_async() + assert (await refresh_job.wait()).rows_written == 2 + + drop_job = await db.drop_materialized_view_async("job_view") + assert await drop_job.wait() is None + await db.drop_materialized_view("adults") + assert await db.list_materialized_views() == [] + def test_namespaced_select_kind_is_read_and_unknown_kinds_are_refused(): import json diff --git a/python/src/connection.rs b/python/src/connection.rs index 2d613966a..65d4c98e8 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -381,7 +381,7 @@ impl Connection { }) } - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None))] + #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, @@ -389,6 +389,7 @@ impl Connection { projections: Option>, filter: Option, limit: Option, + with_no_data: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { @@ -402,16 +403,79 @@ impl Connection { if let Some(limit) = limit { builder = builder.limit(limit); } - let view = builder.execute().await.infer_error()?; + builder = builder.with_no_data(with_no_data); + let view = Box::pin(builder.execute()).await.infer_error()?; Ok(Table::new(view.table().clone())) }) } + #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false))] + pub fn create_materialized_view_async( + self_: PyRef<'_, Self>, + name: String, + source: String, + projections: Option>, + filter: Option, + limit: Option, + with_no_data: bool, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let mut builder = inner.create_materialized_view(name, source); + if let Some(projections) = projections { + builder = builder.select(projections); + } + if let Some(filter) = filter { + builder = builder.only_if(filter); + } + if let Some(limit) = limit { + builder = builder.limit(limit); + } + let job = Box::pin(builder.with_no_data(with_no_data).execute_async()) + .await + .infer_error()?; + Ok(crate::job::Job::new(job)) + }) + } + pub fn list_materialized_views(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let views = inner.list_materialized_views().await.infer_error()?; - Ok(views.into_iter().map(|view| view.name).collect::>()) + Ok(views) + }) + } + + #[pyo3(signature = (name, namespace_path=None))] + pub fn drop_materialized_view( + self_: PyRef<'_, Self>, + name: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let namespace_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + inner + .drop_materialized_view(name, &namespace_path) + .await + .infer_error() + }) + } + + #[pyo3(signature = (name, namespace_path=None))] + pub fn drop_materialized_view_async( + self_: PyRef<'_, Self>, + name: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let namespace_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + inner + .drop_materialized_view_async(name, &namespace_path) + .await + .infer_error() + .map(crate::job::Job::new) }) } diff --git a/python/src/error.rs b/python/src/error.rs index aa13a8e87..b46fa6c83 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -29,6 +29,7 @@ impl PythonErrorExt for std::result::Result { LanceError::InvalidInput { .. } | LanceError::InvalidTableName { .. } | LanceError::TableNotFound { .. } + | LanceError::NotAMaterializedView { .. } | LanceError::Schema { .. } | LanceError::TableAlreadyExists { .. } => self.value_error(), LanceError::CreateDir { .. } => self.os_error(), diff --git a/python/src/table.rs b/python/src/table.rs index 784d29136..4cea61543 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -452,6 +452,17 @@ pub struct RefreshMaterializedViewResult { #[pymethods] impl RefreshMaterializedViewResult { + #[staticmethod] + pub fn from_json(value: &str) -> PyResult { + let result: lancedb::RefreshMaterializedViewResult = + serde_json::from_str(value).map_err(|err| { + PyValueError::new_err(format!( + "failed to decode materialized-view refresh result: {err}" + )) + })?; + Ok(Self::from(result)) + } + pub fn __repr__(&self) -> String { format!( "RefreshMaterializedViewResult(mode={}, rows_written={}, source_version={}, version={})", @@ -1647,6 +1658,40 @@ impl Table { }) } + #[pyo3(signature = (full=false, source_version=None))] + pub fn refresh_materialized_view_async( + self_: PyRef<'_, Self>, + full: bool, + source_version: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let view = lancedb::MaterializedView::from_table(inner) + .await + .infer_error()?; + let mut builder = view.refresh().full(full); + if let Some(version) = source_version { + builder = builder.source_version(version); + } + let job = builder.execute_async().await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + + pub fn materialized_view_definition(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let view = lancedb::MaterializedView::from_table(inner) + .await + .infer_error()?; + serde_json::to_string(view.definition()).map_err(|err| { + PyRuntimeError::new_err(format!( + "failed to serialize materialized-view definition: {err}" + )) + }) + }) + } + pub fn add_columns_with_schema( self_: PyRef<'_, Self>, schema: PyArrowType, diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 843170030..b8d19443b 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -14,7 +14,7 @@ //! * Tables may be managed by a database system (e.g. Postgres) //! * A custom table implementation (e.g. remote table, etc.) may be used -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::time::Duration; @@ -28,6 +28,8 @@ use lance_namespace::models::{ use crate::data::scannable::Scannable; use crate::error::Result; +use crate::job::Job; +use crate::materialized_view::CreateMaterializedViewRequest; use crate::table::{BaseTable, WriteOptions}; pub mod listing; @@ -301,6 +303,73 @@ pub trait Database: ) -> Result> { function_catalog_not_supported() } + /// Create a materialized view through a remote catalog and return its + /// initial-population job. Local connections use the native declaration + /// path directly. + #[doc(hidden)] + async fn create_materialized_view_async( + &self, + _request: CreateMaterializedViewRequest, + ) -> Result { + job_op_not_supported("remote materialized-view creation") + } + /// Drop a materialized view through its resource endpoint and return its + /// cleanup job. Local connections validate the view and use table drop. + #[doc(hidden)] + async fn drop_materialized_view_async( + &self, + _name: &str, + _namespace_path: &[String], + ) -> Result { + job_op_not_supported("remote materialized-view drop") + } + /// List materialized-view names in a namespace. + #[doc(hidden)] + async fn list_materialized_views(&self, namespace_path: &[String]) -> Result> { + let mut names = Vec::new(); + let mut page_token = None; + let mut seen_page_tokens = HashSet::new(); + loop { + let response = self + .list_tables(ListTablesRequest { + id: Some(namespace_path.to_vec()), + page_token: page_token.clone(), + ..Default::default() + }) + .await?; + for name in response.tables { + let Ok(table) = self + .open_table(OpenTableRequest { + name: name.clone(), + namespace_path: namespace_path.to_vec(), + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + .await + else { + continue; + }; + let schema = table.schema().await?; + if crate::materialized_view::materialized_view_kind(schema.metadata())?.is_some() { + names.push(name); + } + } + let Some(next_page_token) = response.page_token.filter(|token| !token.is_empty()) + else { + break; + }; + if !seen_page_tokens.insert(next_page_token.clone()) { + return Err(crate::Error::Runtime { + message: "materialized-view listing repeated a page token".into(), + }); + } + page_token = Some(next_page_token); + } + Ok(names) + } /// Look up one exact immutable Function version. async fn get_function( &self, diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 98f1338d0..342e89bfa 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -5,9 +5,10 @@ //! //! A materialized view is a table whose contents are defined by a query over //! one source table and maintained by refresh rather than by writes. Creation -//! commits an empty table carrying the kind-tagged definition in schema -//! metadata; a kind added later reads back as unrefreshable, not as a plain -//! table. Queries, indexes and search work on the view unchanged. +//! records a kind-tagged definition in schema metadata and populates the view +//! unless creation explicitly requests no data. A kind added later reads back +//! as unrefreshable, not as a plain table. Queries, indexes and search work on +//! the view unchanged. pub mod refresh; @@ -28,6 +29,7 @@ use crate::database::listing::OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS; use crate::database::{CreateTableRequest, Database, OpenTableRequest}; use crate::embeddings::EmbeddingDefinition; use crate::function::FunctionBinding; +use crate::job::Job; use crate::table::Table; use crate::table::computed_columns::{ FUNCTION_BINDINGS_META_KEY, computed_column_from_field, computed_columns, @@ -124,6 +126,30 @@ pub struct MaterializedViewDefinition { pub inputs: Vec, } +/// The backend-independent metadata needed to open a materialized view. +#[doc(hidden)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MaterializedViewInfo { + /// The parsed view definition. + pub definition: MaterializedViewDefinition, + /// The current physical incarnation, when one has been minted. + pub incarnation: Option, +} + +/// The backend-independent request used to create a remote materialized view. +#[doc(hidden)] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CreateMaterializedViewRequest { + /// Name of the new view. + pub name: String, + /// Namespace in which to create the view. + pub namespace_path: Vec, + /// Defining SELECT query. + pub query: String, + /// Whether to skip the initial population job. + pub with_no_data: bool, +} + /// Prefix of the internal columns holding source columns a computed column /// reads without the view projecting them; see /// [`PreparedDeclaration::input_column`]. @@ -199,6 +225,28 @@ pub fn materialized_view_kind( Ok(Some(MaterializedViewKind::Select(definition))) } +pub(crate) fn materialized_view_info_from_metadata( + name: &str, + metadata: &HashMap, +) -> Result { + let incarnation = metadata.get(INCARNATION_META_KEY).cloned(); + match materialized_view_kind(metadata)? { + Some(MaterializedViewKind::Select(definition)) => Ok(MaterializedViewInfo { + definition, + incarnation, + }), + Some(MaterializedViewKind::Unrecognized { kind }) => Err(Error::NotSupported { + message: format!( + "materialized view '{name}' is defined by '{kind}', which this version of \ + lancedb cannot refresh" + ), + }), + None => Err(Error::NotAMaterializedView { + name: name.to_string(), + }), + } +} + /// Resolve a definition against the source schema into the view's projected /// fields, with `inputs` filled in. Everything statically checkable is /// checked here rather than at refresh time. Empty `projections` selects @@ -1114,27 +1162,6 @@ pub async fn prepare_declaration( }) } -/// One row of [`Connection::list_materialized_views`]: a view's name and its -/// definition kind, which may be one this version cannot refresh. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MaterializedViewEntry { - /// Name of the view's table. - pub name: String, - /// The view's definition as stored. - pub kind: MaterializedViewKind, -} - -/// Materialized views are local-only; refuse a remote connection before any -/// request is made. -fn ensure_local(connection: &Connection) -> Result<()> { - if connection.uri().starts_with("db://") { - return Err(Error::NotSupported { - message: "materialized views are supported only on local databases".into(), - }); - } - Ok(()) -} - /// Builds a materialized view. Created by /// [`Connection::create_materialized_view`]. pub struct CreateMaterializedViewBuilder { @@ -1146,6 +1173,7 @@ pub struct CreateMaterializedViewBuilder { projections: Vec<(String, String)>, filter: Option, limit: Option, + with_no_data: bool, } impl CreateMaterializedViewBuilder { @@ -1159,6 +1187,7 @@ impl CreateMaterializedViewBuilder { projections: Vec::new(), filter: None, limit: None, + with_no_data: false, } } @@ -1200,11 +1229,84 @@ impl CreateMaterializedViewBuilder { self } - /// Create the view: an empty table carrying the definition; refresh - /// computes the rows. The source must keep stable row ids -- they hold - /// provenance across compaction, and cannot be enabled later. + /// Create only the definition and empty backing table. By default create + /// also waits for the initial refresh so the returned view is populated. + pub fn with_no_data(mut self, with_no_data: bool) -> Self { + self.with_no_data = with_no_data; + self + } + + fn query(&self) -> String { + fn quote(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) + } + + let projection = if self.projections.is_empty() { + "*".to_string() + } else { + self.projections + .iter() + .map(|(output, expression)| format!("{expression} AS {}", quote(output))) + .collect::>() + .join(", ") + }; + let source = self + .source_namespace + .iter() + .chain(std::iter::once(&self.source)) + .map(|part| quote(part)) + .collect::>() + .join("."); + let mut query = format!("SELECT {projection} FROM {source}"); + if let Some(filter) = &self.filter { + query.push_str(" WHERE "); + query.push_str(filter); + } + if let Some(limit) = self.limit { + query.push_str(&format!(" LIMIT {limit}")); + } + query + } + + /// Submit creation and initial population, returning a [`Job`] that + /// settles when the view is ready. The source must keep stable row ids -- + /// they hold provenance across compaction, and cannot be enabled later. + pub async fn execute_async(self) -> Result { + if self.connection.uri().starts_with("db://") { + return self + .connection + .database() + .create_materialized_view_async(CreateMaterializedViewRequest { + name: self.name.clone(), + namespace_path: self.namespace.clone(), + query: self.query(), + with_no_data: self.with_no_data, + }) + .await; + } + Ok(Job::spawned(tokio::spawn(async move { + self.execute_native().await.map(|_| ()) + }))) + } + + /// Create and populate the view, waiting until it is ready. pub async fn execute(self) -> Result { - ensure_local(&self.connection)?; + if !self.connection.uri().starts_with("db://") { + return self.execute_native().await; + } + let connection = self.connection.clone(); + let name = self.name.clone(); + let namespace = self.namespace.clone(); + self.execute_async().await?.wait().await?; + let table = connection + .open_table(name) + .namespace(namespace) + .execute() + .await?; + MaterializedView::from_table(table).await + } + + async fn execute_native(self) -> Result { let source = self .connection .open_table(&self.source) @@ -1218,7 +1320,11 @@ impl CreateMaterializedViewBuilder { self.limit, ) .await?; - prepared.create_in(&self.namespace, &self.name).await + let view = prepared.create_in(&self.namespace, &self.name).await?; + if !self.with_no_data { + view.refresh().execute().await?; + } + Ok(view) } } @@ -1235,32 +1341,12 @@ impl MaterializedView { /// for a plain table, [`Error::NotSupported`] for a kind this version /// cannot refresh. pub async fn from_table(table: Table) -> Result { - // Same local-only boundary the connection-level entry points hold, - // applied before the schema read so a remote table costs no request. - if table.as_native().is_none() { - return Err(Error::NotSupported { - message: "materialized views are supported only on local databases".into(), - }); - } - let schema = table.schema().await?; - let incarnation = schema.metadata().get(INCARNATION_META_KEY).cloned(); - match materialized_view_kind(schema.metadata())? { - Some(MaterializedViewKind::Select(definition)) => Ok(Self { - table, - definition, - incarnation, - }), - Some(MaterializedViewKind::Unrecognized { kind }) => Err(Error::NotSupported { - message: format!( - "materialized view '{}' is defined by '{kind}', which this version of \ - lancedb cannot refresh", - table.name() - ), - }), - None => Err(Error::NotAMaterializedView { - name: table.name().to_string(), - }), - } + let info = table.base_table().materialized_view_info().await?; + Ok(Self { + table, + definition: info.definition, + incarnation: info.incarnation, + }) } /// The view, as the table it is. Queries, indexes and search all apply. @@ -1345,22 +1431,52 @@ impl RefreshMaterializedViewBuilder { self } + /// Submit the refresh and return a job that settles with its result. + pub async fn execute_async(self) -> Result> { + if self.view.table.as_native().is_none() { + return self + .view + .table + .base_table() + .refresh_materialized_view_async( + self.full, + self.source_version, + self.expected_incarnation.as_deref(), + ) + .await; + } + Ok(Job::spawned(tokio::spawn(async move { + refresh::execute_refresh( + &self.view.table, + self.full, + self.source_version, + self.expected_incarnation.as_deref(), + ) + .await + }))) + } + + /// Refresh the view, waiting for the job to finish. pub async fn execute(self) -> Result { - refresh::execute_refresh( - &self.view.table, - self.full, - self.source_version, - self.expected_incarnation.as_deref(), - ) - .await + if self.view.table.as_native().is_some() { + return refresh::execute_refresh( + &self.view.table, + self.full, + self.source_version, + self.expected_incarnation.as_deref(), + ) + .await; + } + self.execute_async().await?.wait().await } } impl Connection { /// Define a materialized view named `name` over `source`. /// - /// The view is created empty, with the definition recorded in its schema - /// metadata; refresh computes the rows. Local databases only. + /// The definition is recorded in schema metadata and the initial refresh + /// is completed before this method returns. Use + /// [`CreateMaterializedViewBuilder::with_no_data`] to skip population. /// /// ```no_run /// # #![recursion_limit = "256"] @@ -1372,7 +1488,7 @@ impl Connection { /// .only_if("age >= 18") /// .execute() /// .await?; - /// view.refresh().execute().await?; + /// assert_eq!(view.table().count_rows(None).await?, 1); /// # Ok(()) /// # } /// ``` @@ -1389,28 +1505,75 @@ impl Connection { &self, name: impl Into, ) -> Result { - ensure_local(self)?; let table = self.open_table(name).execute().await?; MaterializedView::from_table(table).await } - /// The materialized views in this database, unrefreshable kinds included. - /// Costs a table open per table; one that cannot be opened is skipped - /// rather than failing the listing. - pub async fn list_materialized_views(&self) -> Result> { - ensure_local(self)?; - let names = self.table_names().execute().await?; - let mut views = Vec::new(); - for name in names { - let Ok(table) = self.open_table(&name).execute().await else { - continue; - }; - let schema = table.schema().await?; - if let Some(kind) = materialized_view_kind(schema.metadata())? { - views.push(MaterializedViewEntry { name, kind }); - } + /// The names of materialized views in the root namespace. + pub async fn list_materialized_views(&self) -> Result> { + self.database().list_materialized_views(&[]).await + } + + /// Drop a materialized view. + /// + /// The view may become unavailable before its physical data is removed. + /// Use [`Connection::drop_materialized_view_async`] to retain the cleanup + /// job and wait for it explicitly. + pub async fn drop_materialized_view( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result<()> { + let name = name.as_ref(); + if self.uri().starts_with("db://") { + return self + .database() + .drop_materialized_view_async(name, namespace_path) + .await + .map(|_| ()); } - Ok(views) + let table = self + .open_table(name) + .namespace(namespace_path.to_vec()) + .execute() + .await?; + MaterializedView::from_table(table).await?; + self.drop_table(name, namespace_path).await + } + + /// Start dropping a materialized view and return its cleanup job. + /// + /// This validates that the named resource is a materialized view rather + /// than an ordinary table. Call [`Job::wait`] before assuming physical + /// cleanup has finished. + /// + /// ```no_run + /// # use lancedb::Connection; + /// # async fn drop_view(conn: &Connection) -> lancedb::Result<()> { + /// let job = conn.drop_materialized_view_async("daily_sales", &[]).await?; + /// job.wait().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn drop_materialized_view_async( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result { + let name = name.as_ref(); + if self.uri().starts_with("db://") { + return self + .database() + .drop_materialized_view_async(name, namespace_path) + .await; + } + let table = self + .open_table(name) + .namespace(namespace_path.to_vec()) + .execute() + .await?; + MaterializedView::from_table(table).await?; + self.drop_table_async(name, namespace_path).await } } @@ -1523,9 +1686,86 @@ mod tests { .data_type(), &DataType::UInt64 ); + assert_eq!(view.table().count_rows(None).await.unwrap(), 3); + } + + #[tokio::test] + async fn test_with_no_data_skips_initial_refresh() { + let conn = people_db().await; + let view = conn + .create_materialized_view("empty", "people") + .with_no_data(true) + .execute() + .await + .unwrap(); assert_eq!(view.table().count_rows(None).await.unwrap(), 0); } + #[tokio::test] + async fn test_create_and_refresh_async_jobs() { + let conn = people_db().await; + let create_job = conn + .create_materialized_view("async_view", "people") + .with_no_data(true) + .execute_async() + .await + .unwrap(); + assert!(create_job.id().is_none()); + create_job.wait().await.unwrap(); + + let view = conn.open_materialized_view("async_view").await.unwrap(); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + + let refresh_job = view.refresh().execute_async().await.unwrap(); + assert!(refresh_job.id().is_none()); + let result = refresh_job.wait().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(result.rows_written, 3); + assert_eq!(view.table().count_rows(None).await.unwrap(), 3); + + let drop_job = conn + .drop_materialized_view_async("async_view", &[]) + .await + .unwrap(); + assert!(drop_job.id().is_none()); + drop_job.wait().await.unwrap(); + assert!(conn.open_table("async_view").execute().await.is_err()); + } + + #[tokio::test] + async fn test_drop_materialized_view_rejects_plain_tables() { + let conn = people_db().await; + let error = conn + .drop_materialized_view("people", &[]) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotAMaterializedView { .. })); + + conn.create_materialized_view("drop_me", "people") + .with_no_data(true) + .execute() + .await + .unwrap(); + conn.drop_materialized_view("drop_me", &[]).await.unwrap(); + assert!(conn.open_table("drop_me").execute().await.is_err()); + } + + #[tokio::test] + async fn test_remote_query_quotes_resource_identifiers() { + let conn = people_db().await; + let query = conn + .create_materialized_view("unused", "odd\"source") + .source_namespace(vec!["raw data".into()]) + .select([("double\"age", "age * 2")]) + .only_if("age >= 18") + .limit(10) + .query(); + assert_eq!( + query, + "SELECT age * 2 AS \"double\"\"age\" FROM \"raw data\".\"odd\"\"source\" WHERE age >= 18 LIMIT 10" + ); + } + /// No projection selects every source column, expanded now: the schema /// captured at creation is the definition. #[tokio::test] @@ -1673,14 +1913,9 @@ mod tests { .unwrap(); let views = conn.list_materialized_views().await.unwrap(); - assert_eq!( - views.iter().map(|v| v.name.as_str()).collect::>(), - vec!["adults"] - ); - let MaterializedViewKind::Select(definition) = &views[0].kind else { - panic!("expected a select view"); - }; - assert_eq!(definition.filter.as_deref(), Some("age >= 18")); + assert_eq!(views, vec!["adults"]); + let view = conn.open_materialized_view("adults").await.unwrap(); + assert_eq!(view.definition().filter.as_deref(), Some("age >= 18")); } /// The creation option outranks a connection configured to create @@ -1763,7 +1998,7 @@ mod tests { /// A newer-kind view must not disappear from the listing. #[tokio::test] - async fn test_unrecognized_kind_is_listed_with_its_kind() { + async fn test_unrecognized_kind_is_listed_by_name() { let conn = people_db().await; conn.create_materialized_view("v", "people") .execute() @@ -1781,36 +2016,7 @@ mod tests { .unwrap(); let views = conn.list_materialized_views().await.unwrap(); - assert_eq!(views.len(), 1); - assert_eq!(views[0].name, "v"); - assert_eq!( - views[0].kind, - MaterializedViewKind::Unrecognized { - kind: "join".into() - } - ); - } - - /// Remote connections are refused before any request is made. - #[cfg(feature = "remote")] - #[tokio::test] - async fn test_remote_connection_is_refused_up_front() { - let conn = connect("db://nowhere") - .api_key("sk_test") - .region("us-east-1") - .execute() - .await - .unwrap(); - let err = conn - .create_materialized_view("v", "src") - .execute() - .await - .unwrap_err(); - assert!(matches!(err, Error::NotSupported { .. })); - let err = conn.open_materialized_view("v").await.unwrap_err(); - assert!(matches!(err, Error::NotSupported { .. })); - let err = conn.list_materialized_views().await.unwrap_err(); - assert!(matches!(err, Error::NotSupported { .. })); + assert_eq!(views, vec!["v"]); } /// A definition must evaluate identically across refreshes; anything @@ -2461,6 +2667,7 @@ mod tests { let view = conn .create_materialized_view("adults", "people") + .with_no_data(true) .namespace(vec!["ns".to_string()]) .source_namespace(vec!["ns".to_string()]) .select([("name", "name")]) diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 433b185f7..62b3db22f 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -1657,6 +1657,7 @@ mod tests { async fn doubled_view(conn: &Connection) -> MaterializedView { conn.create_materialized_view("doubled", "src") + .with_no_data(true) .select([("x", "x"), ("twice", "x * 2")]) .execute() .await @@ -1724,6 +1725,7 @@ mod tests { let (conn, _) = db_with_source(vec![1, 20, 3, 40]).await; let view = conn .create_materialized_view("big", "src") + .with_no_data(true) .select([("x", "x")]) .only_if("x > 10") .execute() @@ -1749,6 +1751,7 @@ mod tests { .await .unwrap(); conn.create_materialized_view("democrats", "src") + .with_no_data(true) .select([("id", "id")]) .only_if(r#""PartyAbbrev" = 'D'"#) .execute() @@ -1784,6 +1787,7 @@ mod tests { .unwrap(); let view = conn .create_materialized_view("legacy_view", "legacy_src") + .with_no_data(true) .select([("id", "id")]) .only_if(r#""PartyAbbrev" = 'X'"#) .execute() @@ -1851,6 +1855,7 @@ mod tests { let (conn, source) = db_with_source(vec![1, 20]).await; let view = conn .create_materialized_view("big", "src") + .with_no_data(true) .select([("x", "x")]) .only_if("x > 10") .execute() @@ -1872,6 +1877,7 @@ mod tests { let (conn, source) = db_with_source(vec![20]).await; let view = conn .create_materialized_view("big", "src") + .with_no_data(true) .select([("x", "x")]) .only_if("x > 10") .execute() @@ -1929,6 +1935,7 @@ mod tests { .unwrap(); let view = conn .create_materialized_view("legacy_doubled", "legacy_src") + .with_no_data(true) .select([("x", "x"), ("twice", "x * 2")]) .execute() .await @@ -2007,6 +2014,7 @@ mod tests { let (conn, source) = db_with_source(vec![1, 2, 3]).await; let view = conn .create_materialized_view("drifting_view", "src") + .with_no_data(true) .select([("x", "x"), ("twice", "x * 2")]) .execute() .await @@ -2093,6 +2101,7 @@ mod tests { let (conn, source) = db_with_source(vec![1, 2, 3]).await; let view = conn .create_materialized_view("atomic_view", "src") + .with_no_data(true) .select([("x", "x"), ("twice", "x * 2")]) .execute() .await @@ -2195,6 +2204,7 @@ mod tests { let (conn, _) = db_with_source(vec![1, 2, 3]).await; let view = conn .create_materialized_view("raced_rebuild", "src") + .with_no_data(true) .select([("x", "x"), ("twice", "x * 2")]) .execute() .await @@ -2291,6 +2301,7 @@ mod tests { let (conn, source) = db_with_source(vec![1, 2, 3]).await; let view = conn .create_materialized_view("raced_incremental", "src") + .with_no_data(true) .select([("x", "x"), ("twice", "x * 2")]) .execute() .await @@ -2409,6 +2420,7 @@ mod tests { let (conn, source) = db_with_source(vec![1, 2, 3]).await; let view = conn .create_materialized_view("empty", "src") + .with_no_data(true) .select([("x", "x")]) .limit(0) .execute() @@ -2576,6 +2588,7 @@ mod tests { let (conn, source) = db_with_source(vec![1, 2]).await; let view = conn .create_materialized_view("capped", "src") + .with_no_data(true) .select([("x", "x")]) .limit(2) .execute() @@ -2608,6 +2621,7 @@ mod tests { let (conn, source) = db_with_source(vec![1, 2, 3]).await; let view = conn .create_materialized_view("capped", "src") + .with_no_data(true) .select([("x", "x")]) .limit(4) .execute() @@ -2677,6 +2691,7 @@ mod tests { let (conn, _) = db_with_source(vec![1, 2]).await; let view = conn .create_materialized_view("none", "src") + .with_no_data(true) .select([("x", "x")]) .only_if("x > 100") .execute() @@ -2720,6 +2735,7 @@ mod tests { let (conn, source) = db_with_source(vec![1]).await; let view = conn .create_materialized_view("v", "src") + .with_no_data(true) .select([("twice", "x * 2")]) .execute() .await @@ -2779,6 +2795,7 @@ mod tests { let second = conn .create_materialized_view("second", "doubled") + .with_no_data(true) .only_if("twice > 10") .execute() .await @@ -3146,6 +3163,7 @@ mod tests { let (conn, _) = db_with_source(vec![1, 2]).await; let view = conn .create_materialized_view("v", "src") + .with_no_data(true) .select([("double value", "x * 2")]) .execute() .await @@ -3199,6 +3217,7 @@ mod tests { // An active-LSM source is refused at create. let err = conn .create_materialized_view("v", "src") + .with_no_data(true) .execute() .await .unwrap_err(); @@ -3209,6 +3228,7 @@ mod tests { table.unset_lsm_write_spec().await.unwrap(); let view = conn .create_materialized_view("v", "src") + .with_no_data(true) .execute() .await .unwrap(); diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 1d6f9abe8..7180b04ce 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -26,6 +26,7 @@ use crate::database::{ use crate::error::Result; use crate::function::{FunctionRegistrationRequest, FunctionVersion}; use crate::job::Job; +use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::job::{RemoteJob, job_state_to_client}; use crate::remote::util::stream_as_body; use crate::table::BaseTable; @@ -587,6 +588,127 @@ impl Database for RemoteDatabase { }) } + async fn create_materialized_view_async( + &self, + request: CreateMaterializedViewRequest, + ) -> Result { + let identifier = build_table_identifier( + &request.name, + &request.namespace_path, + &self.client.id_delimiter, + ); + let req = self + .client + .post(&format!("/v1/materialized_view/{identifier}/create")) + .json(&serde_json::json!({ + "query": request.query, + "with_no_data": request.with_no_data, + })); + let (request_id, response) = self.client.send(req).await?; + let response = self.client.check_response(&request_id, response).await?; + let status = response.status(); + let body = response.text().await.err_to_http(request_id.clone())?; + let job_id = extract_job_id(&body); + + if request.with_no_data { + return Ok(match job_id { + Some(job_id) => Job::new(Box::new(RemoteJob::new(self.client.clone(), job_id))), + None => Job::new_done(), + }); + } + if status != StatusCode::ACCEPTED { + return Err(Error::Http { + source: "materialized-view creation with data must return 202 Accepted".into(), + request_id, + status_code: Some(status), + }); + } + let job_id = job_id.ok_or_else(|| Error::Http { + source: "materialized-view creation response did not contain a valid job_id".into(), + request_id, + status_code: Some(status), + })?; + Ok(Job::new(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + + async fn drop_materialized_view_async( + &self, + name: &str, + namespace_path: &[String], + ) -> Result { + let identifier = build_table_identifier(name, namespace_path, &self.client.id_delimiter); + let request = self + .client + .post(&format!("/v1/materialized_view/{identifier}/drop")); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let status = response.status(); + let body = response.text().await.err_to_http(request_id.clone())?; + if status != StatusCode::ACCEPTED { + return Err(Error::Http { + source: "materialized-view drop must return 202 Accepted".into(), + request_id, + status_code: Some(status), + }); + } + let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { + source: "materialized-view drop response did not contain a valid job_id".into(), + request_id, + status_code: Some(status), + })?; + self.table_cache + .remove(&build_cache_key(name, namespace_path)) + .await; + Ok(Job::new(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + + async fn list_materialized_views(&self, namespace_path: &[String]) -> Result> { + #[derive(serde::Deserialize)] + struct ListMaterializedViewsResponse { + #[serde(default)] + views: Vec, + #[serde(default)] + page_token: Option, + } + + let namespace_id = build_namespace_identifier(namespace_path, &self.client.id_delimiter); + let path = format!("/v1/namespace/{namespace_id}/materialized_view/list"); + let mut views = Vec::new(); + let mut page_token: Option = None; + let mut seen_page_tokens = HashSet::new(); + loop { + let mut req = self.client.get(&path); + if let Some(token) = &page_token { + req = req.query(&[("page_token", token)]); + } + let (request_id, response) = self.client.send(req).await?; + let response = self.client.check_response(&request_id, response).await?; + let status = response.status(); + let response: ListMaterializedViewsResponse = + response.json().await.err_to_http(request_id.clone())?; + views.extend(response.views); + let Some(next_page_token) = response.page_token.filter(|token| !token.is_empty()) + else { + break; + }; + if !seen_page_tokens.insert(next_page_token.clone()) { + return Err(Error::Http { + source: "Materialized-view listing response repeated a page_token".into(), + request_id, + status_code: Some(status), + }); + } + page_token = Some(next_page_token); + } + Ok(views) + } + async fn create_function_async( &self, request: FunctionRegistrationRequest, @@ -1292,6 +1414,8 @@ mod tests { use lance_namespace_impls::{DynamicContextProvider, OperationInfo}; use crate::connection::ConnectBuilder; + use crate::database::Database; + use crate::materialized_view::CreateMaterializedViewRequest; use crate::{ Connection, Error, database::CreateTableMode, @@ -1331,6 +1455,103 @@ mod tests { assert_eq!(key1, key6, "Same inputs should produce same cache key"); } + #[tokio::test] + async fn test_create_materialized_view_uses_item_route_and_job() { + let db = super::RemoteDatabase::new_mock(|request| { + assert_eq!(request.method(), "POST"); + assert_eq!( + request.url().path(), + "/v1/materialized_view/analytics$adults/create" + ); + let body = request + .body() + .and_then(reqwest::Body::as_bytes) + .and_then(|bytes| serde_json::from_slice::(bytes).ok()) + .unwrap(); + assert_eq!( + body["query"], + "SELECT age AS \"age\" FROM \"raw\".\"people\" WHERE age >= 18 LIMIT 10" + ); + assert_eq!(body["with_no_data"], false); + http::Response::builder() + .status(202) + .body(serde_json::json!({"job_id": "j1-mv-create"}).to_string()) + .unwrap() + }); + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "adults".into(), + namespace_path: vec!["analytics".into()], + query: "SELECT age AS \"age\" FROM \"raw\".\"people\" WHERE age >= 18 LIMIT 10" + .into(), + with_no_data: false, + }) + .await + .unwrap(); + assert_eq!(job.id(), Some("j1-mv-create")); + } + + #[tokio::test] + async fn test_drop_materialized_view_uses_item_route_and_job() { + let db = super::RemoteDatabase::new_mock(|request| { + assert_eq!(request.method(), "POST"); + assert_eq!( + request.url().path(), + "/v1/materialized_view/analytics$adults/drop" + ); + assert!(request.body().is_none()); + http::Response::builder() + .status(202) + .body(serde_json::json!({"job_id": "j1-mv-drop"}).to_string()) + .unwrap() + }); + let job = db + .drop_materialized_view_async("adults", &["analytics".into()]) + .await + .unwrap(); + assert_eq!(job.id(), Some("j1-mv-drop")); + } + + #[tokio::test] + async fn test_list_materialized_views_follows_empty_pages() { + let page = Arc::new(AtomicUsize::new(0)); + let db = super::RemoteDatabase::new_mock({ + let page = page.clone(); + move |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().path(), + "/v1/namespace/analytics/materialized_view/list" + ); + match page.fetch_add(1, Ordering::SeqCst) { + 0 => { + assert!(request.url().query().is_none()); + http::Response::builder() + .status(200) + .body( + serde_json::json!({"views": [], "page_token": "next"}).to_string(), + ) + .unwrap() + } + 1 => { + assert_eq!(request.url().query(), Some("page_token=next")); + http::Response::builder() + .status(200) + .body(serde_json::json!({"views": ["adults"]}).to_string()) + .unwrap() + } + _ => panic!("listing requested too many pages"), + } + } + }); + assert_eq!( + db.list_materialized_views(&["analytics".into()]) + .await + .unwrap(), + ["adults"] + ); + } + #[tokio::test] async fn test_retries() { // We'll record the request_id here, to check it matches the one in the error. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 5c32e3cdd..747e2b73c 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -17,6 +17,9 @@ use crate::index::IndexStatistics; use crate::index::scalar::FtsQuery; use crate::index::waiter::wait_for_index; use crate::job::Job; +use crate::materialized_view::{ + MaterializedViewDefinition, MaterializedViewInfo, RefreshMaterializedViewResult, ViewProjection, +}; use crate::query::{QueryFilter, QueryRequest, Select, VectorQueryRequest}; use crate::remote::job::RemoteJob; use crate::table::AddColumnsResult; @@ -250,10 +253,17 @@ struct FreshnessJob { inner: RemoteJob, freshness: Arc>, version: Arc>>, - track_refresh_result: bool, + tracked_result: TrackedJobResult, freshness_request: FreshnessHeaders, } +#[derive(Clone, Copy)] +enum TrackedJobResult { + None, + RefreshColumn, + MaterializedView, +} + #[async_trait] impl crate::job::JobHandle for FreshnessJob { fn id(&self) -> Option<&str> { @@ -279,22 +289,26 @@ impl crate::job::JobHandle for FreshnessJob { let result = crate::job::JobHandle::wait(&self.inner).await?; let version = self.version.read().await; if version.is_none() { - let result_version = self - .track_refresh_result - .then(|| result.value()) - .flatten() - .and_then(|value| { + let result_version = match self.tracked_result { + TrackedJobResult::None => None, + TrackedJobResult::RefreshColumn => result.value().and_then(|value| { serde_json::from_value::(value.clone()) .ok() - }) - .map(|result| { - result - .published_version - .map_or(result.source_version, |version| { - version.max(result.source_version) + .map(|result| { + result + .published_version + .map_or(result.source_version, |version| { + version.max(result.source_version) + }) }) - }) - .filter(|version| *version != 0); + }), + TrackedJobResult::MaterializedView => result.value().and_then(|value| { + serde_json::from_value::(value.clone()) + .ok() + .map(|result| result.version) + }), + } + .filter(|version| *version != 0); if let Some(version) = result_version { self.freshness_request .observe_version(&self.freshness, version); @@ -2051,6 +2065,106 @@ impl BaseTable for RemoteTable { fn id(&self) -> &str { &self.identifier } + async fn materialized_view_info(&self) -> Result { + #[derive(Deserialize)] + struct Projection { + output_column: String, + expression: String, + } + + #[derive(Deserialize)] + struct DescribeMaterializedViewResponse { + source_table: String, + #[serde(default)] + source_namespace: Vec, + #[serde(default)] + projections: Vec, + #[serde(default)] + filter: Option, + #[serde(default)] + limit: Option, + #[serde(default)] + inputs: Vec, + #[serde(default)] + incarnation: Option, + } + + let request = self.client.post(&format!( + "/v1/materialized_view/{}/describe", + self.identifier + )); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let response: DescribeMaterializedViewResponse = + response.json().await.err_to_http(request_id)?; + Ok(MaterializedViewInfo { + definition: MaterializedViewDefinition { + source_table: response.source_table, + source_namespace: response.source_namespace, + projections: response + .projections + .into_iter() + .map(|projection| ViewProjection { + output: projection.output_column, + expression: projection.expression, + }) + .collect(), + filter: response.filter, + limit: response.limit, + inputs: response.inputs, + }, + incarnation: response.incarnation, + }) + } + + async fn refresh_materialized_view_async( + &self, + full: bool, + source_version: Option, + expected_incarnation: Option<&str>, + ) -> Result> { + self.check_mutable().await?; + let mut body = serde_json::json!({ "full": full }); + if let Some(source_version) = source_version { + body["source_version"] = source_version.into(); + } + if let Some(expected_incarnation) = expected_incarnation { + body["expected_incarnation"] = expected_incarnation.into(); + } + let request = self + .client + .post(&format!( + "/v1/materialized_view/{}/refresh", + self.identifier + )) + .json(&body); + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; + let response = self.check_table_response(&request_id, response).await?; + let status = response.status(); + let body = response.text().await.err_to_http(request_id.clone())?; + if status != StatusCode::ACCEPTED { + return Err(Error::Http { + source: "materialized-view refresh must return 202 Accepted".into(), + request_id, + status_code: Some(status), + }); + } + let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { + source: "materialized-view refresh response did not contain a valid job_id".into(), + request_id, + status_code: Some(status), + })?; + Ok(Job::new_typed(Box::new(FreshnessJob { + inner: RemoteJob::new(self.client.clone(), job_id), + freshness: self.freshness.clone(), + version: self.version.clone(), + tracked_result: TrackedJobResult::MaterializedView, + freshness_request, + }))) + } async fn query_snapshot(&self) -> Result> { let description = self.describe().await?; let TableDescription { @@ -2901,7 +3015,7 @@ impl BaseTable for RemoteTable { inner: RemoteJob::new(self.client.clone(), job_id), freshness: self.freshness.clone(), version: self.version.clone(), - track_refresh_result: false, + tracked_result: TrackedJobResult::None, freshness_request: self.snapshot_freshness_headers(), })), None => Job::new_done(), @@ -3384,7 +3498,7 @@ impl BaseTable for RemoteTable { inner: RemoteJob::new(self.client.clone(), response.job_id), freshness: self.freshness.clone(), version: self.version.clone(), - track_refresh_result: true, + tracked_result: TrackedJobResult::RefreshColumn, freshness_request: self.snapshot_freshness_headers(), }))) } @@ -12017,17 +12131,77 @@ mod tests { } #[tokio::test] - async fn test_materialized_view_refused_without_a_request() { - // Materialized views are local-only. The table-level entry the - // bindings use must refuse a remote table before reading its schema, - // so the panicking handler is the assertion. - let table = Table::new_with_handler("my_table", |request| -> http::Response { - panic!("unexpected request: {}", request.url().path()) + async fn test_materialized_view_describe_and_refresh() { + let table = Table::new_with_handler("my_table", |request| match request.url().path() { + "/v1/materialized_view/my_table/describe" => http::Response::builder() + .status(200) + .body( + json!({ + "name": "my_table", + "source_table": "source", + "source_namespace": ["analytics"], + "projections": [{ + "output_column": "double_x", + "expression": "x * 2" + }], + "filter": "x > 0", + "limit": 10, + "inputs": ["x"], + "incarnation": "inc-1" + }) + .to_string(), + ) + .unwrap(), + "/v1/materialized_view/my_table/refresh" => { + assert_eq!(request.method(), "POST"); + assert_eq!( + request_body_json(&request), + json!({ + "full": true, + "source_version": 7, + "expected_incarnation": "inc-1" + }) + ); + http::Response::builder() + .status(202) + .body(json!({"job_id": "j1-mv-refresh"}).to_string()) + .unwrap() + } + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body( + json!({ + "job_id": "j1-mv-refresh", + "job_state": "DONE", + "result": { + "mode": "rebuild", + "rows_written": 2, + "source_version": 7, + "version": 9 + } + }) + .to_string(), + ) + .unwrap(), + path => panic!("unexpected request: {path}"), }); - let err = crate::MaterializedView::from_table(table) + let view = crate::MaterializedView::from_table(table).await.unwrap(); + assert_eq!(view.definition().source_table, "source"); + assert_eq!(view.definition().source_namespace, ["analytics"]); + assert_eq!(view.definition().inputs, ["x"]); + assert_eq!(view.incarnation(), Some("inc-1")); + + let result = view + .refresh() + .full(true) + .source_version(7) + .expect_incarnation("inc-1") + .execute() .await - .unwrap_err(); - assert!(matches!(err, Error::NotSupported { .. }), "got {err:?}"); + .unwrap(); + assert_eq!(result.mode, crate::RefreshMode::Rebuild); + assert_eq!(result.rows_written, 2); + assert_eq!(result.version, 9); } #[tokio::test] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 5732955f5..0cf6a0e4f 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -563,6 +563,29 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { fn id(&self) -> &str; /// Get the arrow [Schema] of the table. async fn schema(&self) -> Result; + /// Read this table's materialized-view definition and incarnation. + #[doc(hidden)] + async fn materialized_view_info( + &self, + ) -> Result { + let schema = self.schema().await?; + crate::materialized_view::materialized_view_info_from_metadata( + self.name(), + schema.metadata(), + ) + } + /// Submit a materialized-view refresh. + #[doc(hidden)] + async fn refresh_materialized_view_async( + &self, + _full: bool, + _source_version: Option, + _expected_incarnation: Option<&str>, + ) -> Result> { + Err(Error::NotSupported { + message: "remote materialized-view refresh is not supported on this table type".into(), + }) + } /// Create a read-only handle pinned to the table's current active revision. /// /// The returned handle is independent from later refreshes or checkouts on