Skip to main content

datafusion_common/types/
logical.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use super::NativeType;
6use crate::error::Result;
7use arrow::datatypes::DataType;
8use core::fmt;
9use std::{cmp::Ordering, hash::Hash, sync::Arc};
10
11/// Signature that uniquely identifies a type among other types.
12#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub enum TypeSignature<'a> {
14    /// Represents a built-in native type.
15    Native(&'a NativeType),
16    /// Represents an arrow-compatible extension type.
17    /// (<https://arrow.apache.org/docs/format/Columnar.html#extension-types>)
18    ///
19    /// The `name` should contain the same value as 'ARROW:extension:name'.
20    Extension {
21        name: &'a str,
22        parameters: &'a [TypeParameter<'a>],
23    },
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
27pub enum TypeParameter<'a> {
28    Type(TypeSignature<'a>),
29    Number(i128),
30}
31
32/// A reference counted [`LogicalType`].
33pub type LogicalTypeRef = Arc<dyn LogicalType>;
34
35/// Representation of a logical type with its signature and its native backing
36/// type.
37///
38/// The logical type is meant to be used during the DataFusion logical planning
39/// phase in order to reason about logical types without worrying about their
40/// underlying physical implementation.
41///
42/// ### Extension types
43///
44/// [`LogicalType`] is a trait in order to allow the possibility of declaring
45/// extension types:
46///
47/// ```
48/// use datafusion_common::types::{LogicalType, NativeType, TypeSignature};
49///
50/// struct JSON {}
51///
52/// impl LogicalType for JSON {
53///     fn native(&self) -> &NativeType {
54///         &NativeType::String
55///     }
56///
57///     fn signature(&self) -> TypeSignature<'_> {
58///         TypeSignature::Extension {
59///             name: "JSON",
60///             parameters: &[],
61///         }
62///     }
63/// }
64/// ```
65pub trait LogicalType: Sync + Send {
66    /// Get the native backing type of this logical type.
67    fn native(&self) -> &NativeType;
68    /// Get the unique type signature for this logical type. Logical types with identical
69    /// signatures are considered equal.
70    fn signature(&self) -> TypeSignature<'_>;
71
72    /// Get the default physical type to cast `origin` to in order to obtain a physical type
73    /// that is logically compatible with this logical type.
74    fn default_cast_for(&self, origin: &DataType) -> Result<DataType> {
75        self.native().default_cast_for(origin)
76    }
77}
78
79impl fmt::Debug for dyn LogicalType {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.debug_tuple("LogicalType")
82            .field(&self.signature())
83            .field(&self.native())
84            .finish()
85    }
86}
87
88impl std::fmt::Display for dyn LogicalType {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        match self.signature() {
91            TypeSignature::Native(_) => write!(f, "{}", self.native()),
92            TypeSignature::Extension { name, .. } => write!(f, "{name}"),
93        }
94    }
95}
96
97impl PartialEq for dyn LogicalType {
98    fn eq(&self, other: &Self) -> bool {
99        // Logical types with identical signatures are considered equal.
100        self.signature().eq(&other.signature())
101    }
102}
103
104impl Eq for dyn LogicalType {}
105
106impl PartialOrd for dyn LogicalType {
107    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
108        Some(self.cmp(other))
109    }
110}
111
112impl Ord for dyn LogicalType {
113    fn cmp(&self, other: &Self) -> Ordering {
114        // Logical types with identical signatures are considered equal.
115        self.signature().cmp(&other.signature())
116    }
117}
118
119impl Hash for dyn LogicalType {
120    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
121        // Logical types with identical signatures are considered equal.
122        self.signature().hash(state);
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::types::{
130        LogicalField, LogicalFields, logical_boolean, logical_date, logical_float32,
131        logical_float64, logical_int32, logical_int64, logical_null, logical_string,
132    };
133    use arrow::datatypes::{Field, Fields};
134    use insta::assert_snapshot;
135
136    #[test]
137    fn test_logical_type_display_simple() {
138        assert_snapshot!(logical_null(), @"Null");
139        assert_snapshot!(logical_boolean(), @"Boolean");
140        assert_snapshot!(logical_int32(), @"Int32");
141        assert_snapshot!(logical_int64(), @"Int64");
142        assert_snapshot!(logical_float32(), @"Float32");
143        assert_snapshot!(logical_float64(), @"Float64");
144        assert_snapshot!(logical_string(), @"String");
145        assert_snapshot!(logical_date(), @"Date");
146    }
147
148    #[test]
149    fn test_logical_type_display_list() {
150        let list_type: Arc<dyn LogicalType> = Arc::new(NativeType::List(Arc::new(
151            LogicalField::from(&Field::new("item", DataType::Int32, true)),
152        )));
153        assert_snapshot!(list_type, @"List(Int32)");
154    }
155
156    #[test]
157    fn test_logical_type_display_struct() {
158        let struct_type: Arc<dyn LogicalType> = Arc::new(NativeType::Struct(
159            LogicalFields::from(&Fields::from(vec![
160                Field::new("x", DataType::Float64, false),
161                Field::new("y", DataType::Float64, true),
162            ])),
163        ));
164        assert_snapshot!(struct_type, @r#"Struct("x": non-null Float64, "y": Float64)"#);
165    }
166
167    #[test]
168    fn test_logical_type_display_fixed_size_list() {
169        let fsl_type: Arc<dyn LogicalType> = Arc::new(NativeType::FixedSizeList(
170            Arc::new(LogicalField::from(&Field::new(
171                "item",
172                DataType::Float32,
173                false,
174            ))),
175            3,
176        ));
177        assert_snapshot!(fsl_type, @"FixedSizeList(3 x non-null Float32)");
178    }
179
180    #[test]
181    fn test_logical_type_display_map() {
182        let map_type: Arc<dyn LogicalType> = Arc::new(NativeType::Map(Arc::new(
183            LogicalField::from(&Field::new("entries", DataType::Utf8, false)),
184        )));
185        assert_snapshot!(map_type, @"Map(non-null String)");
186    }
187
188    #[test]
189    fn test_logical_type_display_union() {
190        use arrow::datatypes::UnionFields;
191
192        let union_fields = UnionFields::try_new(
193            vec![0, 1],
194            vec![
195                Field::new("int_val", DataType::Int32, false),
196                Field::new("str_val", DataType::Utf8, true),
197            ],
198        )
199        .unwrap();
200        let union_type: Arc<dyn LogicalType> = Arc::new(NativeType::Union(
201            crate::types::LogicalUnionFields::from(&union_fields),
202        ));
203        assert_snapshot!(union_type, @r#"Union(0: ("int_val": non-null Int32), 1: ("str_val": String))"#);
204    }
205
206    #[test]
207    fn test_logical_type_display_nullable_vs_non_nullable() {
208        let nullable_list: Arc<dyn LogicalType> = Arc::new(NativeType::List(Arc::new(
209            LogicalField::from(&Field::new("item", DataType::Int32, true)),
210        )));
211        let non_nullable_list: Arc<dyn LogicalType> =
212            Arc::new(NativeType::List(Arc::new(LogicalField::from(&Field::new(
213                "item",
214                DataType::Int32,
215                false,
216            )))));
217
218        assert_snapshot!(nullable_list, @"List(Int32)");
219        assert_snapshot!(non_nullable_list, @"List(non-null Int32)");
220    }
221
222    #[test]
223    fn test_logical_type_display_extension() {
224        struct JsonType;
225        impl LogicalType for JsonType {
226            fn native(&self) -> &NativeType {
227                &NativeType::String
228            }
229            fn signature(&self) -> TypeSignature<'_> {
230                TypeSignature::Extension {
231                    name: "JSON",
232                    parameters: &[],
233                }
234            }
235        }
236        let json: Arc<dyn LogicalType> = Arc::new(JsonType);
237        assert_snapshot!(json, @"JSON");
238    }
239}