datafusion-common 56.0.0

Common functionality for DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use std::{collections::BTreeMap, sync::Arc};

use arrow::datatypes::{DataType, Field, FieldRef, Metadata};
use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
use hashbrown::HashMap;

use crate::{DataFusionError, ScalarValue, error::_plan_err};

/// A [`ScalarValue`] with optional [`FieldMetadata`]
#[derive(Debug, Clone)]
pub struct ScalarAndMetadata {
    pub value: ScalarValue,
    pub metadata: Option<FieldMetadata>,
}

impl ScalarAndMetadata {
    /// Create a new Literal from a scalar value with optional [`FieldMetadata`]
    pub fn new(value: ScalarValue, metadata: Option<FieldMetadata>) -> Self {
        Self { value, metadata }
    }

    /// Access the underlying [ScalarValue] storage
    pub fn value(&self) -> &ScalarValue {
        &self.value
    }

    /// Access the [FieldMetadata] attached to this value, if any
    pub fn metadata(&self) -> Option<&FieldMetadata> {
        self.metadata.as_ref()
    }

    /// Consume self and return components
    pub fn into_inner(self) -> (ScalarValue, Option<FieldMetadata>) {
        (self.value, self.metadata)
    }

    /// Cast this values's storage type
    ///
    /// This operation assumes that if the underlying [ScalarValue] can be casted
    /// to a given type that any extension type represented by the metadata is also
    /// valid.
    pub fn cast_storage_to(
        &self,
        target_type: &DataType,
    ) -> Result<Self, DataFusionError> {
        let new_value = self.value().cast_to(target_type)?;
        Ok(Self::new(new_value, self.metadata.clone()))
    }
}

/// create a new ScalarAndMetadata from a ScalarValue without
/// any metadata
impl From<ScalarValue> for ScalarAndMetadata {
    fn from(value: ScalarValue) -> Self {
        Self::new(value, None)
    }
}

/// Assert equality of data types where one or both sides may have field metadata
///
/// This currently compares absent metadata (e.g., one side was a DataType) and
/// empty metadata (e.g., one side was a field where the field had no metadata)
/// as equal and uses byte-for-byte comparison for the keys and values of the
/// fields, even though this is potentially too strict for some cases (e.g.,
/// extension types where extension metadata is represented by JSON, or cases
/// where field metadata is orthogonal to the interpretation of the data type).
///
/// Returns a planning error with suitably formatted type representations if
/// actual and expected do not compare to equal.
pub fn check_metadata_with_storage_equal(
    actual: (&DataType, Option<&Metadata>),
    expected: (&DataType, Option<&Metadata>),
    what: &str,
    context: &str,
) -> Result<(), DataFusionError> {
    if actual.0 != expected.0 {
        return _plan_err!(
            "Expected {what} of type {}, got {}{context}",
            format_type_and_metadata(expected.0, expected.1),
            format_type_and_metadata(actual.0, actual.1)
        );
    }

    let metadata_equal = match (actual.1, expected.1) {
        (None, None) => true,
        (None, Some(expected_metadata)) => expected_metadata.is_empty(),
        (Some(actual_metadata), None) => actual_metadata.is_empty(),
        (Some(actual_metadata), Some(expected_metadata)) => {
            actual_metadata == expected_metadata
        }
    };

    if !metadata_equal {
        return _plan_err!(
            "Expected {what} of type {}, got {}{context}",
            format_type_and_metadata(expected.0, expected.1),
            format_type_and_metadata(actual.0, actual.1)
        );
    }

    Ok(())
}

