Skip to content

Commit 9996717

Browse files
feat(reader): comparator parity — intervals_as_string + empty-result schema + composite + TIMESTAMP tz + getTables/getColumns metadata + named params
Eight comparator-parity fixes in the kernel's result-reader, metadata-reshape, and parameter-binding pipelines, surfaced by the python-comparator audit. ### 1. `intervals_as_string` post-processor option pyarrow's Python bindings can't decode Arrow's `month_interval` (id 21) at all. Every kernel-backend `SELECT *` over a table with `INTERVAL YEAR TO MONTH` columns threw `ArrowNotImplementedError`. 32 / 88 comparator diffs. - `ResultConfig::intervals_as_string` (default false) + `PostProcessOptions::intervals_as_string`. When true, the post-processor stringifies Interval / Duration columns to `Utf8`. - Disjoint with the JSON-rewrite path; fused into one per-batch walk. Renames `build_json_batch` → `build_rewritten_batch`. ### 2. PyO3 binding for both result-config knobs Exposes `complex_types_as_json` and `intervals_as_string` as kwargs on `Session(...)`. Merged into one `ResultConfig` so the toggles don't clobber each other. ### 3. Empty-result schema fix: shared type-mapper + composite parsing `extract_schema_from_manifest` was calling a local `map_databricks_type` that handled ~10 type names. DECIMAL, INTERVAL, VOID, ARRAY, MAP, STRUCT all fell through to `Utf8`. - Delete the duplicate. Route through the shared `metadata::type_mapping::databricks_type_to_arrow`. Pass `col.type_text` instead of `col.type_name` so precision/scale come through. - Parse composite type text via recursive descent. Nested shapes parse correctly; bad input falls back to `Utf8`. ### 4. TIMESTAMP is tz-aware (was reported as tz-less) Plain TIMESTAMP is logically TIMESTAMP_LTZ; the non-empty wire schema emits `Timestamp(Microsecond, Some("Etc/UTC"))`. Split the TIMESTAMP / TIMESTAMP_NTZ match arms. ### 5. `getTables`: `types=[]` returns zero rows (was: returned all) In `reshape_tables`, the `table_types` filter was treating `Some(&[])` identically to `None` ("no filter"). Thrift backend returns zero rows on an explicit empty array — the literal reading of "filter accepting nothing". Picks Thrift's reading for parity. ### 6. `getColumns`: REMARKS null → "" `reshape_columns` (and `reshape_tables`) emitted Arrow nulls for REMARKS when the server didn't supply a comment. New `utf8_column_or_empty(batch, name)` helper substitutes "" for null entries. ### 7. `getColumns`: IS_AUTO_INCREMENT defaults to "NO" Refactored `bool_string_to_yn` into a thin wrapper over `bool_string_to_yn_with_default(batch, name, default)`. Each callsite picks its null-fallback. IS_NULLABLE keeps the "" default (genuine unknown for computed columns / views). ### 8. Named-parameter binding (new) `StatementSpec.named_params` was rejected at execute time with "named parameter bindings are not supported in v0 — SEA wire format carries positional bindings only". That conclusion was sourced from the kernel's local Rust `StatementParameter` struct, which only had `ordinal`. The canonical SEA proto (`sql_exec_api_service.proto`) defines: message StatementParameter { optional int32 ordinal = 1 [(visibility) = PUBLIC_UNDOCUMENTED]; optional string name = 2 [(databricks.openapi.field).openapi_required = true]; optional string value = 3; optional string type = 4; repeated StatementParameterValueArg args = 5; } `name` is the documented public field; `ordinal` is marked `PUBLIC_UNDOCUMENTED` "for future extension to positional parameters". The kernel's local types were out of sync. - `StatementParameter` gains `name: Option<String>`; `ordinal` becomes `Option<i32>`. Both serialize with `skip_serializing_if = "Option::is_none"` so the JSON shape on the wire matches the proto: a positional param sends only `ordinal`, a named one sends only `name`. - `named_typed_value_to_sea_parameter(name, value)` helper mirrors the existing positional helper. - `Statement::execute` forwards `spec.named_params` via the new helper instead of rejecting. - PyO3 gains `Statement.bind_named_param(name, value_str, sql_type)` mirroring `bind_param`. Server side: live e2e against a real warehouse confirms named-only binding works. Mixed positional + named in one statement is rejected by the server with `INVALID_PARAMETER_MARKER_VALUE.MISSING_NAME` — bindings must be uniformly one or the other. ## Comparator outcome | | Before any kernel work | After this PR + connector #803 | |---|---|---| | **match / diff (of 132 cases)** | 60 / 88 | **97 / 34 / 1 skipped** | | Bucket A (ArrowNotImplementedError) | 32 | 0 ✅ | | `decimal_column` precision/scale | 88 (connector) | 0 ✅ | | `decimal_column` type slot (empty) | 7 | 0 ✅ | | Complex-type slots (fetchall_arrow) | 12 | 0 ✅ | | `timestamp_column` tz slot | 1 | 0 ✅ | | `getTables(types=[])` rows | 8 | 0 ✅ | | `getColumns` IS_AUTO_INCREMENT cells | 5150 | 0 ✅ | | `getColumns` REMARKS cells | 5122 | 3796 (residual real diffs) | | Bucket B1 (named params) | 1 | 0 ✅ | | Fully-clean (config × suite) pairs | 12 / 30 | 18 / 30 | Remaining diffs cluster into documented buckets — see `~/docs/python-kernel/comparator-diff-tasklist.md`. ## Test plan - [x] `cargo test --lib` — 421/421 pass (3 new tests on top of #64 baseline: named StatementParameter JSON shape, named TypedValue helper, named Binary rejection) - [x] `cargo test --test v0_execute_wiremock` — 11/11 (`execute_rejects_named_params_in_v0` flipped to `execute_sends_named_params_in_wire_form`) - [x] `cargo test --test v0_execute_e2e -- --ignored` — live against pecotesting warehouse. New: `select_with_named_params` passes, `mixed_positional_and_named_params_is_server_side_error` documents the server-side constraint. - [x] Full thrift-vs-kernel comparator (132 cases): 97 / 34 / 1 skipped — bucket B1 confirmed dropped from 1 → 0. Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
1 parent 04c8625 commit 9996717

