From 547dc96ad738ecd0bef620e2fe25ef82913b4603 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 24 Sep 2026 21:00:22 +0000 Subject: [PATCH] feat(results): add geospatial string representation Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- CONNECTION_PARAMETERS.md | 39 +- Cargo.lock | 120 +++++ Cargo.toml | 2 + NEXT_CHANGELOG.md | 3 + napi/Cargo.lock | 187 ++++++- pyo3/Cargo.lock | 203 +++++++- src/client/sea.rs | 2 + src/config.rs | 49 +- src/lib.rs | 5 +- src/metadata/type_mapping.rs | 164 +++++- src/reader/mod.rs | 16 +- src/reader/post_processor/geospatial.rs | 658 +++++++++++++++++++++--- src/reader/post_processor/json.rs | 21 +- src/reader/post_processor/mod.rs | 164 +++++- src/session.rs | 36 +- tests/v0_execute_wiremock.rs | 534 +++++++++++++------ tests/v0_session_wiremock.rs | 138 ++++- 17 files changed, 1976 insertions(+), 365 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2d312a49..b4dc22be 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -15,6 +15,7 @@ by the struct it lives on. `ConnectionConfig` and `AuthConfig` are | [`ProxyConfig`](#proxyconfig--httphttps-proxy-optional) | HTTP/HTTPS proxy | | [`TlsConfig`](#tlsconfig--tls--ssl-optional) | cert validation, custom CA, mTLS | | [`ResultConfig`](#resultconfig--result-handling-optional) | CloudFetch tuning, type rendering | +| [`geospatial_result_representation`](#geospatial_result_representation--geospatial-result-encoding-optional) | GEOMETRY / GEOGRAPHY result encoding | | [`LoggingConfig`](#loggingconfig--logging-optional) | log filter / file | | [`transport`](#transport--wire-protocol-optional) | wire protocol | | [`session_conf`](#session_conf--server-side-session-configuration-optional) | server-side SQL / Spark config | @@ -173,9 +174,45 @@ Setting only one of `client_cert_pem` / `client_key_pem` is rejected at | `cloudfetch_link_prefetch_window` | Number of presigned URLs to prefetch ahead of the consumer. | `10` | | `cloudfetch_max_chunks_in_memory` | Max decompressed CloudFetch chunks held in memory at once (bounds download parallelism and peak RSS). | `16` | | `inline_max_chunks_in_memory` | Prefetch window for the inline-Arrow path (used when CloudFetch is disabled). `1` disables prefetching. | `4` | -| `complex_types_as_json` | Render complex columns (`ARRAY` / `MAP` / `STRUCT` / `VARIANT` / `GEOMETRY` / `GEOGRAPHY`) as compact JSON strings instead of native Arrow nested types. | `false` | +| `complex_types_as_json` | Render complex columns (`ARRAY` / `MAP` / `STRUCT` / `VARIANT`) as compact JSON strings instead of native Arrow nested types. Top-level geo columns use `geospatial_result_representation`; nested geo leaves are normalized before the enclosing value is rendered as JSON. | `false` | | `intervals_as_string` | Render `INTERVAL` / `DURATION` columns as canonical Databricks text (e.g. `"Y-M"`, `"D HH:MM:SS.nnnnnnnnn"`) instead of native Arrow interval types. | `false` | +## `geospatial_result_representation` — geospatial result encoding (optional) + +Set with `SessionBuilder::geospatial_result_representation(...)`. Both modes +keep the outer result format as Arrow; this setting only selects the physical +Arrow representation of `GEOMETRY` and `GEOGRAPHY` values. + +| Value | Arrow representation | +|-------|----------------------| +| `GeospatialResultRepresentation::String` | Arrow `Utf8` containing EWKT (the default). | +| `GeospatialResultRepresentation::Binary` | Arrow `struct` containing the SRID and little-endian OGC WKB. The WKB itself is not EWKB. | + +Reyden returns every geo value as that native struct. The physical attachment +can omit the canonical Arrow tags, while Reyder's structured manifest reports +the logical `GEOMETRY(...)` or `GEOGRAPHY(...)` type and is the source of +truth. The kernel reconciles the attachment with that logical schema: binary +mode attaches `geometry=true` or `geography=true` and the type-level `srid` +(`-1` for `ANY`) to the `wkb` field, and string mode recursively converts the +WKB to EWKT. Every row's sibling `srid` carries the actual value. Nested values +in arrays, maps, and structs and null outer structs are preserved. + +On legacy SEA paths that already return geospatial columns as Arrow `Utf8`, +string mode preserves those values. Binary mode requires Reyden's native +`struct` attachment and returns an error when only text is available; +the kernel does not parse server-rendered text back into WKB. + +This is entirely client-side and is never forwarded to SEA. Set it through +the typed kernel or binding API. A `geospatial_as_string` entry placed +directly in `session_conf` is not interpreted by the kernel and is forwarded +unchanged; SEA/Reyden does not define that server configuration. + +The structured manifest type text is authoritative for identifying geo leaves; +the attachment supplies the physical values. The same post-processing step +produces the requested client-facing schema for non-empty and empty results. +Manifest field metadata preserves the logical type and SRID text under +`databricks.type_name` and `databricks.type_text`. + ## `LoggingConfig` — logging (optional) | Field | Description | Default | diff --git a/Cargo.lock b/Cargo.lock index a84b11de..7fa21427 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,6 +63,15 @@ dependencies = [ "libc", ] +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + [[package]] name = "arrow-array" version = "59.1.0" @@ -346,6 +355,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" @@ -634,6 +649,7 @@ dependencies = [ "dashmap", "dirs", "futures", + "geo-traits", "hex", "hmac 0.13.0", "jsonwebtoken", @@ -660,6 +676,7 @@ dependencies = [ "tracing", "tracing-subscriber", "wiremock", + "wkb", "zeroize", ] @@ -989,6 +1006,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "geo-traits" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e7c353d12a704ccfab1ba8bfb1a7fe6cb18b665bf89d37f4f7890edcd260206" +dependencies = [ + "geo-types", +] + +[[package]] +name = "geo-types" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "777d18aa0f12f8b285331cd867133ee14422b3f023f6d388034c47d43e28786a" +dependencies = [ + "approx", + "num-traits", + "serde", + "thiserror 2.0.19", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -1746,6 +1784,28 @@ dependencies = [ "libc", ] +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.118", +] + [[package]] name = "oauth2" version = "5.0.0" @@ -2003,6 +2063,15 @@ dependencies = [ "elliptic-curve", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -2892,6 +2961,36 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.15+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + [[package]] name = "tower" version = "0.5.3" @@ -3333,6 +3432,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "wiremock" version = "0.6.5" @@ -3362,6 +3470,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wkb" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a120b336c7ad17749026d50427c23d838ecb50cd64aaea6254b5030152f890a9" +dependencies = [ + "byteorder", + "geo-traits", + "num_enum", + "thiserror 1.0.69", +] + [[package]] name = "writeable" version = "0.6.3" diff --git a/Cargo.toml b/Cargo.toml index cc612131..04fc5867 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" base64 = "0.22" hex = "0.4" # Hex encoding (binary param literals, token cache key) +wkb = "0.9.2" # OGC WKB parser for geospatial result rendering +geo-traits = "0.3" # Generic geometry traversal for WKB-to-EWKT rendering # Date/time handling chrono = { version = "0.4", features = ["serde"] } diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index f39e12c7..380b525e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -17,6 +17,9 @@ changes go in their respective binding's NEXT_CHANGELOG. The kernel treats Reyder's structured logical manifest as authoritative and reconciles attachments that omit the canonical tags without copying child buffers. +- Added typed client-side `GEOMETRY` / `GEOGRAPHY` result representation + selection. String mode renders the native WKB as EWKT locally; binary mode + retains the tagged Arrow struct. No representation setting is sent to SEA. ### Changed diff --git a/napi/Cargo.lock b/napi/Cargo.lock index ab591591..39f6ea6c 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -63,6 +63,15 @@ dependencies = [ "libc", ] +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + [[package]] name = "arrow-array" version = "59.1.0" @@ -207,7 +216,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -292,6 +301,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" @@ -577,6 +592,7 @@ dependencies = [ "dashmap", "dirs", "futures", + "geo-traits", "hex", "hmac 0.13.0", "jsonwebtoken", @@ -590,11 +606,12 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", - "thiserror 2.0.18", + "thiserror 2.0.19", "tokio", "tokio-util", "tracing", "tracing-subscriber", + "wkb", "zeroize", ] @@ -706,7 +723,7 @@ checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -822,7 +839,7 @@ checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -864,6 +881,27 @@ dependencies = [ "version_check", ] +[[package]] +name = "geo-traits" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e7c353d12a704ccfab1ba8bfb1a7fe6cb18b665bf89d37f4f7890edcd260206" +dependencies = [ + "geo-types", +] + +[[package]] +name = "geo-types" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "777d18aa0f12f8b285331cd867133ee14422b3f023f6d388034c47d43e28786a" +dependencies = [ + "approx", + "num-traits", + "serde", + "thiserror 2.0.19", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -1506,7 +1544,7 @@ dependencies = [ "napi-derive-backend", "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -1519,7 +1557,7 @@ dependencies = [ "proc-macro2", "quote", "semver", - "syn", + "syn 2.0.118", ] [[package]] @@ -1600,6 +1638,28 @@ dependencies = [ "libc", ] +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.118", +] + [[package]] name = "oauth2" version = "5.0.0" @@ -1773,6 +1833,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -1796,7 +1865,7 @@ dependencies = [ "rustc-hash", "rustls", "socket2", - "thiserror 2.0.18", + "thiserror 2.0.19", "tokio", "tracing", "web-time", @@ -1818,7 +1887,7 @@ dependencies = [ "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror 2.0.19", "tinyvec", "tracing", "web-time", @@ -1932,7 +2001,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.17", "libredox", - "thiserror 2.0.18", + "thiserror 2.0.19", ] [[package]] @@ -2185,7 +2254,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2285,7 +2354,7 @@ checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" dependencies = [ "num-bigint", "num-traits", - "thiserror 2.0.18", + "thiserror 2.0.19", "time", ] @@ -2344,6 +2413,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -2361,7 +2441,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2375,11 +2455,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.19", ] [[package]] @@ -2390,18 +2470,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.3", ] [[package]] @@ -2502,7 +2582,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2528,6 +2608,36 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.15+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + [[package]] name = "tower" version = "0.5.3" @@ -2598,7 +2708,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2773,7 +2883,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 2.0.118", "wasm-bindgen-shared", ] @@ -2849,7 +2959,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2860,7 +2970,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2969,6 +3079,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "wiremock" version = "0.6.5" @@ -2998,6 +3117,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wkb" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a120b336c7ad17749026d50427c23d838ecb50cd64aaea6254b5030152f890a9" +dependencies = [ + "byteorder", + "geo-traits", + "num_enum", + "thiserror 1.0.69", +] + [[package]] name = "writeable" version = "0.6.3" @@ -3023,7 +3154,7 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", "synstructure", ] @@ -3044,7 +3175,7 @@ checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -3064,7 +3195,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", "synstructure", ] @@ -3104,7 +3235,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 277a55a8..b9ff31d6 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -63,6 +63,15 @@ dependencies = [ "libc", ] +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + [[package]] name = "arc-swap" version = "1.9.2" @@ -218,7 +227,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -303,6 +312,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" @@ -573,6 +588,7 @@ dependencies = [ "dashmap", "dirs", "futures", + "geo-traits", "hex", "hmac 0.13.0", "jsonwebtoken", @@ -586,11 +602,12 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", - "thiserror 2.0.18", + "thiserror 2.0.19", "tokio", "tokio-util", "tracing", "tracing-subscriber", + "wkb", "zeroize", ] @@ -679,9 +696,15 @@ checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "errno" version = "0.3.14" @@ -783,7 +806,7 @@ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -825,6 +848,27 @@ dependencies = [ "version_check", ] +[[package]] +name = "geo-traits" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e7c353d12a704ccfab1ba8bfb1a7fe6cb18b665bf89d37f4f7890edcd260206" +dependencies = [ + "geo-types", +] + +[[package]] +name = "geo-types" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "777d18aa0f12f8b285331cd867133ee14422b3f023f6d388034c47d43e28786a" +dependencies = [ + "approx", + "num-traits", + "serde", + "thiserror 2.0.19", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -1154,6 +1198,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + [[package]] name = "inout" version = "0.1.4" @@ -1440,6 +1494,28 @@ dependencies = [ "libm", ] +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.118", +] + [[package]] name = "oauth2" version = "5.0.0" @@ -1619,6 +1695,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -1681,7 +1766,7 @@ dependencies = [ "proc-macro2", "pyo3-macros-backend", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -1693,7 +1778,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -1710,7 +1795,7 @@ dependencies = [ "rustc-hash", "rustls", "socket2", - "thiserror 2.0.18", + "thiserror 2.0.19", "tokio", "tracing", "web-time", @@ -1732,7 +1817,7 @@ dependencies = [ "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror 2.0.19", "tinyvec", "tracing", "web-time", @@ -1846,7 +1931,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.17", "libredox", - "thiserror 2.0.18", + "thiserror 2.0.19", ] [[package]] @@ -2087,7 +2172,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2187,7 +2272,7 @@ checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" dependencies = [ "num-bigint", "num-traits", - "thiserror 2.0.18", + "thiserror 2.0.19", "time", ] @@ -2246,6 +2331,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -2263,7 +2359,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2283,11 +2379,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.19", ] [[package]] @@ -2298,18 +2394,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.3", ] [[package]] @@ -2410,7 +2506,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2436,6 +2532,36 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.15+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + [[package]] name = "tower" version = "0.5.3" @@ -2506,7 +2632,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2675,7 +2801,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 2.0.118", "wasm-bindgen-shared", ] @@ -2751,7 +2877,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2762,7 +2888,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2871,12 +2997,33 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wkb" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a120b336c7ad17749026d50427c23d838ecb50cd64aaea6254b5030152f890a9" +dependencies = [ + "byteorder", + "geo-traits", + "num_enum", + "thiserror 1.0.69", +] + [[package]] name = "writeable" version = "0.6.3" @@ -2902,7 +3049,7 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", "synstructure", ] @@ -2923,7 +3070,7 @@ checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -2943,7 +3090,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", "synstructure", ] @@ -2983,7 +3130,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] diff --git a/src/client/sea.rs b/src/client/sea.rs index dd31887e..2ff7f15e 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -1804,6 +1804,7 @@ mod tests { use crate::auth::PersonalAccessToken; use crate::client::retry::{build_retry_configs, RetryConfig}; use crate::client::HttpClientConfig; + use crate::config::GeospatialResultRepresentation; use crate::reader::post_processor::PostProcessOptions; use crate::result_stream::{ResultBatch, ResultStream}; use crate::types::cloudfetch::CloudFetchConfig; @@ -1851,6 +1852,7 @@ mod tests { http_client, CloudFetchConfig::default(), PostProcessOptions::default(), + GeospatialResultRepresentation::String, runtime_handle.clone(), ); transport.set_reader_factory(reader_factory, runtime_handle); diff --git a/src/config.rs b/src/config.rs index 16317627..defaae55 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1134,10 +1134,12 @@ pub struct ResultConfig { pub inline_max_chunks_in_memory: usize, /// When `true`, every column of complex type (`List` / - /// `LargeList` / `FixedSizeList` / `Map` / `Struct`, plus the - /// precise types `VARIANT` / `GEOMETRY` / `GEOGRAPHY` carried in - /// field metadata) is replaced with a `Utf8` column holding - /// compact JSON text per row. + /// `LargeList` / `FixedSizeList` / `Map` / `Struct`, plus the precise type + /// `VARIANT` carried in field metadata) is replaced with a `Utf8` column + /// holding compact JSON text per row. Top-level `GEOMETRY` / `GEOGRAPHY` + /// columns instead follow [`SessionConfig::geospatial_result_representation`]; + /// geo leaves nested inside a complex column are normalized before that + /// outer column is rendered as JSON. /// /// The JSON format matches what the Databricks server emits on /// the Thrift wire when `complexTypesAsArrow=false` (compact — @@ -1484,6 +1486,38 @@ pub enum TransportMode { SeaRest, } +// ─── Client-side result representation ───────────────────────────────────── + +/// Client-facing representation for geospatial values inside Arrow result +/// batches. +/// +/// The outer result format remains Arrow in both modes: +/// +/// - [`String`](Self::String) returns Arrow `Utf8` values containing EWKT. +/// - [`Binary`](Self::Binary) returns +/// `struct` values. +/// +/// This is a client-side result setting and is never sent to SEA. Reyden +/// returns `struct` values, and Reyder's structured manifest carries +/// their logical `GEOMETRY(...)` / `GEOGRAPHY(...)` types. The manifest is the +/// source of truth when an attachment omits the canonical tags. The kernel +/// reconciles the two, then exposes tagged binary values or recursively renders +/// EWKT strings. Legacy SEA paths that already return `Utf8` EWKT satisfy +/// string mode directly; requesting binary mode on such a path returns an +/// error because the original WKB cannot be recovered losslessly. Empty and +/// non-empty results use the same client-facing schema. +#[non_exhaustive] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum GeospatialResultRepresentation { + /// Arrow `Utf8` containing EWKT. This is the kernel default. + #[default] + String, + /// Arrow `struct` containing little-endian OGC + /// WKB. The SRID is carried by the sibling `srid` value, not by EWKB. + /// Requires the native Reyden Arrow result path. + Binary, +} + // ─── Assembled SessionConfig ──────────────────────────────────────────────── /// The fully-assembled session configuration consumed by `Session::open` @@ -1531,6 +1565,13 @@ pub struct SessionConfig { /// so non-canonical values flow to the server as-is. pub session_conf: HashMap, + /// Optional typed override for the physical representation of + /// `GEOMETRY` / `GEOGRAPHY` values in Arrow results. + /// + /// `None` uses [`GeospatialResultRepresentation::String`]. The + /// choice is applied locally and is not forwarded to SEA. + pub geospatial_result_representation: Option, + pub http: HttpConfig, pub proxy: Option, pub tls: TlsConfig, diff --git a/src/lib.rs b/src/lib.rs index b386628b..43938e3d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -127,8 +127,9 @@ pub mod c_abi; // === Public re-exports === pub use config::{ - AuthConfig, ConnectionConfig, DefaultOpts, HttpConfig, LoggingConfig, ProxyConfig, - ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, TransportMode, + AuthConfig, ConnectionConfig, DefaultOpts, GeospatialResultRepresentation, HttpConfig, + LoggingConfig, ProxyConfig, ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, + TokenCacheConfig, TransportMode, }; pub use kernel_error::{Error, ErrorCode, Result}; /// The `tracing` target string stamped on every kernel log event. diff --git a/src/metadata/type_mapping.rs b/src/metadata/type_mapping.rs index f6911fa5..4253a931 100644 --- a/src/metadata/type_mapping.rs +++ b/src/metadata/type_mapping.rs @@ -23,6 +23,7 @@ //! //! When adding a new type, update **both** mapping functions. +use crate::config::GeospatialResultRepresentation; use arrow_schema::{DataType, Field, Fields, IntervalUnit, TimeUnit}; use std::collections::HashMap; use std::sync::Arc; @@ -110,6 +111,11 @@ pub(crate) const JDBC_ARRAY: i16 = 2003; /// Unrecognised input falls back to `DataType::Utf8` rather than /// panicking; the kernel always returns *some* schema even when the /// type is unknown. +/// +/// `GEOMETRY` / `GEOGRAPHY` also default to `DataType::Utf8`: this public +/// mapping describes the string representation exposed by default, whose +/// values are rendered locally as EWKT. The result reader uses the internal +/// representation-aware mapper below when it needs the tagged binary schema. pub fn databricks_type_to_arrow(type_text: &str) -> DataType { databricks_type_to_arrow_with_interval(type_text, None) } @@ -125,11 +131,34 @@ pub fn databricks_type_to_arrow(type_text: &str) -> DataType { /// the parser falls back to the `type_text` itself, which for /// real SEA columns is `"INTERVAL YEAR TO MONTH"` / /// `"INTERVAL DAY TO SECOND"`. +/// +/// Like [`databricks_type_to_arrow`], this public helper maps geospatial +/// leaves to their default EWKT `DataType::Utf8` representation. pub fn databricks_type_to_arrow_with_interval( type_text: &str, type_interval_type: Option<&str>, ) -> DataType { - parse_type(type_text, type_interval_type, 0).unwrap_or(DataType::Utf8) + databricks_type_to_arrow_with_options( + type_text, + type_interval_type, + GeospatialResultRepresentation::String, + ) +} + +/// Manifest-aware mapping with an explicit physical representation for +/// `GEOMETRY` / `GEOGRAPHY` leaves. +/// +/// SEA's structured manifest reports the logical geospatial type. This mapper +/// reconstructs its tagged `struct` schema when binary output is +/// requested, including for attachments whose IPC schema omits the tags. The +/// choice is applied recursively through ARRAY / MAP / STRUCT type text. +pub(crate) fn databricks_type_to_arrow_with_options( + type_text: &str, + type_interval_type: Option<&str>, + geospatial_representation: GeospatialResultRepresentation, +) -> DataType { + parse_type(type_text, type_interval_type, geospatial_representation, 0) + .unwrap_or(DataType::Utf8) } /// Maximum depth of nested composite types we'll parse before @@ -147,7 +176,12 @@ const MAX_PARSE_DEPTH: usize = 64; /// only consulted at the `INTERVAL` arm — it has no meaning for /// nested composites, so passing it down is harmless and lets the /// caller specify it once. -fn parse_type(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option { +fn parse_type( + s: &str, + type_interval_type: Option<&str>, + geospatial_representation: GeospatialResultRepresentation, + depth: usize, +) -> Option { if depth >= MAX_PARSE_DEPTH { return None; } @@ -198,10 +232,28 @@ fn parse_type(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option } "TIMESTAMP_NTZ" => DataType::Timestamp(TimeUnit::Microsecond, None), "INTERVAL" => DataType::Interval(resolve_interval_unit(trimmed, type_interval_type)), - "ARRAY" => parse_array(trimmed, type_interval_type, depth)?, - "MAP" => parse_map(trimmed, type_interval_type, depth)?, - "STRUCT" => parse_struct(trimmed, type_interval_type, depth)?, - "GEOMETRY" | "GEOGRAPHY" => geospatial_binary_arrow_type(trimmed)?, + "ARRAY" => parse_array( + trimmed, + type_interval_type, + geospatial_representation, + depth, + )?, + "MAP" => parse_map( + trimmed, + type_interval_type, + geospatial_representation, + depth, + )?, + "STRUCT" => parse_struct( + trimmed, + type_interval_type, + geospatial_representation, + depth, + )?, + "GEOMETRY" | "GEOGRAPHY" => match geospatial_representation { + GeospatialResultRepresentation::String => DataType::Utf8, + GeospatialResultRepresentation::Binary => 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 @@ -282,9 +334,19 @@ fn split_top_level_commas(s: &str) -> Vec<&str> { /// `list_(t)` default also uses `"item"`. Using anything else would /// make the empty-result schema fail field-level equality against /// the non-empty Arrow IPC payload. -fn parse_array(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option { +fn parse_array( + s: &str, + type_interval_type: Option<&str>, + geospatial_representation: GeospatialResultRepresentation, + depth: usize, +) -> Option { let inner = inside_angle_brackets(s)?; - let inner_dt = parse_type(inner, type_interval_type, depth + 1)?; + let inner_dt = parse_type( + inner, + type_interval_type, + geospatial_representation, + depth + 1, + )?; Some(DataType::List(Arc::new(Field::new_list_field( inner_dt, true, )))) @@ -292,14 +354,29 @@ fn parse_array(s: &str, type_interval_type: Option<&str>, depth: usize) -> Optio /// Parse `MAP` into Arrow's canonical `Map(entries: Struct{key, value})`. /// Field names `"entries"` / `"key"` / `"value"` match pyarrow.map_(k, v). -fn parse_map(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option { +fn parse_map( + s: &str, + type_interval_type: Option<&str>, + geospatial_representation: GeospatialResultRepresentation, + depth: usize, +) -> Option { let inner = inside_angle_brackets(s)?; let parts = split_top_level_commas(inner); if parts.len() != 2 { return None; } - let key_dt = parse_type(parts[0], type_interval_type, depth + 1)?; - let val_dt = parse_type(parts[1], type_interval_type, depth + 1)?; + let key_dt = parse_type( + parts[0], + type_interval_type, + geospatial_representation, + depth + 1, + )?; + let val_dt = parse_type( + parts[1], + type_interval_type, + geospatial_representation, + depth + 1, + )?; let entries = Field::new( "entries", DataType::Struct(Fields::from(vec![ @@ -314,7 +391,12 @@ fn parse_map(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option< /// Parse `STRUCT` into `Struct(Fields::from([Field; N]))`. /// Each child field is nullable (SEA's manifest doesn't carry per-field /// nullability) — same convention used elsewhere in the kernel. -fn parse_struct(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option { +fn parse_struct( + s: &str, + type_interval_type: Option<&str>, + geospatial_representation: GeospatialResultRepresentation, + depth: usize, +) -> Option { let inner = inside_angle_brackets(s)?; if inner.is_empty() { return Some(DataType::Struct(Fields::empty())); @@ -330,7 +412,12 @@ fn parse_struct(s: &str, type_interval_type: Option<&str>, depth: usize) -> Opti if name.is_empty() { return None; } - let dt = parse_type(type_text, type_interval_type, depth + 1)?; + let dt = parse_type( + type_text, + type_interval_type, + geospatial_representation, + depth + 1, + )?; fields.push(Field::new(name, dt, true)); } Some(DataType::Struct(Fields::from(fields))) @@ -624,10 +711,34 @@ mod tests { } #[test] - fn test_geospatial_types_use_srid_wkb_struct() { + fn test_geospatial_types_default_to_ewkt_string() { + for type_text in [ + "GEOGRAPHY", + "GEOGRAPHY(4326)", + "GEOMETRY(ANY)", + "geometry(3857)", + ] { + assert_eq!( + databricks_type_to_arrow(type_text), + DataType::Utf8, + "{type_text}" + ); + } + } + + #[test] + fn test_geospatial_binary_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}"); + assert_eq!( + databricks_type_to_arrow_with_options( + type_text, + None, + GeospatialResultRepresentation::Binary, + ), + expected, + "{type_text}" + ); } let expected = geospatial_binary_arrow_type("GEOMETRY(ANY)").unwrap(); @@ -684,9 +795,17 @@ mod tests { } #[test] - fn test_geospatial_types_are_reconstructed_inside_nested_type_text() { - let binary = - databricks_type_to_arrow("STRUCT>"); + fn test_geospatial_representation_applies_to_nested_type_text() { + let binary = databricks_type_to_arrow_with_options( + "STRUCT>", + None, + GeospatialResultRepresentation::Binary, + ); + let string = databricks_type_to_arrow_with_options( + "STRUCT>", + None, + GeospatialResultRepresentation::String, + ); let DataType::Struct(binary_fields) = binary else { panic!("expected outer struct") @@ -702,6 +821,15 @@ mod tests { binary_items.data_type(), &geospatial_binary_arrow_type("GEOGRAPHY(4326)").unwrap() ); + + let DataType::Struct(string_fields) = string else { + panic!("expected outer struct") + }; + assert_eq!(string_fields[0].data_type(), &DataType::Utf8); + let DataType::List(string_items) = string_fields[1].data_type() else { + panic!("expected geography list") + }; + assert_eq!(string_items.data_type(), &DataType::Utf8); } #[test] diff --git a/src/reader/mod.rs b/src/reader/mod.rs index fd2eda7e..b7683e4d 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -26,6 +26,7 @@ pub mod post_processor; pub(crate) mod test_utils; use crate::client::{DatabricksHttpClient, ExecuteResponse, Transport}; +use crate::config::GeospatialResultRepresentation; use crate::kernel_error::{Error, Result}; use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; use crate::reader::cloudfetch::link_fetcher::{SeaChunkLinkFetcher, SeaChunkLinkFetcherHandle}; @@ -64,9 +65,11 @@ impl ResultReaderFactory { client: Arc, http_client: Arc, config: CloudFetchConfig, - post_process_options: PostProcessOptions, + mut post_process_options: PostProcessOptions, + geospatial_result_representation: GeospatialResultRepresentation, runtime_handle: tokio::runtime::Handle, ) -> Self { + post_process_options.geospatial_result_representation = geospatial_result_representation; Self { client, http_client, @@ -424,13 +427,15 @@ impl ResultReaderFactory { // `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. + // `struct` values. The physical schema comes from + // the attachment (or `manifest.arrow_schema` for an empty + // result); `ResultPostProcessor` reconciles it and applies the + // local string-vs-binary choice uniformly. let data_type = - crate::metadata::type_mapping::databricks_type_to_arrow_with_interval( + crate::metadata::type_mapping::databricks_type_to_arrow_with_options( &col.type_text, col.type_interval_type.as_deref(), + GeospatialResultRepresentation::Binary, ); Field::new(&col.name, data_type, true) // nullable by default }) @@ -1804,6 +1809,7 @@ mod tests { http_client, CloudFetchConfig::default(), PostProcessOptions::default(), + GeospatialResultRepresentation::String, runtime, ) } diff --git a/src/reader/post_processor/geospatial.rs b/src/reader/post_processor/geospatial.rs index 48e94894..6ec75d5c 100644 --- a/src/reader/post_processor/geospatial.rs +++ b/src/reader/post_processor/geospatial.rs @@ -12,21 +12,30 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Reconciliation of Reyden GEOMETRY / GEOGRAPHY Arrow results. +//! Local rendering 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. +//! contain the same struct without the canonical Arrow tags. This module uses +//! the logical schema to reconstruct the tags in binary mode without copying +//! child buffers, or to recursively render each declared geo value as EWKT in +//! string mode. +use crate::config::GeospatialResultRepresentation; use crate::kernel_error::{Error, Result}; +use arrow_array::builder::StringBuilder; use arrow_array::{ - Array, ArrayRef, FixedSizeListArray, LargeListArray, LargeListViewArray, ListArray, - ListViewArray, MapArray, StructArray, + Array, ArrayRef, BinaryArray, FixedSizeListArray, Int32Array, LargeListArray, + LargeListViewArray, ListArray, ListViewArray, MapArray, StructArray, }; use arrow_schema::{DataType, Field, FieldRef, Fields}; +use geo_traits::{ + CoordTrait, Dimensions, GeometryCollectionTrait, GeometryTrait, GeometryType, LineStringTrait, + MultiLineStringTrait, MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait, +}; +use std::fmt::Write as _; use std::sync::Arc; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -47,9 +56,9 @@ impl GeoFamily { /// Schema decision for a top-level result column. #[derive(Debug)] pub(super) struct GeoPlan { - /// Type after attaching canonical geo metadata recursively. + /// Type after applying the requested geo representation recursively. pub(super) output_type: DataType, - /// Whether the values need local tag attachment. + /// Whether the values need either local tag attachment or EWKT rendering. 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. @@ -76,10 +85,15 @@ struct TypePlan { /// `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> { +pub(super) fn plan( + field: &Field, + logical_field: Option<&Field>, + target: GeospatialResultRepresentation, +) -> Result> { let type_plan = plan_data_type( field.data_type(), logical_field.map(Field::data_type), + target, field.name(), )?; if !type_plan.contains_geo { @@ -94,8 +108,9 @@ pub(super) fn plan(field: &Field, logical_field: Option<&Field>) -> Result, path: &str) -> Result { +fn plan_data_type( + physical: &DataType, + logical: Option<&DataType>, + target: GeospatialResultRepresentation, + 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. + // DBR/legacy SEA paths can already serialize geo values as EWKT even + // though the structured manifest declares GEOMETRY / GEOGRAPHY. That + // satisfies string mode without another conversion. Binary mode must + // fail explicitly: an EWKT attachment cannot be losslessly turned back + // into Reyden's canonical `struct` representation here. if matches!(physical, DataType::Utf8 | DataType::LargeUtf8) { + if target == GeospatialResultRepresentation::Binary { + return Err(Error::not_implemented().message(format!( + "binary geospatial result representation is unavailable for '{path}': the server returned {physical:?}" + ))); + } return Ok(TypePlan { output_type: physical.clone(), - contains_geo: false, - is_root_geo: false, + contains_geo: true, + is_root_geo: true, }); } 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(); + let output_type = match target { + GeospatialResultRepresentation::String => DataType::Utf8, + GeospatialResultRepresentation::Binary => { + // The logical schema is canonical and contains the family and + // type-level SRID tags that can be missing from the payload. + logical.expect("logical_tag implies a logical type").clone() + } + }; return Ok(TypePlan { output_type, contains_geo: true, @@ -139,8 +170,12 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - actual.srid, ))); } + let output_type = match target { + GeospatialResultRepresentation::String => DataType::Utf8, + GeospatialResultRepresentation::Binary => physical.clone(), + }; return Ok(TypePlan { - output_type: physical.clone(), + output_type, contains_geo: true, is_root_geo: true, }); @@ -169,6 +204,7 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - let child = plan_data_type( field.data_type(), logical_field.map(|field| field.data_type()), + target, &child_path, )?; contains_geo |= child.contains_geo; @@ -190,6 +226,7 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - DataType::List(field) => Some(field.as_ref()), _ => None, }), + target, path, DataType::List, logical, @@ -200,6 +237,7 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - DataType::LargeList(field) => Some(field.as_ref()), _ => None, }), + target, path, DataType::LargeList, logical, @@ -210,6 +248,7 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - DataType::ListView(field) => Some(field.as_ref()), _ => None, }), + target, path, DataType::ListView, logical, @@ -220,6 +259,7 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - DataType::LargeListView(field) => Some(field.as_ref()), _ => None, }), + target, path, DataType::LargeListView, logical, @@ -234,6 +274,7 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - plan_nested_field( field, logical_field, + target, path, |field| DataType::FixedSizeList(field, *size), logical, @@ -249,6 +290,7 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - plan_nested_field( field, logical_field, + target, path, |field| DataType::Map(field, *ordered), logical, @@ -275,6 +317,7 @@ fn plan_data_type(physical: &DataType, logical: Option<&DataType>, path: &str) - fn plan_nested_field( physical_field: &FieldRef, logical_field: Option<&Field>, + target: GeospatialResultRepresentation, path: &str, constructor: impl FnOnce(FieldRef) -> DataType, logical_container: Option<&DataType>, @@ -287,6 +330,7 @@ fn plan_nested_field( let child = plan_data_type( physical_field.data_type(), logical_field.map(Field::data_type), + target, path, )?; let output_field = if &child.output_type == physical_field.data_type() { @@ -347,7 +391,7 @@ fn contains_tagged_geo(data_type: &DataType) -> Result { fn unsupported_container(data_type: &DataType) -> Result { Err(Error::not_implemented().message(format!( - "geospatial metadata reconciliation is not implemented for Arrow container {data_type:?}" + "geospatial EWKT conversion is not implemented for Arrow container {data_type:?}" ))) } @@ -430,6 +474,10 @@ fn native_geo_tag(data_type: &DataType) -> Result> { })) } +fn native_geo_family(data_type: &DataType) -> Result> { + Ok(native_geo_tag(data_type)?.map(|tag| tag.family)) +} + 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)?; @@ -449,6 +497,16 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result return Ok(Arc::new(output)); } + if output_type == &DataType::Utf8 && is_geo_struct_shape(array.data_type()) { + return native_to_ewkt(array, path); + } + + if native_geo_family(array.data_type())?.is_some() { + return Err(Error::internal().message(format!( + "geospatial rewrite for '{path}' planned unexpected output type {output_type:?}" + ))); + } + match (array.data_type(), output_type) { (DataType::Struct(source_fields), DataType::Struct(output_fields)) => { let values = downcast::(array, path, "StructArray")?; @@ -567,6 +625,340 @@ fn rewrite_array(array: &ArrayRef, output_type: &DataType, path: &str) -> Result } } +fn native_to_ewkt(array: &ArrayRef, path: &str) -> Result { + let values = downcast::(array, path, "StructArray")?; + let srids = values + .column_by_name("srid") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(|| malformed_native(path, "missing Int32 child 'srid'"))?; + let wkbs = values + .column_by_name("wkb") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(|| malformed_native(path, "missing Binary child 'wkb'"))?; + + let mut output = StringBuilder::with_capacity(values.len(), values.len() * 32); + for row in 0..values.len() { + if values.is_null(row) { + output.append_null(); + continue; + } + if srids.is_null(row) || wkbs.is_null(row) { + return Err(malformed_native( + path, + &format!("row {row} has a null child under a non-null struct"), + )); + } + + let geometry = wkb::reader::read_wkb(wkbs.value(row)).map_err(|error| { + Error::data_loss().message(format!( + "geospatial value '{path}' row {row} contains invalid WKB: {error}" + )) + })?; + let mut ewkt = String::new(); + let srid = srids.value(row); + if srid != 0 { + write!(&mut ewkt, "SRID={srid};").expect("writing to String is infallible"); + } + write_ogc_wkt(&mut ewkt, &geometry).map_err(|error| { + Error::data_loss().message(format!( + "geospatial value '{path}' row {row} could not be rendered as WKT: {error}" + )) + })?; + output.append_value(ewkt); + } + Ok(Arc::new(output.finish()) as ArrayRef) +} + +/// Error from rendering an already-validated WKB geometry as OGC WKT. +/// +/// WKB only contains the seven Simple Features geometry families handled +/// below. The additional `geo_traits` variants are rejected explicitly so a +/// future parser change cannot silently emit a non-OGC representation. +#[derive(Debug)] +enum WktRenderError { + UnsupportedDimension(Dimensions), + CoordinateDimension { + geometry: Dimensions, + coordinate: Dimensions, + }, + MissingCoordinate(usize), + UnsupportedGeometry(&'static str), +} + +impl std::fmt::Display for WktRenderError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnsupportedDimension(dimension) => { + write!(formatter, "unsupported coordinate dimension {dimension:?}") + } + Self::CoordinateDimension { + geometry, + coordinate, + } => write!( + formatter, + "coordinate dimension {coordinate:?} does not match geometry dimension {geometry:?}" + ), + Self::MissingCoordinate(index) => { + write!(formatter, "coordinate is missing ordinate {index}") + } + Self::UnsupportedGeometry(kind) => { + write!(formatter, "unsupported non-WKB geometry kind {kind}") + } + } + } +} + +type WktRenderResult = std::result::Result<(), WktRenderError>; + +/// Render the OGC/ISO WKB geometry as WKT without allocating an intermediate +/// geometry tree. +/// +/// The `wkt` crate's generic writer currently assumes that members of multi +/// geometries are never empty. Databricks permits values such as +/// `MULTIPOINT(EMPTY,(1 2))` and `MULTIPOLYGON(EMPTY,...)`, so walking the +/// `geo_traits` view directly is both allocation-free and preserves those +/// valid values instead of panicking. +fn write_ogc_wkt(output: &mut String, geometry: &impl GeometryTrait) -> WktRenderResult { + match geometry.as_type() { + GeometryType::Point(point) => write_point(output, point), + GeometryType::LineString(line) => write_line_string(output, line), + GeometryType::Polygon(polygon) => write_polygon(output, polygon), + GeometryType::MultiPoint(points) => write_multi_point(output, points), + GeometryType::MultiLineString(lines) => write_multi_line_string(output, lines), + GeometryType::MultiPolygon(polygons) => write_multi_polygon(output, polygons), + GeometryType::GeometryCollection(collection) => { + write_geometry_collection(output, collection) + } + GeometryType::Rect(_) => Err(WktRenderError::UnsupportedGeometry("RECT")), + GeometryType::Triangle(_) => Err(WktRenderError::UnsupportedGeometry("TRIANGLE")), + GeometryType::Line(_) => Err(WktRenderError::UnsupportedGeometry("LINE")), + } +} + +fn write_point(output: &mut String, point: &impl PointTrait) -> WktRenderResult { + let dimension = point.dim(); + write_type_name(output, "POINT", dimension)?; + match point.coord() { + Some(coordinate) => { + write_body_start(output, dimension); + write_coordinate(output, &coordinate, dimension)?; + output.push(')'); + } + None => output.push_str(" EMPTY"), + } + Ok(()) +} + +fn write_line_string(output: &mut String, line: &impl LineStringTrait) -> WktRenderResult { + let dimension = line.dim(); + write_type_name(output, "LINESTRING", dimension)?; + if line.num_coords() == 0 { + output.push_str(" EMPTY"); + } else { + write_body_start(output, dimension); + write_coordinates(output, line, dimension)?; + output.push(')'); + } + Ok(()) +} + +fn write_polygon(output: &mut String, polygon: &impl PolygonTrait) -> WktRenderResult { + let dimension = polygon.dim(); + write_type_name(output, "POLYGON", dimension)?; + match polygon.exterior() { + Some(exterior) if exterior.num_coords() != 0 => { + write_body_start(output, dimension); + write_polygon_body(output, &exterior, polygon.interiors(), dimension)?; + output.push(')'); + } + _ => output.push_str(" EMPTY"), + } + Ok(()) +} + +fn write_multi_point( + output: &mut String, + points: &impl MultiPointTrait, +) -> WktRenderResult { + let dimension = points.dim(); + write_type_name(output, "MULTIPOINT", dimension)?; + if points.num_points() == 0 { + output.push_str(" EMPTY"); + return Ok(()); + } + + write_body_start(output, dimension); + for (index, point) in points.points().enumerate() { + write_separator(output, index); + if let Some(coordinate) = point.coord() { + output.push('('); + write_coordinate(output, &coordinate, dimension)?; + output.push(')'); + } else { + output.push_str("EMPTY"); + } + } + output.push(')'); + Ok(()) +} + +fn write_multi_line_string( + output: &mut String, + lines: &impl MultiLineStringTrait, +) -> WktRenderResult { + let dimension = lines.dim(); + write_type_name(output, "MULTILINESTRING", dimension)?; + if lines.num_line_strings() == 0 { + output.push_str(" EMPTY"); + return Ok(()); + } + + write_body_start(output, dimension); + for (index, line) in lines.line_strings().enumerate() { + write_separator(output, index); + if line.num_coords() == 0 { + output.push_str("EMPTY"); + } else { + output.push('('); + write_coordinates(output, &line, dimension)?; + output.push(')'); + } + } + output.push(')'); + Ok(()) +} + +fn write_multi_polygon( + output: &mut String, + polygons: &impl MultiPolygonTrait, +) -> WktRenderResult { + let dimension = polygons.dim(); + write_type_name(output, "MULTIPOLYGON", dimension)?; + if polygons.num_polygons() == 0 { + output.push_str(" EMPTY"); + return Ok(()); + } + + write_body_start(output, dimension); + for (index, polygon) in polygons.polygons().enumerate() { + write_separator(output, index); + match polygon.exterior() { + Some(exterior) if exterior.num_coords() != 0 => { + output.push('('); + write_polygon_body(output, &exterior, polygon.interiors(), dimension)?; + output.push(')'); + } + _ => output.push_str("EMPTY"), + } + } + output.push(')'); + Ok(()) +} + +fn write_geometry_collection( + output: &mut String, + collection: &impl GeometryCollectionTrait, +) -> WktRenderResult { + let dimension = collection.dim(); + write_type_name(output, "GEOMETRYCOLLECTION", dimension)?; + if collection.num_geometries() == 0 { + output.push_str(" EMPTY"); + return Ok(()); + } + + write_body_start(output, dimension); + for (index, geometry) in collection.geometries().enumerate() { + write_separator(output, index); + write_ogc_wkt(output, &geometry)?; + } + output.push(')'); + Ok(()) +} + +fn write_polygon_body( + output: &mut String, + exterior: &R, + interiors: I, + dimension: Dimensions, +) -> WktRenderResult +where + R: LineStringTrait, + I: Iterator, +{ + output.push('('); + write_coordinates(output, exterior, dimension)?; + output.push(')'); + for interior in interiors { + output.push_str(",("); + write_coordinates(output, &interior, dimension)?; + output.push(')'); + } + Ok(()) +} + +fn write_coordinates( + output: &mut String, + line: &impl LineStringTrait, + dimension: Dimensions, +) -> WktRenderResult { + for (index, coordinate) in line.coords().enumerate() { + write_separator(output, index); + write_coordinate(output, &coordinate, dimension)?; + } + Ok(()) +} + +fn write_coordinate( + output: &mut String, + coordinate: &impl CoordTrait, + dimension: Dimensions, +) -> WktRenderResult { + if coordinate.dim().size() != dimension.size() { + return Err(WktRenderError::CoordinateDimension { + geometry: dimension, + coordinate: coordinate.dim(), + }); + } + for index in 0..dimension.size() { + if index != 0 { + output.push(' '); + } + let ordinate = coordinate + .nth(index) + .ok_or(WktRenderError::MissingCoordinate(index))?; + write!(output, "{ordinate}").expect("writing to String is infallible"); + } + Ok(()) +} + +fn write_type_name(output: &mut String, type_name: &str, dimension: Dimensions) -> WktRenderResult { + output.push_str(type_name); + match dimension { + Dimensions::Xy | Dimensions::Unknown(2) => {} + Dimensions::Xyz | Dimensions::Unknown(3) => output.push_str(" Z"), + Dimensions::Xym => output.push_str(" M"), + Dimensions::Xyzm | Dimensions::Unknown(4) => output.push_str(" ZM"), + unsupported => return Err(WktRenderError::UnsupportedDimension(unsupported)), + } + Ok(()) +} + +fn write_body_start(output: &mut String, dimension: Dimensions) { + if matches!(dimension, Dimensions::Xy | Dimensions::Unknown(2)) { + output.push('('); + } else { + // Databricks' canonical higher-dimensional spelling includes a + // space between the Z/M qualifier and the coordinate body. + output.push_str(" ("); + } +} + +fn write_separator(output: &mut String, index: usize) { + if index != 0 { + output.push(','); + } +} + 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!( @@ -576,9 +968,15 @@ fn downcast<'a, T: 'static>(array: &'a ArrayRef, path: &str, expected: &str) -> }) } +fn malformed_native(path: &str, detail: &str) -> Error { + Error::data_loss().message(format!( + "geospatial value '{path}' has malformed native Arrow data: {detail}" + )) +} + 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}" + "failed to rebuild Arrow container '{path}' after geospatial conversion: {error}" )) } @@ -586,7 +984,7 @@ fn rebuild_error(path: &str, error: arrow_schema::ArrowError) -> Error { mod tests { use super::*; use arrow_array::builder::{BinaryBuilder, Int32Builder}; - use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; + use arrow_buffer::NullBuffer; use std::collections::HashMap; const POINT_1_2_WKB: &[u8] = &[ @@ -638,23 +1036,27 @@ mod tests { )) } + fn wkt_from_hex(value: &str) -> String { + let bytes = hex::decode(value).unwrap(); + let geometry = wkb::reader::read_wkb(&bytes).unwrap(); + let mut output = String::new(); + write_ogc_wkt(&mut output, &geometry).unwrap(); + output + } + #[test] fn recognizes_only_canonical_tagged_structs() { assert_eq!( - native_geo_tag(&geo_type(GeoFamily::Geometry, -1)) - .unwrap() - .map(|tag| tag.family), + native_geo_family(&geo_type(GeoFamily::Geometry, -1)).unwrap(), Some(GeoFamily::Geometry) ); assert_eq!( - native_geo_tag(&geo_type(GeoFamily::Geography, 4326)) - .unwrap() - .map(|tag| tag.family), + native_geo_family(&geo_type(GeoFamily::Geography, 4326)).unwrap(), Some(GeoFamily::Geography) ); let plain = plain_geo_type(); - assert_eq!(native_geo_tag(&plain).unwrap(), None); + assert_eq!(native_geo_family(&plain).unwrap(), None); } #[test] @@ -662,31 +1064,95 @@ mod tests { 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(); + let binary = plan( + &physical, + Some(&logical), + GeospatialResultRepresentation::Binary, + ) + .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(); + let binary = plan( + &already_tagged, + Some(&logical), + GeospatialResultRepresentation::Binary, + ) + .unwrap() + .unwrap(); assert!(!binary.needs_rewrite); assert_eq!(binary.output_type, logical.data_type().clone()); - let fallback = plan(&already_tagged, None).unwrap().unwrap(); + let fallback = plan( + &already_tagged, + None, + GeospatialResultRepresentation::Binary, + ) + .unwrap() + .unwrap(); assert!(!fallback.needs_rewrite); assert_eq!(fallback.output_type, already_tagged.data_type().clone()); + let string = plan( + &physical, + Some(&logical), + GeospatialResultRepresentation::String, + ) + .unwrap() + .unwrap(); + assert_eq!(string.output_type, DataType::Utf8); + let wrong_family = Field::new("g", geo_type(GeoFamily::Geography, -1), true); - let error = plan(&wrong_family, Some(&logical)).unwrap_err(); + let error = plan( + &wrong_family, + Some(&logical), + GeospatialResultRepresentation::Binary, + ) + .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(); + let error = plan( + &already_tagged, + Some(&logical_plain), + GeospatialResultRepresentation::Binary, + ) + .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()); + for text_type in [DataType::Utf8, DataType::LargeUtf8] { + let text = Field::new("g", text_type.clone(), true); + let string = plan( + &text, + Some(&logical), + GeospatialResultRepresentation::String, + ) + .unwrap() + .unwrap(); + assert!(!string.needs_rewrite); + assert_eq!(string.output_type, text_type); + + let error = plan( + &text, + Some(&logical), + GeospatialResultRepresentation::Binary, + ) + .unwrap_err(); + assert!( + error + .message + .contains(&format!("server returned {text_type:?}")), + "{error:?}" + ); + } - assert!(plan(&physical, None).unwrap().is_none()); + assert!( + plan(&physical, None, GeospatialResultRepresentation::String) + .unwrap() + .is_none() + ); } #[test] @@ -716,49 +1182,81 @@ mod tests { } #[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() + fn native_geometry_converts_to_ewkt_and_preserves_outer_null() { + let array = geo_array(GeoFamily::Geometry, -1, 4326); + let output = rewrite(&array, &DataType::Utf8, "g").unwrap(); + let output = output .as_any() - .downcast_ref::() + .downcast_ref::() .unwrap(); - let DataType::Struct(fields) = values.data_type() else { - panic!("nested geometry must remain a struct") + assert_eq!(output.value(0), "SRID=4326;POINT(1 2)"); + assert!(output.is_null(1)); + } + + #[test] + fn srid_zero_uses_plain_wkt() { + let array = geo_array(GeoFamily::Geometry, 0, 0); + let output = rewrite(&array, &DataType::Utf8, "g").unwrap(); + let output = output + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(output.value(0), "POINT(1 2)"); + } + + #[test] + fn invalid_wkb_is_reported_as_data_loss() { + let DataType::Struct(fields) = geo_type(GeoFamily::Geometry, 0) else { + unreachable!() }; - 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)); + let array: ArrayRef = Arc::new(StructArray::new( + fields, + vec![ + Arc::new(Int32Array::from(vec![0])), + Arc::new(BinaryArray::from(vec![&b"not-wkb"[..]])), + ], + None, + )); + + let error = rewrite(&array, &DataType::Utf8, "g").unwrap_err(); + assert!(error.message.contains("contains invalid WKB")); + } + + #[test] + fn wkb_renderer_handles_dimensions_collections_and_empty_members() { + let cases = [ + ( + "0101000000000000000000f87f000000000000f87f", + "POINT EMPTY", + ), + ( + "01b90b0000000000000000f03f000000000000004000000000000008400000000000001040", + "POINT ZM (1 2 3 4)", + ), + ( + "010100000050fc1873d79a5ec0d0d556ec2fe34240", + "POINT(-122.4194 37.7749)", + ), + ( + "0104000000040000000101000000000000000000f03f00000000000000400101000000000000000000f87f000000000000f87f0101000000000000000000f87f000000000000f87f010100000000000000000008400000000000001040", + "MULTIPOINT((1 2),EMPTY,EMPTY,(3 4))", + ), + ( + "010500000003000000010200000000000000010200000002000000000000000000f03f000000000000004000000000000008400000000000001040010200000000000000", + "MULTILINESTRING(EMPTY,(1 2,3 4),EMPTY)", + ), + ( + "010600000001000000010300000000000000", + "MULTIPOLYGON(EMPTY)", + ), + ( + "0107000000020000000101000000000000000000f03f0000000000000040010200000000000000", + "GEOMETRYCOLLECTION(POINT(1 2),LINESTRING EMPTY)", + ), + ]; + + for (wkb, expected) in cases { + assert_eq!(wkt_from_hex(wkb), expected); + } } } diff --git a/src/reader/post_processor/json.rs b/src/reader/post_processor/json.rs index 50387b54..ac3be3d2 100644 --- a/src/reader/post_processor/json.rs +++ b/src/reader/post_processor/json.rs @@ -231,20 +231,17 @@ pub(crate) fn append_json( Ok(()) } -/// Decide if `field` says the column is one of the precise Databricks -/// types whose `Utf8` payload is **already** correctly formatted -/// (VARIANT carries JSON text, GEOMETRY/GEOGRAPHY carry WKT). In that -/// case we pass through verbatim, including the surrounding quoting -/// the server emitted; otherwise we treat it as a normal string and -/// JSON-escape it. +/// Encode an `Utf8` value using any logical Databricks type metadata on +/// `field`. VARIANT contains an already-encoded JSON value and is inserted +/// verbatim. GEOMETRY / GEOGRAPHY contain kernel-rendered EWKT and are JSON +/// strings, like ordinary `Utf8` values. /// /// Known limitation: the manifest only attaches `databricks.type_name` /// to top-level Arrow fields, so inner fields of `ARRAY` / /// `MAP<…, VARIANT>` / `STRUCT` lack the metadata and the /// nested element is treated as a plain `Utf8` and JSON-escaped -/// (`"\"{\\\"a\\\":1}\""` instead of `{"a":1}`). Same for nested -/// `GEOMETRY` / `GEOGRAPHY`. Producing the JDBC-matching form for -/// nested VARIANTs requires parsing the manifest's `type_text` +/// (`"\"{\\\"a\\\":1}\""` instead of `{"a":1}`). Producing the +/// JDBC-matching form for nested VARIANTs requires parsing the manifest's `type_text` /// (e.g. `ARRAY`) and propagating into inner Arrow fields; /// tracked separately, see `tests::nested_variant_inside_list_is_escaped_known_limitation`. fn append_utf8_value(out: &mut String, value: &str, field: &Field) { @@ -257,9 +254,9 @@ fn append_utf8_value(out: &mut String, value: &str, field: &Field) { out.push_str(value); return; } - // GEOMETRY / GEOGRAPHY render as quoted WKT text. The - // server delivers the raw WKT (without quotes); we add - // the JSON quoting here. + // GEOMETRY / GEOGRAPHY reach this path as kernel-rendered EWKT + // text after the tagged Arrow struct has been normalized. Add + // JSON quoting around that scalar value. "GEOMETRY" | "GEOGRAPHY" => { append_quoted(out, value); return; diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index f68f06f9..94a4b833 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -36,6 +36,7 @@ mod geospatial; mod json; +use crate::config::GeospatialResultRepresentation; use crate::kernel_error::{Error, Result}; use crate::reader::{ResultReader, ResultReaderAdapter, ResultReaderMetrics}; use crate::types::sea::ResultManifest; @@ -65,6 +66,11 @@ pub(crate) struct PostProcessOptions { /// Python; non-Python consumers can leave it `false` if they /// have a working interval decoder. pub intervals_as_string: bool, + /// Client-facing physical representation for logical GEOMETRY and + /// GEOGRAPHY columns. The structured logical manifest schema is reconciled + /// with the physical `struct` attachment, then exposed with + /// canonical tags or recursively rendered as EWKT. + pub geospatial_result_representation: GeospatialResultRepresentation, } /// Wrapper that runs all per-batch post-processing the kernel does @@ -118,9 +124,10 @@ impl ResultPostProcessor { }; // 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. + // rewrites. Geo normalization runs first because a geo leaf may be + // nested inside a complex column that is subsequently rendered as + // JSON. Binary geo mode may rebuild array containers to attach + // metadata, but it reuses the existing child/value buffers. let mut json_columns: Vec = Vec::new(); let mut interval_columns: Vec = Vec::new(); let mut null_columns: Vec = Vec::new(); @@ -133,7 +140,11 @@ impl ResultPostProcessor { .as_ref() .and_then(|schema| schema.fields().get(i)) .map(|field| field.as_ref()); - let geo_plan = geospatial::plan(field, logical_field)?; + let geo_plan = geospatial::plan( + field, + logical_field, + options.geospatial_result_representation, + )?; let (normalized_field, is_top_level_geo) = match geo_plan { Some(plan) => { if plan.needs_rewrite { @@ -439,8 +450,8 @@ mod tests { use arrow_array::builder::{ BinaryBuilder, Int32Builder, ListBuilder, MapBuilder, StringBuilder, }; - use arrow_array::{Array, Int32Array, StringArray, StructArray}; - use arrow_buffer::NullBuffer; + use arrow_array::{Array, Int32Array, ListArray, MapArray, StringArray, StructArray}; + use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; use arrow_schema::Fields; fn make_manifest(columns: Vec) -> ResultManifest { @@ -867,7 +878,60 @@ mod tests { } #[tokio::test] - async fn geospatial_results_attach_tags_and_reuse_child_arrays() { + async fn geospatial_string_mode_converts_geometry_geography_any_and_nulls() { + let geometry = untagged_geo_values(&[Some(3857), None]); + let geography = untagged_geo_values(&[Some(4326), None]); + 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), + ])); + let batch = RecordBatch::try_new(schema, vec![geometry, geography]).unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + let manifest = make_manifest(vec![ + column_info("geom", "GEOMETRY", "GEOMETRY(ANY)", 0), + column_info("geog", "GEOGRAPHY", "GEOGRAPHY(4326)", 1), + ]); + + let mut pp = + ResultPostProcessor::new(inner, Some(&manifest), PostProcessOptions::default()) + .await + .unwrap(); + assert_eq!( + pp.schema().await.unwrap().field(0).data_type(), + &DataType::Utf8 + ); + assert_eq!( + pp.schema().await.unwrap().field(1).data_type(), + &DataType::Utf8 + ); + + let out = pp.next_batch().await.unwrap().unwrap(); + let geometry = out + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let geography = out + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(geometry.value(0), "SRID=3857;POINT(1 2)"); + assert_eq!(geography.value(0), "SRID=4326;POINT(1 2)"); + assert!(geometry.is_null(1)); + assert!(geography.is_null(1)); + assert_eq!( + out.schema() + .field(0) + .metadata() + .get(metadata_keys::TYPE_TEXT) + .map(String::as_str), + Some("GEOMETRY(ANY)") + ); + } + + #[tokio::test] + async fn geospatial_binary_mode_attaches_tags_and_reuses_child_arrays() { let geometry = untagged_geo_values(&[Some(4326)]); let original = geometry .as_any() @@ -883,10 +947,14 @@ mod tests { 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 options = PostProcessOptions { + geospatial_result_representation: GeospatialResultRepresentation::Binary, + ..Default::default() + }; + + let mut pp = ResultPostProcessor::new(inner, Some(&manifest), options) + .await + .unwrap(); let out = pp.next_batch().await.unwrap().unwrap(); let values = out .column(0) @@ -908,4 +976,78 @@ mod tests { Some("-1") ); } + + #[tokio::test] + async fn nested_geo_is_converted_before_complex_json() { + let list_values = untagged_geo_values(&[Some(4326), None]); + let list_item = Arc::new(Field::new("item", list_values.data_type().clone(), true)); + let list = ListArray::new( + list_item, + OffsetBuffer::new(ScalarBuffer::from(vec![0_i32, 2])), + list_values, + None, + ); + + let struct_values = untagged_geo_values(&[Some(0)]); + let struct_fields = Fields::from(vec![Field::new( + "g", + struct_values.data_type().clone(), + true, + )]); + let struct_array = StructArray::new(struct_fields, vec![struct_values], None); + + let map_values = untagged_geo_values(&[Some(4326)]); + let entry_fields = Fields::from(vec![ + Field::new("key", DataType::Utf8, false), + Field::new("value", map_values.data_type().clone(), true), + ]); + let entries = StructArray::new( + entry_fields.clone(), + vec![Arc::new(StringArray::from(vec!["k"])), map_values], + None, + ); + let map = MapArray::new( + Arc::new(Field::new("entries", DataType::Struct(entry_fields), false)), + OffsetBuffer::new(ScalarBuffer::from(vec![0_i32, 1])), + entries, + None, + false, + ); + + let schema = Arc::new(Schema::new(vec![ + Field::new("col_0", list.data_type().clone(), true), + Field::new("col_1", struct_array.data_type().clone(), true), + Field::new("col_2", map.data_type().clone(), true), + ])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(list), Arc::new(struct_array), Arc::new(map)], + ) + .unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + let manifest = make_manifest(vec![ + column_info("arr", "ARRAY", "ARRAY", 0), + column_info("s", "STRUCT", "STRUCT", 1), + column_info("m", "MAP", "MAP", 2), + ]); + let options = PostProcessOptions { + complex_types_as_json: true, + ..Default::default() + }; + + let mut pp = ResultPostProcessor::new(inner, Some(&manifest), options) + .await + .unwrap(); + let out = pp.next_batch().await.unwrap().unwrap(); + let value = |index| { + out.column(index) + .as_any() + .downcast_ref::() + .unwrap() + .value(0) + }; + assert_eq!(value(0), "[\"SRID=4326;POINT(1 2)\",null]"); + assert_eq!(value(1), "{\"g\":\"POINT(1 2)\"}"); + assert_eq!(value(2), "{\"k\":\"SRID=4326;POINT(1 2)\"}"); + } } diff --git a/src/session.rs b/src/session.rs index 7f05b065..31118bd3 100644 --- a/src/session.rs +++ b/src/session.rs @@ -59,8 +59,9 @@ use crate::client::{ SessionAttribution, Transport, }; use crate::config::{ - AuthConfig, ConnectionConfig, DefaultOpts, HttpConfig, LoggingConfig, ProxyConfig, - ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TransportMode, + AuthConfig, ConnectionConfig, DefaultOpts, GeospatialResultRepresentation, HttpConfig, + LoggingConfig, ProxyConfig, ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, + TransportMode, }; use crate::kernel_error::{Error, Result}; use crate::klog::debug; @@ -332,6 +333,12 @@ impl Session { // is sent on the wire. apply_client_result_overrides(&mut config); + // Resolve the typed client-side representation once. It is applied + // locally by the reader factory and is never synthesized into + // `session_conf` or sent to SEA. + let geospatial_result_representation = + config.geospatial_result_representation.unwrap_or_default(); + let host = config.connection.host.clone(); let warehouse_id = config.connection.warehouse_id.clone(); let org_id = config.connection.org_id.clone(); @@ -378,6 +385,7 @@ impl Session { http_client.clone(), result_to_cloudfetch_config(&config.result), result_to_post_process_options(&config.result), + geospatial_result_representation, runtime_handle.clone(), ); sea.set_reader_factory(reader_factory, runtime_handle.clone()); @@ -392,8 +400,8 @@ impl Session { // CloudFetch-disable is expressed per-statement via the SEA // `disposition` (threaded onto `TransportConfig` above), not via a - // session conf. The kernel synthesises no session_conf entries; - // caller-supplied server-bound entries pass through unchanged. + // session conf. The kernel synthesises no geospatial session-conf + // entry; caller-supplied server-bound entries pass through unchanged. let create_started = Instant::now(); let session_info = transport .create_session( @@ -788,6 +796,7 @@ pub struct SessionBuilder { telemetry: Option, driver_system_configuration: Option, session_conf: HashMap, + geospatial_result_representation: Option, transport: Option, /// Sentinel for [`SessionBuilder::http_path`] parse failures. /// Defers the error to `open()` so the builder API stays @@ -935,6 +944,21 @@ impl SessionBuilder { self } + /// Request the physical representation used for `GEOMETRY` and + /// `GEOGRAPHY` values inside Arrow result batches. + /// + /// Both choices keep the outer result format as Arrow. String mode emits + /// `Utf8` EWKT values; binary mode emits + /// `struct` values. The kernel normalizes the + /// server result locally; this setting is not forwarded to SEA. + pub fn geospatial_result_representation( + mut self, + representation: GeospatialResultRepresentation, + ) -> Self { + self.geospatial_result_representation = Some(representation); + self + } + /// Transport override. Default = `SeaRest`. Wrappers translate /// user-facing flags (`UseThriftClient=0/1`, `transport=...`) /// into this field. @@ -969,6 +993,7 @@ impl SessionBuilder { auth, driver_system_configuration: self.driver_system_configuration, session_conf: self.session_conf, + geospatial_result_representation: self.geospatial_result_representation, http: self.http.unwrap_or_default(), proxy: self.proxy, tls: self.tls.unwrap_or_default(), @@ -1251,6 +1276,7 @@ fn result_to_post_process_options( crate::reader::post_processor::PostProcessOptions { complex_types_as_json: result.complex_types_as_json, intervals_as_string: result.intervals_as_string, + ..Default::default() } } @@ -1512,6 +1538,7 @@ mod mtls_endpoint_tests { }, driver_system_configuration: None, session_conf: Default::default(), + geospatial_result_representation: None, http: HttpConfig::default(), proxy: None, tls, @@ -1640,6 +1667,7 @@ mod retry_config_tests { }, driver_system_configuration: None, session_conf: Default::default(), + geospatial_result_representation: None, http, proxy: None, tls: Default::default(), diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 9bffb18f..cc0807d3 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -23,15 +23,17 @@ use arrow_array::builder::{BinaryBuilder, Int32Builder}; use arrow_array::cast::AsArray; use arrow_array::{ - Array, BinaryArray, Int32Array, Int64Array, RecordBatch, StringArray, StructArray, + Array, ArrayRef, BinaryArray, Int32Array, Int64Array, LargeStringArray, RecordBatch, + StringArray, StructArray, }; use arrow_buffer::NullBuffer; use arrow_ipc::writer::StreamWriter; 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, + AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, + GeospatialResultRepresentation, HttpConfig, ResultBatch, ResultConfig, Session, TypedValue, + MAX_CLIENT_QUERY_TIMEOUT, }; use serde_json::json; use std::collections::HashMap; @@ -76,6 +78,25 @@ async fn open_session_with_result(server: &MockServer, result: ResultConfig) -> .expect("Session::open should succeed") } +async fn open_session_with_geospatial( + server: &MockServer, + representation: GeospatialResultRepresentation, +) -> Session { + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .geospatial_result_representation(representation) + .open() + .await + .expect("Session::open should succeed") +} + async fn open_session_with_http(server: &MockServer, http: HttpConfig) -> Session { Session::builder() .connection( @@ -415,19 +436,29 @@ fn geospatial_batch() -> RecordBatch { RecordBatch::try_new(schema, vec![geometry, geography]).unwrap() } -fn legacy_geospatial_batch() -> RecordBatch { +fn legacy_geospatial_batch(data_type: DataType) -> RecordBatch { let schema = Arc::new(Schema::new(vec![ - Field::new("col_0", DataType::Utf8, true), - Field::new("col_1", DataType::Utf8, true), + Field::new("col_0", data_type.clone(), true), + Field::new("col_1", data_type.clone(), true), ])); - RecordBatch::try_new( - schema, - vec![ + let columns: Vec = match data_type { + DataType::Utf8 => 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() + DataType::LargeUtf8 => vec![ + Arc::new(LargeStringArray::from(vec![ + Some("SRID=3857;POINT (1 2)"), + None, + ])) as _, + Arc::new(LargeStringArray::from(vec![ + Some("SRID=4326;POINT (1 2)"), + None, + ])) as _, + ], + other => panic!("legacy geospatial text must be Utf8 or LargeUtf8, got {other:?}"), + }; + RecordBatch::try_new(schema, columns).unwrap() } fn logical_geospatial_schema() -> Schema { @@ -611,7 +642,76 @@ async fn execute_succeeded_inline_returns_one_row() { } #[tokio::test] -async fn execute_geospatial_applies_manifest_tags_to_arrow_ipc() { +async fn execute_geospatial_string_mode_uses_manifest_tags_for_untagged_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-string", &batch), + ) + .await; + + let session = + open_session_with_geospatial(&server, GeospatialResultRepresentation::String).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]; + assert_eq!(out.schema().field(0).name(), "geom"); + assert_eq!(out.schema().field(1).name(), "geog"); + assert_eq!(out.schema().field(0).data_type(), &DataType::Utf8); + assert_eq!(out.schema().field(1).data_type(), &DataType::Utf8); + let geometry = out + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let geography = out + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(geometry.value(0), "SRID=3857;POINT(1 2)"); + assert_eq!(geography.value(0), "SRID=4326;POINT(1 2)"); + assert!(geometry.is_null(1)); + assert!(geography.is_null(1)); + assert_eq!( + out.schema() + .field(0) + .metadata() + .get("databricks.type_text") + .map(String::as_str), + Some("GEOMETRY(ANY)") + ); + exec.close().await.expect("close"); + + let requests = server.received_requests().await.unwrap(); + let create = requests + .iter() + .find(|request| request.url.path() == "/api/2.0/sql/sessions") + .expect("create-session request"); + let body: serde_json::Value = serde_json::from_slice(&create.body).unwrap(); + let forwarded_geo_setting = body + .get("session_confs") + .and_then(serde_json::Value::as_object) + .is_some_and(|confs| { + confs + .keys() + .any(|key| key.eq_ignore_ascii_case("geospatial_as_string")) + }); + assert!( + !forwarded_geo_setting, + "geospatial representation is client-side and must not reach SEA" + ); +} + +#[tokio::test] +async fn execute_geospatial_binary_mode_applies_manifest_tags_to_arrow_ipc() { let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; @@ -623,7 +723,8 @@ async fn execute_geospatial_applies_manifest_tags_to_arrow_ipc() { ) .await; - let session = open_session(&server).await; + let session = + open_session_with_geospatial(&server, GeospatialResultRepresentation::Binary).await; let mut stmt = session.statement(); stmt.spec().sql("SELECT geom, geog FROM geo_values"); let mut exec = stmt.execute().await.expect("execute"); @@ -698,182 +799,273 @@ async fn execute_geospatial_applies_manifest_tags_to_arrow_ipc() { #[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; + for data_type in [DataType::Utf8, DataType::LargeUtf8] { + 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(data_type.clone()); + mount_execute( + &server, + succeeded_legacy_geospatial_body( + &format!("stmt-legacy-geo-{data_type:?}"), + &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"); + 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(), &data_type); + assert_eq!(output.schema().field(1).data_type(), &data_type); + let value = match data_type { + DataType::Utf8 => output.column(0).as_string::().value(0), + DataType::LargeUtf8 => output.column(0).as_string::().value(0), + _ => unreachable!("test covers both text representations"), + }; + assert_eq!(value, "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; +async fn execute_legacy_geospatial_text_rejects_binary_mode() { + for data_type in [DataType::Utf8, DataType::LargeUtf8] { + for include_rows in [true, false] { + 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(data_type.clone()); + mount_execute( + &server, + succeeded_legacy_geospatial_body( + &format!("stmt-legacy-geo-binary-{data_type:?}-{include_rows}"), + &batch, + include_rows, + ), + ) + .await; + + let session = + open_session_with_geospatial(&server, GeospatialResultRepresentation::Binary).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT geom FROM legacy_geo_values"); + let error = match stmt.execute().await { + Ok(_) => panic!("binary mode must reject a legacy {data_type:?} geo attachment"), + Err(error) => error, + }; + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert!( + error + .message + .contains(&format!("server returned {data_type:?}")), + "{error:?}" + ); + } + } +} - 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, - } - ], +#[tokio::test] +async fn execute_cloudfetch_geospatial_reconciles_manifest_and_untagged_payload() { + for representation in [ + GeospatialResultRepresentation::String, + GeospatialResultRepresentation::Binary, + ] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let statement_id = match representation { + GeospatialResultRepresentation::String => "stmt-cloud-geo-string", + GeospatialResultRepresentation::Binary => "stmt-cloud-geo-binary", + _ => unreachable!("test covers every current representation"), + }; + 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 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, }, - "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"); + "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_with_geospatial(&server, representation).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(); + match representation { + GeospatialResultRepresentation::String => { + assert_eq!(schema.field(0).data_type(), &DataType::Utf8); + let geometry = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(geometry.value(0), "SRID=3857;POINT(1 2)"); + } + GeospatialResultRepresentation::Binary => { + 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") + ); + } + _ => unreachable!("test covers every current representation"), + } + 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") - ); + for representation in [ + GeospatialResultRepresentation::String, + GeospatialResultRepresentation::Binary, + ] { + 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_with_geospatial(&server, representation).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!( - fields[1].metadata().get("srid").map(String::as_str), - Some(type_srid) + schema + .field(0) + .metadata() + .get("databricks.type_text") + .map(String::as_str), + Some("GEOMETRY(ANY)") ); + + match representation { + GeospatialResultRepresentation::String => { + assert_eq!(schema.field(0).data_type(), &DataType::Utf8); + assert_eq!(schema.field(1).data_type(), &DataType::Utf8); + } + GeospatialResultRepresentation::Binary => { + 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) + ); + } + } + _ => unreachable!("test covers every current representation"), + } + + assert!(drain(exec.result_stream_mut()).await.is_empty()); + exec.close().await.expect("close"); } - 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; + for data_type in [DataType::Utf8, DataType::LargeUtf8] { + 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(data_type.clone()); + mount_execute( + &server, + succeeded_legacy_geospatial_body( + &format!("stmt-empty-legacy-geo-{data_type:?}"), + &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"); + 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(), &data_type); + assert_eq!(exec.schema().field(1).data_type(), &data_type); + assert!(drain(exec.result_stream_mut()).await.is_empty()); + exec.close().await.expect("close"); + } } #[tokio::test] diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index 997fc55d..f6ca5546 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -28,7 +28,8 @@ //! production backoff ladder before their final error is observable. use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, ErrorCode, HttpConfig, ResultConfig, Session, + AuthConfig, ConnectionConfig, ErrorCode, GeospatialResultRepresentation, HttpConfig, + ResultConfig, Session, }; use wiremock::matchers::{method, path, query_param}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -472,6 +473,141 @@ async fn create_session_forwards_user_supplied_session_conf_unchanged() { ); } +async fn open_session_with_geospatial_config( + server: &MockServer, + representation: Option, + session_conf: std::collections::HashMap, +) -> Session { + let mut builder = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .session_conf(session_conf); + if let Some(representation) = representation { + builder = builder.geospatial_result_representation(representation); + } + builder.open().await.expect("session must open") +} + +async fn mount_geospatial_session(server: &MockServer, session_id: &str) { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "session_id": session_id, + "warehouse_id": "test_wh", + }))) + .expect(1) + .mount(server) + .await; +} + +#[tokio::test] +async fn create_session_keeps_geospatial_string_mode_client_side() { + let server = MockServer::start().await; + mount_geospatial_session(&server, "sess-geo-string").await; + + let session = open_session_with_geospatial_config( + &server, + Some(GeospatialResultRepresentation::String), + Default::default(), + ) + .await; + assert_eq!(session.session_id(), "sess-geo-string"); + + let body = create_session_body(&server).await; + assert!(body + .pointer("/session_confs/geospatial_as_string") + .is_none()); +} + +#[tokio::test] +async fn create_session_keeps_geospatial_binary_mode_client_side() { + let server = MockServer::start().await; + mount_geospatial_session(&server, "sess-geo-binary").await; + + let session = open_session_with_geospatial_config( + &server, + Some(GeospatialResultRepresentation::Binary), + Default::default(), + ) + .await; + assert_eq!(session.session_id(), "sess-geo-binary"); + + let body = create_session_body(&server).await; + assert!(body + .pointer("/session_confs/geospatial_as_string") + .is_none()); +} + +#[tokio::test] +async fn create_session_omits_geospatial_conf_when_unset() { + let server = MockServer::start().await; + mount_geospatial_session(&server, "sess-geo-default").await; + + let session = open_session_with_geospatial_config(&server, None, Default::default()).await; + assert_eq!(session.session_id(), "sess-geo-default"); + + let body = create_session_body(&server).await; + let has_geospatial_conf = body + .get("session_confs") + .and_then(|value| value.as_object()) + .is_some_and(|confs| { + confs + .keys() + .any(|key| key.eq_ignore_ascii_case("geospatial_as_string")) + }); + assert!( + !has_geospatial_conf, + "unset mode must not synthesize a geospatial server conf" + ); +} + +#[tokio::test] +async fn typed_geospatial_config_does_not_reinterpret_raw_session_conf() { + let server = MockServer::start().await; + mount_geospatial_session(&server, "sess-geo-pass-through").await; + + let session_conf = std::collections::HashMap::from([ + ("GEOSPATIAL_AS_STRING".to_string(), "true".to_string()), + ("Geospatial_As_String".to_string(), "false".to_string()), + ("ansi_mode".to_string(), "true".to_string()), + ]); + let session = open_session_with_geospatial_config( + &server, + Some(GeospatialResultRepresentation::Binary), + session_conf, + ) + .await; + assert_eq!(session.session_id(), "sess-geo-pass-through"); + + let body = create_session_body(&server).await; + let confs = body + .get("session_confs") + .and_then(|value| value.as_object()) + .expect("session_confs object"); + assert_eq!( + confs + .get("GEOSPATIAL_AS_STRING") + .and_then(|value| value.as_str()), + Some("true") + ); + assert_eq!( + confs + .get("Geospatial_As_String") + .and_then(|value| value.as_str()), + Some("false") + ); + assert_eq!( + confs.get("ansi_mode").and_then(|value| value.as_str()), + Some("true") + ); +} + #[tokio::test] async fn create_session_with_cloudfetch_enabled_omits_can_cloud_download() { // The default (cloudfetch_enabled=true) path must also never send a