diff --git a/napi/Cargo.toml b/napi/Cargo.toml index c091baae..55190844 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -97,6 +97,13 @@ arrow-ipc = "57" # `src/error.rs` without bouncing through a hand-rolled escaper. serde_json = "1" +# Date/time parsing for the params codec. Already a kernel transitive +# dep (the kernel's `TypedValue::Date`/`Timestamp{,Ntz,Ltz}` variants +# wrap `chrono` types directly); declared here so `params.rs` can name +# `NaiveDate` / `NaiveDateTime` / `DateTime` for literal parsing. +# Version kept in lock-step with the kernel's `chrono` dep. +chrono = { version = "0.4", default-features = false, features = ["clock"] } + [build-dependencies] napi-build = "2" diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 20d3d11a..676a1d96 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -27,16 +27,141 @@ //! fire-and-forget close on the captured runtime handle if explicit //! close was never called. +use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::{Error as KernelError, Session}; +use databricks_sql_kernel::{Error as KernelError, Session, TypedValue}; use crate::error::napi_err_from_kernel; +use crate::params::{parse_typed_value, TypedValueInput}; use crate::runtime; use crate::statement::Statement; use crate::util::guarded; +/// Per-statement options for `Connection.executeStatement`. +/// +/// Mirrors the kernel `StatementSpec` knobs that are safe to thread +/// through napi without a kernel-side change. Today this covers: +/// - `statementConf` — per-statement Spark conf overlay +/// (`StatementSpec.statement_conf` → SEA `parameters` / +/// Thrift `confOverlay`) +/// - `queryTags` — convenience wrapper over `statementConf` with +/// key `query_tags`; serialised to the same comma-separated +/// `key:value` wire shape NodeJS Thrift's `serializeQueryTags` +/// produces (`lib/utils/queryTags.ts`). Backslashes in keys are +/// doubled; backslash/colon/comma in values are backslash-escaped. +/// +/// `rowLimit` (SEA `row_limit`) and `queryTimeoutSecs` (the per-statement +/// server wait timeout) are exposed here and threaded onto the kernel +/// `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) +/// carry bound query parameters, decoded via `params::parse_typed_value`. +/// +/// **Tag-order caveat (M4 parity note).** The napi `queryTags` field +/// is a Rust `HashMap` whose iteration order is +/// non-deterministic, so the serialised `query_tags` value may have +/// a different key order than Thrift's `serializeQueryTags` (which +/// iterates `Object.keys(...)` in insertion order) for the same +/// input. The SEA server is order-insensitive on conf values, so +/// the two are functionally equivalent. If a caller needs +/// byte-identical Thrift parity, the JS adapter pre-serialises via +/// `serializeQueryTags` and writes the result into +/// `statementConf["query_tags"]` directly — see +/// `SeaSessionBackend.executeStatement` in the NodeJS driver. This +/// path is the one the production code uses. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct ExecuteOptions { + /// Per-statement Spark conf overlay. Merged on top of the + /// session-level `sessionConf` at execute time; this map wins + /// on key collisions. Unknown keys are rejected by the server. + pub statement_conf: Option>, + /// Query tags as key→value pairs. Serialised to a comma- + /// separated `key:value` string (backslash-escaping `\`, `:`, + /// `,`) and placed into `statementConf["query_tags"]`, matching + /// NodeJS Thrift's `serializeQueryTags` wire shape. Passing + /// both `queryTags` AND a `query_tags` key in `statementConf` + /// raises `InvalidArgument` — the caller's intent is ambiguous + /// so we refuse to silently pick one over the other. + /// + /// See the struct-level "Tag-order caveat" for the + /// HashMap-iteration-order vs `Object.keys`-iteration-order + /// divergence and the byte-identical-Thrift-parity workaround. + pub query_tags: Option>, + /// Server-side cap on the number of rows this statement returns + /// (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + /// `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + pub row_limit: Option, + /// Per-statement server wait timeout in whole seconds. Bounds how + /// long the server waits before cancelling the statement + /// (`on_wait_timeout = CANCEL`), surfacing as a timeout — the + /// server statement timeout (JDBC `setQueryTimeout`). Maps to + /// `StatementSpec.query_timeout_secs`. Distinct from the + /// connection-level transport timeout. The SEA wire caps it at 50s. + pub query_timeout_secs: Option, + /// Positional parameters, in 1-based wire order. Index `i` in this + /// Vec corresponds to the `i+1`-th `?` placeholder in the SQL. + /// Each entry is a `{ sqlType, value }` pair — `value` is the + /// string-encoded literal or `null` for SQL NULL. Mirrors + /// `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. + pub positional_params: Option>, + /// Named parameters (`:name` placeholders). Each carries its `name` + /// alongside the `{ sqlType, value? }` pair. Mapped to a kernel + /// `TypedValue` via the same [`parse_typed_value`] codec and bound with + /// `StatementSpec::param_named`. Named is the SEA-spec-required public + /// param form (`StatementParameter.name` is `openapi_required`); + /// positional is the documented-undocumented variant. The two are + /// mutually exclusive at the SQL level (`?` vs `:name`). + pub named_params: Option>, +} + +/// A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a +/// distinct napi object (rather than an optional `name` on `TypedValueInput`) +/// so the positional surface stays a clean ordered list with no name field. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct NamedTypedValueInput { + pub name: String, + pub sql_type: String, + pub value: Option, +} + +/// Translate `ExecuteOptions.positional_params` into the kernel's +/// `Vec`, parsing each entry through [`parse_typed_value`] +/// (same validation surface as the pyo3 binding). Returns `Err` on the +/// first malformed entry so the kernel never receives a partially-bound +/// spec. +fn decode_positional_params(inputs: Vec) -> Result, napi::Error> { + inputs + .into_iter() + .map(|tv| { + parse_typed_value(&tv.sql_type, tv.value.as_deref()).map_err(napi_err_from_kernel) + }) + .collect() +} + +/// Translate `ExecuteOptions.named_params` into `(name, TypedValue)` pairs, +/// parsing each value through the same [`parse_typed_value`] codec as the +/// positional path. Returns `Err` on the first malformed entry. +fn decode_named_params( + inputs: Vec, +) -> Result, napi::Error> { + inputs + .into_iter() + .map(|nv| { + parse_typed_value(&nv.sql_type, nv.value.as_deref()) + .map(|tv| (nv.name, tv)) + .map_err(napi_err_from_kernel) + }) + .collect() +} + /// Closed-state error builder. Mirrors `statement::statement_closed_err` /// — route through the kernel envelope so the TS reviver mints a typed /// `KernelError(code='InvalidStatementHandle')`. Single source of truth @@ -47,6 +172,73 @@ fn connection_closed_err() -> napi::Error { ) } +/// Merge `statement_conf` and `query_tags` from JS-supplied +/// `ExecuteOptions` into the single `HashMap` the +/// kernel's `StatementSpec::statement_conf` accepts. +/// +/// Returns `Ok(None)` when no per-statement conf is set (caller skips +/// the `.statement_conf(...)` builder call so the kernel sees the +/// session-level conf untouched). Returns `Ok(Some(conf))` when at +/// least one knob was set. Returns `Err(InvalidArgument)` when both +/// `queryTags` and `statementConf["query_tags"]` are present — the +/// caller's intent is ambiguous. +fn build_merged_statement_conf( + options: Option, +) -> napi::Result>> { + let Some(options) = options else { + return Ok(None); + }; + + let mut conf = options.statement_conf.unwrap_or_default(); + if let Some(tags) = options.query_tags { + if !tags.is_empty() && conf.contains_key("query_tags") { + return Err(napi_err_from_kernel( + KernelError::invalid_argument().message( + "ExecuteOptions: cannot supply both `queryTags` and \ + `statementConf[\"query_tags\"]` — pick one", + ), + )); + } + if !tags.is_empty() { + conf.insert("query_tags".to_string(), serialize_query_tags(&tags)); + } + } + + if conf.is_empty() { + Ok(None) + } else { + Ok(Some(conf)) + } +} + +/// Serialise a tag map to the same wire shape NodeJS Thrift's +/// `serializeQueryTags` produces: comma-separated `key:value` pairs. +/// Backslashes in keys are doubled; backslash, colon, and comma in +/// values are backslash-escaped. Null/empty values would produce a +/// bare key with no colon — but the napi `HashMap` +/// shape can't carry nulls today, so every tag here is `key:value`. +/// +/// Match the Thrift wire shape exactly: the SEA server merges +/// `confOverlay.query_tags` the same way regardless of which backend +/// produced it, and JS callers porting from Thrift expect identical +/// behaviour. +fn serialize_query_tags(tags: &HashMap) -> String { + tags.iter() + .map(|(k, v)| { + let esc_key = k.replace('\\', "\\\\"); + let esc_val = v + .chars() + .flat_map(|c| match c { + '\\' | ':' | ',' => vec!['\\', c], + other => vec![other], + }) + .collect::(); + format!("{esc_key}:{esc_val}") + }) + .collect::>() + .join(",") +} + /// Opaque connection handle wrapping a kernel `Session`. /// /// `inner` is `Arc>>` so: @@ -88,17 +280,75 @@ impl Connection { /// Execute a SQL statement and return a Statement handle that /// streams batches via `fetchNextBatch()`. /// - /// No per-statement options: catalog / schema / sessionConf are - /// session-level (`openSession`). + /// Catalog / schema / sessionConf are session-level + /// (`openSession`). Per-statement options on `ExecuteOptions`: + /// - `statementConf` — per-statement Spark conf overlay + /// - `queryTags` — serialised to a comma-separated `key:value` + /// string and placed in `statement_conf["query_tags"]`, + /// matching NodeJS Thrift's `serializeQueryTags` wire shape + /// + /// `options` is omitted/`None` for the no-options path; passing + /// `{ statementConf: {} }` (an empty map) is treated the same as + /// omission to keep the wire shape stable for the common case. #[napi] - pub async fn execute_statement(&self, sql: String) -> napi::Result { + pub async fn execute_statement( + &self, + sql: String, + mut options: Option, + ) -> napi::Result { let inner = Arc::clone(&self.inner); + // Pull the scalar knobs out before `build_merged_statement_conf` + // consumes `options` (both `i64`/`u32` are `Copy`). + let row_limit = options.as_ref().and_then(|o| o.row_limit); + let query_timeout_secs = options.as_ref().and_then(|o| o.query_timeout_secs); + // Decode positional params before `options` is consumed below; a + // malformed entry surfaces as InvalidArgument here, before any wire + // round-trip. + let positional_params = options + .as_mut() + .and_then(|o| o.positional_params.take()) + .map(decode_positional_params) + .transpose()? + .unwrap_or_default(); + let named_params = options + .as_mut() + .and_then(|o| o.named_params.take()) + .map(decode_named_params) + .transpose()? + .unwrap_or_default(); + // Merge `query_tags` into `statement_conf` at the napi boundary + // so the kernel sees a single conf map. Serialise the tag + // map to the comma-separated `key:value` wire shape NodeJS + // Thrift produces in `serializeQueryTags` + // (`lib/utils/queryTags.ts`). + let merged_conf = build_merged_statement_conf(options)?; guarded(async move { let guard = inner.lock().await; let session = guard.as_ref().ok_or_else(connection_closed_err)?; let mut stmt = session.statement(); stmt.spec().sql(sql); + if let Some(conf) = merged_conf { + stmt.spec().statement_conf(conf); + } + // `None` leaves the kernel's omit-the-field default in place, + // so threading unconditionally is safe and keeps the spec the + // single source of truth. + stmt.spec() + .row_limit(row_limit) + .query_timeout_secs(query_timeout_secs); + // Bind positional params 1-based on the wire. + for (i, value) in positional_params.into_iter().enumerate() { + stmt.spec() + .param(i + 1, value) + .map_err(napi_err_from_kernel)?; + } + // Bind named params (`:name`). + for (name, value) in named_params { + stmt.spec() + .param_named(name, value) + .map_err(napi_err_from_kernel)?; + } let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. @@ -218,4 +468,227 @@ mod tests { }; assert_eq!(conn.session_id(), "session-survives-close"); } + + // ─── ExecuteOptions / build_merged_statement_conf ─────────────────── + + #[test] + fn merged_conf_none_when_options_is_none() { + let result = build_merged_statement_conf(None).unwrap(); + assert!(result.is_none(), "no options → no statement_conf"); + } + + #[test] + fn merged_conf_none_when_both_maps_empty() { + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(HashMap::new()), + query_tags: Some(HashMap::new()), + row_limit: None, + query_timeout_secs: None, + positional_params: None, + named_params: None, + })) + .unwrap(); + assert!(result.is_none(), "empty maps → no statement_conf"); + } + + #[test] + fn merged_conf_passes_through_statement_conf() { + let mut conf = HashMap::new(); + conf.insert("ANSI_MODE".to_string(), "true".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: None, + row_limit: None, + query_timeout_secs: None, + positional_params: None, + named_params: None, + })) + .unwrap() + .unwrap(); + assert_eq!(result.get("ANSI_MODE").map(String::as_str), Some("true")); + } + + #[test] + fn merged_conf_query_tags_serialised_into_query_tags_key() { + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, + positional_params: None, + named_params: None, + })) + .unwrap() + .unwrap(); + // Single-tag case is deterministic regardless of HashMap order. + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("team:platform"), + ); + } + + #[test] + fn merged_conf_query_tags_escape_special_chars_in_values() { + let mut tags = HashMap::new(); + tags.insert("k".to_string(), "v:1,v\\2".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, + positional_params: None, + named_params: None, + })) + .unwrap() + .unwrap(); + let encoded = result.get("query_tags").unwrap(); + // `:` → `\:`, `,` → `\,`, `\` → `\\`. Order in the input is + // `v:1,v\2` so the encoded form is `v\:1\,v\\2`. + assert_eq!(encoded, "k:v\\:1\\,v\\\\2"); + } + + #[test] + fn merged_conf_query_tags_escape_backslash_in_keys() { + let mut tags = HashMap::new(); + tags.insert("k\\1".to_string(), "v".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, + positional_params: None, + named_params: None, + })) + .unwrap() + .unwrap(); + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("k\\\\1:v") + ); + } + + #[test] + fn merged_conf_rejects_dual_query_tags_definition() { + let mut conf = HashMap::new(); + conf.insert("query_tags".to_string(), "explicit:value".to_string()); + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + let err = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: Some(tags), + row_limit: None, + query_timeout_secs: None, + positional_params: None, + named_params: None, + })) + .expect_err("must reject when both are set"); + assert!( + err.reason.contains("cannot supply both"), + "error must explain the conflict: {}", + err.reason, + ); + } + + #[test] + fn merged_conf_empty_query_tags_does_not_collide_with_existing_key() { + // An empty `queryTags: {}` map should be ignored, so the + // caller can still pass an explicit + // `statementConf["query_tags"]` alongside `queryTags: {}` + // without tripping the ambiguity guard. Convention: empty + // input maps mean "not supplied". + let mut conf = HashMap::new(); + conf.insert("query_tags".to_string(), "explicit:value".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: Some(HashMap::new()), + row_limit: None, + query_timeout_secs: None, + positional_params: None, + named_params: None, + })) + .unwrap() + .unwrap(); + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("explicit:value"), + ); + } + + // ─── DA round-2 M4 parity — byte-shape vs Thrift's serializeQueryTags ─ + + /// `serializeQueryTags` (NodeJS Thrift, `lib/utils/queryTags.ts`) + /// is the canonical wire shape for `query_tags`. Pin the + /// per-tag byte shape produced by the kernel-side serializer + /// against the algorithm Thrift uses, so a regression on either + /// side fails this test. + /// + /// Algorithm (per Thrift): + /// - Keys: backslash doubled (`\` → `\\`); no other escaping + /// - Values: backslash, colon, and comma each backslash-escaped + /// - Tags: joined with `,` + /// - Single-tag case is order-deterministic; multi-tag case + /// asserts each pair appears regardless of HashMap iteration + /// order (the documented order caveat). + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_single_tag() { + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + assert_eq!(serialize_query_tags(&tags), "team:platform"); + } + + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_escapes() { + // Per Thrift's `escapedValue.replace(/[\\:,]/g, c => '\\' + c)`: + // input `v:1,v\2` + // output `v\:1\,v\\2` + let mut tags = HashMap::new(); + tags.insert("k".to_string(), "v:1,v\\2".to_string()); + assert_eq!(serialize_query_tags(&tags), "k:v\\:1\\,v\\\\2"); + } + + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_key_backslash_only() { + // Per Thrift's `escapedKey = key.replace(/\\/g, '\\\\')`: + // input `k\1` + // output `k\\1` + // Colons/commas in keys are NOT escaped on Thrift's path — + // they're only escaped in values. Test pins this asymmetry + // so a future "uniformity" refactor that escapes them in + // keys too gets caught. + let mut tags = HashMap::new(); + tags.insert("k\\1".to_string(), "v".to_string()); + assert_eq!(serialize_query_tags(&tags), "k\\\\1:v"); + } + + #[test] + fn serialize_query_tags_empty_map_yields_empty_string() { + // Thrift returns `undefined` for empty input, but Thrift's + // caller only invokes the serializer when input is non-empty + // (see `lib/DBSQLSession.ts:231` `if (serializedQueryTags + // !== undefined)`). Our serializer is called only by + // `build_merged_statement_conf` which already filters empty + // input out, so this test pins the never-called case for + // defense. + assert_eq!(serialize_query_tags(&HashMap::new()), ""); + } + + #[test] + fn serialize_query_tags_multi_tag_contains_each_pair_regardless_of_order() { + // Multi-tag case: HashMap iteration is non-deterministic, so + // we can't assert a single byte string. Assert each pair is + // present and the join uses `,`. SEA server treats conf + // values as order-insensitive, so this is functionally + // equivalent to the Thrift output regardless of order. + let mut tags = HashMap::new(); + tags.insert("a".to_string(), "1".to_string()); + tags.insert("b".to_string(), "2".to_string()); + let s = serialize_query_tags(&tags); + let pairs: std::collections::HashSet<&str> = s.split(',').collect(); + assert!( + pairs == ["a:1", "b:2"].iter().copied().collect(), + "got: {s}", + ); + } } diff --git a/napi/src/database.rs b/napi/src/database.rs index d2b8fac4..02135172 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -28,7 +28,9 @@ use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::{AuthConfig, DefaultOpts, HttpConfig, Session}; +use databricks_sql_kernel::{ + AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ResultConfig, Session, +}; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. /// @@ -49,8 +51,35 @@ use crate::error::napi_err_from_kernel; use crate::runtime; use crate::util::guarded; -/// JS-visible options for opening a Databricks SQL session over PAT. -/// `token` is required. +/// Authentication mode selector crossing the napi boundary. The string +/// literals are what napi-rs emits from this `#[napi(string_enum)]` — the +/// NodeJS SEA adapter (`SeaAuth`) matches them verbatim (`'Pat'`, +/// `'OAuthM2m'`, `'OAuthU2m'`). +/// +/// Mirrors the kernel [`AuthConfig`] variants this binding supports. +/// `OAuthFederation` / `External` are intentionally not exposed yet — the +/// kernel marks federation as not-yet-implemented and `External` is a +/// Rust-trait escape hatch with no JS-callback bridge. +#[napi(string_enum)] +#[derive(Default)] +pub enum AuthMode { + /// Personal access token (`token`). + #[default] + Pat, + /// OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. + OAuthM2m, + /// OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` + /// + `oauthRedirectPort`. + OAuthU2m, +} + +/// JS-visible options for opening a Databricks SQL session. +/// +/// Authentication is selected by `authMode` (default [`AuthMode::Pat`]): +/// - `Pat` — `token` required. +/// - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. +/// - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional (kernel +/// defaults to the `databricks-cli` client on port 8020). /// /// Catalog / schema / sessionConf are applied once at session creation /// and remain in effect for every statement run on the resulting @@ -69,9 +98,23 @@ pub struct ConnectionOptions { /// JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The /// kernel parses out the warehouse id. pub http_path: String, - /// Personal access token. Must be non-empty (the kernel rejects - /// empty PATs at session construction). - pub token: String, + /// Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: + /// existing PAT callers pass only `token`). + pub auth_mode: Option, + /// Personal access token. Required (and non-empty) for + /// [`AuthMode::Pat`]; ignored otherwise. + pub token: Option, + /// OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for + /// [`AuthMode::OAuthU2m`] (kernel defaults to `databricks-cli`). + pub oauth_client_id: Option, + /// OAuth client secret. Required for [`AuthMode::OAuthM2m`]. + pub oauth_client_secret: Option, + /// Localhost callback port for the [`AuthMode::OAuthU2m`] browser + /// flow. Omitted ⇒ kernel default (8020). + pub oauth_redirect_port: Option, + /// OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults + /// (`["all-apis"]` for M2M; `["all-apis", "offline_access"]` for U2M). + pub oauth_scopes: Option>, /// Default catalog for statements executed on this session. /// Routed through the kernel's `DefaultOpts` and onto the SEA /// `CreateSession.catalog` wire field. @@ -105,10 +148,68 @@ pub struct ConnectionOptions { /// Napi-rs serialises `u32` as JS `number`; values up to /// `2^32 - 1` round-trip safely (any reasonable pool size fits). pub max_connections: Option, + /// Render `INTERVAL` / `DURATION` result columns as strings + /// (`ResultConfig.intervals_as_string`). The kernel default is + /// native Arrow `month_interval` / `duration[us]` types; the NodeJS + /// Thrift driver surfaces intervals as strings, so the SEA driver + /// sets this `true` for byte-compatible parity. Omitted ⇒ kernel + /// default (native Arrow interval types). + pub intervals_as_string: Option, + /// Render complex (`ARRAY` / `MAP` / `STRUCT` / `VARIANT`) result + /// columns as JSON strings (`ResultConfig.complex_types_as_json`) + /// instead of native Arrow nested types. Omitted ⇒ kernel default + /// (native Arrow nested types, which the NodeJS Arrow decoder + /// already renders identically to the Thrift path). + pub complex_types_as_json: Option, } -/// Open a Databricks SQL session over PAT auth and return an opaque -/// `Connection` wrapping the kernel `Session`. +/// Require a non-empty `Option` field for a given auth mode, +/// returning a typed `InvalidArgument` naming the JS field otherwise. +fn require_field(value: &Option, js_name: &str, mode: &str) -> napi::Result { + value.clone().filter(|s| !s.is_empty()).ok_or_else(|| { + napi_err_from_kernel( + KernelError::invalid_argument() + .message(format!("authMode {mode} requires a non-empty `{js_name}`")), + ) + }) +} + +/// Map the JS `ConnectionOptions` auth fields onto the kernel +/// [`AuthConfig`]. Per-mode required-field validation lives here at the +/// binding boundary so the kernel always receives a fully-formed variant. +/// Pure (borrows `options`) so it is unit-testable without opening a +/// session. +fn build_auth_config(options: &ConnectionOptions) -> napi::Result { + match options.auth_mode.unwrap_or_default() { + AuthMode::Pat => Ok(AuthConfig::Pat { + token: require_field(&options.token, "token", "Pat")?, + }), + AuthMode::OAuthM2m => Ok(AuthConfig::OAuthM2M { + client_id: require_field(&options.oauth_client_id, "oauthClientId", "OAuthM2m")?, + client_secret: require_field( + &options.oauth_client_secret, + "oauthClientSecret", + "OAuthM2m", + )?, + scopes: options.oauth_scopes.clone(), + token_url_override: None, + }), + AuthMode::OAuthU2m => Ok(AuthConfig::OAuthU2M { + // All U2M fields are optional — the kernel fills `databricks-cli` + // / port 8020 / default scopes when omitted. + client_id: options.oauth_client_id.clone(), + redirect_port: options.oauth_redirect_port, + scopes: options.oauth_scopes.clone(), + token_url_override: None, + callback_timeout: None, + }), + } +} + +/// Open a Databricks SQL session and return an opaque `Connection` +/// wrapping the kernel `Session`. Authentication is selected by +/// `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see +/// [`build_auth_config`]. /// /// The JS-visible name is `openSession` (napi-rs converts snake_case /// to camelCase for free functions). @@ -125,6 +226,10 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result napi::Result napi::Result napi::Result ConnectionOptions { + ConnectionOptions { + host_name: "adb-1.azuredatabricks.net".to_owned(), + http_path: "/sql/1.0/warehouses/abc".to_owned(), + auth_mode: None, + token: None, + oauth_client_id: None, + oauth_client_secret: None, + oauth_redirect_port: None, + oauth_scopes: None, + catalog: None, + schema: None, + session_conf: None, + max_connections: None, + intervals_as_string: None, + complex_types_as_json: None, + } + } + + #[test] + fn default_mode_is_pat_and_requires_token() { + let mut o = base(); + // No authMode + no token → fail-fast InvalidArgument. + assert!(build_auth_config(&o).is_err()); + o.token = Some("dapi-xxx".to_owned()); + assert!(matches!( + build_auth_config(&o).unwrap(), + AuthConfig::Pat { .. } + )); + } + + #[test] + fn pat_rejects_empty_token() { + let mut o = base(); + o.auth_mode = Some(AuthMode::Pat); + o.token = Some(String::new()); + assert!(build_auth_config(&o).is_err()); + } + + #[test] + fn m2m_requires_client_id_and_secret() { + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthM2m); + assert!(build_auth_config(&o).is_err(), "missing both"); + o.oauth_client_id = Some("cid".to_owned()); + assert!(build_auth_config(&o).is_err(), "missing secret"); + o.oauth_client_secret = Some("sec".to_owned()); + o.oauth_scopes = Some(vec!["all-apis".to_owned()]); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthM2M { + client_id, + client_secret, + scopes, + .. + } => { + assert_eq!(client_id, "cid"); + assert_eq!(client_secret, "sec"); + assert_eq!(scopes, Some(vec!["all-apis".to_owned()])); + } + other => panic!("expected OAuthM2M, got {other:?}"), + } + } + + #[test] + fn u2m_fields_are_all_optional() { + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthU2m); + // Bare U2M: kernel fills databricks-cli / port 8020 / default scopes. + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { + client_id, + redirect_port, + .. + } => { + assert!(client_id.is_none()); + assert!(redirect_port.is_none()); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + // Explicit overrides thread through. + o.oauth_client_id = Some("custom-cli".to_owned()); + o.oauth_redirect_port = Some(9000); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { + client_id, + redirect_port, + .. + } => { + assert_eq!(client_id.as_deref(), Some("custom-cli")); + assert_eq!(redirect_port, Some(9000)); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } +} diff --git a/napi/src/error.rs b/napi/src/error.rs index afd5c3bc..70518fe3 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -185,26 +185,11 @@ fn status_from_kernel_code(code: ErrorCode) -> Status { /// versions because v0's `ErrorCode` is `#[non_exhaustive]` and we /// pattern-match exhaustively against the known set. fn error_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", - // Forward-compat: ErrorCode is `#[non_exhaustive]`. Any new - // variant the kernel adds in v0.x lands here until we mirror - // it in this match. The TS layer treats Unknown as a generic - // failure. - _ => "Unknown", - } + // Delegate to the kernel's single-source-of-truth slug map so the napi and + // pyo3 wire slugs can never drift. `ErrorCode` is `#[non_exhaustive]`, but + // `slug()` is defined in the kernel crate (exhaustive there), so any future + // variant is covered automatically without a wildcard here. + code.slug() } #[cfg(test)] diff --git a/napi/src/lib.rs b/napi/src/lib.rs index d1751a44..ec439879 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -43,6 +43,8 @@ pub(crate) mod connection; pub(crate) mod database; pub(crate) mod error; pub(crate) mod logger; +pub(crate) mod metadata; +pub(crate) mod params; pub(crate) mod result; pub(crate) mod runtime; pub(crate) mod statement; diff --git a/napi/src/metadata.rs b/napi/src/metadata.rs new file mode 100644 index 00000000..b216589e --- /dev/null +++ b/napi/src/metadata.rs @@ -0,0 +1,329 @@ +// 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 methods on `Connection` — napi-rs layer over the kernel's +//! flat `Metadata` API. +//! +//! Each method mirrors a `databricks_sql_kernel::Metadata` method +//! one-to-one and returns the same `Statement` type that +//! `executeStatement` returns, so the JS side can wrap any result in +//! `SeaOperationBackend` uniformly. The `Statement` is constructed via +//! `Statement::from_result_stream` — no parent kernel `Statement` is +//! involved (metadata calls don't use the mutable `Statement` path). +//! +//! Parameter mapping from JS strings to kernel newtypes follows the +//! pyo3 binding pattern: `Option` → `Option>` +//! or `Option>`, with runtime validation left to the +//! kernel. Rejected inputs surface as `InvalidArgument` via the +//! standard kernel-error envelope. +//! +//! ## `!Send` future workaround +//! +//! The kernel's `Metadata` methods hold a `tracing::EnteredSpan` +//! (`!Send`) across their internal `.await` points, making each +//! method's future `!Send`. napi-rs requires the top-level async fn +//! future to be `Send`. The fix: acquire the lock, clone a `Metadata` +//! handle (`Send + Sync` — wraps `Arc`), release the +//! lock, and then run the `!Send` kernel future inside +//! `tokio::task::spawn_blocking` via `Handle::block_on`. A blocking +//! thread is outside the tokio executor's scheduler, so `block_on` is +//! safe there and the `!Send` constraint does not propagate to the +//! enclosing `Send` async fn. +//! +//! ## Cancel on metadata `Statement`s +//! +//! Cancel is a no-op for metadata streams: the kernel has no +//! in-flight cancellation surface for metadata calls today. This is +//! documented on `Statement::cancel` and tracked as a kernel follow-up +//! for v1. + +use std::sync::Arc; + +use databricks_sql_kernel::{Identifier, LikePattern, Metadata, Result as KResult, ResultStream}; + +use crate::connection::Connection; +use crate::error::napi_err_from_kernel; +use crate::runtime::get_handle; +use crate::statement::Statement; +use crate::util::guarded; + +// ─── Conversion helpers ───────────────────────────────────────────────────── + +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() +} + +/// Run a `!Send` async kernel metadata operation on a blocking thread. +/// +/// `Metadata` itself is `Send + 'static` (wraps `Arc`). +/// The *futures* its methods return are `!Send` because they hold a +/// `tracing::EnteredSpan` across internal await points. Running them +/// inside `spawn_blocking` moves execution to a thread-pool thread +/// where `Handle::block_on` is safe and the `!Send` constraint doesn't +/// infect the enclosing napi async fn. +async fn run_on_blocking(f: F) -> napi::Result +where + F: FnOnce() -> Fut + Send + 'static, + Fut: std::future::Future>, +{ + // Capture the handle before entering spawn_blocking; get_handle() + // must be called from inside an async context (it snapshots + // Handle::current() on first call). + let handle = get_handle().clone(); + let stream = tokio::task::spawn_blocking(move || handle.block_on(f())) + .await + .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))? + .map_err(napi_err_from_kernel)?; + Ok(stream) +} + +/// Acquire the lock, return a `Metadata` handle, and release the lock. +async fn take_metadata( + inner: &Arc>>, +) -> napi::Result { + let guard = inner.lock().await; + let session = guard + .as_ref() + .ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, "connection already closed"))?; + Ok(session.metadata()) +} + +// ─── Metadata impls on Connection ─────────────────────────────────────────── + +#[napi] +impl Connection { + /// All catalogs visible to the session. + /// + /// JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + #[napi] + pub async fn list_catalogs(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { meta.list_catalogs().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Schemas filtered by catalog (exact) and schema name pattern. + /// + /// JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + #[napi] + pub async fn list_schemas( + &self, + catalog: Option, + schema_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { + let cat = opt_identifier(&catalog)?; + let pat = opt_pattern(&schema_pattern)?; + meta.list_schemas(cat, pat).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Tables filtered by catalog (exact), schema (pattern), table (pattern). + /// + /// JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + /// filters rows by `TABLE_TYPE` kernel-side. + /// + /// `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + /// NOT honour the table-type filter server-side; the kernel applies + /// it client-side after the result returns. Callers expecting + /// server-side rejection of off-type tables should not rely on this. + #[napi] + pub async fn list_tables( + &self, + catalog: Option, + schema_pattern: Option, + table_pattern: Option, + table_types: Option>, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { + 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(); + meta.list_tables(cat, sch, tbl, types_slice).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Columns of tables matching the filter. + /// + /// JDBC `getColumns` shape: 23 columns. + #[napi] + pub async fn list_columns( + &self, + catalog: Option, + schema_pattern: Option, + table_pattern: Option, + column_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let tbl = opt_pattern(&table_pattern)?; + let col = opt_pattern(&column_pattern)?; + meta.list_columns(cat, sch, tbl, col).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Functions visible to the session. `catalog` is exact; + /// `schemaPattern` and `functionPattern` are SQL LIKE. + #[napi] + pub async fn list_functions( + &self, + catalog: Option, + schema_pattern: Option, + function_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&function_pattern)?; + meta.functions(cat, sch, nam).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Procedures visible to the session. `catalog` is exact; + /// `schemaPattern` and `procedurePattern` are SQL LIKE. + #[napi] + pub async fn list_procedures( + &self, + catalog: Option, + schema_pattern: Option, + procedure_pattern: Option, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { + let cat = opt_identifier(&catalog)?; + let sch = opt_pattern(&schema_pattern)?; + let nam = opt_pattern(&procedure_pattern)?; + meta.procedures(cat, sch, nam).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + /// No wire call — static in-memory result. + #[napi] + pub async fn list_table_types(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { meta.table_types().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// SQL data types supported by the workspace. + /// No wire call — static in-memory result. + #[napi] + pub async fn list_type_info(&self) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { meta.type_info().await }).await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Primary keys for the given table. All three identifiers are + /// exact — ODBC `SQLPrimaryKeys` does not support patterns. + #[napi] + pub async fn get_primary_keys( + &self, + catalog: String, + schema: String, + table: String, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { + let cat = Some(Identifier::new(&catalog)?); + let sch = Some(Identifier::new(&schema)?); + let tbl = Identifier::new(&table)?; + meta.primary_keys(cat, sch, tbl).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } + + /// Foreign-key relationships. The foreign side must be fully + /// specified (catalog + schema + table); the parent side is + /// optional. All identifiers are exact — no LIKE patterns. + #[napi] + #[allow(clippy::too_many_arguments)] + pub async fn get_cross_reference( + &self, + parent_catalog: Option, + parent_schema: Option, + parent_table: Option, + foreign_catalog: String, + foreign_schema: String, + foreign_table: String, + ) -> napi::Result { + let meta = take_metadata(&self.inner).await?; + guarded(async move { + let stream = run_on_blocking(move || async move { + 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)?); + meta.foreign_keys(pc, ps, pt, fc, fs, ft).await + }) + .await?; + Ok(Statement::from_result_stream(stream)) + }) + .await + } +} diff --git a/napi/src/params.rs b/napi/src/params.rs new file mode 100644 index 00000000..9afa4c5b --- /dev/null +++ b/napi/src/params.rs @@ -0,0 +1,743 @@ +// 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. + +//! JS↔napi parameter codec — parses a connector-style +//! `{ type, value }` pair into a kernel `TypedValue`. +//! +//! Mirrors `pyo3/src/params.rs` line-for-line so the two bindings share +//! a single contract for what the kernel sees on the wire. The JS-side +//! `DBSQLParameter` already stringifies values before crossing the FFI +//! (see `lib/DBSQLParameter.ts::toSparkParameter` in the Node driver): +//! the napi binding takes the `(sql_type, value_str)` form directly to +//! avoid a per-call JS-value → Rust-value reflection trip. +//! +//! Compound types (`ARRAY` / `MAP` / `STRUCT`) and BINARY are +//! explicitly rejected — the SEA wire does not accept either as a bound +//! parameter today, and we surface that as an `InvalidArgument` error +//! at bind time so the failure mode matches pyo3's `NotSupportedError` +//! shape rather than an opaque server-side execute error. + +use chrono::{NaiveDate, NaiveDateTime}; +use databricks_sql_kernel::{Error, Result, TypedValue}; + +/// JS-visible binding for a single positional parameter. +/// +/// Shape mirrors the `TSparkParameter` wire object the Thrift backend +/// already emits via `DBSQLParameter.toSparkParameter()` — `type` is the +/// canonical Databricks SQL type name (`"INT"`, `"STRING"`, +/// `"DECIMAL(10,2)"`, ...), `value` is the string-encoded literal or +/// `None` for SQL NULL. +/// +/// Why a string for `value` instead of a tagged JS union: round-tripping +/// arbitrary JS values across the FFI requires either (a) a custom +/// napi `FromNapiValue` per arm, or (b) a `serde_json::Value`-style +/// dynamic dispatch on the Rust side. The Node-driver adapter already +/// stringifies before calling the binding (see `DBSQLParameter` and the +/// existing pyo3 wrapper), so the string-in / string-parsed contract +/// adds no JS-side complexity and keeps the kernel-side validation in +/// one place. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct TypedValueInput { + /// Canonical Databricks SQL type name. Case-insensitive for the + /// simple variants; for DECIMAL the parenthesised form + /// (`"DECIMAL(10,2)"`) is required so the kernel can extract + /// precision/scale. + pub sql_type: String, + /// String-encoded value. `None` always produces `TypedValue::Null` + /// regardless of `sql_type` — matches the connector's + /// `VoidParameter` shape and the pyo3 binding's contract. + pub value: Option, +} + +/// Parse a single `TypedValueInput` into a kernel `TypedValue`. +/// +/// Public for cross-module use within the crate (the future +/// `Connection::execute_statement` overload will call this for each +/// entry in `ExecuteOptions.positional_params`). +pub(crate) fn parse_typed_value(sql_type: &str, value_str: Option<&str>) -> Result { + let s = match value_str { + None => return Ok(TypedValue::Null), + Some(s) => s, + }; + + let upper = sql_type.to_ascii_uppercase(); + match upper.as_str() { + "VOID" => Ok(TypedValue::Null), + "BOOLEAN" | "BOOL" => parse_bool(s), + "TINYINT" => parse_i8(s), + "SMALLINT" => parse_i16(s), + "INT" | "INTEGER" => parse_i32(s), + "BIGINT" | "LONG" => parse_i64(s), + "FLOAT" => parse_f32(s), + "DOUBLE" => parse_f64(s), + "STRING" | "VARCHAR" | "CHAR" => Ok(TypedValue::String(s.to_owned())), + "BINARY" => Err(invalid( + "BINARY parameters are not supported by the SEA wire today", + )), + "DATE" => parse_date(s), + // TIMESTAMP / TIMESTAMP_NTZ share `parse_timestamp` for naive + // parsing; the NTZ arm re-wraps so the SEA wire payload emits + // the explicit type-name. TIMESTAMP_LTZ has its own parser since + // it carries a timezone offset. + "TIMESTAMP" => parse_timestamp(s), + "TIMESTAMP_NTZ" => parse_timestamp(s).map(|v| match v { + TypedValue::Timestamp(ts) => TypedValue::TimestampNtz(ts), + other => other, + }), + "TIMESTAMP_LTZ" => parse_timestamp_ltz(s), + "INTERVAL" => Ok(TypedValue::Interval(s.to_owned())), + // VARIANT — JSON text passes through verbatim. Same JSON-null + // vs SQL-NULL distinction as the pyo3 codec: `value=None` + // short-circuits to TypedValue::Null at the top of this + // function; `value=Some("null")` lands here as + // TypedValue::Variant("null") which is a JSON-null VARIANT + // value, not SQL NULL. + "VARIANT" => Ok(TypedValue::Variant(s.to_owned())), + _ if upper.starts_with("DECIMAL(") => parse_decimal(sql_type, s), + _ if is_compound_type_name(&upper) => Err(invalid( + "compound parameter types (ARRAY/MAP/STRUCT) are not yet supported", + )), + _ => Err(invalid_msg(format!( + "unsupported parameter SQL type: {sql_type:?}" + ))), + } +} + +/// True iff `upper` is one of ARRAY/MAP/STRUCT exactly, or one of +/// those followed by `<` (generic) or `(` (function-style). Tighter +/// than a `starts_with("ARRAY")` test, which would also match unrelated +/// names like `ARRAYBUFFER` or `STRUCTURE`. +fn is_compound_type_name(upper: &str) -> bool { + for prefix in ["ARRAY", "MAP", "STRUCT"] { + if upper == prefix { + return true; + } + if let Some(rest) = upper.strip_prefix(prefix) { + if rest.starts_with('<') || rest.starts_with('(') { + return true; + } + } + } + false +} + +fn invalid(msg: &'static str) -> Error { + Error::invalid_argument().message(msg) +} + +fn invalid_msg(msg: String) -> Error { + Error::invalid_argument().message(msg) +} + +fn parse_bool(s: &str) -> Result { + match s.to_ascii_lowercase().as_str() { + "true" | "1" => Ok(TypedValue::Bool(true)), + "false" | "0" => Ok(TypedValue::Bool(false)), + _ => Err(invalid_msg(format!("invalid BOOLEAN literal: {s:?}"))), + } +} + +fn parse_i8(s: &str) -> Result { + s.parse::() + .map(TypedValue::Int8) + .map_err(|e| invalid_msg(format!("invalid TINYINT literal {s:?}: {e}"))) +} + +fn parse_i16(s: &str) -> Result { + s.parse::() + .map(TypedValue::Int16) + .map_err(|e| invalid_msg(format!("invalid SMALLINT literal {s:?}: {e}"))) +} + +fn parse_i32(s: &str) -> Result { + s.parse::() + .map(TypedValue::Int32) + .map_err(|e| invalid_msg(format!("invalid INT literal {s:?}: {e}"))) +} + +fn parse_i64(s: &str) -> Result { + s.parse::() + .map(TypedValue::Int64) + .map_err(|e| invalid_msg(format!("invalid BIGINT literal {s:?}: {e}"))) +} + +fn parse_f32(s: &str) -> Result { + let v = s + .parse::() + .map_err(|e| invalid_msg(format!("invalid FLOAT literal {s:?}: {e}")))?; + if !v.is_finite() { + return Err(invalid_msg(format!("non-finite FLOAT literal {s:?}"))); + } + Ok(TypedValue::Float32(v)) +} + +fn parse_f64(s: &str) -> Result { + let v = s + .parse::() + .map_err(|e| invalid_msg(format!("invalid DOUBLE literal {s:?}: {e}")))?; + if !v.is_finite() { + return Err(invalid_msg(format!("non-finite DOUBLE literal {s:?}"))); + } + Ok(TypedValue::Float64(v)) +} + +fn parse_date(s: &str) -> Result { + NaiveDate::parse_from_str(s, "%Y-%m-%d") + .map(TypedValue::Date) + .map_err(|e| invalid_msg(format!("invalid DATE literal {s:?}: {e}"))) +} + +fn parse_timestamp(s: &str) -> Result { + // JS's `Date.prototype.toISOString()` always emits a trailing `Z`; + // strip it before parsing since `TypedValue::Timestamp` is a naive + // `NaiveDateTime` (the SEA wire encodes timestamps in UTC). + let body = s.strip_suffix('Z').unwrap_or(s); + let formats = [ + "%Y-%m-%d %H:%M:%S%.f", + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%dT%H:%M:%S%.f", + "%Y-%m-%dT%H:%M:%S", + ]; + for fmt in formats { + if let Ok(ts) = NaiveDateTime::parse_from_str(body, fmt) { + return Ok(TypedValue::Timestamp(ts)); + } + } + Err(invalid_msg(format!("invalid TIMESTAMP literal {s:?}"))) +} + +fn parse_timestamp_ltz(s: &str) -> Result { + use chrono::{DateTime, FixedOffset, Utc}; + + if let Ok(dt) = DateTime::::parse_from_rfc3339(s) { + return Ok(TypedValue::TimestampLtz(dt.with_timezone(&Utc))); + } + if let Ok(dt) = DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f%:z") { + return Ok(TypedValue::TimestampLtz(dt.with_timezone(&Utc))); + } + let body = s.strip_suffix('Z').unwrap_or(s); + let formats = [ + "%Y-%m-%d %H:%M:%S%.f", + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%dT%H:%M:%S%.f", + "%Y-%m-%dT%H:%M:%S", + ]; + for fmt in formats { + if let Ok(naive) = NaiveDateTime::parse_from_str(body, fmt) { + return Ok(TypedValue::TimestampLtz( + DateTime::::from_naive_utc_and_offset(naive, Utc), + )); + } + } + Err(invalid_msg(format!("invalid TIMESTAMP_LTZ literal {s:?}"))) +} + +fn parse_decimal(sql_type: &str, value: &str) -> Result { + let (precision, scale) = extract_decimal_precision_scale(sql_type)?; + validate_decimal_literal(value)?; + Ok(TypedValue::Decimal { + value: value.to_owned(), + precision, + scale, + }) +} + +/// Reject DECIMAL value strings that don't represent a finite number. +/// Accepts an optional sign followed by an integer part (digits) and, +/// optionally, a dot and a fractional part — but requires at least one +/// digit on each side of the dot when a dot is present. Forms like +/// `42.`, `.5` and the bare sign `-` are rejected to match Databricks' +/// DECIMAL literal parser. Scientific notation (`1e5`) is disallowed +/// because it changes the implicit precision/scale and the connector +/// never emits it. +fn validate_decimal_literal(value: &str) -> Result<()> { + let bytes = value.as_bytes(); + if bytes.is_empty() { + return Err(invalid_msg(format!("invalid DECIMAL literal {value:?}"))); + } + let mut i = 0; + if matches!(bytes[i], b'+' | b'-') { + i += 1; + } + let int_start = i; + while i < bytes.len() && bytes[i].is_ascii_digit() { + i += 1; + } + let int_digits = i - int_start; + let mut has_dot = false; + let mut frac_digits = 0; + if i < bytes.len() && bytes[i] == b'.' { + has_dot = true; + i += 1; + let frac_start = i; + while i < bytes.len() && bytes[i].is_ascii_digit() { + i += 1; + } + frac_digits = i - frac_start; + } + let well_formed = i == bytes.len() && int_digits >= 1 && (!has_dot || frac_digits >= 1); + if !well_formed { + return Err(invalid_msg(format!("invalid DECIMAL literal {value:?}"))); + } + Ok(()) +} + +fn extract_decimal_precision_scale(sql_type: &str) -> Result<(u8, i8)> { + let lparen = sql_type.find('(').ok_or_else(|| { + invalid_msg(format!( + "DECIMAL type missing precision/scale: {sql_type:?}" + )) + })?; + let rparen = sql_type + .rfind(')') + .ok_or_else(|| invalid_msg(format!("DECIMAL type missing closing paren: {sql_type:?}")))?; + if rparen <= lparen { + return Err(invalid_msg(format!( + "DECIMAL type has malformed parens: {sql_type:?}" + ))); + } + let inner = &sql_type[lparen + 1..rparen]; + let parts: Vec<&str> = inner.split(',').map(|p| p.trim()).collect(); + let (precision_str, scale_str) = match parts.as_slice() { + [p] => (*p, "0"), + [p, s] => (*p, *s), + _ => { + return Err(invalid_msg(format!( + "DECIMAL type must have one or two parameters: {sql_type:?}" + ))); + } + }; + let precision = precision_str + .parse::() + .map_err(|e| invalid_msg(format!("invalid DECIMAL precision {sql_type:?}: {e}")))?; + let scale = scale_str + .parse::() + .map_err(|e| invalid_msg(format!("invalid DECIMAL scale {sql_type:?}: {e}")))?; + // Kernel-side bind constraint, intentionally tighter than the + // Databricks server spec. Mirrors pyo3 — see `pyo3/src/params.rs` + // for the rationale. + if !(1..=38).contains(&precision) { + return Err(invalid_msg(format!( + "DECIMAL precision must be in 1..=38: {sql_type:?}" + ))); + } + if scale < 0 || (scale as i16) > (precision as i16) { + return Err(invalid_msg(format!( + "DECIMAL scale must be in 0..=precision: {sql_type:?}" + ))); + } + Ok((precision, scale)) +} + +#[cfg(test)] +mod tests { + use super::*; + use databricks_sql_kernel::ErrorCode; + + // ─── Basic-type unit tests ────────────────────────────────────── + // + // These mirror the pyo3 codec's tests so a future maintainer who + // changes one binding's contract sees the other binding's test + // fail. The 10-type matrix corresponds to the C5 cluster — see + // `sea-workflow/decisions/2026-05-28-autonomous-parity-decisions.md` + // row 2.5-2.10 / 3.18-3.22. + + #[test] + fn none_value_is_null() { + assert!(matches!( + parse_typed_value("INT", None).unwrap(), + TypedValue::Null + )); + assert!(matches!( + parse_typed_value("STRING", None).unwrap(), + TypedValue::Null + )); + // Even a bad SQL type is fine when value is None — VOID-style. + assert!(matches!( + parse_typed_value("NOPE", None).unwrap(), + TypedValue::Null + )); + } + + #[test] + fn void_type_is_null() { + assert!(matches!( + parse_typed_value("VOID", Some("anything")).unwrap(), + TypedValue::Null + )); + } + + #[test] + fn boolean_parses_truthy_falsey() { + assert!(matches!( + parse_typed_value("BOOLEAN", Some("true")).unwrap(), + TypedValue::Bool(true) + )); + assert!(matches!( + parse_typed_value("BOOLEAN", Some("False")).unwrap(), + TypedValue::Bool(false) + )); + assert!(matches!( + parse_typed_value("BOOL", Some("1")).unwrap(), + TypedValue::Bool(true) + )); + let e = parse_typed_value("BOOLEAN", Some("yes")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn integer_types_parse() { + assert!(matches!( + parse_typed_value("TINYINT", Some("127")).unwrap(), + TypedValue::Int8(127) + )); + assert!(matches!( + parse_typed_value("SMALLINT", Some("-100")).unwrap(), + TypedValue::Int16(-100) + )); + assert!(matches!( + parse_typed_value("INT", Some("42")).unwrap(), + TypedValue::Int32(42) + )); + assert!(matches!( + parse_typed_value("INTEGER", Some("-42")).unwrap(), + TypedValue::Int32(-42) + )); + assert!(matches!( + parse_typed_value("BIGINT", Some("9999999999")).unwrap(), + TypedValue::Int64(9999999999) + )); + assert!(matches!( + parse_typed_value("LONG", Some("9999999999")).unwrap(), + TypedValue::Int64(9999999999) + )); + } + + #[test] + fn out_of_range_int_errors() { + let e = parse_typed_value("TINYINT", Some("300")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + let e = parse_typed_value("INT", Some("9999999999")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn floats_parse() { + assert!(matches!( + parse_typed_value("FLOAT", Some("3.14")).unwrap(), + TypedValue::Float32(_) + )); + assert!(matches!( + parse_typed_value("DOUBLE", Some("2.718281828459045")).unwrap(), + TypedValue::Float64(_) + )); + } + + #[test] + fn float_overflow_and_nan_rejected() { + for s in ["1e500", "-1e500", "nan", "NaN", "inf", "-Infinity"] { + let e = parse_typed_value("FLOAT", Some(s)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "FLOAT {s:?}"); + let e = parse_typed_value("DOUBLE", Some(s)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "DOUBLE {s:?}"); + } + } + + #[test] + fn string_passes_through() { + match parse_typed_value("STRING", Some("hello world")).unwrap() { + TypedValue::String(s) => assert_eq!(s, "hello world"), + other => panic!("expected String, got {other:?}"), + } + assert!(matches!( + parse_typed_value("VARCHAR", Some("x")).unwrap(), + TypedValue::String(_) + )); + assert!(matches!( + parse_typed_value("CHAR", Some("y")).unwrap(), + TypedValue::String(_) + )); + } + + #[test] + fn string_preserves_embedded_quotes() { + // SEA wire-level escaping is the server's job; the codec must + // not transform a string with an embedded single quote. + match parse_typed_value("STRING", Some("test'quote")).unwrap() { + TypedValue::String(s) => assert_eq!(s, "test'quote"), + other => panic!("expected String, got {other:?}"), + } + } + + #[test] + fn date_parses_iso() { + let v = parse_typed_value("DATE", Some("2026-05-15")).unwrap(); + match v { + TypedValue::Date(d) => { + assert_eq!(d, NaiveDate::from_ymd_opt(2026, 5, 15).unwrap()) + } + other => panic!("expected Date, got {other:?}"), + } + let e = parse_typed_value("DATE", Some("not-a-date")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn timestamp_parses_naive_and_iso() { + let a = parse_typed_value("TIMESTAMP", Some("2026-05-15 12:30:45")).unwrap(); + assert!(matches!(a, TypedValue::Timestamp(_))); + let b = parse_typed_value("TIMESTAMP", Some("2026-05-15 12:30:45.123456")).unwrap(); + assert!(matches!(b, TypedValue::Timestamp(_))); + let c = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45")).unwrap(); + assert!(matches!(c, TypedValue::Timestamp(_))); + } + + #[test] + fn timestamp_accepts_trailing_z() { + // JS's `Date.prototype.toISOString()` always emits the trailing + // `Z`. Confirms the strip is in place. + let v = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45.123Z")).unwrap(); + assert!(matches!(v, TypedValue::Timestamp(_))); + let v = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45Z")).unwrap(); + assert!(matches!(v, TypedValue::Timestamp(_))); + } + + #[test] + fn decimal_extracts_precision_and_scale() { + let v = parse_typed_value("DECIMAL(10,2)", Some("-123.45")).unwrap(); + match v { + TypedValue::Decimal { + value, + precision, + scale, + } => { + assert_eq!(value, "-123.45"); + assert_eq!(precision, 10); + assert_eq!(scale, 2); + } + other => panic!("expected Decimal, got {other:?}"), + } + // Spaces between p and s. + let v = parse_typed_value("DECIMAL(8, 4)", Some("0.0001")).unwrap(); + match v { + TypedValue::Decimal { + precision, scale, .. + } => { + assert_eq!((precision, scale), (8, 4)); + } + other => panic!("expected Decimal, got {other:?}"), + } + } + + #[test] + fn decimal_without_precision_errors() { + let e = parse_typed_value("DECIMAL", Some("1.0")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn decimal_single_arg_defaults_scale_to_zero() { + match parse_typed_value("DECIMAL(38)", Some("123456789")).unwrap() { + TypedValue::Decimal { + precision, scale, .. + } => assert_eq!((precision, scale), (38, 0)), + other => panic!("expected Decimal, got {other:?}"), + } + } + + #[test] + fn decimal_rejects_bad_value_literal() { + let e = parse_typed_value("DECIMAL(10,2)", Some("not-a-number")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + assert!(e.message.contains("DECIMAL"), "{}", e.message); + } + + #[test] + fn decimal_rejects_partial_dot_forms() { + for v in ["42.", ".5", "-.5", "+.", "-", "+", "."] { + let e = parse_typed_value("DECIMAL(10,4)", Some(v)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{v:?}"); + } + } + + #[test] + fn decimal_rejects_out_of_bound_precision_and_scale() { + for ty in [ + "DECIMAL(0,0)", + "DECIMAL(39,0)", + "DECIMAL(10,11)", + "DECIMAL(10,-1)", + ] { + let e = parse_typed_value(ty, Some("1.0")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{ty}"); + } + } + + #[test] + fn binary_is_rejected() { + // BINARY is documented kernel-side as unsupported on the SEA + // wire today; the Node-side adapter must use `unhex(?)` as a + // workaround. The error message must contain "BINARY" so the + // adapter's reviver can distinguish this from an arbitrary + // bind failure. + let e = parse_typed_value("BINARY", Some("cafe")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + assert!(e.message.contains("BINARY"), "{}", e.message); + } + + #[test] + fn compound_types_are_rejected() { + for ty in ["ARRAY", "ARRAY", "MAP", "STRUCT"] { + let e = parse_typed_value(ty, Some("x")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{ty}"); + assert!(e.message.contains("compound"), "{ty}: {}", e.message); + } + } + + #[test] + fn compound_match_does_not_overreach() { + // ARRAYBUFFER / MAPLE / STRUCTURE fall through to the generic + // "unsupported parameter SQL type" message — they're not + // compound types and not real Databricks types. + for ty in ["ARRAYBUFFER", "MAPLE", "STRUCTURE"] { + let e = parse_typed_value(ty, Some("x")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{ty}"); + assert!( + e.message.contains("unsupported"), + "{ty} should fall through, got {}", + e.message + ); + } + } + + #[test] + fn lowercase_sql_type_works() { + // DBSQLParameterType.* enum uppercases, but accept lowercase + // for robustness against direct napi callers. + assert!(matches!( + parse_typed_value("int", Some("1")).unwrap(), + TypedValue::Int32(1) + )); + assert!(matches!( + parse_typed_value("decimal(5,2)", Some("1.23")).unwrap(), + TypedValue::Decimal { .. } + )); + } + + #[test] + fn unknown_type_errors() { + let e = parse_typed_value("MAGIC", Some("x")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn timestamp_ntz_maps_to_distinct_variant() { + let v = parse_typed_value("TIMESTAMP_NTZ", Some("2026-05-15 12:30:45")).unwrap(); + assert!(matches!(v, TypedValue::TimestampNtz(_))); + } + + #[test] + fn timestamp_ltz_parses_naive_offset_and_z_forms() { + let v = parse_typed_value("TIMESTAMP_LTZ", Some("2026-05-15 12:30:45")).unwrap(); + let TypedValue::TimestampLtz(dt) = v else { + panic!("expected TimestampLtz"); + }; + assert_eq!( + dt.format("%Y-%m-%dT%H:%M:%SZ").to_string(), + "2026-05-15T12:30:45Z" + ); + let v = parse_typed_value("TIMESTAMP_LTZ", Some("2026-05-15T18:00:00+05:30")).unwrap(); + let TypedValue::TimestampLtz(dt) = v else { + panic!("expected TimestampLtz"); + }; + assert_eq!(dt.format("%H:%M").to_string(), "12:30"); + } + + #[test] + fn variant_passes_json_text_through() { + let json = r#"{"k":1,"nested":{"a":[true,null]}}"#; + match parse_typed_value("VARIANT", Some(json)).unwrap() { + TypedValue::Variant(s) => assert_eq!(s, json), + other => panic!("expected Variant, got {other:?}"), + } + } + + #[test] + fn interval_passes_through() { + match parse_typed_value("INTERVAL", Some("INTERVAL '1' DAY")).unwrap() { + TypedValue::Interval(s) => assert_eq!(s, "INTERVAL '1' DAY"), + other => panic!("expected Interval, got {other:?}"), + } + } + + // ─── 10-type matrix coverage check ────────────────────────────── + // + // The C5 cluster's headline contract is that all 10 basic types + // surface via this codec. This test exercises each one with a + // representative value that mirrors what the Node adapter will + // send today. + + #[test] + fn c5_ten_type_matrix_round_trips() { + // (sql_type, value_str, predicate-on-the-decoded-TypedValue) + // BINARY is intentionally NOT in the round-trip list — see + // binary_is_rejected above for the documented contract. + type MatrixCase = (&'static str, &'static str, fn(&TypedValue) -> bool); + let cases: &[MatrixCase] = &[ + ("INT", "42", |v| matches!(v, TypedValue::Int32(42))), + ("BIGINT", "9999999999", |v| { + matches!(v, TypedValue::Int64(9999999999)) + }), + ("FLOAT", "3.14", |v| matches!(v, TypedValue::Float32(_))), + ("DOUBLE", "2.718281828459045", |v| { + matches!(v, TypedValue::Float64(_)) + }), + ( + "STRING", + "hello world", + |v| matches!(v, TypedValue::String(s) if s == "hello world"), + ), + ("BOOLEAN", "true", |v| matches!(v, TypedValue::Bool(true))), + ("DATE", "2026-05-15", |v| matches!(v, TypedValue::Date(_))), + ("TIMESTAMP", "2026-05-15 12:30:45", |v| { + matches!(v, TypedValue::Timestamp(_)) + }), + ("DECIMAL(10,2)", "-123.45", |v| { + matches!( + v, + TypedValue::Decimal { + precision: 10, + scale: 2, + .. + } + ) + }), + ]; + for (sql_type, value, pred) in cases { + let got = parse_typed_value(sql_type, Some(value)) + .unwrap_or_else(|e| panic!("{sql_type} {value:?} should parse: {e:?}")); + assert!( + pred(&got), + "{sql_type} {value:?} decoded to unexpected variant: {got:?}" + ); + } + // BINARY — pin the contract: bind-time InvalidArgument. + let e = parse_typed_value("BINARY", Some("cafe")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } +} diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 84c734e2..9d825e37 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -36,7 +36,7 @@ use tokio::sync::Mutex; use arrow_ipc::writer::StreamWriter; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ - Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, + Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, ResultStream, Statement as KernelStatement, }; @@ -70,6 +70,30 @@ struct StatementInner { executed: ExecutedStatement, } +/// Discriminated inner state for `Statement`. +enum AnyInner { + /// Produced by `Connection::execute_statement`. Boxed to keep the + /// enum size close to the `Metadata` variant (StatementInner is + /// large; ResultStream is much smaller). + Executed(Box), + /// Produced by metadata methods — wraps a bare `ResultStream`. + Metadata(ResultStream), +} + +impl AnyInner { + /// Borrow the underlying result stream regardless of variant. The + /// executed-statement variant delegates to its + /// `ExecutedStatement::result_stream_mut`; the metadata variant + /// returns the bare `ResultStream` directly. Used by + /// `fetch_next_batch` to share one streaming path across both. + fn result_stream_mut(&mut self) -> &mut ResultStream { + match self { + AnyInner::Executed(s) => s.executed.result_stream_mut(), + AnyInner::Metadata(rs) => rs, + } + } +} + /// Opaque executed-statement handle. /// /// **Current concurrency shape** — every method takes `inner.lock()` @@ -88,21 +112,31 @@ struct StatementInner { /// disposed statement can still read them. #[napi] pub struct Statement { - /// Wraps the kernel `Statement` + `ExecutedStatement` pair so the - /// parent's `Drop` doesn't fire (and invalidate the executed - /// handle via the shared `ValidityFlag`) while JS still holds - /// this wrapper. See `StatementInner` docs above. - inner: Arc>>, + /// Discriminated inner state: the `Executed` variant wraps the + /// kernel `Statement` + `ExecutedStatement` pair (the parent kept + /// alive to prevent its `Drop` from invalidating the executed + /// handle via the shared `ValidityFlag`); the `Metadata` variant + /// wraps a bare `ResultStream` produced by `Metadata::list_*` / + /// `primary_keys` / `foreign_keys` / `type_info` / `table_types`. + inner: Arc>>, /// Schema captured at construction. Available even after `close()`. + /// For the `Executed` variant this is the executed handle's + /// schema; for the `Metadata` variant it's the result-stream's + /// schema. Either way, cached so JS callers can build error + /// reports against a disposed statement. schema: SchemaRef, - /// Server-issued id. Available even after `close()` for log - /// correlation. + /// Server-issued statement id. Populated for the `Executed` + /// variant; empty string for the `Metadata` variant (the kernel + /// does not emit a statement id for SHOW/information_schema + /// queries driven through `Metadata`). statement_id: String, /// Set to `true` when `fetchNextBatch` observes the natural end of /// the stream (`None`). `cancel()` short-circuits to `Ok(())` when /// this is set, matching the JDBC `Statement.cancel()` no-op-after- /// completion contract — without it, a defensive cancel after the /// stream is drained surfaces an opaque server-side error. + /// (Irrelevant for the `Metadata` variant where cancel is already + /// a no-op kernel-side; harmless to carry the field regardless.) finished: Arc, } @@ -119,15 +153,37 @@ impl Statement { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); Self { - inner: Arc::new(Mutex::new(Some(StatementInner { - _parent: parent, - executed, - }))), + inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( + StatementInner { + _parent: parent, + executed, + }, + ))))), schema, statement_id, finished: Arc::new(AtomicBool::new(false)), } } + + /// Crate-internal constructor for metadata calls. Wraps a bare + /// `ResultStream` returned by `Metadata::list_*` / `primary_keys` / + /// `foreign_keys` / `type_info` / `table_types`. Cancel is a no-op + /// for metadata streams (the kernel has no in-flight cancellation + /// surface for them); close just drops the stream. + /// + /// `schema` is captured from the stream so the `schema()` getter + /// works after close. `statement_id` is empty (kernel does not + /// emit one for metadata queries). `finished` defaults false and + /// is unread on this path (cancel is already a no-op). + pub(crate) fn from_result_stream(stream: ResultStream) -> Self { + let schema = stream.schema(); + Self { + inner: Arc::new(Mutex::new(Some(AnyInner::Metadata(stream)))), + schema, + statement_id: String::new(), + finished: Arc::new(AtomicBool::new(false)), + } + } } #[napi] @@ -261,9 +317,14 @@ impl Statement { guarded(async move { let mut guard = inner.lock().await; let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?; - let executed = &mut inner_state.executed; - - let stream = executed.result_stream_mut(); + // `result_stream_mut` returns `&mut ResultStream` for both + // variants — the executed-path borrows from its + // `ExecutedStatement`, the metadata-path borrows from its + // bare `ResultStream`. The IPC schema header serialised + // into every batch payload comes from the cached + // `self.schema` captured outside the lock (see method + // start), so no need to re-fetch from the stream. + let stream = inner_state.result_stream_mut(); let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; let Some(batch) = maybe_batch else { // End of stream — record so a defensive cancel after @@ -329,11 +390,15 @@ impl Statement { /// Server-side cancel. /// - /// Short-circuits to `Ok(())` if `fetchNextBatch` has already - /// returned `null` (stream naturally exhausted) — matches the - /// JDBC `Statement.cancel()` no-op-after-completion contract, so - /// JS callers can fire cancel defensively without distinguishing - /// "real cancel" from "raced with natural completion." + /// For executed statements: short-circuits to `Ok(())` if + /// `fetchNextBatch` has already returned `null` (stream + /// naturally exhausted) — matches the JDBC `Statement.cancel()` + /// no-op-after-completion contract, so JS callers can fire cancel + /// defensively without distinguishing "real cancel" from "raced + /// with natural completion." + /// + /// For metadata streams: no-op (the kernel has no in-flight + /// cancellation surface for metadata calls today). /// /// Returns `KernelError(InvalidStatementHandle)` if the statement /// has been explicitly `close()`d. @@ -344,20 +409,32 @@ impl Statement { return Ok(()); } let inner = Arc::clone(&self.inner); + let finished = Arc::clone(&self.finished); guarded(async move { let guard = inner.lock().await; + // Re-check `finished` after acquiring the lock to close the + // fetch-vs-cancel TOCTOU: a concurrent `fetch_next_batch` may have + // drained to completion and set `finished` while this cancel was + // queued on the mutex. Without the re-check we'd dispatch a + // `CancelStatement` against an already-terminal statement (a + // redundant, wire-benign-but-wasteful RPC). + if finished.load(Ordering::Acquire) { + return Ok(()); + } let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - inner_state - .executed - .cancel() - .await - .map_err(napi_err_from_kernel) + match inner_state { + AnyInner::Executed(s) => s.executed.cancel().await.map_err(napi_err_from_kernel), + // Metadata streams have no server-side cancel handle. + AnyInner::Metadata(_) => Ok(()), + } }) .await } - /// Explicit close. Awaits the server-side `CloseStatement` so the - /// JS caller can observe failures (auth revoked mid-session, + /// Explicit close. + /// + /// For executed statements: awaits the server-side `CloseStatement` + /// so the JS caller can observe failures (auth revoked mid-session, /// network error, server-side error). Idempotent — a second call /// on an already-closed statement returns `Ok`. /// @@ -373,26 +450,27 @@ impl Statement { /// runtime. The JS caller can log the error but cannot drive a /// further retry. If you need retry-on-failure semantics for /// `CloseStatement`, layer them above this method. + /// + /// For metadata streams: drops the stream (no server round-trip + /// needed — metadata results have no in-flight server-side + /// resource to release). #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); guarded(async move { // Take the inner state out so `Drop` knows there's nothing - // left to clean up. The parent kernel `Statement`'s Drop - // runs here too — but only AFTER the executed handle's - // close has finished, so we still observe a clean - // server-side close result before the validity flag flips. + // left to clean up. let inner_state = { let mut guard = inner.lock().await; guard.take() }; - if let Some(inner_state) = inner_state { - inner_state - .executed - .close() - .await - .map_err(napi_err_from_kernel)?; - // _parent drops here, after close has resolved. + match inner_state { + Some(AnyInner::Executed(s)) => { + s.executed.close().await.map_err(napi_err_from_kernel)?; + // _parent drops here, after close has resolved. + } + // Metadata stream: just drop it. + Some(AnyInner::Metadata(_)) | None => {} } Ok(()) }) @@ -624,4 +702,18 @@ mod tests { stmt.finished.store(true, Ordering::Release); assert!(stmt.finished.load(Ordering::Acquire)); } + + #[tokio::test] + async fn cancel_short_circuits_when_finished_even_on_closed_inner() { + // `finished = true` must short-circuit cancel to Ok(()) BEFORE the + // closed-state check — so a cancel racing a just-completed fetch is a + // no-op, not a CancelStatement RPC (and not a closed-handle error). + let stmt = Statement { + inner: Arc::new(Mutex::new(None)), // closed + schema: make_schema(), + statement_id: "x".to_owned(), + finished: Arc::new(AtomicBool::new(true)), + }; + assert!(stmt.cancel().await.is_ok()); + } } diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 874e52d6..60b4d0f2 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -42,22 +42,9 @@ create_exception!(databricks_sql_kernel, KernelError, PyException); /// `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", - } + // Delegate to the kernel's single-source-of-truth slug map (shared with + // the napi binding) so the wire slugs can never drift across bindings. + code.slug() } /// Common attribute-set used by both `to_py_err` (kernel error diff --git a/src/client/http.rs b/src/client/http.rs index da714288..e17b05a3 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -341,6 +341,18 @@ impl DatabricksHttpClient { ); } + if let Some(ref pem) = config.tls.trusted_certificate_pem { + let cert = reqwest::Certificate::from_pem(pem).map_err(|e| { + Error::invalid_argument() + .message(format!("Invalid in-memory PEM certificate: {}", e)) + })?; + builder = builder.add_root_certificate(cert); + debug!( + "Added custom CA certificate from in-memory bytes ({} bytes)", + pem.len() + ); + } + // Apply proxy configuration if let Some(ref proxy_url) = config.proxy.url { // Validate proxy URL scheme @@ -1064,6 +1076,91 @@ lGrv15pBcePj ); } + #[test] + fn test_http_client_with_in_memory_pem_bytes() { + // Public-API path: PEM bytes pass through the internal + // `trusted_certificate_pem` field directly (no tempfile shim + // required by foreign-language wrappers). + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(TEST_CA_CERT_PEM.as_bytes().to_vec()); + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!(client.is_ok()); + } + + #[test] + fn test_tls_config_from_public_maps_all_fields() { + // accept_self_signed=true maps to Some(true); + // skip_hostname_verification=true maps to Some(true); + // custom_ca_cert maps to trusted_certificate_pem. + let public = crate::config::TlsConfig { + custom_ca_cert: Some(b"pem-bytes".to_vec()), + accept_self_signed: true, + skip_hostname_verification: true, + }; + let internal = TlsConfig::from_public(&public); + assert_eq!(internal.allow_self_signed, Some(true)); + assert_eq!(internal.allow_hostname_mismatch, Some(true)); + assert_eq!( + internal.trusted_certificate_pem, + Some(b"pem-bytes".to_vec()) + ); + // `enabled` and `trusted_certificate_path` stay at internal + // defaults — the public surface doesn't expose them. + assert!(internal.enabled.is_none()); + assert!(internal.trusted_certificate_path.is_none()); + } + + #[test] + fn test_tls_config_from_public_default_is_strict() { + // A default public TlsConfig produces an internal config that + // does NOT relax any default — `None` everywhere on the + // permissive switches so log output stays clean. + let internal = TlsConfig::from_public(&crate::config::TlsConfig::default()); + assert!(internal.allow_self_signed.is_none()); + assert!(internal.allow_hostname_mismatch.is_none()); + assert!(internal.trusted_certificate_pem.is_none()); + assert!(internal.trusted_certificate_path.is_none()); + } + + #[test] + fn test_http_client_via_public_tls_config_with_self_signed_accepts_build() { + // End-to-end builder check: a Session-style construction + // (public TlsConfig -> from_public -> HttpClientConfig -> + // reqwest builder) succeeds when accept_self_signed is set. + let public = crate::config::TlsConfig { + custom_ca_cert: None, + accept_self_signed: true, + skip_hostname_verification: false, + }; + let config = HttpClientConfig { + tls: TlsConfig::from_public(&public), + ..HttpClientConfig::default() + }; + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!( + client.is_ok(), + "reqwest client construction should succeed when accept_self_signed=true is set" + ); + } + + #[test] + fn test_http_client_via_public_tls_config_with_custom_ca_accepts_build() { + let public = crate::config::TlsConfig { + custom_ca_cert: Some(TEST_CA_CERT_PEM.as_bytes().to_vec()), + accept_self_signed: false, + skip_hostname_verification: false, + }; + let config = HttpClientConfig { + tls: TlsConfig::from_public(&public), + ..HttpClientConfig::default() + }; + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!( + client.is_ok(), + "reqwest client construction should succeed when custom_ca_cert is set with a valid PEM" + ); + } + #[test] fn test_proxy_config_debug_redacts_password() { let config = ProxyConfig { diff --git a/src/config.rs b/src/config.rs index 1397fcf5..f08651d1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -322,7 +322,13 @@ pub struct HttpConfig { /// Maximum total time across retries for a single logical RPC. pub overall_timeout: Duration, - /// Connection pool size. + /// Connection pool size (max idle warm sockets per remote host). + /// + /// Defaults to `100`, matching the JDBC driver's `HttpConnectionPoolSize` + /// default. Raise this for workloads that burst many concurrent + /// `executeStatement` calls or CloudFetch chunk downloads against a + /// single host; too low a value forces fresh TLS handshakes when the + /// pool fills. pub pool_max_idle_per_host: usize, } @@ -331,7 +337,7 @@ impl Default for HttpConfig { Self { request_timeout: Duration::from_secs(120), overall_timeout: Duration::from_secs(900), - pool_max_idle_per_host: 10, + pool_max_idle_per_host: 100, } } } diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 2a07e2d0..f348bc32 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -133,6 +133,30 @@ pub enum ErrorCode { SqlError, } +impl ErrorCode { + /// Stable string slug for cross-binding wire formats. Single source of + /// truth shared by the pyo3 (`code_str`) and napi (`error_code_str`) + /// bindings — keeping the mapping here makes drift across bindings + /// structurally impossible. + pub fn slug(&self) -> &'static str { + match self { + 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", + } + } +} + /// Typed kernel error. /// /// `cause` chains preserve the underlying provenance — a `SqlError` diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index cca8ea02..c15f0b6e 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -134,6 +134,8 @@ impl<'a> Identifier<'a> { /// Rejects: /// - Empty string — meaningless as an identifier; almost always a /// bug at the wrapper layer. + /// - Strings consisting only of whitespace — would backtick-escape + /// to a blank token and produce a server-side parse error. /// - Embedded NUL bytes (`\0`) — would terminate the string at the /// first FFI / C ABI boundary and silently truncate the /// identifier in transit. @@ -148,6 +150,9 @@ impl<'a> Identifier<'a> { if s.is_empty() { return Err(Error::invalid_argument().message("identifier must not be empty")); } + if s.trim().is_empty() { + return Err(Error::invalid_argument().message("identifier must not be all whitespace")); + } if s.len() > MAX_IDENTIFIER_BYTES { return Err(Error::invalid_argument().message(format!( "identifier exceeds {MAX_IDENTIFIER_BYTES}-byte limit ({} bytes)", @@ -194,6 +199,8 @@ impl<'a> LikePattern<'a> { /// /// Rejects: /// - Empty string — callers should pass `None` for "match all". + /// - Strings consisting only of whitespace — callers should pass + /// `None` for "match all". /// - Embedded NUL bytes — same FFI-truncation hazard as /// [`Identifier::new`]. /// - Strings exceeding 255 bytes. @@ -206,6 +213,10 @@ impl<'a> LikePattern<'a> { return Err(Error::invalid_argument() .message("LIKE pattern must not be empty (pass None for \"match all\")")); } + if s.trim().is_empty() { + return Err(Error::invalid_argument() + .message("LIKE pattern must not be all whitespace (pass None for \"match all\")")); + } if s.len() > MAX_LIKE_PATTERN_BYTES { return Err(Error::invalid_argument().message(format!( "LIKE pattern exceeds {MAX_LIKE_PATTERN_BYTES}-byte limit ({} bytes)", @@ -669,4 +680,30 @@ mod tests { let err = LikePattern::new(&s).expect_err("oversize pattern rejected"); assert_eq!(err.code, ErrorCode::InvalidArgument); } + + #[test] + fn identifier_rejects_whitespace_only() { + for s in &[" ", "\t", "\n", " \t "] { + let err = Identifier::new(s).expect_err("whitespace-only identifier rejected"); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!( + err.message.contains("whitespace"), + "expected 'whitespace' in: {}", + err.message + ); + } + } + + #[test] + fn like_pattern_rejects_whitespace_only() { + for s in &[" ", "\t", "\n", " \t "] { + let err = LikePattern::new(s).expect_err("whitespace-only pattern rejected"); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!( + err.message.contains("whitespace"), + "expected 'whitespace' in: {}", + err.message + ); + } + } } diff --git a/src/reader/inline/provider.rs b/src/reader/inline/provider.rs index 5a135dcf..4449a290 100644 --- a/src/reader/inline/provider.rs +++ b/src/reader/inline/provider.rs @@ -38,6 +38,37 @@ pub struct InlineArrowProvider { schema: Option, } +/// Clamp a sequence of record batches to an authoritative logical row +/// count (`manifest.total_row_count`), slicing the batch that crosses the +/// boundary and dropping any rows past it. `None` (or a negative count) +/// leaves the batches untouched. Pure so the boundary arithmetic is +/// unit-testable. See [`InlineArrowProvider::new`] for why the manifest +/// count, not the raw Arrow row count, is authoritative. +fn clamp_to_total_rows( + batches: Vec, + total_row_count: Option, +) -> Vec { + let Some(limit) = total_row_count.filter(|n| *n >= 0).map(|n| n as usize) else { + return batches; + }; + let mut out = Vec::with_capacity(batches.len()); + let mut remaining = limit; + for batch in batches { + if remaining == 0 { + break; + } + if batch.num_rows() <= remaining { + remaining -= batch.num_rows(); + out.push(batch); + } else { + // This batch crosses the boundary — keep only `remaining` rows. + out.push(batch.slice(0, remaining)); + remaining = 0; + } + } + out +} + impl InlineArrowProvider { /// Create a new provider from raw Arrow IPC bytes. /// @@ -46,6 +77,14 @@ impl InlineArrowProvider { /// # Arguments /// * `attachment` - Raw Arrow IPC bytes (decoded from base64) /// * `compression` - Compression codec used (from manifest.result_compression) + /// * `total_row_count` - Authoritative logical row count from + /// `manifest.total_row_count`. When `Some`, the decoded batches are + /// clamped to this count: with a `row_limit` applied the SEA server + /// returns one extra look-ahead Arrow row beyond the logical count + /// (`manifest.truncated = true`), and the manifest count — not the + /// raw Arrow row count — is the result size. Mirrors the Python SEA + /// connector, which bounds its `ArrowQueue` by `total_row_count`. + /// `None` leaves the batches unclamped. /// /// # Returns /// A new provider with parsed batches ready for iteration @@ -53,7 +92,11 @@ impl InlineArrowProvider { /// # Errors /// - If decompression fails /// - If Arrow IPC parsing fails - pub fn new(attachment: Vec, compression: CompressionCodec) -> Result { + pub fn new( + attachment: Vec, + compression: CompressionCodec, + total_row_count: Option, + ) -> Result { if attachment.is_empty() { tracing::debug!("Empty attachment, creating empty provider"); return Ok(Self { @@ -69,10 +112,12 @@ impl InlineArrowProvider { ); // Reuse the shared Arrow IPC parser (same format as CloudFetch) - let batches = parse_arrow_ipc(&attachment, compression).map_err(|e| { + let parsed = parse_arrow_ipc(&attachment, compression).map_err(|e| { Error::io().message(format!("Failed to parse inline Arrow data: {}", e)) })?; + let batches = clamp_to_total_rows(parsed, total_row_count); + let schema = batches.first().map(|b| b.schema()); tracing::debug!( @@ -156,7 +201,8 @@ mod tests { let batch = create_test_batch(100); let ipc_data = create_test_arrow_ipc(&[batch]); - let mut provider = InlineArrowProvider::new(ipc_data, CompressionCodec::None).unwrap(); + let mut provider = + InlineArrowProvider::new(ipc_data, CompressionCodec::None, None).unwrap(); // Check schema assert!(provider.schema().is_some()); @@ -189,7 +235,7 @@ mod tests { } let mut provider = - InlineArrowProvider::new(compressed, CompressionCodec::Lz4Frame).unwrap(); + InlineArrowProvider::new(compressed, CompressionCodec::Lz4Frame, None).unwrap(); let batch = provider.next_batch().unwrap().unwrap(); assert_eq!(batch.num_rows(), 100); @@ -201,7 +247,8 @@ mod tests { let batch2 = create_test_batch(30); let ipc_data = create_test_arrow_ipc(&[batch1, batch2]); - let mut provider = InlineArrowProvider::new(ipc_data, CompressionCodec::None).unwrap(); + let mut provider = + InlineArrowProvider::new(ipc_data, CompressionCodec::None, None).unwrap(); // First batch let batch = provider.next_batch().unwrap().unwrap(); @@ -217,7 +264,7 @@ mod tests { #[test] fn test_inline_provider_with_empty_data() { - let provider = InlineArrowProvider::new(vec![], CompressionCodec::None).unwrap(); + let provider = InlineArrowProvider::new(vec![], CompressionCodec::None, None).unwrap(); assert!(provider.schema().is_none()); assert!(!provider.has_more()); @@ -227,7 +274,53 @@ mod tests { fn test_inline_provider_with_invalid_data() { let invalid_data = b"this is not valid arrow ipc data".to_vec(); - let result = InlineArrowProvider::new(invalid_data, CompressionCodec::None); + let result = InlineArrowProvider::new(invalid_data, CompressionCodec::None, None); assert!(result.is_err()); } + + #[test] + fn clamp_none_is_passthrough() { + let batches = vec![create_test_batch(10)]; + let out = clamp_to_total_rows(batches, None); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 10); + } + + #[test] + fn clamp_slices_across_batches() { + // 4 + 4 + 4 = 12 rows; clamp to 10 -> 4 + 4 + 2. + let batches = vec![ + create_test_batch(4), + create_test_batch(4), + create_test_batch(4), + ]; + let out = clamp_to_total_rows(batches, Some(10)); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 10); + assert_eq!(out.len(), 3); + assert_eq!(out[2].num_rows(), 2); + } + + #[test] + fn clamp_above_actual_is_noop() { + let batches = vec![create_test_batch(5)]; + let out = clamp_to_total_rows(batches, Some(1000)); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 5); + } + + #[test] + fn inline_provider_clamps_look_ahead_row_to_manifest_count() { + // Reproduces the row_limit=N -> N+1 server look-ahead: an 11-row + // Arrow attachment with manifest.total_row_count = 10 must surface + // exactly 10 rows (parity with Python use_sea and Thrift). + let batch = create_test_batch(11); + let ipc = create_test_arrow_ipc(&[batch]); + let mut provider = InlineArrowProvider::new(ipc, CompressionCodec::None, Some(10)).unwrap(); + let mut total = 0; + while let Some(b) = provider.next_batch().unwrap() { + total += b.num_rows(); + } + assert_eq!( + total, 10, + "must clamp the +1 look-ahead row to the manifest count" + ); + } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 38258b62..e94f642e 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -183,7 +183,12 @@ impl ResultReaderFactory { inline_data.len() ); - return self.create_inline_reader(inline_data, compression); + // Pass the manifest's authoritative row count so the + // inline provider clamps off any look-ahead row the SEA + // server appends when a row_limit truncates the result. + let total_row_count = + response.manifest.as_ref().and_then(|m| m.total_row_count); + return self.create_inline_reader(inline_data, compression, total_row_count); } } @@ -316,14 +321,17 @@ impl ResultReaderFactory { &self, inline_data: &[u8], compression: CompressionCodec, + total_row_count: Option, ) -> Result> { tracing::debug!( - "Creating inline Arrow reader: {} bytes, compression={:?}", + "Creating inline Arrow reader: {} bytes, compression={:?}, total_row_count={:?}", inline_data.len(), - compression + compression, + total_row_count ); - let provider = InlineArrowProvider::new(inline_data.to_vec(), compression)?; + let provider = + InlineArrowProvider::new(inline_data.to_vec(), compression, total_row_count)?; Ok(Box::new(InlineArrowReader::new(provider))) } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index e7be9189..93d4d4ce 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -67,6 +67,31 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tracing::{warn, Instrument}; +/// Resolve the SEA `(wait_timeout, on_wait_timeout)` pair for an execute / +/// submit dispatch. Pure so the precedence rules are unit-testable without +/// a live `Session`. +/// +/// - `caller_wait_secs = Some(s)` — the caller pinned the wait shape +/// (e.g. `submit` passes `"0s"` for async). Respected verbatim with +/// `CONTINUE`; overriding it would make async submit block. +/// - `caller_wait_secs = None` — the sync `execute` path. A per-statement +/// `spec_query_timeout_secs` then bounds the server wait and `CANCEL`s +/// the statement on elapse (JDBC `setQueryTimeout` / Python `use_sea`'s +/// `wait_timeout` semantics). With no spec timeout, both are omitted so +/// the server applies its default (~10s wait + auto-close on success). +fn resolve_wait_timeout( + caller_wait_secs: Option<&str>, + spec_query_timeout_secs: Option, +) -> (Option, Option) { + match caller_wait_secs { + Some(s) => (Some(s.to_string()), Some("CONTINUE".to_string())), + None => match spec_query_timeout_secs { + Some(secs) => (Some(format!("{secs}s")), Some("CANCEL".to_string())), + None => (None, None), + }, + } +} + /// Lifecycle owner for a single statement spec. /// /// Mutable, reusable. Mutate the spec in place via [`Statement::spec`], @@ -312,13 +337,12 @@ impl Statement { if self.spec.result_format != ResultFormat::Arrow { return Err(Error::invalid_argument().message("v0 supports ResultFormat::Arrow only")); } - // `wait_timeout = None` means "omit the field"; the server - // applies its default (~10s wait + auto-close on success). - // `on_wait_timeout` only matters when wait_timeout is set, - // so mirror the presence. + let (wait_timeout, on_wait_timeout) = + resolve_wait_timeout(wait_timeout_secs, self.spec.query_timeout_secs); let mut exec_params = ExecuteParams { - wait_timeout: wait_timeout_secs.map(|s| s.to_string()), - on_wait_timeout: wait_timeout_secs.map(|_| "CONTINUE".to_string()), + wait_timeout, + on_wait_timeout, + row_limit: self.spec.row_limit, ..ExecuteParams::default() }; for (i, value) in self.spec.positional_params.iter().enumerate() { @@ -480,3 +504,35 @@ impl Drop for Statement { // remaining cleanup obligation here. } } + +#[cfg(test)] +mod tests { + use super::resolve_wait_timeout; + + #[test] + fn async_submit_caller_value_is_respected_verbatim() { + // submit() pins "0s" for async; never overridden, even if a spec + // query_timeout is set (overriding would make submit block). + let (wait, on_wait) = resolve_wait_timeout(Some("0s"), Some(30)); + assert_eq!(wait.as_deref(), Some("0s")); + assert_eq!(on_wait.as_deref(), Some("CONTINUE")); + } + + #[test] + fn sync_with_query_timeout_cancels_on_elapse() { + // execute() passes None; a spec query_timeout bounds the wait and + // CANCELs the statement on elapse (server statement-timeout). + let (wait, on_wait) = resolve_wait_timeout(None, Some(30)); + assert_eq!(wait.as_deref(), Some("30s")); + assert_eq!(on_wait.as_deref(), Some("CANCEL")); + } + + #[test] + fn sync_without_query_timeout_omits_field() { + // No caller pin and no spec timeout: omit both so the server uses + // its default (~10s wait + auto-close on success). + let (wait, on_wait) = resolve_wait_timeout(None, None); + assert_eq!(wait, None); + assert_eq!(on_wait, None); + } +} diff --git a/src/statement/spec.rs b/src/statement/spec.rs index f202c01d..5c8692de 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -192,6 +192,25 @@ pub struct StatementSpec { /// `session_conf` at execute time; this map wins on key collisions. pub statement_conf: HashMap, + /// Server-side cap on the number of rows returned by this statement, + /// independent of SQL `LIMIT`. Maps directly to the SEA + /// `ExecuteStatement.row_limit` wire field (Python `use_sea`'s + /// `row_limit=` kwarg is the canonical cross-driver surface). `None` + /// omits the field, so the server applies no driver-imposed cap. + pub row_limit: Option, + + /// Server-side statement wait timeout, in whole seconds. Bounds how + /// long the server waits for the statement to reach a terminal state + /// before the wait elapses; on elapse the statement is cancelled + /// (`on_wait_timeout = CANCEL`), surfacing as a timeout to the caller. + /// This is the per-statement server timeout (JDBC `setQueryTimeout` / + /// Python `use_sea`'s `wait_timeout=`), distinct from the transport + /// `overall_timeout`. `None` lets the kernel pick its sync/async + /// default (see `Statement::execute` / `submit`). The SEA wire caps + /// the value at 50s; the kernel forwards the requested value verbatim + /// and lets the server clamp. + pub query_timeout_secs: Option, + /// Result wire format. pub result_format: ResultFormat, } @@ -259,6 +278,20 @@ impl StatementSpec { self } + /// Set the server-side row cap (SEA `row_limit`). `None` clears it. + pub fn row_limit(&mut self, row_limit: Option) -> &mut Self { + self.row_limit = row_limit; + self + } + + /// Set the per-statement server wait timeout in whole seconds. `None` + /// clears it (kernel default applies). See the field docs for the + /// `CANCEL`-on-elapse semantics and the 50s server cap. + pub fn query_timeout_secs(&mut self, secs: Option) -> &mut Self { + self.query_timeout_secs = secs; + self + } + /// Set the result wire format. pub fn result_format(&mut self, fmt: ResultFormat) -> &mut Self { self.result_format = fmt; @@ -277,9 +310,25 @@ mod tests { assert!(s.positional_params.is_empty()); assert!(s.named_params.is_empty()); assert!(s.statement_conf.is_empty()); + // row_limit / query_timeout default to "omit the field" so the + // server applies no driver-imposed cap and its own wait default. + assert!(s.row_limit.is_none()); + assert!(s.query_timeout_secs.is_none()); assert_eq!(s.result_format, ResultFormat::Arrow); } + #[test] + fn row_limit_and_query_timeout_setters() { + let mut s = StatementSpec::new(); + s.row_limit(Some(100)).query_timeout_secs(Some(30)); + assert_eq!(s.row_limit, Some(100)); + assert_eq!(s.query_timeout_secs, Some(30)); + // `None` clears back to the omit-the-field default. + s.row_limit(None).query_timeout_secs(None); + assert!(s.row_limit.is_none()); + assert!(s.query_timeout_secs.is_none()); + } + #[test] fn fluent_setters_compose() -> Result<()> { let mut s = StatementSpec::new();