diff --git a/.github/workflows/napi-checks.yml b/.github/workflows/napi-checks.yml index 7700409e..cc35c1fb 100644 --- a/.github/workflows/napi-checks.yml +++ b/.github/workflows/napi-checks.yml @@ -49,12 +49,9 @@ concurrency: permissions: contents: read - # Required for the OIDC token exchange that the - # `.github/actions/setup-jfrog` composite uses to authenticate - # against the JFrog cargo proxy. The protected runner group blocks - # direct crates.io access, so cargo must route through the proxy. - # See go/hardened-gha. - id-token: write +# `id-token: write` is NOT granted workflow-wide: the `precondition` +# job only checks out and inspects the tree, so least-privilege keeps +# it on the single job that needs it (`check-and-test`, below). defaults: run: @@ -91,6 +88,12 @@ jobs: name: "napi fmt + clippy + test" needs: precondition if: needs.precondition.outputs.ready == 'true' + # Scoped here (not workflow-wide): `id-token: write` is only needed + # for the OIDC token exchange in `.github/actions/setup-jfrog` that + # authenticates against the JFrog cargo proxy. See go/hardened-gha. + permissions: + contents: read + id-token: write runs-on: group: databricks-protected-runner-group labels: linux-ubuntu-latest diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 16fd146d..cf129a0e 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -412,6 +412,7 @@ dependencies = [ "arrow-array", "arrow-ipc", "arrow-schema", + "chrono", "databricks-sql-kernel", "futures", "napi", @@ -420,6 +421,7 @@ dependencies = [ "once_cell", "serde_json", "tokio", + "tracing", ] [[package]] diff --git a/napi/Cargo.toml b/napi/Cargo.toml index c091baae..e06cf4e1 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -70,6 +70,11 @@ napi-derive = "2" # kernel's default feature. databricks-sql-kernel = { path = "..", default-features = false, features = ["tls-rustls"] } +# Tracing — transitive via the kernel; declared explicitly so the napi layer +# can emit its own `tracing::debug!` breadcrumbs (metadata blocking-pool +# entry/exit, metadata-cancel no-op) through the same subscriber the kernel uses. +tracing = "0.1" + # Tokio is a transitive dep via the kernel and via napi's `async` feature; # declared explicitly so we can name `tokio::runtime::Handle` and # `tokio::sync::Mutex` directly. @@ -97,6 +102,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/package.json b/napi/package.json index a183f18d..db1ab8de 100644 --- a/napi/package.json +++ b/napi/package.json @@ -1,7 +1,7 @@ { - "name": "@databricks/sql-kernel-linux-x64-gnu", + "name": "@databricks/sql-kernel", "version": "0.1.0", - "description": "Databricks SQL Kernel — Node.js native binding (linux-x64-gnu).", + "description": "Databricks SQL Kernel — Node.js native binding.", "main": "index.js", "types": "index.d.ts", "files": [ @@ -14,7 +14,7 @@ "node": ">=18.0.0" }, "napi": { - "binaryName": "sql-kernel", + "binaryName": "index", "targets": [ "x86_64-unknown-linux-gnu" ] diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs new file mode 100644 index 00000000..ed1dd00e --- /dev/null +++ b/napi/src/async_statement.rs @@ -0,0 +1,464 @@ +// 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. + +//! Opaque `AsyncStatement` + `AsyncResultHandle` wrappers around the +//! kernel's submit/poll/await_result path. +//! +//! - `Connection.submitStatement(sql, options?)` builds a kernel +//! `Statement`, calls `submit()` (which sends `wait_timeout=0s` so +//! the server returns Pending/Running immediately with a +//! statement_id), and wraps the returned `ExecutedAsyncStatement` +//! in this napi class. JS callers drive polling via `status()` or +//! `awaitResult()`. +//! +//! - `AsyncStatement.status()` issues a single GetStatementStatus +//! RPC, mapped to a JS-side string enum +//! (`'Pending'|'Running'|'Succeeded'|'Failed'|'Cancelled'|'Closed'`). +//! The Failed variant carries the same error envelope the sync +//! path produces (sql_state / error_code / query_id when present). +//! +//! - `AsyncStatement.awaitResult()` blocks until the server reaches +//! a terminal state, then returns an `AsyncResultHandle` over the +//! materialised `ResultStream`. It holds `inner.lock()` across the +//! whole poll. Two independent cancellation paths cover it: +//! (1) the kernel's own `AwaitResultCancelGuard` handles drop-cancel +//! — if the JS Promise's underlying tokio future is dropped mid-poll +//! (a timeout wrapper, a `tokio::select!` loser, a `Promise.race` +//! loser), the kernel fires a fire-and-forget `cancel_statement` so +//! the server stops charging DBUs on the orphaned query; and +//! (2) an explicit `AsyncStatement.cancel()` (see below) fires a +//! server-side cancel *without* taking the lock, flipping the +//! statement terminal so the parked `awaitResult()` poll observes +//! `Cancelled` and returns. The `util::guarded` `catch_unwind` +//! wrapper applied to every entry here covers the +//! V8-panic-across-boundary case on top of both. +//! +//! `close()` routes through the `ExecutedStatementHandle` trait the +//! kernel implements for both `ExecutedStatement` and +//! `ExecutedAsyncStatement`, holding `inner.lock()` like the sync path. +//! `cancel()` is the one method that does *not* take the lock — it +//! fires through a detached `AsyncStatementCanceller` (session + +//! statement_id) so it can interrupt an in-flight `awaitResult()` +//! rather than queue behind it. The `Arc>>` shape is +//! otherwise the same as `Connection`/`Statement` so Drop's +//! fire-and-forget cleanup behaves consistently. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use tokio::sync::Mutex; + +use arrow_schema::SchemaRef; +use databricks_sql_kernel::{ + AsyncStatementCanceller, Error as KernelError, ExecutedAsyncStatement, ExecutedStatementHandle, + ResultBatch, ResultStream, Statement as KernelStatement, +}; + +use crate::error::napi_err_from_kernel; +use crate::result::{encode_ipc_stream, ArrowBatch, ArrowSchema}; +use crate::runtime; +use crate::util::guarded; + +// ───────────────────────── shared helpers ───────────────────────── + +/// Closed-state error builder for both `AsyncStatement` and +/// `AsyncResultHandle`. Mirrors the sync `Statement` path's +/// `statement_closed_err` so the TS reviver sees the same +/// `KernelError(code='InvalidStatementHandle')` shape regardless of +/// which napi class produced the error. +fn closed_err(what: &str) -> napi::Error { + napi_err_from_kernel( + KernelError::invalid_statement_handle().message(format!("{what} already closed")), + ) +} + +// Arrow IPC encoding is shared with the sync `Statement` path via +// `crate::result::encode_ipc_stream` (its single home — see the +// encoder-lift refactor). Both paths emit byte-identical envelopes and +// route encode failures through the same kernel error envelope. + +// ───────────────────────── AsyncStatement ───────────────────────── + +/// Inner state for the JS-visible `AsyncStatement` wrapper. Same +/// shape rationale as `StatementInner` in `statement.rs`: we hold +/// the parent kernel `Statement` alive so its `Drop` (which +/// invalidates the executed handle via the shared `ValidityFlag`) +/// doesn't fire while JS still holds this wrapper. +struct AsyncStatementInner { + /// The kernel's `Statement` (mutable). Kept alive solely to + /// prevent its `Drop` from invalidating `executed_async`. + _parent: KernelStatement, + /// The kernel async-consumption handle — drives `status()` / + /// `awaitResult()` / `cancel()` / `close()`. + executed_async: ExecutedAsyncStatement, +} + +/// Opaque async-statement handle. +/// +/// Returned by `Connection.submitStatement(...)` after the kernel +/// `Statement::submit()` returns (server sent `wait_timeout=0s`, so +/// the response carries a `statement_id` but the statement is still +/// `Pending`/`Running`). JS drives polling via `status()` / +/// `awaitResult()`. +/// +/// Concurrency shape: `status()`, `awaitResult()`, and `close()` take +/// `inner.lock()` and hold the guard across the kernel `.await` (tokio +/// `Mutex` is FIFO), so `status()` / `close()` queue behind any +/// in-flight `awaitResult()` until it returns naturally. `cancel()` is +/// the deliberate exception: it does **not** touch `inner` — it fires +/// through the detached `AsyncStatementCanceller` (session + +/// statement_id, captured at construction), so an explicit +/// `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of +/// queueing behind it. The server-side cancel flips the statement +/// terminal, which the parked `awaitResult()` poll loop observes +/// (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` +/// still covers the drop-cancel case (Promise.race / timeout) +/// independently — see module docs. +#[napi] +pub struct AsyncStatement { + inner: Arc>>, + /// Detached canceller (session handle + statement_id), captured at + /// construction and held **outside** `inner` so `cancel()` can fire + /// a server-side cancel without contending for the mutex an + /// in-flight `awaitResult()` holds. See the struct-level + /// concurrency note. + canceller: AsyncStatementCanceller, + /// Lock-free mirror of "has `close()` taken `inner`". Set by + /// `close()`; read by the lock-free `cancel()` so a cancel after an + /// explicit close still surfaces `InvalidStatementHandle` without + /// taking the mutex. + closed: Arc, + /// Server-issued statement id. Cached at construction; readable + /// even after `close()` for log correlation against kernel / + /// server logs which key on the same id. + statement_id: String, +} + +impl AsyncStatement { + /// Crate-internal constructor — called from + /// `Connection::submit_statement` once the kernel hands back + /// the `ExecutedAsyncStatement`. The parent kernel `Statement` + /// is passed in alongside so its `Drop` doesn't fire while JS + /// still holds the executed-async handle (see + /// `StatementInner` docs in `statement.rs` for the + /// validity-flag rationale). + pub(crate) fn from_executed_async( + parent: KernelStatement, + executed_async: ExecutedAsyncStatement, + ) -> Self { + let statement_id = executed_async.statement_id().to_owned(); + // Capture the detached canceller before `executed_async` moves + // into the mutex, so `cancel()` never needs `inner.lock()`. + let canceller = executed_async.canceller(); + Self { + inner: Arc::new(Mutex::new(Some(AsyncStatementInner { + _parent: parent, + executed_async, + }))), + canceller, + closed: Arc::new(AtomicBool::new(false)), + statement_id, + } + } +} + +#[napi] +impl AsyncStatement { + /// Server-issued statement id. Cached at construction; readable + /// even after `close()` so JS-side log lines can correlate + /// against kernel / server logs which key on the same id. + #[napi(getter)] + pub fn statement_id(&self) -> &str { + &self.statement_id + } + + /// One-shot status check. Returns a string enum matching the + /// kernel `StatementStatus` shape: + /// `'Pending' | 'Running' | 'Succeeded' | 'Failed' | + /// 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the + /// `#[non_exhaustive]` forward-compat catch-all that + /// `StatementStatus::as_str` can return — consumers switching on + /// the state must handle it.) Returns + /// `KernelError(InvalidStatementHandle)` if the statement has + /// been explicitly `close()`d. + /// + /// The `Failed` variant collapses to the string `'Failed'` on + /// the JS side; the underlying error envelope (sql_state / + /// error_code / query_id) is surfaced by `awaitResult()`'s + /// rejection, which is where callers actually need the typed + /// error. `status()` is intended for polling progress UIs + /// that only need the state name. + #[napi] + pub async fn status(&self) -> napi::Result { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?; + let status = inner_state + .executed_async + .status() + .await + .map_err(napi_err_from_kernel)?; + // String mapping lives on the kernel `StatementStatus::as_str` + // so all bindings share one taxonomy (incl. the + // `#[non_exhaustive]` `"Unknown"` catch-all). + Ok(status.as_str().to_owned()) + }) + .await + } + + /// Block until the server reaches a terminal state, then return + /// an `AsyncResultHandle` that wraps the materialised result + /// stream. The handle exposes `fetchNextBatch()` / `schema()` + /// for consuming the result, plus `statementId` for log + /// correlation. + /// + /// Drop-cancel safety: kernel `await_result` installs + /// `AwaitResultCancelGuard` which fires a fire-and-forget + /// `cancel_statement` if the future is dropped mid-poll + /// (timeout, tokio::select! loser, JS-side `Promise.race` + /// loser). The `util::guarded` `catch_unwind` here covers the + /// V8-panic-across-boundary case on top. Returns + /// `KernelError(InvalidStatementHandle)` if the statement has + /// been explicitly `close()`d. + #[napi] + pub async fn await_result(&self) -> napi::Result { + let inner = Arc::clone(&self.inner); + guarded(async move { + // Acquire and HOLD the lock across the kernel await: + // dropping the guard while the long-running + // `await_result()` is in-flight would let `close()` / + // `status()` race for the inner state. `cancel()` is + // intentionally lock-free (it fires the detached + // `AsyncStatementCanceller`, not the mutex-guarded handle), + // so it can still interrupt this await; the kernel-side + // `AwaitResultCancelGuard` covers the drop-the-future case. + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?; + let stream = inner_state + .executed_async + .await_result() + .await + .map_err(napi_err_from_kernel)?; + let statement_id = inner_state.executed_async.statement_id().to_owned(); + let schema = stream.schema(); + Ok(AsyncResultHandle { + inner: Arc::new(Mutex::new(Some(stream))), + schema, + statement_id, + }) + }) + .await + } + + /// Server-side cancel. Returns + /// `KernelError(InvalidStatementHandle)` if the statement has + /// been explicitly `close()`d. Idempotent against a server + /// that already reached a terminal state — the kernel's + /// `cancel_statement` is a no-op there. + /// + /// **Lock-free by design.** Unlike `status()` / `awaitResult()` / + /// `close()`, this does not take `inner.lock()` — it fires through + /// the detached `AsyncStatementCanceller` captured at construction. + /// That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` + /// (which holds the mutex for the whole poll) instead of queueing + /// behind it: the server-side cancel flips the statement terminal, + /// the parked `awaitResult()` poll loop observes `Cancelled` and + /// returns. The closed-state check reads a lock-free flag so a + /// cancel after an explicit `close()` still surfaces + /// `InvalidStatementHandle`. + #[napi] + pub async fn cancel(&self) -> napi::Result<()> { + if self.closed.load(Ordering::Acquire) { + return Err(closed_err("AsyncStatement")); + } + let canceller = self.canceller.clone(); + guarded(async move { canceller.cancel().await.map_err(napi_err_from_kernel) }).await + } + + /// Explicit close. Idempotent — a second call on an + /// already-closed handle returns `Ok(())`. On `Err`, the napi + /// inner is already `None`, so a JS-side retry sees the + /// closed-handle short-circuit and returns `Ok(())` without + /// re-attempting the wire call. The kernel's own `Drop` + /// fire-and-forget retry runs once in the background. + #[napi] + pub async fn close(&self) -> napi::Result<()> { + let inner = Arc::clone(&self.inner); + let closed = Arc::clone(&self.closed); + guarded(async move { + let taken = { + let mut guard = inner.lock().await; + guard.take() + }; + let Some(inner_state) = taken else { + return Ok(()); + }; + // Flip the lock-free flag once we own the close so a racing + // lock-free `cancel()` short-circuits to InvalidStatementHandle + // rather than firing a wire cancel on a closing statement. + closed.store(true, Ordering::Release); + inner_state + .executed_async + .close() + .await + .map_err(napi_err_from_kernel) + }) + .await + } +} + +impl Drop for AsyncStatement { + fn drop(&mut self) { + // Best-effort cleanup — same shape as `Connection::Drop`. + // JS callers needing a guaranteed close-with-error-surface + // call `close()` explicitly. + let Some(handle) = runtime::try_get_handle() else { + return; + }; + let inner = Arc::clone(&self.inner); + handle.spawn(async move { + let _taken = { + let mut guard = inner.lock().await; + guard.take() + }; + }); + } +} + +// ─────────────────────── AsyncResultHandle ──────────────────────── + +/// Opaque result-fetch handle returned by +/// `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` +/// directly; structurally analogous to the sync `Statement`'s +/// fetch-side surface (`fetchNextBatch` / `schema` / +/// `statementId`). +/// +/// `cancel()` / `close()` are not exposed: the parent +/// `AsyncStatement` owns server-side lifecycle. A `close()` here +/// would create dual-ownership of the same statement_id with +/// inconsistent close semantics. Callers `close()` the parent +/// `AsyncStatement` after they're done fetching. +/// +/// Schema is cached at construction so it survives the underlying +/// stream being drained; mirrors the sync `Statement.schema()` +/// post-close contract. +#[napi] +pub struct AsyncResultHandle { + /// `Option` only so a future explicit-close path + /// can `.take()` consistently. Today the slot is filled at + /// construction and never emptied until Drop. + inner: Arc>>, + schema: SchemaRef, + statement_id: String, +} + +#[napi] +impl AsyncResultHandle { + /// Server-issued statement id. Cached at construction; readable + /// for log correlation. Matches the parent `AsyncStatement`'s + /// `statementId`. + #[napi(getter)] + pub fn statement_id(&self) -> &str { + &self.statement_id + } + + /// Pull the next batch of results. Returns `null` when the + /// stream is exhausted. The returned `ArrowBatch.ipcBytes` is a + /// complete Arrow IPC stream (schema header + 1 record-batch + /// message), suitable for handing to `apache-arrow`'s + /// `RecordBatchReader`. Byte-identical to the sync + /// `Statement.fetchNextBatch()` payload for the same query. + #[napi] + pub async fn fetch_next_batch(&self) -> napi::Result> { + let inner = Arc::clone(&self.inner); + let schema = self.schema.clone(); + guarded(async move { + let mut guard = inner.lock().await; + let stream = guard + .as_mut() + .ok_or_else(|| closed_err("AsyncResultHandle"))?; + let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; + let Some(batch) = maybe_batch else { + return Ok(None); + }; + let record_batch = match batch { + ResultBatch::Arrow(rb) => rb, + _ => { + return Err(napi_err_from_kernel( + KernelError::invalid_argument().message(format!( + "non-Arrow ResultBatch variant from kernel — \ + databricks-sea-native v{} cannot decode this batch \ + shape, upgrade the binding", + env!("CARGO_PKG_VERSION"), + )), + )); + } + }; + let bytes = encode_ipc_stream(&schema, Some(record_batch))?; + Ok(Some(ArrowBatch { + ipc_bytes: bytes.into(), + })) + }) + .await + } + + /// Result schema as an Arrow IPC payload (schema header only, + /// no record-batch message). Available before any batches have + /// been fetched. Sync because the body has no `.await` — + /// `encode_ipc_stream` is pure CPU work over the cached + /// `Arc`. + #[napi] + pub fn schema(&self) -> napi::Result { + let bytes = encode_ipc_stream(&self.schema, None)?; + Ok(ArrowSchema { + ipc_bytes: bytes.into(), + }) + } +} + +// The `StatementStatus` → JS-string mapping now lives on the kernel as +// `StatementStatus::as_str` (one taxonomy for all bindings, including +// the `#[non_exhaustive]` `"Unknown"` catch-all). `status()` calls it at +// the call site above. + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn closed_err_carries_invalid_statement_handle_envelope() { + let err = closed_err("AsyncStatement"); + assert!( + err.reason.starts_with(crate::error::ERROR_SENTINEL), + "expected envelope-sentinel-prefixed error, got: {}", + err.reason, + ); + assert!( + err.reason.contains(r#""code":"InvalidStatementHandle""#), + "envelope payload missing InvalidStatementHandle: {}", + err.reason, + ); + assert!( + err.reason.contains("AsyncStatement already closed"), + "closed-state error must carry the human message: {}", + err.reason, + ); + } + + #[test] + fn closed_err_status_collapses_to_invalid_arg() { + let err = closed_err("AsyncResultHandle"); + assert_eq!(err.status, napi::Status::InvalidArg); + } +} diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 20d3d11a..97cad23c 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -27,26 +27,221 @@ //! 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::async_statement::AsyncStatement; 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. + /// + /// **Applies to `executeStatement` only.** The async `submitStatement` + /// path always sends `wait_timeout=0s` (so the server returns a + /// `statement_id` immediately and never blocks), which means this + /// field is *not* consulted on the submit path — the caller drives + /// completion via `AsyncStatement.status()` / `awaitResult()` and is + /// responsible for its own timeout (e.g. `Promise.race`). Passing + /// `queryTimeoutSecs` to `submitStatement` is silently ignored. This + /// matches the Python `use_sea` async-submit contract, where the + /// wait-timeout and any statement timeout are orthogonal. + 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 -/// for `executeStatement` on a closed Connection. -fn connection_closed_err() -> napi::Error { +/// for `executeStatement` on a closed Connection. Also reused by +/// `metadata::take_metadata` so closed-state errors share one envelope. +pub(crate) fn connection_closed_err() -> napi::Error { napi_err_from_kernel( KernelError::invalid_statement_handle().message("connection already closed"), ) } +/// Build a kernel `Statement` from a decoded option set, under the caller's +/// session lock. Shared verbatim by `execute_statement` and `submit_statement` +/// so the option → spec mapping lives in exactly one place (any new option is +/// edited once). `Session::statement()` clones the session's internal `Arc`, +/// so the returned `Statement` is independent of the borrow and the caller can +/// release the lock before `execute()` / `submit()`. +/// +/// `query_timeout_secs` is honoured on the sync `execute` path; the submit path +/// passes `None` because submit pins `wait_timeout=0s` and `resolve_wait_timeout` +/// never consults the spec timeout there (see `statement/mutable.rs`). +#[allow(clippy::too_many_arguments)] +fn build_statement( + session: &Session, + sql: String, + statement_conf: Option>, + query_tags: Option>, + row_limit: Option, + query_timeout_secs: Option, + positional_params: Vec, + named_params: Vec<(String, TypedValue)>, +) -> napi::Result { + // Positional/named mutual-exclusivity is enforced in the kernel's + // `build_execute_params` (StatementSpec dispatch), so every binding + // — napi, pyo3, direct Rust — gets the same bind-time InvalidArgument. + // No napi-layer guard needed here. + let mut stmt = session.statement(); + stmt.spec().sql(sql); + // Set the explicit per-statement conf overlay first (only when non-empty) + // so the kernel's `query_tags` merge can detect a dual definition against it. + if let Some(conf) = statement_conf { + if !conf.is_empty() { + stmt.spec().statement_conf(conf); + } + } + // Fold the `queryTags` convenience map into the conf overlay. Empty map is + // a no-op; a dual definition with `statementConf["query_tags"]` rejects. + if let Some(tags) = query_tags { + stmt.spec().query_tags(tags).map_err(napi_err_from_kernel)?; + } + // `None` leaves the kernel's omit-the-field default in place. + 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)?; + } + Ok(stmt) +} + /// Opaque connection handle wrapping a kernel `Session`. /// /// `inner` is `Arc>>` so: @@ -56,15 +251,16 @@ fn connection_closed_err() -> napi::Error { /// - `close()` can `.take()` the session to consume it for the kernel's /// move-by-value `Session::close(self)` signature. /// -/// **Current concurrency shape** — `executeStatement` holds -/// `inner.lock()` across `stmt.execute().await`, so two concurrent -/// `Promise.all([executeStatement(q1), executeStatement(q2)])` calls -/// on the same Connection serialise even though the kernel transport -/// supports concurrent statements per session, and `close()` blocks -/// behind any in-flight execute. The kernel's `Session::statement()` -/// is `&self`-callable, so the right shape is `Arc` with -/// concurrent execute paths; that lands in the follow-up lock-shape -/// refactor — see +/// **Concurrency shape** — both `executeStatement` and +/// `submitStatement` build the kernel `Statement` under `inner.lock()` +/// and then RELEASE the guard before the wire call +/// (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` +/// is `&self`-callable and only clones the session's internal `Arc`, so +/// the built statement is independent of the guard. Concurrent +/// `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore +/// serialise only for the microsecond statement-build, not the network +/// round-trip, and `close()` never blocks behind an in-flight execute or +/// submit. See /// `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. #[napi] pub struct Connection { @@ -88,17 +284,76 @@ 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 (both `i64`/`u32` are `Copy`) before + // the `.take()`s below consume the map fields out of `options`. + 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(); + // Pull the explicit `statement_conf` map and the `query_tags` + // convenience map out of `options`. The kernel `StatementSpec` + // owns the merge + serialisation: set the explicit conf first, + // then fold `query_tags` in via `spec.query_tags(...)`, which + // serialises to the Thrift wire shape and rejects the dual + // `queryTags` + `statementConf["query_tags"]` definition. + let statement_conf = options.as_mut().and_then(|o| o.statement_conf.take()); + let query_tags = options.as_mut().and_then(|o| o.query_tags.take()); 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); + // Build the kernel `Statement` while holding the session lock, + // then RELEASE the lock before `execute().await`. `Session::statement()` + // returns an owned `Statement` (it clones the session's internal + // `Arc`), so the built statement is independent of the guard — we + // do not need to hold the mutex across the network round-trip. + // This unblocks concurrent `Promise.all([executeStatement(...)])` + // (they serialise only for the microsecond statement-build, not the + // wire call) and stops `close()` from blocking behind an in-flight + // execute. See jira-candidate 2026-05-24-napi-cancel-during-fetch + // (connection-side half). + let mut stmt = { + let guard = inner.lock().await; + let session = guard.as_ref().ok_or_else(connection_closed_err)?; + build_statement( + session, + sql, + statement_conf, + query_tags, + row_limit, + query_timeout_secs, + positional_params, + named_params, + )? + // session lock released here + }; let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. @@ -110,6 +365,92 @@ impl Connection { .await } + /// Submit a SQL statement and return immediately with an + /// `AsyncStatement` handle, without blocking until the query + /// finishes. The kernel's `Statement::submit()` sends + /// `wait_timeout=0s`, so the server responds as soon as it has a + /// `statement_id` (state `Pending`/`Running`); JS drives polling + /// via `AsyncStatement.status()` and materialises results with + /// `AsyncStatement.awaitResult()`. + /// + /// This is the async-execution path the Thrift backend always + /// uses (`runAsync: true`): the SEA backend submits, returns a + /// pending operation handle, and polls to terminal during + /// fetch. Option semantics (statementConf / queryTags / + /// rowLimit / positional + named params) match `executeStatement`, + /// with one carve-out: `queryTimeoutSecs` is **ignored** here. + /// Submit always sends `wait_timeout=0s` so the call returns + /// immediately, leaving no server wait to bound; the caller drives + /// completion and its own timeout via `status()` / `awaitResult()` + /// (e.g. `Promise.race`). Only the blocking-vs-pending return + /// contract — and that timeout carve-out — differ from + /// `executeStatement`. + #[napi] + pub async fn submit_statement( + &self, + sql: String, + mut options: Option, + ) -> napi::Result { + let inner = Arc::clone(&self.inner); + // Same option decoding as `execute_statement` — malformed + // params surface as InvalidArgument before any wire round-trip. + // `queryTimeoutSecs` is intentionally NOT read here: submit pins + // `wait_timeout=0s`, so `resolve_wait_timeout` never consults the + // spec timeout on this path (see statement/mutable.rs). + let row_limit = options.as_ref().and_then(|o| o.row_limit); + 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(); + // Same conf + query_tags plumbing as `execute_statement`: the + // kernel `StatementSpec` owns the merge + serialisation. + let statement_conf = options.as_mut().and_then(|o| o.statement_conf.take()); + let query_tags = options.as_mut().and_then(|o| o.query_tags.take()); + guarded(async move { + // Build the kernel `Statement` while holding the session lock, + // then RELEASE the lock before `submit().await` — same shape as + // `execute_statement`. `Session::statement()` clones the session's + // internal `Arc`, so the built statement is independent of the + // guard and we never need the mutex across the wire round-trip. + // This keeps concurrent `submitStatement` calls from serialising + // on the session mutex and stops `close()` blocking behind an + // in-flight submit (matters on transport retries — submit itself + // sends `wait_timeout=0s`). See jira-candidate + // 2026-05-24-napi-cancel-during-fetch (connection-side half). + let mut stmt = { + let guard = inner.lock().await; + let session = guard.as_ref().ok_or_else(connection_closed_err)?; + // `None` for query_timeout_secs — ignored on the submit path. + build_statement( + session, + sql, + statement_conf, + query_tags, + row_limit, + None, + positional_params, + named_params, + )? + // session lock released here + }; + + let executed_async = stmt.submit().await.map_err(napi_err_from_kernel)?; + // Pass the parent kernel `Statement` into the JS wrapper so + // its `Drop` doesn't invalidate the executed-async handle + // via the shared ValidityFlag while JS still holds it. + Ok(AsyncStatement::from_executed_async(stmt, executed_async)) + }) + .await + } + /// Explicit close. Awaits the server-side `DeleteSession` so the /// JS caller can observe failures (auth revoked mid-session, /// warehouse stopped, network error). Idempotent — a second call diff --git a/napi/src/database.rs b/napi/src/database.rs index d2b8fac4..cfe3cb0f 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -28,7 +28,14 @@ use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; -use databricks_sql_kernel::{AuthConfig, DefaultOpts, HttpConfig, Session}; +#[cfg(not(test))] +use napi::bindgen_prelude::Buffer; +#[cfg(test)] +type Buffer = Vec; + +use databricks_sql_kernel::{ + AuthConfig, DefaultOpts, HttpConfig, ResultConfig, Session, TlsConfig, +}; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. /// @@ -49,8 +56,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 +103,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 +153,102 @@ 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, + /// Whether to verify the server's TLS certificate. + /// + /// Omitted / `true` ⇒ strict validation against the system / Mozilla + /// trust store (full chain + expiry + hostname), matching JDBC / ODBC + /// and every modern HTTPS client. This is the **default** for the SEA + /// backend — secure by default. + /// + /// `false` ⇒ permissive: accept self-signed / untrusted / expired + /// certs AND skip the hostname-vs-SNI check. This is **insecure** (no + /// protection against active MITM); it exists only as an opt-out for + /// parity with the legacy NodeJS Thrift driver, which hard-codes + /// `rejectUnauthorized: false`. Prefer pairing strict checking with + /// `custom_ca_cert` over disabling verification entirely. + /// + /// Maps onto the kernel [`TlsConfig::accept_self_signed`] + + /// [`TlsConfig::skip_hostname_verification`] (both = `!check`). + pub check_server_certificate: Option, + /// PEM-encoded CA certificate bytes to add to the trust store on + /// top of the system roots. Use for corporate TLS-inspecting + /// proxies that re-sign TLS, or on-prem deployments with an + /// internal CA. Honoured regardless of `check_server_certificate`. + /// Maps onto the kernel [`TlsConfig::custom_ca_cert`]. + pub custom_ca_cert: Option, } -/// Open a Databricks SQL session over PAT auth and return an opaque -/// `Connection` wrapping the kernel `Session`. +/// Map the JS `ConnectionOptions` auth fields onto the kernel +/// [`AuthConfig`]. Per-mode required-field validation lives in the +/// kernel's validating constructors ([`AuthConfig::pat`] / +/// [`AuthConfig::oauth_m2m`]); this binding just forwards the JS +/// optionals and maps any kernel `InvalidArgument` onto a napi error. +/// 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 => AuthConfig::pat(options.token.clone()).map_err(napi_err_from_kernel), + AuthMode::OAuthM2m => AuthConfig::oauth_m2m( + options.oauth_client_id.clone(), + options.oauth_client_secret.clone(), + options.oauth_scopes.clone(), + None, + ) + .map_err(napi_err_from_kernel), + // All U2M fields are optional — the kernel fills `databricks-cli` + // / port 8020 / default scopes when omitted. + AuthMode::OAuthU2m => Ok(AuthConfig::oauth_u2m( + options.oauth_client_id.clone(), + options.oauth_redirect_port, + options.oauth_scopes.clone(), + None, + None, + )), + } +} + +/// Map the JS TLS fields onto the kernel [`TlsConfig`]. +/// +/// The default (no `check_server_certificate`) is **secure** — it keeps +/// the kernel's strict [`TlsConfig::default()`] (full chain + expiry + +/// hostname validation). Setting `check_server_certificate: false` is an +/// explicit opt-out that relaxes both knobs, matching the legacy NodeJS +/// Thrift driver's permissive `rejectUnauthorized: false` behaviour for +/// callers that need it. A `custom_ca_cert` is always added to the trust +/// store regardless of the strictness toggle. +/// +/// `TlsConfig` is `#[non_exhaustive]` — construct via `default()` then +/// mutate (same pattern as `ResultConfig` / `HttpConfig` above). Pure +/// (borrows `options`) so it is unit-testable without opening a session. +fn build_tls_config(options: &ConnectionOptions) -> TlsConfig { + // Secure-by-default: only an explicit `false` relaxes verification. + let strict = options.check_server_certificate.unwrap_or(true); + let mut tls = TlsConfig::default(); + tls.accept_self_signed = !strict; + tls.skip_hostname_verification = !strict; + if let Some(ca) = &options.custom_ca_cert { + tls.custom_ca_cert = Some(ca.to_vec()); + } + tls +} + +/// 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 +265,16 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result 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, + check_server_certificate: None, + custom_ca_cert: None, + } + } + + /// Assert a `build_auth_config` failure surfaces as a kernel + /// `InvalidArgument` (napi `Status::InvalidArg` + `"code": + /// "InvalidArgument"` in the error envelope) and that the kernel + /// constructor's message text contains `substr`. The required-field + /// validation now lives in the kernel ctors, so the binding tests + /// assert the kernel error flows through `napi_err_from_kernel`. + fn assert_invalid_arg(err: napi::Error, substr: &str) { + assert_eq!(err.status, napi::Status::InvalidArg); + let reason = err.reason.to_string(); + assert!( + reason.contains("\"code\":\"InvalidArgument\""), + "expected InvalidArgument envelope, got: {reason}" + ); + assert!( + reason.contains(substr), + "expected message to contain {substr:?}, got: {reason}" + ); + } + + #[test] + fn default_mode_is_pat_and_requires_token() { + let mut o = base(); + // No authMode + no token → fail-fast InvalidArgument from the + // kernel `AuthConfig::pat` ctor. + assert_invalid_arg( + build_auth_config(&o).unwrap_err(), + "requires a non-empty access token", + ); + 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_invalid_arg( + build_auth_config(&o).unwrap_err(), + "requires a non-empty access token", + ); + } + + #[test] + fn m2m_requires_client_id_and_secret() { + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthM2m); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_id"); + o.oauth_client_id = Some("cid".to_owned()); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_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:?}"), + } + } + + #[test] + fn tls_defaults_to_secure() { + // No `check_server_certificate` ⇒ secure by default: strict chain + + // hostname validation (the kernel's TlsConfig::default()). A caller + // must opt out explicitly with `check_server_certificate: false`. + let tls = build_tls_config(&base()); + assert!( + !tls.accept_self_signed, + "self-signed must be rejected by default" + ); + assert!( + !tls.skip_hostname_verification, + "hostname check must run by default" + ); + assert!(tls.custom_ca_cert.is_none()); + } + + #[test] + fn tls_strict_when_check_enabled() { + let mut o = base(); + o.check_server_certificate = Some(true); + let tls = build_tls_config(&o); + assert!(!tls.accept_self_signed); + assert!(!tls.skip_hostname_verification); + assert!(tls.custom_ca_cert.is_none()); + } + + #[test] + fn tls_explicit_false_is_permissive() { + let mut o = base(); + o.check_server_certificate = Some(false); + let tls = build_tls_config(&o); + assert!(tls.accept_self_signed); + assert!(tls.skip_hostname_verification); + } + + #[test] + fn tls_custom_ca_threads_through_regardless_of_strictness() { + const PEM: &[u8] = b"-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"; + // Custom CA is honoured in both strict and permissive modes. + for strict in [None, Some(true), Some(false)] { + let mut o = base(); + o.check_server_certificate = strict; + o.custom_ca_cert = Some(PEM.to_vec()); + let tls = build_tls_config(&o); + assert_eq!(tls.custom_ca_cert.as_deref(), Some(PEM)); + } + } +} 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..810c4889 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -39,10 +39,13 @@ #[macro_use] extern crate napi_derive; +pub(crate) mod async_statement; 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..8f8d5e84 --- /dev/null +++ b/napi/src/metadata.rs @@ -0,0 +1,377 @@ +// 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::{ + Error as KernelError, Identifier, LikePattern, Metadata, Result as KResult, ResultStream, +}; + +use crate::connection::{connection_closed_err, Connection}; +use crate::error::napi_err_from_kernel; +use crate::runtime::get_handle; +use crate::statement::Statement; +use crate::util::guarded; + +// ─── Helpers ───────────────────────────────────────────────────────────────── +// +// The `Option` → `Option` / `Option` +// conversion lives on the kernel newtypes as `Identifier::from_opt` / +// `LikePattern::from_opt` (one home shared by all bindings); call sites +// below use those directly and keep the napi error mapping +// (`napi_err_from_kernel`) on the run-on-blocking boundary. + +/// 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(); + // Each metadata RPC parks one blocking-pool thread for the whole wire + // round-trip (the kernel futures are `!Send`; see the doc above). Bracket + // it with debug breadcrumbs so a "metadata hangs under load" incident — a + // fan-out exhausting the blocking pool — is localizable from logs without + // a profiler. (Long-term fix tracked separately: make the metadata futures + // `Send` via `.instrument(span)` so they can await on a worker thread.) + tracing::debug!("metadata RPC: entering blocking pool"); + let stream = tokio::task::spawn_blocking(move || handle.block_on(f())) + .await + .map_err(|e| { + napi_err_from_kernel( + KernelError::internal().message(format!("metadata task join failed: {e}")), + ) + })? + .map_err(napi_err_from_kernel)?; + tracing::debug!("metadata RPC: blocking-pool thread released"); + 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(connection_closed_err)?; + 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 = Identifier::from_opt(&catalog)?; + let pat = LikePattern::from_opt(&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 = Identifier::from_opt(&catalog)?; + let sch = LikePattern::from_opt(&schema_pattern)?; + let tbl = LikePattern::from_opt(&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 = Identifier::from_opt(&catalog)?; + let sch = LikePattern::from_opt(&schema_pattern)?; + let tbl = LikePattern::from_opt(&table_pattern)?; + let col = LikePattern::from_opt(&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 = Identifier::from_opt(&catalog)?; + let sch = LikePattern::from_opt(&schema_pattern)?; + let nam = LikePattern::from_opt(&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 = Identifier::from_opt(&catalog)?; + let sch = LikePattern::from_opt(&schema_pattern)?; + let nam = LikePattern::from_opt(&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 = Identifier::from_opt(&parent_catalog)?; + let ps = Identifier::from_opt(&parent_schema)?; + let pt = Identifier::from_opt(&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 + } +} + +#[cfg(test)] +mod tests { + use super::*; + use databricks_sql_kernel::ErrorCode; + + // The `Option` → kernel-newtype conversion now lives on the + // kernel as `Identifier::from_opt` / `LikePattern::from_opt` (tested + // exhaustively there). These thin smoke tests pin that the binding + // calls through to the same contract — whitespace-only rejects as + // `InvalidArgument`, `None` passes through as `Ok(None)`. + + #[test] + fn identifier_from_opt_rejects_whitespace_only() { + let input = Some(" ".to_owned()); + let err = Identifier::from_opt(&input).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument); + } + + #[test] + fn identifier_from_opt_none_is_ok_none() { + let input: Option = None; + assert!(Identifier::from_opt(&input).unwrap().is_none()); + } + + #[test] + fn like_pattern_from_opt_rejects_whitespace_only() { + let input = Some(" ".to_owned()); + let err = LikePattern::from_opt(&input).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument); + } + + #[test] + fn like_pattern_from_opt_none_is_ok_none() { + let input: Option = None; + assert!(LikePattern::from_opt(&input).unwrap().is_none()); + } +} diff --git a/napi/src/params.rs b/napi/src/params.rs new file mode 100644 index 00000000..733a0588 --- /dev/null +++ b/napi/src/params.rs @@ -0,0 +1,68 @@ +// 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 input types plus a re-export of the kernel codec. +//! +//! The `(sql_type, value_str) -> TypedValue` parsing logic used to live +//! here, duplicated in `pyo3/src/params.rs`. It now lives once in the +//! kernel at `databricks_sql_kernel::statement::params_codec` (re-exported +//! as `databricks_sql_kernel::parse_typed_value`), so both bindings share +//! one codec. As a result `GEOGRAPHY` / `GEOMETRY` are now supported in +//! napi exactly as in pyo3 — the earlier napi-only divergence (geo types +//! falling through to `unsupported parameter SQL type`) is gone. +//! +//! This module re-exports the kernel codec under `crate::params::` so the +//! existing `crate::params::parse_typed_value` callers in `connection.rs` +//! keep resolving unchanged, and it keeps the napi-visible +//! [`TypedValueInput`] struct (referenced by `connection.rs`). +//! +//! Compound types (`ARRAY` / `MAP` / `STRUCT`) and BINARY remain +//! explicitly rejected by the kernel codec — the SEA wire does not accept +//! either as a bound parameter today, surfaced as an `InvalidArgument` +//! error at bind time. + +pub(crate) use databricks_sql_kernel::parse_typed_value; + +/// 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, +} diff --git a/napi/src/result.rs b/napi/src/result.rs index f0515e23..2573bb84 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -19,8 +19,14 @@ //! JavaScript rows…" — so the napi boundary is intentionally narrow: //! one envelope per batch, one envelope per schema. +use arrow_array::RecordBatch; +use arrow_ipc::writer::StreamWriter; +use arrow_schema::SchemaRef; +use databricks_sql_kernel::Error as KernelError; use napi::bindgen_prelude::Buffer; +use crate::error::napi_err_from_kernel; + /// A single Arrow IPC stream payload encoding one record batch (plus /// the schema header so the JS-side reader is stateless). #[napi(object)] @@ -39,3 +45,95 @@ pub struct ArrowSchema { /// the reader will expose the schema and immediately end. pub ipc_bytes: Buffer, } + +/// Encode an Arrow schema (and an optional single record batch) as a +/// complete, self-contained Arrow IPC stream payload. +/// +/// Shared single source of truth for every batch/schema that crosses +/// the napi boundary: the sync `Statement` path (`schema()` / +/// `fetchNextBatch()` in `statement.rs`) and the async +/// `AsyncResultHandle` path (`async_statement.rs`) both call this, so +/// the two emit byte-identical envelopes and route encode failures +/// through the same kernel error envelope (`napi_err_from_kernel`) — +/// the TS reviver sees a typed `KernelError(code='Internal')` rather +/// than a bare `GenericFailure` string. Lives here in `result.rs` +/// because this module already owns `ArrowBatch` / `ArrowSchema`, the +/// payload types these bytes are wrapped in. +/// +/// Returning a self-contained IPC stream per call is wasteful +/// header-wise but lets the JS adapter stay stateless — it decodes +/// each `ipcBytes` independently via the same `apache-arrow` +/// `RecordBatchReader` path. +pub(crate) fn encode_ipc_stream( + schema: &SchemaRef, + batch: Option<&RecordBatch>, +) -> napi::Result> { + fn encode_err(stage: &str, e: impl std::fmt::Display) -> napi::Error { + napi_err_from_kernel( + KernelError::internal().message(format!("Arrow IPC writer {stage} failed: {e}")), + ) + } + // Pre-size the buffer so a typical 500KB batch doesn't reallocate + // ~17 times growing from `Vec::new()`'s default capacity of 0. + // `get_array_memory_size` is the kernel-side memory footprint (close + // enough to the IPC-encoded size for capacity-hint purposes — IPC + // adds ~hundreds of bytes of framing per batch, not orders of + // magnitude). 4 KiB slack covers the schema-header on the + // schema-only path (`batch = None`) and the framing overhead on + // the schema+batch path. + let estimated = batch.map(|rb| rb.get_array_memory_size()).unwrap_or(0) + 4096; + let mut buf: Vec = Vec::with_capacity(estimated); + { + let mut writer = + StreamWriter::try_new(&mut buf, schema).map_err(|e| encode_err("init", e))?; + if let Some(rb) = batch { + writer.write(rb).map_err(|e| encode_err("write", e))?; + } + writer.finish().map_err(|e| encode_err("finish", e))?; + } + Ok(buf) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::Int32Array; + use arrow_ipc::reader::StreamReader; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + fn make_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])) + } + + #[test] + fn encode_ipc_stream_schema_only_yields_zero_batches() { + let schema = make_schema(); + let bytes = encode_ipc_stream(&schema, None).expect("encode succeeds"); + let reader = StreamReader::try_new(bytes.as_slice(), None).expect("reader opens"); + let decoded_schema = reader.schema(); + let batches: Vec<_> = reader + .collect::, _>>() + .expect("decode succeeds"); + assert_eq!(decoded_schema.fields(), schema.fields()); + assert_eq!(batches.len(), 0, "schema-only payload yields 0 batches"); + } + + #[test] + fn encode_ipc_stream_schema_plus_batch_round_trips() { + let schema = make_schema(); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .expect("batch builds"); + let bytes = encode_ipc_stream(&schema, Some(&batch)).expect("encode succeeds"); + let reader = StreamReader::try_new(bytes.as_slice(), None).expect("reader opens"); + let decoded: Vec<_> = reader + .collect::, _>>() + .expect("decode succeeds"); + assert_eq!(decoded.len(), 1, "exactly one batch decoded"); + assert_eq!(decoded[0].num_rows(), 3); + assert_eq!(decoded[0].schema().fields(), schema.fields()); + } +} diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 84c734e2..13118901 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -33,10 +33,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; 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 +69,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 +111,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 +152,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] @@ -166,7 +221,10 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.num_modified_rows()) + match inner_state { + AnyInner::Executed(s) => Ok(s.executed.num_modified_rows()), + AnyInner::Metadata(_) => Ok(None), + } }) .await } @@ -198,7 +256,10 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.display_message().map(str::to_owned)) + match inner_state { + AnyInner::Executed(s) => Ok(s.executed.display_message().map(str::to_owned)), + AnyInner::Metadata(_) => Ok(None), + } }) .await } @@ -214,7 +275,10 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.diagnostic_info().map(str::to_owned)) + match inner_state { + AnyInner::Executed(s) => Ok(s.executed.diagnostic_info().map(str::to_owned)), + AnyInner::Metadata(_) => Ok(None), + } }) .await } @@ -239,7 +303,10 @@ impl Statement { guarded(async move { let guard = inner.lock().await; let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?; - Ok(inner_state.executed.error_details_json().map(str::to_owned)) + match inner_state { + AnyInner::Executed(s) => Ok(s.executed.error_details_json().map(str::to_owned)), + AnyInner::Metadata(_) => Ok(None), + } }) .await } @@ -261,9 +328,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 @@ -298,7 +370,7 @@ impl Statement { )); } }; - let bytes = encode_ipc_stream(&schema, Some(record_batch))?; + let bytes = crate::result::encode_ipc_stream(&schema, Some(record_batch))?; Ok(Some(ArrowBatch { ipc_bytes: bytes.into(), })) @@ -321,7 +393,7 @@ impl Statement { /// entry points use is not required for this method. #[napi] pub fn schema(&self) -> napi::Result { - let bytes = encode_ipc_stream(&self.schema, None)?; + let bytes = crate::result::encode_ipc_stream(&self.schema, None)?; Ok(ArrowSchema { ipc_bytes: bytes.into(), }) @@ -329,11 +401,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 +420,39 @@ 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, so the + // query keeps running server-side. Emit a breadcrumb so a + // "cancel() didn't cancel" report is diagnosable from logs. + AnyInner::Metadata(_) => { + tracing::debug!( + "cancel() on a metadata statement is a no-op (no server-side cancel handle); the query continues server-side" + ); + 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 +468,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(()) }) @@ -447,80 +543,19 @@ fn statement_closed_err() -> napi::Error { ) } -/// Encode an Arrow schema (and optional one record batch) as an IPC -/// stream payload. Used for both `schema()` (schema only) and -/// `fetchNextBatch()` (schema + one batch). Returning a self-contained -/// IPC stream per call is wasteful header-wise but lets the JS adapter -/// stay stateless — it decodes each `ipcBytes` independently via the -/// same `apache-arrow` `RecordBatchReader` path. -fn encode_ipc_stream( - schema: &arrow_schema::SchemaRef, - batch: Option<&arrow_array::RecordBatch>, -) -> napi::Result> { - fn arrow_err(e: impl std::fmt::Display) -> napi::Error { - napi::Error::new(napi::Status::GenericFailure, e.to_string()) - } - // Pre-size the buffer so a typical 500KB batch doesn't reallocate - // ~17 times growing from `Vec::new()`'s default capacity of 0. - // `get_array_memory_size` is the kernel-side memory footprint (close - // enough to the IPC-encoded size for capacity-hint purposes — IPC - // adds ~hundreds of bytes of framing per batch, not orders of - // magnitude). 4 KiB slack covers the schema-header on the - // schema-only path (`batch = None`) and the framing overhead on - // the schema+batch path. - let estimated = batch.map(|rb| rb.get_array_memory_size()).unwrap_or(0) + 4096; - let mut buf: Vec = Vec::with_capacity(estimated); - { - let mut writer = StreamWriter::try_new(&mut buf, schema).map_err(arrow_err)?; - if let Some(rb) = batch { - writer.write(rb).map_err(arrow_err)?; - } - writer.finish().map_err(arrow_err)?; - } - Ok(buf) -} - #[cfg(test)] mod tests { use super::*; - use arrow_array::{Int32Array, RecordBatch}; - use arrow_ipc::reader::StreamReader; use arrow_schema::{DataType, Field, Schema}; fn make_schema() -> Arc { Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])) } - #[test] - fn encode_ipc_stream_schema_only_yields_zero_batches() { - let schema = make_schema(); - let bytes = encode_ipc_stream(&schema, None).expect("encode succeeds"); - let reader = StreamReader::try_new(bytes.as_slice(), None).expect("reader opens"); - let decoded_schema = reader.schema(); - let batches: Vec<_> = reader - .collect::, _>>() - .expect("decode succeeds"); - assert_eq!(decoded_schema.fields(), schema.fields()); - assert_eq!(batches.len(), 0, "schema-only payload yields 0 batches"); - } - - #[test] - fn encode_ipc_stream_schema_plus_batch_round_trips() { - let schema = make_schema(); - let batch = RecordBatch::try_new( - schema.clone(), - vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], - ) - .expect("batch builds"); - let bytes = encode_ipc_stream(&schema, Some(&batch)).expect("encode succeeds"); - let reader = StreamReader::try_new(bytes.as_slice(), None).expect("reader opens"); - let decoded: Vec<_> = reader - .collect::, _>>() - .expect("decode succeeds"); - assert_eq!(decoded.len(), 1, "exactly one batch decoded"); - assert_eq!(decoded[0].num_rows(), 3); - assert_eq!(decoded[0].schema().fields(), schema.fields()); - } + // Arrow IPC encoding is exercised by `encode_ipc_stream`'s own + // round-trip tests in `result.rs` (its new home — see the + // encoder-lift refactor). `schema()` / `fetchNextBatch()` just + // delegate to it, so the load-bearing assertions live there. // ─── Closed-state behaviour ───────────────────────────────────── // @@ -624,4 +659,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/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs index 7e42d9be..55a54767 100644 --- a/pyo3/src/executed_async.rs +++ b/pyo3/src/executed_async.rs @@ -29,23 +29,6 @@ use pyo3::prelude::*; use std::sync::Arc; use tokio::runtime::Runtime; -/// Map a kernel `StatementStatus` to a stable string slug. Matches -/// the connector's `CommandState` taxonomy one-for-one so the Python -/// side can branch on the result without holding a reference to a -/// `StatementStatus` enum. -fn status_str(status: &StatementStatus) -> &'static str { - match status { - StatementStatus::Pending => "Pending", - StatementStatus::Running => "Running", - StatementStatus::Succeeded => "Succeeded", - StatementStatus::Failed(_) => "Failed", - StatementStatus::Cancelled => "Cancelled", - StatementStatus::Closed => "Closed", - // `StatementStatus` is `#[non_exhaustive]`. - _ => "Unknown", - } -} - #[pyclass(name = "ExecutedAsyncStatement")] pub(crate) struct ExecutedAsyncStatement { inner: Option, @@ -95,7 +78,9 @@ impl ExecutedAsyncStatement { let inner = alive!(self, "ExecutedAsyncStatement"); let runtime = inner.runtime.clone(); let status = run_kernel!(py, runtime, inner.exec.status())?; - let state = status_str(&status); + // String mapping lives on the kernel `StatementStatus::as_str` + // so all bindings share one taxonomy. + let state = status.as_str(); let failure: Bound<'py, PyAny> = match &status { StatementStatus::Failed(err) => { // Build the KernelError instance the same way every diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs index f3cae519..0c0a8eed 100644 --- a/pyo3/src/metadata.rs +++ b/pyo3/src/metadata.rs @@ -42,7 +42,7 @@ //! conversions stay explicit and grep-able. use crate::result_stream::ResultStream; -use databricks_sql_kernel::{Identifier, LikePattern, Metadata as KMetadata, Result as KResult}; +use databricks_sql_kernel::{Identifier, LikePattern, Metadata as KMetadata}; use pyo3::prelude::*; use std::sync::Arc; use tokio::runtime::Runtime; @@ -64,16 +64,11 @@ impl Metadata { } } -/// Build a kernel `Identifier` from an optional Python string, or -/// `None` if the input was `None`. Empty / NUL / backtick rejection -/// happens kernel-side and surfaces as `InvalidArgument`. -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() -} +// The `Option` → `Option` / `Option` +// conversion lives on the kernel newtypes as `Identifier::from_opt` / +// `LikePattern::from_opt` (one home shared by all bindings, with empty / +// NUL / backtick / whitespace rejection kernel-side surfacing as +// `InvalidArgument`). Call sites below use those directly. #[pymethods] impl Metadata { @@ -92,8 +87,8 @@ impl Metadata { schema_pattern: Option, ) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { - let cat = opt_identifier(&catalog)?; - let pat = opt_pattern(&schema_pattern)?; + let cat = Identifier::from_opt(&catalog)?; + let pat = LikePattern::from_opt(&schema_pattern)?; self.inner.list_schemas(cat, pat).await })?; Ok(ResultStream::new(stream, self.runtime.clone())) @@ -113,9 +108,9 @@ impl Metadata { table_types: Option>, ) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { - let cat = opt_identifier(&catalog)?; - let sch = opt_pattern(&schema_pattern)?; - let tbl = opt_pattern(&table_pattern)?; + let cat = Identifier::from_opt(&catalog)?; + let sch = LikePattern::from_opt(&schema_pattern)?; + let tbl = LikePattern::from_opt(&table_pattern)?; let types_owned: Option> = table_types .as_ref() .map(|v| v.iter().map(String::as_str).collect()); @@ -142,9 +137,9 @@ impl Metadata { Some(s) => Some(Identifier::new(s)?), None => None, }; - let sch = opt_pattern(&schema_pattern)?; - let tbl = opt_pattern(&table_pattern)?; - let col = opt_pattern(&column_pattern)?; + let sch = LikePattern::from_opt(&schema_pattern)?; + let tbl = LikePattern::from_opt(&table_pattern)?; + let col = LikePattern::from_opt(&column_pattern)?; self.inner.list_columns(cat, sch, tbl, col).await })?; Ok(ResultStream::new(stream, self.runtime.clone())) @@ -186,9 +181,9 @@ impl Metadata { foreign_table: String, ) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { - let pc = opt_identifier(&parent_catalog)?; - let ps = opt_identifier(&parent_schema)?; - let pt = opt_identifier(&parent_table)?; + let pc = Identifier::from_opt(&parent_catalog)?; + let ps = Identifier::from_opt(&parent_schema)?; + let pt = Identifier::from_opt(&parent_table)?; let fc = Some(Identifier::new(&foreign_catalog)?); let fs = Some(Identifier::new(&foreign_schema)?); let ft = Some(Identifier::new(&foreign_table)?); @@ -207,9 +202,9 @@ impl Metadata { name_pattern: Option, ) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { - let cat = opt_identifier(&catalog)?; - let sch = opt_pattern(&schema_pattern)?; - let nam = opt_pattern(&name_pattern)?; + let cat = Identifier::from_opt(&catalog)?; + let sch = LikePattern::from_opt(&schema_pattern)?; + let nam = LikePattern::from_opt(&name_pattern)?; self.inner.functions(cat, sch, nam).await })?; Ok(ResultStream::new(stream, self.runtime.clone())) @@ -225,9 +220,9 @@ impl Metadata { name_pattern: Option, ) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { - let cat = opt_identifier(&catalog)?; - let sch = opt_pattern(&schema_pattern)?; - let nam = opt_pattern(&name_pattern)?; + let cat = Identifier::from_opt(&catalog)?; + let sch = LikePattern::from_opt(&schema_pattern)?; + let nam = LikePattern::from_opt(&name_pattern)?; self.inner.procedures(cat, sch, nam).await })?; Ok(ResultStream::new(stream, self.runtime.clone())) diff --git a/pyo3/src/params.rs b/pyo3/src/params.rs index 5a8ce95d..b74d21d5 100644 --- a/pyo3/src/params.rs +++ b/pyo3/src/params.rs @@ -12,1011 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Parse a connector-style `(sql_type, value_str)` pair into a -//! kernel `TypedValue`. +//! Thin re-export of the kernel parameter codec. //! -//! The PySQL connector hands us parameters as -//! ``TSparkParameter(type="INT", value=stringValue("42"))`` — -//! the value is always a string, and the SQL type carries the -//! intent. To avoid a Python ↔ Rust round-trip through native -//! Python types, the PyO3 surface takes the string form directly -//! and we parse it here. -//! -//! Compound types (``ARRAY`` / ``MAP`` / ``STRUCT``) and the -//! never-used named-binding mode are explicitly rejected — the -//! connector backend surfaces those as ``NotSupportedError``. - -use chrono::{NaiveDate, NaiveDateTime}; -use databricks_sql_kernel::statement::spec::geo_wire; -use databricks_sql_kernel::{Error, Result, TypedValue}; - -/// Parse a Databricks SQL type name + string-encoded value into a -/// kernel ``TypedValue``. -/// -/// ``value_str = None`` always produces ``TypedValue::Null``, -/// regardless of ``sql_type`` — matches the connector's -/// ``VoidParameter`` shape. -/// -/// ``sql_type`` is the canonical SQL type name the connector -/// produces (``"INT"``, ``"BIGINT"``, ``"STRING"``, etc.). For -/// DECIMAL, the form is ``"DECIMAL(precision,scale)"``; we parse -/// the parenthesized form to populate ``TypedValue::Decimal``'s -/// precision/scale fields so the kernel doesn't have to default -/// them to ``DECIMAL(10, 0)`` on the wire (which loses fractional -/// digits — see `statement/params.rs` for the kernel-side -/// rationale). -/// -/// Errors are ``Error::invalid_argument()`` so they surface to the -/// Python caller as ``KernelError(code='InvalidArgument', ...)``. -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, - }; - - // Normalise to uppercase for the simple variants; DECIMAL keeps - // its case-sensitive parenthesised form so we can extract - // precision/scale. - 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), - // The three timestamp variants map to three distinct TypedValue - // arms so the SEA wire payload carries the exact type-name - // string the server expects. `TIMESTAMP` and `TIMESTAMP_NTZ` - // share `parse_timestamp` for the naive-datetime parsing; the - // NTZ arm re-wraps as `TimestampNtz` so the SEA payload mapper - // 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 — pass the JSON text through verbatim. We don't - // validate parseability: the connector is expected to have - // produced valid JSON (Python's `json.dumps`, JS's - // `JSON.stringify`, etc.), and on a malformed payload the - // server returns a typed error which the kernel surfaces - // back to the caller. - // - // Note on the JSON-null vs SQL-NULL asymmetry: a caller - // binding a JSON `null` value sends `value_str=Some("null")` - // and lands here as `TypedValue::Variant("null")` — a VARIANT - // column containing the JSON-null value. The SQL-NULL path is - // distinct: `value_str=None` short-circuits at the top of - // this function to `TypedValue::Null` regardless of - // `sql_type`. Both are correct and intentionally different. - // Don't "fix" this by collapsing `Variant("null")` into - // `TypedValue::Null` — JSON-null is a meaningful VARIANT - // payload that the server stores and reads back as a JSON - // `null` literal, not as SQL NULL. - "VARIANT" => Ok(TypedValue::Variant(s.to_owned())), - _ if upper.starts_with("DECIMAL(") => parse_decimal(sql_type, s), - _ if is_geo_type_name(&upper, geo_wire::GEOGRAPHY) => parse_geography(&upper, s), - _ if is_geo_type_name(&upper, geo_wire::GEOMETRY) => parse_geometry(&upper, 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 the bare geo family name or the SRID-decorated -/// form (e.g. `"GEOGRAPHY"`, `"GEOGRAPHY(4326)"`). The closing paren -/// is required so we don't false-positive on hypothetical -/// `"GEOGRAPHYX"`. -fn is_geo_type_name(upper: &str, family: &str) -> bool { - if upper == family { - return true; - } - if let Some(rest) = upper.strip_prefix(family) { - return rest.starts_with('(') && rest.ends_with(')'); - } - false -} - -/// True iff `upper` is one of ARRAY/MAP/STRUCT exactly, or one of -/// those followed by `<` (generic) or `(` (function-style). This is -/// 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}")))?; - // `str::parse::()` returns ±inf for overflow ("1e500") and - // NaN for the literals "nan"/"NaN", both of which the SEA wire - // can't represent. Reject so bad literals fail at bind time - // rather than producing a misleading row at execute time. - 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 { - // The connector's TimestampParameter stringifies via str(), - // which on a Python datetime produces ``YYYY-MM-DD HH:MM:SS`` - // optionally with ``.microseconds``. Accept both with and - // without sub-second precision. - // - // Also accept the trailing-``Z`` UTC marker that JavaScript's - // ``Date.prototype.toISOString()`` always emits — 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:?}"))) -} - -/// Parse a `TIMESTAMP_LTZ` literal into a tz-aware `DateTime`. -/// -/// Accepts three input shapes, all interpreted as UTC on the wire: -/// -/// 1. Naive form (`"2026-05-15 12:30:45[.f]"` or T-separator) — the -/// value is taken as UTC. This matches what Python's -/// `datetime.utcnow().isoformat()` produces. -/// 2. Trailing `Z` (`"2026-05-15T12:30:45Z"`) — explicit UTC marker; -/// same semantics as #1 after stripping `Z`. -/// 3. Explicit offset (`"2026-05-15T12:30:45+05:30"`) — parsed and -/// converted to UTC, preserving the wall-clock-to-instant -/// relationship. -/// -/// The naive form is what most connector code emits today; the -/// offset form covers callers using Python `datetime.astimezone(tz).isoformat()`. -fn parse_timestamp_ltz(s: &str) -> Result { - use chrono::{DateTime, FixedOffset, Utc}; - - // Try explicit-offset (RFC 3339) form first — covers `+HH:MM` and - // `Z` suffix in one call. - if let Ok(dt) = DateTime::::parse_from_rfc3339(s) { - return Ok(TypedValue::TimestampLtz(dt.with_timezone(&Utc))); - } - // Also try the space-separated equivalent (`%Y-%m-%d %H:%M:%S%.f%:z`) - // which Python's `datetime.astimezone().isoformat(sep=' ')` - // happens to emit. - 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))); - } - // Fall back to the naive forms `parse_timestamp` accepts, treating - // them as UTC. Strip trailing `Z` first. - 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:?}"))) -} - -/// Parse a `GEOGRAPHY` binding. -/// -/// `upper` is the uppercased type-name as received from the -/// connector — bare `"GEOGRAPHY"` or SRID-decorated -/// `"GEOGRAPHY(4326)"`. `value` is the textual binding — -/// either bare WKT (`"POINT(1 2)"`) or EWKT -/// (`"SRID=4326;POINT(1 2)"`). -/// -/// SRID precedence: if both the type-name and the value carry an -/// SRID, they MUST agree. Disagreement is an `InvalidArgument` -/// error — silently picking one would hide a connector bug. -fn parse_geography(upper: &str, value: &str) -> Result { - let (wkt, srid) = parse_ewkt_with_type_srid(upper, geo_wire::GEOGRAPHY, value)?; - Ok(TypedValue::Geography { - wkt, - srid, - wkb: None, - }) -} - -/// Parse a `GEOMETRY` binding. Same rules as `parse_geography`. -fn parse_geometry(upper: &str, value: &str) -> Result { - let (wkt, srid) = parse_ewkt_with_type_srid(upper, geo_wire::GEOMETRY, value)?; - Ok(TypedValue::Geometry { - wkt, - srid, - wkb: None, - }) -} - -/// Common geo-binding parser. Returns `(wkt, srid)` where `wkt` has -/// no `SRID=N;` prefix. -fn parse_ewkt_with_type_srid( - upper: &str, - family: &str, - value: &str, -) -> Result<(String, Option)> { - let type_srid = extract_type_srid(upper, family)?; - let (value_srid, wkt) = split_ewkt(value)?; - - // Reject empty WKT at the kernel boundary. The server would - // also reject this, but doing it locally gives a clearer - // error message that names the type-family and avoids a - // round-trip on what's almost certainly a connector bug. - // `"SRID=4326;"` (SRID prefix but no WKT body) is the most - // likely shape that lands here — `split_ewkt` happily strips - // the prefix and leaves an empty body. - if wkt.trim().is_empty() { - return Err(invalid_msg(format!( - "{family} binding has empty WKT body (value: {value:?})" - ))); - } - - let srid = match (type_srid, value_srid) { - (Some(t), Some(v)) if t != v => { - return Err(invalid_msg(format!( - "SRID mismatch: {family} type-name says {t} but value EWKT prefix says {v}" - ))); - } - (Some(t), _) => Some(t), - (None, Some(v)) => Some(v), - (None, None) => None, - }; - - Ok((wkt.to_owned(), srid)) -} - -/// Pull the SRID out of a decorated type-name like -/// `"GEOGRAPHY(4326)"`. Returns `Ok(None)` for the bare form. -fn extract_type_srid(upper: &str, family: &str) -> Result> { - let Some(rest) = upper.strip_prefix(family) else { - return Ok(None); - }; - if rest.is_empty() { - return Ok(None); - } - // Must be `(N)` — `is_geo_type_name` already accepted the shape. - let inner = rest - .strip_prefix('(') - .and_then(|r| r.strip_suffix(')')) - .ok_or_else(|| invalid_msg(format!("malformed {family} type-name: {upper:?}")))?; - inner - .trim() - .parse::() - .map(Some) - .map_err(|e| invalid_msg(format!("invalid {family} SRID {inner:?}: {e}"))) -} - -/// Split an EWKT string into `(srid, wkt_body)`. If there's no -/// `SRID=N;` prefix the SRID is `None` and the whole string is the -/// WKT body. Whitespace inside the prefix is tolerated -/// (`"SRID = 4326 ; POINT(...)"`). -fn split_ewkt(value: &str) -> Result<(Option, &str)> { - let trimmed = value.trim_start(); - // Case-insensitive ASCII match on the EWKT SRID prefix - // (`geo_wire::EWKT_SRID_PREFIX`, today literally `"SRID="`). - // Operating on bytes is safe here because the prefix is pure - // ASCII; a non-ASCII byte at index 0 fails the comparison - // without splitting a UTF-8 code point. - let prefix = geo_wire::EWKT_SRID_PREFIX.as_bytes(); - let bytes = trimmed.as_bytes(); - if bytes.len() < prefix.len() || !bytes[..prefix.len()].eq_ignore_ascii_case(prefix) { - return Ok((None, value)); - } - // Find the `;` that terminates the SRID prefix. - let after_eq = &trimmed[prefix.len()..]; - let semi = after_eq.find(';').ok_or_else(|| { - invalid_msg(format!( - "malformed EWKT: missing ';' after SRID prefix: {value:?}" - )) - })?; - let srid_text = after_eq[..semi].trim(); - let srid: i32 = srid_text - .parse() - .map_err(|e| invalid_msg(format!("invalid EWKT SRID {srid_text:?}: {e}")))?; - let wkt = after_eq[semi + 1..].trim_start(); - Ok((Some(srid), wkt)) -} - -fn parse_decimal(sql_type: &str, value: &str) -> Result { - // Extract precision/scale from "DECIMAL(p,s)" / "DECIMAL(p)" / - // "Decimal(p, s)". - let (precision, scale) = extract_decimal_precision_scale(sql_type)?; - // Validate the value itself parses as a finite decimal number, - // so bad literals like ``bind_param(1, "abc", "DECIMAL(10,2)")`` - // fail at bind time rather than at execute. The kernel's - // ``TypedValue::Decimal`` carries the value as a string and - // doesn't re-validate. - 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 (``-123.45``, ``0``, ``123``). Forms like ``42.``, -/// ``.5`` and the bare sign ``-`` are rejected to match -/// Databricks' DECIMAL literal parser — they'd otherwise pass -/// bind-time validation here and surface as a server error at -/// execute, defeating the headline "bad literal fails at bind" -/// contract. -/// -/// 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)> { - // sql_type looks like "DECIMAL(10,2)", "DECIMAL(10, 2)", - // "DECIMAL(38)" (scale defaults to 0), or "Decimal(10,2)" - // depending on casing. - 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. The server accepts precision in - // ``1..=38`` and scale in ``-(38 - precision)..=precision`` - // (negative scale rounds to multiples of ``10^|s|``), but no - // current Databricks connector emits negative-scale DECIMAL - // parameters and the kernel's ``TypedValue::Decimal`` doesn't - // round-trip them cleanly. Reject here so obvious junk like - // ``DECIMAL(0,0)`` or ``DECIMAL(255,127)`` fails at bind time; - // when a negative-scale caller materialises, widen this check - // and the ``i8`` scale parse together. - 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; - - // None → Null regardless of SQL type - #[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("BIGINT", 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); - } - - #[test] - fn floats_parse() { - assert!(matches!( - parse_typed_value("FLOAT", Some("3.14")).unwrap(), - TypedValue::Float32(_) - )); - assert!(matches!( - parse_typed_value("DOUBLE", Some("3.141592653589793")).unwrap(), - TypedValue::Float64(_) - )); - } - - #[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:?}"), - } - // VARCHAR / CHAR aliases. - assert!(matches!( - parse_typed_value("VARCHAR", Some("x")).unwrap(), - TypedValue::String(_) - )); - } - - #[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_with_and_without_microseconds() { - 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(_))); - // ISO-8601 T-separator variant (some Python datetime formatters use it). - let c = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45")).unwrap(); - assert!(matches!(c, TypedValue::Timestamp(_))); - } - - #[test] - fn timestamp_ntz_maps_to_distinct_variant() { - // Same literal as TIMESTAMP, but the type-name distinguishes: - // TIMESTAMP_NTZ → TypedValue::TimestampNtz, not Timestamp. - let v = parse_typed_value("TIMESTAMP_NTZ", Some("2026-05-15 12:30:45")).unwrap(); - assert!(matches!(v, TypedValue::TimestampNtz(_))); - let v = parse_typed_value("TIMESTAMP_NTZ", Some("2026-05-15T12:30:45.123Z")).unwrap(); - assert!(matches!(v, TypedValue::TimestampNtz(_))); - } - - #[test] - fn timestamp_ltz_parses_naive_offset_and_z_forms() { - // Naive form — interpreted as UTC. - 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" - ); - - // Trailing-Z form — equivalent UTC. - let v = parse_typed_value("TIMESTAMP_LTZ", Some("2026-05-15T12:30:45Z")).unwrap(); - assert!(matches!(v, TypedValue::TimestampLtz(_))); - - // Explicit positive offset — wall-clock 18:00 in +05:30 → - // 12:30 UTC. Confirms tz conversion (not just stripping). - 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 timestamp_ltz_rejects_invalid_literal() { - let e = parse_typed_value("TIMESTAMP_LTZ", Some("not-a-timestamp")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - } - - #[test] - fn variant_passes_json_text_through() { - // Object form — verbatim through to TypedValue::Variant. - let json = r#"{"k":1,"nested":{"a":[true,null]}}"#; - let v = parse_typed_value("VARIANT", Some(json)).unwrap(); - match v { - TypedValue::Variant(s) => assert_eq!(s, json), - other => panic!("expected Variant, got {other:?}"), - } - } - - #[test] - fn variant_accepts_scalar_json_values() { - // VARIANT permits any JSON value, not just objects / arrays. - // Note: `"null"` here is a JSON-null literal inside the VARIANT - // (i.e. `TypedValue::Variant("null".into())`), NOT SQL NULL. - // SQL NULL is reached via `value_str=None`, which short- - // circuits to `TypedValue::Null` before this match arm. See - // the comment on the `"VARIANT"` arm in `parse_typed_value`. - for raw in [r#""hello""#, "42", "true", "null", "[1,2,3]"] { - let v = parse_typed_value("VARIANT", Some(raw)).unwrap(); - assert!(matches!(v, TypedValue::Variant(_)), "case {raw}"); - } - } - - #[test] - fn variant_does_not_validate_json() { - // The kernel doesn't parse VARIANT — malformed JSON is the - // server's job to reject. Confirms we don't accidentally - // pre-validate at the kernel boundary. - let v = parse_typed_value("VARIANT", Some("not even close to json")).unwrap(); - assert!(matches!(v, TypedValue::Variant(_))); - } - - #[test] - fn geography_decorated_type_with_ewkt_value() { - // The most common shape: connector tells us SRID via the - // type-name AND embeds it in the value EWKT prefix. - let v = parse_typed_value("GEOGRAPHY(4326)", Some("SRID=4326;POINT(1 2)")).unwrap(); - match v { - TypedValue::Geography { wkt, srid, wkb } => { - assert_eq!(wkt, "POINT(1 2)"); - assert_eq!(srid, Some(4326)); - assert!(wkb.is_none(), "wkb stays None on the EWKT path"); - } - other => panic!("expected Geography, got {other:?}"), - } - } - - #[test] - fn geography_bare_type_with_ewkt_value() { - // Connector lacks the SRID decorator in the type-name, but - // the value EWKT carries one. SRID comes from the value. - let v = parse_typed_value("GEOGRAPHY", Some("SRID=4326;POINT(1 2)")).unwrap(); - let TypedValue::Geography { wkt, srid, .. } = v else { - panic!("expected Geography"); - }; - assert_eq!(wkt, "POINT(1 2)"); - assert_eq!(srid, Some(4326)); - } - - #[test] - fn geography_decorated_type_with_bare_wkt_value() { - // SRID only in the type-name. Value has no EWKT prefix. - let v = parse_typed_value("GEOGRAPHY(4326)", Some("POINT(1 2)")).unwrap(); - let TypedValue::Geography { wkt, srid, .. } = v else { - panic!("expected Geography"); - }; - assert_eq!(wkt, "POINT(1 2)"); - assert_eq!(srid, Some(4326)); - } - - #[test] - fn geography_bare_type_with_bare_wkt_value() { - // No SRID anywhere — legal per the SEA design (`srid: None`). - let v = parse_typed_value("GEOGRAPHY", Some("POINT(1 2)")).unwrap(); - let TypedValue::Geography { wkt, srid, .. } = v else { - panic!("expected Geography"); - }; - assert_eq!(wkt, "POINT(1 2)"); - assert!(srid.is_none()); - } - - #[test] - fn geography_rejects_srid_mismatch() { - // Connector bug: type-name and EWKT prefix disagree. Better - // to surface as InvalidArgument than to silently pick one. - let e = parse_typed_value("GEOGRAPHY(4326)", Some("SRID=3857;POINT(1 2)")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - } - - #[test] - fn geometry_round_trips_like_geography() { - // GEOMETRY uses the same parser; sanity-check the dispatch. - let v = parse_typed_value("GEOMETRY(0)", Some("LINESTRING(0 0,1 1)")).unwrap(); - let TypedValue::Geometry { wkt, srid, wkb } = v else { - panic!("expected Geometry"); - }; - assert_eq!(wkt, "LINESTRING(0 0,1 1)"); - assert_eq!(srid, Some(0)); - assert!(wkb.is_none()); - } - - #[test] - fn geo_type_name_does_not_overreach() { - // `GEOGRAPHYX` / `GEOMETRYBUFFER` must NOT match — same - // discipline as the compound-type matcher. - let e = parse_typed_value("GEOGRAPHYX", Some("POINT(1 2)")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - let e = parse_typed_value("GEOMETRYBUFFER", Some("POINT(1 2)")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - } - - #[test] - fn geography_rejects_malformed_ewkt() { - // SRID= prefix with no terminating ';'. - let e = parse_typed_value("GEOGRAPHY", Some("SRID=4326 POINT(1 2)")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - // Non-numeric SRID in the prefix. - let e = parse_typed_value("GEOGRAPHY", Some("SRID=abc;POINT(1 2)")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - } - - #[test] - fn geography_rejects_empty_wkt_body() { - // Various shapes that produce an empty WKT body after the - // EWKT split. Each should surface as `InvalidArgument` at - // the kernel boundary rather than round-tripping to the - // server. - for empty_shape in [ - "", // wholly empty - " ", // only whitespace - "SRID=4326;", // SRID prefix with no body - "SRID=4326; ", - ] { - let e = parse_typed_value("GEOGRAPHY", Some(empty_shape)).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument, "case {empty_shape:?}",); - } - // Same expectation for GEOMETRY. - let e = parse_typed_value("GEOMETRY", Some("")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - } - - #[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 binary_is_rejected() { - // BINARY is documented kernel-side as unsupported on the - // SEA wire today; the connector backend will need its own - // unhex(?) workaround if a user passes BinaryParameter. - let e = parse_typed_value("BINARY", Some("cafe")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - assert!(e.message.contains("BINARY")); - } - - #[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 unknown_type_errors() { - let e = parse_typed_value("MAGIC", Some("x")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument); - } - - #[test] - fn lowercase_sql_type_works() { - // The connector uppercases via DatabricksSupportedType.name, - // but accept lowercase too for robustness. - 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 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:?}"), - } - } - - #[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 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() { - // The headline contract — `bind_param(1, "abc", "DECIMAL(10,2)")` - // must fail at bind time, not at execute. - 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_accepts_canonical_value_literals() { - // Only forms with at least one digit on each side of the dot - // (or no dot at all). Databricks' DECIMAL literal parser - // rejects "42." and ".5" — so do we, see the dedicated - // rejection test below. - for v in ["0", "-0", "-123.45", "0.0001", "+1.5", "123"] { - let r = parse_typed_value("DECIMAL(10,4)", Some(v)); - assert!(r.is_ok(), "expected {v:?} to parse: {:?}", r.err()); - } - } - - #[test] - fn decimal_rejects_partial_dot_forms() { - // "42." (no fractional digits) and ".5" (no integer digits) - // round-trip past Rust's `str::parse::()` but the - // Databricks server rejects them, so we reject at bind time - // to keep the headline contract honest. The bare sign "-" - // is the obvious adjacent case. - 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)", // precision below 1 - "DECIMAL(39,0)", // precision above 38 - "DECIMAL(10,11)", // scale above precision - "DECIMAL(10,-1)", // scale below 0 - ] { - let e = parse_typed_value(ty, Some("1.0")).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidArgument, "{ty}"); - } - } - - #[test] - fn timestamp_accepts_trailing_z() { - 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 compound_match_does_not_overreach() { - // `ARRAYBUFFER` / `MAPLE` / `STRUCTURE` are not real - // Databricks types, but the compound-rejection branch should - // not claim them — they should fall through to the generic - // "unsupported parameter SQL type" message. - 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 - ); - } - // ARRAY/MAP/STRUCT with bracket or paren forms are still - // recognised as compound types. - for ty in ["ARRAY", "ARRAY", "ARRAY(INT)", "MAP"] { - let e = parse_typed_value(ty, Some("x")).unwrap_err(); - assert!( - e.message.contains("compound"), - "{ty} should be compound, got {}", - e.message - ); - } - } -} +//! The `(sql_type, value_str) -> TypedValue` parsing logic used to live +//! here, duplicated in `napi/src/params.rs`. It now lives once in the +//! kernel at `databricks_sql_kernel::statement::params_codec` (re-exported +//! as `databricks_sql_kernel::parse_typed_value`), so both bindings share +//! a single source of truth and can never diverge in what the kernel sees +//! on the wire. This module just re-exports it under `crate::params::` so +//! the existing `crate::params::parse_typed_value` callers in +//! `statement.rs` keep resolving unchanged. + +pub(crate) use databricks_sql_kernel::parse_typed_value; diff --git a/pyo3/tests/test_execute.py b/pyo3/tests/test_execute.py index 741eb502..19fa9220 100644 --- a/pyo3/tests/test_execute.py +++ b/pyo3/tests/test_execute.py @@ -266,6 +266,29 @@ def test_bind_param_duplicate_ordinal_last_wins(session): stmt.close() +@live +def test_mixed_positional_and_named_params_rejected_at_execute(session): + """Positional and named bindings are mutually exclusive. The kernel + rejects them at execute time (bind just records them) with + ``KernelError(InvalidArgument)`` — before the wire — so the Python + binding gets the same fast, typed failure that napi and direct-Rust + callers do, instead of an opaque server BAD_REQUEST round-trip.""" + stmt = session.statement() + stmt.set_sql("SELECT ? AS pos, :n AS named") + stmt.bind_param(1, "7", "INT") + stmt.bind_named_param("n", "99", "INT") + try: + try: + stmt.execute() + except k.KernelError as e: + assert e.code == "InvalidArgument", e.code + assert "mutually exclusive" in e.message.lower(), e.message + else: + raise AssertionError("expected KernelError for mixed positional + named params") + finally: + stmt.close() + + @live def test_bad_sql_surfaces_structured_kernel_error(session): stmt = session.statement() diff --git a/pyo3/tests/test_metadata.py b/pyo3/tests/test_metadata.py index deaa00ce..c9c57d58 100644 --- a/pyo3/tests/test_metadata.py +++ b/pyo3/tests/test_metadata.py @@ -55,10 +55,11 @@ def test_list_tables_in_information_schema(session): try: table = rs.fetch_all_arrow() assert table.num_rows > 0 - # Server-shape sanity: the columns should match the kernel's - # documented `SHOW TABLES` server-shape. + # Shape sanity: the kernel returns JDBC-shaped metadata columns + # (TABLE_CAT / TABLE_SCHEM / TABLE_NAME / TABLE_TYPE …), matching + # Thrift's getTables — not the raw `SHOW TABLES` shape. col_names = [f.name for f in table.schema] - for required in ("tableName", "tableType"): + for required in ("TABLE_NAME", "TABLE_TYPE"): assert required in col_names, f"missing column {required!r}: {col_names}" finally: rs.close() @@ -110,10 +111,19 @@ def test_empty_identifier_rejected(session): @live -def test_list_columns_requires_catalog_kwarg(session): - # `catalog` is a kwarg-only required parameter (no default). - with pytest.raises(TypeError): - session.metadata().list_columns(schema_pattern="x") # type: ignore[call-arg] +def test_list_columns_catalog_is_optional(session): + # `catalog` is optional (defaults to None = "across all catalogs"), + # so omitting it must NOT raise. Narrow the scan with schema + table + # patterns to keep the cross-catalog query bounded. + rs = session.metadata().list_columns( + schema_pattern="information_schema", table_pattern="tables" + ) + try: + # Executing without `catalog` succeeds; the column rows + # themselves are covered by test_list_columns_in_tables. + rs.fetch_all_arrow() + finally: + rs.close() @live diff --git a/src/client/sea.rs b/src/client/sea.rs index a95f2b52..7864c657 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -271,8 +271,13 @@ impl SeaRestTransport { .and_then(|e| e.message.clone()) .unwrap_or_else(|| "Unknown error".to_string()); - // Server-reported execution error → SqlError with the - // structured fields populated from the envelope. + // Server-reported failure → SqlError. The server's + // `error_code` slug is NOT used to pick the categorical + // bucket: SEA returns the generic `BAD_REQUEST` slug for + // genuine SQL errors too (e.g. `TABLE_OR_VIEW_NOT_FOUND`, + // SQLSTATE 42P01 — verified live), so it is not a reliable + // InvalidArgument signal. The slug + SQLSTATE are carried + // below for wrappers that want finer-grained mapping. let mut error = Error::sql_error() .message(&error_msg) .with_query_id(&response.statement_id); @@ -532,6 +537,14 @@ impl SeaRestTransport { /// to clean up shows up in traces with the failing-phase /// attribution (`wait_for_completion` vs `create_reader`). async fn close_orphaned_statement(&self, statement_id: &str, phase: &str) { + // A synchronously-rejected request (e.g. a `BAD_REQUEST` + // parameter-binding failure) returns FAILED with no + // `statement_id` — nothing was opened server-side, so there is + // nothing to close. Skip rather than issue a CloseStatement for + // an empty id. + if statement_id.is_empty() { + return; + } debug!( statement_id = %statement_id, phase = %phase, @@ -979,11 +992,26 @@ impl Transport for SeaRestTransport { Error::invalid_argument().message(format!("Failed to build request: {e}")) })?; - // Ignore errors on statement close (best effort cleanup) - let _ = self + // Surface the wire error so the caller's retry-on-failure path can + // run — `ExecutedStatement::close` / `ExecutedAsyncStatement::close` + // only flip their `closed` flag on success, so a swallowed error here + // would make their store-on-success semantics dead code (and a failed + // explicit close would look like it succeeded). The HTTP client has + // already applied the SEA retry policy, so callers see only the + // post-retry result; the `Drop` fire-and-forget fallback close still + // runs on the kernel side if the explicit close errored. + if let Err(e) = self .http_client .execute(request, RequestType::CloseStatement) - .await; + .await + { + tracing::warn!( + statement_id = %statement_id, + error = %e, + "close_statement failed after HTTP retries; surfacing to caller (Drop fallback close will run)" + ); + return Err(e); + } debug!("Closed statement: {}", statement_id); @@ -1200,6 +1228,51 @@ mod tests { assert_eq!(client.base_url(), "https://test.databricks.com/api/2.0/sql"); } + #[test] + fn terminal_outcome_failed_envelope_without_statement_id_surfaces_full_error() { + // A synchronously-rejected request (e.g. a parameter-binding + // `BAD_REQUEST`) comes back FAILED with no statement_id. The + // envelope must surface as a SqlError carrying the real server + // message, parsed SQLSTATE, and the `error_code` slug — NOT an + // opaque DataLoss parse failure. The slug is deliberately NOT + // remapped to InvalidArgument: SEA returns `BAD_REQUEST` for + // genuine SQL errors too (TABLE_OR_VIEW_NOT_FOUND etc.), so it's + // not a reliable caller-error signal. (The mutually-exclusive + // param case that motivated this is caught client-side at bind + // time; see `statement::mutable`.) + use crate::types::sea::{ServiceError, StatementState, StatementStatus}; + let response = ExecuteResponse { + statement_id: String::new(), + status: StatementStatus { + state: StatementState::Failed, + error: Some(ServiceError { + error_code: Some("BAD_REQUEST".to_string()), + message: Some( + "[INVALID_PARAMETER_MARKER_VALUE.MISSING_NAME] ... SQLSTATE: 22023" + .to_string(), + ), + sql_state: None, + }), + num_modified_rows: None, + display_message: None, + diagnostic_info: None, + error_details_json: None, + }, + manifest: None, + result: None, + }; + match SeaRestTransport::terminal_outcome(response) { + StatementOutcome::Err(e) => { + assert_eq!(e.code, crate::kernel_error::ErrorCode::SqlError); + assert_eq!(e.error_code.as_deref(), Some("BAD_REQUEST")); + assert!(e.message.contains("MISSING_NAME")); + // SQLSTATE parsed from the message text. + assert_eq!(e.sql_state.as_deref(), Some("22023")); + } + _ => panic!("expected Err outcome for a FAILED response"), + } + } + #[test] fn test_base_url_strips_trailing_slash() { let retry_configs = build_retry_configs(&RetryConfig::default(), &HashMap::new()); diff --git a/src/config.rs b/src/config.rs index be6c39d2..9840ffa4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -255,6 +255,71 @@ pub enum AuthConfig { External(Box), } +impl AuthConfig { + /// Construct a [`AuthConfig::Pat`] from an optional token, validating + /// that it is present and non-empty. + /// + /// Bindings forward the raw optional from their host language; the + /// required-field check lives here so every wrapper rejects a + /// missing/empty token identically (`ErrorCode::InvalidArgument`) + /// instead of each re-implementing it at the binding boundary. + pub fn pat(token: Option) -> crate::Result { + match token { + Some(token) if !token.is_empty() => Ok(AuthConfig::Pat { token }), + _ => Err(crate::kernel_error::Error::invalid_argument() + .message("PAT auth requires a non-empty access token")), + } + } + + /// Construct a [`AuthConfig::OAuthM2M`] from optional fields, + /// validating that the required `client_id` / `client_secret` are + /// present and non-empty. `scopes` / `token_url_override` are + /// optional and forwarded as-is (the kernel fills defaults). + pub fn oauth_m2m( + client_id: Option, + client_secret: Option, + scopes: Option>, + token_url_override: Option, + ) -> crate::Result { + let client_id = client_id.filter(|s| !s.is_empty()).ok_or_else(|| { + crate::kernel_error::Error::invalid_argument() + .message("OAuth M2M auth requires a non-empty client_id") + })?; + let client_secret = client_secret.filter(|s| !s.is_empty()).ok_or_else(|| { + crate::kernel_error::Error::invalid_argument() + .message("OAuth M2M auth requires a non-empty client_secret") + })?; + Ok(AuthConfig::OAuthM2M { + client_id, + client_secret, + scopes, + token_url_override, + }) + } + + /// Construct a [`AuthConfig::OAuthU2M`] from optional fields. All + /// U2M fields are optional — the kernel fills `databricks-cli` / + /// port 8020 / default scopes when omitted — so this performs no + /// validation and exists for symmetry with [`AuthConfig::pat`] / + /// [`AuthConfig::oauth_m2m`] so bindings can forward optionals + /// uniformly. + pub fn oauth_u2m( + client_id: Option, + redirect_port: Option, + scopes: Option>, + token_url_override: Option, + callback_timeout: Option, + ) -> Self { + AuthConfig::OAuthU2M { + client_id, + redirect_port, + scopes, + token_url_override, + callback_timeout, + } + } +} + /// Caller-supplied token provider trait. /// /// Used by [`AuthConfig::External`] to plug a host-side auth @@ -322,7 +387,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 +402,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, } } } @@ -813,6 +884,75 @@ mod tests { } } + // ─── AuthConfig validating constructors ─────────────────────── + + #[test] + fn pat_rejects_missing_or_empty_token() { + let err = AuthConfig::pat(None).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("non-empty access token")); + + let err = AuthConfig::pat(Some(String::new())).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + } + + #[test] + fn pat_accepts_non_empty_token() { + match AuthConfig::pat(Some("dapi-x".to_string())).unwrap() { + AuthConfig::Pat { token } => assert_eq!(token, "dapi-x"), + other => panic!("expected Pat, got {other:?}"), + } + } + + #[test] + fn oauth_m2m_rejects_missing_or_empty_client_id() { + let err = AuthConfig::oauth_m2m(None, Some("sec".to_string()), None, None).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("client_id")); + + let err = AuthConfig::oauth_m2m(Some(String::new()), Some("sec".to_string()), None, None) + .unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("client_id")); + } + + #[test] + fn oauth_m2m_rejects_missing_or_empty_client_secret() { + let err = AuthConfig::oauth_m2m(Some("cid".to_string()), None, None, None).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("client_secret")); + + let err = AuthConfig::oauth_m2m(Some("cid".to_string()), Some(String::new()), None, None) + .unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("client_secret")); + } + + #[test] + fn oauth_m2m_accepts_full_credentials() { + match AuthConfig::oauth_m2m( + Some("cid".to_string()), + Some("sec".to_string()), + Some(vec!["all-apis".to_string()]), + None, + ) + .unwrap() + { + AuthConfig::OAuthM2M { + client_id, + client_secret, + scopes, + token_url_override, + } => { + assert_eq!(client_id, "cid"); + assert_eq!(client_secret, "sec"); + assert_eq!(scopes, Some(vec!["all-apis".to_string()])); + assert!(token_url_override.is_none()); + } + other => panic!("expected OAuthM2M, got {other:?}"), + } + } + // ─── ConnectionConfig parsing ────────────────────────────────── #[test] 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/lib.rs b/src/lib.rs index 013b7bb6..b9602956 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -120,9 +120,12 @@ pub use metadata_v0::{Identifier, LikePattern, Metadata}; pub use result_stream::{OwnedBatchIter, ResultBatch, ResultStream, Row, SchemaRef}; pub use session::{Session, SessionBuilder}; pub use statement::executed::ExecutedStatement; -pub use statement::executed_async::{ExecutedAsyncStatement, StatementStatus}; +pub use statement::executed_async::{ + AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus, +}; pub use statement::handle::ExecutedStatementHandle; pub use statement::mutable::Statement; +pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; // === Compile-time guarantees on auto-traits === diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index cca8ea02..b2c6bf98 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)", @@ -164,6 +169,18 @@ impl<'a> Identifier<'a> { Ok(Self(s)) } + /// Construct from an optional borrowed string. + /// + /// Maps `None` to `Ok(None)` ("not supplied" — e.g. ODBC-style + /// "match all" for an exact catalog/schema), and `Some(s)` through + /// [`Identifier::new`] (so whitespace-only / empty / NUL / backtick / + /// oversize inputs reject as `InvalidArgument`). Single home for the + /// `Option` → `Option` conversion the wrappers + /// (napi / pyo3) all need at their metadata call sites. + pub fn from_opt(s: &'a Option) -> Result>> { + s.as_deref().map(Identifier::new).transpose() + } + /// Borrow the underlying string. pub fn as_str(&self) -> &'a str { self.0 @@ -194,6 +211,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 +225,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)", @@ -220,6 +243,17 @@ impl<'a> LikePattern<'a> { Ok(Self(s)) } + /// Construct from an optional borrowed pattern. + /// + /// Maps `None` to `Ok(None)` (the canonical "match all" intent), and + /// `Some(s)` through [`LikePattern::new`] (so whitespace-only / empty + /// / NUL / oversize inputs reject as `InvalidArgument`). Single home + /// for the `Option` → `Option` conversion the + /// wrappers (napi / pyo3) all need at their metadata call sites. + pub fn from_opt(s: &'a Option) -> Result>> { + s.as_deref().map(LikePattern::new).transpose() + } + /// Borrow the underlying pattern. pub fn as_str(&self) -> &'a str { self.0 @@ -669,4 +703,72 @@ 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 + ); + } + } + + // ─── from_opt — the wrapper-facing Option adapters ────────── + + #[test] + fn identifier_from_opt_none_is_ok_none() { + let input: Option = None; + assert!(Identifier::from_opt(&input).unwrap().is_none()); + } + + #[test] + fn identifier_from_opt_real_name_is_ok_some() { + let input = Some("main".to_owned()); + let id = Identifier::from_opt(&input).unwrap().expect("some"); + assert_eq!(id.as_str(), "main"); + } + + #[test] + fn identifier_from_opt_rejects_whitespace_only() { + let input = Some(" ".to_owned()); + let err = Identifier::from_opt(&input).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument); + } + + #[test] + fn like_pattern_from_opt_none_is_ok_none() { + let input: Option = None; + assert!(LikePattern::from_opt(&input).unwrap().is_none()); + } + + #[test] + fn like_pattern_from_opt_real_pattern_is_ok_some() { + let input = Some("info%".to_owned()); + let pat = LikePattern::from_opt(&input).unwrap().expect("some"); + assert_eq!(pat.as_str(), "info%"); + } + + #[test] + fn like_pattern_from_opt_rejects_whitespace_only() { + let input = Some(" ".to_owned()); + let err = LikePattern::from_opt(&input).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument); + } } diff --git a/src/reader/cloudfetch/chunk_downloader.rs b/src/reader/cloudfetch/chunk_downloader.rs index f4347aae..1504f90e 100644 --- a/src/reader/cloudfetch/chunk_downloader.rs +++ b/src/reader/cloudfetch/chunk_downloader.rs @@ -130,8 +130,67 @@ impl ChunkDownloader { batches.iter().map(|b| b.num_rows()).sum::() ); + // Trim the decoded chunk down to the link's declared row_count. + // + // Under a `row_limit=N` query the SEA server can hand back a + // chunk that decodes to more rows than the external link's + // declared `row_count` (a +1 server look-ahead row, or more). + // Mirror the Python SEA driver's + // `CloudFetchQueue._create_table_at_offset` (utils.py), which + // slices each downloaded chunk to its own external-link + // `row_count`. The inline-Arrow path clamps via the manifest's + // `total_row_count`; this is the CloudFetch-side equivalent so + // both transports return exactly N rows. + let batches = Self::trim_to_row_count(batches, link.row_count); + Ok(batches) } + + /// Trim a decoded chunk's batches so their total row count does not + /// exceed `row_count` (the external link's declared row count). + /// + /// Mirrors Python's per-chunk `arrow_table.slice(0, row_count)`: + /// only ever shrinks, never expands. A negative `row_count` (server + /// never sends this for a real link) is treated as "no trim". When + /// the decoded data already fits within `row_count` the batches are + /// returned untouched. Otherwise batches are kept whole until the + /// budget is reached and the boundary batch is sliced; any trailing + /// batches beyond the budget are dropped. + fn trim_to_row_count(batches: Vec, row_count: i64) -> Vec { + if row_count < 0 { + return batches; + } + let limit = row_count as usize; + + let total: usize = batches.iter().map(|b| b.num_rows()).sum(); + if total <= limit { + return batches; + } + + let mut trimmed = Vec::with_capacity(batches.len()); + let mut remaining = limit; + for batch in batches { + if remaining == 0 { + break; + } + let rows = batch.num_rows(); + if rows <= remaining { + remaining -= rows; + trimmed.push(batch); + } else { + // Slice the boundary batch down to the remaining budget. + trimmed.push(batch.slice(0, remaining)); + remaining = 0; + } + } + + debug!( + "Trimmed CloudFetch chunk from {} to {} rows (link row_count={})", + total, limit, row_count + ); + + trimmed + } } #[cfg(test)] @@ -169,4 +228,62 @@ mod tests { // Note: Full download tests require mocking the HTTP layer // Integration tests should be added in a separate test module + + use arrow_array::Int32Array; + use arrow_schema::{DataType, Field, Schema}; + + /// Build a single-column Int32 RecordBatch with `num_rows` rows. + fn make_batch(start: i32, num_rows: usize) -> RecordBatch { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let ids: Vec = (start..start + num_rows as i32).collect(); + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(ids))]).unwrap() + } + + fn total_rows(batches: &[RecordBatch]) -> usize { + batches.iter().map(|b| b.num_rows()).sum() + } + + #[test] + fn test_trim_to_row_count_single_batch_overrun() { + // A chunk that decoded to N+1 rows but the link only declares N. + // Mirrors the SEA `row_limit` look-ahead overrun. + let batch = make_batch(0, 101); + let trimmed = ChunkDownloader::trim_to_row_count(vec![batch], 100); + assert_eq!(total_rows(&trimmed), 100); + assert_eq!(trimmed.len(), 1); + assert_eq!(trimmed[0].num_rows(), 100); + } + + #[test] + fn test_trim_to_row_count_multiple_batches_trims_across_chunk() { + // Three batches (40 + 40 + 40 = 120 rows) but link declares 100. + // Expect the first two batches whole and the third sliced to 20. + let batches = vec![make_batch(0, 40), make_batch(40, 40), make_batch(80, 40)]; + let trimmed = ChunkDownloader::trim_to_row_count(batches, 100); + assert_eq!(total_rows(&trimmed), 100); + assert_eq!(trimmed.len(), 3); + assert_eq!(trimmed[0].num_rows(), 40); + assert_eq!(trimmed[1].num_rows(), 40); + assert_eq!(trimmed[2].num_rows(), 20); + } + + #[test] + fn test_trim_to_row_count_drops_trailing_batches() { + // Budget is exhausted within the first batch; the trailing batch + // must be dropped entirely, not expanded. + let batches = vec![make_batch(0, 100), make_batch(100, 50)]; + let trimmed = ChunkDownloader::trim_to_row_count(batches, 100); + assert_eq!(total_rows(&trimmed), 100); + assert_eq!(trimmed.len(), 1); + } + + #[test] + fn test_trim_to_row_count_no_overrun_passthrough() { + // Decoded rows fit within the declared row_count → never expand, + // batches returned untouched. + let batches = vec![make_batch(0, 30), make_batch(30, 20)]; + let trimmed = ChunkDownloader::trim_to_row_count(batches, 100); + assert_eq!(total_rows(&trimmed), 50); + assert_eq!(trimmed.len(), 2); + } } 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 3ac5b97a..3f7ab413 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -293,7 +293,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); } } @@ -426,14 +431,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/executed_async.rs b/src/statement/executed_async.rs index c8fe7a24..ed9ecb97 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -94,6 +94,32 @@ pub enum StatementStatus { } impl StatementStatus { + /// Stable string slug for this status, matching the connector's + /// `CommandState` taxonomy one-for-one: + /// `"Pending" | "Running" | "Succeeded" | "Failed" | "Cancelled" | + /// "Closed"`. The `Failed` variant collapses to `"Failed"` (the + /// carried `Error` is surfaced separately by callers that need the + /// structured failure). `StatementStatus` is `#[non_exhaustive]`, so + /// a future variant a stale caller doesn't recognise maps to + /// `"Unknown"` — bindings get something deterministic instead of a + /// panic. + pub fn as_str(&self) -> &'static str { + // The `_` arm is unreachable *within* this crate (the enum is + // fully covered here), but `StatementStatus` is + // `#[non_exhaustive]`, so a future variant must map to something + // deterministic for downstream callers rather than panic. + #[allow(unreachable_patterns)] + match self { + StatementStatus::Pending => "Pending", + StatementStatus::Running => "Running", + StatementStatus::Succeeded => "Succeeded", + StatementStatus::Failed(_) => "Failed", + StatementStatus::Cancelled => "Cancelled", + StatementStatus::Closed => "Closed", + _ => "Unknown", + } + } + /// Map a SEA `ExecuteResponse` to its public kernel status. The /// `Failed` arm preserves the same structured error /// `Transport::execute_statement`'s sync polling produces, so @@ -111,6 +137,10 @@ impl StatementStatus { let error_msg = service_error .and_then(|e| e.message.clone()) .unwrap_or_else(|| "Unknown error".to_string()); + // Server-reported failure → SqlError. See the sync path + // (`SeaClient::terminal_outcome`) for why the `error_code` + // slug is carried but not used to pick the bucket: SEA's + // `BAD_REQUEST` is overloaded across genuine SQL errors. let mut error = Error::sql_error() .message(&error_msg) .with_query_id(&response.statement_id); @@ -577,6 +607,73 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { } } +impl ExecutedAsyncStatement { + /// Produce a detached [`AsyncStatementCanceller`] that can fire a + /// server-side cancel for this statement *without borrowing the + /// handle*. + /// + /// Use when the handle is parked inside a long-running + /// [`await_result`](Self::await_result) — behind a binding-side + /// lock, say — and an out-of-band `cancel()` must still reach the + /// server. The canceller flips the statement to a terminal state, + /// which the parked `await_result` poll loop observes (`Cancelled`) + /// and returns on, so an explicit cancel interrupts the await + /// instead of queueing behind it. + pub fn canceller(&self) -> AsyncStatementCanceller { + AsyncStatementCanceller { + session: Arc::clone(&self.session), + statement_id: self.statement_id.clone(), + valid: self.valid.clone(), + } + } +} + +/// Detached canceller for an in-flight async statement. +/// +/// Holds only the shared session handle, the statement id, and the +/// shared [`ValidityFlag`] — **not** the [`ExecutedAsyncStatement`] +/// itself — so a binding can fire a server-side cancel while the handle +/// is borrowed elsewhere (e.g. parked inside a long-running +/// [`ExecutedAsyncStatement::await_result`] that a binding-side lock is +/// held across). Produced by [`ExecutedAsyncStatement::canceller`]. +/// +/// Cheap to [`Clone`] (one `Arc` bump plus a `String` / flag clone). +#[derive(Clone)] +pub struct AsyncStatementCanceller { + session: Arc, + statement_id: String, + valid: ValidityFlag, +} + +impl AsyncStatementCanceller { + /// Server-side cancel via `cancel_statement(statement_id)`. + /// + /// Short-circuits to `InvalidStatementHandle` (no wire round-trip) + /// if the parent handle was invalidated (re-execute / parent + /// `Statement` drop). Idempotent against a server already in a + /// terminal state — the kernel's `cancel_statement` is a no-op + /// there. Byte-for-byte the same operation as + /// [`ExecutedAsyncStatement::cancel`]; the two share no mutable + /// state, so this can run concurrently with an in-flight + /// `await_result` on the same statement. + pub async fn cancel(&self) -> Result<()> { + async { + self.valid.check()?; + self.session + .transport() + .cancel_statement(&self.statement_id) + .await + } + .instrument(self.session.log_span().clone()) + .await + } + + /// The server-issued statement id this canceller targets. + pub fn statement_id(&self) -> &str { + &self.statement_id + } +} + impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { // `swap` (not `load`) so the shared `closed` flag — held by the @@ -605,3 +702,19 @@ impl Drop for ExecutedAsyncStatement { }); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_as_str_covers_all_variants() { + assert_eq!(StatementStatus::Pending.as_str(), "Pending"); + assert_eq!(StatementStatus::Running.as_str(), "Running"); + assert_eq!(StatementStatus::Succeeded.as_str(), "Succeeded"); + assert_eq!(StatementStatus::Cancelled.as_str(), "Cancelled"); + assert_eq!(StatementStatus::Closed.as_str(), "Closed"); + let failed = StatementStatus::Failed(Error::sql_error().message("boom")); + assert_eq!(failed.as_str(), "Failed"); + } +} diff --git a/src/statement/mod.rs b/src/statement/mod.rs index 51b552cd..c000aa6d 100644 --- a/src/statement/mod.rs +++ b/src/statement/mod.rs @@ -29,6 +29,7 @@ pub mod executed_async; pub mod handle; pub mod mutable; pub mod params; +pub mod params_codec; pub mod spec; pub(crate) mod validity; @@ -37,7 +38,7 @@ pub(crate) mod validity; // of the deeper submodule paths. The crate-root re-exports in `lib.rs` // also resolve here, so both paths work. pub use executed::ExecutedStatement; -pub use executed_async::{ExecutedAsyncStatement, StatementStatus}; +pub use executed_async::{AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus}; pub use handle::ExecutedStatementHandle; pub use mutable::Statement; pub use spec::{ResultFormat, StatementSpec, TypedValue}; diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index e7be9189..15411c9e 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -67,6 +67,83 @@ 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), + }, + } +} + +/// Build the `(sql, ExecuteParams)` dispatch pair from a statement spec. +/// +/// Pure — borrows `spec`, touches no `Session` — so the spec → wire-params +/// mapping (row_limit, the resolved wait/on-wait pair, and **1-based** +/// positional + named parameter binding) is unit-testable without a live +/// session. Shared by both the sync and async dispatch paths via +/// [`Statement::prepare_for_dispatch`]. +fn build_execute_params( + spec: &StatementSpec, + wait_timeout_secs: Option<&str>, +) -> Result<(String, ExecuteParams)> { + let sql = spec + .sql + .as_deref() + .ok_or_else(|| { + Error::invalid_argument().message("StatementSpec.sql must be set before execute()") + })? + .to_owned(); + if spec.result_format != ResultFormat::Arrow { + return Err(Error::invalid_argument().message("v0 supports ResultFormat::Arrow only")); + } + // Positional and named parameters are mutually exclusive: the SEA + // server rejects a mixed `parameters` array with + // `INVALID_PARAMETER_MARKER_VALUE.MISSING_NAME` (a `BAD_REQUEST`). + // Reject at bind time in the kernel so every binding (napi, pyo3, + // direct Rust) gets the same InvalidArgument before the wire, + // rather than an opaque server round-trip failure. + if !spec.positional_params.is_empty() && !spec.named_params.is_empty() { + return Err(Error::invalid_argument() + .message("positional and named parameters are mutually exclusive; pass only one")); + } + let (wait_timeout, on_wait_timeout) = + resolve_wait_timeout(wait_timeout_secs, spec.query_timeout_secs); + let mut exec_params = ExecuteParams { + wait_timeout, + on_wait_timeout, + row_limit: spec.row_limit, + ..ExecuteParams::default() + }; + for (i, value) in spec.positional_params.iter().enumerate() { + exec_params + .parameters + .push(typed_value_to_sea_parameter((i + 1) as i32, value)?); + } + for (name, value) in spec.named_params.iter() { + exec_params + .parameters + .push(named_typed_value_to_sea_parameter(name.clone(), value)?); + } + Ok((sql, exec_params)) +} + /// Lifecycle owner for a single statement spec. /// /// Mutable, reusable. Mutate the spec in place via [`Statement::spec`], @@ -301,37 +378,7 @@ impl Statement { &self, wait_timeout_secs: Option<&str>, ) -> Result<(String, ExecuteParams)> { - let sql = self - .spec - .sql - .as_deref() - .ok_or_else(|| { - Error::invalid_argument().message("StatementSpec.sql must be set before execute()") - })? - .to_owned(); - 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 mut exec_params = ExecuteParams { - wait_timeout: wait_timeout_secs.map(|s| s.to_string()), - on_wait_timeout: wait_timeout_secs.map(|_| "CONTINUE".to_string()), - ..ExecuteParams::default() - }; - for (i, value) in self.spec.positional_params.iter().enumerate() { - exec_params - .parameters - .push(typed_value_to_sea_parameter((i + 1) as i32, value)?); - } - for (name, value) in self.spec.named_params.iter() { - exec_params - .parameters - .push(named_typed_value_to_sea_parameter(name.clone(), value)?); - } - Ok((sql, exec_params)) + build_execute_params(&self.spec, wait_timeout_secs) } /// Auto-close any prior executed handle this `Statement` produced. @@ -480,3 +527,100 @@ impl Drop for Statement { // remaining cleanup obligation here. } } + +#[cfg(test)] +mod tests { + use super::{build_execute_params, resolve_wait_timeout}; + use crate::statement::spec::{StatementSpec, TypedValue}; + + #[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); + } + + #[test] + fn build_execute_params_threads_row_limit_to_wire() { + // Headline parity feature: spec.row_limit must reach + // ExecuteParams.row_limit. A regression dropping it would otherwise + // pass every other test (the seam this pins). + let mut spec = StatementSpec::new(); + spec.sql("SELECT 1").row_limit(Some(100)); + let (sql, params) = build_execute_params(&spec, None).unwrap(); + assert_eq!(sql, "SELECT 1"); + assert_eq!(params.row_limit, Some(100)); + } + + #[test] + fn build_execute_params_binds_positional_params_one_based() { + let mut spec = StatementSpec::new(); + spec.sql("SELECT ?, ?"); + spec.param(1, TypedValue::Bool(true)).unwrap(); + spec.param(2, TypedValue::Bool(false)).unwrap(); + let (_, params) = build_execute_params(&spec, None).unwrap(); + assert_eq!(params.parameters.len(), 2); + // Positional binding is 1-based on the wire and carries no name. + assert_eq!(params.parameters[0].ordinal, Some(1)); + assert_eq!(params.parameters[1].ordinal, Some(2)); + assert!(params.parameters[0].name.is_none()); + } + + #[test] + fn build_execute_params_binds_named_params() { + let mut spec = StatementSpec::new(); + spec.sql("SELECT :flag"); + spec.param_named("flag", TypedValue::Bool(true)).unwrap(); + let (_, params) = build_execute_params(&spec, None).unwrap(); + assert_eq!(params.parameters.len(), 1); + assert_eq!(params.parameters[0].name.as_deref(), Some("flag")); + assert!(params.parameters[0].ordinal.is_none()); + } + + #[test] + fn build_execute_params_requires_sql() { + // Malformed/incomplete spec fails before any wire dispatch. + let spec = StatementSpec::new(); + assert!(build_execute_params(&spec, None).is_err()); + } + + #[test] + fn build_execute_params_rejects_mixed_positional_and_named() { + // Positional + named bindings are mutually exclusive — the + // kernel rejects at bind time so every binding (napi, pyo3, + // direct Rust) gets InvalidArgument before the wire instead of + // an opaque server `BAD_REQUEST` / `MISSING_NAME`. + let mut spec = StatementSpec::new(); + spec.sql("SELECT ? AS pos, :n AS named"); + spec.param(1, TypedValue::Int64(7)).unwrap(); + spec.param_named("n", TypedValue::Int64(99)).unwrap(); + let err = build_execute_params(&spec, None) + .expect_err("mixed positional + named must be rejected"); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!( + err.message.contains("mutually exclusive"), + "expected 'mutually exclusive' in error, got: {}", + err.message + ); + } +} diff --git a/src/statement/params_codec.rs b/src/statement/params_codec.rs new file mode 100644 index 00000000..f5743333 --- /dev/null +++ b/src/statement/params_codec.rs @@ -0,0 +1,1114 @@ +// 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. + +//! Parse a connector-style `(sql_type, value_str)` pair into a kernel +//! [`TypedValue`]. +//! +//! This is the single source of truth for the parameter codec shared by +//! every binding. The PyO3 and napi wrappers both re-export +//! [`parse_typed_value`] from here (`databricks_sql_kernel::parse_typed_value`) +//! rather than re-implementing the `(sql_type, value_str) -> TypedValue` +//! logic, so the two surfaces can never diverge in what the kernel sees +//! on the wire. +//! +//! Both connectors hand parameters across the FFI as a `(type, value)` +//! pair where the value is always a string and the SQL type carries the +//! intent — e.g. the PySQL connector's +//! `TSparkParameter(type="INT", value=stringValue("42"))`, and the Node +//! driver's `DBSQLParameter.toSparkParameter()`. Taking the string form +//! directly avoids a per-call native-value reflection trip and keeps all +//! validation in one place. +//! +//! Compound types (`ARRAY` / `MAP` / `STRUCT`) and BINARY are explicitly +//! rejected — the SEA wire does not accept either as a bound parameter +//! today, and surfacing that as an `InvalidArgument` at bind time gives a +//! clearer error than an opaque server-side execute failure. + +use crate::kernel_error::{Error, Result}; +use crate::statement::spec::{geo_wire, TypedValue}; +use chrono::{NaiveDate, NaiveDateTime}; + +/// Parse a Databricks SQL type name + string-encoded value into a kernel +/// [`TypedValue`]. +/// +/// `value_str = None` always produces [`TypedValue::Null`], regardless of +/// `sql_type` — matches the connector's `VoidParameter` shape. +/// +/// `sql_type` is the canonical SQL type name the connector produces +/// (`"INT"`, `"BIGINT"`, `"STRING"`, etc.). For DECIMAL, the form is +/// `"DECIMAL(precision,scale)"`; we parse the parenthesized form to +/// populate [`TypedValue::Decimal`]'s precision/scale fields so the kernel +/// doesn't have to default them to `DECIMAL(10, 0)` on the wire (which +/// loses fractional digits — see `statement/params.rs` for the +/// kernel-side rationale). +/// +/// Errors are [`Error::invalid_argument`] so they surface to the binding +/// caller as the binding's invalid-argument shape (PyO3 +/// `KernelError(code='InvalidArgument', ...)`, napi `InvalidArgument`). +pub 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, + }; + + // Normalise to uppercase for the simple variants; DECIMAL keeps + // its case-sensitive parenthesised form so we can extract + // precision/scale. + 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), + // The three timestamp variants map to three distinct TypedValue + // arms so the SEA wire payload carries the exact type-name + // string the server expects. `TIMESTAMP` and `TIMESTAMP_NTZ` + // share `parse_timestamp` for the naive-datetime parsing; the + // NTZ arm re-wraps as `TimestampNtz` so the SEA payload mapper + // 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 — pass the JSON text through verbatim. We don't + // validate parseability: the connector is expected to have + // produced valid JSON (Python's `json.dumps`, JS's + // `JSON.stringify`, etc.), and on a malformed payload the + // server returns a typed error which the kernel surfaces + // back to the caller. + // + // Note on the JSON-null vs SQL-NULL asymmetry: a caller + // binding a JSON `null` value sends `value_str=Some("null")` + // and lands here as `TypedValue::Variant("null")` — a VARIANT + // column containing the JSON-null value. The SQL-NULL path is + // distinct: `value_str=None` short-circuits at the top of + // this function to `TypedValue::Null` regardless of + // `sql_type`. Both are correct and intentionally different. + // Don't "fix" this by collapsing `Variant("null")` into + // `TypedValue::Null` — JSON-null is a meaningful VARIANT + // payload that the server stores and reads back as a JSON + // `null` literal, not as SQL NULL. + "VARIANT" => Ok(TypedValue::Variant(s.to_owned())), + _ if upper.starts_with("DECIMAL(") => parse_decimal(sql_type, s), + _ if is_geo_type_name(&upper, geo_wire::GEOGRAPHY) => parse_geography(&upper, s), + _ if is_geo_type_name(&upper, geo_wire::GEOMETRY) => parse_geometry(&upper, 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 the bare geo family name or the SRID-decorated +/// form (e.g. `"GEOGRAPHY"`, `"GEOGRAPHY(4326)"`). The closing paren +/// is required so we don't false-positive on hypothetical +/// `"GEOGRAPHYX"`. +fn is_geo_type_name(upper: &str, family: &str) -> bool { + if upper == family { + return true; + } + if let Some(rest) = upper.strip_prefix(family) { + return rest.starts_with('(') && rest.ends_with(')'); + } + false +} + +/// True iff `upper` is one of ARRAY/MAP/STRUCT exactly, or one of +/// those followed by `<` (generic) or `(` (function-style). This is +/// 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}")))?; + // `str::parse::()` returns ±inf for overflow ("1e500") and + // NaN for the literals "nan"/"NaN", both of which the SEA wire + // can't represent. Reject so bad literals fail at bind time + // rather than producing a misleading row at execute time. + 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 { + // The connector's TimestampParameter stringifies via str(), + // which on a Python datetime produces ``YYYY-MM-DD HH:MM:SS`` + // optionally with ``.microseconds``. Accept both with and + // without sub-second precision. + // + // Also accept the trailing-``Z`` UTC marker that JavaScript's + // ``Date.prototype.toISOString()`` always emits — 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:?}"))) +} + +/// Parse a `TIMESTAMP_LTZ` literal into a tz-aware `DateTime`. +/// +/// Accepts three input shapes, all interpreted as UTC on the wire: +/// +/// 1. Naive form (`"2026-05-15 12:30:45[.f]"` or T-separator) — the +/// value is taken as UTC. This matches what Python's +/// `datetime.utcnow().isoformat()` produces. +/// 2. Trailing `Z` (`"2026-05-15T12:30:45Z"`) — explicit UTC marker; +/// same semantics as #1 after stripping `Z`. +/// 3. Explicit offset (`"2026-05-15T12:30:45+05:30"`) — parsed and +/// converted to UTC, preserving the wall-clock-to-instant +/// relationship. +/// +/// The naive form is what most connector code emits today; the +/// offset form covers callers using Python `datetime.astimezone(tz).isoformat()`. +fn parse_timestamp_ltz(s: &str) -> Result { + use chrono::{DateTime, FixedOffset, Utc}; + + // Try explicit-offset (RFC 3339) form first — covers `+HH:MM` and + // `Z` suffix in one call. + if let Ok(dt) = DateTime::::parse_from_rfc3339(s) { + return Ok(TypedValue::TimestampLtz(dt.with_timezone(&Utc))); + } + // Also try the space-separated equivalent (`%Y-%m-%d %H:%M:%S%.f%:z`) + // which Python's `datetime.astimezone().isoformat(sep=' ')` + // happens to emit. + 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))); + } + // Fall back to the naive forms `parse_timestamp` accepts, treating + // them as UTC. Strip trailing `Z` first. + 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:?}"))) +} + +/// Parse a `GEOGRAPHY` binding. +/// +/// `upper` is the uppercased type-name as received from the +/// connector — bare `"GEOGRAPHY"` or SRID-decorated +/// `"GEOGRAPHY(4326)"`. `value` is the textual binding — +/// either bare WKT (`"POINT(1 2)"`) or EWKT +/// (`"SRID=4326;POINT(1 2)"`). +/// +/// SRID precedence: if both the type-name and the value carry an +/// SRID, they MUST agree. Disagreement is an `InvalidArgument` +/// error — silently picking one would hide a connector bug. +fn parse_geography(upper: &str, value: &str) -> Result { + let (wkt, srid) = parse_ewkt_with_type_srid(upper, geo_wire::GEOGRAPHY, value)?; + Ok(TypedValue::Geography { + wkt, + srid, + wkb: None, + }) +} + +/// Parse a `GEOMETRY` binding. Same rules as `parse_geography`. +fn parse_geometry(upper: &str, value: &str) -> Result { + let (wkt, srid) = parse_ewkt_with_type_srid(upper, geo_wire::GEOMETRY, value)?; + Ok(TypedValue::Geometry { + wkt, + srid, + wkb: None, + }) +} + +/// Common geo-binding parser. Returns `(wkt, srid)` where `wkt` has +/// no `SRID=N;` prefix. +fn parse_ewkt_with_type_srid( + upper: &str, + family: &str, + value: &str, +) -> Result<(String, Option)> { + let type_srid = extract_type_srid(upper, family)?; + let (value_srid, wkt) = split_ewkt(value)?; + + // Reject empty WKT at the kernel boundary. The server would + // also reject this, but doing it locally gives a clearer + // error message that names the type-family and avoids a + // round-trip on what's almost certainly a connector bug. + // `"SRID=4326;"` (SRID prefix but no WKT body) is the most + // likely shape that lands here — `split_ewkt` happily strips + // the prefix and leaves an empty body. + if wkt.trim().is_empty() { + return Err(invalid_msg(format!( + "{family} binding has empty WKT body (value: {value:?})" + ))); + } + + let srid = match (type_srid, value_srid) { + (Some(t), Some(v)) if t != v => { + return Err(invalid_msg(format!( + "SRID mismatch: {family} type-name says {t} but value EWKT prefix says {v}" + ))); + } + (Some(t), _) => Some(t), + (None, Some(v)) => Some(v), + (None, None) => None, + }; + + Ok((wkt.to_owned(), srid)) +} + +/// Pull the SRID out of a decorated type-name like +/// `"GEOGRAPHY(4326)"`. Returns `Ok(None)` for the bare form. +fn extract_type_srid(upper: &str, family: &str) -> Result> { + let Some(rest) = upper.strip_prefix(family) else { + return Ok(None); + }; + if rest.is_empty() { + return Ok(None); + } + // Must be `(N)` — `is_geo_type_name` already accepted the shape. + let inner = rest + .strip_prefix('(') + .and_then(|r| r.strip_suffix(')')) + .ok_or_else(|| invalid_msg(format!("malformed {family} type-name: {upper:?}")))?; + inner + .trim() + .parse::() + .map(Some) + .map_err(|e| invalid_msg(format!("invalid {family} SRID {inner:?}: {e}"))) +} + +/// Split an EWKT string into `(srid, wkt_body)`. If there's no +/// `SRID=N;` prefix the SRID is `None` and the whole string is the +/// WKT body. Whitespace inside the prefix is tolerated +/// (`"SRID = 4326 ; POINT(...)"`). +fn split_ewkt(value: &str) -> Result<(Option, &str)> { + let trimmed = value.trim_start(); + // Case-insensitive ASCII match on the EWKT SRID prefix + // (`geo_wire::EWKT_SRID_PREFIX`, today literally `"SRID="`). + // Operating on bytes is safe here because the prefix is pure + // ASCII; a non-ASCII byte at index 0 fails the comparison + // without splitting a UTF-8 code point. + let prefix = geo_wire::EWKT_SRID_PREFIX.as_bytes(); + let bytes = trimmed.as_bytes(); + if bytes.len() < prefix.len() || !bytes[..prefix.len()].eq_ignore_ascii_case(prefix) { + return Ok((None, value)); + } + // Find the `;` that terminates the SRID prefix. + let after_eq = &trimmed[prefix.len()..]; + let semi = after_eq.find(';').ok_or_else(|| { + invalid_msg(format!( + "malformed EWKT: missing ';' after SRID prefix: {value:?}" + )) + })?; + let srid_text = after_eq[..semi].trim(); + let srid: i32 = srid_text + .parse() + .map_err(|e| invalid_msg(format!("invalid EWKT SRID {srid_text:?}: {e}")))?; + let wkt = after_eq[semi + 1..].trim_start(); + Ok((Some(srid), wkt)) +} + +fn parse_decimal(sql_type: &str, value: &str) -> Result { + // Extract precision/scale from "DECIMAL(p,s)" / "DECIMAL(p)" / + // "Decimal(p, s)". + let (precision, scale) = extract_decimal_precision_scale(sql_type)?; + // Validate the value itself parses as a finite decimal number, + // so bad literals like ``bind_param(1, "abc", "DECIMAL(10,2)")`` + // fail at bind time rather than at execute. The kernel's + // ``TypedValue::Decimal`` carries the value as a string and + // doesn't re-validate. + 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 (``-123.45``, ``0``, ``123``). Forms like ``42.``, +/// ``.5`` and the bare sign ``-`` are rejected to match +/// Databricks' DECIMAL literal parser — they'd otherwise pass +/// bind-time validation here and surface as a server error at +/// execute, defeating the headline "bad literal fails at bind" +/// contract. +/// +/// 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)> { + // sql_type looks like "DECIMAL(10,2)", "DECIMAL(10, 2)", + // "DECIMAL(38)" (scale defaults to 0), or "Decimal(10,2)" + // depending on casing. + 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. The server accepts precision in + // ``1..=38`` and scale in ``-(38 - precision)..=precision`` + // (negative scale rounds to multiples of ``10^|s|``), but no + // current Databricks connector emits negative-scale DECIMAL + // parameters and the kernel's ``TypedValue::Decimal`` doesn't + // round-trip them cleanly. Reject here so obvious junk like + // ``DECIMAL(0,0)`` or ``DECIMAL(255,127)`` fails at bind time; + // when a negative-scale caller materialises, widen this check + // and the ``i8`` scale parse together. + 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 crate::kernel_error::ErrorCode; + + // None → Null regardless of SQL type + #[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("3.141592653589793")).unwrap(), + TypedValue::Float64(_) + )); + 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:?}"), + } + // VARCHAR / CHAR aliases. + 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_with_and_without_microseconds() { + 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(_))); + // ISO-8601 T-separator variant (some Python datetime formatters use it). + let c = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45")).unwrap(); + assert!(matches!(c, TypedValue::Timestamp(_))); + } + + #[test] + fn timestamp_ntz_maps_to_distinct_variant() { + // Same literal as TIMESTAMP, but the type-name distinguishes: + // TIMESTAMP_NTZ → TypedValue::TimestampNtz, not Timestamp. + let v = parse_typed_value("TIMESTAMP_NTZ", Some("2026-05-15 12:30:45")).unwrap(); + assert!(matches!(v, TypedValue::TimestampNtz(_))); + let v = parse_typed_value("TIMESTAMP_NTZ", Some("2026-05-15T12:30:45.123Z")).unwrap(); + assert!(matches!(v, TypedValue::TimestampNtz(_))); + } + + #[test] + fn timestamp_ltz_parses_naive_offset_and_z_forms() { + // Naive form — interpreted as UTC. + 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" + ); + + // Trailing-Z form — equivalent UTC. + let v = parse_typed_value("TIMESTAMP_LTZ", Some("2026-05-15T12:30:45Z")).unwrap(); + assert!(matches!(v, TypedValue::TimestampLtz(_))); + + // Explicit positive offset — wall-clock 18:00 in +05:30 → + // 12:30 UTC. Confirms tz conversion (not just stripping). + 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 timestamp_ltz_rejects_invalid_literal() { + let e = parse_typed_value("TIMESTAMP_LTZ", Some("not-a-timestamp")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn variant_passes_json_text_through() { + // Object form — verbatim through to TypedValue::Variant. + let json = r#"{"k":1,"nested":{"a":[true,null]}}"#; + let v = parse_typed_value("VARIANT", Some(json)).unwrap(); + match v { + TypedValue::Variant(s) => assert_eq!(s, json), + other => panic!("expected Variant, got {other:?}"), + } + } + + #[test] + fn variant_accepts_scalar_json_values() { + // VARIANT permits any JSON value, not just objects / arrays. + // Note: `"null"` here is a JSON-null literal inside the VARIANT + // (i.e. `TypedValue::Variant("null".into())`), NOT SQL NULL. + // SQL NULL is reached via `value_str=None`, which short- + // circuits to `TypedValue::Null` before this match arm. See + // the comment on the `"VARIANT"` arm in `parse_typed_value`. + for raw in [r#""hello""#, "42", "true", "null", "[1,2,3]"] { + let v = parse_typed_value("VARIANT", Some(raw)).unwrap(); + assert!(matches!(v, TypedValue::Variant(_)), "case {raw}"); + } + } + + #[test] + fn variant_does_not_validate_json() { + // The kernel doesn't parse VARIANT — malformed JSON is the + // server's job to reject. Confirms we don't accidentally + // pre-validate at the kernel boundary. + let v = parse_typed_value("VARIANT", Some("not even close to json")).unwrap(); + assert!(matches!(v, TypedValue::Variant(_))); + } + + #[test] + fn geography_decorated_type_with_ewkt_value() { + // The most common shape: connector tells us SRID via the + // type-name AND embeds it in the value EWKT prefix. + let v = parse_typed_value("GEOGRAPHY(4326)", Some("SRID=4326;POINT(1 2)")).unwrap(); + match v { + TypedValue::Geography { wkt, srid, wkb } => { + assert_eq!(wkt, "POINT(1 2)"); + assert_eq!(srid, Some(4326)); + assert!(wkb.is_none(), "wkb stays None on the EWKT path"); + } + other => panic!("expected Geography, got {other:?}"), + } + } + + #[test] + fn geography_bare_type_with_ewkt_value() { + // Connector lacks the SRID decorator in the type-name, but + // the value EWKT carries one. SRID comes from the value. + let v = parse_typed_value("GEOGRAPHY", Some("SRID=4326;POINT(1 2)")).unwrap(); + let TypedValue::Geography { wkt, srid, .. } = v else { + panic!("expected Geography"); + }; + assert_eq!(wkt, "POINT(1 2)"); + assert_eq!(srid, Some(4326)); + } + + #[test] + fn geography_decorated_type_with_bare_wkt_value() { + // SRID only in the type-name. Value has no EWKT prefix. + let v = parse_typed_value("GEOGRAPHY(4326)", Some("POINT(1 2)")).unwrap(); + let TypedValue::Geography { wkt, srid, .. } = v else { + panic!("expected Geography"); + }; + assert_eq!(wkt, "POINT(1 2)"); + assert_eq!(srid, Some(4326)); + } + + #[test] + fn geography_bare_type_with_bare_wkt_value() { + // No SRID anywhere — legal per the SEA design (`srid: None`). + let v = parse_typed_value("GEOGRAPHY", Some("POINT(1 2)")).unwrap(); + let TypedValue::Geography { wkt, srid, .. } = v else { + panic!("expected Geography"); + }; + assert_eq!(wkt, "POINT(1 2)"); + assert!(srid.is_none()); + } + + #[test] + fn geography_rejects_srid_mismatch() { + // Connector bug: type-name and EWKT prefix disagree. Better + // to surface as InvalidArgument than to silently pick one. + let e = parse_typed_value("GEOGRAPHY(4326)", Some("SRID=3857;POINT(1 2)")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn geometry_round_trips_like_geography() { + // GEOMETRY uses the same parser; sanity-check the dispatch. + let v = parse_typed_value("GEOMETRY(0)", Some("LINESTRING(0 0,1 1)")).unwrap(); + let TypedValue::Geometry { wkt, srid, wkb } = v else { + panic!("expected Geometry"); + }; + assert_eq!(wkt, "LINESTRING(0 0,1 1)"); + assert_eq!(srid, Some(0)); + assert!(wkb.is_none()); + } + + #[test] + fn geo_type_name_does_not_overreach() { + // `GEOGRAPHYX` / `GEOMETRYBUFFER` must NOT match — same + // discipline as the compound-type matcher. + let e = parse_typed_value("GEOGRAPHYX", Some("POINT(1 2)")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + let e = parse_typed_value("GEOMETRYBUFFER", Some("POINT(1 2)")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn geography_rejects_malformed_ewkt() { + // SRID= prefix with no terminating ';'. + let e = parse_typed_value("GEOGRAPHY", Some("SRID=4326 POINT(1 2)")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + // Non-numeric SRID in the prefix. + let e = parse_typed_value("GEOGRAPHY", Some("SRID=abc;POINT(1 2)")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn geography_rejects_empty_wkt_body() { + // Various shapes that produce an empty WKT body after the + // EWKT split. Each should surface as `InvalidArgument` at + // the kernel boundary rather than round-tripping to the + // server. + for empty_shape in [ + "", // wholly empty + " ", // only whitespace + "SRID=4326;", // SRID prefix with no body + "SRID=4326; ", + ] { + let e = parse_typed_value("GEOGRAPHY", Some(empty_shape)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "case {empty_shape:?}",); + } + // Same expectation for GEOMETRY. + let e = parse_typed_value("GEOMETRY", Some("")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[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 binary_is_rejected() { + // BINARY is documented kernel-side as unsupported on the + // SEA wire today; the connector backend will need its own + // unhex(?) workaround if a user passes BinaryParameter. 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")); + } + + #[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 unknown_type_errors() { + let e = parse_typed_value("MAGIC", Some("x")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument); + } + + #[test] + fn lowercase_sql_type_works() { + // The connector uppercases via DatabricksSupportedType.name, + // but accept lowercase too for robustness. + 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 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:?}"), + } + } + + #[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() { + // The headline contract — `bind_param(1, "abc", "DECIMAL(10,2)")` + // must fail at bind time, not at execute. + 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_accepts_canonical_value_literals() { + // Only forms with at least one digit on each side of the dot + // (or no dot at all). Databricks' DECIMAL literal parser + // rejects "42." and ".5" — so do we, see the dedicated + // rejection test below. + for v in ["0", "-0", "-123.45", "0.0001", "+1.5", "123"] { + let r = parse_typed_value("DECIMAL(10,4)", Some(v)); + assert!(r.is_ok(), "expected {v:?} to parse: {:?}", r.err()); + } + } + + #[test] + fn decimal_rejects_partial_dot_forms() { + // "42." (no fractional digits) and ".5" (no integer digits) + // round-trip past Rust's `str::parse::()` but the + // Databricks server rejects them, so we reject at bind time + // to keep the headline contract honest. The bare sign "-" + // is the obvious adjacent case. + 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)", // precision below 1 + "DECIMAL(39,0)", // precision above 38 + "DECIMAL(10,11)", // scale above precision + "DECIMAL(10,-1)", // scale below 0 + ] { + let e = parse_typed_value(ty, Some("1.0")).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{ty}"); + } + } + + #[test] + fn timestamp_accepts_trailing_z() { + 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 compound_match_does_not_overreach() { + // `ARRAYBUFFER` / `MAPLE` / `STRUCTURE` are not real + // Databricks types, but the compound-rejection branch should + // not claim them — they should fall through to the generic + // "unsupported parameter SQL type" message. + 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 + ); + } + // ARRAY/MAP/STRUCT with bracket or paren forms are still + // recognised as compound types. + for ty in ["ARRAY", "ARRAY", "ARRAY(INT)", "MAP"] { + let e = parse_typed_value(ty, Some("x")).unwrap_err(); + assert!( + e.message.contains("compound"), + "{ty} should be compound, got {}", + e.message + ); + } + } + + // ─── 10-type matrix coverage check (originally napi-only) ─────────── + // + // 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 sends. + #[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/src/statement/spec.rs b/src/statement/spec.rs index f202c01d..2b180abe 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -180,11 +180,15 @@ pub struct StatementSpec { pub sql: Option, /// Positional parameters, 1-based on the wire. Index `i` in this Vec - /// corresponds to ordinal `i + 1`. + /// corresponds to ordinal `i + 1`. Mutually exclusive with + /// `named_params` (see below). pub positional_params: Vec, - /// Named parameters. Mutually compatible with `positional_params`; the - /// kernel forwards both to the SEA `parameters` field. + /// Named parameters. Mutually exclusive with `positional_params`: + /// `execute()` / `submit()` return `ErrorCode::InvalidArgument` if + /// both are non-empty. The SEA server rejects a mixed `parameters` + /// array with `INVALID_PARAMETER_MARKER_VALUE.MISSING_NAME`, so the + /// kernel rejects at bind time before the wire. pub named_params: HashMap, /// Per-statement conf overlay. Maps to SEA `parameters` / @@ -192,6 +196,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 +282,52 @@ impl StatementSpec { self } + /// Merge a `query_tags` map into the per-statement conf overlay. + /// + /// Serialises `tags` to the comma-separated `key:value` wire shape + /// the SEA server expects under the `query_tags` conf key (the same + /// shape NodeJS Thrift's `serializeQueryTags` produces: backslashes + /// in keys are doubled; backslash / colon / comma in values are + /// backslash-escaped) and inserts it into `statement_conf` under + /// `"query_tags"`. + /// + /// - An **empty** `tags` map is a no-op (returns `Ok(self)`), + /// matching the "empty map means not-supplied" convention. + /// - If `statement_conf` already carries an explicit `"query_tags"` + /// key, returns `Err(InvalidArgument)` — supplying both a + /// `queryTags` map and `statementConf["query_tags"]` is an + /// ambiguous intent the kernel refuses to silently resolve. Set + /// the explicit `statement_conf` map (via [`Self::statement_conf`]) + /// before calling this so the conflict is detected. + pub fn query_tags(&mut self, tags: HashMap) -> Result<&mut Self> { + if tags.is_empty() { + return Ok(self); + } + if self.statement_conf.contains_key("query_tags") { + return Err(Error::new( + ErrorCode::InvalidArgument, + "cannot supply both `queryTags` and `statementConf[\"query_tags\"]` — pick one", + )); + } + self.statement_conf + .insert("query_tags".to_string(), serialize_query_tags(&tags)); + Ok(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; @@ -266,6 +335,35 @@ impl StatementSpec { } } +/// Serialise a tag map to the comma-separated `key:value` wire shape the +/// SEA server expects under the `query_tags` conf key — identical to the +/// shape NodeJS Thrift's `serializeQueryTags` (`lib/utils/queryTags.ts`) +/// produces. Backslashes in keys are doubled; backslash, colon, and comma +/// in values are each backslash-escaped. The SEA server merges +/// `confOverlay.query_tags` the same way regardless of which backend +/// produced it, so callers porting from Thrift see identical behaviour. +/// +/// Tag ordering follows `HashMap` iteration order, which is +/// non-deterministic; the SEA server treats conf values as +/// order-insensitive, so the result is functionally equivalent to the +/// Thrift output regardless of key order. +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(",") +} + #[cfg(test)] mod tests { use super::*; @@ -277,9 +375,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(); @@ -326,4 +440,123 @@ mod tests { assert_eq!(err.code, ErrorCode::InvalidArgument); assert!(s.named_params.is_empty()); } + + // ─── query_tags merge behaviour ───────────────────────────────────── + + #[test] + fn query_tags_empty_map_is_noop() { + let mut s = StatementSpec::new(); + s.query_tags(HashMap::new()).unwrap(); + assert!(s.statement_conf.is_empty()); + } + + #[test] + fn query_tags_serialised_into_query_tags_key() { + let mut s = StatementSpec::new(); + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + s.query_tags(tags).unwrap(); + assert_eq!( + s.statement_conf.get("query_tags").map(String::as_str), + Some("team:platform"), + ); + } + + #[test] + fn query_tags_rejects_dual_definition() { + let mut s = StatementSpec::new(); + let mut conf = HashMap::new(); + conf.insert("query_tags".to_string(), "explicit:value".to_string()); + s.statement_conf(conf); + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + let err = s.query_tags(tags).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!( + err.message.contains("cannot supply both"), + "error must explain the conflict: {}", + err.message, + ); + // The explicit key is left untouched. + assert_eq!( + s.statement_conf.get("query_tags").map(String::as_str), + Some("explicit:value"), + ); + } + + #[test] + fn query_tags_empty_map_does_not_collide_with_existing_key() { + // An empty `queryTags: {}` map is ignored, so a caller can pass + // an explicit `statementConf["query_tags"]` alongside an empty + // tag map without tripping the ambiguity guard. + let mut s = StatementSpec::new(); + let mut conf = HashMap::new(); + conf.insert("query_tags".to_string(), "explicit:value".to_string()); + s.statement_conf(conf); + s.query_tags(HashMap::new()).unwrap(); + assert_eq!( + s.statement_conf.get("query_tags").map(String::as_str), + Some("explicit:value"), + ); + } + + // ─── serialize_query_tags byte-shape parity with Thrift ───────────── + + /// `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. + #[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 — only + // in values. 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() { + 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 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/src/types/sea.rs b/src/types/sea.rs index a93fb3d3..5bb997ef 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -24,6 +24,14 @@ use std::collections::HashMap; /// Response from statement execution or status polling. #[derive(Debug, Clone, Deserialize)] pub struct StatementExecutionResponse { + // The server omits `statement_id` when it rejects a request + // synchronously — e.g. a parameter-binding `BAD_REQUEST` returns + // HTTP 200 with `{"status":{"state":"FAILED","error":{...}}}` and + // no id (no statement was ever opened). Defaulting to "" lets the + // FAILED envelope deserialize so the error classifier sees the + // `error_code` slug, instead of dying in serde and surfacing an + // opaque `DataLoss` parse error. + #[serde(default)] pub statement_id: String, pub status: StatementStatus, #[serde(default)] @@ -493,6 +501,31 @@ mod tests { assert_eq!(manifest.total_row_count, Some(100)); } + #[test] + fn test_failed_response_without_statement_id_deserializes() { + // A synchronously-rejected request (e.g. mixed positional + + // named params) comes back HTTP 200 with a FAILED envelope and + // NO `statement_id` — no statement was ever opened. Without the + // `#[serde(default)]` on `statement_id` this fails to parse and + // the error surfaces as an opaque `DataLoss` ("missing field + // `statement_id`") instead of the server's actual BAD_REQUEST. + let json = r#"{ + "status": { + "state": "FAILED", + "error": { + "error_code": "BAD_REQUEST", + "message": "[INVALID_PARAMETER_MARKER_VALUE.MISSING_NAME] ... SQLSTATE: 22023" + } + } + }"#; + + let response: StatementExecutionResponse = serde_json::from_str(json).unwrap(); + assert_eq!(response.statement_id, ""); + assert_eq!(response.status.state, StatementState::Failed); + let err = response.status.error.expect("error envelope present"); + assert_eq!(err.error_code.as_deref(), Some("BAD_REQUEST")); + } + #[test] fn test_chunk_info_byte_count_optional() { // Per the bounded SEA API contract, `byte_count` on diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index e5827805..c1201aec 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -131,13 +131,14 @@ async fn select_with_named_params() { #[tokio::test] #[ignore] -async fn mixed_positional_and_named_params_is_server_side_error() { - // The kernel can serialise mixed positional + named bindings in - // the same `parameters` array — but the server rejects with - // `INVALID_PARAMETER_MARKER_VALUE.MISSING_NAME` when any - // parameter has a `name` set and another doesn't. This test - // documents the server contract: bindings must be uniformly - // positional or uniformly named. +async fn mixed_positional_and_named_params_rejected_before_dispatch() { + // Positional + named bindings in the same statement are mutually + // exclusive. The kernel rejects them at bind time (in + // `build_execute_params`) with `InvalidArgument` — before the wire — + // so every binding gets a consistent, fast failure instead of an + // opaque server `BAD_REQUEST` / `MISSING_NAME` round-trip. The + // pure-unit coverage lives in `statement::mutable`'s test module; + // this e2e asserts the guard fires in the real `execute()` path. let session = live_session().await; let mut stmt = session.statement(); stmt.spec() @@ -150,17 +151,18 @@ async fn mixed_positional_and_named_params_is_server_side_error() { .execute() .await .err() - .expect("server should reject mixed bindings"); - // Surfaced as DataLoss because the FAILED response is parsed via - // the generic execute-response path and the kernel's error - // classifier hasn't decoded BAD_REQUEST → InvalidArgument here. - // The important assertion is the BAD_REQUEST / MISSING_NAME - // text — the kernel correctly forwarded the mixed payload and - // surfaced the server-side rejection without losing context. - let msg = err.message; + .expect("kernel should reject mixed bindings at bind time"); + assert_eq!( + err.code, + ErrorCode::InvalidArgument, + "mixed positional + named params must be InvalidArgument, got {:?}: {}", + err.code, + err.message + ); assert!( - msg.contains("MISSING_NAME") || msg.contains("BAD_REQUEST"), - "expected MISSING_NAME / BAD_REQUEST in error, got: {msg}" + err.message.contains("mutually exclusive"), + "expected 'mutually exclusive' in error, got: {}", + err.message ); session.close().await.expect("session close"); }