/// Compute the field metadata to propagate for an expression whose result
/// may come from any one of several inputs coerced to a common type, such as
/// `COALESCE`, `NVL2`, or `CASE WHEN`.
///
/// Metadata is merged across the fields whose data type is not `Null` (an
/// untyped NULL literal carries no metadata and cannot contribute a typed
/// value), with earlier fields taking precedence for repeated keys. Unrelated
/// keys are not required to agree: metadata that arrived with the data (e.g.
/// from an Arrow file or an embedded Arrow schema in a Parquet file) must not
/// cause an extension type to be silently dropped from the result.
///
/// The Arrow extension type keys are handled as a unit, like in
/// [`Expr::Cast`] output field derivation:
/// - Differing values of `ARROW:extension:name` produce a planning error;
///   the inputs are of different logical types even though they were coerced
///   to a common storage type.
/// - `ARROW:extension:metadata` is taken from the field that supplied the
///   extension name, never combined from another field. Byte-wise differences
///   in the extension metadata of fields that agree on the extension name are
///   tolerated, since extension parameters are often JSON-encoded, where byte
///   equality is too strict.
///
/// [`Expr::Cast`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html#variant.Cast
pub fn coerced_fields_metadata<'a>(
    fields: impl IntoIterator<Item = &'a Field>,
) -> Result<FieldMetadata, DataFusionError> {
    let mut merged: BTreeMap<String, String> = BTreeMap::new();
    let mut extension: Option<(String, Option<String>)> = None;

    for field in fields {
        if field.data_type().is_null() {
            continue;
        }
        let metadata = FieldMetadata::new_from_field(field);
        if let Some(name) = metadata.inner().get(EXTENSION_TYPE_NAME_KEY) {
            match &extension {
                Some((first_name, _)) if first_name != name => {
                    return _plan_err!(
                        "Cannot merge field metadata with differing values of \
                         '{EXTENSION_TYPE_NAME_KEY}': '{first_name}' and '{name}'"
                    );
                }
                Some(_) => {}
                None => {
                    extension = Some((
                        name.clone(),
                        metadata.inner().get(EXTENSION_TYPE_METADATA_KEY).cloned(),
                    ));
                }
            }
        }
        for (key, value) in metadata.inner() {
            if key == EXTENSION_TYPE_NAME_KEY || key == EXTENSION_TYPE_METADATA_KEY {
                continue;
            }
            merged.entry(key.clone()).or_insert_with(|| value.clone());
        }
    }

    if let Some((name, extension_metadata)) = extension {
        merged.insert(EXTENSION_TYPE_NAME_KEY.to_string(), name);
        if let Some(extension_metadata) = extension_metadata {
            merged.insert(EXTENSION_TYPE_METADATA_KEY.to_string(), extension_metadata);
        }
    }

    Ok(FieldMetadata::from(merged))
}

/// Given a data type represented by storage and optional metadata, generate
/// a user-facing string
///
/// This function exists to reduce the number of Field debug strings that are
/// used to communicate type information in error messages and plan explain
/// renderings.
pub fn format_type_and_metadata(
    data_type: &DataType,
    metadata: Option<&Metadata>,
) -> String {
    match metadata {
        Some(metadata) if !metadata.is_empty() => {
            format!("{data_type}<{metadata:?}>")
        }
        _ => data_type.to_string(),
    }
}

/// Merges the field or schema metadata of the inputs of a `UNION`.
///
/// Inputs are merged in order: keys present in only some inputs are kept, and
/// when inputs disagree on a key's value, the last input wins. Inputs without
/// metadata (e.g. `NULL` literals) contribute nothing.
///
/// # Example
/// ```
/// # use arrow::datatypes::Metadata;
/// # use datafusion_common::metadata::merge_metadata_for_union;
/// let first = Metadata::new().with("id", "1").with("only_first", "a");
/// let last = Metadata::new().with("id", "2");
/// assert_eq!(
///     merge_metadata_for_union([&first, &last]),
///     Metadata::new().with("id", "2").with("only_first", "a"),
/// );
/// ```
pub fn merge_metadata_for_union<'a>(
    metadatas: impl IntoIterator<Item = &'a Metadata>,
) -> Metadata {
    metadatas
        .into_iter()
        .fold(Metadata::new(), |mut merged, metadata| {
            if merged.is_empty() {
                // Shares the underlying map rather than copying it
                metadata.clone()
            } else {
                merged.extend(metadata);
                merged
            }
        })
}

