diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index cc07864a..88ff4257 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -62,6 +62,14 @@ fn attach_attrs( http_status: Option, retryable: bool, query_id: Option<&str>, + // Extended server-supplied status. These mirror the Thrift path's + // `displayMessage` / `diagnosticInfo` so the connector can populate + // `ServerOperationError.context["diagnostic-info"]` (the Spark stack + // trace) at parity. The kernel `Error` carries them but they were + // previously dropped here. + display_message: Option<&str>, + diagnostic_info: Option<&str>, + error_details_json: Option<&str>, ) -> PyResult<()> { bound.setattr("code", code)?; bound.setattr("message", message)?; @@ -71,6 +79,28 @@ fn attach_attrs( bound.setattr("http_status", http_status)?; bound.setattr("retryable", retryable)?; bound.setattr("query_id", query_id)?; + bound.setattr("display_message", display_message)?; + bound.setattr("diagnostic_info", diagnostic_info)?; + // ``error_details_json`` is documented (types/sea.rs) as a + // potentially multi-MB server blob, and the type-level doc requires + // wrappers to bound its size. Cap what we expose as a Python + // exception attribute so ``repr(e)`` / log lines can't pump + // multi-MB strings into a customer's centralized logging. The full + // blob remains server-side; this is the boundary's exposure cap. + const MAX_ERROR_DETAILS_JSON: usize = 64 * 1024; + let bounded_details = error_details_json.map(|s| { + if s.len() > MAX_ERROR_DETAILS_JSON { + // Truncate on a char boundary, with a marker. + let mut end = MAX_ERROR_DETAILS_JSON; + while !s.is_char_boundary(end) { + end -= 1; + } + format!("{}…[truncated {} bytes]", &s[..end], s.len() - end) + } else { + s.to_owned() + } + }); + bound.setattr("error_details_json", bounded_details)?; let _ = py; // silence unused-var warning if pyo3 ever drops the Python<'_> arg Ok(()) } @@ -105,14 +135,24 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { err.http_status, err.retryable, err.query_id.as_deref(), + err.display_message.as_deref(), + err.diagnostic_info.as_deref(), + err.error_details_json.as_deref(), ) { - // Attribute attachment is best-effort. If something goes - // wrong (extremely unlikely for plain string/int setattrs), - // surface that error so the caller sees it rather than a - // partially-populated exception. Fold the original kernel - // message into the new error so debugging context isn't - // lost. - return setattr_err; + // Attribute attachment is best-effort. If something goes wrong + // (extremely unlikely for plain string/int setattrs — but + // marginally less so now that `error_details_json` can be a + // large blob), don't let the partially-populated exception + // swallow the original kernel context: chain the kernel message + // into the setattr error's cause so debugging context survives. + // ``str(setattr_err)`` would otherwise be a generic Python + // internal error with no hint of the underlying SQL failure. + let chained = KernelError::new_err(format!( + "failed to attach kernel error attributes (original kernel error: {}): {}", + err.message, setattr_err + )); + chained.set_cause(py, Some(setattr_err)); + return chained; } py_err } @@ -139,6 +179,9 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr { None, false, None, + None, + None, + None, ) { return setattr_err; } diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 9a24d277..4909cee0 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -81,6 +81,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/pyo3/src/macros.rs b/pyo3/src/macros.rs index 22ea1df0..9eb9b740 100644 --- a/pyo3/src/macros.rs +++ b/pyo3/src/macros.rs @@ -46,6 +46,59 @@ macro_rules! run_kernel { }}; } +/// Like [`run_kernel!`], but periodically re-acquires the GIL to poll +/// Python signal handlers so a long-running blocking call (e.g. a sync +/// `execute()`) can be interrupted by `KeyboardInterrupt` (Ctrl-C). +/// +/// The bare `py.detach(|| block_on(fut))` form runs the future to +/// completion with the GIL released; the main thread is parked in the +/// FFI call, so a SIGINT-set Python signal flag isn't observed until +/// the call returns. This variant instead drives the future in ~100ms +/// slices: each slice runs with the GIL released, and on each timeout +/// the GIL is re-acquired to call [`Python::check_signals`], which +/// raises (e.g. `KeyboardInterrupt`) if a handler is pending. On +/// interrupt the future is dropped — which fires the kernel's +/// mid-execute cancel guard, so the server-side statement is cancelled +/// too, not just abandoned. +/// +/// `$runtime` must be a `&tokio::runtime::Runtime` (so the future can +/// be driven across slices). Expands to a `PyResult` (the future's +/// `Ok` value), mapping kernel `Error`s via `to_py_err` and surfacing +/// any signal `PyErr` directly. +#[macro_export] +macro_rules! run_kernel_interruptible { + ($py:expr, $runtime:expr, $future:expr) => {{ + let py = $py; + let runtime = $runtime; + // 100ms balances interrupt latency against per-tick overhead. + const TICK: ::std::time::Duration = ::std::time::Duration::from_millis(100); + let mut fut = ::std::boxed::Box::pin($future); + loop { + let step = py.detach(|| { + runtime.block_on(async { + match ::tokio::time::timeout(TICK, &mut fut).await { + Ok(done) => Some(done), + Err(_elapsed) => None, + } + }) + }); + match step { + // Future completed within this slice. + Some(result) => break result.map_err(|e| $crate::errors::to_py_err(py, e)), + // Slice timed out: poll Python signals. A pending + // handler (e.g. KeyboardInterrupt) returns Err, which + // we propagate — dropping `fut` fires the kernel's + // mid-execute cancel guard. + None => { + if let Err(signal_err) = py.check_signals() { + break Err(signal_err); + } + } + } + } + }}; +} + /// Variant that accepts a block expression — useful when the future /// is constructed inline from borrowed state that can't escape the /// `detach` closure cleanly with the simpler form. Same shape, same diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index a1c1c156..cb831b2e 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -27,7 +27,7 @@ use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{ Error as KError, ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, - Statement as KStatement, + Statement as KStatement, StatementCanceller as KStatementCanceller, }; use pyo3::prelude::*; use std::collections::HashMap; @@ -186,17 +186,39 @@ impl Statement { Ok(()) } + /// Produce a detached [`StatementCanceller`] for the statement + /// about to run (or running) on this `Statement`. + /// + /// The sync `execute()` blocks and consumes the statement, so a + /// second thread can't reach an `ExecutedStatement` to cancel a + /// *running* query (the default PEP-249 `cursor.cancel()` shape). + /// Obtain a canceller **before** calling `execute()`; once the + /// server issues the statement id mid-execute, `canceller.cancel()` + /// reaches it. Cheap; safe to call from another thread. + fn canceller(&self) -> PyResult { + let inner = alive!(self, "Statement"); + Ok(StatementCanceller { + inner: inner.stmt.canceller(), + runtime: inner.runtime.clone(), + }) + } + /// Wait-for-result execution. Blocks until the kernel finishes /// polling and returns an `ExecutedStatement` with the result /// stream ready to drain. + /// + /// The blocking drive is interruptible: a `KeyboardInterrupt` + /// (Ctrl-C) raised while this is running aborts the query — the + /// in-flight future is dropped, firing the kernel's mid-execute + /// cancel guard so the server-side statement is cancelled too. fn execute(&mut self, py: Python<'_>) -> PyResult { let inner = alive_mut!(self, "Statement"); let runtime = inner.runtime.clone(); tracing::debug!( target: crate::logging::PYO3_LOG_TARGET, - "Statement.execute: running statement synchronously (GIL released)" + "Statement.execute: running statement synchronously (GIL released, interruptible)" ); - let exec = run_kernel!(py, runtime, inner.stmt.execute())?; + let exec = run_kernel_interruptible!(py, &runtime, inner.stmt.execute())?; Ok(ExecutedStatement::new(exec, runtime)) } @@ -361,3 +383,37 @@ impl ExecutedStatement { ) } } + +/// Detached canceller for the statement in flight on a [`Statement`]. +/// +/// Obtained from [`Statement::canceller`] *before* the blocking +/// `execute()` so a second Python thread can cancel a running sync +/// query — the PEP-249 `cursor.cancel()`-from-another-thread shape. +/// Holds no borrow on the `Statement`; safe to call concurrently with +/// the `execute()` it targets. +#[pyclass(name = "StatementCanceller")] +pub(crate) struct StatementCanceller { + inner: KStatementCanceller, + runtime: Arc, +} + +#[pymethods] +impl StatementCanceller { + /// Server-side cancel of the in-flight statement. + /// + /// No-op if nothing has executed yet, or the query is still in its + /// initial submit round-trip (no statement id observed). Idempotent + /// against a server already in a terminal state. Releases the GIL + /// while the cancel RPC is in flight. + fn cancel(&self, py: Python<'_>) -> PyResult<()> { + let runtime = self.runtime.clone(); + run_kernel!(py, runtime, self.inner.cancel())?; + Ok(()) + } + + /// The server-issued statement id this canceller targets, if one + /// has been observed yet (`None` before the server issues it). + fn statement_id(&self) -> Option { + self.inner.statement_id() + } +} diff --git a/src/client/sea.rs b/src/client/sea.rs index a0161daf..4e7a0b31 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -486,6 +486,17 @@ impl SeaRestTransport { .await?; let statement_id = response.statement_id.clone(); + // Publish the server statement id to the caller's canceller + // slot NOW — before polling — so a concurrent + // `StatementCanceller::cancel()` can target a still-running + // sync query. (The initial POST returns within the server + // wait_timeout, ~10s, even for a long query.) + if let Some(observer) = params.inflight_id_observer.as_ref() { + if let Ok(mut slot) = observer.lock() { + *slot = Some(statement_id.clone()); + } + } + let response = match self.wait_for_completion(response).await { Ok(r) => r, Err(e) => { diff --git a/src/lib.rs b/src/lib.rs index f1559a13..fa7db7bb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -130,7 +130,7 @@ pub use statement::executed_async::{ AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus, }; pub use statement::handle::ExecutedStatementHandle; -pub use statement::mutable::Statement; +pub use statement::mutable::{Statement, StatementCanceller}; pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; diff --git a/src/statement/mod.rs b/src/statement/mod.rs index c000aa6d..13a461cb 100644 --- a/src/statement/mod.rs +++ b/src/statement/mod.rs @@ -40,5 +40,5 @@ pub(crate) mod validity; pub use executed::ExecutedStatement; pub use executed_async::{AsyncStatementCanceller, ExecutedAsyncStatement, StatementStatus}; pub use handle::ExecutedStatementHandle; -pub use mutable::Statement; +pub use mutable::{Statement, StatementCanceller}; pub use spec::{ResultFormat, StatementSpec, TypedValue}; diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 8b075d6c..98387ddb 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -65,9 +65,18 @@ use crate::statement::spec::{ResultFormat, StatementSpec}; use crate::statement::validity::ValidityFlag; use crate::types::sea::{ExecuteParams, StatementState}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use tracing::Instrument; +/// Shared slot holding the server statement id of the statement +/// currently in flight on a [`Statement`] (or its most recent +/// execution). Written by `execute()` / `submit()` as soon as the +/// transport surfaces the id; read by [`StatementCanceller`] so an +/// out-of-band `cancel()` from another thread can reach a *running* +/// sync query — the case the per-call drop guard can't cover because +/// the binding's `block_on` runs the execute future to completion. +type InflightId = Arc>>; + /// 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`. @@ -172,6 +181,13 @@ pub struct Statement { /// skip the `CloseStatement` round-trip entirely when the server /// side is already gone. last_closed: Option>, + /// Server statement id of the in-flight (or most recent) execution, + /// shared with any [`StatementCanceller`] handed out via + /// [`Statement::canceller`]. Populated mid-execute as soon as the + /// transport returns the id; reset to `None` at the start of each + /// new `execute()` / `submit()` so a canceller never targets a + /// stale prior statement. + inflight_id: InflightId, } impl Statement { @@ -184,6 +200,31 @@ impl Statement { last_statement_id: None, last_valid: None, last_closed: None, + inflight_id: Arc::new(Mutex::new(None)), + } + } + + /// Produce a detached [`StatementCanceller`] that can cancel the + /// statement currently in flight on this `Statement` *without + /// borrowing it*. + /// + /// This is the sync-execute counterpart to + /// [`ExecutedAsyncStatement::canceller`](crate::statement::executed_async::ExecutedAsyncStatement::canceller). + /// The blocking `execute()` consumes `&mut self` and runs to + /// completion inside the binding's `block_on`, so a second thread + /// can't reach an `ExecutedStatement` to cancel a *running* query. + /// Obtain a `StatementCanceller` **before** calling `execute()`; + /// once the server issues the statement id mid-execute, the + /// canceller's [`cancel`](StatementCanceller::cancel) reaches it. + /// + /// Cheap to clone (two `Arc` bumps). If `cancel()` fires before the + /// id is observed (query still in the initial submit round-trip) it + /// is a no-op; the per-call drop guard still covers the + /// future-dropped case. + pub fn canceller(&self) -> StatementCanceller { + StatementCanceller { + session: Arc::clone(&self.session), + inflight_id: Arc::clone(&self.inflight_id), } } @@ -227,11 +268,22 @@ impl Statement { let span = self.session.log_span().clone(); async { self.invalidate_prior().await; - let (sql, exec_params) = self.prepare_for_dispatch(None)?; + let (sql, mut exec_params) = self.prepare_for_dispatch(None)?; - let cancel_state = MidExecuteCancelState::new(Arc::clone(&self.session)); + let cancel_state = MidExecuteCancelState::new( + Arc::clone(&self.session), + Arc::clone(&self.inflight_id), + ); let guard = cancel_state.guard(); + // Publish the server statement id to the shared in-flight + // slot as soon as the initial POST returns (the transport + // fills this before its poll loop) so a concurrent + // `StatementCanceller` can cancel a still-running query. + // `MidExecuteCancelState::new` already cleared the slot, so + // set the observer after it. + exec_params.inflight_id_observer = Some(Arc::clone(&self.inflight_id)); + // SeaRestTransport::execute_statement polls to completion // (10s server-side wait_timeout, then GetStatementStatus // loop until terminal). @@ -286,7 +338,10 @@ impl Statement { self.invalidate_prior().await; let (sql, exec_params) = self.prepare_for_dispatch(Some("0s"))?; - let cancel_state = MidExecuteCancelState::new(Arc::clone(&self.session)); + let cancel_state = MidExecuteCancelState::new( + Arc::clone(&self.session), + Arc::clone(&self.inflight_id), + ); let guard = cancel_state.guard(); let response = self @@ -446,15 +501,24 @@ impl Statement { /// statement_id (if any). struct MidExecuteCancelState { session: Arc, - observed_id: std::sync::Mutex>, + /// Shared with the owning [`Statement::inflight_id`] so an + /// out-of-band [`StatementCanceller`] reads the same id this guard + /// observes. Reset to `None` on construction (new execution). + observed_id: InflightId, defused: std::sync::atomic::AtomicBool, } impl MidExecuteCancelState { - fn new(session: Arc) -> Arc { + /// `inflight_id` is the owning `Statement`'s shared slot. We clear + /// it here so a canceller can't fire against a prior statement + /// while this execution is still establishing its own id. + fn new(session: Arc, inflight_id: InflightId) -> Arc { + if let Ok(mut slot) = inflight_id.lock() { + *slot = None; + } Arc::new(Self { session, - observed_id: std::sync::Mutex::new(None), + observed_id: inflight_id, defused: std::sync::atomic::AtomicBool::new(false), }) } @@ -507,6 +571,53 @@ impl Drop for MidExecuteCancelGuard { } } +/// Detached canceller for the statement currently in flight on a +/// [`Statement`]. Produced by [`Statement::canceller`]. +/// +/// Holds only the shared session handle and the `Statement`'s shared +/// in-flight-id slot — **not** the `Statement` itself — so a binding +/// can fire a server-side cancel from another thread while `execute()` +/// is blocked. The sync-execute analogue of +/// [`AsyncStatementCanceller`](crate::statement::executed_async::AsyncStatementCanceller). +/// +/// Cheap to [`Clone`] (two `Arc` bumps). +#[derive(Clone)] +pub struct StatementCanceller { + session: Arc, + inflight_id: InflightId, +} + +impl StatementCanceller { + /// Server-side cancel of the in-flight statement via + /// `cancel_statement(statement_id)`. + /// + /// No-op (returns `Ok`) if no statement id has been observed yet — + /// either nothing has executed, or the query is still in its + /// initial submit round-trip and the server hasn't issued an id. + /// Idempotent against a server already in a terminal state (the + /// kernel's `cancel_statement` is a no-op there). Safe to call + /// concurrently with the `execute()` it targets — the two share + /// only the id slot (behind a `Mutex`), no mutable statement state. + pub async fn cancel(&self) -> Result<()> { + let id = self.inflight_id.lock().ok().and_then(|g| g.clone()); + let Some(id) = id else { + return Ok(()); + }; + async { + self.session.transport().cancel_statement(&id).await?; + Ok(()) + } + .instrument(self.session.log_span().clone()) + .await + } + + /// The server-issued statement id this canceller currently targets, + /// if one has been observed yet. + pub fn statement_id(&self) -> Option { + self.inflight_id.lock().ok().and_then(|g| g.clone()) + } +} + impl Drop for Statement { fn drop(&mut self) { // Flip the validity flag so any executed handle the caller diff --git a/src/statement/params_codec.rs b/src/statement/params_codec.rs index f5743333..ebe8257b 100644 --- a/src/statement/params_codec.rs +++ b/src/statement/params_codec.rs @@ -228,15 +228,32 @@ fn parse_date(s: &str) -> Result { } fn parse_timestamp(s: &str) -> Result { + use chrono::{DateTime, FixedOffset, Utc}; + // 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). + // A tz-AWARE Python datetime (``datetime.now(timezone.utc)``, + // ``.astimezone(tz)``, or ORM/db-sourced values) stringifies with + // an explicit ``+HH:MM`` / ``-HH:MM`` offset. The Thrift path + // forwards such literals verbatim and the server resolves the + // instant; to keep parity, accept the offset forms here too and + // normalise to the equivalent UTC wall-clock, since + // ``TypedValue::Timestamp`` is a naive ``NaiveDateTime`` and the + // SEA wire encodes timestamps in UTC. (Mirrors the offset handling + // in ``parse_timestamp_ltz``.) + if let Ok(dt) = DateTime::::parse_from_rfc3339(s) { + return Ok(TypedValue::Timestamp(dt.with_timezone(&Utc).naive_utc())); + } + if let Ok(dt) = DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f%:z") { + return Ok(TypedValue::Timestamp(dt.with_timezone(&Utc).naive_utc())); + } + + // Naive forms. Also accept the trailing-``Z`` UTC marker that + // JavaScript's ``Date.prototype.toISOString()`` always emits — + // strip it before parsing (the value is already UTC on the wire). let body = s.strip_suffix('Z').unwrap_or(s); let formats = [ "%Y-%m-%d %H:%M:%S%.f", @@ -447,8 +464,15 @@ fn parse_decimal(sql_type: &str, value: &str) -> Result { /// 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. +/// Scientific notation (``1E+2``, ``1E-7``) IS accepted: Python's +/// ``str(Decimal(...))`` emits an exponent for large- or +/// small-magnitude values (``Decimal("1E+2")`` -> ``"1E+2"``, +/// ``Decimal("1E-7")`` -> ``"1E-7"``), and the Databricks server +/// accepts scientific-notation DECIMAL literals — the Thrift path +/// forwards them verbatim. Rejecting them here would make common +/// Decimal bindings fail at bind on the kernel path but work on +/// Thrift. An optional trailing ``[eE][+-]?digits`` exponent is +/// allowed after the (otherwise required) mantissa. fn validate_decimal_literal(value: &str) -> Result<()> { let bytes = value.as_bytes(); if bytes.is_empty() { @@ -474,7 +498,23 @@ fn validate_decimal_literal(value: &str) -> Result<()> { } frac_digits = i - frac_start; } - let well_formed = i == bytes.len() && int_digits >= 1 && (!has_dot || frac_digits >= 1); + let mantissa_ok = int_digits >= 1 && (!has_dot || frac_digits >= 1); + + // Optional exponent: ``[eE][+-]?``. + let mut exp_ok = true; + if i < bytes.len() && matches!(bytes[i], b'e' | b'E') { + i += 1; + if i < bytes.len() && matches!(bytes[i], b'+' | b'-') { + i += 1; + } + let exp_start = i; + while i < bytes.len() && bytes[i].is_ascii_digit() { + i += 1; + } + exp_ok = i - exp_start >= 1; + } + + let well_formed = i == bytes.len() && mantissa_ok && exp_ok; if !well_formed { return Err(invalid_msg(format!("invalid DECIMAL literal {value:?}"))); } @@ -700,6 +740,37 @@ mod tests { assert!(matches!(c, TypedValue::Timestamp(_))); } + #[test] + fn timestamp_accepts_tz_aware_offset_normalised_to_utc() { + // A tz-aware Python datetime (datetime.now(timezone.utc), + // .astimezone(tz), ORM/db-sourced) stringifies with an explicit + // offset. Thrift forwards such literals; the kernel must accept + // them too and normalise to the equivalent UTC wall-clock, + // since TypedValue::Timestamp is naive UTC on the SEA wire. + // + // 18:00 at +05:30 == 12:30 UTC — confirms real conversion, not + // just offset-stripping. + let v = parse_typed_value("TIMESTAMP", Some("2026-05-15T18:00:00+05:30")).unwrap(); + let TypedValue::Timestamp(dt) = v else { + panic!("expected Timestamp"); + }; + assert_eq!( + dt.format("%Y-%m-%dT%H:%M:%S").to_string(), + "2026-05-15T12:30:00" + ); + + // Space-separated offset form (datetime.astimezone().isoformat(sep=' ')). + let v = parse_typed_value("TIMESTAMP", Some("2026-05-15 18:00:00.500000+05:30")).unwrap(); + let TypedValue::Timestamp(dt) = v else { + panic!("expected Timestamp"); + }; + assert_eq!(dt.format("%H:%M:%S%.3f").to_string(), "12:30:00.500"); + + // UTC offset (+00:00) — same wall-clock. + let v = parse_typed_value("TIMESTAMP", Some("2026-05-15T12:30:45+00:00")).unwrap(); + assert!(matches!(v, TypedValue::Timestamp(_))); + } + #[test] fn timestamp_ntz_maps_to_distinct_variant() { // Same literal as TIMESTAMP, but the type-name distinguishes: @@ -997,6 +1068,23 @@ mod tests { } } + #[test] + fn decimal_accepts_scientific_notation() { + // Python's str(Decimal(...)) emits an exponent for large/small + // magnitudes (Decimal("1E+2") -> "1E+2", Decimal("1E-7") -> + // "1E-7"). The server accepts these; Thrift forwards them; the + // kernel must too (the value string is carried verbatim). + for v in ["1E+2", "1E-7", "1e5", "-2.5E10", "+3.14e-2", "0E0"] { + let r = parse_typed_value("DECIMAL(38,10)", Some(v)); + assert!(r.is_ok(), "expected {v:?} to parse: {:?}", r.err()); + } + // A malformed exponent (no digits) is still rejected. + for v in ["1E", "1E+", "1e-", "1EE2"] { + let e = parse_typed_value("DECIMAL(38,10)", Some(v)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidArgument, "{v:?}"); + } + } + #[test] fn decimal_rejects_partial_dot_forms() { // "42." (no fractional digits) and ".5" (no integer digits) diff --git a/src/types/sea.rs b/src/types/sea.rs index 5bb997ef..b6af8066 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -338,6 +338,16 @@ pub struct ExecuteParams { pub row_limit: Option, /// Parameters for parameterized query execution. pub parameters: Vec, + /// Optional sink for the server statement id, published as soon as + /// the initial `POST /statements` returns it — *before* the + /// sync-execute poll loop. Lets a detached canceller + /// (`StatementCanceller`) target a still-running sync query (the + /// id is otherwise only known once `execute_statement` returns, + /// which for a long query is after it has already finished). + /// `None` on the async / metadata / submit paths, which don't poll + /// inside the transport. Never serialized (this is the internal + /// params struct; the wire struct is separate). + pub inflight_id_observer: Option>>>, } /// Compression codec for result data.