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
32 changes: 32 additions & 0 deletions pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
//! pyclass alive longer than the user keeps a reference.

use crate::auth::{build_auth_config, OAuthParams};
use crate::executed_async::ExecutedAsyncStatement;
use crate::metadata::Metadata;
use crate::statement::Statement;
use databricks_sql_kernel::Session as KSession;
Expand Down Expand Up @@ -341,6 +342,37 @@ impl Session {
Ok(Metadata::new(kmeta, inner.runtime.clone()))
}

/// Re-attach to an already-submitted server statement by its id,
/// returning an `ExecutedAsyncStatement` the caller can poll
/// (`status()`), await (`await_result()`), or cancel/close — without
/// having been the handle that submitted it.
///
/// This is the resume path the connector uses for
/// `get_query_state` / `get_async_execution_result`: server
/// statement state is keyed solely by the id, so a caller holding
/// only the id can recover a working handle bound to this session.
///
/// Issues one `GetStatementStatus` to seed the handle. Raises
/// `KernelError` with code `NotFound` if the server doesn't
/// recognise the id (never submitted, or its result TTL elapsed). A
/// *closed* statement is not an error — the server keeps reporting
/// `CLOSED` (and terminal `SUCCEEDED`/`FAILED`) until GC, so the
/// returned handle's `status()` surfaces the real server state.
fn attach_async_statement(
&self,
py: Python<'_>,
statement_id: String,
) -> PyResult<ExecutedAsyncStatement> {
let inner = alive!(self, "Session");
let runtime = inner.runtime.clone();
tracing::debug!(
target: crate::logging::PYO3_LOG_TARGET,
"Session.attach_async_statement: re-attaching by id (GIL released)"
);
let exec = run_kernel!(py, runtime, inner.session.attach_async_statement(statement_id))?;
Ok(ExecutedAsyncStatement::new(exec, runtime))
}

