Skip to content
7 changes: 7 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ changes go in the root `NEXT_CHANGELOG.md`.
## [Unreleased]

### Added
- `ExecutedStatement.fetch_all_rows(max_rows, nan_ok=False)` (and the same
on `ResultStream`) returns all remaining rows as tuples of Python values,
equal to what pyarrow's `to_pylist()` returns, when there are at most
`max_rows` of them and every column type is supported; otherwise it
returns `None` and the Arrow fetches return the batches it read.
`schema_key()` returns a `SchemaKey` that compares equal for equal result
schemas. Together they let callers handle small results without pyarrow.

### Changed

Expand Down
71 changes: 43 additions & 28 deletions pyo3/src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use arrow_pyarrow::ToPyArrow;
use arrow_schema::Schema;
use databricks_sql_kernel::{Error, ExecutedStatement, Result, ResultBatch, ResultStream};
use pyo3::prelude::*;
use std::collections::VecDeque;
use std::sync::Arc;
use tokio::runtime::Runtime;

Expand All @@ -47,24 +48,6 @@ pub(crate) fn next_batch(
})
}

/// 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)
})
}

/// Like [`next_batch`], but drives the `ExecutedStatement` (not a bare
/// `ResultStream`) so the kernel's auto-close-on-drain fires when the
/// stream is exhausted. Used by `ExecutedStatement.fetch_next_batch`.
Expand All @@ -82,26 +65,58 @@ pub(crate) fn next_batch_exec(
})
}

/// Like [`drain`], but drives the `ExecutedStatement` so auto-close-on-
/// drain fires once the stream is exhausted. Used by
/// `ExecutedStatement.fetch_all_arrow`.
pub(crate) fn drain_exec(
/// Pull batches into `pending` until it holds more than `max_rows` rows or
/// the stream ends (`usize::MAX`: to the end). Returns whether the stream
/// ended. A failed read leaves every batch read so far in `pending`.
pub(crate) fn fill(
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
runtime: &Runtime,
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
stream: &mut ResultStream,
pending: &mut VecDeque<RecordBatch>,
max_rows: usize,
) -> Result<bool> {
runtime.block_on(async {
let mut rows: usize = pending.iter().map(RecordBatch::num_rows).sum();
while rows <= max_rows {
match stream.next_batch().await? {
Some(ResultBatch::Arrow(rb)) => {
rows += rb.num_rows();
pending.push_back(rb.clone());
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
}
Some(_) => {
return Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant"));
}
None => return Ok(true),
}
}
Ok(false)
})
}

/// Like [`fill`], but drives the `ExecutedStatement` so auto-close-on-drain
/// fires once the stream is exhausted.
pub(crate) fn fill_exec(
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
runtime: &Runtime,
exec: &mut ExecutedStatement,
) -> Result<Vec<RecordBatch>> {
pending: &mut VecDeque<RecordBatch>,
max_rows: usize,
) -> Result<bool> {
runtime.block_on(async {
let mut out = Vec::new();
loop {
let mut rows: usize = pending.iter().map(RecordBatch::num_rows).sum();
while rows <= max_rows {
match exec.next_batch().await? {
Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()),
Some(ResultBatch::Arrow(rb)) => {
rows += rb.num_rows();
pending.push_back(rb.clone());
}
Some(_) => {
return Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant"));
}
None => break,
None => return Ok(true),
}
}
Ok(out)
Ok(false)
})
}

Expand Down
3 changes: 3 additions & 0 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ mod logging;
mod metadata;
mod params;
mod result_stream;
mod rows;
mod runtime;
mod session;
mod statement;
Expand Down Expand Up @@ -87,8 +88,10 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<executed_async::AsyncStatementReader>()?;
m.add_class::<metadata::Metadata>()?;
m.add_class::<result_stream::ResultStream>()?;
m.add_class::<rows::SchemaKey>()?;
m.add_function(wrap_pyfunction!(init_logging, m)?)?;
m.add_function(wrap_pyfunction!(reset_logging, m)?)?;
m.add_function(wrap_pyfunction!(rows::rows_from_arrow, m)?)?;

// Install the log bridge at module import so *any* consumer of the
// bare wheel (the connector, integration tests, custom embedders)
Expand Down
2 changes: 1 addition & 1 deletion pyo3/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ macro_rules! run_kernel_block {
}};
}

