diff --git a/src/metadata/type_mapping.rs b/src/metadata/type_mapping.rs index 75dfb619..e3396fab 100644 --- a/src/metadata/type_mapping.rs +++ b/src/metadata/type_mapping.rs @@ -202,7 +202,14 @@ fn parse_type(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option "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, + // Untyped NULL (`SELECT NULL` / VOID) maps to `Utf8`, not + // `DataType::Null`: the server reports it as STRING (and the + // Thrift / JDBC reference exposes it as STRING), so an + // empty-result VOID column reports the same type as a + // `CAST(NULL AS STRING)` sibling — consistent with the live-data + // path, which coerces the Arrow `Null` column to `Utf8` in the + // result post-processor. See issue #203 (DATATYPE-041). + "VOID" | "NULL" => DataType::Utf8, _ => DataType::Utf8, }) } @@ -449,6 +456,14 @@ pub fn databricks_type_to_xdbc(type_name: &str) -> i16 { // splitter doesn't cut on whitespace) and fall through to // `JDBC_OTHER`, matching Thrift's behaviour for those. "INTERVAL" => JDBC_VARCHAR, + // ── Untyped NULL / VOID ────────────────────────────────── + // The server reports untyped NULL (`SELECT NULL`) as STRING and + // the JDBC reference maps a NULL-named column to `Types.VARCHAR` + // (DatabricksTypeUtil: `case NULL: return Types.VARCHAR`), so + // report VARCHAR rather than the `JDBC_OTHER` sentinel — keeping + // this surface consistent with the Arrow type (`Utf8`). See + // issue #203 (DATATYPE-041). + "VOID" | "NULL" => JDBC_VARCHAR, // ── Unknown ────────────────────────────────────────────── // `JDBC_OTHER` (1111) is the JDBC sentinel "I don't know what // this is". Earlier kernel versions returned `VARCHAR` here @@ -726,8 +741,11 @@ mod tests { #[test] fn test_databricks_type_to_arrow_special() { - assert_eq!(databricks_type_to_arrow("VOID"), DataType::Null); - assert_eq!(databricks_type_to_arrow("NULL"), DataType::Null); + // Untyped NULL / VOID surfaces as the server-reported STRING + // (`Utf8`), matching a `CAST(NULL AS STRING)` sibling and the + // Thrift / JDBC reference — see issue #203 (DATATYPE-041). + assert_eq!(databricks_type_to_arrow("VOID"), DataType::Utf8); + assert_eq!(databricks_type_to_arrow("NULL"), DataType::Utf8); assert_eq!( databricks_type_to_arrow("INTERVAL"), DataType::Interval(IntervalUnit::DayTime) @@ -840,6 +858,15 @@ mod tests { ); } + #[test] + fn test_databricks_type_to_xdbc_void_null_is_varchar() { + // Untyped NULL / VOID reports VARCHAR (12), matching the server's + // STRING type and the JDBC reference (`case NULL: Types.VARCHAR`) + // — not the `JDBC_OTHER` sentinel. Issue #203 (DATATYPE-041). + assert_eq!(databricks_type_to_xdbc("VOID"), JDBC_VARCHAR); + assert_eq!(databricks_type_to_xdbc("NULL"), JDBC_VARCHAR); + } + #[test] fn test_databricks_type_to_xdbc_unknown_falls_back_to_other() { // The default arm now returns `JDBC_OTHER` (1111). Prior diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 706c3d04..b8fe9b19 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1056,9 +1056,10 @@ mod tests { &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); + // VOID surfaces as `Utf8` — the server reports untyped NULL / VOID + // as STRING, so an empty-result VOID column reports the same type + // as a `CAST(NULL AS STRING)` sibling (issue #203, DATATYPE-041). + assert_eq!(schema.field(2).data_type(), &DataType::Utf8); } #[test] diff --git a/src/reader/post_processor/json.rs b/src/reader/post_processor/json.rs index 9a3e7415..50387b54 100644 --- a/src/reader/post_processor/json.rs +++ b/src/reader/post_processor/json.rs @@ -163,25 +163,21 @@ pub(crate) fn append_json( .value_as_datetime(index), }; let dt = dt.unwrap_or(chrono::DateTime::UNIX_EPOCH.naive_utc()); - // Render at the Arrow column's native subsecond precision - // so we don't silently truncate microseconds/nanoseconds — - // matches JDBC's `DatabricksArray.toString()` chain, which - // honours the underlying type's precision. + // A TIMESTAMP leaf read through the text surface must be + // spelled as the session-timezone wall clock, exactly like + // a top-level TIMESTAMP-to-text (conformance case + // COMPLEX-016): a space separator (no 'T'), no 'Z'/offset + // suffix, and trailing-zero fractional seconds stripped — + // whole seconds carry no fraction at all + // (`2025-01-24 07:07:41`), a fractional value keeps only its + // significant digits (`2024-01-15 12:30:45.123456`). // - // TIMESTAMP carries a tz on the Arrow side; TIMESTAMP_NTZ - // does not. Match Thrift: tz'd → trailing 'Z', NTZ → no - // offset suffix. - let base = match unit { - TimeUnit::Second => dt.format("%Y-%m-%dT%H:%M:%S").to_string(), - TimeUnit::Millisecond => dt.format("%Y-%m-%dT%H:%M:%S%.3f").to_string(), - TimeUnit::Microsecond => dt.format("%Y-%m-%dT%H:%M:%S%.6f").to_string(), - TimeUnit::Nanosecond => dt.format("%Y-%m-%dT%H:%M:%S%.9f").to_string(), - }; - let s = if tz.is_some() { - format!("{base}Z") - } else { - base - }; + // chrono's `%.f` already omits the point for a zero + // fraction and trims trailing zeros otherwise, which is + // precisely the wall-clock spelling; the Arrow `tz` is not + // rendered (the instant is already the wall clock). + let _ = tz; + let s = dt.format("%Y-%m-%d %H:%M:%S%.f").to_string(); append_quoted(out, &s); } DataType::Interval(_) => { @@ -402,9 +398,71 @@ fn append_float(out: &mut String, v: f64) { out.push_str("null"); return; } - // Rust's `{}` formatter for f64 uses the shortest round-trippable - // representation, matching Java's `Double.toString`. - write!(out, "{v}").unwrap(); + out.push_str(&java_double_to_string(v)); +} + +/// Format an `f64` the way the JVM's `Double.toString` does. +/// +/// This is the reference spelling for a DOUBLE leaf read through the +/// text surface (conformance case COMPLEX-015): a *forced* fractional +/// part (`100` → `100.0`), a capital `E` for scientific notation, and +/// an unsigned, unpadded exponent (`1e21` → `1.0E21`, `1e-4` → +/// `1.0E-4`). Java switches to scientific notation when the decimal +/// exponent is `>= 7` or `< -3`, and uses plain decimal otherwise — +/// distinct from Rust's `{}`, which prints the shortest round-trippable +/// form with neither the forced fraction nor the capital-E layout +/// (`100`, `0.0001`, a 22-digit integer for `1e21`). +/// +/// Both Java and Rust pick the same *shortest round-trippable* digit +/// string; only the surrounding layout differs. So we lean on Rust's +/// `{:e}` (shortest scientific form: `d.dddde±XX`) for the digits and +/// exponent, then re-lay them out under Java's rules. +fn java_double_to_string(v: f64) -> String { + if v == 0.0 { + // Preserve the sign of negative zero, matching `Double.toString`. + return if v.is_sign_negative() { + "-0.0".to_string() + } else { + "0.0".to_string() + }; + } + + let sign = if v < 0.0 { "-" } else { "" }; + + // `{:e}` gives the shortest round-trip mantissa and a base-10 + // exponent, e.g. 3.2033798725730455e8, 1e21, 1e-4, -2.5e0. + let sci = format!("{:e}", v.abs()); + let (mantissa, exp): (&str, i32) = match sci.split_once('e') { + Some((m, e)) => (m, e.parse().expect("`{:e}` always emits an exponent")), + None => (sci.as_str(), 0), + }; + // Mantissa is `d` or `d.ddd`; collect the significant digits. + let digits: String = mantissa.chars().filter(|c| *c != '.').collect(); + + // Java uses scientific notation when the decimal exponent is + // `>= 7` or `< -3`, plain decimal otherwise. + if !(-3..7).contains(&exp) { + // Scientific: first digit, '.', remaining digits (forced `.0` + // when only one significant digit), 'E', unsigned/unpadded exp. + let first = &digits[..1]; + let rest = &digits[1..]; + let frac = if rest.is_empty() { "0" } else { rest }; + format!("{sign}{first}.{frac}E{exp}") + } else if exp >= 0 { + // Plain decimal, point after `exp + 1` digits. + let point = (exp + 1) as usize; + if digits.len() <= point { + // Integer value: pad with zeros and force a `.0` fraction. + let zeros = "0".repeat(point - digits.len()); + format!("{sign}{digits}{zeros}.0") + } else { + format!("{sign}{}.{}", &digits[..point], &digits[point..]) + } + } else { + // -3 <= exp < 0: leading `0.`, then `-exp - 1` zeros, then digits. + let zeros = "0".repeat((-exp - 1) as usize); + format!("{sign}0.{zeros}{digits}") + } } fn format_decimal128(raw: i128, scale: i8) -> String { @@ -781,22 +839,23 @@ mod tests { fn timestamp_microsecond_precision_preserved() { let arr = arrow_array::TimestampMicrosecondArray::from(vec![1_705_314_600_123_456_i64]); let field = field_of(DataType::Timestamp(TimeUnit::Microsecond, None)); - // 2024-01-15T10:30:00.123456 (NTZ → no Z). - assert_eq!(render(&arr, 0, &field), "\"2024-01-15T10:30:00.123456\""); + // Wall-clock spelling: space separator, no 'T', no 'Z', and the + // microsecond precision preserved (COMPLEX-016). + assert_eq!(render(&arr, 0, &field), "\"2024-01-15 10:30:00.123456\""); } #[test] - fn timestamp_nanosecond_with_tz_keeps_nine_digits_and_z() { + fn timestamp_nanosecond_with_tz_keeps_nine_digits_no_z() { let arr = arrow_array::TimestampNanosecondArray::from(vec![1_705_314_600_123_456_789_i64]) .with_timezone("UTC"); let field = field_of(DataType::Timestamp( TimeUnit::Nanosecond, Some("UTC".into()), )); - assert_eq!( - render(&arr, 0, &field), - "\"2024-01-15T10:30:00.123456789Z\"" - ); + // Nanosecond precision preserved; a tz on the Arrow side does + // NOT add a 'Z' — the leaf is spelled as the wall clock, the + // same as the top-level TIMESTAMP-to-text path (COMPLEX-016). + assert_eq!(render(&arr, 0, &field), "\"2024-01-15 10:30:00.123456789\""); } #[test] @@ -833,6 +892,92 @@ mod tests { ); } + #[test] + fn nested_double_leaf_uses_java_double_layout() { + // COMPLEX-015 (conformance): a DOUBLE leaf inside a complex + // type, read through the JSON-text surface, must be spelled + // with the reference forced-fraction / capital-'E' / + // unsigned-unpadded-exponent layout — the same one the JVM's + // `Double.toString` produces and the ODBC issue #197 alignment + // pinned as the shared spec. The array carries the boundary + // set from the spec's contract. + let arr = arrow_array::Float64Array::from(vec![ + 3.2033798725730455E8, // sci + 1.0E-4, // small + 100.0, // whole + 1.0E21, // big + 1.0E-7, // tiny + 1.0, + -2.5, + 1.0E7, + 9999999.0, + 0.001, + 1.0E100, + ]); + let field = field_of(DataType::Float64); + let expected = [ + "3.2033798725730455E8", + "1.0E-4", + "100.0", + "1.0E21", + "1.0E-7", + "1.0", + "-2.5", + "1.0E7", + "9999999.0", + "0.001", + "1.0E100", + ]; + for (i, want) in expected.iter().enumerate() { + assert_eq!(render(&arr, i, &field), *want, "leaf index {i}"); + } + } + + #[test] + fn java_double_layout_switch_boundaries() { + // Pin the plain-decimal ↔ scientific switch (exp >= 7 or + // < -3), the sign, and negative zero — cross-checked against + // the JVM's `Double.toString`. + let cases = [ + (0.0, "0.0"), + (-0.0, "-0.0"), + (123.456, "123.456"), + (9999999.0, "9999999.0"), // exp 6 → plain + (1.0E7, "1.0E7"), // exp 7 → scientific + (12345678.0, "1.2345678E7"), + (0.001, "0.001"), // exp -3 → plain + (1.0E-4, "1.0E-4"), + (-2.5, "-2.5"), + ]; + for (v, want) in cases { + assert_eq!(java_double_to_string(v), want, "value {v}"); + } + } + + #[test] + fn nested_timestamp_leaf_uses_wall_clock_spelling() { + // COMPLEX-016 (conformance): a TIMESTAMP leaf inside a complex + // type, read through the JSON-text surface, must be spelled as + // the session-timezone wall clock — space separator, no 'T', no + // 'Z', trailing-zero fractional seconds stripped — matching the + // top-level TIMESTAMP-to-text spelling (ODBC issue #197 + // alignment). Whole seconds carry no fraction at all. + // + // 2025-01-24 07:07:41 UTC = 1_737_702_461 s. + let whole = arrow_array::TimestampMicrosecondArray::from(vec![1_737_702_461_000_000_i64]) + .with_timezone("UTC"); + let field = field_of(DataType::Timestamp( + TimeUnit::Microsecond, + Some("UTC".into()), + )); + assert_eq!(render(&whole, 0, &field), "\"2025-01-24 07:07:41\""); + + // 2024-01-15 12:30:45.123456 UTC — non-zero micros kept. + let frac = arrow_array::TimestampMicrosecondArray::from(vec![1_705_321_845_123_456_i64]) + .with_timezone("UTC"); + assert_eq!(render(&frac, 0, &field), "\"2024-01-15 12:30:45.123456\""); + } + #[test] fn nested_variant_inside_list_is_escaped_known_limitation() { // Known limitation pinned: ARRAY inner fields don't diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index a5d7d632..7ace6520 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -119,6 +119,7 @@ impl ResultPostProcessor { // at most one transform. let mut json_columns: Vec = Vec::new(); let mut interval_columns: Vec = Vec::new(); + let mut null_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() { @@ -135,6 +136,22 @@ impl ResultPostProcessor { new_fields .push(Field::new(field.name(), DataType::Utf8, true).with_metadata(metadata)); schema_changed = true; + } else if matches!(dt, DataType::Null) { + // Untyped NULL (`SELECT NULL` / VOID) arrives as an Arrow + // `Null`-typed column, but the server reports it as STRING + // (the manifest carries `type_name=NULL`/`type_text=VOID`, + // whose canonical Arrow surface is Utf8) and the Thrift / + // JDBC reference exposes it as STRING — identically to a + // `CAST(NULL AS STRING)` sibling in the same query. Surface + // the server type: rewrite the column to an all-null `Utf8`. + // Always on (not option-gated); `DataType::Null` never + // carries values, so this is lossless. See issue #203 + // (DATATYPE-041). + null_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()); } @@ -162,7 +179,8 @@ impl ResultPostProcessor { // primitives and emits new Utf8 arrays for the rewritten // columns. let needs_rebuild = !schemas_field_equal(&inner_schema, &output_schema); - let has_rewrites = !json_columns.is_empty() || !interval_columns.is_empty(); + let has_rewrites = + !json_columns.is_empty() || !interval_columns.is_empty() || !null_columns.is_empty(); let transform: Option = if !needs_rebuild && !has_rewrites { None } else if !has_rewrites { @@ -186,6 +204,7 @@ impl ResultPostProcessor { let augmented = augmented_schema.clone(); let json_cols: Vec = json_columns; let interval_cols: Vec = interval_columns; + let null_cols: Vec = null_columns; Some(Box::new(move |batch: &RecordBatch| { build_rewritten_batch( batch, @@ -193,6 +212,7 @@ impl ResultPostProcessor { &target_schema, &json_cols, &interval_cols, + &null_cols, ) })) }; @@ -242,25 +262,31 @@ fn schemas_field_equal(a: &SchemaRef, b: &SchemaRef) -> bool { /// Build a `RecordBatch` whose primitive columns are reprojected /// from `batch`, complex columns (indexed by `json_cols`) are replaced -/// with `Utf8` arrays of compact JSON text, and interval / duration +/// with `Utf8` arrays of compact JSON text, interval / duration /// columns (indexed by `interval_cols`) are replaced with `Utf8` -/// arrays of canonical Databricks interval text. +/// arrays of canonical Databricks interval text, and untyped-NULL +/// columns (indexed by `null_cols`) are replaced with all-null `Utf8` +/// arrays (the server-reported STRING type — see issue #203). /// -/// `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). +/// `json_cols`, `interval_cols`, and `null_cols` are assumed to be +/// sorted in ascending order (the constructor walks the schema +/// linearly) and pairwise disjoint (`is_complex_type` returns false +/// for intervals; a `Null`-typed column is neither complex nor +/// interval). fn build_rewritten_batch( batch: &RecordBatch, augmented: &SchemaRef, output: &SchemaRef, json_cols: &[usize], interval_cols: &[usize], + null_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; + let mut next_null_idx = 0; for (col_idx, column) in batch.columns().iter().enumerate() { let is_json = json_cols .get(next_json_idx) @@ -270,6 +296,10 @@ fn build_rewritten_batch( .get(next_interval_idx) .copied() .is_some_and(|target| target == col_idx); + let is_null_col = null_cols + .get(next_null_idx) + .copied() + .is_some_and(|target| target == col_idx); if is_json { next_json_idx += 1; // Use the augmented field (carries databricks.* metadata) @@ -318,6 +348,12 @@ fn build_rewritten_batch( builder.append_value(&s); } columns.push(Arc::new(builder.finish())); + } else if is_null_col { + next_null_idx += 1; + // `DataType::Null` carries no values, so every row is null: + // emit an all-null `Utf8` array of the same length. Matches + // the server-reported STRING type for untyped NULL / VOID. + columns.push(arrow_array::new_null_array(&DataType::Utf8, num_rows)); } else { columns.push(column.clone()); } @@ -478,6 +514,91 @@ mod tests { ); } + #[tokio::test] + async fn untyped_null_column_rewritten_to_utf8() { + // Regression for issue #203 (DATATYPE-041): an untyped NULL + // (`SELECT NULL` / VOID) arrives as an Arrow `Null`-typed column; + // the post-processor must surface the server-reported STRING type + // as an all-null `Utf8` column — always on, no option needed. + let schema = Arc::new(Schema::new(vec![ + Field::new("untyped_null", DataType::Null, true), + Field::new("typed_null_string", DataType::Utf8, true), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(arrow_array::NullArray::new(1)) as _, + Arc::new(StringArray::from(vec![None::<&str>])) as _, + ], + ) + .unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + + // Default options (no complex/interval rewrite): the Null→Utf8 + // coercion is unconditional. + let mut pp = ResultPostProcessor::new(inner, None, PostProcessOptions::default()) + .await + .unwrap(); + + // Both the advertised schema and the yielded batch report Utf8 for + // the untyped-NULL column, identical to the CAST(NULL AS STRING) + // sibling. + let advertised = pp.schema().await.unwrap(); + assert_eq!(advertised.field(0).data_type(), &DataType::Utf8); + assert_eq!(advertised.field(1).data_type(), &DataType::Utf8); + assert_eq!( + advertised.field(0).data_type(), + advertised.field(1).data_type() + ); + + let out = pp.next_batch().await.unwrap().unwrap(); + assert_eq!(out.schema().field(0).data_type(), &DataType::Utf8); + assert_eq!(out.num_rows(), 1); + // The value is still NULL in the rewritten column. + let col = out + .column(0) + .as_any() + .downcast_ref::() + .expect("untyped_null rewritten to StringArray"); + assert_eq!(col.len(), 1); + assert!(col.is_null(0)); + } + + #[tokio::test] + async fn untyped_null_carries_manifest_metadata_and_real_name() { + // The Null→Utf8 rewrite must compose with manifest augmentation: + // the rewritten field keeps the manifest's real name and the + // server-reported `databricks.type_name`/`type_text` (NULL/VOID). + let positional = Arc::new(Schema::new(vec![Field::new("col_0", DataType::Null, true)])); + let batch = RecordBatch::try_new( + positional, + vec![Arc::new(arrow_array::NullArray::new(2)) as _], + ) + .unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + let manifest = make_manifest(vec![column_info("untyped_null", "NULL", "VOID", 0)]); + + let mut pp = + ResultPostProcessor::new(inner, Some(&manifest), PostProcessOptions::default()) + .await + .unwrap(); + + let out = pp.next_batch().await.unwrap().unwrap(); + let field = out.schema().field(0).clone(); + assert_eq!(field.name(), "untyped_null"); + assert_eq!(field.data_type(), &DataType::Utf8); + assert_eq!( + field.metadata().get(metadata_keys::TYPE_NAME), + Some(&"NULL".to_string()) + ); + assert_eq!( + field.metadata().get(metadata_keys::TYPE_TEXT), + Some(&"VOID".to_string()) + ); + assert_eq!(out.num_rows(), 2); + assert!(out.column(0).is_null(0) && out.column(0).is_null(1)); + } + #[tokio::test] async fn json_path_rewrites_list_column_to_utf8() { // Build a one-row batch with a list column.