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
9 changes: 9 additions & 0 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,16 @@ impl SeaRestTransport {
.await?;
let response = self.wait_for_completion(response).await?;
let reader_factory = self.reader_factory()?;
// `create_reader` wraps in a `ManifestAugmentingReader`
// 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).
let reader = reader_factory.create_reader(&response.statement_id, &response)?;

// `server_state` carries the terminal state forward so the
// executed handle can skip a redundant CloseStatement when
// the server already cleaned up (state=Closed).
Expand Down
169 changes: 167 additions & 2 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,41 @@ impl ResultReaderFactory {

/// Create a reader from a statement execution response.
///
/// Automatically selects CloudFetch, inline, or other reader based on response.
/// 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.
///
/// There is one other augmentation site for Arrow-FFI consumers:
/// [`ResultReaderAdapter::new`] also applies the same
/// [`augment_schema_with_manifest`](ResultReaderAdapter::augment_schema_with_manifest)
/// to the wrapped reader's schema. Both sites share the same helper,
/// so the metadata-attachment behaviour is consistent across the
/// two surfaces.
pub(crate) fn create_reader(
&self,
statement_id: &str,
response: &ExecuteResponse,
) -> Result<Box<dyn ResultReader + Send>> {
let inner = self.create_inner_reader(statement_id, response)?;
Ok(Box::new(ManifestAugmentingReader::new(
inner,
response.manifest.as_ref(),
)?))
}

/// Pick the right concrete reader for `response`: CloudFetch,
/// inline Arrow, or a typed empty stream. Split from
/// [`create_reader`] so the manifest-augmentation wrap lives at
/// exactly one site.
fn create_inner_reader(
&self,
statement_id: &str,
response: &ExecuteResponse,
) -> Result<Box<dyn ResultReader + Send>> {
// Log manifest info for debugging
if let Some(ref manifest) = response.manifest {
Expand Down Expand Up @@ -430,6 +460,76 @@ 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 @@ -457,7 +557,10 @@ impl ResultReaderAdapter {
/// attach `databricks.*` key-value metadata to the field. This preserves
/// server-provided type_name, type_text, precision, scale, etc. through the
/// Arrow C Data Interface FFI boundary.
fn augment_schema_with_manifest(schema: &SchemaRef, manifest: &ResultManifest) -> SchemaRef {
pub(crate) fn augment_schema_with_manifest(
schema: &SchemaRef,
manifest: &ResultManifest,
) -> SchemaRef {
use std::collections::HashMap;

let col_by_pos: HashMap<usize, &crate::types::sea::ColumnInfo> = manifest
Expand Down Expand Up @@ -872,4 +975,66 @@ mod tests {
.metadata()
.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"
);
}
}