From 6bc3ecdffa295657d7ac9527f52bc415a06d8f48 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 13 May 2026 10:08:39 +0000 Subject: [PATCH] feat(pyo3): metadata + ResultStream surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 step 3 of the PySQL × kernel integration plan. Wraps the kernel's `Metadata` API and adds a standalone `ResultStream` Python class for the bare streams the metadata calls return. New Python surface: - `Session.metadata() -> Metadata` - `Metadata.list_catalogs() -> ResultStream` - `Metadata.list_schemas(*, catalog=None, schema_pattern=None) -> ResultStream` - `Metadata.list_tables(*, catalog=None, schema_pattern=None, table_pattern=None, table_types=None) -> ResultStream` - `Metadata.list_columns(*, catalog, schema_pattern=None, table_pattern=None, column_pattern=None) -> ResultStream` - `Metadata.primary_keys(*, catalog, schema, table) -> ResultStream` - `Metadata.foreign_keys(*, parent_catalog=None, parent_schema=None, parent_table=None, foreign_catalog, foreign_schema, foreign_table) -> ResultStream` - `Metadata.functions / procedures(*, catalog=None, schema_pattern=None, name_pattern=None) -> ResultStream` - `Metadata.type_info() / table_types() -> ResultStream` (static, no wire call) - `ResultStream` — `arrow_schema()`, `fetch_next_batch()`, `fetch_all_arrow()`, `close()`. The Python surface collapses kernel `Identifier` / `LikePattern` back to `Option[str]`; the kernel still enforces empty / NUL / backtick / length-cap checks, surfacing bad input as `KernelError(code='InvalidArgument', ...)`. Implementation notes: - New `fetch.rs` shared helpers (`next_batch`, `drain`, `batches_to_pyarrow_table`) so `ExecutedStatement` and the new `ResultStream` produce identical Python objects from the same code path. - `ExecutedStatement::fetch_*` refactored to call the helpers; no behavior change. - `Metadata` methods are inline `block_on`s — the `for<'a> FnOnce(&'a Metadata) -> Fut` HRTB trick can't express the bound the borrow checker needs, and the inline form is simpler anyway. Smoke test (`pyo3/smoke.py`) extended with the metadata surface and validation checks; verified end-to-end against dogfood. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- pyo3/smoke.py | 212 +++++++++++++++++++++++++++++++ pyo3/src/fetch.rs | 84 +++++++++++++ pyo3/src/lib.rs | 13 +- pyo3/src/metadata.rs | 254 ++++++++++++++++++++++++++++++++++++++ pyo3/src/result_stream.rs | 133 ++++++++++++++++++++ pyo3/src/session.rs | 10 ++ pyo3/src/statement.rs | 59 ++------- 7 files changed, 713 insertions(+), 52 deletions(-) create mode 100644 pyo3/smoke.py create mode 100644 pyo3/src/fetch.rs create mode 100644 pyo3/src/metadata.rs create mode 100644 pyo3/src/result_stream.rs diff --git a/pyo3/smoke.py b/pyo3/smoke.py new file mode 100644 index 00000000..ae05260a --- /dev/null +++ b/pyo3/smoke.py @@ -0,0 +1,212 @@ +"""Live smoke test for the databricks_sql_kernel PyO3 wheel. + +Exercises the surface that's currently implemented (PAT auth, sync +execute, metadata, ResultStream draining, error mapping) against a +live Databricks warehouse. Reads creds from env vars (set via +`set -a && source ~/.databricks/pecotesting-creds && set +a`). + +Run from `pyo3/` so maturin picks up the project-local `.venv`: + + cd pyo3 + .venv/bin/maturin develop --release + .venv/bin/python smoke.py +""" + +from __future__ import annotations +import os +import sys +import traceback + +import databricks_sql_kernel as k +import pyarrow as pa + + +def require_env(name: str) -> str: + v = os.environ.get(name) + if not v: + sys.exit(f"missing env var: {name}") + return v + + +HOST = require_env("DATABRICKS_HOST") +HTTP_PATH = require_env("DATABRICKS_HTTP_PATH") +TOKEN = require_env("DATABRICKS_TOKEN") + + +def banner(s: str) -> None: + print(f"\n=== {s} ===") + + +def check(cond: bool, msg: str) -> None: + print(f" {'OK ' if cond else 'FAIL '} {msg}") + if not cond: + sys.exit(1) + + +def main() -> None: + banner("module + version") + print(f" databricks_sql_kernel.__version__ = {k.__version__}") + + banner("open session") + session = k.Session( + host=HOST, + http_path=HTTP_PATH, + access_token=TOKEN, + ) + check(bool(session.session_id), f"session_id non-empty: {session.session_id!r}") + print(f" repr: {session!r}") + + banner("SELECT 1 — fetch_next_batch path") + stmt = session.statement() + stmt.set_sql("SELECT 1 AS n") + exec_ = stmt.execute() + check(bool(exec_.statement_id), f"statement_id non-empty: {exec_.statement_id!r}") + schema = exec_.arrow_schema() + check(isinstance(schema, pa.Schema), f"arrow_schema is pyarrow.Schema: {schema}") + batch = exec_.fetch_next_batch() + check(isinstance(batch, pa.RecordBatch), f"first batch is RecordBatch: {batch.num_rows} rows") + check(batch.num_rows == 1, "one row") + check(batch.column(0).to_pylist() == [1], f"value is 1: {batch.column(0).to_pylist()}") + nxt = exec_.fetch_next_batch() + check(nxt is None, "second fetch returns None") + exec_.close() + print(f" repr after close: {exec_!r}") + stmt.close() + + banner("SELECT range(10000) — fetch_all_arrow path") + stmt = session.statement() + stmt.set_sql("SELECT * FROM range(10000)") + exec_ = stmt.execute() + table = exec_.fetch_all_arrow() + check(isinstance(table, pa.Table), f"got pyarrow.Table with {table.num_rows} rows") + check(table.num_rows == 10000, f"expected 10000 rows, got {table.num_rows}") + exec_.close() + stmt.close() + + banner("idempotent close") + stmt = session.statement() + stmt.set_sql("SELECT 42") + exec_ = stmt.execute() + exec_.close() + exec_.close() # second call should be a no-op + check(True, "double-close on ExecutedStatement did not raise") + + banner("operations on closed ExecutedStatement raise KernelError") + try: + exec_.fetch_next_batch() + check(False, "should have raised") + except k.KernelError as e: + check("closed" in str(e), f"KernelError mentions closed: {e}") + + # --- metadata surface --- + meta = session.metadata() + + banner("metadata.list_catalogs") + rs = meta.list_catalogs() + check(isinstance(rs.arrow_schema(), pa.Schema), "ResultStream schema is pyarrow.Schema") + cat_table = rs.fetch_all_arrow() + check(isinstance(cat_table, pa.Table), f"got Table with {cat_table.num_rows} catalogs") + check(cat_table.num_rows > 0, "at least one catalog visible") + print(f" first few: {cat_table.column(0).to_pylist()[:5]}") + rs.close() + + banner("metadata.list_schemas — main catalog") + rs = meta.list_schemas(catalog="main") + schemas_table = rs.fetch_all_arrow() + check(schemas_table.num_rows > 0, f"main has schemas: {schemas_table.num_rows}") + rs.close() + + banner("metadata.list_tables — system.information_schema") + rs = meta.list_tables(catalog="system", schema_pattern="information_schema") + tables_table = rs.fetch_all_arrow() + check(tables_table.num_rows > 0, f"information_schema has tables: {tables_table.num_rows}") + print(f" columns in result: {[f.name for f in tables_table.schema]}") + rs.close() + + banner("metadata.list_columns — system.information_schema.tables") + rs = meta.list_columns( + catalog="system", schema_pattern="information_schema", table_pattern="tables" + ) + cols_table = rs.fetch_all_arrow() + check(cols_table.num_rows > 0, f"tables has columns: {cols_table.num_rows}") + rs.close() + + banner("metadata.type_info — static, no wire call") + rs = meta.type_info() + ti_table = rs.fetch_all_arrow() + check(ti_table.num_rows > 0, f"type_info rows: {ti_table.num_rows}") + rs.close() + + banner("metadata.table_types — static, no wire call") + rs = meta.table_types() + tt_table = rs.fetch_all_arrow() + check(tt_table.num_rows > 0, f"table_types rows: {tt_table.num_rows}") + rs.close() + + banner("metadata input validation — empty identifier is rejected") + try: + meta.list_schemas(catalog="") + check(False, "empty catalog should have raised") + except k.KernelError as e: + attrs = e.args[1] + check(attrs.get("code") == "InvalidArgument", f"code=InvalidArgument, got: {attrs.get('code')}") + check( + "identifier" in attrs.get("message", "").lower(), + f"message mentions identifier: {attrs.get('message')}", + ) + + banner("metadata input validation — list_columns requires catalog kwarg") + try: + meta.list_columns(schema_pattern="x", table_pattern="y") # type: ignore[call-arg] + check(False, "missing catalog kwarg should have raised TypeError") + except TypeError as e: + check(True, f"TypeError as expected: {e}") + + banner("ResultStream close + use-after-close") + rs = meta.list_catalogs() + rs.close() + rs.close() # idempotent + try: + rs.fetch_next_batch() + check(False, "should have raised") + except k.KernelError as e: + check("closed" in str(e), f"KernelError mentions closed: {e}") + + banner("close session") + session.close() + session.close() # idempotent + check(True, "double-close on Session did not raise") + + banner("operations on closed Session raise KernelError") + try: + session.statement() + check(False, "should have raised") + except k.KernelError as e: + check("closed" in str(e), f"KernelError mentions closed: {e}") + + banner("error mapping — bad SQL surfaces as KernelError") + s2 = k.Session(host=HOST, http_path=HTTP_PATH, access_token=TOKEN) + stmt = s2.statement() + stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_smoke") + try: + stmt.execute() + check(False, "should have raised on bad SQL") + except k.KernelError as e: + args = e.args + check(len(args) >= 2 and isinstance(args[1], dict), f"args carry structured dict: {args!r}") + attrs = args[1] + check("code" in attrs, "attrs has 'code'") + check("message" in attrs, "attrs has 'message'") + s2.close() + + print("\nAll smoke checks passed.") + + +if __name__ == "__main__": + try: + main() + except SystemExit: + raise + except Exception: + traceback.print_exc() + sys.exit(2) diff --git a/pyo3/src/fetch.rs b/pyo3/src/fetch.rs new file mode 100644 index 00000000..0ae41fb8 --- /dev/null +++ b/pyo3/src/fetch.rs @@ -0,0 +1,84 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Internal helpers for pulling batches out of a `ResultStream`. +//! +//! Shared by `ExecutedStatement` (drives the kernel `ExecutedStatement`'s +//! borrowed result stream) and `ResultStream` (owns its kernel +//! `ResultStream` directly). Both call `next_batch` on the kernel +//! stream and clone the Arrow `RecordBatch` out from under the +//! borrow so the result can cross the GIL boundary as an owned value. + +use arrow_array::RecordBatch; +use arrow_pyarrow::ToPyArrow; +use arrow_schema::Schema; +use databricks_sql_kernel::{Error, Result, ResultBatch, ResultStream}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Pull the next batch from the kernel stream and return it as an +/// owned `RecordBatch`, or `None` if the stream is exhausted. +/// +/// Caller is responsible for holding `py.detach(...)` open around +/// the call — this function does kernel I/O. +pub(crate) fn next_batch( + runtime: &Runtime, + stream: &mut ResultStream, +) -> Result> { + runtime.block_on(async { + match stream.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), + Some(_) => Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")), + None => Ok(None), + } + }) +} + +/// Drain the kernel stream and collect every remaining batch. +pub(crate) fn drain(runtime: &Runtime, stream: &mut ResultStream) -> Result> { + runtime.block_on(async { + let mut out = Vec::new(); + loop { + match stream.next_batch().await? { + Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), + Some(_) => { + return Err(Error::invalid_argument() + .message("kernel returned a non-Arrow ResultBatch variant")); + } + None => break, + } + } + Ok(out) + }) +} + +/// Wrap a Vec of `RecordBatch` into a `pyarrow.Table`. Centralised +/// so both `ExecutedStatement.fetch_all_arrow` and +/// `ResultStream.fetch_all_arrow` produce identical Python objects. +pub(crate) fn batches_to_pyarrow_table<'py>( + py: Python<'py>, + schema: &Arc, + batches: Vec, +) -> PyResult> { + let py_batches: Vec> = batches + .into_iter() + .map(|b| b.to_pyarrow(py)) + .collect::>()?; + let py_schema = schema.as_ref().to_pyarrow(py)?; + let pa = py.import("pyarrow")?; + pa.getattr("Table")? + .call_method1("from_batches", (py_batches, py_schema)) +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 6a2ca291..14556959 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -14,15 +14,18 @@ //! Python bindings for the Databricks SQL Kernel. //! -//! Phase 1 scaffold: `Session`, `Statement`, `ExecutedStatement`. PAT -//! auth only; synchronous `execute()` path. Built as the -//! `databricks_sql_kernel` extension module via `maturin develop` / -//! `maturin build`. +//! Phase 1 surface today: `Session`, `Statement`, `ExecutedStatement`, +//! `Metadata`, `ResultStream`. PAT auth only; synchronous `execute()` +//! path. Built as the `databricks_sql_kernel` extension module via +//! `maturin develop` / `maturin build`. //! //! The kernel's API is async — every method call from Python detaches //! the GIL and `block_on`s on the session-owned tokio runtime. mod errors; +mod fetch; +mod metadata; +mod result_stream; mod session; mod statement; @@ -35,5 +38,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; Ok(()) } diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs new file mode 100644 index 00000000..f1fe657d --- /dev/null +++ b/pyo3/src/metadata.rs @@ -0,0 +1,254 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `Metadata` — Python wrapper for the kernel's flat metadata API. +//! +//! Mirrors `kernel::Metadata` one-to-one. Each method blocks on the +//! session's tokio runtime, returns a `ResultStream` that the caller +//! drains the same way it drains `ExecutedStatement` results. +//! +//! The kernel splits exact identifiers (`Identifier`) from LIKE +//! patterns (`LikePattern`) at the type level. The Python surface +//! collapses both back to `Option[str]` because Python lacks a +//! convenient way to express two distinct string-flavoured types at +//! a call site. The kernel's runtime checks (empty, NUL, backticks +//! for identifiers; length caps for both) still apply; bad input +//! surfaces as `KernelError(code='InvalidArgument', ...)`. + +use crate::errors::to_py_err; +use crate::result_stream::ResultStream; +use databricks_sql_kernel::{Identifier, LikePattern, Metadata as KMetadata, Result as KResult}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Python-facing metadata handle. +/// +/// Constructed via `Session.metadata()`. Cheap to construct and +/// throw away — the underlying kernel `Metadata` is a thin wrapper +/// around the shared session state. +#[pyclass(name = "Metadata", unsendable)] +pub(crate) struct Metadata { + inner: KMetadata, + runtime: Arc, +} + +impl Metadata { + pub(crate) fn new(inner: KMetadata, runtime: Arc) -> Self { + Self { inner, runtime } + } +} + +/// Build a kernel `Identifier` from an optional Python string, or +/// `None` if the input was `None`. Empty / NUL / backtick rejection +/// happens kernel-side and surfaces as `InvalidArgument`. +fn opt_identifier(s: &Option) -> KResult>> { + s.as_deref().map(Identifier::new).transpose() +} + +fn opt_pattern(s: &Option) -> KResult>> { + s.as_deref().map(LikePattern::new).transpose() +} + +#[pymethods] +impl Metadata { + /// All catalogs visible to the session. + fn list_catalogs(&self, py: Python<'_>) -> PyResult { + let stream = py + .detach(|| self.runtime.block_on(self.inner.list_catalogs())) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Schemas filtered by catalog (exact) and schema name pattern. + #[pyo3(signature = (*, catalog=None, schema_pattern=None))] + fn list_schemas( + &self, + py: Python<'_>, + catalog: Option, + schema_pattern: Option, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = opt_identifier(&catalog)?; + let pat = opt_pattern(&schema_pattern)?; + self.runtime.block_on(self.inner.list_schemas(cat, pat)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Tables filtered by catalog (exact), schema (pattern), table + /// (pattern). `table_types` is advisory — Databricks does not + /// honour it server-side; wrappers filter the returned + /// `tableType` column themselves. + #[pyo3(signature = (*, catalog=None, schema_pattern=None, table_pattern=None, table_types=None))] + fn list_tables( + &self, + py: Python<'_>, + catalog: Option, + schema_pattern: Option, + table_pattern: Option, + table_types: Option>, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let types_owned: Option> = table_types + .as_ref() + .map(|v| v.iter().map(String::as_str).collect()); + let types_slice: Option<&[&str]> = types_owned.as_deref(); + self.runtime + .block_on(self.inner.list_tables(cat, sch, tbl, types_slice)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Columns of tables matching the filter. `catalog` is required + /// (Databricks `SHOW COLUMNS` cannot span catalogs). + #[pyo3(signature = (*, catalog, schema_pattern=None, table_pattern=None, column_pattern=None))] + fn list_columns( + &self, + py: Python<'_>, + catalog: String, + schema_pattern: Option, + table_pattern: Option, + column_pattern: Option, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = Some(Identifier::new(&catalog)?); + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let col = opt_pattern(&column_pattern)?; + self.runtime + .block_on(self.inner.list_columns(cat, sch, tbl, col)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Primary keys for the given table. All identifiers are exact. + #[pyo3(signature = (*, catalog, schema, table))] + fn primary_keys( + &self, + py: Python<'_>, + catalog: String, + schema: String, + table: String, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = Some(Identifier::new(&catalog)?); + let sch = Some(Identifier::new(&schema)?); + let tbl = Identifier::new(&table)?; + self.runtime + .block_on(self.inner.primary_keys(cat, sch, tbl)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Foreign-key relationships. The foreign side must be fully + /// specified (catalog + schema + table); the parent side is + /// optional. + #[pyo3(signature = (*, + parent_catalog=None, parent_schema=None, parent_table=None, + foreign_catalog, foreign_schema, foreign_table))] + #[allow(clippy::too_many_arguments)] + fn foreign_keys( + &self, + py: Python<'_>, + parent_catalog: Option, + parent_schema: Option, + parent_table: Option, + foreign_catalog: String, + foreign_schema: String, + foreign_table: String, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let pc = opt_identifier(&parent_catalog)?; + let ps = opt_identifier(&parent_schema)?; + let pt = opt_identifier(&parent_table)?; + let fc = Some(Identifier::new(&foreign_catalog)?); + let fs = Some(Identifier::new(&foreign_schema)?); + let ft = Some(Identifier::new(&foreign_table)?); + self.runtime + .block_on(self.inner.foreign_keys(pc, ps, pt, fc, fs, ft)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Functions visible to the session. + #[pyo3(signature = (*, catalog=None, schema_pattern=None, name_pattern=None))] + fn functions( + &self, + py: Python<'_>, + catalog: Option, + schema_pattern: Option, + name_pattern: Option, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&name_pattern)?; + self.runtime.block_on(self.inner.functions(cat, sch, nam)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// Procedures visible to the session. + #[pyo3(signature = (*, catalog=None, schema_pattern=None, name_pattern=None))] + fn procedures( + &self, + py: Python<'_>, + catalog: Option, + schema_pattern: Option, + name_pattern: Option, + ) -> PyResult { + let stream = py + .detach(|| -> KResult<_> { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&name_pattern)?; + self.runtime.block_on(self.inner.procedures(cat, sch, nam)) + }) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// SQL data types supported by the workspace. No filters; no + /// wire call (static in-memory result). + fn type_info(&self, py: Python<'_>) -> PyResult { + let stream = py + .detach(|| self.runtime.block_on(self.inner.type_info())) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// All table types. No wire call. + fn table_types(&self, py: Python<'_>) -> PyResult { + let stream = py + .detach(|| self.runtime.block_on(self.inner.table_types())) + .map_err(|e| to_py_err(py, e))?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } +} diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs new file mode 100644 index 00000000..4673e65f --- /dev/null +++ b/pyo3/src/result_stream.rs @@ -0,0 +1,133 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `ResultStream` — Python class wrapping a kernel `ResultStream`. +//! +//! Returned by `Session.metadata().list_*` calls and (in future) +//! anywhere the kernel hands back a bare `ResultStream` without an +//! enclosing `ExecutedStatement`. Identical fetch surface to +//! `ExecutedStatement` (Arrow batches, drain-to-Table), minus the +//! statement_id / cancel hooks that only make sense for an executed +//! statement. +//! +//! The actual batch-pulling logic lives in `fetch::*` helpers so +//! `ExecutedStatement::fetch_next_batch` / `fetch_all_arrow` can call +//! the same code path through its `result_stream_mut()` borrow. + +use crate::errors::to_py_err; +use crate::fetch; +use arrow_pyarrow::ToPyArrow; +use arrow_schema::Schema; +use databricks_sql_kernel::ResultStream as KResultStream; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Python-facing borrowed result stream. +/// +/// `unsendable` — like the rest of the surface, holding a tokio +/// `Runtime` makes the pyclass `!Send`. +#[pyclass(name = "ResultStream", unsendable)] +pub(crate) struct ResultStream { + inner: Option, + /// Cached schema — survives `close()` so callers can still read + /// the description after exhausting / closing the stream. + schema: Arc, +} + +struct ResultStreamInner { + stream: KResultStream, + runtime: Arc, + exhausted: bool, +} + +impl ResultStream { + pub(crate) fn new(stream: KResultStream, runtime: Arc) -> Self { + let schema = stream.schema(); + Self { + schema, + inner: Some(ResultStreamInner { + stream, + runtime, + exhausted: false, + }), + } + } + + fn alive_mut(&mut self) -> PyResult<&mut ResultStreamInner> { + self.inner + .as_mut() + .ok_or_else(|| crate::errors::KernelError::new_err("ResultStream is closed")) + } +} + +#[pymethods] +impl ResultStream { + /// Result schema as a `pyarrow.Schema`. Available even after `close()`. + fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult> { + self.schema.as_ref().to_pyarrow(py) + } + + /// Pull the next batch as a `pyarrow.RecordBatch`, or `None` when + /// exhausted. + fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { + let inner = self.alive_mut()?; + if inner.exhausted { + return Ok(None); + } + let runtime = inner.runtime.clone(); + let batch = py + .detach(|| fetch::next_batch(&runtime, &mut inner.stream)) + .map_err(|e| to_py_err(py, e))?; + match batch { + Some(b) => Ok(Some(b.to_pyarrow(py)?)), + None => { + inner.exhausted = true; + Ok(None) + } + } + } + + /// Drain the full result and return a single `pyarrow.Table`. + fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { + let inner = self.alive_mut()?; + let runtime = inner.runtime.clone(); + let batches = py + .detach(|| fetch::drain(&runtime, &mut inner.stream)) + .map_err(|e| to_py_err(py, e))?; + inner.exhausted = true; + fetch::batches_to_pyarrow_table(py, &self.schema, batches) + } + + /// Release client-side resources. Idempotent. Subsequent calls + /// on this handle raise `KernelError`. + fn close(&mut self) { + if let Some(inner) = self.inner.take() { + // ResultStream::close() is sync (no server RPC) and + // consumes self; the kernel's Drop performs the same + // cleanup, but the explicit call is cheaper to reason + // about. + inner.stream.close(); + } + } + + fn __repr__(&self) -> String { + let state = if self.inner.is_some() { + "open" + } else { + "closed" + }; + format!("ResultStream(state={state})") + } +} diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 897f00bd..801ebccc 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -21,6 +21,7 @@ //! pyclass alive longer than the user keeps a reference. use crate::errors::to_py_err; +use crate::metadata::Metadata; use crate::statement::Statement; use databricks_sql_kernel::{AuthConfig, Session as KSession}; use pyo3::prelude::*; @@ -125,6 +126,15 @@ impl Session { Ok(Statement::new(kstmt, inner.runtime.clone())) } + /// Metadata operations bound to this session (flat per-method, + /// ODBC-shaped). Returns a fresh `Metadata` handle on every call; + /// the handle is cheap to construct and throw away. + fn metadata(&self) -> PyResult { + let inner = self.alive()?; + let kmeta = inner.session.metadata(); + Ok(Metadata::new(kmeta, inner.runtime.clone())) + } + /// Explicitly close the session. Idempotent. Subsequent calls on /// this `Session` raise `KernelError`. fn close(&mut self, py: Python<'_>) -> PyResult<()> { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index cb482147..983bff3d 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -20,12 +20,11 @@ //! batch-by-batch as pyarrow `RecordBatch`es. use crate::errors::to_py_err; -use arrow_array::RecordBatch; +use crate::fetch; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{ - ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, ResultBatch, - Statement as KStatement, + ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, Statement as KStatement, }; use pyo3::prelude::*; use std::sync::Arc; @@ -149,25 +148,12 @@ impl ExecutedStatement { if inner.exhausted { return Ok(None); } - // Drive next_batch() on the session runtime with the GIL - // released for the whole I/O. The returned reference borrows - // from the stream; clone the RecordBatch (Arc-backed columns - // — cheap) out into an owned value so the borrow ends before - // we touch pyarrow. let runtime = inner.runtime.clone(); - let batch_result: databricks_sql_kernel::Result> = py.detach(|| { - runtime.block_on(async { - let stream = inner.exec.result_stream_mut(); - match stream.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())), - Some(_) => Err(databricks_sql_kernel::Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")), - None => Ok(None), - } - }) - }); - match batch_result.map_err(|e| to_py_err(py, e))? { - Some(batch) => Ok(Some(batch.to_pyarrow(py)?)), + let batch = py + .detach(|| fetch::next_batch(&runtime, inner.exec.result_stream_mut())) + .map_err(|e| to_py_err(py, e))?; + match batch { + Some(b) => Ok(Some(b.to_pyarrow(py)?)), None => { inner.exhausted = true; Ok(None) @@ -179,34 +165,11 @@ impl ExecutedStatement { fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult> { let inner = self.alive_mut()?; let runtime = inner.runtime.clone(); - let drain_result: databricks_sql_kernel::Result> = py.detach(|| { - runtime.block_on(async { - let mut out = Vec::new(); - let stream = inner.exec.result_stream_mut(); - loop { - match stream.next_batch().await? { - Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()), - Some(_) => { - return Err(databricks_sql_kernel::Error::invalid_argument() - .message("kernel returned a non-Arrow ResultBatch variant")); - } - None => break, - } - } - Ok(out) - }) - }); - let batches = drain_result.map_err(|e| to_py_err(py, e))?; + let batches = py + .detach(|| fetch::drain(&runtime, inner.exec.result_stream_mut())) + .map_err(|e| to_py_err(py, e))?; inner.exhausted = true; - - let py_batches: Vec> = batches - .into_iter() - .map(|b| b.to_pyarrow(py)) - .collect::>()?; - let py_schema = self.schema.as_ref().to_pyarrow(py)?; - let pa = py.import("pyarrow")?; - pa.getattr("Table")? - .call_method1("from_batches", (py_batches, py_schema)) + fetch::batches_to_pyarrow_table(py, &self.schema, batches) } /// Cancel the in-flight statement on the server. Local validity