Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 212 additions & 0 deletions pyo3/smoke.py
Original file line number Diff line number Diff line change
@@ -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)
84 changes: 84 additions & 0 deletions pyo3/src/fetch.rs
Original file line number Diff line number Diff line change
@@ -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<Option<RecordBatch>> {
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<Vec<RecordBatch>> {
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<Schema>,
batches: Vec<RecordBatch>,
) -> PyResult<Bound<'py, PyAny>> {
let py_batches: Vec<Bound<'py, PyAny>> = batches
.into_iter()
.map(|b| b.to_pyarrow(py))
.collect::<PyResult<_>>()?;
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))
}
13 changes: 9 additions & 4 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -35,5 +38,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<session::Session>()?;
m.add_class::<statement::Statement>()?;
m.add_class::<statement::ExecutedStatement>()?;
m.add_class::<metadata::Metadata>()?;
m.add_class::<result_stream::ResultStream>()?;
Ok(())
}
Loading