/// Literal metadata
///
/// Stores metadata associated with a literal expressions
/// and is designed to be fast to `clone`.
///
/// This structure is used to store metadata associated with a literal expression, and it
/// corresponds to the `metadata` field on [`Field`].
///
/// # Example: Create [`FieldMetadata`] from a [`Field`]
/// ```
/// # use std::collections::HashMap;
/// # use datafusion_common::metadata::FieldMetadata;
/// # use arrow::datatypes::{Field, DataType};
/// # let field = Field::new("c1", DataType::Int32, true)
/// #  .with_metadata(HashMap::from([("foo".to_string(), "bar".to_string())]));
/// // Create a new `FieldMetadata` instance from a `Field`
/// let metadata = FieldMetadata::new_from_field(&field);
/// // There is also a `From` impl:
/// let metadata = FieldMetadata::from(&field);
/// ```
///
/// # Example: Update a [`Field`] with [`FieldMetadata`]
/// ```
/// # use datafusion_common::metadata::FieldMetadata;
/// # use arrow::datatypes::{Field, DataType};
/// # let field = Field::new("c1", DataType::Int32, true);
/// # let metadata = FieldMetadata::new_from_field(&field);
/// // Add any metadata from `FieldMetadata` to `Field`
/// let updated_field = metadata.add_to_field(field);
/// ```
///
/// For more background, please also see the [Implementing User Defined Types and Custom Metadata in DataFusion blog]
///
/// [Implementing User Defined Types and Custom Metadata in DataFusion blog]: https://datafusion.apache.org/blog/2025/09/21/custom-types-using-metadata
#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
pub struct FieldMetadata {
    /// The inner metadata of a literal expression, which is a map of string
    /// keys to string values.
    inner: Metadata,
}

impl Default for FieldMetadata {
    fn default() -> Self {
        Self::new_empty()
    }
}

impl FieldMetadata {
    /// Create a new empty metadata instance.
    pub fn new_empty() -> Self {
        Self {
            inner: Metadata::new(),
        }
    }

    /// Merges two optional `FieldMetadata` instances, overwriting any existing
    /// keys in `m` with keys from `n` if present.
    ///
    /// This function is commonly used in alias operations, particularly for literals
    /// with metadata. When creating an alias expression, the metadata from the original
    /// expression (such as a literal) is combined with any metadata specified on the alias.
    ///
    /// # Arguments
    ///
    /// * `m` - The first metadata (typically from the original expression like a literal)
    /// * `n` - The second metadata (typically from the alias definition)
    ///
    /// # Merge Strategy
    ///
    /// - If both metadata instances exist, they are merged with `n` taking precedence
    /// - Keys from `n` will overwrite keys from `m` if they have the same name
    /// - If only one metadata instance exists, it is returned unchanged
    /// - If neither exists, `None` is returned
    ///
    /// # Example usage
    /// ```rust
    /// use datafusion_common::metadata::FieldMetadata;
    /// use std::collections::BTreeMap;
    ///
    /// // Create metadata for a literal expression
    /// let literal_metadata = Some(FieldMetadata::from(BTreeMap::from([
    ///     ("source".to_string(), "constant".to_string()),
    ///     ("type".to_string(), "int".to_string()),
    /// ])));
    ///
    /// // Create metadata for an alias
    /// let alias_metadata = Some(FieldMetadata::from(BTreeMap::from([
    ///     ("description".to_string(), "answer".to_string()),
    ///     ("source".to_string(), "user".to_string()), // This will override literal's "source"
    /// ])));
    ///
    /// // Merge the metadata
    /// let merged = FieldMetadata::merge_options(
    ///     literal_metadata.as_ref(),
    ///     alias_metadata.as_ref(),
    /// );
    ///
    /// // Result contains: {"source": "user", "type": "int", "description": "answer"}
    /// assert!(merged.is_some());
    /// ```
    pub fn merge_options(
        m: Option<&FieldMetadata>,
        n: Option<&FieldMetadata>,
    ) -> Option<FieldMetadata> {
        match (m, n) {
            (Some(m), Some(n)) => {
                let mut merged = m.clone();
                merged.extend(n.clone());
                Some(merged)
            }
            (Some(m), None) => Some(m.clone()),
            (None, Some(n)) => Some(n.clone()),
            (None, None) => None,
        }
    }

