diff --git a/Cargo.lock b/Cargo.lock index dfaa6003..eb20cabf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1961,9 +1961,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.150" +version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ "itoa", "memchr", diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index aaa601ec..d6708059 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -80,6 +80,8 @@ impl Session { catalog=None, schema=None, session_conf=None, + complex_types_as_json=false, + intervals_as_string=false, ))] #[allow(clippy::too_many_arguments)] fn new( @@ -91,6 +93,8 @@ impl Session { catalog: Option, schema: Option, session_conf: Option>, + complex_types_as_json: bool, + intervals_as_string: bool, ) -> PyResult { // Resolve auth_type: default to "pat" only when the caller // also passed access_token. This keeps existing PAT callers @@ -140,6 +144,14 @@ impl Session { if let Some(conf) = session_conf { builder = builder.session_conf(conf); } + // Merge result-config knobs into one `ResultConfig` so two + // toggles don't clobber each other when both are set. + if complex_types_as_json || intervals_as_string { + let mut result = databricks_sql_kernel::ResultConfig::default(); + result.complex_types_as_json = complex_types_as_json; + result.intervals_as_string = intervals_as_string; + builder = builder.result(result); + } builder.open().await })?; diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 7e293d26..89a48033 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -87,11 +87,10 @@ impl Statement { /// 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()``. + /// 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, @@ -126,6 +125,32 @@ impl Statement { Ok(()) } + /// Bind a named parameter. + /// + /// The SQL must reference the binding as ``:name``. The canonical + /// SEA proto marks ``StatementParameter.name`` as + /// ``openapi_required=true``; named binding is the spec-required + /// public form. ``value_str`` and ``sql_type`` follow the same + /// conventions as ``bind_param``. + #[pyo3(signature = (name, value_str, sql_type))] + fn bind_named_param( + &mut self, + py: Python<'_>, + name: String, + value_str: Option, + sql_type: String, + ) -> PyResult<()> { + let inner = alive_mut!(self, "Statement"); + let typed = + parse_typed_value(&sql_type, value_str.as_deref()).map_err(|e| to_py_err(py, e))?; + inner + .stmt + .spec() + .param_named(name, 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/src/config.rs b/src/config.rs index d7670592..d5ae76ca 100644 --- a/src/config.rs +++ b/src/config.rs @@ -390,6 +390,22 @@ pub struct ResultConfig { /// ADBC and any other Arrow-native consumer should leave it /// `false`. pub complex_types_as_json: bool, + + /// When `true`, `Interval(*)` and `Duration(*)` columns are + /// replaced with `Utf8` columns containing the canonical + /// Databricks text form (`"Y-M"` for YEAR-MONTH, + /// `"D HH:MM:SS.nnnnnnnnn"` for DAY-TIME / durations). + /// + /// Motivation: pyarrow's Python bindings can't decode Arrow's + /// `month_interval` (id 21) — `.as_py()` / `.to_pylist()` / + /// `cast(string)` / `to_pandas()` all fail with KeyError or + /// `ArrowNotImplementedError`, killing the result set. Bindings + /// that hand Arrow batches to pyarrow Python (the PySQL kernel + /// backend) should set this `true`. Rust consumers and bindings + /// with their own interval decoder can leave it `false`. + /// + /// Default `false`. + pub intervals_as_string: bool, } impl Default for ResultConfig { @@ -399,6 +415,7 @@ impl Default for ResultConfig { cloudfetch_link_prefetch_window: 10, cloudfetch_max_chunks_in_memory: 4, complex_types_as_json: false, + intervals_as_string: false, } } } diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index 7723ee36..54612343 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -214,6 +214,41 @@ fn utf8_column(batch: &RecordBatch, name: &str) -> Result { } } +/// Like `utf8_column`, but substitutes `""` for null entries instead +/// of preserving them as Arrow nulls. Used for JDBC string fields +/// where the spec allows null but downstream consumers (Java +/// `String`-handling code, SQLAlchemy reflection, etc.) routinely +/// crash on null and the Thrift backend has historically returned +/// `""` for the same fields. Today only `REMARKS`. +fn utf8_column_or_empty(batch: &RecordBatch, name: &str) -> Result { + let n = batch.num_rows(); + let Some(idx) = column_index(batch.schema_ref(), name) else { + return Ok(Arc::new(StringArray::from(vec![Some(""); n]))); + }; + let col = batch.column(idx); + let casted = if col.data_type() == &DataType::Utf8 { + Arc::clone(col) + } else { + arrow_cast::cast(col.as_ref(), &DataType::Utf8).map_err(|e| { + Error::data_loss().message(format!( + "unexpected non-Utf8 type for SHOW response column {name:?}: {e}" + )) + })? + }; + let strs = casted + .as_any() + .downcast_ref::() + .ok_or_else(|| { + Error::data_loss().message(format!( + "utf8_column_or_empty: column {name:?} cast did not yield StringArray" + )) + })?; + let values: Vec<&str> = (0..n) + .map(|i| if strs.is_null(i) { "" } else { strs.value(i) }) + .collect(); + Ok(Arc::new(StringArray::from(values))) +} + /// Build an all-null `Utf8` column of `len` rows. Used for JDBC columns /// that have no server-side source (`TYPE_CAT`, `SELF_REFERENCING_COL_NAME`, /// `COLUMN_DEF`, …). @@ -268,15 +303,28 @@ fn null_int8(len: usize) -> ArrayRef { } /// Map a server-side `"true"` / `"false"` string column to JDBC's -/// `"YES"` / `"NO"` / `""` convention. Used for `IS_NULLABLE` and -/// `IS_AUTO_INCREMENT` in `reshape_columns`; both follow the same -/// rule (JDBC defines an empty string when the value is "unknown", -/// which we use for null / unrecognised inputs). Missing source -/// column → all-empty string array. +/// `"YES"` / `"NO"` / `""` convention. Used for `IS_NULLABLE` — +/// when the server doesn't give a definitive boolean we fall back +/// to `""` (JDBC's "unknown" sentinel). For `IS_AUTO_INCREMENT` use +/// [`bool_string_to_yn_with_default`] with `"NO"` instead, since +/// Databricks tables don't support auto-increment and "unknown" is +/// strictly less informative than the known-correct answer. fn bool_string_to_yn(batch: &RecordBatch, name: &str) -> Result { + bool_string_to_yn_with_default(batch, name, "") +} + +/// Variant of [`bool_string_to_yn`] where the caller picks the fallback +/// value used when the server returns null, a non-`"true"`/`"false"` +/// string, or omits the source column entirely. Server-provided +/// `"true"` / `"false"` always win. +fn bool_string_to_yn_with_default( + batch: &RecordBatch, + name: &str, + default: &str, +) -> Result { let n = batch.num_rows(); let Some(idx) = column_index(batch.schema_ref(), name) else { - return Ok(Arc::new(StringArray::from(vec![Some(""); n]))); + return Ok(Arc::new(StringArray::from(vec![Some(default); n]))); }; let arr = batch.column(idx); let strs = arrow_cast::cast(arr.as_ref(), &DataType::Utf8).map_err(|e| { @@ -290,12 +338,12 @@ fn bool_string_to_yn(batch: &RecordBatch, name: &str) -> Result { let labels: Vec<&str> = (0..n) .map(|i| { if strs.is_null(i) { - "" + default } else { match strs.value(i) { "true" => "YES", "false" => "NO", - _ => "", + _ => default, } } }) @@ -367,11 +415,12 @@ pub(crate) fn reshape_tables( // driver's behaviour when SHOW TABLES doesn't expose tableType. Arc::new(StringArray::from(vec![Some("TABLE"); n])) }; - let remarks = if column_index(batch.schema_ref(), "remarks").is_some() { - utf8_column(batch, "remarks")? - } else { - Arc::new(StringArray::from(vec![Some(""); n])) - }; + // REMARKS is contractually nullable per the JDBC spec, but the Thrift + // backend has historically emitted `""` for tables without a comment + // and most string-handling consumers expect a `String`, not `null`. + // `utf8_column_or_empty` covers both branches: column present with + // null entries → `""`; column absent → all `""`. + let remarks = utf8_column_or_empty(batch, "remarks")?; let reshaped = RecordBatch::try_new( GET_TABLES_SCHEMA.clone(), vec![ @@ -389,12 +438,21 @@ pub(crate) fn reshape_tables( ) .map_err(|e| Error::data_loss().message(format!("reshape tables: {e}")))?; - // Apply table_types filter, if requested. JDBC's contract: - // null/empty = no filter; otherwise keep only rows whose - // TABLE_TYPE is in the list. + // Apply table_types filter, if requested. The JDBC `DatabaseMetaData. + // getTables(...)` Javadoc specifies that `null` types returns all + // types, but is silent on what an *explicit empty array* means. + // Two interpretations exist in the wild: + // - Empty == null (returns all rows). Convenient, but conflates + // "I didn't filter" with "I asked for nothing". + // - Empty == "filter accepting nothing" (returns zero rows). Literal + // reading of the filter contract. + // The Databricks Thrift backend follows the literal reading: zero + // rows on `types=[]`. We match Thrift here for cross-backend parity + // (verified via the python-comparator). Callers that want "all + // types" should pass `None`, not `Some(&[])`. let filtered = match table_types { - Some(types) if !types.is_empty() => filter_tables_by_type(&reshaped, types)?, - _ => reshaped, + None => reshaped, + Some(types) => filter_tables_by_type(&reshaped, types)?, }; // Sort to match the JDBC driver's `getTables` row order // (`TABLE_TYPE, TABLE_CAT, TABLE_SCHEM, TABLE_NAME`). JDBC's @@ -529,12 +587,23 @@ pub(crate) fn reshape_columns( } None => Arc::new(Int32Array::from(vec![2_i32; n])), }; - let remarks = utf8_column(batch, "remarks")?; + // REMARKS: JDBC allows null, but the Thrift backend has historically + // returned "" and string-handling consumers expect a `String`. Map + // null → "" at the kernel layer. + let remarks = utf8_column_or_empty(batch, "remarks")?; let ordinal_position = int32_column(batch, "ordinalPosition")?; - // IS_NULLABLE / IS_AUTO_INCREMENT: server emits "true"/"false"; - // JDBC contract is "YES"/"NO"/"" (empty for unknown). + // IS_NULLABLE: server emits "true"/"false"; JDBC contract is + // "YES"/"NO"/"" (empty when unknown). The "unknown" sentinel is + // appropriate here — the server doesn't always know nullability for + // computed columns / views. let is_nullable_str = bool_string_to_yn(batch, "isNullable")?; - let is_autoincrement = bool_string_to_yn(batch, "isAutoIncrement")?; + // IS_AUTO_INCREMENT: Databricks tables don't support auto-increment + // columns, so when the server omits this field (or returns null / + // an unrecognised value) the correct JDBC answer is "NO", not the + // "unknown" sentinel "". Server-provided "true" / "false" still + // wins — if Databricks ever ships identity columns, this honours + // them. Code comment + grep makes the assumption findable. + let is_autoincrement = bool_string_to_yn_with_default(batch, "isAutoIncrement", "NO")?; RecordBatch::try_new( GET_COLUMNS_SCHEMA.clone(), @@ -824,9 +893,23 @@ mod tests { } #[test] - fn tables_empty_types_filter_passes_everything() { + fn tables_empty_types_filter_returns_zero_rows() { + // Matches Thrift's behavior: explicit `Some(&[])` is a filter + // that accepts no table types, so the result is empty. + // `None` (caller didn't pass a type filter at all) is the + // separate "all types" path — see `tables_none_types_passes_all`. let b = server_tables_full(); let out = reshape_tables(&b, Some("main"), Some(&[])).unwrap(); + assert_eq!(out.num_rows(), 0); + } + + #[test] + fn tables_none_types_passes_all() { + // The all-types path — distinct from the explicit-empty path + // above. Locks the contract so future refactors don't quietly + // re-merge the two. + let b = server_tables_full(); + let out = reshape_tables(&b, Some("main"), None).unwrap(); assert_eq!(out.num_rows(), 3); } @@ -933,4 +1016,115 @@ mod tests { assert_eq!(is_nullable.value(0), "NO"); assert_eq!(is_nullable.value(1), "YES"); } + + #[test] + fn columns_remarks_null_becomes_empty_string() { + // `server_columns_full` builds REMARKS as `[None, None]`. After + // reshape, both rows must be `""` (not null), matching Thrift's + // historical behaviour and downstream consumers that expect a + // `String`. REMARKS is JDBC column index 11. + let b = server_columns_full(); + let out = reshape_columns(&b, Some("main")).unwrap(); + let remarks = out + .column(11) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(!remarks.is_null(0), "REMARKS row 0 should be '', not null"); + assert!(!remarks.is_null(1), "REMARKS row 1 should be '', not null"); + assert_eq!(remarks.value(0), ""); + assert_eq!(remarks.value(1), ""); + } + + #[test] + fn columns_is_auto_increment_defaults_to_no() { + // Databricks doesn't support auto-increment, so when the server + // returns "false" (or omits the column entirely) the JDBC value + // is "NO". IS_AUTO_INCREMENT is JDBC column index 22. + let b = server_columns_full(); + let out = reshape_columns(&b, Some("main")).unwrap(); + let is_ai = out + .column(22) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(is_ai.value(0), "NO"); + assert_eq!(is_ai.value(1), "NO"); + } + + #[test] + fn columns_is_auto_increment_honors_server_true() { + // The `"NO"` default in `bool_string_to_yn_with_default` is a + // fallback for the server-silent case; if Databricks ever ships + // identity columns and the server emits `"true"`, the kernel + // honours it. Synthetic input with explicit `"true"` values. + let schema = Arc::new(Schema::new(vec![ + Field::new("col_name", DataType::Utf8, false), + Field::new("catalogName", DataType::Utf8, false), + Field::new("namespace", DataType::Utf8, false), + Field::new("tableName", DataType::Utf8, false), + Field::new("columnType", DataType::Utf8, false), + Field::new("isNullable", DataType::Utf8, true), + Field::new("ordinalPosition", DataType::Int32, true), + Field::new("isAutoIncrement", DataType::Utf8, true), + ])); + let b = RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec!["id"])), + Arc::new(StringArray::from(vec!["main"])), + Arc::new(StringArray::from(vec!["s"])), + Arc::new(StringArray::from(vec!["t"])), + Arc::new(StringArray::from(vec!["INT"])), + Arc::new(StringArray::from(vec![Some("false")])), + Arc::new(Int32Array::from(vec![Some(1)])), + Arc::new(StringArray::from(vec![Some("true")])), + ], + ) + .unwrap(); + let out = reshape_columns(&b, Some("main")).unwrap(); + let is_ai = out + .column(22) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(is_ai.value(0), "YES"); + } + + #[test] + fn columns_is_auto_increment_no_when_column_missing() { + // If the server doesn't include `isAutoIncrement` at all (e.g. + // an older DBR's SHOW COLUMNS variant), the kernel still returns + // "NO" rather than "" — same domain reasoning. + let schema = Arc::new(Schema::new(vec![ + Field::new("col_name", DataType::Utf8, false), + Field::new("catalogName", DataType::Utf8, false), + Field::new("namespace", DataType::Utf8, false), + Field::new("tableName", DataType::Utf8, false), + Field::new("columnType", DataType::Utf8, false), + Field::new("isNullable", DataType::Utf8, true), + Field::new("ordinalPosition", DataType::Int32, true), + // isAutoIncrement intentionally absent + ])); + let b = RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec!["id"])), + Arc::new(StringArray::from(vec!["main"])), + Arc::new(StringArray::from(vec!["s"])), + Arc::new(StringArray::from(vec!["t"])), + Arc::new(StringArray::from(vec!["INT"])), + Arc::new(StringArray::from(vec![Some("false")])), + Arc::new(Int32Array::from(vec![Some(1)])), + ], + ) + .unwrap(); + let out = reshape_columns(&b, Some("main")).unwrap(); + let is_ai = out + .column(22) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(is_ai.value(0), "NO"); + } } diff --git a/src/metadata/type_mapping.rs b/src/metadata/type_mapping.rs index a8d73347..487fdae2 100644 --- a/src/metadata/type_mapping.rs +++ b/src/metadata/type_mapping.rs @@ -23,14 +23,89 @@ //! //! When adding a new type, update **both** mapping functions. -use arrow_schema::{DataType, IntervalUnit, TimeUnit}; +use arrow_schema::{DataType, Field, Fields, IntervalUnit, TimeUnit}; +use std::sync::Arc; -/// Map Databricks SQL type name to Arrow DataType. -pub fn databricks_type_to_arrow(type_name: &str) -> DataType { - let type_upper = type_name.to_uppercase(); - let base_type = type_upper.split('(').next().unwrap_or(&type_upper).trim(); +/// Map a Databricks SQL type spec to an Arrow `DataType`. +/// +/// Accepts both bare names (e.g. `"INT"`) and full type-text shapes +/// emitted by SEA's `ColumnInfo.type_text` (e.g. `"DECIMAL(10,2)"`, +/// `"ARRAY"`, `"MAP"`, `"STRUCT"`). +/// The latter is the form the kernel uses to synthesise an Arrow schema +/// for empty-result responses where no Arrow IPC payload is available +/// — see `reader::ResultReaderFactory::extract_schema_from_manifest`. +/// +/// Unrecognised input falls back to `DataType::Utf8` rather than +/// panicking; the kernel always returns *some* schema even when the +/// type is unknown. +pub fn databricks_type_to_arrow(type_text: &str) -> DataType { + databricks_type_to_arrow_with_interval(type_text, None) +} - match base_type { +/// Like [`databricks_type_to_arrow`] but accepts the manifest's +/// `type_interval_type` hint (`"YEAR_MONTH"` / `"DAY_TIME"`) to +/// disambiguate the Arrow `IntervalUnit`. Use this when calling +/// from the SEA manifest path; the hint resolves the YEAR-MONTH +/// vs DAY-TIME distinction that the wire payload otherwise encodes. +/// +/// Caller passes `type_interval_type` from `ColumnInfo`; absent +/// callers (the public `databricks_type_to_arrow`) pass `None` and +/// the parser falls back to the `type_text` itself, which for +/// real SEA columns is `"INTERVAL YEAR TO MONTH"` / +/// `"INTERVAL DAY TO SECOND"`. +pub fn databricks_type_to_arrow_with_interval( + type_text: &str, + type_interval_type: Option<&str>, +) -> DataType { + parse_type(type_text, type_interval_type, 0).unwrap_or(DataType::Utf8) +} + +/// Maximum depth of nested composite types we'll parse before +/// falling back to `Utf8`. `type_text` is server-controlled input; +/// without a guard a deeply-nested ARRAY/MAP/STRUCT could +/// stack-overflow the kernel. 64 is well past any real-world type. +const MAX_PARSE_DEPTH: usize = 64; + +/// Recursive entry point. Returns `None` only when parsing genuinely +/// fails (malformed composite text); callers convert that to +/// `DataType::Utf8` at the top level so the public function never +/// returns `None`. +/// +/// `type_interval_type` is propagated through recursive calls but +/// only consulted at the `INTERVAL` arm — it has no meaning for +/// nested composites, so passing it down is harmless and lets the +/// caller specify it once. +fn parse_type( + s: &str, + type_interval_type: Option<&str>, + depth: usize, +) -> Option { + if depth >= MAX_PARSE_DEPTH { + return None; + } + let trimmed = s.trim(); + if trimmed.is_empty() { + return None; + } + // Split base name from the parameter / composite tail. The base + // ends at the first of: + // - `<` (composite: ARRAY, MAP, STRUCT) + // - `(` (parameterised primitive: DECIMAL(p,s)) + // - whitespace (qualified primitive: + // "INTERVAL YEAR TO MONTH", "INTERVAL DAY TO SECOND" — + // the canonical SEA `type_text` for INTERVAL columns) + // Whichever appears first wins. + let split_at = trimmed + .char_indices() + .find(|(_, c)| matches!(c, '<' | '(' | ' ' | '\t')) + .map(|(i, _)| i); + let base = match split_at { + Some(i) => trimmed[..i].trim(), + None => trimmed, + }; + let base_upper = base.to_uppercase(); + + Some(match base_upper.as_str() { "BOOLEAN" | "BOOL" => DataType::Boolean, "TINYINT" | "BYTE" => DataType::Int8, "SMALLINT" | "SHORT" => DataType::Int16, @@ -39,21 +114,176 @@ pub fn databricks_type_to_arrow(type_name: &str) -> DataType { "FLOAT" | "REAL" => DataType::Float32, "DOUBLE" => DataType::Float64, "DECIMAL" | "DEC" | "NUMERIC" => { - let (precision, scale) = parse_decimal_params(type_name); + let (precision, scale) = parse_decimal_params(trimmed); DataType::Decimal128(precision, scale) } "STRING" | "VARCHAR" | "CHAR" | "TEXT" => DataType::Utf8, "BINARY" | "VARBINARY" => DataType::Binary, "DATE" => DataType::Date32, - "TIMESTAMP" | "TIMESTAMP_NTZ" => DataType::Timestamp(TimeUnit::Microsecond, None), - "TIMESTAMP_LTZ" => DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())), - "INTERVAL" => DataType::Interval(IntervalUnit::DayTime), - "ARRAY" => DataType::Utf8, // Represented as JSON string - "MAP" => DataType::Utf8, // Represented as JSON string - "STRUCT" => DataType::Utf8, // Represented as JSON string + // Databricks `TIMESTAMP` is tz-aware (logically `TIMESTAMP_LTZ`). + // The non-empty wire schema (Arrow IPC from SEA) reports + // `Timestamp(Microsecond, Some("Etc/UTC"))` for plain TIMESTAMP + // columns; matching that here keeps the empty-result schema in + // sync. `TIMESTAMP_NTZ` is the only no-timezone variant. + "TIMESTAMP" | "TIMESTAMP_LTZ" => { + DataType::Timestamp(TimeUnit::Microsecond, Some("Etc/UTC".into())) + } + "TIMESTAMP_NTZ" => DataType::Timestamp(TimeUnit::Microsecond, None), + "INTERVAL" => DataType::Interval(resolve_interval_unit(trimmed, type_interval_type)), + "ARRAY" => parse_array(trimmed, type_interval_type, depth)?, + "MAP" => parse_map(trimmed, type_interval_type, depth)?, + "STRUCT" => parse_struct(trimmed, type_interval_type, depth)?, "VOID" | "NULL" => DataType::Null, - _ => DataType::Utf8, // Default fallback + _ => DataType::Utf8, + }) +} + +/// Pick the Arrow `IntervalUnit` for an INTERVAL column. Prefers +/// the manifest's `type_interval_type` (canonical) and falls back +/// to keyword-matching the `type_text` ("YEAR" / "MONTH" → YearMonth; +/// anything else → DayTime). Bare `"INTERVAL"` with no qualifier +/// keeps the historical DayTime default. +fn resolve_interval_unit(type_text: &str, type_interval_type: Option<&str>) -> IntervalUnit { + if let Some(hint) = type_interval_type { + let h = hint.to_uppercase(); + if h.contains("YEAR") || h.contains("MONTH") { + return IntervalUnit::YearMonth; + } + if h.contains("DAY") || h.contains("HOUR") || h.contains("MINUTE") || h.contains("SECOND") { + return IntervalUnit::DayTime; + } + } + // Fall back to type_text keywords. "INTERVAL YEAR TO MONTH" / + // "INTERVAL DAY TO SECOND" are the canonical SEA forms. + let up = type_text.to_uppercase(); + if up.contains("YEAR") || up.contains("MONTH") { + IntervalUnit::YearMonth + } else { + IntervalUnit::DayTime + } +} + +/// Slice out the content between the outer `<...>` of a composite type +/// spec. Returns `None` if the brackets are missing or unbalanced. +fn inside_angle_brackets(s: &str) -> Option<&str> { + let start = s.find('<')?; + // Walk from the end to find the matching close — composite values + // can nest, but the kernel's input is single-rooted so the outermost + // `<...>` is everything from the first `<` to the last `>`. + let end = s.rfind('>')?; + if end <= start { + return None; + } + Some(s[start + 1..end].trim()) +} + +/// Split a comma-separated list at depth-0 commas. `STRUCT,b:INT>` +/// has two top-level fields, not three; the inner `MAP` comma must +/// not split. +fn split_top_level_commas(s: &str) -> Vec<&str> { + let mut parts: Vec<&str> = Vec::new(); + let mut depth: i32 = 0; + let mut last = 0; + for (i, ch) in s.char_indices() { + match ch { + '<' | '(' => depth += 1, + '>' | ')' => depth -= 1, + ',' if depth == 0 => { + parts.push(s[last..i].trim()); + last = i + 1; + } + _ => {} + } + } + parts.push(s[last..].trim()); + parts +} + +/// Parse `ARRAY` into a `List(Field("item", inner, true))`. +/// Field name `"item"` matches arrow-rs's canonical default +/// (`Field::new_list_field`) and every other call site in this +/// kernel (`reader/post_processor/`). pyarrow's +/// `list_(t)` default also uses `"item"`. Using anything else would +/// make the empty-result schema fail field-level equality against +/// the non-empty Arrow IPC payload. +fn parse_array( + s: &str, + type_interval_type: Option<&str>, + depth: usize, +) -> Option { + let inner = inside_angle_brackets(s)?; + let inner_dt = parse_type(inner, type_interval_type, depth + 1)?; + Some(DataType::List(Arc::new(Field::new_list_field( + inner_dt, true, + )))) +} + +/// Parse `MAP` into Arrow's canonical `Map(entries: Struct{key, value})`. +/// Field names `"entries"` / `"key"` / `"value"` match pyarrow.map_(k, v). +fn parse_map( + s: &str, + type_interval_type: Option<&str>, + depth: usize, +) -> Option { + let inner = inside_angle_brackets(s)?; + let parts = split_top_level_commas(inner); + if parts.len() != 2 { + return None; + } + let key_dt = parse_type(parts[0], type_interval_type, depth + 1)?; + let val_dt = parse_type(parts[1], type_interval_type, depth + 1)?; + let entries = Field::new( + "entries", + DataType::Struct(Fields::from(vec![ + Field::new("key", key_dt, false), + Field::new("value", val_dt, true), + ])), + false, + ); + Some(DataType::Map(Arc::new(entries), false)) +} + +/// Parse `STRUCT` into `Struct(Fields::from([Field; N]))`. +/// Each child field is nullable (SEA's manifest doesn't carry per-field +/// nullability) — same convention used elsewhere in the kernel. +fn parse_struct( + s: &str, + type_interval_type: Option<&str>, + depth: usize, +) -> Option { + let inner = inside_angle_brackets(s)?; + if inner.is_empty() { + return Some(DataType::Struct(Fields::empty())); + } + let mut fields: Vec = Vec::new(); + for part in split_top_level_commas(inner) { + // `name:type` — split on the first colon at depth 0. Names are + // unquoted identifiers; types may contain colons inside + // composites (none today, but be defensive). + let colon_idx = depth_zero_colon(part)?; + let name = part[..colon_idx].trim(); + let type_text = part[colon_idx + 1..].trim(); + if name.is_empty() { + return None; + } + let dt = parse_type(type_text, type_interval_type, depth + 1)?; + fields.push(Field::new(name, dt, true)); + } + Some(DataType::Struct(Fields::from(fields))) +} + +/// Find the first `:` at angle/paren depth 0 in a STRUCT field text. +fn depth_zero_colon(s: &str) -> Option { + let mut depth: i32 = 0; + for (i, ch) in s.char_indices() { + match ch { + '<' | '(' => depth += 1, + '>' | ')' => depth -= 1, + ':' if depth == 0 => return Some(i), + _ => {} + } } + None } /// Map Arrow DataType to Databricks SQL type name. @@ -142,6 +372,13 @@ fn parse_decimal_params(type_name: &str) -> (u8, i8) { .and_then(|s| s.parse::().ok()) .unwrap_or(default_scale); + // Clamp to legal `Decimal128` range. Arrow requires precision in + // [1, 38] and scale in [-38, 38]; pathological server input + // (`DECIMAL(0, 0)`, `DECIMAL(99, 50)`) would otherwise produce an + // invalid Arrow type that panics in downstream array builders. + let precision = precision.clamp(1, 38); + let scale = scale.clamp(-38, 38); + (precision, scale) } @@ -173,17 +410,23 @@ mod tests { #[test] fn test_databricks_type_to_arrow_timestamps() { + // Plain TIMESTAMP is tz-aware in Databricks (logical + // TIMESTAMP_LTZ); matches what the non-empty wire path emits + // via Arrow IPC. The tz string is "Etc/UTC" to match what SEA + // produces — not bare "UTC" — so empty-result and non-empty + // schemas are byte-equal. assert_eq!( databricks_type_to_arrow("TIMESTAMP"), - DataType::Timestamp(TimeUnit::Microsecond, None) + DataType::Timestamp(TimeUnit::Microsecond, Some("Etc/UTC".into())) ); assert_eq!( - databricks_type_to_arrow("TIMESTAMP_NTZ"), - DataType::Timestamp(TimeUnit::Microsecond, None) + databricks_type_to_arrow("TIMESTAMP_LTZ"), + DataType::Timestamp(TimeUnit::Microsecond, Some("Etc/UTC".into())) ); + // TIMESTAMP_NTZ is the only no-timezone variant. assert_eq!( - databricks_type_to_arrow("TIMESTAMP_LTZ"), - DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())) + databricks_type_to_arrow("TIMESTAMP_NTZ"), + DataType::Timestamp(TimeUnit::Microsecond, None) ); } @@ -209,12 +452,167 @@ mod tests { #[test] fn test_databricks_type_to_arrow_complex() { - // Complex types represented as JSON strings + // Bare composite names (no `<...>` payload) fall back to Utf8. + // This is the legacy behavior for callers that pass only + // ColumnInfo.type_name; the structured composite shape only + // arrives via type_text and gets parsed below. assert_eq!(databricks_type_to_arrow("ARRAY"), DataType::Utf8); assert_eq!(databricks_type_to_arrow("MAP"), DataType::Utf8); assert_eq!(databricks_type_to_arrow("STRUCT"), DataType::Utf8); } + #[test] + fn test_databricks_type_to_arrow_array_nested() { + // ARRAY → List. Field name is "item" — the + // arrow-rs canonical default; matches the non-empty wire + // payload and every other call site in this kernel. + assert_eq!( + databricks_type_to_arrow("ARRAY"), + DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))) + ); + // ARRAY + assert_eq!( + databricks_type_to_arrow("ARRAY"), + DataType::List(Arc::new(Field::new_list_field(DataType::Utf8, true))) + ); + // Nested: ARRAY> + assert_eq!( + databricks_type_to_arrow("ARRAY>"), + DataType::List(Arc::new(Field::new_list_field( + DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))), + true, + ))) + ); + } + + #[test] + fn test_array_field_name_is_item_not_element() { + // Lock in the field-name convention. The non-empty-result + // schema (wire payload) uses "item"; if this regresses, + // empty-result and non-empty-result schemas stop being + // field-equal — directly defeats the empty-result schema-fix + // goal of bucket A/E in the comparator parity tasklist. + let dt = databricks_type_to_arrow("ARRAY"); + let DataType::List(field) = dt else { + panic!("expected List, got {dt:?}"); + }; + assert_eq!(field.name(), "item", "list field name must be 'item'"); + } + + #[test] + fn test_databricks_type_to_arrow_map() { + // MAP → Map + let dt = databricks_type_to_arrow("MAP"); + match dt { + DataType::Map(entries, sorted) => { + assert!(!sorted); + assert_eq!(entries.name(), "entries"); + let DataType::Struct(fields) = entries.data_type() else { + panic!("expected Struct inside Map"); + }; + assert_eq!(fields.len(), 2); + assert_eq!(fields[0].name(), "key"); + assert_eq!(fields[0].data_type(), &DataType::Utf8); + assert!(!fields[0].is_nullable()); + assert_eq!(fields[1].name(), "value"); + assert_eq!(fields[1].data_type(), &DataType::Int32); + assert!(fields[1].is_nullable()); + } + other => panic!("expected Map, got {other:?}"), + } + } + + #[test] + fn test_databricks_type_to_arrow_map_nested() { + // MAP> — top-level comma split must + // ignore inner commas. Asserts the comma-depth tracking in + // `split_top_level_commas` works. + let dt = databricks_type_to_arrow("MAP>"); + let DataType::Map(entries, _) = dt else { + panic!("expected Map"); + }; + let DataType::Struct(fields) = entries.data_type() else { + panic!("expected Struct"); + }; + // The value field is itself a Map. + let DataType::Map(_, _) = fields[1].data_type() else { + panic!("expected inner Map"); + }; + } + + #[test] + fn test_databricks_type_to_arrow_struct() { + // STRUCT + let dt = databricks_type_to_arrow("STRUCT"); + let DataType::Struct(fields) = dt else { + panic!("expected Struct"); + }; + assert_eq!(fields.len(), 2); + assert_eq!(fields[0].name(), "x"); + assert_eq!(fields[0].data_type(), &DataType::Int32); + assert!(fields[0].is_nullable()); + assert_eq!(fields[1].name(), "y"); + assert_eq!(fields[1].data_type(), &DataType::Utf8); + } + + #[test] + fn test_databricks_type_to_arrow_struct_whitespace_and_complex_fields() { + // Whitespace tolerance + a STRUCT field whose type is itself a + // composite. Confirms `depth_zero_colon` doesn't trip on inner + // colons (there aren't any today, but be defensive) and that + // whitespace inside <...> is trimmed. + let dt = databricks_type_to_arrow("STRUCT< a : ARRAY , b : MAP >"); + let DataType::Struct(fields) = dt else { + panic!("expected Struct"); + }; + assert_eq!(fields.len(), 2); + assert_eq!(fields[0].name(), "a"); + assert!(matches!(fields[0].data_type(), DataType::List(_))); + assert_eq!(fields[1].name(), "b"); + assert!(matches!(fields[1].data_type(), DataType::Map(_, _))); + } + + #[test] + fn test_databricks_type_to_arrow_array_of_struct() { + // ARRAY> — mirrors the corpus + // `array_of_structs_column`. Asserts the kernel produces the + // same nested Arrow type the connector and Thrift use. + let dt = databricks_type_to_arrow("ARRAY>"); + let DataType::List(field) = dt else { + panic!("expected List"); + }; + let DataType::Struct(fields) = field.data_type() else { + panic!("expected Struct inside List"); + }; + assert_eq!(fields.len(), 2); + assert_eq!(fields[0].name(), "x"); + assert_eq!(fields[1].name(), "y"); + } + + #[test] + fn test_databricks_type_to_arrow_struct_with_decimal_field() { + // STRUCT — confirms the parser correctly + // delegates back to the DECIMAL handler when a struct field's + // type carries parameters. + let dt = databricks_type_to_arrow("STRUCT"); + let DataType::Struct(fields) = dt else { + panic!("expected Struct"); + }; + assert_eq!(fields[0].data_type(), &DataType::Decimal128(10, 2)); + } + + #[test] + fn test_databricks_type_to_arrow_malformed_falls_back_to_utf8() { + // Unbalanced or partial composite text falls back to Utf8 rather + // than panicking — the kernel must always produce *some* schema. + assert_eq!(databricks_type_to_arrow("ARRAY<"), DataType::Utf8); + assert_eq!(databricks_type_to_arrow("MAP"), DataType::Utf8); + assert_eq!( + databricks_type_to_arrow("STRUCT"), + DataType::Utf8 + ); + } + #[test] fn test_databricks_type_to_arrow_special() { assert_eq!(databricks_type_to_arrow("VOID"), DataType::Null); @@ -309,4 +707,99 @@ mod tests { assert_eq!(arrow_type_to_databricks(&DataType::UInt32), "BIGINT"); assert_eq!(arrow_type_to_databricks(&DataType::UInt64), "BIGINT"); } + + // ── INTERVAL type_text + type_interval_type plumbing ────────────── + + #[test] + fn test_interval_real_wire_strings_resolve_to_correct_unit() { + // Production SEA `type_text` is `"INTERVAL YEAR TO MONTH"` / + // `"INTERVAL DAY TO SECOND"`. The parser must split on + // whitespace to find the `INTERVAL` base. + assert_eq!( + databricks_type_to_arrow("INTERVAL YEAR TO MONTH"), + DataType::Interval(IntervalUnit::YearMonth) + ); + assert_eq!( + databricks_type_to_arrow("INTERVAL DAY TO SECOND"), + DataType::Interval(IntervalUnit::DayTime) + ); + // Other DAY-TIME variants. + assert_eq!( + databricks_type_to_arrow("INTERVAL HOUR TO MINUTE"), + DataType::Interval(IntervalUnit::DayTime) + ); + assert_eq!( + databricks_type_to_arrow("INTERVAL MINUTE TO SECOND"), + DataType::Interval(IntervalUnit::DayTime) + ); + } + + #[test] + fn test_interval_type_interval_type_hint_wins() { + // `type_interval_type` from the manifest is canonical and + // overrides any keyword guessing from `type_text`. Mismatch is + // hypothetical (server is consistent in practice), but the + // hint precedence is the contract. + assert_eq!( + databricks_type_to_arrow_with_interval("INTERVAL", Some("YEAR_MONTH")), + DataType::Interval(IntervalUnit::YearMonth) + ); + assert_eq!( + databricks_type_to_arrow_with_interval("INTERVAL", Some("DAY_TIME")), + DataType::Interval(IntervalUnit::DayTime) + ); + // Hint substring matching tolerates the qualifier-style form + // (`"YEAR TO MONTH"`, `"DAY TO SECOND"`) too. + assert_eq!( + databricks_type_to_arrow_with_interval("INTERVAL", Some("YEAR TO MONTH")), + DataType::Interval(IntervalUnit::YearMonth) + ); + } + + #[test] + fn test_interval_bare_falls_back_to_day_time() { + // Backward-compat: bare `"INTERVAL"` with no hint and no + // qualifier maps to DayTime (the historical default). + assert_eq!( + databricks_type_to_arrow("INTERVAL"), + DataType::Interval(IntervalUnit::DayTime) + ); + } + + // ── parse_type depth guard + DECIMAL clamps ────────────────────── + + #[test] + fn test_parse_type_deeply_nested_falls_back_to_utf8() { + // Server-controlled `type_text` could nest arbitrarily; + // without a depth guard the recursive parser would blow the + // stack. 64 levels of nesting is well past anything real. + let deep = "ARRAY<".repeat(MAX_PARSE_DEPTH + 1) + + "INT" + + &">".repeat(MAX_PARSE_DEPTH + 1); + assert_eq!(databricks_type_to_arrow(&deep), DataType::Utf8); + } + + #[test] + fn test_decimal_clamps_invalid_precision_scale() { + // `Decimal128` requires precision in [1, 38] and scale in + // [-38, 38]. Pathological server input (DECIMAL(0,0), + // DECIMAL(99,50)) would otherwise produce an invalid Arrow + // type that panics later. Clamp to legal range. + let dt = databricks_type_to_arrow("DECIMAL(0,0)"); + match dt { + DataType::Decimal128(p, s) => { + assert!(p >= 1, "precision must clamp to >= 1, got {p}"); + assert!((-38..=38).contains(&s), "scale must be in [-38,38], got {s}"); + } + other => panic!("expected Decimal128, got {other:?}"), + } + let dt = databricks_type_to_arrow("DECIMAL(99,50)"); + match dt { + DataType::Decimal128(p, s) => { + assert!(p <= 38, "precision must clamp to <= 38, got {p}"); + assert!(s <= 38, "scale must clamp to <= 38, got {s}"); + } + other => panic!("expected Decimal128, got {other:?}"), + } + } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 46ff0e41..0a9f7e5e 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -36,7 +36,7 @@ use crate::types::cloudfetch::{CloudFetchConfig, CloudFetchLink}; use crate::types::sea::{CompressionCodec, ResultManifest, StatementState}; use crate::util::runtime::block_on_in_runtime; use arrow_array::RecordBatch; -use arrow_schema::{ArrowError, DataType, Field, Schema, SchemaRef}; +use arrow_schema::{ArrowError, Field, Schema, SchemaRef}; use std::sync::Arc; pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader; @@ -195,7 +195,7 @@ impl ResultReaderFactory { "Using empty reader: no result data present for {:?} statement", response.status.state ); - let schema = self.extract_schema_from_manifest(response.manifest.as_ref())?; + let schema = Self::extract_schema_from_manifest(response.manifest.as_ref())?; Ok(Box::new(EmptyReader::new(schema))) } StatementState::Pending | StatementState::Running => Err(Error::invalid_state() @@ -216,7 +216,7 @@ impl ResultReaderFactory { /// Extract Arrow schema from the result manifest. /// /// Falls back to an empty schema if no manifest is available. - fn extract_schema_from_manifest(&self, manifest: Option<&ResultManifest>) -> Result { + fn extract_schema_from_manifest(manifest: Option<&ResultManifest>) -> Result { let Some(manifest) = manifest else { tracing::warn!("No manifest available for empty result set, using empty schema"); return Ok(Arc::new(Schema::empty())); @@ -227,7 +227,27 @@ impl ResultReaderFactory { .columns .iter() .map(|col| { - let data_type = Self::map_databricks_type(&col.type_name); + // Pass `type_text` (e.g. `"DECIMAL(10,2)"` or + // `"INTERVAL YEAR TO MONTH"`) rather than `type_name` + // (e.g. `"DECIMAL"` or `"INTERVAL"`) so the shared mapper + // can recover precision/scale / interval qualifier. The + // non-empty result path uses the Arrow schema embedded in + // the wire payload (which already encodes these); only + // this empty-result path has to reconstruct the Arrow type + // from the manifest, and reconstructing without those + // produces wrong defaults that diverge from the Thrift + // backend's wire schema for the same query. + // + // `type_interval_type` (`"YEAR_MONTH"` / `"DAY_TIME"`) is + // the canonical hint for INTERVAL columns; passing it + // through lets the mapper choose + // `IntervalUnit::YearMonth` vs `IntervalUnit::DayTime` + // without re-parsing the `type_text`. + let data_type = + crate::metadata::type_mapping::databricks_type_to_arrow_with_interval( + &col.type_text, + col.type_interval_type.as_deref(), + ); Field::new(&col.name, data_type, true) // nullable by default }) .collect(); @@ -235,32 +255,6 @@ impl ResultReaderFactory { Ok(Arc::new(Schema::new(fields))) } - /// Map Databricks SQL type names to Arrow DataTypes. - fn map_databricks_type(type_name: &str) -> DataType { - // Databricks type names from the API - match type_name.to_uppercase().as_str() { - "BOOLEAN" => DataType::Boolean, - "BYTE" | "TINYINT" => DataType::Int8, - "SHORT" | "SMALLINT" => DataType::Int16, - "INT" | "INTEGER" => DataType::Int32, - "LONG" | "BIGINT" => DataType::Int64, - "FLOAT" | "REAL" => DataType::Float32, - "DOUBLE" => DataType::Float64, - "STRING" => DataType::Utf8, - "BINARY" => DataType::Binary, - "DATE" => DataType::Date32, - "TIMESTAMP" | "TIMESTAMP_NTZ" => { - DataType::Timestamp(arrow_schema::TimeUnit::Microsecond, None) - } - // For complex types and unknown types, fall back to string - // The actual Arrow IPC data will have the correct type - _ => { - tracing::debug!("Unknown Databricks type '{}', mapping to Utf8", type_name); - DataType::Utf8 - } - } - } - fn create_cloudfetch_reader( &self, statement_id: &str, @@ -580,6 +574,7 @@ mod tests { use crate::reader::test_utils::{ErrorReader, MockReader, SchemaErrorReader}; use crate::types::sea::{ColumnInfo, ResultManifest, ResultSchema}; use arrow_array::StringArray; + use arrow_schema::DataType; fn make_test_batch(values: Vec<&str>) -> RecordBatch { let schema = Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, false)])); @@ -668,34 +663,146 @@ mod tests { } #[test] - fn test_map_databricks_types() { - assert_eq!( - ResultReaderFactory::map_databricks_type("BOOLEAN"), - DataType::Boolean - ); + fn test_extract_schema_from_manifest_primitives() { + // The simple-primitive cases the previous private mapper covered. + // Verifies the shared `databricks_type_to_arrow` still produces + // the same Arrow types for these so behaviour didn't regress when + // the duplicate was removed. + let manifest = make_manifest(vec![ + make_column_info("a", "BOOLEAN", "BOOLEAN", 0, None, None, None), + make_column_info("b", "INT", "INT", 1, None, None, None), + make_column_info("c", "BIGINT", "BIGINT", 2, None, None, None), + make_column_info("d", "STRING", "STRING", 3, None, None, None), + make_column_info("e", "DOUBLE", "DOUBLE", 4, None, None, None), + ]); + let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap(); + assert_eq!(schema.field(0).data_type(), &DataType::Boolean); + assert_eq!(schema.field(1).data_type(), &DataType::Int32); + assert_eq!(schema.field(2).data_type(), &DataType::Int64); + assert_eq!(schema.field(3).data_type(), &DataType::Utf8); + assert_eq!(schema.field(4).data_type(), &DataType::Float64); + } + + #[test] + fn test_extract_schema_from_manifest_decimal_carries_precision_scale() { + // Regression test for the comparator bucket-C cause #1: + // empty-result schema for a DECIMAL column was previously + // `Utf8` (because the local mapper fell through to the catch-all + // and ignored type_text/type_precision/type_scale), producing + // a divergence vs Thrift's `Decimal128(p, s)`. + let manifest = make_manifest(vec![make_column_info( + "decimal_column", + "DECIMAL", + "DECIMAL(10,2)", + 0, + Some(10), + Some(2), + None, + )]); + let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap(); + assert_eq!(schema.field(0).data_type(), &DataType::Decimal128(10, 2)); + } + + #[test] + fn test_extract_schema_from_manifest_interval_void() { + // INTERVAL and VOID were both falling through to Utf8 in the + // previous private mapper — bucket-C cause #1 sub-cases. + // + // Canonical SEA `type_text` for INTERVAL columns is + // `"INTERVAL YEAR TO MONTH"` / `"INTERVAL DAY TO SECOND"` — + // the parser must split on whitespace to recognise the + // `INTERVAL` base. `type_interval_type` (`"YEAR_MONTH"` / + // `"DAY_TIME"`) is the canonical disambiguator and is + // preferred over the keyword-match fallback. + let manifest = make_manifest(vec![ + make_column_info( + "ym", + "INTERVAL", + "INTERVAL YEAR TO MONTH", + 0, + None, + None, + Some("YEAR_MONTH"), + ), + make_column_info( + "ds", + "INTERVAL", + "INTERVAL DAY TO SECOND", + 1, + None, + None, + Some("DAY_TIME"), + ), + make_column_info("v", "VOID", "VOID", 2, None, None, None), + ]); + let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap(); assert_eq!( - ResultReaderFactory::map_databricks_type("INT"), - DataType::Int32 + schema.field(0).data_type(), + &DataType::Interval(arrow_schema::IntervalUnit::YearMonth), + "INTERVAL YEAR TO MONTH must map to IntervalUnit::YearMonth" ); assert_eq!( - ResultReaderFactory::map_databricks_type("BIGINT"), - DataType::Int64 + schema.field(1).data_type(), + &DataType::Interval(arrow_schema::IntervalUnit::DayTime), + "INTERVAL DAY TO SECOND must map to IntervalUnit::DayTime" ); + // VOID must surface as `Null`, not as Utf8 — Thrift's surface for + // a `CAST(NULL AS VOID)` column carries a null type. + assert_eq!(schema.field(2).data_type(), &DataType::Null); + } + + #[test] + fn test_extract_schema_from_manifest_interval_keyword_fallback() { + // When `type_interval_type` is absent, the mapper falls back to + // keyword-matching the `type_text`. Bare `"INTERVAL"` (no + // qualifier) historically meant DAY_TIME; preserve that. + let manifest = make_manifest(vec![ + make_column_info("ym", "INTERVAL", "INTERVAL YEAR TO MONTH", 0, None, None, None), + make_column_info("ds", "INTERVAL", "INTERVAL DAY TO SECOND", 1, None, None, None), + make_column_info("bare", "INTERVAL", "INTERVAL", 2, None, None, None), + ]); + let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap(); assert_eq!( - ResultReaderFactory::map_databricks_type("STRING"), - DataType::Utf8 + schema.field(0).data_type(), + &DataType::Interval(arrow_schema::IntervalUnit::YearMonth) ); assert_eq!( - ResultReaderFactory::map_databricks_type("DOUBLE"), - DataType::Float64 + schema.field(1).data_type(), + &DataType::Interval(arrow_schema::IntervalUnit::DayTime) ); - // Unknown types fall back to Utf8 assert_eq!( - ResultReaderFactory::map_databricks_type("UNKNOWN_TYPE"), - DataType::Utf8 + schema.field(2).data_type(), + &DataType::Interval(arrow_schema::IntervalUnit::DayTime) ); } + #[test] + fn test_extract_schema_from_manifest_complex_types_parse_into_nested_arrow() { + // ARRAY / MAP / STRUCT carry their structure in the manifest's + // `type_text` field; the empty-result schema now reconstructs the + // matching nested Arrow type so the empty-result path agrees + // with the non-empty wire-payload schema. The actual parsing + // lives in `metadata::type_mapping::databricks_type_to_arrow`; + // this asserts the factory plumbs `type_text` through correctly. + let manifest = make_manifest(vec![ + make_column_info("a", "ARRAY", "ARRAY", 0, None, None, None), + make_column_info("m", "MAP", "MAP", 1, None, None, None), + make_column_info("s", "STRUCT", "STRUCT", 2, None, None, None), + ]); + let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap(); + assert!(matches!(schema.field(0).data_type(), DataType::List(_))); + assert!(matches!(schema.field(1).data_type(), DataType::Map(_, _))); + assert!(matches!(schema.field(2).data_type(), DataType::Struct(_))); + } + + #[test] + fn test_extract_schema_from_manifest_no_manifest_returns_empty() { + // Pre-existing fallback path: no manifest at all → empty schema, + // no warning, no panic. Lock in. + let schema = ResultReaderFactory::extract_schema_from_manifest(None).unwrap(); + assert_eq!(schema.fields().len(), 0); + } + // --- Schema augmentation tests --- fn make_manifest(columns: Vec) -> ResultManifest { diff --git a/src/reader/post_processor/json.rs b/src/reader/post_processor/json.rs index 49dbf373..9a3e7415 100644 --- a/src/reader/post_processor/json.rs +++ b/src/reader/post_processor/json.rs @@ -470,7 +470,7 @@ fn base64_encode(bytes: &[u8]) -> String { base64::engine::general_purpose::STANDARD.encode(bytes) } -fn format_interval(array: &dyn Array, index: usize) -> Result { +pub(super) fn format_interval(array: &dyn Array, index: usize) -> Result { match array.data_type() { DataType::Interval(arrow_schema::IntervalUnit::YearMonth) => { let months = array.as_primitive::().value(index); @@ -529,7 +529,7 @@ fn format_day_time_interval(days: i64, nanos: i64) -> String { format!("{sign}{d} {h:02}:{m:02}:{s:02}.{nanos_rem:09}") } -fn format_duration(array: &dyn Array, index: usize) -> Result { +pub(super) fn format_duration(array: &dyn Array, index: usize) -> Result { let nanos: i128 = match array.data_type() { DataType::Duration(TimeUnit::Second) => { (array.as_primitive::().value(index) as i128) * 1_000_000_000 diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 93af0e73..33bea3ac 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -51,6 +51,18 @@ pub(crate) struct PostProcessOptions { /// columns containing compact JSON text per row. See /// [`ResultConfig::complex_types_as_json`](crate::config::ResultConfig::complex_types_as_json). pub complex_types_as_json: bool, + /// When `true`, `Interval(*)` and `Duration(*)` columns are + /// replaced with `Utf8` columns containing the canonical + /// Databricks text form (e.g. `"2-6"` for YEAR-MONTH, + /// `"3 12:30:15.000000000"` for DAY-TIME). + /// + /// Motivation: pyarrow's Python bindings can't decode Arrow's + /// `month_interval` type (id 21) at all — `.as_py()` / `.to_pylist()` / + /// `cast(string)` / `to_pandas()` all fail. The Python connector + /// requests this flag so interval results are usable from + /// Python; non-Python consumers can leave it `false` if they + /// have a working interval decoder. + pub intervals_as_string: bool, } /// Wrapper that runs all per-batch post-processing the kernel does @@ -97,23 +109,36 @@ impl ResultPostProcessor { None => inner_schema.clone(), }; - // 2. JSON-stringification rewrite: identify complex columns - // in the augmented schema and turn them into nullable Utf8 - // while preserving the Databricks metadata. + // 2. Compute the set of column indices that need stringification. + // JSON-rewrite covers complex types; interval-rewrite covers + // `Interval(*)` and `Duration(*)`. Each is gated by its own + // option; both produce a `Utf8` output column. The two sets + // are disjoint by construction (`is_complex_type` returns + // false for interval/duration), so a column is rewritten by + // at most one transform. let mut json_columns: Vec = Vec::new(); - let output_schema: SchemaRef = if options.complex_types_as_json { - let mut new_fields: Vec = Vec::with_capacity(augmented_schema.fields().len()); - for (i, field) in augmented_schema.fields().iter().enumerate() { - if json::is_complex_type(field.data_type()) { - json_columns.push(i); - let metadata = field.metadata().clone(); - new_fields.push( - Field::new(field.name(), DataType::Utf8, true).with_metadata(metadata), - ); - } else { - new_fields.push(field.as_ref().clone()); - } + let mut interval_columns: Vec = Vec::new(); + let mut new_fields: Vec = Vec::with_capacity(augmented_schema.fields().len()); + let mut schema_changed = false; + for (i, field) in augmented_schema.fields().iter().enumerate() { + let dt = field.data_type(); + if options.complex_types_as_json && json::is_complex_type(dt) { + json_columns.push(i); + let metadata = field.metadata().clone(); + new_fields + .push(Field::new(field.name(), DataType::Utf8, true).with_metadata(metadata)); + schema_changed = true; + } else if options.intervals_as_string && is_interval_or_duration_type(dt) { + interval_columns.push(i); + let metadata = field.metadata().clone(); + new_fields + .push(Field::new(field.name(), DataType::Utf8, true).with_metadata(metadata)); + schema_changed = true; + } else { + new_fields.push(field.as_ref().clone()); } + } + let output_schema: SchemaRef = if schema_changed { Arc::new(Schema::new_with_metadata( new_fields, augmented_schema.metadata().clone(), @@ -126,18 +151,20 @@ impl ResultPostProcessor { // // Cases: // - `inner_schema == output_schema` (Arc-eq or - // structurally identical): no work needed. + // structurally identical) and no column rewrites: no work + // needed. // - Output schema differs only in field metadata (manifest - // augmentation, no JSON rewrite): a single + // augmentation, no column rewrites): a single // `RecordBatch::try_new` re-project onto the augmented // schema. - // - JSON columns present: fused walk that re-projects - // primitives and emits new Utf8 arrays for complex + // - Any rewrites present: fused walk that re-projects + // primitives and emits new Utf8 arrays for the rewritten // columns. let needs_rebuild = !schemas_field_equal(&inner_schema, &output_schema); - let transform: Option = if !needs_rebuild && json_columns.is_empty() { + let has_rewrites = !json_columns.is_empty() || !interval_columns.is_empty(); + let transform: Option = if !needs_rebuild && !has_rewrites { None - } else if json_columns.is_empty() { + } else if !has_rewrites { // Manifest-only path: cheap re-project. Reuses upstream // ArrayRefs unchanged. let target_schema = output_schema.clone(); @@ -151,13 +178,21 @@ impl ResultPostProcessor { })) } else { // Fused walk: re-project primitives, stringify complex - // columns. Captures only what each closure invocation - // actually needs. + // columns (JSON path), stringify intervals/durations + // (interval path). Captures only what each closure + // invocation actually needs. let target_schema = output_schema.clone(); let augmented = augmented_schema.clone(); let json_cols: Vec = json_columns; + let interval_cols: Vec = interval_columns; Some(Box::new(move |batch: &RecordBatch| { - build_json_batch(batch, &augmented, &target_schema, &json_cols) + build_rewritten_batch( + batch, + &augmented, + &target_schema, + &json_cols, + &interval_cols, + ) })) }; @@ -204,23 +239,35 @@ fn schemas_field_equal(a: &SchemaRef, b: &SchemaRef) -> bool { } /// Build a `RecordBatch` whose primitive columns are reprojected -/// from `batch` and whose complex columns (indexed by `json_cols`) -/// are replaced with `Utf8` arrays of compact JSON text. -fn build_json_batch( +/// from `batch`, complex columns (indexed by `json_cols`) are replaced +/// with `Utf8` arrays of compact JSON text, and interval / duration +/// columns (indexed by `interval_cols`) are replaced with `Utf8` +/// arrays of canonical Databricks interval text. +/// +/// `json_cols` and `interval_cols` are assumed to be sorted in +/// ascending order (the constructor walks the schema linearly) and +/// disjoint (`is_complex_type` returns false for intervals). +fn build_rewritten_batch( batch: &RecordBatch, augmented: &SchemaRef, output: &SchemaRef, json_cols: &[usize], + interval_cols: &[usize], ) -> Result { let num_rows = batch.num_rows(); let mut columns: Vec = Vec::with_capacity(batch.num_columns()); let mut next_json_idx = 0; + let mut next_interval_idx = 0; for (col_idx, column) in batch.columns().iter().enumerate() { let is_json = json_cols .get(next_json_idx) .copied() .is_some_and(|target| target == col_idx); + let is_interval = interval_cols + .get(next_interval_idx) + .copied() + .is_some_and(|target| target == col_idx); if is_json { next_json_idx += 1; // Use the augmented field (carries databricks.* metadata) @@ -248,6 +295,27 @@ fn build_json_batch( builder.append_value(&scratch); } columns.push(Arc::new(builder.finish())); + } else if is_interval { + next_interval_idx += 1; + let mut builder = StringBuilder::with_capacity(num_rows, num_rows * 16); + let dt = column.data_type(); + for row in 0..num_rows { + if column.is_null(row) { + builder.append_null(); + continue; + } + let s = match dt { + DataType::Interval(_) => json::format_interval(column.as_ref(), row)?, + DataType::Duration(_) => json::format_duration(column.as_ref(), row)?, + other => { + return Err(Error::internal().message(format!( + "intervals_as_string: column {col_idx} expected Interval/Duration, got {other:?}" + ))); + } + }; + builder.append_value(&s); + } + columns.push(Arc::new(builder.finish())); } else { columns.push(column.clone()); } @@ -255,11 +323,17 @@ fn build_json_batch( RecordBatch::try_new(output.clone(), columns).map_err(|e| { Error::internal().message(format!( - "ResultPostProcessor: failed to assemble JSON-rewritten batch: {e}" + "ResultPostProcessor: failed to assemble rewritten batch: {e}" )) }) } +/// True iff `dt` is an Arrow `Interval(*)` or `Duration(*)` — the +/// types the `intervals_as_string` post-processor stringifies. +fn is_interval_or_duration_type(dt: &DataType) -> bool { + matches!(dt, DataType::Interval(_) | DataType::Duration(_)) +} + #[cfg(test)] mod tests { use super::*; @@ -372,6 +446,7 @@ mod tests { let opts = PostProcessOptions { complex_types_as_json: true, + ..Default::default() }; let mut pp = ResultPostProcessor::new(inner, None, opts).unwrap(); @@ -415,6 +490,7 @@ mod tests { let opts = PostProcessOptions { complex_types_as_json: true, + ..Default::default() }; let mut pp = ResultPostProcessor::new(inner, None, opts).unwrap(); let out_batch = pp.next_batch().unwrap().unwrap(); @@ -452,6 +528,7 @@ mod tests { let opts = PostProcessOptions { complex_types_as_json: true, + ..Default::default() }; let mut pp = ResultPostProcessor::new(inner, None, opts).unwrap(); let out = pp.next_batch().unwrap().unwrap(); @@ -478,6 +555,7 @@ mod tests { let opts = PostProcessOptions { complex_types_as_json: true, + ..Default::default() }; let mut pp = ResultPostProcessor::new(inner, None, opts).unwrap(); let out = pp.next_batch().unwrap().unwrap(); diff --git a/src/session.rs b/src/session.rs index 95aa51da..113eb180 100644 --- a/src/session.rs +++ b/src/session.rs @@ -585,6 +585,7 @@ fn result_to_post_process_options( ) -> crate::reader::post_processor::PostProcessOptions { crate::reader::post_processor::PostProcessOptions { complex_types_as_json: result.complex_types_as_json, + intervals_as_string: result.intervals_as_string, } } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 46b8bb13..1f38ae32 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -58,7 +58,7 @@ use crate::result_stream::ResultStream; use crate::session::SessionInner; use crate::statement::executed::ExecutedStatement; use crate::statement::executed_async::ExecutedAsyncStatement; -use crate::statement::params::typed_value_to_sea_parameter; +use crate::statement::params::{named_typed_value_to_sea_parameter, typed_value_to_sea_parameter}; use crate::statement::spec::{ResultFormat, StatementSpec}; use crate::statement::validity::ValidityFlag; use crate::types::sea::{ExecuteParams, StatementState}; @@ -284,13 +284,6 @@ impl Statement { if self.spec.result_format != ResultFormat::Arrow { return Err(Error::invalid_argument().message("v0 supports ResultFormat::Arrow only")); } - if !self.spec.named_params.is_empty() { - return Err(Error::invalid_argument().message( - "named parameter bindings are not supported in v0 — SEA wire format \ - carries positional bindings only", - )); - } - // `wait_timeout = None` means "omit the field"; the server // applies its default (~10s wait + auto-close on success). // `on_wait_timeout` only matters when wait_timeout is set, @@ -305,6 +298,11 @@ impl Statement { .parameters .push(typed_value_to_sea_parameter((i + 1) as i32, value)?); } + for (name, value) in self.spec.named_params.iter() { + exec_params + .parameters + .push(named_typed_value_to_sea_parameter(name.clone(), value)?); + } Ok((sql, exec_params)) } diff --git a/src/statement/params.rs b/src/statement/params.rs index ed0c223c..1063ae81 100644 --- a/src/statement/params.rs +++ b/src/statement/params.rs @@ -186,7 +186,8 @@ pub fn record_batch_to_sea_parameters(batch: &RecordBatch) -> Result Result { let payload = typed_value_to_sea_payload(value)?; Ok(StatementParameter { - ordinal, + name: None, + ordinal: Some(ordinal), param_type: payload.type_name, value: payload.value, }) } -// Note: SEA's `StatementParameter` is positional-only today -// (`ordinal` + `type` + `value`; no `name` field on the wire). Named -// parameter bindings on `StatementSpec.named_params` aren't supported -// at the wire layer yet — `Statement::execute` returns -// `InvalidArgument` if any are present. Tracked as a §7 follow-up -// pending SEA wire support for named bindings. +/// Convert a named [`TypedValue`] binding to a SEA +/// [`StatementParameter`]. The canonical SEA proto marks +/// `StatementParameter.name` as `openapi_required=true` — named +/// binding is the spec-required public form; positional is +/// `PUBLIC_UNDOCUMENTED`. Returns `Err(InvalidArgument)` for variants +/// the SEA wire protocol does not accept (today: `Binary`). +pub(crate) fn named_typed_value_to_sea_parameter( + name: impl Into, + value: &TypedValue, +) -> Result { + let payload = typed_value_to_sea_payload(value)?; + Ok(StatementParameter { + name: Some(name.into()), + ordinal: None, + param_type: payload.type_name, + value: payload.value, + }) +} // --------------------------------------------------------------------------- // DESCRIBE QUERY result → Arrow Schema @@ -641,7 +655,7 @@ mod tests { )]); let params = record_batch_to_sea_parameters(&batch).unwrap(); assert_eq!(params.len(), 1); - assert_eq!(params[0].ordinal, 1); + assert_eq!(params[0].ordinal, Some(1)); assert_eq!(params[0].param_type, "INT"); assert_eq!(params[0].value, Some("42".to_string())); } @@ -686,11 +700,11 @@ mod tests { ]); let params = record_batch_to_sea_parameters(&batch).unwrap(); assert_eq!(params.len(), 3); - assert_eq!(params[0].ordinal, 1); + assert_eq!(params[0].ordinal, Some(1)); assert_eq!(params[0].param_type, "INT"); - assert_eq!(params[1].ordinal, 2); + assert_eq!(params[1].ordinal, Some(2)); assert_eq!(params[1].param_type, "STRING"); - assert_eq!(params[2].ordinal, 3); + assert_eq!(params[2].ordinal, Some(3)); assert_eq!(params[2].param_type, "DOUBLE"); } @@ -783,12 +797,14 @@ mod tests { fn test_statement_parameter_serialization() { let params = vec![ StatementParameter { - ordinal: 1, + name: None, + ordinal: Some(1), param_type: "INT".to_string(), value: Some("100".to_string()), }, StatementParameter { - ordinal: 2, + name: None, + ordinal: Some(2), param_type: "STRING".to_string(), value: None, }, @@ -799,6 +815,29 @@ mod tests { assert!(json.contains(r#""type":"INT""#)); assert!(json.contains(r#""value":"100""#)); assert!(json.contains(r#""value":null"#)); + // Positional params must not emit a `name` field — the + // canonical SEA proto distinguishes named vs positional by + // which field is set. + assert!(!json.contains(r#""name""#), "json={json}"); + } + + #[test] + fn test_named_statement_parameter_serialization() { + // Named binding is the spec-required public form (canonical + // proto marks `name` as openapi_required=true). When `name` + // is set, `ordinal` must be omitted from the wire payload. + let params = vec![StatementParameter { + name: Some("n".to_string()), + ordinal: None, + param_type: "INT".to_string(), + value: Some("42".to_string()), + }]; + + let json = serde_json::to_string(¶ms).unwrap(); + assert!(json.contains(r#""name":"n""#), "json={json}"); + assert!(json.contains(r#""type":"INT""#)); + assert!(json.contains(r#""value":"42""#)); + assert!(!json.contains(r#""ordinal""#), "json={json}"); } // ─── TypedValue → SEA tests ───────────────────────────────────── @@ -806,7 +845,8 @@ mod tests { #[test] fn typed_value_null_emits_string_type_with_no_value() { let p = typed_value_to_sea_parameter(1, &TypedValue::Null).unwrap(); - assert_eq!(p.ordinal, 1); + assert_eq!(p.ordinal, Some(1)); + assert_eq!(p.name, None); assert_eq!(p.param_type, "STRING"); assert_eq!(p.value, None); } @@ -830,7 +870,7 @@ mod tests { ]; for (v, expect_type, expect_value) in cases { let p = typed_value_to_sea_parameter(7, &v).unwrap(); - assert_eq!(p.ordinal, 7); + assert_eq!(p.ordinal, Some(7)); assert_eq!(p.param_type, expect_type, "type for {v:?}"); assert_eq!(p.value.as_deref(), Some(expect_value), "value for {v:?}"); } @@ -862,6 +902,24 @@ mod tests { assert!(err.message.contains("unhex"), "{}", err.message); } + #[test] + fn named_typed_value_sets_name_and_clears_ordinal() { + let p = named_typed_value_to_sea_parameter("n", &TypedValue::Int32(42)).unwrap(); + assert_eq!(p.name.as_deref(), Some("n")); + assert_eq!(p.ordinal, None); + assert_eq!(p.param_type, "INT"); + assert_eq!(p.value.as_deref(), Some("42")); + } + + #[test] + fn named_typed_value_binary_is_rejected() { + use crate::kernel_error::ErrorCode; + let err = named_typed_value_to_sea_parameter("b", &TypedValue::Binary(vec![0xCA, 0xFE])) + .unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!(err.message.contains("unhex"), "{}", err.message); + } + #[test] fn typed_value_decimal_emits_value_string_with_precision_scale() { // Precision and scale must be in the type name; otherwise diff --git a/src/types/sea.rs b/src/types/sea.rs index 912e4665..294113e9 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -172,11 +172,22 @@ pub struct ExternalLink { pub next_chunk_index: Option, } -/// A positional parameter for a parameterized SEA statement execution. +/// A bound parameter for a parameterized SEA statement execution. +/// +/// Exactly one of `name` or `ordinal` should be set. `name` is the +/// public, spec-required binding form (canonical proto marks +/// `StatementParameter.name` as `openapi_required=true`); `ordinal` +/// is the `PUBLIC_UNDOCUMENTED` positional form. Server accepts both. #[derive(Debug, Clone, Serialize)] pub struct StatementParameter { - /// 1-based position of the parameter in the SQL statement. - pub ordinal: i32, + /// Named parameter identifier. When `Some`, the SQL uses + /// `:name`-style markers and `ordinal` should be `None`. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// 1-based position of the parameter in the SQL statement. When + /// `Some`, the SQL uses `?` markers and `name` should be `None`. + #[serde(skip_serializing_if = "Option::is_none")] + pub ordinal: Option, /// Databricks SQL type name (e.g., "INT", "STRING", "DOUBLE", "TIMESTAMP"). #[serde(rename = "type")] pub param_type: String, diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 6b77283c..e0b138a8 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -100,6 +100,71 @@ async fn select_with_positional_params() { session.close().await.expect("session close"); } +#[tokio::test] +#[ignore] +async fn select_with_named_params() { + // Named binding is the spec-required public form per the canonical + // SEA proto (`StatementParameter.name` is openapi_required=true). + // This proves the server accepts named bindings when the kernel + // populates `name` instead of `ordinal` on the wire. + let session = live_session().await; + let mut stmt = session.statement(); + stmt.spec() + .sql("SELECT :n AS n, :s AS s, :b AS b") + .param_named("n", TypedValue::Int64(42)) + .unwrap() + .param_named("s", TypedValue::String("hello".into())) + .unwrap() + .param_named("b", TypedValue::Bool(true)) + .unwrap(); + let mut exec = stmt.execute().await.expect("execute with named params"); + + let stream = exec.result_stream_mut(); + stream.next_batch().await.unwrap().unwrap(); + let row = stream.next_row_in_batch().expect("one row"); + assert_eq!(row.get_i64(0).unwrap(), Some(42)); + assert_eq!(row.get_str(1).unwrap(), Some("hello")); + assert_eq!(row.get_bool(2).unwrap(), Some(true)); + exec.close().await.expect("close"); + session.close().await.expect("session close"); +} + +#[tokio::test] +#[ignore] +async fn mixed_positional_and_named_params_is_server_side_error() { + // The kernel can serialise mixed positional + named bindings in + // the same `parameters` array — but the server rejects with + // `INVALID_PARAMETER_MARKER_VALUE.MISSING_NAME` when any + // parameter has a `name` set and another doesn't. This test + // documents the server contract: bindings must be uniformly + // positional or uniformly named. + let session = live_session().await; + let mut stmt = session.statement(); + stmt.spec() + .sql("SELECT ? AS pos, :n AS named") + .param(1, TypedValue::Int64(7)) + .unwrap() + .param_named("n", TypedValue::Int64(99)) + .unwrap(); + let err = stmt + .execute() + .await + .err() + .expect("server should reject mixed bindings"); + // Surfaced as DataLoss because the FAILED response is parsed via + // the generic execute-response path and the kernel's error + // classifier hasn't decoded BAD_REQUEST → InvalidArgument here. + // The important assertion is the BAD_REQUEST / MISSING_NAME + // text — the kernel correctly forwarded the mixed payload and + // surfaced the server-side rejection without losing context. + let msg = err.message; + assert!( + msg.contains("MISSING_NAME") || msg.contains("BAD_REQUEST"), + "expected MISSING_NAME / BAD_REQUEST in error, got: {msg}" + ); + session.close().await.expect("session close"); +} + #[tokio::test] #[ignore] async fn multi_batch_range_succeeds() { diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 39de5ec2..f7f3aec9 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -302,10 +302,18 @@ async fn execute_validates_missing_sql() { } #[tokio::test] -async fn execute_rejects_named_params_in_v0() { +async fn execute_sends_named_params_in_wire_form() { + // Named binding is the spec-required public form (canonical SEA + // proto marks `StatementParameter.name` as openapi_required=true). + // The kernel must forward `StatementSpec.named_params` to the + // SEA `parameters` array with `name` set and `ordinal` omitted. let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = str_batch("v", vec!["bound"]); + mount_execute(&server, succeeded_inline_body("stmt-named", &batch)).await; let session = open_session(&server).await; let mut stmt = session.statement(); @@ -313,12 +321,10 @@ async fn execute_rejects_named_params_in_v0() { .sql("SELECT :x") .param_named("x", TypedValue::Int64(1)) .expect("param_named"); - let err = match stmt.execute().await { - Ok(_) => panic!("named params not yet wired on the wire"), - Err(e) => e, - }; - assert_eq!(err.code, ErrorCode::InvalidArgument); - assert!(err.message.contains("named"), "{}", err.message); + let mut exec = stmt.execute().await.expect("execute with named params"); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches[0].num_rows(), 1); + exec.close().await.expect("close"); } #[tokio::test]