diff --git a/datafusion/common/src/types/canonical_extensions/bool8.rs b/datafusion/common/src/types/canonical_extensions/bool8.rs new file mode 100644 index 000000000000..7c8264ae5a44 --- /dev/null +++ b/datafusion/common/src/types/canonical_extensions/bool8.rs @@ -0,0 +1,131 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use crate::error::_internal_err; +use crate::types::extension::DFExtensionType; +use arrow::array::{Array, Int8Array}; +use arrow::datatypes::DataType; +use arrow::util::display::{ArrayFormatter, DisplayIndex, FormatOptions, FormatResult}; +use std::fmt::Write; + +/// Defines the extension type logic for the canonical `arrow.bool8` extension type. +/// +/// Bool8 values are displayed as `true` or `false`, where `0` maps to `false` and +/// any non-zero value maps to `true`. +/// +/// See [`DFExtensionType`] for information on DataFusion's extension type mechanism. +impl DFExtensionType for arrow_schema::extension::Bool8 { + fn storage_type(&self) -> DataType { + DataType::Int8 + } + + fn serialize_metadata(&self) -> Option { + // Bool8 metadata is an empty string per the Arrow spec. + Some(String::new()) + } + + fn create_array_formatter<'fmt>( + &self, + array: &'fmt dyn Array, + options: &FormatOptions<'fmt>, + ) -> crate::Result>> { + if array.data_type() != &DataType::Int8 { + return _internal_err!("Wrong array type for Bool8"); + } + + let display_index = Bool8ValueDisplayIndex { + array: array.as_any().downcast_ref().unwrap(), + null_str: options.null(), + }; + Ok(Some(ArrayFormatter::new( + Box::new(display_index), + options.safe(), + ))) + } +} + +/// Pretty printer for 8-bit Boolean values. +/// +/// Displays `false` for zero values and `true` for any non-zero value. +#[derive(Debug, Clone, Copy)] +struct Bool8ValueDisplayIndex<'a> { + array: &'a Int8Array, + null_str: &'a str, +} + +impl DisplayIndex for Bool8ValueDisplayIndex<'_> { + fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult { + if self.array.is_null(idx) { + write!(f, "{}", self.null_str)?; + return Ok(()); + } + + let value = self.array.value(idx); + if value == 0 { + write!(f, "false")?; + } else { + write!(f, "true")?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ScalarValue; + + #[test] + pub fn test_pretty_print_bool8_false() { + let bool8 = ScalarValue::Int8(Some(0)).to_array_of_size(1).unwrap(); + + let extension_type = arrow_schema::extension::Bool8 {}; + let formatter = extension_type + .create_array_formatter(bool8.as_ref(), &FormatOptions::default()) + .unwrap() + .unwrap(); + + assert_eq!(formatter.value(0).to_string(), "false"); + } + + #[test] + pub fn test_pretty_print_bool8_true() { + let bool8 = ScalarValue::Int8(Some(1)).to_array_of_size(1).unwrap(); + + let extension_type = arrow_schema::extension::Bool8 {}; + let formatter = extension_type + .create_array_formatter(bool8.as_ref(), &FormatOptions::default()) + .unwrap() + .unwrap(); + + assert_eq!(formatter.value(0).to_string(), "true"); + } + + #[test] + pub fn test_pretty_print_bool8_nonzero_is_true() { + // Any non-zero value should display as "true" + let bool8 = ScalarValue::Int8(Some(42)).to_array_of_size(1).unwrap(); + + let extension_type = arrow_schema::extension::Bool8 {}; + let formatter = extension_type + .create_array_formatter(bool8.as_ref(), &FormatOptions::default()) + .unwrap() + .unwrap(); + + assert_eq!(formatter.value(0).to_string(), "true"); + } +} diff --git a/datafusion/common/src/types/canonical_extensions/fixed_shape_tensor.rs b/datafusion/common/src/types/canonical_extensions/fixed_shape_tensor.rs new file mode 100644 index 000000000000..ac35fd6afc81 --- /dev/null +++ b/datafusion/common/src/types/canonical_extensions/fixed_shape_tensor.rs @@ -0,0 +1,42 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use crate::types::extension::DFExtensionType; +use arrow::datatypes::DataType; +use arrow_schema::extension::ExtensionType; + +/// Defines the extension type logic for the canonical `arrow.fixed_shape_tensor` extension type. +/// +/// Fixed shape tensors are stored as `FixedSizeList` arrays; the default Arrow formatter +/// is used for display. +/// +/// See [`DFExtensionType`] for information on DataFusion's extension type mechanism. +impl DFExtensionType for arrow_schema::extension::FixedShapeTensor { + fn storage_type(&self) -> DataType { + DataType::new_fixed_size_list( + self.value_type().clone(), + i32::try_from(self.list_size()).expect("list size overflow"), + false, + ) + } + + fn serialize_metadata(&self) -> Option { + ::serialize_metadata( + self, + ) + } +} diff --git a/datafusion/common/src/types/canonical_extensions/json.rs b/datafusion/common/src/types/canonical_extensions/json.rs new file mode 100644 index 000000000000..88d1ed0a73bd --- /dev/null +++ b/datafusion/common/src/types/canonical_extensions/json.rs @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use crate::types::extension::DFExtensionType; +use arrow::datatypes::DataType; +use arrow_schema::extension::ExtensionType; + +/// Defines the extension type logic for the canonical `arrow.json` extension type. +/// +/// JSON values are already stored as UTF-8 strings, so the default Arrow string +/// formatter is used for display. +/// +/// See [`DFExtensionType`] for information on DataFusion's extension type mechanism. +impl DFExtensionType for arrow_schema::extension::Json { + fn storage_type(&self) -> DataType { + // JSON can be stored as Utf8, LargeUtf8, or Utf8View; Utf8 is the most common default. + DataType::Utf8 + } + + fn serialize_metadata(&self) -> Option { + ::serialize_metadata(self) + } +} diff --git a/datafusion/common/src/types/canonical_extensions/mod.rs b/datafusion/common/src/types/canonical_extensions/mod.rs index e61c415b4481..d4359c73497a 100644 --- a/datafusion/common/src/types/canonical_extensions/mod.rs +++ b/datafusion/common/src/types/canonical_extensions/mod.rs @@ -15,4 +15,10 @@ // specific language governing permissions and limitations // under the License. +mod bool8; +mod fixed_shape_tensor; +mod json; +mod opaque; +mod timestamp_with_offset; mod uuid; +mod variable_shape_tensor; diff --git a/datafusion/common/src/types/canonical_extensions/opaque.rs b/datafusion/common/src/types/canonical_extensions/opaque.rs new file mode 100644 index 000000000000..2b58b8c4a82b --- /dev/null +++ b/datafusion/common/src/types/canonical_extensions/opaque.rs @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use crate::types::extension::DFExtensionType; +use arrow::datatypes::DataType; +use arrow_schema::extension::ExtensionType; + +/// Defines the extension type logic for the canonical `arrow.opaque` extension type. +/// +/// Opaque represents a type received from an external system that cannot be interpreted. +/// The default Arrow formatter is used for display. +/// +/// See [`DFExtensionType`] for information on DataFusion's extension type mechanism. +impl DFExtensionType for arrow_schema::extension::Opaque { + fn storage_type(&self) -> DataType { + // Opaque supports any storage type; Null is recommended when there is no underlying data. + DataType::Null + } + + fn serialize_metadata(&self) -> Option { + ::serialize_metadata(self) + } +} diff --git a/datafusion/common/src/types/canonical_extensions/timestamp_with_offset.rs b/datafusion/common/src/types/canonical_extensions/timestamp_with_offset.rs new file mode 100644 index 000000000000..a252aceb9772 --- /dev/null +++ b/datafusion/common/src/types/canonical_extensions/timestamp_with_offset.rs @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use crate::types::extension::DFExtensionType; +use arrow::datatypes::DataType; + +/// Defines the extension type logic for the canonical `arrow.timestamp_with_offset` extension type. +/// +/// Timestamp with offset values are stored as `Struct` arrays containing a UTC timestamp +/// and an offset in minutes. The default Arrow formatter is used for display. +/// +/// See [`DFExtensionType`] for information on DataFusion's extension type mechanism. +impl DFExtensionType for arrow_schema::extension::TimestampWithOffset { + fn storage_type(&self) -> DataType { + // TimestampWithOffset stores no internal state to determine the timestamp precision. + // The actual storage type depends on the time unit chosen by the producer. + // Returning Null here is a placeholder; the actual DataType is validated at registration + // time via ExtensionType::supports_data_type. + DataType::Null + } + + fn serialize_metadata(&self) -> Option { + // TimestampWithOffset has no metadata. + None + } +} diff --git a/datafusion/common/src/types/canonical_extensions/variable_shape_tensor.rs b/datafusion/common/src/types/canonical_extensions/variable_shape_tensor.rs new file mode 100644 index 000000000000..53dab987658b --- /dev/null +++ b/datafusion/common/src/types/canonical_extensions/variable_shape_tensor.rs @@ -0,0 +1,49 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use crate::types::extension::DFExtensionType; +use arrow::datatypes::{DataType, Field, Fields}; +use arrow_schema::extension::ExtensionType; + +/// Defines the extension type logic for the canonical `arrow.variable_shape_tensor` extension type. +/// +/// Variable shape tensors are stored as `Struct` arrays containing `data` (a list of elements) +/// and `shape` (a fixed-size list of int32 dimensions). The default Arrow formatter is used +/// for display. +/// +/// See [`DFExtensionType`] for information on DataFusion's extension type mechanism. +impl DFExtensionType for arrow_schema::extension::VariableShapeTensor { + fn storage_type(&self) -> DataType { + let dims = i32::try_from(self.dimensions()).expect("dimensions overflow"); + DataType::Struct(Fields::from_iter([ + Field::new_list( + "data", + Field::new_list_field(self.value_type().clone(), false), + false, + ), + Field::new( + "shape", + DataType::new_fixed_size_list(DataType::Int32, dims, false), + false, + ), + ])) + } + + fn serialize_metadata(&self) -> Option { + ::serialize_metadata(self) + } +} diff --git a/datafusion/core/tests/extension_types/pretty_printing.rs b/datafusion/core/tests/extension_types/pretty_printing.rs index c0796887b8b6..8d5476368512 100644 --- a/datafusion/core/tests/extension_types/pretty_printing.rs +++ b/datafusion/core/tests/extension_types/pretty_printing.rs @@ -15,8 +15,8 @@ // specific language governing permissions and limitations // under the License. -use arrow::array::{FixedSizeBinaryArray, RecordBatch}; -use arrow_schema::extension::Uuid; +use arrow::array::{FixedSizeBinaryArray, Int8Array, RecordBatch, StringArray}; +use arrow_schema::extension::{Bool8, Json, Uuid}; use arrow_schema::{DataType, Field, Schema, SchemaRef}; use datafusion::dataframe::DataFrame; use datafusion::error::Result; @@ -76,3 +76,92 @@ async fn test_pretty_print_extension_type_formatter() -> Result<()> { Ok(()) } + +fn bool8_test_schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("my_bools", DataType::Int8, false).with_extension_type(Bool8), + ])) +} + +async fn create_bool8_test_table() -> Result { + let schema = bool8_test_schema(); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int8Array::from(vec![0, 1, 42, -1]))], + )?; + + let state = SessionStateBuilder::default() + .with_extension_type_registry(Arc::new( + MemoryExtensionTypeRegistry::new_with_canonical_extension_types(), + )) + .build(); + let ctx = SessionContext::new_with_state(state); + ctx.register_batch("test", batch)?; + ctx.table("test").await +} + +#[tokio::test] +async fn test_pretty_print_bool8() -> Result<()> { + let result = create_bool8_test_table().await?.to_string().await?; + + assert_snapshot!( + result, + @r" + +----------+ + | my_bools | + +----------+ + | false | + | true | + | true | + | true | + +----------+ + " + ); + + Ok(()) +} + +fn json_test_schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("my_json", DataType::Utf8, false).with_extension_type(Json::default()), + ])) +} + +async fn create_json_test_table() -> Result { + let schema = json_test_schema(); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(StringArray::from(vec![ + r#"{"key": "value"}"#, + r#"[1, 2, 3]"#, + ]))], + )?; + + let state = SessionStateBuilder::default() + .with_extension_type_registry(Arc::new( + MemoryExtensionTypeRegistry::new_with_canonical_extension_types(), + )) + .build(); + let ctx = SessionContext::new_with_state(state); + ctx.register_batch("test", batch)?; + ctx.table("test").await +} + +#[tokio::test] +async fn test_pretty_print_json() -> Result<()> { + let result = create_json_test_table().await?.to_string().await?; + + assert_snapshot!( + result, + @r#" + +------------------+ + | my_json | + +------------------+ + | {"key": "value"} | + | [1, 2, 3] | + +------------------+ + "# + ); + + Ok(()) +} diff --git a/datafusion/expr/src/registry.rs b/datafusion/expr/src/registry.rs index 52a29019bc96..4e7e9bb4fc27 100644 --- a/datafusion/expr/src/registry.rs +++ b/datafusion/expr/src/registry.rs @@ -22,9 +22,15 @@ use crate::planner::ExprPlanner; use crate::{AggregateUDF, ScalarUDF, UserDefinedLogicalNode, WindowUDF}; use arrow::datatypes::Field; use arrow_schema::DataType; -use arrow_schema::extension::ExtensionType; +use arrow_schema::extension::{ + Bool8, ExtensionType, FixedShapeTensor, FixedShapeTensorMetadata, Json, JsonMetadata, + Opaque, OpaqueMetadata, TimestampWithOffset, VariableShapeTensor, + VariableShapeTensorMetadata, +}; use datafusion_common::types::{DFExtensionType, DFExtensionTypeRef}; -use datafusion_common::{HashMap, Result, not_impl_err, plan_datafusion_err}; +use datafusion_common::{ + DataFusionError, HashMap, Result, not_impl_err, plan_datafusion_err, +}; use std::collections::HashSet; use std::fmt::{Debug, Formatter}; use std::sync::{Arc, RwLock}; @@ -424,9 +430,32 @@ impl MemoryExtensionTypeRegistry { /// Pre-registers the [canonical extension types](https://arrow.apache.org/docs/format/CanonicalExtensions.html) /// in the extension type registry. pub fn new_with_canonical_extension_types() -> Self { - let mapping = [DefaultExtensionTypeRegistration::new_arc(|_, _| { - Ok(arrow_schema::extension::Uuid {}) - })]; + let mapping: [ExtensionTypeRegistrationRef; 7] = [ + DefaultExtensionTypeRegistration::new_arc(|_, _| { + Ok(arrow_schema::extension::Uuid {}) + }), + DefaultExtensionTypeRegistration::new_arc(|_, _: &'static str| Ok(Bool8 {})), + DefaultExtensionTypeRegistration::new_arc(|dt, metadata: JsonMetadata| { + ::try_new(dt, metadata) + .map_err(DataFusionError::from) + }), + DefaultExtensionTypeRegistration::new_arc(|_, metadata: OpaqueMetadata| { + Ok(Opaque::from(metadata)) + }), + DefaultExtensionTypeRegistration::new_arc( + |dt, metadata: FixedShapeTensorMetadata| { + ::try_new(dt, metadata) + .map_err(DataFusionError::from) + }, + ), + DefaultExtensionTypeRegistration::new_arc( + |dt, metadata: VariableShapeTensorMetadata| { + ::try_new(dt, metadata) + .map_err(DataFusionError::from) + }, + ), + DefaultExtensionTypeRegistration::new_arc(|_, _| Ok(TimestampWithOffset {})), + ]; let mut extension_types = HashMap::new(); for registration in mapping.into_iter() {