Skip to main content

datafusion_common/
unnest.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
5//! [`UnnestOptions`] for unnesting structured types
6
7use crate::Column;
8
9/// How [`UnnestOptions`] handles `NULL` and empty list values in the input column.
10///
11/// The variants enumerate the three observable behaviors so that callers do
12/// not have to compose multiple boolean flags to express what they want.
13#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Hash)]
14pub enum NullHandling {
15    /// Drop rows where the input list is `NULL` or empty. Matches the
16    /// default behavior of systems such as DuckDB and ClickHouse.
17    Drop,
18    /// Preserve `NULL` input rows as a single output row containing `NULL`.
19    /// Empty lists still produce zero output rows. This is the default and
20    /// matches DataFusion's historical `preserve_nulls = true` behavior.
21    #[default]
22    Preserve,
23    /// Like [`Self::Preserve`], and additionally treat an empty list
24    /// identically to a `NULL` list, producing a single output row
25    /// containing `NULL`.
26    PreserveAndExpandEmpty,
27}
28
29/// Options for unnesting a column that contains a list type,
30/// replicating values in the other, non nested rows.
31///
32/// Conceptually this operation is like joining each row with all the
33/// values in the list column.
34///
35/// The behavior with `NULL` and empty input lists is controlled by
36/// [`NullHandling`]. See its variants for full details.
37///
38/// # Examples
39///
40/// ## `Unnest(c1)`, null_handling: NullHandling::Drop
41/// ```text
42///      ┌─────────┐ ┌─────┐                ┌─────────┐ ┌─────┐
43///      │ {1, 2}  │ │  A  │   Unnest       │    1    │ │  A  │
44///      ├─────────┤ ├─────┤                ├─────────┤ ├─────┤
45///      │  null   │ │  B  │                │    2    │ │  A  │
46///      ├─────────┤ ├─────┤ ────────────▶  ├─────────┤ ├─────┤
47///      │   {}    │ │  D  │                │    3    │ │  E  │
48///      ├─────────┤ ├─────┤                └─────────┘ └─────┘
49///      │   {3}   │ │  E  │                    c1        c2
50///      └─────────┘ └─────┘
51///        c1         c2
52/// ```
53///
54/// ## `Unnest(c1)`, null_handling: NullHandling::Preserve
55/// ```text
56///      ┌─────────┐ ┌─────┐                ┌─────────┐ ┌─────┐
57///      │ {1, 2}  │ │  A  │   Unnest       │    1    │ │  A  │
58///      ├─────────┤ ├─────┤                ├─────────┤ ├─────┤
59///      │  null   │ │  B  │                │    2    │ │  A  │
60///      ├─────────┤ ├─────┤ ────────────▶  ├─────────┤ ├─────┤
61///      │   {}    │ │  D  │                │  null   │ │  B  │
62///      ├─────────┤ ├─────┤                ├─────────┤ ├─────┤
63///      │   {3}   │ │  E  │                │    3    │ │  E  │
64///      └─────────┘ └─────┘                └─────────┘ └─────┘
65///        c1         c2                        c1        c2
66/// ```
67///
68/// ## `Unnest(c1)`, null_handling: NullHandling::PreserveAndExpandEmpty
69/// ```text
70///      ┌─────────┐ ┌─────┐                ┌─────────┐ ┌─────┐
71///      │ {1, 2}  │ │  A  │   Unnest       │    1    │ │  A  │
72///      ├─────────┤ ├─────┤                ├─────────┤ ├─────┤
73///      │  null   │ │  B  │                │    2    │ │  A  │
74///      ├─────────┤ ├─────┤ ────────────▶  ├─────────┤ ├─────┤
75///      │   {}    │ │  D  │                │  null   │ │  B  │
76///      ├─────────┤ ├─────┤                ├─────────┤ ├─────┤
77///      │   {3}   │ │  E  │                │  null   │ │  D  │
78///      └─────────┘ └─────┘                ├─────────┤ ├─────┤
79///        c1         c2                    │    3    │ │  E  │
80///                                         └─────────┘ └─────┘
81///                                             c1        c2
82/// ```
83///
84/// `recursions` instruct how a column should be unnested (e.g unnesting a column multiple
85/// time, with depth = 1 and depth = 2). Any unnested column not being mentioned inside this
86/// options is inferred to be unnested with depth = 1
87#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq)]
88pub struct UnnestOptions {
89    /// How to handle `NULL` and empty list values in the input column.
90    /// Defaults to [`NullHandling::Preserve`].
91    pub null_handling: NullHandling,
92    /// If specific columns need to be unnested multiple times (e.g at different depth),
93    /// declare them here. Any unnested columns not being mentioned inside this option
94    /// will be unnested with depth = 1
95    pub recursions: Vec<RecursionUnnestOption>,
96}
97
98/// Instruction on how to unnest a column (mostly with a list type)
99/// such as how to name the output, and how many level it should be unnested
100#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd)]
101pub struct RecursionUnnestOption {
102    pub input_column: Column,
103    pub output_column: Column,
104    pub depth: usize,
105}
106
107impl Default for UnnestOptions {
108    fn default() -> Self {
109        Self {
110            null_handling: NullHandling::Preserve,
111            recursions: vec![],
112        }
113    }
114}
115
116impl UnnestOptions {
117    /// Create a new [`UnnestOptions`] with default values
118    pub fn new() -> Self {
119        Default::default()
120    }
121
122    /// Set the [`NullHandling`] mode used when unnesting `NULL` or empty
123    /// input lists.
124    pub fn with_null_handling(mut self, null_handling: NullHandling) -> Self {
125        self.null_handling = null_handling;
126        self
127    }
128
129    /// Backward-compatible setter that maps the previous boolean
130    /// `preserve_nulls` flag onto [`NullHandling`].
131    ///
132    /// `true` maps to [`NullHandling::Preserve`]; `false` maps to
133    /// [`NullHandling::Drop`]. To opt into the new empty-list-preserving
134    /// mode, call [`Self::with_null_handling`] directly with
135    /// [`NullHandling::PreserveAndExpandEmpty`].
136    pub fn with_preserve_nulls(self, preserve_nulls: bool) -> Self {
137        let null_handling = if preserve_nulls {
138            NullHandling::Preserve
139        } else {
140            NullHandling::Drop
141        };
142        self.with_null_handling(null_handling)
143    }
144
145    /// Returns true if `NULL` input rows produce a single output row
146    /// containing `NULL`.
147    pub fn preserve_nulls(&self) -> bool {
148        !matches!(self.null_handling, NullHandling::Drop)
149    }
150
151    /// Returns true if empty input lists should produce a single
152    /// output row containing `NULL`.
153    pub fn expand_empty_as_null(&self) -> bool {
154        matches!(self.null_handling, NullHandling::PreserveAndExpandEmpty)
155    }
156
157    /// Set the recursions for the unnest operation
158    pub fn with_recursions(mut self, recursion: RecursionUnnestOption) -> Self {
159        self.recursions.push(recursion);
160        self
161    }
162}