/// Run a synchronous helper (e.g. `fetch::next_batch` / `fetch::drain`,
/// Run a synchronous helper (e.g. `fetch::next_batch` / `fetch::fill`,
/// which `block_on` internally) with the GIL released, mapping kernel
/// errors into `KernelError`.
///
Expand Down
62 changes: 59 additions & 3 deletions pyo3/src/result_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,15 @@
//! the same code path through its `result_stream_mut()` borrow.

use crate::fetch;
use crate::rows::{self, SchemaKey};
use crate::runtime::KernelRuntime;
use arrow_array::RecordBatch;
use arrow_pyarrow::ToPyArrow;
use arrow_schema::Schema;
use databricks_sql_kernel::ResultStream as KResultStream;
use pyo3::prelude::*;
use pyo3::types::PyList;
use std::collections::VecDeque;
use std::sync::Arc;

/// Python-facing borrowed result stream.
Expand All @@ -40,23 +44,30 @@ pub(crate) struct ResultStream {
/// Cached schema — survives `close()` so callers can still read
/// the description after exhausting / closing the stream.
schema: Arc<Schema>,
/// Whether `fetch_all_rows` converts every column type of `schema`.
rows_supported: bool,
}

struct ResultStreamInner {
stream: KResultStream,
runtime: Arc<KernelRuntime>,
exhausted: bool,
/// Batches `fetch_all_rows` pulled but didn't convert; served first by
/// the Arrow fetches.
pending: VecDeque<RecordBatch>,
}

impl ResultStream {
pub(crate) fn new(stream: KResultStream, runtime: Arc<KernelRuntime>) -> Self {
let schema = stream.schema();
Self {
rows_supported: rows::schema_is_supported(&schema),
schema,
inner: Some(ResultStreamInner {
stream,
runtime,
exhausted: false,
pending: VecDeque::new(),
}),
}
}
Expand All @@ -69,10 +80,49 @@ impl ResultStream {
self.schema.as_ref().to_pyarrow(py)
}

/// See `ExecutedStatement.schema_key`.
fn schema_key(&self) -> SchemaKey {
SchemaKey::new(self.schema.clone())
}

/// See `ExecutedStatement.fetch_all_rows`.
#[pyo3(signature = (max_rows, nan_ok = false))]
fn fetch_all_rows<'py>(
&mut self,
py: Python<'py>,
max_rows: i64,
nan_ok: bool,
) -> PyResult<Option<Bound<'py, PyList>>> {
let max_rows = rows::max_rows(py, max_rows)?;
let inner = alive_mut!(self, "ResultStream");
if !self.rows_supported {
return Ok(None);
}
// No GIL hand-off when an earlier call already read more than fits.
if !inner.exhausted && rows::pending_rows(&inner.pending) <= max_rows {
let runtime = inner.runtime.clone();
inner.exhausted = run_sync_kernel!(
py,
fetch::fill(&runtime, &mut inner.stream, &mut inner.pending, max_rows)
)?;
}
rows::take_rows(
py,
&self.schema,
inner.exhausted,
&mut inner.pending,
max_rows,
nan_ok,
)
}

/// Pull the next batch as a `pyarrow.RecordBatch`, or `None` when
/// exhausted.
fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
let inner = alive_mut!(self, "ResultStream");
if let Some(batch) = inner.pending.pop_front() {
return Ok(Some(batch.to_pyarrow(py)?));
}
if inner.exhausted {
return Ok(None);
}
Expand All @@ -90,9 +140,15 @@ impl ResultStream {
/// Drain the full result and return a single `pyarrow.Table`.
fn fetch_all_arrow<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
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;
if !inner.exhausted {
let runtime = inner.runtime.clone();
// Read through `pending`, so a failed read loses no batch.
inner.exhausted = run_sync_kernel!(
py,
fetch::fill(&runtime, &mut inner.stream, &mut inner.pending, usize::MAX)
)?;
}
let batches: Vec<RecordBatch> = inner.pending.drain(..).collect();
fetch::batches_to_pyarrow_table(py, &self.schema, batches)
}

Expand Down
Loading
Loading