Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
484 changes: 484 additions & 0 deletions docs/designs/complex-types-json-stringify.md

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
}
}
}
Expand Down
158 changes: 20 additions & 138 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

pub mod cloudfetch;
pub mod inline;
pub mod post_processor;
#[cfg(test)]
pub(crate) mod test_utils;

Expand All @@ -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;
Expand All @@ -49,6 +51,7 @@ pub(crate) struct ResultReaderFactory {
client: Arc<dyn Transport>,
http_client: Arc<DatabricksHttpClient>,
config: CloudFetchConfig,
post_process_options: PostProcessOptions,
runtime_handle: tokio::runtime::Handle,
}

Expand All @@ -58,12 +61,14 @@ impl ResultReaderFactory {
client: Arc<dyn Transport>,
http_client: Arc<DatabricksHttpClient>,
config: CloudFetchConfig,
post_process_options: PostProcessOptions,
runtime_handle: tokio::runtime::Handle,
) -> Self {
Self {
client,
http_client,
config,
post_process_options,
runtime_handle,
}
}
Expand All @@ -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
Expand All @@ -91,9 +100,10 @@ impl ResultReaderFactory {
response: &ExecuteResponse,
) -> Result<Box<dyn ResultReader + Send>> {
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(),
)?))
}

Expand Down Expand Up @@ -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<dyn ResultReader + Send>,
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<dyn ResultReader + Send>,
manifest: Option<&ResultManifest>,
) -> Result<Self> {
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<SchemaRef> {
Ok(self.schema.clone())
}

fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
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<arrow_array::ArrayRef> = 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<dyn ResultReader + Send>,
Expand Down Expand Up @@ -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<dyn ResultReader + Send> = 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<dyn ResultReader + Send> = 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`.
}
Loading