    /// Create a new metadata instance from a `Field`'s metadata.
    ///
    /// This is cheap, as [`Metadata`] is cheap to clone.
    pub fn new_from_field(field: &Field) -> Self {
        Self {
            inner: field.metadata().clone(),
        }
    }

    /// Create a new metadata instance from a map of string keys to string values.
    pub fn new(inner: BTreeMap<String, String>) -> Self {
        Self {
            inner: Metadata::from(inner),
        }
    }

    /// Get the inner [`Metadata`]
    pub fn inner(&self) -> &Metadata {
        &self.inner
    }

    /// Return the inner [`Metadata`]
    pub fn into_inner(self) -> Metadata {
        self.inner
    }

    /// Adds metadata from `other` into `self`, overwriting any existing keys.
    pub fn extend(&mut self, other: Self) {
        if other.is_empty() {
            return;
        }
        self.inner.extend(other.inner);
    }

    /// Returns true if the metadata is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the number of key-value pairs in the metadata.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Convert this `FieldMetadata` into a `HashMap<String, String>`
    pub fn to_hashmap(&self) -> std::collections::HashMap<String, String> {
        (&self.inner).into()
    }

    /// Convert this `FieldMetadata` into an arrow [`Metadata`]
    ///
    /// This is cheap, as [`Metadata`] is cheap to clone.
    pub fn to_metadata(&self) -> Metadata {
        self.inner.clone()
    }

    /// Updates the metadata on the Field with this metadata, if it is not empty.
    pub fn add_to_field(&self, field: Field) -> Field {
        if self.inner.is_empty() {
            return field;
        }

        field.with_metadata(self.inner.clone())
    }

    /// Updates the metadata on the FieldRef with this metadata, if it is not empty.
    pub fn add_to_field_ref(&self, mut field_ref: FieldRef) -> FieldRef {
        if self.inner.is_empty() {
            return field_ref;
        }

        Arc::make_mut(&mut field_ref).set_metadata(self.inner.clone());
        field_ref
    }
}

impl From<&FieldMetadata> for Metadata {
    fn from(value: &FieldMetadata) -> Self {
        value.to_metadata()
    }
}

impl From<Metadata> for FieldMetadata {
    fn from(value: Metadata) -> Self {
        Self { inner: value }
    }
}

impl From<&Metadata> for FieldMetadata {
    fn from(value: &Metadata) -> Self {
        Self::from(value.clone())
    }
}

impl From<&Field> for FieldMetadata {
    fn from(field: &Field) -> Self {
        Self::new_from_field(field)
    }
}

impl From<BTreeMap<String, String>> for FieldMetadata {
    fn from(inner: BTreeMap<String, String>) -> Self {
        Self::new(inner)
    }
}

impl From<std::collections::HashMap<String, String>> for FieldMetadata {
    fn from(map: std::collections::HashMap<String, String>) -> Self {
        Self {
            inner: Metadata::from(map),
        }
    }
}

/// From reference
impl From<&std::collections::HashMap<String, String>> for FieldMetadata {
    fn from(map: &std::collections::HashMap<String, String>) -> Self {
        let inner = map
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        Self::new(inner)
    }
}

/// From hashbrown map
impl From<HashMap<String, String>> for FieldMetadata {
    fn from(map: HashMap<String, String>) -> Self {
        Self {
            inner: map.into_iter().collect(),
        }
    }
}

