Skip to main content

mz_expr/relation/
func.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#![allow(missing_docs)]
11
12use std::cmp::{max, min};
13use std::iter::Sum;
14use std::ops::Deref;
15use std::str::FromStr;
16use std::{fmt, iter};
17
18use chrono::{DateTime, NaiveDateTime, NaiveTime, Utc};
19use dec::OrderedDecimal;
20use itertools::{Either, Itertools};
21use mz_ore::cast::CastFrom;
22
23use mz_ore::str::separated;
24use mz_ore::{soft_assert_eq_no_log, soft_assert_or_log};
25use mz_repr::adt::array::ArrayDimension;
26use mz_repr::adt::date::Date;
27use mz_repr::adt::interval::Interval;
28use mz_repr::adt::numeric::{self, Numeric, NumericMaxScale};
29use mz_repr::adt::regex::{Regex as ReprRegex, RegexCompilationError};
30use mz_repr::adt::timestamp::{CheckedTimestamp, TimestampLike};
31use mz_repr::{
32    ColumnName, Datum, Diff, ReprColumnType, ReprRelationType, Row, RowArena, RowPacker, SharedRow,
33    SqlColumnType, SqlRelationType, SqlScalarType, datum_size,
34};
35use num::{CheckedAdd, Integer, Signed, ToPrimitive};
36use ordered_float::OrderedFloat;
37use regex::Regex;
38use serde::{Deserialize, Serialize};
39use smallvec::SmallVec;
40
41use crate::EvalError;
42use crate::WindowFrameBound::{
43    CurrentRow, OffsetFollowing, OffsetPreceding, UnboundedFollowing, UnboundedPreceding,
44};
45use crate::WindowFrameUnits::{Groups, Range, Rows};
46use crate::explain::{HumanizedExpr, HumanizerMode};
47use crate::relation::{
48    ColumnOrder, WindowFrame, WindowFrameBound, WindowFrameUnits, compare_columns,
49};
50use crate::scalar::func::{add_timestamp_months, jsonb_stringify};
51
52// TODO(jamii) be careful about overflow in sum/avg
53// see https://timely.zulipchat.com/#narrow/stream/186635-engineering/topic/additional.20work/near/163507435
54
55fn max_string<'a, I>(datums: I) -> Datum<'a>
56where
57    I: IntoIterator<Item = Datum<'a>>,
58{
59    match datums
60        .into_iter()
61        .filter(|d| !d.is_null())
62        .max_by(|a, b| a.unwrap_str().cmp(b.unwrap_str()))
63    {
64        Some(datum) => datum,
65        None => Datum::Null,
66    }
67}
68
69fn max_datum<'a, I, DatumType>(datums: I) -> Datum<'a>
70where
71    I: IntoIterator<Item = Datum<'a>>,
72    DatumType: TryFrom<Datum<'a>> + Ord,
73    <DatumType as TryFrom<Datum<'a>>>::Error: std::fmt::Debug,
74    Datum<'a>: From<Option<DatumType>>,
75{
76    let x: Option<DatumType> = datums
77        .into_iter()
78        .filter(|d| !d.is_null())
79        .map(|d| DatumType::try_from(d).expect("unexpected type"))
80        .max();
81
82    x.into()
83}
84
85fn min_datum<'a, I, DatumType>(datums: I) -> Datum<'a>
86where
87    I: IntoIterator<Item = Datum<'a>>,
88    DatumType: TryFrom<Datum<'a>> + Ord,
89    <DatumType as TryFrom<Datum<'a>>>::Error: std::fmt::Debug,
90    Datum<'a>: From<Option<DatumType>>,
91{
92    let x: Option<DatumType> = datums
93        .into_iter()
94        .filter(|d| !d.is_null())
95        .map(|d| DatumType::try_from(d).expect("unexpected type"))
96        .min();
97
98    x.into()
99}
100
101fn min_string<'a, I>(datums: I) -> Datum<'a>
102where
103    I: IntoIterator<Item = Datum<'a>>,
104{
105    match datums
106        .into_iter()
107        .filter(|d| !d.is_null())
108        .min_by(|a, b| a.unwrap_str().cmp(b.unwrap_str()))
109    {
110        Some(datum) => datum,
111        None => Datum::Null,
112    }
113}
114
115fn sum_datum<'a, I, DatumType, ResultType>(datums: I) -> Datum<'a>
116where
117    I: IntoIterator<Item = Datum<'a>>,
118    DatumType: TryFrom<Datum<'a>>,
119    <DatumType as TryFrom<Datum<'a>>>::Error: std::fmt::Debug,
120    ResultType: From<DatumType> + Sum + Into<Datum<'a>>,
121{
122    let mut datums = datums.into_iter().filter(|d| !d.is_null()).peekable();
123    if datums.peek().is_none() {
124        Datum::Null
125    } else {
126        let x = datums
127            .map(|d| ResultType::from(DatumType::try_from(d).expect("unexpected type")))
128            .sum::<ResultType>();
129        x.into()
130    }
131}
132
133/// Count-aware signed-integer sum. Accumulates `Σ value·diff` in `i128`, which
134/// matches the width of the dataflow's `Accum::SimpleNumber` accumulator (see
135/// `build_accumulable` and `finalize_accum` in `mz_compute::render::reduce`);
136/// `narrow` then reproduces that variant's `finalize_accum` arm. Unlike
137/// `expand_counts`, this consumes the multiplicity directly, so it is linear in
138/// the number of distinct values and correct for negative diffs (retractions),
139/// which `expand_counts` would silently drop.
140///
141/// Returns `Datum::Null` when no non-null value was accumulated, matching
142/// `finalize_accum`'s null handling: its `is_zero` check on `SimpleNumber`
143/// requires both a zero running sum and a zero non-null count.
144fn sum_signed_int_counted<'a, I, N>(datums: I, narrow: N) -> Datum<'a>
145where
146    I: IntoIterator<Item = (Datum<'a>, Diff)>,
147    N: FnOnce(i128) -> Datum<'a>,
148{
149    let mut accum: i128 = 0;
150    let mut non_nulls = Diff::ZERO;
151    for (datum, diff) in datums {
152        if datum.is_null() {
153            continue;
154        }
155        let value = match datum {
156            Datum::Int16(i) => i128::from(i),
157            Datum::Int32(i) => i128::from(i),
158            Datum::Int64(i) => i128::from(i),
159            other => panic!("unexpected non-integer datum in signed sum: {other:?}"),
160        };
161        // The dataflow accumulates `value * diff` in an `Overflowing<i128>`; we
162        // mirror that. Genuine i128 overflow would require summands far beyond
163        // any realistic input, so wrapping matches the dataflow's production
164        // behavior.
165        accum = accum.wrapping_add(value.wrapping_mul(i128::from(diff.into_inner())));
166        non_nulls += diff;
167    }
168    if accum == 0 && non_nulls.is_zero() {
169        Datum::Null
170    } else {
171        narrow(accum)
172    }
173}
174
175fn sum_numeric<'a, I>(datums: I) -> Datum<'a>
176where
177    I: IntoIterator<Item = Datum<'a>>,
178{
179    let mut cx = numeric::cx_datum();
180    let mut sum = Numeric::zero();
181    let mut empty = true;
182    for d in datums {
183        if !d.is_null() {
184            empty = false;
185            cx.add(&mut sum, &d.unwrap_numeric().0);
186        }
187    }
188    match empty {
189        true => Datum::Null,
190        false => Datum::from(sum),
191    }
192}
193
194/// Sums intervals component-wise, as PostgreSQL's interval addition does:
195/// months, days, and microseconds each accumulate on their own, and nothing is
196/// carried from a coarser component into a finer one.
197fn sum_interval<'a, I>(datums: I) -> Datum<'a>
198where
199    I: IntoIterator<Item = Datum<'a>>,
200{
201    sum_interval_counted(datums.into_iter().map(|datum| (datum, Diff::ONE)))
202}
203
204/// Count-aware interval sum. Accumulates `Σ value·diff` per interval component
205/// in `i128`, which matches `Accum::Interval` in `mz_compute::render::reduce`;
206/// the narrowing back to the `Interval` field widths reproduces that variant's
207/// `finalize_accum` arm. Consuming the multiplicity directly keeps this linear
208/// in the number of distinct values and correct for negative diffs
209/// (retractions), which `expand_counts` would silently drop.
210///
211/// A sum whose components exceed the `Interval` field widths is a query error
212/// only where the aggregate renders as an accumulable reduce, because that is
213/// the only rendering that pairs `finalize_accum` with `AccumulableErrorCheck`.
214/// This function and `finalize_accum` both return a bare `Datum`, so every
215/// other caller (constant folding, and window aggregates, which arrive through
216/// `eval` for whole-partition frames and through `AccumulableOneByOneAggr`
217/// otherwise) yields `Datum::Null` on overflow, which a reader cannot tell
218/// apart from an all-null input. `SumUInt*` has the same split today for
219/// negative accumulations. Closing it means giving aggregate evaluation an
220/// error channel.
221///
222/// Returns `Datum::Null` when no non-null value was accumulated, matching
223/// `finalize_accum`'s null handling: its `is_zero` check on `Accum::Interval`
224/// requires all three running sums and the non-null count to be zero.
225fn sum_interval_counted<'a, I>(datums: I) -> Datum<'a>
226where
227    I: IntoIterator<Item = (Datum<'a>, Diff)>,
228{
229    let (mut months, mut days, mut micros) = (0i128, 0i128, 0i128);
230    let mut non_nulls = Diff::ZERO;
231    for (datum, diff) in datums {
232        if datum.is_null() {
233            continue;
234        }
235        let interval = datum.unwrap_interval();
236        // The dataflow accumulates each component in an `Overflowing<i128>`; we
237        // mirror that. Genuine i128 overflow would require summands far beyond
238        // any realistic input, so wrapping matches the dataflow's production
239        // behavior.
240        let scale = i128::from(diff.into_inner());
241        months = months.wrapping_add(i128::from(interval.months).wrapping_mul(scale));
242        days = days.wrapping_add(i128::from(interval.days).wrapping_mul(scale));
243        micros = micros.wrapping_add(i128::from(interval.micros).wrapping_mul(scale));
244        non_nulls += diff;
245    }
246    if months == 0 && days == 0 && micros == 0 && non_nulls.is_zero() {
247        return Datum::Null;
248    }
249    match Interval::try_new(months, days, micros) {
250        Some(interval) => Datum::Interval(interval),
251        None => Datum::Null,
252    }
253}
254
255fn count<'a, I>(datums: I) -> Datum<'a>
256where
257    I: IntoIterator<Item = (Datum<'a>, Diff)>,
258{
259    // Count is accumulable: rather than expand each `(datum, diff)` into `diff`
260    // copies and count them, we sum the diffs directly. A net-negative count is
261    // possible (the surface does not define behavior in that case) and surfaces
262    // here as a negative result.
263    // TODO(jkosh44) This should error when the count can't fit inside of an `i64` instead of returning a negative result.
264    let mut count = Diff::ZERO;
265    for (datum, diff) in datums {
266        if !datum.is_null() {
267            count += diff;
268        }
269    }
270    Datum::from(count.into_inner())
271}
272
273fn any<'a, I>(datums: I) -> Datum<'a>
274where
275    I: IntoIterator<Item = Datum<'a>>,
276{
277    datums
278        .into_iter()
279        .fold(Datum::False, |state, next| match (state, next) {
280            (Datum::True, _) | (_, Datum::True) => Datum::True,
281            (Datum::Null, _) | (_, Datum::Null) => Datum::Null,
282            _ => Datum::False,
283        })
284}
285
286fn all<'a, I>(datums: I) -> Datum<'a>
287where
288    I: IntoIterator<Item = Datum<'a>>,
289{
290    datums
291        .into_iter()
292        .fold(Datum::True, |state, next| match (state, next) {
293            (Datum::False, _) | (_, Datum::False) => Datum::False,
294            (Datum::Null, _) | (_, Datum::Null) => Datum::Null,
295            _ => Datum::True,
296        })
297}
298
299fn string_agg<'a, I>(datums: I, temp_storage: &'a RowArena, order_by: &[ColumnOrder]) -> Datum<'a>
300where
301    I: IntoIterator<Item = Datum<'a>>,
302{
303    const EMPTY_SEP: &str = "";
304
305    let datums = order_aggregate_datums(datums, order_by);
306    let mut sep_value_pairs = datums.into_iter().filter_map(|d| {
307        if d.is_null() {
308            return None;
309        }
310        let mut value_sep = d.unwrap_list().iter();
311        match (value_sep.next().unwrap(), value_sep.next().unwrap()) {
312            (Datum::Null, _) => None,
313            (Datum::String(val), Datum::Null) => Some((EMPTY_SEP, val)),
314            (Datum::String(val), Datum::String(sep)) => Some((sep, val)),
315            _ => unreachable!(),
316        }
317    });
318
319    let mut s = String::default();
320    match sep_value_pairs.next() {
321        // First value not prefixed by its separator
322        Some((_, value)) => s.push_str(value),
323        // If no non-null values sent, return NULL.
324        None => return Datum::Null,
325    }
326
327    for (sep, value) in sep_value_pairs {
328        s.push_str(sep);
329        s.push_str(value);
330    }
331
332    Datum::String(temp_storage.push_string(s))
333}
334
335fn jsonb_agg<'a, I>(datums: I, temp_storage: &'a RowArena, order_by: &[ColumnOrder]) -> Datum<'a>
336where
337    I: IntoIterator<Item = Datum<'a>>,
338{
339    let datums = order_aggregate_datums(datums, order_by);
340    temp_storage.make_datum(|packer| {
341        packer.push_list(datums.into_iter().filter(|d| !d.is_null()));
342    })
343}
344
345fn dict_agg<'a, I>(datums: I, temp_storage: &'a RowArena, order_by: &[ColumnOrder]) -> Datum<'a>
346where
347    I: IntoIterator<Item = Datum<'a>>,
348{
349    let datums = order_aggregate_datums(datums, order_by);
350    temp_storage.make_datum(|packer| {
351        let mut datums: Vec<_> = datums
352            .into_iter()
353            .filter_map(|d| {
354                if d.is_null() {
355                    return None;
356                }
357                let mut list = d.unwrap_list().iter();
358                let key = list.next().unwrap();
359                let val = list.next().unwrap();
360                if key.is_null() {
361                    // TODO(benesch): this should produce an error, but
362                    // aggregate functions cannot presently produce errors.
363                    None
364                } else {
365                    Some((key.unwrap_str(), val))
366                }
367            })
368            .collect();
369        // datums are ordered by any ORDER BY clause now, and we want to preserve
370        // the last entry for each key, but we also need to present unique and sorted
371        // keys to push_dict. Use sort_by here, which is stable, and so will preserve
372        // the ORDER BY order. Then reverse and dedup to retain the last of each
373        // key. Reverse again so we're back in push_dict order.
374        datums.sort_by_key(|(k, _v)| *k);
375        datums.reverse();
376        datums.dedup_by_key(|(k, _v)| *k);
377        datums.reverse();
378        packer.push_dict(datums);
379    })
380}
381
382/// Assuming datums is a List, sort them by the 2nd through Nth elements
383/// corresponding to order_by, then return the 1st element.
384///
385/// Near the usages of this function, we sometimes want to produce Datums with a shorter lifetime
386/// than 'a. We have to actually perform the shortening of the lifetime here, inside this function,
387/// because if we were to simply return `impl Iterator<Item = Datum<'a>>`, that wouldn't be
388/// covariant in the item type, because opaque types are always invariant. (Contrast this with how
389/// we perform the shortening _inside_ this function: the input of the `map` is known to
390/// specifically be `std::vec::IntoIter`, which is known to be covariant.)
391pub fn order_aggregate_datums<'a: 'b, 'b, I>(
392    datums: I,
393    order_by: &[ColumnOrder],
394) -> impl Iterator<Item = Datum<'b>>
395where
396    I: IntoIterator<Item = Datum<'a>>,
397{
398    order_aggregate_datums_with_rank_inner(datums, order_by)
399        .into_iter()
400        // (`payload` is coerced here to `Datum<'b>` in the argument of the closure)
401        .map(|(payload, _order_datums)| payload)
402}
403
404/// Assuming datums is a List, sort them by the 2nd through Nth elements
405/// corresponding to order_by, then return the 1st element and computed order by expression.
406fn order_aggregate_datums_with_rank<'a, I>(
407    datums: I,
408    order_by: &[ColumnOrder],
409) -> impl Iterator<Item = (Datum<'a>, Row)>
410where
411    I: IntoIterator<Item = Datum<'a>>,
412{
413    order_aggregate_datums_with_rank_inner(datums, order_by)
414        .into_iter()
415        .map(|(payload, order_by_datums)| (payload, Row::pack(order_by_datums)))
416}
417
418fn order_aggregate_datums_with_rank_inner<'a, I>(
419    datums: I,
420    order_by: &[ColumnOrder],
421) -> Vec<(Datum<'a>, Vec<Datum<'a>>)>
422where
423    I: IntoIterator<Item = Datum<'a>>,
424{
425    let mut decoded: Vec<(Datum, Vec<Datum>)> = datums
426        .into_iter()
427        .map(|d| {
428            let list = d.unwrap_list();
429            let mut list_it = list.iter();
430            let payload = list_it.next().unwrap();
431
432            // We decode the order_by Datums here instead of the comparison function, because the
433            // comparison function is expected to be called `O(log n)` times on each input row.
434            // The only downside is that the decoded data might be bigger, but I think that's fine,
435            // because:
436            // - if we have a window partition so big that this would create a memory problem, then
437            //   the non-incrementalness of window functions will create a serious CPU problem
438            //   anyway,
439            // - and anyhow various other parts of the window function code already do decoding
440            //   upfront.
441            let mut order_by_datums = Vec::with_capacity(order_by.len());
442            for _ in 0..order_by.len() {
443                order_by_datums.push(
444                    list_it
445                        .next()
446                        .expect("must have exactly the same number of Datums as `order_by`"),
447                );
448            }
449
450            (payload, order_by_datums)
451        })
452        .collect();
453
454    let mut sort_by =
455        |(payload_left, left_order_by_datums): &(Datum, Vec<Datum>),
456         (payload_right, right_order_by_datums): &(Datum, Vec<Datum>)| {
457            compare_columns(
458                order_by,
459                left_order_by_datums,
460                right_order_by_datums,
461                || payload_left.cmp(payload_right),
462            )
463        };
464    // `sort_unstable_by` can be faster and uses less memory than `sort_by`. An unstable sort is
465    // enough here, because if two elements are equal in our `compare` function, then the elements
466    // are actually binary-equal (because of the `tiebreaker` given to `compare_columns`), so it
467    // doesn't matter what order they end up in.
468    decoded.sort_unstable_by(&mut sort_by);
469    decoded
470}
471
472fn array_concat<'a, I>(datums: I, temp_storage: &'a RowArena, order_by: &[ColumnOrder]) -> Datum<'a>
473where
474    I: IntoIterator<Item = Datum<'a>>,
475{
476    let datums = order_aggregate_datums(datums, order_by);
477    let datums: Vec<_> = datums
478        .into_iter()
479        .map(|d| d.unwrap_array().elements().iter())
480        .flatten()
481        .collect();
482    let dims = ArrayDimension {
483        lower_bound: 1,
484        length: datums.len(),
485    };
486    temp_storage.make_datum(|packer| {
487        packer.try_push_array(&[dims], datums).unwrap();
488    })
489}
490
491fn list_concat<'a, I>(datums: I, temp_storage: &'a RowArena, order_by: &[ColumnOrder]) -> Datum<'a>
492where
493    I: IntoIterator<Item = Datum<'a>>,
494{
495    let datums = order_aggregate_datums(datums, order_by);
496    temp_storage.make_datum(|packer| {
497        packer.push_list(datums.into_iter().map(|d| d.unwrap_list().iter()).flatten());
498    })
499}
500
501/// The expected input is in the format of `[((OriginalRow, [EncodedArgs]), OrderByExprs...)]`
502/// The output is in the format of `[result_value, original_row]`.
503/// See an example at `lag_lead`, where the input-output formats are similar.
504fn row_number<'a, I>(
505    datums: I,
506    callers_temp_storage: &'a RowArena,
507    order_by: &[ColumnOrder],
508) -> Datum<'a>
509where
510    I: IntoIterator<Item = Datum<'a>>,
511{
512    // We want to use our own temp_storage here, to avoid flooding `callers_temp_storage` with a
513    // large number of new datums. This is because we don't want to make an assumption about
514    // whether the caller creates a new temp_storage between window partitions.
515    let temp_storage = RowArena::new();
516    let datums = row_number_no_list(datums, &temp_storage, order_by);
517
518    callers_temp_storage.make_datum(|packer| {
519        packer.push_list(datums);
520    })
521}
522
523/// Like `row_number`, but doesn't perform the final wrapping in a list, returning an Iterator
524/// instead.
525fn row_number_no_list<'a: 'b, 'b, I>(
526    datums: I,
527    callers_temp_storage: &'b RowArena,
528    order_by: &[ColumnOrder],
529) -> impl Iterator<Item = Datum<'b>>
530where
531    I: IntoIterator<Item = Datum<'a>>,
532{
533    let datums = order_aggregate_datums(datums, order_by);
534
535    callers_temp_storage.reserve(datums.size_hint().0);
536    #[allow(clippy::disallowed_methods)]
537    datums
538        .into_iter()
539        .map(|d| d.unwrap_list().iter())
540        .flatten()
541        .zip(1i64..)
542        .map(|(d, i)| {
543            callers_temp_storage.make_datum(|packer| {
544                packer.push_list_with(|packer| {
545                    packer.push(Datum::Int64(i));
546                    packer.push(d);
547                });
548            })
549        })
550}
551
552/// The expected input is in the format of `[((OriginalRow, [EncodedArgs]), OrderByExprs...)]`
553/// The output is in the format of `[result_value, original_row]`.
554/// See an example at `lag_lead`, where the input-output formats are similar.
555fn rank<'a, I>(datums: I, callers_temp_storage: &'a RowArena, order_by: &[ColumnOrder]) -> Datum<'a>
556where
557    I: IntoIterator<Item = Datum<'a>>,
558{
559    let temp_storage = RowArena::new();
560    let datums = rank_no_list(datums, &temp_storage, order_by);
561
562    callers_temp_storage.make_datum(|packer| {
563        packer.push_list(datums);
564    })
565}
566
567/// Like `rank`, but doesn't perform the final wrapping in a list, returning an Iterator
568/// instead.
569fn rank_no_list<'a: 'b, 'b, I>(
570    datums: I,
571    callers_temp_storage: &'b RowArena,
572    order_by: &[ColumnOrder],
573) -> impl Iterator<Item = Datum<'b>>
574where
575    I: IntoIterator<Item = Datum<'a>>,
576{
577    // Keep the row used for ordering around, as it is used to determine the rank
578    let datums = order_aggregate_datums_with_rank(datums, order_by);
579
580    let mut datums = datums
581        .into_iter()
582        .map(|(d0, order_row)| {
583            d0.unwrap_list()
584                .iter()
585                .map(move |d1| (d1, order_row.clone()))
586        })
587        .flatten();
588
589    callers_temp_storage.reserve(datums.size_hint().0);
590    datums
591        .next()
592        .map_or(vec![], |(first_datum, first_order_row)| {
593            // Folding with (last order_by row, last assigned rank,
594            // row number, output vec)
595            datums.fold(
596                (first_order_row, 1, 1, vec![(first_datum, 1)]),
597                |mut acc, (next_datum, next_order_row)| {
598                let (ref mut acc_row, ref mut acc_rank, ref mut acc_row_num, ref mut output) = acc;
599                *acc_row_num += 1;
600                // Identity is based on the order_by expression
601                if *acc_row != next_order_row {
602                    *acc_rank = *acc_row_num;
603                    *acc_row = next_order_row;
604                }
605
606                (*output).push((next_datum, *acc_rank));
607                acc
608            })
609        }.3).into_iter().map(|(d, i)| {
610        callers_temp_storage.make_datum(|packer| {
611            packer.push_list_with(|packer| {
612                packer.push(Datum::Int64(i));
613                packer.push(d);
614            });
615        })
616    })
617}
618
619/// The expected input is in the format of `[((OriginalRow, [EncodedArgs]), OrderByExprs...)]`
620/// The output is in the format of `[result_value, original_row]`.
621/// See an example at `lag_lead`, where the input-output formats are similar.
622fn dense_rank<'a, I>(
623    datums: I,
624    callers_temp_storage: &'a RowArena,
625    order_by: &[ColumnOrder],
626) -> Datum<'a>
627where
628    I: IntoIterator<Item = Datum<'a>>,
629{
630    let temp_storage = RowArena::new();
631    let datums = dense_rank_no_list(datums, &temp_storage, order_by);
632
633    callers_temp_storage.make_datum(|packer| {
634        packer.push_list(datums);
635    })
636}
637
638/// Like `dense_rank`, but doesn't perform the final wrapping in a list, returning an Iterator
639/// instead.
640fn dense_rank_no_list<'a: 'b, 'b, I>(
641    datums: I,
642    callers_temp_storage: &'b RowArena,
643    order_by: &[ColumnOrder],
644) -> impl Iterator<Item = Datum<'b>>
645where
646    I: IntoIterator<Item = Datum<'a>>,
647{
648    // Keep the row used for ordering around, as it is used to determine the rank
649    let datums = order_aggregate_datums_with_rank(datums, order_by);
650
651    let mut datums = datums
652        .into_iter()
653        .map(|(d0, order_row)| {
654            d0.unwrap_list()
655                .iter()
656                .map(move |d1| (d1, order_row.clone()))
657        })
658        .flatten();
659
660    callers_temp_storage.reserve(datums.size_hint().0);
661    datums
662        .next()
663        .map_or(vec![], |(first_datum, first_order_row)| {
664            // Folding with (last order_by row, last assigned rank,
665            // output vec)
666            datums.fold(
667                (first_order_row, 1, vec![(first_datum, 1)]),
668                |mut acc, (next_datum, next_order_row)| {
669                let (ref mut acc_row, ref mut acc_rank, ref mut output) = acc;
670                // Identity is based on the order_by expression
671                if *acc_row != next_order_row {
672                    *acc_rank += 1;
673                    *acc_row = next_order_row;
674                }
675
676                (*output).push((next_datum, *acc_rank));
677                acc
678            })
679        }.2).into_iter().map(|(d, i)| {
680        callers_temp_storage.make_datum(|packer| {
681            packer.push_list_with(|packer| {
682                packer.push(Datum::Int64(i));
683                packer.push(d);
684            });
685        })
686    })
687}
688
689/// The expected input is in the format of `[((OriginalRow, EncodedArgs), OrderByExprs...)]`
690/// For example,
691///
692/// lag(x*y, 1, null) over (partition by x+y order by x-y, x/y)
693///
694/// list of:
695/// row(
696///   row(
697///     row(#0, #1),
698///     row((#0 * #1), 1, null)
699///   ),
700///   (#0 - #1),
701///   (#0 / #1)
702/// )
703///
704/// The output is in the format of `[result_value, original_row]`, e.g.
705/// list of:
706/// row(
707///   42,
708///   row(7, 8)
709/// )
710fn lag_lead<'a, I>(
711    datums: I,
712    callers_temp_storage: &'a RowArena,
713    order_by: &[ColumnOrder],
714    lag_lead_type: &LagLeadType,
715    ignore_nulls: &bool,
716) -> Datum<'a>
717where
718    I: IntoIterator<Item = Datum<'a>>,
719{
720    let temp_storage = RowArena::new();
721    let iter = lag_lead_no_list(datums, &temp_storage, order_by, lag_lead_type, ignore_nulls);
722    callers_temp_storage.make_datum(|packer| {
723        packer.push_list(iter);
724    })
725}
726
727/// Like `lag_lead`, but doesn't perform the final wrapping in a list, returning an Iterator
728/// instead.
729fn lag_lead_no_list<'a: 'b, 'b, I>(
730    datums: I,
731    callers_temp_storage: &'b RowArena,
732    order_by: &[ColumnOrder],
733    lag_lead_type: &LagLeadType,
734    ignore_nulls: &bool,
735) -> impl Iterator<Item = Datum<'b>>
736where
737    I: IntoIterator<Item = Datum<'a>>,
738{
739    // Sort the datums according to the ORDER BY expressions and return the (OriginalRow, EncodedArgs) record
740    let datums = order_aggregate_datums(datums, order_by);
741
742    // Take the (OriginalRow, EncodedArgs) records and unwrap them into separate datums.
743    // EncodedArgs = (InputValue, Offset, DefaultValue) for Lag/Lead
744    // (`OriginalRow` is kept in a record form, as we don't need to look inside that.)
745    let (orig_rows, unwrapped_args): (Vec<_>, Vec<_>) = datums
746        .into_iter()
747        .map(|d| {
748            let mut iter = d.unwrap_list().iter();
749            let original_row = iter.next().unwrap();
750            let (input_value, offset, default_value) =
751                unwrap_lag_lead_encoded_args(iter.next().unwrap());
752            (original_row, (input_value, offset, default_value))
753        })
754        .unzip();
755
756    let result = lag_lead_inner(unwrapped_args, lag_lead_type, ignore_nulls);
757
758    callers_temp_storage.reserve(result.len());
759    result
760        .into_iter()
761        .zip_eq(orig_rows)
762        .map(|(result_value, original_row)| {
763            callers_temp_storage.make_datum(|packer| {
764                packer.push_list_with(|packer| {
765                    packer.push(result_value);
766                    packer.push(original_row);
767                });
768            })
769        })
770}
771
772/// lag/lead's arguments are in a record. This function unwraps this record.
773fn unwrap_lag_lead_encoded_args(encoded_args: Datum) -> (Datum, Datum, Datum) {
774    let mut encoded_args_iter = encoded_args.unwrap_list().iter();
775    let (input_value, offset, default_value) = (
776        encoded_args_iter.next().unwrap(),
777        encoded_args_iter.next().unwrap(),
778        encoded_args_iter.next().unwrap(),
779    );
780    (input_value, offset, default_value)
781}
782
783/// Each element of `args` has the 3 arguments evaluated for a single input row.
784/// Returns the results for each input row.
785fn lag_lead_inner<'a>(
786    args: Vec<(Datum<'a>, Datum<'a>, Datum<'a>)>,
787    lag_lead_type: &LagLeadType,
788    ignore_nulls: &bool,
789) -> Vec<Datum<'a>> {
790    if *ignore_nulls {
791        lag_lead_inner_ignore_nulls(args, lag_lead_type)
792    } else {
793        lag_lead_inner_respect_nulls(args, lag_lead_type)
794    }
795}
796
797fn lag_lead_inner_respect_nulls<'a>(
798    args: Vec<(Datum<'a>, Datum<'a>, Datum<'a>)>,
799    lag_lead_type: &LagLeadType,
800) -> Vec<Datum<'a>> {
801    let mut result: Vec<Datum> = Vec::with_capacity(args.len());
802    for (idx, (_, offset, default_value)) in args.iter().enumerate() {
803        // Null offsets are acceptable, and always return null
804        if offset.is_null() {
805            result.push(Datum::Null);
806            continue;
807        }
808
809        let idx = i64::try_from(idx).expect("Array index does not fit in i64");
810        let offset = i64::from(offset.unwrap_int32());
811        let offset = match lag_lead_type {
812            LagLeadType::Lag => -offset,
813            LagLeadType::Lead => offset,
814        };
815
816        // Get a Datum from `datums`. Return None if index is out of range.
817        let datums_get = |i: i64| -> Option<Datum> {
818            match u64::try_from(i) {
819                Ok(i) => args
820                    .get(usize::cast_from(i))
821                    .map(|d| Some(d.0)) // succeeded in getting a Datum from the vec
822                    .unwrap_or(None), // overindexing
823                Err(_) => None, // underindexing (negative index)
824            }
825        };
826
827        let lagged_value = datums_get(idx + offset).unwrap_or(*default_value);
828
829        result.push(lagged_value);
830    }
831
832    result
833}
834
835// `i64` indexes get involved in this function because it's convenient to allow negative indexes and
836// have `datums_get` fail on them, and thus handle the beginning and end of the input vector
837// uniformly, rather than checking underflow separately during index manipulations.
838#[allow(clippy::as_conversions)]
839fn lag_lead_inner_ignore_nulls<'a>(
840    args: Vec<(Datum<'a>, Datum<'a>, Datum<'a>)>,
841    lag_lead_type: &LagLeadType,
842) -> Vec<Datum<'a>> {
843    // We check here once that even the largest index fits in `i64`, and then do silent `as`
844    // conversions from `usize` indexes to `i64` indexes throughout this function.
845    if i64::try_from(args.len()).is_err() {
846        panic!("window partition way too big")
847    }
848    // Preparation: Make sure we can jump over a run of nulls in constant time, i.e., regardless of
849    // how many nulls the run has. The following skip tables will point to the next non-null index.
850    let mut skip_nulls_backward = vec![None; args.len()];
851    let mut last_non_null: i64 = -1;
852    let pairs = args
853        .iter()
854        .enumerate()
855        .zip_eq(skip_nulls_backward.iter_mut());
856    for ((i, (d, _, _)), slot) in pairs {
857        if d.is_null() {
858            *slot = Some(last_non_null);
859        } else {
860            last_non_null = i as i64;
861        }
862    }
863    let mut skip_nulls_forward = vec![None; args.len()];
864    let mut last_non_null: i64 = args.len() as i64;
865    let pairs = args
866        .iter()
867        .enumerate()
868        .rev()
869        .zip_eq(skip_nulls_forward.iter_mut().rev());
870    for ((i, (d, _, _)), slot) in pairs {
871        if d.is_null() {
872            *slot = Some(last_non_null);
873        } else {
874            last_non_null = i as i64;
875        }
876    }
877
878    // The actual computation.
879    let mut result: Vec<Datum> = Vec::with_capacity(args.len());
880    for (idx, (_, offset, default_value)) in args.iter().enumerate() {
881        // Null offsets are acceptable, and always return null
882        if offset.is_null() {
883            result.push(Datum::Null);
884            continue;
885        }
886
887        let idx = idx as i64; // checked at the beginning of the function that len() fits
888        let offset = i64::cast_from(offset.unwrap_int32());
889        let offset = match lag_lead_type {
890            LagLeadType::Lag => -offset,
891            LagLeadType::Lead => offset,
892        };
893        let increment = offset.signum();
894
895        // Get a Datum from `datums`. Return None if index is out of range.
896        let datums_get = |i: i64| -> Option<Datum> {
897            match u64::try_from(i) {
898                Ok(i) => args
899                    .get(usize::cast_from(i))
900                    .map(|d| Some(d.0)) // succeeded in getting a Datum from the vec
901                    .unwrap_or(None), // overindexing
902                Err(_) => None, // underindexing (negative index)
903            }
904        };
905
906        let lagged_value = if increment != 0 {
907            // We start j from idx, and step j until we have seen an abs(offset) number of non-null
908            // values or reach the beginning or end of the partition.
909            //
910            // If offset is big, then this is slow: Considering the entire function, it's
911            // `O(partition_size * offset)`.
912            // However, a common use case is an offset of 1, for which this doesn't matter.
913            // TODO: For larger offsets, we could have a completely different implementation
914            // that starts the inner loop from the index where we found the previous result:
915            // https://github.com/MaterializeInc/materialize/pull/29287#discussion_r1738695174
916            let mut j = idx;
917            for _ in 0..num::abs(offset) {
918                j += increment;
919                // Jump over a run of nulls
920                if datums_get(j).is_some_and(|d| d.is_null()) {
921                    let ju = j as usize; // `j >= 0` because of the above `is_some_and`
922                    if increment > 0 {
923                        j = skip_nulls_forward[ju].expect("checked above that it's null");
924                    } else {
925                        j = skip_nulls_backward[ju].expect("checked above that it's null");
926                    }
927                }
928                if datums_get(j).is_none() {
929                    break;
930                }
931            }
932            match datums_get(j) {
933                Some(datum) => datum,
934                None => *default_value,
935            }
936        } else {
937            assert_eq!(offset, 0);
938            let datum = datums_get(idx).expect("known to exist");
939            if !datum.is_null() {
940                datum
941            } else {
942                // Not clear what should the semantics be here. See
943                // https://github.com/MaterializeInc/database-issues/issues/8497
944                // (We used to run into an infinite loop in this case, so panicking is
945                // better.)
946                panic!("0 offset in lag/lead IGNORE NULLS");
947            }
948        };
949
950        result.push(lagged_value);
951    }
952
953    result
954}
955
956/// The expected input is in the format of [((OriginalRow, InputValue), OrderByExprs...)]
957fn first_value<'a, I>(
958    datums: I,
959    callers_temp_storage: &'a RowArena,
960    order_by: &[ColumnOrder],
961    window_frame: &WindowFrame,
962) -> Datum<'a>
963where
964    I: IntoIterator<Item = Datum<'a>>,
965{
966    let temp_storage = RowArena::new();
967    let iter = first_value_no_list(datums, &temp_storage, order_by, window_frame);
968    callers_temp_storage.make_datum(|packer| {
969        packer.push_list(iter);
970    })
971}
972
973/// Like `first_value`, but doesn't perform the final wrapping in a list, returning an Iterator
974/// instead.
975fn first_value_no_list<'a: 'b, 'b, I>(
976    datums: I,
977    callers_temp_storage: &'b RowArena,
978    order_by: &[ColumnOrder],
979    window_frame: &WindowFrame,
980) -> impl Iterator<Item = Datum<'b>>
981where
982    I: IntoIterator<Item = Datum<'a>>,
983{
984    // Sort the datums according to the ORDER BY expressions and return the (OriginalRow, InputValue) record
985    let datums = order_aggregate_datums(datums, order_by);
986
987    // Decode the input (OriginalRow, InputValue) into separate datums
988    let (orig_rows, args): (Vec<_>, Vec<_>) = datums
989        .into_iter()
990        .map(|d| {
991            let mut iter = d.unwrap_list().iter();
992            let original_row = iter.next().unwrap();
993            let arg = iter.next().unwrap();
994
995            (original_row, arg)
996        })
997        .unzip();
998
999    let results = first_value_inner(args, window_frame);
1000
1001    callers_temp_storage.reserve(results.len());
1002    results
1003        .into_iter()
1004        .zip_eq(orig_rows)
1005        .map(|(result_value, original_row)| {
1006            callers_temp_storage.make_datum(|packer| {
1007                packer.push_list_with(|packer| {
1008                    packer.push(result_value);
1009                    packer.push(original_row);
1010                });
1011            })
1012        })
1013}
1014
1015fn first_value_inner<'a>(datums: Vec<Datum<'a>>, window_frame: &WindowFrame) -> Vec<Datum<'a>> {
1016    let length = datums.len();
1017    let mut result: Vec<Datum> = Vec::with_capacity(length);
1018    for (idx, current_datum) in datums.iter().enumerate() {
1019        let first_value = match &window_frame.start_bound {
1020            // Always return the current value
1021            WindowFrameBound::CurrentRow => *current_datum,
1022            WindowFrameBound::UnboundedPreceding => {
1023                if let WindowFrameBound::OffsetPreceding(end_offset) = &window_frame.end_bound {
1024                    let end_offset = usize::cast_from(*end_offset);
1025
1026                    // If the frame ends before the first row, return null
1027                    if idx < end_offset {
1028                        Datum::Null
1029                    } else {
1030                        datums[0]
1031                    }
1032                } else {
1033                    datums[0]
1034                }
1035            }
1036            WindowFrameBound::OffsetPreceding(offset) => {
1037                let start_offset = usize::cast_from(*offset);
1038                let start_idx = idx.saturating_sub(start_offset);
1039                if let WindowFrameBound::OffsetPreceding(end_offset) = &window_frame.end_bound {
1040                    let end_offset = usize::cast_from(*end_offset);
1041
1042                    // If the frame is empty or ends before the first row, return null
1043                    if start_offset < end_offset || idx < end_offset {
1044                        Datum::Null
1045                    } else {
1046                        datums[start_idx]
1047                    }
1048                } else {
1049                    datums[start_idx]
1050                }
1051            }
1052            WindowFrameBound::OffsetFollowing(offset) => {
1053                let start_offset = usize::cast_from(*offset);
1054                let start_idx = idx.saturating_add(start_offset);
1055                if let WindowFrameBound::OffsetFollowing(end_offset) = &window_frame.end_bound {
1056                    // If the frame is empty or starts after the last row, return null
1057                    if offset > end_offset || start_idx >= length {
1058                        Datum::Null
1059                    } else {
1060                        datums[start_idx]
1061                    }
1062                } else {
1063                    datums
1064                        .get(start_idx)
1065                        .map(|d| d.clone())
1066                        .unwrap_or(Datum::Null)
1067                }
1068            }
1069            // Forbidden during planning
1070            WindowFrameBound::UnboundedFollowing => unreachable!(),
1071        };
1072        result.push(first_value);
1073    }
1074    result
1075}
1076
1077/// The expected input is in the format of [((OriginalRow, InputValue), OrderByExprs...)]
1078fn last_value<'a, I>(
1079    datums: I,
1080    callers_temp_storage: &'a RowArena,
1081    order_by: &[ColumnOrder],
1082    window_frame: &WindowFrame,
1083) -> Datum<'a>
1084where
1085    I: IntoIterator<Item = Datum<'a>>,
1086{
1087    let temp_storage = RowArena::new();
1088    let iter = last_value_no_list(datums, &temp_storage, order_by, window_frame);
1089    callers_temp_storage.make_datum(|packer| {
1090        packer.push_list(iter);
1091    })
1092}
1093
1094/// Like `last_value`, but doesn't perform the final wrapping in a list, returning an Iterator
1095/// instead.
1096fn last_value_no_list<'a: 'b, 'b, I>(
1097    datums: I,
1098    callers_temp_storage: &'b RowArena,
1099    order_by: &[ColumnOrder],
1100    window_frame: &WindowFrame,
1101) -> impl Iterator<Item = Datum<'b>>
1102where
1103    I: IntoIterator<Item = Datum<'a>>,
1104{
1105    // Sort the datums according to the ORDER BY expressions and return the ((OriginalRow, InputValue), OrderByRow) record
1106    // The OrderByRow is kept around because it is required to compute the peer groups in RANGE mode
1107    let datums = order_aggregate_datums_with_rank(datums, order_by);
1108
1109    // Decode the input (OriginalRow, InputValue) into separate datums, while keeping the OrderByRow
1110    let size_hint = datums.size_hint().0;
1111    let mut args = Vec::with_capacity(size_hint);
1112    let mut original_rows = Vec::with_capacity(size_hint);
1113    let mut order_by_rows = Vec::with_capacity(size_hint);
1114    for (d, order_by_row) in datums.into_iter() {
1115        let mut iter = d.unwrap_list().iter();
1116        let original_row = iter.next().unwrap();
1117        let arg = iter.next().unwrap();
1118        order_by_rows.push(order_by_row);
1119        original_rows.push(original_row);
1120        args.push(arg);
1121    }
1122
1123    let results = last_value_inner(args, &order_by_rows, window_frame);
1124
1125    callers_temp_storage.reserve(results.len());
1126    results
1127        .into_iter()
1128        .zip_eq(original_rows)
1129        .map(|(result_value, original_row)| {
1130            callers_temp_storage.make_datum(|packer| {
1131                packer.push_list_with(|packer| {
1132                    packer.push(result_value);
1133                    packer.push(original_row);
1134                });
1135            })
1136        })
1137}
1138
1139fn last_value_inner<'a>(
1140    args: Vec<Datum<'a>>,
1141    order_by_rows: &[Row],
1142    window_frame: &WindowFrame,
1143) -> Vec<Datum<'a>> {
1144    let length = args.len();
1145    let mut results: Vec<Datum> = Vec::with_capacity(length);
1146    let mut peer_end = 0;
1147    for (idx, (current_datum, order_by_row)) in args.iter().zip_eq(order_by_rows).enumerate() {
1148        let last_value = match &window_frame.end_bound {
1149            WindowFrameBound::CurrentRow => match &window_frame.units {
1150                // Always return the current value when in ROWS mode
1151                WindowFrameUnits::Rows => *current_datum,
1152                WindowFrameUnits::Range => {
1153                    // When in RANGE mode, return the last value of the peer group
1154                    // The peer group is the group of rows with the same ORDER BY value
1155                    // Note: Range is only supported for the default window frame (RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW),
1156                    // which is why it does not appear in the other branches
1157                    if idx == peer_end {
1158                        peer_end = idx + 1;
1159                        while peer_end < length && &order_by_rows[peer_end] == order_by_row {
1160                            peer_end += 1;
1161                        }
1162                    }
1163                    args[peer_end - 1]
1164                }
1165                // GROUPS is not supported, and forbidden during planning
1166                WindowFrameUnits::Groups => unreachable!(),
1167            },
1168            WindowFrameBound::UnboundedFollowing => {
1169                if let WindowFrameBound::OffsetFollowing(start_offset) = &window_frame.start_bound {
1170                    let start_offset = usize::cast_from(*start_offset);
1171
1172                    // If the frame starts after the last row of the window, return null
1173                    if idx + start_offset > length - 1 {
1174                        Datum::Null
1175                    } else {
1176                        args[length - 1]
1177                    }
1178                } else {
1179                    args[length - 1]
1180                }
1181            }
1182            WindowFrameBound::OffsetFollowing(offset) => {
1183                let end_offset = usize::cast_from(*offset);
1184                let end_idx = idx.saturating_add(end_offset);
1185                if let WindowFrameBound::OffsetFollowing(start_offset) = &window_frame.start_bound {
1186                    let start_offset = usize::cast_from(*start_offset);
1187                    let start_idx = idx.saturating_add(start_offset);
1188
1189                    // If the frame is empty or starts after the last row of the window, return null
1190                    if end_offset < start_offset || start_idx >= length {
1191                        Datum::Null
1192                    } else {
1193                        // Return the last valid element in the window
1194                        args.get(end_idx).unwrap_or(&args[length - 1]).clone()
1195                    }
1196                } else {
1197                    args.get(end_idx).unwrap_or(&args[length - 1]).clone()
1198                }
1199            }
1200            WindowFrameBound::OffsetPreceding(offset) => {
1201                let end_offset = usize::cast_from(*offset);
1202                let end_idx = idx.saturating_sub(end_offset);
1203                if idx < end_offset {
1204                    // If the frame ends before the first row, return null
1205                    Datum::Null
1206                } else if let WindowFrameBound::OffsetPreceding(start_offset) =
1207                    &window_frame.start_bound
1208                {
1209                    // If the frame is empty, return null
1210                    if offset > start_offset {
1211                        Datum::Null
1212                    } else {
1213                        args[end_idx]
1214                    }
1215                } else {
1216                    args[end_idx]
1217                }
1218            }
1219            // Forbidden during planning
1220            WindowFrameBound::UnboundedPreceding => unreachable!(),
1221        };
1222        results.push(last_value);
1223    }
1224    results
1225}
1226
1227/// Executes `FusedValueWindowFunc` on a reduction group.
1228/// The expected input is in the format of `[((OriginalRow, (Args1, Args2, ...)), OrderByExprs...)]`
1229/// where `Args1`, `Args2`, are the arguments of each of the fused functions. For functions that
1230/// have only a single argument (first_value/last_value), these are simple values. For functions
1231/// that have multiple arguments (lag/lead), these are also records.
1232fn fused_value_window_func<'a, I>(
1233    input_datums: I,
1234    callers_temp_storage: &'a RowArena,
1235    funcs: &Vec<AggregateFunc>,
1236    order_by: &Vec<ColumnOrder>,
1237) -> Datum<'a>
1238where
1239    I: IntoIterator<Item = Datum<'a>>,
1240{
1241    let temp_storage = RowArena::new();
1242    let iter = fused_value_window_func_no_list(input_datums, &temp_storage, funcs, order_by);
1243    callers_temp_storage.make_datum(|packer| {
1244        packer.push_list(iter);
1245    })
1246}
1247
1248/// Like `fused_value_window_func`, but doesn't perform the final wrapping in a list, returning an
1249/// Iterator instead.
1250fn fused_value_window_func_no_list<'a: 'b, 'b, I>(
1251    input_datums: I,
1252    callers_temp_storage: &'b RowArena,
1253    funcs: &Vec<AggregateFunc>,
1254    order_by: &Vec<ColumnOrder>,
1255) -> impl Iterator<Item = Datum<'b>>
1256where
1257    I: IntoIterator<Item = Datum<'a>>,
1258{
1259    let has_last_value = funcs
1260        .iter()
1261        .any(|f| matches!(f, AggregateFunc::LastValue { .. }));
1262
1263    let input_datums_with_ranks = order_aggregate_datums_with_rank(input_datums, order_by);
1264
1265    let size_hint = input_datums_with_ranks.size_hint().0;
1266    let mut encoded_argsss = vec![Vec::with_capacity(size_hint); funcs.len()];
1267    let mut original_rows = Vec::with_capacity(size_hint);
1268    let mut order_by_rows = Vec::with_capacity(size_hint);
1269    for (d, order_by_row) in input_datums_with_ranks {
1270        let mut iter = d.unwrap_list().iter();
1271        let original_row = iter.next().unwrap();
1272        original_rows.push(original_row);
1273        let mut argss_iter = iter.next().unwrap().unwrap_list().iter();
1274        for i in 0..funcs.len() {
1275            let encoded_args = argss_iter.next().unwrap();
1276            encoded_argsss[i].push(encoded_args);
1277        }
1278        if has_last_value {
1279            order_by_rows.push(order_by_row);
1280        }
1281    }
1282
1283    let mut results_per_row = vec![Vec::with_capacity(funcs.len()); original_rows.len()];
1284    for (func, encoded_argss) in funcs.iter().zip_eq(encoded_argsss) {
1285        let results = match func {
1286            AggregateFunc::LagLead {
1287                order_by: inner_order_by,
1288                lag_lead,
1289                ignore_nulls,
1290            } => {
1291                assert_eq!(order_by, inner_order_by);
1292                let unwrapped_argss = encoded_argss
1293                    .into_iter()
1294                    .map(|encoded_args| unwrap_lag_lead_encoded_args(encoded_args))
1295                    .collect();
1296                lag_lead_inner(unwrapped_argss, lag_lead, ignore_nulls)
1297            }
1298            AggregateFunc::FirstValue {
1299                order_by: inner_order_by,
1300                window_frame,
1301            } => {
1302                assert_eq!(order_by, inner_order_by);
1303                // (No unwrapping to do on the args here, because there is only 1 arg, so it's not
1304                // wrapped into a record.)
1305                first_value_inner(encoded_argss, window_frame)
1306            }
1307            AggregateFunc::LastValue {
1308                order_by: inner_order_by,
1309                window_frame,
1310            } => {
1311                assert_eq!(order_by, inner_order_by);
1312                // (No unwrapping to do on the args here, because there is only 1 arg, so it's not
1313                // wrapped into a record.)
1314                last_value_inner(encoded_argss, &order_by_rows, window_frame)
1315            }
1316            _ => panic!("unknown window function in FusedValueWindowFunc"),
1317        };
1318        for (results, result) in results_per_row.iter_mut().zip_eq(results) {
1319            results.push(result);
1320        }
1321    }
1322
1323    callers_temp_storage.reserve(2 * original_rows.len());
1324    results_per_row
1325        .into_iter()
1326        .enumerate()
1327        .map(move |(i, results)| {
1328            callers_temp_storage.make_datum(|packer| {
1329                packer.push_list_with(|packer| {
1330                    packer
1331                        .push(callers_temp_storage.make_datum(|packer| packer.push_list(results)));
1332                    packer.push(original_rows[i]);
1333                });
1334            })
1335        })
1336}
1337
1338/// `input_datums` is an entire window partition.
1339/// The expected input is in the format of `[((OriginalRow, InputValue), OrderByExprs...)]`
1340/// See also in the comment in `window_func_applied_to`.
1341///
1342/// `wrapped_aggregate`: e.g., for `sum(...) OVER (...)`, this is the `sum(...)`.
1343///
1344/// Note that this `order_by` doesn't have expressions, only `ColumnOrder`s. For an explanation,
1345/// see the comment on `WindowExprType`.
1346fn window_aggr<'a, I, A>(
1347    input_datums: I,
1348    callers_temp_storage: &'a RowArena,
1349    wrapped_aggregate: &AggregateFunc,
1350    order_by: &[ColumnOrder],
1351    window_frame: &WindowFrame,
1352) -> Datum<'a>
1353where
1354    I: IntoIterator<Item = Datum<'a>>,
1355    A: OneByOneAggr,
1356{
1357    let temp_storage = RowArena::new();
1358    let iter = window_aggr_no_list::<I, A>(
1359        input_datums,
1360        &temp_storage,
1361        wrapped_aggregate,
1362        order_by,
1363        window_frame,
1364    );
1365    callers_temp_storage.make_datum(|packer| {
1366        packer.push_list(iter);
1367    })
1368}
1369
1370/// Like `window_aggr`, but doesn't perform the final wrapping in a list, returning an Iterator
1371/// instead.
1372fn window_aggr_no_list<'a: 'b, 'b, I, A>(
1373    input_datums: I,
1374    callers_temp_storage: &'b RowArena,
1375    wrapped_aggregate: &AggregateFunc,
1376    order_by: &[ColumnOrder],
1377    window_frame: &WindowFrame,
1378) -> impl Iterator<Item = Datum<'b>>
1379where
1380    I: IntoIterator<Item = Datum<'a>>,
1381    A: OneByOneAggr,
1382{
1383    // Sort the datums according to the ORDER BY expressions and return the ((OriginalRow, InputValue), OrderByRow) record
1384    // The OrderByRow is kept around because it is required to compute the peer groups in RANGE mode
1385    let datums = order_aggregate_datums_with_rank(input_datums, order_by);
1386
1387    // Decode the input (OriginalRow, InputValue) into separate datums, while keeping the OrderByRow
1388    let size_hint = datums.size_hint().0;
1389    let mut args: Vec<Datum> = Vec::with_capacity(size_hint);
1390    let mut original_rows: Vec<Datum> = Vec::with_capacity(size_hint);
1391    let mut order_by_rows = Vec::with_capacity(size_hint);
1392    for (d, order_by_row) in datums.into_iter() {
1393        let mut iter = d.unwrap_list().iter();
1394        let original_row = iter.next().unwrap();
1395        let arg = iter.next().unwrap();
1396        order_by_rows.push(order_by_row);
1397        original_rows.push(original_row);
1398        args.push(arg);
1399    }
1400
1401    let results = window_aggr_inner::<A>(
1402        args,
1403        &order_by_rows,
1404        wrapped_aggregate,
1405        order_by,
1406        window_frame,
1407        callers_temp_storage,
1408    );
1409
1410    callers_temp_storage.reserve(results.len());
1411    results
1412        .into_iter()
1413        .zip_eq(original_rows)
1414        .map(|(result_value, original_row)| {
1415            callers_temp_storage.make_datum(|packer| {
1416                packer.push_list_with(|packer| {
1417                    packer.push(result_value);
1418                    packer.push(original_row);
1419                });
1420            })
1421        })
1422}
1423
1424fn window_aggr_inner<'a, A>(
1425    mut args: Vec<Datum<'a>>,
1426    order_by_rows: &Vec<Row>,
1427    wrapped_aggregate: &AggregateFunc,
1428    order_by: &[ColumnOrder],
1429    window_frame: &WindowFrame,
1430    temp_storage: &'a RowArena,
1431) -> Vec<Datum<'a>>
1432where
1433    A: OneByOneAggr,
1434{
1435    let length = args.len();
1436    let mut result: Vec<Datum> = Vec::with_capacity(length);
1437
1438    // In this degenerate case, all results would be `wrapped_aggregate.default()` (usually null).
1439    // However, this currently can't happen, because
1440    // - Groups frame mode is currently not supported;
1441    // - Range frame mode is currently supported only for the default frame, which includes the
1442    //   current row.
1443    soft_assert_or_log!(
1444        !((matches!(window_frame.units, WindowFrameUnits::Groups)
1445            || matches!(window_frame.units, WindowFrameUnits::Range))
1446            && !window_frame.includes_current_row()),
1447        "window frame without current row"
1448    );
1449
1450    if (matches!(
1451        window_frame.start_bound,
1452        WindowFrameBound::UnboundedPreceding
1453    ) && matches!(window_frame.end_bound, WindowFrameBound::UnboundedFollowing))
1454        || (order_by.is_empty()
1455            && (matches!(window_frame.units, WindowFrameUnits::Groups)
1456                || matches!(window_frame.units, WindowFrameUnits::Range))
1457            && window_frame.includes_current_row())
1458    {
1459        // Either
1460        //  - UNBOUNDED frame in both directions, or
1461        //  - There is no ORDER BY and the frame is such that the current peer group is included.
1462        //    (The current peer group will be the whole partition if there is no ORDER BY.)
1463        // We simply need to compute the aggregate once, on the entire partition, and each input
1464        // row will get this one aggregate value as result.
1465        let result_value =
1466            wrapped_aggregate.eval(args.into_iter().map(|d| (d, Diff::ONE)), temp_storage);
1467        // Every row will get the above aggregate as result.
1468        for _ in 0..length {
1469            result.push(result_value);
1470        }
1471    } else {
1472        fn rows_between_unbounded_preceding_and_current_row<'a, A>(
1473            args: Vec<Datum<'a>>,
1474            result: &mut Vec<Datum<'a>>,
1475            mut one_by_one_aggr: A,
1476            temp_storage: &'a RowArena,
1477        ) where
1478            A: OneByOneAggr,
1479        {
1480            for current_arg in args.into_iter() {
1481                one_by_one_aggr.give(&current_arg);
1482                let result_value = one_by_one_aggr.get_current_aggregate(temp_storage);
1483                result.push(result_value);
1484            }
1485        }
1486
1487        fn groups_between_unbounded_preceding_and_current_row<'a, A>(
1488            args: Vec<Datum<'a>>,
1489            order_by_rows: &Vec<Row>,
1490            result: &mut Vec<Datum<'a>>,
1491            mut one_by_one_aggr: A,
1492            temp_storage: &'a RowArena,
1493        ) where
1494            A: OneByOneAggr,
1495        {
1496            let mut peer_group_start = 0;
1497            while peer_group_start < args.len() {
1498                // Find the boundaries of the current peer group.
1499                // peer_group_start will point to the first element of the peer group,
1500                // peer_group_end will point to _just after_ the last element of the peer group.
1501                let mut peer_group_end = peer_group_start + 1;
1502                while peer_group_end < args.len()
1503                    && order_by_rows[peer_group_start] == order_by_rows[peer_group_end]
1504                {
1505                    // The peer group goes on while the OrderByRows not differ.
1506                    peer_group_end += 1;
1507                }
1508                // Let's compute the aggregate (which will be the same for all records in this
1509                // peer group).
1510                for current_arg in args[peer_group_start..peer_group_end].iter() {
1511                    one_by_one_aggr.give(current_arg);
1512                }
1513                let agg_for_peer_group = one_by_one_aggr.get_current_aggregate(temp_storage);
1514                // Put the above aggregate into each record in the peer group.
1515                for _ in args[peer_group_start..peer_group_end].iter() {
1516                    result.push(agg_for_peer_group);
1517                }
1518                // Point to the start of the next peer group.
1519                peer_group_start = peer_group_end;
1520            }
1521        }
1522
1523        fn rows_between_offset_and_offset<'a>(
1524            args: Vec<Datum<'a>>,
1525            result: &mut Vec<Datum<'a>>,
1526            wrapped_aggregate: &AggregateFunc,
1527            temp_storage: &'a RowArena,
1528            offset_start: i64,
1529            offset_end: i64,
1530        ) {
1531            let len = args
1532                .len()
1533                .to_i64()
1534                .expect("window partition's len should fit into i64");
1535            for i in 0..len {
1536                let i = i.to_i64().expect("window partition shouldn't be super big");
1537                // Trim the start of the frame to make it not reach over the start of the window
1538                // partition.
1539                let frame_start = max(i + offset_start, 0)
1540                    .to_usize()
1541                    .expect("The max made sure it's not negative");
1542                // Trim the end of the frame to make it not reach over the end of the window
1543                // partition.
1544                let frame_end = min(i + offset_end, len - 1).to_usize();
1545                match frame_end {
1546                    Some(frame_end) => {
1547                        if frame_start <= frame_end {
1548                            // Compute the aggregate on the frame.
1549                            // TODO:
1550                            // This implementation is quite slow if the frame is large: we do an
1551                            // inner loop over the entire frame, and compute the aggregate from
1552                            // scratch. We could do better:
1553                            //  - For invertible aggregations we could do a rolling aggregation.
1554                            //  - There are various tricks for min/max as well, making use of either
1555                            //    the fixed size of the window, or that we are not retracting
1556                            //    arbitrary elements but doing queue operations. E.g., see
1557                            //    http://codercareer.blogspot.com/2012/02/no-33-maximums-in-sliding-windows.html
1558                            let frame_values = args[frame_start..=frame_end]
1559                                .iter()
1560                                .map(|d| (*d, Diff::ONE));
1561                            let result_value = wrapped_aggregate.eval(frame_values, temp_storage);
1562                            result.push(result_value);
1563                        } else {
1564                            // frame_start > frame_end, so this is an empty frame.
1565                            let result_value = wrapped_aggregate.default();
1566                            result.push(result_value);
1567                        }
1568                    }
1569                    None => {
1570                        // frame_end would be negative, so this is an empty frame.
1571                        let result_value = wrapped_aggregate.default();
1572                        result.push(result_value);
1573                    }
1574                }
1575            }
1576        }
1577
1578        match (
1579            &window_frame.units,
1580            &window_frame.start_bound,
1581            &window_frame.end_bound,
1582        ) {
1583            // Cases where one edge of the frame is CurrentRow.
1584            // Note that these cases could be merged into the more general cases below where one
1585            // edge is some offset (with offset = 0), but the CurrentRow cases probably cover 95%
1586            // of user queries, so let's make this simple and fast.
1587            (Rows, UnboundedPreceding, CurrentRow) => {
1588                rows_between_unbounded_preceding_and_current_row::<A>(
1589                    args,
1590                    &mut result,
1591                    A::new(wrapped_aggregate, false),
1592                    temp_storage,
1593                );
1594            }
1595            (Rows, CurrentRow, UnboundedFollowing) => {
1596                // Same as above, but reverse.
1597                args.reverse();
1598                rows_between_unbounded_preceding_and_current_row::<A>(
1599                    args,
1600                    &mut result,
1601                    A::new(wrapped_aggregate, true),
1602                    temp_storage,
1603                );
1604                result.reverse();
1605            }
1606            (Range, UnboundedPreceding, CurrentRow) => {
1607                // Note that for the default frame, the RANGE frame mode is identical to the GROUPS
1608                // frame mode.
1609                groups_between_unbounded_preceding_and_current_row::<A>(
1610                    args,
1611                    order_by_rows,
1612                    &mut result,
1613                    A::new(wrapped_aggregate, false),
1614                    temp_storage,
1615                );
1616            }
1617            // The next several cases all call `rows_between_offset_and_offset`. Note that the
1618            // offset passed to `rows_between_offset_and_offset` should be negated when it's
1619            // PRECEDING.
1620            (Rows, OffsetPreceding(start_prec), OffsetPreceding(end_prec)) => {
1621                let start_prec = start_prec.to_i64().expect(
1622                    "window frame start OFFSET shouldn't be super big (the planning ensured this)",
1623                );
1624                let end_prec = end_prec.to_i64().expect(
1625                    "window frame end OFFSET shouldn't be super big (the planning ensured this)",
1626                );
1627                rows_between_offset_and_offset(
1628                    args,
1629                    &mut result,
1630                    wrapped_aggregate,
1631                    temp_storage,
1632                    -start_prec,
1633                    -end_prec,
1634                );
1635            }
1636            (Rows, OffsetPreceding(start_prec), OffsetFollowing(end_fol)) => {
1637                let start_prec = start_prec.to_i64().expect(
1638                    "window frame start OFFSET shouldn't be super big (the planning ensured this)",
1639                );
1640                let end_fol = end_fol.to_i64().expect(
1641                    "window frame end OFFSET shouldn't be super big (the planning ensured this)",
1642                );
1643                rows_between_offset_and_offset(
1644                    args,
1645                    &mut result,
1646                    wrapped_aggregate,
1647                    temp_storage,
1648                    -start_prec,
1649                    end_fol,
1650                );
1651            }
1652            (Rows, OffsetFollowing(start_fol), OffsetFollowing(end_fol)) => {
1653                let start_fol = start_fol.to_i64().expect(
1654                    "window frame start OFFSET shouldn't be super big (the planning ensured this)",
1655                );
1656                let end_fol = end_fol.to_i64().expect(
1657                    "window frame end OFFSET shouldn't be super big (the planning ensured this)",
1658                );
1659                rows_between_offset_and_offset(
1660                    args,
1661                    &mut result,
1662                    wrapped_aggregate,
1663                    temp_storage,
1664                    start_fol,
1665                    end_fol,
1666                );
1667            }
1668            (Rows, OffsetFollowing(_), OffsetPreceding(_)) => {
1669                unreachable!() // The planning ensured that this nonsensical case can't happen
1670            }
1671            (Rows, OffsetPreceding(start_prec), CurrentRow) => {
1672                let start_prec = start_prec.to_i64().expect(
1673                    "window frame start OFFSET shouldn't be super big (the planning ensured this)",
1674                );
1675                let end_fol = 0;
1676                rows_between_offset_and_offset(
1677                    args,
1678                    &mut result,
1679                    wrapped_aggregate,
1680                    temp_storage,
1681                    -start_prec,
1682                    end_fol,
1683                );
1684            }
1685            (Rows, CurrentRow, OffsetFollowing(end_fol)) => {
1686                let start_fol = 0;
1687                let end_fol = end_fol.to_i64().expect(
1688                    "window frame end OFFSET shouldn't be super big (the planning ensured this)",
1689                );
1690                rows_between_offset_and_offset(
1691                    args,
1692                    &mut result,
1693                    wrapped_aggregate,
1694                    temp_storage,
1695                    start_fol,
1696                    end_fol,
1697                );
1698            }
1699            (Rows, CurrentRow, CurrentRow) => {
1700                // We could have a more efficient implementation for this, but this is probably
1701                // super rare. (Might be more common with RANGE or GROUPS frame mode, though!)
1702                let start_fol = 0;
1703                let end_fol = 0;
1704                rows_between_offset_and_offset(
1705                    args,
1706                    &mut result,
1707                    wrapped_aggregate,
1708                    temp_storage,
1709                    start_fol,
1710                    end_fol,
1711                );
1712            }
1713            (Rows, CurrentRow, OffsetPreceding(_))
1714            | (Rows, UnboundedFollowing, _)
1715            | (Rows, _, UnboundedPreceding)
1716            | (Rows, OffsetFollowing(..), CurrentRow) => {
1717                unreachable!() // The planning ensured that these nonsensical cases can't happen
1718            }
1719            (Rows, UnboundedPreceding, UnboundedFollowing) => {
1720                // This is handled by the complicated if condition near the beginning of this
1721                // function.
1722                unreachable!()
1723            }
1724            (Rows, UnboundedPreceding, OffsetPreceding(_))
1725            | (Rows, UnboundedPreceding, OffsetFollowing(_))
1726            | (Rows, OffsetPreceding(..), UnboundedFollowing)
1727            | (Rows, OffsetFollowing(..), UnboundedFollowing) => {
1728                // Unsupported. Bail in the planner.
1729                // https://github.com/MaterializeInc/database-issues/issues/6720
1730                unreachable!()
1731            }
1732            (Range, _, _) => {
1733                // Unsupported.
1734                // The planner doesn't allow Range frame mode for now (except for the default
1735                // frame), see https://github.com/MaterializeInc/database-issues/issues/6585
1736                // Note that it would be easy to handle (Range, CurrentRow, UnboundedFollowing):
1737                // it would be similar to (Rows, CurrentRow, UnboundedFollowing), but would call
1738                // groups_between_unbounded_preceding_current_row.
1739                unreachable!()
1740            }
1741            (Groups, _, _) => {
1742                // Unsupported.
1743                // The planner doesn't allow Groups frame mode for now, see
1744                // https://github.com/MaterializeInc/database-issues/issues/6588
1745                unreachable!()
1746            }
1747        }
1748    }
1749
1750    result
1751}
1752
1753/// Computes a bundle of fused window aggregations.
1754/// The input is similar to `window_aggr`, but `InputValue` is not just a single value, but a record
1755/// where each component is the input to one of the aggregations.
1756fn fused_window_aggr<'a, I, A>(
1757    input_datums: I,
1758    callers_temp_storage: &'a RowArena,
1759    wrapped_aggregates: &Vec<AggregateFunc>,
1760    order_by: &Vec<ColumnOrder>,
1761    window_frame: &WindowFrame,
1762) -> Datum<'a>
1763where
1764    I: IntoIterator<Item = Datum<'a>>,
1765    A: OneByOneAggr,
1766{
1767    let temp_storage = RowArena::new();
1768    let iter = fused_window_aggr_no_list::<_, A>(
1769        input_datums,
1770        &temp_storage,
1771        wrapped_aggregates,
1772        order_by,
1773        window_frame,
1774    );
1775    callers_temp_storage.make_datum(|packer| {
1776        packer.push_list(iter);
1777    })
1778}
1779
1780/// Like `fused_window_aggr`, but doesn't perform the final wrapping in a list, returning an
1781/// Iterator instead.
1782fn fused_window_aggr_no_list<'a: 'b, 'b, I, A>(
1783    input_datums: I,
1784    callers_temp_storage: &'b RowArena,
1785    wrapped_aggregates: &Vec<AggregateFunc>,
1786    order_by: &Vec<ColumnOrder>,
1787    window_frame: &WindowFrame,
1788) -> impl Iterator<Item = Datum<'b>>
1789where
1790    I: IntoIterator<Item = Datum<'a>>,
1791    A: OneByOneAggr,
1792{
1793    // Sort the datums according to the ORDER BY expressions and return the ((OriginalRow, InputValue), OrderByRow) record
1794    // The OrderByRow is kept around because it is required to compute the peer groups in RANGE mode
1795    let datums = order_aggregate_datums_with_rank(input_datums, order_by);
1796
1797    let size_hint = datums.size_hint().0;
1798    let mut argss = vec![Vec::with_capacity(size_hint); wrapped_aggregates.len()];
1799    let mut original_rows = Vec::with_capacity(size_hint);
1800    let mut order_by_rows = Vec::with_capacity(size_hint);
1801    for (d, order_by_row) in datums {
1802        let mut iter = d.unwrap_list().iter();
1803        let original_row = iter.next().unwrap();
1804        original_rows.push(original_row);
1805        let args_iter = iter.next().unwrap().unwrap_list().iter();
1806        // Push each argument into the respective list
1807        for (args, arg) in argss.iter_mut().zip_eq(args_iter) {
1808            args.push(arg);
1809        }
1810        order_by_rows.push(order_by_row);
1811    }
1812
1813    let mut results_per_row =
1814        vec![Vec::with_capacity(wrapped_aggregates.len()); original_rows.len()];
1815    for (wrapped_aggr, args) in wrapped_aggregates.iter().zip_eq(argss) {
1816        let results = window_aggr_inner::<A>(
1817            args,
1818            &order_by_rows,
1819            wrapped_aggr,
1820            order_by,
1821            window_frame,
1822            callers_temp_storage,
1823        );
1824        for (results, result) in results_per_row.iter_mut().zip_eq(results) {
1825            results.push(result);
1826        }
1827    }
1828
1829    callers_temp_storage.reserve(2 * original_rows.len());
1830    results_per_row
1831        .into_iter()
1832        .enumerate()
1833        .map(move |(i, results)| {
1834            callers_temp_storage.make_datum(|packer| {
1835                packer.push_list_with(|packer| {
1836                    packer
1837                        .push(callers_temp_storage.make_datum(|packer| packer.push_list(results)));
1838                    packer.push(original_rows[i]);
1839                });
1840            })
1841        })
1842}
1843
1844/// An implementation of an aggregation where we can send in the input elements one-by-one, and
1845/// can also ask the current aggregate at any moment. (This just delegates to other aggregation
1846/// evaluation approaches.)
1847pub trait OneByOneAggr {
1848    /// The `reverse` parameter makes the aggregations process input elements in reverse order.
1849    /// This has an effect only for non-commutative aggregations, e.g. `list_agg`. These are
1850    /// currently only some of the Basic aggregations. (Basic aggregations are handled by
1851    /// `NaiveOneByOneAggr`).
1852    fn new(agg: &AggregateFunc, reverse: bool) -> Self;
1853    /// Pushes one input element into the aggregation.
1854    fn give(&mut self, d: &Datum);
1855    /// Returns the value of the aggregate computed on the given values so far.
1856    fn get_current_aggregate<'a>(&self, temp_storage: &'a RowArena) -> Datum<'a>;
1857}
1858
1859/// Naive implementation of [OneByOneAggr], suitable for stuff like const folding, but too slow for
1860/// rendering. This relies only on infrastructure available in `mz-expr`. It simply saves all the
1861/// given input, and calls the given [AggregateFunc]'s `eval` method when asked about the current
1862/// aggregate. (For Accumulable and Hierarchical aggregations, the rendering has more efficient
1863/// implementations, but for Basic aggregations even the rendering uses this naive implementation.)
1864#[derive(Debug)]
1865pub struct NaiveOneByOneAggr {
1866    agg: AggregateFunc,
1867    input: Vec<Row>,
1868    reverse: bool,
1869}
1870
1871impl OneByOneAggr for NaiveOneByOneAggr {
1872    fn new(agg: &AggregateFunc, reverse: bool) -> Self {
1873        NaiveOneByOneAggr {
1874            agg: agg.clone(),
1875            input: Vec::new(),
1876            reverse,
1877        }
1878    }
1879
1880    fn give(&mut self, d: &Datum) {
1881        let mut row = Row::default();
1882        row.packer().push(d);
1883        self.input.push(row);
1884    }
1885
1886    fn get_current_aggregate<'a>(&self, temp_storage: &'a RowArena) -> Datum<'a> {
1887        temp_storage.make_datum(|packer| {
1888            packer.push(if !self.reverse {
1889                self.agg.eval(
1890                    self.input.iter().map(|r| (r.unpack_first(), Diff::ONE)),
1891                    temp_storage,
1892                )
1893            } else {
1894                self.agg.eval(
1895                    self.input
1896                        .iter()
1897                        .rev()
1898                        .map(|r| (r.unpack_first(), Diff::ONE)),
1899                    temp_storage,
1900                )
1901            });
1902        })
1903    }
1904}
1905
1906/// Identify whether the given aggregate function is Lag or Lead, since they share
1907/// implementations.
1908#[derive(
1909    Clone,
1910    Debug,
1911    Eq,
1912    PartialEq,
1913    Ord,
1914    PartialOrd,
1915    Serialize,
1916    Deserialize,
1917    Hash
1918)]
1919pub enum LagLeadType {
1920    Lag,
1921    Lead,
1922}
1923
1924#[derive(
1925    Clone,
1926    Debug,
1927    Eq,
1928    PartialEq,
1929    Ord,
1930    PartialOrd,
1931    Serialize,
1932    Deserialize,
1933    Hash
1934)]
1935pub enum AggregateFunc {
1936    MaxNumeric,
1937    MaxInt16,
1938    MaxInt32,
1939    MaxInt64,
1940    MaxUInt16,
1941    MaxUInt32,
1942    MaxUInt64,
1943    MaxMzTimestamp,
1944    MaxFloat32,
1945    MaxFloat64,
1946    MaxBool,
1947    MaxString,
1948    MaxDate,
1949    MaxTimestamp,
1950    MaxTimestampTz,
1951    MaxInterval,
1952    MaxTime,
1953    MaxArray,
1954    MaxList,
1955    MinNumeric,
1956    MinInt16,
1957    MinInt32,
1958    MinInt64,
1959    MinUInt16,
1960    MinUInt32,
1961    MinUInt64,
1962    MinMzTimestamp,
1963    MinFloat32,
1964    MinFloat64,
1965    MinBool,
1966    MinString,
1967    MinDate,
1968    MinTimestamp,
1969    MinTimestampTz,
1970    MinInterval,
1971    MinTime,
1972    MinArray,
1973    MinList,
1974    SumInt16,
1975    SumInt32,
1976    SumInt64,
1977    SumUInt16,
1978    SumUInt32,
1979    SumUInt64,
1980    SumFloat32,
1981    SumFloat64,
1982    SumNumeric,
1983    SumInterval,
1984    Count,
1985    Any,
1986    All,
1987    /// Accumulates `Datum::List`s whose first element is a JSON-typed `Datum`s
1988    /// into a JSON list. The other elements are columns used by `order_by`.
1989    ///
1990    /// WARNING: Unlike the `jsonb_agg` function that is exposed by the SQL
1991    /// layer, this function filters out `Datum::Null`, for consistency with
1992    /// the other aggregate functions.
1993    JsonbAgg {
1994        order_by: Vec<ColumnOrder>,
1995    },
1996    /// Zips `Datum::List`s whose first element is a JSON-typed `Datum`s into a
1997    /// JSON map. The other elements are columns used by `order_by`.
1998    ///
1999    /// WARNING: Unlike the `jsonb_object_agg` function that is exposed by the SQL
2000    /// layer, this function filters out `Datum::Null`, for consistency with
2001    /// the other aggregate functions.
2002    JsonbObjectAgg {
2003        order_by: Vec<ColumnOrder>,
2004    },
2005    /// Zips a `Datum::List` whose first element is a `Datum::List` guaranteed
2006    /// to be non-empty and whose len % 2 == 0 into a `Datum::Map`. The other
2007    /// elements are columns used by `order_by`.
2008    MapAgg {
2009        order_by: Vec<ColumnOrder>,
2010        value_type: SqlScalarType,
2011    },
2012    /// Accumulates `Datum::Array`s of `SqlScalarType::Record` whose first element is a `Datum::Array`
2013    /// into a single `Datum::Array` (the remaining fields are used by `order_by`).
2014    ArrayConcat {
2015        order_by: Vec<ColumnOrder>,
2016    },
2017    /// Accumulates `Datum::List`s of `SqlScalarType::Record` whose first field is a `Datum::List`
2018    /// into a single `Datum::List` (the remaining fields are used by `order_by`).
2019    ListConcat {
2020        order_by: Vec<ColumnOrder>,
2021    },
2022    StringAgg {
2023        order_by: Vec<ColumnOrder>,
2024    },
2025    RowNumber {
2026        order_by: Vec<ColumnOrder>,
2027    },
2028    Rank {
2029        order_by: Vec<ColumnOrder>,
2030    },
2031    DenseRank {
2032        order_by: Vec<ColumnOrder>,
2033    },
2034    LagLead {
2035        order_by: Vec<ColumnOrder>,
2036        lag_lead: LagLeadType,
2037        ignore_nulls: bool,
2038    },
2039    FirstValue {
2040        order_by: Vec<ColumnOrder>,
2041        window_frame: WindowFrame,
2042    },
2043    LastValue {
2044        order_by: Vec<ColumnOrder>,
2045        window_frame: WindowFrame,
2046    },
2047    /// Several value window functions fused into one function, to amortize overheads.
2048    FusedValueWindowFunc {
2049        funcs: Vec<AggregateFunc>,
2050        /// Currently, all the fused functions must have the same `order_by`. (We can later
2051        /// eliminate this limitation.)
2052        order_by: Vec<ColumnOrder>,
2053    },
2054    WindowAggregate {
2055        wrapped_aggregate: Box<AggregateFunc>,
2056        order_by: Vec<ColumnOrder>,
2057        window_frame: WindowFrame,
2058    },
2059    FusedWindowAggregate {
2060        wrapped_aggregates: Vec<AggregateFunc>,
2061        order_by: Vec<ColumnOrder>,
2062        window_frame: WindowFrame,
2063    },
2064    /// Accumulates any number of `Datum::Dummy`s into `Datum::Dummy`.
2065    ///
2066    /// Useful for removing an expensive aggregation while maintaining the shape
2067    /// of a reduce operator.
2068    Dummy,
2069}
2070
2071/// Expands an iterator of `(datum, diff)` into one `datum` per unit of `diff`.
2072///
2073/// A non-positive `diff` contributes no copies. This is used by aggregates that
2074/// are sensitive to multiplicity (e.g. `sum`), to recover a flat datum stream
2075/// from the count-aware surface.
2076fn expand_counts<'a, I>(datums: I) -> impl Iterator<Item = Datum<'a>>
2077where
2078    I: IntoIterator<Item = (Datum<'a>, Diff)>,
2079{
2080    datums.into_iter().flat_map(|(datum, diff)| {
2081        let copies = usize::try_from(diff.into_inner()).unwrap_or(0);
2082        std::iter::repeat(datum).take(copies)
2083    })
2084}
2085
2086impl AggregateFunc {
2087    /// Whether this aggregate's result is independent of the multiplicity of its
2088    /// inputs (e.g. `min`/`max`/`any`/`all`).
2089    ///
2090    /// Such aggregates can ignore the `diff` of each input, evaluating over the
2091    /// distinct datums rather than expanding by count. This keeps idempotent
2092    /// reductions linear in the number of distinct inputs.
2093    fn ignores_multiplicity(&self) -> bool {
2094        use AggregateFunc::*;
2095        matches!(
2096            self,
2097            MaxNumeric
2098                | MaxInt16
2099                | MaxInt32
2100                | MaxInt64
2101                | MaxUInt16
2102                | MaxUInt32
2103                | MaxUInt64
2104                | MaxMzTimestamp
2105                | MaxFloat32
2106                | MaxFloat64
2107                | MaxBool
2108                | MaxString
2109                | MaxDate
2110                | MaxTimestamp
2111                | MaxTimestampTz
2112                | MaxInterval
2113                | MaxTime
2114                | MaxArray
2115                | MaxList
2116                | MinNumeric
2117                | MinInt16
2118                | MinInt32
2119                | MinInt64
2120                | MinUInt16
2121                | MinUInt32
2122                | MinUInt64
2123                | MinMzTimestamp
2124                | MinFloat32
2125                | MinFloat64
2126                | MinBool
2127                | MinString
2128                | MinDate
2129                | MinTimestamp
2130                | MinTimestampTz
2131                | MinInterval
2132                | MinTime
2133                | MinArray
2134                | MinList
2135                | Any
2136                | All
2137        )
2138    }
2139
2140    /// Evaluates the aggregate over an iterator of `(datum, diff)` pairs.
2141    ///
2142    /// Each aggregate consumes the multiplicity (`diff`) in whatever way is most
2143    /// efficient: `count` sums the diffs, multiplicity-insensitive aggregates
2144    /// (see `AggregateFunc::ignores_multiplicity`) ignore them, and everything
2145    /// else expands each datum into `diff` copies (see `expand_counts`).
2146    pub fn eval<'a, I>(&self, datums: I, temp_storage: &'a RowArena) -> Datum<'a>
2147    where
2148        I: IntoIterator<Item = (Datum<'a>, Diff)>,
2149    {
2150        // Accumulable aggregates consume multiplicity directly rather than
2151        // expanding each `(datum, diff)` into `diff` copies. The cases handled
2152        // here mirror the dataflow's accumulable reduction (`build_accumulable`
2153        // in `mz_compute::render::reduce`) so that constant folding produces the
2154        // same result the dataflow would. Signed integer and interval sums are
2155        // folded here; unsigned sums are not, because their
2156        // negative-accumulation case is a query error in the dataflow that this
2157        // `Datum`-returning path cannot signal. Floats and numerics use bespoke
2158        // fixed-point/wide-decimal accumulators in the dataflow that
2159        // `expand_counts` does not reproduce.
2160        match self {
2161            AggregateFunc::Count => count(datums),
2162            AggregateFunc::SumInt16 | AggregateFunc::SumInt32 => {
2163                // `finalize_accum` narrows these to `i64` with wrapping.
2164                sum_signed_int_counted(datums, |accum| {
2165                    #[allow(clippy::as_conversions)]
2166                    let narrowed = accum as i64;
2167                    Datum::Int64(narrowed)
2168                })
2169            }
2170            AggregateFunc::SumInt64 => sum_signed_int_counted(datums, Datum::from),
2171            AggregateFunc::SumInterval => sum_interval_counted(datums),
2172            _ if self.ignores_multiplicity() => {
2173                self.eval_datums(datums.into_iter().map(|(datum, _diff)| datum), temp_storage)
2174            }
2175            _ => self.eval_datums(expand_counts(datums), temp_storage),
2176        }
2177    }
2178
2179    /// Evaluates the aggregate over a flat iterator of datums, ignoring multiplicity.
2180    fn eval_datums<'a, I>(&self, datums: I, temp_storage: &'a RowArena) -> Datum<'a>
2181    where
2182        I: IntoIterator<Item = Datum<'a>>,
2183    {
2184        match self {
2185            AggregateFunc::MaxNumeric => {
2186                max_datum::<'a, I, OrderedDecimal<numeric::Numeric>>(datums)
2187            }
2188            AggregateFunc::MaxInt16 => max_datum::<'a, I, i16>(datums),
2189            AggregateFunc::MaxInt32 => max_datum::<'a, I, i32>(datums),
2190            AggregateFunc::MaxInt64 => max_datum::<'a, I, i64>(datums),
2191            AggregateFunc::MaxUInt16 => max_datum::<'a, I, u16>(datums),
2192            AggregateFunc::MaxUInt32 => max_datum::<'a, I, u32>(datums),
2193            AggregateFunc::MaxUInt64 => max_datum::<'a, I, u64>(datums),
2194            AggregateFunc::MaxMzTimestamp => max_datum::<'a, I, mz_repr::Timestamp>(datums),
2195            AggregateFunc::MaxFloat32 => max_datum::<'a, I, OrderedFloat<f32>>(datums),
2196            AggregateFunc::MaxFloat64 => max_datum::<'a, I, OrderedFloat<f64>>(datums),
2197            AggregateFunc::MaxBool => max_datum::<'a, I, bool>(datums),
2198            AggregateFunc::MaxString => max_string(datums),
2199            AggregateFunc::MaxDate => max_datum::<'a, I, Date>(datums),
2200            AggregateFunc::MaxTimestamp => {
2201                max_datum::<'a, I, CheckedTimestamp<NaiveDateTime>>(datums)
2202            }
2203            AggregateFunc::MaxTimestampTz => {
2204                max_datum::<'a, I, CheckedTimestamp<DateTime<Utc>>>(datums)
2205            }
2206            AggregateFunc::MaxInterval => max_datum::<'a, I, Interval>(datums),
2207            AggregateFunc::MaxTime => max_datum::<'a, I, NaiveTime>(datums),
2208            AggregateFunc::MaxArray | AggregateFunc::MaxList => {
2209                max_datum::<'a, I, Datum<'a>>(datums)
2210            }
2211            AggregateFunc::MinNumeric => {
2212                min_datum::<'a, I, OrderedDecimal<numeric::Numeric>>(datums)
2213            }
2214            AggregateFunc::MinInt16 => min_datum::<'a, I, i16>(datums),
2215            AggregateFunc::MinInt32 => min_datum::<'a, I, i32>(datums),
2216            AggregateFunc::MinInt64 => min_datum::<'a, I, i64>(datums),
2217            AggregateFunc::MinUInt16 => min_datum::<'a, I, u16>(datums),
2218            AggregateFunc::MinUInt32 => min_datum::<'a, I, u32>(datums),
2219            AggregateFunc::MinUInt64 => min_datum::<'a, I, u64>(datums),
2220            AggregateFunc::MinMzTimestamp => min_datum::<'a, I, mz_repr::Timestamp>(datums),
2221            AggregateFunc::MinFloat32 => min_datum::<'a, I, OrderedFloat<f32>>(datums),
2222            AggregateFunc::MinFloat64 => min_datum::<'a, I, OrderedFloat<f64>>(datums),
2223            AggregateFunc::MinBool => min_datum::<'a, I, bool>(datums),
2224            AggregateFunc::MinString => min_string(datums),
2225            AggregateFunc::MinDate => min_datum::<'a, I, Date>(datums),
2226            AggregateFunc::MinTimestamp => {
2227                min_datum::<'a, I, CheckedTimestamp<NaiveDateTime>>(datums)
2228            }
2229            AggregateFunc::MinTimestampTz => {
2230                min_datum::<'a, I, CheckedTimestamp<DateTime<Utc>>>(datums)
2231            }
2232            AggregateFunc::MinInterval => min_datum::<'a, I, Interval>(datums),
2233            AggregateFunc::MinTime => min_datum::<'a, I, NaiveTime>(datums),
2234            AggregateFunc::MinArray | AggregateFunc::MinList => {
2235                min_datum::<'a, I, Datum<'a>>(datums)
2236            }
2237            AggregateFunc::SumInt16 => sum_datum::<'a, I, i16, i64>(datums),
2238            AggregateFunc::SumInt32 => sum_datum::<'a, I, i32, i64>(datums),
2239            AggregateFunc::SumInt64 => sum_datum::<'a, I, i64, i128>(datums),
2240            AggregateFunc::SumUInt16 => sum_datum::<'a, I, u16, u64>(datums),
2241            AggregateFunc::SumUInt32 => sum_datum::<'a, I, u32, u64>(datums),
2242            AggregateFunc::SumUInt64 => sum_datum::<'a, I, u64, u128>(datums),
2243            AggregateFunc::SumFloat32 => sum_datum::<'a, I, f32, f32>(datums),
2244            AggregateFunc::SumFloat64 => sum_datum::<'a, I, f64, f64>(datums),
2245            AggregateFunc::SumNumeric => sum_numeric(datums),
2246            AggregateFunc::SumInterval => sum_interval(datums),
2247            AggregateFunc::Count => unreachable!("Count is handled in `eval`"),
2248            AggregateFunc::Any => any(datums),
2249            AggregateFunc::All => all(datums),
2250            AggregateFunc::JsonbAgg { order_by } => jsonb_agg(datums, temp_storage, order_by),
2251            AggregateFunc::MapAgg { order_by, .. } | AggregateFunc::JsonbObjectAgg { order_by } => {
2252                dict_agg(datums, temp_storage, order_by)
2253            }
2254            AggregateFunc::ArrayConcat { order_by } => array_concat(datums, temp_storage, order_by),
2255            AggregateFunc::ListConcat { order_by } => list_concat(datums, temp_storage, order_by),
2256            AggregateFunc::StringAgg { order_by } => string_agg(datums, temp_storage, order_by),
2257            AggregateFunc::RowNumber { order_by } => row_number(datums, temp_storage, order_by),
2258            AggregateFunc::Rank { order_by } => rank(datums, temp_storage, order_by),
2259            AggregateFunc::DenseRank { order_by } => dense_rank(datums, temp_storage, order_by),
2260            AggregateFunc::LagLead {
2261                order_by,
2262                lag_lead: lag_lead_type,
2263                ignore_nulls,
2264            } => lag_lead(datums, temp_storage, order_by, lag_lead_type, ignore_nulls),
2265            AggregateFunc::FirstValue {
2266                order_by,
2267                window_frame,
2268            } => first_value(datums, temp_storage, order_by, window_frame),
2269            AggregateFunc::LastValue {
2270                order_by,
2271                window_frame,
2272            } => last_value(datums, temp_storage, order_by, window_frame),
2273            AggregateFunc::WindowAggregate {
2274                wrapped_aggregate,
2275                order_by,
2276                window_frame,
2277            } => window_aggr::<_, NaiveOneByOneAggr>(
2278                datums,
2279                temp_storage,
2280                wrapped_aggregate,
2281                order_by,
2282                window_frame,
2283            ),
2284            AggregateFunc::FusedValueWindowFunc { funcs, order_by } => {
2285                fused_value_window_func(datums, temp_storage, funcs, order_by)
2286            }
2287            AggregateFunc::FusedWindowAggregate {
2288                wrapped_aggregates,
2289                order_by,
2290                window_frame,
2291            } => fused_window_aggr::<_, NaiveOneByOneAggr>(
2292                datums,
2293                temp_storage,
2294                wrapped_aggregates,
2295                order_by,
2296                window_frame,
2297            ),
2298            AggregateFunc::Dummy => Datum::Dummy,
2299        }
2300    }
2301
2302    /// Like `eval`, but it's given a [OneByOneAggr]. If `self` is a `WindowAggregate`, then
2303    /// the given [OneByOneAggr] will be used to evaluate the wrapped aggregate inside the
2304    /// `WindowAggregate`. If `self` is not a `WindowAggregate`, then it simply calls `eval`.
2305    pub fn eval_with_fast_window_agg<'a, I, W>(
2306        &self,
2307        datums: I,
2308        temp_storage: &'a RowArena,
2309    ) -> Datum<'a>
2310    where
2311        I: IntoIterator<Item = (Datum<'a>, Diff)>,
2312        W: OneByOneAggr,
2313    {
2314        match self {
2315            AggregateFunc::WindowAggregate {
2316                wrapped_aggregate,
2317                order_by,
2318                window_frame,
2319            } => window_aggr::<_, W>(
2320                expand_counts(datums),
2321                temp_storage,
2322                wrapped_aggregate,
2323                order_by,
2324                window_frame,
2325            ),
2326            AggregateFunc::FusedWindowAggregate {
2327                wrapped_aggregates,
2328                order_by,
2329                window_frame,
2330            } => fused_window_aggr::<_, W>(
2331                expand_counts(datums),
2332                temp_storage,
2333                wrapped_aggregates,
2334                order_by,
2335                window_frame,
2336            ),
2337            _ => self.eval(datums, temp_storage),
2338        }
2339    }
2340
2341    pub fn eval_with_unnest_list<'a, I, W>(
2342        &self,
2343        datums: I,
2344        temp_storage: &'a RowArena,
2345    ) -> impl Iterator<Item = Datum<'a>>
2346    where
2347        I: IntoIterator<Item = (Datum<'a>, Diff)>,
2348        W: OneByOneAggr,
2349    {
2350        // TODO: Use `enum_dispatch` to construct a unified iterator instead of `collect_vec`.
2351        assert!(self.can_fuse_with_unnest_list());
2352        // Window functions are sensitive to multiplicity, so expand counts.
2353        let datums = expand_counts(datums);
2354        match self {
2355            AggregateFunc::RowNumber { order_by } => {
2356                row_number_no_list(datums, temp_storage, order_by).collect_vec()
2357            }
2358            AggregateFunc::Rank { order_by } => {
2359                rank_no_list(datums, temp_storage, order_by).collect_vec()
2360            }
2361            AggregateFunc::DenseRank { order_by } => {
2362                dense_rank_no_list(datums, temp_storage, order_by).collect_vec()
2363            }
2364            AggregateFunc::LagLead {
2365                order_by,
2366                lag_lead: lag_lead_type,
2367                ignore_nulls,
2368            } => lag_lead_no_list(datums, temp_storage, order_by, lag_lead_type, ignore_nulls)
2369                .collect_vec(),
2370            AggregateFunc::FirstValue {
2371                order_by,
2372                window_frame,
2373            } => first_value_no_list(datums, temp_storage, order_by, window_frame).collect_vec(),
2374            AggregateFunc::LastValue {
2375                order_by,
2376                window_frame,
2377            } => last_value_no_list(datums, temp_storage, order_by, window_frame).collect_vec(),
2378            AggregateFunc::FusedValueWindowFunc { funcs, order_by } => {
2379                fused_value_window_func_no_list(datums, temp_storage, funcs, order_by).collect_vec()
2380            }
2381            AggregateFunc::WindowAggregate {
2382                wrapped_aggregate,
2383                order_by,
2384                window_frame,
2385            } => window_aggr_no_list::<_, W>(
2386                datums,
2387                temp_storage,
2388                wrapped_aggregate,
2389                order_by,
2390                window_frame,
2391            )
2392            .collect_vec(),
2393            AggregateFunc::FusedWindowAggregate {
2394                wrapped_aggregates,
2395                order_by,
2396                window_frame,
2397            } => fused_window_aggr_no_list::<_, W>(
2398                datums,
2399                temp_storage,
2400                wrapped_aggregates,
2401                order_by,
2402                window_frame,
2403            )
2404            .collect_vec(),
2405            _ => unreachable!("asserted above that `can_fuse_with_unnest_list`"),
2406        }
2407        .into_iter()
2408    }
2409
2410    /// Returns the output of the aggregation function when applied on an empty
2411    /// input relation.
2412    pub fn default(&self) -> Datum<'static> {
2413        match self {
2414            AggregateFunc::Count => Datum::Int64(0),
2415            AggregateFunc::Any => Datum::False,
2416            AggregateFunc::All => Datum::True,
2417            AggregateFunc::Dummy => Datum::Dummy,
2418            _ => Datum::Null,
2419        }
2420    }
2421
2422    /// Returns a datum whose inclusion in the aggregation will not change its
2423    /// result.
2424    pub fn identity_datum(&self) -> Datum<'static> {
2425        match self {
2426            AggregateFunc::Any => Datum::False,
2427            AggregateFunc::All => Datum::True,
2428            AggregateFunc::Dummy => Datum::Dummy,
2429            AggregateFunc::ArrayConcat { .. } => Datum::empty_array(),
2430            AggregateFunc::ListConcat { .. } => Datum::empty_list(),
2431            AggregateFunc::RowNumber { .. }
2432            | AggregateFunc::Rank { .. }
2433            | AggregateFunc::DenseRank { .. }
2434            | AggregateFunc::LagLead { .. }
2435            | AggregateFunc::FirstValue { .. }
2436            | AggregateFunc::LastValue { .. }
2437            | AggregateFunc::WindowAggregate { .. }
2438            | AggregateFunc::FusedValueWindowFunc { .. }
2439            | AggregateFunc::FusedWindowAggregate { .. } => Datum::empty_list(),
2440            AggregateFunc::MaxNumeric
2441            | AggregateFunc::MaxInt16
2442            | AggregateFunc::MaxInt32
2443            | AggregateFunc::MaxInt64
2444            | AggregateFunc::MaxUInt16
2445            | AggregateFunc::MaxUInt32
2446            | AggregateFunc::MaxUInt64
2447            | AggregateFunc::MaxMzTimestamp
2448            | AggregateFunc::MaxFloat32
2449            | AggregateFunc::MaxFloat64
2450            | AggregateFunc::MaxBool
2451            | AggregateFunc::MaxString
2452            | AggregateFunc::MaxDate
2453            | AggregateFunc::MaxTimestamp
2454            | AggregateFunc::MaxTimestampTz
2455            | AggregateFunc::MaxInterval
2456            | AggregateFunc::MaxTime
2457            | AggregateFunc::MaxArray
2458            | AggregateFunc::MaxList
2459            | AggregateFunc::MinNumeric
2460            | AggregateFunc::MinInt16
2461            | AggregateFunc::MinInt32
2462            | AggregateFunc::MinInt64
2463            | AggregateFunc::MinUInt16
2464            | AggregateFunc::MinUInt32
2465            | AggregateFunc::MinUInt64
2466            | AggregateFunc::MinMzTimestamp
2467            | AggregateFunc::MinFloat32
2468            | AggregateFunc::MinFloat64
2469            | AggregateFunc::MinBool
2470            | AggregateFunc::MinString
2471            | AggregateFunc::MinDate
2472            | AggregateFunc::MinTimestamp
2473            | AggregateFunc::MinTimestampTz
2474            | AggregateFunc::MinInterval
2475            | AggregateFunc::MinTime
2476            | AggregateFunc::MinArray
2477            | AggregateFunc::MinList
2478            | AggregateFunc::SumInt16
2479            | AggregateFunc::SumInt32
2480            | AggregateFunc::SumInt64
2481            | AggregateFunc::SumUInt16
2482            | AggregateFunc::SumUInt32
2483            | AggregateFunc::SumUInt64
2484            | AggregateFunc::SumFloat32
2485            | AggregateFunc::SumFloat64
2486            | AggregateFunc::SumNumeric
2487            | AggregateFunc::SumInterval
2488            | AggregateFunc::Count
2489            | AggregateFunc::JsonbAgg { .. }
2490            | AggregateFunc::JsonbObjectAgg { .. }
2491            | AggregateFunc::MapAgg { .. }
2492            | AggregateFunc::StringAgg { .. } => Datum::Null,
2493        }
2494    }
2495
2496    pub fn can_fuse_with_unnest_list(&self) -> bool {
2497        match self {
2498            AggregateFunc::RowNumber { .. }
2499            | AggregateFunc::Rank { .. }
2500            | AggregateFunc::DenseRank { .. }
2501            | AggregateFunc::LagLead { .. }
2502            | AggregateFunc::FirstValue { .. }
2503            | AggregateFunc::LastValue { .. }
2504            | AggregateFunc::WindowAggregate { .. }
2505            | AggregateFunc::FusedValueWindowFunc { .. }
2506            | AggregateFunc::FusedWindowAggregate { .. } => true,
2507            AggregateFunc::ArrayConcat { .. }
2508            | AggregateFunc::ListConcat { .. }
2509            | AggregateFunc::Any
2510            | AggregateFunc::All
2511            | AggregateFunc::Dummy
2512            | AggregateFunc::MaxNumeric
2513            | AggregateFunc::MaxInt16
2514            | AggregateFunc::MaxInt32
2515            | AggregateFunc::MaxInt64
2516            | AggregateFunc::MaxUInt16
2517            | AggregateFunc::MaxUInt32
2518            | AggregateFunc::MaxUInt64
2519            | AggregateFunc::MaxMzTimestamp
2520            | AggregateFunc::MaxFloat32
2521            | AggregateFunc::MaxFloat64
2522            | AggregateFunc::MaxBool
2523            | AggregateFunc::MaxString
2524            | AggregateFunc::MaxDate
2525            | AggregateFunc::MaxTimestamp
2526            | AggregateFunc::MaxTimestampTz
2527            | AggregateFunc::MaxInterval
2528            | AggregateFunc::MaxTime
2529            | AggregateFunc::MaxArray
2530            | AggregateFunc::MaxList
2531            | AggregateFunc::MinNumeric
2532            | AggregateFunc::MinInt16
2533            | AggregateFunc::MinInt32
2534            | AggregateFunc::MinInt64
2535            | AggregateFunc::MinUInt16
2536            | AggregateFunc::MinUInt32
2537            | AggregateFunc::MinUInt64
2538            | AggregateFunc::MinMzTimestamp
2539            | AggregateFunc::MinFloat32
2540            | AggregateFunc::MinFloat64
2541            | AggregateFunc::MinBool
2542            | AggregateFunc::MinString
2543            | AggregateFunc::MinDate
2544            | AggregateFunc::MinTimestamp
2545            | AggregateFunc::MinTimestampTz
2546            | AggregateFunc::MinInterval
2547            | AggregateFunc::MinTime
2548            | AggregateFunc::MinArray
2549            | AggregateFunc::MinList
2550            | AggregateFunc::SumInt16
2551            | AggregateFunc::SumInt32
2552            | AggregateFunc::SumInt64
2553            | AggregateFunc::SumUInt16
2554            | AggregateFunc::SumUInt32
2555            | AggregateFunc::SumUInt64
2556            | AggregateFunc::SumFloat32
2557            | AggregateFunc::SumFloat64
2558            | AggregateFunc::SumNumeric
2559            | AggregateFunc::SumInterval
2560            | AggregateFunc::Count
2561            | AggregateFunc::JsonbAgg { .. }
2562            | AggregateFunc::JsonbObjectAgg { .. }
2563            | AggregateFunc::MapAgg { .. }
2564            | AggregateFunc::StringAgg { .. } => false,
2565        }
2566    }
2567
2568    /// The output column type for the result of an aggregation.
2569    ///
2570    /// The output column type also contains nullability information, which
2571    /// is (without further information) true for aggregations that are not
2572    /// counts.
2573    pub fn output_sql_type(&self, input_type: SqlColumnType) -> SqlColumnType {
2574        let scalar_type = match self {
2575            AggregateFunc::Count => SqlScalarType::Int64,
2576            AggregateFunc::Any => SqlScalarType::Bool,
2577            AggregateFunc::All => SqlScalarType::Bool,
2578            AggregateFunc::JsonbAgg { .. } => SqlScalarType::Jsonb,
2579            AggregateFunc::JsonbObjectAgg { .. } => SqlScalarType::Jsonb,
2580            AggregateFunc::SumInt16 => SqlScalarType::Int64,
2581            AggregateFunc::SumInt32 => SqlScalarType::Int64,
2582            AggregateFunc::SumInt64 => SqlScalarType::Numeric {
2583                max_scale: Some(NumericMaxScale::ZERO),
2584            },
2585            AggregateFunc::SumUInt16 => SqlScalarType::UInt64,
2586            AggregateFunc::SumUInt32 => SqlScalarType::UInt64,
2587            AggregateFunc::SumUInt64 => SqlScalarType::Numeric {
2588                max_scale: Some(NumericMaxScale::ZERO),
2589            },
2590            AggregateFunc::MapAgg { value_type, .. } => SqlScalarType::Map {
2591                value_type: Box::new(value_type.clone()),
2592                custom_id: None,
2593            },
2594            AggregateFunc::ArrayConcat { .. } | AggregateFunc::ListConcat { .. } => {
2595                match input_type.scalar_type {
2596                    // The input is wrapped in a Record if there's an ORDER BY, so extract it out.
2597                    SqlScalarType::Record { ref fields, .. } => fields[0].1.scalar_type.clone(),
2598                    _ => unreachable!(),
2599                }
2600            }
2601            AggregateFunc::StringAgg { .. } => SqlScalarType::String,
2602            AggregateFunc::RowNumber { .. } => {
2603                AggregateFunc::output_type_ranking_window_funcs(&input_type, "?row_number?")
2604            }
2605            AggregateFunc::Rank { .. } => {
2606                AggregateFunc::output_type_ranking_window_funcs(&input_type, "?rank?")
2607            }
2608            AggregateFunc::DenseRank { .. } => {
2609                AggregateFunc::output_type_ranking_window_funcs(&input_type, "?dense_rank?")
2610            }
2611            AggregateFunc::LagLead { lag_lead: lag_lead_type, .. } => {
2612                // The input type for Lag is ((OriginalRow, EncodedArgs), OrderByExprs...)
2613                let fields = input_type.scalar_type.unwrap_record_element_type();
2614                let original_row_type = fields[0].unwrap_record_element_type()[0]
2615                    .clone()
2616                    .nullable(false);
2617                let encoded_args = fields[0].unwrap_record_element_type()[1];
2618                let output_type_inner =
2619                    Self::lag_lead_output_type_inner_from_encoded_args(encoded_args);
2620                let column_name = Self::lag_lead_result_column_name(lag_lead_type);
2621
2622                SqlScalarType::List {
2623                    element_type: Box::new(SqlScalarType::Record {
2624                        fields: [
2625                            (column_name, output_type_inner),
2626                            (ColumnName::from("?orig_row?"), original_row_type),
2627                        ].into(),
2628                        custom_id: None,
2629                    }),
2630                    custom_id: None,
2631                }
2632            }
2633            AggregateFunc::FirstValue { .. } => {
2634                // The input type for FirstValue is ((OriginalRow, Arg), OrderByExprs...)
2635                let fields = input_type.scalar_type.unwrap_record_element_type();
2636                let original_row_type = fields[0].unwrap_record_element_type()[0]
2637                    .clone()
2638                    .nullable(false);
2639                let value_type = fields[0].unwrap_record_element_type()[1]
2640                    .clone()
2641                    .nullable(true); // null when the partition is empty
2642
2643                SqlScalarType::List {
2644                    element_type: Box::new(SqlScalarType::Record {
2645                        fields: [
2646                            (ColumnName::from("?first_value?"), value_type),
2647                            (ColumnName::from("?orig_row?"), original_row_type),
2648                        ].into(),
2649                        custom_id: None,
2650                    }),
2651                    custom_id: None,
2652                }
2653            }
2654            AggregateFunc::LastValue { .. } => {
2655                // The input type for LastValue is ((OriginalRow, Arg), OrderByExprs...)
2656                let fields = input_type.scalar_type.unwrap_record_element_type();
2657                let original_row_type = fields[0].unwrap_record_element_type()[0]
2658                    .clone()
2659                    .nullable(false);
2660                let value_type = fields[0].unwrap_record_element_type()[1]
2661                    .clone()
2662                    .nullable(true); // null when the partition is empty
2663
2664                SqlScalarType::List {
2665                    element_type: Box::new(SqlScalarType::Record {
2666                        fields: [
2667                            (ColumnName::from("?last_value?"), value_type),
2668                            (ColumnName::from("?orig_row?"), original_row_type),
2669                        ].into(),
2670                        custom_id: None,
2671                    }),
2672                    custom_id: None,
2673                }
2674            }
2675            AggregateFunc::WindowAggregate {
2676                wrapped_aggregate, ..
2677            } => {
2678                // The input type for a window aggregate is ((OriginalRow, Arg), OrderByExprs...)
2679                let fields = input_type.scalar_type.unwrap_record_element_type();
2680                let original_row_type = fields[0].unwrap_record_element_type()[0]
2681                    .clone()
2682                    .nullable(false);
2683                let arg_type = fields[0].unwrap_record_element_type()[1]
2684                    .clone()
2685                    .nullable(true);
2686                let wrapped_aggr_out_type = wrapped_aggregate.output_sql_type(arg_type);
2687
2688                SqlScalarType::List {
2689                    element_type: Box::new(SqlScalarType::Record {
2690                        fields: [
2691                            (ColumnName::from("?window_agg?"), wrapped_aggr_out_type),
2692                            (ColumnName::from("?orig_row?"), original_row_type),
2693                        ].into(),
2694                        custom_id: None,
2695                    }),
2696                    custom_id: None,
2697                }
2698            }
2699            AggregateFunc::FusedWindowAggregate {
2700                wrapped_aggregates, ..
2701            } => {
2702                // The input type for a fused window aggregate is ((OriginalRow, Args), OrderByExprs...)
2703                // where `Args` is a record.
2704                let fields = input_type.scalar_type.unwrap_record_element_type();
2705                let original_row_type = fields[0].unwrap_record_element_type()[0]
2706                    .clone()
2707                    .nullable(false);
2708                let args_type = fields[0].unwrap_record_element_type()[1];
2709                let arg_types = args_type.unwrap_record_element_type();
2710                let out_fields = arg_types.iter().zip_eq(wrapped_aggregates).map(
2711                    |(arg_type, wrapped_agg)| {
2712                    (
2713                        ColumnName::from(wrapped_agg.name()),
2714                        wrapped_agg.output_sql_type((**arg_type).clone().nullable(true)),
2715                    )
2716                }).collect_vec();
2717
2718                SqlScalarType::List {
2719                    element_type: Box::new(SqlScalarType::Record {
2720                        fields: [
2721                            (ColumnName::from("?fused_window_agg?"), SqlScalarType::Record {
2722                                fields: out_fields.into(),
2723                                custom_id: None,
2724                            }.nullable(false)),
2725                            (ColumnName::from("?orig_row?"), original_row_type),
2726                        ].into(),
2727                        custom_id: None,
2728                    }),
2729                    custom_id: None,
2730                }
2731            }
2732            AggregateFunc::FusedValueWindowFunc { funcs, order_by: _ } => {
2733                // The input type is ((OriginalRow, EncodedArgs), OrderByExprs...)
2734                // where EncodedArgs is a record, where each element is the argument to one of the
2735                // function calls that got fused. This is a record for lag/lead, and a simple type
2736                // for first_value/last_value.
2737                let fields = input_type.scalar_type.unwrap_record_element_type();
2738                let original_row_type = fields[0].unwrap_record_element_type()[0]
2739                    .clone()
2740                    .nullable(false);
2741                let encoded_args_type = fields[0]
2742                    .unwrap_record_element_type()[1]
2743                    .unwrap_record_element_type();
2744
2745                SqlScalarType::List {
2746                    element_type: Box::new(SqlScalarType::Record {
2747                        fields: [
2748                            (
2749                                ColumnName::from("?fused_value_window_func?"),
2750                                SqlScalarType::Record {
2751                                fields: encoded_args_type.into_iter().zip_eq(funcs).map(
2752                                    |(arg_type, func)| {
2753                                    match func {
2754                                        AggregateFunc::LagLead {
2755                                            lag_lead: lag_lead_type, ..
2756                                        } => {
2757                                            let name = Self::lag_lead_result_column_name(
2758                                                lag_lead_type,
2759                                            );
2760                                            let ty = Self
2761                                                ::lag_lead_output_type_inner_from_encoded_args(
2762                                                    arg_type,
2763                                                );
2764                                            (name, ty)
2765                                        },
2766                                        AggregateFunc::FirstValue { .. } => {
2767                                            (
2768                                                ColumnName::from("?first_value?"),
2769                                                arg_type.clone().nullable(true),
2770                                            )
2771                                        }
2772                                        AggregateFunc::LastValue { .. } => {
2773                                            (
2774                                                ColumnName::from("?last_value?"),
2775                                                arg_type.clone().nullable(true),
2776                                            )
2777                                        }
2778                                        _ => panic!("FusedValueWindowFunc has an unknown function"),
2779                                    }
2780                                }).collect(),
2781                                custom_id: None,
2782                            }.nullable(false)),
2783                            (ColumnName::from("?orig_row?"), original_row_type),
2784                        ].into(),
2785                        custom_id: None,
2786                    }),
2787                    custom_id: None,
2788                }
2789            }
2790            AggregateFunc::Dummy
2791            | AggregateFunc::MaxNumeric
2792            | AggregateFunc::MaxInt16
2793            | AggregateFunc::MaxInt32
2794            | AggregateFunc::MaxInt64
2795            | AggregateFunc::MaxUInt16
2796            | AggregateFunc::MaxUInt32
2797            | AggregateFunc::MaxUInt64
2798            | AggregateFunc::MaxMzTimestamp
2799            | AggregateFunc::MaxFloat32
2800            | AggregateFunc::MaxFloat64
2801            | AggregateFunc::MaxBool
2802            // Note AggregateFunc::MaxString, MinString rely on returning input
2803            // type as output type to support the proper return type for
2804            // character input.
2805            | AggregateFunc::MaxString
2806            | AggregateFunc::MaxDate
2807            | AggregateFunc::MaxTimestamp
2808            | AggregateFunc::MaxTimestampTz
2809            | AggregateFunc::MaxInterval
2810            | AggregateFunc::MaxTime
2811            | AggregateFunc::MaxArray
2812            | AggregateFunc::MaxList
2813            | AggregateFunc::MinNumeric
2814            | AggregateFunc::MinInt16
2815            | AggregateFunc::MinInt32
2816            | AggregateFunc::MinInt64
2817            | AggregateFunc::MinUInt16
2818            | AggregateFunc::MinUInt32
2819            | AggregateFunc::MinUInt64
2820            | AggregateFunc::MinMzTimestamp
2821            | AggregateFunc::MinFloat32
2822            | AggregateFunc::MinFloat64
2823            | AggregateFunc::MinBool
2824            | AggregateFunc::MinString
2825            | AggregateFunc::MinDate
2826            | AggregateFunc::MinTimestamp
2827            | AggregateFunc::MinTimestampTz
2828            | AggregateFunc::MinInterval
2829            | AggregateFunc::MinTime
2830            | AggregateFunc::MinArray
2831            | AggregateFunc::MinList
2832            | AggregateFunc::SumFloat32
2833            | AggregateFunc::SumFloat64
2834            | AggregateFunc::SumNumeric
2835            | AggregateFunc::SumInterval => input_type.scalar_type.clone(),
2836        };
2837        // Count never produces null, and other aggregations only produce
2838        // null in the presence of null inputs.
2839        let nullable = match self {
2840            AggregateFunc::Count => false,
2841            // Use the nullability of the underlying column being aggregated, not the Records wrapping it
2842            AggregateFunc::StringAgg { .. } => match input_type.scalar_type {
2843                // The outer Record wraps the input in the first position, and any ORDER BY expressions afterwards
2844                SqlScalarType::Record { fields, .. } => match &fields[0].1.scalar_type {
2845                    // The inner Record is a (value, separator) tuple
2846                    SqlScalarType::Record { fields, .. } => fields[0].1.nullable,
2847                    _ => unreachable!(),
2848                },
2849                _ => unreachable!(),
2850            },
2851            _ => input_type.nullable,
2852        };
2853        scalar_type.nullable(nullable)
2854    }
2855
2856    /// Computes the representation type of this aggregate function.
2857    ///
2858    /// This is a wrapper around [`Self::output_sql_type`] that converts the result to a representation type.
2859    pub fn output_type(&self, input_type: ReprColumnType) -> ReprColumnType {
2860        ReprColumnType::from(&self.output_sql_type(SqlColumnType::from_repr(&input_type)))
2861    }
2862
2863    /// Compute output type for ROW_NUMBER, RANK, DENSE_RANK
2864    fn output_type_ranking_window_funcs(
2865        input_type: &SqlColumnType,
2866        col_name: &str,
2867    ) -> SqlScalarType {
2868        match input_type.scalar_type {
2869            SqlScalarType::Record { ref fields, .. } => SqlScalarType::List {
2870                element_type: Box::new(SqlScalarType::Record {
2871                    fields: [
2872                        (
2873                            ColumnName::from(col_name),
2874                            SqlScalarType::Int64.nullable(false),
2875                        ),
2876                        (ColumnName::from("?orig_row?"), {
2877                            let inner = match &fields[0].1.scalar_type {
2878                                SqlScalarType::List { element_type, .. } => element_type.clone(),
2879                                _ => unreachable!(),
2880                            };
2881                            inner.nullable(false)
2882                        }),
2883                    ]
2884                    .into(),
2885                    custom_id: None,
2886                }),
2887                custom_id: None,
2888            },
2889            _ => unreachable!(),
2890        }
2891    }
2892
2893    /// Given the `EncodedArgs` part of `((OriginalRow, EncodedArgs), OrderByExprs...)`,
2894    /// this computes the type of the first field of the output type. (The first field is the
2895    /// real result, the rest is the original row.)
2896    fn lag_lead_output_type_inner_from_encoded_args(
2897        encoded_args_type: &SqlScalarType,
2898    ) -> SqlColumnType {
2899        // lag/lead have 3 arguments, and the output type is
2900        // the same as the first of these, but always nullable. (It's null when the
2901        // lag/lead computation reaches over the bounds of the window partition.)
2902        encoded_args_type.unwrap_record_element_type()[0]
2903            .clone()
2904            .nullable(true)
2905    }
2906
2907    fn lag_lead_result_column_name(lag_lead_type: &LagLeadType) -> ColumnName {
2908        ColumnName::from(match lag_lead_type {
2909            LagLeadType::Lag => "?lag?",
2910            LagLeadType::Lead => "?lead?",
2911        })
2912    }
2913
2914    /// Returns true if the non-null constraint on the aggregation can be
2915    /// converted into a non-null constraint on its parameter expression, ie.
2916    /// whether the result of the aggregation is null if all the input values
2917    /// are null.
2918    pub fn propagates_nonnull_constraint(&self) -> bool {
2919        match self {
2920            AggregateFunc::MaxNumeric
2921            | AggregateFunc::MaxInt16
2922            | AggregateFunc::MaxInt32
2923            | AggregateFunc::MaxInt64
2924            | AggregateFunc::MaxUInt16
2925            | AggregateFunc::MaxUInt32
2926            | AggregateFunc::MaxUInt64
2927            | AggregateFunc::MaxMzTimestamp
2928            | AggregateFunc::MaxFloat32
2929            | AggregateFunc::MaxFloat64
2930            | AggregateFunc::MaxBool
2931            | AggregateFunc::MaxString
2932            | AggregateFunc::MaxDate
2933            | AggregateFunc::MaxTimestamp
2934            | AggregateFunc::MaxTimestampTz
2935            | AggregateFunc::MaxInterval
2936            | AggregateFunc::MaxTime
2937            | AggregateFunc::MaxArray
2938            | AggregateFunc::MaxList
2939            | AggregateFunc::MinNumeric
2940            | AggregateFunc::MinInt16
2941            | AggregateFunc::MinInt32
2942            | AggregateFunc::MinInt64
2943            | AggregateFunc::MinUInt16
2944            | AggregateFunc::MinUInt32
2945            | AggregateFunc::MinUInt64
2946            | AggregateFunc::MinMzTimestamp
2947            | AggregateFunc::MinFloat32
2948            | AggregateFunc::MinFloat64
2949            | AggregateFunc::MinBool
2950            | AggregateFunc::MinString
2951            | AggregateFunc::MinDate
2952            | AggregateFunc::MinTimestamp
2953            | AggregateFunc::MinTimestampTz
2954            | AggregateFunc::MinInterval
2955            | AggregateFunc::MinTime
2956            | AggregateFunc::MinArray
2957            | AggregateFunc::MinList
2958            | AggregateFunc::SumInt16
2959            | AggregateFunc::SumInt32
2960            | AggregateFunc::SumInt64
2961            | AggregateFunc::SumUInt16
2962            | AggregateFunc::SumUInt32
2963            | AggregateFunc::SumUInt64
2964            | AggregateFunc::SumFloat32
2965            | AggregateFunc::SumFloat64
2966            | AggregateFunc::SumNumeric
2967            | AggregateFunc::SumInterval
2968            | AggregateFunc::StringAgg { .. } => true,
2969            // Count is never null
2970            AggregateFunc::Count
2971            | AggregateFunc::Any
2972            | AggregateFunc::All
2973            | AggregateFunc::JsonbAgg { .. }
2974            | AggregateFunc::JsonbObjectAgg { .. }
2975            | AggregateFunc::MapAgg { .. }
2976            | AggregateFunc::ArrayConcat { .. }
2977            | AggregateFunc::ListConcat { .. }
2978            | AggregateFunc::RowNumber { .. }
2979            | AggregateFunc::Rank { .. }
2980            | AggregateFunc::DenseRank { .. }
2981            | AggregateFunc::LagLead { .. }
2982            | AggregateFunc::FirstValue { .. }
2983            | AggregateFunc::LastValue { .. }
2984            | AggregateFunc::FusedValueWindowFunc { .. }
2985            | AggregateFunc::WindowAggregate { .. }
2986            | AggregateFunc::FusedWindowAggregate { .. }
2987            | AggregateFunc::Dummy => false,
2988        }
2989    }
2990}
2991
2992fn jsonb_each<'a>(a: Datum<'a>) -> impl Iterator<Item = (Row, Diff)> + 'a {
2993    // First produce a map, so that a common iterator can be returned.
2994    let map = match a {
2995        Datum::Map(dict) => dict,
2996        _ => mz_repr::DatumMap::empty(),
2997    };
2998
2999    map.iter()
3000        .map(move |(k, v)| (Row::pack_slice(&[Datum::String(k), v]), Diff::ONE))
3001}
3002
3003fn jsonb_each_stringify<'a>(
3004    a: Datum<'a>,
3005    temp_storage: &'a RowArena,
3006) -> impl Iterator<Item = (Row, Diff)> + 'a {
3007    // First produce a map, so that a common iterator can be returned.
3008    let map = match a {
3009        Datum::Map(dict) => dict,
3010        _ => mz_repr::DatumMap::empty(),
3011    };
3012
3013    map.iter().map(move |(k, mut v)| {
3014        v = jsonb_stringify(v, temp_storage)
3015            .map(Datum::String)
3016            .unwrap_or(Datum::Null);
3017        (Row::pack_slice(&[Datum::String(k), v]), Diff::ONE)
3018    })
3019}
3020
3021fn jsonb_object_keys<'a>(a: Datum<'a>) -> impl Iterator<Item = (Row, Diff)> + 'a {
3022    let map = match a {
3023        Datum::Map(dict) => dict,
3024        _ => mz_repr::DatumMap::empty(),
3025    };
3026
3027    map.iter()
3028        .map(move |(k, _)| (Row::pack_slice(&[Datum::String(k)]), Diff::ONE))
3029}
3030
3031fn jsonb_array_elements<'a>(a: Datum<'a>) -> impl Iterator<Item = (Row, Diff)> + 'a {
3032    let list = match a {
3033        Datum::List(list) => list,
3034        _ => mz_repr::DatumList::empty(),
3035    };
3036    list.iter().map(move |e| (Row::pack_slice(&[e]), Diff::ONE))
3037}
3038
3039fn jsonb_array_elements_stringify<'a>(
3040    a: Datum<'a>,
3041    temp_storage: &'a RowArena,
3042) -> impl Iterator<Item = (Row, Diff)> + 'a {
3043    let list = match a {
3044        Datum::List(list) => list,
3045        _ => mz_repr::DatumList::empty(),
3046    };
3047    list.iter().map(move |mut e| {
3048        e = jsonb_stringify(e, temp_storage)
3049            .map(Datum::String)
3050            .unwrap_or(Datum::Null);
3051        (Row::pack_slice(&[e]), Diff::ONE)
3052    })
3053}
3054
3055fn regexp_extract(a: Datum, r: &AnalyzedRegex) -> Option<(Row, Diff)> {
3056    let r = r.inner();
3057    let a = a.unwrap_str();
3058    let captures = r.captures(a)?;
3059    let datums = captures
3060        .iter()
3061        .skip(1)
3062        .map(|m| Datum::from(m.map(|m| m.as_str())));
3063    Some((Row::pack(datums), Diff::ONE))
3064}
3065
3066fn regexp_matches<'a>(
3067    exprs: &[Datum<'a>],
3068) -> Result<impl Iterator<Item = (Row, Diff)> + 'a, EvalError> {
3069    // There are only two acceptable ways to call this function:
3070    // 1. regexp_matches(string, regex)
3071    // 2. regexp_matches(string, regex, flag)
3072    assert!(exprs.len() == 2 || exprs.len() == 3);
3073    let a = exprs[0].unwrap_str();
3074    let r = exprs[1].unwrap_str();
3075
3076    let (regex, opts) = if exprs.len() == 3 {
3077        let flag = exprs[2].unwrap_str();
3078        let opts = AnalyzedRegexOpts::from_str(flag)?;
3079        (AnalyzedRegex::new(r, opts)?, opts)
3080    } else {
3081        let opts = AnalyzedRegexOpts::default();
3082        (AnalyzedRegex::new(r, opts)?, opts)
3083    };
3084
3085    let regex = regex.inner().clone();
3086
3087    let iter = regex.captures_iter(a).map(move |captures| {
3088        let matches = captures
3089            .iter()
3090            // The first match is the *entire* match, we want the capture groups by themselves.
3091            .skip(1)
3092            .map(|m| Datum::from(m.map(|m| m.as_str())))
3093            .collect::<Vec<_>>();
3094
3095        let mut binding = SharedRow::get();
3096        let mut packer = binding.packer();
3097
3098        let dimension = ArrayDimension {
3099            lower_bound: 1,
3100            length: matches.len(),
3101        };
3102        packer
3103            .try_push_array(&[dimension], matches)
3104            .expect("generated dimensions above");
3105
3106        (binding.clone(), Diff::ONE)
3107    });
3108
3109    // This is slightly unfortunate, but we need to collect the captures into a
3110    // Vec before we can yield them, because we can't return a iter with a
3111    // reference to the local `regex` variable.
3112    // We attempt to minimize the cost of this by using a SmallVec.
3113    let out = iter.collect::<SmallVec<[_; 3]>>();
3114
3115    if opts.global {
3116        Ok(Either::Left(out.into_iter()))
3117    } else {
3118        Ok(Either::Right(out.into_iter().take(1)))
3119    }
3120}
3121
3122fn generate_series<N>(
3123    start: N,
3124    stop: N,
3125    step: N,
3126) -> Result<impl Iterator<Item = (Row, Diff)>, EvalError>
3127where
3128    N: Integer + Signed + CheckedAdd + Clone,
3129    Datum<'static>: From<N>,
3130{
3131    if step == N::zero() {
3132        return Err(EvalError::InvalidParameterValue(
3133            "step size cannot equal zero".into(),
3134        ));
3135    }
3136    Ok(num::range_step_inclusive(start, stop, step)
3137        .map(move |i| (Row::pack_slice(&[Datum::from(i)]), Diff::ONE)))
3138}
3139
3140/// Like
3141/// [`num::range_step_inclusive`](https://github.com/rust-num/num-iter/blob/ddb14c1e796d401014c6c7a727de61d8109ad986/src/lib.rs#L279),
3142/// but for our timestamp types using [`Interval`] for `step`.xwxw
3143#[derive(Clone)]
3144pub struct TimestampRangeStepInclusive<T> {
3145    state: CheckedTimestamp<T>,
3146    stop: CheckedTimestamp<T>,
3147    step: Interval,
3148    rev: bool,
3149    done: bool,
3150}
3151
3152impl<T: TimestampLike> Iterator for TimestampRangeStepInclusive<T> {
3153    type Item = CheckedTimestamp<T>;
3154
3155    #[inline]
3156    fn next(&mut self) -> Option<CheckedTimestamp<T>> {
3157        if !self.done
3158            && ((self.rev && self.state >= self.stop) || (!self.rev && self.state <= self.stop))
3159        {
3160            let result = self.state.clone();
3161            match add_timestamp_months(self.state.deref(), self.step.months) {
3162                Ok(state) => match state.checked_add_signed(self.step.duration_as_chrono()) {
3163                    Some(v) => match CheckedTimestamp::from_timestamplike(v) {
3164                        Ok(v) => {
3165                            // Advance only if the step makes progress toward `stop`. A mixed
3166                            // month/day step can reach an in-bounds fixed point (month addition
3167                            // saturates a short month back onto the start day), which would
3168                            // otherwise loop forever.
3169                            let progressed = if self.rev {
3170                                v < self.state
3171                            } else {
3172                                v > self.state
3173                            };
3174                            if progressed {
3175                                self.state = v
3176                            } else {
3177                                self.done = true
3178                            }
3179                        }
3180                        Err(_) => self.done = true,
3181                    },
3182                    None => self.done = true,
3183                },
3184                Err(..) => {
3185                    self.done = true;
3186                }
3187            }
3188
3189            Some(result)
3190        } else {
3191            None
3192        }
3193    }
3194}
3195
3196fn generate_series_ts<T: TimestampLike>(
3197    start: CheckedTimestamp<T>,
3198    stop: CheckedTimestamp<T>,
3199    step: Interval,
3200    conv: fn(CheckedTimestamp<T>) -> Datum<'static>,
3201) -> Result<impl Iterator<Item = (Row, Diff)>, EvalError> {
3202    let normalized_step = step.as_microseconds();
3203    if normalized_step == 0 {
3204        return Err(EvalError::InvalidParameterValue(
3205            "step size cannot equal zero".into(),
3206        ));
3207    }
3208    let rev = normalized_step < 0;
3209
3210    let trsi = TimestampRangeStepInclusive {
3211        state: start,
3212        stop,
3213        step,
3214        rev,
3215        done: false,
3216    };
3217
3218    Ok(trsi.map(move |i| (Row::pack_slice(&[conv(i)]), Diff::ONE)))
3219}
3220
3221fn generate_subscripts_array(
3222    a: Datum,
3223    dim: i32,
3224) -> Result<Box<dyn Iterator<Item = (Row, Diff)>>, EvalError> {
3225    if dim <= 0 {
3226        return Ok(Box::new(iter::empty()));
3227    }
3228
3229    match a.unwrap_array().dims().into_iter().nth(
3230        (dim - 1)
3231            .try_into()
3232            .map_err(|_| EvalError::Int32OutOfRange((dim - 1).to_string().into()))?,
3233    ) {
3234        Some(requested_dim) => {
3235            let lower_bound: i32 = requested_dim.lower_bound.try_into().map_err(|_| {
3236                EvalError::Int32OutOfRange(requested_dim.lower_bound.to_string().into())
3237            })?;
3238            // The subscripts run from the lower bound to the upper bound,
3239            // inclusive. The upper bound is `lower_bound + length - 1`.
3240            let length: i32 = requested_dim
3241                .length
3242                .try_into()
3243                .map_err(|_| EvalError::Int32OutOfRange(requested_dim.length.to_string().into()))?;
3244            let upper_bound = lower_bound.checked_add(length - 1).ok_or_else(|| {
3245                EvalError::Int32OutOfRange(requested_dim.length.to_string().into())
3246            })?;
3247            Ok(Box::new(generate_series::<i32>(
3248                lower_bound,
3249                upper_bound,
3250                1,
3251            )?))
3252        }
3253        None => Ok(Box::new(iter::empty())),
3254    }
3255}
3256
3257fn unnest_array<'a>(a: Datum<'a>) -> impl Iterator<Item = (Row, Diff)> + 'a {
3258    a.unwrap_array()
3259        .elements()
3260        .iter()
3261        .map(move |e| (Row::pack_slice(&[e]), Diff::ONE))
3262}
3263
3264fn unnest_list<'a>(a: Datum<'a>) -> impl Iterator<Item = (Row, Diff)> + 'a {
3265    a.unwrap_list()
3266        .iter()
3267        .map(move |e| (Row::pack_slice(&[e]), Diff::ONE))
3268}
3269
3270fn unnest_map<'a>(a: Datum<'a>) -> impl Iterator<Item = (Row, Diff)> + 'a {
3271    a.unwrap_map()
3272        .iter()
3273        .map(move |(k, v)| (Row::pack_slice(&[Datum::from(k), v]), Diff::ONE))
3274}
3275
3276impl AggregateFunc {
3277    /// The base function name without the `~[...]` suffix used when rendering
3278    /// variants that represent a parameterized function family.
3279    pub fn name(&self) -> &'static str {
3280        match self {
3281            Self::MaxNumeric => "max",
3282            Self::MaxInt16 => "max",
3283            Self::MaxInt32 => "max",
3284            Self::MaxInt64 => "max",
3285            Self::MaxUInt16 => "max",
3286            Self::MaxUInt32 => "max",
3287            Self::MaxUInt64 => "max",
3288            Self::MaxMzTimestamp => "max",
3289            Self::MaxFloat32 => "max",
3290            Self::MaxFloat64 => "max",
3291            Self::MaxBool => "max",
3292            Self::MaxString => "max",
3293            Self::MaxDate => "max",
3294            Self::MaxTimestamp => "max",
3295            Self::MaxTimestampTz => "max",
3296            Self::MaxInterval => "max",
3297            Self::MaxTime => "max",
3298            Self::MaxArray => "max",
3299            Self::MaxList => "max",
3300            Self::MinNumeric => "min",
3301            Self::MinInt16 => "min",
3302            Self::MinInt32 => "min",
3303            Self::MinInt64 => "min",
3304            Self::MinUInt16 => "min",
3305            Self::MinUInt32 => "min",
3306            Self::MinUInt64 => "min",
3307            Self::MinMzTimestamp => "min",
3308            Self::MinFloat32 => "min",
3309            Self::MinFloat64 => "min",
3310            Self::MinBool => "min",
3311            Self::MinString => "min",
3312            Self::MinDate => "min",
3313            Self::MinTimestamp => "min",
3314            Self::MinTimestampTz => "min",
3315            Self::MinInterval => "min",
3316            Self::MinTime => "min",
3317            Self::MinArray => "min",
3318            Self::MinList => "min",
3319            Self::SumInt16 => "sum",
3320            Self::SumInt32 => "sum",
3321            Self::SumInt64 => "sum",
3322            Self::SumUInt16 => "sum",
3323            Self::SumUInt32 => "sum",
3324            Self::SumUInt64 => "sum",
3325            Self::SumFloat32 => "sum",
3326            Self::SumFloat64 => "sum",
3327            Self::SumNumeric => "sum",
3328            Self::SumInterval => "sum",
3329            Self::Count => "count",
3330            Self::Any => "any",
3331            Self::All => "all",
3332            Self::JsonbAgg { .. } => "jsonb_agg",
3333            Self::JsonbObjectAgg { .. } => "jsonb_object_agg",
3334            Self::MapAgg { .. } => "map_agg",
3335            Self::ArrayConcat { .. } => "array_agg",
3336            Self::ListConcat { .. } => "list_agg",
3337            Self::StringAgg { .. } => "string_agg",
3338            Self::RowNumber { .. } => "row_number",
3339            Self::Rank { .. } => "rank",
3340            Self::DenseRank { .. } => "dense_rank",
3341            Self::LagLead {
3342                lag_lead: LagLeadType::Lag,
3343                ..
3344            } => "lag",
3345            Self::LagLead {
3346                lag_lead: LagLeadType::Lead,
3347                ..
3348            } => "lead",
3349            Self::FirstValue { .. } => "first_value",
3350            Self::LastValue { .. } => "last_value",
3351            Self::WindowAggregate { .. } => "window_agg",
3352            Self::FusedValueWindowFunc { .. } => "fused_value_window_func",
3353            Self::FusedWindowAggregate { .. } => "fused_window_agg",
3354            Self::Dummy => "dummy",
3355        }
3356    }
3357}
3358
3359impl<'a, M> fmt::Display for HumanizedExpr<'a, AggregateFunc, M>
3360where
3361    M: HumanizerMode,
3362{
3363    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3364        use AggregateFunc::*;
3365        let name = self.expr.name();
3366        match self.expr {
3367            JsonbAgg { order_by }
3368            | JsonbObjectAgg { order_by }
3369            | MapAgg { order_by, .. }
3370            | ArrayConcat { order_by }
3371            | ListConcat { order_by }
3372            | StringAgg { order_by }
3373            | RowNumber { order_by }
3374            | Rank { order_by }
3375            | DenseRank { order_by } => {
3376                let order_by = order_by.iter().map(|col| self.child(col));
3377                write!(f, "{}[order_by=[{}]]", name, separated(", ", order_by))
3378            }
3379            LagLead {
3380                lag_lead: _,
3381                ignore_nulls,
3382                order_by,
3383            } => {
3384                let order_by = order_by.iter().map(|col| self.child(col));
3385                f.write_str(name)?;
3386                f.write_str("[")?;
3387                if *ignore_nulls {
3388                    f.write_str("ignore_nulls=true, ")?;
3389                }
3390                write!(f, "order_by=[{}]", separated(", ", order_by))?;
3391                f.write_str("]")
3392            }
3393            FirstValue {
3394                order_by,
3395                window_frame,
3396            } => {
3397                let order_by = order_by.iter().map(|col| self.child(col));
3398                f.write_str(name)?;
3399                f.write_str("[")?;
3400                write!(f, "order_by=[{}]", separated(", ", order_by))?;
3401                if *window_frame != WindowFrame::default() {
3402                    write!(f, " {}", window_frame)?;
3403                }
3404                f.write_str("]")
3405            }
3406            LastValue {
3407                order_by,
3408                window_frame,
3409            } => {
3410                let order_by = order_by.iter().map(|col| self.child(col));
3411                f.write_str(name)?;
3412                f.write_str("[")?;
3413                write!(f, "order_by=[{}]", separated(", ", order_by))?;
3414                if *window_frame != WindowFrame::default() {
3415                    write!(f, " {}", window_frame)?;
3416                }
3417                f.write_str("]")
3418            }
3419            WindowAggregate {
3420                wrapped_aggregate,
3421                order_by,
3422                window_frame,
3423            } => {
3424                let order_by = order_by.iter().map(|col| self.child(col));
3425                let wrapped_aggregate = self.child(wrapped_aggregate.deref());
3426                f.write_str(name)?;
3427                f.write_str("[")?;
3428                write!(f, "{} ", wrapped_aggregate)?;
3429                write!(f, "order_by=[{}]", separated(", ", order_by))?;
3430                if *window_frame != WindowFrame::default() {
3431                    write!(f, " {}", window_frame)?;
3432                }
3433                f.write_str("]")
3434            }
3435            FusedValueWindowFunc { funcs, order_by } => {
3436                let order_by = order_by.iter().map(|col| self.child(col));
3437                let funcs = separated(", ", funcs.iter().map(|func| self.child(func)));
3438                f.write_str(name)?;
3439                f.write_str("[")?;
3440                write!(f, "{} ", funcs)?;
3441                write!(f, "order_by=[{}]", separated(", ", order_by))?;
3442                f.write_str("]")
3443            }
3444            _ => f.write_str(name),
3445        }
3446    }
3447}
3448
3449#[derive(
3450    Clone,
3451    Debug,
3452    Eq,
3453    PartialEq,
3454    Ord,
3455    PartialOrd,
3456    Serialize,
3457    Deserialize,
3458    Hash
3459)]
3460pub struct CaptureGroupDesc {
3461    pub index: u32,
3462    pub name: Option<String>,
3463    pub nullable: bool,
3464}
3465
3466#[derive(
3467    Clone,
3468    Copy,
3469    Debug,
3470    Eq,
3471    PartialEq,
3472    Ord,
3473    PartialOrd,
3474    Serialize,
3475    Deserialize,
3476    Hash,
3477    Default
3478)]
3479pub struct AnalyzedRegexOpts {
3480    pub case_insensitive: bool,
3481    pub global: bool,
3482}
3483
3484impl FromStr for AnalyzedRegexOpts {
3485    type Err = EvalError;
3486
3487    fn from_str(s: &str) -> Result<Self, Self::Err> {
3488        let mut opts = AnalyzedRegexOpts::default();
3489        for c in s.chars() {
3490            match c {
3491                'i' => opts.case_insensitive = true,
3492                'g' => opts.global = true,
3493                _ => return Err(EvalError::InvalidRegexFlag(c)),
3494            }
3495        }
3496        Ok(opts)
3497    }
3498}
3499
3500#[derive(
3501    Clone,
3502    Debug,
3503    Eq,
3504    PartialEq,
3505    Ord,
3506    PartialOrd,
3507    Serialize,
3508    Deserialize,
3509    Hash
3510)]
3511pub struct AnalyzedRegex(ReprRegex, Vec<CaptureGroupDesc>, AnalyzedRegexOpts);
3512
3513impl AnalyzedRegex {
3514    pub fn new(s: &str, opts: AnalyzedRegexOpts) -> Result<Self, RegexCompilationError> {
3515        let r = ReprRegex::new(s, opts.case_insensitive)?;
3516        // TODO(benesch): remove potentially dangerous usage of `as`.
3517        #[allow(clippy::as_conversions)]
3518        let descs: Vec<_> = r
3519            .capture_names()
3520            .enumerate()
3521            // The first capture is the entire matched string.
3522            // This will often not be useful, so skip it.
3523            // If people want it they can just surround their
3524            // entire regex in an explicit capture group.
3525            .skip(1)
3526            .map(|(i, name)| CaptureGroupDesc {
3527                index: i as u32,
3528                name: name.map(String::from),
3529                // TODO -- we can do better.
3530                // https://github.com/MaterializeInc/database-issues/issues/612
3531                nullable: true,
3532            })
3533            .collect();
3534        Ok(Self(r, descs, opts))
3535    }
3536    pub fn capture_groups_len(&self) -> usize {
3537        self.1.len()
3538    }
3539    pub fn capture_groups_iter(&self) -> impl Iterator<Item = &CaptureGroupDesc> {
3540        self.1.iter()
3541    }
3542    pub fn inner(&self) -> &Regex {
3543        &(self.0).regex
3544    }
3545    pub fn opts(&self) -> &AnalyzedRegexOpts {
3546        &self.2
3547    }
3548}
3549
3550pub fn csv_extract(a: Datum<'_>, n_cols: usize) -> impl Iterator<Item = (Row, Diff)> + '_ {
3551    let bytes = a.unwrap_str().as_bytes();
3552    let mut row = Row::default();
3553    let csv_reader = csv::ReaderBuilder::new()
3554        .has_headers(false)
3555        .from_reader(bytes);
3556    csv_reader.into_records().filter_map(move |res| match res {
3557        Ok(sr) if sr.len() == n_cols => {
3558            row.packer().extend(sr.iter().map(Datum::String));
3559            Some((row.clone(), Diff::ONE))
3560        }
3561        _ => None,
3562    })
3563}
3564
3565pub fn repeat_row(a: Datum) -> Option<(Row, Diff)> {
3566    let n = a.unwrap_int64();
3567    if n != 0 {
3568        Some((Row::default(), n.into()))
3569    } else {
3570        None
3571    }
3572}
3573
3574pub fn repeat_row_non_negative<'a>(
3575    a: Datum,
3576) -> Result<Box<dyn Iterator<Item = (Row, Diff)> + 'a>, EvalError> {
3577    let n = a.unwrap_int64();
3578    if n < 0 {
3579        Err(EvalError::InvalidParameterValue(
3580            format!("repeat_row_non_negative got {}", n).into(),
3581        ))
3582    } else if n == 0 {
3583        Ok(Box::new(iter::empty()))
3584    } else {
3585        // iterator with 1 element; n goes into the diff
3586        Ok(Box::new(iter::once((Row::default(), n.into()))))
3587    }
3588}
3589
3590fn wrap<'a>(datums: &'a [Datum<'a>], width: usize) -> impl Iterator<Item = (Row, Diff)> + 'a {
3591    datums
3592        .chunks(width)
3593        .map(|chunk| (Row::pack(chunk), Diff::ONE))
3594}
3595
3596fn acl_explode<'a>(
3597    acl_items: Datum<'a>,
3598    temp_storage: &'a RowArena,
3599) -> Result<impl Iterator<Item = (Row, Diff)> + 'a, EvalError> {
3600    let acl_items = acl_items.unwrap_array();
3601    let mut res = Vec::new();
3602    for acl_item in acl_items.elements().iter() {
3603        if acl_item.is_null() {
3604            return Err(EvalError::AclArrayNullElement);
3605        }
3606        let acl_item = acl_item.unwrap_acl_item();
3607        for privilege in acl_item.acl_mode.explode() {
3608            let row = [
3609                Datum::UInt32(acl_item.grantor.0),
3610                Datum::UInt32(acl_item.grantee.0),
3611                Datum::String(temp_storage.push_string(privilege.to_string())),
3612                // GRANT OPTION is not implemented, so we hardcode false.
3613                Datum::False,
3614            ];
3615            res.push((Row::pack_slice(&row), Diff::ONE));
3616        }
3617    }
3618    Ok(res.into_iter())
3619}
3620
3621fn mz_acl_explode<'a>(
3622    mz_acl_items: Datum<'a>,
3623    temp_storage: &'a RowArena,
3624) -> Result<impl Iterator<Item = (Row, Diff)> + 'a, EvalError> {
3625    let mz_acl_items = mz_acl_items.unwrap_array();
3626    let mut res = Vec::new();
3627    for mz_acl_item in mz_acl_items.elements().iter() {
3628        if mz_acl_item.is_null() {
3629            return Err(EvalError::MzAclArrayNullElement);
3630        }
3631        let mz_acl_item = mz_acl_item.unwrap_mz_acl_item();
3632        for privilege in mz_acl_item.acl_mode.explode() {
3633            let row = [
3634                Datum::String(temp_storage.push_string(mz_acl_item.grantor.to_string())),
3635                Datum::String(temp_storage.push_string(mz_acl_item.grantee.to_string())),
3636                Datum::String(temp_storage.push_string(privilege.to_string())),
3637                // GRANT OPTION is not implemented, so we hardcode false.
3638                Datum::False,
3639            ];
3640            res.push((Row::pack_slice(&row), Diff::ONE));
3641        }
3642    }
3643    Ok(res.into_iter())
3644}
3645
3646/// When adding a new `TableFunc` variant, please consider adding it to
3647/// `TableFunc::with_ordinality`!
3648#[derive(
3649    Clone,
3650    Debug,
3651    Eq,
3652    PartialEq,
3653    Ord,
3654    PartialOrd,
3655    Serialize,
3656    Deserialize,
3657    Hash
3658)]
3659pub enum TableFunc {
3660    AclExplode,
3661    MzAclExplode,
3662    JsonbEach,
3663    JsonbEachStringify,
3664    JsonbObjectKeys,
3665    JsonbArrayElements,
3666    JsonbArrayElementsStringify,
3667    RegexpExtract(AnalyzedRegex),
3668    CsvExtract(usize),
3669    GenerateSeriesInt32,
3670    GenerateSeriesInt64,
3671    /// An int64 `generate_series` that the optimizer promises to leave as an
3672    /// enumeration: no transform may match on this variant to replace its
3673    /// evaluation with a cardinality shortcut (compare the collapse of an
3674    /// unused `GenerateSeriesInt64` into `RepeatRowNonNegative`). Its
3675    /// *argument* expressions are still simplified like any other scalar.
3676    ///
3677    /// Exposed as `mz_unsafe.generate_series_unoptimized` for tests that rely
3678    /// on the work of enumeration actually happening (e.g. stress tests whose
3679    /// load would otherwise be optimized away). As with everything in
3680    /// `mz_unsafe`, it is not a supported surface: bug reports must not
3681    /// depend on it.
3682    GenerateSeriesUnoptimized,
3683    GenerateSeriesTimestamp,
3684    GenerateSeriesTimestampTz,
3685    /// Supplied with an input count,
3686    ///   1. Adds a column as if a typed subquery result,
3687    ///   2. Filters the row away if the count is only one,
3688    ///   3. Errors if the count is not exactly one.
3689    /// The intent is that this presents as if a subquery result with too many
3690    /// records contributing. The error column has the same type as the result
3691    /// should have, but we only produce it if the count exceeds one.
3692    ///
3693    /// This logic could nearly be achieved with map, filter, project logic,
3694    /// but has been challenging to do in a way that respects the vagaries of
3695    /// SQL and our semantics. If we reveal a constant value in the column we
3696    /// risk the optimizer pruning the branch; if we reveal that this will not
3697    /// produce rows we risk the optimizer pruning the branch; if we reveal that
3698    /// the only possible value is an error we risk the optimizer propagating that
3699    /// error without guards.
3700    ///
3701    /// Before replacing this by an `MirScalarExpr`, quadruple check that it
3702    /// would not result in misoptimizations due to expression evaluation order
3703    /// being utterly undefined, and predicate pushdown trimming any fragments
3704    /// that might produce columns that will not be needed.
3705    GuardSubquerySize {
3706        column_type: SqlScalarType,
3707    },
3708    /// Repeats the input row the given number of times. Can even repeat a negative number of times,
3709    /// which has some important consequences:
3710    /// - can lead to negative accumulations downstream;
3711    /// - can't be used in `WITH ORDINALITY` and other constructs that are implemented by
3712    ///   `TableFunc::WithOrdinality`, e.g., `ROWS FROM`;
3713    /// - output is non-monotonic.
3714    RepeatRow,
3715    /// Same as `RepeatRow`, but errors on a negative count, and thereby avoids the above
3716    /// peculiarities.
3717    RepeatRowNonNegative,
3718    UnnestArray {
3719        el_typ: SqlScalarType,
3720    },
3721    UnnestList {
3722        el_typ: SqlScalarType,
3723    },
3724    UnnestMap {
3725        value_type: SqlScalarType,
3726    },
3727    /// Given `n` input expressions, wraps them into `n / width` rows, each of
3728    /// `width` columns.
3729    ///
3730    /// This function is not intended to be called directly by end users, but
3731    /// is useful in the planning of e.g. VALUES clauses.
3732    Wrap {
3733        types: Vec<SqlColumnType>,
3734        width: usize,
3735    },
3736    GenerateSubscriptsArray,
3737    /// Execute some arbitrary scalar function as a table function.
3738    TabletizedScalar {
3739        name: String,
3740        relation: SqlRelationType,
3741    },
3742    RegexpMatches,
3743    /// Implements the WITH ORDINALITY clause.
3744    ///
3745    /// Don't construct `TableFunc::WithOrdinality` manually! Use the `with_ordinality` constructor
3746    /// function instead, which checks whether the given table function supports `WithOrdinality`.
3747    #[allow(private_interfaces)]
3748    WithOrdinality(WithOrdinality),
3749}
3750
3751/// Evaluates the inner table function, expands its results into unary (repeating each row as
3752/// many times as the diff indicates), and appends an integer corresponding to the ordinal
3753/// position (starting from 1). For example, it numbers the elements of a list when calling
3754/// `unnest_list`.
3755///
3756/// Private enum variant of `TableFunc`. Don't construct this directly, but use
3757/// `TableFunc::with_ordinality` instead.
3758#[derive(
3759    Clone,
3760    Debug,
3761    Eq,
3762    PartialEq,
3763    Ord,
3764    PartialOrd,
3765    Serialize,
3766    Deserialize,
3767    Hash
3768)]
3769struct WithOrdinality {
3770    inner: Box<TableFunc>,
3771}
3772
3773impl TableFunc {
3774    /// Adds `WITH ORDINALITY` to a table function if it's allowed on the given table function.
3775    pub fn with_ordinality(inner: TableFunc) -> Option<TableFunc> {
3776        match inner {
3777            TableFunc::AclExplode
3778            | TableFunc::MzAclExplode
3779            | TableFunc::JsonbEach
3780            | TableFunc::JsonbEachStringify
3781            | TableFunc::JsonbObjectKeys
3782            | TableFunc::JsonbArrayElements
3783            | TableFunc::JsonbArrayElementsStringify
3784            | TableFunc::RegexpExtract(_)
3785            | TableFunc::CsvExtract(_)
3786            | TableFunc::GenerateSeriesInt32
3787            | TableFunc::GenerateSeriesInt64
3788            | TableFunc::GenerateSeriesUnoptimized
3789            | TableFunc::GenerateSeriesTimestamp
3790            | TableFunc::GenerateSeriesTimestampTz
3791            | TableFunc::GuardSubquerySize { .. }
3792            | TableFunc::RepeatRowNonNegative
3793            | TableFunc::UnnestArray { .. }
3794            | TableFunc::UnnestList { .. }
3795            | TableFunc::UnnestMap { .. }
3796            | TableFunc::Wrap { .. }
3797            | TableFunc::GenerateSubscriptsArray
3798            | TableFunc::TabletizedScalar { .. }
3799            | TableFunc::RegexpMatches => Some(TableFunc::WithOrdinality(WithOrdinality {
3800                inner: Box::new(inner),
3801            })),
3802            // IMPORTANT: Before adding a new table function above, consider negative diffs:
3803            // `WithOrdinality::eval` will panic if the inner table function emits a negative diff.
3804            // (Note that negative diffs in the table function's _input_ don't matter. The table
3805            // function implementation doesn't see the input diffs, so the thing that matters here
3806            // is whether the table function itself can emit a negative diff.)
3807            TableFunc::RepeatRow // can produce negative diffs
3808            | TableFunc::WithOrdinality(_) => None, // no nesting of `WITH ORDINALITY` allowed
3809        }
3810    }
3811}
3812
3813impl TableFunc {
3814    /// Executes `self` on the given input row (`datums`).
3815    pub fn eval<'a>(
3816        &'a self,
3817        datums: &'a [Datum<'a>],
3818        temp_storage: &'a RowArena,
3819    ) -> Result<Box<dyn Iterator<Item = (Row, Diff)> + 'a>, EvalError> {
3820        if self.empty_on_null_input() && datums.iter().any(|d| d.is_null()) {
3821            return Ok(Box::new(vec![].into_iter()));
3822        }
3823        match self {
3824            TableFunc::AclExplode => Ok(Box::new(acl_explode(datums[0], temp_storage)?)),
3825            TableFunc::MzAclExplode => Ok(Box::new(mz_acl_explode(datums[0], temp_storage)?)),
3826            TableFunc::JsonbEach => Ok(Box::new(jsonb_each(datums[0]))),
3827            TableFunc::JsonbEachStringify => {
3828                Ok(Box::new(jsonb_each_stringify(datums[0], temp_storage)))
3829            }
3830            TableFunc::JsonbObjectKeys => Ok(Box::new(jsonb_object_keys(datums[0]))),
3831            TableFunc::JsonbArrayElements => Ok(Box::new(jsonb_array_elements(datums[0]))),
3832            TableFunc::JsonbArrayElementsStringify => Ok(Box::new(jsonb_array_elements_stringify(
3833                datums[0],
3834                temp_storage,
3835            ))),
3836            TableFunc::RegexpExtract(a) => Ok(Box::new(regexp_extract(datums[0], a).into_iter())),
3837            TableFunc::CsvExtract(n_cols) => Ok(Box::new(csv_extract(datums[0], *n_cols))),
3838            TableFunc::GenerateSeriesInt32 => {
3839                let res = generate_series(
3840                    datums[0].unwrap_int32(),
3841                    datums[1].unwrap_int32(),
3842                    datums[2].unwrap_int32(),
3843                )?;
3844                Ok(Box::new(res))
3845            }
3846            TableFunc::GenerateSeriesInt64 | TableFunc::GenerateSeriesUnoptimized => {
3847                let res = generate_series(
3848                    datums[0].unwrap_int64(),
3849                    datums[1].unwrap_int64(),
3850                    datums[2].unwrap_int64(),
3851                )?;
3852                Ok(Box::new(res))
3853            }
3854            TableFunc::GenerateSeriesTimestamp => {
3855                fn pass_through<'a>(d: CheckedTimestamp<NaiveDateTime>) -> Datum<'a> {
3856                    Datum::from(d)
3857                }
3858                let res = generate_series_ts(
3859                    datums[0].unwrap_timestamp(),
3860                    datums[1].unwrap_timestamp(),
3861                    datums[2].unwrap_interval(),
3862                    pass_through,
3863                )?;
3864                Ok(Box::new(res))
3865            }
3866            TableFunc::GenerateSeriesTimestampTz => {
3867                fn gen_ts_tz<'a>(d: CheckedTimestamp<DateTime<Utc>>) -> Datum<'a> {
3868                    Datum::from(d)
3869                }
3870                let res = generate_series_ts(
3871                    datums[0].unwrap_timestamptz(),
3872                    datums[1].unwrap_timestamptz(),
3873                    datums[2].unwrap_interval(),
3874                    gen_ts_tz,
3875                )?;
3876                Ok(Box::new(res))
3877            }
3878            TableFunc::GenerateSubscriptsArray => {
3879                generate_subscripts_array(datums[0], datums[1].unwrap_int32())
3880            }
3881            TableFunc::GuardSubquerySize { column_type: _ } => {
3882                // A subquery used as an expression may return at most one row.
3883                // For 0 or 1 we emit no rows and let the subquery's own output
3884                // flow through. Zero can't come directly from the count that
3885                // lowering plants (an MIR `count(true)`, at least 1 per group),
3886                // but over a provably empty subquery body the optimizer may
3887                // vacuously rewrite the counted expression to `null`, and a
3888                // count of `null` over a group is 0. Later simplifications can
3889                // surface that 0 as a literal argument that is evaluated
3890                // during optimization. Emitting no rows is also the correct
3891                // semantics: the empty subquery decorrelates to NULL via the
3892                // outer lookup.
3893                let count = datums[0].unwrap_int64();
3894                if count > 1 {
3895                    Err(EvalError::MultipleRowsFromSubquery)
3896                } else if count < 0 {
3897                    // Would require negative multiplicities to reach the guard.
3898                    Err(EvalError::NegativeRowsFromSubquery)
3899                } else {
3900                    Ok(Box::new([].into_iter()))
3901                }
3902            }
3903            TableFunc::RepeatRow => Ok(Box::new(repeat_row(datums[0]).into_iter())),
3904            TableFunc::RepeatRowNonNegative => repeat_row_non_negative(datums[0]),
3905            TableFunc::UnnestArray { .. } => Ok(Box::new(unnest_array(datums[0]))),
3906            TableFunc::UnnestList { .. } => Ok(Box::new(unnest_list(datums[0]))),
3907            TableFunc::UnnestMap { .. } => Ok(Box::new(unnest_map(datums[0]))),
3908            TableFunc::Wrap { width, .. } => Ok(Box::new(wrap(datums, *width))),
3909            TableFunc::TabletizedScalar { .. } => {
3910                let r = Row::pack_slice(datums);
3911                Ok(Box::new(std::iter::once((r, Diff::ONE))))
3912            }
3913            TableFunc::RegexpMatches => Ok(Box::new(regexp_matches(datums)?)),
3914            TableFunc::WithOrdinality(func_with_ordinality) => {
3915                func_with_ordinality.eval(datums, temp_storage)
3916            }
3917        }
3918    }
3919
3920    pub fn output_sql_type(&self) -> SqlRelationType {
3921        let (column_types, keys) = match self {
3922            TableFunc::AclExplode => {
3923                let column_types = vec![
3924                    SqlScalarType::Oid.nullable(false),
3925                    SqlScalarType::Oid.nullable(false),
3926                    SqlScalarType::String.nullable(false),
3927                    SqlScalarType::Bool.nullable(false),
3928                ];
3929                let keys = vec![];
3930                (column_types, keys)
3931            }
3932            TableFunc::MzAclExplode => {
3933                let column_types = vec![
3934                    SqlScalarType::String.nullable(false),
3935                    SqlScalarType::String.nullable(false),
3936                    SqlScalarType::String.nullable(false),
3937                    SqlScalarType::Bool.nullable(false),
3938                ];
3939                let keys = vec![];
3940                (column_types, keys)
3941            }
3942            TableFunc::JsonbEach => {
3943                let column_types = vec![
3944                    SqlScalarType::String.nullable(false),
3945                    SqlScalarType::Jsonb.nullable(false),
3946                ];
3947                let keys = vec![];
3948                (column_types, keys)
3949            }
3950            TableFunc::JsonbEachStringify => {
3951                let column_types = vec![
3952                    SqlScalarType::String.nullable(false),
3953                    SqlScalarType::String.nullable(true),
3954                ];
3955                let keys = vec![];
3956                (column_types, keys)
3957            }
3958            TableFunc::JsonbObjectKeys => {
3959                let column_types = vec![SqlScalarType::String.nullable(false)];
3960                let keys = vec![];
3961                (column_types, keys)
3962            }
3963            TableFunc::JsonbArrayElements => {
3964                let column_types = vec![SqlScalarType::Jsonb.nullable(false)];
3965                let keys = vec![];
3966                (column_types, keys)
3967            }
3968            TableFunc::JsonbArrayElementsStringify => {
3969                let column_types = vec![SqlScalarType::String.nullable(true)];
3970                let keys = vec![];
3971                (column_types, keys)
3972            }
3973            TableFunc::RegexpExtract(a) => {
3974                let column_types = a
3975                    .capture_groups_iter()
3976                    .map(|cg| SqlScalarType::String.nullable(cg.nullable))
3977                    .collect();
3978                let keys = vec![];
3979                (column_types, keys)
3980            }
3981            TableFunc::CsvExtract(n_cols) => {
3982                let column_types = iter::repeat(SqlScalarType::String.nullable(false))
3983                    .take(*n_cols)
3984                    .collect();
3985                let keys = vec![];
3986                (column_types, keys)
3987            }
3988            TableFunc::GenerateSeriesInt32 => {
3989                let column_types = vec![SqlScalarType::Int32.nullable(false)];
3990                let keys = vec![vec![0]];
3991                (column_types, keys)
3992            }
3993            TableFunc::GenerateSeriesInt64 | TableFunc::GenerateSeriesUnoptimized => {
3994                let column_types = vec![SqlScalarType::Int64.nullable(false)];
3995                let keys = vec![vec![0]];
3996                (column_types, keys)
3997            }
3998            TableFunc::GenerateSeriesTimestamp => {
3999                let column_types =
4000                    vec![SqlScalarType::Timestamp { precision: None }.nullable(false)];
4001                let keys = vec![vec![0]];
4002                (column_types, keys)
4003            }
4004            TableFunc::GenerateSeriesTimestampTz => {
4005                let column_types =
4006                    vec![SqlScalarType::TimestampTz { precision: None }.nullable(false)];
4007                let keys = vec![vec![0]];
4008                (column_types, keys)
4009            }
4010            TableFunc::GenerateSubscriptsArray => {
4011                let column_types = vec![SqlScalarType::Int32.nullable(false)];
4012                let keys = vec![vec![0]];
4013                (column_types, keys)
4014            }
4015            TableFunc::GuardSubquerySize { column_type } => {
4016                let column_types = vec![column_type.clone().nullable(false)];
4017                let keys = vec![];
4018                (column_types, keys)
4019            }
4020            TableFunc::RepeatRow | TableFunc::RepeatRowNonNegative => {
4021                let column_types = vec![];
4022                let keys = vec![];
4023                (column_types, keys)
4024            }
4025            TableFunc::UnnestArray { el_typ } => {
4026                let column_types = vec![el_typ.clone().nullable(true)];
4027                let keys = vec![];
4028                (column_types, keys)
4029            }
4030            TableFunc::UnnestList { el_typ } => {
4031                let column_types = vec![el_typ.clone().nullable(true)];
4032                let keys = vec![];
4033                (column_types, keys)
4034            }
4035            TableFunc::UnnestMap { value_type } => {
4036                let column_types = vec![
4037                    SqlScalarType::String.nullable(false),
4038                    value_type.clone().nullable(true),
4039                ];
4040                let keys = vec![vec![0]];
4041                (column_types, keys)
4042            }
4043            TableFunc::Wrap { types, .. } => {
4044                let column_types = types.clone();
4045                let keys = vec![];
4046                (column_types, keys)
4047            }
4048            TableFunc::TabletizedScalar { relation, .. } => {
4049                return relation.clone();
4050            }
4051            TableFunc::RegexpMatches => {
4052                let column_types =
4053                    vec![SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false)];
4054                let keys = vec![];
4055
4056                (column_types, keys)
4057            }
4058            TableFunc::WithOrdinality(WithOrdinality { inner }) => {
4059                let mut typ = inner.output_sql_type();
4060                // Add the ordinality column.
4061                typ.column_types.push(SqlScalarType::Int64.nullable(false));
4062                // The ordinality column is always a key.
4063                typ.keys.push(vec![typ.column_types.len() - 1]);
4064                (typ.column_types, typ.keys)
4065            }
4066        };
4067
4068        soft_assert_eq_no_log!(column_types.len(), self.output_arity());
4069
4070        if !keys.is_empty() {
4071            SqlRelationType::new(column_types).with_keys(keys)
4072        } else {
4073            SqlRelationType::new(column_types)
4074        }
4075    }
4076
4077    /// Computes the representation type of this table function.
4078    ///
4079    /// This is a wrapper around [`Self::output_sql_type`] that converts the result to a representation type.
4080    pub fn output_type(&self) -> ReprRelationType {
4081        ReprRelationType::from(&self.output_sql_type())
4082    }
4083
4084    pub fn output_arity(&self) -> usize {
4085        match self {
4086            TableFunc::AclExplode => 4,
4087            TableFunc::MzAclExplode => 4,
4088            TableFunc::JsonbEach => 2,
4089            TableFunc::JsonbEachStringify => 2,
4090            TableFunc::JsonbObjectKeys => 1,
4091            TableFunc::JsonbArrayElements => 1,
4092            TableFunc::JsonbArrayElementsStringify => 1,
4093            TableFunc::RegexpExtract(a) => a.capture_groups_len(),
4094            TableFunc::CsvExtract(n_cols) => *n_cols,
4095            TableFunc::GenerateSeriesInt32 => 1,
4096            TableFunc::GenerateSeriesInt64 => 1,
4097            TableFunc::GenerateSeriesUnoptimized => 1,
4098            TableFunc::GenerateSeriesTimestamp => 1,
4099            TableFunc::GenerateSeriesTimestampTz => 1,
4100            TableFunc::GenerateSubscriptsArray => 1,
4101            TableFunc::GuardSubquerySize { .. } => 1,
4102            TableFunc::RepeatRow => 0,
4103            TableFunc::RepeatRowNonNegative => 0,
4104            TableFunc::UnnestArray { .. } => 1,
4105            TableFunc::UnnestList { .. } => 1,
4106            TableFunc::UnnestMap { .. } => 2,
4107            TableFunc::Wrap { width, .. } => *width,
4108            TableFunc::TabletizedScalar { relation, .. } => relation.column_types.len(),
4109            TableFunc::RegexpMatches => 1,
4110            TableFunc::WithOrdinality(WithOrdinality { inner }) => inner.output_arity() + 1,
4111        }
4112    }
4113
4114    pub fn empty_on_null_input(&self) -> bool {
4115        match self {
4116            TableFunc::AclExplode
4117            | TableFunc::MzAclExplode
4118            | TableFunc::JsonbEach
4119            | TableFunc::JsonbEachStringify
4120            | TableFunc::JsonbObjectKeys
4121            | TableFunc::JsonbArrayElements
4122            | TableFunc::JsonbArrayElementsStringify
4123            | TableFunc::GenerateSeriesInt32
4124            | TableFunc::GenerateSeriesInt64
4125            | TableFunc::GenerateSeriesUnoptimized
4126            | TableFunc::GenerateSeriesTimestamp
4127            | TableFunc::GenerateSeriesTimestampTz
4128            | TableFunc::GenerateSubscriptsArray
4129            | TableFunc::RegexpExtract(_)
4130            | TableFunc::CsvExtract(_)
4131            | TableFunc::RepeatRow
4132            | TableFunc::RepeatRowNonNegative
4133            | TableFunc::UnnestArray { .. }
4134            | TableFunc::UnnestList { .. }
4135            | TableFunc::UnnestMap { .. }
4136            | TableFunc::RegexpMatches => true,
4137            TableFunc::GuardSubquerySize { .. } => false,
4138            TableFunc::Wrap { .. } => false,
4139            TableFunc::TabletizedScalar { .. } => false,
4140            TableFunc::WithOrdinality(WithOrdinality { inner }) => inner.empty_on_null_input(),
4141        }
4142    }
4143
4144    /// True iff the table function preserves the append-only property of its input.
4145    pub fn preserves_monotonicity(&self) -> bool {
4146        // Most variants preserve monotonicity, but all variants are enumerated to
4147        // ensure that added variants at least check that this is the case.
4148        match self {
4149            TableFunc::AclExplode => false,
4150            TableFunc::MzAclExplode => false,
4151            TableFunc::JsonbEach => true,
4152            TableFunc::JsonbEachStringify => true,
4153            TableFunc::JsonbObjectKeys => true,
4154            TableFunc::JsonbArrayElements => true,
4155            TableFunc::JsonbArrayElementsStringify => true,
4156            TableFunc::RegexpExtract(_) => true,
4157            TableFunc::CsvExtract(_) => true,
4158            TableFunc::GenerateSeriesInt32 => true,
4159            TableFunc::GenerateSeriesInt64 => true,
4160            TableFunc::GenerateSeriesUnoptimized => true,
4161            TableFunc::GenerateSeriesTimestamp => true,
4162            TableFunc::GenerateSeriesTimestampTz => true,
4163            TableFunc::GenerateSubscriptsArray => true,
4164            TableFunc::RepeatRow => false,
4165            TableFunc::RepeatRowNonNegative => true,
4166            TableFunc::UnnestArray { .. } => true,
4167            TableFunc::UnnestList { .. } => true,
4168            TableFunc::UnnestMap { .. } => true,
4169            TableFunc::Wrap { .. } => true,
4170            TableFunc::TabletizedScalar { .. } => true,
4171            TableFunc::RegexpMatches => true,
4172            TableFunc::GuardSubquerySize { .. } => false,
4173            TableFunc::WithOrdinality(WithOrdinality { inner }) => inner.preserves_monotonicity(),
4174        }
4175    }
4176}
4177
4178impl fmt::Display for TableFunc {
4179    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4180        match self {
4181            TableFunc::AclExplode => f.write_str("aclexplode"),
4182            TableFunc::MzAclExplode => f.write_str("mz_aclexplode"),
4183            TableFunc::JsonbEach => f.write_str("jsonb_each"),
4184            TableFunc::JsonbEachStringify => f.write_str("jsonb_each_text"),
4185            TableFunc::JsonbObjectKeys => f.write_str("jsonb_object_keys"),
4186            TableFunc::JsonbArrayElements => f.write_str("jsonb_array_elements"),
4187            TableFunc::JsonbArrayElementsStringify => f.write_str("jsonb_array_elements_text"),
4188            TableFunc::RegexpExtract(a) => write!(f, "regexp_extract({:?}, _)", a.0),
4189            TableFunc::CsvExtract(n_cols) => write!(f, "csv_extract({}, _)", n_cols),
4190            TableFunc::GenerateSeriesInt32 => f.write_str("generate_series"),
4191            TableFunc::GenerateSeriesInt64 => f.write_str("generate_series"),
4192            TableFunc::GenerateSeriesUnoptimized => f.write_str("generate_series_unoptimized"),
4193            TableFunc::GenerateSeriesTimestamp => f.write_str("generate_series"),
4194            TableFunc::GenerateSeriesTimestampTz => f.write_str("generate_series"),
4195            TableFunc::GenerateSubscriptsArray => f.write_str("generate_subscripts"),
4196            TableFunc::GuardSubquerySize { .. } => f.write_str("guard_subquery_size"),
4197            TableFunc::RepeatRow => f.write_str(REPEAT_ROW_NAME),
4198            TableFunc::RepeatRowNonNegative => f.write_str("repeat_row_non_negative"),
4199            TableFunc::UnnestArray { .. } => f.write_str("unnest_array"),
4200            TableFunc::UnnestList { .. } => f.write_str("unnest_list"),
4201            TableFunc::UnnestMap { .. } => f.write_str("unnest_map"),
4202            TableFunc::Wrap { width, .. } => write!(f, "wrap{}", width),
4203            TableFunc::TabletizedScalar { name, .. } => f.write_str(name),
4204            TableFunc::RegexpMatches => write!(f, "regexp_matches(_, _, _)"),
4205            TableFunc::WithOrdinality(WithOrdinality { inner }) => {
4206                write!(f, "{}[with_ordinality]", inner)
4207            }
4208        }
4209    }
4210}
4211
4212impl WithOrdinality {
4213    /// Executes the `self.inner` table function on the given input row (`datums`), and zips
4214    /// 1, 2, 3, ... to the result as a new column. We need to expand rows with non-1 diffs into the
4215    /// corresponding number of rows with unit diffs, because the ordinality column will have
4216    /// different values for each copy.
4217    ///
4218    /// # Panics
4219    ///
4220    /// Panics if the `inner` table function emits a negative diff.
4221    fn eval<'a>(
4222        &'a self,
4223        datums: &'a [Datum<'a>],
4224        temp_storage: &'a RowArena,
4225    ) -> Result<Box<dyn Iterator<Item = (Row, Diff)> + 'a>, EvalError> {
4226        let mut next_ordinal: i64 = 1;
4227        let it = self
4228            .inner
4229            .eval(datums, temp_storage)?
4230            .flat_map(move |(mut row, diff)| {
4231                let diff = diff.into_inner();
4232                // WITH ORDINALITY is not well-defined for negative diffs. This is ok, and
4233                // `TableFunc::with_ordinality` refuses to wrap such table functions in
4234                // `WithOrdinality` that can emit negative diffs, e.g., `repeat_row`.
4235                //
4236                // (Note that we don't need to worry about negative diffs in FlatMap's input,
4237                // because the diff of the input of the FlatMap is factored in after we return from
4238                // here.)
4239                assert!(diff >= 0);
4240                // The ordinals that will be associated with this row.
4241                let mut ordinals = next_ordinal..(next_ordinal + diff);
4242                next_ordinal += diff;
4243                // The maximum byte capacity we need for the original row and its ordinal.
4244                let cap = row.data_len() + datum_size(&Datum::Int64(next_ordinal));
4245                iter::from_fn(move || {
4246                    let ordinal = ordinals.next()?;
4247                    let mut row = if ordinals.is_empty() {
4248                        // This is the last row, so no need to clone. (Most table functions emit
4249                        // only 1 diffs, so this completely avoids cloning in most cases.)
4250                        std::mem::take(&mut row)
4251                    } else {
4252                        let mut new_row = Row::with_capacity(cap);
4253                        new_row.clone_from(&row);
4254                        new_row
4255                    };
4256                    RowPacker::for_existing_row(&mut row).push(Datum::Int64(ordinal));
4257                    Some((row, Diff::ONE))
4258                })
4259            });
4260        Ok(Box::new(it))
4261    }
4262}
4263
4264pub const REPEAT_ROW_NAME: &str = "repeat_row";
4265
4266#[cfg(test)]
4267mod tests {
4268    use mz_repr::{Datum, RowArena, SqlScalarType};
4269
4270    use super::TableFunc;
4271    use crate::EvalError;
4272
4273    /// 0 and 1 are valid (no guard rows), >1 errors with
4274    /// `MultipleRowsFromSubquery`, <0 with `NegativeRowsFromSubquery`. Zero is
4275    /// legitimate, not "can't happen": the optimizer can turn an empty
4276    /// subquery's count into a literal `0` that is evaluated during
4277    /// optimization (see the comment in `eval`), so it must not panic (exposed
4278    /// by #37049).
4279    #[mz_ore::test]
4280    fn guard_subquery_size_accepts_zero_and_one() {
4281        let func = TableFunc::GuardSubquerySize {
4282            column_type: SqlScalarType::Int64,
4283        };
4284        let temp_storage = RowArena::new();
4285
4286        for count in [0_i64, 1] {
4287            let rows = func
4288                .eval(&[Datum::Int64(count)], &temp_storage)
4289                .unwrap_or_else(|e| panic!("count {count} should be accepted, got {e:?}"))
4290                .count();
4291            assert_eq!(rows, 0, "count {count} should emit no guard rows");
4292        }
4293
4294        assert_eq!(
4295            func.eval(&[Datum::Int64(2)], &temp_storage).err(),
4296            Some(EvalError::MultipleRowsFromSubquery),
4297        );
4298        assert_eq!(
4299            func.eval(&[Datum::Int64(-1)], &temp_storage).err(),
4300            Some(EvalError::NegativeRowsFromSubquery),
4301        );
4302    }
4303}