diff --git a/datafusion/core/tests/extension_types/mod.rs b/datafusion/core/tests/extension_types/mod.rs --- a/datafusion/core/tests/extension_types/mod.rs +++ b/datafusion/core/tests/extension_types/mod.rs @@ -15,4 +15,5 @@ // specific language governing permissions and limitations // under the License. +mod lolbench_aug; mod pretty_printing; diff --git a/datafusion/core/tests/extension_types/lolbench_aug.rs b/datafusion/core/tests/extension_types/lolbench_aug.rs new file mode 100644 index 000000000..8f23e1ab9 --- /dev/null +++ b/datafusion/core/tests/extension_types/lolbench_aug.rs @@ -0,0 +1,462 @@ +// 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 arrow::array::{Array, FixedSizeBinaryArray, Int32Array, RecordBatch, StringArray}; +use arrow::util::display::{ArrayFormatter, DisplayIndex, FormatOptions, FormatResult}; +use arrow_schema::extension::{ExtensionType, Uuid}; +use arrow_schema::{ArrowError, DataType, Field, Schema}; +use datafusion::error::Result; +use datafusion::execution::SessionStateBuilder; +use datafusion::prelude::SessionContext; +use datafusion_common::HashMap as DFHashMap; +use datafusion_common::types::DFExtensionType; +use datafusion_expr::registry::{ + DefaultExtensionTypeRegistration, ExtensionTypeRegistration, ExtensionTypeRegistry, ExtensionTypeRegistryRef, + MemoryExtensionTypeRegistry, +}; +use insta::assert_snapshot; +use std::collections::HashMap; +use std::fmt::{Debug, Write}; +use std::sync::Arc; + +const EXTENSION_NAME_KEY: &str = "ARROW:extension:name"; +const EXTENSION_METADATA_KEY: &str = "ARROW:extension:metadata"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ScoreStyle { + Raw, + Bracketed, +} + +#[derive(Debug, Clone, Copy)] +struct ScoreExtensionType { + style: ScoreStyle, +} + +impl ScoreExtensionType { + const NAME_VALUE: &'static str = "lolbench.score"; + + fn new(style: ScoreStyle) -> Self { + Self { style } + } +} + +impl ExtensionType for ScoreExtensionType { + const NAME: &'static str = Self::NAME_VALUE; + type Metadata = ScoreStyle; + + fn metadata(&self) -> &Self::Metadata { + &self.style + } + + fn serialize_metadata(&self) -> Option { + Some( + match self.style { + ScoreStyle::Raw => "raw", + ScoreStyle::Bracketed => "bracketed", + } + .to_string(), + ) + } + + fn deserialize_metadata( + metadata: Option<&str>, + ) -> std::result::Result { + match metadata { + Some("raw") => Ok(ScoreStyle::Raw), + Some("bracketed") => Ok(ScoreStyle::Bracketed), + Some(other) => Err(ArrowError::InvalidArgumentError(format!( + "invalid score metadata: {other}" + ))), + None => Ok(ScoreStyle::Raw), + } + } + + fn supports_data_type( + &self, + data_type: &DataType, + ) -> std::result::Result<(), ArrowError> { + if data_type == &DataType::Int32 { + Ok(()) + } else { + Err(ArrowError::InvalidArgumentError(format!( + "score extension requires Int32 storage, got {data_type}" + ))) + } + } + + fn try_new( + data_type: &DataType, + metadata: Self::Metadata, + ) -> std::result::Result { + let instance = Self::new(metadata); + instance.supports_data_type(data_type)?; + Ok(instance) + } +} + +impl DFExtensionType for ScoreExtensionType { + fn storage_type(&self) -> DataType { + DataType::Int32 + } + + fn serialize_metadata(&self) -> Option { + ExtensionType::serialize_metadata(self) + } + + fn create_array_formatter<'fmt>( + &self, + array: &'fmt dyn Array, + options: &FormatOptions<'fmt>, + ) -> Result>> { + let Some(values) = array.as_any().downcast_ref::() else { + return Ok(None); + }; + let display_index = ScoreDisplayIndex { + values, + null_str: options.null(), + style: self.style, + }; + Ok(Some(ArrayFormatter::new( + Box::new(display_index), + options.safe(), + ))) + } +} + +#[derive(Debug)] +struct ScoreDisplayIndex<'a> { + values: &'a Int32Array, + null_str: &'a str, + style: ScoreStyle, +} + +impl DisplayIndex for ScoreDisplayIndex<'_> { + fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult { + if self.values.is_null(idx) { + write!(f, "{}", self.null_str)?; + return Ok(()); + } + + match self.style { + ScoreStyle::Raw => write!(f, "score={}", self.values.value(idx))?, + ScoreStyle::Bracketed => write!(f, "[{}]", self.values.value(idx))?, + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy)] +struct UnknownScoreExtensionType; + +impl ExtensionType for UnknownScoreExtensionType { + const NAME: &'static str = "lolbench.unknown_score"; + type Metadata = (); + + fn metadata(&self) -> &Self::Metadata { + &() + } + + fn serialize_metadata(&self) -> Option { + None + } + + fn deserialize_metadata( + _metadata: Option<&str>, + ) -> std::result::Result { + Ok(()) + } + + fn supports_data_type( + &self, + data_type: &DataType, + ) -> std::result::Result<(), ArrowError> { + if data_type == &DataType::Int32 { + Ok(()) + } else { + Err(ArrowError::InvalidArgumentError(format!( + "unknown score extension requires Int32 storage, got {data_type}" + ))) + } + } + + fn try_new( + data_type: &DataType, + metadata: Self::Metadata, + ) -> std::result::Result { + let instance = Self; + let _ = metadata; + instance.supports_data_type(data_type)?; + Ok(instance) + } +} + +#[derive(Debug)] +struct NoFormatterExtensionType; + +impl DFExtensionType for NoFormatterExtensionType { + fn storage_type(&self) -> DataType { + DataType::Int32 + } + + fn serialize_metadata(&self) -> Option { + None + } +} + +fn score_registration() -> datafusion_expr::registry::ExtensionTypeRegistrationRef { + DefaultExtensionTypeRegistration::new_arc(|_storage_type, metadata| { + Ok(ScoreExtensionType::new(metadata)) + }) +} + +fn registry_with_score_type() -> Result { + let registry = MemoryExtensionTypeRegistry::new_empty(); + registry.add_extension_type_registration(score_registration())?; + Ok(Arc::new(registry)) +} + +fn context_with_registry(registry: ExtensionTypeRegistryRef) -> SessionContext { + let state = SessionStateBuilder::default() + .with_extension_type_registry(registry) + .build(); + SessionContext::new_with_state(state) +} + +fn score_field(name: &str, style: ScoreStyle) -> Field { + Field::new(name, DataType::Int32, true) + .with_extension_type(ScoreExtensionType::new(style)) +} + +fn manual_extension_field(name: &str, data_type: DataType, type_name: &str, metadata: &str) -> Field { + Field::new(name, data_type, false).with_metadata(HashMap::from([ + (EXTENSION_NAME_KEY.to_string(), type_name.to_string()), + (EXTENSION_METADATA_KEY.to_string(), metadata.to_string()), + ])) +} + +async fn table_string( + ctx: &SessionContext, + table_name: &str, + batch: RecordBatch, +) -> Result { + ctx.register_batch(table_name, batch)?; + ctx.table(table_name).await?.to_string().await +} + +#[tokio::test] +async fn lolbench_aug_canonical_uuid_uses_default_registry() -> Result<()> { + let ctx = context_with_registry(Arc::new( + MemoryExtensionTypeRegistry::new_with_canonical_extension_types(), + )); + let schema = Arc::new(Schema::new(vec![ + Field::new("uuid_value", DataType::FixedSizeBinary(16), false) + .with_extension_type(Uuid), + ])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(FixedSizeBinaryArray::from(vec![&[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + ][..]]))], + )?; + let result = table_string(&ctx, "uuid_defaults", batch).await?; + + assert_snapshot!( + result, + @r" + +--------------------------------------+ + | uuid_value | + +--------------------------------------+ + | 00010203-0405-0607-0809-0a0b0c0d0e0f | + +--------------------------------------+ + " + ); + Ok(()) +} + +#[tokio::test] +async fn lolbench_aug_unknown_extension_falls_back_to_default_display() -> Result<()> { + let schema = Arc::new(Schema::new(vec![ + Field::new("plain_value", DataType::Int32, false) + .with_extension_type(UnknownScoreExtensionType), + ])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![42]))])?; + let result = table_string(&SessionContext::new(), "unknown_extension", batch).await?; + + assert_snapshot!( + result, + @r" + +-------------+ + | plain_value | + +-------------+ + | 42 | + +-------------+ + " + ); + Ok(()) +} + +#[tokio::test] +async fn lolbench_aug_metadata_drives_registered_formatter() -> Result<()> { + let ctx = context_with_registry(registry_with_score_type()?); + let schema = Arc::new(Schema::new(vec![ + score_field("raw_score", ScoreStyle::Raw), + score_field("bracketed_score", ScoreStyle::Bracketed), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from(vec![7, 9])), + Arc::new(Int32Array::from(vec![7, 9])), + ], + )?; + let result = table_string(&ctx, "score_metadata", batch).await?; + + assert_snapshot!( + result, + @r" + +-----------+-----------------+ + | raw_score | bracketed_score | + +-----------+-----------------+ + | score=7 | [7] | + | score=9 | [9] | + +-----------+-----------------+ + " + ); + Ok(()) +} + +#[tokio::test] +async fn lolbench_aug_storage_type_mismatch_is_rejected() -> Result<()> { + let ctx = context_with_registry(registry_with_score_type()?); + let schema = Arc::new(Schema::new(vec![manual_extension_field( + "bad_score", + DataType::Utf8, + ScoreExtensionType::NAME, + "bracketed", + )])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(StringArray::from(vec!["not-an-int"]))], + )?; + ctx.register_batch("bad_score_storage", batch)?; + let err = ctx + .table("bad_score_storage") + .await? + .to_string() + .await + .expect_err("mismatched extension storage must be rejected"); + assert!( + err.to_string() + .contains(""), + "unexpected error: {err}" + ); + Ok(()) +} + +#[tokio::test] +async fn lolbench_aug_dynamic_registration_can_be_removed() -> Result<()> { + let registry = Arc::new(MemoryExtensionTypeRegistry::new_empty()); + registry.add_extension_type_registration(score_registration())?; + + let ctx = context_with_registry(registry.clone()); + let schema = Arc::new(Schema::new(vec![score_field( + "score", + ScoreStyle::Bracketed, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![11]))])?; + let result = table_string(&ctx, "registered_scores", batch).await?; + assert!(result.contains("[11]"), "registered formatter was not used: {result}"); + + let removed = registry.remove_extension_type_registration(ScoreExtensionType::NAME)?; + assert!(removed.is_some(), "expected score registration to be removed"); + + let ctx = context_with_registry(registry); + let schema = Arc::new(Schema::new(vec![score_field( + "score", + ScoreStyle::Bracketed, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![11]))])?; + let result = table_string(&ctx, "removed_scores", batch).await?; + assert!( + result.contains("| 11 |"), + "removed registration should use default formatting: {result}" + ); + assert!( + !result.contains("[11]"), + "removed registration still used custom formatting: {result}" + ); + Ok(()) +} + +#[tokio::test] +async fn lolbench_aug_registry_api_round_trips_registered_fields() -> Result<()> { + let registration = score_registration(); + assert!( + registration.type_name() == ScoreExtensionType::NAME, + "registration should name the extension type via type_name()" + ); + + let registry = MemoryExtensionTypeRegistry::new_with_types([registration])?; + assert_eq!(registry.all_extension_types().len(), 1); + assert_eq!(registry.extension_type_registrations().len(), 1); + assert!( + registry + .create_extension_type_for_field(&Field::new("plain", DataType::Int32, false))? + .is_none(), + "plain fields should not resolve to a DataFusion extension type" + ); + + let extension_type = registry + .create_extension_type_for_field(&score_field("score", ScoreStyle::Bracketed))? + .expect("registered score field should resolve to an extension type"); + assert_eq!(extension_type.storage_type(), DataType::Int32); + assert_eq!( + extension_type.serialize_metadata().as_deref(), + Some("bracketed") + ); + + let empty_registry = MemoryExtensionTypeRegistry::new_empty(); + empty_registry.extend(&[score_registration()])?; + assert_eq!(empty_registry.all_extension_types().len(), 1); + + let mut registrations = DFHashMap::new(); + registrations.insert(ScoreExtensionType::NAME.to_string(), score_registration()); + let from_map = MemoryExtensionTypeRegistry::from(registrations); + assert_eq!(from_map.extension_type_registrations().len(), 1); + Ok(()) +} + +#[tokio::test] +async fn lolbench_aug_default_formatter_hook_falls_back() -> Result<()> { + let values = Int32Array::from(vec![1]); + let no_formatter = NoFormatterExtensionType; + assert!( + no_formatter + .create_array_formatter(&values, &FormatOptions::default())? + .is_none(), + "extension types without a formatter should fall back to Arrow formatting" + ); + + let uuid = Uuid; + assert_eq!( + ::storage_type(&uuid), + DataType::FixedSizeBinary(16) + ); + assert_eq!(::serialize_metadata(&uuid), None); + Ok(()) +} diff --git a/datafusion/expr-common/src/type_coercion/binary/tests/comparison.rs b/datafusion/expr-common/src/type_coercion/binary/tests/comparison.rs --- a/datafusion/expr-common/src/type_coercion/binary/tests/comparison.rs +++ b/datafusion/expr-common/src/type_coercion/binary/tests/comparison.rs @@ -95,6 +95,16 @@ fn test_like_coercion() { Some(DataType::LargeUtf8) ); } + +#[test] +fn lolbench_aug_like_binary_utf8_stays_unchanged() { + test_like_rule!(DataType::Binary, DataType::Utf8, Some(DataType::Utf8)); + test_like_rule!(DataType::LargeBinary, DataType::Utf8, Some(DataType::LargeUtf8)); + assert_eq!( + like_coercion(&DataType::Utf8, &DataType::LargeUtf8), + Some(DataType::LargeUtf8) + ); +} #[test] fn test_type_coercion() -> Result<()> {