diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs
index ed1dd00e..863b9369 100644
--- a/napi/src/async_statement.rs
+++ b/napi/src/async_statement.rs
@@ -217,6 +217,67 @@ impl AsyncStatement {
.await
}
+ // ─── SEA extended status accessors (Thrift parity, async path) ─────
+ //
+ // Mirror the same-named accessors on the sync `Statement`. The
+ // underlying values come off the kernel `ExecutedAsyncStatement`'s
+ // latest observed `StatementStatus`; for a DML the kernel derives
+ // `num_modified_rows` from the result that rides on the terminal
+ // GetStatement poll (see `SeaRestTransport::enrich_num_modified_rows`),
+ // so a caller gets the count after the statement has reached a terminal
+ // state via `status()` / `awaitResult()` — no extra fetch. `null` until
+ // then, and on SELECT / warehouses that don't surface the counter.
+ // Throws `InvalidStatementHandle` after `close()`, matching `status()`.
+
+ /// Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE).
+ #[napi]
+ pub async fn num_modified_rows(&self) -> napi::Result> {
+ let inner = Arc::clone(&self.inner);
+ guarded(async move {
+ let guard = inner.lock().await;
+ let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?;
+ Ok(inner_state.executed_async.num_modified_rows())
+ })
+ .await
+ }
+
+ /// Server-supplied user-facing message (may contain SQL fragments —
+ /// redact before centralised logging).
+ #[napi]
+ pub async fn display_message(&self) -> napi::Result > {
+ let inner = Arc::clone(&self.inner);
+ guarded(async move {
+ let guard = inner.lock().await;
+ let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?;
+ Ok(inner_state.executed_async.display_message())
+ })
+ .await
+ }
+
+ /// Server-supplied diagnostic detail.
+ #[napi]
+ pub async fn diagnostic_info(&self) -> napi::Result > {
+ let inner = Arc::clone(&self.inner);
+ guarded(async move {
+ let guard = inner.lock().await;
+ let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?;
+ Ok(inner_state.executed_async.diagnostic_info())
+ })
+ .await
+ }
+
+ /// Server-supplied structured error detail (JSON), when enabled.
+ #[napi]
+ pub async fn error_details_json(&self) -> napi::Result > {
+ let inner = Arc::clone(&self.inner);
+ guarded(async move {
+ let guard = inner.lock().await;
+ let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?;
+ Ok(inner_state.executed_async.error_details_json())
+ })
+ .await
+ }
+
/// Block until the server reaches a terminal state, then return
/// an `AsyncResultHandle` that wraps the materialised result
/// stream. The handle exposes `fetchNextBatch()` / `schema()`
diff --git a/napi/src/database.rs b/napi/src/database.rs
index fb7337dd..f0435cf3 100644
--- a/napi/src/database.rs
+++ b/napi/src/database.rs
@@ -280,6 +280,27 @@ pub struct ConnectionOptions {
/// identity. The NodeJS driver folds its `userAgentEntry` into a
/// `User-Agent` entry here.
pub custom_headers: Option>,
+
+ /// Retry/backoff tuning — all optional. An unset field keeps the kernel's
+ /// built-in policy (1s/60s exponential backoff, 6 total attempts, 900s
+ /// budget). Mirrors the pyo3 binding's `retry_*` kwargs so the Node.js
+ /// driver can forward the same retry knobs the Python connector does.
+ ///
+ /// Lower bound of the exponential backoff (also clamps a server
+ /// `Retry-After`). Maps onto [`HttpConfig::retry_min_wait`].
+ pub retry_min_wait_secs: Option,
+ /// Upper bound of the exponential backoff. Maps onto
+ /// [`HttpConfig::retry_max_wait`].
+ pub retry_max_wait_secs: Option,
+ /// **Total** number of attempts (matching the connector's
+ /// `_retry_stop_after_attempts_count` and JDBC count semantics). The
+ /// kernel's [`HttpConfig::retry_max_retries`] counts retries *after* the
+ /// first attempt, so this is converted with `max(0, attempts - 1)` in
+ /// [`build_http_config`] — `0` / `1` both mean a single attempt, no retry.
+ pub retry_max_attempts: Option,
+ /// Overall retry budget in whole seconds. Maps onto
+ /// [`HttpConfig::overall_timeout`].
+ pub retry_overall_timeout_secs: Option,
}
/// Map the JS `ConnectionOptions` auth fields onto the kernel
@@ -406,6 +427,23 @@ fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig {
// duplicate names).
http.custom_headers = headers.into_iter().map(|h| (h.name, h.value)).collect();
}
+ // Retry/backoff knobs — only override the kernel default when the caller
+ // set one. `retry_max_attempts` is a TOTAL attempt count; the kernel's
+ // `retry_max_retries` counts retries *after* the first, so convert with
+ // `saturating_sub(1)` (0/1 ⇒ no retries). Centralises the off-by-one here,
+ // mirroring the pyo3 binding's `Session::new`.
+ if let Some(s) = options.retry_min_wait_secs {
+ http.retry_min_wait = std::time::Duration::from_secs(u64::from(s));
+ }
+ if let Some(s) = options.retry_max_wait_secs {
+ http.retry_max_wait = std::time::Duration::from_secs(u64::from(s));
+ }
+ if let Some(attempts) = options.retry_max_attempts {
+ http.retry_max_retries = attempts.saturating_sub(1);
+ }
+ if let Some(s) = options.retry_overall_timeout_secs {
+ http.overall_timeout = std::time::Duration::from_secs(u64::from(s));
+ }
http
}
@@ -522,6 +560,10 @@ mod tests {
client_cert_pem: None,
client_key_pem: None,
custom_headers: None,
+ retry_min_wait_secs: None,
+ retry_max_wait_secs: None,
+ retry_max_attempts: None,
+ retry_overall_timeout_secs: None,
}
}
@@ -876,4 +918,40 @@ mod tests {
assert_eq!(http.custom_headers[0].1, "Caller/1.0");
assert_eq!(http.custom_headers[1].1, "Connector/2.0");
}
+
+ #[test]
+ fn http_retry_knobs_map_onto_http_config() {
+ let mut o = base();
+ o.retry_min_wait_secs = Some(2);
+ o.retry_max_wait_secs = Some(45);
+ o.retry_max_attempts = Some(4); // total attempts → 3 retries
+ o.retry_overall_timeout_secs = Some(120);
+ let http = build_http_config(&mut o);
+ assert_eq!(http.retry_min_wait, std::time::Duration::from_secs(2));
+ assert_eq!(http.retry_max_wait, std::time::Duration::from_secs(45));
+ // total attempts (4) → retries after the first (3): the off-by-one.
+ assert_eq!(http.retry_max_retries, 3);
+ assert_eq!(http.overall_timeout, std::time::Duration::from_secs(120));
+ }
+
+ #[test]
+ fn http_retry_attempts_zero_or_one_means_no_retries() {
+ for attempts in [0u32, 1] {
+ let mut o = base();
+ o.retry_max_attempts = Some(attempts);
+ let http = build_http_config(&mut o);
+ assert_eq!(http.retry_max_retries, 0, "attempts={attempts}");
+ }
+ }
+
+ #[test]
+ fn http_retry_unset_keeps_kernel_defaults() {
+ let mut o = base();
+ let http = build_http_config(&mut o);
+ let def = HttpConfig::default();
+ assert_eq!(http.retry_min_wait, def.retry_min_wait);
+ assert_eq!(http.retry_max_wait, def.retry_max_wait);
+ assert_eq!(http.retry_max_retries, def.retry_max_retries);
+ assert_eq!(http.overall_timeout, def.overall_timeout);
+ }
}
diff --git a/src/client/retry.rs b/src/client/retry.rs
index d2191d94..3ffdfc7e 100644
--- a/src/client/retry.rs
+++ b/src/client/retry.rs
@@ -235,6 +235,14 @@ impl RetryStrategy {
/// Whether the given network/client error is retryable.
pub fn is_retryable_error(&self, error: &reqwest::Error) -> bool {
+ // A DNS *resolution* failure (the host name does not resolve) is
+ // permanent — retrying it just burns the whole retry budget on a host
+ // that will never come back. reqwest reports it as a "connect" error,
+ // which the branches below would otherwise treat as retryable, so
+ // short-circuit it here regardless of idempotency.
+ if is_dns_resolution_failure(error) {
+ return false;
+ }
match self.idempotency {
// Idempotent: all network errors are retryable
RequestIdempotency::Idempotent => {
@@ -246,6 +254,43 @@ impl RetryStrategy {
}
}
+/// Heuristic: is this network error a DNS *resolution* failure (the host name
+/// does not resolve), as opposed to a transient connect/timeout error?
+///
+/// A non-existent host (NXDOMAIN) will never resolve, so it must not be
+/// retried. reqwest does not expose a typed DNS-error variant, so we walk the
+/// error's source chain and match the resolver's message. Matching is broad
+/// and lowercased to cover the common phrasings across platforms/resolvers:
+/// libc/getaddrinfo (`Name or service not known`), macOS
+/// (`nodename nor servname provided`), and hyper/hickory
+/// (`dns error`, `failed to lookup address information`).
+fn is_dns_resolution_failure(error: &reqwest::Error) -> bool {
+ error_chain_indicates_dns_failure(error)
+}
+
+/// Walk an error's `source()` chain looking for a DNS-resolution marker.
+///
+/// Split out from [`is_dns_resolution_failure`] so it can be unit-tested with a
+/// synthetic error chain — `reqwest::Error` has no public constructor, so the
+/// matching logic can't be exercised through the typed wrapper directly.
+fn error_chain_indicates_dns_failure(error: &(dyn std::error::Error + 'static)) -> bool {
+ let mut source: Option<&(dyn std::error::Error + 'static)> = Some(error);
+ while let Some(err) = source {
+ let msg = err.to_string().to_ascii_lowercase();
+ if msg.contains("dns error")
+ || msg.contains("failed to lookup address")
+ || msg.contains("name or service not known")
+ || msg.contains("nodename nor servname")
+ || msg.contains("name resolution")
+ || msg.contains("no such host")
+ {
+ return true;
+ }
+ source = err.source();
+ }
+ false
+}
+
// --- Backoff Calculator ---
/// Calculate the backoff duration for a retry attempt.
@@ -307,6 +352,57 @@ fn parse_retry_after(value: &str) -> Option {
mod tests {
use super::*;
+ // --- DNS-resolution detection tests ---
+
+ #[test]
+ fn dns_marker_detected_for_common_resolver_phrasings() {
+ use std::io::Error as IoError;
+ for msg in [
+ "failed to lookup address information: Name or service not known",
+ "dns error: failed to lookup address information",
+ "nodename nor servname provided, or not known",
+ "No such host is known. (os error 11001)",
+ ] {
+ let err = IoError::other(msg);
+ assert!(
+ error_chain_indicates_dns_failure(&err),
+ "expected DNS marker in: {msg}"
+ );
+ }
+ }
+
+ #[test]
+ fn non_dns_connect_errors_are_not_flagged() {
+ use std::io::{Error as IoError, ErrorKind};
+ let refused = IoError::new(
+ ErrorKind::ConnectionRefused,
+ "Connection refused (os error 111)",
+ );
+ assert!(!error_chain_indicates_dns_failure(&refused));
+ let reset = IoError::new(ErrorKind::ConnectionReset, "connection reset by peer");
+ assert!(!error_chain_indicates_dns_failure(&reset));
+ }
+
+ #[test]
+ fn dns_marker_detected_through_nested_source() {
+ #[derive(Debug)]
+ struct Wrapper(std::io::Error);
+ impl std::fmt::Display for Wrapper {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ // Top-level message has no DNS marker — the marker is only on
+ // the inner source, mirroring the reqwest → connector chain.
+ write!(f, "error sending request for url (https://bogus.invalid/)")
+ }
+ }
+ impl std::error::Error for Wrapper {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ Some(&self.0)
+ }
+ }
+ let inner = std::io::Error::other("dns error");
+ assert!(error_chain_indicates_dns_failure(&Wrapper(inner)));
+ }
+
// --- RequestType mapping tests ---
#[test]
diff --git a/src/client/sea.rs b/src/client/sea.rs
index 27637b2b..6c75c78e 100644
--- a/src/client/sea.rs
+++ b/src/client/sea.rs
@@ -254,7 +254,52 @@ impl SeaRestTransport {
sea_response.statement_id, sea_response.status.state
);
- Self::convert_response(sea_response)
+ let mut response = Self::convert_response(sea_response)?;
+ self.enrich_num_modified_rows(&mut response).await;
+ Ok(response)
+ }
+
+ /// SEA omits the DML row count from the status envelope — for an
+ /// INSERT/UPDATE/DELETE/MERGE it rides in the result set instead (a single
+ /// row of `num_*_rows` counters). Thrift, by contrast, reports it on the
+ /// operation status. When a terminal GetStatement response carries a
+ /// DML-count result inline, derive `num_affected_rows` (the total) and set
+ /// it on the status so the extended-status accessors reach Thrift parity —
+ /// crucially on the async path, where the count would otherwise require an
+ /// explicit result fetch. No extra round-trip: the count rides on the status
+ /// poll the caller already made.
+ ///
+ /// Gated on the manifest's column signature so SELECTs (real columns) never
+ /// hit the decode path; a DML-count result is always tiny and inline.
+ async fn enrich_num_modified_rows(&self, response: &mut ExecuteResponse) {
+ if response.status.num_modified_rows.is_some() {
+ return;
+ }
+ match response.manifest.as_ref() {
+ Some(m) if crate::statement::dml_count::manifest_is_dml_count(m) => {}
+ _ => return,
+ }
+ let Ok(factory) = self.reader_factory() else {
+ return;
+ };
+ // Decode the inline count via a throwaway reader; this is independent of
+ // any later fetch the caller makes (a fresh GetStatement builds its own
+ // reader), so result consumption is unaffected.
+ let reader = match factory
+ .create_reader(&response.statement_id, response)
+ .await
+ {
+ Ok(r) => r,
+ Err(_) => return,
+ };
+ let mut stream = match crate::result_stream::ResultStream::from_reader(reader).await {
+ Ok(s) => s,
+ Err(_) => return,
+ };
+ if let Ok(Some(n)) = crate::statement::dml_count::read_dml_affected_rows(&mut stream).await
+ {
+ response.status.num_modified_rows = Some(n);
+ }
}
/// Decode a single SEA `ExecuteResponse` into a terminal outcome.
diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs
index 0f82b304..97158ad5 100644
--- a/src/metadata/thrift_shape.rs
+++ b/src/metadata/thrift_shape.rs
@@ -170,6 +170,53 @@ pub(crate) static GET_COLUMNS_SCHEMA: LazyLock = LazyLock::new(|| {
]))
});
+/// JDBC `getPrimaryKeys` — 6 columns. Matches
+/// `java.sql.DatabaseMetaData.getPrimaryKeys` (and the Databricks
+/// Thrift `TGetPrimaryKeysResp` column set). `KEY_SEQ` follows the
+/// Thrift wire type (`INT` / Int32), not JDBC's `short`, so the kernel
+/// backend is a drop-in replacement for existing PySQL / JDBC users.
+pub(crate) static GET_PRIMARY_KEYS_SCHEMA: LazyLock = LazyLock::new(|| {
+ Arc::new(Schema::new(vec![
+ Field::new("TABLE_CAT", DataType::Utf8, true),
+ Field::new("TABLE_SCHEM", DataType::Utf8, true),
+ Field::new("TABLE_NAME", DataType::Utf8, false),
+ Field::new("COLUMN_NAME", DataType::Utf8, false),
+ // JDBC spec says non-null, but declare nullable so the reshape
+ // doesn't fail on the rare server response that omits `keySeq`;
+ // modern DBR always populates it and the value flows through.
+ Field::new("KEY_SEQ", DataType::Int32, true),
+ Field::new("PK_NAME", DataType::Utf8, true),
+ ]))
+});
+
+/// JDBC `getCrossReference` / `getImportedKeys` — 14 columns. Matches
+/// `java.sql.DatabaseMetaData.getCrossReference` (and the Databricks
+/// Thrift `TGetCrossReferenceResp` column set). `KEY_SEQ` is `INT`
+/// (Int32) and `UPDATE_RULE` / `DELETE_RULE` / `DEFERRABILITY` are
+/// `SMALLINT` (Int16), matching the Thrift wire types. `UPDATE_RULE` /
+/// `DELETE_RULE` / `PK_NAME` have no source in the Databricks
+/// `SHOW FOREIGN KEYS` response, so they are emitted as typed nulls
+/// (no value is synthesized).
+pub(crate) static GET_CROSS_REFERENCE_SCHEMA: LazyLock = LazyLock::new(|| {
+ Arc::new(Schema::new(vec![
+ Field::new("PKTABLE_CAT", DataType::Utf8, true),
+ Field::new("PKTABLE_SCHEM", DataType::Utf8, true),
+ Field::new("PKTABLE_NAME", DataType::Utf8, false),
+ Field::new("PKCOLUMN_NAME", DataType::Utf8, false),
+ Field::new("FKTABLE_CAT", DataType::Utf8, true),
+ Field::new("FKTABLE_SCHEM", DataType::Utf8, true),
+ Field::new("FKTABLE_NAME", DataType::Utf8, false),
+ Field::new("FKCOLUMN_NAME", DataType::Utf8, false),
+ // Nullable for the same reason as `getPrimaryKeys` KEY_SEQ.
+ Field::new("KEY_SEQ", DataType::Int32, true),
+ Field::new("UPDATE_RULE", DataType::Int16, true),
+ Field::new("DELETE_RULE", DataType::Int16, true),
+ Field::new("FK_NAME", DataType::Utf8, true),
+ Field::new("PK_NAME", DataType::Utf8, true),
+ Field::new("DEFERRABILITY", DataType::Int16, true),
+ ]))
+});
+
// ─── Helpers ───────────────────────────────────────────────────────
/// Find the index of a column by name in the source schema, returning
@@ -298,6 +345,34 @@ fn null_int16(len: usize) -> ArrayRef {
Arc::new(arrow_array::Int16Array::from(vec![None::; len]))
}
+/// Return the named source column as an `Int16` array, casting from a
+/// related integer type if necessary. Returns an all-null `Int16`
+/// array when the column is absent — symmetric with [`int32_column`].
+/// A cast failure is surfaced as `Error::data_loss` rather than
+/// silently producing nulls. Used for JDBC `SMALLINT` columns
+/// (`DEFERRABILITY`) whose server source ships as a wider integer.
+fn int16_column(batch: &RecordBatch, name: &str) -> Result {
+ match column_index(batch.schema_ref(), name) {
+ Some(idx) => {
+ let col = batch.column(idx);
+ if col.data_type() == &DataType::Int16 {
+ Ok(Arc::clone(col))
+ } else {
+ arrow_cast::cast(col.as_ref(), &DataType::Int16).map_err(|e| {
+ Error::data_loss().message(format!(
+ "unexpected non-Int16 type for SHOW response column {name:?}: {e}"
+ ))
+ })
+ }
+ }
+ None => Ok(Arc::new(arrow_array::Int16Array::from(vec![
+ None::;
+ batch
+ .num_rows()
+ ]))),
+ }
+}
+
fn null_int8(len: usize) -> ArrayRef {
Arc::new(arrow_array::Int8Array::from(vec![None::; len]))
}
@@ -671,6 +746,84 @@ fn filter_tables_by_type(batch: &RecordBatch, types: &[&str]) -> Result Result {
+ let table_cat = utf8_column(batch, "catalogName")?;
+ let table_schem = utf8_column(batch, "namespace")?;
+ let table_name = utf8_column(batch, "tableName")?;
+ let column_name = utf8_column(batch, "col_name")?;
+ let key_seq = int32_column(batch, "keySeq")?;
+ let pk_name = utf8_column(batch, "constraintName")?;
+ RecordBatch::try_new(
+ GET_PRIMARY_KEYS_SCHEMA.clone(),
+ vec![
+ table_cat,
+ table_schem,
+ table_name,
+ column_name,
+ key_seq,
+ pk_name,
+ ],
+ )
+ .map_err(|e| Error::data_loss().message(format!("reshape primary_keys: {e}")))
+}
+
+/// Reshape Databricks `SHOW FOREIGN KEYS` output into the JDBC
+/// `getCrossReference` shape.
+///
+/// Server shape (same columns as `SHOW KEYS`): the foreign
+/// (FK-bearing) side is in `catalogName / namespace / tableName /
+/// col_name`, and the referenced primary side is in the `parent*`
+/// columns. This is a pure column rename + projection onto the 14
+/// JDBC columns. `UPDATE_RULE`, `DELETE_RULE`, and `PK_NAME` have no
+/// source in the server response — they are emitted as typed nulls
+/// rather than synthesizing a value (e.g. the kernel does not fabricate
+/// a JDBC `importedKeyNoAction` rule code).
+pub(crate) fn reshape_foreign_keys(batch: &RecordBatch) -> Result {
+ let n = batch.num_rows();
+ let pktable_cat = utf8_column(batch, "parentCatalogName")?;
+ let pktable_schem = utf8_column(batch, "parentNamespace")?;
+ let pktable_name = utf8_column(batch, "parentTableName")?;
+ let pkcolumn_name = utf8_column(batch, "parentColName")?;
+ let fktable_cat = utf8_column(batch, "catalogName")?;
+ let fktable_schem = utf8_column(batch, "namespace")?;
+ let fktable_name = utf8_column(batch, "tableName")?;
+ let fkcolumn_name = utf8_column(batch, "col_name")?;
+ let key_seq = int32_column(batch, "keySeq")?;
+ let fk_name = utf8_column(batch, "constraintName")?;
+ let deferrability = int16_column(batch, "deferrability")?;
+ RecordBatch::try_new(
+ GET_CROSS_REFERENCE_SCHEMA.clone(),
+ vec![
+ pktable_cat,
+ pktable_schem,
+ pktable_name,
+ pkcolumn_name,
+ fktable_cat,
+ fktable_schem,
+ fktable_name,
+ fkcolumn_name,
+ key_seq,
+ null_int16(n), // UPDATE_RULE — no server source; not synthesized
+ null_int16(n), // DELETE_RULE — no server source; not synthesized
+ fk_name,
+ null_utf8(n), // PK_NAME — no server source; not synthesized
+ deferrability,
+ ],
+ )
+ .map_err(|e| Error::data_loss().message(format!("reshape foreign_keys: {e}")))
+}
+
// ─── Streaming reshape reader ──────────────────────────────────────
/// Per-batch reshape closure used by [`ThriftReshapingReader`]. Held
@@ -1137,6 +1290,148 @@ mod tests {
assert_eq!(is_ai.value(0), "NO");
}
+ // ─── primary / foreign keys reshape ────────────────────────────
+
+ fn server_show_keys() -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("catalogName", DataType::Utf8, false),
+ Field::new("namespace", DataType::Utf8, false),
+ Field::new("tableName", DataType::Utf8, false),
+ Field::new("col_name", DataType::Utf8, false),
+ Field::new("keySeq", DataType::Int32, true),
+ Field::new("constraintName", DataType::Utf8, true),
+ Field::new("constraintType", DataType::Utf8, true),
+ ]));
+ RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(StringArray::from(vec!["main", "main"])),
+ Arc::new(StringArray::from(vec!["s", "s"])),
+ Arc::new(StringArray::from(vec!["t", "t"])),
+ Arc::new(StringArray::from(vec!["id", "code"])),
+ Arc::new(Int32Array::from(vec![Some(1), Some(2)])),
+ Arc::new(StringArray::from(vec!["pk_t", "pk_t"])),
+ Arc::new(StringArray::from(vec!["PRIMARY", "PRIMARY"])),
+ ],
+ )
+ .unwrap()
+ }
+
+ #[test]
+ fn primary_keys_renames_to_jdbc_columns() {
+ let out = reshape_primary_keys(&server_show_keys()).unwrap();
+ assert_eq!(
+ out.schema()
+ .fields()
+ .iter()
+ .map(|f| f.name().as_str())
+ .collect::>(),
+ vec![
+ "TABLE_CAT",
+ "TABLE_SCHEM",
+ "TABLE_NAME",
+ "COLUMN_NAME",
+ "KEY_SEQ",
+ "PK_NAME",
+ ]
+ );
+ assert_eq!(out.num_rows(), 2);
+ let key_seq = out.column(4).as_any().downcast_ref::().unwrap();
+ assert_eq!(key_seq.value(0), 1);
+ assert_eq!(key_seq.value(1), 2);
+ let pk_name = out
+ .column(5)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ assert_eq!(pk_name.value(0), "pk_t");
+ }
+
+ fn server_show_foreign_keys() -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("catalogName", DataType::Utf8, false),
+ Field::new("namespace", DataType::Utf8, false),
+ Field::new("tableName", DataType::Utf8, false),
+ Field::new("col_name", DataType::Utf8, false),
+ Field::new("keySeq", DataType::Int32, true),
+ Field::new("constraintName", DataType::Utf8, true),
+ Field::new("parentCatalogName", DataType::Utf8, true),
+ Field::new("parentNamespace", DataType::Utf8, true),
+ Field::new("parentTableName", DataType::Utf8, true),
+ Field::new("parentColName", DataType::Utf8, true),
+ Field::new("deferrability", DataType::Int32, true),
+ ]));
+ RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(StringArray::from(vec!["main"])),
+ Arc::new(StringArray::from(vec!["s"])),
+ Arc::new(StringArray::from(vec!["child"])),
+ Arc::new(StringArray::from(vec!["pid"])),
+ Arc::new(Int32Array::from(vec![Some(1)])),
+ Arc::new(StringArray::from(vec!["fk_child"])),
+ Arc::new(StringArray::from(vec!["main"])),
+ Arc::new(StringArray::from(vec!["s"])),
+ Arc::new(StringArray::from(vec!["parent"])),
+ Arc::new(StringArray::from(vec!["id"])),
+ Arc::new(Int32Array::from(vec![Some(7)])),
+ ],
+ )
+ .unwrap()
+ }
+
+ #[test]
+ fn foreign_keys_renames_to_jdbc_columns_and_nulls_unsourced() {
+ let out = reshape_foreign_keys(&server_show_foreign_keys()).unwrap();
+ assert_eq!(
+ out.schema()
+ .fields()
+ .iter()
+ .map(|f| f.name().as_str())
+ .collect::>(),
+ vec![
+ "PKTABLE_CAT",
+ "PKTABLE_SCHEM",
+ "PKTABLE_NAME",
+ "PKCOLUMN_NAME",
+ "FKTABLE_CAT",
+ "FKTABLE_SCHEM",
+ "FKTABLE_NAME",
+ "FKCOLUMN_NAME",
+ "KEY_SEQ",
+ "UPDATE_RULE",
+ "DELETE_RULE",
+ "FK_NAME",
+ "PK_NAME",
+ "DEFERRABILITY",
+ ]
+ );
+ assert_eq!(out.num_rows(), 1);
+ // Parent (PK) side and foreign (FK) side land in the right columns.
+ let pk_table = out
+ .column(2)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ assert_eq!(pk_table.value(0), "parent");
+ let fk_table = out
+ .column(6)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ assert_eq!(fk_table.value(0), "child");
+ // DEFERRABILITY is cast through to SMALLINT (Int16).
+ let deferr = out
+ .column(13)
+ .as_any()
+ .downcast_ref::()
+ .unwrap();
+ assert_eq!(deferr.value(0), 7);
+ // No server source → typed nulls, not synthesized values.
+ assert!(out.column(9).is_null(0)); // UPDATE_RULE
+ assert!(out.column(10).is_null(0)); // DELETE_RULE
+ assert!(out.column(12).is_null(0)); // PK_NAME
+ }
// ─── filter_tables_by_type tests ───────────────────────────────
fn tables_with_types(types: &[&str]) -> RecordBatch {
diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs
index 56acda96..e0efde55 100644
--- a/src/metadata_v0.rs
+++ b/src/metadata_v0.rs
@@ -84,7 +84,7 @@ use crate::kernel_error::{Error, Result};
use crate::metadata::static_data;
use crate::metadata::thrift_shape::{
self, is_object_not_found, ThriftReshapingReader, GET_CATALOGS_SCHEMA, GET_COLUMNS_SCHEMA,
- GET_SCHEMAS_SCHEMA, GET_TABLES_SCHEMA,
+ GET_CROSS_REFERENCE_SCHEMA, GET_PRIMARY_KEYS_SCHEMA, GET_SCHEMAS_SCHEMA, GET_TABLES_SCHEMA,
};
use crate::reader::EmptyReader;
use crate::result_stream::ResultStream;
@@ -490,9 +490,11 @@ impl Metadata {
/// namespace, tableName, col_name, keySeq, constraintName,
/// constraintType, parentCatalogName, parentNamespace,
/// parentTableName, parentColName, updateRule, deleteRule,
- /// deferrability`. Wrappers filter `constraintType =
- /// 'PRIMARY KEY'` to isolate the PK rows from the FK rows the
- /// server returns alongside.
+ /// deferrability`. The result is reshaped kernel-side into the
+ /// JDBC `getPrimaryKeys` column set (`TABLE_CAT`, `TABLE_SCHEM`,
+ /// `TABLE_NAME`, `COLUMN_NAME`, `KEY_SEQ`, `PK_NAME`) by
+ /// [`thrift_shape::reshape_primary_keys`] so every binding sees the
+ /// canonical names without re-mapping.
///
/// Catalog and schema are required at the kernel layer:
/// Databricks `SHOW KEYS` needs `IN CATALOG / IN SCHEMA / IN
@@ -512,7 +514,7 @@ impl Metadata {
let schema = schema.ok_or_else(|| {
Error::invalid_argument().message("primary_keys requires a schema identifier")
})?;
- let raw = self
+ let raw = match self
.session
.transport()
.list_primary_keys(
@@ -521,10 +523,23 @@ impl Metadata {
schema.as_str(),
table.as_str(),
)
- .await?;
- let stmt_id = raw.statement_id.clone();
- ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id)
.await
+ {
+ Ok(r) => r,
+ Err(e) => return not_found_or(e, GET_PRIMARY_KEYS_SCHEMA.clone(), Err).await,
+ };
+ let stmt_id = raw.statement_id.clone();
+ let reshaped = ThriftReshapingReader::new(
+ raw.reader,
+ GET_PRIMARY_KEYS_SCHEMA.clone(),
+ Box::new(thrift_shape::reshape_primary_keys),
+ );
+ ResultStream::from_reader_with_close(
+ Box::new(reshaped),
+ Arc::clone(&self.session),
+ stmt_id,
+ )
+ .await
}
.instrument(span)
.await
@@ -541,6 +556,12 @@ impl Metadata {
///
/// Server shape: same as [`primary_keys`](Self::primary_keys) —
/// `SHOW FOREIGN KEYS` shares its result schema with `SHOW KEYS`.
+ /// The result is reshaped kernel-side into the JDBC
+ /// `getCrossReference` column set (`PKTABLE_*`, `FKTABLE_*`,
+ /// `KEY_SEQ`, `UPDATE_RULE`, `DELETE_RULE`, `FK_NAME`, `PK_NAME`,
+ /// `DEFERRABILITY`) by [`thrift_shape::reshape_foreign_keys`].
+ /// `UPDATE_RULE` / `DELETE_RULE` / `PK_NAME` have no source in the
+ /// server response and are emitted as typed nulls (not synthesized).
pub async fn foreign_keys(
&self,
parent_catalog: Option>,
@@ -561,7 +582,7 @@ impl Metadata {
let foreign_table = foreign_table.ok_or_else(|| {
Error::invalid_argument().message("foreign_keys requires foreign_table")
})?;
- let raw = self
+ let raw = match self
.session
.transport()
.list_foreign_keys(
@@ -573,10 +594,23 @@ impl Metadata {
foreign_schema.as_str(),
foreign_table.as_str(),
)
- .await?;
- let stmt_id = raw.statement_id.clone();
- ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id)
.await
+ {
+ Ok(r) => r,
+ Err(e) => return not_found_or(e, GET_CROSS_REFERENCE_SCHEMA.clone(), Err).await,
+ };
+ let stmt_id = raw.statement_id.clone();
+ let reshaped = ThriftReshapingReader::new(
+ raw.reader,
+ GET_CROSS_REFERENCE_SCHEMA.clone(),
+ Box::new(thrift_shape::reshape_foreign_keys),
+ );
+ ResultStream::from_reader_with_close(
+ Box::new(reshaped),
+ Arc::clone(&self.session),
+ stmt_id,
+ )
+ .await
}
.instrument(span)
.await
diff --git a/src/result_stream.rs b/src/result_stream.rs
index 6fdd8501..79249879 100644
--- a/src/result_stream.rs
+++ b/src/result_stream.rs
@@ -453,6 +453,15 @@ pub struct ResultStream {
/// until the next call to `next_batch` replaces it.
current: Option,
+ /// A single batch pulled early by [`peek_first_batch`](Self::peek_first_batch)
+ /// and buffered for replay so the peek is **non-consuming**: the next
+ /// [`next_batch`](Self::next_batch) returns this batch instead of
+ /// re-entering the reader. Lets the statement layer read a DML
+ /// row-count result (which SEA delivers as the result set) without
+ /// stealing it from the caller's fetch — keeping result rows at parity
+ /// with the Thrift path. `None` once drained or when never peeked.
+ prefetched: Option,
+
/// Row cursor inside [`current`](Self::current). Reset to `0`
/// every time `next_batch` populates a fresh batch.
/// `next_row_in_batch` reads and increments.
@@ -526,6 +535,7 @@ impl ResultStream {
reader,
schema,
current: None,
+ prefetched: None,
current_row_idx: 0,
exhausted: false,
close_guard: None,
@@ -587,6 +597,13 @@ impl ResultStream {
/// performed on this path, so calling from a tokio runtime
/// (napi-rs, PyO3 async) is safe.
pub async fn next_batch(&mut self) -> Result> {
+ // A batch buffered by `peek_first_batch` is replayed here first,
+ // so a non-consuming peek doesn't steal it from the caller.
+ if let Some(batch) = self.prefetched.take() {
+ self.current = Some(batch);
+ self.current_row_idx = 0;
+ return Ok(self.current.as_ref());
+ }
if self.exhausted {
return Ok(None);
}
@@ -605,6 +622,25 @@ impl ResultStream {
}
}
+ /// Non-consuming peek at the **first** batch of the stream.
+ ///
+ /// Pulls one batch from the reader exactly once and buffers it so a
+ /// subsequent [`next_batch`](Self::next_batch) still returns it — the
+ /// peek does not advance consumption. Returns `None` for an empty
+ /// stream. Only valid before any `next_batch`/`peek_first_batch` has
+ /// run (it no-ops if a batch is already current or buffered), which is
+ /// the only context it's used in: deriving a DML row-count off the
+ /// terminal result at statement-construction time.
+ pub(crate) async fn peek_first_batch(&mut self) -> Result > {
+ if self.prefetched.is_none() && self.current.is_none() && !self.exhausted {
+ match self.reader.next_batch().await? {
+ Some(rb) => self.prefetched = Some(ResultBatch::Arrow(rb)),
+ None => self.exhausted = true,
+ }
+ }
+ Ok(self.prefetched.as_ref())
+ }
+
/// The batch most recently buffered by
/// [`next_batch`](Self::next_batch), without advancing the stream
/// or doing any I/O. `None` before the first `next_batch` or after
@@ -691,8 +727,13 @@ impl ResultStream {
/// runtime at all. Errors are surfaced once; subsequent calls
/// after an `Err` keep returning `None`.
pub fn into_owned_batches(self) -> OwnedBatchIter {
+ // Preserve a peeked-but-not-yet-consumed first batch: it was
+ // pulled from the reader, so it must be yielded ahead of the
+ // reader's remaining batches or it would be silently dropped.
+ let prefetched = self.prefetched.map(|ResultBatch::Arrow(rb)| rb);
OwnedBatchIter {
reader: self.reader,
+ prefetched,
done: false,
}
}
@@ -706,6 +747,10 @@ impl ResultStream {
/// reader's natural end-of-stream the same way.
pub struct OwnedBatchIter {
reader: Box,
+ /// A batch peeked off the stream before conversion (see
+ /// [`ResultStream::peek_first_batch`]); yielded before the reader's
+ /// own batches so it isn't lost.
+ prefetched: Option,
done: bool,
}
@@ -716,6 +761,9 @@ impl Iterator for OwnedBatchIter {
if self.done {
return None;
}
+ if let Some(batch) = self.prefetched.take() {
+ return Some(Ok(batch));
+ }
// Runtime-aware blocking poll: uses block_in_place + the
// current Handle when there's a tokio runtime on this thread
// (the case for CloudFetch readers, which await tokio
diff --git a/src/statement/dml_count.rs b/src/statement/dml_count.rs
new file mode 100644
index 00000000..acfedd17
--- /dev/null
+++ b/src/statement/dml_count.rs
@@ -0,0 +1,301 @@
+// 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.
+
+//! Derive `num_modified_rows` for SEA DML statements from the result set.
+//!
+//! Thrift surfaces `numModifiedRows` on the operation **status**
+//! (`TGetOperationStatusResp`, populated by the server on the terminal
+//! status of a DML). The SEA REST API does **not** put a row count on its
+//! status envelope at all — it returns the count as the statement's
+//! *result set*, a single row of `num_*_rows` counters:
+//!
+//! | Statement | Result columns |
+//! |-----------|-------------------------------------------------------------------------|
+//! | INSERT | `num_affected_rows`, `num_inserted_rows` |
+//! | UPDATE | `num_affected_rows` |
+//! | DELETE | `num_affected_rows` |
+//! | MERGE | `num_affected_rows`, `num_updated_rows`, `num_deleted_rows`, `num_inserted_rows` |
+//!
+//! `num_affected_rows` is the total, matching Thrift's `numModifiedRows`.
+//! Reading it here lets the kernel's `num_modified_rows()` accessor reach
+//! Thrift parity. The read is **non-consuming** (via
+//! [`ResultStream::peek_first_batch`]) so the count row still flows to the
+//! caller's fetch exactly as it does on the Thrift path — this only adds
+//! the status value, it does not change which rows are returned.
+
+use crate::kernel_error::Result;
+use crate::result_stream::{ResultBatch, ResultStream};
+use crate::types::sea::ResultManifest;
+use arrow_array::cast::AsArray;
+use arrow_array::types::{Int16Type, Int32Type, Int64Type, Int8Type};
+use arrow_array::Array;
+use arrow_schema::DataType;
+
+/// The exact set of column names a SEA DML count result is built from.
+const DML_COUNT_COLUMNS: [&str; 4] = [
+ "num_affected_rows",
+ "num_inserted_rows",
+ "num_updated_rows",
+ "num_deleted_rows",
+];
+
+/// The total-affected column whose value maps to `num_modified_rows`.
+const AFFECTED_ROWS_COLUMN: &str = "num_affected_rows";
+
+/// Does this result `manifest` describe a DML row-count result?
+///
+/// Same strict signature as [`read_dml_affected_rows`], but checked against
+/// the manifest's column metadata so a caller can decide whether the inline
+/// result is worth decoding *before* building a reader — keeping SELECTs (real
+/// columns) off the decode path entirely.
+pub(crate) fn manifest_is_dml_count(manifest: &ResultManifest) -> bool {
+ let cols = &manifest.schema.columns;
+ !cols.is_empty()
+ && cols
+ .iter()
+ .all(|c| DML_COUNT_COLUMNS.contains(&c.name.as_str()))
+ && cols.iter().any(|c| c.name == AFFECTED_ROWS_COLUMN)
+}
+
+/// If `stream`'s result set is a DML row-count result, return its
+/// `num_affected_rows` value; otherwise `None`.
+///
+/// Detection is deliberately strict — **every** column must be one of the
+/// known `num_*_rows` counters and `num_affected_rows` must be present —
+/// so a `SELECT 1 AS num_affected_rows` (a real query that merely aliases
+/// a column to that name) is not mistaken for a DML result. Thrift never
+/// faces this ambiguity because it reads the count from operation
+/// metadata rather than the result columns; the strict signature keeps us
+/// as close as the SEA wire shape allows.
+///
+/// Non-consuming: peeks the first batch and buffers it, so the caller's
+/// subsequent fetch still sees the row.
+pub(crate) async fn read_dml_affected_rows(stream: &mut ResultStream) -> Result> {
+ let schema = stream.schema();
+ let fields = schema.fields();
+ if fields.is_empty() {
+ return Ok(None);
+ }
+ if !fields
+ .iter()
+ .all(|f| DML_COUNT_COLUMNS.contains(&f.name().as_str()))
+ {
+ return Ok(None);
+ }
+ let Some(col_idx) = fields.iter().position(|f| f.name() == AFFECTED_ROWS_COLUMN) else {
+ return Ok(None);
+ };
+
+ let Some(ResultBatch::Arrow(batch)) = stream.peek_first_batch().await? else {
+ return Ok(None);
+ };
+ // A DML count result is always exactly one summary row.
+ if batch.num_rows() != 1 {
+ return Ok(None);
+ }
+ let col = batch.column(col_idx);
+ if col.is_null(0) {
+ return Ok(None);
+ }
+ // The server types these BIGINT (Arrow Int64); accept the narrower
+ // signed widths defensively, and ignore anything else rather than
+ // mis-reporting.
+ let value = match col.data_type() {
+ DataType::Int64 => col.as_primitive::().value(0),
+ DataType::Int32 => col.as_primitive::().value(0) as i64,
+ DataType::Int16 => col.as_primitive::().value(0) as i64,
+ DataType::Int8 => col.as_primitive::().value(0) as i64,
+ _ => return Ok(None),
+ };
+ Ok(Some(value))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::reader::InMemoryReader;
+ use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray};
+ use arrow_schema::{Field, Schema};
+ use std::sync::Arc;
+
+ /// Build a single-batch `ResultStream` from `(name, Int64 values)` columns.
+ async fn count_stream(cols: &[(&str, &[i64])]) -> ResultStream {
+ let fields: Vec = cols
+ .iter()
+ .map(|(n, _)| Field::new(*n, DataType::Int64, false))
+ .collect();
+ let arrays: Vec = cols
+ .iter()
+ .map(|(_, v)| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef)
+ .collect();
+ let schema = Arc::new(Schema::new(fields));
+ let batch = RecordBatch::try_new(schema.clone(), arrays).unwrap();
+ ResultStream::from_reader(Box::new(InMemoryReader::new(schema, vec![batch])))
+ .await
+ .unwrap()
+ }
+
+ #[test]
+ fn manifest_detection_gates_on_strict_signature() {
+ let dml: ResultManifest = serde_json::from_str(
+ r#"{"format":"ARROW_STREAM","schema":{"column_count":2,"columns":[
+ {"name":"num_affected_rows","type_name":"LONG","type_text":"BIGINT","position":0},
+ {"name":"num_inserted_rows","type_name":"LONG","type_text":"BIGINT","position":1}]},
+ "total_row_count":1}"#,
+ )
+ .unwrap();
+ assert!(manifest_is_dml_count(&dml));
+
+ let select: ResultManifest = serde_json::from_str(
+ r#"{"format":"ARROW_STREAM","schema":{"column_count":1,"columns":[
+ {"name":"id","type_name":"INT","type_text":"INT","position":0}]},
+ "total_row_count":3}"#,
+ )
+ .unwrap();
+ assert!(!manifest_is_dml_count(&select));
+
+ // Leads with the counter name but has a non-counter column → declined.
+ let aliased: ResultManifest = serde_json::from_str(
+ r#"{"format":"ARROW_STREAM","schema":{"column_count":2,"columns":[
+ {"name":"num_affected_rows","type_name":"LONG","type_text":"BIGINT","position":0},
+ {"name":"label","type_name":"STRING","type_text":"STRING","position":1}]},
+ "total_row_count":1}"#,
+ )
+ .unwrap();
+ assert!(!manifest_is_dml_count(&aliased));
+ }
+
+ #[tokio::test]
+ async fn insert_shape_returns_affected_rows() {
+ // INSERT → [num_affected_rows, num_inserted_rows].
+ let mut s = count_stream(&[("num_affected_rows", &[3]), ("num_inserted_rows", &[3])]).await;
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), Some(3));
+ }
+
+ #[tokio::test]
+ async fn update_delete_shape_returns_affected_rows() {
+ let mut s = count_stream(&[("num_affected_rows", &[2])]).await;
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), Some(2));
+ }
+
+ #[tokio::test]
+ async fn merge_shape_returns_affected_not_other_counters() {
+ // MERGE → [num_affected_rows, num_updated_rows, num_deleted_rows, num_inserted_rows];
+ // we report num_affected_rows (the total), not a sibling column.
+ let mut s = count_stream(&[
+ ("num_affected_rows", &[2]),
+ ("num_updated_rows", &[1]),
+ ("num_deleted_rows", &[0]),
+ ("num_inserted_rows", &[1]),
+ ])
+ .await;
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), Some(2));
+ }
+
+ #[tokio::test]
+ async fn zero_affected_rows_is_a_real_value_not_none() {
+ let mut s = count_stream(&[("num_affected_rows", &[0])]).await;
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), Some(0));
+ }
+
+ #[tokio::test]
+ async fn peek_is_non_consuming_count_row_still_fetchable() {
+ // The derive must not steal the row from the caller's fetch — parity
+ // with Thrift, whose DML fetch also returns the count row.
+ let mut s = count_stream(&[("num_affected_rows", &[7])]).await;
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), Some(7));
+ // The single count row is still there for next_batch().
+ let batch = s.next_batch().await.unwrap().expect("count row preserved");
+ let ResultBatch::Arrow(rb) = batch;
+ assert_eq!(rb.num_rows(), 1);
+ assert_eq!(rb.column(0).as_primitive::().value(0), 7);
+ // And the stream is then exhausted.
+ assert!(s.next_batch().await.unwrap().is_none());
+ }
+
+ #[tokio::test]
+ async fn select_with_real_columns_is_not_a_dml_count() {
+ // A genuine SELECT: not all columns are counters → None, and nothing
+ // is peeked/consumed.
+ let fields = vec![
+ Field::new("id", DataType::Int64, false),
+ Field::new("v", DataType::Utf8, true),
+ ];
+ let schema = Arc::new(Schema::new(fields));
+ let batch = RecordBatch::try_new(
+ schema.clone(),
+ vec![
+ Arc::new(Int64Array::from(vec![1])) as ArrayRef,
+ Arc::new(StringArray::from(vec!["a"])) as ArrayRef,
+ ],
+ )
+ .unwrap();
+ let mut s = ResultStream::from_reader(Box::new(InMemoryReader::new(schema, vec![batch])))
+ .await
+ .unwrap();
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), None);
+ // Untouched: the real row is the first thing the caller fetches.
+ assert!(s.next_batch().await.unwrap().is_some());
+ }
+
+ #[tokio::test]
+ async fn select_aliasing_a_counter_name_is_rejected_by_strict_match() {
+ // `SELECT 1 AS num_affected_rows, 'x' AS label` — leads with a counter
+ // name but `label` is not a counter, so the strict all-columns guard
+ // declines rather than mis-reporting a row count.
+ let fields = vec![
+ Field::new("num_affected_rows", DataType::Int64, false),
+ Field::new("label", DataType::Utf8, true),
+ ];
+ let schema = Arc::new(Schema::new(fields));
+ let batch = RecordBatch::try_new(
+ schema.clone(),
+ vec![
+ Arc::new(Int64Array::from(vec![1])) as ArrayRef,
+ Arc::new(StringArray::from(vec!["x"])) as ArrayRef,
+ ],
+ )
+ .unwrap();
+ let mut s = ResultStream::from_reader(Box::new(InMemoryReader::new(schema, vec![batch])))
+ .await
+ .unwrap();
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), None);
+ }
+
+ #[tokio::test]
+ async fn empty_schema_ddl_is_not_a_dml_count() {
+ let schema = Arc::new(Schema::empty());
+ let s_reader = InMemoryReader::new(schema.clone(), vec![]);
+ let mut s = ResultStream::from_reader(Box::new(s_reader)).await.unwrap();
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), None);
+ }
+
+ #[tokio::test]
+ async fn null_affected_rows_reports_none() {
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "num_affected_rows",
+ DataType::Int64,
+ true,
+ )]));
+ let batch = RecordBatch::try_new(
+ schema.clone(),
+ vec![Arc::new(Int64Array::from(vec![None as Option])) as ArrayRef],
+ )
+ .unwrap();
+ let mut s = ResultStream::from_reader(Box::new(InMemoryReader::new(schema, vec![batch])))
+ .await
+ .unwrap();
+ assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), None);
+ }
+}
diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs
index 1cac1586..ceec21c7 100644
--- a/src/statement/executed_async.rs
+++ b/src/statement/executed_async.rs
@@ -541,7 +541,23 @@ impl ExecutedAsyncStatement {
.fetch_completed_result(&self.statement_id)
.await?
{
- Some(result) => ResultStream::from_reader(result.reader).await,
+ Some(result) => {
+ let mut stream = ResultStream::from_reader(result.reader).await?;
+ // SEA carries no row count on the async status either; for a
+ // DML the count rides in the result set. Derive it once
+ // (non-consuming) and record it onto the latest status so
+ // `num_modified_rows()` matches the sync path / Thrift.
+ if self.num_modified_rows().is_none() {
+ if let Some(n) =
+ crate::statement::dml_count::read_dml_affected_rows(&mut stream).await?
+ {
+ if let Ok(mut guard) = self.latest_status.lock() {
+ guard.num_modified_rows = Some(n);
+ }
+ }
+ }
+ Ok(stream)
+ }
None => {
// Re-read the status so the error message names the
// observed state (Pending vs Running). Best-effort —
diff --git a/src/statement/mod.rs b/src/statement/mod.rs
index bad2077b..330fd759 100644
--- a/src/statement/mod.rs
+++ b/src/statement/mod.rs
@@ -24,6 +24,7 @@
//! `params` holds the protocol-neutral parameter conversion helpers used
//! by `Statement` to encode `TypedValue` bindings for SEA.
+pub(crate) mod dml_count;
pub mod executed;
pub mod executed_async;
pub mod handle;
diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs
index aea2c76f..c6bac02f 100644
--- a/src/statement/mutable.rs
+++ b/src/statement/mutable.rs
@@ -326,14 +326,24 @@ impl Statement {
self.last_valid = Some(valid.clone());
self.last_closed = Some(Arc::clone(&closed));
- let result_stream = ResultStream::from_reader(result.reader).await?;
+ let mut result_stream = ResultStream::from_reader(result.reader).await?;
+ // SEA puts no row count on the status envelope; for a DML it
+ // returns the count as the result set. If the server didn't
+ // already supply `num_modified_rows`, derive it from that
+ // result (non-consuming — the count row still reaches the
+ // caller's fetch) so `num_modified_rows()` matches Thrift.
+ let mut status = result.status;
+ if status.num_modified_rows.is_none() {
+ status.num_modified_rows =
+ crate::statement::dml_count::read_dml_affected_rows(&mut result_stream).await?;
+ }
Ok(ExecutedStatement::new(
Arc::clone(&self.session),
result.statement_id,
valid,
result_stream,
closed,
- result.status,
+ status,
))
}
.instrument(span)
diff --git a/tests/v0_metadata_e2e.rs b/tests/v0_metadata_e2e.rs
index f1db167c..477ecfea 100644
--- a/tests/v0_metadata_e2e.rs
+++ b/tests/v0_metadata_e2e.rs
@@ -311,7 +311,7 @@ async fn find_known_table(session: &Session) -> Option<(String, String, String)>
#[tokio::test]
#[ignore]
-async fn primary_keys_returns_server_show_keys_columns() {
+async fn primary_keys_returns_jdbc_columns() {
let session = live_session().await;
let Some((cat, schema, table)) = find_known_table(&session).await else {
eprintln!("skipping primary_keys E2E — no known sample table reachable");
@@ -328,24 +328,20 @@ async fn primary_keys_returns_server_show_keys_columns() {
.await
.expect("primary_keys");
- // Live SHOW KEYS shape on Dogfood: 14 columns including
- // catalogName / namespace / tableName / col_name / keySeq /
- // constraintName / constraintType / parent* / updateRule /
- // deleteRule / deferrability. Required minimum:
+ // Reshaped kernel-side into the JDBC getPrimaryKeys column set
+ // (the raw SHOW KEYS columns are renamed by reshape_primary_keys).
let names = col_names(&stream.schema());
- for required in [
- "catalogName",
- "namespace",
- "tableName",
- "col_name",
- "keySeq",
- "constraintName",
- ] {
- assert!(
- names.iter().any(|n| n == required),
- "expected '{required}' in {names:?}"
- );
- }
+ assert_eq!(
+ names,
+ vec![
+ "TABLE_CAT",
+ "TABLE_SCHEM",
+ "TABLE_NAME",
+ "COLUMN_NAME",
+ "KEY_SEQ",
+ "PK_NAME",
+ ]
+ );
let _ = collect(stream).await;
session.close().await.expect("close");
@@ -353,7 +349,7 @@ async fn primary_keys_returns_server_show_keys_columns() {
#[tokio::test]
#[ignore]
-async fn foreign_keys_returns_server_show_foreign_keys_columns() {
+async fn foreign_keys_returns_jdbc_columns() {
let session = live_session().await;
let Some((cat, schema, table)) = find_known_table(&session).await else {
eprintln!("skipping foreign_keys E2E — no known sample table reachable");
@@ -373,22 +369,29 @@ async fn foreign_keys_returns_server_show_foreign_keys_columns() {
.await
.expect("foreign_keys");
+ // Reshaped kernel-side into the JDBC getCrossReference column set
+ // (the raw SHOW FOREIGN KEYS columns are renamed by
+ // reshape_foreign_keys).
let names = col_names(&stream.schema());
- for required in [
- "catalogName",
- "namespace",
- "tableName",
- "col_name",
- "parentCatalogName",
- "parentNamespace",
- "parentTableName",
- "parentColName",
- ] {
- assert!(
- names.iter().any(|n| n == required),
- "expected '{required}' in {names:?}"
- );
- }
+ assert_eq!(
+ names,
+ vec![
+ "PKTABLE_CAT",
+ "PKTABLE_SCHEM",
+ "PKTABLE_NAME",
+ "PKCOLUMN_NAME",
+ "FKTABLE_CAT",
+ "FKTABLE_SCHEM",
+ "FKTABLE_NAME",
+ "FKCOLUMN_NAME",
+ "KEY_SEQ",
+ "UPDATE_RULE",
+ "DELETE_RULE",
+ "FK_NAME",
+ "PK_NAME",
+ "DEFERRABILITY",
+ ]
+ );
let _ = collect(stream).await;
session.close().await.expect("close");
diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs
index 08ab50de..3425eb0a 100644
--- a/tests/v0_metadata_wiremock.rs
+++ b/tests/v0_metadata_wiremock.rs
@@ -513,20 +513,22 @@ async fn list_columns_without_catalog_emits_all_catalogs_query() {
}
#[tokio::test]
-async fn primary_keys_passes_server_columns_through() {
+async fn primary_keys_reshaped_to_jdbc_columns() {
let server = MockServer::start().await;
mount_create_session(&server).await;
mount_delete_session(&server).await;
- // Live `SHOW KEYS` shape — full 14-column row including the
- // parent linkage columns and constraintType.
+ // Live `SHOW KEYS` shape — the kernel reshapes the server's
+ // `catalogName / namespace / tableName / col_name / keySeq /
+ // constraintName` columns into the JDBC `getPrimaryKeys` set.
let raw = string_batch(vec![
- ("catalogName", vec![Some("main")]),
- ("namespace", vec![Some("d")]),
- ("tableName", vec![Some("t")]),
- ("col_name", vec![Some("id")]),
- ("constraintName", vec![Some("pk_t")]),
- ("constraintType", vec![Some("PRIMARY KEY")]),
+ ("catalogName", vec![Some("main"), Some("main")]),
+ ("namespace", vec![Some("d"), Some("d")]),
+ ("tableName", vec![Some("t"), Some("t")]),
+ ("col_name", vec![Some("id"), Some("code")]),
+ ("keySeq", vec![Some("1"), Some("2")]),
+ ("constraintName", vec![Some("pk_t"), Some("pk_t")]),
+ ("constraintType", vec![Some("PRIMARY"), Some("PRIMARY")]),
]);
mount_execute(&server, succeeded_inline_response_body(&raw)).await;
@@ -544,25 +546,140 @@ async fn primary_keys_passes_server_columns_through() {
assert_eq!(
col_names(&stream.schema()),
vec![
- "catalogName",
- "namespace",
- "tableName",
- "col_name",
- "constraintName",
- "constraintType",
+ "TABLE_CAT",
+ "TABLE_SCHEM",
+ "TABLE_NAME",
+ "COLUMN_NAME",
+ "KEY_SEQ",
+ "PK_NAME",
]
);
let batches = drain_stream(&mut stream).await;
- assert_eq!(batches[0].num_rows(), 1);
+ assert_eq!(batches[0].num_rows(), 2);
assert_eq!(
batches[0]
- .column_by_name("constraintType")
+ .column_by_name("TABLE_CAT")
+ .unwrap()
+ .as_string::()
+ .value(0),
+ "main"
+ );
+ assert_eq!(
+ batches[0]
+ .column_by_name("COLUMN_NAME")
+ .unwrap()
+ .as_string::()
+ .value(1),
+ "code"
+ );
+ let key_seq = batches[0]
+ .column_by_name("KEY_SEQ")
+ .unwrap()
+ .as_any()
+ .downcast_ref::()
+ .expect("KEY_SEQ is Int32");
+ assert_eq!(key_seq.value(0), 1);
+ assert_eq!(key_seq.value(1), 2);
+ assert_eq!(
+ batches[0]
+ .column_by_name("PK_NAME")
+ .unwrap()
+ .as_string::()
+ .value(0),
+ "pk_t"
+ );
+}
+
+#[tokio::test]
+async fn foreign_keys_reshaped_to_jdbc_columns() {
+ let server = MockServer::start().await;
+ mount_create_session(&server).await;
+ mount_delete_session(&server).await;
+
+ // Live `SHOW FOREIGN KEYS` shape — the FK-bearing side is in
+ // `catalogName / namespace / tableName / col_name`, the referenced
+ // primary side in the `parent*` columns. The kernel reshapes into
+ // the JDBC `getCrossReference` set; UPDATE_RULE / DELETE_RULE /
+ // PK_NAME have no server source and come back null.
+ let raw = string_batch(vec![
+ ("catalogName", vec![Some("main")]),
+ ("namespace", vec![Some("d")]),
+ ("tableName", vec![Some("child")]),
+ ("col_name", vec![Some("pid")]),
+ ("keySeq", vec![Some("1")]),
+ ("constraintName", vec![Some("fk_child")]),
+ ("constraintType", vec![Some("FOREIGN")]),
+ ("parentCatalogName", vec![Some("main")]),
+ ("parentNamespace", vec![Some("d")]),
+ ("parentTableName", vec![Some("parent")]),
+ ("parentColName", vec![Some("id")]),
+ ("deferrability", vec![Some("7")]),
+ ]);
+ mount_execute(&server, succeeded_inline_response_body(&raw)).await;
+
+ let session = open_session(&server).await;
+ let mut stream = session
+ .metadata()
+ .foreign_keys(
+ None,
+ None,
+ None,
+ Some(Identifier::new("main").unwrap()),
+ Some(Identifier::new("d").unwrap()),
+ Some(Identifier::new("child").unwrap()),
+ )
+ .await
+ .expect("foreign_keys");
+
+ assert_eq!(
+ col_names(&stream.schema()),
+ vec![
+ "PKTABLE_CAT",
+ "PKTABLE_SCHEM",
+ "PKTABLE_NAME",
+ "PKCOLUMN_NAME",
+ "FKTABLE_CAT",
+ "FKTABLE_SCHEM",
+ "FKTABLE_NAME",
+ "FKCOLUMN_NAME",
+ "KEY_SEQ",
+ "UPDATE_RULE",
+ "DELETE_RULE",
+ "FK_NAME",
+ "PK_NAME",
+ "DEFERRABILITY",
+ ]
+ );
+
+ let batches = drain_stream(&mut stream).await;
+ assert_eq!(batches[0].num_rows(), 1);
+ let b = &batches[0];
+ assert_eq!(
+ b.column_by_name("PKTABLE_NAME")
+ .unwrap()
+ .as_string::()
+ .value(0),
+ "parent"
+ );
+ assert_eq!(
+ b.column_by_name("FKTABLE_NAME")
+ .unwrap()
+ .as_string::()
+ .value(0),
+ "child"
+ );
+ assert_eq!(
+ b.column_by_name("FK_NAME")
.unwrap()
.as_string::()
.value(0),
- "PRIMARY KEY"
+ "fk_child"
);
+ // UPDATE_RULE / DELETE_RULE / PK_NAME have no server source → null.
+ assert!(b.column_by_name("UPDATE_RULE").unwrap().is_null(0));
+ assert!(b.column_by_name("DELETE_RULE").unwrap().is_null(0));
+ assert!(b.column_by_name("PK_NAME").unwrap().is_null(0));
}
#[tokio::test]