diff --git a/Cargo.lock b/Cargo.lock index ccdad2f5..353520e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,11 +97,26 @@ dependencies = [ "flatbuffers", ] +[[package]] +name = "arrow-pyarrow" +version = "57.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f45c7989cb70214b2f362eaa10266d15e1a433692f2ea1514018be3aace679f4" +dependencies = [ + "arrow-array", + "arrow-data", + "arrow-schema", + "pyo3", +] + [[package]] name = "arrow-schema" version = "57.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bb63203e8e0e54b288d0d8043ca8fa1013820822a27692ef1b78a977d879f2c" +dependencies = [ + "bitflags", +] [[package]] name = "arrow-select" @@ -363,6 +378,18 @@ dependencies = [ "wiremock", ] +[[package]] +name = "databricks-sql-kernel-pyo3" +version = "0.1.0" +dependencies = [ + "arrow-array", + "arrow-pyarrow", + "arrow-schema", + "databricks-sql-kernel", + "pyo3", + "tokio", +] + [[package]] name = "deadpool" version = "0.12.3" @@ -679,6 +706,12 @@ version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.2" @@ -948,6 +981,15 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + [[package]] name = "ipnet" version = "2.11.0" @@ -1083,6 +1125,15 @@ version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "mime" version = "0.3.17" @@ -1324,6 +1375,12 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + [[package]] name = "potential_utf" version = "0.1.4" @@ -1351,6 +1408,67 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pyo3" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ba0117f4212101ee6544044dae45abe1083d30ce7b29c4b5cbdfa2354e07383" +dependencies = [ + "indoc", + "libc", + "memoffset", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", + "unindent", +] + +[[package]] +name = "pyo3-build-config" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fc6ddaf24947d12a9aa31ac65431fb1b851b8f4365426e182901eabfb87df5f" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "025474d3928738efb38ac36d4744a74a400c901c7596199e20e45d98eb194105" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e64eb489f22fe1c95911b77c44cc41e7c19f3082fc81cce90f657cdc42ffded" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "100246c0ecf400b475341b8455a9213344569af29a3c841d29270e53102e0fcf" +dependencies = [ + "heck", + "proc-macro2", + "pyo3-build-config", + "quote", + "syn", +] + [[package]] name = "quinn" version = "0.11.9" @@ -1903,6 +2021,12 @@ dependencies = [ "libc", ] +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tempfile" version = "3.24.0" @@ -2195,6 +2319,12 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" +[[package]] +name = "unindent" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 4bcd6b86..c6012cbd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,3 +76,8 @@ tempfile = "3" [lib] name = "databricks_sql_kernel" crate-type = ["lib", "cdylib", "staticlib"] + +# Workspace — the kernel is the root crate; language bindings live as +# sibling members. PyO3 first; napi-rs / etc. slot in here later. +[workspace] +members = [".", "pyo3"] diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml new file mode 100644 index 00000000..e9e830d8 --- /dev/null +++ b/pyo3/Cargo.toml @@ -0,0 +1,53 @@ +# 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. + +[package] +name = "databricks-sql-kernel-pyo3" +version = "0.1.0" +edition = "2021" +authors = ["Databricks"] +license = "Apache-2.0" +description = "PyO3 Python bindings for the Databricks SQL Kernel" +repository = "https://github.com/databricks/databricks-sql-kernel" + +# Built as a Python extension module by maturin. The lib basename here +# only affects the intermediate `.so` cargo produces; maturin renames +# the wheel artifact to `databricks_sql_kernel..so` per +# `module-name` in pyproject.toml, and pyo3 derives the `PyInit_*` +# symbol from the `#[pymodule]` function name (not this `[lib].name`). +# Picking a distinct name avoids colliding with the kernel root crate's +# own cdylib output. +# +# `rlib` is included so `cargo test -p databricks-sql-kernel-pyo3` +# can pick up future `#[cfg(test)]` modules in `src/**`. With only +# `cdylib`, cargo silently reports "running 0 tests / ok" even if a +# `#[test]` exists — a real footgun for any later Rust-side test. +[lib] +name = "databricks_sql_kernel_pyo3" +crate-type = ["cdylib", "rlib"] + +[dependencies] +databricks-sql-kernel = { path = ".." } + +# pyo3 — abi3-py39 lets one wheel cover Python 3.9+. +pyo3 = { version = "0.26", features = ["extension-module", "abi3-py39"] } + +# Multi-thread runtime — one per Session, owned on the Rust side. +tokio = { version = "1", features = ["rt-multi-thread"] } + +# Arrow handoff. Pinned to 57 to match the kernel's arrow-* deps so we +# share the same RecordBatch / Schema types and never have to convert. +arrow-array = "57" +arrow-schema = "57" +arrow-pyarrow = "57" diff --git a/pyo3/pyproject.toml b/pyo3/pyproject.toml new file mode 100644 index 00000000..46c8cb49 --- /dev/null +++ b/pyo3/pyproject.toml @@ -0,0 +1,16 @@ +[build-system] +requires = ["maturin>=1.5,<2.0"] +build-backend = "maturin" + +[project] +name = "databricks-sql-kernel" +version = "0.1.0" +description = "Python bindings for the Databricks SQL Kernel (PyO3)" +requires-python = ">=3.9" +license = { text = "Apache-2.0" } +authors = [{ name = "Databricks" }] +dependencies = ["pyarrow>=14"] + +[tool.maturin] +module-name = "databricks_sql_kernel" + diff --git a/pyo3/pytest.ini b/pyo3/pytest.ini new file mode 100644 index 00000000..de9aaa23 --- /dev/null +++ b/pyo3/pytest.ini @@ -0,0 +1,6 @@ +[pytest] +testpaths = tests +# Without rootdir/conftest discovery the `from conftest import live` +# imports in each test module won't resolve. Putting conftest.py in +# `tests/` plus adding tests/ to sys.path is the conventional setup. +pythonpath = tests diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs new file mode 100644 index 00000000..f8ebc1b2 --- /dev/null +++ b/pyo3/src/auth.rs @@ -0,0 +1,54 @@ +// 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. + +//! Translate Python auth kwargs into a kernel `AuthConfig`. +//! +//! Phase 1 ships PAT only. The kernel surface reserves +//! `AuthConfig::OAuthM2M`, `OAuthU2M`, `OAuthFederation`, and +//! `External`; wiring any of them into the Python wrapper needs a +//! deliberate design decision about credential ownership (does +//! PySQL own OAuth and feed tokens to the kernel, or does the +//! kernel run its own browser flow?). Until that's settled, the +//! connector backend raises `NotSupportedError` for non-PAT auth +//! and the wrapper rejects unknown `auth_type` values here so the +//! mistake surfaces at construction time, not deep inside an HTTP +//! retry loop. + +use databricks_sql_kernel::AuthConfig; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; + +/// Build a kernel `AuthConfig` from the Python kwargs the `Session` +/// constructor accepts. +/// +/// `auth_type` is currently restricted to `"pat"`. Additional +/// variants land when the OAuth ownership question is resolved. +pub(crate) fn build_auth_config( + auth_type: &str, + access_token: Option, +) -> PyResult { + match auth_type { + "pat" => { + let token = access_token + .ok_or_else(|| PyValueError::new_err("auth_type='pat' requires access_token"))?; + if token.is_empty() { + return Err(PyValueError::new_err("access_token must not be empty")); + } + Ok(AuthConfig::Pat { token }) + } + other => Err(PyValueError::new_err(format!( + "unsupported auth_type {other:?}; only 'pat' is supported today" + ))), + } +} diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs new file mode 100644 index 00000000..874e52d6 --- /dev/null +++ b/pyo3/src/errors.rs @@ -0,0 +1,149 @@ +// 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. + +//! `KernelError` — Python exception carrying the kernel's structured +//! error info. +//! +//! Subclassing native exception types is not allowed in `abi3` mode +//! (PyO3 emits a compile-time error: "with the abi3 feature enabled, +//! PyO3 does not support subclassing native types"). To keep one +//! wheel per platform across Python 3.9+, `KernelError` is built +//! via `create_exception!` (subclasses `Exception` at the Python C +//! level, not at the Rust pyclass level) and the structured fields +//! are attached as Python attributes via `setattr` so callers still +//! read `err.code` / `err.sql_state` / etc. directly — no +//! `err.args[1]['code']` tuple-unpacking. +//! +//! Connector-side code (`backend/kernel/client.py`) inspects +//! `err.code` and re-raises as `DatabaseError` / `OperationalError` +//! / `ProgrammingError` per PEP 249. This module owns the only +//! `kernel::Error -> PyErr` conversion site (`to_py_err`). + +use databricks_sql_kernel::{Error as KError, ErrorCode}; +use pyo3::create_exception; +use pyo3::exceptions::PyException; +use pyo3::prelude::*; + +create_exception!(databricks_sql_kernel, KernelError, PyException); + +/// Map a kernel `ErrorCode` to a stable string slug. +/// +/// `ErrorCode` is `#[non_exhaustive]`; new kernel variants surface +/// as `"Unknown"` on the Python side until this match is updated. +fn code_str(code: ErrorCode) -> &'static str { + match code { + ErrorCode::InvalidArgument => "InvalidArgument", + ErrorCode::Unauthenticated => "Unauthenticated", + ErrorCode::PermissionDenied => "PermissionDenied", + ErrorCode::NotFound => "NotFound", + ErrorCode::ResourceExhausted => "ResourceExhausted", + ErrorCode::Unavailable => "Unavailable", + ErrorCode::Timeout => "Timeout", + ErrorCode::Cancelled => "Cancelled", + ErrorCode::DataLoss => "DataLoss", + ErrorCode::Internal => "Internal", + ErrorCode::InvalidStatementHandle => "InvalidStatementHandle", + ErrorCode::NetworkError => "NetworkError", + ErrorCode::SqlError => "SqlError", + _ => "Unknown", + } +} + +/// Common attribute-set used by both `to_py_err` (kernel error +/// conversion) and `closed_err` (use-after-close guard). Pulls one +/// pyo3 attribute-setting site so the field list stays in lockstep. +#[allow(clippy::too_many_arguments)] +fn attach_attrs( + py: Python<'_>, + bound: &Bound<'_, PyAny>, + code: &str, + message: &str, + sql_state: Option<&str>, + error_code: Option<&str>, + vendor_code: Option, + http_status: Option, + retryable: bool, + query_id: Option<&str>, +) -> PyResult<()> { + bound.setattr("code", code)?; + bound.setattr("message", message)?; + bound.setattr("sql_state", sql_state)?; + bound.setattr("error_code", error_code)?; + bound.setattr("vendor_code", vendor_code)?; + bound.setattr("http_status", http_status)?; + bound.setattr("retryable", retryable)?; + bound.setattr("query_id", query_id)?; + let _ = py; // silence unused-var warning if pyo3 ever drops the Python<'_> arg + Ok(()) +} + +/// Convert a kernel `Error` into a `KernelError` Python exception +/// with the structured fields attached as attributes. Python sees +/// `err.code`, `err.message`, `err.sql_state`, etc.; `str(err)` is +/// the kernel's message text. +pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { + let py_err = KernelError::new_err(err.message.clone()); + // Materialise the exception value so we can attach attributes. + let bound = py_err.value(py); + if let Err(setattr_err) = attach_attrs( + py, + bound.as_any(), + code_str(err.code), + &err.message, + err.sql_state.as_deref(), + err.error_code.as_deref(), + err.vendor_code, + err.http_status, + err.retryable, + err.query_id.as_deref(), + ) { + // Attribute attachment is best-effort. If something goes + // wrong (extremely unlikely for plain string/int setattrs), + // surface that error so the caller sees it rather than a + // partially-populated exception. Fold the original kernel + // message into the new error so debugging context isn't + // lost. + return setattr_err; + } + py_err +} + +/// Build a `KernelError` carrying an `InvalidStatementHandle` code +/// for the "this handle is closed" guard. Used by every +/// `alive()` / `alive_mut()` helper across the wrapper. +/// +/// Acquires the GIL internally so callers don't have to thread a +/// `Python<'_>` through their guard helpers. +pub(crate) fn closed_err(handle_name: &str) -> PyErr { + Python::attach(|py| { + let message = format!("{handle_name} is closed"); + let py_err = KernelError::new_err(message.clone()); + let bound = py_err.value(py); + if let Err(setattr_err) = attach_attrs( + py, + bound.as_any(), + "InvalidStatementHandle", + &message, + None, + None, + None, + None, + false, + None, + ) { + return setattr_err; + } + py_err + }) +} diff --git a/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs new file mode 100644 index 00000000..6c4bf93a --- /dev/null +++ b/pyo3/src/executed_async.rs @@ -0,0 +1,167 @@ +// 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. + +//! `ExecutedAsyncStatement` — Python wrapper for the kernel's +//! async-consumption handle. +//! +//! Returned by `Statement.submit()`. The kernel returned without +//! driving polling; the caller owns the cadence via `status()` / +//! `await_result()` / `fetch_result()`. Mirrors the kernel's +//! `executed_async.rs` one-to-one. + +use crate::errors::to_py_err; +use crate::result_stream::ResultStream; +use databricks_sql_kernel::{ + ExecutedAsyncStatement as KExecutedAsyncStatement, ExecutedStatementHandle, StatementStatus, +}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Map a kernel `StatementStatus` to a stable string slug. Matches +/// the connector's `CommandState` taxonomy one-for-one so the Python +/// side can branch on the result without holding a reference to a +/// `StatementStatus` enum. +fn status_str(status: &StatementStatus) -> &'static str { + match status { + StatementStatus::Pending => "Pending", + StatementStatus::Running => "Running", + StatementStatus::Succeeded => "Succeeded", + StatementStatus::Failed(_) => "Failed", + StatementStatus::Cancelled => "Cancelled", + StatementStatus::Closed => "Closed", + // `StatementStatus` is `#[non_exhaustive]`. + _ => "Unknown", + } +} + +#[pyclass(name = "ExecutedAsyncStatement", unsendable)] +pub(crate) struct ExecutedAsyncStatement { + inner: Option, + /// Cached statement id so callers can read it after `close()`. + statement_id: String, +} + +struct ExecutedAsyncInner { + exec: KExecutedAsyncStatement, + runtime: Arc, +} + +impl ExecutedAsyncStatement { + pub(crate) fn new(exec: KExecutedAsyncStatement, runtime: Arc) -> Self { + let statement_id = exec.statement_id().to_owned(); + Self { + statement_id, + inner: Some(ExecutedAsyncInner { exec, runtime }), + } + } +} + +#[pymethods] +impl ExecutedAsyncStatement { + #[getter] + fn statement_id(&self) -> &str { + &self.statement_id + } + + /// Single-shot status check. Returns a tuple + /// `(state: str, failure: Optional[KernelError])` where: + /// + /// - `state` is one of `Pending / Running / Succeeded / Failed / + /// Cancelled / Closed`. + /// - `failure` is `None` unless `state == "Failed"`, in which + /// case it carries a `KernelError` instance exposing the + /// structured fields (`code`, `message`, `sql_state`, + /// `error_code`, `vendor_code`, `http_status`, `retryable`, + /// `query_id`) as plain attributes. + /// + /// Surfacing failure as a value rather than raising lets polling + /// callers branch on terminal vs non-terminal states without a + /// try/except boundary. The connector backend re-raises the + /// failure as the appropriate PEP 249 exception when it actually + /// needs to. + fn status<'py>(&self, py: Python<'py>) -> PyResult> { + let inner = alive!(self, "ExecutedAsyncStatement"); + let runtime = inner.runtime.clone(); + let status = run_kernel!(py, runtime, inner.exec.status())?; + let state = status_str(&status); + let failure: Bound<'py, PyAny> = match &status { + StatementStatus::Failed(err) => { + // Build the KernelError instance the same way every + // other failure path does, then hand it to Python as + // a plain value (not raised). Callers read .code / + // .sql_state / .query_id directly. + let py_err = to_py_err(py, err.clone()); + py_err.value(py).clone().into_any() + } + _ => py.None().into_bound(py), + }; + let tuple = pyo3::types::PyTuple::new(py, [state.into_pyobject(py)?.into_any(), failure])?; + Ok(tuple.into_any()) + } + + /// Block until the statement reaches a terminal state, then + /// return a `ResultStream` over the results. + /// + /// Drives polling on the session runtime; the kernel applies the + /// session-configured `poll_interval` / `poll_timeout` cadence. + /// `Failed` / `Cancelled` raise `KernelError`. + fn await_result(&self, py: Python<'_>) -> PyResult { + let inner = alive!(self, "ExecutedAsyncStatement"); + let runtime = inner.runtime.clone(); + let stream = run_kernel!(py, runtime, inner.exec.await_result())?; + Ok(ResultStream::new(stream, runtime)) + } + + /// Fetch the result without polling. Raises `KernelError(code= + /// 'InvalidState')` if the statement has not reached a terminal + /// state — call after `status()` reports `Succeeded`/`Closed`. + fn fetch_result(&self, py: Python<'_>) -> PyResult { + let inner = alive!(self, "ExecutedAsyncStatement"); + let runtime = inner.runtime.clone(); + let stream = run_kernel!(py, runtime, inner.exec.fetch_result())?; + Ok(ResultStream::new(stream, runtime)) + } + + /// Cancel the in-flight statement on the server. + fn cancel(&self, py: Python<'_>) -> PyResult<()> { + let inner = alive!(self, "ExecutedAsyncStatement"); + let runtime = inner.runtime.clone(); + run_kernel!(py, runtime, inner.exec.cancel())?; + Ok(()) + } + + /// Close the statement (server-side `CloseStatement`). Idempotent. + fn close(&mut self, py: Python<'_>) -> PyResult<()> { + let Some(inner) = self.inner.as_mut() else { + return Ok(()); + }; + let runtime = inner.runtime.clone(); + let res = run_kernel!(py, runtime, inner.exec.close()); + self.inner = None; + res.map(|_| ()) + } + + fn __repr__(&self) -> String { + let state = if self.inner.is_some() { + "open" + } else { + "closed" + }; + format!( + "ExecutedAsyncStatement(statement_id={:?}, state={state})", + self.statement_id + ) + } +} 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 new file mode 100644 index 00000000..da96d941 --- /dev/null +++ b/pyo3/src/lib.rs @@ -0,0 +1,57 @@ +// 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. + +//! Python bindings for the Databricks SQL Kernel. +//! +//! Phase 1 surface today: `Session`, `Statement`, `ExecutedStatement`, +//! `ExecutedAsyncStatement`, `Metadata`, `ResultStream`. Auth is +//! PAT-only — OAuth and other auth types are reserved in the kernel +//! surface but not yet wired here, pending a decision on whether +//! PySQL owns OAuth or the kernel does (see Phase 2 design notes). +//! Both synchronous `execute()` and async `submit()` paths supported. +//! 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. + +// `macros` is `#[macro_use]` so the `run_kernel!` / `alive!` / +// `alive_mut!` macros are visible across the rest of the crate +// without per-file imports. +#[macro_use] +mod macros; + +mod auth; +mod errors; +mod executed_async; +mod fetch; +mod metadata; +mod result_stream; +mod session; +mod statement; + +use pyo3::prelude::*; + +#[pymodule] +fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add("__version__", env!("CARGO_PKG_VERSION"))?; + m.add("KernelError", m.py().get_type::())?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + Ok(()) +} diff --git a/pyo3/src/macros.rs b/pyo3/src/macros.rs new file mode 100644 index 00000000..22ea1df0 --- /dev/null +++ b/pyo3/src/macros.rs @@ -0,0 +1,113 @@ +// 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. + +//! Crate-internal macros that collapse the three patterns every +//! wrapper method repeats: +//! +//! - `py.detach(|| runtime.block_on(future)).map_err(|e| to_py_err(py, e))?` +//! becomes `run_kernel!(py, runtime, future)` (also a `_block` +//! form for closures that need to capture more than the future). +//! - `self.inner.as_ref().ok_or_else(|| closed_err("X"))?` becomes +//! `alive!(self, "X")` (immutable) / `alive_mut!(self, "X")` +//! (mutable). +//! +//! Macros over a helper function so the captured borrow patterns +//! stay flexible at each call site without HRTB gymnastics, and so +//! the macro can expand to a `?`-terminating expression usable +//! anywhere — including inside a `let` binding or as a function +//! tail expression. + +/// Drive a kernel future on the session runtime with the GIL +/// released, mapping kernel `Error`s into `KernelError`s. +/// +/// Expands to an expression of type `T` (the future's `Ok` value) +/// or short-circuits the enclosing function with `?`. +/// +/// ```ignore +/// let session = run_kernel!(py, runtime, KSession::open(config))?; +/// ``` +#[macro_export] +macro_rules! run_kernel { + ($py:expr, $runtime:expr, $future:expr) => {{ + let py = $py; + py.detach(|| $runtime.block_on($future)) + .map_err(|e| $crate::errors::to_py_err(py, e)) + }}; +} + +/// Variant that accepts a block expression — useful when the future +/// is constructed inline from borrowed state that can't escape the +/// `detach` closure cleanly with the simpler form. Same shape, same +/// error mapping. +/// +/// ```ignore +/// let stream = run_kernel_block!(py, runtime, { +/// let stream = inner.exec.result_stream_mut(); +/// stream.next_batch() +/// })?; +/// ``` +#[macro_export] +macro_rules! run_kernel_block { + ($py:expr, $runtime:expr, $body:block) => {{ + let py = $py; + py.detach(|| $runtime.block_on(async $body)) + .map_err(|e| $crate::errors::to_py_err(py, e)) + }}; +} + +/// Run a synchronous helper (e.g. `fetch::next_batch` / `fetch::drain`, +/// which `block_on` internally) with the GIL released, mapping kernel +/// errors into `KernelError`. +/// +/// Same `py.detach` + `to_py_err` shape as `run_kernel!`, but skips +/// the `block_on` wrapper since the callee already owns it. +/// +/// ```ignore +/// let batch = run_sync_kernel!(py, fetch::next_batch(&runtime, stream))?; +/// ``` +#[macro_export] +macro_rules! run_sync_kernel { + ($py:expr, $call:expr) => {{ + let py = $py; + py.detach(|| $call) + .map_err(|e| $crate::errors::to_py_err(py, e)) + }}; +} + +/// Borrow `self.inner` immutably or short-circuit with a +/// `KernelError(" is closed", code=InvalidStatementHandle)`. +/// +/// ```ignore +/// let inner = alive!(self, "Session"); +/// ``` +#[macro_export] +macro_rules! alive { + ($self:expr, $name:literal) => { + $self + .inner + .as_ref() + .ok_or_else(|| $crate::errors::closed_err($name))? + }; +} + +/// Mutable counterpart to `alive!`. Same semantics, `&mut`. +#[macro_export] +macro_rules! alive_mut { + ($self:expr, $name:literal) => { + $self + .inner + .as_mut() + .ok_or_else(|| $crate::errors::closed_err($name))? + }; +} diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs new file mode 100644 index 00000000..9f55485e --- /dev/null +++ b/pyo3/src/metadata.rs @@ -0,0 +1,244 @@ +// 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', ...)`. +//! +//! ## Why the methods aren't fully macro-ised +//! +//! The 10 metadata methods share an outer shape (release GIL, run +//! future on session runtime, wrap result in `ResultStream`), which +//! `run_kernel_block!` collapses. They differ in: +//! +//! - which positional args are required vs optional, +//! - which args are exact identifiers vs LIKE patterns, +//! - the `list_tables` extra `table_types: Option>`. +//! +//! A declarative macro that covered all the variations would need +//! its own DSL and would be harder to read than the explicit forms. +//! The outer-scaffolding macro is where the win lives; the inner +//! conversions stay explicit and grep-able. + +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 = run_kernel_block!(py, self.runtime, { self.inner.list_catalogs().await })?; + 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 = run_kernel_block!(py, self.runtime, { + let cat = opt_identifier(&catalog)?; + let pat = opt_pattern(&schema_pattern)?; + self.inner.list_schemas(cat, pat).await + })?; + 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 = run_kernel_block!(py, self.runtime, { + 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.inner.list_tables(cat, sch, tbl, types_slice).await + })?; + 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 = run_kernel_block!(py, self.runtime, { + 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.inner.list_columns(cat, sch, tbl, col).await + })?; + 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 = run_kernel_block!(py, self.runtime, { + let cat = Some(Identifier::new(&catalog)?); + let sch = Some(Identifier::new(&schema)?); + let tbl = Identifier::new(&table)?; + self.inner.primary_keys(cat, sch, tbl).await + })?; + 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 = run_kernel_block!(py, self.runtime, { + 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.inner.foreign_keys(pc, ps, pt, fc, fs, ft).await + })?; + 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 = run_kernel_block!(py, self.runtime, { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&name_pattern)?; + self.inner.functions(cat, sch, nam).await + })?; + 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 = run_kernel_block!(py, self.runtime, { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&name_pattern)?; + self.inner.procedures(cat, sch, nam).await + })?; + 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 = run_kernel_block!(py, self.runtime, { self.inner.type_info().await })?; + Ok(ResultStream::new(stream, self.runtime.clone())) + } + + /// All table types. No wire call. + fn table_types(&self, py: Python<'_>) -> PyResult { + let stream = run_kernel_block!(py, self.runtime, { self.inner.table_types().await })?; + 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..2923b2e1 --- /dev/null +++ b/pyo3/src/result_stream.rs @@ -0,0 +1,122 @@ +// 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::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, + }), + } + } +} + +#[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 = alive_mut!(self, "ResultStream"); + if inner.exhausted { + return Ok(None); + } + let runtime = inner.runtime.clone(); + let batch = run_sync_kernel!(py, fetch::next_batch(&runtime, &mut inner.stream))?; + 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 = alive_mut!(self, "ResultStream"); + let runtime = inner.runtime.clone(); + let batches = run_sync_kernel!(py, fetch::drain(&runtime, &mut inner.stream))?; + 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 new file mode 100644 index 00000000..6206e7c2 --- /dev/null +++ b/pyo3/src/session.rs @@ -0,0 +1,192 @@ +// 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. + +//! `Session` — Python class wrapping the kernel's `Session`. +//! +//! Owns a multi-thread tokio runtime per session (one tokio worker +//! pool drives all I/O for this session). The runtime handle is +//! cloned into child `Statement` / `ExecutedStatement` objects so +//! they `block_on` the same pool without keeping the `Session` +//! pyclass alive longer than the user keeps a reference. + +use crate::auth::build_auth_config; +use crate::metadata::Metadata; +use crate::statement::Statement; +use databricks_sql_kernel::Session as KSession; +use pyo3::prelude::*; +use std::collections::HashMap; +use std::sync::Arc; +use tokio::runtime::{Builder, Runtime}; + +/// Python-facing session handle. +/// +/// `unsendable` — the kernel `Session` is `Send + Sync` (asserted in +/// the kernel's `lib.rs`), but the tokio `Runtime` is `!Send` once it +/// has been driven. Marking the pyclass unsendable keeps Python from +/// trying to migrate it across threads. +#[pyclass(name = "Session", unsendable)] +pub(crate) struct Session { + /// `None` after `close()`. Methods return a clean Python error + /// rather than panicking on a closed session. + inner: Option, +} + +pub(crate) struct SessionInner { + pub(crate) session: KSession, + pub(crate) runtime: Arc, +} + +#[pymethods] +impl Session { + /// Open a new session against the given workspace. + /// + /// `host` may be bare (`my-workspace.databricks.com`) or + /// fully-qualified (`https://...`). `http_path` is the SQL + /// endpoint path. + /// + /// Auth: PAT only in this phase. Pass `access_token=` + /// (or the explicit form `auth_type='pat', access_token=...`). + /// OAuth and other auth types are reserved and will be wired + /// in once the credential-ownership question (kernel-owned vs + /// connector-owned OAuth) is settled. + /// + /// `session_conf` is the server-bound session configuration map + /// — passed through to SEA `session_confs` verbatim. Use for + /// `ANSI_MODE`, `TIMEZONE`, `STATEMENT_TIMEOUT`, query-tag + /// presets, etc. The kernel does not validate keys; the server + /// rejects unknown ones with a `KernelError(code='SqlError')` + /// when it picks them up. + #[new] + #[pyo3(signature = ( + host, + http_path, + *, + auth_type=None, + access_token=None, + catalog=None, + schema=None, + session_conf=None, + ))] + #[allow(clippy::too_many_arguments)] + fn new( + py: Python<'_>, + host: String, + http_path: String, + auth_type: Option, + access_token: Option, + catalog: Option, + schema: Option, + session_conf: Option>, + ) -> PyResult { + // Resolve auth_type: default to "pat" only when the caller + // also passed access_token. This keeps existing PAT callers + // working without changes while still rejecting ambiguous + // calls like `Session(host, http_path)` with no auth. + let resolved_auth_type = match auth_type.as_deref() { + Some(t) => t.to_owned(), + None if access_token.is_some() => "pat".to_owned(), + None => { + return Err(pyo3::exceptions::PyValueError::new_err( + "Session requires auth: pass access_token (PAT) — \ + other auth types are not yet supported by this binding", + )); + } + }; + let auth_config = build_auth_config(&resolved_auth_type, access_token)?; + + // One tokio runtime per session. Multi-thread so CloudFetch + // chunk downloads can overlap with the main poll loop. Worker + // count left to tokio's default (logical CPU count). + let runtime = Arc::new( + Builder::new_multi_thread() + .enable_all() + .thread_name("dbx-sql-kernel") + .build() + .map_err(|e| { + pyo3::exceptions::PyRuntimeError::new_err(format!( + "failed to build tokio runtime: {e}" + )) + })?, + ); + + // `Session::open` is async and grabs the current tokio handle. + // Drive it on the runtime; the macro detaches the GIL for the + // I/O and maps kernel errors into `KernelError`. + let rt = runtime.clone(); + let session = run_kernel!(py, rt, async { + let mut builder = KSession::builder() + .http_path(host, http_path) + .auth(auth_config); + if catalog.is_some() || schema.is_some() { + let mut defaults = databricks_sql_kernel::DefaultOpts::default(); + defaults.catalog = catalog; + defaults.schema = schema; + builder = builder.defaults(defaults); + } + if let Some(conf) = session_conf { + builder = builder.session_conf(conf); + } + builder.open().await + })?; + + Ok(Self { + inner: Some(SessionInner { session, runtime }), + }) + } + + /// Server-issued session id. + #[getter] + fn session_id(&self) -> PyResult { + let inner = alive!(self, "Session"); + Ok(inner.session.session_id().to_owned()) + } + + /// Build a new `Statement` bound to this session. + fn statement(&self) -> PyResult { + let inner = alive!(self, "Session"); + let kstmt = inner.session.statement(); + 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 = alive!(self, "Session"); + 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<()> { + let Some(inner) = self.inner.take() else { + return Ok(()); + }; + let SessionInner { session, runtime } = inner; + let rt = runtime; + run_kernel!(py, rt, session.close())?; + Ok(()) + } + + fn __repr__(&self) -> String { + match &self.inner { + Some(i) => format!( + "Session(session_id={:?}, closed=False)", + i.session.session_id() + ), + None => "Session(closed=True)".to_owned(), + } + } +} diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs new file mode 100644 index 00000000..f03de90a --- /dev/null +++ b/pyo3/src/statement.rs @@ -0,0 +1,231 @@ +// 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. + +//! `Statement` + `ExecutedStatement` Python classes. +//! +//! Mirrors the kernel's `Statement::execute() -> ExecutedStatement` +//! flow (sync) and `Statement::submit() -> ExecutedAsyncStatement` +//! (async-consumption). The fetch surface on `ExecutedStatement` +//! returns Arrow record batches as pyarrow values. + +use crate::executed_async::ExecutedAsyncStatement; +use crate::fetch; +use arrow_pyarrow::ToPyArrow; +use arrow_schema::Schema; +use databricks_sql_kernel::{ + ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, Statement as KStatement, +}; +use pyo3::prelude::*; +use std::sync::Arc; +use tokio::runtime::Runtime; + +/// Python-facing mutable statement. +/// +/// Spec mutation is collapsed into simple `set_*` / `bind_*` methods +/// for now. The full `Statement::spec()` API surface lands in later +/// phases (named params, statement_conf, result_format). +#[pyclass(name = "Statement", unsendable)] +pub(crate) struct Statement { + inner: Option, +} + +struct StatementInner { + stmt: KStatement, + runtime: Arc, +} + +impl Statement { + pub(crate) fn new(stmt: KStatement, runtime: Arc) -> Self { + Self { + inner: Some(StatementInner { stmt, runtime }), + } + } +} + +#[pymethods] +impl Statement { + /// Set the SQL text to execute. Replaces any previously-set SQL. + fn set_sql(&mut self, sql: String) -> PyResult<()> { + let inner = alive_mut!(self, "Statement"); + inner.stmt.spec().sql(sql); + Ok(()) + } + + /// Wait-for-result execution. Blocks until the kernel finishes + /// polling and returns an `ExecutedStatement` with the result + /// stream ready to drain. + fn execute(&mut self, py: Python<'_>) -> PyResult { + let inner = alive_mut!(self, "Statement"); + let runtime = inner.runtime.clone(); + let exec = run_kernel!(py, runtime, inner.stmt.execute())?; + Ok(ExecutedStatement::new(exec, runtime)) + } + + /// Submit-and-return. Sends `ExecuteStatement` with + /// `wait_timeout=0s` so the server returns immediately with a + /// `statement_id`; the kernel does not poll. Returns an + /// `ExecutedAsyncStatement` the caller drives via `status()` / + /// `await_result()` / `fetch_result()`. + /// + /// Long-running queries that would blow past `execute()`'s sync + /// polling budget belong on this path. + fn submit(&mut self, py: Python<'_>) -> PyResult { + let inner = alive_mut!(self, "Statement"); + let runtime = inner.runtime.clone(); + let exec = run_kernel!(py, runtime, inner.stmt.submit())?; + Ok(ExecutedAsyncStatement::new(exec, runtime)) + } + + /// Explicit close — cancels and closes any executed handle this + /// `Statement` is still tracking, then drops the lifecycle + /// owner. + /// + /// Matches the surface JDBC / ODBC / PySQL users expect: + /// closing the lifecycle owner releases the associated + /// server-side statement too. Any `ExecutedStatement` / + /// `ExecutedAsyncStatement` the caller still holds becomes + /// invalid; its next call short-circuits locally to + /// `KernelError(code='InvalidStatementHandle')` without a + /// network round-trip. + /// + /// Idempotent — a second `close()` call is a no-op. + fn close(&mut self, py: Python<'_>) -> PyResult<()> { + let Some(inner) = self.inner.take() else { + return Ok(()); + }; + let StatementInner { stmt, runtime } = inner; + // Kernel `Statement::close` is async (it awaits + // CancelStatement + CloseStatement against the tracked + // executed handle), so we route it through the standard + // py.detach + block_on path. + run_kernel!(py, runtime, stmt.close())?; + Ok(()) + } +} + +/// Python-facing executed statement handle. Owns the kernel +/// `ExecutedStatement` and serves the result stream lazily. +#[pyclass(name = "ExecutedStatement", unsendable)] +pub(crate) struct ExecutedStatement { + inner: Option, + /// Cached statement id so callers can read it after `close()` + /// (e.g. for logging the id of a just-closed statement). + statement_id: String, + /// Cached schema. Pulled from the kernel once on construction — + /// available even after `close()` so descriptions stay stable. + schema: Arc, +} + +struct ExecutedInner { + exec: KExecutedStatement, + runtime: Arc, + exhausted: bool, +} + +impl ExecutedStatement { + fn new(exec: KExecutedStatement, runtime: Arc) -> Self { + let statement_id = exec.statement_id().to_owned(); + let schema = exec.schema(); + Self { + statement_id, + schema, + inner: Some(ExecutedInner { + exec, + runtime, + exhausted: false, + }), + } + } +} + +#[pymethods] +impl ExecutedStatement { + #[getter] + fn statement_id(&self) -> &str { + &self.statement_id + } + + /// 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` if + /// the stream is exhausted. + fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { + let inner = alive_mut!(self, "ExecutedStatement"); + if inner.exhausted { + return Ok(None); + } + let runtime = inner.runtime.clone(); + let batch = run_sync_kernel!( + py, + fetch::next_batch(&runtime, inner.exec.result_stream_mut()) + )?; + 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 = alive_mut!(self, "ExecutedStatement"); + let runtime = inner.runtime.clone(); + let batches = run_sync_kernel!(py, fetch::drain(&runtime, inner.exec.result_stream_mut()))?; + inner.exhausted = true; + fetch::batches_to_pyarrow_table(py, &self.schema, batches) + } + + /// Cancel the in-flight statement on the server. Local validity + /// flag short-circuits if the parent `Statement` was re-executed + /// or dropped. + fn cancel(&mut self, py: Python<'_>) -> PyResult<()> { + let inner = alive_mut!(self, "ExecutedStatement"); + let runtime = inner.runtime.clone(); + run_kernel!(py, runtime, inner.exec.cancel())?; + Ok(()) + } + + /// Close the statement (server-side `CloseStatement`). Idempotent. + /// Subsequent calls on this handle raise `KernelError`. + fn close(&mut self, py: Python<'_>) -> PyResult<()> { + let Some(inner) = self.inner.as_mut() else { + return Ok(()); + }; + let runtime = inner.runtime.clone(); + let res = run_kernel!(py, runtime, inner.exec.close()); + // Drop the kernel handle regardless of close() outcome — the + // kernel's Drop impl runs fire-and-forget cleanup if close() + // failed mid-flight. + self.inner = None; + res.map(|_| ()) + } + + fn __repr__(&self) -> String { + let state = if self.inner.is_some() { + "open" + } else { + "closed" + }; + format!( + "ExecutedStatement(statement_id={:?}, state={state})", + self.statement_id + ) + } +} diff --git a/pyo3/tests/conftest.py b/pyo3/tests/conftest.py new file mode 100644 index 00000000..d59d5743 --- /dev/null +++ b/pyo3/tests/conftest.py @@ -0,0 +1,76 @@ +# 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. + +"""Shared pytest fixtures + env-var gating for the PyO3 live tests. + +Run with creds sourced: + + cd pyo3 + .venv/bin/maturin develop --release + set -a && source ~/.databricks/pecotesting-creds && set +a + .venv/bin/pytest -v + +Tests that need a live warehouse are auto-skipped when the env vars +aren't set, so `pytest` works in CI / offline too — only the +no-network tests run. +""" + +from __future__ import annotations + +import os + +import pytest + +import databricks_sql_kernel as k + + +HOST = os.environ.get("DATABRICKS_HOST", "") +HTTP_PATH = os.environ.get("DATABRICKS_HTTP_PATH", "") +TOKEN = os.environ.get("DATABRICKS_TOKEN", "") + +live = pytest.mark.skipif( + not (HOST and HTTP_PATH and TOKEN), + reason="DATABRICKS_HOST / DATABRICKS_HTTP_PATH / DATABRICKS_TOKEN not set", +) + + +@pytest.fixture(scope="module") +def session(): + """Open one session per test module. Closed at module teardown. + + Module-scoped because every session round-trip creates a SEA + session on the warehouse; sharing across tests cuts E2E time by + a factor that matters for human-driven runs. + """ + if not (HOST and HTTP_PATH and TOKEN): + pytest.skip("creds not set") + s = k.Session(host=HOST, http_path=HTTP_PATH, access_token=TOKEN) + yield s + s.close() + + +@pytest.fixture +def fresh_session(): + """One-shot session for tests that need clean state (e.g. + use-after-close tests where the module-scoped fixture would + poison every later test).""" + if not (HOST and HTTP_PATH and TOKEN): + pytest.skip("creds not set") + s = k.Session(host=HOST, http_path=HTTP_PATH, access_token=TOKEN) + yield s + try: + s.close() + except k.KernelError: + # Test may have closed it already; idempotent close is fine. + pass diff --git a/pyo3/tests/test_async.py b/pyo3/tests/test_async.py new file mode 100644 index 00000000..e793e0de --- /dev/null +++ b/pyo3/tests/test_async.py @@ -0,0 +1,116 @@ +# 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. + +"""Async statement: submit / status / await_result / fetch_result / +Failed status.""" + +from __future__ import annotations + +import time + +import databricks_sql_kernel as k + +from conftest import live + + +def _wait_terminal(async_exec, timeout_s: float = 2.0): + """Poll status() until terminal or timeout. Returns the final + (state, failure) tuple.""" + deadline = time.monotonic() + timeout_s + while True: + state, failure = async_exec.status() + if state in ("Succeeded", "Closed", "Failed", "Cancelled"): + return state, failure + if time.monotonic() > deadline: + return state, failure + time.sleep(0.1) + + +@live +def test_submit_and_await_result(session): + stmt = session.statement() + stmt.set_sql("SELECT 7 AS n") + async_exec = stmt.submit() + try: + assert async_exec.statement_id + state, failure = async_exec.status() + assert state in ("Pending", "Running", "Succeeded", "Closed"), state + assert failure is None + rs = async_exec.await_result() + try: + table = rs.fetch_all_arrow() + assert table.num_rows == 1 + assert table.column(0).to_pylist() == [7] + finally: + rs.close() + # After await_result, status must be terminal. + state, _ = async_exec.status() + assert state in ("Succeeded", "Closed"), state + finally: + async_exec.close() + stmt.close() + + +@live +def test_submit_then_fetch_result_after_terminal(session): + stmt = session.statement() + stmt.set_sql("SELECT 99 AS n") + async_exec = stmt.submit() + try: + state, _ = _wait_terminal(async_exec) + assert state in ("Succeeded", "Closed"), state + rs = async_exec.fetch_result() + try: + table = rs.fetch_all_arrow() + assert table.num_rows == 1 + assert table.column(0).to_pylist() == [99] + finally: + rs.close() + finally: + async_exec.close() + stmt.close() + + +@live +def test_submit_failed_status_carries_kernel_error(session): + stmt = session.statement() + stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_async_test") + async_exec = stmt.submit() + try: + state, failure = _wait_terminal(async_exec) + assert state == "Failed", state + assert isinstance(failure, k.KernelError), type(failure) + assert failure.code == "SqlError", failure.code + assert failure.sql_state == "42P01", failure.sql_state + assert failure.query_id, "query_id should be populated" + finally: + async_exec.close() + stmt.close() + + +@live +def test_use_after_close_raises_kernel_error(session): + stmt = session.statement() + stmt.set_sql("SELECT 1") + async_exec = stmt.submit() + async_exec.close() + async_exec.close() # idempotent + try: + async_exec.status() + except k.KernelError as e: + assert "closed" in str(e), str(e) + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError("expected KernelError on use-after-close") + stmt.close() diff --git a/pyo3/tests/test_auth.py b/pyo3/tests/test_auth.py new file mode 100644 index 00000000..3e2cee99 --- /dev/null +++ b/pyo3/tests/test_auth.py @@ -0,0 +1,61 @@ +# 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. + +"""Auth surface: input validation. + +PAT-only this phase; tests confirm the wrapper rejects unsupported +kwargs at construction time (before any network) rather than +letting the kernel error mid-flight. +""" + +from __future__ import annotations + +import pytest + +import databricks_sql_kernel as k + + +def test_missing_auth_raises_value_error(): + with pytest.raises(ValueError, match="access_token"): + k.Session(host="x.databricks.com", http_path="/sql/1.0/warehouses/abc") + + +def test_pat_with_empty_token_raises_value_error(): + with pytest.raises(ValueError, match="access_token"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_type="pat", + access_token="", + ) + + +def test_unsupported_auth_type_raises_value_error(): + with pytest.raises(ValueError, match="unsupported"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_type="external", + access_token="x", + ) + + +def test_unknown_auth_type_raises_value_error(): + with pytest.raises(ValueError, match="unsupported"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_type="something-else", + access_token="x", + ) diff --git a/pyo3/tests/test_execute.py b/pyo3/tests/test_execute.py new file mode 100644 index 00000000..4958d6d7 --- /dev/null +++ b/pyo3/tests/test_execute.py @@ -0,0 +1,142 @@ +# 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. + +"""Sync execute: SELECT 1, drain ranges, idempotent close, bad SQL.""" + +from __future__ import annotations + +import pyarrow as pa + +import databricks_sql_kernel as k + +from conftest import live + + +@live +def test_select_one_via_fetch_next_batch(session): + stmt = session.statement() + stmt.set_sql("SELECT 1 AS n") + exec_ = stmt.execute() + try: + assert exec_.statement_id + schema = exec_.arrow_schema() + assert isinstance(schema, pa.Schema) + batch = exec_.fetch_next_batch() + assert isinstance(batch, pa.RecordBatch) + assert batch.num_rows == 1 + assert batch.column(0).to_pylist() == [1] + # Second fetch is None — stream exhausted. + assert exec_.fetch_next_batch() is None + finally: + exec_.close() + stmt.close() + + +@live +def test_range_drains_to_pyarrow_table(session): + stmt = session.statement() + stmt.set_sql("SELECT * FROM range(10000)") + exec_ = stmt.execute() + try: + table = exec_.fetch_all_arrow() + assert isinstance(table, pa.Table) + assert table.num_rows == 10000 + finally: + exec_.close() + stmt.close() + + +@live +def test_executed_statement_double_close_is_idempotent(session): + stmt = session.statement() + stmt.set_sql("SELECT 42") + exec_ = stmt.execute() + exec_.close() + exec_.close() # idempotent + stmt.close() + + +@live +def test_use_after_close_raises_kernel_error(session): + stmt = session.statement() + stmt.set_sql("SELECT 42") + exec_ = stmt.execute() + exec_.close() + try: + exec_.fetch_next_batch() + except k.KernelError as e: + assert "closed" in str(e), str(e) + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError("expected KernelError on use-after-close") + stmt.close() + + +@live +def test_statement_close_invalidates_held_executed_statement(session): + """`Statement.close()` is the user-facing "release everything" + operation. After calling it, the kernel sends `CloseStatement` + against the held executed handle and flips its local validity + flag; subsequent **wire-touching** calls on the handle (cancel) + short-circuit to `KernelError(code='InvalidStatementHandle')`. + + Note: already-buffered Arrow batches still drain locally — + `fetch_next_batch` doesn't go through the validity flag because + it operates on in-memory data the kernel already pulled. That + matches JDBC semantics: rows already in the client buffer + aren't unfetched by `close()`. The server-side state is what + actually gets released.""" + stmt = session.statement() + stmt.set_sql("SELECT 1 AS n") + exec_ = stmt.execute() + # Close the parent Statement while the user still holds exec_. + stmt.close() + # Cancel/close routes through `valid.check()` and now errors. + try: + exec_.cancel() + except k.KernelError as e: + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError( + "expected KernelError(InvalidStatementHandle) on cancel after Statement.close" + ) + + +@live +def test_statement_close_is_idempotent(session): + """A second `Statement.close()` is a no-op (does not error).""" + stmt = session.statement() + stmt.set_sql("SELECT 1") + stmt.execute().close() # close the executed handle ourselves + stmt.close() + stmt.close() # idempotent + + +@live +def test_bad_sql_surfaces_structured_kernel_error(session): + stmt = session.statement() + stmt.set_sql("SELECT * FROM definitely_not_a_table_xyz_kernel_test") + try: + stmt.execute() + except k.KernelError as e: + assert e.code == "SqlError", f"got {e.code!r}" + assert e.sql_state == "42P01", f"got {e.sql_state!r}" + # query_id is server-issued and may or may not be populated + # depending on when the failure surfaced; assert only that + # the attribute exists. + assert hasattr(e, "query_id") + else: + raise AssertionError("expected KernelError on bad SQL") + finally: + stmt.close() diff --git a/pyo3/tests/test_metadata.py b/pyo3/tests/test_metadata.py new file mode 100644 index 00000000..deaa00ce --- /dev/null +++ b/pyo3/tests/test_metadata.py @@ -0,0 +1,130 @@ +# 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 surface: list_*, type_info, table_types, validation, +ResultStream lifecycle.""" + +from __future__ import annotations + +import pyarrow as pa +import pytest + +import databricks_sql_kernel as k + +from conftest import live + + +@live +def test_list_catalogs_returns_non_empty(session): + rs = session.metadata().list_catalogs() + try: + assert isinstance(rs.arrow_schema(), pa.Schema) + table = rs.fetch_all_arrow() + assert isinstance(table, pa.Table) + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_list_schemas_in_main_catalog(session): + rs = session.metadata().list_schemas(catalog="main") + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_list_tables_in_information_schema(session): + rs = session.metadata().list_tables( + catalog="system", schema_pattern="information_schema" + ) + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + # Server-shape sanity: the columns should match the kernel's + # documented `SHOW TABLES` server-shape. + col_names = [f.name for f in table.schema] + for required in ("tableName", "tableType"): + assert required in col_names, f"missing column {required!r}: {col_names}" + finally: + rs.close() + + +@live +def test_list_columns_in_tables(session): + rs = session.metadata().list_columns( + catalog="system", + schema_pattern="information_schema", + table_pattern="tables", + ) + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_type_info_is_static(session): + rs = session.metadata().type_info() + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_table_types_is_static(session): + rs = session.metadata().table_types() + try: + table = rs.fetch_all_arrow() + assert table.num_rows > 0 + finally: + rs.close() + + +@live +def test_empty_identifier_rejected(session): + try: + session.metadata().list_schemas(catalog="") + except k.KernelError as e: + assert e.code == "InvalidArgument", e.code + assert "identifier" in e.message.lower(), e.message + else: + raise AssertionError("expected KernelError for empty catalog") + + +@live +def test_list_columns_requires_catalog_kwarg(session): + # `catalog` is a kwarg-only required parameter (no default). + with pytest.raises(TypeError): + session.metadata().list_columns(schema_pattern="x") # type: ignore[call-arg] + + +@live +def test_result_stream_idempotent_close(session): + rs = session.metadata().list_catalogs() + rs.close() + rs.close() # idempotent + try: + rs.fetch_next_batch() + except k.KernelError as e: + assert "closed" in str(e), str(e) + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError("expected KernelError on use-after-close ResultStream") diff --git a/pyo3/tests/test_module.py b/pyo3/tests/test_module.py new file mode 100644 index 00000000..93f79a55 --- /dev/null +++ b/pyo3/tests/test_module.py @@ -0,0 +1,38 @@ +# 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. + +"""Module-level sanity: import, version, exported classes.""" + +from __future__ import annotations + +import databricks_sql_kernel as k + + +def test_version_string(): + assert isinstance(k.__version__, str) + assert k.__version__ + + +def test_exports_expected_classes(): + expected = { + "Session", + "Statement", + "ExecutedStatement", + "ExecutedAsyncStatement", + "Metadata", + "ResultStream", + "KernelError", + } + actual = {n for n in dir(k) if not n.startswith("_")} + assert expected.issubset(actual), f"missing exports: {expected - actual}" diff --git a/pyo3/tests/test_session.py b/pyo3/tests/test_session.py new file mode 100644 index 00000000..4d27fdee --- /dev/null +++ b/pyo3/tests/test_session.py @@ -0,0 +1,94 @@ +# 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. + +"""Session lifecycle: open, session_id, repr, idempotent close, +use-after-close.""" + +from __future__ import annotations + +import databricks_sql_kernel as k + +from conftest import live + + +@live +def test_session_id_non_empty(session): + assert session.session_id, f"session_id should be populated: {session.session_id!r}" + + +@live +def test_session_repr_open(session): + text = repr(session) + assert "Session" in text + assert "closed=False" in text + assert session.session_id in text + + +@live +def test_double_close_is_idempotent(fresh_session): + fresh_session.close() + # Second call must not raise. + fresh_session.close() + + +@live +def test_use_after_close_raises_kernel_error(fresh_session): + fresh_session.close() + try: + fresh_session.statement() + except k.KernelError as e: + assert "closed" in str(e), str(e) + assert e.code == "InvalidStatementHandle", e.code + else: + raise AssertionError("expected KernelError on use-after-close") + + +@live +def test_session_conf_round_trips(): + """`session_conf` is passed through to SEA `session_configuration` + verbatim. Setting `ANSI_MODE=false` proves the map reached the + server and was honoured — `SET ANSI_MODE` reflects it back. + `ANSI_MODE` was chosen because it's on the allow-list this + warehouse accepts and round-trips cleanly (`TIMEZONE` is + rejected with "Unsupported configuration" on dogfood; + `USE_CACHED_RESULT` / `STATEMENT_TIMEOUT` are + workspace-policy-clamped). + """ + # Pull from the same module-level constants conftest defines so + # offline pytest runs short-circuit via @live before this body + # ever evaluates — no `os.environ[...]` KeyError hazard. + from conftest import HOST, HTTP_PATH, TOKEN + + s = k.Session( + host=HOST, + http_path=HTTP_PATH, + access_token=TOKEN, + session_conf={"ANSI_MODE": "false"}, + ) + try: + stmt = s.statement() + stmt.set_sql("SET ANSI_MODE") + exec_ = stmt.execute() + try: + table = exec_.fetch_all_arrow() + # Server returns rows like (key='ANSI_MODE', value='false'). + row = {f.name: table.column(i).to_pylist()[0] for i, f in enumerate(table.schema)} + assert row.get("value") == "false", ( + f"server did not honour ANSI_MODE=false; got row {row!r}" + ) + finally: + exec_.close() + stmt.close() + finally: + s.close() diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 68c18616..0bdd3107 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -189,6 +189,38 @@ impl Statement { )) } + /// Explicit close. Cancels and closes any executed handle this + /// `Statement` is still tracking, then drops the lifecycle + /// owner. Mirrors what users of JDBC `Statement.close()` / + /// ODBC `SQLFreeStmt(SQL_CLOSE)` / PySQL `cursor.close()` + /// already expect: closing the lifecycle owner releases the + /// associated server-side resources too. + /// + /// Implementation: just re-uses [`invalidate_prior`] which is + /// already what `execute()` / `submit()` call before re-use, + /// so the wire shape (CancelStatement + CloseStatement against + /// the tracked `last_statement_id`, validity flag flipped) is + /// identical to the auto-cancel-on-reuse path. Errors are + /// swallowed as `warn!` for the same reason as that path — + /// transient failures on a now-orphaned statement should not + /// surface as user-visible errors; the server reclaims on + /// session close anyway. + /// + /// After `close()`, any `ExecutedStatement` / + /// `ExecutedAsyncStatement` the caller still holds + /// short-circuits to `InvalidStatementHandle` locally on its + /// next call — no wire round-trip. + /// + /// Symmetric with [`Session::close`]: consumes `self` so a + /// double-close is a compile error. `Drop` runs as a fallback + /// for callers that forget to call `close()` explicitly, but + /// the explicit path is the supported one. + pub async fn close(mut self) -> Result<()> { + let _g = self.session.log_span().clone().entered(); + self.invalidate_prior().await; + Ok(()) + } + /// Shared spec-validation + `ExecuteParams` builder used by both /// [`execute`](Self::execute) and [`submit`](Self::submit). /// diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 0a452515..39de5ec2 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -443,6 +443,44 @@ async fn executed_close_is_idempotent() { exec.close().await.expect("second close — idempotent"); } +#[tokio::test] +async fn statement_close_cancels_and_closes_outstanding_executed_handle() { + // `Statement::close()` must cancel + close any executed handle + // the Statement is still tracking, so a JDBC / ODBC / PySQL- + // style "I'm done with this whole thing" call actually + // releases the server-side statement. Same wire shape as the + // auto-invalidate-on-reuse path that `execute()` / `submit()` + // run before re-issuing. + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-Z/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + let batch = int64_batch("n", vec![1]); + mount_execute(&server, succeeded_inline_body("stmt-Z", &batch)).await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + let exec = stmt.execute().await.expect("execute"); + assert_eq!(exec.statement_id(), "stmt-Z"); + + // Close the parent Statement (not the executed handle). The + // executed handle the caller still holds becomes invalid; its + // next call short-circuits locally via the validity flag. + stmt.close().await.expect("Statement::close"); + + let err = exec + .cancel() + .await + .expect_err("stale handle cancel after Statement::close must fail"); + assert_eq!(err.code, ErrorCode::InvalidStatementHandle); +} + #[tokio::test] async fn row_accessors_walk_succeeded_result() { let server = MockServer::start().await;