From 1b128cebc72e9456b9d3c1f34aac0972e3220272 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Fri, 15 May 2026 09:12:09 +0000 Subject: [PATCH] feat(pyo3): Statement.bind_param for positional parameter binding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Surfaces the kernel's positional-param API to Python. Lifts the NotSupportedError the connector backend currently raises for parametrized queries — the biggest functional gap for use_sea=True users. PyO3 surface: stmt.bind_param(ordinal: int, value_str: Optional[str], sql_type: str) `(ordinal, value_str, sql_type)` matches the shape the connector already produces in `TSparkParameter` — value is string-serialized, type carries the SQL intent (`"INT"`, `"DECIMAL(10,2)"`, `"TIMESTAMP"`, etc.). Re-parsing into a native Python type just to re-encode into a kernel `TypedValue` would be a lossy round-trip, so the kernel binding takes the string directly. Implementation: - New `params.rs` module owns the `(sql_type, value_str) -> TypedValue` parser. Free function so it's unit-testable in pure Rust. - Handles: BOOLEAN, TINYINT/SMALLINT/INT/BIGINT, FLOAT/DOUBLE, STRING/VARCHAR/CHAR, DATE, TIMESTAMP (with and without sub-second precision, ISO-8601 T-separator), INTERVAL, DECIMAL(p,s), VOID/None. - Rejects: BINARY (SEA wire limitation kernel-side), compound types (ARRAY/MAP/STRUCT — own follow-up), named-binding mode (kernel v0 rejects at execute time anyway). - Errors map to `KernelError(code='InvalidArgument', ...)` — surfaces at bind time, before execute, with a clear message. Tests: - 16 Rust unit tests in `params.rs` covering each type variant, error paths, casing tolerance. Visible to `cargo test -p` thanks to the `rlib` crate-type addition from PR #13's C1. - 4 new live pytests against dogfood: - all-types round-trip in one SELECT (INT, BIGINT, STRING, BOOL, DOUBLE, DECIMAL(10,2), DATE, TIMESTAMP, NULL) - VOID-as-null - compound type rejection - bad literal at bind time Total pyo3 pytest count: 35/35 pass (was 31). Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- Cargo.lock | 1 + pyo3/Cargo.toml | 5 + pyo3/src/lib.rs | 1 + pyo3/src/params.rs | 623 +++++++++++++++++++++++++++++++++++++ pyo3/src/statement.rs | 66 +++- pyo3/tests/test_execute.py | 143 +++++++++ 6 files changed, 838 insertions(+), 1 deletion(-) create mode 100644 pyo3/src/params.rs diff --git a/Cargo.lock b/Cargo.lock index 353520e1..63d237cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -385,6 +385,7 @@ dependencies = [ "arrow-array", "arrow-pyarrow", "arrow-schema", + "chrono", "databricks-sql-kernel", "pyo3", "tokio", diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index e9e830d8..c083a5ce 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -51,3 +51,8 @@ tokio = { version = "1", features = ["rt-multi-thread"] } arrow-array = "57" arrow-schema = "57" arrow-pyarrow = "57" + +# Date / timestamp parsing for parameter binding. Same version the +# kernel uses for its `TypedValue::Date` / `TypedValue::Timestamp` +# variants — the parsed values flow directly into those. +chrono = "0.4" diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index da96d941..212174ae 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -37,6 +37,7 @@ mod errors; mod executed_async; mod fetch; mod metadata; +mod params; mod result_stream; mod session; mod statement; diff --git a/pyo3/src/params.rs b/pyo3/src/params.rs new file mode 100644 index 00000000..3365716d --- /dev/null +++ b/pyo3/src/params.rs @@ -0,0 +1,623 @@ +// 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`. +//! +//! 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::{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), + "TIMESTAMP" | "TIMESTAMP_NTZ" => parse_timestamp(s), + "INTERVAL" => Ok(TypedValue::Interval(s.to_owned())), + _ if upper.starts_with("DECIMAL(") => parse_decimal(sql_type, s), + _ if is_compound_type_name(&upper) => Err(invalid( + "compound parameter types (ARRAY/MAP/STRUCT) are not yet supported", + )), + _ => Err(invalid_msg(format!( + "unsupported parameter SQL type: {sql_type:?}" + ))), + } +} + +/// True iff `upper` is one of ARRAY/MAP/STRUCT exactly, or one of +/// those followed by `<` (generic) or `(` (function-style). 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:?}"))) +} + +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 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 + ); + } + } +} diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index f03de90a..afe208c3 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -19,12 +19,15 @@ //! (async-consumption). The fetch surface on `ExecutedStatement` //! returns Arrow record batches as pyarrow values. +use crate::errors::to_py_err; use crate::executed_async::ExecutedAsyncStatement; use crate::fetch; +use crate::params::parse_typed_value; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{ - ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, Statement as KStatement, + Error as KError, ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, + Statement as KStatement, }; use pyo3::prelude::*; use std::sync::Arc; @@ -62,6 +65,67 @@ impl Statement { Ok(()) } + /// Bind a positional parameter. + /// + /// ``ordinal`` is 1-based on the SEA wire. ``value_str`` is the + /// connector's string-serialised form (or ``None`` for SQL + /// NULL); ``sql_type`` is the Databricks SQL type name. + /// + /// Accepted ``sql_type`` values (case-insensitive): + /// ``"VOID"``, ``"BOOLEAN"`` / ``"BOOL"``, ``"TINYINT"``, + /// ``"SMALLINT"``, ``"INT"`` / ``"INTEGER"``, ``"BIGINT"`` / + /// ``"LONG"``, ``"FLOAT"``, ``"DOUBLE"``, ``"STRING"`` / + /// ``"VARCHAR"`` / ``"CHAR"``, ``"DATE"``, ``"TIMESTAMP"`` / + /// ``"TIMESTAMP_NTZ"``, ``"INTERVAL"``, ``"DECIMAL(p,s)"`` and + /// ``"DECIMAL(p)"`` (scale defaults to 0). See + /// ``pyo3/src/params.rs`` for the authoritative mapping. + /// + /// This shape — string value + type name — exists because the + /// connector's ``TSparkParameter`` already string-serialises + /// every value (the Thrift wire format uses + /// ``stringValue``). Re-parsing into a native Python type just + /// to re-encode to a kernel ``TypedValue`` would be a lossy + /// round-trip; the kernel takes the string directly. + /// + /// Named bindings, compound types (ARRAY/MAP/STRUCT), and + /// BINARY are not yet supported and raise + /// ``KernelError(code='InvalidArgument', ...)``. Bad value + /// literals (e.g. ``bind_param(1, "abc", "INT")``) also raise + /// at bind time, before ``execute()``. + #[pyo3(signature = (ordinal, value_str, sql_type))] + fn bind_param( + &mut self, + py: Python<'_>, + ordinal: i64, + value_str: Option, + sql_type: String, + ) -> PyResult<()> { + let inner = alive_mut!(self, "Statement"); + // Reject ordinal < 1 here rather than via PyO3's `usize` + // extraction. A `usize` parameter would surface a negative + // ordinal as Python `OverflowError` before the function body + // ran, breaking the documented `KernelError(InvalidArgument)` + // contract that wrappers catch on. The kernel itself also + // rejects 0 (see `StatementSpec::param`), but we surface that + // here for the same reason — one error code, one type, for + // every invalid ordinal. + if ordinal < 1 { + return Err(to_py_err( + py, + KError::invalid_argument() + .message("positional parameter ordinal must be >= 1 (1-based)"), + )); + } + let typed = + parse_typed_value(&sql_type, value_str.as_deref()).map_err(|e| to_py_err(py, e))?; + inner + .stmt + .spec() + .param(ordinal as usize, typed) + .map_err(|e| to_py_err(py, e))?; + Ok(()) + } + /// Wait-for-result execution. Blocks until the kernel finishes /// polling and returns an `ExecutedStatement` with the result /// stream ready to drain. diff --git a/pyo3/tests/test_execute.py b/pyo3/tests/test_execute.py index 4958d6d7..741eb502 100644 --- a/pyo3/tests/test_execute.py +++ b/pyo3/tests/test_execute.py @@ -17,6 +17,7 @@ from __future__ import annotations import pyarrow as pa +import pytest import databricks_sql_kernel as k @@ -123,6 +124,148 @@ def test_statement_close_is_idempotent(session): stmt.close() # idempotent +@live +def test_bind_param_positional_round_trips_all_simple_types(session): + """Bind positional parameters across the primary type spectrum + and confirm the server echoes the same values back. Single + SELECT bundles all bindings so we exercise multiple ordinals + in one round-trip.""" + stmt = session.statement() + stmt.set_sql( + "SELECT ? AS i, ? AS l, ? AS s, ? AS b, ? AS d, ? AS dec, ? AS dt, ? AS ts, ? AS n" + ) + stmt.bind_param(1, "42", "INT") + stmt.bind_param(2, "9999999999", "BIGINT") + stmt.bind_param(3, "hello world", "STRING") + stmt.bind_param(4, "true", "BOOLEAN") + stmt.bind_param(5, "3.14", "DOUBLE") + stmt.bind_param(6, "-123.45", "DECIMAL(10,2)") + stmt.bind_param(7, "2026-05-15", "DATE") + stmt.bind_param(8, "2026-05-15 12:30:45", "TIMESTAMP") + stmt.bind_param(9, None, "STRING") # SQL NULL + exec_ = stmt.execute() + try: + table = exec_.fetch_all_arrow() + assert table.num_rows == 1 + row = {table.schema[i].name: table.column(i).to_pylist()[0] + for i in range(table.num_columns)} + # Server-side type widening: BIGINT stays bigint, but the + # column types are server-decided. Compare values not types. + assert row["i"] == 42 + assert row["l"] == 9999999999 + assert row["s"] == "hello world" + assert row["b"] is True + assert row["d"] == 3.14 + # Decimal comes back as Python Decimal — match string form. + assert str(row["dec"]) == "-123.45" + import datetime + assert row["dt"] == datetime.date(2026, 5, 15) + # TIMESTAMP comes back tz-aware from the server. The kernel + # treats `TypedValue::Timestamp` as a naive UTC value, so the + # echo MUST be UTC-aware and the wall-clock fields must match + # the input. Asserting both pins the round-trip contract + # instead of just normalising it away. + ts = row["ts"] + assert ts.tzinfo is not None, "expected tz-aware timestamp" + assert ts.utcoffset() == datetime.timedelta(0), ts.utcoffset() + assert ts.replace(tzinfo=None) == datetime.datetime(2026, 5, 15, 12, 30, 45) + assert row["n"] is None + finally: + exec_.close() + stmt.close() + + +@live +def test_bind_param_void_treated_as_null(session): + """`VOID` SQL type is the connector's way of expressing + `cursor.execute(..., [None])` — value_str is ignored, result + is SQL NULL.""" + stmt = session.statement() + stmt.set_sql("SELECT ? IS NULL AS is_null") + # Connector's VoidParameter passes stringValue("None") with + # type "VOID" — the parser ignores the value. + stmt.bind_param(1, "None", "VOID") + exec_ = stmt.execute() + try: + table = exec_.fetch_all_arrow() + assert table.column(0).to_pylist() == [True] + finally: + exec_.close() + stmt.close() + + +@live +def test_bind_param_compound_type_rejected(session): + """ARRAY/MAP/STRUCT parameter binding is a documented gap.""" + stmt = session.statement() + stmt.set_sql("SELECT ?") + try: + try: + stmt.bind_param(1, "[1,2,3]", "ARRAY") + except k.KernelError as e: + assert e.code == "InvalidArgument", e.code + assert "compound" in e.message.lower(), e.message + else: + raise AssertionError("expected KernelError for ARRAY parameter") + finally: + stmt.close() + + +@live +def test_bind_param_invalid_value_surfaces_error(session): + """A non-numeric value for an INT param should surface as + KernelError(InvalidArgument) at bind time, before execute.""" + stmt = session.statement() + stmt.set_sql("SELECT ?") + try: + try: + stmt.bind_param(1, "not-a-number", "INT") + except k.KernelError as e: + assert e.code == "InvalidArgument", e.code + else: + raise AssertionError("expected KernelError for bad INT literal") + finally: + stmt.close() + + +@live +@pytest.mark.parametrize("ordinal", [0, -1, -1000]) +def test_bind_param_non_positive_ordinal_rejected(session, ordinal): + """SEA parameter ordinals are 1-based; both zero and negative + ordinals must raise ``KernelError(InvalidArgument)`` — not + Python ``OverflowError`` (which a ``usize`` extractor would + raise before the kernel could surface a typed error).""" + stmt = session.statement() + stmt.set_sql("SELECT ?") + try: + try: + stmt.bind_param(ordinal, "1", "INT") + except k.KernelError as e: + assert e.code == "InvalidArgument", e.code + else: + raise AssertionError(f"expected KernelError for ordinal={ordinal}") + finally: + stmt.close() + + +@live +def test_bind_param_duplicate_ordinal_last_wins(session): + """Re-binding the same ordinal overwrites the prior value + (last-write-wins). This documents the contract rather than + discovering it later.""" + stmt = session.statement() + stmt.set_sql("SELECT ? AS x") + stmt.bind_param(1, "1", "INT") + stmt.bind_param(1, "42", "INT") # overwrites + exec_ = stmt.execute() + try: + table = exec_.fetch_all_arrow() + assert table.column(0).to_pylist() == [42] + finally: + exec_.close() + stmt.close() + + @live def test_bad_sql_surfaces_structured_kernel_error(session): stmt = session.statement()