/// Explicitly close the session. Idempotent. Subsequent calls on
/// this `Session` raise `KernelError`.
fn close(&mut self, py: Python<'_>) -> PyResult<()> {
Expand Down
17 changes: 17 additions & 0 deletions pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ pub(crate) struct ExecutedStatement {
/// Cached schema. Pulled from the kernel once on construction —
/// available even after `close()` so descriptions stay stable.
schema: Arc<Schema>,
/// Rows modified by the statement (DML: INSERT/UPDATE/DELETE/MERGE),
/// or `None` for SELECT / warehouses that don't report it. Cached at
/// construction (it's fixed once the statement completed) so it
/// survives `close()`, like `statement_id` / `schema`. The connector
/// surfaces this as `cursor.rowcount`.
num_modified_rows: Option<i64>,
}

struct ExecutedInner {
Expand All @@ -291,9 +297,11 @@ impl ExecutedStatement {
fn new(exec: KExecutedStatement, runtime: Arc<Runtime>) -> Self {
let statement_id = exec.statement_id().to_owned();
let schema = exec.schema();
let num_modified_rows = exec.num_modified_rows();
Self {
statement_id,
schema,
num_modified_rows,
inner: Some(ExecutedInner {
exec,
runtime,
Expand All @@ -310,6 +318,15 @@ impl ExecutedStatement {
&self.statement_id
}

/// Rows modified by the statement (DML), or `None` for SELECT /
/// warehouses that don't report it. The connector maps this to
/// `cursor.rowcount` (falling back to -1 when `None`). Available
/// after `close()` (cached at construction).
#[getter]
fn num_modified_rows(&self) -> Option<i64> {
self.num_modified_rows
}

/// Result schema as a `pyarrow.Schema`. Available even after
/// `close()`.
fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
Expand Down
143 changes: 133 additions & 10 deletions src/client/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,70 @@ use crate::client::retry::{
};
use crate::kernel_error::{Error, Result};
use crate::klog::{debug, warn};
use crate::types::sea::ServiceError;
use reqwest::{Client, NoProxy, Proxy, Request, Response};
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use tokio::time::sleep;

/// Build an `Error` for a transport-level non-2xx HTTP response, parsing
/// the SEA error envelope out of the response body when present.
///
/// The SEA REST API returns a JSON error body — either a bare
/// `{"error_code", "message", "sql_state"}` ([`ServiceError`]) or a
/// `{"error": {...}}` wrapper. Mirrors the statement-level path
/// (`sea.rs terminal_outcome`) so transport-level failures surface the
/// structured `error_code` / `sql_state` instead of only the raw body
/// stuffed into the message. Falls back to `context` (the raw body) as
/// the message when the body isn't a recognised envelope.
///
/// `context` is a caller-supplied prefix (e.g. "HTTP 400" / retry-timeout
/// detail) folded into the message so existing diagnostics are preserved.
fn http_error(status: u16, body: &str, context: impl std::fmt::Display) -> Error {
#[derive(serde::Deserialize)]
struct ErrorWrapper {
error: ServiceError,
}
// Try the bare envelope first, then the `{"error": ...}` wrapper.
let svc: Option<ServiceError> = serde_json::from_str::<ServiceError>(body)
.ok()
.filter(|e| e.error_code.is_some() || e.message.is_some() || e.sql_state.is_some())
.or_else(|| {
serde_json::from_str::<ErrorWrapper>(body)
.ok()
.map(|w| w.error)
});

let mut err = Error::from_http_status(status);
match svc {
Some(svc) => {
// Prefer the server's structured message; keep the caller
// context as a prefix for continuity with existing logs.
let msg = svc.message.as_deref().unwrap_or(body);
err = err.message(format!("{context}: {msg}"));
if let Some(ec) = svc.error_code.as_deref().filter(|s| !s.is_empty()) {
err = err.with_error_code(ec);
}
// SQL state: explicit field, else the "SQLSTATE: XXXXX"
// pattern in the message — same precedence as terminal_outcome.
let sql_state = svc
.sql_state
.filter(|s| !s.is_empty())
.or_else(|| crate::kernel_error::extract_sqlstate_from_message(msg));
if let Some(s) = sql_state {
err = err.with_sql_state(s);
}
}
None => {
// Not a recognised envelope — preserve today's behavior
// (raw body folded into the message).
err = err.message(format!("{context}: {body}"));
}
}
err
}

/// Configuration for HTTP proxy.
///
/// When `url` is set, the driver uses the specified proxy for all requests,
Expand Down Expand Up @@ -781,13 +839,16 @@ impl DatabricksHttpClient {
attempts,
elapsed.as_secs_f64()
);
return Err(Error::from_http_status(status.as_u16()).message(format!(
"HTTP {} — retry timeout exceeded after {} attempts ({:.1}s): {}",
return Err(http_error(
status.as_u16(),
attempts,
elapsed.as_secs_f64(),
error_body
)));
&error_body,
format_args!(
"HTTP {} — retry timeout exceeded after {} attempts ({:.1}s)",
status.as_u16(),
attempts,
elapsed.as_secs_f64()
),
));
}

last_error = Some(format!("HTTP {}", status.as_u16()));
Expand All @@ -812,11 +873,11 @@ impl DatabricksHttpClient {
start_time.elapsed().as_secs_f64(),
status.as_u16()
);
return Err(Error::from_http_status(status.as_u16()).message(format!(
"HTTP {} - {}",
return Err(http_error(
status.as_u16(),
error_body
)));
&error_body,
format_args!("HTTP {}", status.as_u16()),
));
}
Err(e) => {
if strategy.is_retryable_error(&e) && attempts < max_attempts {
Expand Down Expand Up @@ -1597,6 +1658,68 @@ lGrv15pBcePj
assert_eq!(attempt_count.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn test_http_error_parses_sea_error_envelope() {
// A transport-level 4xx whose body is the SEA error envelope
// must surface the structured error_code / sql_state on the
// returned Error (not just the raw body in the message),
// mirroring the statement-level terminal_outcome path.
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/test"))
.respond_with(ResponseTemplate::new(400).set_body_string(
r#"{"error_code":"BAD_REQUEST","message":"bad thing happened","sql_state":"42000"}"#,
))
.mount(&mock_server)
.await;

let client = test_client(&mock_server, fast_retry_config(3));
let request = client
.inner()
.get(format!("{}/test", mock_server.uri()))
.build()
.unwrap();
let err = client
.execute(request, RequestType::GetStatementStatus)
.await
.expect_err("400 must error");

assert_eq!(err.error_code.as_deref(), Some("BAD_REQUEST"));
assert_eq!(err.sql_state.as_deref(), Some("42000"));
// The structured server message is folded into the message.
assert!(
err.message.contains("bad thing happened"),
"message should carry the server text, got: {}",
err.message
);
}

#[tokio::test]
async fn test_http_error_non_envelope_body_falls_back_to_raw() {
// A non-JSON body keeps today's behavior: raw body in the
// message, no structured error_code/sql_state.
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/test"))
.respond_with(ResponseTemplate::new(400).set_body_string("plain text error"))
.mount(&mock_server)
.await;

let client = test_client(&mock_server, fast_retry_config(3));
let request = client
.inner()
.get(format!("{}/test", mock_server.uri()))
.build()
.unwrap();
let err = client
.execute(request, RequestType::GetStatementStatus)
.await
.expect_err("400 must error");

assert!(err.error_code.is_none());
assert!(err.message.contains("plain text error"));
}

#[tokio::test]
async fn test_idempotent_no_retry_on_401() {
let mock_server = MockServer::start().await;
Expand Down
48 changes: 47 additions & 1 deletion src/metadata/thrift_shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,12 @@ fn filter_tables_by_type(batch: &RecordBatch, types: &[&str]) -> Result<RecordBa
false
} else {
let t = types_arr.value(i);
types.contains(&t)
// Case-insensitive match: callers may pass `"view"` /
// `"Table"` (JDBC `getTables` allows any case) while the
// warehouse reports canonical uppercase (`TABLE` / `VIEW`
// / `SYSTEM_TABLE` / `METRIC_VIEW`). An exact match would
// silently drop all rows for a mixed-case request.
types.iter().any(|req| req.eq_ignore_ascii_case(t))
}
})
.collect();
Expand Down Expand Up @@ -1131,4 +1136,45 @@ mod tests {
.unwrap();
assert_eq!(is_ai.value(0), "NO");
}

// ─── filter_tables_by_type tests ───────────────────────────────

fn tables_with_types(types: &[&str]) -> RecordBatch {
// Minimal batch carrying only the TABLE_TYPE column that
// `filter_tables_by_type` inspects.
let schema = Arc::new(Schema::new(vec![Field::new(
"TABLE_TYPE",
DataType::Utf8,
true,
)]));
let arr = StringArray::from(types.iter().map(|s| Some(*s)).collect::<Vec<_>>());
RecordBatch::try_new(schema, vec![Arc::new(arr)]).unwrap()
}

fn kept_types(batch: &RecordBatch) -> Vec<String> {
let arr = batch
.column(0)
.as_any()
.downcast_ref::<StringArray>()
.unwrap();
(0..batch.num_rows())
.map(|i| arr.value(i).to_owned())
.collect()
}

#[test]
fn filter_tables_by_type_is_case_insensitive() {
// Warehouse reports canonical uppercase; a lowercase / mixed-case
// request must still match (JDBC getTables allows any case).
let batch = tables_with_types(&["TABLE", "VIEW", "SYSTEM_TABLE"]);
let out = filter_tables_by_type(&batch, &["view", "Table"]).unwrap();
assert_eq!(kept_types(&out), vec!["TABLE", "VIEW"]);
}

#[test]
fn filter_tables_by_type_drops_non_matching_and_nulls() {
let batch = tables_with_types(&["TABLE", "VIEW"]);
let out = filter_tables_by_type(&batch, &["MANAGED"]).unwrap();
assert_eq!(out.num_rows(), 0);
}
}
Loading
Loading