Skip to main content

mz_expr/
relation.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10#![warn(missing_docs)]
11
12use std::cell::RefCell;
13use std::cmp::{Ordering, max};
14use std::collections::{BTreeMap, BTreeSet};
15use std::fmt;
16use std::fmt::{Display, Formatter};
17use std::hash::{DefaultHasher, Hash, Hasher};
18use std::num::NonZeroU64;
19use std::time::Instant;
20
21use bytesize::ByteSize;
22use columnation::{Columnation, CopyRegion};
23use itertools::Itertools;
24use mz_ore::cast::{CastFrom, CastInto};
25use mz_ore::collections::CollectionExt;
26use mz_ore::id_gen::IdGen;
27use mz_ore::metrics::Histogram;
28use mz_ore::num::NonNeg;
29use mz_ore::soft_assert_no_log;
30use mz_ore::stack::RecursionLimitError;
31use mz_ore::str::Indent;
32use mz_repr::adt::numeric::NumericMaxScale;
33use mz_repr::explain::text::text_string_at;
34use mz_repr::explain::{
35    DummyHumanizer, ExplainConfig, ExprHumanizer, IndexUsageType, PlanRenderingContext,
36};
37use mz_repr::{
38    ColumnName, Datum, DatumVec, Diff, GlobalId, IntoRowIterator, ReprColumnType, ReprRelationType,
39    ReprScalarType, Row, RowIterator, RowRef, SqlColumnType, SqlRelationType, SqlScalarType,
40};
41use serde::{Deserialize, Serialize};
42
43use crate::Id::Local;
44use crate::explain::{HumanizedExpr, HumanizerMode};
45use crate::relation::func::{AggregateFunc, LagLeadType, TableFunc};
46use crate::row::{RowCollection, RowCollectionIter};
47use crate::scalar::columns::Columns;
48use crate::scalar::func::variadic::{
49    JsonbBuildArray, JsonbBuildObject, ListCreate, ListIndex, MapBuild, RecordCreate,
50};
51use crate::visit::{Visit, VisitChildren};
52use crate::{
53    EvalError, FilterCharacteristics, Id, LocalId, MirScalarExpr, UnaryFunc, func as scalar_func,
54};
55
56pub mod canonicalize;
57pub mod func;
58pub mod join_input_mapper;
59
60/// A recursion limit to be used for stack-safe traversals of [`MirRelationExpr`] trees.
61///
62/// The recursion limit must be large enough to accommodate for the linear representation
63/// of some pathological but frequently occurring query fragments.
64///
65/// For example, in MIR we could have long chains of
66/// - (1) `Let` bindings,
67/// - (2) `CallBinary` calls with associative functions such as `+`
68///
69/// Until we fix those, we need to stick with the larger recursion limit.
70pub const RECURSION_LIMIT: usize = 2048;
71
72/// A trait for types that describe how to build a collection.
73pub trait CollectionPlan {
74    /// Collects the set of global identifiers from dataflows referenced in Get.
75    fn depends_on_into(&self, out: &mut BTreeSet<GlobalId>);
76
77    /// Returns the set of global identifiers from dataflows referenced in Get.
78    ///
79    /// See [`CollectionPlan::depends_on_into`] to reuse an existing `BTreeSet`.
80    fn depends_on(&self) -> BTreeSet<GlobalId> {
81        let mut out = BTreeSet::new();
82        self.depends_on_into(&mut out);
83        out
84    }
85}
86
87/// An abstract syntax tree which defines a collection.
88///
89/// The AST is meant to reflect the capabilities of the `differential_dataflow::Collection` type,
90/// written generically enough to avoid run-time compilation work.
91///
92/// `derived_hash_with_manual_eq` was complaining for the wrong reason: This lint exists because
93/// it's bad when `Eq` doesn't agree with `Hash`, which is often quite likely if one of them is
94/// implemented manually. However, our manual implementation of `Eq` _will_ agree with the derived
95/// one. This is because the reason for the manual implementation is not to change the semantics
96/// from the derived one, but to avoid stack overflows.
97#[allow(clippy::derived_hash_with_manual_eq)]
98#[derive(Clone, Debug, Ord, PartialOrd, Serialize, Deserialize, Hash)]
99pub enum MirRelationExpr {
100    /// A constant relation containing specified rows.
101    ///
102    /// The runtime memory footprint of this operator is zero.
103    ///
104    /// When you would like to pattern match on this, consider using `MirRelationExpr::as_const`
105    /// instead, which looks behind `ArrangeBy`s. You might want this matching behavior because
106    /// constant folding doesn't remove `ArrangeBy`s.
107    Constant {
108        /// Rows of the constant collection and their multiplicities.
109        rows: Result<Vec<(Row, Diff)>, EvalError>,
110        /// Schema of the collection.
111        typ: ReprRelationType,
112    },
113    /// Get an existing dataflow.
114    ///
115    /// The runtime memory footprint of this operator is zero.
116    Get {
117        /// The identifier for the collection to load.
118        id: Id,
119        /// Schema of the collection.
120        typ: ReprRelationType,
121        /// If this is a global Get, this will indicate whether we are going to read from Persist or
122        /// from an index, or from a different object in `objects_to_build`. If it's an index, then
123        /// how downstream dataflow operations will use this index is also recorded. This is filled
124        /// by `prune_and_annotate_dataflow_index_imports`. Note that this is not used by the
125        /// lowering to LIR, but is used only by EXPLAIN.
126        access_strategy: AccessStrategy,
127    },
128    /// Introduce a temporary dataflow.
129    ///
130    /// The runtime memory footprint of this operator is zero.
131    Let {
132        /// The identifier to be used in `Get` variants to retrieve `value`.
133        id: LocalId,
134        /// The collection to be bound to `id`.
135        value: Box<MirRelationExpr>,
136        /// The result of the `Let`, evaluated with `id` bound to `value`.
137        body: Box<MirRelationExpr>,
138    },
139    /// Introduce mutually recursive bindings.
140    ///
141    /// Each `LocalId` is immediately bound to an initially empty  collection
142    /// with the type of its corresponding `MirRelationExpr`. Repeatedly, each
143    /// binding is evaluated using the current contents of each other binding,
144    /// and is refreshed to contain the new evaluation. This process continues
145    /// through all bindings, and repeats as long as changes continue to occur.
146    ///
147    /// The resulting value of the expression is `body` evaluated once in the
148    /// context of the final iterates.
149    ///
150    /// A zero-binding instance can be replaced by `body`.
151    /// A single-binding instance is equivalent to `MirRelationExpr::Let`.
152    ///
153    /// The runtime memory footprint of this operator is zero.
154    LetRec {
155        /// The identifiers to be used in `Get` variants to retrieve each `value`.
156        ids: Vec<LocalId>,
157        /// The collections to be bound to each `id`.
158        values: Vec<MirRelationExpr>,
159        /// Maximum number of iterations, after which we should artificially force a fixpoint.
160        /// (Whether we error or just stop is configured by `LetRecLimit::return_at_limit`.)
161        /// The per-`LetRec` limit that the user specified is initially copied to each binding to
162        /// accommodate slicing and merging of `LetRec`s in MIR transforms (e.g., `NormalizeLets`).
163        limits: Vec<Option<LetRecLimit>>,
164        /// The result of the `Let`, evaluated with `id` bound to `value`.
165        body: Box<MirRelationExpr>,
166    },
167    /// Project out some columns from a dataflow
168    ///
169    /// The runtime memory footprint of this operator is zero.
170    Project {
171        /// The source collection.
172        input: Box<MirRelationExpr>,
173        /// Indices of columns to retain.
174        outputs: Vec<usize>,
175    },
176    /// Append new columns to a dataflow
177    ///
178    /// The runtime memory footprint of this operator is zero.
179    Map {
180        /// The source collection.
181        input: Box<MirRelationExpr>,
182        /// Expressions which determine values to append to each row.
183        /// An expression may refer to columns in `input` or
184        /// expressions defined earlier in the vector
185        scalars: Vec<MirScalarExpr>,
186    },
187    /// Like Map, but yields zero-or-more output rows per input row
188    ///
189    /// The runtime memory footprint of this operator is zero.
190    FlatMap {
191        /// The source collection
192        input: Box<MirRelationExpr>,
193        /// The table func to apply
194        func: TableFunc,
195        /// The argument to the table func
196        exprs: Vec<MirScalarExpr>,
197    },
198    /// Keep rows from a dataflow where all the predicates are true
199    ///
200    /// The runtime memory footprint of this operator is zero.
201    Filter {
202        /// The source collection.
203        input: Box<MirRelationExpr>,
204        /// Predicates, each of which must be true.
205        predicates: Vec<MirScalarExpr>,
206    },
207    /// Join several collections, where some columns must be equal.
208    ///
209    /// For further details consult the documentation for [`MirRelationExpr::join`].
210    ///
211    /// The runtime memory footprint of this operator can be proportional to
212    /// the sizes of all inputs and the size of all joins of prefixes.
213    /// This may be reduced due to arrangements available at rendering time.
214    Join {
215        /// A sequence of input relations.
216        inputs: Vec<MirRelationExpr>,
217        /// A sequence of equivalence classes of expressions on the cross product of inputs.
218        ///
219        /// Each equivalence class is a list of scalar expressions, where for each class the
220        /// intended interpretation is that all evaluated expressions should be equal.
221        ///
222        /// Each scalar expression is to be evaluated over the cross-product of all records
223        /// from all inputs. In many cases this may just be column selection from specific
224        /// inputs, but more general cases exist (e.g. complex functions of multiple columns
225        /// from multiple inputs, or just constant literals).
226        equivalences: Vec<Vec<MirScalarExpr>>,
227        /// Join implementation information.
228        #[serde(default)]
229        implementation: JoinImplementation,
230    },
231    /// Group a dataflow by some columns and aggregate over each group
232    ///
233    /// The runtime memory footprint of this operator is at most proportional to the
234    /// number of distinct records in the input and output. The actual requirements
235    /// can be less: the number of distinct inputs to each aggregate, summed across
236    /// each aggregate, plus the output size. For more details consult the code that
237    /// builds the associated dataflow.
238    Reduce {
239        /// The source collection.
240        input: Box<MirRelationExpr>,
241        /// Column indices used to form groups.
242        group_key: Vec<MirScalarExpr>,
243        /// Expressions which determine values to append to each row, after the group keys.
244        aggregates: Vec<AggregateExpr>,
245        /// True iff the input is known to monotonically increase (only addition of records).
246        #[serde(default)]
247        monotonic: bool,
248        /// User hint: expected number of values per group key. Used to optimize physical rendering.
249        #[serde(default)]
250        expected_group_size: Option<u64>,
251    },
252    /// Groups and orders within each group, limiting output.
253    ///
254    /// The runtime memory footprint of this operator is proportional to its input and output.
255    TopK {
256        /// The source collection.
257        input: Box<MirRelationExpr>,
258        /// Column indices used to form groups.
259        group_key: Vec<usize>,
260        /// Column indices used to order rows within groups.
261        order_key: Vec<ColumnOrder>,
262        /// Number of records to retain
263        #[serde(default)]
264        limit: Option<MirScalarExpr>,
265        /// Number of records to skip
266        #[serde(default)]
267        offset: usize,
268        /// True iff the input is known to monotonically increase (only addition of records).
269        #[serde(default)]
270        monotonic: bool,
271        /// User-supplied hint: how many rows will have the same group key.
272        #[serde(default)]
273        expected_group_size: Option<u64>,
274    },
275    /// Return a dataflow where the row counts are negated
276    ///
277    /// The runtime memory footprint of this operator is zero.
278    Negate {
279        /// The source collection.
280        input: Box<MirRelationExpr>,
281    },
282    /// Keep rows from a dataflow where the row counts are positive
283    ///
284    /// The runtime memory footprint of this operator is proportional to its input and output.
285    Threshold {
286        /// The source collection.
287        input: Box<MirRelationExpr>,
288    },
289    /// Adds the frequencies of elements in contained sets.
290    ///
291    /// The runtime memory footprint of this operator is zero.
292    Union {
293        /// A source collection.
294        base: Box<MirRelationExpr>,
295        /// Source collections to union.
296        inputs: Vec<MirRelationExpr>,
297    },
298    /// Technically a no-op. Used to render an index. Will be used to optimize queries
299    /// on finer grain. Each `keys` item represents a different index that should be
300    /// produced from the `keys`.
301    ///
302    /// The runtime memory footprint of this operator is proportional to its input.
303    ArrangeBy {
304        /// The source collection
305        input: Box<MirRelationExpr>,
306        /// Columns to arrange `input` by, in order of decreasing primacy
307        keys: Vec<Vec<MirScalarExpr>>,
308    },
309}
310
311impl PartialEq for MirRelationExpr {
312    fn eq(&self, other: &Self) -> bool {
313        // Capture the result and test it wrt `Ord` implementation in test environments.
314        let result = structured_diff::MreDiff::new(self, other).next().is_none();
315        mz_ore::soft_assert_eq_no_log!(result, self.cmp(other) == Ordering::Equal);
316        result
317    }
318}
319impl Eq for MirRelationExpr {}
320
321impl MirRelationExpr {
322    /// Reports the schema of the relation.
323    ///
324    /// This is the SQL-type parallel of [`Self::typ`]; it is merely
325    /// a wrapper around it, returning a [`SqlRelationType`] instead of
326    /// a [`ReprRelationType`].
327    pub fn sql_typ(&self) -> SqlRelationType {
328        let repr_typ = self.typ();
329        SqlRelationType::from_repr(&repr_typ)
330    }
331
332    /// Reports the repr schema of the relation.
333    ///
334    /// This method determines the type through recursive traversal of the
335    /// relation expression, drawing from the types of base collections.
336    /// As such, this is not an especially cheap method, and should be used
337    /// judiciously.
338    ///
339    /// The relation type is computed incrementally with a recursive post-order
340    /// traversal, that accumulates the input types for the relations yet to be
341    /// visited in `type_stack`.
342    pub fn typ(&self) -> ReprRelationType {
343        let mut type_stack = Vec::new();
344        self.visit_pre_post(
345            &mut |e: &MirRelationExpr| -> Option<Vec<&MirRelationExpr>> {
346                match &e {
347                    MirRelationExpr::Let { body, .. } => Some(vec![&*body]),
348                    MirRelationExpr::LetRec { body, .. } => Some(vec![&*body]),
349                    _ => None,
350                }
351            },
352            &mut |e: &MirRelationExpr| {
353                match e {
354                    MirRelationExpr::Let { .. } => {
355                        let body_typ = type_stack.pop().unwrap();
356                        // Insert a dummy relation type for the value, since `typ_with_input_types`
357                        // won't look at it, but expects the relation type of the body to be second.
358                        type_stack.push(ReprRelationType::empty());
359                        type_stack.push(body_typ);
360                    }
361                    MirRelationExpr::LetRec { values, .. } => {
362                        let body_typ = type_stack.pop().unwrap();
363                        type_stack.extend(
364                            std::iter::repeat(ReprRelationType::empty()).take(values.len()),
365                        );
366                        // Insert dummy relation types for the values, since `typ_with_input_types`
367                        // won't look at them, but expects the relation type of the body to be last.
368                        type_stack.push(body_typ);
369                    }
370                    _ => {}
371                }
372                let num_inputs = e.num_inputs();
373                let relation_type =
374                    e.typ_with_input_types(&type_stack[type_stack.len() - num_inputs..]);
375                type_stack.truncate(type_stack.len() - num_inputs);
376                type_stack.push(relation_type);
377            },
378        );
379        assert_eq!(type_stack.len(), 1);
380        type_stack.pop().unwrap()
381    }
382
383    /// Reports the repr schema of the relation given the repr schema of the input relations.
384    pub fn typ_with_input_types(&self, input_types: &[ReprRelationType]) -> ReprRelationType {
385        let column_types = self.col_with_input_cols(input_types.iter().map(|i| &i.column_types));
386        let unique_keys = self.keys_with_input_keys(
387            input_types.iter().map(|i| i.arity()),
388            input_types.iter().map(|i| &i.keys),
389        );
390        ReprRelationType::new(column_types).with_keys(unique_keys)
391    }
392
393    /// Reports the column types of the relation given the column types of the
394    /// input relations.
395    ///
396    /// This method delegates to `try_col_with_input_cols`, panicking if an `Err`
397    /// variant is returned.
398    pub fn col_with_input_cols<'a, I>(&self, input_types: I) -> Vec<ReprColumnType>
399    where
400        I: Iterator<Item = &'a Vec<ReprColumnType>>,
401    {
402        match self.try_col_with_input_cols(input_types) {
403            Ok(col_types) => col_types,
404            Err(err) => panic!("{err}"),
405        }
406    }
407
408    /// Reports the column types of the relation given the column types of the input relations.
409    ///
410    /// `input_types` is required to contain the column types for the input relations of
411    /// the current relation in the same order as they are visited by `try_visit_children`
412    /// method, even though not all may be used for computing the schema of the
413    /// current relation. For example, `Let` expects two input types, one for the
414    /// value relation and one for the body, in that order, but only the one for the
415    /// body is used to determine the type of the `Let` relation.
416    ///
417    /// It is meant to be used during post-order traversals to compute column types
418    /// incrementally.
419    pub fn try_col_with_input_cols<'a, I>(
420        &self,
421        mut input_types: I,
422    ) -> Result<Vec<ReprColumnType>, String>
423    where
424        I: Iterator<Item = &'a Vec<ReprColumnType>>,
425    {
426        use MirRelationExpr::*;
427
428        let col_types = match self {
429            Constant { rows, typ } => {
430                let mut col_types = typ.column_types.clone();
431                let mut seen_null = vec![false; typ.arity()];
432                if let Ok(rows) = rows {
433                    for (row, _diff) in rows {
434                        for (datum, i) in row.iter().zip_eq(0..typ.arity()) {
435                            if datum.is_null() {
436                                seen_null[i] = true;
437                            }
438                        }
439                    }
440                }
441                for (&seen_null, i) in seen_null.iter().zip_eq(0..typ.arity()) {
442                    if !seen_null {
443                        col_types[i].nullable = false;
444                    } else {
445                        assert!(col_types[i].nullable);
446                    }
447                }
448                col_types
449            }
450            Get { typ, .. } => typ.column_types.clone(),
451            Project { outputs, .. } => {
452                let input = input_types.next().unwrap();
453                outputs.iter().map(|&i| input[i].clone()).collect()
454            }
455            Map { scalars, .. } => {
456                let mut result = input_types.next().unwrap().clone();
457                for scalar in scalars.iter() {
458                    result.push(scalar.typ(&result))
459                }
460                result
461            }
462            FlatMap { func, .. } => {
463                let mut result = input_types.next().unwrap().clone();
464                result.extend(
465                    func.output_sql_type()
466                        .column_types
467                        .iter()
468                        .map(ReprColumnType::from),
469                );
470                result
471            }
472            Filter { predicates, .. } => {
473                let mut result = input_types.next().unwrap().clone();
474
475                // Set as nonnull any columns where null values would cause
476                // any predicate to evaluate to null.
477                for column in non_nullable_columns(predicates) {
478                    result[column].nullable = false;
479                }
480                result
481            }
482            Join { equivalences, .. } => {
483                // Concatenate input column types
484                let mut types = input_types.flat_map(|cols| cols.to_owned()).collect_vec();
485                // In an equivalence class, if any column is non-null, then make all non-null
486                for equivalence in equivalences {
487                    let col_inds = equivalence
488                        .iter()
489                        .filter_map(|expr| match expr {
490                            MirScalarExpr::Column(col, _name) => Some(*col),
491                            _ => None,
492                        })
493                        .collect_vec();
494                    if col_inds.iter().any(|i| !types.get(*i).unwrap().nullable) {
495                        for i in col_inds {
496                            types.get_mut(i).unwrap().nullable = false;
497                        }
498                    }
499                }
500                types
501            }
502            Reduce {
503                group_key,
504                aggregates,
505                ..
506            } => {
507                let input = input_types.next().unwrap();
508                group_key
509                    .iter()
510                    .map(|e| e.typ(input))
511                    .chain(aggregates.iter().map(|agg| agg.typ(input)))
512                    .collect()
513            }
514            TopK { .. } | Negate { .. } | Threshold { .. } | ArrangeBy { .. } => {
515                input_types.next().unwrap().clone()
516            }
517            Let { .. } => {
518                // skip over the input types for `value`.
519                input_types.nth(1).unwrap().clone()
520            }
521            LetRec { values, .. } => {
522                // skip over the input types for `values`.
523                input_types.nth(values.len()).unwrap().clone()
524            }
525            Union { .. } => {
526                let mut result = input_types.next().unwrap().clone();
527                for input_col_types in input_types {
528                    for (base_col, col) in result.iter_mut().zip_eq(input_col_types) {
529                        *base_col = base_col
530                            .union(col)
531                            .map_err(|e| format!("{}\nin plan:\n{}", e, self.pretty()))?;
532                    }
533                }
534                result
535            }
536        };
537
538        Ok(col_types)
539    }
540
541    /// Reports the unique keys of the relation given the arities and the unique
542    /// keys of the input relations.
543    ///
544    /// `input_arities` and `input_keys` are required to contain the
545    /// corresponding info for the input relations of
546    /// the current relation in the same order as they are visited by `try_visit_children`
547    /// method, even though not all may be used for computing the schema of the
548    /// current relation. For example, `Let` expects two input types, one for the
549    /// value relation and one for the body, in that order, but only the one for the
550    /// body is used to determine the type of the `Let` relation.
551    ///
552    /// It is meant to be used during post-order traversals to compute unique keys
553    /// incrementally.
554    pub fn keys_with_input_keys<'a, I, J>(
555        &self,
556        mut input_arities: I,
557        mut input_keys: J,
558    ) -> Vec<Vec<usize>>
559    where
560        I: Iterator<Item = usize>,
561        J: Iterator<Item = &'a Vec<Vec<usize>>>,
562    {
563        use MirRelationExpr::*;
564
565        let mut keys = match self {
566            Constant {
567                rows: Ok(rows),
568                typ,
569            } => {
570                let n_cols = typ.arity();
571                // If the `i`th entry is `Some`, then we have not yet observed non-uniqueness in the `i`th column.
572                let mut unique_values_per_col = vec![Some(BTreeSet::<Datum>::default()); n_cols];
573                for (row, diff) in rows {
574                    for (i, datum) in row.iter().enumerate() {
575                        if datum != Datum::Dummy {
576                            if let Some(unique_vals) = &mut unique_values_per_col[i] {
577                                let is_dupe = *diff != Diff::ONE || !unique_vals.insert(datum);
578                                if is_dupe {
579                                    unique_values_per_col[i] = None;
580                                }
581                            }
582                        }
583                    }
584                }
585                if rows.len() == 0 || (rows.len() == 1 && rows[0].1 == Diff::ONE) {
586                    vec![vec![]]
587                } else {
588                    // XXX - Multi-column keys are not detected.
589                    typ.keys
590                        .iter()
591                        .cloned()
592                        .chain(
593                            unique_values_per_col
594                                .into_iter()
595                                .enumerate()
596                                .filter(|(_idx, unique_vals)| unique_vals.is_some())
597                                .map(|(idx, _)| vec![idx]),
598                        )
599                        .collect()
600                }
601            }
602            Constant { rows: Err(_), typ } | Get { typ, .. } => typ.keys.clone(),
603            Threshold { .. } | ArrangeBy { .. } => input_keys.next().unwrap().clone(),
604            Let { .. } => {
605                // skip over the unique keys for value
606                input_keys.nth(1).unwrap().clone()
607            }
608            LetRec { values, .. } => {
609                // skip over the unique keys for value
610                input_keys.nth(values.len()).unwrap().clone()
611            }
612            Project { outputs, .. } => {
613                let input = input_keys.next().unwrap();
614                input
615                    .iter()
616                    .filter_map(|key_set| {
617                        if key_set.iter().all(|k| outputs.contains(k)) {
618                            Some(
619                                key_set
620                                    .iter()
621                                    .map(|c| outputs.iter().position(|o| o == c).unwrap())
622                                    .collect(),
623                            )
624                        } else {
625                            None
626                        }
627                    })
628                    .collect()
629            }
630            Map { scalars, .. } => {
631                let mut remappings = Vec::new();
632                let arity = input_arities.next().unwrap();
633                for (column, scalar) in scalars.iter().enumerate() {
634                    // assess whether the scalar preserves uniqueness,
635                    // and could participate in a key!
636
637                    fn uniqueness(expr: &MirScalarExpr) -> Option<usize> {
638                        match expr {
639                            MirScalarExpr::CallUnary { func, expr } => {
640                                if func.preserves_uniqueness() {
641                                    uniqueness(expr)
642                                } else {
643                                    None
644                                }
645                            }
646                            MirScalarExpr::Column(c, _name) => Some(*c),
647                            _ => None,
648                        }
649                    }
650
651                    if let Some(c) = uniqueness(scalar) {
652                        remappings.push((c, column + arity));
653                    }
654                }
655
656                let mut result = input_keys.next().unwrap().clone();
657                let mut new_keys = Vec::new();
658                // Any column in `remappings` could be replaced in a key
659                // by the corresponding c. This could lead to combinatorial
660                // explosion using our current representation, so we wont
661                // do that. Instead, we'll handle the case of one remapping.
662                if remappings.len() == 1 {
663                    let (old, new) = remappings.pop().unwrap();
664                    for key in &result {
665                        if key.contains(&old) {
666                            let mut new_key: Vec<usize> =
667                                key.iter().cloned().filter(|k| k != &old).collect();
668                            new_key.push(new);
669                            new_key.sort_unstable();
670                            new_keys.push(new_key);
671                        }
672                    }
673                    result.append(&mut new_keys);
674                }
675                result
676            }
677            FlatMap { .. } => {
678                // FlatMap can add duplicate rows, so input keys are no longer
679                // valid
680                vec![]
681            }
682            Negate { .. } => {
683                // Although negate may have distinct records for each key,
684                // the multiplicity is -1 rather than 1. This breaks many
685                // of the optimization uses of "keys".
686                vec![]
687            }
688            Filter { predicates, .. } => {
689                // A filter inherits the keys of its input unless the filters
690                // have reduced the input to a single row, in which case the
691                // keys of the input are `()`.
692                let mut input = input_keys.next().unwrap().clone();
693
694                if !input.is_empty() {
695                    // Track columns equated to literals, which we can prune.
696                    let mut cols_equal_to_literal = BTreeSet::new();
697
698                    // Perform union find on `col1 = col2` to establish
699                    // connected components of equated columns. Absent any
700                    // equalities, this will be `0 .. #c` (where #c is the
701                    // greatest column referenced by a predicate), but each
702                    // equality will orient the root of the greater to the root
703                    // of the lesser.
704                    let mut union_find = Vec::new();
705
706                    for expr in predicates.iter() {
707                        if let MirScalarExpr::CallBinary {
708                            func: crate::BinaryFunc::Eq(_),
709                            expr1,
710                            expr2,
711                        } = expr
712                        {
713                            if let MirScalarExpr::Column(c, _name) = &**expr1 {
714                                if expr2.is_literal_ok() {
715                                    cols_equal_to_literal.insert(c);
716                                }
717                            }
718                            if let MirScalarExpr::Column(c, _name) = &**expr2 {
719                                if expr1.is_literal_ok() {
720                                    cols_equal_to_literal.insert(c);
721                                }
722                            }
723                            // Perform union-find to equate columns.
724                            if let (Some(c1), Some(c2)) = (expr1.as_column(), expr2.as_column()) {
725                                if c1 != c2 {
726                                    // Ensure union_find has entries up to
727                                    // max(c1, c2) by filling up missing
728                                    // positions with identity mappings.
729                                    while union_find.len() <= std::cmp::max(c1, c2) {
730                                        union_find.push(union_find.len());
731                                    }
732                                    let mut r1 = c1; // Find the representative column of [c1].
733                                    while r1 != union_find[r1] {
734                                        assert!(union_find[r1] < r1);
735                                        r1 = union_find[r1];
736                                    }
737                                    let mut r2 = c2; // Find the representative column of [c2].
738                                    while r2 != union_find[r2] {
739                                        assert!(union_find[r2] < r2);
740                                        r2 = union_find[r2];
741                                    }
742                                    // Union [c1] and [c2] by pointing the
743                                    // larger to the smaller representative (we
744                                    // update the remaining equivalence class
745                                    // members only once after this for-loop).
746                                    union_find[std::cmp::max(r1, r2)] = std::cmp::min(r1, r2);
747                                }
748                            }
749                        }
750                    }
751
752                    // Complete union-find by pointing each element at its representative column.
753                    for i in 0..union_find.len() {
754                        // Iteration not required, as each prior already references the right column.
755                        union_find[i] = union_find[union_find[i]];
756                    }
757
758                    // Remove columns bound to literals, and remap columns equated to earlier columns.
759                    // We will re-expand remapped columns in a moment, but this avoids exponential work.
760                    for key_set in &mut input {
761                        key_set.retain(|k| !cols_equal_to_literal.contains(&k));
762                        for col in key_set.iter_mut() {
763                            if let Some(equiv) = union_find.get(*col) {
764                                *col = *equiv;
765                            }
766                        }
767                        key_set.sort();
768                        key_set.dedup();
769                    }
770                    input.sort();
771                    input.dedup();
772
773                    // Expand out each key to each of its equivalent forms.
774                    // Each instance of `col` can be replaced by any equivalent column.
775                    // This has the potential to result in exponentially sized number of unique keys,
776                    // and in the future we should probably maintain unique keys modulo equivalence.
777
778                    // First, compute an inverse map from each representative
779                    // column `sub` to all other equivalent columns `col`.
780                    let mut subs = Vec::new();
781                    for (col, sub) in union_find.iter().enumerate() {
782                        if *sub != col {
783                            assert!(*sub < col);
784                            while subs.len() <= *sub {
785                                subs.push(Vec::new());
786                            }
787                            subs[*sub].push(col);
788                        }
789                    }
790                    // For each column, substitute for it in each occurrence.
791                    let mut to_add = Vec::new();
792                    for (col, subs) in subs.iter().enumerate() {
793                        if !subs.is_empty() {
794                            for key_set in input.iter() {
795                                if key_set.contains(&col) {
796                                    let mut to_extend = key_set.clone();
797                                    to_extend.retain(|c| c != &col);
798                                    for sub in subs {
799                                        to_extend.push(*sub);
800                                        to_add.push(to_extend.clone());
801                                        to_extend.pop();
802                                    }
803                                }
804                            }
805                        }
806                        // No deduplication, as we cannot introduce duplicates.
807                        input.append(&mut to_add);
808                    }
809                    for key_set in input.iter_mut() {
810                        key_set.sort();
811                        key_set.dedup();
812                    }
813                }
814                input
815            }
816            Join { equivalences, .. } => {
817                // It is important the `new_from_input_arities` constructor is
818                // used. Otherwise, Materialize may potentially end up in an
819                // infinite loop.
820                let input_mapper = crate::JoinInputMapper::new_from_input_arities(input_arities);
821
822                input_mapper.global_keys(input_keys, equivalences)
823            }
824            Reduce { group_key, .. } => {
825                // The group key should form a key, but we might already have
826                // keys that are subsets of the group key, and should retain
827                // those instead, if so.
828                let mut result = Vec::new();
829                for key_set in input_keys.next().unwrap() {
830                    if key_set
831                        .iter()
832                        .all(|k| group_key.contains(&MirScalarExpr::column(*k)))
833                    {
834                        result.push(
835                            key_set
836                                .iter()
837                                .map(|i| {
838                                    group_key
839                                        .iter()
840                                        .position(|k| k == &MirScalarExpr::column(*i))
841                                        .unwrap()
842                                })
843                                .collect::<Vec<_>>(),
844                        );
845                    }
846                }
847                if result.is_empty() {
848                    result.push((0..group_key.len()).collect());
849                }
850                result
851            }
852            TopK {
853                group_key, limit, ..
854            } => {
855                // If `limit` is `Some(1)` then the group key will become
856                // a unique key, as there will be only one record with that key.
857                let mut result = input_keys.next().unwrap().clone();
858                if limit.as_ref().and_then(|x| x.as_literal_int64()) == Some(1) {
859                    result.push(group_key.clone())
860                }
861                result
862            }
863            Union { base, inputs } => {
864                // Generally, unions do not have any unique keys, because
865                // each input might duplicate some. However, there is at
866                // least one idiomatic structure that does preserve keys,
867                // which results from SQL aggregations that must populate
868                // absent records with default values. In that pattern,
869                // the union of one GET with its negation, which has first
870                // been subjected to a projection and map, we can remove
871                // their influence on the key structure.
872                //
873                // If there are A, B, each with a unique `key` such that
874                // we are looking at
875                //
876                //     A.proj(set_containing_key) + (B - A.proj(key)).map(stuff)
877                //
878                // Then we can report `key` as a unique key.
879                //
880                // TODO: make unique key structure an optimization analysis
881                // rather than part of the type information.
882                // TODO: perhaps ensure that (above) A.proj(key) is a
883                // subset of B, as otherwise there are negative records
884                // and who knows what is true (not expected, but again
885                // who knows what the query plan might look like).
886
887                let arity = input_arities.next().unwrap();
888                let (base_projection, base_with_project_stripped) =
889                    if let MirRelationExpr::Project { input, outputs } = &**base {
890                        (outputs.clone(), &**input)
891                    } else {
892                        // A input without a project is equivalent to an input
893                        // with the project being all columns in the input in order.
894                        ((0..arity).collect::<Vec<_>>(), &**base)
895                    };
896                let mut result = Vec::new();
897                if let MirRelationExpr::Get {
898                    id: first_id,
899                    typ: _,
900                    ..
901                } = base_with_project_stripped
902                {
903                    if inputs.len() == 1 {
904                        if let MirRelationExpr::Map { input, .. } = &inputs[0] {
905                            if let MirRelationExpr::Union { base, inputs } = &**input {
906                                if inputs.len() == 1 {
907                                    if let Some((input, outputs)) = base.is_negated_project() {
908                                        if let MirRelationExpr::Get {
909                                            id: second_id,
910                                            typ: _,
911                                            ..
912                                        } = input
913                                        {
914                                            if first_id == second_id {
915                                                result.extend(
916                                                    input_keys
917                                                        .next()
918                                                        .unwrap()
919                                                        .into_iter()
920                                                        .filter(|key| {
921                                                            key.iter().all(|c| {
922                                                                outputs.get(*c) == Some(c)
923                                                                    && base_projection.get(*c)
924                                                                        == Some(c)
925                                                            })
926                                                        })
927                                                        .cloned(),
928                                                );
929                                            }
930                                        }
931                                    }
932                                }
933                            }
934                        }
935                    }
936                }
937                // Important: do not inherit keys of either input, as not unique.
938                result
939            }
940        };
941        keys.sort();
942        keys.dedup();
943        keys
944    }
945
946    /// The number of columns in the relation.
947    ///
948    /// This number is determined from the type, which is determined recursively
949    /// at non-trivial cost.
950    ///
951    /// The arity is computed incrementally with a recursive post-order
952    /// traversal, that accumulates the arities for the relations yet to be
953    /// visited in `arity_stack`.
954    pub fn arity(&self) -> usize {
955        let mut arity_stack = Vec::new();
956        self.visit_pre_post(
957            &mut |e: &MirRelationExpr| -> Option<Vec<&MirRelationExpr>> {
958                match &e {
959                    MirRelationExpr::Let { body, .. } => {
960                        // Do not traverse the value sub-graph, since it's not relevant for
961                        // determining the arity of Let operators.
962                        Some(vec![&*body])
963                    }
964                    MirRelationExpr::LetRec { body, .. } => {
965                        // Do not traverse the value sub-graph, since it's not relevant for
966                        // determining the arity of Let operators.
967                        Some(vec![&*body])
968                    }
969                    MirRelationExpr::Project { .. } | MirRelationExpr::Reduce { .. } => {
970                        // No further traversal is required; these operators know their arity.
971                        Some(Vec::new())
972                    }
973                    _ => None,
974                }
975            },
976            &mut |e: &MirRelationExpr| {
977                match &e {
978                    MirRelationExpr::Let { .. } => {
979                        let body_arity = arity_stack.pop().unwrap();
980                        arity_stack.push(0);
981                        arity_stack.push(body_arity);
982                    }
983                    MirRelationExpr::LetRec { values, .. } => {
984                        let body_arity = arity_stack.pop().unwrap();
985                        arity_stack.extend(std::iter::repeat(0).take(values.len()));
986                        arity_stack.push(body_arity);
987                    }
988                    MirRelationExpr::Project { .. } | MirRelationExpr::Reduce { .. } => {
989                        arity_stack.push(0);
990                    }
991                    _ => {}
992                }
993                let num_inputs = e.num_inputs();
994                let input_arities = arity_stack.drain(arity_stack.len() - num_inputs..);
995                let arity = e.arity_with_input_arities(input_arities);
996                arity_stack.push(arity);
997            },
998        );
999        assert_eq!(arity_stack.len(), 1);
1000        arity_stack.pop().unwrap()
1001    }
1002
1003    /// Reports the arity of the relation given the schema of the input relations.
1004    ///
1005    /// `input_arities` is required to contain the arities for the input relations of
1006    /// the current relation in the same order as they are visited by `try_visit_children`
1007    /// method, even though not all may be used for computing the schema of the
1008    /// current relation. For example, `Let` expects two input types, one for the
1009    /// value relation and one for the body, in that order, but only the one for the
1010    /// body is used to determine the type of the `Let` relation.
1011    ///
1012    /// It is meant to be used during post-order traversals to compute arities
1013    /// incrementally.
1014    pub fn arity_with_input_arities<I>(&self, mut input_arities: I) -> usize
1015    where
1016        I: Iterator<Item = usize>,
1017    {
1018        use MirRelationExpr::*;
1019
1020        match self {
1021            Constant { rows: _, typ } => typ.arity(),
1022            Get { typ, .. } => typ.arity(),
1023            Let { .. } => {
1024                input_arities.next();
1025                input_arities.next().unwrap()
1026            }
1027            LetRec { values, .. } => {
1028                for _ in 0..values.len() {
1029                    input_arities.next();
1030                }
1031                input_arities.next().unwrap()
1032            }
1033            Project { outputs, .. } => outputs.len(),
1034            Map { scalars, .. } => input_arities.next().unwrap() + scalars.len(),
1035            FlatMap { func, .. } => input_arities.next().unwrap() + func.output_arity(),
1036            Join { .. } => input_arities.sum(),
1037            Reduce {
1038                input: _,
1039                group_key,
1040                aggregates,
1041                ..
1042            } => group_key.len() + aggregates.len(),
1043            Filter { .. }
1044            | TopK { .. }
1045            | Negate { .. }
1046            | Threshold { .. }
1047            | Union { .. }
1048            | ArrangeBy { .. } => input_arities.next().unwrap(),
1049        }
1050    }
1051
1052    /// The number of child relations this relation has.
1053    pub fn num_inputs(&self) -> usize {
1054        let mut count = 0;
1055
1056        self.visit_children(|_| count += 1);
1057
1058        count
1059    }
1060
1061    /// Constructs a constant collection from specific rows and schema, where
1062    /// each row will have a multiplicity of one.
1063    pub fn constant(rows: Vec<Vec<Datum>>, typ: ReprRelationType) -> Self {
1064        let rows = rows.into_iter().map(|row| (row, Diff::ONE)).collect();
1065        MirRelationExpr::constant_diff(rows, typ)
1066    }
1067
1068    /// Constructs a constant collection from specific rows and schema, where
1069    /// each row can have an arbitrary multiplicity.
1070    pub fn constant_diff(rows: Vec<(Vec<Datum>, Diff)>, typ: ReprRelationType) -> Self {
1071        for (row, _diff) in &rows {
1072            for (datum, column_typ) in row.iter().zip_eq(typ.column_types.iter()) {
1073                assert!(
1074                    datum.is_instance_of(column_typ),
1075                    "Expected datum of type {:?}, got value {:?}",
1076                    column_typ,
1077                    datum
1078                );
1079            }
1080        }
1081        let rows = Ok(rows
1082            .into_iter()
1083            .map(move |(row, diff)| (Row::pack_slice(&row), diff))
1084            .collect());
1085        MirRelationExpr::Constant { rows, typ }
1086    }
1087
1088    /// If self is a constant, return the value and the type, otherwise `None`.
1089    /// Looks behind `ArrangeBy`s.
1090    pub fn as_const(&self) -> Option<(&Result<Vec<(Row, Diff)>, EvalError>, &ReprRelationType)> {
1091        match self {
1092            MirRelationExpr::Constant { rows, typ } => Some((rows, typ)),
1093            MirRelationExpr::ArrangeBy { input, .. } => input.as_const(),
1094            _ => None,
1095        }
1096    }
1097
1098    /// If self is a constant, mutably return the value and the type, otherwise `None`.
1099    /// Looks behind `ArrangeBy`s.
1100    pub fn as_const_mut(
1101        &mut self,
1102    ) -> Option<(
1103        &mut Result<Vec<(Row, Diff)>, EvalError>,
1104        &mut ReprRelationType,
1105    )> {
1106        match self {
1107            MirRelationExpr::Constant { rows, typ } => Some((rows, typ)),
1108            MirRelationExpr::ArrangeBy { input, .. } => input.as_const_mut(),
1109            _ => None,
1110        }
1111    }
1112
1113    /// If self is a constant error, return the error, otherwise `None`.
1114    /// Looks behind `ArrangeBy`s.
1115    pub fn as_const_err(&self) -> Option<&EvalError> {
1116        match self {
1117            MirRelationExpr::Constant { rows: Err(e), .. } => Some(e),
1118            MirRelationExpr::ArrangeBy { input, .. } => input.as_const_err(),
1119            _ => None,
1120        }
1121    }
1122
1123    /// Checks if `self` is the single element collection with no columns.
1124    pub fn is_constant_singleton(&self) -> bool {
1125        if let Some((Ok(rows), typ)) = self.as_const() {
1126            rows.len() == 1 && typ.column_types.len() == 0 && rows[0].1 == Diff::ONE
1127        } else {
1128            false
1129        }
1130    }
1131
1132    /// Constructs the expression for getting a local collection.
1133    pub fn local_get(id: LocalId, typ: ReprRelationType) -> Self {
1134        MirRelationExpr::Get {
1135            id: Id::Local(id),
1136            typ,
1137            access_strategy: AccessStrategy::UnknownOrLocal,
1138        }
1139    }
1140
1141    /// Constructs the expression for getting a global collection
1142    pub fn global_get(id: GlobalId, typ: ReprRelationType) -> Self {
1143        MirRelationExpr::Get {
1144            id: Id::Global(id),
1145            typ,
1146            access_strategy: AccessStrategy::UnknownOrLocal,
1147        }
1148    }
1149
1150    /// Retains only the columns specified by `output`.
1151    pub fn project(mut self, mut outputs: Vec<usize>) -> Self {
1152        if let MirRelationExpr::Project {
1153            outputs: columns, ..
1154        } = &mut self
1155        {
1156            // Update `outputs` to reference base columns of `input`.
1157            for column in outputs.iter_mut() {
1158                *column = columns[*column];
1159            }
1160            *columns = outputs;
1161            self
1162        } else {
1163            MirRelationExpr::Project {
1164                input: Box::new(self),
1165                outputs,
1166            }
1167        }
1168    }
1169
1170    /// Append to each row the results of applying elements of `scalar`.
1171    pub fn map(mut self, scalars: Vec<MirScalarExpr>) -> Self {
1172        if let MirRelationExpr::Map { scalars: s, .. } = &mut self {
1173            s.extend(scalars);
1174            self
1175        } else if !scalars.is_empty() {
1176            MirRelationExpr::Map {
1177                input: Box::new(self),
1178                scalars,
1179            }
1180        } else {
1181            self
1182        }
1183    }
1184
1185    /// Append to each row a single `scalar`.
1186    pub fn map_one(self, scalar: MirScalarExpr) -> Self {
1187        self.map(vec![scalar])
1188    }
1189
1190    /// Like `map`, but yields zero-or-more output rows per input row
1191    pub fn flat_map(self, func: TableFunc, exprs: Vec<MirScalarExpr>) -> Self {
1192        MirRelationExpr::FlatMap {
1193            input: Box::new(self),
1194            func,
1195            exprs,
1196        }
1197    }
1198
1199    /// Retain only the rows satisfying each of several predicates.
1200    pub fn filter<I>(mut self, predicates: I) -> Self
1201    where
1202        I: IntoIterator<Item = MirScalarExpr>,
1203    {
1204        // Extract existing predicates
1205        let mut new_predicates = if let MirRelationExpr::Filter { input, predicates } = self {
1206            self = *input;
1207            predicates
1208        } else {
1209            Vec::new()
1210        };
1211        // Normalize collection of predicates.
1212        new_predicates.extend(predicates);
1213        new_predicates.retain(|p| !p.is_literal_true());
1214        new_predicates.sort();
1215        new_predicates.dedup();
1216        // Introduce a `Filter` only if we have predicates.
1217        if !new_predicates.is_empty() {
1218            self = MirRelationExpr::Filter {
1219                input: Box::new(self),
1220                predicates: new_predicates,
1221            };
1222        }
1223
1224        self
1225    }
1226
1227    /// Form the Cartesian outer-product of rows in both inputs.
1228    pub fn product(mut self, right: Self) -> Self {
1229        if right.is_constant_singleton() {
1230            self
1231        } else if self.is_constant_singleton() {
1232            right
1233        } else if let MirRelationExpr::Join { inputs, .. } = &mut self {
1234            inputs.push(right);
1235            self
1236        } else {
1237            MirRelationExpr::join(vec![self, right], vec![])
1238        }
1239    }
1240
1241    /// Performs a relational equijoin among the input collections.
1242    ///
1243    /// The sequence `inputs` each describe different input collections, and the sequence `variables` describes
1244    /// equality constraints that some of their columns must satisfy. Each element in `variable` describes a set
1245    /// of pairs  `(input_index, column_index)` where every value described by that set must be equal.
1246    ///
1247    /// For example, the pair `(input, column)` indexes into `inputs[input][column]`, extracting the `input`th
1248    /// input collection and for each row examining its `column`th column.
1249    ///
1250    /// # Example
1251    ///
1252    /// ```rust
1253    /// use mz_repr::{Datum, SqlColumnType, ReprRelationType, ReprScalarType};
1254    /// use mz_expr::MirRelationExpr;
1255    ///
1256    /// // A common schema for each input.
1257    /// let schema = ReprRelationType::new(vec![
1258    ///     ReprScalarType::Int32.nullable(false),
1259    ///     ReprScalarType::Int32.nullable(false),
1260    /// ]);
1261    ///
1262    /// // the specific data are not important here.
1263    /// let data = vec![Datum::Int32(0), Datum::Int32(1)];
1264    ///
1265    /// // Three collections that could have been different.
1266    /// let input0 = MirRelationExpr::constant(vec![data.clone()], schema.clone());
1267    /// let input1 = MirRelationExpr::constant(vec![data.clone()], schema.clone());
1268    /// let input2 = MirRelationExpr::constant(vec![data.clone()], schema.clone());
1269    ///
1270    /// // Join the three relations looking for triangles, like so.
1271    /// //
1272    /// //     Output(A,B,C) := Input0(A,B), Input1(B,C), Input2(A,C)
1273    /// let joined = MirRelationExpr::join(
1274    ///     vec![input0, input1, input2],
1275    ///     vec![
1276    ///         vec![(0,0), (2,0)], // fields A of inputs 0 and 2.
1277    ///         vec![(0,1), (1,0)], // fields B of inputs 0 and 1.
1278    ///         vec![(1,1), (2,1)], // fields C of inputs 1 and 2.
1279    ///     ],
1280    /// );
1281    ///
1282    /// // Technically the above produces `Output(A,B,B,C,A,C)` because the columns are concatenated.
1283    /// // A projection resolves this and produces the correct output.
1284    /// let result = joined.project(vec![0, 1, 3]);
1285    /// ```
1286    pub fn join(inputs: Vec<MirRelationExpr>, variables: Vec<Vec<(usize, usize)>>) -> Self {
1287        let input_mapper = join_input_mapper::JoinInputMapper::new(&inputs);
1288
1289        let equivalences = variables
1290            .into_iter()
1291            .map(|vs| {
1292                vs.into_iter()
1293                    .map(|(r, c)| input_mapper.map_expr_to_global(MirScalarExpr::column(c), r))
1294                    .collect::<Vec<_>>()
1295            })
1296            .collect::<Vec<_>>();
1297
1298        Self::join_scalars(inputs, equivalences)
1299    }
1300
1301    /// Constructs a join operator from inputs and required-equal scalar expressions.
1302    pub fn join_scalars(
1303        mut inputs: Vec<MirRelationExpr>,
1304        equivalences: Vec<Vec<MirScalarExpr>>,
1305    ) -> Self {
1306        // Remove all constant inputs that are the identity for join.
1307        // They neither introduce nor modify any column references.
1308        inputs.retain(|i| !i.is_constant_singleton());
1309        MirRelationExpr::Join {
1310            inputs,
1311            equivalences,
1312            implementation: JoinImplementation::Unimplemented,
1313        }
1314    }
1315
1316    /// Perform a key-wise reduction / aggregation.
1317    ///
1318    /// The `group_key` argument indicates columns in the input collection that should
1319    /// be grouped, and `aggregates` lists aggregation functions each of which produces
1320    /// one output column in addition to the keys.
1321    pub fn reduce(
1322        self,
1323        group_key: Vec<usize>,
1324        aggregates: Vec<AggregateExpr>,
1325        expected_group_size: Option<u64>,
1326    ) -> Self {
1327        MirRelationExpr::Reduce {
1328            input: Box::new(self),
1329            group_key: group_key.into_iter().map(MirScalarExpr::column).collect(),
1330            aggregates,
1331            monotonic: false,
1332            expected_group_size,
1333        }
1334    }
1335
1336    /// Perform a key-wise reduction order by and limit.
1337    ///
1338    /// The `group_key` argument indicates columns in the input collection that should
1339    /// be grouped, the `order_key` argument indicates columns that should be further
1340    /// used to order records within groups, and the `limit` argument constrains the
1341    /// total number of records that should be produced in each group.
1342    pub fn top_k(
1343        self,
1344        group_key: Vec<usize>,
1345        order_key: Vec<ColumnOrder>,
1346        limit: Option<MirScalarExpr>,
1347        offset: usize,
1348        expected_group_size: Option<u64>,
1349    ) -> Self {
1350        MirRelationExpr::TopK {
1351            input: Box::new(self),
1352            group_key,
1353            order_key,
1354            limit,
1355            offset,
1356            expected_group_size,
1357            monotonic: false,
1358        }
1359    }
1360
1361    /// Negates the occurrences of each row.
1362    pub fn negate(self) -> Self {
1363        if let MirRelationExpr::Negate { input } = self {
1364            *input
1365        } else {
1366            MirRelationExpr::Negate {
1367                input: Box::new(self),
1368            }
1369        }
1370    }
1371
1372    /// Removes all but the first occurrence of each row.
1373    pub fn distinct(self) -> Self {
1374        let arity = self.arity();
1375        self.distinct_by((0..arity).collect())
1376    }
1377
1378    /// Removes all but the first occurrence of each key. Columns not included
1379    /// in the `group_key` are discarded.
1380    pub fn distinct_by(self, group_key: Vec<usize>) -> Self {
1381        self.reduce(group_key, vec![], None)
1382    }
1383
1384    /// Discards rows with a negative frequency.
1385    pub fn threshold(self) -> Self {
1386        if let MirRelationExpr::Threshold { .. } = &self {
1387            self
1388        } else {
1389            MirRelationExpr::Threshold {
1390                input: Box::new(self),
1391            }
1392        }
1393    }
1394
1395    /// Unions together any number inputs.
1396    ///
1397    /// If `inputs` is empty, then an empty relation of type `typ` is
1398    /// constructed.
1399    pub fn union_many(mut inputs: Vec<Self>, typ: ReprRelationType) -> Self {
1400        // Deconstruct `inputs` as `Union`s and reconstitute.
1401        let mut flat_inputs = Vec::with_capacity(inputs.len());
1402        for input in inputs {
1403            if let MirRelationExpr::Union { base, inputs } = input {
1404                flat_inputs.push(*base);
1405                flat_inputs.extend(inputs);
1406            } else {
1407                flat_inputs.push(input);
1408            }
1409        }
1410        inputs = flat_inputs;
1411        if inputs.len() == 0 {
1412            MirRelationExpr::Constant {
1413                rows: Ok(vec![]),
1414                typ,
1415            }
1416        } else if inputs.len() == 1 {
1417            inputs.into_element()
1418        } else {
1419            MirRelationExpr::Union {
1420                base: Box::new(inputs.remove(0)),
1421                inputs,
1422            }
1423        }
1424    }
1425
1426    /// Produces one collection where each row is present with the sum of its frequencies in each input.
1427    pub fn union(self, other: Self) -> Self {
1428        // Deconstruct `self` and `other` as `Union`s and reconstitute.
1429        let mut flat_inputs = Vec::with_capacity(2);
1430        if let MirRelationExpr::Union { base, inputs } = self {
1431            flat_inputs.push(*base);
1432            flat_inputs.extend(inputs);
1433        } else {
1434            flat_inputs.push(self);
1435        }
1436        if let MirRelationExpr::Union { base, inputs } = other {
1437            flat_inputs.push(*base);
1438            flat_inputs.extend(inputs);
1439        } else {
1440            flat_inputs.push(other);
1441        }
1442
1443        MirRelationExpr::Union {
1444            base: Box::new(flat_inputs.remove(0)),
1445            inputs: flat_inputs,
1446        }
1447    }
1448
1449    /// Arranges the collection by the specified columns
1450    pub fn arrange_by(self, keys: &[Vec<MirScalarExpr>]) -> Self {
1451        MirRelationExpr::ArrangeBy {
1452            input: Box::new(self),
1453            keys: keys.to_owned(),
1454        }
1455    }
1456
1457    /// Indicates if this is a constant empty collection.
1458    ///
1459    /// A false value does not mean the collection is known to be non-empty,
1460    /// only that we cannot currently determine that it is statically empty.
1461    pub fn is_empty(&self) -> bool {
1462        if let Some((Ok(rows), ..)) = self.as_const() {
1463            rows.is_empty()
1464        } else {
1465            false
1466        }
1467    }
1468
1469    /// If the expression is a negated project, return the input and the projection.
1470    pub fn is_negated_project(&self) -> Option<(&MirRelationExpr, &[usize])> {
1471        if let MirRelationExpr::Negate { input } = self {
1472            if let MirRelationExpr::Project { input, outputs } = &**input {
1473                return Some((&**input, outputs));
1474            }
1475        }
1476        if let MirRelationExpr::Project { input, outputs } = self {
1477            if let MirRelationExpr::Negate { input } = &**input {
1478                return Some((&**input, outputs));
1479            }
1480        }
1481        None
1482    }
1483
1484    /// Pretty-print this [MirRelationExpr] to a string.
1485    pub fn pretty(&self) -> String {
1486        let config = ExplainConfig::default();
1487        self.debug_explain(&config, None)
1488    }
1489
1490    /// Pretty-print this [MirRelationExpr] to a string using a custom
1491    /// [ExplainConfig] and an optionally provided [ExprHumanizer].
1492    /// This is intended for debugging and tests, not users.
1493    pub fn debug_explain(
1494        &self,
1495        config: &ExplainConfig,
1496        humanizer: Option<&dyn ExprHumanizer>,
1497    ) -> String {
1498        text_string_at(self, || PlanRenderingContext {
1499            indent: Indent::default(),
1500            humanizer: humanizer.unwrap_or(&DummyHumanizer),
1501            annotations: BTreeMap::default(),
1502            config,
1503            ambiguous_ids: BTreeSet::default(),
1504        })
1505    }
1506
1507    /// Take ownership of `self`, leaving an empty `MirRelationExpr::Constant` with the optionally
1508    /// given scalar types. The given scalar types should be `base_eq` with the types that `typ()`
1509    /// would find. Keys and nullability are ignored in the given `SqlRelationType`, and instead we set
1510    /// the best possible key and nullability, since we are making an empty collection.
1511    ///
1512    /// If `typ` is not given, then this calls `.typ()` (which is possibly expensive) to determine
1513    /// the correct type.
1514    pub fn take_safely(&mut self, typ: Option<ReprRelationType>) -> MirRelationExpr {
1515        if let Some(typ) = &typ {
1516            let self_typ = self.typ();
1517            soft_assert_no_log!(
1518                self_typ
1519                    .column_types
1520                    .iter()
1521                    .zip_eq(typ.column_types.iter())
1522                    .all(|(t1, t2)| t1.scalar_type == t2.scalar_type)
1523            );
1524        }
1525        let mut typ = typ.unwrap_or_else(|| self.typ());
1526        typ.keys = vec![vec![]];
1527        for ct in typ.column_types.iter_mut() {
1528            ct.nullable = false;
1529        }
1530        std::mem::replace(
1531            self,
1532            MirRelationExpr::Constant {
1533                rows: Ok(vec![]),
1534                typ,
1535            },
1536        )
1537    }
1538
1539    /// Take ownership of `self`, leaving an empty `MirRelationExpr::Constant` with the given scalar
1540    /// types. Nullability is ignored in the given `SqlColumnType`s, and instead we set the best
1541    /// possible nullability, since we are making an empty collection.
1542    pub fn take_safely_with_sql_col_types(&mut self, typ: Vec<SqlColumnType>) -> MirRelationExpr {
1543        self.take_safely(Some(ReprRelationType::from(&SqlRelationType::new(typ))))
1544    }
1545
1546    /// Like [`Self::take_safely_with_col_types`], but accepts `Vec<ReprColumnType>`.
1547    ///
1548    /// This is the preferred entry point for optimizer transforms, where repr
1549    /// types are the native currency. Internally converts to [`SqlColumnType`]
1550    /// and delegates to [`Self::take_safely_with_col_types`].
1551    pub fn take_safely_with_col_types(&mut self, typ: Vec<ReprColumnType>) -> MirRelationExpr {
1552        self.take_safely(Some(ReprRelationType::new(typ)))
1553    }
1554
1555    /// Take ownership of `self`, leaving an empty `MirRelationExpr::Constant` with an **incorrect** type.
1556    ///
1557    /// This should only be used if `self` is about to be dropped or otherwise overwritten.
1558    pub fn take_dangerous(&mut self) -> MirRelationExpr {
1559        let empty = MirRelationExpr::Constant {
1560            rows: Ok(vec![]),
1561            typ: ReprRelationType::new(Vec::new()),
1562        };
1563        std::mem::replace(self, empty)
1564    }
1565
1566    /// Replaces `self` with some logic applied to `self`.
1567    pub fn replace_using<F>(&mut self, logic: F)
1568    where
1569        F: FnOnce(MirRelationExpr) -> MirRelationExpr,
1570    {
1571        let empty = MirRelationExpr::Constant {
1572            rows: Ok(vec![]),
1573            typ: ReprRelationType::new(Vec::new()),
1574        };
1575        let expr = std::mem::replace(self, empty);
1576        *self = logic(expr);
1577    }
1578
1579    /// Store `self` in a `Let` and pass the corresponding `Get` to `body`.
1580    pub fn let_in<Body, E>(self, id_gen: &mut IdGen, body: Body) -> Result<MirRelationExpr, E>
1581    where
1582        Body: FnOnce(&mut IdGen, MirRelationExpr) -> Result<MirRelationExpr, E>,
1583    {
1584        if let MirRelationExpr::Get { .. } = self {
1585            // already done
1586            body(id_gen, self)
1587        } else {
1588            let id = LocalId::new(id_gen.allocate_id());
1589            let get = MirRelationExpr::Get {
1590                id: Id::Local(id),
1591                typ: self.typ(),
1592                access_strategy: AccessStrategy::UnknownOrLocal,
1593            };
1594            let body = (body)(id_gen, get)?;
1595            Ok(MirRelationExpr::Let {
1596                id,
1597                value: Box::new(self),
1598                body: Box::new(body),
1599            })
1600        }
1601    }
1602
1603    /// Return every row in `self` that does not have a matching row in the first columns of `keys_and_values`, using `default` to fill in the remaining columns
1604    /// (If `default` is a row of nulls, this is the 'outer' part of LEFT OUTER JOIN)
1605    pub fn anti_lookup<E>(
1606        self,
1607        id_gen: &mut IdGen,
1608        keys_and_values: MirRelationExpr,
1609        default: Vec<(Datum, ReprScalarType)>,
1610    ) -> Result<MirRelationExpr, E> {
1611        let (data, column_types): (Vec<_>, Vec<_>) = default
1612            .into_iter()
1613            .map(|(datum, scalar_type)| {
1614                (
1615                    datum,
1616                    ReprColumnType {
1617                        scalar_type,
1618                        nullable: datum.is_null(),
1619                    },
1620                )
1621            })
1622            .unzip();
1623        assert_eq!(keys_and_values.arity() - self.arity(), data.len());
1624        self.let_in(id_gen, |_id_gen, get_keys| {
1625            let get_keys_arity = get_keys.arity();
1626            Ok(MirRelationExpr::join(
1627                vec![
1628                    // all the missing keys (with count 1)
1629                    keys_and_values
1630                        .distinct_by((0..get_keys_arity).collect())
1631                        .negate()
1632                        .union(get_keys.clone().distinct()),
1633                    // join with keys to get the correct counts
1634                    get_keys.clone(),
1635                ],
1636                (0..get_keys_arity).map(|i| vec![(0, i), (1, i)]).collect(),
1637            )
1638            // get rid of the extra copies of columns from keys
1639            .project((0..get_keys_arity).collect())
1640            // This join is logically equivalent to
1641            // `.map(<default_expr>)`, but using a join allows for
1642            // potential predicate pushdown and elision in the
1643            // optimizer.
1644            .product(MirRelationExpr::constant(
1645                vec![data],
1646                ReprRelationType::new(column_types),
1647            )))
1648        })
1649    }
1650
1651    /// Return:
1652    /// * every row in keys_and_values
1653    /// * every row in `self` that does not have a matching row in the first columns of
1654    ///   `keys_and_values`, using `default` to fill in the remaining columns
1655    /// (This is LEFT OUTER JOIN if:
1656    /// 1) `default` is a row of null
1657    /// 2) matching rows in `keys_and_values` and `self` have the same multiplicity.)
1658    pub fn lookup<E>(
1659        self,
1660        id_gen: &mut IdGen,
1661        keys_and_values: MirRelationExpr,
1662        default: Vec<(Datum<'static>, ReprScalarType)>,
1663    ) -> Result<MirRelationExpr, E> {
1664        keys_and_values.let_in(id_gen, |id_gen, get_keys_and_values| {
1665            Ok(get_keys_and_values.clone().union(self.anti_lookup(
1666                id_gen,
1667                get_keys_and_values,
1668                default,
1669            )?))
1670        })
1671    }
1672
1673    /// True iff the expression contains a `NullaryFunc::MzLogicalTimestamp`.
1674    pub fn contains_temporal(&self) -> bool {
1675        let mut contains = false;
1676        self.visit_scalars(&mut |e| contains = contains || e.contains_temporal());
1677        contains
1678    }
1679
1680    /// Fallible visitor for the [`MirScalarExpr`]s directly owned by this relation expression.
1681    ///
1682    /// The `f` visitor should not recursively descend into owned [`MirRelationExpr`]s.
1683    pub fn try_visit_scalars_mut1<F, E>(&mut self, f: &mut F) -> Result<(), E>
1684    where
1685        F: FnMut(&mut MirScalarExpr) -> Result<(), E>,
1686    {
1687        use MirRelationExpr::*;
1688        match self {
1689            Map { scalars, .. } => {
1690                for s in scalars {
1691                    f(s)?;
1692                }
1693            }
1694            Filter { predicates, .. } => {
1695                for p in predicates {
1696                    f(p)?;
1697                }
1698            }
1699            FlatMap { exprs, .. } => {
1700                for expr in exprs {
1701                    f(expr)?;
1702                }
1703            }
1704            Join {
1705                inputs: _,
1706                equivalences,
1707                implementation,
1708            } => {
1709                for equivalence in equivalences {
1710                    for expr in equivalence {
1711                        f(expr)?;
1712                    }
1713                }
1714                match implementation {
1715                    JoinImplementation::Differential((_, start_key, _), order) => {
1716                        if let Some(start_key) = start_key {
1717                            for k in start_key {
1718                                f(k)?;
1719                            }
1720                        }
1721                        for (_, lookup_key, _) in order {
1722                            for k in lookup_key {
1723                                f(k)?;
1724                            }
1725                        }
1726                    }
1727                    JoinImplementation::DeltaQuery(paths) => {
1728                        for path in paths {
1729                            for (_, lookup_key, _) in path {
1730                                for k in lookup_key {
1731                                    f(k)?;
1732                                }
1733                            }
1734                        }
1735                    }
1736                    JoinImplementation::IndexedFilter(_coll_id, _idx_id, index_key, _) => {
1737                        for k in index_key {
1738                            f(k)?;
1739                        }
1740                    }
1741                    JoinImplementation::Unimplemented => {} // No scalar exprs
1742                }
1743            }
1744            ArrangeBy { keys, .. } => {
1745                for key in keys {
1746                    for s in key {
1747                        f(s)?;
1748                    }
1749                }
1750            }
1751            Reduce {
1752                group_key,
1753                aggregates,
1754                ..
1755            } => {
1756                for s in group_key {
1757                    f(s)?;
1758                }
1759                for agg in aggregates {
1760                    f(&mut agg.expr)?;
1761                }
1762            }
1763            TopK { limit, .. } => {
1764                if let Some(s) = limit {
1765                    f(s)?;
1766                }
1767            }
1768            Constant { .. }
1769            | Get { .. }
1770            | Let { .. }
1771            | LetRec { .. }
1772            | Project { .. }
1773            | Negate { .. }
1774            | Threshold { .. }
1775            | Union { .. } => (),
1776        }
1777        Ok(())
1778    }
1779
1780    /// Fallible mutable visitor for the [`MirScalarExpr`]s in the [`MirRelationExpr`] subtree
1781    /// rooted at `self`.
1782    ///
1783    /// Note that this does not recurse into [`MirRelationExpr`] subtrees within [`MirScalarExpr`]
1784    /// nodes.
1785    pub fn try_visit_scalars_mut<F, E>(&mut self, f: &mut F) -> Result<(), E>
1786    where
1787        F: FnMut(&mut MirScalarExpr) -> Result<(), E>,
1788    {
1789        self.try_visit_mut_post(&mut |expr| expr.try_visit_scalars_mut1(f))
1790    }
1791
1792    /// Infallible mutable visitor for the [`MirScalarExpr`]s in the [`MirRelationExpr`] subtree
1793    /// rooted at `self`.
1794    ///
1795    /// Note that this does not recurse into [`MirRelationExpr`] subtrees within [`MirScalarExpr`]
1796    /// nodes.
1797    pub fn visit_scalars_mut<F>(&mut self, f: &mut F)
1798    where
1799        F: FnMut(&mut MirScalarExpr),
1800    {
1801        self.try_visit_scalars_mut(&mut |s| {
1802            f(s);
1803            Ok::<_, RecursionLimitError>(())
1804        })
1805        .expect("Unexpected error in `visit_scalars_mut` call");
1806    }
1807
1808    /// Fallible visitor for the [`MirScalarExpr`]s directly owned by this relation expression.
1809    ///
1810    /// The `f` visitor should not recursively descend into owned [`MirRelationExpr`]s.
1811    pub fn try_visit_scalars_1<F, E>(&self, f: &mut F) -> Result<(), E>
1812    where
1813        F: FnMut(&MirScalarExpr) -> Result<(), E>,
1814    {
1815        use MirRelationExpr::*;
1816        match self {
1817            Map { scalars, .. } => {
1818                for s in scalars {
1819                    f(s)?;
1820                }
1821            }
1822            Filter { predicates, .. } => {
1823                for p in predicates {
1824                    f(p)?;
1825                }
1826            }
1827            FlatMap { exprs, .. } => {
1828                for expr in exprs {
1829                    f(expr)?;
1830                }
1831            }
1832            Join {
1833                inputs: _,
1834                equivalences,
1835                implementation,
1836            } => {
1837                for equivalence in equivalences {
1838                    for expr in equivalence {
1839                        f(expr)?;
1840                    }
1841                }
1842                match implementation {
1843                    JoinImplementation::Differential((_, start_key, _), order) => {
1844                        if let Some(start_key) = start_key {
1845                            for k in start_key {
1846                                f(k)?;
1847                            }
1848                        }
1849                        for (_, lookup_key, _) in order {
1850                            for k in lookup_key {
1851                                f(k)?;
1852                            }
1853                        }
1854                    }
1855                    JoinImplementation::DeltaQuery(paths) => {
1856                        for path in paths {
1857                            for (_, lookup_key, _) in path {
1858                                for k in lookup_key {
1859                                    f(k)?;
1860                                }
1861                            }
1862                        }
1863                    }
1864                    JoinImplementation::IndexedFilter(_coll_id, _idx_id, index_key, _) => {
1865                        for k in index_key {
1866                            f(k)?;
1867                        }
1868                    }
1869                    JoinImplementation::Unimplemented => {} // No scalar exprs
1870                }
1871            }
1872            ArrangeBy { keys, .. } => {
1873                for key in keys {
1874                    for s in key {
1875                        f(s)?;
1876                    }
1877                }
1878            }
1879            Reduce {
1880                group_key,
1881                aggregates,
1882                ..
1883            } => {
1884                for s in group_key {
1885                    f(s)?;
1886                }
1887                for agg in aggregates {
1888                    f(&agg.expr)?;
1889                }
1890            }
1891            TopK { limit, .. } => {
1892                if let Some(s) = limit {
1893                    f(s)?;
1894                }
1895            }
1896            Constant { .. }
1897            | Get { .. }
1898            | Let { .. }
1899            | LetRec { .. }
1900            | Project { .. }
1901            | Negate { .. }
1902            | Threshold { .. }
1903            | Union { .. } => (),
1904        }
1905        Ok(())
1906    }
1907
1908    /// Fallible immutable visitor for the [`MirScalarExpr`]s in the [`MirRelationExpr`] subtree
1909    /// rooted at `self`.
1910    ///
1911    /// Note that this does not recurse into [`MirRelationExpr`] subtrees within [`MirScalarExpr`]
1912    /// nodes.
1913    pub fn try_visit_scalars<F, E>(&self, f: &mut F) -> Result<(), E>
1914    where
1915        F: FnMut(&MirScalarExpr) -> Result<(), E>,
1916    {
1917        self.try_visit_post(&mut |expr| expr.try_visit_scalars_1(f))
1918    }
1919
1920    /// Infallible immutable visitor for the [`MirScalarExpr`]s in the [`MirRelationExpr`] subtree
1921    /// rooted at `self`.
1922    ///
1923    /// Note that this does not recurse into [`MirRelationExpr`] subtrees within [`MirScalarExpr`]
1924    /// nodes.
1925    pub fn visit_scalars<F>(&self, f: &mut F)
1926    where
1927        F: FnMut(&MirScalarExpr),
1928    {
1929        self.try_visit_scalars(&mut |s| {
1930            f(s);
1931            Ok::<_, RecursionLimitError>(())
1932        })
1933        .expect("Unexpected error in `visit_scalars` call");
1934    }
1935
1936    /// Clears the contents of `self` even if it's so deep that simply dropping it would cause a
1937    /// stack overflow in `drop_in_place`.
1938    ///
1939    /// Leaves `self` in an unusable state, so this should only be used if `self` is about to be
1940    /// dropped or otherwise overwritten.
1941    pub fn destroy_carefully(&mut self) {
1942        let mut todo = vec![self.take_dangerous()];
1943        while let Some(mut expr) = todo.pop() {
1944            for child in expr.children_mut() {
1945                todo.push(child.take_dangerous());
1946            }
1947        }
1948    }
1949
1950    /// Computes the size (total number of nodes) and maximum depth of a MirRelationExpr for
1951    /// debug printing purposes.
1952    pub fn debug_size_and_depth(&self) -> (usize, usize) {
1953        let mut size = 0;
1954        let mut max_depth = 0;
1955        let mut todo = vec![(self, 1)];
1956        while let Some((expr, depth)) = todo.pop() {
1957            size += 1;
1958            max_depth = max(max_depth, depth);
1959            todo.extend(expr.children().map(|c| (c, depth + 1)));
1960        }
1961        (size, max_depth)
1962    }
1963
1964    /// The MirRelationExpr is considered potentially expensive if and only if
1965    /// at least one of the following conditions is true:
1966    ///
1967    ///  - It contains at least one MirScalarExpr with a function call.
1968    ///  - It contains at least one FlatMap or a Reduce operator.
1969    ///  - We run into a RecursionLimitError while analyzing the expression.
1970    ///
1971    /// !!!WARNING!!!: this method has an HirRelationExpr counterpart. The two
1972    /// should be kept in sync w.r.t. HIR ⇒ MIR lowering!
1973    pub fn could_run_expensive_function(&self) -> bool {
1974        let mut result = false;
1975        use MirRelationExpr::*;
1976        use MirScalarExpr::*;
1977        if let Err(_) = self.try_visit_scalars::<_, RecursionLimitError>(&mut |scalar| {
1978            result |= match scalar {
1979                Column(_, _) | Literal(_, _) | CallUnmaterializable(_) | If { .. } => false,
1980                // Function calls are considered expensive
1981                CallUnary { .. } | CallBinary { .. } | CallVariadic { .. } => true,
1982            };
1983            Ok(())
1984        }) {
1985            // Conservatively set `true` if on RecursionLimitError.
1986            result = true;
1987        }
1988        self.visit_pre(|e: &MirRelationExpr| {
1989            // FlatMap has a table function; Reduce has an aggregate function.
1990            // Other constructs use MirScalarExpr to run a function
1991            result |= matches!(e, FlatMap { .. } | Reduce { .. });
1992        });
1993        result
1994    }
1995
1996    /// Hash to an u64 using Rust's default Hasher. (Which is a somewhat slower, but better Hasher
1997    /// than what `Hashable::hashed` would give us.)
1998    pub fn hash_to_u64(&self) -> u64 {
1999        let mut h = DefaultHasher::new();
2000        self.hash(&mut h);
2001        h.finish()
2002    }
2003}
2004
2005// `LetRec` helpers
2006impl MirRelationExpr {
2007    /// True when `expr` contains a `LetRec` AST node.
2008    pub fn is_recursive(self: &MirRelationExpr) -> bool {
2009        let mut worklist = vec![self];
2010        while let Some(expr) = worklist.pop() {
2011            if let MirRelationExpr::LetRec { .. } = expr {
2012                return true;
2013            }
2014            worklist.extend(expr.children());
2015        }
2016        false
2017    }
2018
2019    /// Return the number of sub-expressions in the tree (including self).
2020    pub fn size(&self) -> usize {
2021        let mut size = 0;
2022        self.visit_pre(|_| size += 1);
2023        size
2024    }
2025
2026    /// Given the ids and values of a LetRec, it computes the subset of ids that are used across
2027    /// iterations. These are those ids that have a reference before they are defined, when reading
2028    /// all the bindings in order.
2029    ///
2030    /// For example:
2031    /// ```SQL
2032    /// WITH MUTUALLY RECURSIVE
2033    ///     x(...) AS f(z),
2034    ///     y(...) AS g(x),
2035    ///     z(...) AS h(y)
2036    /// ...;
2037    /// ```
2038    /// Here, only `z` is returned, because `x` and `y` are referenced only within the same
2039    /// iteration.
2040    ///
2041    /// Note that if a binding references itself, that is also returned.
2042    pub fn recursive_ids(ids: &[LocalId], values: &[MirRelationExpr]) -> BTreeSet<LocalId> {
2043        let mut used_across_iterations = BTreeSet::new();
2044        let mut defined = BTreeSet::new();
2045        for (binding_id, value) in itertools::zip_eq(ids.iter(), values.iter()) {
2046            value.visit_pre(|expr| {
2047                if let MirRelationExpr::Get {
2048                    id: Local(get_id), ..
2049                } = expr
2050                {
2051                    // If we haven't seen a definition for it yet, then this will refer
2052                    // to the previous iteration.
2053                    // The `ids.contains` part of the condition is needed to exclude
2054                    // those ids that are not really in this LetRec, but either an inner
2055                    // or outer one.
2056                    if !defined.contains(get_id) && ids.contains(get_id) {
2057                        used_across_iterations.insert(*get_id);
2058                    }
2059                }
2060            });
2061            defined.insert(*binding_id);
2062        }
2063        used_across_iterations
2064    }
2065
2066    /// Replaces `LetRec` nodes with a stack of `Let` nodes.
2067    ///
2068    /// In each `Let` binding, uses of `Get` in `value` that are not at strictly greater
2069    /// identifiers are rewritten to be the constant collection.
2070    /// This makes the computation perform exactly "one" iteration.
2071    ///
2072    /// This was used only temporarily while developing `LetRec`.
2073    pub fn make_nonrecursive(self: &mut MirRelationExpr) {
2074        let mut deadlist = BTreeSet::new();
2075        let mut worklist = vec![self];
2076        while let Some(expr) = worklist.pop() {
2077            if let MirRelationExpr::LetRec {
2078                ids,
2079                values,
2080                limits: _,
2081                body,
2082            } = expr
2083            {
2084                let ids_values = values
2085                    .drain(..)
2086                    .zip_eq(ids)
2087                    .map(|(value, id)| (*id, value))
2088                    .collect::<Vec<_>>();
2089                *expr = body.take_dangerous();
2090                for (id, mut value) in ids_values.into_iter().rev() {
2091                    // Remove references to potentially recursive identifiers.
2092                    deadlist.insert(id);
2093                    value.visit_pre_mut(|e| {
2094                        if let MirRelationExpr::Get {
2095                            id: crate::Id::Local(id),
2096                            typ,
2097                            ..
2098                        } = e
2099                        {
2100                            let typ = typ.clone();
2101                            if deadlist.contains(id) {
2102                                e.take_safely(Some(typ));
2103                            }
2104                        }
2105                    });
2106                    *expr = MirRelationExpr::Let {
2107                        id,
2108                        value: Box::new(value),
2109                        body: Box::new(expr.take_dangerous()),
2110                    };
2111                }
2112                worklist.push(expr);
2113            } else {
2114                worklist.extend(expr.children_mut().rev());
2115            }
2116        }
2117    }
2118
2119    /// For each Id `id'` referenced in `expr`, if it is larger or equal than `id`, then record in
2120    /// `expire_whens` that when `id'` is redefined, then we should expire the information that
2121    /// we are holding about `id`. Call `do_expirations` with `expire_whens` at each Id
2122    /// redefinition.
2123    ///
2124    /// IMPORTANT: Relies on the numbering of Ids to be what `renumber_bindings` gives.
2125    pub fn collect_expirations(
2126        id: LocalId,
2127        expr: &MirRelationExpr,
2128        expire_whens: &mut BTreeMap<LocalId, Vec<LocalId>>,
2129    ) {
2130        expr.visit_pre(|e| {
2131            if let MirRelationExpr::Get {
2132                id: Id::Local(referenced_id),
2133                ..
2134            } = e
2135            {
2136                // The following check needs `renumber_bindings` to have run recently
2137                if referenced_id >= &id {
2138                    expire_whens
2139                        .entry(*referenced_id)
2140                        .or_insert_with(Vec::new)
2141                        .push(id);
2142                }
2143            }
2144        });
2145    }
2146
2147    /// Call this function when `id` is redefined. It modifies `id_infos` by removing information
2148    /// about such Ids whose information depended on the earlier definition of `id`, according to
2149    /// `expire_whens`. Also modifies `expire_whens`: it removes the currently processed entry.
2150    pub fn do_expirations<I>(
2151        redefined_id: LocalId,
2152        expire_whens: &mut BTreeMap<LocalId, Vec<LocalId>>,
2153        id_infos: &mut BTreeMap<LocalId, I>,
2154    ) -> Vec<(LocalId, I)> {
2155        let mut expired_infos = Vec::new();
2156        if let Some(expirations) = expire_whens.remove(&redefined_id) {
2157            for expired_id in expirations.into_iter() {
2158                if let Some(offer) = id_infos.remove(&expired_id) {
2159                    expired_infos.push((expired_id, offer));
2160                }
2161            }
2162        }
2163        expired_infos
2164    }
2165}
2166/// Augment non-nullability of columns, by observing either
2167/// 1. Predicates that explicitly test for null values, and
2168/// 2. Columns that if null would make a predicate be null.
2169pub fn non_nullable_columns(predicates: &[MirScalarExpr]) -> BTreeSet<usize> {
2170    let mut nonnull_required_columns = BTreeSet::new();
2171    for predicate in predicates {
2172        // Add any columns that being null would force the predicate to be null.
2173        // Should that happen, the row would be discarded.
2174        predicate.non_null_requirements(&mut nonnull_required_columns);
2175
2176        /*
2177        Test for explicit checks that a column is non-null.
2178
2179        This analysis is ad hoc, and will miss things:
2180
2181        materialize=> create table a(x int, y int);
2182        CREATE TABLE
2183        materialize=> explain with(types) select x from a where (y=x and y is not null) or x is not null;
2184        Optimized Plan
2185        --------------------------------------------------------------------------------------------------------
2186        Explained Query:                                                                                      +
2187        Project (#0) // { types: "(integer?)" }                                                             +
2188        Filter ((#0) IS NOT NULL OR ((#1) IS NOT NULL AND (#0 = #1))) // { types: "(integer?, integer?)" }+
2189        Get materialize.public.a // { types: "(integer?, integer?)" }                                   +
2190                                                                                  +
2191        Source materialize.public.a                                                                           +
2192        filter=(((#0) IS NOT NULL OR ((#1) IS NOT NULL AND (#0 = #1))))                                     +
2193
2194        (1 row)
2195        */
2196
2197        if let MirScalarExpr::CallUnary {
2198            func: UnaryFunc::Not(scalar_func::Not),
2199            expr,
2200        } = predicate
2201        {
2202            if let MirScalarExpr::CallUnary {
2203                func: UnaryFunc::IsNull(scalar_func::IsNull),
2204                expr,
2205            } = &**expr
2206            {
2207                if let MirScalarExpr::Column(c, _name) = &**expr {
2208                    nonnull_required_columns.insert(*c);
2209                }
2210            }
2211        }
2212    }
2213
2214    nonnull_required_columns
2215}
2216
2217impl CollectionPlan for MirRelationExpr {
2218    /// Collects the global collections that this MIR expression directly depends on, i.e., that it
2219    /// has a `Get` for. (It does _not_ traverse view definitions transitively.)
2220    ///
2221    /// !!!WARNING!!!: this method has an HirRelationExpr counterpart. The two
2222    /// should be kept in sync w.r.t. HIR ⇒ MIR lowering!
2223    fn depends_on_into(&self, out: &mut BTreeSet<GlobalId>) {
2224        if let MirRelationExpr::Get {
2225            id: Id::Global(id), ..
2226        } = self
2227        {
2228            out.insert(*id);
2229        }
2230        self.visit_children(|expr| expr.depends_on_into(out))
2231    }
2232}
2233
2234impl MirRelationExpr {
2235    /// Iterates through references to child expressions.
2236    pub fn children(&self) -> impl DoubleEndedIterator<Item = &Self> {
2237        let mut first = None;
2238        let mut second = None;
2239        let mut rest = None;
2240        let mut last = None;
2241
2242        use MirRelationExpr::*;
2243        match self {
2244            Constant { .. } | Get { .. } => (),
2245            Let { value, body, .. } => {
2246                first = Some(&**value);
2247                second = Some(&**body);
2248            }
2249            LetRec { values, body, .. } => {
2250                rest = Some(values);
2251                last = Some(&**body);
2252            }
2253            Project { input, .. }
2254            | Map { input, .. }
2255            | FlatMap { input, .. }
2256            | Filter { input, .. }
2257            | Reduce { input, .. }
2258            | TopK { input, .. }
2259            | Negate { input }
2260            | Threshold { input }
2261            | ArrangeBy { input, .. } => {
2262                first = Some(&**input);
2263            }
2264            Join { inputs, .. } => {
2265                rest = Some(inputs);
2266            }
2267            Union { base, inputs } => {
2268                first = Some(&**base);
2269                rest = Some(inputs);
2270            }
2271        }
2272
2273        first
2274            .into_iter()
2275            .chain(second)
2276            .chain(rest.into_iter().flatten())
2277            .chain(last)
2278    }
2279
2280    /// Iterates through mutable references to child expressions.
2281    pub fn children_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Self> {
2282        let mut first = None;
2283        let mut second = None;
2284        let mut rest = None;
2285        let mut last = None;
2286
2287        use MirRelationExpr::*;
2288        match self {
2289            Constant { .. } | Get { .. } => (),
2290            Let { value, body, .. } => {
2291                first = Some(&mut **value);
2292                second = Some(&mut **body);
2293            }
2294            LetRec { values, body, .. } => {
2295                rest = Some(values);
2296                last = Some(&mut **body);
2297            }
2298            Project { input, .. }
2299            | Map { input, .. }
2300            | FlatMap { input, .. }
2301            | Filter { input, .. }
2302            | Reduce { input, .. }
2303            | TopK { input, .. }
2304            | Negate { input }
2305            | Threshold { input }
2306            | ArrangeBy { input, .. } => {
2307                first = Some(&mut **input);
2308            }
2309            Join { inputs, .. } => {
2310                rest = Some(inputs);
2311            }
2312            Union { base, inputs } => {
2313                first = Some(&mut **base);
2314                rest = Some(inputs);
2315            }
2316        }
2317
2318        first
2319            .into_iter()
2320            .chain(second)
2321            .chain(rest.into_iter().flatten())
2322            .chain(last)
2323    }
2324
2325    /// Iterative pre-order visitor.
2326    pub fn visit_pre<'a, F: FnMut(&'a Self)>(&'a self, mut f: F) {
2327        let mut worklist = vec![self];
2328        while let Some(expr) = worklist.pop() {
2329            f(expr);
2330            worklist.extend(expr.children().rev());
2331        }
2332    }
2333
2334    /// Iterative pre-order visitor.
2335    pub fn visit_pre_mut<F: FnMut(&mut Self)>(&mut self, mut f: F) {
2336        let mut worklist = vec![self];
2337        while let Some(expr) = worklist.pop() {
2338            f(expr);
2339            worklist.extend(expr.children_mut().rev());
2340        }
2341    }
2342
2343    /// Return a vector of references to the subtrees of this expression
2344    /// in post-visit order (the last element is `&self`).
2345    pub fn post_order_vec(&self) -> Vec<&Self> {
2346        let mut stack = vec![self];
2347        let mut result = vec![];
2348        while let Some(expr) = stack.pop() {
2349            result.push(expr);
2350            stack.extend(expr.children());
2351        }
2352        result.reverse();
2353        result
2354    }
2355}
2356
2357impl VisitChildren<Self> for MirRelationExpr {
2358    fn visit_children<F>(&self, mut f: F)
2359    where
2360        F: FnMut(&Self),
2361    {
2362        for child in self.children() {
2363            f(child)
2364        }
2365    }
2366
2367    fn visit_mut_children<F>(&mut self, mut f: F)
2368    where
2369        F: FnMut(&mut Self),
2370    {
2371        for child in self.children_mut() {
2372            f(child)
2373        }
2374    }
2375
2376    fn try_visit_children<F, E>(&self, mut f: F) -> Result<(), E>
2377    where
2378        F: FnMut(&Self) -> Result<(), E>,
2379    {
2380        for child in self.children() {
2381            f(child)?
2382        }
2383        Ok(())
2384    }
2385
2386    fn try_visit_mut_children<F, E>(&mut self, mut f: F) -> Result<(), E>
2387    where
2388        F: FnMut(&mut Self) -> Result<(), E>,
2389    {
2390        for child in self.children_mut() {
2391            f(child)?
2392        }
2393        Ok(())
2394    }
2395
2396    fn children<'a>(&'a self) -> impl DoubleEndedIterator<Item = &'a MirRelationExpr>
2397    where
2398        Self: 'a,
2399    {
2400        self.children()
2401    }
2402
2403    fn children_mut<'a>(&'a mut self) -> impl DoubleEndedIterator<Item = &'a mut MirRelationExpr>
2404    where
2405        Self: 'a,
2406    {
2407        self.children_mut()
2408    }
2409}
2410
2411/// Specification for an ordering by a column.
2412#[derive(
2413    Debug,
2414    Clone,
2415    Copy,
2416    Eq,
2417    PartialEq,
2418    Ord,
2419    PartialOrd,
2420    Serialize,
2421    Deserialize,
2422    Hash
2423)]
2424pub struct ColumnOrder {
2425    /// The column index.
2426    pub column: usize,
2427    /// Whether to sort in descending order.
2428    #[serde(default)]
2429    pub desc: bool,
2430    /// Whether to sort nulls last.
2431    #[serde(default)]
2432    pub nulls_last: bool,
2433}
2434
2435impl Columnation for ColumnOrder {
2436    type InnerRegion = CopyRegion<Self>;
2437}
2438
2439impl<'a, M> fmt::Display for HumanizedExpr<'a, ColumnOrder, M>
2440where
2441    M: HumanizerMode,
2442{
2443    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2444        // If you modify this, then please also attend to Display for ColumnOrderWithExpr!
2445        write!(
2446            f,
2447            "{} {} {}",
2448            self.child(&self.expr.column),
2449            if self.expr.desc { "desc" } else { "asc" },
2450            if self.expr.nulls_last {
2451                "nulls_last"
2452            } else {
2453                "nulls_first"
2454            },
2455        )
2456    }
2457}
2458
2459/// Describes an aggregation expression.
2460#[derive(
2461    Clone,
2462    Debug,
2463    Eq,
2464    PartialEq,
2465    Ord,
2466    PartialOrd,
2467    Serialize,
2468    Deserialize,
2469    Hash
2470)]
2471pub struct AggregateExpr {
2472    /// Names the aggregation function.
2473    pub func: AggregateFunc,
2474    /// An expression which extracts from each row the input to `func`.
2475    pub expr: MirScalarExpr,
2476    /// Should the aggregation be applied only to distinct results in each group.
2477    #[serde(default)]
2478    pub distinct: bool,
2479}
2480
2481impl AggregateExpr {
2482    /// Computes the type of this `AggregateExpr`.
2483    pub fn sql_typ(&self, column_types: &[SqlColumnType]) -> SqlColumnType {
2484        self.func.output_sql_type(self.expr.sql_typ(column_types))
2485    }
2486
2487    /// Computes the type of this `AggregateExpr`.
2488    pub fn typ(&self, column_types: &[ReprColumnType]) -> ReprColumnType {
2489        self.func.output_type(self.expr.typ(column_types))
2490    }
2491
2492    /// Returns whether the expression has a constant result.
2493    pub fn is_constant(&self) -> bool {
2494        match self.func {
2495            AggregateFunc::MaxNumeric
2496            | AggregateFunc::MaxInt16
2497            | AggregateFunc::MaxInt32
2498            | AggregateFunc::MaxInt64
2499            | AggregateFunc::MaxUInt16
2500            | AggregateFunc::MaxUInt32
2501            | AggregateFunc::MaxUInt64
2502            | AggregateFunc::MaxMzTimestamp
2503            | AggregateFunc::MaxFloat32
2504            | AggregateFunc::MaxFloat64
2505            | AggregateFunc::MaxBool
2506            | AggregateFunc::MaxString
2507            | AggregateFunc::MaxDate
2508            | AggregateFunc::MaxTimestamp
2509            | AggregateFunc::MaxTimestampTz
2510            | AggregateFunc::MaxInterval
2511            | AggregateFunc::MaxTime
2512            | AggregateFunc::MaxArray
2513            | AggregateFunc::MaxList
2514            | AggregateFunc::MinNumeric
2515            | AggregateFunc::MinInt16
2516            | AggregateFunc::MinInt32
2517            | AggregateFunc::MinInt64
2518            | AggregateFunc::MinUInt16
2519            | AggregateFunc::MinUInt32
2520            | AggregateFunc::MinUInt64
2521            | AggregateFunc::MinMzTimestamp
2522            | AggregateFunc::MinFloat32
2523            | AggregateFunc::MinFloat64
2524            | AggregateFunc::MinBool
2525            | AggregateFunc::MinString
2526            | AggregateFunc::MinDate
2527            | AggregateFunc::MinTimestamp
2528            | AggregateFunc::MinTimestampTz
2529            | AggregateFunc::MinInterval
2530            | AggregateFunc::MinTime
2531            | AggregateFunc::MinArray
2532            | AggregateFunc::MinList
2533            | AggregateFunc::Any
2534            | AggregateFunc::All
2535            | AggregateFunc::Dummy => self.expr.is_literal(),
2536            AggregateFunc::Count => self.expr.is_literal_null(),
2537            AggregateFunc::SumInt16
2538            | AggregateFunc::SumInt32
2539            | AggregateFunc::SumInt64
2540            | AggregateFunc::SumUInt16
2541            | AggregateFunc::SumUInt32
2542            | AggregateFunc::SumUInt64
2543            | AggregateFunc::SumFloat32
2544            | AggregateFunc::SumFloat64
2545            | AggregateFunc::SumNumeric
2546            | AggregateFunc::SumInterval
2547            | AggregateFunc::JsonbAgg { .. }
2548            | AggregateFunc::JsonbObjectAgg { .. }
2549            | AggregateFunc::MapAgg { .. }
2550            | AggregateFunc::ArrayConcat { .. }
2551            | AggregateFunc::ListConcat { .. }
2552            | AggregateFunc::StringAgg { .. }
2553            | AggregateFunc::RowNumber { .. }
2554            | AggregateFunc::Rank { .. }
2555            | AggregateFunc::DenseRank { .. }
2556            | AggregateFunc::LagLead { .. }
2557            | AggregateFunc::FirstValue { .. }
2558            | AggregateFunc::LastValue { .. }
2559            | AggregateFunc::FusedValueWindowFunc { .. }
2560            | AggregateFunc::WindowAggregate { .. }
2561            | AggregateFunc::FusedWindowAggregate { .. } => self.expr.is_literal_err(),
2562        }
2563    }
2564
2565    /// Returns an expression that computes `self` on a group that has exactly one row.
2566    /// Instead of performing a `Reduce` with `self`, one can perform a `Map` with the expression
2567    /// returned by `on_unique`, which is cheaper. (See `ReduceElision`.)
2568    pub fn on_unique(&self, input_type: &[ReprColumnType]) -> MirScalarExpr {
2569        match &self.func {
2570            // Count is one if non-null, and zero if null.
2571            AggregateFunc::Count => self
2572                .expr
2573                .clone()
2574                .call_unary(UnaryFunc::IsNull(crate::func::IsNull))
2575                .if_then_else(
2576                    MirScalarExpr::literal_ok(Datum::Int64(0), ReprScalarType::Int64),
2577                    MirScalarExpr::literal_ok(Datum::Int64(1), ReprScalarType::Int64),
2578                ),
2579
2580            // SumInt16 takes Int16s as input, but outputs Int64s.
2581            AggregateFunc::SumInt16 => self
2582                .expr
2583                .clone()
2584                .call_unary(UnaryFunc::CastInt16ToInt64(scalar_func::CastInt16ToInt64)),
2585
2586            // SumInt32 takes Int32s as input, but outputs Int64s.
2587            AggregateFunc::SumInt32 => self
2588                .expr
2589                .clone()
2590                .call_unary(UnaryFunc::CastInt32ToInt64(scalar_func::CastInt32ToInt64)),
2591
2592            // SumInt64 takes Int64s as input, but outputs numerics.
2593            AggregateFunc::SumInt64 => self.expr.clone().call_unary(UnaryFunc::CastInt64ToNumeric(
2594                scalar_func::CastInt64ToNumeric(Some(NumericMaxScale::ZERO)),
2595            )),
2596
2597            // SumUInt16 takes UInt16s as input, but outputs UInt64s.
2598            AggregateFunc::SumUInt16 => self.expr.clone().call_unary(
2599                UnaryFunc::CastUint16ToUint64(scalar_func::CastUint16ToUint64),
2600            ),
2601
2602            // SumUInt32 takes UInt32s as input, but outputs UInt64s.
2603            AggregateFunc::SumUInt32 => self.expr.clone().call_unary(
2604                UnaryFunc::CastUint32ToUint64(scalar_func::CastUint32ToUint64),
2605            ),
2606
2607            // SumUInt64 takes UInt64s as input, but outputs numerics.
2608            AggregateFunc::SumUInt64 => {
2609                self.expr.clone().call_unary(UnaryFunc::CastUint64ToNumeric(
2610                    scalar_func::CastUint64ToNumeric(Some(NumericMaxScale::ZERO)),
2611                ))
2612            }
2613
2614            // JsonbAgg takes _anything_ as input, but must output a Jsonb array.
2615            AggregateFunc::JsonbAgg { .. } => MirScalarExpr::call_variadic(
2616                JsonbBuildArray,
2617                vec![
2618                    self.expr
2619                        .clone()
2620                        .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0))),
2621                ],
2622            ),
2623
2624            // JsonbAgg takes _anything_ as input, but must output a Jsonb object.
2625            AggregateFunc::JsonbObjectAgg { .. } => {
2626                let record = self
2627                    .expr
2628                    .clone()
2629                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2630                MirScalarExpr::call_variadic(
2631                    JsonbBuildObject,
2632                    (0..2)
2633                        .map(|i| {
2634                            record
2635                                .clone()
2636                                .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(i)))
2637                        })
2638                        .collect(),
2639                )
2640            }
2641
2642            AggregateFunc::MapAgg { value_type, .. } => {
2643                let record = self
2644                    .expr
2645                    .clone()
2646                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2647                MirScalarExpr::call_variadic(
2648                    MapBuild {
2649                        value_type: value_type.clone(),
2650                    },
2651                    (0..2)
2652                        .map(|i| {
2653                            record
2654                                .clone()
2655                                .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(i)))
2656                        })
2657                        .collect(),
2658                )
2659            }
2660
2661            // StringAgg takes nested records of strings and outputs a string
2662            AggregateFunc::StringAgg { .. } => self
2663                .expr
2664                .clone()
2665                .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)))
2666                .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0))),
2667
2668            // ListConcat and ArrayConcat take a single level of records and output a list containing exactly 1 element
2669            AggregateFunc::ListConcat { .. } | AggregateFunc::ArrayConcat { .. } => self
2670                .expr
2671                .clone()
2672                .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0))),
2673
2674            // RowNumber, Rank, DenseRank take a list of records and output a list containing exactly 1 element
2675            AggregateFunc::RowNumber { .. } => {
2676                self.on_unique_ranking_window_funcs(input_type, "?row_number?")
2677            }
2678            AggregateFunc::Rank { .. } => self.on_unique_ranking_window_funcs(input_type, "?rank?"),
2679            AggregateFunc::DenseRank { .. } => {
2680                self.on_unique_ranking_window_funcs(input_type, "?dense_rank?")
2681            }
2682
2683            // The input type for LagLead is ((OriginalRow, (InputValue, Offset, Default)), OrderByExprs...)
2684            AggregateFunc::LagLead { lag_lead, .. } => {
2685                let tuple = self
2686                    .expr
2687                    .clone()
2688                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2689
2690                // Get the overall return type
2691                let return_type_with_orig_row = self
2692                    .typ(input_type)
2693                    .scalar_type
2694                    .unwrap_list_element_type()
2695                    .clone();
2696                let lag_lead_return_type =
2697                    return_type_with_orig_row.unwrap_record_element_type()[0].clone();
2698
2699                // Extract the original row
2700                let original_row = tuple
2701                    .clone()
2702                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2703
2704                // Extract the encoded args
2705                let encoded_args =
2706                    tuple.call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(1)));
2707
2708                let (result_expr, column_name) =
2709                    Self::on_unique_lag_lead(lag_lead, encoded_args, lag_lead_return_type.clone());
2710
2711                MirScalarExpr::call_variadic(
2712                    ListCreate {
2713                        elem_type: SqlScalarType::from_repr(&return_type_with_orig_row),
2714                    },
2715                    vec![MirScalarExpr::call_variadic(
2716                        RecordCreate {
2717                            field_names: vec![column_name, ColumnName::from("?record?")],
2718                        },
2719                        vec![result_expr, original_row],
2720                    )],
2721                )
2722            }
2723
2724            // The input type for FirstValue is ((OriginalRow, InputValue), OrderByExprs...)
2725            AggregateFunc::FirstValue { window_frame, .. } => {
2726                let tuple = self
2727                    .expr
2728                    .clone()
2729                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2730
2731                // Get the overall return type
2732                let return_type_with_orig_row = self
2733                    .typ(input_type)
2734                    .scalar_type
2735                    .unwrap_list_element_type()
2736                    .clone();
2737                let first_value_return_type =
2738                    return_type_with_orig_row.unwrap_record_element_type()[0].clone();
2739
2740                // Extract the original row
2741                let original_row = tuple
2742                    .clone()
2743                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2744
2745                // Extract the input value
2746                let arg = tuple.call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(1)));
2747
2748                let (result_expr, column_name) = Self::on_unique_first_value_last_value(
2749                    window_frame,
2750                    arg,
2751                    first_value_return_type,
2752                );
2753
2754                MirScalarExpr::call_variadic(
2755                    ListCreate {
2756                        elem_type: SqlScalarType::from_repr(&return_type_with_orig_row),
2757                    },
2758                    vec![MirScalarExpr::call_variadic(
2759                        RecordCreate {
2760                            field_names: vec![column_name, ColumnName::from("?record?")],
2761                        },
2762                        vec![result_expr, original_row],
2763                    )],
2764                )
2765            }
2766
2767            // The input type for LastValue is ((OriginalRow, InputValue), OrderByExprs...)
2768            AggregateFunc::LastValue { window_frame, .. } => {
2769                let tuple = self
2770                    .expr
2771                    .clone()
2772                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2773
2774                // Get the overall return type
2775                let return_type_with_orig_row = self
2776                    .typ(input_type)
2777                    .scalar_type
2778                    .unwrap_list_element_type()
2779                    .clone();
2780                let last_value_return_type =
2781                    return_type_with_orig_row.unwrap_record_element_type()[0].clone();
2782
2783                // Extract the original row
2784                let original_row = tuple
2785                    .clone()
2786                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2787
2788                // Extract the input value
2789                let arg = tuple.call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(1)));
2790
2791                let (result_expr, column_name) = Self::on_unique_first_value_last_value(
2792                    window_frame,
2793                    arg,
2794                    last_value_return_type,
2795                );
2796
2797                MirScalarExpr::call_variadic(
2798                    ListCreate {
2799                        elem_type: SqlScalarType::from_repr(&return_type_with_orig_row),
2800                    },
2801                    vec![MirScalarExpr::call_variadic(
2802                        RecordCreate {
2803                            field_names: vec![column_name, ColumnName::from("?record?")],
2804                        },
2805                        vec![result_expr, original_row],
2806                    )],
2807                )
2808            }
2809
2810            // The input type for window aggs is ((OriginalRow, InputValue), OrderByExprs...)
2811            // See an example MIR in `window_func_applied_to`.
2812            AggregateFunc::WindowAggregate {
2813                wrapped_aggregate,
2814                window_frame,
2815                order_by: _,
2816            } => {
2817                // TODO: deduplicate code between the various window function cases.
2818
2819                let tuple = self
2820                    .expr
2821                    .clone()
2822                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2823
2824                // Get the overall return type
2825                let return_type = self
2826                    .typ(input_type)
2827                    .scalar_type
2828                    .unwrap_list_element_type()
2829                    .clone();
2830                let window_agg_return_type = return_type.unwrap_record_element_type()[0].clone();
2831
2832                // Extract the original row
2833                let original_row = tuple
2834                    .clone()
2835                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2836
2837                // Extract the input value
2838                let arg_expr = tuple.call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(1)));
2839
2840                let (result, column_name) = Self::on_unique_window_agg(
2841                    window_frame,
2842                    arg_expr,
2843                    input_type,
2844                    window_agg_return_type,
2845                    wrapped_aggregate,
2846                );
2847
2848                MirScalarExpr::call_variadic(
2849                    ListCreate {
2850                        elem_type: SqlScalarType::from_repr(&return_type),
2851                    },
2852                    vec![MirScalarExpr::call_variadic(
2853                        RecordCreate {
2854                            field_names: vec![column_name, ColumnName::from("?record?")],
2855                        },
2856                        vec![result, original_row],
2857                    )],
2858                )
2859            }
2860
2861            // The input type is ((OriginalRow, (Arg1, Arg2, ...)), OrderByExprs...)
2862            AggregateFunc::FusedWindowAggregate {
2863                wrapped_aggregates,
2864                order_by: _,
2865                window_frame,
2866            } => {
2867                // Throw away OrderByExprs
2868                let tuple = self
2869                    .expr
2870                    .clone()
2871                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2872
2873                // Extract the original row
2874                let original_row = tuple
2875                    .clone()
2876                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2877
2878                // Extract the args of the fused call
2879                let all_args = tuple.call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(1)));
2880
2881                let return_type_with_orig_row = self
2882                    .typ(input_type)
2883                    .scalar_type
2884                    .unwrap_list_element_type()
2885                    .clone();
2886
2887                let all_func_return_types =
2888                    return_type_with_orig_row.unwrap_record_element_type()[0].clone();
2889                let mut func_result_exprs = Vec::new();
2890                let mut col_names = Vec::new();
2891                for (idx, wrapped_aggr) in wrapped_aggregates.iter().enumerate() {
2892                    let arg = all_args
2893                        .clone()
2894                        .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(idx)));
2895                    let return_type =
2896                        all_func_return_types.unwrap_record_element_type()[idx].clone();
2897                    let (result, column_name) = Self::on_unique_window_agg(
2898                        window_frame,
2899                        arg,
2900                        input_type,
2901                        return_type,
2902                        wrapped_aggr,
2903                    );
2904                    func_result_exprs.push(result);
2905                    col_names.push(column_name);
2906                }
2907
2908                MirScalarExpr::call_variadic(
2909                    ListCreate {
2910                        elem_type: SqlScalarType::from_repr(&return_type_with_orig_row),
2911                    },
2912                    vec![MirScalarExpr::call_variadic(
2913                        RecordCreate {
2914                            field_names: vec![
2915                                ColumnName::from("?fused_window_aggr?"),
2916                                ColumnName::from("?record?"),
2917                            ],
2918                        },
2919                        vec![
2920                            MirScalarExpr::call_variadic(
2921                                RecordCreate {
2922                                    field_names: col_names,
2923                                },
2924                                func_result_exprs,
2925                            ),
2926                            original_row,
2927                        ],
2928                    )],
2929                )
2930            }
2931
2932            // The input type is ((OriginalRow, (Args1, Args2, ...)), OrderByExprs...)
2933            AggregateFunc::FusedValueWindowFunc {
2934                funcs,
2935                order_by: outer_order_by,
2936            } => {
2937                // Throw away OrderByExprs
2938                let tuple = self
2939                    .expr
2940                    .clone()
2941                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2942
2943                // Extract the original row
2944                let original_row = tuple
2945                    .clone()
2946                    .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
2947
2948                // Extract the encoded args of the fused call
2949                let all_encoded_args =
2950                    tuple.call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(1)));
2951
2952                let return_type_with_orig_row = self
2953                    .typ(input_type)
2954                    .scalar_type
2955                    .unwrap_list_element_type()
2956                    .clone();
2957
2958                let all_func_return_types =
2959                    return_type_with_orig_row.unwrap_record_element_type()[0].clone();
2960                let mut func_result_exprs = Vec::new();
2961                let mut col_names = Vec::new();
2962                for (idx, func) in funcs.iter().enumerate() {
2963                    let args_for_func = all_encoded_args
2964                        .clone()
2965                        .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(idx)));
2966                    let return_type_for_func =
2967                        all_func_return_types.unwrap_record_element_type()[idx].clone();
2968                    let (result, column_name) = match func {
2969                        AggregateFunc::LagLead {
2970                            lag_lead,
2971                            order_by,
2972                            ignore_nulls: _,
2973                        } => {
2974                            assert_eq!(order_by, outer_order_by);
2975                            Self::on_unique_lag_lead(lag_lead, args_for_func, return_type_for_func)
2976                        }
2977                        AggregateFunc::FirstValue {
2978                            window_frame,
2979                            order_by,
2980                        } => {
2981                            assert_eq!(order_by, outer_order_by);
2982                            Self::on_unique_first_value_last_value(
2983                                window_frame,
2984                                args_for_func,
2985                                return_type_for_func,
2986                            )
2987                        }
2988                        AggregateFunc::LastValue {
2989                            window_frame,
2990                            order_by,
2991                        } => {
2992                            assert_eq!(order_by, outer_order_by);
2993                            Self::on_unique_first_value_last_value(
2994                                window_frame,
2995                                args_for_func,
2996                                return_type_for_func,
2997                            )
2998                        }
2999                        _ => panic!("unknown function in FusedValueWindowFunc"),
3000                    };
3001                    func_result_exprs.push(result);
3002                    col_names.push(column_name);
3003                }
3004
3005                MirScalarExpr::call_variadic(
3006                    ListCreate {
3007                        elem_type: SqlScalarType::from_repr(&return_type_with_orig_row),
3008                    },
3009                    vec![MirScalarExpr::call_variadic(
3010                        RecordCreate {
3011                            field_names: vec![
3012                                ColumnName::from("?fused_value_window_func?"),
3013                                ColumnName::from("?record?"),
3014                            ],
3015                        },
3016                        vec![
3017                            MirScalarExpr::call_variadic(
3018                                RecordCreate {
3019                                    field_names: col_names,
3020                                },
3021                                func_result_exprs,
3022                            ),
3023                            original_row,
3024                        ],
3025                    )],
3026                )
3027            }
3028
3029            // All other variants should return the argument to the aggregation.
3030            AggregateFunc::MaxNumeric
3031            | AggregateFunc::MaxInt16
3032            | AggregateFunc::MaxInt32
3033            | AggregateFunc::MaxInt64
3034            | AggregateFunc::MaxUInt16
3035            | AggregateFunc::MaxUInt32
3036            | AggregateFunc::MaxUInt64
3037            | AggregateFunc::MaxMzTimestamp
3038            | AggregateFunc::MaxFloat32
3039            | AggregateFunc::MaxFloat64
3040            | AggregateFunc::MaxBool
3041            | AggregateFunc::MaxString
3042            | AggregateFunc::MaxDate
3043            | AggregateFunc::MaxTimestamp
3044            | AggregateFunc::MaxTimestampTz
3045            | AggregateFunc::MaxInterval
3046            | AggregateFunc::MaxTime
3047            | AggregateFunc::MaxArray
3048            | AggregateFunc::MaxList
3049            | AggregateFunc::MinNumeric
3050            | AggregateFunc::MinInt16
3051            | AggregateFunc::MinInt32
3052            | AggregateFunc::MinInt64
3053            | AggregateFunc::MinUInt16
3054            | AggregateFunc::MinUInt32
3055            | AggregateFunc::MinUInt64
3056            | AggregateFunc::MinMzTimestamp
3057            | AggregateFunc::MinFloat32
3058            | AggregateFunc::MinFloat64
3059            | AggregateFunc::MinBool
3060            | AggregateFunc::MinString
3061            | AggregateFunc::MinDate
3062            | AggregateFunc::MinTimestamp
3063            | AggregateFunc::MinTimestampTz
3064            | AggregateFunc::MinInterval
3065            | AggregateFunc::MinTime
3066            | AggregateFunc::MinArray
3067            | AggregateFunc::MinList
3068            | AggregateFunc::SumFloat32
3069            | AggregateFunc::SumFloat64
3070            | AggregateFunc::SumNumeric
3071            | AggregateFunc::SumInterval
3072            | AggregateFunc::Any
3073            | AggregateFunc::All
3074            | AggregateFunc::Dummy => self.expr.clone(),
3075        }
3076    }
3077
3078    /// `on_unique` for ROW_NUMBER, RANK, DENSE_RANK
3079    fn on_unique_ranking_window_funcs(
3080        &self,
3081        input_type: &[ReprColumnType],
3082        col_name: &str,
3083    ) -> MirScalarExpr {
3084        let sql_input_type: Vec<SqlColumnType> =
3085            input_type.iter().map(SqlColumnType::from_repr).collect();
3086        let list = self
3087            .expr
3088            .clone()
3089            // extract the list within the record
3090            .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
3091
3092        // extract the expression within the list
3093        let record = MirScalarExpr::call_variadic(
3094            ListIndex,
3095            vec![
3096                list,
3097                MirScalarExpr::literal_ok(Datum::Int64(1), ReprScalarType::Int64),
3098            ],
3099        );
3100
3101        MirScalarExpr::call_variadic(
3102            ListCreate {
3103                elem_type: self
3104                    .sql_typ(&sql_input_type)
3105                    .scalar_type
3106                    .unwrap_list_element_type()
3107                    .clone(),
3108            },
3109            vec![MirScalarExpr::call_variadic(
3110                RecordCreate {
3111                    field_names: vec![ColumnName::from(col_name), ColumnName::from("?record?")],
3112                },
3113                vec![
3114                    MirScalarExpr::literal_ok(Datum::Int64(1), ReprScalarType::Int64),
3115                    record,
3116                ],
3117            )],
3118        )
3119    }
3120
3121    /// `on_unique` for `lag` and `lead`
3122    fn on_unique_lag_lead(
3123        lag_lead: &LagLeadType,
3124        encoded_args: MirScalarExpr,
3125        return_type: ReprScalarType,
3126    ) -> (MirScalarExpr, ColumnName) {
3127        let expr = encoded_args
3128            .clone()
3129            .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(0)));
3130        let offset = encoded_args
3131            .clone()
3132            .call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(1)));
3133        let default_value =
3134            encoded_args.call_unary(UnaryFunc::RecordGet(scalar_func::RecordGet(2)));
3135
3136        // In this case, the window always has only one element, so if the offset is not null and
3137        // not zero, the default value should be returned instead.
3138        let value = offset
3139            .clone()
3140            .call_binary(
3141                MirScalarExpr::literal_ok(Datum::Int32(0), ReprScalarType::Int32),
3142                crate::func::Eq,
3143            )
3144            .if_then_else(expr, default_value);
3145        let result_expr = offset
3146            .call_unary(UnaryFunc::IsNull(crate::func::IsNull))
3147            .if_then_else(MirScalarExpr::literal_null(return_type), value);
3148
3149        let column_name = ColumnName::from(match lag_lead {
3150            LagLeadType::Lag => "?lag?",
3151            LagLeadType::Lead => "?lead?",
3152        });
3153
3154        (result_expr, column_name)
3155    }
3156
3157    /// `on_unique` for `first_value` and `last_value`
3158    fn on_unique_first_value_last_value(
3159        window_frame: &WindowFrame,
3160        arg: MirScalarExpr,
3161        return_type: ReprScalarType,
3162    ) -> (MirScalarExpr, ColumnName) {
3163        // If the window frame includes the current (single) row, return its value, null otherwise
3164        let result_expr = if window_frame.includes_current_row() {
3165            arg
3166        } else {
3167            MirScalarExpr::literal_null(return_type)
3168        };
3169        (result_expr, ColumnName::from("?first_value?"))
3170    }
3171
3172    /// `on_unique` for window aggregations
3173    fn on_unique_window_agg(
3174        window_frame: &WindowFrame,
3175        arg_expr: MirScalarExpr,
3176        input_type: &[ReprColumnType],
3177        return_type: ReprScalarType,
3178        wrapped_aggr: &AggregateFunc,
3179    ) -> (MirScalarExpr, ColumnName) {
3180        // If the window frame includes the current (single) row, evaluate the wrapped aggregate on
3181        // that row. Otherwise, return the default value for the aggregate.
3182        let result_expr = if window_frame.includes_current_row() {
3183            AggregateExpr {
3184                func: wrapped_aggr.clone(),
3185                expr: arg_expr,
3186                distinct: false, // We have just one input element; DISTINCT doesn't matter.
3187            }
3188            .on_unique(input_type)
3189        } else {
3190            MirScalarExpr::literal_ok(wrapped_aggr.default(), return_type)
3191        };
3192        (result_expr, ColumnName::from("?window_agg?"))
3193    }
3194
3195    /// Returns whether the expression is COUNT(*) or not.  Note that
3196    /// when we define the count builtin in sql::func, we convert
3197    /// COUNT(*) to COUNT(true), making it indistinguishable from
3198    /// literal COUNT(true), but we prefer to consider this as the
3199    /// former.
3200    ///
3201    /// (HIR has the same `is_count_asterisk`.)
3202    pub fn is_count_asterisk(&self) -> bool {
3203        self.func == AggregateFunc::Count && self.expr.is_literal_true() && !self.distinct
3204    }
3205}
3206
3207/// Describe a join implementation in dataflow.
3208#[derive(
3209    Clone,
3210    Debug,
3211    Eq,
3212    PartialEq,
3213    Ord,
3214    PartialOrd,
3215    Serialize,
3216    Deserialize,
3217    Hash
3218)]
3219pub enum JoinImplementation {
3220    /// Perform a sequence of binary differential dataflow joins.
3221    ///
3222    /// The first argument indicates
3223    /// 1) the index of the starting collection,
3224    /// 2) if it should be arranged, the keys to arrange it by, and
3225    /// 3) the characteristics of the starting collection (for EXPLAINing).
3226    /// The sequence that follows lists other relation indexes, and the key for
3227    /// the arrangement we should use when joining it in.
3228    /// The JoinInputCharacteristics are for EXPLAINing the characteristics that
3229    /// were used for join ordering.
3230    ///
3231    /// Each collection index should occur exactly once, either as the starting collection
3232    /// or somewhere in the list.
3233    Differential(
3234        (
3235            usize,
3236            Option<Vec<MirScalarExpr>>,
3237            Option<JoinInputCharacteristics>,
3238        ),
3239        Vec<(usize, Vec<MirScalarExpr>, Option<JoinInputCharacteristics>)>,
3240    ),
3241    /// Perform independent delta query dataflows for each input.
3242    ///
3243    /// The argument is a sequence of plans, for the input collections in order.
3244    /// Each plan starts from the corresponding index, and then in sequence joins
3245    /// against collections identified by index and with the specified arrangement key.
3246    /// The JoinInputCharacteristics are for EXPLAINing the characteristics that were
3247    /// used for join ordering.
3248    DeltaQuery(Vec<Vec<(usize, Vec<MirScalarExpr>, Option<JoinInputCharacteristics>)>>),
3249    /// Join a user-created index with a constant collection to speed up the evaluation of a
3250    /// predicate such as `(f1 = 3 AND f2 = 5) OR (f1 = 7 AND f2 = 9)`.
3251    /// This gets translated to a Differential join during MIR -> LIR lowering, but we still want
3252    /// to represent it in MIR, because the fast path detection wants to match on this.
3253    ///
3254    /// Consists of (`<coll_id>`, `<index_id>`, `<index_key>`, `<constants>`)
3255    IndexedFilter(GlobalId, GlobalId, Vec<MirScalarExpr>, Vec<Row>),
3256    /// No implementation yet selected.
3257    Unimplemented,
3258}
3259
3260impl Default for JoinImplementation {
3261    fn default() -> Self {
3262        JoinImplementation::Unimplemented
3263    }
3264}
3265
3266impl JoinImplementation {
3267    /// Returns `true` iff the value is not [`JoinImplementation::Unimplemented`].
3268    pub fn is_implemented(&self) -> bool {
3269        match self {
3270            Self::Unimplemented => false,
3271            _ => true,
3272        }
3273    }
3274
3275    /// Returns an optional implementation name if the value is not [`JoinImplementation::Unimplemented`].
3276    pub fn name(&self) -> Option<&'static str> {
3277        match self {
3278            Self::Differential(..) => Some("differential"),
3279            Self::DeltaQuery(..) => Some("delta"),
3280            Self::IndexedFilter(..) => Some("indexed_filter"),
3281            Self::Unimplemented => None,
3282        }
3283    }
3284}
3285
3286/// Characteristics of a join order candidate collection.
3287///
3288/// A candidate is described by a collection and a key, and may have various liabilities.
3289/// Primarily, the candidate may risk substantial inflation of records, which is something
3290/// that concerns us greatly. Additionally, the candidate may be unarranged, and we would
3291/// prefer candidates that do not require additional memory. Finally, we prefer lower id
3292/// collections in the interest of consistent tie-breaking. For more characteristics, see
3293/// comments on individual fields.
3294///
3295/// This has more than one version. `new` instantiates the appropriate version based on a
3296/// feature flag.
3297#[derive(
3298    Eq,
3299    PartialEq,
3300    Ord,
3301    PartialOrd,
3302    Debug,
3303    Clone,
3304    Serialize,
3305    Deserialize,
3306    Hash
3307)]
3308pub enum JoinInputCharacteristics {
3309    /// Old version, with `enable_join_prioritize_arranged` turned off.
3310    V1(JoinInputCharacteristicsV1),
3311    /// Newer version, with `enable_join_prioritize_arranged` turned on.
3312    V2(JoinInputCharacteristicsV2),
3313}
3314
3315impl JoinInputCharacteristics {
3316    /// Creates a new instance with the given characteristics.
3317    pub fn new(
3318        unique_key: bool,
3319        key_length: usize,
3320        arranged: bool,
3321        cardinality: Option<usize>,
3322        filters: FilterCharacteristics,
3323        input: usize,
3324        enable_join_prioritize_arranged: bool,
3325    ) -> Self {
3326        if enable_join_prioritize_arranged {
3327            Self::V2(JoinInputCharacteristicsV2::new(
3328                unique_key,
3329                key_length,
3330                arranged,
3331                cardinality,
3332                filters,
3333                input,
3334            ))
3335        } else {
3336            Self::V1(JoinInputCharacteristicsV1::new(
3337                unique_key,
3338                key_length,
3339                arranged,
3340                cardinality,
3341                filters,
3342                input,
3343            ))
3344        }
3345    }
3346
3347    /// Turns the instance into a String to be printed in EXPLAIN.
3348    pub fn explain(&self) -> String {
3349        match self {
3350            Self::V1(jic) => jic.explain(),
3351            Self::V2(jic) => jic.explain(),
3352        }
3353    }
3354
3355    /// Whether the join input described by `self` is arranged.
3356    pub fn arranged(&self) -> bool {
3357        match self {
3358            Self::V1(jic) => jic.arranged,
3359            Self::V2(jic) => jic.arranged,
3360        }
3361    }
3362
3363    /// Returns the `FilterCharacteristics` for the join input described by `self`.
3364    pub fn filters(&mut self) -> &mut FilterCharacteristics {
3365        match self {
3366            Self::V1(jic) => &mut jic.filters,
3367            Self::V2(jic) => &mut jic.filters,
3368        }
3369    }
3370}
3371
3372/// Newer version of `JoinInputCharacteristics`, with `enable_join_prioritize_arranged` turned on.
3373#[derive(
3374    Eq,
3375    PartialEq,
3376    Ord,
3377    PartialOrd,
3378    Debug,
3379    Clone,
3380    Serialize,
3381    Deserialize,
3382    Hash
3383)]
3384pub struct JoinInputCharacteristicsV2 {
3385    /// An excellent indication that record count will not increase.
3386    pub unique_key: bool,
3387    /// Cross joins are bad.
3388    /// (`key_length > 0` also implies that it is not a cross join. However, we need to note cross
3389    /// joins in a separate field, because not being a cross join is more important than `arranged`,
3390    /// but otherwise `key_length` is less important than `arranged`.)
3391    pub not_cross: bool,
3392    /// Indicates that there will be no additional in-memory footprint.
3393    pub arranged: bool,
3394    /// A weaker signal that record count will not increase.
3395    pub key_length: usize,
3396    /// Estimated cardinality (lower is better)
3397    pub cardinality: Option<std::cmp::Reverse<usize>>,
3398    /// Characteristics of the filter that is applied at this input.
3399    pub filters: FilterCharacteristics,
3400    /// We want to prefer input earlier in the input list, for stability of ordering.
3401    pub input: std::cmp::Reverse<usize>,
3402}
3403
3404impl JoinInputCharacteristicsV2 {
3405    /// Creates a new instance with the given characteristics.
3406    pub fn new(
3407        unique_key: bool,
3408        key_length: usize,
3409        arranged: bool,
3410        cardinality: Option<usize>,
3411        filters: FilterCharacteristics,
3412        input: usize,
3413    ) -> Self {
3414        Self {
3415            unique_key,
3416            not_cross: key_length > 0,
3417            arranged,
3418            key_length,
3419            cardinality: cardinality.map(std::cmp::Reverse),
3420            filters,
3421            input: std::cmp::Reverse(input),
3422        }
3423    }
3424
3425    /// Turns the instance into a String to be printed in EXPLAIN.
3426    pub fn explain(&self) -> String {
3427        let mut e = "".to_owned();
3428        if self.unique_key {
3429            e.push_str("U");
3430        }
3431        // Don't need to print `not_cross`, because that is visible in the printed key.
3432        // if !self.not_cross {
3433        //     e.push_str("C");
3434        // }
3435        for _ in 0..self.key_length {
3436            e.push_str("K");
3437        }
3438        if self.arranged {
3439            e.push_str("A");
3440        }
3441        if let Some(std::cmp::Reverse(cardinality)) = self.cardinality {
3442            e.push_str(&format!("|{cardinality}|"));
3443        }
3444        e.push_str(&self.filters.explain());
3445        e
3446    }
3447}
3448
3449/// Old version of `JoinInputCharacteristics`, with `enable_join_prioritize_arranged` turned off.
3450#[derive(
3451    Eq,
3452    PartialEq,
3453    Ord,
3454    PartialOrd,
3455    Debug,
3456    Clone,
3457    Serialize,
3458    Deserialize,
3459    Hash
3460)]
3461pub struct JoinInputCharacteristicsV1 {
3462    /// An excellent indication that record count will not increase.
3463    pub unique_key: bool,
3464    /// A weaker signal that record count will not increase.
3465    pub key_length: usize,
3466    /// Indicates that there will be no additional in-memory footprint.
3467    pub arranged: bool,
3468    /// Estimated cardinality (lower is better)
3469    pub cardinality: Option<std::cmp::Reverse<usize>>,
3470    /// Characteristics of the filter that is applied at this input.
3471    pub filters: FilterCharacteristics,
3472    /// We want to prefer input earlier in the input list, for stability of ordering.
3473    pub input: std::cmp::Reverse<usize>,
3474}
3475
3476impl JoinInputCharacteristicsV1 {
3477    /// Creates a new instance with the given characteristics.
3478    pub fn new(
3479        unique_key: bool,
3480        key_length: usize,
3481        arranged: bool,
3482        cardinality: Option<usize>,
3483        filters: FilterCharacteristics,
3484        input: usize,
3485    ) -> Self {
3486        Self {
3487            unique_key,
3488            key_length,
3489            arranged,
3490            cardinality: cardinality.map(std::cmp::Reverse),
3491            filters,
3492            input: std::cmp::Reverse(input),
3493        }
3494    }
3495
3496    /// Turns the instance into a String to be printed in EXPLAIN.
3497    pub fn explain(&self) -> String {
3498        let mut e = "".to_owned();
3499        if self.unique_key {
3500            e.push_str("U");
3501        }
3502        for _ in 0..self.key_length {
3503            e.push_str("K");
3504        }
3505        if self.arranged {
3506            e.push_str("A");
3507        }
3508        if let Some(std::cmp::Reverse(cardinality)) = self.cardinality {
3509            e.push_str(&format!("|{cardinality}|"));
3510        }
3511        e.push_str(&self.filters.explain());
3512        e
3513    }
3514}
3515
3516/// Instructions for finishing the result of a query.
3517///
3518/// The primary reason for the existence of this structure and attendant code
3519/// is that SQL's ORDER BY requires sorting rows (as already implied by the
3520/// keywords), whereas much of the rest of SQL is defined in terms of unordered
3521/// multisets. But as it turns out, the same idea can be used to optimize
3522/// trivial peeks.
3523///
3524/// The generic parameters are for accommodating prepared statement parameters in
3525/// `limit` and `offset`: the planner can hold these fields as HirScalarExpr long enough to call
3526/// `bind_parameters` on them.
3527#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3528pub struct RowSetFinishing<L = NonNeg<i64>, O = usize> {
3529    /// Order rows by the given columns.
3530    pub order_by: Vec<ColumnOrder>,
3531    /// Include only as many rows (after offset).
3532    pub limit: Option<L>,
3533    /// Omit as many rows.
3534    pub offset: O,
3535    /// Include only given columns.
3536    pub project: Vec<usize>,
3537}
3538
3539impl<L> RowSetFinishing<L> {
3540    /// Returns a trivial finishing, i.e., that does nothing to the result set.
3541    pub fn trivial(arity: usize) -> RowSetFinishing<L> {
3542        RowSetFinishing {
3543            order_by: Vec::new(),
3544            limit: None,
3545            offset: 0,
3546            project: (0..arity).collect(),
3547        }
3548    }
3549    /// True if the finishing does nothing to any result set.
3550    pub fn is_trivial(&self, arity: usize) -> bool {
3551        self.limit.is_none()
3552            && self.order_by.is_empty()
3553            && self.offset == 0
3554            && self.project.iter().copied().eq(0..arity)
3555    }
3556    /// True if the finishing does not require an ORDER BY.
3557    ///
3558    /// LIMIT and OFFSET without an ORDER BY _are_ streamable: without an
3559    /// explicit ordering we will skip an arbitrary bag of elements and return
3560    /// the first arbitrary elements in the remaining bag. The result semantics
3561    /// are still correct but maybe surprising for some users.
3562    pub fn is_streamable(&self, arity: usize) -> bool {
3563        self.order_by.is_empty() && self.project.iter().copied().eq(0..arity)
3564    }
3565}
3566
3567impl RowSetFinishing<NonNeg<i64>, usize> {
3568    /// The number of rows needed from before the finishing to evaluate the finishing:
3569    /// offset + limit.
3570    ///
3571    /// If it returns None, then we need all the rows.
3572    pub fn num_rows_needed(&self) -> Option<usize> {
3573        self.limit
3574            .as_ref()
3575            .map(|l| usize::cast_from(u64::from(l.clone())) + self.offset)
3576    }
3577}
3578
3579impl RowSetFinishing {
3580    /// Applies finishing actions to a [`RowCollection`], and reports the total
3581    /// time it took to run.
3582    ///
3583    /// Returns a [`RowCollectionIter`] that contains all of the response data, as
3584    /// well as the size of the response in bytes.
3585    pub fn finish(
3586        &self,
3587        rows: RowCollection,
3588        max_result_size: u64,
3589        max_returned_query_size: Option<u64>,
3590        duration_histogram: &Histogram,
3591    ) -> Result<(RowCollectionIter, usize), String> {
3592        let now = Instant::now();
3593        let result = self.finish_inner(rows, max_result_size, max_returned_query_size);
3594        let duration = now.elapsed();
3595        duration_histogram.observe(duration.as_secs_f64());
3596
3597        result
3598    }
3599
3600    /// Implementation for [`RowSetFinishing::finish`].
3601    fn finish_inner(
3602        &self,
3603        rows: RowCollection,
3604        max_result_size: u64,
3605        max_returned_query_size: Option<u64>,
3606    ) -> Result<(RowCollectionIter, usize), String> {
3607        // Bail if the already-materialized collection is larger than the cap.
3608        // `byte_len` includes the per-row offset metadata, and finishing does
3609        // not allocate any additional per-entry structure.
3610        if rows.byte_len() > usize::cast_from(max_result_size) {
3611            let max_bytes = ByteSize::b(max_result_size);
3612            return Err(format!("result exceeds max size of {max_bytes}",));
3613        }
3614
3615        let sorted_view = rows;
3616        let mut iter = sorted_view
3617            .into_row_iter()
3618            .apply_offset(self.offset)
3619            .with_projection(self.project.clone());
3620
3621        if let Some(limit) = self.limit {
3622            let limit = u64::from(limit);
3623            let limit = usize::cast_from(limit);
3624            iter = iter.with_limit(limit);
3625        };
3626
3627        // TODO(parkmycar): Re-think how we can calculate the total response size without
3628        // having to iterate through the entire collection of Rows, while still
3629        // respecting the LIMIT, OFFSET, and projections.
3630        //
3631        // Note: It feels a bit bad always calculating the response size, but we almost
3632        // always need it to either check the `max_returned_query_size`, or for reporting
3633        // in the query history.
3634        let response_size: usize = iter.clone().map(|row| row.data().len()).sum();
3635
3636        // Bail if we would end up returning more data to the client than they can support.
3637        if let Some(max) = max_returned_query_size {
3638            if response_size > usize::cast_from(max) {
3639                let max_bytes = ByteSize::b(max);
3640                return Err(format!("result exceeds max size of {max_bytes}"));
3641            }
3642        }
3643
3644        Ok((iter, response_size))
3645    }
3646}
3647
3648/// A [RowSetFinishing] that can be repeatedly applied to batches of updates (in
3649/// a [RowCollection]) and keeps track of the remaining limit, offset, and cap
3650/// on query result size.
3651#[derive(Debug)]
3652pub struct RowSetFinishingIncremental {
3653    /// Include only as many rows (after offset).
3654    pub remaining_limit: Option<usize>,
3655    /// Omit as many rows.
3656    pub remaining_offset: usize,
3657    /// The maximum allowed result size, as requested by the client.
3658    pub max_returned_query_size: Option<u64>,
3659    /// Tracks our remaining allowed budget for result size.
3660    pub remaining_max_returned_query_size: Option<u64>,
3661    /// Include only given columns.
3662    pub project: Vec<usize>,
3663}
3664
3665impl RowSetFinishingIncremental {
3666    /// Turns the given [RowSetFinishing] into a [RowSetFinishingIncremental].
3667    /// Can only be used when [is_streamable](RowSetFinishing::is_streamable) is
3668    /// `true`.
3669    ///
3670    /// # Panics
3671    ///
3672    /// Panics if the result is not streamable, that is it has an ORDER BY.
3673    pub fn new(
3674        offset: usize,
3675        limit: Option<NonNeg<i64>>,
3676        project: Vec<usize>,
3677        max_returned_query_size: Option<u64>,
3678    ) -> Self {
3679        let limit = limit.map(|l| {
3680            let l = u64::from(l);
3681            let l = usize::cast_from(l);
3682            l
3683        });
3684
3685        RowSetFinishingIncremental {
3686            remaining_limit: limit,
3687            remaining_offset: offset,
3688            max_returned_query_size,
3689            remaining_max_returned_query_size: max_returned_query_size,
3690            project,
3691        }
3692    }
3693
3694    /// Applies finishing actions to the given [`RowCollection`], and reports
3695    /// the total time it took to run.
3696    ///
3697    /// Returns a [`RowCollectionIter`] that contains all of the response
3698    /// data.
3699    pub fn finish_incremental(
3700        &mut self,
3701        rows: RowCollection,
3702        max_result_size: u64,
3703        duration_histogram: &Histogram,
3704    ) -> Result<RowCollectionIter, String> {
3705        let now = Instant::now();
3706        let result = self.finish_incremental_inner(rows, max_result_size);
3707        let duration = now.elapsed();
3708        duration_histogram.observe(duration.as_secs_f64());
3709
3710        result
3711    }
3712
3713    fn finish_incremental_inner(
3714        &mut self,
3715        rows: RowCollection,
3716        max_result_size: u64,
3717    ) -> Result<RowCollectionIter, String> {
3718        // Bail if the already-materialized collection is larger than the cap.
3719        // `byte_len` includes the per-row offset metadata, and finishing does
3720        // not allocate any additional per-entry structure.
3721        if rows.byte_len() > usize::cast_from(max_result_size) {
3722            let max_bytes = ByteSize::b(max_result_size);
3723            return Err(format!("total result exceeds max size of {max_bytes}",));
3724        }
3725
3726        let batch_num_rows = rows.count();
3727
3728        let sorted_view = rows;
3729        let mut iter = sorted_view
3730            .into_row_iter()
3731            .apply_offset(self.remaining_offset)
3732            .with_projection(self.project.clone());
3733
3734        if let Some(limit) = self.remaining_limit {
3735            iter = iter.with_limit(limit);
3736        };
3737
3738        self.remaining_offset = self.remaining_offset.saturating_sub(batch_num_rows);
3739        if let Some(remaining_limit) = self.remaining_limit.as_mut() {
3740            *remaining_limit -= iter.count();
3741        }
3742
3743        // TODO(parkmycar): Re-think how we can calculate the total response size without
3744        // having to iterate through the entire collection of Rows, while still
3745        // respecting the LIMIT, OFFSET, and projections.
3746        //
3747        // Note: It feels a bit bad always calculating the response size, but we almost
3748        // always need it to either check the `max_returned_query_size`, or for reporting
3749        // in the query history.
3750        let response_size: usize = iter.clone().map(|row| row.data().len()).sum();
3751
3752        // Bail if we would end up returning more data to the client than they can support.
3753        if let Some(max) = &mut self.remaining_max_returned_query_size {
3754            if let Some(remaining) = max.checked_sub(response_size.cast_into()) {
3755                *max = remaining;
3756            } else {
3757                let max_bytes = ByteSize::b(self.max_returned_query_size.expect("known to exist"));
3758                return Err(format!("total result exceeds max size of {max_bytes}"));
3759            }
3760        }
3761
3762        Ok(iter)
3763    }
3764}
3765
3766/// Compares two rows columnwise, using [compare_columns].
3767///
3768/// Compared to the naive implementation, this allows sharing some memory and implements some
3769/// optimizations that avoid unnecessary row unpacking.
3770#[derive(Debug, Clone)]
3771pub struct RowComparator<O: AsRef<[ColumnOrder]> = Vec<ColumnOrder>> {
3772    order: O,
3773    /// Invariant: all column references in the order are less than this limit.
3774    /// This allows for partial unpacking of rows.
3775    limit: usize,
3776    left_vec: RefCell<DatumVec>,
3777    right_vec: RefCell<DatumVec>,
3778}
3779
3780impl<O: AsRef<[ColumnOrder]>> RowComparator<O> {
3781    /// Create a new row comparator from the given column ordering.
3782    pub fn new(order: O) -> Self {
3783        let limit = order
3784            .as_ref()
3785            .iter()
3786            .map(|o| o.column + 1)
3787            .max()
3788            .unwrap_or(0);
3789        Self {
3790            order,
3791            limit,
3792            left_vec: Default::default(),
3793            right_vec: Default::default(),
3794        }
3795    }
3796
3797    /// Compare two (references to) rows.
3798    pub fn compare_rows(
3799        &self,
3800        left_row: &RowRef,
3801        right_row: &RowRef,
3802        tiebreaker: impl Fn() -> Ordering,
3803    ) -> Ordering {
3804        let order = if self.limit == 0 {
3805            Ordering::Equal
3806        } else {
3807            // These borrows should never fail, since this struct is non-sync and this function
3808            // is non-recursive.
3809            let mut left_ref = self.left_vec.borrow_mut();
3810            let mut right_ref = self.right_vec.borrow_mut();
3811            let left_cols = left_ref.borrow_with_limit(left_row, self.limit);
3812            let right_cols = right_ref.borrow_with_limit(right_row, self.limit);
3813            compare_columns(self.order.as_ref(), &left_cols, &right_cols, || {
3814                Ordering::Equal
3815            })
3816        };
3817        // Tiebreak without the vecs borrowed, in case that recursively invokes this function.
3818        order.then_with(tiebreaker)
3819    }
3820}
3821
3822/// Compare `left` and `right` using `order`. If that doesn't produce a strict
3823/// ordering, call `tiebreaker`.
3824pub fn compare_columns<F>(
3825    order: &[ColumnOrder],
3826    left: &[Datum],
3827    right: &[Datum],
3828    tiebreaker: F,
3829) -> Ordering
3830where
3831    F: Fn() -> Ordering,
3832{
3833    for order in order {
3834        let cmp = match (&left[order.column], &right[order.column]) {
3835            (Datum::Null, Datum::Null) => Ordering::Equal,
3836            (Datum::Null, _) => {
3837                if order.nulls_last {
3838                    Ordering::Greater
3839                } else {
3840                    Ordering::Less
3841                }
3842            }
3843            (_, Datum::Null) => {
3844                if order.nulls_last {
3845                    Ordering::Less
3846                } else {
3847                    Ordering::Greater
3848                }
3849            }
3850            (lval, rval) => {
3851                if order.desc {
3852                    rval.cmp(lval)
3853                } else {
3854                    lval.cmp(rval)
3855                }
3856            }
3857        };
3858        if cmp != Ordering::Equal {
3859            return cmp;
3860        }
3861    }
3862    tiebreaker()
3863}
3864
3865/// Describe a window frame, e.g. `RANGE UNBOUNDED PRECEDING` or
3866/// `ROWS BETWEEN 5 PRECEDING AND CURRENT ROW`.
3867///
3868/// Window frames define a subset of the partition , and only a subset of
3869/// window functions make use of the window frame.
3870#[derive(
3871    Debug,
3872    Clone,
3873    Eq,
3874    PartialEq,
3875    Ord,
3876    PartialOrd,
3877    Serialize,
3878    Deserialize,
3879    Hash
3880)]
3881pub struct WindowFrame {
3882    /// ROWS, RANGE or GROUPS
3883    pub units: WindowFrameUnits,
3884    /// Where the frame starts
3885    pub start_bound: WindowFrameBound,
3886    /// Where the frame ends
3887    pub end_bound: WindowFrameBound,
3888}
3889
3890impl Display for WindowFrame {
3891    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3892        write!(
3893            f,
3894            "{} between {} and {}",
3895            self.units, self.start_bound, self.end_bound
3896        )
3897    }
3898}
3899
3900impl WindowFrame {
3901    /// Return the default window frame used when one is not explicitly defined
3902    pub fn default() -> Self {
3903        WindowFrame {
3904            units: WindowFrameUnits::Range,
3905            start_bound: WindowFrameBound::UnboundedPreceding,
3906            end_bound: WindowFrameBound::CurrentRow,
3907        }
3908    }
3909
3910    fn includes_current_row(&self) -> bool {
3911        use WindowFrameBound::*;
3912        match self.start_bound {
3913            UnboundedPreceding => match self.end_bound {
3914                UnboundedPreceding => false,
3915                OffsetPreceding(0) => true,
3916                OffsetPreceding(_) => false,
3917                CurrentRow => true,
3918                OffsetFollowing(_) => true,
3919                UnboundedFollowing => true,
3920            },
3921            OffsetPreceding(0) => match self.end_bound {
3922                UnboundedPreceding => unreachable!(),
3923                OffsetPreceding(0) => true,
3924                // Any nonzero offsets here will create an empty window
3925                OffsetPreceding(_) => false,
3926                CurrentRow => true,
3927                OffsetFollowing(_) => true,
3928                UnboundedFollowing => true,
3929            },
3930            OffsetPreceding(_) => match self.end_bound {
3931                UnboundedPreceding => unreachable!(),
3932                // Window ends at the current row
3933                OffsetPreceding(0) => true,
3934                OffsetPreceding(_) => false,
3935                CurrentRow => true,
3936                OffsetFollowing(_) => true,
3937                UnboundedFollowing => true,
3938            },
3939            CurrentRow => true,
3940            OffsetFollowing(0) => match self.end_bound {
3941                UnboundedPreceding => unreachable!(),
3942                OffsetPreceding(_) => unreachable!(),
3943                CurrentRow => unreachable!(),
3944                OffsetFollowing(_) => true,
3945                UnboundedFollowing => true,
3946            },
3947            OffsetFollowing(_) => match self.end_bound {
3948                UnboundedPreceding => unreachable!(),
3949                OffsetPreceding(_) => unreachable!(),
3950                CurrentRow => unreachable!(),
3951                OffsetFollowing(_) => false,
3952                UnboundedFollowing => false,
3953            },
3954            UnboundedFollowing => false,
3955        }
3956    }
3957}
3958
3959/// Describe how frame bounds are interpreted
3960#[derive(
3961    Debug,
3962    Clone,
3963    Eq,
3964    PartialEq,
3965    Ord,
3966    PartialOrd,
3967    Serialize,
3968    Deserialize,
3969    Hash
3970)]
3971pub enum WindowFrameUnits {
3972    /// Each row is treated as the unit of work for bounds
3973    Rows,
3974    /// Each peer group is treated as the unit of work for bounds,
3975    /// and offset-based bounds use the value of the ORDER BY expression
3976    Range,
3977    /// Each peer group is treated as the unit of work for bounds.
3978    /// Groups is currently not supported, and it is rejected during planning.
3979    Groups,
3980}
3981
3982impl Display for WindowFrameUnits {
3983    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3984        match self {
3985            WindowFrameUnits::Rows => write!(f, "rows"),
3986            WindowFrameUnits::Range => write!(f, "range"),
3987            WindowFrameUnits::Groups => write!(f, "groups"),
3988        }
3989    }
3990}
3991
3992/// Specifies [WindowFrame]'s `start_bound` and `end_bound`
3993///
3994/// The order between frame bounds is significant, as Postgres enforces
3995/// some restrictions there.
3996#[derive(
3997    Debug,
3998    Clone,
3999    Serialize,
4000    Deserialize,
4001    PartialEq,
4002    Eq,
4003    Hash,
4004    PartialOrd,
4005    Ord
4006)]
4007pub enum WindowFrameBound {
4008    /// `UNBOUNDED PRECEDING`
4009    UnboundedPreceding,
4010    /// `<N> PRECEDING`
4011    OffsetPreceding(u64),
4012    /// `CURRENT ROW`
4013    CurrentRow,
4014    /// `<N> FOLLOWING`
4015    OffsetFollowing(u64),
4016    /// `UNBOUNDED FOLLOWING`.
4017    UnboundedFollowing,
4018}
4019
4020impl Display for WindowFrameBound {
4021    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
4022        match self {
4023            WindowFrameBound::UnboundedPreceding => write!(f, "unbounded preceding"),
4024            WindowFrameBound::OffsetPreceding(offset) => write!(f, "{} preceding", offset),
4025            WindowFrameBound::CurrentRow => write!(f, "current row"),
4026            WindowFrameBound::OffsetFollowing(offset) => write!(f, "{} following", offset),
4027            WindowFrameBound::UnboundedFollowing => write!(f, "unbounded following"),
4028        }
4029    }
4030}
4031
4032/// Maximum iterations for a LetRec.
4033#[derive(
4034    Debug,
4035    Clone,
4036    Copy,
4037    PartialEq,
4038    Eq,
4039    PartialOrd,
4040    Ord,
4041    Hash,
4042    Serialize,
4043    Deserialize
4044)]
4045pub struct LetRecLimit {
4046    /// Maximum number of iterations to evaluate.
4047    pub max_iters: NonZeroU64,
4048    /// Whether to throw an error when reaching the above limit.
4049    /// If true, we simply use the current contents of each Id as the final result.
4050    pub return_at_limit: bool,
4051}
4052
4053impl LetRecLimit {
4054    /// Compute the smallest limit from a Vec of `LetRecLimit`s.
4055    pub fn min_max_iter(limits: &Vec<Option<LetRecLimit>>) -> Option<u64> {
4056        limits
4057            .iter()
4058            .filter_map(|l| l.as_ref().map(|l| l.max_iters.get()))
4059            .min()
4060    }
4061
4062    /// The default value of `LetRecLimit::return_at_limit` when using the RECURSION LIMIT option of
4063    /// WMR without ERROR AT or RETURN AT.
4064    pub const RETURN_AT_LIMIT_DEFAULT: bool = false;
4065}
4066
4067impl Display for LetRecLimit {
4068    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4069        write!(f, "[recursion_limit={}", self.max_iters)?;
4070        if self.return_at_limit != LetRecLimit::RETURN_AT_LIMIT_DEFAULT {
4071            write!(f, ", return_at_limit")?;
4072        }
4073        write!(f, "]")
4074    }
4075}
4076
4077/// For a global Get, this indicates whether we are going to read from Persist or from an index.
4078/// (See comment in MirRelationExpr::Get.)
4079#[derive(
4080    Clone,
4081    Debug,
4082    Eq,
4083    PartialEq,
4084    Ord,
4085    PartialOrd,
4086    Serialize,
4087    Deserialize,
4088    Hash
4089)]
4090pub enum AccessStrategy {
4091    /// It's either a local Get (a CTE), or unknown at the time.
4092    /// `prune_and_annotate_dataflow_index_imports` decides it for global Gets, and thus switches to
4093    /// one of the other variants.
4094    UnknownOrLocal,
4095    /// The Get will read from Persist.
4096    Persist,
4097    /// The Get will read from an index or indexes: (index id, how the index will be used).
4098    Index(Vec<(GlobalId, IndexUsageType)>),
4099    /// The Get will read a collection that is computed by the same dataflow, but in a different
4100    /// `BuildDesc` in `objects_to_build`.
4101    SameDataflow,
4102}
4103
4104#[cfg(test)]
4105mod tests {
4106    use std::num::NonZeroUsize;
4107
4108    use mz_repr::explain::text::text_string_at;
4109
4110    use crate::explain::HumanizedExplain;
4111
4112    use super::*;
4113
4114    #[mz_ore::test]
4115    fn test_row_set_finishing_as_text() {
4116        let finishing = RowSetFinishing {
4117            order_by: vec![ColumnOrder {
4118                column: 4,
4119                desc: true,
4120                nulls_last: true,
4121            }],
4122            limit: Some(NonNeg::try_from(7).unwrap()),
4123            offset: Default::default(),
4124            project: vec![1, 3, 4, 5],
4125        };
4126
4127        let mode = HumanizedExplain::new(false);
4128        let expr = mode.expr(&finishing, None);
4129
4130        let act = text_string_at(&expr, mz_ore::str::Indent::default);
4131
4132        let exp = {
4133            use mz_ore::fmt::FormatBuffer;
4134            let mut s = String::new();
4135            write!(&mut s, "Finish");
4136            write!(&mut s, " order_by=[#4 desc nulls_last]");
4137            write!(&mut s, " limit=7");
4138            write!(&mut s, " output=[#1, #3..=#5]");
4139            writeln!(&mut s, "");
4140            s
4141        };
4142
4143        assert_eq!(act, exp);
4144    }
4145
4146    #[mz_ore::test]
4147    fn test_row_set_finishing_incremental_max_returned_query_size() {
4148        let row = Row::pack_slice(&[Datum::String("hello")]);
4149        let row_size = u64::cast_from(row.data().len());
4150        let diff = NonZeroUsize::new(1).unwrap();
4151        let batch = RowCollection::new(vec![(row, diff)], &[]);
4152
4153        // Set max_returned_query_size to hold exactly 2 batches worth of rows.
4154        let mut finishing = RowSetFinishingIncremental::new(0, None, vec![0], Some(row_size * 2));
4155
4156        let max_result_size = u64::MAX;
4157
4158        let r = finishing.finish_incremental_inner(batch.clone(), max_result_size);
4159        assert!(r.is_ok());
4160        assert_eq!(finishing.remaining_max_returned_query_size, Some(row_size));
4161
4162        let r = finishing.finish_incremental_inner(batch.clone(), max_result_size);
4163        assert!(r.is_ok());
4164        assert_eq!(finishing.remaining_max_returned_query_size, Some(0));
4165
4166        let r = finishing.finish_incremental_inner(batch, max_result_size);
4167        assert!(r.unwrap_err().contains("total result exceeds max size"));
4168    }
4169}
4170
4171/// An iterator over AST structures, which calls out nodes in difference.
4172///
4173/// The iterators visit two ASTs in tandem, continuing as long as the AST node data matches,
4174/// and yielding an output pair as soon as the AST nodes do not match. Their intent is to call
4175/// attention to the moments in the ASTs where they differ, and incidentally a stack-free way
4176/// to compare two ASTs.
4177mod structured_diff {
4178
4179    use super::MirRelationExpr;
4180    use itertools::Itertools;
4181
4182    ///  An iterator over structured differences between two `MirRelationExpr` instances.
4183    pub struct MreDiff<'a> {
4184        /// Pairs of expressions that must still be compared.
4185        todo: Vec<(&'a MirRelationExpr, &'a MirRelationExpr)>,
4186    }
4187
4188    impl<'a> MreDiff<'a> {
4189        /// Create a new `MirRelationExpr` structured difference.
4190        pub fn new(expr1: &'a MirRelationExpr, expr2: &'a MirRelationExpr) -> Self {
4191            MreDiff {
4192                todo: vec![(expr1, expr2)],
4193            }
4194        }
4195    }
4196
4197    impl<'a> Iterator for MreDiff<'a> {
4198        // Pairs of expressions that do not match.
4199        type Item = (&'a MirRelationExpr, &'a MirRelationExpr);
4200
4201        fn next(&mut self) -> Option<Self::Item> {
4202            while let Some((expr1, expr2)) = self.todo.pop() {
4203                match (expr1, expr2) {
4204                    (
4205                        MirRelationExpr::Constant {
4206                            rows: rows1,
4207                            typ: typ1,
4208                        },
4209                        MirRelationExpr::Constant {
4210                            rows: rows2,
4211                            typ: typ2,
4212                        },
4213                    ) => {
4214                        if rows1 != rows2 || typ1 != typ2 {
4215                            return Some((expr1, expr2));
4216                        }
4217                    }
4218                    (
4219                        MirRelationExpr::Get {
4220                            id: id1,
4221                            typ: typ1,
4222                            access_strategy: as1,
4223                        },
4224                        MirRelationExpr::Get {
4225                            id: id2,
4226                            typ: typ2,
4227                            access_strategy: as2,
4228                        },
4229                    ) => {
4230                        if id1 != id2 || typ1 != typ2 || as1 != as2 {
4231                            return Some((expr1, expr2));
4232                        }
4233                    }
4234                    (
4235                        MirRelationExpr::Let {
4236                            id: id1,
4237                            body: body1,
4238                            value: value1,
4239                        },
4240                        MirRelationExpr::Let {
4241                            id: id2,
4242                            body: body2,
4243                            value: value2,
4244                        },
4245                    ) => {
4246                        if id1 != id2 {
4247                            return Some((expr1, expr2));
4248                        } else {
4249                            self.todo.push((body1, body2));
4250                            self.todo.push((value1, value2));
4251                        }
4252                    }
4253                    (
4254                        MirRelationExpr::LetRec {
4255                            ids: ids1,
4256                            body: body1,
4257                            values: values1,
4258                            limits: limits1,
4259                        },
4260                        MirRelationExpr::LetRec {
4261                            ids: ids2,
4262                            body: body2,
4263                            values: values2,
4264                            limits: limits2,
4265                        },
4266                    ) => {
4267                        if ids1 != ids2 || values1.len() != values2.len() || limits1 != limits2 {
4268                            return Some((expr1, expr2));
4269                        } else {
4270                            self.todo.push((body1, body2));
4271                            self.todo.extend(values1.iter().zip_eq(values2.iter()));
4272                        }
4273                    }
4274                    (
4275                        MirRelationExpr::Project {
4276                            outputs: outputs1,
4277                            input: input1,
4278                        },
4279                        MirRelationExpr::Project {
4280                            outputs: outputs2,
4281                            input: input2,
4282                        },
4283                    ) => {
4284                        if outputs1 != outputs2 {
4285                            return Some((expr1, expr2));
4286                        } else {
4287                            self.todo.push((input1, input2));
4288                        }
4289                    }
4290                    (
4291                        MirRelationExpr::Map {
4292                            scalars: scalars1,
4293                            input: input1,
4294                        },
4295                        MirRelationExpr::Map {
4296                            scalars: scalars2,
4297                            input: input2,
4298                        },
4299                    ) => {
4300                        if scalars1 != scalars2 {
4301                            return Some((expr1, expr2));
4302                        } else {
4303                            self.todo.push((input1, input2));
4304                        }
4305                    }
4306                    (
4307                        MirRelationExpr::Filter {
4308                            predicates: predicates1,
4309                            input: input1,
4310                        },
4311                        MirRelationExpr::Filter {
4312                            predicates: predicates2,
4313                            input: input2,
4314                        },
4315                    ) => {
4316                        if predicates1 != predicates2 {
4317                            return Some((expr1, expr2));
4318                        } else {
4319                            self.todo.push((input1, input2));
4320                        }
4321                    }
4322                    (
4323                        MirRelationExpr::FlatMap {
4324                            input: input1,
4325                            func: func1,
4326                            exprs: exprs1,
4327                        },
4328                        MirRelationExpr::FlatMap {
4329                            input: input2,
4330                            func: func2,
4331                            exprs: exprs2,
4332                        },
4333                    ) => {
4334                        if func1 != func2 || exprs1 != exprs2 {
4335                            return Some((expr1, expr2));
4336                        } else {
4337                            self.todo.push((input1, input2));
4338                        }
4339                    }
4340                    (
4341                        MirRelationExpr::Join {
4342                            inputs: inputs1,
4343                            equivalences: eq1,
4344                            implementation: impl1,
4345                        },
4346                        MirRelationExpr::Join {
4347                            inputs: inputs2,
4348                            equivalences: eq2,
4349                            implementation: impl2,
4350                        },
4351                    ) => {
4352                        if inputs1.len() != inputs2.len() || eq1 != eq2 || impl1 != impl2 {
4353                            return Some((expr1, expr2));
4354                        } else {
4355                            self.todo.extend(inputs1.iter().zip_eq(inputs2.iter()));
4356                        }
4357                    }
4358                    (
4359                        MirRelationExpr::Reduce {
4360                            aggregates: aggregates1,
4361                            input: inputs1,
4362                            group_key: gk1,
4363                            monotonic: m1,
4364                            expected_group_size: egs1,
4365                        },
4366                        MirRelationExpr::Reduce {
4367                            aggregates: aggregates2,
4368                            input: inputs2,
4369                            group_key: gk2,
4370                            monotonic: m2,
4371                            expected_group_size: egs2,
4372                        },
4373                    ) => {
4374                        if aggregates1 != aggregates2 || gk1 != gk2 || m1 != m2 || egs1 != egs2 {
4375                            return Some((expr1, expr2));
4376                        } else {
4377                            self.todo.push((inputs1, inputs2));
4378                        }
4379                    }
4380                    (
4381                        MirRelationExpr::TopK {
4382                            group_key: gk1,
4383                            order_key: order1,
4384                            input: input1,
4385                            limit: l1,
4386                            offset: o1,
4387                            monotonic: m1,
4388                            expected_group_size: egs1,
4389                        },
4390                        MirRelationExpr::TopK {
4391                            group_key: gk2,
4392                            order_key: order2,
4393                            input: input2,
4394                            limit: l2,
4395                            offset: o2,
4396                            monotonic: m2,
4397                            expected_group_size: egs2,
4398                        },
4399                    ) => {
4400                        if order1 != order2
4401                            || gk1 != gk2
4402                            || l1 != l2
4403                            || o1 != o2
4404                            || m1 != m2
4405                            || egs1 != egs2
4406                        {
4407                            return Some((expr1, expr2));
4408                        } else {
4409                            self.todo.push((input1, input2));
4410                        }
4411                    }
4412                    (
4413                        MirRelationExpr::Negate { input: input1 },
4414                        MirRelationExpr::Negate { input: input2 },
4415                    ) => {
4416                        self.todo.push((input1, input2));
4417                    }
4418                    (
4419                        MirRelationExpr::Threshold { input: input1 },
4420                        MirRelationExpr::Threshold { input: input2 },
4421                    ) => {
4422                        self.todo.push((input1, input2));
4423                    }
4424                    (
4425                        MirRelationExpr::Union {
4426                            base: base1,
4427                            inputs: inputs1,
4428                        },
4429                        MirRelationExpr::Union {
4430                            base: base2,
4431                            inputs: inputs2,
4432                        },
4433                    ) => {
4434                        if inputs1.len() != inputs2.len() {
4435                            return Some((expr1, expr2));
4436                        } else {
4437                            self.todo.push((base1, base2));
4438                            self.todo.extend(inputs1.iter().zip_eq(inputs2.iter()));
4439                        }
4440                    }
4441                    (
4442                        MirRelationExpr::ArrangeBy {
4443                            keys: keys1,
4444                            input: input1,
4445                        },
4446                        MirRelationExpr::ArrangeBy {
4447                            keys: keys2,
4448                            input: input2,
4449                        },
4450                    ) => {
4451                        if keys1 != keys2 {
4452                            return Some((expr1, expr2));
4453                        } else {
4454                            self.todo.push((input1, input2));
4455                        }
4456                    }
4457                    _ => {
4458                        return Some((expr1, expr2));
4459                    }
4460                }
4461            }
4462            None
4463        }
4464    }
4465}