15 files changed

Lines changed: 1225 additions & 160 deletions

File tree

‎Cargo.lock‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pyo3/src/session.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ impl Session {
8080
catalog=None,
8181
schema=None,
8282
session_conf=None,
83+
complex_types_as_json=false,
84+
intervals_as_string=false,
8385
))]
8486
#[allow(clippy::too_many_arguments)]
8587
fn new(
@@ -91,6 +93,8 @@ impl Session {
9193
catalog: Option<String>,
9294
schema: Option<String>,
9395
session_conf: Option<HashMap<String, String>>,
96+
complex_types_as_json: bool,
97+
intervals_as_string: bool,
9498
) -> PyResult<Self> {
9599
// Resolve auth_type: default to "pat" only when the caller
96100
// also passed access_token. This keeps existing PAT callers
@@ -140,6 +144,14 @@ impl Session {
140144
if let Some(conf) = session_conf {
141145
builder = builder.session_conf(conf);
142146
}
147+
// Merge result-config knobs into one `ResultConfig` so two
148+
// toggles don't clobber each other when both are set.
149+
if complex_types_as_json || intervals_as_string {
150+
let mut result = databricks_sql_kernel::ResultConfig::default();
151+
result.complex_types_as_json = complex_types_as_json;
152+
result.intervals_as_string = intervals_as_string;
153+
builder = builder.result(result);
154+
}
143155
builder.open().await
144156
})?;
145157

‎pyo3/src/statement.rs‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,10 @@ impl Statement {
8787
/// to re-encode to a kernel ``TypedValue`` would be a lossy
8888
/// round-trip; the kernel takes the string directly.
8989
///
90-
/// Named bindings, compound types (ARRAY/MAP/STRUCT), and
91-
/// BINARY are not yet supported and raise
92-
/// ``KernelError(code='InvalidArgument', ...)``. Bad value
93-
/// literals (e.g. ``bind_param(1, "abc", "INT")``) also raise
94-
/// at bind time, before ``execute()``.
90+
/// Compound types (ARRAY/MAP/STRUCT) and BINARY are not yet
91+
/// supported and raise ``KernelError(code='InvalidArgument',
92+
/// ...)``. Bad value literals (e.g. ``bind_param(1, "abc",
93+
/// "INT")``) also raise at bind time, before ``execute()``.
9594
#[pyo3(signature = (ordinal, value_str, sql_type))]
9695
fn bind_param(
9796
&mut self,
@@ -126,6 +125,32 @@ impl Statement {
126125
Ok(())
127126
}
128127

128+
/// Bind a named parameter.
129+
///
130+
/// The SQL must reference the binding as ``:name``. The canonical
131+
/// SEA proto marks ``StatementParameter.name`` as
132+
/// ``openapi_required=true``; named binding is the spec-required
133+
/// public form. ``value_str`` and ``sql_type`` follow the same
134+
/// conventions as ``bind_param``.
135+
#[pyo3(signature = (name, value_str, sql_type))]
136+
fn bind_named_param(
137+
&mut self,
138+
py: Python<'_>,
139+
name: String,
140+
value_str: Option<String>,
141+
sql_type: String,
142+
) -> PyResult<()> {
143+
let inner = alive_mut!(self, "Statement");
144+
let typed =
145+
parse_typed_value(&sql_type, value_str.as_deref()).map_err(|e| to_py_err(py, e))?;
146+
inner
147+
.stmt
148+
.spec()
149+
.param_named(name, typed)
150+
.map_err(|e| to_py_err(py, e))?;
151+
Ok(())
152+
}
153+
129154
/// Wait-for-result execution. Blocks until the kernel finishes
130155
/// polling and returns an `ExecutedStatement` with the result
131156
/// stream ready to drain.

‎src/config.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,22 @@ pub struct ResultConfig {
390390
/// ADBC and any other Arrow-native consumer should leave it
391391
/// `false`.
392392
pub complex_types_as_json: bool,
393+
394+
/// When `true`, `Interval(*)` and `Duration(*)` columns are
395+
/// replaced with `Utf8` columns containing the canonical
396+
/// Databricks text form (`"Y-M"` for YEAR-MONTH,
397+
/// `"D HH:MM:SS.nnnnnnnnn"` for DAY-TIME / durations).
398+
///
399+
/// Motivation: pyarrow's Python bindings can't decode Arrow's
400+
/// `month_interval` (id 21) — `.as_py()` / `.to_pylist()` /
401+
/// `cast(string)` / `to_pandas()` all fail with KeyError or
402+
/// `ArrowNotImplementedError`, killing the result set. Bindings
403+
/// that hand Arrow batches to pyarrow Python (the PySQL kernel
404+
/// backend) should set this `true`. Rust consumers and bindings
405+
/// with their own interval decoder can leave it `false`.
406+
///
407+
/// Default `false`.
408+
pub intervals_as_string: bool,
393409
}
394410

395411
impl Default for ResultConfig {
@@ -399,6 +415,7 @@ impl Default for ResultConfig {
399415
cloudfetch_link_prefetch_window: 10,
400416
cloudfetch_max_chunks_in_memory: 4,
401417
complex_types_as_json: false,
418+
intervals_as_string: false,
402419
}
403420
}
404421
}

0 commit comments

Comments
 (0)