diff --git a/docs/designs/complex-types-json-stringify.md b/docs/designs/complex-types-json-stringify.md new file mode 100644 index 00000000..cc569ed2 --- /dev/null +++ b/docs/designs/complex-types-json-stringify.md @@ -0,0 +1,484 @@ + + +# Complex types as JSON strings — design + +Optional kernel-level conversion of `ARRAY` / `MAP` / `STRUCT` / +`VARIANT` columns into compact JSON text. Off by default; opted into +per session by callers that want a stringified surface (JDBC's +`complexDatatypeSupport=false`, PySQL's +`_use_arrow_native_complex_types=False`). + +Status: design. + +## Why + +### What users see today + +The Databricks SQL server returns complex-typed columns differently +depending on the wire protocol: + +- **Thrift**: when the connection's `complexTypesAsArrow=false`, + the server stringifies complex columns to compact JSON + server-side. The Python connector's Thrift backend receives + `Utf8` columns with values like `'["a","b","c"]'` and hands them + to the user. +- **SEA**: the server always returns native Arrow `List` / `Map` / + `Struct` arrays. There is no `complexTypesAsArrow=false` + equivalent — the wire is always native. + +That asymmetry breaks parity for both new SEA-family backends: + +- The Python connector's **native SEA backend** (`backend/sea/`) + accepts `_use_arrow_native_complex_types=False` but ignores it — + it always serves native Python objects, not JSON strings. +- The Python connector's **kernel backend** (`backend/kernel/`) + inherits the same gap: the kernel hands it native Arrow batches, + and the connector doesn't stringify on the way out. + +The Thrift vs Kernel comparator (`databricks-driver-test#304`) +surfaces this as 5 diffs in the `COMPLEX_TYPES_DISABLED` suite. +Same gap surfaces against the native SEA backend. + +### Why each driver doing it is the wrong shape + +JDBC already does its own client-side conversion. Its +`DatabricksArray.toString()` / `DatabricksMap.toString()` / +`DatabricksStruct.toString()` produce compact JSON: + +| Type | JDBC output | Thrift wire | Match? | +|---|---|---|---| +| `ARRAY` | `["a","b","c"]` | `["a","b","c"]` | yes | +| `MAP` | `{"k1":"v1","k2":"v2"}` | `{"k1":"v1","k2":"v2"}` | yes | +| `STRUCT` | `{"a":"foo","b":1}` | `{"a":"foo","b":1}` | yes | + +So **JDBC and Thrift already converge on the same compact-JSON +output**. Two consumers, identical contract, implemented twice in +two languages. + +The Python connector would need the same. Plus a future Go / Node +binding would need it again. That's the same 50–100 lines of JSON +serialization repeated per language, with subtle differences in +edge cases (string escaping, null handling, nested ordering, +geospatial formatting) that drift over time. + +**ADBC** is the only outlier: it wants raw Arrow, period. Its +binding opts out by leaving the kernel option off. + +### Proposal + +Push the JSON stringification into the kernel as an opt-in feature. + +- **One implementation** of the JSON serializer (in Rust), used by + JDBC's eventual kernel migration, the Python connector, future + Go / Node bindings. +- **One source of truth** for the byte-for-byte JSON format — + same comparator that validates Thrift parity also validates + kernel output, so drift gets caught immediately. +- **ADBC unaffected** — opt-in flag means it pays no cost and sees + no change. + +## API shape + +### Configuration surface + +Add a single bool on `SessionBuilder` (and `Session`'s config): + +```rust +pub struct SessionBuilder { + ... + /// When `true`, the kernel post-processes each result batch: + /// 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. + /// + /// The JSON format matches what the Databricks server emits on + /// the Thrift wire when `complexTypesAsArrow=false` (compact — + /// no whitespace between separators, double-quoted strings, + /// JSON `null` for SQL NULL). See `docs/designs/ + /// complex-types-json-stringify.md` for the exact rules. + /// + /// Default `false`. Bindings that surface a flat-text view + /// (PySQL when `_use_arrow_native_complex_types=False`, JDBC + /// when `complexDatatypeSupport=false`) should set this `true`. + /// ADBC and any other Arrow-native consumer should leave it + /// `false`. + complex_types_as_json: bool, +} +``` + +Per-statement override is not in scope for v0; if it turns out +needed, add a `SessionConfig::complex_types_as_json` override on +`StatementSpec` later. Keeping it session-level matches both PySQL +and JDBC's actual usage — the flag is a connection-level kwarg in +both. + +### Wire integration + +No wire change. The flag is purely client-side post-processing. + +### Result-stream integration + +The existing `ManifestAugmentingReader` is renamed and generalised +into a single `ResultPostProcessor` that owns *all* per-batch +post-processing the kernel does today (and adds tomorrow). It runs +exactly **one** `next_batch` indirection regardless of how many +transforms are enabled, and **zero** per-row work for transforms +that are inactive. + +```rust +pub(crate) struct ResultPostProcessor { + inner: Box, + schema: SchemaRef, + /// `None` when no per-batch reshape is needed (no `databricks.*` + /// metadata to copy through *and* JSON stringification disabled). + /// `Some` when at least one transform applies; the closure walks + /// the batch once, runs every active transform inline, returns a + /// fresh `RecordBatch`. + transform: Option, +} + +type BatchTransform = + Box Result + Send + Sync>; +``` + +`ResultPostProcessor::new` runs once at construction time and +decides what to do: + +1. Take the inner schema; apply the manifest-augmentation rewrite + to produce the output schema (no-op when manifest is `None`). +2. Inspect the *augmented* schema: are any columns complex + (`List` / `Map` / `Struct` / `Utf8`-with-VARIANT-metadata / + ...)? +3. **Decide the transform shape once**, based on what's active: + - **No manifest, no JSON**: `transform = None`, batches passed + through untouched. + - **Manifest only**: the closure just re-projects each batch's + columns onto the augmented schema (single `RecordBatch::try_new`). + - **JSON only** (shouldn't happen — manifest is always present + in execute responses — but kept consistent): walk only the + complex columns. + - **Both**: a single fused walk that re-projects *and* + stringifies complex columns in the same pass, producing + exactly one new `RecordBatch` per upstream batch. + +The hot path on `next_batch` is then unconditional: + +```rust +fn next_batch(&mut self) -> Result> { + let Some(batch) = self.inner.next_batch()? else { + return Ok(None); + }; + match &self.transform { + Some(transform) => Ok(Some(transform(&batch)?)), + None => Ok(Some(batch)), + } +} +``` + +Single struct, single hot-path branch (matched once per batch, not +per row), and the "pass-through" case really is pass-through (no +`Vec` allocation, no `try_new`, no schema rebuild). + +### Why one struct instead of separate `ManifestAugmentingReader` +### and `JsonStringifyingReader` + +The natural object-oriented factoring is one wrapper per +transform. We deliberately don't do that for three reasons: + +1. **Per-batch overhead matters.** Result batches arrive + thousands at a time for CloudFetch streams; every extra + `Box` indirection is a virtual call per batch. + Today's two transforms could grow (interval stringification, + future others). Each is microseconds, but they compound and + would force a measurement-driven cleanup later. +2. **Pass-through paths should actually be free.** With per- + transform wrappers, the "no-op" path (no manifest, no JSON) + still costs one `RecordBatch::try_new` per batch to re-project + onto an identical schema. With one consolidated processor that + decides `transform = None` at construction, the upstream batch + flows through without any rebuild. +3. **The transforms are unidirectional and tightly coupled.** + JSON stringification needs to read field metadata that the + manifest augmenter writes. Layering them per the natural + factoring still requires the JSON layer to look up the + augmenter's output, so the coupling is real either way. A + fused walk is no harder to reason about than two sequential + walks that already have to agree on field-metadata semantics. + +If the kernel later accumulates a transform that genuinely +benefits from being separately addressable (e.g. an Arrow-FFI +adapter that wants only some of the transforms), we revisit then. +Today, all transforms apply to all `ResultReader` consumers, so +the consolidated shape is correct. + +### Migration of the existing `ManifestAugmentingReader` + +`ManifestAugmentingReader` (introduced in PR #35) is renamed to +`ResultPostProcessor`. The existing constructor signature changes +from + +```rust +ManifestAugmentingReader::new(inner, manifest: Option<&ResultManifest>) +``` + +to + +```rust +ResultPostProcessor::new( + inner, + manifest: Option<&ResultManifest>, + options: PostProcessOptions, +) +``` + +where `PostProcessOptions` is a small struct holding the JSON flag +(and any future transform flags). The two existing tests +(`test_manifest_augmenting_reader_*`) are updated to construct the +new struct with `options::default()` (JSON off) and assert the +same behaviour they do today. + +The wrap site in `ResultReaderFactory::create_reader` becomes: + +```rust +pub(crate) fn create_reader( + &self, + statement_id: &str, + response: &ExecuteResponse, +) -> Result> { + let inner = self.create_inner_reader(statement_id, response)?; + Ok(Box::new(ResultPostProcessor::new( + inner, + response.manifest.as_ref(), + self.post_process_options(), + )?)) +} +``` + +`post_process_options()` reads the session config (`complex_types_as_json`) +and builds the `PostProcessOptions` for this reader. + +## JSON format + +The format **must match Thrift's wire format byte-for-byte**, since +that's the contract every existing PySQL/JDBC user already sees. +Verified against Thrift output on Dogfood (`comparator_tests +.oss_jdbc_tests.test_result_set_types`). + +### Compact serialization rules + +- **No whitespace** between separators. `[1,2]` not `[1, 2]`. + Equivalent to Python `json.dumps(obj, separators=(',', ':'))`. +- **JSON `null`** for SQL NULL — not `"null"`. +- **Double-quoted strings** with standard JSON escaping + (`\\"`, `\\\\`, `\\b`, `\\f`, `\\n`, `\\r`, `\\t`, + `\\uXXXX` for control chars). +- **Map keys** stringified the same way (Databricks `MAP` requires + string keys; non-string keys are a server-side error). + +### Per-type formatting + +| Type | JSON form | Notes | +|---|---|---| +| `BOOLEAN` | `true` / `false` | | +| `TINYINT`, `SMALLINT`, `INT`, `BIGINT` | bare integer | `42` | +| `FLOAT`, `DOUBLE` | bare number | `3.14`. `NaN` / `±Inf` are server-side errors today; if they ever surface, emit `null` to stay valid JSON. | +| `DECIMAL(p,s)` | bare number, fixed precision | `99.99` | +| `STRING`, `CHAR`, `VARCHAR` | quoted, JSON-escaped | `"abc"` | +| `BINARY` | base64 quoted | `"aGVsbG8="` (matches what Thrift emits) | +| `DATE` | quoted ISO 8601 | `"2024-01-15"` | +| `TIMESTAMP` | quoted ISO 8601 with offset | `"2024-01-15T10:30:00.000Z"` | +| `TIMESTAMP_NTZ` | quoted ISO 8601 no offset | `"2024-01-15T10:30:00.000"` | +| `INTERVAL YEAR TO MONTH` | quoted Databricks text | `"2-6"` | +| `INTERVAL DAY TO SECOND` | quoted Databricks text | `"3 12:30:15.000000000"` | +| `ARRAY` | `[v1,v2,...]` | Recurse on T | +| `MAP` | `{"k1":v1,"k2":v2}` | Keys stringified per K's rules but always rendered quoted | +| `STRUCT` | `{"f1":v1,...}` | Field-name keys quoted; field order follows declared schema | +| `VARIANT` | depends — the server emits the variant's own JSON value already | Pass through verbatim (already JSON-text on the wire) | +| `GEOMETRY` / `GEOGRAPHY` | quoted WKT | `"POINT (1.5 2.5)"` | + +Edge cases worth calling out, with the rule we pick: + +- **Null inside nested types**: rendered as bare `null`, not the + string `"null"`. Matches both Thrift and JDBC. +- **Empty containers**: `[]` and `{}` respectively. +- **String quoting inside MAP keys**: keys are always quoted in + the JSON output even when the underlying Arrow type is integer + (Databricks `MAP` permits any key type at the SQL level; JSON + requires string keys). Cast to canonical string form using the + same per-type rules. Matches JDBC. +- **Float precision**: emit the shortest round-trippable form + (Rust's `f64::to_string` does this). Matches Java's + `Double.toString`, which is what JDBC produces. + +## Implementation sketch + +### Files touched + +- **`src/reader/post_processor.rs`** (new) — `ResultPostProcessor` + struct + `PostProcessOptions`. Rename target for the existing + `ManifestAugmentingReader` (which is folded into this). +- **`src/reader/post_processor/json.rs`** (new) — pure functions + for the per-type JSON serialization. No `ResultReader` impl; + just `to_json_string(value: &dyn Array, row: usize, field: &Field) -> String`-shape + helpers. Lets us unit-test the formatter without spinning up a + reader. +- **`src/reader/mod.rs`** — drop `ManifestAugmentingReader`, + rewire `ResultReaderFactory::create_reader` to call + `ResultPostProcessor::new` instead. `augment_schema_with_manifest` + helper moves to `post_processor.rs`. +- **`src/client/sea.rs`** — no change; the factory already runs + here. +- **`src/session/builder.rs`** + **`src/session.rs`** — surface + `complex_types_as_json` on `SessionBuilder`. `ResultReaderFactory` + reads it via `self.config` (already plumbed for the wire-path + config knobs). + +The JSON serialization itself uses `serde_json` for primitive value +emission (already pulled in transitively via `reqwest`) so we don't +hand-roll escaping rules. + +### `ResultPostProcessor::new` decision logic + +Run once at construction. Cheap — proportional to column count, not +row count: + +1. Compute the output schema: + - If `manifest = Some`, apply `augment_schema_with_manifest`. + - Else, use the inner schema as-is. +2. Decide whether the batch transform is needed: + - Inspect the augmented schema. Are there any complex columns + (`List` / `LargeList` / `FixedSizeList` / `Map` / `Struct`, + or `Utf8`+VARIANT/GEOMETRY/GEOGRAPHY metadata)? + - If `options.complex_types_as_json` is `true` *and* the schema + has complex columns, **JSON path** is active. + - If the output schema differs structurally from the inner + schema (i.e. we wrote field metadata, so `Field` objects + differ), **re-projection path** is active. + - Else, neither is needed. +3. Build a single `BatchTransform` closure capturing only the + work that's actually active: + - Neither active → `transform = None`. Hot path is pass-through. + - Re-projection only → closure does one `RecordBatch::try_new` + onto the augmented schema, reusing the source `ArrayRef`s. + - JSON only (shouldn't happen, but for completeness) → closure + walks complex columns, leaves primitives untouched. + - Both → closure does a single fused walk: for each column + index, either reproject the source `ArrayRef` (primitive) or + emit a fresh `Utf8` array of JSON strings (complex). Builds + the final `RecordBatch` from the resulting columns. + +### Per-batch hot path + +```rust +fn next_batch(&mut self) -> Result> { + let Some(batch) = self.inner.next_batch()? else { + return Ok(None); + }; + match &self.transform { + Some(t) => Ok(Some(t(&batch)?)), + None => Ok(Some(batch)), + } +} +``` + +One branch per batch, picked once at construction. The +pass-through case is genuinely free — no allocation, no rebuild, +the upstream `RecordBatch` flows through. + +### JSON serialization details + +For each complex column, the closure produced at construction +knows: + +- The column index in the source batch. +- A row-formatter function specialised to that column's schema + (closed over the Arrow `DataType` and any per-field + `databricks.type_name` metadata). + +Per-row, the formatter recurses through the type: + +- Primitives: `serde_json::Value::to_string()` on the canonical + Rust value (matching the per-type formatting table above). +- `List` / `Map` / `Struct`: walk children, recurse. +- `Utf8` with VARIANT/GEOMETRY/GEOGRAPHY metadata: pass through + the source value as-is (the server has already emitted it as + JSON / WKT text). + +The output array is built incrementally via `StringBuilder` for +each complex column. + +VARIANT / GEOMETRY / GEOGRAPHY columns can be handled by a fast +path that just copies the source `ArrayRef` (no re-emit needed), +since the data is already correct. + +### Schema rewriting + +The output schema mirrors the input's order and field names but +every complex column becomes `Utf8` nullable. Field metadata +(`databricks.*` keys) is preserved on the rewritten field so type +info isn't lost — consumers reading metadata can still tell the +original column was `ARRAY`. + +## Test plan + +- Unit tests on `json_stringify_batch` per type, exercising: + - Each primitive: scalar formatting, NULL handling. + - `ARRAY`, `ARRAY>`, `ARRAY`. + - `MAP` and `MAP>`. + - `STRUCT` with mixed primitive + nested fields. + - Empty containers, all-null containers. + - String quoting / escape characters / unicode / control chars. + - DECIMAL precision/scale boundaries (no scientific notation). +- Format comparison fixtures against captured Thrift output for + the `comparator_tests.oss_jdbc_tests.test_result_set_types` + rows the comparator uses. These get committed as golden files + so we know the format hasn't drifted. +- End-to-end via the comparator's `THRIFT_VS_KERNEL_COMPLEX_DISABLED` + suite — should drop from 5 diffs to 0 once the feature is on. + +## Migration + +- Default `false`: kernel behaviour unchanged for existing consumers. +- PySQL connector flips the flag when `_use_arrow_native_complex_types=False`. +- Native SEA backend (separate connector path) could also call into + this once exposed through the kernel — closes the same gap there + for free. Out of scope for the kernel work itself. +- JDBC: when the JDBC driver eventually migrates to the kernel, + it can drop `DatabricksArray.toString()` / `DatabricksMap.toString()` / + `DatabricksStruct.toString()` (~200 lines of Java) in favour of + the kernel option. +- ADBC: leaves the flag off, sees no change. + +## Open questions + +1. **VARIANT / GEOMETRY / GEOGRAPHY pass-through.** The server + emits these as text already; passing through is the obvious + choice. Worth confirming via a probe that the text form Thrift + delivers matches what SEA delivers, byte-for-byte. If they + diverge, the kernel needs to normalise. +2. **DECIMAL formatting.** Both Java's `BigDecimal.toString` and + Rust's `arrow_array::types::Decimal128` formatter emit fixed + notation, but the precise canonicalisation around trailing + zeros (e.g. `99.99` vs `99.9900`) may differ. Worth a probe + before committing. +3. **`TIMESTAMP` UTC offset format.** Java emits + `2024-01-15T10:30:00.000Z`; some Arrow formatters emit + `2024-01-15T10:30:00.000+00:00`. Match Thrift exactly. +4. **Per-statement override.** Defer — no current binding asks + for it. If JDBC ever needs to flip per-statement, revisit. diff --git a/src/client/sea.rs b/src/client/sea.rs index a47ecd3e..fd791688 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -368,14 +368,15 @@ impl SeaRestTransport { .await?; let response = self.wait_for_completion(response).await?; let reader_factory = self.reader_factory()?; - // `create_reader` wraps in a `ManifestAugmentingReader` + // `create_reader` wraps in a `ResultPostProcessor` // internally, so the reader returned here already carries // the server-reported per-column metadata // (`databricks.type_name` etc.) on its schema and on every // emitted batch. Bindings (PySQL, future ADBC) read those // attributes to recover the precise type for columns whose // Arrow shape collapses (VARIANT → Utf8, intervals → Interval, - // GEOMETRY/GEOGRAPHY → Utf8). + // GEOMETRY/GEOGRAPHY → Utf8). The post-processor also handles + // the optional complex-types-as-JSON rewrite in the same pass. let reader = reader_factory.create_reader(&response.statement_id, &response)?; // `server_state` carries the terminal state forward so the diff --git a/src/config.rs b/src/config.rs index fdf018b5..d7670592 100644 --- a/src/config.rs +++ b/src/config.rs @@ -372,6 +372,24 @@ pub struct ResultConfig { /// Maximum number of decompressed chunks held in memory at once. /// Bounds parallelism and peak RSS. pub cloudfetch_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. + /// + /// The JSON format matches what the Databricks server emits on + /// the Thrift wire when `complexTypesAsArrow=false` (compact — + /// no whitespace between separators, double-quoted strings, + /// JSON `null` for SQL NULL). + /// + /// Default `false`. Bindings that surface a flat-text view + /// (PySQL when `_use_arrow_native_complex_types=False`, JDBC + /// when `complexDatatypeSupport=false`) should set this `true`. + /// ADBC and any other Arrow-native consumer should leave it + /// `false`. + pub complex_types_as_json: bool, } impl Default for ResultConfig { @@ -380,6 +398,7 @@ impl Default for ResultConfig { cloudfetch_enabled: true, cloudfetch_link_prefetch_window: 10, cloudfetch_max_chunks_in_memory: 4, + complex_types_as_json: false, } } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 4abac058..46ff0e41 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -21,6 +21,7 @@ pub mod cloudfetch; pub mod inline; +pub mod post_processor; #[cfg(test)] pub(crate) mod test_utils; @@ -30,6 +31,7 @@ use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; use crate::reader::cloudfetch::link_fetcher::{SeaChunkLinkFetcher, SeaChunkLinkFetcherHandle}; use crate::reader::cloudfetch::streaming_provider::StreamingCloudFetchProvider; use crate::reader::inline::InlineArrowProvider; +use crate::reader::post_processor::{PostProcessOptions, ResultPostProcessor}; use crate::types::cloudfetch::{CloudFetchConfig, CloudFetchLink}; use crate::types::sea::{CompressionCodec, ResultManifest, StatementState}; use crate::util::runtime::block_on_in_runtime; @@ -49,6 +51,7 @@ pub(crate) struct ResultReaderFactory { client: Arc, http_client: Arc, config: CloudFetchConfig, + post_process_options: PostProcessOptions, runtime_handle: tokio::runtime::Handle, } @@ -58,12 +61,14 @@ impl ResultReaderFactory { client: Arc, http_client: Arc, config: CloudFetchConfig, + post_process_options: PostProcessOptions, runtime_handle: tokio::runtime::Handle, ) -> Self { Self { client, http_client, config, + post_process_options, runtime_handle, } } @@ -72,12 +77,16 @@ impl ResultReaderFactory { /// /// Automatically selects CloudFetch, inline, or other reader based /// on response. The returned reader is wrapped in a - /// [`ManifestAugmentingReader`] when the response carries a - /// [`ResultManifest`], so per-column metadata - /// (`databricks.type_name`, `databricks.type_text`, precision / - /// scale / interval kind) is attached to the schema and to every - /// emitted batch. Single insertion point for the ResultReader-trait - /// consumers — every caller of `create_reader` benefits automatically. + /// [`ResultPostProcessor`] that owns all per-batch post-processing + /// the kernel does on the way out to consumers: + /// + /// - manifest-driven metadata attachment (`databricks.type_name`, + /// `databricks.type_text`, precision / scale / interval kind); + /// - optional complex-type JSON stringification when the session + /// has `complex_types_as_json = true`. + /// + /// The post-processor is a single insertion point — every caller + /// of `create_reader` benefits automatically. /// /// There is one other augmentation site for Arrow-FFI consumers: /// [`ResultReaderAdapter::new`] also applies the same @@ -91,9 +100,10 @@ impl ResultReaderFactory { response: &ExecuteResponse, ) -> Result> { let inner = self.create_inner_reader(statement_id, response)?; - Ok(Box::new(ManifestAugmentingReader::new( + Ok(Box::new(ResultPostProcessor::new( inner, response.manifest.as_ref(), + self.post_process_options.clone(), )?)) } @@ -460,76 +470,6 @@ pub mod metadata_keys { pub const TYPE_INTERVAL_TYPE: &str = "databricks.type_interval_type"; } -/// Wrapper that augments an upstream `ResultReader`'s schema with -/// Databricks per-column metadata from the SEA `ResultManifest` -/// (server-reported `type_name`, `type_text`, precision, scale, -/// interval kind), and re-projects each emitted `RecordBatch` onto -/// that augmented schema so downstream consumers see the metadata -/// both on `ResultStream::schema()` and on `batch.schema()`. -/// -/// Active in the live `execute_and_read` path; transparent when -/// the manifest is absent (e.g. queries without column info). See -/// also [`ResultReaderAdapter`] for the Arrow-FFI-shaped wrapper. -pub(crate) struct ManifestAugmentingReader { - inner: Box, - schema: SchemaRef, -} - -impl ManifestAugmentingReader { - /// Build an augmenting wrapper around `inner`. - /// - /// When `manifest` is `Some`, the upstream schema is rewritten - /// to attach Databricks column metadata under the - /// `databricks.*` keys. When it's `None`, the wrapper is a - /// pass-through (so callers don't need to special-case the - /// metadata-less path). - pub(crate) fn new( - inner: Box, - manifest: Option<&ResultManifest>, - ) -> Result { - let schema = inner.schema()?; - let schema = match manifest { - Some(m) => ResultReaderAdapter::augment_schema_with_manifest(&schema, m), - None => schema, - }; - Ok(Self { inner, schema }) - } -} - -impl ResultReader for ManifestAugmentingReader { - fn schema(&self) -> Result { - Ok(self.schema.clone()) - } - - fn next_batch(&mut self) -> Result> { - match self.inner.next_batch()? { - None => Ok(None), - Some(batch) => { - // Re-project the batch's columns onto our augmented - // schema. Column count, types, and order are - // unchanged — only `Field::metadata()` differs — so - // this is a cheap rebuild that reuses the same - // `ArrayRef`s under the hood. - // - // A `try_new` failure here means the inner reader - // returned a batch whose array count / types don't - // match the schema it itself advertised — an internal - // invariant violation, not data corruption or a - // partial server response. Map to `Error::internal` - // so the error category matches the actual cause. - let columns: Vec = batch.columns().to_vec(); - RecordBatch::try_new(self.schema.clone(), columns) - .map(Some) - .map_err(|e| { - crate::kernel_error::Error::internal().message(format!( - "ManifestAugmentingReader: upstream batch shape disagrees with the schema it advertised: {e}" - )) - }) - } - } - } -} - /// Adapter to make ResultReader work as arrow's RecordBatchReader. pub struct ResultReaderAdapter { inner: Box, @@ -976,65 +916,7 @@ mod tests { .contains_key(metadata_keys::TYPE_NAME)); } - // --- ManifestAugmentingReader tests --- - - #[test] - fn test_manifest_augmenting_reader_attaches_metadata_to_schema_and_batches() { - // Server-shape: Utf8 column the kernel doesn't otherwise know - // is a VARIANT. The manifest carries the precise type. - let batch = make_test_batch(vec!["{\"a\":1}"]); - let reader: Box = Box::new(MockReader::new(vec![batch])); - let manifest = make_manifest(vec![make_column_info( - "name", "VARIANT", "VARIANT", 0, None, None, None, - )]); - - let mut wrapper = ManifestAugmentingReader::new(reader, Some(&manifest)).unwrap(); - - // Stream-level schema carries the metadata. - let schema = wrapper.schema().unwrap(); - assert_eq!( - schema.field(0).metadata().get(metadata_keys::TYPE_NAME), - Some(&"VARIANT".to_string()) - ); - - // Batches emitted by `next_batch` are re-projected onto the - // augmented schema, so consumers reading `batch.schema()` - // also see the metadata. - let batch = wrapper.next_batch().unwrap().expect("one batch"); - assert_eq!( - batch - .schema() - .field(0) - .metadata() - .get(metadata_keys::TYPE_NAME), - Some(&"VARIANT".to_string()) - ); - assert!(wrapper.next_batch().unwrap().is_none()); - } - - #[test] - fn test_manifest_augmenting_reader_passes_through_when_manifest_absent() { - let batch = make_test_batch(vec!["plain"]); - let reader: Box = Box::new(MockReader::new(vec![batch])); - - let mut wrapper = ManifestAugmentingReader::new(reader, None).unwrap(); - let schema = wrapper.schema().unwrap(); - assert!( - !schema - .field(0) - .metadata() - .contains_key(metadata_keys::TYPE_NAME), - "no manifest → no databricks.* metadata" - ); - - let batch = wrapper.next_batch().unwrap().expect("one batch"); - assert!( - !batch - .schema() - .field(0) - .metadata() - .contains_key(metadata_keys::TYPE_NAME), - "no manifest → batch schema also clean" - ); - } + // ManifestAugmentingReader behaviour is now covered by + // `post_processor::tests` — the wrapper itself was folded into + // `ResultPostProcessor`. } diff --git a/src/reader/post_processor/json.rs b/src/reader/post_processor/json.rs new file mode 100644 index 00000000..49dbf373 --- /dev/null +++ b/src/reader/post_processor/json.rs @@ -0,0 +1,862 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Compact JSON serialization of Arrow row values for complex types. +//! +//! The output matches what the Databricks server emits on the Thrift +//! wire when `complexTypesAsArrow=false` (and what the JDBC driver +//! produces from `DatabricksArray.toString()` / `DatabricksMap.toString()` / +//! `DatabricksStruct.toString()`): +//! +//! - no whitespace between separators (equivalent to +//! `json.dumps(obj, separators=(',', ':'))`); +//! - SQL NULL → JSON `null` (bare, not the string `"null"`); +//! - strings double-quoted with standard JSON escaping; +//! - map keys stringified and always rendered quoted; +//! - VARIANT / GEOMETRY / GEOGRAPHY values are server-emitted text +//! already, so they pass through verbatim. +//! +//! The entry point used by the post-processor is +//! [`append_json`], which writes one row's JSON form into an +//! existing `String` (so the outer column builder can append straight +//! into a `StringBuilder` without an intermediate allocation). + +use crate::kernel_error::{Error, Result}; +use crate::reader::metadata_keys; +use arrow_array::cast::AsArray; +use arrow_array::types::{ + Date32Type, Date64Type, Decimal128Type, Decimal256Type, DurationMicrosecondType, + DurationMillisecondType, DurationNanosecondType, DurationSecondType, Float32Type, Float64Type, + Int16Type, Int32Type, Int64Type, Int8Type, IntervalDayTimeType, IntervalMonthDayNanoType, + IntervalYearMonthType, TimestampMicrosecondType, TimestampMillisecondType, + TimestampNanosecondType, TimestampSecondType, UInt16Type, UInt32Type, UInt64Type, UInt8Type, +}; +use arrow_array::Array; +use arrow_schema::{DataType, Field, TimeUnit}; +use base64::Engine; +use std::fmt::Write as _; + +/// Write the JSON form of `array[index]` into `out`. +/// +/// `field` carries Databricks-specific metadata (VARIANT / GEOMETRY / +/// GEOGRAPHY hints) under `databricks.type_name`; we honour that to +/// decide whether a `Utf8` value should be quoted as a string or +/// passed through as already-JSON. +/// +/// On unsupported Arrow types, returns an `Error::not_implemented`. +/// We never panic on the hot path — a typed error is propagated up to +/// the result reader, which surfaces to the caller. +pub(crate) fn append_json( + out: &mut String, + array: &dyn Array, + index: usize, + field: &Field, +) -> Result<()> { + if array.is_null(index) { + out.push_str("null"); + return Ok(()); + } + + match array.data_type() { + DataType::Null => out.push_str("null"), + DataType::Boolean => { + let v = array.as_boolean().value(index); + out.push_str(if v { "true" } else { "false" }); + } + DataType::Int8 => write!(out, "{}", array.as_primitive::().value(index)).unwrap(), + DataType::Int16 => { + write!(out, "{}", array.as_primitive::().value(index)).unwrap() + } + DataType::Int32 => { + write!(out, "{}", array.as_primitive::().value(index)).unwrap() + } + DataType::Int64 => { + write!(out, "{}", array.as_primitive::().value(index)).unwrap() + } + DataType::UInt8 => { + write!(out, "{}", array.as_primitive::().value(index)).unwrap() + } + DataType::UInt16 => { + write!(out, "{}", array.as_primitive::().value(index)).unwrap() + } + DataType::UInt32 => { + write!(out, "{}", array.as_primitive::().value(index)).unwrap() + } + DataType::UInt64 => { + write!(out, "{}", array.as_primitive::().value(index)).unwrap() + } + DataType::Float32 => { + let v = array.as_primitive::().value(index); + append_float(out, v as f64); + } + DataType::Float64 => { + let v = array.as_primitive::().value(index); + append_float(out, v); + } + DataType::Decimal128(_, scale) => { + let raw = array.as_primitive::().value(index); + out.push_str(&format_decimal128(raw, *scale)); + } + DataType::Decimal256(_, scale) => { + let raw = array.as_primitive::().value(index); + out.push_str(&format_decimal256(raw, *scale)); + } + DataType::Utf8 => { + let s = array.as_string::().value(index); + append_utf8_value(out, s, field); + } + DataType::LargeUtf8 => { + let s = array.as_string::().value(index); + append_utf8_value(out, s, field); + } + DataType::Binary => { + let bytes = array.as_binary::().value(index); + append_quoted(out, &base64_encode(bytes)); + } + DataType::LargeBinary => { + let bytes = array.as_binary::().value(index); + append_quoted(out, &base64_encode(bytes)); + } + DataType::FixedSizeBinary(_) => { + let arr = array + .as_any() + .downcast_ref::() + .ok_or_else(|| { + Error::internal().message("FixedSizeBinary downcast failed in json encoder") + })?; + append_quoted(out, &base64_encode(arr.value(index))); + } + DataType::Date32 => { + let arr = array.as_primitive::(); + let date = arr.value_as_date(index).unwrap_or(chrono::NaiveDate::MIN); + append_quoted(out, &date.format("%Y-%m-%d").to_string()); + } + DataType::Date64 => { + let arr = array.as_primitive::(); + let date = arr.value_as_date(index).unwrap_or(chrono::NaiveDate::MIN); + append_quoted(out, &date.format("%Y-%m-%d").to_string()); + } + DataType::Timestamp(unit, tz) => { + let dt = match unit { + TimeUnit::Second => array + .as_primitive::() + .value_as_datetime(index), + TimeUnit::Millisecond => array + .as_primitive::() + .value_as_datetime(index), + TimeUnit::Microsecond => array + .as_primitive::() + .value_as_datetime(index), + TimeUnit::Nanosecond => array + .as_primitive::() + .value_as_datetime(index), + }; + let dt = dt.unwrap_or(chrono::DateTime::UNIX_EPOCH.naive_utc()); + // Render at the Arrow column's native subsecond precision + // so we don't silently truncate microseconds/nanoseconds — + // matches JDBC's `DatabricksArray.toString()` chain, which + // honours the underlying type's precision. + // + // TIMESTAMP carries a tz on the Arrow side; TIMESTAMP_NTZ + // does not. Match Thrift: tz'd → trailing 'Z', NTZ → no + // offset suffix. + let base = match unit { + TimeUnit::Second => dt.format("%Y-%m-%dT%H:%M:%S").to_string(), + TimeUnit::Millisecond => dt.format("%Y-%m-%dT%H:%M:%S%.3f").to_string(), + TimeUnit::Microsecond => dt.format("%Y-%m-%dT%H:%M:%S%.6f").to_string(), + TimeUnit::Nanosecond => dt.format("%Y-%m-%dT%H:%M:%S%.9f").to_string(), + }; + let s = if tz.is_some() { + format!("{base}Z") + } else { + base + }; + append_quoted(out, &s); + } + DataType::Interval(_) => { + // INTERVAL columns surface as either YEAR_MONTH or + // DAY_TIME variants depending on the SQL kind. We render + // the Databricks text form, matching JDBC's + // `Period`/`Duration`-style output. + let s = format_interval(array, index)?; + append_quoted(out, &s); + } + DataType::Duration(_) => { + let s = format_duration(array, index)?; + append_quoted(out, &s); + } + DataType::List(inner_field) => { + let arr = array.as_list::(); + let values = arr.value(index); + append_array_json(out, values.as_ref(), inner_field)?; + } + DataType::LargeList(inner_field) => { + let arr = array.as_list::(); + let values = arr.value(index); + append_array_json(out, values.as_ref(), inner_field)?; + } + DataType::FixedSizeList(inner_field, _) => { + let arr = array + .as_any() + .downcast_ref::() + .ok_or_else(|| { + Error::internal().message("FixedSizeList downcast failed in json encoder") + })?; + let values = arr.value(index); + append_array_json(out, values.as_ref(), inner_field)?; + } + DataType::Map(entries_field, _) => { + let arr = array.as_map(); + let entries = arr.value(index); + append_map_json(out, &entries, entries_field)?; + } + DataType::Struct(fields) => { + let arr = array.as_struct(); + append_struct_json(out, arr, index, fields)?; + } + other => { + return Err(Error::not_implemented().message(format!( + "JSON stringification not implemented for Arrow type {other:?}" + ))); + } + } + + 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. +/// +/// 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` +/// (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) { + if let Some(type_name) = field.metadata().get(metadata_keys::TYPE_NAME) { + match type_name.as_str() { + // VARIANT is a JSON value already (e.g. `{"a":1}`, + // `[1,2]`, `"foo"`, `null`); inserting another layer of + // quoting would corrupt it. + "VARIANT" => { + 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" => { + append_quoted(out, value); + return; + } + _ => {} + } + } + append_quoted(out, value); +} + +fn append_array_json(out: &mut String, values: &dyn Array, inner_field: &Field) -> Result<()> { + out.push('['); + let len = values.len(); + for i in 0..len { + if i > 0 { + out.push(','); + } + append_json(out, values, i, inner_field)?; + } + out.push(']'); + Ok(()) +} + +fn append_map_json( + out: &mut String, + entries: &arrow_array::StructArray, + entries_field: &Field, +) -> Result<()> { + out.push('{'); + let (key_field, value_field) = match entries_field.data_type() { + DataType::Struct(fields) if fields.len() == 2 => (fields[0].clone(), fields[1].clone()), + other => { + return Err(Error::internal() + .message(format!("Map entries field has unexpected shape: {other:?}"))); + } + }; + let keys = entries.column(0); + let values = entries.column(1); + for i in 0..entries.len() { + if i > 0 { + out.push(','); + } + // Map keys: render the value via the same rules and force + // quoted-string output. For string keys this is a no-op; for + // numeric keys it produces `"42":...` (matches JDBC). + if keys.is_null(i) { + // Null map keys are a server-side anomaly. Match JDBC, + // which writes the literal string "null" (quoted) rather + // than corrupting the JSON shape. + out.push_str("\"null\""); + } else { + let mut key_buf = String::new(); + append_json(&mut key_buf, keys.as_ref(), i, &key_field)?; + if key_buf.starts_with('"') { + out.push_str(&key_buf); + } else if key_buf == "null" { + // A non-null key whose value rendered as bare `null` + // can only come from `append_float` collapsing + // NaN / ±Inf. Disambiguate from the actual null-key + // case above by emitting the standard textual form. + let f = float_key_value(keys.as_ref(), i); + let text = match f { + Some(v) if v.is_nan() => "NaN", + Some(v) if v.is_sign_negative() => "-Infinity", + Some(_) => "Infinity", + None => "null", + }; + append_quoted(out, text); + } else { + // Non-string key — wrap the rendered value in quotes. + append_quoted(out, &key_buf); + } + } + out.push(':'); + append_json(out, values.as_ref(), i, &value_field)?; + } + out.push('}'); + Ok(()) +} + +fn append_struct_json( + out: &mut String, + arr: &arrow_array::StructArray, + row: usize, + fields: &arrow_schema::Fields, +) -> Result<()> { + out.push('{'); + for (i, field) in fields.iter().enumerate() { + if i > 0 { + out.push(','); + } + append_quoted(out, field.name()); + out.push(':'); + let column = arr.column(i); + append_json(out, column.as_ref(), row, field)?; + } + out.push('}'); + Ok(()) +} + +fn append_quoted(out: &mut String, s: &str) { + out.push('"'); + for ch in s.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\x08' => out.push_str("\\b"), + '\x0c' => out.push_str("\\f"), + c if (c as u32) < 0x20 => { + // Other control chars → \uXXXX. + write!(out, "\\u{:04x}", c as u32).unwrap(); + } + c => out.push(c), + } + } + out.push('"'); +} + +/// Return the float value at `index` for Float32/Float64 arrays, used +/// to disambiguate map keys whose `append_json` form collapsed to bare +/// `null` (NaN / ±Inf). Returns `None` for any other array type. +fn float_key_value(array: &dyn Array, index: usize) -> Option { + match array.data_type() { + DataType::Float32 => Some(array.as_primitive::().value(index) as f64), + DataType::Float64 => Some(array.as_primitive::().value(index)), + _ => None, + } +} + +fn append_float(out: &mut String, v: f64) { + if v.is_nan() || v.is_infinite() { + // NaN / ±Inf are not valid JSON; emit `null` to stay parseable. + out.push_str("null"); + return; + } + // Rust's `{}` formatter for f64 uses the shortest round-trippable + // representation, matching Java's `Double.toString`. + write!(out, "{v}").unwrap(); +} + +fn format_decimal128(raw: i128, scale: i8) -> String { + if scale == 0 { + return raw.to_string(); + } + if scale < 0 { + // Negative scale means the stored integer represents + // `raw * 10^|scale|`. Databricks doesn't emit these in + // practice, but if it ever does we render the magnified + // integer with trailing zeros rather than silently dropping + // the multiplier. + let zeros = "0".repeat((-(scale as i32)) as usize); + return format!("{raw}{zeros}"); + } + let scale = scale as u32; + let divisor = 10_i128.pow(scale); + let sign = if raw < 0 { "-" } else { "" }; + let abs_raw = raw.unsigned_abs(); + let whole = abs_raw / divisor as u128; + let frac = abs_raw % divisor as u128; + format!("{sign}{whole}.{frac:0>width$}", width = scale as usize) +} + +fn format_decimal256(raw: arrow_buffer::i256, scale: i8) -> String { + // Defer to the arrow formatter — Decimal256 isn't trivially + // splittable with native arithmetic. + let s = raw.to_string(); + if scale == 0 { + return s; + } + if scale < 0 { + // Same multiplier-bearing rendering as Decimal128 negative + // scale. Dormant in practice on Databricks. + let zeros = "0".repeat((-(scale as i32)) as usize); + return format!("{s}{zeros}"); + } + let scale = scale as usize; + // Insert a decimal point `scale` digits from the right of the + // unsigned representation. + let (sign, digits) = if let Some(rest) = s.strip_prefix('-') { + ("-", rest.to_string()) + } else { + ("", s) + }; + if digits.len() <= scale { + let pad = "0".repeat(scale - digits.len()); + format!("{sign}0.{pad}{digits}") + } else { + let split = digits.len() - scale; + format!("{sign}{}.{}", &digits[..split], &digits[split..]) + } +} + +/// Base64-encode binary payloads inside JSON arrays/maps/structs. +/// +/// Uses RFC 4648 standard encoding (with `=` padding) to match the +/// JDBC reference, whose `DatabricksArray.toString()` defers to +/// `java.util.Base64.getEncoder()` — that encoder is the standard +/// padded one. Switching to the URL-safe or no-padding variant here +/// would byte-mismatch the comparator. +fn base64_encode(bytes: &[u8]) -> String { + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +fn format_interval(array: &dyn Array, index: usize) -> Result { + match array.data_type() { + DataType::Interval(arrow_schema::IntervalUnit::YearMonth) => { + let months = array.as_primitive::().value(index); + let sign = if months < 0 { "-" } else { "" }; + let m = months.unsigned_abs(); + Ok(format!("{sign}{}-{}", m / 12, m % 12)) + } + DataType::Interval(arrow_schema::IntervalUnit::DayTime) => { + let v = array.as_primitive::().value(index); + // arrow_buffer::IntervalDayTime fields: days (i32), milliseconds (i32). + let days = v.days as i64; + let millis = v.milliseconds as i64; + Ok(format_day_time_interval(days, millis * 1_000_000)) + } + DataType::Interval(arrow_schema::IntervalUnit::MonthDayNano) => { + let v = array + .as_primitive::() + .value(index); + // Arrow's MonthDayNano can carry all three components; + // Databricks INTERVAL columns only populate one variant + // at a time, so a non-zero `months` field unambiguously + // identifies a YEAR_MONTH interval. The all-zero case + // `(0, 0, 0)` is ambiguous between zero YEAR_MONTH and + // zero DAY_TIME — we resolve it to DAY_TIME form + // (`"0 00:00:00.000000000"`) since Databricks emits + // explicit interval subtypes upstream (the dedicated + // YearMonth Arrow type for YEAR_MONTH columns), so a + // MonthDayNano column reaching here is in DAY_TIME + // semantics by construction. + if v.months != 0 && v.days == 0 && v.nanoseconds == 0 { + let months = v.months; + let sign = if months < 0 { "-" } else { "" }; + let m = months.unsigned_abs(); + Ok(format!("{sign}{}-{}", m / 12, m % 12)) + } else { + Ok(format_day_time_interval(v.days as i64, v.nanoseconds)) + } + } + other => Err(Error::internal().message(format!("not an interval type: {other:?}"))), + } +} + +fn format_day_time_interval(days: i64, nanos: i64) -> String { + let total_nanos: i128 = (days as i128) * 86_400 * 1_000_000_000 + nanos as i128; + let negative = total_nanos < 0; + let abs_nanos = total_nanos.unsigned_abs(); + let nanos_per_sec: u128 = 1_000_000_000; + let total_secs = (abs_nanos / nanos_per_sec) as u64; + let nanos_rem = (abs_nanos % nanos_per_sec) as u32; + let d = total_secs / 86_400; + let rem = total_secs % 86_400; + let h = rem / 3_600; + let m = (rem % 3_600) / 60; + let s = rem % 60; + let sign = if negative { "-" } else { "" }; + format!("{sign}{d} {h:02}:{m:02}:{s:02}.{nanos_rem:09}") +} + +fn format_duration(array: &dyn Array, index: usize) -> Result { + let nanos: i128 = match array.data_type() { + DataType::Duration(TimeUnit::Second) => { + (array.as_primitive::().value(index) as i128) * 1_000_000_000 + } + DataType::Duration(TimeUnit::Millisecond) => { + (array.as_primitive::().value(index) as i128) * 1_000_000 + } + DataType::Duration(TimeUnit::Microsecond) => { + (array.as_primitive::().value(index) as i128) * 1_000 + } + DataType::Duration(TimeUnit::Nanosecond) => { + array.as_primitive::().value(index) as i128 + } + other => { + return Err(Error::internal().message(format!("not a duration type: {other:?}"))); + } + }; + let total_nanos = nanos; + let days = (total_nanos / (86_400 * 1_000_000_000)) as i64; + let remainder = total_nanos - (days as i128) * 86_400 * 1_000_000_000; + Ok(format_day_time_interval(days, remainder as i64)) +} + +/// Returns `true` when `dt` is an Arrow type that the JSON path +/// should stringify into a `Utf8` column. Primitive columns and +/// `Utf8`/`Binary` columns are pass-through unless their field +/// metadata marks them as VARIANT/GEOMETRY/GEOGRAPHY — which the +/// post-processor already keeps as `Utf8` either way (we only +/// stringify nested structure). +pub(crate) fn is_complex_type(dt: &DataType) -> bool { + matches!( + dt, + DataType::List(_) + | DataType::LargeList(_) + | DataType::FixedSizeList(_, _) + | DataType::Map(_, _) + | DataType::Struct(_) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::builder::{Int32Builder, ListBuilder, MapBuilder, StringBuilder}; + use arrow_array::{Int32Array, StringArray, StructArray}; + use arrow_schema::{DataType, Field, Fields}; + use std::collections::HashMap; + use std::sync::Arc; + + fn field_of(dt: DataType) -> Field { + Field::new("x", dt, true) + } + + fn render(arr: &dyn Array, idx: usize, field: &Field) -> String { + let mut s = String::new(); + append_json(&mut s, arr, idx, field).unwrap(); + s + } + + #[test] + fn primitives_render_bare() { + assert_eq!( + render(&Int32Array::from(vec![42]), 0, &field_of(DataType::Int32),), + "42" + ); + assert_eq!( + render( + &arrow_array::Float64Array::from(vec![2.5]), + 0, + &field_of(DataType::Float64), + ), + "2.5" + ); + assert_eq!( + render( + &arrow_array::BooleanArray::from(vec![true]), + 0, + &field_of(DataType::Boolean), + ), + "true" + ); + } + + #[test] + fn null_renders_bare_null() { + let arr = Int32Array::from(vec![None]); + assert_eq!(render(&arr, 0, &field_of(DataType::Int32)), "null"); + } + + #[test] + fn string_is_quoted_and_escaped() { + let arr = StringArray::from(vec!["he said \"hi\"\n\t"]); + assert_eq!( + render(&arr, 0, &field_of(DataType::Utf8)), + "\"he said \\\"hi\\\"\\n\\t\"" + ); + } + + #[test] + fn float_nan_inf_become_null() { + let arr = arrow_array::Float64Array::from(vec![f64::NAN, f64::INFINITY, f64::NEG_INFINITY]); + for i in 0..3 { + assert_eq!(render(&arr, i, &field_of(DataType::Float64)), "null"); + } + } + + #[test] + fn list_of_strings_renders_as_array() { + let mut b = ListBuilder::new(StringBuilder::new()); + b.values().append_value("a"); + b.values().append_value("b"); + b.values().append_value("c"); + b.append(true); + let arr = b.finish(); + let field = Field::new( + "x", + DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))), + true, + ); + assert_eq!(render(&arr, 0, &field), "[\"a\",\"b\",\"c\"]"); + } + + #[test] + fn empty_list_renders_as_empty_brackets() { + let mut b = ListBuilder::new(StringBuilder::new()); + b.append(true); + let arr = b.finish(); + let field = Field::new( + "x", + DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))), + true, + ); + assert_eq!(render(&arr, 0, &field), "[]"); + } + + #[test] + fn null_inside_list_renders_bare() { + let mut b = ListBuilder::new(Int32Builder::new()); + b.values().append_value(1); + b.values().append_null(); + b.values().append_value(3); + b.append(true); + let arr = b.finish(); + let field = Field::new( + "x", + DataType::List(Arc::new(Field::new("item", DataType::Int32, true))), + true, + ); + assert_eq!(render(&arr, 0, &field), "[1,null,3]"); + } + + #[test] + fn struct_renders_with_field_order_and_quoting() { + let fields: Fields = vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::Int32, true), + ] + .into(); + let arr = StructArray::new( + fields.clone(), + vec![ + Arc::new(StringArray::from(vec!["foo"])) as _, + Arc::new(Int32Array::from(vec![1])) as _, + ], + None, + ); + let field = Field::new("x", DataType::Struct(fields), true); + assert_eq!(render(&arr, 0, &field), "{\"a\":\"foo\",\"b\":1}"); + } + + #[test] + fn map_string_string_renders() { + let mut b = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + b.keys().append_value("k1"); + b.values().append_value("v1"); + b.keys().append_value("k2"); + b.values().append_value("v2"); + b.append(true).unwrap(); + let arr = b.finish(); + let entries_field = match arr.data_type() { + DataType::Map(ef, _) => (**ef).clone(), + _ => unreachable!(), + }; + let field = Field::new("x", DataType::Map(Arc::new(entries_field), false), true); + assert_eq!(render(&arr, 0, &field), "{\"k1\":\"v1\",\"k2\":\"v2\"}"); + } + + #[test] + fn variant_pass_through_no_quoting() { + let arr = StringArray::from(vec!["{\"a\":1}"]); + let mut metadata: HashMap = HashMap::new(); + metadata.insert(metadata_keys::TYPE_NAME.to_string(), "VARIANT".to_string()); + let field = Field::new("x", DataType::Utf8, true).with_metadata(metadata); + assert_eq!(render(&arr, 0, &field), "{\"a\":1}"); + } + + #[test] + fn geometry_quoted_as_wkt() { + let arr = StringArray::from(vec!["POINT (1.5 2.5)"]); + let mut metadata: HashMap = HashMap::new(); + metadata.insert(metadata_keys::TYPE_NAME.to_string(), "GEOMETRY".to_string()); + let field = Field::new("x", DataType::Utf8, true).with_metadata(metadata); + assert_eq!(render(&arr, 0, &field), "\"POINT (1.5 2.5)\""); + } + + #[test] + fn decimal128_renders_with_scale() { + let arr = arrow_array::Decimal128Array::from(vec![9999_i128]) + .with_precision_and_scale(10, 2) + .unwrap(); + let field = field_of(DataType::Decimal128(10, 2)); + assert_eq!(render(&arr, 0, &field), "99.99"); + } + + #[test] + fn binary_renders_base64() { + let arr = arrow_array::BinaryArray::from(vec![b"hello".as_ref()]); + let field = field_of(DataType::Binary); + assert_eq!(render(&arr, 0, &field), "\"aGVsbG8=\""); + } + + #[test] + fn date32_renders_iso() { + let arr = arrow_array::Date32Array::from(vec![19737]); // 2024-01-15 + let field = field_of(DataType::Date32); + assert_eq!(render(&arr, 0, &field), "\"2024-01-15\""); + } + + #[test] + fn struct_field_null_renders_json_null() { + let fields: Fields = vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::Int32, true), + ] + .into(); + let arr = StructArray::new( + fields.clone(), + vec![ + Arc::new(StringArray::from(vec!["foo"])) as _, + Arc::new(Int32Array::from(vec![None])) as _, + ], + None, + ); + let field = Field::new("x", DataType::Struct(fields), true); + assert_eq!(render(&arr, 0, &field), "{\"a\":\"foo\",\"b\":null}"); + } + + #[test] + fn timestamp_microsecond_precision_preserved() { + let arr = arrow_array::TimestampMicrosecondArray::from(vec![1_705_314_600_123_456_i64]); + let field = field_of(DataType::Timestamp(TimeUnit::Microsecond, None)); + // 2024-01-15T10:30:00.123456 (NTZ → no Z). + assert_eq!(render(&arr, 0, &field), "\"2024-01-15T10:30:00.123456\""); + } + + #[test] + fn timestamp_nanosecond_with_tz_keeps_nine_digits_and_z() { + let arr = arrow_array::TimestampNanosecondArray::from(vec![1_705_314_600_123_456_789_i64]) + .with_timezone("UTC"); + let field = field_of(DataType::Timestamp( + TimeUnit::Nanosecond, + Some("UTC".into()), + )); + assert_eq!( + render(&arr, 0, &field), + "\"2024-01-15T10:30:00.123456789Z\"" + ); + } + + #[test] + fn map_float_key_nan_renders_as_nan_not_null() { + // MAP with NaN / +Inf / -Inf keys. Before the + // fix, `append_float` collapsed each to bare `null` and the + // map-key wrapper turned them into `"null"`, indistinguishable + // from an actual null-key entry. The fix detects the + // non-finite numeric key in the wrapper and emits the standard + // textual form. + use arrow_array::builder::Int32Builder; + use arrow_array::builder::MapBuilder; + let mut b = MapBuilder::new( + None, + arrow_array::builder::Float64Builder::new(), + Int32Builder::new(), + ); + b.keys().append_value(f64::NAN); + b.values().append_value(1); + b.keys().append_value(f64::INFINITY); + b.values().append_value(2); + b.keys().append_value(f64::NEG_INFINITY); + b.values().append_value(3); + b.append(true).unwrap(); + let arr = b.finish(); + let entries_field = match arr.data_type() { + DataType::Map(ef, _) => (**ef).clone(), + _ => unreachable!(), + }; + let field = Field::new("x", DataType::Map(Arc::new(entries_field), false), true); + assert_eq!( + render(&arr, 0, &field), + "{\"NaN\":1,\"Infinity\":2,\"-Infinity\":3}" + ); + } + + #[test] + fn nested_variant_inside_list_is_escaped_known_limitation() { + // Known limitation pinned: ARRAY inner fields don't + // carry `databricks.type_name=VARIANT` because the manifest + // augmenter only attaches it to top-level fields. Until we + // propagate metadata into inner Arrow fields (would require + // parsing the manifest's `type_text`), nested VARIANT elements + // are JSON-escaped as plain strings rather than passed + // through. This test exists to surface a behavior change + // loudly if we ever fix the propagation. + let mut b = ListBuilder::new(StringBuilder::new()); + b.values().append_value("{\"a\":1}"); + b.append(true); + let arr = b.finish(); + // Mark the OUTER field as VARIANT — has no effect on inner + // rendering, which is the bug. + let mut metadata: HashMap = HashMap::new(); + metadata.insert(metadata_keys::TYPE_NAME.to_string(), "VARIANT".to_string()); + let field = Field::new( + "x", + DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))), + true, + ) + .with_metadata(metadata); + assert_eq!(render(&arr, 0, &field), "[\"{\\\"a\\\":1}\"]"); + } +} diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs new file mode 100644 index 00000000..93af0e73 --- /dev/null +++ b/src/reader/post_processor/mod.rs @@ -0,0 +1,509 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Consolidated post-processing for result batches. +//! +//! The kernel performs a small amount of work between the wire reader +//! and the consumer: +//! +//! - **Manifest augmentation**: copy server-reported per-column +//! metadata (`databricks.type_name`, precision, scale, interval +//! kind, …) onto the Arrow schema so consumers reading +//! `batch.schema()` see it. +//! - **Complex-type JSON stringification** (optional, off by +//! default): replace `List` / `Map` / `Struct` columns with `Utf8` +//! columns of compact JSON text, matching the Thrift wire +//! `complexTypesAsArrow=false` output. Opt in per session via +//! [`ResultConfig::complex_types_as_json`](crate::config::ResultConfig::complex_types_as_json). +//! +//! Both transforms share one wrapper so the hot path is a single +//! `next_batch` indirection regardless of how many transforms are +//! active, and so the "no work" case is genuinely zero-cost. +//! +//! See `docs/designs/complex-types-json-stringify.md` for the design. + +mod json; + +use crate::kernel_error::{Error, Result}; +use crate::reader::{ResultReader, ResultReaderAdapter}; +use crate::types::sea::ResultManifest; +use arrow_array::builder::StringBuilder; +use arrow_array::{ArrayRef, RecordBatch}; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use std::sync::Arc; + +/// Optional per-batch transforms the post-processor applies. +#[derive(Debug, Clone, Default)] +pub(crate) struct PostProcessOptions { + /// When `true`, complex columns (`List` / `LargeList` / + /// `FixedSizeList` / `Map` / `Struct`) are replaced with `Utf8` + /// columns containing compact JSON text per row. See + /// [`ResultConfig::complex_types_as_json`](crate::config::ResultConfig::complex_types_as_json). + pub complex_types_as_json: bool, +} + +/// Wrapper that runs all per-batch post-processing the kernel does +/// today on the way out to consumers, in a single pass. +/// +/// Consolidates what was previously a `ManifestAugmentingReader` (PR +/// #35) and reserves capacity for future transforms (e.g. interval +/// stringification, GEOMETRY normalisation) without growing a new +/// wrapper layer per transform. +/// +/// The constructor inspects the upstream schema + manifest + options +/// once, decides what — if anything — needs to happen per batch, and +/// stores a single `Option` closure. When the closure +/// is `None`, `next_batch` is true pass-through (no allocation, no +/// rebuild); when it's `Some`, the closure runs every active +/// transform in one fused walk so we never pay multiple +/// `RecordBatch::try_new` rebuilds for the same upstream batch. +pub(crate) struct ResultPostProcessor { + inner: Box, + schema: SchemaRef, + transform: Option, +} + +type BatchTransform = Box Result + Send + Sync>; + +impl ResultPostProcessor { + /// Build a post-processor around `inner`. + /// + /// `manifest` is the SEA `ResultManifest` carrying server-reported + /// per-column metadata; `None` for upstreams that don't have one + /// (e.g. legacy paths). `options` toggles optional transforms + /// (today: complex-type JSON stringification). + pub(crate) fn new( + inner: Box, + manifest: Option<&ResultManifest>, + options: PostProcessOptions, + ) -> Result { + let inner_schema = inner.schema()?; + + // 1. Compute the output schema after manifest augmentation + // (no-op when manifest is None). + let augmented_schema = match manifest { + Some(m) => ResultReaderAdapter::augment_schema_with_manifest(&inner_schema, m), + None => inner_schema.clone(), + }; + + // 2. JSON-stringification rewrite: identify complex columns + // in the augmented schema and turn them into nullable Utf8 + // while preserving the Databricks metadata. + let mut json_columns: Vec = Vec::new(); + let output_schema: SchemaRef = if options.complex_types_as_json { + let mut new_fields: Vec = Vec::with_capacity(augmented_schema.fields().len()); + for (i, field) in augmented_schema.fields().iter().enumerate() { + if json::is_complex_type(field.data_type()) { + json_columns.push(i); + let metadata = field.metadata().clone(); + new_fields.push( + Field::new(field.name(), DataType::Utf8, true).with_metadata(metadata), + ); + } else { + new_fields.push(field.as_ref().clone()); + } + } + Arc::new(Schema::new_with_metadata( + new_fields, + augmented_schema.metadata().clone(), + )) + } else { + augmented_schema.clone() + }; + + // 3. Decide whether we need a per-batch transform at all. + // + // Cases: + // - `inner_schema == output_schema` (Arc-eq or + // structurally identical): no work needed. + // - Output schema differs only in field metadata (manifest + // augmentation, no JSON rewrite): a single + // `RecordBatch::try_new` re-project onto the augmented + // schema. + // - JSON columns present: fused walk that re-projects + // primitives and emits new Utf8 arrays for complex + // columns. + let needs_rebuild = !schemas_field_equal(&inner_schema, &output_schema); + let transform: Option = if !needs_rebuild && json_columns.is_empty() { + None + } else if json_columns.is_empty() { + // Manifest-only path: cheap re-project. Reuses upstream + // ArrayRefs unchanged. + let target_schema = output_schema.clone(); + Some(Box::new(move |batch: &RecordBatch| { + let columns: Vec = batch.columns().to_vec(); + RecordBatch::try_new(target_schema.clone(), columns).map_err(|e| { + Error::internal().message(format!( + "ResultPostProcessor: upstream batch shape disagrees with the schema it advertised: {e}" + )) + }) + })) + } else { + // Fused walk: re-project primitives, stringify complex + // columns. Captures only what each closure invocation + // actually needs. + let target_schema = output_schema.clone(); + let augmented = augmented_schema.clone(); + let json_cols: Vec = json_columns; + Some(Box::new(move |batch: &RecordBatch| { + build_json_batch(batch, &augmented, &target_schema, &json_cols) + })) + }; + + Ok(Self { + inner, + schema: output_schema, + transform, + }) + } +} + +impl ResultReader for ResultPostProcessor { + fn schema(&self) -> Result { + Ok(self.schema.clone()) + } + + fn next_batch(&mut self) -> Result> { + let Some(batch) = self.inner.next_batch()? else { + return Ok(None); + }; + match &self.transform { + Some(t) => Ok(Some(t(&batch)?)), + None => Ok(Some(batch)), + } + } +} + +/// Compare schemas by their field sequence including per-field +/// metadata. Faster than serialising both sides; sufficient because +/// the augmenter only rewrites `Field::metadata` (and the JSON path +/// rewrites field type, which `Field::eq` already covers). +fn schemas_field_equal(a: &SchemaRef, b: &SchemaRef) -> bool { + if Arc::ptr_eq(a, b) { + return true; + } + if a.fields().len() != b.fields().len() { + return false; + } + a.fields() + .iter() + .zip(b.fields().iter()) + .all(|(x, y)| x == y) + && a.metadata() == b.metadata() +} + +/// Build a `RecordBatch` whose primitive columns are reprojected +/// from `batch` and whose complex columns (indexed by `json_cols`) +/// are replaced with `Utf8` arrays of compact JSON text. +fn build_json_batch( + batch: &RecordBatch, + augmented: &SchemaRef, + output: &SchemaRef, + json_cols: &[usize], +) -> Result { + let num_rows = batch.num_rows(); + let mut columns: Vec = Vec::with_capacity(batch.num_columns()); + + let mut next_json_idx = 0; + for (col_idx, column) in batch.columns().iter().enumerate() { + let is_json = json_cols + .get(next_json_idx) + .copied() + .is_some_and(|target| target == col_idx); + if is_json { + next_json_idx += 1; + // Use the augmented field (carries databricks.* metadata) + // so the per-row encoder can see VARIANT / GEOMETRY / + // GEOGRAPHY hints if they ever apply to a complex column. + // Guard against an upstream batch that has more columns + // than the schema it advertised — `Schema::field` would + // panic; we want a typed `Error::internal` instead. + let field = augmented.fields().get(col_idx).ok_or_else(|| { + Error::internal().message(format!( + "ResultPostProcessor: upstream batch has {} columns but advertised schema only has {}", + batch.num_columns(), + augmented.fields().len() + )) + })?; + let mut builder = StringBuilder::with_capacity(num_rows, num_rows * 16); + let mut scratch = String::new(); + for row in 0..num_rows { + if column.is_null(row) { + builder.append_null(); + continue; + } + scratch.clear(); + json::append_json(&mut scratch, column.as_ref(), row, field.as_ref())?; + builder.append_value(&scratch); + } + columns.push(Arc::new(builder.finish())); + } else { + columns.push(column.clone()); + } + } + + RecordBatch::try_new(output.clone(), columns).map_err(|e| { + Error::internal().message(format!( + "ResultPostProcessor: failed to assemble JSON-rewritten batch: {e}" + )) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::reader::metadata_keys; + use crate::reader::test_utils::MockReader; + use crate::reader::ResultReader; + use crate::types::sea::{ColumnInfo, ResultSchema}; + use arrow_array::builder::{ListBuilder, MapBuilder, StringBuilder}; + use arrow_array::{Array, Int32Array, StringArray, StructArray}; + use arrow_schema::Fields; + + fn make_manifest(columns: Vec) -> ResultManifest { + ResultManifest { + format: "ARROW_STREAM".to_string(), + schema: ResultSchema { + column_count: columns.len() as i32, + columns, + }, + total_chunk_count: None, + total_row_count: None, + total_byte_count: None, + truncated: false, + chunks: None, + result_compression: None, + } + } + + fn column_info(name: &str, type_name: &str, type_text: &str, position: i32) -> ColumnInfo { + ColumnInfo { + name: name.to_string(), + type_name: type_name.to_string(), + type_text: type_text.to_string(), + position, + type_precision: None, + type_scale: None, + type_interval_type: None, + } + } + + #[test] + fn pass_through_when_no_manifest_and_json_off() { + let schema = Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, true)])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(StringArray::from(vec!["hi"])) as _], + ) + .unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + + let mut pp = ResultPostProcessor::new(inner, None, PostProcessOptions::default()).unwrap(); + // No transform should have been installed. + assert!(pp.transform.is_none()); + let out = pp.next_batch().unwrap().unwrap(); + assert_eq!(out.num_rows(), 1); + assert_eq!(out.schema().field(0).metadata().len(), 0); + } + + #[test] + fn manifest_only_attaches_metadata_to_batches() { + let schema = Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, true)])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(StringArray::from(vec!["v"])) as _], + ) + .unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + let manifest = make_manifest(vec![column_info("name", "VARIANT", "VARIANT", 0)]); + + let mut pp = + ResultPostProcessor::new(inner, Some(&manifest), PostProcessOptions::default()) + .unwrap(); + assert!(pp.transform.is_some()); + + let out = pp.next_batch().unwrap().unwrap(); + assert_eq!( + out.schema() + .field(0) + .metadata() + .get(metadata_keys::TYPE_NAME), + Some(&"VARIANT".to_string()) + ); + } + + #[test] + fn json_path_rewrites_list_column_to_utf8() { + // Build a one-row batch with a list column. + let mut list_b = ListBuilder::new(arrow_array::builder::Int32Builder::new()); + list_b.values().append_value(1); + list_b.values().append_value(2); + list_b.values().append_value(3); + list_b.append(true); + let list_arr = list_b.finish(); + + let list_field = Field::new( + "vals", + DataType::List(Arc::new(Field::new("item", DataType::Int32, true))), + true, + ); + let other_field = Field::new("n", DataType::Int32, true); + let schema = Arc::new(Schema::new(vec![list_field, other_field])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(list_arr) as _, + Arc::new(Int32Array::from(vec![7])) as _, + ], + ) + .unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + + let opts = PostProcessOptions { + complex_types_as_json: true, + }; + let mut pp = ResultPostProcessor::new(inner, None, opts).unwrap(); + + // Output schema should expose Utf8 for the complex column. + let out_schema = pp.schema().unwrap(); + assert_eq!(out_schema.field(0).data_type(), &DataType::Utf8); + assert_eq!(out_schema.field(1).data_type(), &DataType::Int32); + + let out_batch = pp.next_batch().unwrap().unwrap(); + let arr = out_batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(arr.value(0), "[1,2,3]"); + // Primitive column reprojected unchanged. + let other = out_batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(other.value(0), 7); + } + + #[test] + fn json_path_handles_null_list_value() { + let mut list_b = ListBuilder::new(arrow_array::builder::Int32Builder::new()); + list_b.append(false); // null + list_b.values().append_value(1); + list_b.append(true); + let list_arr = list_b.finish(); + + let list_field = Field::new( + "vals", + DataType::List(Arc::new(Field::new("item", DataType::Int32, true))), + true, + ); + let schema = Arc::new(Schema::new(vec![list_field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(list_arr) as _]).unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + + let opts = PostProcessOptions { + complex_types_as_json: true, + }; + let mut pp = ResultPostProcessor::new(inner, None, opts).unwrap(); + let out_batch = pp.next_batch().unwrap().unwrap(); + let arr = out_batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(arr.is_null(0)); + assert_eq!(arr.value(1), "[1]"); + } + + #[test] + fn json_path_struct_renders_fields_in_order() { + let fields: Fields = vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::Int32, true), + ] + .into(); + let struct_arr = StructArray::new( + fields.clone(), + vec![ + Arc::new(StringArray::from(vec!["foo"])) as _, + Arc::new(Int32Array::from(vec![1])) as _, + ], + None, + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "s", + DataType::Struct(fields), + true, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(struct_arr) as _]).unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + + let opts = PostProcessOptions { + complex_types_as_json: true, + }; + let mut pp = ResultPostProcessor::new(inner, None, opts).unwrap(); + let out = pp.next_batch().unwrap().unwrap(); + let arr = out + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(arr.value(0), "{\"a\":\"foo\",\"b\":1}"); + } + + #[test] + fn json_path_map_renders_object() { + let mut b = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + b.keys().append_value("k"); + b.values().append_value("v"); + b.append(true).unwrap(); + let map_arr = b.finish(); + let map_dt = map_arr.data_type().clone(); + + let schema = Arc::new(Schema::new(vec![Field::new("m", map_dt, true)])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(map_arr) as _]).unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + + let opts = PostProcessOptions { + complex_types_as_json: true, + }; + let mut pp = ResultPostProcessor::new(inner, None, opts).unwrap(); + let out = pp.next_batch().unwrap().unwrap(); + let arr = out + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(arr.value(0), "{\"k\":\"v\"}"); + } + + #[test] + fn json_off_leaves_complex_columns_intact() { + let mut list_b = ListBuilder::new(arrow_array::builder::Int32Builder::new()); + list_b.values().append_value(1); + list_b.append(true); + let list_arr = list_b.finish(); + let list_dt = list_arr.data_type().clone(); + + let schema = Arc::new(Schema::new(vec![Field::new("vals", list_dt.clone(), true)])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(list_arr) as _]).unwrap(); + let inner: Box = Box::new(MockReader::new(vec![batch])); + + let mut pp = ResultPostProcessor::new(inner, None, PostProcessOptions::default()).unwrap(); + assert_eq!(pp.schema().unwrap().field(0).data_type(), &list_dt); + let out = pp.next_batch().unwrap().unwrap(); + assert_eq!(out.schema().field(0).data_type(), &list_dt); + } +} diff --git a/src/session.rs b/src/session.rs index 255ce05f..95aa51da 100644 --- a/src/session.rs +++ b/src/session.rs @@ -239,6 +239,7 @@ impl Session { sea.clone() as Arc, http_client, result_to_cloudfetch_config(&config.result), + result_to_post_process_options(&config.result), runtime_handle.clone(), ); sea.set_reader_factory(reader_factory, runtime_handle.clone()); @@ -576,6 +577,17 @@ fn result_to_cloudfetch_config( } } +/// Project the public [`ResultConfig`] onto the internal +/// [`PostProcessOptions`](crate::reader::post_processor::PostProcessOptions) +/// consumed by `ResultReaderFactory`. +fn result_to_post_process_options( + result: &ResultConfig, +) -> crate::reader::post_processor::PostProcessOptions { + crate::reader::post_processor::PostProcessOptions { + complex_types_as_json: result.complex_types_as_json, + } +} + /// Build the auth provider for a given [`AuthConfig`]. `host` is the /// workspace URL — used for OIDC discovery on M2M / U2M flows. async fn build_auth_provider( diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index e29358e8..6b77283c 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -23,7 +23,8 @@ //! ``` use databricks_sql_kernel::{ - AuthConfig, ErrorCode, ExecutedStatementHandle, ResultBatch, ResultStream, Session, TypedValue, + AuthConfig, ErrorCode, ExecutedStatementHandle, ResultBatch, ResultConfig, ResultStream, + Session, TypedValue, }; use std::env; @@ -471,3 +472,142 @@ async fn cloudfetch_drain_does_not_nest_block_on() { exec.close().await.expect("close"); session.close().await.expect("session close"); } + +/// Open a live session with `complex_types_as_json` toggled. +async fn live_session_with_complex_json(complex_types_as_json: bool) -> Session { + let host = env_var("DATABRICKS_HOST").expect("DATABRICKS_HOST required"); + let path = env_var("DATABRICKS_HTTP_PATH").expect("DATABRICKS_HTTP_PATH required"); + let token = env_var("DATABRICKS_TOKEN").expect("DATABRICKS_TOKEN required"); + + let mut result = ResultConfig::default(); + result.complex_types_as_json = complex_types_as_json; + + Session::builder() + .http_path(host, path) + .auth(AuthConfig::Pat { token }) + .result(result) + .open() + .await + .expect("Session::open against live workspace") +} + +/// **End-to-end check that `complex_types_as_json=true` flips complex +/// columns to compact-JSON `Utf8` strings.** +/// +/// Runs the same `SELECT` against two sessions: one with the flag +/// off (default — server returns native Arrow `List` / `Map` / +/// `Struct`) and one with the flag on (kernel post-processes those +/// columns into `Utf8` compact JSON, matching the Thrift wire form +/// that PySQL/JDBC consumers already see). +/// +/// We don't byte-compare against a captured Thrift fixture here — +/// that's the job of the `databricks-driver-test` comparator suite. +/// What this test catches is the kernel-side wiring: schema rewrite, +/// per-row JSON encoding for the three top-level complex shapes, and +/// nested recursion. +#[tokio::test] +#[ignore] +async fn complex_types_as_json_flag_stringifies_complex_columns() { + use arrow_array::Array; + + let sql = "SELECT \ + ARRAY(1, 2, 3) AS c_arr, \ + MAP('k1', 'v1', 'k2', 'v2') AS c_map, \ + NAMED_STRUCT('a', 'foo', 'b', 1) AS c_struct, \ + ARRAY(NAMED_STRUCT('a', 'x', 'b', 1), + NAMED_STRUCT('a', 'y', 'b', 2)) AS c_arr_struct"; + + // 1. Default (Arrow-native) — sanity check that the server is + // returning native complex shapes, not Utf8. + { + let session = live_session_with_complex_json(false).await; + let mut stmt = session.statement(); + stmt.spec().sql(sql); + let mut exec = stmt.execute().await.expect("execute (default)"); + let stream = exec.result_stream_mut(); + let batch = stream.next_batch().await.unwrap().expect("batch (default)"); + let ResultBatch::Arrow(batch) = batch else { + panic!("expected Arrow batch"); + }; + let schema = batch.schema(); + assert!( + matches!(schema.field(0).data_type(), arrow_schema::DataType::List(_)), + "c_arr should be List (got {:?})", + schema.field(0).data_type() + ); + assert!( + matches!( + schema.field(1).data_type(), + arrow_schema::DataType::Map(_, _) + ), + "c_map should be Map (got {:?})", + schema.field(1).data_type() + ); + assert!( + matches!( + schema.field(2).data_type(), + arrow_schema::DataType::Struct(_) + ), + "c_struct should be Struct (got {:?})", + schema.field(2).data_type() + ); + exec.close().await.expect("close (default)"); + session.close().await.expect("session close (default)"); + } + + // 2. `complex_types_as_json = true` — every complex column is + // rewritten to Utf8 carrying compact JSON. + { + let session = live_session_with_complex_json(true).await; + let mut stmt = session.statement(); + stmt.spec().sql(sql); + let mut exec = stmt.execute().await.expect("execute (json)"); + let stream = exec.result_stream_mut(); + let batch = stream.next_batch().await.unwrap().expect("batch (json)"); + let ResultBatch::Arrow(batch) = batch else { + panic!("expected Arrow batch"); + }; + let schema = batch.schema(); + for (i, name) in ["c_arr", "c_map", "c_struct", "c_arr_struct"] + .iter() + .enumerate() + { + assert_eq!( + schema.field(i).data_type(), + &arrow_schema::DataType::Utf8, + "{name} should be Utf8 (got {:?})", + schema.field(i).data_type() + ); + } + + let strs: Vec<&str> = (0..4) + .map(|i| { + batch + .column(i) + .as_any() + .downcast_ref::() + .unwrap_or_else(|| panic!("column {i} is not Utf8")) + .value(0) + }) + .collect(); + + assert_eq!(strs[0], "[1,2,3]", "c_arr"); + // MAP entry order is not guaranteed across Spark planner + // changes, so assert the parsed key/value pairs instead of a + // string literal. + let map_json: serde_json::Value = + serde_json::from_str(strs[1]).expect("c_map should be valid JSON"); + let map_obj = map_json.as_object().expect("c_map should be a JSON object"); + assert_eq!(map_obj.len(), 2, "c_map should have 2 entries"); + assert_eq!(map_obj.get("k1").and_then(|v| v.as_str()), Some("v1")); + assert_eq!(map_obj.get("k2").and_then(|v| v.as_str()), Some("v2")); + assert_eq!(strs[2], "{\"a\":\"foo\",\"b\":1}", "c_struct"); + assert_eq!( + strs[3], "[{\"a\":\"x\",\"b\":1},{\"a\":\"y\",\"b\":2}]", + "c_arr_struct" + ); + + exec.close().await.expect("close (json)"); + session.close().await.expect("session close (json)"); + } +}