Skip to main content

datafusion_common/
metadata.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 std::{collections::BTreeMap, sync::Arc};
6
7use arrow::datatypes::{DataType, Field, FieldRef, Metadata};
8use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
9use hashbrown::HashMap;
10
11use crate::{DataFusionError, ScalarValue, error::_plan_err};
12
13/// A [`ScalarValue`] with optional [`FieldMetadata`]
14#[derive(Debug, Clone)]
15pub struct ScalarAndMetadata {
16    pub value: ScalarValue,
17    pub metadata: Option<FieldMetadata>,
18}
19
20impl ScalarAndMetadata {
21    /// Create a new Literal from a scalar value with optional [`FieldMetadata`]
22    pub fn new(value: ScalarValue, metadata: Option<FieldMetadata>) -> Self {
23        Self { value, metadata }
24    }
25
26    /// Access the underlying [ScalarValue] storage
27    pub fn value(&self) -> &ScalarValue {
28        &self.value
29    }
30
31    /// Access the [FieldMetadata] attached to this value, if any
32    pub fn metadata(&self) -> Option<&FieldMetadata> {
33        self.metadata.as_ref()
34    }
35
36    /// Consume self and return components
37    pub fn into_inner(self) -> (ScalarValue, Option<FieldMetadata>) {
38        (self.value, self.metadata)
39    }
40
41    /// Cast this values's storage type
42    ///
43    /// This operation assumes that if the underlying [ScalarValue] can be casted
44    /// to a given type that any extension type represented by the metadata is also
45    /// valid.
46    pub fn cast_storage_to(
47        &self,
48        target_type: &DataType,
49    ) -> Result<Self, DataFusionError> {
50        let new_value = self.value().cast_to(target_type)?;
51        Ok(Self::new(new_value, self.metadata.clone()))
52    }
53}
54
55/// create a new ScalarAndMetadata from a ScalarValue without
56/// any metadata
57impl From<ScalarValue> for ScalarAndMetadata {
58    fn from(value: ScalarValue) -> Self {
59        Self::new(value, None)
60    }
61}
62
63/// Assert equality of data types where one or both sides may have field metadata
64///
65/// This currently compares absent metadata (e.g., one side was a DataType) and
66/// empty metadata (e.g., one side was a field where the field had no metadata)
67/// as equal and uses byte-for-byte comparison for the keys and values of the
68/// fields, even though this is potentially too strict for some cases (e.g.,
69/// extension types where extension metadata is represented by JSON, or cases
70/// where field metadata is orthogonal to the interpretation of the data type).
71///
72/// Returns a planning error with suitably formatted type representations if
73/// actual and expected do not compare to equal.
74pub fn check_metadata_with_storage_equal(
75    actual: (&DataType, Option<&Metadata>),
76    expected: (&DataType, Option<&Metadata>),
77    what: &str,
78    context: &str,
79) -> Result<(), DataFusionError> {
80    if actual.0 != expected.0 {
81        return _plan_err!(
82            "Expected {what} of type {}, got {}{context}",
83            format_type_and_metadata(expected.0, expected.1),
84            format_type_and_metadata(actual.0, actual.1)
85        );
86    }
87
88    let metadata_equal = match (actual.1, expected.1) {
89        (None, None) => true,
90        (None, Some(expected_metadata)) => expected_metadata.is_empty(),
91        (Some(actual_metadata), None) => actual_metadata.is_empty(),
92        (Some(actual_metadata), Some(expected_metadata)) => {
93            actual_metadata == expected_metadata
94        }
95    };
96
97    if !metadata_equal {
98        return _plan_err!(
99            "Expected {what} of type {}, got {}{context}",
100            format_type_and_metadata(expected.0, expected.1),
101            format_type_and_metadata(actual.0, actual.1)
102        );
103    }
104
105    Ok(())
106}
107
108/// Compute the field metadata to propagate for an expression whose result
109/// may come from any one of several inputs coerced to a common type, such as
110/// `COALESCE`, `NVL2`, or `CASE WHEN`.
111///
112/// Metadata is merged across the fields whose data type is not `Null` (an
113/// untyped NULL literal carries no metadata and cannot contribute a typed
114/// value), with earlier fields taking precedence for repeated keys. Unrelated
115/// keys are not required to agree: metadata that arrived with the data (e.g.
116/// from an Arrow file or an embedded Arrow schema in a Parquet file) must not
117/// cause an extension type to be silently dropped from the result.
118///
119/// The Arrow extension type keys are handled as a unit, like in
120/// [`Expr::Cast`] output field derivation:
121/// - Differing values of `ARROW:extension:name` produce a planning error;
122///   the inputs are of different logical types even though they were coerced
123///   to a common storage type.
124/// - `ARROW:extension:metadata` is taken from the field that supplied the
125///   extension name, never combined from another field. Byte-wise differences
126///   in the extension metadata of fields that agree on the extension name are
127///   tolerated, since extension parameters are often JSON-encoded, where byte
128///   equality is too strict.
129///
130/// [`Expr::Cast`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html#variant.Cast
131pub fn coerced_fields_metadata<'a>(
132    fields: impl IntoIterator<Item = &'a Field>,
133) -> Result<FieldMetadata, DataFusionError> {
134    let mut merged: BTreeMap<String, String> = BTreeMap::new();
135    let mut extension: Option<(String, Option<String>)> = None;
136
137    for field in fields {
138        if field.data_type().is_null() {
139            continue;
140        }
141        let metadata = FieldMetadata::new_from_field(field);
142        if let Some(name) = metadata.inner().get(EXTENSION_TYPE_NAME_KEY) {
143            match &extension {
144                Some((first_name, _)) if first_name != name => {
145                    return _plan_err!(
146                        "Cannot merge field metadata with differing values of \
147                         '{EXTENSION_TYPE_NAME_KEY}': '{first_name}' and '{name}'"
148                    );
149                }
150                Some(_) => {}
151                None => {
152                    extension = Some((
153                        name.clone(),
154                        metadata.inner().get(EXTENSION_TYPE_METADATA_KEY).cloned(),
155                    ));
156                }
157            }
158        }
159        for (key, value) in metadata.inner() {
160            if key == EXTENSION_TYPE_NAME_KEY || key == EXTENSION_TYPE_METADATA_KEY {
161                continue;
162            }
163            merged.entry(key.clone()).or_insert_with(|| value.clone());
164        }
165    }
166
167    if let Some((name, extension_metadata)) = extension {
168        merged.insert(EXTENSION_TYPE_NAME_KEY.to_string(), name);
169        if let Some(extension_metadata) = extension_metadata {
170            merged.insert(EXTENSION_TYPE_METADATA_KEY.to_string(), extension_metadata);
171        }
172    }
173
174    Ok(FieldMetadata::from(merged))
175}
176
177/// Given a data type represented by storage and optional metadata, generate
178/// a user-facing string
179///
180/// This function exists to reduce the number of Field debug strings that are
181/// used to communicate type information in error messages and plan explain
182/// renderings.
183pub fn format_type_and_metadata(
184    data_type: &DataType,
185    metadata: Option<&Metadata>,
186) -> String {
187    match metadata {
188        Some(metadata) if !metadata.is_empty() => {
189            format!("{data_type}<{metadata:?}>")
190        }
191        _ => data_type.to_string(),
192    }
193}
194
195/// Merges the field or schema metadata of the inputs of a `UNION`.
196///
197/// Inputs are merged in order: keys present in only some inputs are kept, and
198/// when inputs disagree on a key's value, the last input wins. Inputs without
199/// metadata (e.g. `NULL` literals) contribute nothing.
200///
201/// # Example
202/// ```
203/// # use arrow::datatypes::Metadata;
204/// # use datafusion_common::metadata::merge_metadata_for_union;
205/// let first = Metadata::new().with("id", "1").with("only_first", "a");
206/// let last = Metadata::new().with("id", "2");
207/// assert_eq!(
208///     merge_metadata_for_union([&first, &last]),
209///     Metadata::new().with("id", "2").with("only_first", "a"),
210/// );
211/// ```
212pub fn merge_metadata_for_union<'a>(
213    metadatas: impl IntoIterator<Item = &'a Metadata>,
214) -> Metadata {
215    metadatas
216        .into_iter()
217        .fold(Metadata::new(), |mut merged, metadata| {
218            if merged.is_empty() {
219                // Shares the underlying map rather than copying it
220                metadata.clone()
221            } else {
222                merged.extend(metadata);
223                merged
224            }
225        })
226}
227
228/// Literal metadata
229///
230/// Stores metadata associated with a literal expressions
231/// and is designed to be fast to `clone`.
232///
233/// This structure is used to store metadata associated with a literal expression, and it
234/// corresponds to the `metadata` field on [`Field`].
235///
236/// # Example: Create [`FieldMetadata`] from a [`Field`]
237/// ```
238/// # use std::collections::HashMap;
239/// # use datafusion_common::metadata::FieldMetadata;
240/// # use arrow::datatypes::{Field, DataType};
241/// # let field = Field::new("c1", DataType::Int32, true)
242/// #  .with_metadata(HashMap::from([("foo".to_string(), "bar".to_string())]));
243/// // Create a new `FieldMetadata` instance from a `Field`
244/// let metadata = FieldMetadata::new_from_field(&field);
245/// // There is also a `From` impl:
246/// let metadata = FieldMetadata::from(&field);
247/// ```
248///
249/// # Example: Update a [`Field`] with [`FieldMetadata`]
250/// ```
251/// # use datafusion_common::metadata::FieldMetadata;
252/// # use arrow::datatypes::{Field, DataType};
253/// # let field = Field::new("c1", DataType::Int32, true);
254/// # let metadata = FieldMetadata::new_from_field(&field);
255/// // Add any metadata from `FieldMetadata` to `Field`
256/// let updated_field = metadata.add_to_field(field);
257/// ```
258///
259/// For more background, please also see the [Implementing User Defined Types and Custom Metadata in DataFusion blog]
260///
261/// [Implementing User Defined Types and Custom Metadata in DataFusion blog]: https://datafusion.apache.org/blog/2025/09/21/custom-types-using-metadata
262#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
263pub struct FieldMetadata {
264    /// The inner metadata of a literal expression, which is a map of string
265    /// keys to string values.
266    inner: Metadata,
267}
268
269impl Default for FieldMetadata {
270    fn default() -> Self {
271        Self::new_empty()
272    }
273}
274
275impl FieldMetadata {
276    /// Create a new empty metadata instance.
277    pub fn new_empty() -> Self {
278        Self {
279            inner: Metadata::new(),
280        }
281    }
282
283    /// Merges two optional `FieldMetadata` instances, overwriting any existing
284    /// keys in `m` with keys from `n` if present.
285    ///
286    /// This function is commonly used in alias operations, particularly for literals
287    /// with metadata. When creating an alias expression, the metadata from the original
288    /// expression (such as a literal) is combined with any metadata specified on the alias.
289    ///
290    /// # Arguments
291    ///
292    /// * `m` - The first metadata (typically from the original expression like a literal)
293    /// * `n` - The second metadata (typically from the alias definition)
294    ///
295    /// # Merge Strategy
296    ///
297    /// - If both metadata instances exist, they are merged with `n` taking precedence
298    /// - Keys from `n` will overwrite keys from `m` if they have the same name
299    /// - If only one metadata instance exists, it is returned unchanged
300    /// - If neither exists, `None` is returned
301    ///
302    /// # Example usage
303    /// ```rust
304    /// use datafusion_common::metadata::FieldMetadata;
305    /// use std::collections::BTreeMap;
306    ///
307    /// // Create metadata for a literal expression
308    /// let literal_metadata = Some(FieldMetadata::from(BTreeMap::from([
309    ///     ("source".to_string(), "constant".to_string()),
310    ///     ("type".to_string(), "int".to_string()),
311    /// ])));
312    ///
313    /// // Create metadata for an alias
314    /// let alias_metadata = Some(FieldMetadata::from(BTreeMap::from([
315    ///     ("description".to_string(), "answer".to_string()),
316    ///     ("source".to_string(), "user".to_string()), // This will override literal's "source"
317    /// ])));
318    ///
319    /// // Merge the metadata
320    /// let merged = FieldMetadata::merge_options(
321    ///     literal_metadata.as_ref(),
322    ///     alias_metadata.as_ref(),
323    /// );
324    ///
325    /// // Result contains: {"source": "user", "type": "int", "description": "answer"}
326    /// assert!(merged.is_some());
327    /// ```
328    pub fn merge_options(
329        m: Option<&FieldMetadata>,
330        n: Option<&FieldMetadata>,
331    ) -> Option<FieldMetadata> {
332        match (m, n) {
333            (Some(m), Some(n)) => {
334                let mut merged = m.clone();
335                merged.extend(n.clone());
336                Some(merged)
337            }
338            (Some(m), None) => Some(m.clone()),
339            (None, Some(n)) => Some(n.clone()),
340            (None, None) => None,
341        }
342    }
343
344    /// Create a new metadata instance from a `Field`'s metadata.
345    ///
346    /// This is cheap, as [`Metadata`] is cheap to clone.
347    pub fn new_from_field(field: &Field) -> Self {
348        Self {
349            inner: field.metadata().clone(),
350        }
351    }
352
353    /// Create a new metadata instance from a map of string keys to string values.
354    pub fn new(inner: BTreeMap<String, String>) -> Self {
355        Self {
356            inner: Metadata::from(inner),
357        }
358    }
359
360    /// Get the inner [`Metadata`]
361    pub fn inner(&self) -> &Metadata {
362        &self.inner
363    }
364
365    /// Return the inner [`Metadata`]
366    pub fn into_inner(self) -> Metadata {
367        self.inner
368    }
369
370    /// Adds metadata from `other` into `self`, overwriting any existing keys.
371    pub fn extend(&mut self, other: Self) {
372        if other.is_empty() {
373            return;
374        }
375        self.inner.extend(other.inner);
376    }
377
378    /// Returns true if the metadata is empty.
379    pub fn is_empty(&self) -> bool {
380        self.inner.is_empty()
381    }
382
383    /// Returns the number of key-value pairs in the metadata.
384    pub fn len(&self) -> usize {
385        self.inner.len()
386    }
387
388    /// Convert this `FieldMetadata` into a `HashMap<String, String>`
389    pub fn to_hashmap(&self) -> std::collections::HashMap<String, String> {
390        (&self.inner).into()
391    }
392
393    /// Convert this `FieldMetadata` into an arrow [`Metadata`]
394    ///
395    /// This is cheap, as [`Metadata`] is cheap to clone.
396    pub fn to_metadata(&self) -> Metadata {
397        self.inner.clone()
398    }
399
400    /// Updates the metadata on the Field with this metadata, if it is not empty.
401    pub fn add_to_field(&self, field: Field) -> Field {
402        if self.inner.is_empty() {
403            return field;
404        }
405
406        field.with_metadata(self.inner.clone())
407    }
408
409    /// Updates the metadata on the FieldRef with this metadata, if it is not empty.
410    pub fn add_to_field_ref(&self, mut field_ref: FieldRef) -> FieldRef {
411        if self.inner.is_empty() {
412            return field_ref;
413        }
414
415        Arc::make_mut(&mut field_ref).set_metadata(self.inner.clone());
416        field_ref
417    }
418}
419
420impl From<&FieldMetadata> for Metadata {
421    fn from(value: &FieldMetadata) -> Self {
422        value.to_metadata()
423    }
424}
425
426impl From<Metadata> for FieldMetadata {
427    fn from(value: Metadata) -> Self {
428        Self { inner: value }
429    }
430}
431
432impl From<&Metadata> for FieldMetadata {
433    fn from(value: &Metadata) -> Self {
434        Self::from(value.clone())
435    }
436}
437
438impl From<&Field> for FieldMetadata {
439    fn from(field: &Field) -> Self {
440        Self::new_from_field(field)
441    }
442}
443
444impl From<BTreeMap<String, String>> for FieldMetadata {
445    fn from(inner: BTreeMap<String, String>) -> Self {
446        Self::new(inner)
447    }
448}
449
450impl From<std::collections::HashMap<String, String>> for FieldMetadata {
451    fn from(map: std::collections::HashMap<String, String>) -> Self {
452        Self {
453            inner: Metadata::from(map),
454        }
455    }
456}
457
458/// From reference
459impl From<&std::collections::HashMap<String, String>> for FieldMetadata {
460    fn from(map: &std::collections::HashMap<String, String>) -> Self {
461        let inner = map
462            .iter()
463            .map(|(k, v)| (k.to_string(), v.to_string()))
464            .collect();
465        Self::new(inner)
466    }
467}
468
469/// From hashbrown map
470impl From<HashMap<String, String>> for FieldMetadata {
471    fn from(map: HashMap<String, String>) -> Self {
472        Self {
473            inner: map.into_iter().collect(),
474        }
475    }
476}
477
478impl From<&HashMap<String, String>> for FieldMetadata {
479    fn from(map: &HashMap<String, String>) -> Self {
480        Self {
481            inner: map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
482        }
483    }
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489
490    #[test]
491    fn coerced_fields_metadata_merges_with_earlier_precedence() {
492        let a = Field::new("a", DataType::Binary, true).with_metadata(
493            std::collections::HashMap::from([
494                ("k".to_string(), "v1".to_string()),
495                ("only_a".to_string(), "a".to_string()),
496            ]),
497        );
498        let b = Field::new("b", DataType::Binary, true).with_metadata(
499            std::collections::HashMap::from([
500                ("k".to_string(), "v2".to_string()),
501                ("only_b".to_string(), "b".to_string()),
502            ]),
503        );
504        let result = coerced_fields_metadata([&a, &b]).unwrap();
505        assert_eq!(result.inner().get("k").map(String::as_str), Some("v1"));
506        assert_eq!(result.inner().get("only_a").map(String::as_str), Some("a"));
507        assert_eq!(result.inner().get("only_b").map(String::as_str), Some("b"));
508    }
509
510    #[test]
511    fn coerced_fields_metadata_skips_null_typed_fields() {
512        let null = Field::new("null", DataType::Null, true);
513        let b = Field::new("b", DataType::Binary, true).with_metadata(
514            std::collections::HashMap::from([("k".to_string(), "v".to_string())]),
515        );
516        let result = coerced_fields_metadata([&null, &b]).unwrap();
517        assert_eq!(result.inner().get("k").map(String::as_str), Some("v"));
518    }
519
520    #[test]
521    fn coerced_fields_metadata_empty_when_no_field_has_any() {
522        let a = Field::new("a", DataType::Binary, true);
523        let null = Field::new("null", DataType::Null, true);
524        assert!(coerced_fields_metadata([&a, &null]).unwrap().is_empty());
525    }
526
527    #[test]
528    fn coerced_fields_metadata_errors_on_differing_extension_names() {
529        let a = Field::new("a", DataType::Binary, true).with_metadata(
530            std::collections::HashMap::from([(
531                EXTENSION_TYPE_NAME_KEY.to_string(),
532                "arrow.json".to_string(),
533            )]),
534        );
535        let b = Field::new("b", DataType::Binary, true).with_metadata(
536            std::collections::HashMap::from([(
537                EXTENSION_TYPE_NAME_KEY.to_string(),
538                "geoarrow.wkb".to_string(),
539            )]),
540        );
541        let err = coerced_fields_metadata([&a, &b]).unwrap_err();
542        assert!(err.to_string().contains("arrow.json"), "{err}");
543        assert!(err.to_string().contains("geoarrow.wkb"), "{err}");
544    }
545
546    #[test]
547    fn coerced_fields_metadata_keeps_extension_keys_paired() {
548        // The extension metadata travels with the field that supplied the
549        // extension name: byte-wise differences for the same name are
550        // tolerated, and a bare extension name never picks up another
551        // field's parameters.
552        let a = Field::new("a", DataType::Binary, true).with_metadata(
553            std::collections::HashMap::from([(
554                EXTENSION_TYPE_NAME_KEY.to_string(),
555                "ext.type".to_string(),
556            )]),
557        );
558        let b = Field::new("b", DataType::Binary, true).with_metadata(
559            std::collections::HashMap::from([
560                (EXTENSION_TYPE_NAME_KEY.to_string(), "ext.type".to_string()),
561                (
562                    EXTENSION_TYPE_METADATA_KEY.to_string(),
563                    "{\"param\": 1}".to_string(),
564                ),
565            ]),
566        );
567        let result = coerced_fields_metadata([&a, &b]).unwrap();
568        assert_eq!(
569            result
570                .inner()
571                .get(EXTENSION_TYPE_NAME_KEY)
572                .map(String::as_str),
573            Some("ext.type")
574        );
575        // "a" supplied the extension name first and carried no parameters;
576        // "b"'s parameters are not grafted onto it.
577        assert_eq!(result.inner().get(EXTENSION_TYPE_METADATA_KEY), None);
578    }
579}