diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 31673499..f39e12c7 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -12,6 +12,11 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added - Added Thrift-native metadata routing with compatible public-schema casts and one-based `getColumns` ordinals. +- Added native Arrow `GEOMETRY` / `GEOGRAPHY` results as tagged + `struct` values, including nested values and empty-result schemas. + The kernel treats Reyder's structured logical manifest as authoritative and + reconciles attachments that omit the canonical tags without copying child + buffers. ### Changed diff --git a/src/client/sea.rs b/src/client/sea.rs index cd25cf5b..dd31887e 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2342,6 +2342,7 @@ mod tests { column_count: 0, columns: vec![], }, + arrow_schema: None, total_chunk_count: None, total_row_count: None, total_byte_count: None, diff --git a/src/metadata/type_mapping.rs b/src/metadata/type_mapping.rs index db254594..f6911fa5 100644 --- a/src/metadata/type_mapping.rs +++ b/src/metadata/type_mapping.rs @@ -24,6 +24,7 @@ //! When adding a new type, update **both** mapping functions. use arrow_schema::{DataType, Field, Fields, IntervalUnit, TimeUnit}; +use std::collections::HashMap; use std::sync::Arc; // ─── JDBC `Types` integer codes ───────────────────────────────────── @@ -104,7 +105,7 @@ pub(crate) const JDBC_ARRAY: i16 = 2003; /// `"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`. +/// — see `reader::ResultReaderFactory::extract_logical_schema_from_manifest`. /// /// Unrecognised input falls back to `DataType::Utf8` rather than /// panicking; the kernel always returns *some* schema even when the @@ -200,6 +201,7 @@ 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)?, + "GEOMETRY" | "GEOGRAPHY" => geospatial_binary_arrow_type(trimmed)?, // 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 @@ -334,6 +336,42 @@ fn parse_struct(s: &str, type_interval_type: Option<&str>, depth: usize) -> Opti Some(DataType::Struct(Fields::from(fields))) } +/// Native Arrow representation emitted by DBR and Reyden. +/// +/// Besides the `struct` layout, the `wkb` child carries the exact +/// family and type-level SRID tags that geo-aware Arrow consumers use to +/// distinguish this encoding from an ordinary user struct. `ANY` is tagged +/// with Reyden's `-1` sentinel; bare types use their SQL defaults. +pub(crate) fn geospatial_binary_arrow_type(type_text: &str) -> Option { + let upper = type_text.trim().to_ascii_uppercase(); + let (family, default_srid, qualifier) = if let Some(rest) = upper.strip_prefix("GEOGRAPHY") { + ("geography", 4326, rest) + } else { + let rest = upper.strip_prefix("GEOMETRY")?; + ("geometry", 0, rest) + }; + let qualifier = qualifier.trim(); + let srid = if qualifier.is_empty() { + default_srid + } else { + let value = qualifier.strip_prefix('(')?.strip_suffix(')')?.trim(); + if value == "ANY" { + -1 + } else { + value.parse::().ok()? + } + }; + let wkb_metadata = HashMap::from([ + (family.to_string(), "true".to_string()), + ("srid".to_string(), srid.to_string()), + ]); + + Some(DataType::Struct(Fields::from(vec![ + Field::new("srid", DataType::Int32, false), + Field::new("wkb", DataType::Binary, false).with_metadata(wkb_metadata), + ]))) +} + /// 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; @@ -585,6 +623,87 @@ mod tests { assert_eq!(databricks_type_to_arrow("STRUCT"), DataType::Utf8); } + #[test] + fn test_geospatial_types_use_srid_wkb_struct() { + for type_text in ["GEOGRAPHY(4326)", "GEOMETRY(ANY)", "geometry(3857)"] { + let expected = geospatial_binary_arrow_type(type_text).unwrap(); + assert_eq!(databricks_type_to_arrow(type_text), expected, "{type_text}"); + } + + let expected = geospatial_binary_arrow_type("GEOMETRY(ANY)").unwrap(); + let DataType::Struct(fields) = expected else { + unreachable!("geo binary helper must return a struct") + }; + assert_eq!(fields[0].name(), "srid"); + assert_eq!(fields[0].data_type(), &DataType::Int32); + assert!(!fields[0].is_nullable()); + assert_eq!(fields[1].name(), "wkb"); + assert_eq!(fields[1].data_type(), &DataType::Binary); + assert!(!fields[1].is_nullable()); + assert_eq!( + fields[1].metadata().get("geometry").map(String::as_str), + Some("true") + ); + assert_eq!( + fields[1].metadata().get("srid").map(String::as_str), + Some("-1") + ); + + let DataType::Struct(geography_fields) = + geospatial_binary_arrow_type("GEOGRAPHY(4326)").unwrap() + else { + unreachable!("geo binary helper must return a struct") + }; + assert_eq!( + geography_fields[1] + .metadata() + .get("geography") + .map(String::as_str), + Some("true") + ); + assert_eq!( + geography_fields[1] + .metadata() + .get("srid") + .map(String::as_str), + Some("4326") + ); + + for malformed in [ + "GEOMETRY(garbage)", + "GEOGRAPHY()", + "GEOMETRY(4326) trailing", + ] { + assert_eq!( + geospatial_binary_arrow_type(malformed), + None, + "a malformed logical type must not be assigned canonical geo tags" + ); + assert_eq!(databricks_type_to_arrow(malformed), DataType::Utf8); + } + } + + #[test] + fn test_geospatial_types_are_reconstructed_inside_nested_type_text() { + let binary = + databricks_type_to_arrow("STRUCT>"); + + let DataType::Struct(binary_fields) = binary else { + panic!("expected outer struct") + }; + assert_eq!( + binary_fields[0].data_type(), + &geospatial_binary_arrow_type("GEOMETRY(ANY)").unwrap() + ); + let DataType::List(binary_items) = binary_fields[1].data_type() else { + panic!("expected geography list") + }; + assert_eq!( + binary_items.data_type(), + &geospatial_binary_arrow_type("GEOGRAPHY(4326)").unwrap() + ); + } + #[test] fn test_databricks_type_to_arrow_array_nested() { // ARRAY → List. Field name is "item" — the diff --git a/src/reader/mod.rs b/src/reader/mod.rs index f91ea791..fd2eda7e 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -35,8 +35,10 @@ use crate::reader::post_processor::{PostProcessOptions, ResultPostProcessor}; use crate::types::cloudfetch::{CloudFetchConfig, CloudFetchLink}; use crate::types::sea::{CompressionCodec, ResultManifest, StatementState}; use arrow_array::RecordBatch; +use arrow_ipc::reader::StreamReader; use arrow_schema::{ArrowError, Field, Schema, SchemaRef}; use async_trait::async_trait; +use std::io::Cursor; use std::sync::Arc; use std::time::Duration; @@ -171,7 +173,7 @@ impl ResultReaderFactory { statement_id, "Manifest reports total_chunk_count=0; short-circuiting to empty reader", ); - let schema = Self::extract_schema_from_manifest(response.manifest.as_ref())?; + let schema = Self::extract_physical_schema_from_manifest(response.manifest.as_ref())?; return Ok(Box::new(EmptyReader::new(schema))); } @@ -303,7 +305,7 @@ impl ResultReaderFactory { // return `None` and downstream wrappers // would reject the stream. let manifest_schema = response.manifest.as_ref().and_then(|m| { - match Self::extract_schema_from_manifest(Some(m)) { + match Self::extract_physical_schema_from_manifest(Some(m)) { Ok(s) => Some(s), Err(e) => { crate::klog::warn!( @@ -367,7 +369,8 @@ 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_physical_schema_from_manifest(response.manifest.as_ref())?; Ok(Box::new(EmptyReader::new(schema))) } StatementState::Pending | StatementState::Running => Err(Error::invalid_state() @@ -385,10 +388,16 @@ impl ResultReaderFactory { } } - /// Extract Arrow schema from the result manifest. + /// Reconstruct the logical Arrow schema from SEA's structured manifest. /// - /// Falls back to an empty schema if no manifest is available. - fn extract_schema_from_manifest(manifest: Option<&ResultManifest>) -> Result { + /// The post-processor uses this to interpret physical attachments. Empty + /// readers start from `manifest.arrow_schema` via + /// [`Self::extract_physical_schema_from_manifest`] and pass through the + /// same reconciliation. Falls back to an empty schema if no manifest is + /// available. + fn extract_logical_schema_from_manifest( + manifest: Option<&ResultManifest>, + ) -> Result { let Some(manifest) = manifest else { crate::klog::warn!("No manifest available for empty result set, using empty schema"); return Ok(Arc::new(Schema::empty())); @@ -403,18 +412,21 @@ impl ResultReaderFactory { // `"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. + // non-empty result path uses the Arrow schema embedded in the + // wire payload for its values, while this reconstructed schema + // supplies the logical type contract. Reconstructing without + // the qualifiers 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`. + // Reconstruct logical geo leaves as canonical tagged + // `struct` values. For empty results this is also the + // physical schema; for non-empty results it identifies untagged + // attachment structs during post-processing. let data_type = crate::metadata::type_mapping::databricks_type_to_arrow_with_interval( &col.type_text, @@ -427,6 +439,44 @@ impl ResultReaderFactory { Ok(Arc::new(Schema::new(fields))) } + /// Decode the physical schema that SEA says its Arrow attachments use. + /// + /// Reyder intentionally keeps `manifest.arrow_schema` physical while the + /// structured manifest above remains logical. That distinction matters for + /// legacy warehouses (geo arrives as `Utf8`) and for native Reyden results + /// (geo arrives as an untagged `struct`). Empty results and an + /// empty leading streaming chunk must start from this physical schema so + /// the shared post-processor can apply the same reconciliation as it does + /// to a non-empty attachment. + fn extract_physical_schema_from_manifest( + manifest: Option<&ResultManifest>, + ) -> Result { + let logical = Self::extract_logical_schema_from_manifest(manifest)?; + let Some(manifest) = manifest else { + return Ok(logical); + }; + let Some(bytes) = manifest + .arrow_schema + .as_deref() + .filter(|bytes| !bytes.is_empty()) + else { + return Ok(logical); + }; + + let reader = StreamReader::try_new(Cursor::new(bytes), None).map_err(|error| { + Error::data_loss().message(format!("failed to decode manifest.arrow_schema: {error}")) + })?; + let physical = reader.schema(); + if physical.fields().len() != manifest.schema.columns.len() { + return Err(Error::data_loss().message(format!( + "manifest.arrow_schema has {} columns but structured manifest has {}", + physical.fields().len(), + manifest.schema.columns.len() + ))); + } + Ok(physical) + } + fn create_cloudfetch_reader( &self, statement_id: &str, @@ -908,13 +958,22 @@ 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; + use arrow_ipc::writer::StreamWriter; + use arrow_schema::{DataType, Fields}; fn make_test_batch(values: Vec<&str>) -> RecordBatch { let schema = Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, false)])); RecordBatch::try_new(schema, vec![Arc::new(StringArray::from(values))]).unwrap() } + fn schema_ipc(schema: &Schema) -> Vec { + let mut bytes = Vec::new(); + let mut writer = StreamWriter::try_new(&mut bytes, schema).unwrap(); + writer.finish().unwrap(); + drop(writer); + bytes + } + // --- ResultReaderAdapter tests --- #[tokio::test] @@ -997,7 +1056,7 @@ mod tests { } #[test] - fn test_extract_schema_from_manifest_primitives() { + fn test_extract_logical_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 @@ -1009,7 +1068,8 @@ mod tests { 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(); + let schema = + ResultReaderFactory::extract_logical_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); @@ -1018,7 +1078,7 @@ mod tests { } #[test] - fn test_extract_schema_from_manifest_decimal_carries_precision_scale() { + fn test_extract_logical_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 @@ -1033,12 +1093,13 @@ mod tests { Some(2), None, )]); - let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap(); + let schema = + ResultReaderFactory::extract_logical_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() { + fn test_extract_logical_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. // @@ -1069,7 +1130,8 @@ mod tests { ), make_column_info("v", "VOID", "VOID", 2, None, None, None), ]); - let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap(); + let schema = + ResultReaderFactory::extract_logical_schema_from_manifest(Some(&manifest)).unwrap(); assert_eq!( schema.field(0).data_type(), &DataType::Interval(arrow_schema::IntervalUnit::YearMonth), @@ -1087,7 +1149,7 @@ mod tests { } #[test] - fn test_extract_schema_from_manifest_interval_keyword_fallback() { + fn test_extract_logical_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. @@ -1112,7 +1174,8 @@ mod tests { ), make_column_info("bare", "INTERVAL", "INTERVAL", 2, None, None, None), ]); - let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap(); + let schema = + ResultReaderFactory::extract_logical_schema_from_manifest(Some(&manifest)).unwrap(); assert_eq!( schema.field(0).data_type(), &DataType::Interval(arrow_schema::IntervalUnit::YearMonth) @@ -1128,7 +1191,7 @@ mod tests { } #[test] - fn test_extract_schema_from_manifest_complex_types_parse_into_nested_arrow() { + fn test_extract_logical_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 @@ -1140,17 +1203,84 @@ mod tests { 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(); + let schema = + ResultReaderFactory::extract_logical_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() { + fn test_extract_empty_geospatial_schema_uses_canonical_tagged_structs() { + let manifest = make_manifest(vec![ + make_column_info("geom", "GEOMETRY", "GEOMETRY(ANY)", 0, None, None, None), + make_column_info("geog", "GEOGRAPHY", "GEOGRAPHY(4326)", 1, None, None, None), + ]); + + let schema = + ResultReaderFactory::extract_logical_schema_from_manifest(Some(&manifest)).unwrap(); + for field in schema.fields() { + assert!(field.is_nullable(), "geo column itself remains nullable"); + let DataType::Struct(children) = field.data_type() else { + panic!("binary geo must be struct, got {:?}", field.data_type()); + }; + assert_eq!(children[0].name(), "srid"); + assert_eq!(children[0].data_type(), &DataType::Int32); + assert!(!children[0].is_nullable()); + assert_eq!(children[1].name(), "wkb"); + assert_eq!(children[1].data_type(), &DataType::Binary); + assert!(!children[1].is_nullable()); + } + } + + #[test] + fn test_extract_physical_schema_uses_manifest_arrow_schema() { + let mut manifest = make_manifest(vec![make_column_info( + "geom", + "GEOMETRY", + "GEOMETRY(ANY)", + 0, + None, + None, + None, + )]); + manifest.arrow_schema = Some(schema_ipc(&Schema::new(vec![Field::new( + "col_0", + DataType::Utf8, + true, + )]))); + + let logical = + ResultReaderFactory::extract_logical_schema_from_manifest(Some(&manifest)).unwrap(); + assert!(matches!(logical.field(0).data_type(), DataType::Struct(_))); + + let physical = + ResultReaderFactory::extract_physical_schema_from_manifest(Some(&manifest)).unwrap(); + assert_eq!(physical.field(0).data_type(), &DataType::Utf8); + assert_eq!(physical.field(0).name(), "col_0"); + } + + #[test] + fn test_extract_physical_schema_rejects_invalid_or_mismatched_ipc() { + let mut manifest = make_manifest(vec![make_column_info( + "value", "STRING", "STRING", 0, None, None, None, + )]); + manifest.arrow_schema = Some(b"not arrow IPC".to_vec()); + let error = ResultReaderFactory::extract_physical_schema_from_manifest(Some(&manifest)) + .unwrap_err(); + assert!(error.message.contains("manifest.arrow_schema")); + + manifest.arrow_schema = Some(schema_ipc(&Schema::empty())); + let error = ResultReaderFactory::extract_physical_schema_from_manifest(Some(&manifest)) + .unwrap_err(); + assert!(error.message.contains("0 columns")); + } + + #[test] + fn test_extract_logical_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(); + let schema = ResultReaderFactory::extract_logical_schema_from_manifest(None).unwrap(); assert_eq!(schema.fields().len(), 0); } @@ -1163,6 +1293,7 @@ mod tests { column_count: columns.len() as i32, columns, }, + arrow_schema: None, total_chunk_count: None, total_row_count: None, total_byte_count: None, @@ -1325,6 +1456,45 @@ mod tests { ); } + #[test] + fn test_augment_schema_preserves_geospatial_identity_and_srid() { + let binary_geo = DataType::Struct(Fields::from(vec![ + Field::new("srid", DataType::Int32, false), + Field::new("wkb", DataType::Binary, false), + ])); + let schema = Arc::new(Schema::new(vec![ + Field::new("col_0", binary_geo.clone(), true), + Field::new("col_1", binary_geo.clone(), true), + ])); + let manifest = make_manifest(vec![ + make_column_info("geom", "GEOMETRY", "GEOMETRY(ANY)", 0, None, None, None), + make_column_info("geog", "GEOGRAPHY", "GEOGRAPHY(4326)", 1, None, None, None), + ]); + + let augmented = ResultReaderAdapter::augment_schema_with_manifest(&schema, &manifest); + + assert_eq!(augmented.field(0).data_type(), &binary_geo); + assert_eq!(augmented.field(1).data_type(), &binary_geo); + assert_eq!(augmented.field(0).name(), "geom"); + assert_eq!(augmented.field(1).name(), "geog"); + assert_eq!( + augmented.field(0).metadata().get(metadata_keys::TYPE_NAME), + Some(&"GEOMETRY".to_string()) + ); + assert_eq!( + augmented.field(0).metadata().get(metadata_keys::TYPE_TEXT), + Some(&"GEOMETRY(ANY)".to_string()) + ); + assert_eq!( + augmented.field(1).metadata().get(metadata_keys::TYPE_NAME), + Some(&"GEOGRAPHY".to_string()) + ); + assert_eq!( + augmented.field(1).metadata().get(metadata_keys::TYPE_TEXT), + Some(&"GEOGRAPHY(4326)".to_string()) + ); + } + #[test] fn test_augment_schema_interval_type() { let schema = Arc::new(Schema::new(vec![Field::new( @@ -1658,6 +1828,7 @@ mod tests { column_count: 0, columns: vec![], }, + arrow_schema: None, total_chunk_count, total_row_count: None, total_byte_count: None, diff --git a/src/reader/post_processor/geospatial.rs b/src/reader/post_processor/geospatial.rs new file mode 100644 index 00000000..48e94894 --- /dev/null +++ b/src/reader/post_processor/geospatial.rs @@ -0,0 +1,764 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Reconciliation of Reyden GEOMETRY / GEOGRAPHY Arrow results. +//! +//! Reyden encodes each value as +//! `struct`. Reyder's structured +//! manifest retains the logical `GEOMETRY(...)` / `GEOGRAPHY(...)` type and is +//! the source of truth for interpreting result attachments. An attachment can +//! contain the same struct without the canonical Arrow tags, so this module +//! reconstructs them from the logical schema without copying child buffers. + +use crate::kernel_error::{Error, Result}; +use arrow_array::{ + Array, ArrayRef, FixedSizeListArray, LargeListArray, LargeListViewArray, ListArray, + ListViewArray, MapArray, StructArray, +}; +use arrow_schema::{DataType, Field, FieldRef, Fields}; +use std::sync::Arc; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum GeoFamily { + Geometry, + Geography, +} + +impl GeoFamily { + fn manifest_name(self) -> &'static str { + match self { + Self::Geometry => "GEOMETRY", + Self::Geography => "GEOGRAPHY", + } + } +} + +/// Schema decision for a top-level result column. +#[derive(Debug)] +pub(super) struct GeoPlan { + /// Type after attaching canonical geo metadata recursively. + pub(super) output_type: DataType, + /// Whether the values need local tag attachment. + pub(super) needs_rewrite: bool, + /// Whether the column itself is a logical geo value. This distinguishes a + /// native geo struct from an ordinary complex column for JSON rendering. + pub(super) is_top_level_geo: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct GeoTag { + family: GeoFamily, + srid: i32, +} + +#[derive(Debug)] +struct TypePlan { + output_type: DataType, + contains_geo: bool, + is_root_geo: bool, +} + +/// Reconcile an attachment field with its structured-manifest logical field. +/// +/// `logical_field` is reconstructed from the structured SEA manifest. It is +/// the authority for deciding whether an otherwise ordinary-looking +/// `struct` is geospatial. A plain user struct remains a struct unless +/// the logical schema declares it geo. Canonical attachment tags are used as a +/// fallback only when no logical field is available. +pub(super) fn plan(field: &Field, logical_field: Option<&Field>) -> Result> { + let type_plan = plan_data_type( + field.data_type(), + logical_field.map(Field::data_type), + field.name(), + )?; + if !type_plan.contains_geo { + return Ok(None); + } + Ok(Some(GeoPlan { + needs_rewrite: &type_plan.output_type != field.data_type(), + output_type: type_plan.output_type, + is_top_level_geo: type_plan.is_root_geo, + })) +} + +/// Recursively reconcile geo leaves in `array` with `output_type`. +/// +/// Only container array objects whose field metadata must be tagged are +/// rebuilt; value buffers and child arrays remain shared. +pub(super) fn rewrite( + array: &ArrayRef, + output_type: &DataType, + column_name: &str, +) -> Result { + rewrite_array(array, output_type, column_name) +} + +fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) -> Result { + let logical_tag = logical.map(native_geo_tag).transpose()?.flatten(); + let physical_tag = native_geo_tag(physical)?; + + if let Some(expected) = logical_tag { + // DBR/legacy SEA paths serialize geo values as text even though the + // structured manifest still declares GEOMETRY / GEOGRAPHY. Preserve + // that already-public representation. Native Reyden is identified by + // its `struct` attachment and is reconciled below. + if matches!(physical, DataType::Utf8 | DataType::LargeUtf8) { + return Ok(TypePlan { + output_type: physical.clone(), + contains_geo: false, + is_root_geo: false, + }); + } + validate_geo_source(physical, expected, path)?; + // The logical schema is canonical and contains the family and + // type-level SRID tags that can be missing from the payload. + let output_type = logical.expect("logical_tag implies a logical type").clone(); + return Ok(TypePlan { + output_type, + contains_geo: true, + is_root_geo: true, + }); + } + + if let Some(actual) = physical_tag { + if let Some(logical) = logical { + return Err(Error::data_loss().message(format!( + "geospatial value '{path}' is tagged {}({}) in the attachment but its logical manifest type is {logical:?}", + actual.family.manifest_name(), + actual.srid, + ))); + } + return Ok(TypePlan { + output_type: physical.clone(), + contains_geo: true, + is_root_geo: true, + }); + } + + match physical { + DataType::Struct(fields) => { + let logical_fields = match logical { + Some(DataType::Struct(fields)) => Some(fields), + Some(other) if contains_tagged_geo(other)? => { + return logical_shape_mismatch(path, physical, other); + } + _ => None, + }; + if let (Some(logical_fields), Some(logical)) = (logical_fields, logical) { + if logical_fields.len() != fields.len() && contains_tagged_geo(logical)? { + return logical_shape_mismatch(path, physical, logical); + } + } + + let mut contains_geo = false; + let mut output_fields = Vec::with_capacity(fields.len()); + for (index, field) in fields.iter().enumerate() { + let logical_field = logical_fields.and_then(|fields| fields.get(index)); + let child_path = format!("{path}.{}", field.name()); + let child = plan_data_type( + field.data_type(), + logical_field.map(|field| field.data_type()), + &child_path, + )?; + contains_geo |= child.contains_geo; + output_fields.push(if &child.output_type == field.data_type() { + field.clone() + } else { + Arc::new(field.as_ref().clone().with_data_type(child.output_type)) + }); + } + Ok(TypePlan { + output_type: DataType::Struct(Fields::from(output_fields)), + contains_geo, + is_root_geo: false, + }) + } + DataType::List(field) => plan_nested_field( + field, + logical.and_then(|logical| match logical { + DataType::List(field) => Some(field.as_ref()), + _ => None, + }), + path, + DataType::List, + logical, + ), + DataType::LargeList(field) => plan_nested_field( + field, + logical.and_then(|logical| match logical { + DataType::LargeList(field) => Some(field.as_ref()), + _ => None, + }), + path, + DataType::LargeList, + logical, + ), + DataType::ListView(field) => plan_nested_field( + field, + logical.and_then(|logical| match logical { + DataType::ListView(field) => Some(field.as_ref()), + _ => None, + }), + path, + DataType::ListView, + logical, + ), + DataType::LargeListView(field) => plan_nested_field( + field, + logical.and_then(|logical| match logical { + DataType::LargeListView(field) => Some(field.as_ref()), + _ => None, + }), + path, + DataType::LargeListView, + logical, + ), + DataType::FixedSizeList(field, size) => { + let logical_field = logical.and_then(|logical| match logical { + DataType::FixedSizeList(field, logical_size) if logical_size == size => { + Some(field.as_ref()) + } + _ => None, + }); + plan_nested_field( + field, + logical_field, + path, + |field| DataType::FixedSizeList(field, *size), + logical, + ) + } + DataType::Map(field, ordered) => { + let logical_field = logical.and_then(|logical| match logical { + DataType::Map(field, logical_ordered) if logical_ordered == ordered => { + Some(field.as_ref()) + } + _ => None, + }); + plan_nested_field( + field, + logical_field, + path, + |field| DataType::Map(field, *ordered), + logical, + ) + } + _ => { + if let Some(logical) = logical { + if contains_tagged_geo(logical)? { + return logical_shape_mismatch(path, physical, logical); + } + } + if contains_tagged_geo(physical)? { + return unsupported_container(physical); + } + Ok(TypePlan { + output_type: physical.clone(), + contains_geo: false, + is_root_geo: false, + }) + } + } +} + +fn plan_nested_field( + physical_field: &FieldRef, + logical_field: Option<&Field>, + path: &str, + constructor: impl FnOnce(FieldRef) -> DataType, + logical_container: Option<&DataType>, +) -> Result { + if let Some(logical_container) = logical_container { + if logical_field.is_none() && contains_tagged_geo(logical_container)? { + return logical_shape_mismatch(path, physical_field.data_type(), logical_container); + } + } + let child = plan_data_type( + physical_field.data_type(), + logical_field.map(Field::data_type), + path, + )?; + let output_field = if &child.output_type == physical_field.data_type() { + physical_field.clone() + } else { + Arc::new( + physical_field + .as_ref() + .clone() + .with_data_type(child.output_type), + ) + }; + Ok(TypePlan { + output_type: constructor(output_field), + contains_geo: child.contains_geo, + is_root_geo: false, + }) +} + +fn logical_shape_mismatch(path: &str, physical: &DataType, logical: &DataType) -> Result { + Err(Error::data_loss().message(format!( + "geospatial value '{path}' has attachment type {physical:?}, which does not match logical type {logical:?}" + ))) +} + +fn contains_tagged_geo(data_type: &DataType) -> Result { + if native_geo_tag(data_type)?.is_some() { + return Ok(true); + } + match data_type { + DataType::Struct(fields) => { + for field in fields { + if contains_tagged_geo(field.data_type())? { + return Ok(true); + } + } + Ok(false) + } + DataType::Union(fields, _) => { + for (_, field) in fields.iter() { + if contains_tagged_geo(field.data_type())? { + return Ok(true); + } + } + Ok(false) + } + DataType::List(field) + | DataType::LargeList(field) + | DataType::ListView(field) + | DataType::LargeListView(field) + | DataType::FixedSizeList(field, _) + | DataType::Map(field, _) + | DataType::RunEndEncoded(_, field) => contains_tagged_geo(field.data_type()), + DataType::Dictionary(_, value) => contains_tagged_geo(value), + _ => Ok(false), + } +} + +fn unsupported_container(data_type: &DataType) -> Result { + Err(Error::not_implemented().message(format!( + "geospatial metadata reconciliation is not implemented for Arrow container {data_type:?}" + ))) +} + +fn validate_geo_source(data_type: &DataType, expected: GeoTag, path: &str) -> Result<()> { + if !is_geo_struct_shape(data_type) { + return Err(Error::data_loss().message(format!( + "geospatial value '{path}' is declared {} but its attachment type is {data_type:?}; expected struct", + expected.family.manifest_name(), + ))); + } + if let Some(actual) = native_geo_tag(data_type)? { + if actual != expected { + return Err(Error::data_loss().message(format!( + "geospatial value '{path}' is declared {}({}) but its attachment is tagged {}({})", + expected.family.manifest_name(), + expected.srid, + actual.family.manifest_name(), + actual.srid, + ))); + } + } + Ok(()) +} + +fn is_geo_struct_shape(data_type: &DataType) -> bool { + let DataType::Struct(fields) = data_type else { + return false; + }; + fields.len() == 2 + && fields[0].name() == "srid" + && fields[0].data_type() == &DataType::Int32 + && fields[1].name() == "wkb" + && fields[1].data_type() == &DataType::Binary +} + +/// Recognize the canonical geo tag when present. An exact untagged +/// `struct` returns `None`; any partial or conflicting tag is an +/// invalid wire schema. +fn native_geo_tag(data_type: &DataType) -> Result> { + if !is_geo_struct_shape(data_type) { + return Ok(None); + } + let DataType::Struct(fields) = data_type else { + unreachable!("shape check guarantees a struct") + }; + + let metadata = fields[1].metadata(); + let geometry = metadata.get("geometry").map(String::as_str) == Some("true"); + let geography = metadata.get("geography").map(String::as_str) == Some("true"); + let has_geo_metadata = metadata.contains_key("geometry") + || metadata.contains_key("geography") + || metadata.contains_key("srid"); + if !has_geo_metadata { + return Ok(None); + } + if geometry == geography { + return Err(Error::data_loss().message( + "malformed geospatial Arrow tag: expected exactly one of geometry=true or geography=true", + )); + } + let srid = metadata + .get("srid") + .ok_or_else(|| { + Error::data_loss().message("malformed geospatial Arrow tag: missing type-level srid") + })? + .parse::() + .map_err(|error| { + Error::data_loss().message(format!( + "malformed geospatial Arrow tag: invalid type-level srid: {error}" + )) + })?; + + Ok(Some(GeoTag { + family: if geometry { + GeoFamily::Geometry + } else { + GeoFamily::Geography + }, + srid, + })) +} + +fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result { + if let Some(output_tag) = native_geo_tag(output_type)? { + validate_geo_source(array.data_type(), output_tag, path)?; + if array.data_type() == output_type { + return Ok(array.clone()); + } + let values = downcast::(array, path, "StructArray")?; + let DataType::Struct(output_fields) = output_type else { + unreachable!("a geo tag is only valid on a struct") + }; + let output = StructArray::try_new( + output_fields.clone(), + values.columns().to_vec(), + values.nulls().cloned(), + ) + .map_err(|error| rebuild_error(path, error))?; + return Ok(Arc::new(output)); + } + + match (array.data_type(), output_type) { + (DataType::Struct(source_fields), DataType::Struct(output_fields)) => { + let values = downcast::(array, path, "StructArray")?; + let columns = values + .columns() + .iter() + .zip(source_fields.iter()) + .zip(output_fields.iter()) + .map(|((column, source), output)| { + rewrite_array( + column, + output.data_type(), + &format!("{path}.{}", source.name()), + ) + }) + .collect::>>()?; + let output = + StructArray::try_new(output_fields.clone(), columns, values.nulls().cloned()) + .map_err(|error| rebuild_error(path, error))?; + Ok(Arc::new(output)) + } + (DataType::List(_), DataType::List(output_field)) => { + let values = downcast::(array, path, "ListArray")?; + let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let output = ListArray::try_new( + output_field.clone(), + values.offsets().clone(), + child, + values.nulls().cloned(), + ) + .map_err(|error| rebuild_error(path, error))?; + Ok(Arc::new(output)) + } + (DataType::LargeList(_), DataType::LargeList(output_field)) => { + let values = downcast::(array, path, "LargeListArray")?; + let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let output = LargeListArray::try_new( + output_field.clone(), + values.offsets().clone(), + child, + values.nulls().cloned(), + ) + .map_err(|error| rebuild_error(path, error))?; + Ok(Arc::new(output)) + } + (DataType::ListView(_), DataType::ListView(output_field)) => { + let values = downcast::(array, path, "ListViewArray")?; + let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let output = ListViewArray::try_new( + output_field.clone(), + values.offsets().clone(), + values.sizes().clone(), + child, + values.nulls().cloned(), + ) + .map_err(|error| rebuild_error(path, error))?; + Ok(Arc::new(output)) + } + (DataType::LargeListView(_), DataType::LargeListView(output_field)) => { + let values = downcast::(array, path, "LargeListViewArray")?; + let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let output = LargeListViewArray::try_new( + output_field.clone(), + values.offsets().clone(), + values.sizes().clone(), + child, + values.nulls().cloned(), + ) + .map_err(|error| rebuild_error(path, error))?; + Ok(Arc::new(output)) + } + ( + DataType::FixedSizeList(_, source_size), + DataType::FixedSizeList(output_field, output_size), + ) if source_size == output_size => { + let values = downcast::(array, path, "FixedSizeListArray")?; + let child = rewrite_array(values.values(), output_field.data_type(), path)?; + let output = FixedSizeListArray::try_new( + output_field.clone(), + *output_size, + child, + values.nulls().cloned(), + ) + .map_err(|error| rebuild_error(path, error))?; + Ok(Arc::new(output)) + } + (DataType::Map(_, source_ordered), DataType::Map(output_field, output_ordered)) + if source_ordered == output_ordered => + { + let values = downcast::(array, path, "MapArray")?; + let entries: ArrayRef = Arc::new(values.entries().clone()); + let entries = rewrite_array(&entries, output_field.data_type(), path)?; + let entries = entries + .as_any() + .downcast_ref::() + .ok_or_else(|| { + Error::internal().message(format!( + "geospatial map rewrite for '{path}' did not produce StructArray entries" + )) + })? + .clone(); + let output = MapArray::try_new( + output_field.clone(), + values.offsets().clone(), + entries, + values.nulls().cloned(), + *output_ordered, + ) + .map_err(|error| rebuild_error(path, error))?; + Ok(Arc::new(output)) + } + (source, output) if source == output => Ok(array.clone()), + (source, output) => Err(Error::internal().message(format!( + "geospatial rewrite for '{path}' cannot map Arrow type {source:?} to {output:?}" + ))), + } +} + +fn downcast<'a, T: 'static>(array: &'a ArrayRef, path: &str, expected: &str) -> Result<&'a T> { + array.as_any().downcast_ref::().ok_or_else(|| { + Error::data_loss().message(format!( + "geospatial value '{path}' advertised {expected} but supplied {:?}", + array.data_type() + )) + }) +} + +fn rebuild_error(path: &str, error: arrow_schema::ArrowError) -> Error { + Error::data_loss().message(format!( + "failed to rebuild Arrow container '{path}' after geospatial reconciliation: {error}" + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::builder::{BinaryBuilder, Int32Builder}; + use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; + use std::collections::HashMap; + + const POINT_1_2_WKB: &[u8] = &[ + 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 0, 0, 64, + ]; + + fn geo_type(family: GeoFamily, type_srid: i32) -> DataType { + let family_key = match family { + GeoFamily::Geometry => "geometry", + GeoFamily::Geography => "geography", + }; + DataType::Struct(Fields::from(vec![ + Field::new("srid", DataType::Int32, false), + Field::new("wkb", DataType::Binary, false).with_metadata(HashMap::from([ + (family_key.to_string(), "true".to_string()), + ("srid".to_string(), type_srid.to_string()), + ])), + ])) + } + + fn plain_geo_type() -> DataType { + DataType::Struct(Fields::from(vec![ + Field::new("srid", DataType::Int32, false), + Field::new("wkb", DataType::Binary, false), + ])) + } + + fn nullable_plain_geo_type() -> DataType { + DataType::Struct(Fields::from(vec![ + Field::new("srid", DataType::Int32, true), + Field::new("wkb", DataType::Binary, true), + ])) + } + + fn geo_array(family: GeoFamily, type_srid: i32, row_srid: i32) -> ArrayRef { + let DataType::Struct(fields) = geo_type(family, type_srid) else { + unreachable!() + }; + let mut srids = Int32Builder::new(); + srids.append_value(row_srid); + srids.append_value(0); + let mut wkbs = BinaryBuilder::new(); + wkbs.append_value(POINT_1_2_WKB); + wkbs.append_value([]); + Arc::new(StructArray::new( + fields, + vec![Arc::new(srids.finish()), Arc::new(wkbs.finish())], + Some(NullBuffer::from(vec![true, false])), + )) + } + + #[test] + fn recognizes_only_canonical_tagged_structs() { + assert_eq!( + native_geo_tag(&geo_type(GeoFamily::Geometry, -1)) + .unwrap() + .map(|tag| tag.family), + Some(GeoFamily::Geometry) + ); + assert_eq!( + native_geo_tag(&geo_type(GeoFamily::Geography, 4326)) + .unwrap() + .map(|tag| tag.family), + Some(GeoFamily::Geography) + ); + + let plain = plain_geo_type(); + assert_eq!(native_geo_tag(&plain).unwrap(), None); + } + + #[test] + fn logical_geo_identifies_an_untagged_payload_and_validates_existing_tags() { + let physical = Field::new("g", plain_geo_type(), true); + let logical = Field::new("g", geo_type(GeoFamily::Geometry, -1), true); + + let binary = plan(&physical, Some(&logical)).unwrap().unwrap(); + assert!(binary.needs_rewrite); + assert_eq!(binary.output_type, logical.data_type().clone()); + + let already_tagged = Field::new("g", geo_type(GeoFamily::Geometry, -1), true); + let binary = plan(&already_tagged, Some(&logical)).unwrap().unwrap(); + assert!(!binary.needs_rewrite); + assert_eq!(binary.output_type, logical.data_type().clone()); + + let fallback = plan(&already_tagged, None).unwrap().unwrap(); + assert!(!fallback.needs_rewrite); + assert_eq!(fallback.output_type, already_tagged.data_type().clone()); + + let wrong_family = Field::new("g", geo_type(GeoFamily::Geography, -1), true); + let error = plan(&wrong_family, Some(&logical)).unwrap_err(); + assert!(error.message.contains("tagged GEOGRAPHY")); + + let logical_plain = Field::new("g", plain_geo_type(), true); + let error = plan(&already_tagged, Some(&logical_plain)).unwrap_err(); + assert!(error.message.contains("logical manifest type")); + + let bad_shape = Field::new("g", DataType::Utf8, true); + assert!(plan(&bad_shape, Some(&logical)).unwrap().is_none()); + + assert!(plan(&physical, None).unwrap().is_none()); + } + + #[test] + fn binary_rewrite_attaches_logical_tags_without_copying_children() { + let tagged = geo_array(GeoFamily::Geometry, -1, 4326); + let tagged = tagged.as_any().downcast_ref::().unwrap(); + let DataType::Struct(plain_fields) = nullable_plain_geo_type() else { + unreachable!() + }; + let plain: ArrayRef = Arc::new(StructArray::new( + plain_fields, + tagged.columns().to_vec(), + tagged.nulls().cloned(), + )); + let output_type = geo_type(GeoFamily::Geometry, -1); + let output = rewrite(&plain, &output_type, "g").unwrap(); + let output = output.as_any().downcast_ref::().unwrap(); + assert!(Arc::ptr_eq(output.column(0), tagged.column(0))); + assert!(Arc::ptr_eq(output.column(1), tagged.column(1))); + assert_eq!(output.data_type(), &output_type); + + let DataType::Struct(output_fields) = output.data_type() else { + unreachable!() + }; + assert!(!output_fields[0].is_nullable()); + assert!(!output_fields[1].is_nullable()); + } + + #[test] + fn nested_geo_rewrite_attaches_tags_and_preserves_buffers_and_nulls() { + let tagged = geo_array(GeoFamily::Geometry, -1, 4326); + let tagged = tagged.as_any().downcast_ref::().unwrap(); + let DataType::Struct(plain_fields) = plain_geo_type() else { + unreachable!() + }; + let plain_values: ArrayRef = Arc::new(StructArray::new( + plain_fields, + tagged.columns().to_vec(), + tagged.nulls().cloned(), + )); + let list = ListArray::new( + Arc::new(Field::new("item", plain_geo_type(), true)), + OffsetBuffer::new(ScalarBuffer::from(vec![0_i32, 2])), + plain_values, + None, + ); + let physical = Field::new("values", list.data_type().clone(), true); + let logical_type = DataType::List(Arc::new(Field::new( + "item", + geo_type(GeoFamily::Geometry, -1), + true, + ))); + let logical = Field::new("values", logical_type, true); + + let plan = plan(&physical, Some(&logical)).unwrap().unwrap(); + assert!(plan.needs_rewrite); + let output = rewrite(&(Arc::new(list) as ArrayRef), &plan.output_type, "values").unwrap(); + let output = output.as_any().downcast_ref::().unwrap(); + let values = output + .values() + .as_any() + .downcast_ref::() + .unwrap(); + let DataType::Struct(fields) = values.data_type() else { + panic!("nested geometry must remain a struct") + }; + assert_eq!( + fields[1].metadata().get("geometry").map(String::as_str), + Some("true") + ); + assert!(Arc::ptr_eq(values.column(0), tagged.column(0))); + assert!(Arc::ptr_eq(values.column(1), tagged.column(1))); + assert!(values.is_null(1)); + } +} diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 6d57e6be..f68f06f9 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -33,6 +33,7 @@ //! //! See `docs/designs/complex-types-json-stringify.md` for the design. +mod geospatial; mod json; use crate::kernel_error::{Error, Result}; @@ -109,34 +110,59 @@ impl ResultPostProcessor { Some(m) => ResultReaderAdapter::augment_schema_with_manifest(&inner_schema, m), None => inner_schema.clone(), }; + let logical_schema = match manifest { + Some(manifest) => Some( + super::ResultReaderFactory::extract_logical_schema_from_manifest(Some(manifest))?, + ), + None => None, + }; - // 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. + // 2. Compute the normalized schema and the set of per-column + // rewrites. Geo metadata reconciliation runs first because a geo + // leaf may be nested inside a complex column that is subsequently + // rendered as JSON. 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 geospatial_columns: Vec = Vec::new(); + let mut normalized_fields: Vec = Vec::with_capacity(augmented_schema.fields().len()); + let mut output_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) { + let logical_field = logical_schema + .as_ref() + .and_then(|schema| schema.fields().get(i)) + .map(|field| field.as_ref()); + let geo_plan = geospatial::plan(field, logical_field)?; + let (normalized_field, is_top_level_geo) = match geo_plan { + Some(plan) => { + if plan.needs_rewrite { + schema_changed = true; + geospatial_columns.push(i); + } + ( + field.as_ref().clone().with_data_type(plan.output_type), + plan.is_top_level_geo, + ) + } + None => (field.as_ref().clone(), false), + }; + + let normalized_type = normalized_field.data_type(); + let output_field = if options.complex_types_as_json + && !is_top_level_geo + && json::is_complex_type(normalized_type) + { 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) { + Field::new(field.name(), DataType::Utf8, true) + .with_metadata(field.metadata().clone()) + } else if options.intervals_as_string && is_interval_or_duration_type(normalized_type) { 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 if matches!(dt, DataType::Null) { + Field::new(field.name(), DataType::Utf8, true) + .with_metadata(field.metadata().clone()) + } else if matches!(normalized_type, 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`, @@ -148,17 +174,26 @@ impl ResultPostProcessor { // 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; + Field::new(field.name(), DataType::Utf8, true) + .with_metadata(field.metadata().clone()) } else { - new_fields.push(field.as_ref().clone()); - } + normalized_field.clone() + }; + normalized_fields.push(normalized_field); + output_fields.push(output_field); } + let normalized_schema: SchemaRef = if geospatial_columns.is_empty() { + augmented_schema.clone() + } else { + Arc::new(Schema::new_with_metadata( + normalized_fields, + augmented_schema.metadata().clone(), + )) + }; let output_schema: SchemaRef = if schema_changed { Arc::new(Schema::new_with_metadata( - new_fields, + output_fields, augmented_schema.metadata().clone(), )) } else { @@ -179,8 +214,10 @@ 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() || !null_columns.is_empty(); + let has_rewrites = !geospatial_columns.is_empty() + || !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 { @@ -201,15 +238,17 @@ impl ResultPostProcessor { // (interval path). Captures only what each closure // invocation actually needs. let target_schema = output_schema.clone(); - let augmented = augmented_schema.clone(); + let normalized = normalized_schema.clone(); let json_cols: Vec = json_columns; let interval_cols: Vec = interval_columns; let null_cols: Vec = null_columns; + let geo_cols: Vec = geospatial_columns; Some(Box::new(move |batch: &RecordBatch| { build_rewritten_batch( batch, - &augmented, + &normalized, &target_schema, + &geo_cols, &json_cols, &interval_cols, &null_cols, @@ -264,23 +303,21 @@ fn schemas_field_equal(a: &SchemaRef, b: &SchemaRef) -> bool { && a.metadata() == b.metadata() } -/// 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, interval / duration -/// columns (indexed by `interval_cols`) are replaced with `Utf8` -/// 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). +/// Build a `RecordBatch` whose tagged geo values are first recursively +/// normalized, complex columns (indexed by `json_cols`) are replaced with +/// `Utf8` arrays of compact JSON text, interval / duration columns (indexed by +/// `interval_cols`) are replaced with canonical Databricks text, and untyped +/// NULL columns (indexed by `null_cols`) become all-null `Utf8` arrays. /// -/// `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). +/// All index sets are sorted. `geo_cols` may overlap `json_cols` when a +/// complex column contains a geo leaf; geo normalization intentionally runs +/// first so JSON sees the normalized nested schema and values. The other +/// rewrite sets are pairwise disjoint. fn build_rewritten_batch( batch: &RecordBatch, - augmented: &SchemaRef, + normalized: &SchemaRef, output: &SchemaRef, + geo_cols: &[usize], json_cols: &[usize], interval_cols: &[usize], null_cols: &[usize], @@ -288,10 +325,22 @@ fn build_rewritten_batch( let num_rows = batch.num_rows(); let mut columns: Vec = Vec::with_capacity(batch.num_columns()); + let mut next_geo_idx = 0; 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 normalized_field = normalized.fields().get(col_idx).ok_or_else(|| { + Error::internal().message(format!( + "ResultPostProcessor: upstream batch has {} columns but normalized schema only has {}", + batch.num_columns(), + normalized.fields().len() + )) + })?; + let is_geo = geo_cols + .get(next_geo_idx) + .copied() + .is_some_and(|target| target == col_idx); let is_json = json_cols .get(next_json_idx) .copied() @@ -304,21 +353,20 @@ fn build_rewritten_batch( .get(next_null_idx) .copied() .is_some_and(|target| target == col_idx); + + let column = if is_geo { + next_geo_idx += 1; + geospatial::rewrite( + column, + normalized_field.data_type(), + normalized_field.name(), + )? + } else { + column.clone() + }; + if is_json { next_json_idx += 1; - // Use the augmented field (carries databricks.* metadata) - // so the per-row encoder can see VARIANT / GEOMETRY / - // GEOGRAPHY hints if they ever apply to a complex column. - // Guard against an upstream batch that has more columns - // than the schema it advertised — `Schema::field` would - // panic; we want a typed `Error::internal` instead. - let field = augmented.fields().get(col_idx).ok_or_else(|| { - Error::internal().message(format!( - "ResultPostProcessor: upstream batch has {} columns but advertised schema only has {}", - batch.num_columns(), - augmented.fields().len() - )) - })?; let mut builder = StringBuilder::with_capacity(num_rows, num_rows * 16); let mut scratch = String::new(); for row in 0..num_rows { @@ -327,7 +375,12 @@ fn build_rewritten_batch( continue; } scratch.clear(); - json::append_json(&mut scratch, column.as_ref(), row, field.as_ref())?; + json::append_json( + &mut scratch, + column.as_ref(), + row, + normalized_field.as_ref(), + )?; builder.append_value(&scratch); } columns.push(Arc::new(builder.finish())); @@ -359,7 +412,7 @@ fn build_rewritten_batch( // 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()); + columns.push(column); } } @@ -383,8 +436,11 @@ mod tests { use crate::reader::test_utils::MockReader; use crate::reader::ResultReader; use crate::types::sea::{ColumnInfo, ResultSchema}; - use arrow_array::builder::{ListBuilder, MapBuilder, StringBuilder}; + use arrow_array::builder::{ + BinaryBuilder, Int32Builder, ListBuilder, MapBuilder, StringBuilder, + }; use arrow_array::{Array, Int32Array, StringArray, StructArray}; + use arrow_buffer::NullBuffer; use arrow_schema::Fields; fn make_manifest(columns: Vec) -> ResultManifest { @@ -394,6 +450,7 @@ mod tests { column_count: columns.len() as i32, columns, }, + arrow_schema: None, total_chunk_count: None, total_row_count: None, total_byte_count: None, @@ -416,6 +473,41 @@ mod tests { } } + const POINT_1_2_WKB: &[u8] = &[ + 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 0, 0, 64, + ]; + + fn untagged_geo_values(row_srids: &[Option]) -> ArrayRef { + let fields = Fields::from(vec![ + Field::new("srid", DataType::Int32, false), + Field::new("wkb", DataType::Binary, false), + ]); + let mut srids = Int32Builder::new(); + let mut wkbs = BinaryBuilder::new(); + let mut validity = Vec::with_capacity(row_srids.len()); + for row_srid in row_srids { + match row_srid { + Some(srid) => { + srids.append_value(*srid); + wkbs.append_value(POINT_1_2_WKB); + validity.push(true); + } + None => { + // Non-null children carry placeholders masked by the null + // outer struct, matching Reyden's encoding. + srids.append_value(0); + wkbs.append_value([]); + validity.push(false); + } + } + } + Arc::new(StructArray::new( + fields, + vec![Arc::new(srids.finish()), Arc::new(wkbs.finish())], + Some(NullBuffer::from(validity)), + )) + } + #[tokio::test] async fn pass_through_when_no_manifest_and_json_off() { let schema = Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, true)])); @@ -773,4 +865,47 @@ mod tests { let out = pp.next_batch().await.unwrap().unwrap(); assert_eq!(out.schema().field(0).data_type(), &list_dt); } + + #[tokio::test] + async fn geospatial_results_attach_tags_and_reuse_child_arrays() { + let geometry = untagged_geo_values(&[Some(4326)]); + let original = geometry + .as_any() + .downcast_ref::() + .unwrap() + .columns() + .to_vec(); + let schema = Arc::new(Schema::new(vec![Field::new( + "col_0", + geometry.data_type().clone(), + true, + )])); + let batch = RecordBatch::try_new(schema, vec![geometry]).unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + let manifest = make_manifest(vec![column_info("geom", "GEOMETRY", "GEOMETRY(ANY)", 0)]); + let mut pp = + ResultPostProcessor::new(inner, Some(&manifest), PostProcessOptions::default()) + .await + .unwrap(); + let out = pp.next_batch().await.unwrap().unwrap(); + let values = out + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(Arc::ptr_eq(values.column(0), &original[0])); + assert!(Arc::ptr_eq(values.column(1), &original[1])); + let schema = out.schema(); + let DataType::Struct(fields) = schema.field(0).data_type() else { + panic!("binary geometry must remain a struct") + }; + assert_eq!( + fields[1].metadata().get("geometry").map(String::as_str), + Some("true") + ); + assert_eq!( + fields[1].metadata().get("srid").map(String::as_str), + Some("-1") + ); + } } diff --git a/src/types/sea.rs b/src/types/sea.rs index 8104865c..8d877c0c 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -170,6 +170,14 @@ pub struct ServiceError { pub struct ResultManifest { pub format: String, pub schema: ResultSchema, + /// Physical Arrow schema carried by SEA as a schema-only IPC stream. + /// + /// Reyder deliberately keeps this schema aligned with result attachments. + /// It can therefore differ from the logical [`ResultSchema`]: native + /// geospatial attachments use an untagged `struct`, while the + /// structured schema still declares `GEOMETRY` / `GEOGRAPHY`. + #[serde(default, deserialize_with = "deserialize_base64_attachment")] + pub arrow_schema: Option>, #[serde(default)] pub total_chunk_count: Option, #[serde(default)] diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 7e64c03b..9bffb18f 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -20,16 +20,21 @@ //! Session::open → Statement::execute → ExecutedStatement → //! ResultStream::next_batch → Row accessors. +use arrow_array::builder::{BinaryBuilder, Int32Builder}; use arrow_array::cast::AsArray; -use arrow_array::{Int64Array, RecordBatch, StringArray}; +use arrow_array::{ + Array, BinaryArray, Int32Array, Int64Array, RecordBatch, StringArray, StructArray, +}; +use arrow_buffer::NullBuffer; use arrow_ipc::writer::StreamWriter; -use arrow_schema::{DataType, Field, Schema}; +use arrow_schema::{DataType, Field, Fields, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, HttpConfig, ResultBatch, ResultConfig, Session, TypedValue, MAX_CLIENT_QUERY_TIMEOUT, }; use serde_json::json; +use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -144,6 +149,13 @@ fn arrow_ipc_bytes(batch: &RecordBatch) -> Vec { buf } +fn arrow_schema_ipc_bytes(schema: &Schema) -> Vec { + let mut buf = Vec::new(); + let mut writer = StreamWriter::try_new(&mut buf, schema).unwrap(); + writer.finish().unwrap(); + buf +} + fn succeeded_inline_body(statement_id: &str, batch: &RecordBatch) -> String { let ipc = arrow_ipc_bytes(batch); let attachment = STANDARD.encode(&ipc); @@ -352,6 +364,205 @@ fn str_batch(name: &str, values: Vec<&str>) -> RecordBatch { RecordBatch::try_new(schema, vec![Arc::new(StringArray::from(values))]).unwrap() } +const POINT_1_2_WKB: &[u8] = &[ + 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 0, 0, 64, +]; + +fn geospatial_type(family: &str, type_srid: i32) -> DataType { + DataType::Struct(Fields::from(vec![ + Field::new("srid", DataType::Int32, false), + Field::new("wkb", DataType::Binary, false).with_metadata(HashMap::from([ + (family.to_string(), "true".to_string()), + ("srid".to_string(), type_srid.to_string()), + ])), + ])) +} + +fn untagged_geospatial_type() -> DataType { + DataType::Struct(Fields::from(vec![ + Field::new("srid", DataType::Int32, true), + Field::new("wkb", DataType::Binary, true), + ])) +} + +fn geospatial_array(row_srid: i32) -> Arc { + let DataType::Struct(fields) = untagged_geospatial_type() else { + unreachable!() + }; + let mut srids = Int32Builder::new(); + srids.append_value(row_srid); + srids.append_value(0); + let mut wkbs = BinaryBuilder::new(); + wkbs.append_value(POINT_1_2_WKB); + wkbs.append_value([]); + Arc::new(StructArray::new( + fields, + vec![Arc::new(srids.finish()), Arc::new(wkbs.finish())], + Some(NullBuffer::from(vec![true, false])), + )) +} + +fn geospatial_batch() -> RecordBatch { + // Reyden's result projection emits nullable physical children without + // logical geo tags. Reyder retains the canonical geo identity in the + // structured manifest schema below. + let geometry = geospatial_array(3857); + let geography = geospatial_array(4326); + let schema = Arc::new(Schema::new(vec![ + Field::new("col_0", geometry.data_type().clone(), true), + Field::new("col_1", geography.data_type().clone(), true), + ])); + RecordBatch::try_new(schema, vec![geometry, geography]).unwrap() +} + +fn legacy_geospatial_batch() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("col_0", DataType::Utf8, true), + Field::new("col_1", DataType::Utf8, true), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec![Some("SRID=3857;POINT (1 2)"), None])) as _, + Arc::new(StringArray::from(vec![Some("SRID=4326;POINT (1 2)"), None])) as _, + ], + ) + .unwrap() +} + +fn logical_geospatial_schema() -> Schema { + Schema::new(vec![ + Field::new("geom", geospatial_type("geometry", -1), true), + Field::new("geog", geospatial_type("geography", 4326), true), + ]) +} + +fn succeeded_geospatial_inline_body(statement_id: &str, batch: &RecordBatch) -> String { + let ipc = arrow_ipc_bytes(batch); + let logical_schema = arrow_schema_ipc_bytes(&logical_geospatial_schema()); + json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 2, + "columns": [ + { + "name": "geom", + "type_name": "GEOMETRY", + "type_text": "GEOMETRY(ANY)", + "position": 0, + }, + { + "name": "geog", + "type_name": "GEOGRAPHY", + "type_text": "GEOGRAPHY(4326)", + "position": 1, + } + ], + }, + "arrow_schema": STANDARD.encode(logical_schema), + "total_chunk_count": 1, + "total_row_count": batch.num_rows() as i64, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows() as i64, + "byte_count": ipc.len() as i64, + "attachment": STANDARD.encode(&ipc), + }, + }) + .to_string() +} + +fn succeeded_empty_geospatial_body(statement_id: &str) -> String { + let logical_schema = arrow_schema_ipc_bytes(&logical_geospatial_schema()); + json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 2, + "columns": [ + { + "name": "geom", + "type_name": "GEOMETRY", + "type_text": "GEOMETRY(ANY)", + "position": 0, + }, + { + "name": "geog", + "type_name": "GEOGRAPHY", + "type_text": "GEOGRAPHY(4326)", + "position": 1, + } + ], + }, + "arrow_schema": STANDARD.encode(logical_schema), + "total_chunk_count": 0, + "total_row_count": 0, + "total_byte_count": 0, + "truncated": false, + }, + }) + .to_string() +} + +fn succeeded_legacy_geospatial_body( + statement_id: &str, + batch: &RecordBatch, + include_rows: bool, +) -> String { + let ipc = arrow_ipc_bytes(batch); + let physical_schema = arrow_schema_ipc_bytes(batch.schema().as_ref()); + let total_chunks = i32::from(include_rows); + let total_rows = if include_rows { batch.num_rows() } else { 0 }; + let mut body = json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 2, + "columns": [ + { + "name": "geom", + "type_name": "GEOMETRY", + "type_text": "GEOMETRY(ANY)", + "position": 0, + }, + { + "name": "geog", + "type_name": "GEOGRAPHY", + "type_text": "GEOGRAPHY(4326)", + "position": 1, + } + ], + }, + "arrow_schema": STANDARD.encode(physical_schema), + "total_chunk_count": total_chunks, + "total_row_count": total_rows, + "total_byte_count": if include_rows { ipc.len() } else { 0 }, + "truncated": false, + }, + }); + if include_rows { + body["result"] = json!({ + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows(), + "byte_count": ipc.len(), + "attachment": STANDARD.encode(&ipc), + }); + } + body.to_string() +} + async fn drain(stream: &mut databricks_sql_kernel::ResultStream) -> Vec { let mut out = Vec::new(); while let Some(batch) = stream.next_batch().await.expect("next_batch") { @@ -399,6 +610,272 @@ async fn execute_succeeded_inline_returns_one_row() { exec.close().await.expect("close"); } +#[tokio::test] +async fn execute_geospatial_applies_manifest_tags_to_arrow_ipc() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let batch = geospatial_batch(); + mount_execute( + &server, + succeeded_geospatial_inline_body("stmt-geo-binary", &batch), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT geom, geog FROM geo_values"); + let mut exec = stmt.execute().await.expect("execute"); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches.len(), 1); + let out = &batches[0]; + + let geometry = out + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + geometry + .column_by_name("srid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 3857 + ); + assert_eq!( + geometry + .column_by_name("wkb") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + POINT_1_2_WKB + ); + assert!(geometry.is_null(1)); + + let schema = out.schema(); + let DataType::Struct(geometry_fields) = schema.field(0).data_type() else { + panic!("geometry must stay a tagged struct") + }; + assert_eq!( + geometry_fields[1] + .metadata() + .get("geometry") + .map(String::as_str), + Some("true") + ); + assert_eq!( + geometry_fields[1] + .metadata() + .get("srid") + .map(String::as_str), + Some("-1") + ); + let DataType::Struct(geography_fields) = schema.field(1).data_type() else { + panic!("geography must stay a tagged struct") + }; + assert_eq!( + geography_fields[1] + .metadata() + .get("geography") + .map(String::as_str), + Some("true") + ); + assert_eq!( + geography_fields[1] + .metadata() + .get("srid") + .map(String::as_str), + Some("4326") + ); + exec.close().await.expect("close"); +} + +#[tokio::test] +async fn execute_legacy_geospatial_text_is_preserved() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let batch = legacy_geospatial_batch(); + mount_execute( + &server, + succeeded_legacy_geospatial_body("stmt-legacy-geo", &batch, true), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT geom, geog FROM legacy_geo_values"); + let mut exec = stmt.execute().await.expect("execute"); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches.len(), 1); + let output = &batches[0]; + assert_eq!(output.schema().field(0).data_type(), &DataType::Utf8); + assert_eq!(output.schema().field(1).data_type(), &DataType::Utf8); + assert_eq!( + output.column(0).as_string::().value(0), + "SRID=3857;POINT (1 2)" + ); + assert!(output.column(0).is_null(1)); + exec.close().await.expect("close"); +} + +#[tokio::test] +async fn execute_cloudfetch_geospatial_reconciles_manifest_and_untagged_payload() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let statement_id = "stmt-cloud-geo-binary"; + let chunk_path = format!("/cloud-fetch/{statement_id}/chunk-0.arrow"); + let chunk_url = format!("{}{}", server.uri(), chunk_path); + let batch = geospatial_batch(); + let ipc = arrow_ipc_bytes(&batch); + // CloudFetch preserves the physical (currently untagged) IPC schema in + // manifest.arrow_schema. The structured manifest schema remains the + // logical source of GEOMETRY / GEOGRAPHY identity. + let physical_schema = arrow_schema_ipc_bytes(batch.schema().as_ref()); + let execute_body = json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 2, + "columns": [ + { + "name": "geom", + "type_name": "GEOMETRY", + "type_text": "GEOMETRY(ANY)", + "position": 0, + }, + { + "name": "geog", + "type_name": "GEOGRAPHY", + "type_text": "GEOGRAPHY(4326)", + "position": 1, + } + ], + }, + "arrow_schema": STANDARD.encode(physical_schema), + "total_chunk_count": 1, + "total_row_count": batch.num_rows() as i64, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "external_links": [{ + "external_link": chunk_url, + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows() as i64, + "byte_count": ipc.len() as i64, + }], + }, + }) + .to_string(); + mount_execute(&server, execute_body).await; + Mock::given(method("GET")) + .and(path(chunk_path.as_str())) + .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc)) + .expect(1) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT geom, geog FROM geo_values"); + let mut exec = stmt.execute().await.expect("execute"); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches.len(), 1); + let schema = batches[0].schema(); + let DataType::Struct(fields) = schema.field(0).data_type() else { + panic!("binary geometry must be a tagged struct") + }; + assert_eq!( + fields[1].metadata().get("geometry").map(String::as_str), + Some("true") + ); + assert_eq!( + fields[1].metadata().get("srid").map(String::as_str), + Some("-1") + ); + exec.close().await.expect("close"); +} + +#[tokio::test] +async fn execute_empty_geospatial_result_has_the_requested_client_schema() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + mount_execute(&server, succeeded_empty_geospatial_body("stmt-empty-geo")).await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT geom, geog FROM empty_geo_values"); + let mut exec = stmt.execute().await.expect("execute"); + let schema = exec.schema(); + assert_eq!(schema.field(0).name(), "geom"); + assert_eq!(schema.field(1).name(), "geog"); + assert_eq!( + schema + .field(0) + .metadata() + .get("databricks.type_text") + .map(String::as_str), + Some("GEOMETRY(ANY)") + ); + + for (index, family, type_srid) in [(0, "geometry", "-1"), (1, "geography", "4326")] { + let DataType::Struct(fields) = schema.field(index).data_type() else { + panic!("binary geo field must use the tagged struct encoding") + }; + assert_eq!( + fields[1].metadata().get(family).map(String::as_str), + Some("true") + ); + assert_eq!( + fields[1].metadata().get("srid").map(String::as_str), + Some(type_srid) + ); + } + assert!(drain(exec.result_stream_mut()).await.is_empty()); + exec.close().await.expect("close"); +} + +#[tokio::test] +async fn execute_empty_legacy_geospatial_result_uses_physical_text_schema() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let batch = legacy_geospatial_batch(); + mount_execute( + &server, + succeeded_legacy_geospatial_body("stmt-empty-legacy-geo", &batch, false), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec() + .sql("SELECT geom, geog FROM empty_legacy_geo_values"); + let mut exec = stmt.execute().await.expect("execute"); + assert_eq!(exec.schema().field(0).data_type(), &DataType::Utf8); + assert_eq!(exec.schema().field(1).data_type(), &DataType::Utf8); + assert!(drain(exec.result_stream_mut()).await.is_empty()); + exec.close().await.expect("close"); +} + #[tokio::test] async fn execute_with_cloudfetch_enabled_sends_inline_or_external_links_disposition() { // Default (cloudfetch_enabled=true): the ExecuteStatement disposition