impl From<&HashMap<String, String>> for FieldMetadata {
    fn from(map: &HashMap<String, String>) -> Self {
        Self {
            inner: map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn coerced_fields_metadata_merges_with_earlier_precedence() {
        let a = Field::new("a", DataType::Binary, true).with_metadata(
            std::collections::HashMap::from([
                ("k".to_string(), "v1".to_string()),
                ("only_a".to_string(), "a".to_string()),
            ]),
        );
        let b = Field::new("b", DataType::Binary, true).with_metadata(
            std::collections::HashMap::from([
                ("k".to_string(), "v2".to_string()),
                ("only_b".to_string(), "b".to_string()),
            ]),
        );
        let result = coerced_fields_metadata([&a, &b]).unwrap();
        assert_eq!(result.inner().get("k").map(String::as_str), Some("v1"));
        assert_eq!(result.inner().get("only_a").map(String::as_str), Some("a"));
        assert_eq!(result.inner().get("only_b").map(String::as_str), Some("b"));
    }

    #[test]
    fn coerced_fields_metadata_skips_null_typed_fields() {
        let null = Field::new("null", DataType::Null, true);
        let b = Field::new("b", DataType::Binary, true).with_metadata(
            std::collections::HashMap::from([("k".to_string(), "v".to_string())]),
        );
        let result = coerced_fields_metadata([&null, &b]).unwrap();
        assert_eq!(result.inner().get("k").map(String::as_str), Some("v"));
    }

    #[test]
    fn coerced_fields_metadata_empty_when_no_field_has_any() {
        let a = Field::new("a", DataType::Binary, true);
        let null = Field::new("null", DataType::Null, true);
        assert!(coerced_fields_metadata([&a, &null]).unwrap().is_empty());
    }

    #[test]
    fn coerced_fields_metadata_errors_on_differing_extension_names() {
        let a = Field::new("a", DataType::Binary, true).with_metadata(
            std::collections::HashMap::from([(
                EXTENSION_TYPE_NAME_KEY.to_string(),
                "arrow.json".to_string(),
            )]),
        );
        let b = Field::new("b", DataType::Binary, true).with_metadata(
            std::collections::HashMap::from([(
                EXTENSION_TYPE_NAME_KEY.to_string(),
                "geoarrow.wkb".to_string(),
            )]),
        );
        let err = coerced_fields_metadata([&a, &b]).unwrap_err();
        assert!(err.to_string().contains("arrow.json"), "{err}");
        assert!(err.to_string().contains("geoarrow.wkb"), "{err}");
    }

    #[test]
    fn coerced_fields_metadata_keeps_extension_keys_paired() {
        // The extension metadata travels with the field that supplied the
        // extension name: byte-wise differences for the same name are
        // tolerated, and a bare extension name never picks up another
        // field's parameters.
        let a = Field::new("a", DataType::Binary, true).with_metadata(
            std::collections::HashMap::from([(
                EXTENSION_TYPE_NAME_KEY.to_string(),
                "ext.type".to_string(),
            )]),
        );
        let b = Field::new("b", DataType::Binary, true).with_metadata(
            std::collections::HashMap::from([
                (EXTENSION_TYPE_NAME_KEY.to_string(), "ext.type".to_string()),
                (
                    EXTENSION_TYPE_METADATA_KEY.to_string(),
                    "{\"param\": 1}".to_string(),
                ),
            ]),
        );
        let result = coerced_fields_metadata([&a, &b]).unwrap();
        assert_eq!(
            result
                .inner()
                .get(EXTENSION_TYPE_NAME_KEY)
                .map(String::as_str),
            Some("ext.type")
        );
        // "a" supplied the extension name first and carried no parameters;
        // "b"'s parameters are not grafted onto it.
        assert_eq!(result.inner().get(EXTENSION_TYPE_METADATA_KEY), None);
    }
}