Skip to main content

datafusion_common/
functional_dependencies.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//! FunctionalDependencies keeps track of functional dependencies
6//! inside DFSchema.
7
8use std::fmt::{Display, Formatter};
9use std::ops::Deref;
10use std::vec::IntoIter;
11
12use crate::utils::{merge_and_order_indices, set_difference};
13use crate::{DFSchema, HashSet, JoinType, NullEquality};
14
15/// This object defines a constraint on a table.
16#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
17pub enum Constraint {
18    /// Columns with the given indices form a composite primary key (they are
19    /// jointly unique and not nullable):
20    PrimaryKey(Vec<usize>),
21    /// Columns with the given indices form a composite unique key:
22    Unique(Vec<usize>),
23}
24
25/// This object encapsulates a list of functional constraints:
26#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd)]
27pub struct Constraints {
28    inner: Vec<Constraint>,
29}
30
31impl Constraints {
32    /// Create a new [`Constraints`] object from the given `constraints`.
33    /// Users should use the [`Constraints::default`] or [`SqlToRel::new_constraint_from_table_constraints`]
34    /// functions for constructing [`Constraints`] instances. This constructor
35    /// is for internal purposes only and does not check whether the argument
36    /// is valid. The user is responsible for supplying a valid vector of
37    /// [`Constraint`] objects.
38    ///
39    /// [`SqlToRel::new_constraint_from_table_constraints`]: https://docs.rs/datafusion/latest/datafusion/sql/planner/struct.SqlToRel.html#method.new_constraint_from_table_constraints
40    pub fn new_unverified(constraints: Vec<Constraint>) -> Self {
41        Self { inner: constraints }
42    }
43
44    /// Extends the current constraints with the given `other` constraints.
45    pub fn extend(&mut self, other: Constraints) {
46        self.inner.extend(other.inner);
47    }
48
49    /// Projects constraints using the given projection indices. Returns `None`
50    /// if any of the constraint columns are not included in the projection.
51    pub fn project(&self, proj_indices: &[usize]) -> Option<Self> {
52        let projected = self
53            .inner
54            .iter()
55            .filter_map(|constraint| {
56                match constraint {
57                    Constraint::PrimaryKey(indices) => {
58                        let new_indices =
59                            update_elements_with_matching_indices(indices, proj_indices);
60                        // Only keep the constraint if all columns are preserved:
61                        (new_indices.len() == indices.len())
62                            .then_some(Constraint::PrimaryKey(new_indices))
63                    }
64                    Constraint::Unique(indices) => {
65                        let new_indices =
66                            update_elements_with_matching_indices(indices, proj_indices);
67                        // Only keep the constraint if all columns are preserved:
68                        (new_indices.len() == indices.len())
69                            .then_some(Constraint::Unique(new_indices))
70                    }
71                }
72            })
73            .collect::<Vec<_>>();
74
75        (!projected.is_empty()).then_some(Constraints::new_unverified(projected))
76    }
77}
78
79impl IntoIterator for Constraints {
80    type Item = Constraint;
81    type IntoIter = IntoIter<Self::Item>;
82
83    fn into_iter(self) -> Self::IntoIter {
84        self.inner.into_iter()
85    }
86}
87
88impl Display for Constraints {
89    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
90        let pk = self
91            .inner
92            .iter()
93            .map(|c| format!("{c:?}"))
94            .collect::<Vec<_>>();
95        let pk = pk.join(", ");
96        write!(f, "constraints=[{pk}]")
97    }
98}
99
100impl Deref for Constraints {
101    type Target = [Constraint];
102
103    fn deref(&self) -> &Self::Target {
104        self.inner.as_slice()
105    }
106}
107
108/// This object defines a functional dependence in the schema. A functional
109/// dependence defines a relationship between determinant keys and dependent
110/// columns. A determinant key is a column, or a set of columns, whose value
111/// uniquely determines values of some other (dependent) columns. If two rows
112/// have the same determinant key, dependent columns in these rows are
113/// necessarily the same. If the determinant key is unique, the set of
114/// dependent columns is equal to the entire schema and the determinant key can
115/// serve as a primary key. Note that a primary key may "downgrade" into a
116/// determinant key due to an operation such as a join, and this object is
117/// used to track dependence relationships in such cases. For more information
118/// on functional dependencies, see:
119/// <https://www.scaler.com/topics/dbms/functional-dependency-in-dbms/>
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct FunctionalDependence {
122    // Column indices of the (possibly composite) determinant key:
123    pub source_indices: Vec<usize>,
124    // Column indices of dependent column(s):
125    pub target_indices: Vec<usize>,
126    /// Flag indicating whether one of the `source_indices` can receive NULL values.
127    /// For a data source, if the constraint in question is `Constraint::Unique`,
128    /// this flag is `true`. If the constraint in question is `Constraint::PrimaryKey`,
129    /// this flag is `false`.
130    /// Note that as the schema changes between different stages in a plan,
131    /// such as after LEFT JOIN or RIGHT JOIN operations, this property may
132    /// change.
133    pub nullable: bool,
134    /// The NULL-comparison semantics under which this dependency holds. The
135    /// conservative default, [`NullEquality::NullEqualsNothing`], means it
136    /// holds only across rows whose determinant contains no NULLs; e.g. a
137    /// nullable `UNIQUE` constraint permits multiple NULL rows that may differ.
138    /// [`NullEquality::NullEqualsNull`] means it also holds when NULL
139    /// determinant values are treated as equal; e.g. a `GROUP BY` key.
140    pub null_equality: NullEquality,
141    // The functional dependency mode:
142    pub mode: Dependency,
143}
144
145/// Describes functional dependency mode.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Dependency {
148    /// A determinant key may occur only once.
149    Single,
150    /// A determinant key may occur multiple times (in multiple rows).
151    Multi,
152}
153
154impl FunctionalDependence {
155    // Creates a new functional dependence.
156    pub fn new(
157        source_indices: Vec<usize>,
158        target_indices: Vec<usize>,
159        nullable: bool,
160    ) -> Self {
161        Self {
162            source_indices,
163            target_indices,
164            nullable,
165            // Assume the dependency does not hold across NULL rows by default:
166            null_equality: NullEquality::NullEqualsNothing,
167            // Start with the least restrictive mode by default:
168            mode: Dependency::Multi,
169        }
170    }
171
172    pub fn with_mode(mut self, mode: Dependency) -> Self {
173        self.mode = mode;
174        self
175    }
176
177    pub fn with_null_equality(mut self, null_equality: NullEquality) -> Self {
178        self.null_equality = null_equality;
179        self
180    }
181
182    /// Returns `true` if this dependency remains usable for operations that
183    /// treat NULL determinant values as equal (`GROUP BY`, `DISTINCT` and
184    /// sorting, which place all NULL keys together): it must hold under
185    /// NULLs-are-equal semantics, have a non-nullable determinant (e.g. a
186    /// `PRIMARY KEY`), or have no nullable source field in the given `schema`.
187    pub fn is_valid_across_nulls(&self, schema: &DFSchema) -> bool {
188        self.null_equality == NullEquality::NullEqualsNull
189            || !self.nullable
190            || self
191                .source_indices
192                .iter()
193                .all(|&source_idx| !schema.field(source_idx).is_nullable())
194    }
195}
196
197/// This object encapsulates all functional dependencies in a given relation.
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct FunctionalDependencies {
200    deps: Vec<FunctionalDependence>,
201}
202
203impl FunctionalDependencies {
204    /// Creates an empty `FunctionalDependencies` object.
205    pub fn empty() -> Self {
206        Self { deps: vec![] }
207    }
208
209    /// Creates a new `FunctionalDependencies` object from a vector of
210    /// `FunctionalDependence` objects.
211    pub fn new(dependencies: Vec<FunctionalDependence>) -> Self {
212        Self { deps: dependencies }
213    }
214
215    /// Creates a new `FunctionalDependencies` object from the given constraints.
216    pub fn new_from_constraints(
217        constraints: Option<&Constraints>,
218        n_field: usize,
219    ) -> Self {
220        if let Some(Constraints { inner: constraints }) = constraints {
221            // Construct dependency objects based on each individual constraint:
222            let dependencies = constraints
223                .iter()
224                .map(|constraint| {
225                    // All the field indices are associated with the whole table
226                    // since we are dealing with table level constraints:
227                    let dependency = match constraint {
228                        Constraint::PrimaryKey(indices) => FunctionalDependence::new(
229                            indices.to_vec(),
230                            (0..n_field).collect::<Vec<_>>(),
231                            false,
232                        ),
233                        Constraint::Unique(indices) => FunctionalDependence::new(
234                            indices.to_vec(),
235                            (0..n_field).collect::<Vec<_>>(),
236                            true,
237                        ),
238                    };
239                    // As primary keys are guaranteed to be unique, set the
240                    // functional dependency mode to `Dependency::Single`:
241                    dependency.with_mode(Dependency::Single)
242                })
243                .collect::<Vec<_>>();
244            Self::new(dependencies)
245        } else {
246            // There is no constraint, return an empty object:
247            Self::empty()
248        }
249    }
250
251    pub fn with_dependency(mut self, mode: Dependency) -> Self {
252        self.deps.iter_mut().for_each(|item| item.mode = mode);
253        self
254    }
255
256    /// Merges the given functional dependencies with these.
257    pub fn extend(&mut self, other: FunctionalDependencies) {
258        self.deps.extend(other.deps);
259    }
260
261    /// Sanity checks if functional dependencies are valid. For example, if
262    /// there are 10 fields, we cannot receive any index further than 9.
263    pub fn is_valid(&self, n_field: usize) -> bool {
264        self.deps.iter().all(
265            |FunctionalDependence {
266                 source_indices,
267                 target_indices,
268                 ..
269             }| {
270                source_indices
271                    .iter()
272                    .max()
273                    .map(|&max_index| max_index < n_field)
274                    .unwrap_or(true)
275                    && target_indices
276                        .iter()
277                        .max()
278                        .map(|&max_index| max_index < n_field)
279                        .unwrap_or(true)
280            },
281        )
282    }
283
284    /// Adds the `offset` value to `source_indices` and `target_indices` for
285    /// each functional dependency.
286    pub fn add_offset(&mut self, offset: usize) {
287        self.deps.iter_mut().for_each(
288            |FunctionalDependence {
289                 source_indices,
290                 target_indices,
291                 ..
292             }| {
293                *source_indices = add_offset_to_vec(source_indices, offset);
294                *target_indices = add_offset_to_vec(target_indices, offset);
295            },
296        )
297    }
298
299    /// Updates `source_indices` and `target_indices` of each functional
300    /// dependence using the index mapping given in `proj_indices`.
301    ///
302    /// Assume that `proj_indices` is \[2, 5, 8\] and we have a functional
303    /// dependence \[5\] (`source_indices`) -> \[5, 8\] (`target_indices`).
304    /// In the updated schema, fields at indices \[2, 5, 8\] will transform
305    /// to \[0, 1, 2\]. Therefore, the resulting functional dependence will
306    /// be \[1\] -> \[1, 2\].
307    pub fn project_functional_dependencies(
308        &self,
309        proj_indices: &[usize],
310        // The argument `n_out` denotes the schema field length, which is needed
311        // to correctly associate a `Single`-mode dependence with the whole table.
312        n_out: usize,
313    ) -> FunctionalDependencies {
314        let mut projected_func_dependencies = Vec::with_capacity(self.deps.len());
315        for FunctionalDependence {
316            source_indices,
317            target_indices,
318            nullable,
319            null_equality,
320            mode,
321        } in &self.deps
322        {
323            let new_source_indices =
324                update_elements_with_matching_indices(source_indices, proj_indices);
325            let new_target_indices = if *mode == Dependency::Single {
326                // Associate with all of the fields in the schema:
327                (0..n_out).collect()
328            } else {
329                // Update associations according to projection:
330                update_elements_with_matching_indices(target_indices, proj_indices)
331            };
332            // All of the composite indices should still be valid after projection;
333            // otherwise, functional dependency cannot be propagated.
334            if new_source_indices.len() == source_indices.len() {
335                let new_func_dependence = FunctionalDependence::new(
336                    new_source_indices,
337                    new_target_indices,
338                    *nullable,
339                )
340                .with_mode(*mode)
341                .with_null_equality(*null_equality);
342                projected_func_dependencies.push(new_func_dependence);
343            }
344        }
345        FunctionalDependencies::new(projected_func_dependencies)
346    }
347
348    /// This function joins this set of functional dependencies with the `other`
349    /// according to the given `join_type`.
350    pub fn join(
351        &self,
352        other: &FunctionalDependencies,
353        join_type: &JoinType,
354        left_cols_len: usize,
355    ) -> FunctionalDependencies {
356        // Get mutable copies of left and right side dependencies:
357        let mut right_func_dependencies = other.clone();
358        let mut left_func_dependencies = self.clone();
359
360        match join_type {
361            JoinType::Inner | JoinType::Left | JoinType::Right => {
362                // Add offset to right schema:
363                right_func_dependencies.add_offset(left_cols_len);
364
365                // Result may have multiple values, update the dependency mode:
366                left_func_dependencies =
367                    left_func_dependencies.with_dependency(Dependency::Multi);
368                right_func_dependencies =
369                    right_func_dependencies.with_dependency(Dependency::Multi);
370
371                if *join_type == JoinType::Left {
372                    // Downgrade the right side, since it may have additional NULL values:
373                    right_func_dependencies.downgrade_dependencies();
374                } else if *join_type == JoinType::Right {
375                    // Downgrade the left side, since it may have additional NULL values:
376                    left_func_dependencies.downgrade_dependencies();
377                }
378                // Combine left and right functional dependencies:
379                left_func_dependencies.extend(right_func_dependencies);
380                left_func_dependencies
381            }
382            JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
383                // These joins preserve functional dependencies of the left side:
384                left_func_dependencies
385            }
386            JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
387                // These joins preserve functional dependencies of the right side:
388                right_func_dependencies
389            }
390            JoinType::Full => {
391                // All of the functional dependencies are lost in a FULL join:
392                FunctionalDependencies::empty()
393            }
394        }
395    }
396
397    /// This function downgrades a functional dependency when nullability becomes
398    /// a possibility:
399    /// - If the dependency in question is UNIQUE (i.e. nullable), a new null value
400    ///   invalidates the dependency.
401    /// - If the dependency in question is PRIMARY KEY (i.e. not nullable), a new
402    ///   null value turns it into UNIQUE mode.
403    fn downgrade_dependencies(&mut self) {
404        // Delete nullable dependencies, since they are no longer valid:
405        self.deps.retain(|item| !item.nullable);
406        // Survivors had a non-null determinant, so every new NULL comes from a
407        // padded row whose targets are all NULL too:
408        self.deps.iter_mut().for_each(|item| {
409            item.nullable = true;
410            item.null_equality = NullEquality::NullEqualsNull;
411        });
412    }
413
414    /// This function ensures that functional dependencies involving uniquely
415    /// occurring determinant keys cover their entire table in terms of
416    /// dependent columns.
417    pub fn extend_target_indices(&mut self, n_out: usize) {
418        self.deps.iter_mut().for_each(
419            |FunctionalDependence {
420                 mode,
421                 target_indices,
422                 ..
423             }| {
424                // If unique, cover the whole table:
425                if *mode == Dependency::Single {
426                    *target_indices = (0..n_out).collect::<Vec<_>>();
427                }
428            },
429        )
430    }
431}
432
433impl Deref for FunctionalDependencies {
434    type Target = [FunctionalDependence];
435
436    fn deref(&self) -> &Self::Target {
437        self.deps.as_slice()
438    }
439}
440
441/// Calculates functional dependencies for aggregate output, when there is a GROUP BY expression.
442///
443/// `group_by_input_indices[i]` is the index of the input field that GROUP BY
444/// expression `i` passes through unchanged (a column reference), or `None` if
445/// the expression computes a new value. Only a column reference can carry an
446/// input dependency; a computed expression such as `CAST(pk AS INT)` cannot,
447/// even though its output name may equal the column's name.
448pub fn aggregate_functional_dependencies(
449    aggr_input_schema: &DFSchema,
450    group_by_input_indices: &[Option<usize>],
451    aggr_schema: &DFSchema,
452) -> FunctionalDependencies {
453    let mut aggregate_func_dependencies = vec![];
454    let aggr_fields = aggr_schema.fields();
455    // Association covers the whole table:
456    let target_indices = (0..aggr_schema.fields().len()).collect::<Vec<_>>();
457    // Get functional dependencies of the schema:
458    let func_dependencies = aggr_input_schema.functional_dependencies();
459    // The loop below only re-expresses input dependencies. Skip it when the
460    // input has none. The GROUP BY-key dependency below always runs.
461    if !func_dependencies.is_empty() {
462        // Compare the columns covered by every dependency, whatever its NULL
463        // semantics: leaving out the ones that do not hold across NULLs would
464        // hide GROUP BY expressions this determinant does not cover and
465        // upgrade its mode to `Single` wrongly.
466        let existing_target_indices = get_target_indices_from_dependencies(
467            func_dependencies.iter(),
468            group_by_input_indices,
469        );
470        for FunctionalDependence {
471            source_indices,
472            nullable,
473            null_equality,
474            mode,
475            ..
476        } in &func_dependencies.deps
477        {
478            // Indices into the GROUP BY list for this determinant:
479            let mut new_source_indices = vec![];
480            let mut new_source_input_indices = vec![];
481            for (idx, input_idx) in group_by_input_indices.iter().enumerate() {
482                // When one of the input determinant columns is a GROUP BY
483                // expression, add the index of the GROUP BY expression as a new
484                // determinant key:
485                if let Some(input_idx) = input_idx
486                    && source_indices.contains(input_idx)
487                    // A key column can be in the GROUP BY list more than one
488                    // time (`x, x AS k`). Count it one time.
489                    && !new_source_input_indices.contains(&Some(*input_idx))
490                {
491                    new_source_indices.push(idx);
492                    new_source_input_indices.push(Some(*input_idx));
493                }
494            }
495            let new_target_indices = get_target_indices_from_dependencies(
496                func_dependencies.iter(),
497                &new_source_input_indices,
498            );
499            let mode = if existing_target_indices == new_target_indices
500                && new_target_indices.is_some()
501            {
502                // If dependency covers all GROUP BY expressions, mode will be `Single`:
503                Dependency::Single
504            } else {
505                // Otherwise, existing mode is preserved:
506                *mode
507            };
508            // All of the composite indices occur in the GROUP BY expression:
509            if new_source_indices.len() == source_indices.len() {
510                // GROUP BY treats NULLs as equal: a determinant covering the
511                // complete grouping key gets at most one output row per NULL too.
512                let output_null_equality =
513                    if new_source_indices.len() == group_by_input_indices.len() {
514                        NullEquality::NullEqualsNull
515                    } else {
516                        *null_equality
517                    };
518                aggregate_func_dependencies.push(
519                    FunctionalDependence::new(
520                        new_source_indices,
521                        target_indices.clone(),
522                        *nullable,
523                    )
524                    .with_mode(mode)
525                    .with_null_equality(output_null_equality),
526                );
527            }
528        }
529    }
530
531    // When we have a GROUP BY key, we can guarantee uniqueness after
532    // aggregation:
533    if !group_by_input_indices.is_empty() {
534        let count = group_by_input_indices.len();
535        let source_indices = (0..count).collect::<Vec<_>>();
536        let nullable = source_indices
537            .iter()
538            .any(|idx| aggr_fields[*idx].is_nullable());
539        // If GROUP BY expressions do not already act as a determinant:
540        if !aggregate_func_dependencies.iter().any(|item| {
541            // If `item.source_indices` is a subset of GROUP BY expressions, we shouldn't add
542            // them since `item.source_indices` defines this relation already.
543
544            // The following simple comparison is working well because
545            // GROUP BY expressions come here as a prefix.
546            item.source_indices.iter().all(|idx| idx < &count)
547                // A dependency that is not valid across NULLs cannot replace
548                // the whole GROUP BY key dependency:
549                && item.is_valid_across_nulls(aggr_schema)
550        }) {
551            // Add a new functional dependency associated with the whole table:
552            // Use nullable property of the GROUP BY expression:
553            aggregate_func_dependencies.push(
554                FunctionalDependence::new(source_indices, target_indices, nullable)
555                    .with_mode(Dependency::Single)
556                    // Grouping collapses NULL keys into a single group:
557                    .with_null_equality(NullEquality::NullEqualsNull),
558            );
559        }
560    }
561    FunctionalDependencies::new(aggregate_func_dependencies)
562}
563
564/// Returns target indices, for the determinant keys that are inside
565/// group by expressions.
566///
567/// Only dependencies that hold when NULL determinant values are grouped
568/// together are considered (see
569/// [`FunctionalDependence::is_valid_across_nulls`]): a nullable `UNIQUE`
570/// column permits multiple NULL rows that may differ in the other columns,
571/// so it does not determine them across the single NULL group.
572///
573/// `group_by_input_indices` holds, for each GROUP BY expression, the index of
574/// the `schema` field it references, or `None` for a computed expression.
575pub fn get_target_functional_dependencies(
576    schema: &DFSchema,
577    group_by_input_indices: &[Option<usize>],
578) -> Option<Vec<usize>> {
579    let dependencies = schema.functional_dependencies();
580    if dependencies.is_empty() {
581        return None;
582    }
583    let dependencies = dependencies
584        .iter()
585        .filter(|dependency| dependency.is_valid_across_nulls(schema));
586    get_target_indices_from_dependencies(dependencies, group_by_input_indices)
587}
588
589fn get_target_indices_from_dependencies<'a>(
590    dependencies: impl IntoIterator<Item = &'a FunctionalDependence>,
591    group_by_input_indices: &[Option<usize>],
592) -> Option<Vec<usize>> {
593    let mut combined_target_indices = HashSet::new();
594    for dependency in dependencies {
595        // If the GROUP BY expression contains a determinant key, we can use
596        // the associated fields after aggregation even if they are not part
597        // of the GROUP BY expression.
598        if dependency
599            .source_indices
600            .iter()
601            .all(|source_idx| group_by_input_indices.contains(&Some(*source_idx)))
602        {
603            combined_target_indices.extend(dependency.target_indices.iter());
604        }
605    }
606    (!combined_target_indices.is_empty()).then_some({
607        let mut result = combined_target_indices.into_iter().collect::<Vec<_>>();
608        result.sort_unstable();
609        result
610    })
611}
612
613/// Returns indices for the minimal subset of GROUP BY expressions that are
614/// functionally equivalent to the original set of GROUP BY expressions.
615///
616/// `group_by_input_indices` holds, for each GROUP BY expression, the index of
617/// the `schema` field it references, or `None` for a computed expression. If
618/// any GROUP BY expression is computed, returns `None`.
619pub fn get_required_group_by_exprs_indices(
620    schema: &DFSchema,
621    group_by_input_indices: &[Option<usize>],
622) -> Option<Vec<usize>> {
623    let dependencies = schema.functional_dependencies();
624    let mut groupby_expr_indices = group_by_input_indices
625        .iter()
626        .copied()
627        .collect::<Option<Vec<_>>>()?;
628
629    groupby_expr_indices.sort_unstable();
630    for dependency in &dependencies.deps {
631        // If all source indices are among GROUP BY expression indices, we
632        // can remove target indices from GROUP BY expression indices and
633        // use source indices instead. The dependency must also hold across
634        // NULL keys, which GROUP BY collapses into a single group.
635        if dependency
636            .source_indices
637            .iter()
638            .all(|source_idx| groupby_expr_indices.contains(source_idx))
639            && dependency.is_valid_across_nulls(schema)
640        {
641            groupby_expr_indices =
642                set_difference(&groupby_expr_indices, &dependency.target_indices);
643            groupby_expr_indices =
644                merge_and_order_indices(groupby_expr_indices, &dependency.source_indices);
645        }
646    }
647    groupby_expr_indices
648        .iter()
649        .map(|idx| {
650            group_by_input_indices
651                .iter()
652                .position(|input_idx| *input_idx == Some(*idx))
653        })
654        .collect()
655}
656
657/// Returns indices for the minimal subset of ORDER BY expressions that are
658/// functionally equivalent to the original set of ORDER BY expressions.
659///
660/// `sort_input_indices` holds, for each ORDER BY expression, the index of the
661/// `schema` field it references, or `None` for a computed expression.
662pub fn get_required_sort_exprs_indices(
663    schema: &DFSchema,
664    sort_input_indices: &[Option<usize>],
665) -> Vec<usize> {
666    let dependencies = schema.functional_dependencies();
667
668    let mut known_field_indices = HashSet::with_capacity(sort_input_indices.len());
669    let mut required_sort_expr_indices = Vec::with_capacity(sort_input_indices.len());
670
671    for (sort_expr_idx, field_idx) in sort_input_indices.iter().enumerate() {
672        // If the sort expression doesn't reference a schema field (e.g. a
673        // computed expression), we can't reason about it via functional
674        // dependencies, so conservatively keep it.
675        let Some(field_idx) = *field_idx else {
676            required_sort_expr_indices.push(sort_expr_idx);
677            continue;
678        };
679
680        // A sort expression is removable if its value is functionally determined
681        // by fields that already appear earlier in the sort order (and the
682        // dependency remains valid across NULL rows).
683        let removable = dependencies.deps.iter().any(|dependency| {
684            dependency.target_indices.contains(&field_idx)
685                && dependency
686                    .source_indices
687                    .iter()
688                    .all(|source_idx| known_field_indices.contains(source_idx))
689                && dependency.is_valid_across_nulls(schema)
690        });
691
692        if removable {
693            continue;
694        }
695
696        known_field_indices.insert(field_idx);
697        required_sort_expr_indices.push(sort_expr_idx);
698    }
699
700    required_sort_expr_indices
701}
702
703/// Updates entries inside the `entries` vector with their corresponding
704/// indices inside the `proj_indices` vector.
705fn update_elements_with_matching_indices(
706    entries: &[usize],
707    proj_indices: &[usize],
708) -> Vec<usize> {
709    entries
710        .iter()
711        .filter_map(|val| proj_indices.iter().position(|proj_idx| proj_idx == val))
712        .collect()
713}
714
715/// Adds `offset` value to each entry inside `in_data`.
716fn add_offset_to_vec<T: Copy + std::ops::Add<Output = T>>(
717    in_data: &[T],
718    offset: T,
719) -> Vec<T> {
720    in_data.iter().map(|&item| item + offset).collect()
721}
722
723#[cfg(test)]
724mod tests {
725    use super::*;
726
727    #[test]
728    fn constraints_iter() {
729        let constraints = Constraints::new_unverified(vec![
730            Constraint::PrimaryKey(vec![10]),
731            Constraint::Unique(vec![20]),
732        ]);
733        let mut iter = constraints.iter();
734        assert_eq!(iter.next(), Some(&Constraint::PrimaryKey(vec![10])));
735        assert_eq!(iter.next(), Some(&Constraint::Unique(vec![20])));
736        assert_eq!(iter.next(), None);
737    }
738
739    #[test]
740    fn test_project_constraints() {
741        let constraints = Constraints::new_unverified(vec![
742            Constraint::PrimaryKey(vec![1, 2]),
743            Constraint::Unique(vec![0, 3]),
744        ]);
745
746        // Project keeping columns 1,2,3
747        let projected = constraints.project(&[1, 2, 3]).unwrap();
748        assert_eq!(
749            projected,
750            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0, 1])])
751        );
752
753        // Project keeping only column 0 - should return None as no constraints are preserved
754        assert!(constraints.project(&[0]).is_none());
755    }
756
757    #[test]
758    fn test_get_updated_id_keys() {
759        let fund_dependencies =
760            FunctionalDependencies::new(vec![FunctionalDependence::new(
761                vec![1],
762                vec![0, 1, 2],
763                true,
764            )]);
765        let res = fund_dependencies.project_functional_dependencies(&[1, 2], 2);
766        let expected = FunctionalDependencies::new(vec![FunctionalDependence::new(
767            vec![0],
768            vec![0, 1],
769            true,
770        )]);
771        assert_eq!(res, expected);
772    }
773}