Repository navigation
feat(pyo3): Statement.bind_param for positional parameter binding - #18
Conversation
gopalldb
left a comment
There was a problem hiding this comment.
Review summary
This review consolidates findings from a diff/correctness pass and a Databricks-ecosystem pass on feat(pyo3): Statement.bind_param for positional parameter binding. The parameter parser is small, well-tested for the common cases, and aligns cleanly with the wire shape used by peer drivers (PySQL TSparkParameter / SEA StatementParameter, JDBC, Node, Go) — 1-based ordinals, value as a string literal, type as a SQL type name, and the BOOLEAN/DATE/TIMESTAMP/STRING/BINARY conventions all line up with peer driver emission. The findings concentrate on (a) a real contradiction between the PR's headline claim that bad literals surface at bind time and the DECIMAL path which only rejects structural problems, (b) a couple of parser corner cases (single-arg DECIMAL, float overflow silently becoming Inf, trailing Z on timestamps), and (c) a handful of ecosystem mismatches (TIMESTAMP_NTZ silently downgraded, INTERVAL subtype loss, alias parity with JDBC) plus test/doc polish. No blockers.
Severity breakdown
| Severity | Count |
|---|---|
| blocker | 0 |
| major | 2 |
| minor | 8 |
| nit | 5 |
Adjustments made by the consolidating reviewer
agent-1-004(broad prefix match for ARRAY/MAP/STRUCT) downgraded minor → nit: the author's own reasoning notes "none are real Databricks types today," so the impact is cosmetic.agent-2-001(TIMESTAMP_NTZ silently collapsed) kept at minor despite tie-break pressure to upgrade: the reasoning notes JDBC's SEA path does the same TIMESTAMP_NTZ → TIMESTAMP collapse, so the wire-level outcome is likely the server-supported one — the real defect is accepting the name without preserving intent, not silent corruption.agent-2-003(missing BYTE / SHORT aliases) downgraded minor → nit: PySQL and Node don't emit these aliases, so the practical impact is pure parity with JDBC's alias list.agent-2-004(timestamp parser doesn't accept trailingZ): inline line anchor nulled — cited line 197 lands insideextract_decimal_precision_scale, not the timestamp format list at lines 154-159. The content is sound; rendered as a summary-only finding to avoid a misleading inline anchor.- All other findings kept at their original severity.
Findings without a specific location
-
[minor] Timestamp parser doesn't accept Node-style trailing
Z(pyo3/src/params.rs)parse_timestampaccepts four formats —%Y-%m-%d %H:%M:%S[.f]and%Y-%m-%dT%H:%M:%S[.f]— but rejects the trailingZ(UTC marker) that JavaScript'sDate.prototype.toISOString()always emits (2026-05-15T12:30:45.123Z).databricks-sql-nodejs/lib/DBSQLParameter.ts:88callsthis.value.toISOString()to stringify dates. A future Node wrapper of the PyO3 surface or any caller that hand-builds an ISO-8601 timestamp string with an explicitZ(a perfectly valid wire form) will getKernelError(InvalidArgument). Either widen the format list to include%Y-%m-%dT%H:%M:%S%.fZ/%Y-%m-%dT%H:%M:%SZ(and strip the offset sinceTypedValue::Timestampis a naiveNaiveDateTime), or document the supported subset inbind_param's docstring so wrappers know to strip theZbefore calling.
This review was produced by gl-review (3-agent: diff reviewer, ecosystem reviewer, independent verifier). Posted as COMMENTED — final approval is the author/maintainer call.
| Err(invalid_msg(format!("invalid TIMESTAMP literal {s:?}"))) | ||
| } | ||
|
|
||
| fn parse_decimal(sql_type: &str, value: &str) -> Result<TypedValue> { |
There was a problem hiding this comment.
[major] parse_decimal (pyo3/src/params.rs:168) extracts precision and scale but passes the value string straight through unvalidated. So bind_param(1, "not-a-number", "DECIMAL(10,2)") succeeds at bind time and only fails at execute() when the server rejects the wire payload. This directly contradicts the PR description's claim that "Bad literals (bind_param(1, 'not-a-number', 'INT')) surface as KernelError(code='InvalidArgument', ...) at bind time, before execute, with a pointed message" — that contract holds for INT/BIGINT/FLOAT/DOUBLE/DATE/TIMESTAMP but silently breaks for DECIMAL. A minimal fix is to call value.parse::<f64>() (or a stricter decimal-literal check — a quick is_ascii_digit/./- scan is enough) and surface Error::invalid_argument().message(...) on failure. Worth adding a test like parse_typed_value("DECIMAL(10,2)", Some("abc")).unwrap_err() to lock the behaviour in.
There was a problem hiding this comment.
Addressed in b1b769f. parse_decimal now calls a new validate_decimal_literal() helper that accepts an optional sign + digits + optional fractional part (e.g. -123.45, 0, .5, 42.) and rejects anything else, so bind_param(1, "abc", "DECIMAL(10,2)") fails at bind time. Covered by two new unit tests: decimal_rejects_bad_value_literal and decimal_accepts_canonical_value_literals.
| let parts: Vec<&str> = inner.split(',').map(|p| p.trim()).collect(); | ||
| if parts.len() != 2 { |
There was a problem hiding this comment.
[major] extract_decimal_precision_scale (pyo3/src/params.rs:195-200) requires exactly two comma-separated parts inside the parens — "DECIMAL(38)" is rejected with "DECIMAL type must have exactly two parameters". Databricks SQL accepts DECIMAL(p) with scale defaulting to 0 (see the type reference at https://docs.databricks.com/sql/language-manual/data-types/decimal-type.html), and a connector translating a user-supplied type literal could very plausibly hand the kernel "DECIMAL(38)". Either accept parts.len() == 1 and default scale to 0, or document in the bind_param rustdoc that only the two-arg parenthesised form is accepted. Adding a test for "DECIMAL(38)" would pin whichever direction you take.
There was a problem hiding this comment.
Addressed in b1b769f. extract_decimal_precision_scale now accepts parts.len() == 1 (scale defaults to 0) so DECIMAL(38) parses as (precision=38, scale=0). New unit test: decimal_single_arg_defaults_scale_to_zero.
| .map_err(|e| invalid_msg(format!("invalid BIGINT literal {s:?}: {e}"))) | ||
| } | ||
|
|
||
| fn parse_f32(s: &str) -> Result<TypedValue> { |
There was a problem hiding this comment.
[minor] parse_f32/parse_f64 (pyo3/src/params.rs:131-141) rely on str::parse, which by IEEE 754 convention returns +inf / -inf for out-of-range magnitudes (e.g. "1e500".parse::<f32>() == Ok(inf)). Compare with parse_i8("300") which the test suite verifies returns InvalidArgument. So users sending "1e500" as FLOAT will get a successful bind, an Inf on the wire, and an opaque server-side surprise instead of a typed InvalidArgument at bind time. Consider rejecting non-finite parse results: if !v.is_finite() { return Err(invalid_msg(...)) }. Same applies to NaN and the literal strings "inf" / "nan" which f32::from_str accepts.
There was a problem hiding this comment.
Addressed in b1b769f. parse_f32/parse_f64 now reject non-finite results via is_finite() after str::parse, so "1e500", "inf", "nan", "-Infinity" all fail at bind time. New unit test: float_overflow_and_nan_rejected covers FLOAT and DOUBLE for both overflow and NaN literals.
| _ if upper.starts_with("ARRAY") | ||
| || upper.starts_with("MAP") |
There was a problem hiding this comment.
[nit] The compound-rejection arm (pyo3/src/params.rs:77-84) uses upper.starts_with("ARRAY") || upper.starts_with("MAP") || upper.starts_with("STRUCT"). That matches contrived inputs like "ARRAYBUFFER", "MAPLE", or "STRUCTURE" — none are real Databricks types today, but the intent of the arm is plainly "the type is one of the three compound parameterised forms". Tightening to upper == "ARRAY" || upper.starts_with("ARRAY<") || upper.starts_with("ARRAY(") (and equivalents) makes the boundary unambiguous and gives a more useful "unsupported parameter SQL type" message for the bizarre cases. Low-stakes, but worth fixing while the file is still small.
There was a problem hiding this comment.
Addressed in b1b769f. Compound-rejection now goes through a new is_compound_type_name() helper that only matches ARRAY/MAP/STRUCT exactly or followed by < (generic) / ( (function-style). ARRAYBUFFER/MAPLE/STRUCTURE fall through to the generic "unsupported parameter SQL type" message. New unit test: compound_match_does_not_overreach.
| #[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<INT>", "MAP", "STRUCT<a:INT>"] { | ||
| 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:?}"), | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
[minor] StatementSpec::param (src/statement/spec.rs:131) rejects ordinal == 0 with InvalidArgument, and Statement::bind_param (pyo3/src/statement.rs:101) maps that error to KernelError via to_py_err. There's no test for either path — neither in pyo3/src/params.rs (which would need an integration-style test that constructs a StatementSpec directly) nor in pyo3/tests/test_execute.py. A live pytest test_bind_param_zero_ordinal_rejected that asserts KernelError(code='InvalidArgument') would lock the SEA 1-based contract on the Python surface. Same gap applies to duplicate-ordinal last-write-wins semantics (bind_param(1, "x", "INT") then bind_param(1, "y", "INT")) — currently undocumented behaviour that a user could be surprised by.
There was a problem hiding this comment.
Addressed in b1b769f. Added two pytest tests:
test_bind_param_zero_ordinal_rejected— asserts ordinal=0 raisesKernelError(InvalidArgument).test_bind_param_duplicate_ordinal_last_wins— exercises double-binding ordinal 1 (last value wins) and confirms the server echoes the overwritten value.
Last-write-wins is the existing kernel behaviour (StatementSpec::param at src/statement/spec.rs:142 unconditionally assigns), so the test pins that contract rather than introduces it.
| "BINARY parameters are not supported by the SEA wire today", | ||
| )), | ||
| "DATE" => parse_date(s), | ||
| "TIMESTAMP" | "TIMESTAMP_NTZ" => parse_timestamp(s), |
There was a problem hiding this comment.
[minor] parse_typed_value accepts "TIMESTAMP_NTZ" and routes it through the same parse_timestamp → TypedValue::Timestamp(NaiveDateTime) path as plain TIMESTAMP. Downstream, src/statement/params.rs:373 (typed_value_to_sea_payload) only emits "TIMESTAMP" as the SEA type field — there is no TypedValue::TimestampNtz variant. PySQL's TimestampNTZParameter (databricks-sql-python/src/databricks/sql/parameters/native.py:394-418) explicitly preserves the TIMESTAMP_NTZ cast expression on the wire, so a connector faithfully forwarding TimestampNTZParameter.as_tspark_param().type to Statement.bind_param(..., "TIMESTAMP_NTZ") will not get NTZ semantics — the kernel will quietly downgrade. JDBC's SEA path does the same collapse (DatabricksTypeUtil.getColumnInfoType maps both TIMESTAMP and TIMESTAMP_NTZ to ColumnInfoTypeName.TIMESTAMP), so the wire-level outcome may in fact be the server-supported one and the divergence may be intentional — but accepting the name and silently dropping the intent is the worst combination. Either preserve NTZ on the wire (and add a TypedValue::TimestampNtz variant) or reject "TIMESTAMP_NTZ" with a pointed not yet supported — use TIMESTAMP error, so callers aren't surprised.
There was a problem hiding this comment.
Deferred to a follow-up. The real fix is a kernel-side TypedValue::TimestampNtz variant in src/statement/spec.rs, which is a cross-cutting kernel change worth its own PR. For this PR the silent collapse continues to match JDBC SEA-path behaviour as noted in the review summary; will file a follow-up issue.
| )), | ||
| "DATE" => parse_date(s), | ||
| "TIMESTAMP" | "TIMESTAMP_NTZ" => parse_timestamp(s), | ||
| "INTERVAL" => Ok(TypedValue::Interval(s.to_owned())), |
There was a problem hiding this comment.
[minor] The kernel accepts "INTERVAL" only and stores the raw value as TypedValue::Interval(s), which typed_value_to_sea_payload (src/statement/params.rs:377) emits as type name "INTERVAL". Peer drivers that actually expose interval binding distinguish subtypes on the wire: databricks-sql-go/parameters.go:66-69 emits "INTERVAL MONTH" / "INTERVAL DAY", and databricks-sql-nodejs/lib/DBSQLParameter.ts:19-20 defines INTERVALMONTH = 'INTERVAL MONTH' / INTERVALDAY = 'INTERVAL DAY'. The SEA StatementParameter.type doc (SDK StatementParameterListItem.java:16-22) defers to the SQL cast type list, which does enumerate INTERVAL DAY, INTERVAL MONTH, INTERVAL DAY TO SECOND, etc. — bare INTERVAL is not in that list. PySQL and JDBC do not expose interval binding so they don't show this divergence, but a connector author trying to wire up an interval parameter through the kernel can't currently send the qualified form; they'd need to accept "INTERVAL MONTH" etc. as input here. Either widen the match arm to accept "INTERVAL" | "INTERVAL DAY" | "INTERVAL MONTH" | "INTERVAL DAY TO SECOND" | … and forward the qualified form on the wire, or document that intervals must round-trip through TypedValue::String with an explicit CAST(? AS INTERVAL DAY) in SQL.
There was a problem hiding this comment.
Deferred to a follow-up. Qualified intervals (INTERVAL MONTH, INTERVAL DAY, etc.) need either richer kernel-side TypedValue::Interval semantics or wire-side handling of the qualifier. Will file a follow-up issue; for this PR callers can CAST qualified intervals in SQL and bind via STRING instead.
| } | ||
|
|
||
| fn parse_i8(s: &str) -> Result<TypedValue> { | ||
| s.parse::<i8>() |
There was a problem hiding this comment.
[nit] databricks-jdbc/src/main/java/com/databricks/jdbc/common/util/DatabricksTypeUtil.java:43,46 defines BYTE = "BYTE" and SMALLINT = "SHORT" as recognized DBR type-name aliases (the Databricks SQL data-types reference page treats BYTE as a TINYINT synonym and SHORT as a SMALLINT synonym). The PR's match arm currently accepts "TINYINT" and "SMALLINT" only. PySQL and Node don't emit those aliases so this is unlikely to bite in practice, but the PR already accepts a generous alias set ("INT"|"INTEGER", "BIGINT"|"LONG", "BOOLEAN"|"BOOL", "STRING"|"VARCHAR"|"CHAR") for connector robustness, and the JDBC type-util file is the closest thing to a canonical DBR alias list. Worth adding "BYTE" => parse_i8(s) and "SHORT" => parse_i16(s) for parity, or noting explicitly that those aliases are unsupported.
There was a problem hiding this comment.
Deferred. The review summary notes PySQL and Node don't emit BYTE/SHORT (only JDBC does), so the practical impact is JDBC-parity only. Will file a follow-up issue if/when a JDBC-via-PyO3 caller materialises; aliases are a one-line add when needed.
| /// Bind a positional parameter. | ||
| /// | ||
| /// ``ordinal`` is 1-based on the SEA wire. ``value_str`` is the | ||
| /// connector's string-serialized form (or ``None`` for SQL NULL); | ||
| /// ``sql_type`` is the Databricks SQL type name (``"INT"``, | ||
| /// ``"BIGINT"``, ``"STRING"``, ``"BOOLEAN"``, ``"DATE"``, | ||
| /// ``"TIMESTAMP"``, ``"FLOAT"``, ``"DOUBLE"``, | ||
| /// ``"DECIMAL(p,s)"``, ``"VOID"``, ``"TINYINT"``, | ||
| /// ``"SMALLINT"``, ``"INTERVAL"``). | ||
| /// | ||
| /// 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', ...)``. | ||
| #[pyo3(signature = (ordinal, value_str, sql_type))] | ||
| fn bind_param( |
There was a problem hiding this comment.
[nit] bind_param raises KernelError(code='InvalidArgument') for both bad-literal ('not-a-number' as INT) and unsupported-type (ARRAY/MAP/STRUCT/BINARY) cases. PEP-249 §5.2.3 specifies ProgrammingError for invalid input and NotSupportedError for features the driver explicitly does not support — and the connector's own exception hierarchy (databricks-sql-python/src/databricks/sql/exc.py:65,77) implements both. A connector wrapping this surface will want different mappings: bad-literal → ProgrammingError, compound/binary/named → NotSupportedError. The kernel has only one InvalidArgument bucket, so the wrapper has to discriminate on the error message string (e.g. matching "compound" / "BINARY"). Either expose a more granular ErrorCode (ErrorCode::NotSupported) for the explicitly-unsupported cases, or call out in the doc that wrappers should string-match on the message for the PEP-249 split — the current state risks every type-related error collapsing to ProgrammingError on the wrapper side.
There was a problem hiding this comment.
Deferred. Introducing ErrorCode::NotSupported is a kernel-wide taxonomy decision touching src/kernel_error.rs and every existing Error::invalid_argument() site that should arguably re-categorise. Out of scope for this bind_param PR; will file a follow-up issue.
| fn parse_bool(s: &str) -> Result<TypedValue> { | ||
| 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<TypedValue> { | ||
| s.parse::<i8>() | ||
| .map(TypedValue::Int8) | ||
| .map_err(|e| invalid_msg(format!("invalid TINYINT literal {s:?}: {e}"))) | ||
| } | ||
|
|
||
| fn parse_i16(s: &str) -> Result<TypedValue> { | ||
| s.parse::<i16>() | ||
| .map(TypedValue::Int16) | ||
| .map_err(|e| invalid_msg(format!("invalid SMALLINT literal {s:?}: {e}"))) | ||
| } | ||
|
|
||
| fn parse_i32(s: &str) -> Result<TypedValue> { |
There was a problem hiding this comment.
[nit] parse_typed_value does let upper = sql_type.to_ascii_uppercase() and matches upper.starts_with("DECIMAL(") for routing, but parse_decimal then passes the original-case sql_type to extract_decimal_precision_scale. PySQL's DecimalParameter._cast_expr (databricks-sql-python/src/databricks/sql/parameters/native.py:593-597,623) emits "DECIMAL({},{})" upper-case via DatabricksSupportedType.DECIMAL.name, so the practical inputs are always upper-case — but a quick check shows that the "decimal(5,2)" test on line 444 of params.rs only works because extract_decimal_precision_scale is case-agnostic (it scans for (/)/,). That's correct but accidental; a future reader might assume the parser only handles uppercase. Worth adding a comment that the precision/scale extraction is intentionally case-insensitive even though the routing only matches uppercase, so the two stay in sync if anyone refactors. Also worth noting: PySQL's DecimalParameter._cast_expr has a long-standing bug where it formats (scale, precision) instead of (precision, scale) when both are explicitly set (line 595: self.CAST_EXPR.format(self.scale, self.precision) — note the order). The kernel parses (precision, scale) correctly per SQL convention, so a connector forwarding PySQL's explicit-scale path would feed the kernel inverted values. Not the kernel's bug to fix, but worth mentioning so this PR's review surfaces it for the connector-author.
There was a problem hiding this comment.
Note: case-insensitivity for the precision/scale extraction is intentional — parse_typed_value uppercases for routing, and extract_decimal_precision_scale reads digits which are case-agnostic, so Decimal(10,2) and DECIMAL(10,2) behave identically. The new lowercase test lowercase_sql_type_works already covers this path.
c596382 to
b1b769f
Compare
|
Pushed b1b769f addressing the gl-review feedback. Summary: Addressed (10 findings):
Deferred to follow-up issues:
Verification:
|
|
P1 — Important (should fix)
pyo3/src/statement.rs:80 (fn bind_param signature) ordinal: usize makes PyO3 coerce a Python negative int into OverflowError before the function body runs. The docstring promises InvalidArgument semantics ("ordinal is 1-based"), and the live test Fix: Accept ordinal: i64 (or isize), check < 1 explicitly, and surface Error::invalid_argument().message("positional parameter ordinal must be >= 1 (1-based)") through to_py_err before casting to usize. Add
pyo3/src/params.rs:267 (validate_decimal_literal) The validator accepts "42." (trailing dot, no fractional digits) and ".5" (leading dot, no integer digits). Both are listed as canonical in decimal_accepts_canonical_value_literals, but Databricks' decimal Fix: Require int_digits >= 1 && (no dot || frac_digits >= 1). Drop "42."/".5" from the accepted-literals test (or add the empty-fraction shape only if the kernel canonicalises before send).
pyo3/src/params.rs:330-342 (precision/scale validation) Databricks SQL DECIMAL allows scale in -(38 - precision)..=precision — negative scale is legal and rounds to multiples of 10^|s|. The validator rejects all negative scales. No current connector emits Fix: Correct the comment to say "kernel constraint, tighter than server" (conservative path), or widen the bound to -(38 - p) ..= p. |
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 <vikrant.puppala@databricks.com>
b1b769f to
1b128ce
Compare
|
All three addressed in 1b128ce. 1. Negative ordinal bypasses kernel error mapping — 2. Decimal value validation accepts forms the server will reject — 3. Decimal scale doc-comment misstates Databricks spec — rewrote the comment near the precision/scale bound check to call out that the kernel-side bound is intentionally tighter than the server spec (which allows scale in Verification:
|
Summary
Phase 2 follow-up to #13. Adds positional-parameter binding to the PyO3
Statementsurface — the biggest functional gap foruse_sea=Trueusers.What it adds
```python
stmt = session.statement()
stmt.set_sql("SELECT * FROM t WHERE id = ? AND name = ? AND created_at > ?")
stmt.bind_param(1, "42", "INT")
stmt.bind_param(2, "alice", "STRING")
stmt.bind_param(3, "2026-01-01", "DATE")
exec_ = stmt.execute()
```
`(ordinal, value_str, sql_type)` matches the shape the connector already produces in `TSparkParameter` — value is string-serialized, type carries the SQL intent. 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.
Type coverage
Bad literals (`bind_param(1, "not-a-number", "INT")`) surface as `KernelError(code='InvalidArgument', ...)` at bind time, before execute, with a pointed message.
Implementation
Test plan
Total pyo3 pytest count: 35/35 pass (was 31).
This pull request and its description were written by Isaac.