Skip to main content

mz_sql/plan/
query.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//! SQL `Query`s are the declarative, computational part of SQL.
11//! This module turns `Query`s into `HirRelationExpr`s - a more explicit, algebraic way of
12//! describing computation.
13
14//! Functions named plan_* are typically responsible for handling a single node of the SQL ast.
15//! E.g. `plan_query` is responsible for handling `sqlparser::ast::Query`.
16//! plan_* functions which correspond to operations on relations typically return a `HirRelationExpr`.
17//! plan_* functions which correspond to operations on scalars typically return a `HirScalarExpr`
18//! and a `SqlScalarType`. (The latter is because it's not always possible to infer from a
19//! `HirScalarExpr` what the intended type is - notably in the case of decimals where the
20//! scale/precision are encoded only in the type).
21
22//! Aggregates are particularly twisty.
23//!
24//! In SQL, a GROUP BY turns any columns not in the group key into vectors of
25//! values. Then anywhere later in the scope, an aggregate function can be
26//! applied to that group. Inside the arguments of an aggregate function, other
27//! normal functions are applied element-wise over the vectors. Thus, `SELECT
28//! sum(foo.x + foo.y) FROM foo GROUP BY x` means adding the scalar `x` to the
29//! vector `y` and summing the results.
30//!
31//! In `HirRelationExpr`, aggregates can only be applied immediately at the time
32//! of grouping.
33//!
34//! To deal with this, whenever we see a SQL GROUP BY we look ahead for
35//! aggregates and precompute them in the `HirRelationExpr::Reduce`. When we
36//! reach the same aggregates during normal planning later on, we look them up
37//! in an `ExprContext` to find the precomputed versions.
38
39use std::borrow::Cow;
40use std::cell::RefCell;
41use std::collections::{BTreeMap, BTreeSet};
42use std::convert::{TryFrom, TryInto};
43use std::num::NonZeroU64;
44use std::rc::Rc;
45use std::sync::{Arc, LazyLock};
46use std::{iter, mem};
47
48use itertools::Itertools;
49use mz_expr::func::variadic::{
50    ArrayCreate, ArrayIndex, Coalesce, Greatest, Least, ListCreate, ListIndex, ListSliceLinear,
51    MapBuild, RecordCreate,
52};
53use mz_expr::virtual_syntax::AlgExcept;
54use mz_expr::{
55    Id, LetRecLimit, LocalId, MapFilterProject, MirScalarExpr, REPEAT_ROW_NAME, RowSetFinishing,
56    TableFunc, func as expr_func,
57};
58use mz_ore::collections::CollectionExt;
59use mz_ore::error::ErrorExt;
60use mz_ore::id_gen::IdGen;
61use mz_ore::option::FallibleMapExt;
62use mz_ore::stack::{CheckedRecursion, RecursionGuard};
63use mz_ore::str::StrExt;
64use mz_repr::adt::char::CharLength;
65use mz_repr::adt::numeric::{NUMERIC_DATUM_MAX_PRECISION, NumericMaxScale};
66use mz_repr::adt::timestamp::TimestampPrecision;
67use mz_repr::adt::varchar::VarCharMaxLength;
68use mz_repr::namespaces::MZ_CATALOG_SCHEMA;
69use mz_repr::{
70    CatalogItemId, ColumnIndex, ColumnName, Datum, RelationDesc, RelationVersionSelector,
71    ReprColumnType, Row, RowArena, SqlColumnType, SqlRelationType, SqlScalarType,
72    UNKNOWN_COLUMN_NAME, strconv,
73};
74use mz_sql_parser::ast::display::AstDisplay;
75use mz_sql_parser::ast::visit::Visit;
76use mz_sql_parser::ast::visit_mut::{self, VisitMut};
77use mz_sql_parser::ast::{
78    AsOf, Assignment, AstInfo, CastFailureMode, CreateWebhookSourceBody, CreateWebhookSourceCheck,
79    CreateWebhookSourceHeader, CreateWebhookSourceSecret, CteBlock, DeleteStatement, Distinct,
80    Expr, Function, FunctionArgs, HomogenizingFunction, Ident, InsertSource, IsExprConstruct, Join,
81    JoinConstraint, JoinOperator, Limit, MapEntry, MutRecBlock, MutRecBlockOption,
82    MutRecBlockOptionName, OrderByExpr, Query, Select, SelectItem, SelectOption, SelectOptionName,
83    SetExpr, SetOperator, ShowStatement, SubscriptPosition, TableAlias, TableFactor,
84    TableWithJoins, UnresolvedItemName, UpdateStatement, Value, Values, WindowFrame,
85    WindowFrameBound, WindowFrameUnits, WindowSpec, visit,
86};
87use mz_sql_parser::ident;
88
89use crate::catalog::{CatalogItemType, CatalogType, SessionCatalog};
90use crate::func::{self, Func, FuncSpec, TableFuncImpl};
91use crate::names::{
92    Aug, FullItemName, PartialItemName, ResolvedDataType, ResolvedItemName, SchemaSpecifier,
93};
94use crate::plan::PlanError::InvalidWmrRecursionLimit;
95use crate::plan::error::PlanError;
96use crate::plan::hir::{
97    AbstractColumnType, AbstractExpr, AggregateExpr, AggregateFunc, AggregateWindowExpr,
98    BinaryFunc, CoercibleScalarExpr, CoercibleScalarType, ColumnOrder, ColumnRef, Hir,
99    HirRelationExpr, HirScalarExpr, JoinKind, ScalarWindowExpr, ScalarWindowFunc, UnaryFunc,
100    ValueWindowExpr, ValueWindowFunc, VariadicFunc, WindowExpr, WindowExprType,
101};
102use crate::plan::plan_utils::{self, GroupSizeHints, JoinSide};
103use crate::plan::scope::{Scope, ScopeItem, ScopeUngroupedColumn};
104use crate::plan::statement::{StatementContext, StatementDesc, show};
105use crate::plan::typeconv::{self, CastContext, plan_hypothetical_cast};
106use crate::plan::{
107    Params, PlanContext, QueryWhen, ShowCreatePlan, WebhookValidation, WebhookValidationSecret,
108    literal, transform_ast,
109};
110use crate::session::vars::ENABLE_WITH_ORDINALITY_LEGACY_FALLBACK;
111use crate::session::vars::{self, FeatureFlag};
112use crate::{ORDINALITY_COL_NAME, normalize};
113
114#[derive(Debug)]
115pub struct PlannedRootQuery<E> {
116    pub expr: E,
117    pub desc: RelationDesc,
118    pub finishing: RowSetFinishing<HirScalarExpr, HirScalarExpr>,
119    pub scope: Scope,
120}
121
122/// Plans a top-level query, returning the `HirRelationExpr` describing the query
123/// plan, the `RelationDesc` describing the shape of the result set, a
124/// `RowSetFinishing` describing post-processing that must occur before results
125/// are sent to the client, and the types of the parameters in the query, if any
126/// were present.
127///
128/// Note that the returned `RelationDesc` describes the expression after
129/// applying the returned `RowSetFinishing`.
130#[mz_ore::instrument(target = "compiler", level = "trace", name = "ast_to_hir")]
131pub fn plan_root_query(
132    scx: &StatementContext,
133    mut query: Query<Aug>,
134    lifetime: QueryLifetime,
135) -> Result<PlannedRootQuery<HirRelationExpr>, PlanError> {
136    transform_ast::transform(scx, &mut query)?;
137    let mut qcx = QueryContext::root(scx, lifetime);
138    let PlannedQuery {
139        mut expr,
140        scope,
141        order_by,
142        limit,
143        offset,
144        project,
145        group_size_hints,
146    } = plan_query(&mut qcx, &query)?;
147
148    let mut finishing = RowSetFinishing {
149        limit,
150        offset,
151        project,
152        order_by,
153    };
154
155    // Attempt to push the finishing's ordering past its projection. This allows
156    // data to be projected down on the workers rather than the coordinator. It
157    // also improves the optimizer's demand analysis, as the optimizer can only
158    // reason about demand information in `expr` (i.e., it can't see
159    // `finishing.project`).
160    try_push_projection_order_by(&mut expr, &mut finishing.project, &mut finishing.order_by);
161
162    if lifetime.is_maintained() {
163        expr.finish_maintained(&mut finishing, group_size_hints);
164    }
165
166    let typ = qcx.relation_type(&expr);
167    let typ = SqlRelationType::new(
168        finishing
169            .project
170            .iter()
171            .map(|i| typ.column_types[*i].clone())
172            .collect(),
173    );
174    let desc = RelationDesc::new(typ, scope.column_names());
175
176    Ok(PlannedRootQuery {
177        expr,
178        desc,
179        finishing,
180        scope,
181    })
182}
183
184/// Attempts to push a projection through an order by.
185///
186/// The returned bool indicates whether the pushdown was successful or not.
187/// Successful pushdown requires that all the columns referenced in `order_by`
188/// are included in `project`.
189///
190/// When successful, `expr` is wrapped in a projection node, `order_by` is
191/// rewritten to account for the pushed-down projection, and `project` is
192/// replaced with the trivial projection. When unsuccessful, no changes are made
193/// to any of the inputs.
194fn try_push_projection_order_by(
195    expr: &mut HirRelationExpr,
196    project: &mut Vec<usize>,
197    order_by: &mut Vec<ColumnOrder>,
198) -> bool {
199    let mut unproject = vec![None; expr.arity()];
200    for (out_i, in_i) in project.iter().copied().enumerate() {
201        unproject[in_i] = Some(out_i);
202    }
203    if order_by
204        .iter()
205        .all(|ob| ob.column < unproject.len() && unproject[ob.column].is_some())
206    {
207        let trivial_project = (0..project.len()).collect();
208        *expr = expr.take().project(mem::replace(project, trivial_project));
209        for ob in order_by {
210            ob.column = unproject[ob.column].unwrap();
211        }
212        true
213    } else {
214        false
215    }
216}
217
218pub fn plan_insert_query(
219    scx: &StatementContext,
220    table_name: ResolvedItemName,
221    columns: Vec<Ident>,
222    source: InsertSource<Aug>,
223    returning: Vec<SelectItem<Aug>>,
224) -> Result<
225    (
226        CatalogItemId,
227        HirRelationExpr,
228        PlannedRootQuery<Vec<HirScalarExpr>>,
229    ),
230    PlanError,
231> {
232    let mut qcx = QueryContext::root(scx, QueryLifetime::OneShot);
233    let table = scx.get_item_by_resolved_name(&table_name)?;
234
235    // Validate the target of the insert.
236    if table.item_type() != CatalogItemType::Table {
237        sql_bail!(
238            "cannot insert into {} '{}'",
239            table.item_type(),
240            table_name.full_name_str()
241        );
242    }
243    let desc = table
244        .relation_desc()
245        .ok_or_else(|| sql_err!("item does not have a relation description"))?;
246    let mut defaults = table
247        .writable_table_details()
248        .ok_or_else(|| {
249            sql_err!(
250                "cannot insert into non-writeable table '{}'",
251                table_name.full_name_str()
252            )
253        })?
254        .to_vec();
255
256    for default in &mut defaults {
257        transform_ast::transform(scx, default)?;
258    }
259
260    if table.id().is_system() {
261        sql_bail!(
262            "cannot insert into system table '{}'",
263            table_name.full_name_str()
264        );
265    }
266
267    let columns: Vec<_> = columns.into_iter().map(normalize::column_name).collect();
268
269    // Validate target column order.
270    let mut source_types = Vec::with_capacity(columns.len());
271    let mut ordering = Vec::with_capacity(columns.len());
272
273    if columns.is_empty() {
274        // Columns in source query must be in order. Let's guess the full shape and truncate to the
275        // right size later after planning the source query
276        source_types.extend(desc.iter_types().map(|x| &x.scalar_type));
277        ordering.extend(0..desc.arity());
278    } else {
279        let column_by_name: BTreeMap<&ColumnName, (usize, &SqlColumnType)> = desc
280            .iter()
281            .enumerate()
282            .map(|(idx, (name, typ))| (name, (idx, typ)))
283            .collect();
284
285        for c in &columns {
286            if let Some((idx, typ)) = column_by_name.get(c) {
287                ordering.push(*idx);
288                source_types.push(&typ.scalar_type);
289            } else {
290                sql_bail!(
291                    "column {} of relation {} does not exist",
292                    c.quoted(),
293                    table_name.full_name_str().quoted()
294                );
295            }
296        }
297        if let Some(dup) = columns.iter().duplicates().next() {
298            sql_bail!("column {} specified more than once", dup.quoted());
299        }
300    };
301
302    // Plan the source.
303    let expr = match source {
304        InsertSource::Query(mut query) => {
305            transform_ast::transform(scx, &mut query)?;
306
307            match query {
308                // Special-case simple VALUES clauses as PostgreSQL does.
309                Query {
310                    body: SetExpr::Values(Values(values)),
311                    ctes,
312                    order_by,
313                    limit: None,
314                    offset: None,
315                } if ctes.is_empty() && order_by.is_empty() => {
316                    let names: Vec<_> = ordering.iter().map(|i| desc.get_name(*i)).collect();
317                    plan_values_insert(&qcx, &names, &source_types, &values)?
318                }
319                _ => {
320                    let (expr, _scope) = plan_nested_query(&mut qcx, &query)?;
321                    expr
322                }
323            }
324        }
325        InsertSource::DefaultValues => {
326            HirRelationExpr::constant(vec![vec![]], SqlRelationType::empty())
327        }
328    };
329
330    let expr_arity = expr.arity();
331
332    // Validate that the arity of the source query is at most the size of declared columns or the
333    // size of the table if none are declared
334    let max_columns = if columns.is_empty() {
335        desc.arity()
336    } else {
337        columns.len()
338    };
339    if expr_arity > max_columns {
340        sql_bail!("INSERT has more expressions than target columns");
341    }
342    // But it should never have less than the declared columns (or zero)
343    if expr_arity < columns.len() {
344        sql_bail!("INSERT has more target columns than expressions");
345    }
346
347    // Trim now that we know for sure the correct arity of the source query
348    source_types.truncate(expr_arity);
349    ordering.truncate(expr_arity);
350
351    // Ensure the types of the source query match the types of the target table,
352    // installing assignment casts where necessary and possible.
353    let expr = cast_relation(&qcx, CastContext::Assignment, expr, source_types).map_err(|e| {
354        sql_err!(
355            "column {} is of type {} but expression is of type {}",
356            desc.get_name(ordering[e.column]).quoted(),
357            qcx.humanize_sql_scalar_type(&e.target_type, false),
358            qcx.humanize_sql_scalar_type(&e.source_type, false),
359        )
360    })?;
361
362    // Fill in any omitted columns and rearrange into correct order
363    let mut map_exprs = vec![];
364    let mut project_key = Vec::with_capacity(desc.arity());
365
366    // Maps from table column index to position in the source query
367    let col_to_source: BTreeMap<_, _> = ordering.iter().enumerate().map(|(a, b)| (b, a)).collect();
368
369    let column_details = desc.iter_types().zip_eq(defaults).enumerate();
370    for (col_idx, (col_typ, default)) in column_details {
371        if let Some(src_idx) = col_to_source.get(&col_idx) {
372            project_key.push(*src_idx);
373        } else {
374            let hir = plan_default_expr(scx, &default, &col_typ.scalar_type)?;
375            project_key.push(expr_arity + map_exprs.len());
376            map_exprs.push(hir);
377        }
378    }
379
380    let returning = {
381        let (scope, typ) = if let ResolvedItemName::Item {
382            full_name,
383            version: _,
384            ..
385        } = table_name
386        {
387            let scope = Scope::from_source(Some(full_name.clone().into()), desc.iter_names());
388            let typ = desc.typ().clone();
389            (scope, typ)
390        } else {
391            (Scope::empty(), SqlRelationType::empty())
392        };
393        let ecx = &ExprContext {
394            qcx: &qcx,
395            name: "RETURNING clause",
396            scope: &scope,
397            relation_type: &typ,
398            allow_aggregates: false,
399            allow_subqueries: false,
400            allow_parameters: true,
401            allow_windows: false,
402        };
403        let table_func_names = BTreeMap::new();
404        let mut output_columns = vec![];
405        let mut new_exprs = vec![];
406        let mut new_type = SqlRelationType::empty();
407        for mut si in returning {
408            transform_ast::transform(scx, &mut si)?;
409            for (select_item, column_name) in expand_select_item(ecx, &si, &table_func_names)? {
410                let expr = match &select_item {
411                    ExpandedSelectItem::InputOrdinal(i) => HirScalarExpr::column(*i),
412                    ExpandedSelectItem::Expr(expr) => plan_expr(ecx, expr)?.type_as_any(ecx)?,
413                };
414                output_columns.push(column_name);
415                let typ = ecx.column_type(&expr);
416                new_type.column_types.push(typ);
417                new_exprs.push(expr);
418            }
419        }
420        let desc = RelationDesc::new(new_type, output_columns);
421        let desc_arity = desc.arity();
422        PlannedRootQuery {
423            expr: new_exprs,
424            desc,
425            finishing: HirRelationExpr::trivial_row_set_finishing_hir(desc_arity),
426            scope,
427        }
428    };
429
430    Ok((
431        table.id(),
432        expr.map(map_exprs).project(project_key),
433        returning,
434    ))
435}
436
437/// Determines the mapping between some external data and a Materialize relation.
438///
439/// Returns the following:
440/// * [`CatalogItemId`] for the destination table.
441/// * [`RelationDesc`] representing the shape of the __input__ data we are copying from.
442/// * The [`ColumnIndex`]es that the source data maps to. TODO(cf2): We don't need this mapping
443///   since we now return a [`MapFilterProject`].
444/// * [`MapFilterProject`] which will map and project the input data to match the shape of the
445///   destination table.
446///
447pub fn plan_copy_item(
448    scx: &StatementContext,
449    item_name: ResolvedItemName,
450    columns: Vec<Ident>,
451) -> Result<
452    (
453        CatalogItemId,
454        RelationDesc,
455        Vec<ColumnIndex>,
456        Option<MapFilterProject>,
457    ),
458    PlanError,
459> {
460    let item = scx.get_item_by_resolved_name(&item_name)?;
461    let fullname = scx.catalog.resolve_full_name(item.name());
462    let table_desc = match item.relation_desc() {
463        Some(desc) => desc.into_owned(),
464        None => {
465            return Err(PlanError::InvalidDependency {
466                name: fullname.to_string(),
467                item_type: item.item_type().to_string(),
468            });
469        }
470    };
471    let mut ordering = Vec::with_capacity(columns.len());
472
473    // TODO(cf2): The logic here to create the `source_desc` and the MFP are a bit duplicated and
474    // should be simplified. The reason they are currently separate code paths is so we can roll
475    // out `COPY ... FROM <url>` without touching the current `COPY ... FROM ... STDIN` behavior.
476
477    // If we're copying data into a table that users can write into (e.g. not a `CREATE TABLE ...
478    // FROM SOURCE ...`), then we generate an MFP.
479    //
480    // Note: This method is called for both `COPY INTO <table> FROM` and `COPY <expr> TO <external>`
481    // so it's not always guaranteed that our `item` is a table.
482    let mfp = if let Some(table_defaults) = item.writable_table_details() {
483        let mut table_defaults = table_defaults.to_vec();
484
485        for default in &mut table_defaults {
486            transform_ast::transform(scx, default)?;
487        }
488
489        // Fill in any omitted columns and rearrange into correct order
490        let source_column_names: Vec<_> = columns
491            .iter()
492            .cloned()
493            .map(normalize::column_name)
494            .collect();
495
496        let mut default_exprs = Vec::new();
497        let mut project_keys = Vec::with_capacity(table_desc.arity());
498
499        // For each column in the destination table, either project it from the source data, or provide
500        // an expression to fill in a default value.
501        let column_details = table_desc.iter().zip_eq(table_defaults);
502        for ((col_name, col_type), col_default) in column_details {
503            let maybe_src_idx = source_column_names.iter().position(|name| name == col_name);
504            if let Some(src_idx) = maybe_src_idx {
505                project_keys.push(src_idx);
506            } else {
507                // If one a column from the table does not exist in the source data, then a default
508                // value will get appended to the end of the input Row from the source data.
509                let hir = plan_default_expr(scx, &col_default, &col_type.scalar_type)?;
510                let mir = hir.lower_uncorrelated(scx.catalog.system_vars())?;
511                project_keys.push(source_column_names.len() + default_exprs.len());
512                default_exprs.push(mir);
513            }
514        }
515
516        let mfp = MapFilterProject::new(source_column_names.len())
517            .map(default_exprs)
518            .project(project_keys);
519        Some(mfp)
520    } else {
521        None
522    };
523
524    // Create a mapping from input data to the table we're copying into.
525    let source_desc = if columns.is_empty() {
526        let indexes = (0..table_desc.arity()).map(ColumnIndex::from_raw);
527        ordering.extend(indexes);
528
529        // The source data should be in the same order as the table.
530        table_desc
531    } else {
532        let columns: Vec<_> = columns.into_iter().map(normalize::column_name).collect();
533        let column_by_name: BTreeMap<&ColumnName, (ColumnIndex, &SqlColumnType)> = table_desc
534            .iter_all()
535            .map(|(idx, name, typ)| (name, (*idx, typ)))
536            .collect();
537
538        let mut names = Vec::with_capacity(columns.len());
539        let mut source_types = Vec::with_capacity(columns.len());
540
541        for c in &columns {
542            if let Some((idx, typ)) = column_by_name.get(c) {
543                ordering.push(*idx);
544                source_types.push((*typ).clone());
545                names.push(c.clone());
546            } else {
547                sql_bail!(
548                    "column {} of relation {} does not exist",
549                    c.quoted(),
550                    item_name.full_name_str().quoted()
551                );
552            }
553        }
554        if let Some(dup) = columns.iter().duplicates().next() {
555            sql_bail!("column {} specified more than once", dup.quoted());
556        }
557
558        // The source data is a different shape than the destination table.
559        RelationDesc::new(SqlRelationType::new(source_types), names)
560    };
561
562    Ok((item.id(), source_desc, ordering, mfp))
563}
564
565/// See the doc comment on [`plan_copy_item`] for the details of what this function returns.
566///
567/// TODO(cf3): Merge this method with [`plan_copy_item`].
568pub fn plan_copy_from(
569    scx: &StatementContext,
570    table_name: ResolvedItemName,
571    columns: Vec<Ident>,
572) -> Result<
573    (
574        CatalogItemId,
575        RelationDesc,
576        Vec<ColumnIndex>,
577        Option<MapFilterProject>,
578    ),
579    PlanError,
580> {
581    let table = scx.get_item_by_resolved_name(&table_name)?;
582
583    // Validate the target of the insert.
584    if table.item_type() != CatalogItemType::Table {
585        sql_bail!(
586            "cannot insert into {} '{}'",
587            table.item_type(),
588            table_name.full_name_str()
589        );
590    }
591
592    let _ = table.writable_table_details().ok_or_else(|| {
593        sql_err!(
594            "cannot insert into non-writeable table '{}'",
595            table_name.full_name_str()
596        )
597    })?;
598
599    if table.id().is_system() {
600        sql_bail!(
601            "cannot insert into system table '{}'",
602            table_name.full_name_str()
603        );
604    }
605    let (id, desc, ordering, mfp) = plan_copy_item(scx, table_name, columns)?;
606
607    Ok((id, desc, ordering, mfp))
608}
609
610/// Builds a plan that adds the default values for the missing columns and re-orders
611/// the datums in the given rows to match the order in the target table.
612pub fn plan_copy_from_rows(
613    pcx: &PlanContext,
614    catalog: &dyn SessionCatalog,
615    target_id: CatalogItemId,
616    target_name: String,
617    columns: Vec<ColumnIndex>,
618    rows: Vec<mz_repr::Row>,
619) -> Result<HirRelationExpr, PlanError> {
620    let scx = StatementContext::new(Some(pcx), catalog);
621
622    // Always copy at the latest version of the table.
623    let table = catalog
624        .try_get_item(&target_id)
625        .ok_or_else(|| PlanError::CopyFromTargetTableDropped { target_name })?
626        .at_version(RelationVersionSelector::Latest);
627
628    let mut defaults = table
629        .writable_table_details()
630        .ok_or_else(|| sql_err!("cannot copy into non-writeable table"))?
631        .to_vec();
632
633    for default in &mut defaults {
634        transform_ast::transform(&scx, default)?;
635    }
636
637    let desc = table
638        .relation_desc()
639        .ok_or_else(|| sql_err!("item does not have a relation description"))?;
640    let column_types = columns
641        .iter()
642        .map(|x| desc.get_type(x).clone())
643        .map(|mut x| {
644            // Null constraint is enforced later, when inserting the row in the table.
645            // Without this, an assert is hit during lowering.
646            x.nullable = true;
647            x
648        })
649        .collect();
650    let typ = SqlRelationType::new(column_types);
651    let expr = HirRelationExpr::Constant {
652        rows,
653        typ: typ.clone(),
654    };
655
656    // Exit early with just the raw constant if we know that all columns are present
657    // and in the correct order. This lets us bypass expensive downstream optimizations
658    // more easily, as at every stage we know this expression is nothing more than
659    // a constant (as opposed to e.g. a constant with with an identity map and identity
660    // projection).
661    let default: Vec<_> = (0..desc.arity()).map(ColumnIndex::from_raw).collect();
662    if columns == default {
663        return Ok(expr);
664    }
665
666    // Fill in any omitted columns and rearrange into correct order
667    let mut map_exprs = vec![];
668    let mut project_key = Vec::with_capacity(desc.arity());
669
670    // Maps from table column index to position in the source query
671    let col_to_source: BTreeMap<_, _> = columns.iter().enumerate().map(|(a, b)| (b, a)).collect();
672
673    let column_details = desc.iter_all().zip_eq(defaults);
674    for ((col_idx, _col_name, col_typ), default) in column_details {
675        if let Some(src_idx) = col_to_source.get(&col_idx) {
676            project_key.push(*src_idx);
677        } else {
678            let hir = plan_default_expr(&scx, &default, &col_typ.scalar_type)?;
679            project_key.push(typ.arity() + map_exprs.len());
680            map_exprs.push(hir);
681        }
682    }
683
684    Ok(expr.map(map_exprs).project(project_key))
685}
686
687/// Common information used for DELETE, UPDATE, and INSERT INTO ... SELECT plans.
688pub struct ReadThenWritePlan {
689    pub id: CatalogItemId,
690    /// Read portion of query.
691    ///
692    /// NOTE: Even if the WHERE filter is left off, we still need to perform a read to generate
693    /// retractions.
694    pub selection: HirRelationExpr,
695    /// Map from column index to SET expression. Empty for DELETE statements.
696    pub assignments: BTreeMap<usize, HirScalarExpr>,
697    pub finishing: RowSetFinishing,
698}
699
700pub fn plan_delete_query(
701    scx: &StatementContext,
702    mut delete_stmt: DeleteStatement<Aug>,
703) -> Result<ReadThenWritePlan, PlanError> {
704    transform_ast::transform(scx, &mut delete_stmt)?;
705
706    let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
707    plan_mutation_query_inner(
708        qcx,
709        delete_stmt.table_name,
710        delete_stmt.alias,
711        delete_stmt.using,
712        vec![],
713        delete_stmt.selection,
714    )
715}
716
717pub fn plan_update_query(
718    scx: &StatementContext,
719    mut update_stmt: UpdateStatement<Aug>,
720) -> Result<ReadThenWritePlan, PlanError> {
721    transform_ast::transform(scx, &mut update_stmt)?;
722
723    let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
724
725    plan_mutation_query_inner(
726        qcx,
727        update_stmt.table_name,
728        update_stmt.alias,
729        vec![],
730        update_stmt.assignments,
731        update_stmt.selection,
732    )
733}
734
735pub fn plan_mutation_query_inner(
736    qcx: QueryContext,
737    table_name: ResolvedItemName,
738    alias: Option<TableAlias>,
739    using: Vec<TableWithJoins<Aug>>,
740    assignments: Vec<Assignment<Aug>>,
741    selection: Option<Expr<Aug>>,
742) -> Result<ReadThenWritePlan, PlanError> {
743    // Get ID and version of the relation desc.
744    let (id, version) = match table_name {
745        ResolvedItemName::Item { id, version, .. } => (id, version),
746        _ => sql_bail!("cannot mutate non-user table"),
747    };
748
749    // Perform checks on item with given ID.
750    let item = qcx.scx.get_item(&id).at_version(version);
751    if item.item_type() != CatalogItemType::Table {
752        sql_bail!(
753            "cannot mutate {} '{}'",
754            item.item_type(),
755            table_name.full_name_str()
756        );
757    }
758    let _ = item.writable_table_details().ok_or_else(|| {
759        sql_err!(
760            "cannot mutate non-writeable table '{}'",
761            table_name.full_name_str()
762        )
763    })?;
764    if id.is_system() {
765        sql_bail!(
766            "cannot mutate system table '{}'",
767            table_name.full_name_str()
768        );
769    }
770
771    // Derive structs for operation from validated table
772    let (mut get, scope) = qcx.resolve_table_name(table_name)?;
773    let scope = plan_table_alias(scope, alias.as_ref())?;
774    let desc = item.relation_desc().expect("table has desc");
775    let relation_type = qcx.relation_type(&get);
776
777    if using.is_empty() {
778        if let Some(expr) = selection {
779            let ecx = &ExprContext {
780                qcx: &qcx,
781                name: "WHERE clause",
782                scope: &scope,
783                relation_type: &relation_type,
784                allow_aggregates: false,
785                allow_subqueries: true,
786                allow_parameters: true,
787                allow_windows: false,
788            };
789            let expr = plan_expr(ecx, &expr)?.type_as(ecx, &SqlScalarType::Bool)?;
790            get = get.filter(vec![expr]);
791        }
792    } else {
793        get = handle_mutation_using_clause(&qcx, selection, using, get, scope.clone())?;
794    }
795
796    let mut sets = BTreeMap::new();
797    for Assignment { id, value } in assignments {
798        // Get the index and type of the column.
799        let name = normalize::column_name(id);
800        match desc.get_by_name(&name) {
801            Some((idx, typ)) => {
802                let ecx = &ExprContext {
803                    qcx: &qcx,
804                    name: "SET clause",
805                    scope: &scope,
806                    relation_type: &relation_type,
807                    allow_aggregates: false,
808                    allow_subqueries: false,
809                    allow_parameters: true,
810                    allow_windows: false,
811                };
812                let expr = plan_expr(ecx, &value)?.cast_to(
813                    ecx,
814                    CastContext::Assignment,
815                    &typ.scalar_type,
816                )?;
817
818                if sets.insert(idx, expr).is_some() {
819                    sql_bail!("column {} set twice", name)
820                }
821            }
822            None => sql_bail!("unknown column {}", name),
823        };
824    }
825
826    let finishing = RowSetFinishing {
827        order_by: vec![],
828        limit: None,
829        offset: 0,
830        project: (0..desc.arity()).collect(),
831    };
832
833    Ok(ReadThenWritePlan {
834        id,
835        selection: get,
836        finishing,
837        assignments: sets,
838    })
839}
840
841// Adjust `get` to perform an existential subquery on `using` accounting for
842// `selection`.
843//
844// If `USING`, we essentially want to rewrite the query as a correlated
845// existential subquery, i.e.
846// ```
847// ...WHERE EXISTS (SELECT 1 FROM <using> WHERE <selection>)
848// ```
849// However, we can't do that directly because of esoteric rules w/r/t `lateral`
850// subqueries.
851// https://github.com/postgres/postgres/commit/158b7fa6a34006bdc70b515e14e120d3e896589b
852fn handle_mutation_using_clause(
853    qcx: &QueryContext,
854    selection: Option<Expr<Aug>>,
855    using: Vec<TableWithJoins<Aug>>,
856    get: HirRelationExpr,
857    outer_scope: Scope,
858) -> Result<HirRelationExpr, PlanError> {
859    // Plan `USING` as a cross-joined `FROM` without knowledge of the
860    // statement's `FROM` target. This prevents `lateral` subqueries from
861    // "seeing" the `FROM` target.
862    let (mut using_rel_expr, using_scope) =
863        using.into_iter().try_fold(plan_join_identity(), |l, twj| {
864            let (left, left_scope) = l;
865            plan_join(
866                qcx,
867                left,
868                left_scope,
869                &Join {
870                    relation: TableFactor::NestedJoin {
871                        join: Box::new(twj),
872                        alias: None,
873                    },
874                    join_operator: JoinOperator::CrossJoin,
875                },
876            )
877        })?;
878
879    if let Some(expr) = selection {
880        // Join `FROM` with `USING` tables, like `USING..., FROM`. This gives us
881        // PG-like semantics e.g. expressing ambiguous column references. We put
882        // `USING...` first for no real reason, but making a different decision
883        // would require adjusting the column references on this relation
884        // differently.
885        let on = HirScalarExpr::literal_true();
886        let joined = using_rel_expr
887            .clone()
888            .join(get.clone(), on, JoinKind::Inner);
889        let joined_scope = using_scope.product(outer_scope)?;
890        let joined_relation_type = qcx.relation_type(&joined);
891
892        let ecx = &ExprContext {
893            qcx,
894            name: "WHERE clause",
895            scope: &joined_scope,
896            relation_type: &joined_relation_type,
897            allow_aggregates: false,
898            allow_subqueries: true,
899            allow_parameters: true,
900            allow_windows: false,
901        };
902
903        // Plan the filter expression on `FROM, USING...`.
904        let mut expr = plan_expr(ecx, &expr)?.type_as(ecx, &SqlScalarType::Bool)?;
905
906        // Rewrite all column referring to the `FROM` section of `joined` (i.e.
907        // those to the right of `using_rel_expr`), including those inside
908        // subqueries, to instead be correlated to the outer relation, i.e.
909        // `get`.
910        let using_rel_arity = qcx.relation_type(&using_rel_expr).arity();
911        #[allow(deprecated)]
912        expr.visit_columns_mut(0, &mut |depth, c| {
913            if c.level == depth && c.column >= using_rel_arity {
914                c.level += 1;
915                c.column -= using_rel_arity;
916            }
917        });
918
919        // Filter `USING` tables like `<using_rel_expr> WHERE <expr>`. Note that
920        // this filters the `USING` tables, _not_ the joined `USING..., FROM`
921        // relation.
922        using_rel_expr = using_rel_expr.filter(vec![expr]);
923    } else {
924        // Check that scopes are at compatible (i.e. do not double-reference
925        // same table), despite lack of selection
926        let _joined_scope = using_scope.product(outer_scope)?;
927    }
928    // From pg: Since the result [of EXISTS (<subquery>)] depends only on
929    // whether any rows are returned, and not on the contents of those rows,
930    // the output list of the subquery is normally unimportant.
931    //
932    // This means we don't need to worry about projecting/mapping any
933    // additional expressions here.
934    //
935    // https://www.postgresql.org/docs/14/functions-subquery.html
936
937    // Filter `get` like `...WHERE EXISTS (<using_rel_expr>)`.
938    Ok(get.filter(vec![using_rel_expr.exists()]))
939}
940
941#[derive(Debug)]
942pub(crate) struct CastRelationError {
943    pub(crate) column: usize,
944    pub(crate) source_type: SqlScalarType,
945    pub(crate) target_type: SqlScalarType,
946}
947
948/// Cast a relation from one type to another using the specified type of cast.
949///
950/// The length of `target_types` must match the arity of `expr`.
951pub(crate) fn cast_relation<'a, I>(
952    qcx: &QueryContext,
953    ccx: CastContext,
954    expr: HirRelationExpr,
955    target_types: I,
956) -> Result<HirRelationExpr, CastRelationError>
957where
958    I: IntoIterator<Item = &'a SqlScalarType>,
959{
960    let ecx = &ExprContext {
961        qcx,
962        name: "values",
963        scope: &Scope::empty(),
964        relation_type: &qcx.relation_type(&expr),
965        allow_aggregates: false,
966        allow_subqueries: true,
967        allow_parameters: true,
968        allow_windows: false,
969    };
970    let mut map_exprs = vec![];
971    let mut project_key = vec![];
972    for (i, target_typ) in target_types.into_iter().enumerate() {
973        let expr = HirScalarExpr::column(i);
974        // We plan every cast and check the evaluated expressions rather than
975        // checking the types directly because of some complex casting rules
976        // between types not expressed in `SqlScalarType` equality.
977        match typeconv::plan_cast(ecx, ccx, expr.clone(), target_typ) {
978            Ok(cast_expr) => {
979                if expr == cast_expr {
980                    // Cast between types was unnecessary
981                    project_key.push(i);
982                } else {
983                    // Cast between types required
984                    project_key.push(ecx.relation_type.arity() + map_exprs.len());
985                    map_exprs.push(cast_expr);
986                }
987            }
988            Err(_) => {
989                return Err(CastRelationError {
990                    column: i,
991                    source_type: ecx.scalar_type(&expr),
992                    target_type: target_typ.clone(),
993                });
994            }
995        }
996    }
997    Ok(expr.map(map_exprs).project(project_key))
998}
999
1000/// Plans an expression in the AS OF position of a `SELECT` or `SUBSCRIBE`, or `CREATE MATERIALIZED
1001/// VIEW` statement.
1002pub fn plan_as_of(
1003    scx: &StatementContext,
1004    as_of: Option<AsOf<Aug>>,
1005) -> Result<QueryWhen, PlanError> {
1006    match as_of {
1007        None => Ok(QueryWhen::Immediately),
1008        Some(as_of) => match as_of {
1009            AsOf::At(expr) => Ok(QueryWhen::AtTimestamp(plan_as_of_or_up_to(scx, expr)?)),
1010            AsOf::AtLeast(expr) => Ok(QueryWhen::AtLeastTimestamp(plan_as_of_or_up_to(scx, expr)?)),
1011        },
1012    }
1013}
1014
1015/// Plans and evaluates a scalar expression in a OneShot context to a non-null MzTimestamp.
1016///
1017/// Produces [`PlanError::InvalidAsOfUpTo`] if the expression is
1018/// - not a constant,
1019/// - not castable to MzTimestamp,
1020/// - is null,
1021/// - contains an unmaterializable function,
1022/// - some other evaluation error occurs, e.g., a division by 0,
1023/// - contains aggregates, subqueries, parameters, or window function calls.
1024pub fn plan_as_of_or_up_to(
1025    scx: &StatementContext,
1026    mut expr: Expr<Aug>,
1027) -> Result<mz_repr::Timestamp, PlanError> {
1028    let scope = Scope::empty();
1029    let desc = RelationDesc::empty();
1030    // (Even for a SUBSCRIBE, we need QueryLifetime::OneShot, because the AS OF or UP TO is
1031    // evaluated only once.)
1032    let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
1033    transform_ast::transform(scx, &mut expr)?;
1034    let ecx = &ExprContext {
1035        qcx: &qcx,
1036        name: "AS OF or UP TO",
1037        scope: &scope,
1038        relation_type: desc.typ(),
1039        allow_aggregates: false,
1040        allow_subqueries: false,
1041        allow_parameters: false,
1042        allow_windows: false,
1043    };
1044    let hir = plan_expr(ecx, &expr)?.cast_to(
1045        ecx,
1046        CastContext::Assignment,
1047        &SqlScalarType::MzTimestamp,
1048    )?;
1049    if hir.contains_unmaterializable() {
1050        bail_unsupported!("calling an unmaterializable function in AS OF or UP TO");
1051    }
1052    // At this point, we definitely have a constant expression:
1053    // - it can't contain any unmaterializable functions;
1054    // - it can't refer to any columns.
1055    // But the following can still fail due to a variety of reasons: most commonly, the cast can
1056    // fail, but also a null might appear, or some other evaluation error can happen, e.g., a
1057    // division by 0.
1058    let timestamp = hir
1059        .into_literal_mz_timestamp()
1060        .ok_or_else(|| PlanError::InvalidAsOfUpTo)?;
1061    Ok(timestamp)
1062}
1063
1064/// Plans an expression in the AS position of a `CREATE SECRET`.
1065pub fn plan_secret_as(
1066    scx: &StatementContext,
1067    mut expr: Expr<Aug>,
1068) -> Result<MirScalarExpr, PlanError> {
1069    let scope = Scope::empty();
1070    let desc = RelationDesc::empty();
1071    let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
1072
1073    transform_ast::transform(scx, &mut expr)?;
1074
1075    let ecx = &ExprContext {
1076        qcx: &qcx,
1077        name: "AS",
1078        scope: &scope,
1079        relation_type: desc.typ(),
1080        allow_aggregates: false,
1081        allow_subqueries: false,
1082        allow_parameters: false,
1083        allow_windows: false,
1084    };
1085    let expr = plan_expr(ecx, &expr)?
1086        .type_as(ecx, &SqlScalarType::Bytes)?
1087        .lower_uncorrelated(scx.catalog.system_vars())?;
1088    Ok(expr)
1089}
1090
1091/// Plans an expression in the CHECK position of a `CREATE SOURCE ... FROM WEBHOOK`.
1092pub fn plan_webhook_validate_using(
1093    scx: &StatementContext,
1094    validate_using: CreateWebhookSourceCheck<Aug>,
1095) -> Result<WebhookValidation, PlanError> {
1096    let qcx = QueryContext::root(scx, QueryLifetime::Source);
1097
1098    let CreateWebhookSourceCheck {
1099        options,
1100        using: mut expr,
1101    } = validate_using;
1102
1103    let mut column_typs = vec![];
1104    let mut column_names = vec![];
1105
1106    let (bodies, headers, secrets) = options
1107        .map(|o| (o.bodies, o.headers, o.secrets))
1108        .unwrap_or_default();
1109
1110    // Append all of the bodies so they can be used in the expression.
1111    let mut body_tuples = vec![];
1112    for CreateWebhookSourceBody { alias, use_bytes } in bodies {
1113        let scalar_type = use_bytes
1114            .then_some(SqlScalarType::Bytes)
1115            .unwrap_or(SqlScalarType::String);
1116        let name = alias
1117            .map(|a| a.into_string())
1118            .unwrap_or_else(|| "body".to_string());
1119
1120        column_typs.push(SqlColumnType {
1121            scalar_type,
1122            nullable: false,
1123        });
1124        column_names.push(name);
1125
1126        // Store the column index so we can be sure to provide this body correctly.
1127        let column_idx = column_typs.len() - 1;
1128        // Double check we're consistent with column names.
1129        assert_eq!(
1130            column_idx,
1131            column_names.len() - 1,
1132            "body column names and types don't match"
1133        );
1134        body_tuples.push((column_idx, use_bytes));
1135    }
1136
1137    // Append all of the headers so they can be used in the expression.
1138    let mut header_tuples = vec![];
1139
1140    for CreateWebhookSourceHeader { alias, use_bytes } in headers {
1141        let value_type = use_bytes
1142            .then_some(SqlScalarType::Bytes)
1143            .unwrap_or(SqlScalarType::String);
1144        let name = alias
1145            .map(|a| a.into_string())
1146            .unwrap_or_else(|| "headers".to_string());
1147
1148        column_typs.push(SqlColumnType {
1149            scalar_type: SqlScalarType::Map {
1150                value_type: Box::new(value_type),
1151                custom_id: None,
1152            },
1153            nullable: false,
1154        });
1155        column_names.push(name);
1156
1157        // Store the column index so we can be sure to provide this body correctly.
1158        let column_idx = column_typs.len() - 1;
1159        // Double check we're consistent with column names.
1160        assert_eq!(
1161            column_idx,
1162            column_names.len() - 1,
1163            "header column names and types don't match"
1164        );
1165        header_tuples.push((column_idx, use_bytes));
1166    }
1167
1168    // Append all secrets so they can be used in the expression.
1169    let mut validation_secrets = vec![];
1170
1171    for CreateWebhookSourceSecret {
1172        secret,
1173        alias,
1174        use_bytes,
1175    } in secrets
1176    {
1177        // Either provide the secret to the validation expression as Bytes or a String.
1178        let scalar_type = use_bytes
1179            .then_some(SqlScalarType::Bytes)
1180            .unwrap_or(SqlScalarType::String);
1181
1182        column_typs.push(SqlColumnType {
1183            scalar_type,
1184            nullable: false,
1185        });
1186        // A stored source naming one of these panics at boot, which re-plans
1187        // user sources before them (`sort_item_updates`). Other non-secrets
1188        // stay accepted, since stored sources using them boot today and
1189        // rejecting them would make those panic instead.
1190        if let ResolvedItemName::Item { id, .. } = &secret
1191            && id.is_user()
1192            && matches!(
1193                scx.catalog.get_item(id).item_type(),
1194                CatalogItemType::Table
1195                    | CatalogItemType::View
1196                    | CatalogItemType::MaterializedView
1197                    | CatalogItemType::Index
1198                    | CatalogItemType::Sink
1199                    | CatalogItemType::MetricSink
1200            )
1201        {
1202            return Err(PlanError::InvalidSecret(Box::new(secret)));
1203        }
1204        let ResolvedItemName::Item {
1205            id,
1206            full_name: FullItemName { item, .. },
1207            ..
1208        } = secret
1209        else {
1210            return Err(PlanError::InvalidSecret(Box::new(secret)));
1211        };
1212
1213        // Plan the expression using the secret's alias, if one is provided.
1214        let name = if let Some(alias) = alias {
1215            alias.into_string()
1216        } else {
1217            item
1218        };
1219        column_names.push(name);
1220
1221        // Get the column index that corresponds for this secret, so we can make sure to provide the
1222        // secrets in the correct order during evaluation.
1223        let column_idx = column_typs.len() - 1;
1224        // Double check that our column names and types match.
1225        assert_eq!(
1226            column_idx,
1227            column_names.len() - 1,
1228            "column names and types don't match"
1229        );
1230
1231        validation_secrets.push(WebhookValidationSecret {
1232            id,
1233            column_idx,
1234            use_bytes,
1235        });
1236    }
1237
1238    let relation_typ = SqlRelationType::new(column_typs);
1239    let desc = RelationDesc::new(relation_typ, column_names.clone());
1240    let scope = Scope::from_source(None, column_names);
1241
1242    transform_ast::transform(scx, &mut expr)?;
1243
1244    let ecx = &ExprContext {
1245        qcx: &qcx,
1246        name: "CHECK",
1247        scope: &scope,
1248        relation_type: desc.typ(),
1249        allow_aggregates: false,
1250        allow_subqueries: false,
1251        allow_parameters: false,
1252        allow_windows: false,
1253    };
1254    let expr = plan_expr(ecx, &expr)?
1255        .type_as(ecx, &SqlScalarType::Bool)?
1256        .lower_uncorrelated(scx.catalog.system_vars())?;
1257    let validation = WebhookValidation {
1258        expression: expr,
1259        relation_desc: desc,
1260        bodies: body_tuples,
1261        headers: header_tuples,
1262        secrets: validation_secrets,
1263    };
1264    Ok(validation)
1265}
1266
1267pub fn plan_default_expr(
1268    scx: &StatementContext,
1269    expr: &Expr<Aug>,
1270    target_ty: &SqlScalarType,
1271) -> Result<HirScalarExpr, PlanError> {
1272    let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
1273    let ecx = &ExprContext {
1274        qcx: &qcx,
1275        name: "DEFAULT expression",
1276        scope: &Scope::empty(),
1277        relation_type: &SqlRelationType::empty(),
1278        allow_aggregates: false,
1279        allow_subqueries: false,
1280        allow_parameters: false,
1281        allow_windows: false,
1282    };
1283    let hir = plan_expr(ecx, expr)?.cast_to(ecx, CastContext::Assignment, target_ty)?;
1284    Ok(hir)
1285}
1286
1287pub fn plan_params<'a>(
1288    scx: &'a StatementContext,
1289    params: Vec<Expr<Aug>>,
1290    desc: &StatementDesc,
1291) -> Result<Params, PlanError> {
1292    if params.len() != desc.param_types.len() {
1293        sql_bail!(
1294            "expected {} params, got {}",
1295            desc.param_types.len(),
1296            params.len()
1297        );
1298    }
1299
1300    let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
1301
1302    let mut datums = Row::default();
1303    let mut packer = datums.packer();
1304    let mut actual_types = Vec::new();
1305    let temp_storage = &RowArena::new();
1306    for (i, (mut expr, expected_ty)) in params.into_iter().zip_eq(&desc.param_types).enumerate() {
1307        transform_ast::transform(scx, &mut expr)?;
1308
1309        let ecx = execute_expr_context(&qcx);
1310        let ex = plan_expr(&ecx, &expr)?.type_as_any(&ecx)?;
1311        let actual_ty = ecx.scalar_type(&ex);
1312        if plan_hypothetical_cast(&ecx, *EXECUTE_CAST_CONTEXT, &actual_ty, expected_ty).is_none() {
1313            return Err(PlanError::WrongParameterType(
1314                i + 1,
1315                ecx.humanize_sql_scalar_type(expected_ty, false),
1316                ecx.humanize_sql_scalar_type(&actual_ty, false),
1317            ));
1318        }
1319        let ex = ex.lower_uncorrelated(scx.catalog.system_vars())?;
1320        let evaled = ex.eval_constant_foldable(temp_storage)?;
1321        packer.push(evaled);
1322        actual_types.push(actual_ty);
1323    }
1324    Ok(Params {
1325        datums,
1326        execute_types: actual_types,
1327        expected_types: desc.param_types.clone(),
1328    })
1329}
1330
1331static EXECUTE_CONTEXT_SCOPE: LazyLock<Scope> = LazyLock::new(Scope::empty);
1332static EXECUTE_CONTEXT_REL_TYPE: LazyLock<SqlRelationType> = LazyLock::new(SqlRelationType::empty);
1333
1334/// Returns an `ExprContext` for the expressions in the parameters of an EXECUTE statement.
1335pub(crate) fn execute_expr_context<'a>(qcx: &'a QueryContext<'a>) -> ExprContext<'a> {
1336    ExprContext {
1337        qcx,
1338        name: "EXECUTE",
1339        scope: &EXECUTE_CONTEXT_SCOPE,
1340        relation_type: &EXECUTE_CONTEXT_REL_TYPE,
1341        allow_aggregates: false,
1342        allow_subqueries: false,
1343        allow_parameters: false,
1344        allow_windows: false,
1345    }
1346}
1347
1348/// The CastContext used when matching up the types of parameters passed to EXECUTE.
1349///
1350/// This is an assignment cast also in Postgres, see
1351/// <https://github.com/MaterializeInc/database-issues/issues/9266>
1352pub(crate) static EXECUTE_CAST_CONTEXT: LazyLock<CastContext> =
1353    LazyLock::new(|| CastContext::Assignment);
1354
1355pub fn plan_index_exprs<'a>(
1356    scx: &'a StatementContext,
1357    on_desc: &RelationDesc,
1358    exprs: Vec<Expr<Aug>>,
1359) -> Result<Vec<mz_expr::MirScalarExpr>, PlanError> {
1360    let scope = Scope::from_source(None, on_desc.iter_names());
1361    let qcx = QueryContext::root(scx, QueryLifetime::Index);
1362
1363    let ecx = &ExprContext {
1364        qcx: &qcx,
1365        name: "CREATE INDEX",
1366        scope: &scope,
1367        relation_type: on_desc.typ(),
1368        allow_aggregates: false,
1369        allow_subqueries: false,
1370        allow_parameters: false,
1371        allow_windows: false,
1372    };
1373    let repr_col_types: Vec<ReprColumnType> = on_desc
1374        .typ()
1375        .column_types
1376        .iter()
1377        .map(ReprColumnType::from)
1378        .collect();
1379    let mut out = vec![];
1380    for mut expr in exprs {
1381        transform_ast::transform(scx, &mut expr)?;
1382        let expr = plan_expr_or_col_index(ecx, &expr)?;
1383        let mut expr = expr.lower_uncorrelated(scx.catalog.system_vars())?;
1384        expr.reduce(&repr_col_types);
1385        out.push(expr);
1386    }
1387    Ok(out)
1388}
1389
1390fn plan_expr_or_col_index(ecx: &ExprContext, e: &Expr<Aug>) -> Result<HirScalarExpr, PlanError> {
1391    match check_col_index(ecx.name, e, ecx.relation_type.column_types.len())? {
1392        Some(column) => Ok(HirScalarExpr::column(column)),
1393        _ => plan_expr(ecx, e)?.type_as_any(ecx),
1394    }
1395}
1396
1397fn check_col_index(name: &str, e: &Expr<Aug>, max: usize) -> Result<Option<usize>, PlanError> {
1398    match e {
1399        Expr::Value(Value::Number(n)) => {
1400            let n = n.parse::<usize>().map_err(|e| {
1401                sql_err!("unable to parse column reference in {}: {}: {}", name, n, e)
1402            })?;
1403            if n < 1 || n > max {
1404                sql_bail!(
1405                    "column reference {} in {} is out of range (1 - {})",
1406                    n,
1407                    name,
1408                    max
1409                );
1410            }
1411            Ok(Some(n - 1))
1412        }
1413        _ => Ok(None),
1414    }
1415}
1416
1417struct PlannedQuery {
1418    expr: HirRelationExpr,
1419    scope: Scope,
1420    order_by: Vec<ColumnOrder>,
1421    limit: Option<HirScalarExpr>,
1422    /// `offset` is either
1423    /// - an Int64 literal
1424    /// - or contains parameters. (If it contains parameters, then after parameter substitution it
1425    ///   should also be `is_constant` and reduce to an Int64 literal, but we check this only
1426    ///   later.)
1427    offset: HirScalarExpr,
1428    project: Vec<usize>,
1429    group_size_hints: GroupSizeHints,
1430}
1431
1432fn plan_query(qcx: &mut QueryContext, q: &Query<Aug>) -> Result<PlannedQuery, PlanError> {
1433    qcx.checked_recur_mut(|qcx| plan_query_inner(qcx, q))
1434}
1435
1436fn plan_query_inner(qcx: &mut QueryContext, q: &Query<Aug>) -> Result<PlannedQuery, PlanError> {
1437    // Plan CTEs and introduce bindings to `qcx.ctes`. Returns shadowed bindings
1438    // for the identifiers, so that they can be re-installed before returning.
1439    let cte_bindings = plan_ctes(qcx, q)?;
1440
1441    let limit = match &q.limit {
1442        None => None,
1443        Some(Limit {
1444            quantity,
1445            with_ties: false,
1446        }) => {
1447            let ecx = &ExprContext {
1448                qcx,
1449                name: "LIMIT",
1450                scope: &Scope::empty(),
1451                relation_type: &SqlRelationType::empty(),
1452                allow_aggregates: false,
1453                allow_subqueries: true,
1454                allow_parameters: true,
1455                allow_windows: false,
1456            };
1457            let limit = plan_expr(ecx, quantity)?;
1458            let limit = limit.cast_to(ecx, CastContext::Explicit, &SqlScalarType::Int64)?;
1459
1460            let limit = if limit.is_constant() {
1461                let arena = RowArena::new();
1462                let limit = limit.lower_uncorrelated(qcx.scx.catalog.system_vars())?;
1463
1464                // TODO: Don't use ? on eval, but instead wrap the error and add the information
1465                // that the error happened in a LIMIT clause, so that we have better error msg for
1466                // something like `SELECT 5 LIMIT 'aaa'`.
1467                match limit.eval_constant_foldable(&arena)? {
1468                    d @ Datum::Int64(v) if v >= 0 => {
1469                        HirScalarExpr::literal(d, SqlScalarType::Int64)
1470                    }
1471                    d @ Datum::Null => HirScalarExpr::literal(d, SqlScalarType::Int64),
1472                    Datum::Int64(_) => sql_bail!("LIMIT must not be negative"),
1473                    _ => sql_bail!("constant LIMIT expression must reduce to an INT or NULL value"),
1474                }
1475            } else {
1476                // Gate non-constant LIMIT expressions behind a feature flag
1477                qcx.scx
1478                    .require_feature_flag(&vars::ENABLE_EXPRESSIONS_IN_LIMIT_SYNTAX)?;
1479                limit
1480            };
1481
1482            Some(limit)
1483        }
1484        Some(Limit {
1485            quantity: _,
1486            with_ties: true,
1487        }) => bail_unsupported!("FETCH ... WITH TIES"),
1488    };
1489
1490    let offset = match &q.offset {
1491        None => HirScalarExpr::literal(Datum::Int64(0), SqlScalarType::Int64),
1492        Some(offset) => {
1493            let ecx = &ExprContext {
1494                qcx,
1495                name: "OFFSET",
1496                scope: &Scope::empty(),
1497                relation_type: &SqlRelationType::empty(),
1498                allow_aggregates: false,
1499                allow_subqueries: false,
1500                allow_parameters: true,
1501                allow_windows: false,
1502            };
1503            let offset = plan_expr(ecx, offset)?;
1504            let offset = offset.cast_to(ecx, CastContext::Explicit, &SqlScalarType::Int64)?;
1505
1506            let offset = if offset.is_constant() {
1507                // Simplify it to a literal or error out. (E.g., the cast inserted above may fail.)
1508                let offset_value = offset_into_value(offset)?;
1509                HirScalarExpr::literal(Datum::Int64(offset_value), SqlScalarType::Int64)
1510            } else {
1511                // The only case when this is allowed to not be a constant is if it contains
1512                // parameters. (In which case, we'll later check that it's a constant after
1513                // parameter binding.)
1514                if !offset.contains_parameters() {
1515                    return Err(PlanError::InvalidOffset(format!(
1516                        "must be simplifiable to a constant, possibly after parameter binding, got {}",
1517                        offset
1518                    )));
1519                }
1520                offset
1521            };
1522            offset
1523        }
1524    };
1525
1526    let mut planned_query = match &q.body {
1527        SetExpr::Select(s) => {
1528            // Extract query options.
1529            let select_option_extracted = SelectOptionExtracted::try_from(s.options.clone())?;
1530            let group_size_hints = GroupSizeHints::try_from(select_option_extracted)?;
1531
1532            let plan = plan_select_from_where(qcx, *s.clone(), q.order_by.clone())?;
1533            PlannedQuery {
1534                expr: plan.expr,
1535                scope: plan.scope,
1536                order_by: plan.order_by,
1537                project: plan.project,
1538                limit,
1539                offset,
1540                group_size_hints,
1541            }
1542        }
1543        _ => {
1544            let (expr, scope) = plan_set_expr(qcx, &q.body)?;
1545            let ecx = &ExprContext {
1546                qcx,
1547                name: "ORDER BY clause of a set expression",
1548                scope: &scope,
1549                relation_type: &qcx.relation_type(&expr),
1550                allow_aggregates: false,
1551                allow_subqueries: true,
1552                allow_parameters: true,
1553                allow_windows: false,
1554            };
1555            let output_columns: Vec<_> = scope.column_names().enumerate().collect();
1556            let (order_by, map_exprs) = plan_order_by_exprs(ecx, &q.order_by, &output_columns)?;
1557            let project = (0..ecx.relation_type.arity()).collect();
1558            PlannedQuery {
1559                expr: expr.map(map_exprs),
1560                scope,
1561                order_by,
1562                limit,
1563                project,
1564                offset,
1565                group_size_hints: GroupSizeHints::default(),
1566            }
1567        }
1568    };
1569
1570    // Both introduce `Let` bindings atop `result` and re-install shadowed bindings.
1571    match &q.ctes {
1572        CteBlock::Simple(_) => {
1573            for (id, value, shadowed_val) in cte_bindings.into_iter().rev() {
1574                if let Some(cte) = qcx.ctes.remove(&id) {
1575                    planned_query.expr = HirRelationExpr::Let {
1576                        name: cte.name,
1577                        id: id.clone(),
1578                        value: Box::new(value),
1579                        body: Box::new(planned_query.expr),
1580                    };
1581                }
1582                if let Some(shadowed_val) = shadowed_val {
1583                    qcx.ctes.insert(id, shadowed_val);
1584                }
1585            }
1586        }
1587        CteBlock::MutuallyRecursive(MutRecBlock { options, ctes: _ }) => {
1588            let MutRecBlockOptionExtracted {
1589                recursion_limit,
1590                return_at_recursion_limit,
1591                error_at_recursion_limit,
1592                seen: _,
1593            } = MutRecBlockOptionExtracted::try_from(options.clone())?;
1594            let limit = match (
1595                recursion_limit,
1596                return_at_recursion_limit,
1597                error_at_recursion_limit,
1598            ) {
1599                (None, None, None) => None,
1600                (Some(max_iters), None, None) => {
1601                    Some((max_iters, LetRecLimit::RETURN_AT_LIMIT_DEFAULT))
1602                }
1603                (None, Some(max_iters), None) => Some((max_iters, true)),
1604                (None, None, Some(max_iters)) => Some((max_iters, false)),
1605                _ => {
1606                    return Err(InvalidWmrRecursionLimit(
1607                        "More than one recursion limit given. \
1608                         Please give at most one of RECURSION LIMIT, \
1609                         ERROR AT RECURSION LIMIT, \
1610                         RETURN AT RECURSION LIMIT."
1611                            .to_owned(),
1612                    ));
1613                }
1614            }
1615            .try_map(|(max_iters, return_at_limit)| {
1616                Ok::<LetRecLimit, PlanError>(LetRecLimit {
1617                    max_iters: NonZeroU64::new(*max_iters).ok_or(InvalidWmrRecursionLimit(
1618                        "Recursion limit has to be greater than 0.".to_owned(),
1619                    ))?,
1620                    return_at_limit: *return_at_limit,
1621                })
1622            })?;
1623
1624            let mut bindings = Vec::new();
1625            for (id, value, shadowed_val) in cte_bindings.into_iter() {
1626                if let Some(cte) = qcx.ctes.remove(&id) {
1627                    bindings.push((cte.name, id, value, cte.desc.into_typ()));
1628                }
1629                if let Some(shadowed_val) = shadowed_val {
1630                    qcx.ctes.insert(id, shadowed_val);
1631                }
1632            }
1633            if !bindings.is_empty() {
1634                planned_query.expr = HirRelationExpr::LetRec {
1635                    limit,
1636                    bindings,
1637                    body: Box::new(planned_query.expr),
1638                }
1639            }
1640        }
1641    }
1642
1643    Ok(planned_query)
1644}
1645
1646/// Converts an OFFSET expression into a value.
1647pub(crate) fn offset_into_value(offset: HirScalarExpr) -> Result<i64, PlanError> {
1648    let offset = offset
1649        .try_into_literal_int64()
1650        .map_err(|err| PlanError::InvalidOffset(err.to_string_with_causes()))?;
1651    if offset < 0 {
1652        return Err(negative_offset_error(offset));
1653    }
1654    Ok(offset)
1655}
1656
1657pub(crate) fn negative_offset_error(offset: i64) -> PlanError {
1658    PlanError::InvalidOffset(format!("must not be negative, got {}", offset))
1659}
1660
1661generate_extracted_config!(
1662    MutRecBlockOption,
1663    (RecursionLimit, u64),
1664    (ReturnAtRecursionLimit, u64),
1665    (ErrorAtRecursionLimit, u64)
1666);
1667
1668/// Creates plans for CTEs and introduces them to `qcx.ctes`.
1669///
1670/// Returns for each identifier a planned `HirRelationExpr` value, and an optional
1671/// shadowed value that can be reinstalled once the planning has completed.
1672pub fn plan_ctes(
1673    qcx: &mut QueryContext,
1674    q: &Query<Aug>,
1675) -> Result<Vec<(LocalId, HirRelationExpr, Option<CteDesc>)>, PlanError> {
1676    // Accumulate planned expressions and shadowed descriptions.
1677    let mut result = Vec::new();
1678    // Retain the old descriptions of CTE bindings so that we can restore them
1679    // after we're done planning this SELECT.
1680    let mut shadowed_descs = BTreeMap::new();
1681
1682    // A reused identifier indicates a reused name.
1683    if let Some(ident) = q.ctes.bound_identifiers().duplicates().next() {
1684        sql_bail!(
1685            "WITH query name {} specified more than once",
1686            normalize::ident_ref(ident).quoted()
1687        )
1688    }
1689
1690    match &q.ctes {
1691        CteBlock::Simple(ctes) => {
1692            // Plan all CTEs, introducing the types for non-recursive CTEs as we go.
1693            for cte in ctes.iter() {
1694                let cte_name = normalize::ident(cte.alias.name.clone());
1695                let (val, scope) = plan_nested_query(qcx, &cte.query)?;
1696                let typ = qcx.relation_type(&val);
1697                let mut desc = RelationDesc::new(typ, scope.column_names());
1698                plan_utils::maybe_rename_columns(
1699                    format!("CTE {}", cte.alias.name),
1700                    &mut desc,
1701                    &cte.alias.columns,
1702                )?;
1703                // Capture the prior value if it exists, so that it can be re-installed.
1704                let shadowed = qcx.ctes.insert(
1705                    cte.id,
1706                    CteDesc {
1707                        name: cte_name,
1708                        desc,
1709                    },
1710                );
1711
1712                result.push((cte.id, val, shadowed));
1713            }
1714        }
1715        CteBlock::MutuallyRecursive(MutRecBlock { options: _, ctes }) => {
1716            // Insert column types into `qcx.ctes` first for recursive bindings.
1717            for cte in ctes.iter() {
1718                let cte_name = normalize::ident(cte.name.clone());
1719                let mut desc_columns = Vec::with_capacity(cte.columns.capacity());
1720                for column in cte.columns.iter() {
1721                    desc_columns.push((
1722                        normalize::column_name(column.name.clone()),
1723                        SqlColumnType {
1724                            scalar_type: scalar_type_from_sql(qcx.scx, &column.data_type)?,
1725                            nullable: true,
1726                        },
1727                    ));
1728                }
1729                let desc = RelationDesc::from_names_and_types(desc_columns);
1730                let shadowed = qcx.ctes.insert(
1731                    cte.id,
1732                    CteDesc {
1733                        name: cte_name,
1734                        desc,
1735                    },
1736                );
1737                // Capture the prior value if it exists, so that it can be re-installed.
1738                if let Some(shadowed) = shadowed {
1739                    shadowed_descs.insert(cte.id, shadowed);
1740                }
1741            }
1742
1743            // Plan all CTEs and validate the proposed types.
1744            for cte in ctes.iter() {
1745                let (val, _scope) = plan_nested_query(qcx, &cte.query)?;
1746
1747                let proposed_typ = qcx.ctes[&cte.id].desc.typ();
1748
1749                if proposed_typ.column_types.iter().any(|c| !c.nullable) {
1750                    // Once WMR CTEs support NOT NULL constraints, check that
1751                    // nullability of derived column types are compatible.
1752                    sql_bail!(
1753                        "[internal error]: WMR CTEs do not support NOT NULL constraints on proposed column types"
1754                    );
1755                }
1756
1757                if !proposed_typ.keys.is_empty() {
1758                    // Once WMR CTEs support keys, check that keys exactly
1759                    // overlap.
1760                    sql_bail!("[internal error]: WMR CTEs do not support keys");
1761                }
1762
1763                // Validate that the derived and proposed types are the same.
1764                let derived_typ = qcx.relation_type(&val);
1765
1766                let type_err = |proposed_typ: &SqlRelationType, derived_typ: SqlRelationType| {
1767                    let cte_name = normalize::ident(cte.name.clone());
1768                    let proposed_typ = proposed_typ
1769                        .column_types
1770                        .iter()
1771                        .map(|ty| qcx.humanize_sql_scalar_type(&ty.scalar_type, false))
1772                        .collect::<Vec<_>>();
1773                    let inferred_typ = derived_typ
1774                        .column_types
1775                        .iter()
1776                        .map(|ty| qcx.humanize_sql_scalar_type(&ty.scalar_type, false))
1777                        .collect::<Vec<_>>();
1778                    Err(PlanError::RecursiveTypeMismatch(
1779                        cte_name,
1780                        proposed_typ,
1781                        inferred_typ,
1782                    ))
1783                };
1784
1785                if derived_typ.column_types.len() != proposed_typ.column_types.len() {
1786                    return type_err(proposed_typ, derived_typ);
1787                }
1788
1789                // Cast derived types to proposed types or error.
1790                let val = match cast_relation(
1791                    qcx,
1792                    // Choose `CastContext::Assignment`` because the user has
1793                    // been explicit about the types they expect. Choosing
1794                    // `CastContext::Implicit` is not "strong" enough to impose
1795                    // typmods from proposed types onto values.
1796                    CastContext::Assignment,
1797                    val,
1798                    proposed_typ.column_types.iter().map(|c| &c.scalar_type),
1799                ) {
1800                    Ok(val) => val,
1801                    Err(_) => return type_err(proposed_typ, derived_typ),
1802                };
1803
1804                result.push((cte.id, val, shadowed_descs.remove(&cte.id)));
1805            }
1806        }
1807    }
1808
1809    Ok(result)
1810}
1811
1812pub fn plan_nested_query(
1813    qcx: &mut QueryContext,
1814    q: &Query<Aug>,
1815) -> Result<(HirRelationExpr, Scope), PlanError> {
1816    let PlannedQuery {
1817        mut expr,
1818        scope,
1819        order_by,
1820        limit,
1821        offset,
1822        project,
1823        group_size_hints,
1824    } = qcx.checked_recur_mut(|qcx| plan_query(qcx, q))?;
1825    // A nested query is an unordered relation. Its `ORDER BY` is only observable
1826    // in combination with a row-limiting clause (`LIMIT`/`OFFSET`), which selects
1827    // which rows survive. Without such a clause the ordering has no defined
1828    // meaning, so it is dropped rather than materialized into a `TopK`.
1829    //
1830    // NOTE: This diverges from PostgreSQL, where an order-sensitive aggregate
1831    // (`array_agg`, `string_agg`, ...) in the outer query observes a sorted
1832    // subquery's output as an executor artifact. That behavior is not guaranteed
1833    // by the SQL standard and PostgreSQL itself documents it as fragile. Callers
1834    // that need a specific aggregation order must use the in-aggregate
1835    // `agg(value ORDER BY ...)` form instead.
1836    if limit.is_some()
1837        || !offset
1838            .clone()
1839            .try_into_literal_int64()
1840            .is_ok_and(|offset| offset == 0)
1841    {
1842        expr = HirRelationExpr::top_k(
1843            expr,
1844            vec![],
1845            order_by,
1846            limit,
1847            offset,
1848            group_size_hints.limit_input_group_size,
1849        );
1850    }
1851    Ok((expr.project(project), scope))
1852}
1853
1854fn plan_set_expr(
1855    qcx: &mut QueryContext,
1856    q: &SetExpr<Aug>,
1857) -> Result<(HirRelationExpr, Scope), PlanError> {
1858    match q {
1859        SetExpr::Select(select) => {
1860            let order_by_exprs = Vec::new();
1861            let plan = plan_select_from_where(qcx, *select.clone(), order_by_exprs)?;
1862            // We didn't provide any `order_by_exprs`, so `plan_select_from_where`
1863            // should not have planned any ordering.
1864            assert!(plan.order_by.is_empty());
1865            Ok((plan.expr.project(plan.project), plan.scope))
1866        }
1867        SetExpr::SetOperation {
1868            op,
1869            all,
1870            left,
1871            right,
1872        } => {
1873            // Plan the LHS and RHS.
1874            let (left_expr, left_scope) = qcx.checked_recur_mut(|qcx| plan_set_expr(qcx, left))?;
1875            let (right_expr, right_scope) =
1876                qcx.checked_recur_mut(|qcx| plan_set_expr(qcx, right))?;
1877
1878            // Validate that the LHS and RHS are the same width.
1879            let left_type = qcx.relation_type(&left_expr);
1880            let right_type = qcx.relation_type(&right_expr);
1881            if left_type.arity() != right_type.arity() {
1882                sql_bail!(
1883                    "each {} query must have the same number of columns: {} vs {}",
1884                    op,
1885                    left_type.arity(),
1886                    right_type.arity(),
1887                );
1888            }
1889
1890            // Match the types of the corresponding columns on the LHS and RHS
1891            // using the normal type coercion rules. This is equivalent to
1892            // `coerce_homogeneous_exprs`, but implemented in terms of
1893            // `HirRelationExpr` rather than `HirScalarExpr`.
1894            let left_ecx = &ExprContext {
1895                qcx,
1896                name: &op.to_string(),
1897                scope: &left_scope,
1898                relation_type: &left_type,
1899                allow_aggregates: false,
1900                allow_subqueries: false,
1901                allow_parameters: false,
1902                allow_windows: false,
1903            };
1904            let right_ecx = &ExprContext {
1905                qcx,
1906                name: &op.to_string(),
1907                scope: &right_scope,
1908                relation_type: &right_type,
1909                allow_aggregates: false,
1910                allow_subqueries: false,
1911                allow_parameters: false,
1912                allow_windows: false,
1913            };
1914            let mut left_casts = vec![];
1915            let mut right_casts = vec![];
1916            for (i, (left_type, right_type)) in left_type
1917                .column_types
1918                .iter()
1919                .zip_eq(right_type.column_types.iter())
1920                .enumerate()
1921            {
1922                let types = &[
1923                    CoercibleScalarType::Coerced(left_type.scalar_type.clone()),
1924                    CoercibleScalarType::Coerced(right_type.scalar_type.clone()),
1925                ];
1926                let target =
1927                    typeconv::guess_best_common_type(&left_ecx.with_name(&op.to_string()), types)?;
1928                match typeconv::plan_cast(
1929                    left_ecx,
1930                    CastContext::Implicit,
1931                    HirScalarExpr::column(i),
1932                    &target,
1933                ) {
1934                    Ok(expr) => left_casts.push(expr),
1935                    Err(_) => sql_bail!(
1936                        "{} types {} and {} cannot be matched",
1937                        op,
1938                        qcx.humanize_sql_scalar_type(&left_type.scalar_type, false),
1939                        qcx.humanize_sql_scalar_type(&target, false),
1940                    ),
1941                }
1942                match typeconv::plan_cast(
1943                    right_ecx,
1944                    CastContext::Implicit,
1945                    HirScalarExpr::column(i),
1946                    &target,
1947                ) {
1948                    Ok(expr) => right_casts.push(expr),
1949                    Err(_) => sql_bail!(
1950                        "{} types {} and {} cannot be matched",
1951                        op,
1952                        qcx.humanize_sql_scalar_type(&target, false),
1953                        qcx.humanize_sql_scalar_type(&right_type.scalar_type, false),
1954                    ),
1955                }
1956            }
1957            let lhs = if left_casts
1958                .iter()
1959                .enumerate()
1960                .any(|(i, e)| e != &HirScalarExpr::column(i))
1961            {
1962                let project_key: Vec<_> = (left_type.arity()..left_type.arity() * 2).collect();
1963                left_expr.map(left_casts).project(project_key)
1964            } else {
1965                left_expr
1966            };
1967            let rhs = if right_casts
1968                .iter()
1969                .enumerate()
1970                .any(|(i, e)| e != &HirScalarExpr::column(i))
1971            {
1972                let project_key: Vec<_> = (right_type.arity()..right_type.arity() * 2).collect();
1973                right_expr.map(right_casts).project(project_key)
1974            } else {
1975                right_expr
1976            };
1977
1978            let relation_expr = match op {
1979                SetOperator::Union => {
1980                    if *all {
1981                        lhs.union(rhs)
1982                    } else {
1983                        lhs.union(rhs).distinct()
1984                    }
1985                }
1986                SetOperator::Except => Hir::except(all, lhs, rhs),
1987                SetOperator::Intersect => {
1988                    // Planning below duplicates whichever input ends up on the left, so a
1989                    // left-deep chain of INTERSECTs doubles the plan at every level, i.e. would be
1990                    // exponential. INTERSECT is commutative, so put the cheaper input on the left.
1991                    // A subtree is then only duplicated when it is the smaller of the two, so plan
1992                    // size obeys T(a + b) <= 2*T(a) + T(b) for input sizes a <= b. The worst case
1993                    // is balanced trees, where this solves to O(n^log2(3)) instead of O(2^n).
1994                    let (lhs, rhs) = if lhs.relation_node_count() > rhs.relation_node_count() {
1995                        (rhs, lhs)
1996                    } else {
1997                        (lhs, rhs)
1998                    };
1999                    // TODO: Let's not duplicate the left-hand expression into TWO dataflows!
2000                    // The optimizer de-duplicates at some point, but it would be good to already
2001                    // not duplicate here.
2002                    //
2003                    // Also note that we do *not* need another threshold() at the end of the method chain
2004                    // because the right-hand side of the outer union only produces existing records,
2005                    // i.e., the record counts for differential data flow definitely remain non-negative.
2006                    let left_clone = lhs.clone();
2007                    if *all {
2008                        lhs.union(left_clone.union(rhs.negate()).threshold().negate())
2009                    } else {
2010                        lhs.union(left_clone.union(rhs.negate()).threshold().negate())
2011                            .distinct()
2012                    }
2013                }
2014            };
2015            let scope = Scope::from_source(
2016                None,
2017                // Column names are taken from the left, as in Postgres.
2018                left_scope.column_names(),
2019            );
2020
2021            Ok((relation_expr, scope))
2022        }
2023        SetExpr::Values(Values(values)) => plan_values(qcx, values),
2024        SetExpr::Table(name) => {
2025            let (expr, scope) = qcx.resolve_table_name(name.clone())?;
2026            Ok((expr, scope))
2027        }
2028        SetExpr::Query(query) => {
2029            let (expr, scope) = plan_nested_query(qcx, query)?;
2030            Ok((expr, scope))
2031        }
2032        SetExpr::Show(stmt) => {
2033            // The create SQL definition of involving this query, will have the explicit `SHOW`
2034            // command in it. Many `SHOW` commands will expand into a sub-query that involves the
2035            // current schema of the executing user. When Materialize restarts and tries to re-plan
2036            // these queries, it will only have access to the raw `SHOW` command and have no idea
2037            // what schema to use. As a result Materialize will fail to boot.
2038            //
2039            // Some `SHOW` commands are ok, like `SHOW CLUSTERS`, and there are probably other ways
2040            // around this issue. Such as expanding the `SHOW` command in the SQL definition.
2041            // However, banning show commands in views gives us more flexibility to change their
2042            // output.
2043            //
2044            // TODO(jkosh44) Add message to error that prints out an equivalent view definition
2045            // with all show commands expanded into their equivalent SELECT statements.
2046            if !qcx.lifetime.allow_show() {
2047                return Err(PlanError::ShowCommandInView);
2048            }
2049
2050            // Some SHOW statements are a SELECT query. Others produces Rows
2051            // directly. Convert both of these to the needed Hir and Scope.
2052            fn to_hirscope(
2053                plan: ShowCreatePlan,
2054                desc: StatementDesc,
2055            ) -> Result<(HirRelationExpr, Scope), PlanError> {
2056                let rows = vec![plan.row.iter().collect::<Vec<_>>()];
2057                let desc = desc.relation_desc.ok_or_else(|| {
2058                    internal_err!("statement description missing relation descriptor")
2059                })?;
2060                let scope = Scope::from_source(None, desc.iter_names());
2061                let expr = HirRelationExpr::constant(rows, desc.into_typ());
2062                Ok((expr, scope))
2063            }
2064
2065            match stmt.as_ref().clone() {
2066                ShowStatement::ShowColumns(stmt) => {
2067                    show::show_columns(qcx.scx, stmt)?.plan_hir(qcx)
2068                }
2069                ShowStatement::ShowCreateConnection(stmt) => to_hirscope(
2070                    show::plan_show_create_connection(qcx.scx, stmt.clone())?,
2071                    show::describe_show_create_connection(qcx.scx, stmt)?,
2072                ),
2073                ShowStatement::ShowCreateCluster(stmt) => to_hirscope(
2074                    show::plan_show_create_cluster(qcx.scx, stmt.clone())?,
2075                    show::describe_show_create_cluster(qcx.scx, stmt)?,
2076                ),
2077                ShowStatement::ShowCreateIndex(stmt) => to_hirscope(
2078                    show::plan_show_create_index(qcx.scx, stmt.clone())?,
2079                    show::describe_show_create_index(qcx.scx, stmt)?,
2080                ),
2081                ShowStatement::ShowCreateSink(stmt) => to_hirscope(
2082                    show::plan_show_create_sink(qcx.scx, stmt.clone())?,
2083                    show::describe_show_create_sink(qcx.scx, stmt)?,
2084                ),
2085                ShowStatement::ShowCreateMetricSink(stmt) => to_hirscope(
2086                    show::plan_show_create_metric_sink(qcx.scx, stmt.clone())?,
2087                    show::describe_show_create_metric_sink(qcx.scx, stmt)?,
2088                ),
2089                ShowStatement::ShowCreateSource(stmt) => to_hirscope(
2090                    show::plan_show_create_source(qcx.scx, stmt.clone())?,
2091                    show::describe_show_create_source(qcx.scx, stmt)?,
2092                ),
2093                ShowStatement::ShowCreateTable(stmt) => to_hirscope(
2094                    show::plan_show_create_table(qcx.scx, stmt.clone())?,
2095                    show::describe_show_create_table(qcx.scx, stmt)?,
2096                ),
2097                ShowStatement::ShowCreateView(stmt) => to_hirscope(
2098                    show::plan_show_create_view(qcx.scx, stmt.clone())?,
2099                    show::describe_show_create_view(qcx.scx, stmt)?,
2100                ),
2101                ShowStatement::ShowCreateMaterializedView(stmt) => to_hirscope(
2102                    show::plan_show_create_materialized_view(qcx.scx, stmt.clone())?,
2103                    show::describe_show_create_materialized_view(qcx.scx, stmt)?,
2104                ),
2105                ShowStatement::ShowCreateType(stmt) => to_hirscope(
2106                    show::plan_show_create_type(qcx.scx, stmt.clone())?,
2107                    show::describe_show_create_type(qcx.scx, stmt)?,
2108                ),
2109                ShowStatement::ShowObjects(stmt) => {
2110                    show::show_objects(qcx.scx, stmt)?.plan_hir(qcx)
2111                }
2112                ShowStatement::ShowVariable(_) => bail_unsupported!("SHOW variable in subqueries"),
2113                ShowStatement::InspectShard(_) => sql_bail!("unsupported INSPECT statement"),
2114            }
2115        }
2116    }
2117}
2118
2119/// Plans a `VALUES` clause that appears in a `SELECT` statement.
2120fn plan_values(
2121    qcx: &QueryContext,
2122    values: &[Vec<Expr<Aug>>],
2123) -> Result<(HirRelationExpr, Scope), PlanError> {
2124    assert!(!values.is_empty());
2125
2126    let ecx = &ExprContext {
2127        qcx,
2128        name: "VALUES",
2129        scope: &Scope::empty(),
2130        relation_type: &SqlRelationType::empty(),
2131        allow_aggregates: false,
2132        allow_subqueries: true,
2133        allow_parameters: true,
2134        allow_windows: false,
2135    };
2136
2137    let ncols = values[0].len();
2138    let nrows = values.len();
2139
2140    // Arrange input expressions by columns, not rows, so that we can
2141    // call `coerce_homogeneous_exprs` on each column.
2142    let mut cols = vec![vec![]; ncols];
2143    for row in values {
2144        if row.len() != ncols {
2145            sql_bail!(
2146                "VALUES expression has varying number of columns: {} vs {}",
2147                row.len(),
2148                ncols
2149            );
2150        }
2151        for (i, v) in row.iter().enumerate() {
2152            cols[i].push(v);
2153        }
2154    }
2155
2156    // Plan each column.
2157    let mut col_iters = Vec::with_capacity(ncols);
2158    let mut col_types = Vec::with_capacity(ncols);
2159    for col in &cols {
2160        let col = coerce_homogeneous_exprs(ecx, plan_exprs(ecx, col)?, None)?;
2161        let mut col_type = ecx.column_type(&col[0]);
2162        for val in &col[1..] {
2163            col_type = col_type.sql_union(&ecx.column_type(val))?; // HIR deliberately not using `union`
2164        }
2165        col_types.push(col_type);
2166        col_iters.push(col.into_iter());
2167    }
2168
2169    // Build constant relation.
2170    let mut exprs = vec![];
2171    for _ in 0..nrows {
2172        for i in 0..ncols {
2173            exprs.push(col_iters[i].next().unwrap());
2174        }
2175    }
2176    let out = HirRelationExpr::CallTable {
2177        func: TableFunc::Wrap {
2178            width: ncols,
2179            types: col_types,
2180        },
2181        exprs,
2182    };
2183
2184    // Build column names.
2185    let mut scope = Scope::empty();
2186    for i in 0..ncols {
2187        let name = format!("column{}", i + 1);
2188        scope.items.push(ScopeItem::from_column_name(name));
2189    }
2190
2191    Ok((out, scope))
2192}
2193
2194/// Plans a `VALUES` clause that appears at the top level of an `INSERT`
2195/// statement.
2196///
2197/// This is special-cased in PostgreSQL and different enough from `plan_values`
2198/// that it is easier to use a separate function entirely. Unlike a normal
2199/// `VALUES` clause, each value is coerced to the type of the target table
2200/// via an assignment cast.
2201///
2202/// See: <https://github.com/postgres/postgres/blob/ad77039fa/src/backend/parser/analyze.c#L504-L518>
2203fn plan_values_insert(
2204    qcx: &QueryContext,
2205    target_names: &[&ColumnName],
2206    target_types: &[&SqlScalarType],
2207    values: &[Vec<Expr<Aug>>],
2208) -> Result<HirRelationExpr, PlanError> {
2209    assert!(!values.is_empty());
2210
2211    if !values.iter().map(|row| row.len()).all_equal() {
2212        sql_bail!("VALUES lists must all be the same length");
2213    }
2214
2215    let ecx = &ExprContext {
2216        qcx,
2217        name: "VALUES",
2218        scope: &Scope::empty(),
2219        relation_type: &SqlRelationType::empty(),
2220        allow_aggregates: false,
2221        allow_subqueries: true,
2222        allow_parameters: true,
2223        allow_windows: false,
2224    };
2225
2226    let mut exprs = vec![];
2227    let mut types = vec![];
2228    for row in values {
2229        if row.len() > target_names.len() {
2230            sql_bail!("INSERT has more expressions than target columns");
2231        }
2232        for (column, val) in row.into_iter().enumerate() {
2233            let target_type = &target_types[column];
2234            let val = plan_expr(ecx, val)?;
2235            let val = typeconv::plan_coerce(ecx, val, target_type)?;
2236            let source_type = &ecx.scalar_type(&val);
2237            let val = match typeconv::plan_cast(ecx, CastContext::Assignment, val, target_type) {
2238                Ok(val) => val,
2239                Err(_) => sql_bail!(
2240                    "column {} is of type {} but expression is of type {}",
2241                    target_names[column].quoted(),
2242                    qcx.humanize_sql_scalar_type(target_type, false),
2243                    qcx.humanize_sql_scalar_type(source_type, false),
2244                ),
2245            };
2246            if column >= types.len() {
2247                types.push(ecx.column_type(&val));
2248            } else {
2249                types[column] = types[column].sql_union(&ecx.column_type(&val))?; // HIR deliberately not using `union`
2250            }
2251            exprs.push(val);
2252        }
2253    }
2254
2255    Ok(HirRelationExpr::CallTable {
2256        func: TableFunc::Wrap {
2257            width: values[0].len(),
2258            types,
2259        },
2260        exprs,
2261    })
2262}
2263
2264fn plan_join_identity() -> (HirRelationExpr, Scope) {
2265    let typ = SqlRelationType::new(vec![]);
2266    let expr = HirRelationExpr::constant(vec![vec![]], typ);
2267    let scope = Scope::empty();
2268    (expr, scope)
2269}
2270
2271/// Describes how to execute a SELECT query.
2272///
2273/// `order_by` describes how to order the rows in `expr` *before* applying the
2274/// projection. The `scope` describes the columns in `expr` *after* the
2275/// projection has been applied.
2276#[derive(Debug)]
2277struct SelectPlan {
2278    expr: HirRelationExpr,
2279    scope: Scope,
2280    order_by: Vec<ColumnOrder>,
2281    project: Vec<usize>,
2282}
2283
2284generate_extracted_config!(
2285    SelectOption,
2286    (ExpectedGroupSize, u64),
2287    (AggregateInputGroupSize, u64),
2288    (DistinctOnInputGroupSize, u64),
2289    (LimitInputGroupSize, u64)
2290);
2291
2292/// Plans a SELECT query. The SELECT query may contain an intrusive ORDER BY clause.
2293///
2294/// Normally, the ORDER BY clause occurs after the columns specified in the
2295/// SELECT list have been projected. In a query like
2296///
2297///   CREATE TABLE (a int, b int)
2298///   (SELECT a FROM t) UNION (SELECT a FROM t) ORDER BY a
2299///
2300/// it is valid to refer to `a`, because it is explicitly selected, but it would
2301/// not be valid to refer to unselected column `b`.
2302///
2303/// But PostgreSQL extends the standard to permit queries like
2304///
2305///   SELECT a FROM t ORDER BY b
2306///
2307/// where expressions in the ORDER BY clause can refer to *both* input columns
2308/// and output columns.
2309fn plan_select_from_where(
2310    qcx: &QueryContext,
2311    mut s: Select<Aug>,
2312    mut order_by_exprs: Vec<OrderByExpr<Aug>>,
2313) -> Result<SelectPlan, PlanError> {
2314    // TODO: Both `s` and `order_by_exprs` are not references because the
2315    // AggregateTableFuncVisitor needs to be able to rewrite the expressions for
2316    // table function support (the UUID mapping). Attempt to change this so callers
2317    // don't need to clone the Select.
2318
2319    // Extract query options.
2320    let select_option_extracted = SelectOptionExtracted::try_from(s.options.clone())?;
2321    let group_size_hints = GroupSizeHints::try_from(select_option_extracted)?;
2322
2323    // Step 1. Handle FROM clause, including joins.
2324    let (mut relation_expr, mut from_scope) =
2325        s.from.iter().try_fold(plan_join_identity(), |l, twj| {
2326            let (left, left_scope) = l;
2327            plan_join(
2328                qcx,
2329                left,
2330                left_scope,
2331                &Join {
2332                    relation: TableFactor::NestedJoin {
2333                        join: Box::new(twj.clone()),
2334                        alias: None,
2335                    },
2336                    join_operator: JoinOperator::CrossJoin,
2337                },
2338            )
2339        })?;
2340
2341    // Step 2. Handle WHERE clause.
2342    if let Some(selection) = &s.selection {
2343        let ecx = &ExprContext {
2344            qcx,
2345            name: "WHERE clause",
2346            scope: &from_scope,
2347            relation_type: &qcx.relation_type(&relation_expr),
2348            allow_aggregates: false,
2349            allow_subqueries: true,
2350            allow_parameters: true,
2351            allow_windows: false,
2352        };
2353        let expr = plan_expr(ecx, selection)
2354            .map_err(|e| sql_err!("WHERE clause error: {}", e))?
2355            .type_as(ecx, &SqlScalarType::Bool)?;
2356        relation_expr = relation_expr.filter(vec![expr]);
2357    }
2358
2359    // Step 3. Gather aggregates and table functions.
2360    // (But skip window aggregates.)
2361    let (aggregates, table_funcs) = {
2362        let mut visitor = AggregateTableFuncVisitor::new(qcx.scx);
2363        visitor.visit_select_mut(&mut s);
2364        for o in order_by_exprs.iter_mut() {
2365            visitor.visit_order_by_expr_mut(o);
2366        }
2367        visitor.into_result()?
2368    };
2369    let mut table_func_names: BTreeMap<String, Ident> = BTreeMap::new();
2370    // Table functions in the SELECT list apply to the output of the reduce
2371    // (GROUP BY, aggregates, HAVING), but their columns must already be in
2372    // scope when the SELECT list is expanded and GROUP BY items are planned,
2373    // so the join is planned here regardless. Step 5 decides whether the
2374    // reduce consumes this join or the saved pre-join relation, and in the
2375    // latter case Step 8.5 plans the join again on top of the reduce.
2376    let pre_table_funcs_arity = from_scope.len();
2377    let mut pre_table_funcs_relation = None;
2378    let mut table_funcs_deferred = false;
2379    if !table_funcs.is_empty() {
2380        let (expr, scope) = plan_scalar_table_funcs(
2381            qcx,
2382            &table_funcs,
2383            &mut table_func_names,
2384            &relation_expr,
2385            &from_scope,
2386        )?;
2387        if !aggregates.is_empty() || !s.group_by.is_empty() || s.having.is_some() {
2388            pre_table_funcs_relation = Some(relation_expr.clone());
2389        }
2390        relation_expr = relation_expr.join(expr, HirScalarExpr::literal_true(), JoinKind::Inner);
2391        from_scope = from_scope.product(scope)?;
2392    }
2393
2394    // Step 4. Expand SELECT clause.
2395    let projection = {
2396        let ecx = &ExprContext {
2397            qcx,
2398            name: "SELECT clause",
2399            scope: &from_scope,
2400            relation_type: &qcx.relation_type(&relation_expr),
2401            allow_aggregates: true,
2402            allow_subqueries: true,
2403            allow_parameters: true,
2404            allow_windows: true,
2405        };
2406        let mut out = vec![];
2407        for si in &s.projection {
2408            if *si == SelectItem::Wildcard && s.from.is_empty() {
2409                sql_bail!("SELECT * with no tables specified is not valid");
2410            }
2411            out.extend(expand_select_item(ecx, si, &table_func_names)?);
2412        }
2413        out
2414    };
2415
2416    // Step 5. Handle GROUP BY clause.
2417    // This will also plan the aggregates gathered in Step 3.
2418    // See an overview of how aggregates are planned in the doc comment at the top of the file.
2419    let (mut group_scope, select_all_mapping) = {
2420        // Compute GROUP BY expressions.
2421        let ecx = &ExprContext {
2422            qcx,
2423            name: "GROUP BY clause",
2424            scope: &from_scope,
2425            relation_type: &qcx.relation_type(&relation_expr),
2426            allow_aggregates: false,
2427            allow_subqueries: true,
2428            allow_parameters: true,
2429            allow_windows: false,
2430        };
2431        let mut group_key = vec![];
2432        let mut group_exprs: BTreeMap<HirScalarExpr, ScopeItem> = BTreeMap::new();
2433        let mut group_hir_exprs = vec![];
2434        let mut group_scope = Scope::empty();
2435        let mut select_all_mapping = BTreeMap::new();
2436
2437        for group_expr in &s.group_by {
2438            let (group_expr, expr) = plan_group_by_expr(ecx, group_expr, &projection)?;
2439            let new_column = group_key.len();
2440
2441            // Multiple AST expressions can map to the same HIR expression, e.g.
2442            // `GROUP BY 1, 1` or `GROUP BY a, 1` where the positional reference
2443            // `1` resolves to the same column as `a`. When we already have a
2444            // ScopeItem for this HIR expression we must deduplicate: skip adding
2445            // a second group key for it. We must not gate this on `group_expr`
2446            // being `Some`, because a positional reference to an input column
2447            // (e.g. `GROUP BY 1`) has no AST expression to record yet still
2448            // needs to dedup against the existing key; gating on `Some` here is
2449            // what made `GROUP BY 1, 1` panic on the `group_hir_exprs.len() ==
2450            // group_exprs.len()` assertion below.
2451            if let Some(existing_scope_item) = group_exprs.get_mut(&expr) {
2452                // If this AST expression is a named expression (not a bare
2453                // positional reference), record it on the existing ScopeItem so
2454                // name resolution can find it.
2455                if let Some(group_expr) = group_expr {
2456                    existing_scope_item.exprs.insert(group_expr.clone());
2457                }
2458                continue;
2459            }
2460
2461            let mut scope_item = if let HirScalarExpr::Column(
2462                ColumnRef {
2463                    level: 0,
2464                    column: old_column,
2465                },
2466                _name,
2467            ) = &expr
2468            {
2469                // If we later have `SELECT foo.*` then we have to find all
2470                // the `foo` items in `from_scope` and figure out where they
2471                // ended up in `group_scope`. This is really hard to do
2472                // right using SQL name resolution, so instead we just track
2473                // the movement here.
2474                select_all_mapping.insert(*old_column, new_column);
2475                let scope_item = ecx.scope.items[*old_column].clone();
2476                scope_item
2477            } else {
2478                ScopeItem::empty()
2479            };
2480
2481            if let Some(group_expr) = group_expr.cloned() {
2482                scope_item.exprs.insert(group_expr);
2483            }
2484
2485            group_key.push(from_scope.len() + group_exprs.len());
2486            group_hir_exprs.push(expr.clone());
2487            group_exprs.insert(expr, scope_item);
2488        }
2489
2490        assert_eq!(group_hir_exprs.len(), group_exprs.len());
2491        for expr in &group_hir_exprs {
2492            if let Some(scope_item) = group_exprs.remove(expr) {
2493                group_scope.items.push(scope_item);
2494            }
2495        }
2496
2497        // Plan aggregates.
2498        let ecx = &ExprContext {
2499            qcx,
2500            name: "aggregate function",
2501            scope: &from_scope,
2502            relation_type: &qcx.relation_type(&relation_expr.clone().map(group_hir_exprs.clone())),
2503            allow_aggregates: false,
2504            allow_subqueries: true,
2505            allow_parameters: true,
2506            allow_windows: false,
2507        };
2508        let mut agg_exprs = vec![];
2509        for sql_function in aggregates {
2510            if sql_function.over.is_some() {
2511                unreachable!(
2512                    "Window aggregate; AggregateTableFuncVisitor explicitly filters these out"
2513                );
2514            }
2515            agg_exprs.push(plan_aggregate_common(ecx, &sql_function)?);
2516            group_scope
2517                .items
2518                .push(ScopeItem::from_expr(Expr::Function(sql_function.clone())));
2519        }
2520        if !agg_exprs.is_empty() || !group_key.is_empty() || s.having.is_some() {
2521            // Table functions join after the reduce only when no group key or
2522            // aggregate references their columns, e.g. GROUP BY on a SELECT
2523            // list alias of a table function.
2524            if let Some(pre_relation_expr) = pre_table_funcs_relation.take() {
2525                let mut references_table_funcs = false;
2526                let mut check = |column: usize| {
2527                    if column >= pre_table_funcs_arity {
2528                        references_table_funcs = true;
2529                    }
2530                };
2531                for expr in &group_hir_exprs {
2532                    expr.visit_columns_referring_to_root_level(&mut check);
2533                }
2534                for agg_expr in &agg_exprs {
2535                    agg_expr
2536                        .expr
2537                        .visit_columns_referring_to_root_level(&mut check);
2538                }
2539                if !references_table_funcs {
2540                    relation_expr = pre_relation_expr;
2541                    // The group keys point past the table functions' columns,
2542                    // which the saved relation does not have.
2543                    for (i, key) in group_key.iter_mut().enumerate() {
2544                        *key = pre_table_funcs_arity + i;
2545                    }
2546                    table_funcs_deferred = true;
2547                }
2548            }
2549
2550            // apply GROUP BY / aggregates
2551            relation_expr = relation_expr.map(group_hir_exprs).reduce(
2552                group_key,
2553                agg_exprs,
2554                group_size_hints.aggregate_input_group_size,
2555            );
2556
2557            // For every old column that wasn't a group key, add a scope item
2558            // that errors when referenced. We can't simply drop these items
2559            // from scope. These items need to *exist* because they might shadow
2560            // variables in outer scopes that would otherwise be valid to
2561            // reference, but accessing them needs to produce an error.
2562            // Deferred table functions' columns come back into scope in Step
2563            // 8.5, so they must not be recorded as ungrouped.
2564            let ungrouped_arity = if table_funcs_deferred {
2565                pre_table_funcs_arity
2566            } else {
2567                from_scope.len()
2568            };
2569            for i in 0..ungrouped_arity {
2570                if !select_all_mapping.contains_key(&i) {
2571                    let scope_item = &ecx.scope.items[i];
2572                    group_scope.ungrouped_columns.push(ScopeUngroupedColumn {
2573                        table_name: scope_item.table_name.clone(),
2574                        column_name: scope_item.column_name.clone(),
2575                        allow_unqualified_references: scope_item.allow_unqualified_references,
2576                    });
2577                }
2578            }
2579
2580            (group_scope, select_all_mapping)
2581        } else {
2582            // if no GROUP BY, aggregates or having then all columns remain in scope
2583            (
2584                from_scope.clone(),
2585                (0..from_scope.len()).map(|i| (i, i)).collect(),
2586            )
2587        }
2588    };
2589
2590    // Step 6. Handle HAVING clause.
2591    if let Some(ref having) = s.having {
2592        let ecx = &ExprContext {
2593            qcx,
2594            name: "HAVING clause",
2595            scope: &group_scope,
2596            relation_type: &qcx.relation_type(&relation_expr),
2597            allow_aggregates: true,
2598            allow_subqueries: true,
2599            allow_parameters: true,
2600            allow_windows: false,
2601        };
2602        let expr = plan_expr(ecx, having)?.type_as(ecx, &SqlScalarType::Bool)?;
2603        relation_expr = relation_expr.filter(vec![expr]);
2604    }
2605
2606    // Step 7. Gather window functions from SELECT, ORDER BY, and QUALIFY, and plan them.
2607    // (This includes window aggregations.)
2608    //
2609    // Note that window functions can be present only in SELECT, ORDER BY, or QUALIFY (including
2610    // DISTINCT ON), because they are executed after grouped aggregations and HAVING.
2611    //
2612    // Also note that window functions in the ORDER BY can't refer to columns introduced in the
2613    // SELECT. This is because when an output column appears in ORDER BY, it can only stand alone,
2614    // and can't be part of a bigger expression.
2615    // See https://www.postgresql.org/docs/current/queries-order.html:
2616    // "Note that an output column name has to stand alone, that is, it cannot be used in an
2617    // expression"
2618    let window_funcs = {
2619        let mut visitor = WindowFuncCollector::default();
2620        // The `visit_select` call visits both `SELECT` and `QUALIFY` (and many other things, but
2621        // window functions are excluded from other things by `allow_windows` being false when
2622        // planning those before this code).
2623        visitor.visit_select(&s);
2624        for o in order_by_exprs.iter() {
2625            visitor.visit_order_by_expr(o);
2626        }
2627        visitor.into_result()
2628    };
2629    for window_func in window_funcs {
2630        let ecx = &ExprContext {
2631            qcx,
2632            name: "window function",
2633            scope: &group_scope,
2634            relation_type: &qcx.relation_type(&relation_expr),
2635            allow_aggregates: true,
2636            allow_subqueries: true,
2637            allow_parameters: true,
2638            allow_windows: true,
2639        };
2640        relation_expr = relation_expr.map(vec![plan_expr(ecx, &window_func)?.type_as_any(ecx)?]);
2641        group_scope.items.push(ScopeItem::from_expr(window_func));
2642    }
2643    // From this point on, we shouldn't encounter _valid_ window function calls, because those have
2644    // been already planned now. However, we should still set `allow_windows: true` for the
2645    // remaining planning of `QUALIFY`, `SELECT`, and `ORDER BY`, in order to have a correct error
2646    // msg if an OVER clause is missing from a window function.
2647
2648    // Step 8. Handle QUALIFY clause. (very similar to HAVING)
2649    if let Some(ref qualify) = s.qualify {
2650        let ecx = &ExprContext {
2651            qcx,
2652            name: "QUALIFY clause",
2653            scope: &group_scope,
2654            relation_type: &qcx.relation_type(&relation_expr),
2655            allow_aggregates: true,
2656            allow_subqueries: true,
2657            allow_parameters: true,
2658            allow_windows: true,
2659        };
2660        let expr = plan_expr(ecx, qualify)?.type_as(ecx, &SqlScalarType::Bool)?;
2661        relation_expr = relation_expr.filter(vec![expr]);
2662    }
2663
2664    // Step 8.5. Join the table functions deferred in Step 5. Planning them
2665    // again rebinds their arguments' column references to the reduced
2666    // relation.
2667    if table_funcs_deferred {
2668        let (expr, scope) = plan_scalar_table_funcs(
2669            qcx,
2670            &table_funcs,
2671            &mut table_func_names,
2672            &relation_expr,
2673            &group_scope,
2674        )?;
2675        relation_expr = relation_expr.join(expr, HirScalarExpr::literal_true(), JoinKind::Inner);
2676        // `product` resets `ungrouped_columns`, but the ungrouped column
2677        // errors from the reduce must survive for the SELECT list.
2678        let ungrouped_columns = mem::take(&mut group_scope.ungrouped_columns);
2679        group_scope = group_scope.product(scope)?;
2680        group_scope.ungrouped_columns = ungrouped_columns;
2681    }
2682
2683    // Step 9. Handle SELECT clause.
2684    let output_columns = {
2685        let mut new_exprs = vec![];
2686        let mut new_type = qcx.relation_type(&relation_expr);
2687        let mut output_columns = vec![];
2688        for (select_item, column_name) in &projection {
2689            let ecx = &ExprContext {
2690                qcx,
2691                name: "SELECT clause",
2692                scope: &group_scope,
2693                relation_type: &new_type,
2694                allow_aggregates: true,
2695                allow_subqueries: true,
2696                allow_parameters: true,
2697                allow_windows: true,
2698            };
2699            let expr = match select_item {
2700                ExpandedSelectItem::InputOrdinal(i) => {
2701                    if let Some(column) = select_all_mapping.get(i).copied() {
2702                        HirScalarExpr::column(column)
2703                    } else {
2704                        return Err(PlanError::ungrouped_column(&from_scope.items[*i]));
2705                    }
2706                }
2707                ExpandedSelectItem::Expr(expr) => plan_expr(ecx, expr)?.type_as_any(ecx)?,
2708            };
2709            if let HirScalarExpr::Column(ColumnRef { level: 0, column }, _name) = expr {
2710                // Simple column reference; no need to map on a new expression.
2711                output_columns.push((column, column_name));
2712            } else {
2713                // Complicated expression that requires a map expression. We
2714                // update `group_scope` as we go so that future expressions that
2715                // are textually identical to this one can reuse it. This
2716                // duplicate detection is required for proper determination of
2717                // ambiguous column references with SQL92-style `ORDER BY`
2718                // items. See `plan_order_by_or_distinct_expr` for more.
2719                let typ = ecx.column_type(&expr);
2720                new_type.column_types.push(typ);
2721                new_exprs.push(expr);
2722                output_columns.push((group_scope.len(), column_name));
2723                group_scope
2724                    .items
2725                    .push(ScopeItem::from_expr(select_item.as_expr().cloned()));
2726            }
2727        }
2728        relation_expr = relation_expr.map(new_exprs);
2729        output_columns
2730    };
2731    let mut project_key: Vec<_> = output_columns.iter().map(|(i, _name)| *i).collect();
2732
2733    // Step 10. Handle intrusive ORDER BY and DISTINCT.
2734    let order_by = {
2735        let relation_type = qcx.relation_type(&relation_expr);
2736        let (mut order_by, mut map_exprs) = plan_order_by_exprs(
2737            &ExprContext {
2738                qcx,
2739                name: "ORDER BY clause",
2740                scope: &group_scope,
2741                relation_type: &relation_type,
2742                allow_aggregates: true,
2743                allow_subqueries: true,
2744                allow_parameters: true,
2745                allow_windows: true,
2746            },
2747            &order_by_exprs,
2748            &output_columns,
2749        )?;
2750
2751        match s.distinct {
2752            None => relation_expr = relation_expr.map(map_exprs),
2753            Some(Distinct::EntireRow) => {
2754                if relation_type.arity() == 0 {
2755                    sql_bail!("SELECT DISTINCT must have at least one column");
2756                }
2757                // `SELECT DISTINCT` only distincts on the columns in the SELECT
2758                // list, so we can't proceed if `ORDER BY` has introduced any
2759                // columns for arbitrary expressions. This matches PostgreSQL.
2760                if !try_push_projection_order_by(
2761                    &mut relation_expr,
2762                    &mut project_key,
2763                    &mut order_by,
2764                ) {
2765                    sql_bail!(
2766                        "for SELECT DISTINCT, ORDER BY expressions must appear in select list"
2767                    );
2768                }
2769                assert!(map_exprs.is_empty());
2770                relation_expr = relation_expr.distinct();
2771            }
2772            Some(Distinct::On(exprs)) => {
2773                // The table functions deferred in Step 5 join below this TopK,
2774                // so the distinct would collapse their expansion rather than
2775                // expand the rows the distinct picks. PostgreSQL instead
2776                // evaluates a SELECT list table function after the distinct
2777                // whenever the query has an ORDER BY and the function's output
2778                // is not itself a distinct or sort key. Reject these queries
2779                // rather than answer them differently.
2780                if table_funcs_deferred && !order_by_exprs.is_empty() {
2781                    bail_unsupported!(
2782                        "SELECT list table function with DISTINCT ON and ORDER BY over an aggregation"
2783                    );
2784                }
2785
2786                let ecx = &ExprContext {
2787                    qcx,
2788                    name: "DISTINCT ON clause",
2789                    scope: &group_scope,
2790                    relation_type: &qcx.relation_type(&relation_expr),
2791                    allow_aggregates: true,
2792                    allow_subqueries: true,
2793                    allow_parameters: true,
2794                    allow_windows: true,
2795                };
2796
2797                let mut distinct_exprs = vec![];
2798                for expr in &exprs {
2799                    let expr = plan_order_by_or_distinct_expr(ecx, expr, &output_columns)?;
2800                    distinct_exprs.push(expr);
2801                }
2802
2803                let mut distinct_key = vec![];
2804
2805                // If both `DISTINCT ON` and `ORDER BY` are specified, then the
2806                // `DISTINCT ON` expressions must match the initial `ORDER BY`
2807                // expressions, though the order of `DISTINCT ON` expressions
2808                // does not matter. This matches PostgreSQL and leaves the door
2809                // open to a future optimization where the `DISTINCT ON` and
2810                // `ORDER BY` operations happen in one pass.
2811                //
2812                // On the bright side, any columns that have already been
2813                // computed by `ORDER BY` can be reused in the distinct key.
2814                let arity = relation_type.arity();
2815                for ord in order_by.iter().take(distinct_exprs.len()) {
2816                    // The unusual construction of `expr` here is to ensure the
2817                    // temporary column expression lives long enough.
2818                    let mut expr = &HirScalarExpr::column(ord.column);
2819                    if ord.column >= arity {
2820                        expr = &map_exprs[ord.column - arity];
2821                    };
2822                    match distinct_exprs.iter().position(move |e| e == expr) {
2823                        None => sql_bail!(
2824                            "SELECT DISTINCT ON expressions must match initial ORDER BY expressions"
2825                        ),
2826                        Some(pos) => {
2827                            distinct_exprs.remove(pos);
2828                        }
2829                    }
2830                    distinct_key.push(ord.column);
2831                }
2832
2833                // Add any remaining `DISTINCT ON` expressions to the key.
2834                for expr in distinct_exprs {
2835                    // If the expression is a reference to an existing column,
2836                    // do not introduce a new column to support it.
2837                    let column = match expr {
2838                        HirScalarExpr::Column(ColumnRef { level: 0, column }, _name) => column,
2839                        _ => {
2840                            map_exprs.push(expr);
2841                            arity + map_exprs.len() - 1
2842                        }
2843                    };
2844                    distinct_key.push(column);
2845                }
2846
2847                // `DISTINCT ON` is semantically a TopK with limit 1. The
2848                // columns in `ORDER BY` that are not part of the distinct key,
2849                // if there are any, determine the ordering within each group,
2850                // per PostgreSQL semantics.
2851                let distinct_len = distinct_key.len();
2852                relation_expr = HirRelationExpr::top_k(
2853                    relation_expr.map(map_exprs),
2854                    distinct_key,
2855                    order_by.iter().skip(distinct_len).cloned().collect(),
2856                    Some(HirScalarExpr::literal(
2857                        Datum::Int64(1),
2858                        SqlScalarType::Int64,
2859                    )),
2860                    HirScalarExpr::literal(Datum::Int64(0), SqlScalarType::Int64),
2861                    group_size_hints.distinct_on_input_group_size,
2862                );
2863            }
2864        }
2865
2866        order_by
2867    };
2868
2869    // Construct a clean scope to expose outwards, where all of the state that
2870    // accumulated in the scope during planning of this SELECT is erased. The
2871    // clean scope has at most one name for each column, and the names are not
2872    // associated with any table.
2873    let scope = Scope::from_source(None, projection.into_iter().map(|(_expr, name)| name));
2874
2875    Ok(SelectPlan {
2876        expr: relation_expr,
2877        scope,
2878        order_by,
2879        project: project_key,
2880    })
2881}
2882
2883fn plan_scalar_table_funcs(
2884    qcx: &QueryContext,
2885    table_funcs: &BTreeMap<Function<Aug>, String>,
2886    table_func_names: &mut BTreeMap<String, Ident>,
2887    relation_expr: &HirRelationExpr,
2888    from_scope: &Scope,
2889) -> Result<(HirRelationExpr, Scope), PlanError> {
2890    let rows_from_qcx = qcx.derived_context(from_scope.clone(), qcx.relation_type(relation_expr));
2891
2892    for (table_func, id) in table_funcs.iter() {
2893        table_func_names.insert(
2894            id.clone(),
2895            // TODO(parkmycar): Re-visit after having `FullItemName` use `Ident`s.
2896            Ident::new_unchecked(table_func.name.full_item_name().item.clone()),
2897        );
2898    }
2899    // If there's only a single table function, we can skip generating
2900    // ordinality columns.
2901    if table_funcs.len() == 1 {
2902        let (table_func, id) = table_funcs.iter().next().unwrap();
2903        let (expr, mut scope) =
2904            plan_solitary_table_function(&rows_from_qcx, table_func, None, false)?;
2905
2906        // A single table-function might return several columns as a record
2907        let num_cols = scope.len();
2908        for i in 0..scope.len() {
2909            scope.items[i].table_name = Some(PartialItemName {
2910                database: None,
2911                schema: None,
2912                item: id.clone(),
2913            });
2914            scope.items[i].from_single_column_function = num_cols == 1;
2915            scope.items[i].allow_unqualified_references = false;
2916        }
2917        return Ok((expr, scope));
2918    }
2919    if table_funcs.keys().any(is_repeat_row) {
2920        // Note: Would be also caught by WITH ORDINALITY checking for `repeat_row`, but then the
2921        // error message would be misleading, because it would refer to WITH ORDINALITY.
2922        bail_unsupported!(format!(
2923            "{} in a SELECT clause with multiple table functions",
2924            REPEAT_ROW_NAME
2925        ));
2926    }
2927    // Otherwise, plan as usual, emulating the ROWS FROM behavior
2928    let (expr, mut scope, num_cols) =
2929        plan_rows_from_internal(&rows_from_qcx, table_funcs.keys(), None)?;
2930
2931    // Munge the scope so table names match with the generated ids.
2932    let mut i = 0;
2933    for (id, num_cols) in table_funcs.values().zip_eq(num_cols) {
2934        for _ in 0..num_cols {
2935            scope.items[i].table_name = Some(PartialItemName {
2936                database: None,
2937                schema: None,
2938                item: id.clone(),
2939            });
2940            scope.items[i].from_single_column_function = num_cols == 1;
2941            scope.items[i].allow_unqualified_references = false;
2942            i += 1;
2943        }
2944        // Ordinality column. This doubles as the
2945        // `is_exists_column_for_a_table_function_that_was_in_the_target_list` later on
2946        // because it only needs to be NULL or not.
2947        scope.items[i].table_name = Some(PartialItemName {
2948            database: None,
2949            schema: None,
2950            item: id.clone(),
2951        });
2952        scope.items[i].is_exists_column_for_a_table_function_that_was_in_the_target_list = true;
2953        scope.items[i].allow_unqualified_references = false;
2954        i += 1;
2955    }
2956    // Coalesced ordinality column.
2957    scope.items[i].allow_unqualified_references = false;
2958    Ok((expr, scope))
2959}
2960
2961/// Plans an expression in a `GROUP BY` clause.
2962///
2963/// For historical reasons, PostgreSQL allows `GROUP BY` expressions to refer to
2964/// names/expressions defined in the `SELECT` clause. These special cases are
2965/// handled by this function; see comments within the implementation for
2966/// details.
2967fn plan_group_by_expr<'a>(
2968    ecx: &ExprContext,
2969    group_expr: &'a Expr<Aug>,
2970    projection: &'a [(ExpandedSelectItem, ColumnName)],
2971) -> Result<(Option<&'a Expr<Aug>>, HirScalarExpr), PlanError> {
2972    let plan_projection = |column: usize| match &projection[column].0 {
2973        ExpandedSelectItem::InputOrdinal(column) => Ok((None, HirScalarExpr::column(*column))),
2974        ExpandedSelectItem::Expr(expr) => {
2975            Ok((Some(expr.as_ref()), plan_expr(ecx, expr)?.type_as_any(ecx)?))
2976        }
2977    };
2978
2979    // Check if the expression is a numeric literal, as in `GROUP BY 1`. This is
2980    // a special case that means to use the ith item in the SELECT clause.
2981    if let Some(column) = check_col_index(ecx.name, group_expr, projection.len())? {
2982        return plan_projection(column);
2983    }
2984
2985    // Check if the expression is a simple identifier, as in `GROUP BY foo`.
2986    // The `foo` can refer to *either* an input column or an output column. If
2987    // both exist, the input column is preferred.
2988    match group_expr {
2989        Expr::Identifier(names) => match plan_identifier(ecx, names) {
2990            Err(PlanError::UnknownColumn {
2991                table: None,
2992                column,
2993                similar,
2994            }) => {
2995                // The expression was a simple identifier that did not match an
2996                // input column. See if it matches an output column.
2997                let mut iter = projection.iter().map(|(_expr, name)| name);
2998                if let Some(i) = iter.position(|n| *n == column) {
2999                    if iter.any(|n| *n == column) {
3000                        Err(PlanError::AmbiguousColumn(column))
3001                    } else {
3002                        plan_projection(i)
3003                    }
3004                } else {
3005                    // The name didn't match an output column either. Return the
3006                    // "unknown column" error.
3007                    Err(PlanError::UnknownColumn {
3008                        table: None,
3009                        column,
3010                        similar,
3011                    })
3012                }
3013            }
3014            res => Ok((Some(group_expr), res?)),
3015        },
3016        _ => Ok((
3017            Some(group_expr),
3018            plan_expr(ecx, group_expr)?.type_as_any(ecx)?,
3019        )),
3020    }
3021}
3022
3023/// Plans a slice of `ORDER BY` expressions.
3024///
3025/// See `plan_order_by_or_distinct_expr` for details on the `output_columns`
3026/// parameter.
3027///
3028/// Returns the determined column orderings and a list of scalar expressions
3029/// that must be mapped onto the underlying relation expression.
3030pub(crate) fn plan_order_by_exprs(
3031    ecx: &ExprContext,
3032    order_by_exprs: &[OrderByExpr<Aug>],
3033    output_columns: &[(usize, &ColumnName)],
3034) -> Result<(Vec<ColumnOrder>, Vec<HirScalarExpr>), PlanError> {
3035    let mut order_by = vec![];
3036    let mut map_exprs = vec![];
3037    for obe in order_by_exprs {
3038        let expr = plan_order_by_or_distinct_expr(ecx, &obe.expr, output_columns)?;
3039        // If the expression is a reference to an existing column,
3040        // do not introduce a new column to support it.
3041        let column = match expr {
3042            HirScalarExpr::Column(ColumnRef { level: 0, column }, _name) => column,
3043            _ => {
3044                map_exprs.push(expr);
3045                ecx.relation_type.arity() + map_exprs.len() - 1
3046            }
3047        };
3048        order_by.push(resolve_desc_and_nulls_last(obe, column));
3049    }
3050    Ok((order_by, map_exprs))
3051}
3052
3053/// Plans an expression that appears in an `ORDER BY` or `DISTINCT ON` clause.
3054///
3055/// The `output_columns` parameter describes, in order, the physical index and
3056/// name of each expression in the `SELECT` list. For example, `[(3, "a")]`
3057/// corresponds to a `SELECT` list with a single entry named "a" that can be
3058/// found at index 3 in the underlying relation expression.
3059///
3060/// There are three cases to handle.
3061///
3062///    1. A simple numeric literal, as in `ORDER BY 1`. This is an ordinal
3063///       reference to the specified output column.
3064///    2. An unqualified identifier, as in `ORDER BY a`. This is a reference to
3065///       an output column, if it exists; otherwise it is a reference to an
3066///       input column.
3067///    3. An arbitrary expression, as in `ORDER BY -a`. Column references in
3068///       arbitrary expressions exclusively refer to input columns, never output
3069///       columns.
3070fn plan_order_by_or_distinct_expr(
3071    ecx: &ExprContext,
3072    expr: &Expr<Aug>,
3073    output_columns: &[(usize, &ColumnName)],
3074) -> Result<HirScalarExpr, PlanError> {
3075    if let Some(i) = check_col_index(ecx.name, expr, output_columns.len())? {
3076        return Ok(HirScalarExpr::column(output_columns[i].0));
3077    }
3078
3079    if let Expr::Identifier(names) = expr {
3080        if let [name] = &names[..] {
3081            let name = normalize::column_name(name.clone());
3082            let mut iter = output_columns.iter().filter(|(_, n)| **n == name);
3083            if let Some((i, _)) = iter.next() {
3084                match iter.next() {
3085                    // Per SQL92, names are not considered ambiguous if they
3086                    // refer to identical target list expressions, as in
3087                    // `SELECT a + 1 AS foo, a + 1 AS foo ... ORDER BY foo`.
3088                    Some((i2, _)) if i != i2 => return Err(PlanError::AmbiguousColumn(name)),
3089                    _ => return Ok(HirScalarExpr::column(*i)),
3090                }
3091            }
3092        }
3093    }
3094
3095    plan_expr(ecx, expr)?.type_as_any(ecx)
3096}
3097
3098fn plan_table_with_joins(
3099    qcx: &QueryContext,
3100    table_with_joins: &TableWithJoins<Aug>,
3101) -> Result<(HirRelationExpr, Scope), PlanError> {
3102    let (mut expr, mut scope) = plan_table_factor(qcx, &table_with_joins.relation)?;
3103    for join in &table_with_joins.joins {
3104        let (new_expr, new_scope) = plan_join(qcx, expr, scope, join)?;
3105        expr = new_expr;
3106        scope = new_scope;
3107    }
3108    Ok((expr, scope))
3109}
3110
3111fn plan_table_factor(
3112    qcx: &QueryContext,
3113    table_factor: &TableFactor<Aug>,
3114) -> Result<(HirRelationExpr, Scope), PlanError> {
3115    match table_factor {
3116        TableFactor::Table { name, alias } => {
3117            let (expr, scope) = qcx.resolve_table_name(name.clone())?;
3118            let scope = plan_table_alias(scope, alias.as_ref())?;
3119            Ok((expr, scope))
3120        }
3121
3122        TableFactor::Function {
3123            function,
3124            alias,
3125            with_ordinality,
3126        } => plan_solitary_table_function(qcx, function, alias.as_ref(), *with_ordinality),
3127
3128        TableFactor::RowsFrom {
3129            functions,
3130            alias,
3131            with_ordinality,
3132        } => plan_rows_from(qcx, functions, alias.as_ref(), *with_ordinality),
3133
3134        TableFactor::Derived {
3135            lateral,
3136            subquery,
3137            alias,
3138        } => {
3139            let mut qcx = (*qcx).clone();
3140            if !lateral {
3141                // Since this derived table was not marked as `LATERAL`,
3142                // make elements in outer scopes invisible until we reach the
3143                // next lateral barrier.
3144                for scope in &mut qcx.outer_scopes {
3145                    if scope.lateral_barrier {
3146                        break;
3147                    }
3148                    scope.items.clear();
3149                }
3150            }
3151            qcx.outer_scopes[0].lateral_barrier = true;
3152            let (expr, scope) = plan_nested_query(&mut qcx, subquery)?;
3153            let scope = plan_table_alias(scope, alias.as_ref())?;
3154            Ok((expr, scope))
3155        }
3156
3157        TableFactor::NestedJoin { join, alias } => {
3158            let (expr, scope) = plan_table_with_joins(qcx, join)?;
3159            let scope = plan_table_alias(scope, alias.as_ref())?;
3160            Ok((expr, scope))
3161        }
3162    }
3163}
3164
3165/// Plans a `ROWS FROM` expression.
3166///
3167/// `ROWS FROM` concatenates table functions into a single table, filling in
3168/// `NULL`s in places where one table function has fewer rows than another. We
3169/// can achieve this by augmenting each table function with a row number, doing
3170/// a `FULL JOIN` between each table function on the row number and eventually
3171/// projecting away the row number columns. Concretely, the following query
3172/// using `ROWS FROM`
3173///
3174/// ```sql
3175/// SELECT
3176///     *
3177/// FROM
3178///     ROWS FROM (
3179///         generate_series(1, 2),
3180///         information_schema._pg_expandarray(ARRAY[9]),
3181///         generate_series(3, 6)
3182///     );
3183/// ```
3184///
3185/// is equivalent to the following query that does not use `ROWS FROM`:
3186///
3187/// ```sql
3188/// SELECT
3189///     gs1.generate_series, expand.x, expand.n, gs2.generate_series
3190/// FROM
3191///     generate_series(1, 2) WITH ORDINALITY AS gs1
3192///     FULL JOIN information_schema._pg_expandarray(ARRAY[9]) WITH ORDINALITY AS expand
3193///         ON gs1.ordinality = expand.ordinality
3194///     FULL JOIN generate_series(3, 6) WITH ORDINALITY AS gs3
3195///         ON coalesce(gs1.ordinality, expand.ordinality) = gs3.ordinality;
3196/// ```
3197///
3198/// Note the call to `coalesce` in the last join condition, which ensures that
3199/// `gs3` will align with whichever of `gs1` or `expand` has more rows.
3200///
3201/// This function creates a HirRelationExpr that follows the structure of the
3202/// latter query.
3203///
3204/// `with_ordinality` can be used to have the output expression contain a
3205/// single coalesced ordinality column at the end of the entire expression.
3206fn plan_rows_from(
3207    qcx: &QueryContext,
3208    functions: &[Function<Aug>],
3209    alias: Option<&TableAlias>,
3210    with_ordinality: bool,
3211) -> Result<(HirRelationExpr, Scope), PlanError> {
3212    // The `repeat_row` function is not supported in ROWS FROM.
3213    if functions.iter().any(is_repeat_row) {
3214        // Note: Would be also caught by WITH ORDINALITY checking for `repeat_row`, but then the
3215        // error message would be misleading, because it would refer to WITH ORDINALITY instead of
3216        // ROWS FROM.
3217        bail_unsupported!(format!("{} in ROWS FROM", REPEAT_ROW_NAME));
3218    }
3219
3220    // If there's only a single table function, planning proceeds as if `ROWS
3221    // FROM` hadn't been written at all.
3222    if let [function] = functions {
3223        return plan_solitary_table_function(qcx, function, alias, with_ordinality);
3224    }
3225
3226    // Per PostgreSQL, all scope items take the name of the first function
3227    // (unless aliased).
3228    // See: https://github.com/postgres/postgres/blob/639a86e36/src/backend/parser/parse_relation.c#L1701-L1705
3229    let (expr, mut scope, num_cols) = plan_rows_from_internal(
3230        qcx,
3231        functions,
3232        Some(functions[0].name.full_item_name().clone()),
3233    )?;
3234
3235    // Columns tracks the set of columns we will keep in the projection.
3236    let mut columns = Vec::new();
3237    let mut offset = 0;
3238    // Retain table function's non-ordinality columns.
3239    for (idx, cols) in num_cols.into_iter().enumerate() {
3240        for i in 0..cols {
3241            columns.push(offset + i);
3242        }
3243        offset += cols + 1;
3244
3245        // Remove the ordinality column from the scope, accounting for previous scope
3246        // changes from this loop.
3247        scope.items.remove(offset - idx - 1);
3248    }
3249
3250    // If `WITH ORDINALITY` was specified, include the coalesced ordinality
3251    // column. Otherwise remove it from the scope.
3252    if with_ordinality {
3253        columns.push(offset);
3254    } else {
3255        scope.items.pop();
3256    }
3257
3258    let expr = expr.project(columns);
3259
3260    let scope = plan_table_alias(scope, alias)?;
3261    Ok((expr, scope))
3262}
3263
3264fn is_repeat_row(f: &Function<Aug>) -> bool {
3265    f.name.full_name_str().as_str() == format!("{}.{}", MZ_CATALOG_SCHEMA, REPEAT_ROW_NAME)
3266}
3267
3268/// Plans an expression coalescing multiple table functions. Each table
3269/// function is followed by its row ordinality. The entire expression is
3270/// followed by the coalesced row ordinality.
3271///
3272/// The returned Scope will set all item's table_name's to the `table_name`
3273/// parameter if it is `Some`. If `None`, they will be the name of each table
3274/// function.
3275///
3276/// The returned `Vec<usize>` is the number of (non-ordinality) columns from
3277/// each table function.
3278///
3279/// For example, with table functions tf1 returning 1 column (a) and tf2
3280/// returning 2 columns (b, c), this function will return an expr 6 columns:
3281///
3282/// - tf1.a
3283/// - tf1.ordinality
3284/// - tf2.b
3285/// - tf2.c
3286/// - tf2.ordinality
3287/// - coalesced_ordinality
3288///
3289/// And a `Vec<usize>` of `[1, 2]`.
3290fn plan_rows_from_internal<'a>(
3291    qcx: &QueryContext,
3292    functions: impl IntoIterator<Item = &'a Function<Aug>>,
3293    table_name: Option<FullItemName>,
3294) -> Result<(HirRelationExpr, Scope, Vec<usize>), PlanError> {
3295    let mut functions = functions.into_iter();
3296    let mut num_cols = Vec::new();
3297
3298    // Join together each of the table functions in turn. The last column is
3299    // always the column to join against and is maintained to be the coalescence
3300    // of the row number column for all prior functions.
3301    let (mut left_expr, mut left_scope) =
3302        plan_table_function_internal(qcx, functions.next().unwrap(), true, table_name.clone())?;
3303    num_cols.push(left_scope.len() - 1);
3304    // Create the coalesced ordinality column.
3305    left_expr = left_expr.map(vec![HirScalarExpr::column(left_scope.len() - 1)]);
3306    left_scope
3307        .items
3308        .push(ScopeItem::from_column_name(ORDINALITY_COL_NAME));
3309
3310    for function in functions {
3311        // The right hand side of a join must be planned in a new scope.
3312        let qcx = qcx.empty_derived_context();
3313        let (right_expr, mut right_scope) =
3314            plan_table_function_internal(&qcx, function, true, table_name.clone())?;
3315        num_cols.push(right_scope.len() - 1);
3316        let left_col = left_scope.len() - 1;
3317        let right_col = left_scope.len() + right_scope.len() - 1;
3318        let on = HirScalarExpr::call_binary(
3319            HirScalarExpr::column(left_col),
3320            HirScalarExpr::column(right_col),
3321            expr_func::Eq,
3322        );
3323        left_expr = left_expr
3324            .join(right_expr, on, JoinKind::FullOuter)
3325            .map(vec![HirScalarExpr::call_variadic(
3326                Coalesce,
3327                vec![
3328                    HirScalarExpr::column(left_col),
3329                    HirScalarExpr::column(right_col),
3330                ],
3331            )]);
3332
3333        // Project off the previous iteration's coalesced column, but keep both of this
3334        // iteration's ordinality columns.
3335        left_expr = left_expr.project(
3336            (0..left_col) // non-coalesced ordinality columns from left function
3337                .chain(left_col + 1..right_col + 2) // non-ordinality columns from right function
3338                .collect(),
3339        );
3340        // Move the coalesced ordinality column.
3341        right_scope.items.push(left_scope.items.pop().unwrap());
3342
3343        left_scope.items.extend(right_scope.items);
3344    }
3345
3346    Ok((left_expr, left_scope, num_cols))
3347}
3348
3349/// Plans a table function that appears alone, i.e., that is not part of a `ROWS
3350/// FROM` clause that contains other table functions. Special aliasing rules
3351/// apply.
3352fn plan_solitary_table_function(
3353    qcx: &QueryContext,
3354    function: &Function<Aug>,
3355    alias: Option<&TableAlias>,
3356    with_ordinality: bool,
3357) -> Result<(HirRelationExpr, Scope), PlanError> {
3358    let (expr, mut scope) = plan_table_function_internal(qcx, function, with_ordinality, None)?;
3359
3360    let single_column_function = scope.len() == 1 + if with_ordinality { 1 } else { 0 };
3361    if single_column_function {
3362        let item = &mut scope.items[0];
3363
3364        // Mark that the function only produced a single column. This impacts
3365        // whole-row references.
3366        item.from_single_column_function = true;
3367
3368        // Strange special case for solitary table functions that output one
3369        // column whose name matches the name of the table function. If a table
3370        // alias is provided, the column name is changed to the table alias's
3371        // name. Concretely, the following query returns a column named `x`
3372        // rather than a column named `generate_series`:
3373        //
3374        //     SELECT * FROM generate_series(1, 5) AS x
3375        //
3376        // Note that this case does not apply to e.g. `jsonb_array_elements`,
3377        // since its output column is explicitly named `value`, not
3378        // `jsonb_array_elements`.
3379        //
3380        // Note also that we may (correctly) change the column name again when
3381        // we plan the table alias below if the `alias.columns` is non-empty.
3382        if let Some(alias) = alias {
3383            if let ScopeItem {
3384                table_name: Some(table_name),
3385                column_name,
3386                ..
3387            } = item
3388            {
3389                if table_name.item.as_str() == column_name.as_str() {
3390                    *column_name = normalize::column_name(alias.name.clone());
3391                }
3392            }
3393        }
3394    }
3395
3396    let scope = plan_table_alias(scope, alias)?;
3397    Ok((expr, scope))
3398}
3399
3400/// Plans a table function.
3401///
3402/// You generally should call `plan_rows_from` or `plan_solitary_table_function`
3403/// instead to get the appropriate aliasing behavior.
3404fn plan_table_function_internal(
3405    qcx: &QueryContext,
3406    Function {
3407        name,
3408        args,
3409        filter,
3410        over,
3411        distinct,
3412    }: &Function<Aug>,
3413    with_ordinality: bool,
3414    table_name: Option<FullItemName>,
3415) -> Result<(HirRelationExpr, Scope), PlanError> {
3416    // The parser rejects FILTER, OVER, and DISTINCT in every table function
3417    // position (`FROM f(...)`, `ROWS FROM (...)`), and table functions in
3418    // scalar position are only lifted into a `FROM` clause when all three are
3419    // absent, so these are defensive.
3420    if filter.is_some() {
3421        sql_bail!("FILTER is not allowed for table functions in FROM");
3422    }
3423    if over.is_some() {
3424        sql_bail!("OVER is not allowed for table functions in FROM");
3425    }
3426    if *distinct {
3427        sql_bail!("DISTINCT is not allowed for table functions in FROM");
3428    }
3429
3430    let ecx = &ExprContext {
3431        qcx,
3432        name: "table function arguments",
3433        scope: &Scope::empty(),
3434        relation_type: &SqlRelationType::empty(),
3435        allow_aggregates: false,
3436        allow_subqueries: true,
3437        allow_parameters: true,
3438        allow_windows: false,
3439    };
3440
3441    let scalar_args = match args {
3442        FunctionArgs::Star => sql_bail!("{} does not accept * as an argument", name),
3443        FunctionArgs::Args { args, order_by } => {
3444            if !order_by.is_empty() {
3445                sql_bail!(
3446                    "ORDER BY specified, but {} is not an aggregate function",
3447                    name
3448                );
3449            }
3450            plan_exprs(ecx, args)?
3451        }
3452    };
3453
3454    let table_name = match table_name {
3455        Some(table_name) => table_name.item,
3456        None => name.full_item_name().item.clone(),
3457    };
3458
3459    let scope_name = Some(PartialItemName {
3460        database: None,
3461        schema: None,
3462        item: table_name,
3463    });
3464
3465    let (expr, mut scope) = match resolve_func(ecx, name, args)? {
3466        Func::Table(impls) => {
3467            let tf = func::select_impl(ecx, FuncSpec::Func(name), impls, scalar_args, vec![])?;
3468            let scope = Scope::from_source(scope_name.clone(), tf.column_names);
3469            let expr = match tf.imp {
3470                TableFuncImpl::CallTable { mut func, exprs } => {
3471                    if with_ordinality {
3472                        func = TableFunc::with_ordinality(func.clone()).ok_or(
3473                            PlanError::Unsupported {
3474                                feature: format!("WITH ORDINALITY on {}", func),
3475                                discussion_no: None,
3476                            },
3477                        )?;
3478                    }
3479                    HirRelationExpr::CallTable { func, exprs }
3480                }
3481                TableFuncImpl::Expr(expr) => {
3482                    if !with_ordinality {
3483                        expr
3484                    } else {
3485                        // The table function is defined by a SQL query (i.e., TableFuncImpl::Expr),
3486                        // so we can't use the new `WITH ORDINALITY` implementation. We can fall
3487                        // back to the legacy implementation or error out the query.
3488                        if qcx
3489                            .scx
3490                            .is_feature_flag_enabled(&ENABLE_WITH_ORDINALITY_LEGACY_FALLBACK)
3491                        {
3492                            // Note that this can give an incorrect ordering, and also has an extreme
3493                            // performance problem in some cases. See the doc comment of
3494                            // `TableFuncImpl`.
3495                            tracing::error!(
3496                                %name,
3497                                "Using the legacy WITH ORDINALITY / ROWS FROM implementation for a table function",
3498                            );
3499                            expr.map(vec![HirScalarExpr::windowing(WindowExpr {
3500                                func: WindowExprType::Scalar(ScalarWindowExpr {
3501                                    func: ScalarWindowFunc::RowNumber,
3502                                    order_by: vec![],
3503                                }),
3504                                partition_by: vec![],
3505                                order_by: vec![],
3506                            })])
3507                        } else {
3508                            bail_unsupported!(format!(
3509                                "WITH ORDINALITY or ROWS FROM with {}",
3510                                name
3511                            ));
3512                        }
3513                    }
3514                }
3515            };
3516            (expr, scope)
3517        }
3518        Func::Scalar(impls) => {
3519            let expr = func::select_impl(ecx, FuncSpec::Func(name), impls, scalar_args, vec![])?;
3520            let output = expr.typ(
3521                &qcx.outer_relation_types,
3522                &SqlRelationType::new(vec![]),
3523                &qcx.scx.param_types.borrow(),
3524            );
3525
3526            let relation = SqlRelationType::new(vec![output]);
3527
3528            let function_ident = Ident::new(name.full_item_name().item.clone())?;
3529            let column_name = normalize::column_name(function_ident);
3530            let name = column_name.to_string();
3531
3532            let scope = Scope::from_source(scope_name.clone(), vec![column_name]);
3533
3534            let mut func = TableFunc::TabletizedScalar { relation, name };
3535            if with_ordinality {
3536                func = TableFunc::with_ordinality(func.clone()).ok_or(PlanError::Unsupported {
3537                    feature: format!("WITH ORDINALITY on {}", func),
3538                    discussion_no: None,
3539                })?;
3540            }
3541            (
3542                HirRelationExpr::CallTable {
3543                    func,
3544                    exprs: vec![expr],
3545                },
3546                scope,
3547            )
3548        }
3549        o => sql_bail!(
3550            "{} functions are not supported in functions in FROM",
3551            o.class()
3552        ),
3553    };
3554
3555    if with_ordinality {
3556        scope
3557            .items
3558            .push(ScopeItem::from_name(scope_name, "ordinality"));
3559    }
3560
3561    Ok((expr, scope))
3562}
3563
3564fn plan_table_alias(mut scope: Scope, alias: Option<&TableAlias>) -> Result<Scope, PlanError> {
3565    if let Some(TableAlias {
3566        name,
3567        columns,
3568        strict,
3569    }) = alias
3570    {
3571        if (columns.len() > scope.items.len()) || (*strict && columns.len() != scope.items.len()) {
3572            sql_bail!(
3573                "{} has {} columns available but {} columns specified",
3574                name,
3575                scope.items.len(),
3576                columns.len()
3577            );
3578        }
3579
3580        let table_name = normalize::ident(name.to_owned());
3581        for (i, item) in scope.items.iter_mut().enumerate() {
3582            item.table_name = if item.allow_unqualified_references {
3583                Some(PartialItemName {
3584                    database: None,
3585                    schema: None,
3586                    item: table_name.clone(),
3587                })
3588            } else {
3589                // Columns that prohibit unqualified references are special
3590                // columns from the output of a NATURAL or USING join that can
3591                // only be referenced by their full, pre-join name. Applying an
3592                // alias to the output of that join renders those columns
3593                // inaccessible, which we accomplish here by setting the
3594                // table name to `None`.
3595                //
3596                // Concretely, consider:
3597                //
3598                //      CREATE TABLE t1 (a int);
3599                //      CREATE TABLE t2 (a int);
3600                //  (1) SELECT ... FROM (t1 NATURAL JOIN t2);
3601                //  (2) SELECT ... FROM (t1 NATURAL JOIN t2) AS t;
3602                //
3603                // In (1), the join has no alias. The underlying columns from
3604                // either side of the join can be referenced as `t1.a` and
3605                // `t2.a`, respectively, and the unqualified name `a` refers to
3606                // a column whose value is `coalesce(t1.a, t2.a)`.
3607                //
3608                // In (2), the join is aliased as `t`. The columns from either
3609                // side of the join (`t1.a` and `t2.a`) are inaccessible, and
3610                // the coalesced column can be named as either `a` or `t.a`.
3611                //
3612                // We previously had a bug [0] that mishandled this subtle
3613                // logic.
3614                //
3615                // NOTE(benesch): We could in theory choose to project away
3616                // those inaccessible columns and drop them from the scope
3617                // entirely, but that would require that this function also
3618                // take and return the `HirRelationExpr` that is being aliased,
3619                // which is a rather large refactor.
3620                //
3621                // [0]: https://github.com/MaterializeInc/database-issues/issues/4887
3622                None
3623            };
3624            item.column_name = columns
3625                .get(i)
3626                .map(|a| normalize::column_name(a.clone()))
3627                .unwrap_or_else(|| item.column_name.clone());
3628        }
3629    }
3630    Ok(scope)
3631}
3632
3633// `table_func_names` is a mapping from a UUID to the original function
3634// name. The UUIDs are identifiers that have been rewritten from some table
3635// function expression, and this mapping restores the original names.
3636fn invent_column_name(
3637    ecx: &ExprContext,
3638    expr: &Expr<Aug>,
3639    table_func_names: &BTreeMap<String, Ident>,
3640) -> Result<Option<ColumnName>, PlanError> {
3641    // We follow PostgreSQL exactly here, which has some complicated rules
3642    // around "high" and "low" quality names. Low quality names override other
3643    // low quality names but not high quality names.
3644    //
3645    // See: https://github.com/postgres/postgres/blob/1f655fdc3/src/backend/parser/parse_target.c#L1716-L1728
3646
3647    #[derive(Debug)]
3648    enum NameQuality {
3649        Low,
3650        High,
3651    }
3652
3653    fn invent(
3654        ecx: &ExprContext,
3655        expr: &Expr<Aug>,
3656        table_func_names: &BTreeMap<String, Ident>,
3657    ) -> Result<Option<(ColumnName, NameQuality)>, PlanError> {
3658        Ok(match expr {
3659            Expr::Identifier(names) => {
3660                if let [name] = names.as_slice() {
3661                    if let Some(table_func_name) = table_func_names.get(name.as_str()) {
3662                        return Ok(Some((
3663                            normalize::column_name(table_func_name.clone()),
3664                            NameQuality::High,
3665                        )));
3666                    }
3667                }
3668                names
3669                    .last()
3670                    .map(|n| (normalize::column_name(n.clone()), NameQuality::High))
3671            }
3672            Expr::Value(v) => match v {
3673                // Per PostgreSQL, `bool` and `interval` literals take on the name
3674                // of their type, but not other literal types.
3675                Value::Boolean(_) => Some(("bool".into(), NameQuality::High)),
3676                Value::Interval(_) => Some(("interval".into(), NameQuality::High)),
3677                _ => None,
3678            },
3679            Expr::Function(func) => {
3680                let (schema, item) = match &func.name {
3681                    ResolvedItemName::Item {
3682                        qualifiers,
3683                        full_name,
3684                        ..
3685                    } => (&qualifiers.schema_spec, full_name.item.clone()),
3686                    // Name resolution should have rejected anything other than
3687                    // `Item` for a function call.
3688                    _ => {
3689                        bail_internal!("function name did not resolve to an item: {:?}", func.name)
3690                    }
3691                };
3692
3693                if schema == &SchemaSpecifier::from(ecx.qcx.scx.catalog.get_mz_internal_schema_id())
3694                    || schema
3695                        == &SchemaSpecifier::from(ecx.qcx.scx.catalog.get_mz_unsafe_schema_id())
3696                {
3697                    None
3698                } else {
3699                    Some((item.into(), NameQuality::High))
3700                }
3701            }
3702            Expr::HomogenizingFunction { function, .. } => Some((
3703                function.to_string().to_lowercase().into(),
3704                NameQuality::High,
3705            )),
3706            Expr::NullIf { .. } => Some(("nullif".into(), NameQuality::High)),
3707            Expr::Array { .. } => Some(("array".into(), NameQuality::High)),
3708            Expr::List { .. } => Some(("list".into(), NameQuality::High)),
3709            Expr::Map { .. } | Expr::MapSubquery(_) => Some(("map".into(), NameQuality::High)),
3710            Expr::Cast {
3711                expr, data_type, ..
3712            } => match invent(ecx, expr, table_func_names)? {
3713                Some((name, NameQuality::High)) => Some((name, NameQuality::High)),
3714                _ => Some((data_type.unqualified_item_name().into(), NameQuality::Low)),
3715            },
3716            Expr::Case { else_result, .. } => {
3717                let inner = match else_result.as_ref() {
3718                    Some(else_result) => invent(ecx, else_result, table_func_names)?,
3719                    None => None,
3720                };
3721                match inner {
3722                    Some((name, NameQuality::High)) => Some((name, NameQuality::High)),
3723                    _ => Some(("case".into(), NameQuality::Low)),
3724                }
3725            }
3726            Expr::FieldAccess { field, .. } => {
3727                Some((normalize::column_name(field.clone()), NameQuality::High))
3728            }
3729            Expr::Exists { .. } => Some(("exists".into(), NameQuality::High)),
3730            Expr::Subscript { expr, .. } => invent(ecx, expr, table_func_names)?,
3731            Expr::Subquery(query) | Expr::ListSubquery(query) | Expr::ArraySubquery(query) => {
3732                // A bit silly to have to plan the query here just to get its column
3733                // name, since we throw away the planned expression, but fixing this
3734                // requires a separate semantic analysis phase.
3735                //
3736                // We deliberately swallow planning errors here: if the subquery
3737                // doesn't plan, we just don't invent a name for it; the real
3738                // planning attempt elsewhere will surface the error.
3739                let Ok((_expr, scope)) = plan_nested_query(&mut ecx.derived_query_context(), query)
3740                else {
3741                    return Ok(None);
3742                };
3743                scope
3744                    .items
3745                    .first()
3746                    .map(|name| (name.column_name.clone(), NameQuality::High))
3747            }
3748            Expr::Row { .. } => Some(("row".into(), NameQuality::High)),
3749            _ => None,
3750        })
3751    }
3752
3753    Ok(invent(ecx, expr, table_func_names)?.map(|(name, _quality)| name))
3754}
3755
3756#[derive(Debug)]
3757enum ExpandedSelectItem<'a> {
3758    InputOrdinal(usize),
3759    Expr(Cow<'a, Expr<Aug>>),
3760}
3761
3762impl ExpandedSelectItem<'_> {
3763    fn as_expr(&self) -> Option<&Expr<Aug>> {
3764        match self {
3765            ExpandedSelectItem::InputOrdinal(_) => None,
3766            ExpandedSelectItem::Expr(expr) => Some(expr),
3767        }
3768    }
3769}
3770
3771fn expand_select_item<'a>(
3772    ecx: &ExprContext,
3773    s: &'a SelectItem<Aug>,
3774    table_func_names: &BTreeMap<String, Ident>,
3775) -> Result<Vec<(ExpandedSelectItem<'a>, ColumnName)>, PlanError> {
3776    match s {
3777        SelectItem::Expr {
3778            expr: Expr::QualifiedWildcard(table_name),
3779            alias: _,
3780        } => {
3781            *ecx.qcx.scx.ambiguous_columns.borrow_mut() = true;
3782            let table_name =
3783                normalize::unresolved_item_name(UnresolvedItemName(table_name.clone()))?;
3784            let out: Vec<_> = ecx
3785                .scope
3786                .items
3787                .iter()
3788                .enumerate()
3789                .filter(|(_i, item)| item.is_from_table(&table_name))
3790                .map(|(i, item)| {
3791                    let name = item.column_name.clone();
3792                    (ExpandedSelectItem::InputOrdinal(i), name)
3793                })
3794                .collect();
3795            if out.is_empty() {
3796                sql_bail!("no table named '{}' in scope", table_name);
3797            }
3798            Ok(out)
3799        }
3800        SelectItem::Expr {
3801            expr: Expr::WildcardAccess(sql_expr),
3802            alias: _,
3803        } => {
3804            *ecx.qcx.scx.ambiguous_columns.borrow_mut() = true;
3805            // A bit silly to have to plan the expression here just to get its
3806            // type, since we throw away the planned expression, but fixing this
3807            // requires a separate semantic analysis phase. Luckily this is an
3808            // uncommon operation and the PostgreSQL docs have a warning that
3809            // this operation is slow in Postgres too.
3810            let expr = plan_expr(ecx, sql_expr)?.type_as_any(ecx)?;
3811            let fields = match ecx.scalar_type(&expr) {
3812                SqlScalarType::Record { fields, .. } => fields,
3813                ty => sql_bail!(
3814                    "type {} is not composite",
3815                    ecx.humanize_sql_scalar_type(&ty, false)
3816                ),
3817            };
3818            let mut skip_cols: BTreeSet<ColumnName> = BTreeSet::new();
3819            if let Expr::Identifier(ident) = sql_expr.as_ref() {
3820                if let [name] = ident.as_slice() {
3821                    if let Ok(items) = ecx.scope.items_from_table(
3822                        &[],
3823                        &PartialItemName {
3824                            database: None,
3825                            schema: None,
3826                            item: name.as_str().to_string(),
3827                        },
3828                    ) {
3829                        for (_, item) in items {
3830                            if item
3831                                .is_exists_column_for_a_table_function_that_was_in_the_target_list
3832                            {
3833                                skip_cols.insert(item.column_name.clone());
3834                            }
3835                        }
3836                    }
3837                }
3838            }
3839            let items = fields
3840                .iter()
3841                .filter_map(|(name, _ty)| {
3842                    if skip_cols.contains(name) {
3843                        None
3844                    } else {
3845                        let item = ExpandedSelectItem::Expr(Cow::Owned(Expr::FieldAccess {
3846                            expr: sql_expr.clone(),
3847                            field: normalize::column_name_ident(name),
3848                        }));
3849                        Some((item, name.clone()))
3850                    }
3851                })
3852                .collect();
3853            Ok(items)
3854        }
3855        SelectItem::Wildcard => {
3856            *ecx.qcx.scx.ambiguous_columns.borrow_mut() = true;
3857            let items: Vec<_> = ecx
3858                .scope
3859                .items
3860                .iter()
3861                .enumerate()
3862                .filter(|(_i, item)| item.allow_unqualified_references)
3863                .map(|(i, item)| {
3864                    let name = item.column_name.clone();
3865                    (ExpandedSelectItem::InputOrdinal(i), name)
3866                })
3867                .collect();
3868
3869            Ok(items)
3870        }
3871        SelectItem::Expr { expr, alias } => {
3872            let name = match alias.clone().map(normalize::column_name) {
3873                Some(name) => name,
3874                None => invent_column_name(ecx, expr, table_func_names)?
3875                    .unwrap_or_else(|| UNKNOWN_COLUMN_NAME.into()),
3876            };
3877            Ok(vec![(ExpandedSelectItem::Expr(Cow::Borrowed(expr)), name)])
3878        }
3879    }
3880}
3881
3882fn plan_join(
3883    left_qcx: &QueryContext,
3884    left: HirRelationExpr,
3885    left_scope: Scope,
3886    join: &Join<Aug>,
3887) -> Result<(HirRelationExpr, Scope), PlanError> {
3888    const ON_TRUE: JoinConstraint<Aug> = JoinConstraint::On(Expr::Value(Value::Boolean(true)));
3889    let (kind, constraint) = match &join.join_operator {
3890        JoinOperator::CrossJoin => (JoinKind::Inner, &ON_TRUE),
3891        JoinOperator::Inner(constraint) => (JoinKind::Inner, constraint),
3892        JoinOperator::LeftOuter(constraint) => (JoinKind::LeftOuter, constraint),
3893        JoinOperator::RightOuter(constraint) => (JoinKind::RightOuter, constraint),
3894        JoinOperator::FullOuter(constraint) => (JoinKind::FullOuter, constraint),
3895    };
3896
3897    let mut right_qcx = left_qcx.derived_context(left_scope.clone(), left_qcx.relation_type(&left));
3898    if !kind.can_be_correlated() {
3899        for item in &mut right_qcx.outer_scopes[0].items {
3900            // Per PostgreSQL (and apparently SQL:2008), we can't simply remove
3901            // these items from scope. These items need to *exist* because they
3902            // might shadow variables in outer scopes that would otherwise be
3903            // valid to reference, but accessing them needs to produce an error.
3904            item.error_if_referenced =
3905                Some(|table, column| PlanError::WrongJoinTypeForLateralColumn {
3906                    table: table.cloned(),
3907                    column: column.clone(),
3908                });
3909        }
3910    }
3911    let (right, right_scope) = plan_table_factor(&right_qcx, &join.relation)?;
3912
3913    let (expr, scope) = match constraint {
3914        JoinConstraint::On(expr) => {
3915            let product_scope = left_scope.product(right_scope)?;
3916            let ecx = &ExprContext {
3917                qcx: left_qcx,
3918                name: "ON clause",
3919                scope: &product_scope,
3920                relation_type: &SqlRelationType::new(
3921                    left_qcx
3922                        .relation_type(&left)
3923                        .column_types
3924                        .into_iter()
3925                        .chain(right_qcx.relation_type(&right).column_types)
3926                        .collect(),
3927                ),
3928                allow_aggregates: false,
3929                allow_subqueries: true,
3930                allow_parameters: true,
3931                allow_windows: false,
3932            };
3933            let on = plan_expr(ecx, expr)?.type_as(ecx, &SqlScalarType::Bool)?;
3934            let joined = left.join(right, on, kind);
3935            (joined, product_scope)
3936        }
3937        JoinConstraint::Using { columns, alias } => {
3938            let column_names = columns
3939                .iter()
3940                .map(|ident| normalize::column_name(ident.clone()))
3941                .collect::<Vec<_>>();
3942
3943            plan_using_constraint(
3944                &column_names,
3945                left_qcx,
3946                left,
3947                left_scope,
3948                &right_qcx,
3949                right,
3950                right_scope,
3951                kind,
3952                alias.as_ref(),
3953            )?
3954        }
3955        JoinConstraint::Natural => {
3956            // We shouldn't need to set ambiguous_columns on both the right and left qcx since they
3957            // have the same scx. However, it doesn't hurt to be safe.
3958            *left_qcx.scx.ambiguous_columns.borrow_mut() = true;
3959            *right_qcx.scx.ambiguous_columns.borrow_mut() = true;
3960            let left_column_names = left_scope.column_names();
3961            let right_column_names: BTreeSet<_> = right_scope.column_names().collect();
3962            let column_names: Vec<_> = left_column_names
3963                .filter(|col| right_column_names.contains(col))
3964                .cloned()
3965                .collect();
3966            plan_using_constraint(
3967                &column_names,
3968                left_qcx,
3969                left,
3970                left_scope,
3971                &right_qcx,
3972                right,
3973                right_scope,
3974                kind,
3975                None,
3976            )?
3977        }
3978    };
3979    Ok((expr, scope))
3980}
3981
3982// See page 440 of ANSI SQL 2016 spec for details on scoping of using/natural joins
3983#[allow(clippy::too_many_arguments)]
3984fn plan_using_constraint(
3985    column_names: &[ColumnName],
3986    left_qcx: &QueryContext,
3987    left: HirRelationExpr,
3988    left_scope: Scope,
3989    right_qcx: &QueryContext,
3990    right: HirRelationExpr,
3991    right_scope: Scope,
3992    kind: JoinKind,
3993    alias: Option<&Ident>,
3994) -> Result<(HirRelationExpr, Scope), PlanError> {
3995    let mut both_scope = left_scope.clone().product(right_scope.clone())?;
3996
3997    // Cargo culting PG here; no discernable reason this must fail, but PG does
3998    // so we do, as well.
3999    let mut unique_column_names = BTreeSet::new();
4000    for c in column_names {
4001        if !unique_column_names.insert(c) {
4002            return Err(PlanError::Unsupported {
4003                feature: format!(
4004                    "column name {} appears more than once in USING clause",
4005                    c.quoted()
4006                ),
4007                discussion_no: None,
4008            });
4009        }
4010    }
4011
4012    let alias_item_name = alias.map(|alias| PartialItemName {
4013        database: None,
4014        schema: None,
4015        item: alias.clone().to_string(),
4016    });
4017
4018    if let Some(alias_item_name) = &alias_item_name {
4019        for partial_item_name in both_scope.table_names() {
4020            if partial_item_name.matches(alias_item_name) {
4021                sql_bail!(
4022                    "table name \"{}\" specified more than once",
4023                    alias_item_name
4024                )
4025            }
4026        }
4027    }
4028
4029    let ecx = &ExprContext {
4030        qcx: right_qcx,
4031        name: "USING clause",
4032        scope: &both_scope,
4033        relation_type: &SqlRelationType::new(
4034            left_qcx
4035                .relation_type(&left)
4036                .column_types
4037                .into_iter()
4038                .chain(right_qcx.relation_type(&right).column_types)
4039                .collect(),
4040        ),
4041        allow_aggregates: false,
4042        allow_subqueries: false,
4043        allow_parameters: false,
4044        allow_windows: false,
4045    };
4046
4047    let mut join_exprs = vec![];
4048    let mut map_exprs = vec![];
4049    let mut new_items = vec![];
4050    let mut join_cols = vec![];
4051    let mut hidden_cols = vec![];
4052
4053    for column_name in column_names {
4054        // the two sides will have different names (e.g., `t1.a` and `t2.a`)
4055        let (lhs, lhs_name) = left_scope.resolve_using_column(
4056            column_name,
4057            JoinSide::Left,
4058            &mut left_qcx.name_manager.borrow_mut(),
4059        )?;
4060        let (mut rhs, rhs_name) = right_scope.resolve_using_column(
4061            column_name,
4062            JoinSide::Right,
4063            &mut right_qcx.name_manager.borrow_mut(),
4064        )?;
4065
4066        // Adjust the RHS reference to its post-join location.
4067        rhs.column += left_scope.len();
4068
4069        // Join keys must be resolved to same type.
4070        let mut exprs = coerce_homogeneous_exprs(
4071            &ecx.with_name(&format!(
4072                "NATURAL/USING join column {}",
4073                column_name.quoted()
4074            )),
4075            vec![
4076                CoercibleScalarExpr::Coerced(HirScalarExpr::named_column(
4077                    lhs,
4078                    Arc::clone(&lhs_name),
4079                )),
4080                CoercibleScalarExpr::Coerced(HirScalarExpr::named_column(
4081                    rhs,
4082                    Arc::clone(&rhs_name),
4083                )),
4084            ],
4085            None,
4086        )?;
4087        let (expr1, expr2) = (exprs.remove(0), exprs.remove(0));
4088
4089        match kind {
4090            JoinKind::LeftOuter { .. } | JoinKind::Inner { .. } => {
4091                join_cols.push(lhs.column);
4092                hidden_cols.push(rhs.column);
4093            }
4094            JoinKind::RightOuter => {
4095                join_cols.push(rhs.column);
4096                hidden_cols.push(lhs.column);
4097            }
4098            JoinKind::FullOuter => {
4099                // Create a new column that will be the coalesced value of left
4100                // and right.
4101                join_cols.push(both_scope.items.len() + map_exprs.len());
4102                hidden_cols.push(lhs.column);
4103                hidden_cols.push(rhs.column);
4104                map_exprs.push(HirScalarExpr::call_variadic(
4105                    Coalesce,
4106                    vec![expr1.clone(), expr2.clone()],
4107                ));
4108                new_items.push(ScopeItem::from_column_name(column_name));
4109            }
4110        }
4111
4112        // If a `join_using_alias` is present, add a new scope item that accepts
4113        // only table-qualified references for each specified join column.
4114        // Unlike regular table aliases, a `join_using_alias` should not hide the
4115        // names of the joined relations.
4116        if alias_item_name.is_some() {
4117            let new_item_col = both_scope.items.len() + new_items.len();
4118            join_cols.push(new_item_col);
4119            hidden_cols.push(new_item_col);
4120
4121            new_items.push(ScopeItem::from_name(
4122                alias_item_name.clone(),
4123                column_name.clone().to_string(),
4124            ));
4125
4126            // The aliased column `alias.col` must take the same value as the
4127            // unqualified join output column `col`. For INNER and LEFT joins
4128            // that's the LHS value, for RIGHT joins it's the RHS value, and
4129            // for FULL OUTER joins it's COALESCE(lhs, rhs). Using `lhs`
4130            // unconditionally produces wrong results for RIGHT/FULL joins on
4131            // rows where the LHS side is NULL.
4132            let alias_expr = match kind {
4133                JoinKind::LeftOuter { .. } | JoinKind::Inner { .. } => {
4134                    HirScalarExpr::named_column(lhs, Arc::clone(&lhs_name))
4135                }
4136                JoinKind::RightOuter => HirScalarExpr::named_column(rhs, Arc::clone(&rhs_name)),
4137                JoinKind::FullOuter => {
4138                    HirScalarExpr::call_variadic(Coalesce, vec![expr1.clone(), expr2.clone()])
4139                }
4140            };
4141            map_exprs.push(alias_expr);
4142        }
4143
4144        join_exprs.push(expr1.call_binary(expr2, expr_func::Eq));
4145    }
4146    both_scope.items.extend(new_items);
4147
4148    // The columns from the secondary side of the join remain accessible by
4149    // their table-qualified name, but not by their column name alone. They are
4150    // also excluded from `SELECT *`.
4151    for c in hidden_cols {
4152        both_scope.items[c].allow_unqualified_references = false;
4153    }
4154
4155    // Reproject all returned elements to the front of the list.
4156    let project_key = join_cols
4157        .into_iter()
4158        .chain(0..both_scope.items.len())
4159        .unique()
4160        .collect::<Vec<_>>();
4161
4162    both_scope = both_scope.project(&project_key);
4163
4164    let on = HirScalarExpr::variadic_and(join_exprs);
4165
4166    let both = left
4167        .join(right, on, kind)
4168        .map(map_exprs)
4169        .project(project_key);
4170    Ok((both, both_scope))
4171}
4172
4173pub fn plan_expr<'a>(
4174    ecx: &'a ExprContext,
4175    e: &Expr<Aug>,
4176) -> Result<CoercibleScalarExpr, PlanError> {
4177    ecx.checked_recur(|ecx| plan_expr_inner(ecx, e))
4178}
4179
4180fn plan_expr_inner<'a>(
4181    ecx: &'a ExprContext,
4182    e: &Expr<Aug>,
4183) -> Result<CoercibleScalarExpr, PlanError> {
4184    if let Some((i, item)) = ecx.scope.resolve_expr(e) {
4185        // We've already calculated this expression.
4186        return Ok(HirScalarExpr::named_column(
4187            i,
4188            ecx.qcx.name_manager.borrow_mut().intern_scope_item(item),
4189        )
4190        .into());
4191    }
4192
4193    match e {
4194        // Names.
4195        Expr::Identifier(names) | Expr::QualifiedWildcard(names) => {
4196            Ok(plan_identifier(ecx, names)?.into())
4197        }
4198
4199        // Literals.
4200        Expr::Value(val) => plan_literal(val),
4201        Expr::Parameter(n) => plan_parameter(ecx, *n),
4202        Expr::Array(exprs) => plan_array(ecx, exprs, None),
4203        Expr::List(exprs) => plan_list(ecx, exprs, None),
4204        Expr::Map(exprs) => plan_map(ecx, exprs, None),
4205        Expr::Row { exprs } => plan_row(ecx, exprs),
4206
4207        // Generalized functions, operators, and casts.
4208        Expr::Op { op, expr1, expr2 } => {
4209            Ok(plan_op(ecx, normalize::op(op)?, expr1, expr2.as_deref())?.into())
4210        }
4211        Expr::Cast {
4212            expr,
4213            data_type,
4214            failure_mode,
4215        } => plan_cast(ecx, expr, data_type, *failure_mode),
4216        Expr::Function(func) => Ok(plan_function(ecx, func)?.into()),
4217
4218        // Special functions and operators.
4219        Expr::Not { expr } => plan_not(ecx, expr),
4220        Expr::And { left, right } => plan_and(ecx, left, right),
4221        Expr::Or { left, right } => plan_or(ecx, left, right),
4222        Expr::IsExpr {
4223            expr,
4224            construct,
4225            negated,
4226        } => Ok(plan_is_expr(ecx, expr, construct, *negated)?.into()),
4227        Expr::Case {
4228            operand,
4229            conditions,
4230            results,
4231            else_result,
4232        } => Ok(plan_case(ecx, operand, conditions, results, else_result)?.into()),
4233        Expr::HomogenizingFunction { function, exprs } => {
4234            plan_homogenizing_function(ecx, function, exprs)
4235        }
4236        Expr::NullIf { l_expr, r_expr } => Ok(plan_case(
4237            ecx,
4238            &None,
4239            &[l_expr.clone().equals(*r_expr.clone())],
4240            &[Expr::null()],
4241            &Some(Box::new(*l_expr.clone())),
4242        )?
4243        .into()),
4244        Expr::FieldAccess { expr, field } => plan_field_access(ecx, expr, field),
4245        Expr::WildcardAccess(expr) => plan_expr(ecx, expr),
4246        Expr::Subscript { expr, positions } => plan_subscript(ecx, expr, positions),
4247        Expr::Like {
4248            expr,
4249            pattern,
4250            escape,
4251            case_insensitive,
4252            negated,
4253        } => Ok(plan_like(
4254            ecx,
4255            expr,
4256            pattern,
4257            escape.as_deref(),
4258            *case_insensitive,
4259            *negated,
4260        )?
4261        .into()),
4262
4263        Expr::InList {
4264            expr,
4265            list,
4266            negated,
4267        } => plan_in_list(ecx, expr, list, negated),
4268
4269        // Subqueries.
4270        Expr::Exists(query) => plan_exists(ecx, query),
4271        Expr::Subquery(query) => plan_subquery(ecx, query),
4272        Expr::ListSubquery(query) => plan_list_subquery(ecx, query),
4273        Expr::MapSubquery(query) => plan_map_subquery(ecx, query),
4274        Expr::ArraySubquery(query) => plan_array_subquery(ecx, query),
4275        Expr::Collate { expr, collation } => plan_collate(ecx, expr, collation),
4276        Expr::Nested(_) => bail_internal!("Expr::Nested should have been desugared"),
4277        Expr::InSubquery { .. } => {
4278            bail_internal!("Expr::InSubquery should have been desugared")
4279        }
4280        Expr::AnyExpr { .. } => {
4281            bail_internal!("Expr::AnyExpr should have been desugared")
4282        }
4283        Expr::AllExpr { .. } => {
4284            bail_internal!("Expr::AllExpr should have been desugared")
4285        }
4286        Expr::AnySubquery { .. } => {
4287            bail_internal!("Expr::AnySubquery should have been desugared")
4288        }
4289        Expr::AllSubquery { .. } => {
4290            bail_internal!("Expr::AllSubquery should have been desugared")
4291        }
4292        Expr::Between { .. } => {
4293            bail_internal!("Expr::Between should have been desugared")
4294        }
4295    }
4296}
4297
4298fn plan_parameter(ecx: &ExprContext, n: usize) -> Result<CoercibleScalarExpr, PlanError> {
4299    if !ecx.allow_parameters {
4300        // It might be clearer to return an error like "cannot use parameter
4301        // here", but this is how PostgreSQL does it, and so for now we follow
4302        // PostgreSQL.
4303        return Err(PlanError::UnknownParameter(n));
4304    }
4305    if n == 0 || n > 65536 {
4306        return Err(PlanError::UnknownParameter(n));
4307    }
4308    if ecx.param_types().borrow().contains_key(&n) {
4309        Ok(HirScalarExpr::parameter(n).into())
4310    } else {
4311        Ok(CoercibleScalarExpr::Parameter(n))
4312    }
4313}
4314
4315fn plan_row(ecx: &ExprContext, exprs: &[Expr<Aug>]) -> Result<CoercibleScalarExpr, PlanError> {
4316    let mut out = vec![];
4317    for e in exprs {
4318        out.push(plan_expr(ecx, e)?);
4319    }
4320    Ok(CoercibleScalarExpr::LiteralRecord(out))
4321}
4322
4323/// Plans `CAST(expr AS data_type)` or, under
4324/// [`CastFailureMode::NullFallback`], `TRY_CAST(expr AS data_type)`.
4325fn plan_cast(
4326    ecx: &ExprContext,
4327    expr: &Expr<Aug>,
4328    data_type: &ResolvedDataType,
4329    failure_mode: CastFailureMode,
4330) -> Result<CoercibleScalarExpr, PlanError> {
4331    let name = match failure_mode {
4332        CastFailureMode::Error => "CAST",
4333        CastFailureMode::NullFallback => {
4334            ecx.qcx.scx.require_feature_flag(&vars::ENABLE_TRY_CAST)?;
4335            "TRY_CAST"
4336        }
4337    };
4338    let to_scalar_type = scalar_type_from_sql(ecx.qcx.scx, data_type)?;
4339    let keeps_hint = |empty: bool| failure_mode == CastFailureMode::Error || empty;
4340    let expr = match expr {
4341        // Special case a direct cast of an ARRAY, LIST, or MAP expression so
4342        // we can pass in the target type as a type hint. This is
4343        // a limited form of the coercion that we do for string literals
4344        // via CoercibleScalarExpr. We used to let CoercibleScalarExpr
4345        // handle ARRAY/LIST/MAP coercion too, but doing so causes
4346        // PostgreSQL compatibility trouble.
4347        //
4348        // See: https://github.com/postgres/postgres/blob/31f403e95/src/backend/parser/parse_expr.c#L2762-L2768
4349        //
4350        // The hint makes the element casts part of the literal, where a
4351        // failure mode cannot reach them. Under `NullFallback` a non-empty
4352        // ARRAY or LIST literal is planned on its own instead, so the cast
4353        // that gets wrapped is the whole-value one, and a bad element yields
4354        // NULL for the whole value just as it does for a non-literal source.
4355        // An empty literal has no element casts, so it keeps the hint, which
4356        // is the only thing that can type it. A non-empty MAP literal has no
4357        // whole-value cast to fall back on, since there is no cast between
4358        // map types, so under `NullFallback` it is rejected rather than
4359        // converted with the hint's element-level strictness.
4360        Expr::Array(exprs) if keeps_hint(exprs.is_empty()) => {
4361            plan_array(ecx, exprs, Some(&to_scalar_type))?
4362        }
4363        Expr::List(exprs) if keeps_hint(exprs.is_empty()) => {
4364            plan_list(ecx, exprs, Some(&to_scalar_type))?
4365        }
4366        Expr::Map(exprs) if keeps_hint(exprs.is_empty()) => {
4367            plan_map(ecx, exprs, Some(&to_scalar_type))?
4368        }
4369        Expr::Map(_) => {
4370            bail_unsupported!("non-empty MAP constructor as the argument of TRY_CAST")
4371        }
4372        expr => plan_expr(ecx, expr)?,
4373    };
4374    let ecx = &ecx.with_name(name);
4375    // A string literal reaches its cast through coercion, so the failure mode
4376    // has to apply there too, or `TRY_CAST('abc' AS int4)` would still error.
4377    let expr = typeconv::plan_coerce_with_failure_mode(ecx, expr, &to_scalar_type, failure_mode)?;
4378    let expr = typeconv::plan_cast_with_failure_mode(
4379        ecx,
4380        CastContext::Explicit,
4381        failure_mode,
4382        expr,
4383        &to_scalar_type,
4384    )?;
4385    Ok(expr.into())
4386}
4387
4388fn plan_not(ecx: &ExprContext, expr: &Expr<Aug>) -> Result<CoercibleScalarExpr, PlanError> {
4389    let ecx = ecx.with_name("NOT argument");
4390    Ok(plan_expr(&ecx, expr)?
4391        .type_as(&ecx, &SqlScalarType::Bool)?
4392        .call_unary(UnaryFunc::Not(expr_func::Not))
4393        .into())
4394}
4395
4396fn plan_and(
4397    ecx: &ExprContext,
4398    left: &Expr<Aug>,
4399    right: &Expr<Aug>,
4400) -> Result<CoercibleScalarExpr, PlanError> {
4401    let ecx = ecx.with_name("AND argument");
4402    Ok(HirScalarExpr::variadic_and(vec![
4403        plan_expr(&ecx, left)?.type_as(&ecx, &SqlScalarType::Bool)?,
4404        plan_expr(&ecx, right)?.type_as(&ecx, &SqlScalarType::Bool)?,
4405    ])
4406    .into())
4407}
4408
4409fn plan_or(
4410    ecx: &ExprContext,
4411    left: &Expr<Aug>,
4412    right: &Expr<Aug>,
4413) -> Result<CoercibleScalarExpr, PlanError> {
4414    let ecx = ecx.with_name("OR argument");
4415    Ok(HirScalarExpr::variadic_or(vec![
4416        plan_expr(&ecx, left)?.type_as(&ecx, &SqlScalarType::Bool)?,
4417        plan_expr(&ecx, right)?.type_as(&ecx, &SqlScalarType::Bool)?,
4418    ])
4419    .into())
4420}
4421
4422fn plan_in_list(
4423    ecx: &ExprContext,
4424    lhs: &Expr<Aug>,
4425    list: &Vec<Expr<Aug>>,
4426    negated: &bool,
4427) -> Result<CoercibleScalarExpr, PlanError> {
4428    let ecx = ecx.with_name("IN list");
4429    let or = HirScalarExpr::variadic_or(
4430        list.into_iter()
4431            .map(|e| {
4432                let eq = lhs.clone().equals(e.clone());
4433                plan_expr(&ecx, &eq)?.type_as(&ecx, &SqlScalarType::Bool)
4434            })
4435            .collect::<Result<Vec<HirScalarExpr>, PlanError>>()?,
4436    );
4437    Ok(if *negated {
4438        or.call_unary(UnaryFunc::Not(expr_func::Not))
4439    } else {
4440        or
4441    }
4442    .into())
4443}
4444
4445fn plan_homogenizing_function(
4446    ecx: &ExprContext,
4447    function: &HomogenizingFunction,
4448    exprs: &[Expr<Aug>],
4449) -> Result<CoercibleScalarExpr, PlanError> {
4450    assert!(!exprs.is_empty()); // `COALESCE()` is a syntax error
4451    let expr = HirScalarExpr::call_variadic(
4452        match function {
4453            HomogenizingFunction::Coalesce => VariadicFunc::from(Coalesce),
4454            HomogenizingFunction::Greatest => VariadicFunc::from(Greatest),
4455            HomogenizingFunction::Least => VariadicFunc::from(Least),
4456        },
4457        coerce_homogeneous_exprs(
4458            &ecx.with_name(&function.to_string().to_lowercase()),
4459            plan_exprs(ecx, exprs)?,
4460            None,
4461        )?,
4462    );
4463    Ok(expr.into())
4464}
4465
4466fn plan_field_access(
4467    ecx: &ExprContext,
4468    expr: &Expr<Aug>,
4469    field: &Ident,
4470) -> Result<CoercibleScalarExpr, PlanError> {
4471    let field = normalize::column_name(field.clone());
4472    let expr = plan_expr(ecx, expr)?.type_as_any(ecx)?;
4473    let ty = ecx.scalar_type(&expr);
4474    let i = match &ty {
4475        SqlScalarType::Record { fields, .. } => {
4476            fields.iter().position(|(name, _ty)| *name == field)
4477        }
4478        ty => sql_bail!(
4479            "column notation applied to type {}, which is not a composite type",
4480            ecx.humanize_sql_scalar_type(ty, false)
4481        ),
4482    };
4483    match i {
4484        None => sql_bail!(
4485            "field {} not found in data type {}",
4486            field,
4487            ecx.humanize_sql_scalar_type(&ty, false)
4488        ),
4489        Some(i) => Ok(expr
4490            .call_unary(UnaryFunc::RecordGet(expr_func::RecordGet(i)))
4491            .into()),
4492    }
4493}
4494
4495fn plan_subscript(
4496    ecx: &ExprContext,
4497    expr: &Expr<Aug>,
4498    positions: &[SubscriptPosition<Aug>],
4499) -> Result<CoercibleScalarExpr, PlanError> {
4500    assert!(
4501        !positions.is_empty(),
4502        "subscript expression must contain at least one position"
4503    );
4504
4505    let ecx = &ecx.with_name("subscripting");
4506    let expr = plan_expr(ecx, expr)?.type_as_any(ecx)?;
4507    let ty = ecx.scalar_type(&expr);
4508    match &ty {
4509        SqlScalarType::Array(..) | SqlScalarType::Int2Vector => plan_subscript_array(
4510            ecx,
4511            expr,
4512            positions,
4513            // Int2Vector uses 0-based indexing, while arrays use 1-based indexing, so we need to
4514            // adjust all Int2Vector subscript operations by 1 (both w/r/t input and the values we
4515            // track in its backing data).
4516            if ty == SqlScalarType::Int2Vector {
4517                1
4518            } else {
4519                0
4520            },
4521        ),
4522        SqlScalarType::Jsonb => plan_subscript_jsonb(ecx, expr, positions),
4523        SqlScalarType::List { element_type, .. } => {
4524            // `elem_type_name` is used only in error msgs, so we set `postgres_compat` to false.
4525            let elem_type_name = ecx.humanize_sql_scalar_type(element_type, false);
4526            let n_layers = ty.unwrap_list_n_layers();
4527            plan_subscript_list(ecx, expr, positions, n_layers, &elem_type_name)
4528        }
4529        ty => sql_bail!(
4530            "cannot subscript type {}",
4531            ecx.humanize_sql_scalar_type(ty, false)
4532        ),
4533    }
4534}
4535
4536// All subscript positions are of the form [<expr>(:<expr>?)?]; extract all
4537// expressions from those that look like indexes (i.e. `[<expr>]`) or error if
4538// any were slices (i.e. included colon).
4539fn extract_scalar_subscript_from_positions<'a>(
4540    positions: &'a [SubscriptPosition<Aug>],
4541    expr_type_name: &str,
4542) -> Result<Vec<&'a Expr<Aug>>, PlanError> {
4543    let mut scalar_subscripts = Vec::with_capacity(positions.len());
4544    for p in positions {
4545        if p.explicit_slice {
4546            sql_bail!("{} subscript does not support slices", expr_type_name);
4547        }
4548        assert!(
4549            p.end.is_none(),
4550            "index-appearing subscripts cannot have end value"
4551        );
4552        scalar_subscripts.push(p.start.as_ref().expect("has start if not slice"));
4553    }
4554    Ok(scalar_subscripts)
4555}
4556
4557fn plan_subscript_array(
4558    ecx: &ExprContext,
4559    expr: HirScalarExpr,
4560    positions: &[SubscriptPosition<Aug>],
4561    offset: i64,
4562) -> Result<CoercibleScalarExpr, PlanError> {
4563    let mut exprs = Vec::with_capacity(positions.len() + 1);
4564    exprs.push(expr);
4565
4566    // Subscripting arrays doesn't yet support slicing, so we always want to
4567    // extract scalars or error.
4568    let indexes = extract_scalar_subscript_from_positions(positions, "array")?;
4569
4570    for i in indexes {
4571        exprs.push(plan_expr(ecx, i)?.cast_to(
4572            ecx,
4573            CastContext::Explicit,
4574            &SqlScalarType::Int64,
4575        )?);
4576    }
4577
4578    Ok(HirScalarExpr::call_variadic(ArrayIndex { offset }, exprs).into())
4579}
4580
4581fn plan_subscript_list(
4582    ecx: &ExprContext,
4583    mut expr: HirScalarExpr,
4584    positions: &[SubscriptPosition<Aug>],
4585    mut remaining_layers: usize,
4586    elem_type_name: &str,
4587) -> Result<CoercibleScalarExpr, PlanError> {
4588    let mut i = 0;
4589
4590    while i < positions.len() {
4591        // Take all contiguous index operations, i.e. find next slice operation.
4592        let j = positions[i..]
4593            .iter()
4594            .position(|p| p.explicit_slice)
4595            .unwrap_or(positions.len() - i);
4596        if j != 0 {
4597            let indexes = extract_scalar_subscript_from_positions(&positions[i..i + j], "")?;
4598            let (n, e) = plan_index_list(
4599                ecx,
4600                expr,
4601                indexes.as_slice(),
4602                remaining_layers,
4603                elem_type_name,
4604            )?;
4605            remaining_layers = n;
4606            expr = e;
4607            i += j;
4608        }
4609
4610        // Take all contiguous slice operations, i.e. find next index operation.
4611        let j = positions[i..]
4612            .iter()
4613            .position(|p| !p.explicit_slice)
4614            .unwrap_or(positions.len() - i);
4615        if j != 0 {
4616            expr = plan_slice_list(
4617                ecx,
4618                expr,
4619                &positions[i..i + j],
4620                remaining_layers,
4621                elem_type_name,
4622            )?;
4623            i += j;
4624        }
4625    }
4626
4627    Ok(expr.into())
4628}
4629
4630fn plan_index_list(
4631    ecx: &ExprContext,
4632    expr: HirScalarExpr,
4633    indexes: &[&Expr<Aug>],
4634    n_layers: usize,
4635    elem_type_name: &str,
4636) -> Result<(usize, HirScalarExpr), PlanError> {
4637    let depth = indexes.len();
4638
4639    if depth > n_layers {
4640        if n_layers == 0 {
4641            sql_bail!("cannot subscript type {}", elem_type_name)
4642        } else {
4643            sql_bail!(
4644                "cannot index into {} layers; list only has {} layer{}",
4645                depth,
4646                n_layers,
4647                if n_layers == 1 { "" } else { "s" }
4648            )
4649        }
4650    }
4651
4652    let mut exprs = Vec::with_capacity(depth + 1);
4653    exprs.push(expr);
4654
4655    for i in indexes {
4656        exprs.push(plan_expr(ecx, i)?.cast_to(
4657            ecx,
4658            CastContext::Explicit,
4659            &SqlScalarType::Int64,
4660        )?);
4661    }
4662
4663    Ok((
4664        n_layers - depth,
4665        HirScalarExpr::call_variadic(ListIndex, exprs),
4666    ))
4667}
4668
4669fn plan_slice_list(
4670    ecx: &ExprContext,
4671    expr: HirScalarExpr,
4672    slices: &[SubscriptPosition<Aug>],
4673    n_layers: usize,
4674    elem_type_name: &str,
4675) -> Result<HirScalarExpr, PlanError> {
4676    if n_layers == 0 {
4677        sql_bail!("cannot subscript type {}", elem_type_name)
4678    }
4679
4680    // first arg will be list
4681    let mut exprs = Vec::with_capacity(slices.len() + 1);
4682    exprs.push(expr);
4683    // extract (start, end) parts from collected slices
4684    let extract_position_or_default = |position, default| -> Result<HirScalarExpr, PlanError> {
4685        Ok(match position {
4686            Some(p) => {
4687                plan_expr(ecx, p)?.cast_to(ecx, CastContext::Explicit, &SqlScalarType::Int64)?
4688            }
4689            None => HirScalarExpr::literal(Datum::Int64(default), SqlScalarType::Int64),
4690        })
4691    };
4692    for p in slices {
4693        let start = extract_position_or_default(p.start.as_ref(), 1)?;
4694        let end = extract_position_or_default(p.end.as_ref(), i64::MAX - 1)?;
4695        exprs.push(start);
4696        exprs.push(end);
4697    }
4698
4699    Ok(HirScalarExpr::call_variadic(ListSliceLinear, exprs))
4700}
4701
4702fn plan_like(
4703    ecx: &ExprContext,
4704    expr: &Expr<Aug>,
4705    pattern: &Expr<Aug>,
4706    escape: Option<&Expr<Aug>>,
4707    case_insensitive: bool,
4708    not: bool,
4709) -> Result<HirScalarExpr, PlanError> {
4710    use CastContext::Implicit;
4711    let ecx = ecx.with_name("LIKE argument");
4712    let expr = plan_expr(&ecx, expr)?;
4713    let haystack = match ecx.scalar_type(&expr) {
4714        CoercibleScalarType::Coerced(ref ty @ SqlScalarType::Char { length }) => expr
4715            .type_as(&ecx, ty)?
4716            .call_unary(UnaryFunc::PadChar(expr_func::PadChar { length })),
4717        _ => expr.cast_to(&ecx, Implicit, &SqlScalarType::String)?,
4718    };
4719    let mut pattern = plan_expr(&ecx, pattern)?.cast_to(&ecx, Implicit, &SqlScalarType::String)?;
4720    if let Some(escape) = escape {
4721        pattern = pattern.call_binary(
4722            plan_expr(&ecx, escape)?.cast_to(&ecx, Implicit, &SqlScalarType::String)?,
4723            expr_func::LikeEscape,
4724        );
4725    }
4726    let func: BinaryFunc = if case_insensitive {
4727        expr_func::IsLikeMatchCaseInsensitive.into()
4728    } else {
4729        expr_func::IsLikeMatchCaseSensitive.into()
4730    };
4731    let like = haystack.call_binary(pattern, func);
4732    if not {
4733        Ok(like.call_unary(UnaryFunc::Not(expr_func::Not)))
4734    } else {
4735        Ok(like)
4736    }
4737}
4738
4739fn plan_subscript_jsonb(
4740    ecx: &ExprContext,
4741    expr: HirScalarExpr,
4742    positions: &[SubscriptPosition<Aug>],
4743) -> Result<CoercibleScalarExpr, PlanError> {
4744    use CastContext::Implicit;
4745    use SqlScalarType::{Int64, String};
4746
4747    // JSONB doesn't support the slicing syntax, so simply error if you
4748    // encounter any explicit slices.
4749    let subscripts = extract_scalar_subscript_from_positions(positions, "jsonb")?;
4750
4751    let mut exprs = Vec::with_capacity(subscripts.len());
4752    for s in subscripts {
4753        let subscript = plan_expr(ecx, s)?;
4754        let subscript = if let Ok(subscript) = subscript.clone().cast_to(ecx, Implicit, &String) {
4755            subscript
4756        } else if let Ok(subscript) = subscript.cast_to(ecx, Implicit, &Int64) {
4757            // Integers are converted to a string here and then re-parsed as an
4758            // integer by `JsonbGetPath`. Weird, but this is how PostgreSQL says to
4759            // do it.
4760            typeconv::to_string(ecx, subscript)?
4761        } else {
4762            sql_bail!("jsonb subscript type must be coercible to integer or text");
4763        };
4764        exprs.push(subscript);
4765    }
4766
4767    // Subscripting works like `expr #> ARRAY[subscript]` rather than
4768    // `expr->subscript` as you might expect.
4769    let expr = expr.call_binary(
4770        HirScalarExpr::call_variadic(
4771            ArrayCreate {
4772                elem_type: SqlScalarType::String,
4773            },
4774            exprs,
4775        ),
4776        expr_func::JsonbGetPath,
4777    );
4778    Ok(expr.into())
4779}
4780
4781fn plan_exists(ecx: &ExprContext, query: &Query<Aug>) -> Result<CoercibleScalarExpr, PlanError> {
4782    if !ecx.allow_subqueries {
4783        sql_bail!("{} does not allow subqueries", ecx.name)
4784    }
4785    let mut qcx = ecx.derived_query_context();
4786    let (expr, _scope) = plan_nested_query(&mut qcx, query)?;
4787    Ok(expr.exists().into())
4788}
4789
4790fn plan_subquery(ecx: &ExprContext, query: &Query<Aug>) -> Result<CoercibleScalarExpr, PlanError> {
4791    if !ecx.allow_subqueries {
4792        sql_bail!("{} does not allow subqueries", ecx.name)
4793    }
4794    let mut qcx = ecx.derived_query_context();
4795    let (expr, _scope) = plan_nested_query(&mut qcx, query)?;
4796    let column_types = qcx.relation_type(&expr).column_types;
4797    if column_types.len() != 1 {
4798        sql_bail!(
4799            "Expected subselect to return 1 column, got {} columns",
4800            column_types.len()
4801        );
4802    }
4803    Ok(expr.select().into())
4804}
4805
4806fn plan_list_subquery(
4807    ecx: &ExprContext,
4808    query: &Query<Aug>,
4809) -> Result<CoercibleScalarExpr, PlanError> {
4810    plan_vector_like_subquery(
4811        ecx,
4812        query,
4813        |_| false,
4814        |elem_type| ListCreate { elem_type }.into(),
4815        |order_by| AggregateFunc::ListConcat { order_by },
4816        expr_func::ListListConcat.into(),
4817        |elem_type| {
4818            HirScalarExpr::literal(
4819                Datum::empty_list(),
4820                SqlScalarType::List {
4821                    element_type: Box::new(elem_type),
4822                    custom_id: None,
4823                },
4824            )
4825        },
4826        "list",
4827    )
4828}
4829
4830fn plan_array_subquery(
4831    ecx: &ExprContext,
4832    query: &Query<Aug>,
4833) -> Result<CoercibleScalarExpr, PlanError> {
4834    plan_vector_like_subquery(
4835        ecx,
4836        query,
4837        |elem_type| {
4838            matches!(
4839                elem_type,
4840                SqlScalarType::Char { .. }
4841                    | SqlScalarType::Array { .. }
4842                    | SqlScalarType::List { .. }
4843                    | SqlScalarType::Map { .. }
4844            )
4845        },
4846        |elem_type| ArrayCreate { elem_type }.into(),
4847        |order_by| AggregateFunc::ArrayConcat { order_by },
4848        expr_func::ArrayArrayConcat.into(),
4849        |elem_type| {
4850            HirScalarExpr::literal(
4851                Datum::empty_array(),
4852                SqlScalarType::Array(Box::new(elem_type)),
4853            )
4854        },
4855        "[]",
4856    )
4857}
4858
4859/// Generic function used to plan both array subqueries and list subqueries
4860fn plan_vector_like_subquery<F1, F2, F3, F4>(
4861    ecx: &ExprContext,
4862    query: &Query<Aug>,
4863    is_unsupported_type: F1,
4864    vector_create: F2,
4865    aggregate_concat: F3,
4866    binary_concat: BinaryFunc,
4867    empty_literal: F4,
4868    vector_type_string: &str,
4869) -> Result<CoercibleScalarExpr, PlanError>
4870where
4871    F1: Fn(&SqlScalarType) -> bool,
4872    F2: Fn(SqlScalarType) -> VariadicFunc,
4873    F3: Fn(Vec<ColumnOrder>) -> AggregateFunc,
4874    F4: Fn(SqlScalarType) -> HirScalarExpr,
4875{
4876    if !ecx.allow_subqueries {
4877        sql_bail!("{} does not allow subqueries", ecx.name)
4878    }
4879
4880    let mut qcx = ecx.derived_query_context();
4881    let mut planned_query = plan_query(&mut qcx, query)?;
4882    if planned_query.limit.is_some()
4883        || !planned_query
4884            .offset
4885            .clone()
4886            .try_into_literal_int64()
4887            .is_ok_and(|offset| offset == 0)
4888    {
4889        planned_query.expr = HirRelationExpr::top_k(
4890            planned_query.expr,
4891            vec![],
4892            planned_query.order_by.clone(),
4893            planned_query.limit,
4894            planned_query.offset,
4895            planned_query.group_size_hints.limit_input_group_size,
4896        );
4897    }
4898
4899    if planned_query.project.len() != 1 {
4900        sql_bail!(
4901            "Expected subselect to return 1 column, got {} columns",
4902            planned_query.project.len()
4903        );
4904    }
4905
4906    let project_column = *planned_query.project.get(0).unwrap();
4907    let elem_type = qcx
4908        .relation_type(&planned_query.expr)
4909        .column_types
4910        .get(project_column)
4911        .cloned()
4912        .unwrap()
4913        .scalar_type();
4914
4915    if is_unsupported_type(&elem_type) {
4916        bail_unsupported!(format!(
4917            "cannot build array from subquery because return type {}{}",
4918            ecx.humanize_sql_scalar_type(&elem_type, false),
4919            vector_type_string
4920        ));
4921    }
4922
4923    // `ColumnRef`s in `aggregation_exprs` refers to the columns produced by planning the
4924    // subquery above.
4925    let aggregation_exprs: Vec<_> = iter::once(HirScalarExpr::call_variadic(
4926        vector_create(elem_type.clone()),
4927        vec![HirScalarExpr::column(project_column)],
4928    ))
4929    .chain(
4930        planned_query
4931            .order_by
4932            .iter()
4933            .map(|co| HirScalarExpr::column(co.column)),
4934    )
4935    .collect();
4936
4937    // However, column references for `aggregation_projection` and `aggregation_order_by`
4938    // are with reference to the `exprs` of the aggregation expression.  Here that is
4939    // `aggregation_exprs`.
4940    let aggregation_projection = vec![0];
4941    let aggregation_order_by = planned_query
4942        .order_by
4943        .into_iter()
4944        .enumerate()
4945        .map(|(i, order)| ColumnOrder { column: i, ..order })
4946        .collect();
4947
4948    let reduced_expr = planned_query
4949        .expr
4950        .reduce(
4951            vec![],
4952            vec![AggregateExpr {
4953                func: aggregate_concat(aggregation_order_by),
4954                expr: Box::new(HirScalarExpr::call_variadic(
4955                    RecordCreate {
4956                        field_names: iter::repeat(ColumnName::from(""))
4957                            .take(aggregation_exprs.len())
4958                            .collect(),
4959                    },
4960                    aggregation_exprs,
4961                )),
4962                distinct: false,
4963            }],
4964            None,
4965        )
4966        .project(aggregation_projection);
4967
4968    // If `expr` has no rows, return an empty array/list rather than NULL.
4969    Ok(reduced_expr
4970        .select()
4971        .call_binary(empty_literal(elem_type), binary_concat)
4972        .into())
4973}
4974
4975fn plan_map_subquery(
4976    ecx: &ExprContext,
4977    query: &Query<Aug>,
4978) -> Result<CoercibleScalarExpr, PlanError> {
4979    if !ecx.allow_subqueries {
4980        sql_bail!("{} does not allow subqueries", ecx.name)
4981    }
4982
4983    let mut qcx = ecx.derived_query_context();
4984    let mut query = plan_query(&mut qcx, query)?;
4985    if query.limit.is_some()
4986        || !query
4987            .offset
4988            .clone()
4989            .try_into_literal_int64()
4990            .is_ok_and(|offset| offset == 0)
4991    {
4992        query.expr = HirRelationExpr::top_k(
4993            query.expr,
4994            vec![],
4995            query.order_by.clone(),
4996            query.limit,
4997            query.offset,
4998            query.group_size_hints.limit_input_group_size,
4999        );
5000    }
5001    if query.project.len() != 2 {
5002        sql_bail!(
5003            "expected map subquery to return 2 columns, got {} columns",
5004            query.project.len()
5005        );
5006    }
5007
5008    let query_types = qcx.relation_type(&query.expr).column_types;
5009    let key_column = query.project[0];
5010    let key_type = query_types[key_column].clone().scalar_type();
5011    let value_column = query.project[1];
5012    let value_type = query_types[value_column].clone().scalar_type();
5013
5014    if key_type != SqlScalarType::String {
5015        sql_bail!("cannot build map from subquery because first column is not of type text");
5016    }
5017
5018    let aggregation_exprs: Vec<_> = iter::once(HirScalarExpr::call_variadic(
5019        RecordCreate {
5020            field_names: vec![ColumnName::from("key"), ColumnName::from("value")],
5021        },
5022        vec![
5023            HirScalarExpr::column(key_column),
5024            HirScalarExpr::column(value_column),
5025        ],
5026    ))
5027    .chain(
5028        query
5029            .order_by
5030            .iter()
5031            .map(|co| HirScalarExpr::column(co.column)),
5032    )
5033    .collect();
5034
5035    let expr = query
5036        .expr
5037        .reduce(
5038            vec![],
5039            vec![AggregateExpr {
5040                func: AggregateFunc::MapAgg {
5041                    order_by: query
5042                        .order_by
5043                        .into_iter()
5044                        .enumerate()
5045                        .map(|(i, order)| ColumnOrder { column: i, ..order })
5046                        .collect(),
5047                    value_type: value_type.clone(),
5048                },
5049                expr: Box::new(HirScalarExpr::call_variadic(
5050                    RecordCreate {
5051                        field_names: iter::repeat(ColumnName::from(""))
5052                            .take(aggregation_exprs.len())
5053                            .collect(),
5054                    },
5055                    aggregation_exprs,
5056                )),
5057                distinct: false,
5058            }],
5059            None,
5060        )
5061        .project(vec![0]);
5062
5063    // If `expr` has no rows, return an empty map rather than NULL.
5064    let expr = HirScalarExpr::call_variadic(
5065        Coalesce,
5066        vec![
5067            expr.select(),
5068            HirScalarExpr::literal(
5069                Datum::empty_map(),
5070                SqlScalarType::Map {
5071                    value_type: Box::new(value_type),
5072                    custom_id: None,
5073                },
5074            ),
5075        ],
5076    );
5077
5078    Ok(expr.into())
5079}
5080
5081/// Reports whether `collation` is one Materialize supports in a `COLLATE`
5082/// clause. Only `pg_catalog.default` is, which is a no-op.
5083pub fn is_supported_collation(collation: &UnresolvedItemName) -> bool {
5084    collation.0.len() == 2
5085        && collation.0[0] == ident!(mz_repr::namespaces::PG_CATALOG_SCHEMA)
5086        && collation.0[1] == ident!("default")
5087}
5088
5089fn plan_collate(
5090    ecx: &ExprContext,
5091    expr: &Expr<Aug>,
5092    collation: &UnresolvedItemName,
5093) -> Result<CoercibleScalarExpr, PlanError> {
5094    if is_supported_collation(collation) {
5095        plan_expr(ecx, expr)
5096    } else {
5097        bail_unsupported!("COLLATE");
5098    }
5099}
5100
5101/// Plans a slice of expressions.
5102///
5103/// This function is a simple convenience function for mapping [`plan_expr`]
5104/// over a slice of expressions. The planned expressions are returned in the
5105/// same order as the input. If any of the expressions fail to plan, returns an
5106/// error instead.
5107fn plan_exprs<E>(ecx: &ExprContext, exprs: &[E]) -> Result<Vec<CoercibleScalarExpr>, PlanError>
5108where
5109    E: std::borrow::Borrow<Expr<Aug>>,
5110{
5111    let mut out = vec![];
5112    for expr in exprs {
5113        out.push(plan_expr(ecx, expr.borrow())?);
5114    }
5115    Ok(out)
5116}
5117
5118/// Plans an `ARRAY` expression.
5119fn plan_array(
5120    ecx: &ExprContext,
5121    exprs: &[Expr<Aug>],
5122    type_hint: Option<&SqlScalarType>,
5123) -> Result<CoercibleScalarExpr, PlanError> {
5124    // Plan each element expression.
5125    let mut out = vec![];
5126    for expr in exprs {
5127        out.push(match expr {
5128            // Special case nested ARRAY expressions so we can plumb
5129            // the type hint through.
5130            Expr::Array(exprs) => plan_array(ecx, exprs, type_hint.clone())?,
5131            _ => plan_expr(ecx, expr)?,
5132        });
5133    }
5134
5135    // Attempt to make use of the type hint.
5136    let type_hint = match type_hint {
5137        // The user has provided an explicit cast to an array type. We know the
5138        // element type to coerce to. Need to be careful, though: if there's
5139        // evidence that any of the array elements are themselves arrays, we
5140        // want to coerce to the array type, not the element type.
5141        Some(SqlScalarType::Array(elem_type)) => {
5142            let multidimensional = out.iter().any(|e| {
5143                matches!(
5144                    ecx.scalar_type(e),
5145                    CoercibleScalarType::Coerced(SqlScalarType::Array(_))
5146                )
5147            });
5148            if multidimensional {
5149                type_hint
5150            } else {
5151                Some(&**elem_type)
5152            }
5153        }
5154        // The user provided an explicit cast to a non-array type. We'll have to
5155        // guess what the correct type for the array. Our caller will then
5156        // handle converting that array type to the desired non-array type.
5157        Some(_) => None,
5158        // No type hint. We'll have to guess the correct type for the array.
5159        None => None,
5160    };
5161
5162    // Coerce all elements to the same type.
5163    let (elem_type, exprs) = if exprs.is_empty() {
5164        if let Some(elem_type) = type_hint {
5165            (elem_type.clone(), vec![])
5166        } else {
5167            sql_bail!("cannot determine type of empty array");
5168        }
5169    } else {
5170        let out = coerce_homogeneous_exprs(&ecx.with_name("ARRAY"), out, type_hint)?;
5171        (union_scalar_types(ecx, &out)?, out)
5172    };
5173
5174    // Arrays of `char` type are disallowed due to a known limitation:
5175    // https://github.com/MaterializeInc/database-issues/issues/2360.
5176    //
5177    // Arrays of `list` and `map` types are disallowed due to mind-bending
5178    // semantics.
5179    if matches!(
5180        elem_type,
5181        SqlScalarType::Char { .. } | SqlScalarType::List { .. } | SqlScalarType::Map { .. }
5182    ) {
5183        bail_unsupported!(format!(
5184            "{}[]",
5185            ecx.humanize_sql_scalar_type(&elem_type, false)
5186        ));
5187    }
5188
5189    Ok(HirScalarExpr::call_variadic(ArrayCreate { elem_type }, exprs).into())
5190}
5191
5192fn plan_list(
5193    ecx: &ExprContext,
5194    exprs: &[Expr<Aug>],
5195    type_hint: Option<&SqlScalarType>,
5196) -> Result<CoercibleScalarExpr, PlanError> {
5197    let (elem_type, exprs) = if exprs.is_empty() {
5198        if let Some(SqlScalarType::List { element_type, .. }) = type_hint {
5199            (element_type.without_modifiers(), vec![])
5200        } else {
5201            sql_bail!("cannot determine type of empty list");
5202        }
5203    } else {
5204        let type_hint = match type_hint {
5205            Some(SqlScalarType::List { element_type, .. }) => Some(&**element_type),
5206            _ => None,
5207        };
5208
5209        let mut out = vec![];
5210        for expr in exprs {
5211            out.push(match expr {
5212                // Special case nested LIST expressions so we can plumb
5213                // the type hint through.
5214                Expr::List(exprs) => plan_list(ecx, exprs, type_hint)?,
5215                _ => plan_expr(ecx, expr)?,
5216            });
5217        }
5218        let out = coerce_homogeneous_exprs(&ecx.with_name("LIST"), out, type_hint)?;
5219        (union_scalar_types(ecx, &out)?.without_modifiers(), out)
5220    };
5221
5222    if matches!(elem_type, SqlScalarType::Char { .. }) {
5223        bail_unsupported!("char list");
5224    }
5225
5226    Ok(HirScalarExpr::call_variadic(ListCreate { elem_type }, exprs).into())
5227}
5228
5229fn plan_map(
5230    ecx: &ExprContext,
5231    entries: &[MapEntry<Aug>],
5232    type_hint: Option<&SqlScalarType>,
5233) -> Result<CoercibleScalarExpr, PlanError> {
5234    let (value_type, exprs) = if entries.is_empty() {
5235        if let Some(SqlScalarType::Map { value_type, .. }) = type_hint {
5236            (value_type.without_modifiers(), vec![])
5237        } else {
5238            sql_bail!("cannot determine type of empty map");
5239        }
5240    } else {
5241        let type_hint = match type_hint {
5242            Some(SqlScalarType::Map { value_type, .. }) => Some(&**value_type),
5243            _ => None,
5244        };
5245
5246        let mut keys = vec![];
5247        let mut values = vec![];
5248        for MapEntry { key, value } in entries {
5249            let key = plan_expr(ecx, key)?.type_as(ecx, &SqlScalarType::String)?;
5250            let value = match value {
5251                // Special case nested MAP expressions so we can plumb
5252                // the type hint through.
5253                Expr::Map(entries) => plan_map(ecx, entries, type_hint)?,
5254                _ => plan_expr(ecx, value)?,
5255            };
5256            keys.push(key);
5257            values.push(value);
5258        }
5259        let values = coerce_homogeneous_exprs(&ecx.with_name("MAP"), values, type_hint)?;
5260        let value_type = union_scalar_types(ecx, &values)?.without_modifiers();
5261        let out = itertools::interleave(keys, values).collect();
5262        (value_type, out)
5263    };
5264
5265    if matches!(value_type, SqlScalarType::Char { .. }) {
5266        bail_unsupported!("char map");
5267    }
5268
5269    let expr = HirScalarExpr::call_variadic(MapBuild { value_type }, exprs);
5270    Ok(expr.into())
5271}
5272
5273/// Coerces a list of expressions such that all input expressions will be cast
5274/// to the same type. If successful, returns a new list of expressions in the
5275/// same order as the input, where each expression has the appropriate casts to
5276/// make them all of a uniform type.
5277///
5278/// If `force_type` is `Some`, the expressions are forced to the specified type
5279/// via an explicit cast. Otherwise the best common type is guessed via
5280/// [`typeconv::guess_best_common_type`] and conversions are attempted via
5281/// implicit casts
5282///
5283/// Note that this is our implementation of Postgres' type conversion for
5284/// ["`UNION`, `CASE`, and Related Constructs"][union-type-conv], though it
5285/// isn't yet used in all of those cases.
5286///
5287/// [union-type-conv]:
5288/// https://www.postgresql.org/docs/12/typeconv-union-case.html
5289pub fn coerce_homogeneous_exprs(
5290    ecx: &ExprContext,
5291    exprs: Vec<CoercibleScalarExpr>,
5292    force_type: Option<&SqlScalarType>,
5293) -> Result<Vec<HirScalarExpr>, PlanError> {
5294    assert!(!exprs.is_empty());
5295
5296    let target_holder;
5297    let target = match force_type {
5298        Some(t) => t,
5299        None => {
5300            let types: Vec<_> = exprs.iter().map(|e| ecx.scalar_type(e)).collect();
5301            target_holder = typeconv::guess_best_common_type(ecx, &types)?;
5302            &target_holder
5303        }
5304    };
5305
5306    // Try to cast all expressions to `target`.
5307    let mut out = Vec::new();
5308    for expr in exprs {
5309        let arg = typeconv::plan_coerce(ecx, expr, target)?;
5310        let ccx = match force_type {
5311            None => CastContext::Implicit,
5312            Some(_) => CastContext::Explicit,
5313        };
5314        match typeconv::plan_cast(ecx, ccx, arg.clone(), target) {
5315            Ok(expr) => out.push(expr),
5316            Err(_) => sql_bail!(
5317                "{} could not convert type {} to {}",
5318                ecx.name,
5319                ecx.humanize_sql_scalar_type(&ecx.scalar_type(&arg), false),
5320                ecx.humanize_sql_scalar_type(target, false),
5321            ),
5322        }
5323    }
5324    Ok(out)
5325}
5326
5327/// Returns the least upper bound of the types of `exprs`, which
5328/// [`coerce_homogeneous_exprs`] has already coerced to a common type.
5329fn union_scalar_types(
5330    ecx: &ExprContext,
5331    exprs: &[HirScalarExpr],
5332) -> Result<SqlScalarType, PlanError> {
5333    let mut typ = ecx.scalar_type(&exprs[0]);
5334    for expr in &exprs[1..] {
5335        typ = typ.sql_union(&ecx.scalar_type(expr))?;
5336    }
5337    Ok(typ)
5338}
5339
5340/// Creates a `ColumnOrder` from an `OrderByExpr` and column index.
5341/// Column index is specified by the caller, but `desc` and `nulls_last` is figured out here.
5342pub(crate) fn resolve_desc_and_nulls_last<T: AstInfo>(
5343    obe: &OrderByExpr<T>,
5344    column: usize,
5345) -> ColumnOrder {
5346    let desc = !obe.asc.unwrap_or(true);
5347    ColumnOrder {
5348        column,
5349        desc,
5350        // https://www.postgresql.org/docs/14/queries-order.html
5351        //   "NULLS FIRST is the default for DESC order, and NULLS LAST otherwise"
5352        nulls_last: obe.nulls_last.unwrap_or(!desc),
5353    }
5354}
5355
5356/// Plans the ORDER BY clause of a window function.
5357///
5358/// Unfortunately, we have to create two HIR structs from an AST OrderByExpr:
5359/// A ColumnOrder has asc/desc and nulls first/last, but can't represent an HirScalarExpr, just
5360/// a column reference by index. Therefore, we return both HirScalarExprs and ColumnOrders.
5361/// Note that the column references in the ColumnOrders point NOT to input columns, but into the
5362/// `Vec<HirScalarExpr>` that we return.
5363fn plan_function_order_by(
5364    ecx: &ExprContext,
5365    order_by: &[OrderByExpr<Aug>],
5366) -> Result<(Vec<HirScalarExpr>, Vec<ColumnOrder>), PlanError> {
5367    let mut order_by_exprs = vec![];
5368    let mut col_orders = vec![];
5369    {
5370        for (i, obe) in order_by.iter().enumerate() {
5371            // Unlike `SELECT ... ORDER BY` clauses, function `ORDER BY` clauses
5372            // do not support ordinal references in PostgreSQL. So we use
5373            // `plan_expr` directly rather than `plan_order_by_or_distinct_expr`.
5374            let expr = plan_expr(ecx, &obe.expr)?.type_as_any(ecx)?;
5375            order_by_exprs.push(expr);
5376            col_orders.push(resolve_desc_and_nulls_last(obe, i));
5377        }
5378    }
5379    Ok((order_by_exprs, col_orders))
5380}
5381
5382/// Returns a human-readable rendering of `name`, falling back to a debug
5383/// dump of the `ResolvedItemName` if humanization fails. Used to construct
5384/// user-facing error messages on already-failing paths, where we'd rather
5385/// surface the raw resolved name than emit a useless `<unknown>` placeholder.
5386fn humanize_or_debug(scx: &StatementContext, name: &ResolvedItemName) -> String {
5387    scx.humanize_resolved_name(name)
5388        .map(|n| n.to_string())
5389        .unwrap_or_else(|_| format!("<error when trying to humanize `{name:?}`>"))
5390}
5391
5392/// Common part of the planning of windowed and non-windowed aggregation functions.
5393fn plan_aggregate_common(
5394    ecx: &ExprContext,
5395    Function::<Aug> {
5396        name,
5397        args,
5398        filter,
5399        over: _,
5400        distinct,
5401    }: &Function<Aug>,
5402) -> Result<AggregateExpr, PlanError> {
5403    // Normal aggregate functions, like `sum`, expect as input a single expression
5404    // which yields the datum to aggregate. Order sensitive aggregate functions,
5405    // like `jsonb_agg`, are special, and instead expect a Record whose first
5406    // element yields the datum to aggregate and whose successive elements yield
5407    // keys to order by. This expectation is hard coded within the implementation
5408    // of each of the order-sensitive aggregates. The specification of how many
5409    // order by keys to consider, and in what order, is passed via the `order_by`
5410    // field on the `AggregateFunc` variant.
5411
5412    // While all aggregate functions support the ORDER BY syntax, it's a no-op for
5413    // most, so explicitly drop it if the function doesn't care about order. This
5414    // prevents the projection into Record below from triggering on unsupported
5415    // functions.
5416
5417    let impls = match resolve_func(ecx, name, args)? {
5418        Func::Aggregate(impls) => impls,
5419        _ => bail_internal!("plan_aggregate_common called on non-aggregate function"),
5420    };
5421
5422    // We follow PostgreSQL's rule here for mapping `count(*)` into the
5423    // generalized function selection framework. The rule is simple: the user
5424    // must type `count(*)`, but the function selection framework sees an empty
5425    // parameter list, as if the user had typed `count()`. But if the user types
5426    // `count()` directly, that is an error. Like PostgreSQL, we apply these
5427    // rules to all aggregates, not just `count`, since we may one day support
5428    // user-defined aggregates, including user-defined aggregates that take no
5429    // parameters.
5430    let (args, order_by) = match &args {
5431        FunctionArgs::Star => (vec![], vec![]),
5432        FunctionArgs::Args { args, order_by } => {
5433            if args.is_empty() {
5434                sql_bail!(
5435                    "{}(*) must be used to call a parameterless aggregate function",
5436                    humanize_or_debug(ecx.qcx.scx, name)
5437                );
5438            }
5439            let args = plan_exprs(ecx, args)?;
5440            (args, order_by.clone())
5441        }
5442    };
5443
5444    let (order_by_exprs, col_orders) = plan_function_order_by(ecx, &order_by)?;
5445
5446    let (mut expr, func) = func::select_impl(ecx, FuncSpec::Func(name), impls, args, col_orders)?;
5447    if let Some(filter) = &filter {
5448        // If a filter is present, as in
5449        //
5450        //     <agg>(<expr>) FILTER (WHERE <cond>)
5451        //
5452        // we plan it by essentially rewriting the expression to
5453        //
5454        //     <agg>(CASE WHEN <cond> THEN <expr> ELSE <identity>)
5455        //
5456        // where <identity> is the identity input for <agg>.
5457        let cond =
5458            plan_expr(&ecx.with_name("FILTER"), filter)?.type_as(ecx, &SqlScalarType::Bool)?;
5459        let expr_typ = ecx.scalar_type(&expr);
5460        expr = HirScalarExpr::if_then_else(
5461            cond,
5462            expr,
5463            HirScalarExpr::literal(func.identity_datum(), expr_typ),
5464        );
5465    }
5466
5467    let mut seen_outer = false;
5468    let mut seen_inner = false;
5469    #[allow(deprecated)]
5470    expr.visit_columns(0, &mut |depth, col| {
5471        if depth == 0 && col.level == 0 {
5472            seen_inner = true;
5473        } else if col.level > depth {
5474            seen_outer = true;
5475        }
5476    });
5477    if seen_outer && !seen_inner {
5478        bail_unsupported!(
5479            3720,
5480            "aggregate functions that refer exclusively to outer columns"
5481        );
5482    }
5483
5484    // If a function supports ORDER BY (even if there was no ORDER BY specified),
5485    // map the needed expressions into the aggregate datum.
5486    if func.is_order_sensitive() {
5487        let field_names = iter::repeat(ColumnName::from(""))
5488            .take(1 + order_by_exprs.len())
5489            .collect();
5490        let mut exprs = vec![expr];
5491        exprs.extend(order_by_exprs);
5492        expr = HirScalarExpr::call_variadic(RecordCreate { field_names }, exprs);
5493    }
5494
5495    Ok(AggregateExpr {
5496        func,
5497        expr: Box::new(expr),
5498        distinct: *distinct,
5499    })
5500}
5501
5502fn plan_identifier(ecx: &ExprContext, names: &[Ident]) -> Result<HirScalarExpr, PlanError> {
5503    let mut names = names.to_vec();
5504    // The parser guarantees that an `Expr::Identifier` is constructed with a
5505    // non-empty list of name parts, so an empty list here is an internal bug.
5506    let Some(last) = names.pop() else {
5507        bail_internal!("empty identifier");
5508    };
5509    let col_name = normalize::column_name(last);
5510
5511    // If the name is qualified, it must refer to a column in a table.
5512    if !names.is_empty() {
5513        let table_name = normalize::unresolved_item_name(UnresolvedItemName(names))?;
5514        let (i, i_name) = ecx.scope.resolve_table_column(
5515            &ecx.qcx.outer_scopes,
5516            &table_name,
5517            &col_name,
5518            &mut ecx.qcx.name_manager.borrow_mut(),
5519        )?;
5520        return Ok(HirScalarExpr::named_column(i, i_name));
5521    }
5522
5523    // If the name is unqualified, first check if it refers to a column. Track any similar names
5524    // that might exist for a better error message.
5525    let similar_names = match ecx.scope.resolve_column(
5526        &ecx.qcx.outer_scopes,
5527        &col_name,
5528        &mut ecx.qcx.name_manager.borrow_mut(),
5529    ) {
5530        Ok((i, i_name)) => {
5531            return Ok(HirScalarExpr::named_column(i, i_name));
5532        }
5533        Err(PlanError::UnknownColumn { similar, .. }) => similar,
5534        Err(e) => return Err(e),
5535    };
5536
5537    // The name doesn't refer to a column. Check if it is a whole-row reference
5538    // to a table.
5539    let items = ecx.scope.items_from_table(
5540        &ecx.qcx.outer_scopes,
5541        &PartialItemName {
5542            database: None,
5543            schema: None,
5544            item: col_name.as_str().to_owned(),
5545        },
5546    )?;
5547    match items.as_slice() {
5548        // The name doesn't refer to a table either. Return an error.
5549        [] => Err(PlanError::UnknownColumn {
5550            table: None,
5551            column: col_name,
5552            similar: similar_names,
5553        }),
5554        // The name refers to a table that is the result of a function that
5555        // returned a single column. Per PostgreSQL, this is a special case
5556        // that returns the value directly.
5557        // See: https://github.com/postgres/postgres/blob/22592e10b/src/backend/parser/parse_expr.c#L2519-L2524
5558        [(column, item)] if item.from_single_column_function => Ok(HirScalarExpr::named_column(
5559            *column,
5560            ecx.qcx.name_manager.borrow_mut().intern_scope_item(item),
5561        )),
5562        // The name refers to a normal table. Return a record containing all the
5563        // columns of the table.
5564        _ => {
5565            let mut has_exists_column = None;
5566            let (exprs, field_names): (Vec<_>, Vec<_>) = items
5567                .into_iter()
5568                .filter_map(|(column, item)| {
5569                    if item.is_exists_column_for_a_table_function_that_was_in_the_target_list {
5570                        has_exists_column = Some(column);
5571                        None
5572                    } else {
5573                        let expr = HirScalarExpr::named_column(
5574                            column,
5575                            ecx.qcx.name_manager.borrow_mut().intern_scope_item(item),
5576                        );
5577                        let name = item.column_name.clone();
5578                        Some((expr, name))
5579                    }
5580                })
5581                .unzip();
5582            // For the special case of a table function with a single column, the single column is instead not wrapped.
5583            let expr = if exprs.len() == 1 && has_exists_column.is_some() {
5584                exprs.into_element()
5585            } else {
5586                HirScalarExpr::call_variadic(RecordCreate { field_names }, exprs)
5587            };
5588            if let Some(has_exists_column) = has_exists_column {
5589                Ok(HirScalarExpr::if_then_else(
5590                    HirScalarExpr::unnamed_column(has_exists_column)
5591                        .call_unary(UnaryFunc::IsNull(mz_expr::func::IsNull)),
5592                    HirScalarExpr::literal_null(ecx.scalar_type(&expr)),
5593                    expr,
5594                ))
5595            } else {
5596                Ok(expr)
5597            }
5598        }
5599    }
5600}
5601
5602fn plan_op(
5603    ecx: &ExprContext,
5604    op: &str,
5605    expr1: &Expr<Aug>,
5606    expr2: Option<&Expr<Aug>>,
5607) -> Result<HirScalarExpr, PlanError> {
5608    let impls = func::resolve_op(op)?;
5609    let args = match expr2 {
5610        None => plan_exprs(ecx, &[expr1])?,
5611        Some(expr2) => plan_exprs(ecx, &[expr1, expr2])?,
5612    };
5613    func::select_impl(ecx, FuncSpec::Op(op), impls, args, vec![])
5614}
5615
5616fn plan_function<'a>(
5617    ecx: &ExprContext,
5618    f @ Function {
5619        name,
5620        args,
5621        filter,
5622        over,
5623        distinct,
5624    }: &'a Function<Aug>,
5625) -> Result<HirScalarExpr, PlanError> {
5626    let impls = match resolve_func(ecx, name, args)? {
5627        Func::Table(_) => {
5628            sql_bail!(
5629                "table functions are not allowed in {} (function {})",
5630                ecx.name,
5631                name
5632            );
5633        }
5634        Func::Scalar(impls) => {
5635            if over.is_some() {
5636                sql_bail!(
5637                    "OVER clause not allowed on {name}. The OVER clause can only be used with window functions (including aggregations)."
5638                );
5639            }
5640            impls
5641        }
5642        Func::ScalarWindow(impls) => {
5643            let (
5644                ignore_nulls,
5645                order_by_exprs,
5646                col_orders,
5647                _window_frame,
5648                partition_by,
5649                scalar_args,
5650            ) = plan_window_function_non_aggr(ecx, f)?;
5651
5652            // All scalar window functions have 0 parameters. Let's print a nice error msg if the
5653            // user gave some args. (The below `func::select_impl` would fail anyway, but the error
5654            // msg there is less informative.)
5655            if !scalar_args.is_empty() {
5656                if let ResolvedItemName::Item {
5657                    full_name: FullItemName { item, .. },
5658                    ..
5659                } = name
5660                {
5661                    sql_bail!(
5662                        "function {} has 0 parameters, but was called with {}",
5663                        item,
5664                        scalar_args.len()
5665                    );
5666                }
5667            }
5668
5669            // Note: the window frame doesn't affect scalar window funcs, but, strangely, we should
5670            // accept a window frame here without an error msg. (Postgres also does this.)
5671            // TODO: maybe we should give a notice
5672
5673            let func = func::select_impl(ecx, FuncSpec::Func(name), impls, scalar_args, vec![])?;
5674
5675            if ignore_nulls {
5676                // If we ever add a scalar window function that supports ignore, then don't forget
5677                // to also update HIR EXPLAIN.
5678                bail_unsupported!(IGNORE_NULLS_ERROR_MSG);
5679            }
5680
5681            return Ok(HirScalarExpr::windowing(WindowExpr {
5682                func: WindowExprType::Scalar(ScalarWindowExpr {
5683                    func,
5684                    order_by: col_orders,
5685                }),
5686                partition_by,
5687                order_by: order_by_exprs,
5688            }));
5689        }
5690        Func::ValueWindow(impls) => {
5691            let window_plan = plan_window_function_non_aggr(ecx, f)?;
5692            let (ignore_nulls, order_by_exprs, col_orders, window_frame, partition_by, win_args) =
5693                window_plan;
5694
5695            let (args_encoded, func) =
5696                func::select_impl(ecx, FuncSpec::Func(name), impls, win_args, vec![])?;
5697
5698            if ignore_nulls {
5699                match func {
5700                    ValueWindowFunc::Lag | ValueWindowFunc::Lead => {}
5701                    _ => bail_unsupported!(IGNORE_NULLS_ERROR_MSG),
5702                }
5703            }
5704
5705            return Ok(HirScalarExpr::windowing(WindowExpr {
5706                func: WindowExprType::Value(ValueWindowExpr {
5707                    func,
5708                    args: Box::new(args_encoded),
5709                    order_by: col_orders,
5710                    window_frame,
5711                    ignore_nulls, // (RESPECT NULLS is the default)
5712                }),
5713                partition_by,
5714                order_by: order_by_exprs,
5715            }));
5716        }
5717        Func::Aggregate(_) => {
5718            if f.over.is_none() {
5719                // Not a window aggregate. Something is wrong.
5720                if ecx.allow_aggregates {
5721                    // Should already have been caught by `scope.resolve_expr` in `plan_expr_inner`
5722                    // (after having been planned earlier in `Step 5` of `plan_select_from_where`).
5723                    sql_bail!(
5724                        "Internal error: encountered unplanned non-windowed aggregate function: {:?}",
5725                        name,
5726                    );
5727                } else {
5728                    // scope.resolve_expr didn't catch it because we have not yet planned it,
5729                    // because it was in an unsupported context.
5730                    sql_bail!(
5731                        "aggregate functions are not allowed in {} (function {})",
5732                        ecx.name,
5733                        name
5734                    );
5735                }
5736            } else {
5737                let (ignore_nulls, order_by_exprs, col_orders, window_frame, partition_by) =
5738                    plan_window_function_common(ecx, &f.name, f.over.as_deref())?;
5739
5740                // https://github.com/MaterializeInc/database-issues/issues/6720
5741                match (&window_frame.start_bound, &window_frame.end_bound) {
5742                    (
5743                        mz_expr::WindowFrameBound::UnboundedPreceding,
5744                        mz_expr::WindowFrameBound::OffsetPreceding(..),
5745                    )
5746                    | (
5747                        mz_expr::WindowFrameBound::UnboundedPreceding,
5748                        mz_expr::WindowFrameBound::OffsetFollowing(..),
5749                    )
5750                    | (
5751                        mz_expr::WindowFrameBound::OffsetPreceding(..),
5752                        mz_expr::WindowFrameBound::UnboundedFollowing,
5753                    )
5754                    | (
5755                        mz_expr::WindowFrameBound::OffsetFollowing(..),
5756                        mz_expr::WindowFrameBound::UnboundedFollowing,
5757                    ) => bail_unsupported!("mixed unbounded - offset frames"),
5758                    (_, _) => {} // other cases are ok
5759                }
5760
5761                if ignore_nulls {
5762                    // https://github.com/MaterializeInc/database-issues/issues/6722
5763                    // If we ever add support for ignore_nulls for a window aggregate, then don't
5764                    // forget to also update HIR EXPLAIN.
5765                    bail_unsupported!(IGNORE_NULLS_ERROR_MSG);
5766                }
5767
5768                let aggregate_expr = plan_aggregate_common(ecx, f)?;
5769
5770                if aggregate_expr.distinct {
5771                    // https://github.com/MaterializeInc/database-issues/issues/6626
5772                    bail_unsupported!("DISTINCT in window aggregates");
5773                }
5774
5775                return Ok(HirScalarExpr::windowing(WindowExpr {
5776                    func: WindowExprType::Aggregate(AggregateWindowExpr {
5777                        aggregate_expr,
5778                        order_by: col_orders,
5779                        window_frame,
5780                    }),
5781                    partition_by,
5782                    order_by: order_by_exprs,
5783                }));
5784            }
5785        }
5786    };
5787
5788    if over.is_some() {
5789        bail_internal!("OVER clause should have been handled by the window function path above");
5790    }
5791
5792    if *distinct {
5793        sql_bail!(
5794            "DISTINCT specified, but {} is not an aggregate function",
5795            humanize_or_debug(ecx.qcx.scx, name)
5796        );
5797    }
5798    if filter.is_some() {
5799        sql_bail!(
5800            "FILTER specified, but {} is not an aggregate function",
5801            humanize_or_debug(ecx.qcx.scx, name)
5802        );
5803    }
5804
5805    let scalar_args = match &args {
5806        FunctionArgs::Star => {
5807            sql_bail!(
5808                "* argument is invalid with non-aggregate function {}",
5809                humanize_or_debug(ecx.qcx.scx, name)
5810            )
5811        }
5812        FunctionArgs::Args { args, order_by } => {
5813            if !order_by.is_empty() {
5814                sql_bail!(
5815                    "ORDER BY specified, but {} is not an aggregate function",
5816                    humanize_or_debug(ecx.qcx.scx, name)
5817                );
5818            }
5819            plan_exprs(ecx, args)?
5820        }
5821    };
5822
5823    func::select_impl(ecx, FuncSpec::Func(name), impls, scalar_args, vec![])
5824}
5825
5826pub const IGNORE_NULLS_ERROR_MSG: &str =
5827    "IGNORE NULLS and RESPECT NULLS options for functions other than LAG and LEAD";
5828
5829/// Resolves the name to a set of function implementations.
5830///
5831/// If the name does not specify a known built-in function, returns an error.
5832pub fn resolve_func(
5833    ecx: &ExprContext,
5834    name: &ResolvedItemName,
5835    args: &mz_sql_parser::ast::FunctionArgs<Aug>,
5836) -> Result<&'static Func, PlanError> {
5837    if let Ok(i) = ecx.qcx.scx.get_item_by_resolved_name(name) {
5838        if let Ok(f) = i.func() {
5839            return Ok(f);
5840        }
5841    }
5842
5843    // Couldn't resolve function with this name, so generate verbose error
5844    // message.
5845    let cexprs = match args {
5846        mz_sql_parser::ast::FunctionArgs::Star => vec![],
5847        mz_sql_parser::ast::FunctionArgs::Args { args, order_by } => {
5848            if !order_by.is_empty() {
5849                sql_bail!(
5850                    "ORDER BY specified, but {} is not an aggregate function",
5851                    name
5852                );
5853            }
5854            plan_exprs(ecx, args)?
5855        }
5856    };
5857
5858    let arg_types: Vec<_> = cexprs
5859        .into_iter()
5860        .map(|ty| match ecx.scalar_type(&ty) {
5861            CoercibleScalarType::Coerced(ty) => ecx.humanize_sql_scalar_type(&ty, false),
5862            CoercibleScalarType::Record(_) => "record".to_string(),
5863            CoercibleScalarType::Uncoerced => "unknown".to_string(),
5864        })
5865        .collect();
5866
5867    Err(PlanError::UnknownFunction {
5868        name: name.to_string(),
5869        arg_types,
5870    })
5871}
5872
5873fn plan_is_expr<'a>(
5874    ecx: &ExprContext,
5875    expr: &'a Expr<Aug>,
5876    construct: &IsExprConstruct<Aug>,
5877    not: bool,
5878) -> Result<HirScalarExpr, PlanError> {
5879    let expr_hir = plan_expr(ecx, expr)?;
5880
5881    let mut result = match construct {
5882        IsExprConstruct::Null => {
5883            // PostgreSQL can plan `NULL IS NULL` but not `$1 IS NULL`. This is
5884            // at odds with our type coercion rules, which treat `NULL` literals
5885            // and unconstrained parameters identically. Providing a type hint
5886            // of string means we wind up supporting both.
5887            expr_hir.type_as_any(ecx)?.call_is_null()
5888        }
5889        IsExprConstruct::Unknown => expr_hir.type_as(ecx, &SqlScalarType::Bool)?.call_is_null(),
5890        IsExprConstruct::True => expr_hir
5891            .type_as(ecx, &SqlScalarType::Bool)?
5892            .call_unary(UnaryFunc::IsTrue(expr_func::IsTrue)),
5893        IsExprConstruct::False => expr_hir
5894            .type_as(ecx, &SqlScalarType::Bool)?
5895            .call_unary(UnaryFunc::IsFalse(expr_func::IsFalse)),
5896        IsExprConstruct::DistinctFrom(expr2) => {
5897            // There are three cases:
5898            // 1. Both terms are non-null, in which case the result should be `a != b`.
5899            // 2. Exactly one term is null, in which case the result should be true.
5900            // 3. Both terms are null, in which case the result should be false.
5901            //
5902            // (a != b OR a IS NULL OR b IS NULL) AND (a IS NOT NULL OR b IS NOT NULL)
5903
5904            // We'll need `expr != expr2`, but don't just construct this HIR directly. Instead,
5905            // construct an AST expression for `expr != expr2` and plan it to get proper type
5906            // checking, implicit casts, etc. (This seems to be also what Postgres does.)
5907            let ne_ast = expr.clone().not_equals(expr2.as_ref().clone());
5908            let ne_hir = plan_expr(ecx, &ne_ast)?.type_as_any(ecx)?;
5909
5910            let expr1_hir = expr_hir.type_as_any(ecx)?;
5911            let expr2_hir = plan_expr(ecx, expr2)?.type_as_any(ecx)?;
5912
5913            let term1 = HirScalarExpr::variadic_or(vec![
5914                ne_hir,
5915                expr1_hir.clone().call_is_null(),
5916                expr2_hir.clone().call_is_null(),
5917            ]);
5918            let term2 = HirScalarExpr::variadic_or(vec![
5919                expr1_hir.call_is_null().not(),
5920                expr2_hir.call_is_null().not(),
5921            ]);
5922            term1.and(term2)
5923        }
5924    };
5925    if not {
5926        result = result.not();
5927    }
5928    Ok(result)
5929}
5930
5931fn plan_case<'a>(
5932    ecx: &ExprContext,
5933    operand: &'a Option<Box<Expr<Aug>>>,
5934    conditions: &'a [Expr<Aug>],
5935    results: &'a [Expr<Aug>],
5936    else_result: &'a Option<Box<Expr<Aug>>>,
5937) -> Result<HirScalarExpr, PlanError> {
5938    let mut cond_exprs = Vec::new();
5939    let mut result_exprs = Vec::new();
5940    for (c, r) in conditions.iter().zip_eq(results) {
5941        let c = match operand {
5942            Some(operand) => operand.clone().equals(c.clone()),
5943            None => c.clone(),
5944        };
5945        let cexpr = plan_expr(ecx, &c)?.type_as(ecx, &SqlScalarType::Bool)?;
5946        cond_exprs.push(cexpr);
5947        result_exprs.push(r);
5948    }
5949    result_exprs.push(match else_result {
5950        Some(else_result) => else_result,
5951        None => &Expr::Value(Value::Null),
5952    });
5953    let mut result_exprs = coerce_homogeneous_exprs(
5954        &ecx.with_name("CASE"),
5955        plan_exprs(ecx, &result_exprs)?,
5956        None,
5957    )?;
5958    let mut expr = result_exprs.pop().unwrap();
5959    assert_eq!(cond_exprs.len(), result_exprs.len());
5960    for (cexpr, rexpr) in cond_exprs
5961        .into_iter()
5962        .rev()
5963        .zip_eq(result_exprs.into_iter().rev())
5964    {
5965        expr = HirScalarExpr::if_then_else(cexpr, rexpr, expr);
5966    }
5967    Ok(expr)
5968}
5969
5970fn plan_literal<'a>(l: &'a Value) -> Result<CoercibleScalarExpr, PlanError> {
5971    let (datum, scalar_type) = match l {
5972        Value::Number(s) => {
5973            let d = strconv::parse_numeric(s.as_str())?;
5974            if !s.contains(&['E', '.'][..]) {
5975                // Maybe representable as an int?
5976                if let Ok(n) = d.0.try_into() {
5977                    (Datum::Int32(n), SqlScalarType::Int32)
5978                } else if let Ok(n) = d.0.try_into() {
5979                    (Datum::Int64(n), SqlScalarType::Int64)
5980                } else {
5981                    (
5982                        Datum::Numeric(d),
5983                        SqlScalarType::Numeric { max_scale: None },
5984                    )
5985                }
5986            } else {
5987                (
5988                    Datum::Numeric(d),
5989                    SqlScalarType::Numeric { max_scale: None },
5990                )
5991            }
5992        }
5993        Value::HexString(_) => bail_unsupported!("hex string literals"),
5994        Value::Boolean(b) => match b {
5995            false => (Datum::False, SqlScalarType::Bool),
5996            true => (Datum::True, SqlScalarType::Bool),
5997        },
5998        Value::Interval(i) => {
5999            let i = literal::plan_interval(i)?;
6000            (Datum::Interval(i), SqlScalarType::Interval)
6001        }
6002        Value::String(s) => return Ok(CoercibleScalarExpr::LiteralString(s.clone())),
6003        Value::Null => return Ok(CoercibleScalarExpr::LiteralNull),
6004    };
6005    let expr = HirScalarExpr::literal(datum, scalar_type);
6006    Ok(expr.into())
6007}
6008
6009/// The common part of the planning of non-aggregate window functions, i.e.,
6010/// scalar window functions and value window functions.
6011fn plan_window_function_non_aggr<'a>(
6012    ecx: &ExprContext,
6013    Function {
6014        name,
6015        args,
6016        filter,
6017        over,
6018        distinct,
6019    }: &'a Function<Aug>,
6020) -> Result<
6021    (
6022        bool,
6023        Vec<HirScalarExpr>,
6024        Vec<ColumnOrder>,
6025        mz_expr::WindowFrame,
6026        Vec<HirScalarExpr>,
6027        Vec<CoercibleScalarExpr>,
6028    ),
6029    PlanError,
6030> {
6031    let (ignore_nulls, order_by_exprs, col_orders, window_frame, partition) =
6032        plan_window_function_common(ecx, name, over.as_deref())?;
6033
6034    if *distinct {
6035        sql_bail!(
6036            "DISTINCT specified, but {} is not an aggregate function",
6037            name
6038        );
6039    }
6040
6041    if filter.is_some() {
6042        bail_unsupported!("FILTER in non-aggregate window functions");
6043    }
6044
6045    let scalar_args = match &args {
6046        FunctionArgs::Star => {
6047            sql_bail!("* argument is invalid with non-aggregate function {}", name)
6048        }
6049        FunctionArgs::Args { args, order_by } => {
6050            if !order_by.is_empty() {
6051                sql_bail!(
6052                    "ORDER BY specified, but {} is not an aggregate function",
6053                    name
6054                );
6055            }
6056            plan_exprs(ecx, args)?
6057        }
6058    };
6059
6060    Ok((
6061        ignore_nulls,
6062        order_by_exprs,
6063        col_orders,
6064        window_frame,
6065        partition,
6066        scalar_args,
6067    ))
6068}
6069
6070/// The common part of the planning of all window functions.
6071fn plan_window_function_common(
6072    ecx: &ExprContext,
6073    name: &<Aug as AstInfo>::ItemName,
6074    over: Option<&WindowSpec<Aug>>,
6075) -> Result<
6076    (
6077        bool,
6078        Vec<HirScalarExpr>,
6079        Vec<ColumnOrder>,
6080        mz_expr::WindowFrame,
6081        Vec<HirScalarExpr>,
6082    ),
6083    PlanError,
6084> {
6085    if !ecx.allow_windows {
6086        sql_bail!(
6087            "window functions are not allowed in {} (function {})",
6088            ecx.name,
6089            name
6090        );
6091    }
6092
6093    let window_spec = match over {
6094        Some(over) => over,
6095        None => sql_bail!("window function {} requires an OVER clause", name),
6096    };
6097    if window_spec.ignore_nulls && window_spec.respect_nulls {
6098        sql_bail!("Both IGNORE NULLS and RESPECT NULLS were given.");
6099    }
6100    let window_frame = match window_spec.window_frame.as_ref() {
6101        Some(frame) => plan_window_frame(frame)?,
6102        None => mz_expr::WindowFrame::default(),
6103    };
6104    let mut partition = Vec::new();
6105    for expr in &window_spec.partition_by {
6106        partition.push(plan_expr(ecx, expr)?.type_as_any(ecx)?);
6107    }
6108
6109    let (order_by_exprs, col_orders) = plan_function_order_by(ecx, &window_spec.order_by)?;
6110
6111    Ok((
6112        window_spec.ignore_nulls,
6113        order_by_exprs,
6114        col_orders,
6115        window_frame,
6116        partition,
6117    ))
6118}
6119
6120fn plan_window_frame(
6121    WindowFrame {
6122        units,
6123        start_bound,
6124        end_bound,
6125    }: &WindowFrame,
6126) -> Result<mz_expr::WindowFrame, PlanError> {
6127    use mz_expr::WindowFrameBound::*;
6128    let units = window_frame_unit_ast_to_expr(units)?;
6129    let start_bound = window_frame_bound_ast_to_expr(start_bound);
6130    let end_bound = end_bound
6131        .as_ref()
6132        .map(window_frame_bound_ast_to_expr)
6133        .unwrap_or(CurrentRow);
6134
6135    // Validate bounds according to Postgres rules
6136    match (&start_bound, &end_bound) {
6137        // Start bound can't be UNBOUNDED FOLLOWING
6138        (UnboundedFollowing, _) => {
6139            sql_bail!("frame start cannot be UNBOUNDED FOLLOWING")
6140        }
6141        // End bound can't be UNBOUNDED PRECEDING
6142        (_, UnboundedPreceding) => {
6143            sql_bail!("frame end cannot be UNBOUNDED PRECEDING")
6144        }
6145        // Start bound should come before end bound in the list of bound definitions
6146        (CurrentRow, OffsetPreceding(_)) => {
6147            sql_bail!("frame starting from current row cannot have preceding rows")
6148        }
6149        (OffsetFollowing(_), OffsetPreceding(_) | CurrentRow) => {
6150            sql_bail!("frame starting from following row cannot have preceding rows")
6151        }
6152        // The above rules are adopted from Postgres.
6153        // The following rules are Materialize-specific.
6154        (OffsetPreceding(o1), OffsetFollowing(o2)) => {
6155            // Note that the only hard limit is that partition size + offset should fit in i64, so
6156            // in theory, we could support much larger offsets than this. But for our current
6157            // performance, even 1000000 is quite big.
6158            if *o1 > 1000000 || *o2 > 1000000 {
6159                sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6160            }
6161        }
6162        (OffsetPreceding(o1), OffsetPreceding(o2)) => {
6163            if *o1 > 1000000 || *o2 > 1000000 {
6164                sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6165            }
6166        }
6167        (OffsetFollowing(o1), OffsetFollowing(o2)) => {
6168            if *o1 > 1000000 || *o2 > 1000000 {
6169                sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6170            }
6171        }
6172        (OffsetPreceding(o), CurrentRow) => {
6173            if *o > 1000000 {
6174                sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6175            }
6176        }
6177        (CurrentRow, OffsetFollowing(o)) => {
6178            if *o > 1000000 {
6179                sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6180            }
6181        }
6182        // Other bounds are valid
6183        (_, _) => (),
6184    }
6185
6186    // RANGE is only supported in the default frame
6187    // https://github.com/MaterializeInc/database-issues/issues/6585
6188    if units == mz_expr::WindowFrameUnits::Range
6189        && (start_bound != UnboundedPreceding || end_bound != CurrentRow)
6190    {
6191        bail_unsupported!("RANGE in non-default window frames")
6192    }
6193
6194    let frame = mz_expr::WindowFrame {
6195        units,
6196        start_bound,
6197        end_bound,
6198    };
6199    Ok(frame)
6200}
6201
6202fn window_frame_unit_ast_to_expr(
6203    unit: &WindowFrameUnits,
6204) -> Result<mz_expr::WindowFrameUnits, PlanError> {
6205    match unit {
6206        WindowFrameUnits::Rows => Ok(mz_expr::WindowFrameUnits::Rows),
6207        WindowFrameUnits::Range => Ok(mz_expr::WindowFrameUnits::Range),
6208        WindowFrameUnits::Groups => bail_unsupported!("GROUPS in window frames"),
6209    }
6210}
6211
6212fn window_frame_bound_ast_to_expr(bound: &WindowFrameBound) -> mz_expr::WindowFrameBound {
6213    match bound {
6214        WindowFrameBound::CurrentRow => mz_expr::WindowFrameBound::CurrentRow,
6215        WindowFrameBound::Preceding(None) => mz_expr::WindowFrameBound::UnboundedPreceding,
6216        WindowFrameBound::Preceding(Some(offset)) => {
6217            mz_expr::WindowFrameBound::OffsetPreceding(*offset)
6218        }
6219        WindowFrameBound::Following(None) => mz_expr::WindowFrameBound::UnboundedFollowing,
6220        WindowFrameBound::Following(Some(offset)) => {
6221            mz_expr::WindowFrameBound::OffsetFollowing(*offset)
6222        }
6223    }
6224}
6225
6226pub fn scalar_type_from_sql(
6227    scx: &StatementContext,
6228    data_type: &ResolvedDataType,
6229) -> Result<SqlScalarType, PlanError> {
6230    match data_type {
6231        ResolvedDataType::AnonymousList(elem_type) => {
6232            let elem_type = scalar_type_from_sql(scx, elem_type)?;
6233            if matches!(elem_type, SqlScalarType::Char { .. }) {
6234                bail_unsupported!("char list");
6235            }
6236            Ok(SqlScalarType::List {
6237                element_type: Box::new(elem_type),
6238                custom_id: None,
6239            })
6240        }
6241        ResolvedDataType::AnonymousMap {
6242            key_type,
6243            value_type,
6244        } => {
6245            match scalar_type_from_sql(scx, key_type)? {
6246                SqlScalarType::String => {}
6247                other => sql_bail!(
6248                    "map key type must be {}, got {}",
6249                    scx.humanize_sql_scalar_type(&SqlScalarType::String, false),
6250                    scx.humanize_sql_scalar_type(&other, false)
6251                ),
6252            }
6253            Ok(SqlScalarType::Map {
6254                value_type: Box::new(scalar_type_from_sql(scx, value_type)?),
6255                custom_id: None,
6256            })
6257        }
6258        ResolvedDataType::Named { id, modifiers, .. } => {
6259            scalar_type_from_catalog(scx.catalog, *id, modifiers)
6260        }
6261        ResolvedDataType::Error => bail_internal!("should have been caught in name resolution"),
6262    }
6263}
6264
6265/// Maximum nesting depth of a custom type. A deeper type is rejected rather than
6266/// recursed into, so a long `CREATE TYPE` chain (`l0 <- l1 <- ... <- lN`) cannot
6267/// overflow the stack while resolving.
6268const MAX_TYPE_NESTING_DEPTH: usize = 128;
6269
6270/// Maximum number of sub-type resolutions performed while resolving a single
6271/// custom type. A record whose fields reference the same sub-type produces a
6272/// type tree that is exponential in its depth (fields hold owned copies, not
6273/// shared references), so bound the total work to reject such a type before it
6274/// exhausts memory / CPU rather than after.
6275const MAX_TYPE_RESOLUTION_NODES: usize = 100_000;
6276
6277pub fn scalar_type_from_catalog(
6278    catalog: &dyn SessionCatalog,
6279    id: CatalogItemId,
6280    modifiers: &[i64],
6281) -> Result<SqlScalarType, PlanError> {
6282    let (depth_limit, mut budget) = type_resolution_limits(catalog);
6283    scalar_type_from_catalog_inner(catalog, id, modifiers, 0, depth_limit, &mut budget)
6284}
6285
6286/// The `(nesting-depth, resolution-node)` limits to apply while resolving one
6287/// root custom type. See [`MAX_TYPE_NESTING_DEPTH`] and
6288/// [`MAX_TYPE_RESOLUTION_NODES`] for what each guards against.
6289///
6290/// The limits are lifted while re-planning a persisted catalog item. The
6291/// `unsafe_enable_unbounded_custom_type_resolution` flag signals this, and
6292/// `SystemVars::enable_for_item_parsing` force-enables it during bootstrap. A
6293/// type that an earlier version already accepted resolves to a finite tree, so
6294/// its persisted `create_sql` must keep re-planning after these limits were
6295/// introduced. Rejecting such a grandfathered type during rehydration would
6296/// turn a graceful planning error into a fatal bootstrap panic. A later
6297/// resolution in a normal user session still applies the limits and returns the
6298/// graceful error.
6299fn type_resolution_limits(catalog: &dyn SessionCatalog) -> (usize, usize) {
6300    if catalog
6301        .system_vars()
6302        .unsafe_enable_unbounded_custom_type_resolution()
6303    {
6304        (usize::MAX, usize::MAX)
6305    } else {
6306        (MAX_TYPE_NESTING_DEPTH, MAX_TYPE_RESOLUTION_NODES)
6307    }
6308}
6309
6310/// Bounds the total resolution work while resolving one root custom type into a
6311/// `SqlScalarType`. A single budget must span the entire root type: a record's
6312/// fields, and any containers nested within them, all draw from one shared pool.
6313/// A type that is small field-by-field but enormous in aggregate is therefore
6314/// still rejected. Resetting the budget per field would let a wide record of
6315/// individually-cheap fields resolve into an unbounded type tree and exhaust
6316/// memory, which is the denial of service this bound exists to prevent.
6317///
6318/// Use this when resolving a type that is being assembled from its parts (for
6319/// example at `CREATE TYPE` time, before the root exists in the catalog) so that
6320/// creation-time validation rejects exactly the types a later direct
6321/// [`scalar_type_from_catalog`] call would reject.
6322pub struct TypeResolutionBudget {
6323    /// Sub-type resolutions remaining before the root type is rejected as too
6324    /// complex.
6325    remaining: usize,
6326    /// Nesting depth past which the root type is rejected. Shared by every
6327    /// child so the whole root type is bounded consistently.
6328    depth_limit: usize,
6329}
6330
6331impl TypeResolutionBudget {
6332    /// Creates a budget for resolving one root type, charging the root node
6333    /// itself against the budget. Children resolved through
6334    /// [`TypeResolutionBudget::resolve_child`] begin at nesting depth one,
6335    /// mirroring a direct [`scalar_type_from_catalog`] call. The limits are
6336    /// relaxed for grandfathered persisted items, see [`type_resolution_limits`].
6337    pub fn for_root(catalog: &dyn SessionCatalog) -> TypeResolutionBudget {
6338        let (depth_limit, budget) = type_resolution_limits(catalog);
6339        TypeResolutionBudget {
6340            // The root type counts as one node.
6341            remaining: budget.saturating_sub(1),
6342            depth_limit,
6343        }
6344    }
6345
6346    /// Resolves a type referenced directly by the root (a record field, list
6347    /// element, or map value) into a `SqlScalarType`, drawing from this shared
6348    /// budget so that all such children of one root are bounded together.
6349    pub fn resolve_child(
6350        &mut self,
6351        catalog: &dyn SessionCatalog,
6352        id: CatalogItemId,
6353        modifiers: &[i64],
6354    ) -> Result<SqlScalarType, PlanError> {
6355        scalar_type_from_catalog_inner(
6356            catalog,
6357            id,
6358            modifiers,
6359            1,
6360            self.depth_limit,
6361            &mut self.remaining,
6362        )
6363    }
6364}
6365
6366fn scalar_type_from_catalog_inner(
6367    catalog: &dyn SessionCatalog,
6368    id: CatalogItemId,
6369    modifiers: &[i64],
6370    depth: usize,
6371    depth_limit: usize,
6372    budget: &mut usize,
6373) -> Result<SqlScalarType, PlanError> {
6374    if depth > depth_limit {
6375        sql_bail!("custom type nesting depth exceeds limit of {}", depth_limit);
6376    }
6377    *budget = match budget.checked_sub(1) {
6378        Some(remaining) => remaining,
6379        None => sql_bail!("custom type is too complex to resolve"),
6380    };
6381    let entry = catalog.get_item(&id);
6382    let type_details = match entry.type_details() {
6383        Some(type_details) => type_details,
6384        None => {
6385            // Resolution should never produce a `ResolvedDataType::Named` with
6386            // an ID of a non-type, but we error gracefully just in case.
6387            sql_bail!(
6388                "internal error: {} does not refer to a type",
6389                catalog.resolve_full_name(entry.name()).to_string().quoted()
6390            );
6391        }
6392    };
6393    match &type_details.typ {
6394        CatalogType::Numeric => {
6395            let mut modifiers = modifiers.iter().fuse();
6396            let precision = match modifiers.next() {
6397                Some(p) if *p < 1 || *p > i64::from(NUMERIC_DATUM_MAX_PRECISION) => {
6398                    sql_bail!(
6399                        "precision for type numeric must be between 1 and {}",
6400                        NUMERIC_DATUM_MAX_PRECISION,
6401                    );
6402                }
6403                Some(p) => Some(*p),
6404                None => None,
6405            };
6406            let scale = match modifiers.next() {
6407                Some(scale) => {
6408                    if let Some(precision) = precision {
6409                        if *scale > precision {
6410                            sql_bail!(
6411                                "scale for type numeric must be between 0 and precision {}",
6412                                precision
6413                            );
6414                        }
6415                    }
6416                    Some(NumericMaxScale::try_from(*scale)?)
6417                }
6418                None => None,
6419            };
6420            if modifiers.next().is_some() {
6421                sql_bail!("type numeric supports at most two type modifiers");
6422            }
6423            Ok(SqlScalarType::Numeric { max_scale: scale })
6424        }
6425        CatalogType::Char => {
6426            let mut modifiers = modifiers.iter().fuse();
6427            let length = match modifiers.next() {
6428                Some(l) => Some(CharLength::try_from(*l)?),
6429                None => Some(CharLength::ONE),
6430            };
6431            if modifiers.next().is_some() {
6432                sql_bail!("type character supports at most one type modifier");
6433            }
6434            Ok(SqlScalarType::Char { length })
6435        }
6436        CatalogType::VarChar => {
6437            let mut modifiers = modifiers.iter().fuse();
6438            let length = match modifiers.next() {
6439                Some(l) => Some(VarCharMaxLength::try_from(*l)?),
6440                None => None,
6441            };
6442            if modifiers.next().is_some() {
6443                sql_bail!("type character varying supports at most one type modifier");
6444            }
6445            Ok(SqlScalarType::VarChar { max_length: length })
6446        }
6447        CatalogType::Timestamp => {
6448            let mut modifiers = modifiers.iter().fuse();
6449            let precision = match modifiers.next() {
6450                Some(p) => Some(TimestampPrecision::try_from(*p)?),
6451                None => None,
6452            };
6453            if modifiers.next().is_some() {
6454                sql_bail!("type timestamp supports at most one type modifier");
6455            }
6456            Ok(SqlScalarType::Timestamp { precision })
6457        }
6458        CatalogType::TimestampTz => {
6459            let mut modifiers = modifiers.iter().fuse();
6460            let precision = match modifiers.next() {
6461                Some(p) => Some(TimestampPrecision::try_from(*p)?),
6462                None => None,
6463            };
6464            if modifiers.next().is_some() {
6465                sql_bail!("type timestamp with time zone supports at most one type modifier");
6466            }
6467            Ok(SqlScalarType::TimestampTz { precision })
6468        }
6469        t => {
6470            if !modifiers.is_empty() {
6471                sql_bail!(
6472                    "{} does not support type modifiers",
6473                    catalog.resolve_full_name(entry.name()).to_string()
6474                );
6475            }
6476            match t {
6477                CatalogType::Array {
6478                    element_reference: element_id,
6479                } => Ok(SqlScalarType::Array(Box::new(
6480                    scalar_type_from_catalog_inner(
6481                        catalog,
6482                        *element_id,
6483                        modifiers,
6484                        depth + 1,
6485                        depth_limit,
6486                        budget,
6487                    )?,
6488                ))),
6489                CatalogType::List {
6490                    element_reference: element_id,
6491                    element_modifiers,
6492                } => Ok(SqlScalarType::List {
6493                    element_type: Box::new(scalar_type_from_catalog_inner(
6494                        catalog,
6495                        *element_id,
6496                        element_modifiers,
6497                        depth + 1,
6498                        depth_limit,
6499                        budget,
6500                    )?),
6501                    custom_id: Some(id),
6502                }),
6503                CatalogType::Map {
6504                    key_reference: _,
6505                    key_modifiers: _,
6506                    value_reference: value_id,
6507                    value_modifiers,
6508                } => Ok(SqlScalarType::Map {
6509                    value_type: Box::new(scalar_type_from_catalog_inner(
6510                        catalog,
6511                        *value_id,
6512                        value_modifiers,
6513                        depth + 1,
6514                        depth_limit,
6515                        budget,
6516                    )?),
6517                    custom_id: Some(id),
6518                }),
6519                CatalogType::Range {
6520                    element_reference: element_id,
6521                } => Ok(SqlScalarType::Range {
6522                    element_type: Box::new(scalar_type_from_catalog_inner(
6523                        catalog,
6524                        *element_id,
6525                        &[],
6526                        depth + 1,
6527                        depth_limit,
6528                        budget,
6529                    )?),
6530                }),
6531                CatalogType::Record { fields } => {
6532                    let scalars: Box<[(ColumnName, SqlColumnType)]> = fields
6533                        .iter()
6534                        .map(|f| {
6535                            let scalar_type = scalar_type_from_catalog_inner(
6536                                catalog,
6537                                f.type_reference,
6538                                &f.type_modifiers,
6539                                depth + 1,
6540                                depth_limit,
6541                                budget,
6542                            )?;
6543                            Ok((
6544                                f.name.clone(),
6545                                SqlColumnType {
6546                                    scalar_type,
6547                                    nullable: true,
6548                                },
6549                            ))
6550                        })
6551                        .collect::<Result<Box<_>, PlanError>>()?;
6552                    Ok(SqlScalarType::Record {
6553                        fields: scalars,
6554                        custom_id: Some(id),
6555                    })
6556                }
6557                CatalogType::AclItem => Ok(SqlScalarType::AclItem),
6558                CatalogType::Bool => Ok(SqlScalarType::Bool),
6559                CatalogType::Bytes => Ok(SqlScalarType::Bytes),
6560                CatalogType::Date => Ok(SqlScalarType::Date),
6561                CatalogType::Float32 => Ok(SqlScalarType::Float32),
6562                CatalogType::Float64 => Ok(SqlScalarType::Float64),
6563                CatalogType::Int16 => Ok(SqlScalarType::Int16),
6564                CatalogType::Int32 => Ok(SqlScalarType::Int32),
6565                CatalogType::Int64 => Ok(SqlScalarType::Int64),
6566                CatalogType::UInt16 => Ok(SqlScalarType::UInt16),
6567                CatalogType::UInt32 => Ok(SqlScalarType::UInt32),
6568                CatalogType::UInt64 => Ok(SqlScalarType::UInt64),
6569                CatalogType::MzTimestamp => Ok(SqlScalarType::MzTimestamp),
6570                CatalogType::Interval => Ok(SqlScalarType::Interval),
6571                CatalogType::Jsonb => Ok(SqlScalarType::Jsonb),
6572                CatalogType::Oid => Ok(SqlScalarType::Oid),
6573                CatalogType::PgLegacyChar => Ok(SqlScalarType::PgLegacyChar),
6574                CatalogType::PgLegacyName => Ok(SqlScalarType::PgLegacyName),
6575                CatalogType::Pseudo => {
6576                    sql_bail!(
6577                        "cannot reference pseudo type {}",
6578                        catalog.resolve_full_name(entry.name()).to_string()
6579                    )
6580                }
6581                CatalogType::RegClass => Ok(SqlScalarType::RegClass),
6582                CatalogType::RegProc => Ok(SqlScalarType::RegProc),
6583                CatalogType::RegType => Ok(SqlScalarType::RegType),
6584                CatalogType::String => Ok(SqlScalarType::String),
6585                CatalogType::Time => Ok(SqlScalarType::Time),
6586                CatalogType::Uuid => Ok(SqlScalarType::Uuid),
6587                CatalogType::Int2Vector => Ok(SqlScalarType::Int2Vector),
6588                CatalogType::MzAclItem => Ok(SqlScalarType::MzAclItem),
6589                CatalogType::Numeric => unreachable!("handled above"),
6590                CatalogType::Char => unreachable!("handled above"),
6591                CatalogType::VarChar => unreachable!("handled above"),
6592                CatalogType::Timestamp => unreachable!("handled above"),
6593                CatalogType::TimestampTz => unreachable!("handled above"),
6594            }
6595        }
6596    }
6597}
6598
6599/// This is used to collect aggregates and table functions from within an `Expr`.
6600/// See the explanation of aggregate handling at the top of the file for more details.
6601struct AggregateTableFuncVisitor<'a> {
6602    scx: &'a StatementContext<'a>,
6603    aggs: Vec<Function<Aug>>,
6604    within_aggregate: bool,
6605    tables: BTreeMap<Function<Aug>, String>,
6606    table_disallowed_context: Vec<&'static str>,
6607    in_select_item: bool,
6608    id_gen: IdGen,
6609    err: Option<PlanError>,
6610}
6611
6612impl<'a> AggregateTableFuncVisitor<'a> {
6613    fn new(scx: &'a StatementContext<'a>) -> AggregateTableFuncVisitor<'a> {
6614        AggregateTableFuncVisitor {
6615            scx,
6616            aggs: Vec::new(),
6617            within_aggregate: false,
6618            tables: BTreeMap::new(),
6619            table_disallowed_context: Vec::new(),
6620            in_select_item: false,
6621            id_gen: Default::default(),
6622            err: None,
6623        }
6624    }
6625
6626    fn into_result(
6627        self,
6628    ) -> Result<(Vec<Function<Aug>>, BTreeMap<Function<Aug>, String>), PlanError> {
6629        match self.err {
6630            Some(err) => Err(err),
6631            None => {
6632                // Dedup while preserving the order. We don't care what the order is, but it
6633                // has to be reproducible so that EXPLAIN PLAN tests work.
6634                let mut seen = BTreeSet::new();
6635                let aggs = self
6636                    .aggs
6637                    .into_iter()
6638                    .filter(move |agg| seen.insert(agg.clone()))
6639                    .collect();
6640                Ok((aggs, self.tables))
6641            }
6642        }
6643    }
6644}
6645
6646impl<'a> VisitMut<'_, Aug> for AggregateTableFuncVisitor<'a> {
6647    fn visit_function_mut(&mut self, func: &mut Function<Aug>) {
6648        let item = match self.scx.get_item_by_resolved_name(&func.name) {
6649            Ok(i) => i,
6650            // Catching missing functions later in planning improves error messages.
6651            Err(_) => return,
6652        };
6653
6654        match item.func() {
6655            // We don't want to collect window aggregations, because these will be handled not by
6656            // plan_aggregate, but by plan_function.
6657            Ok(Func::Aggregate { .. }) if func.over.is_none() => {
6658                if self.within_aggregate {
6659                    self.err = Some(sql_err!("nested aggregate functions are not allowed",));
6660                    return;
6661                }
6662                self.aggs.push(func.clone());
6663                let Function {
6664                    name: _,
6665                    args,
6666                    filter,
6667                    over: _,
6668                    distinct: _,
6669                } = func;
6670                if let Some(filter) = filter {
6671                    self.visit_expr_mut(filter);
6672                }
6673                let old_within_aggregate = self.within_aggregate;
6674                self.within_aggregate = true;
6675                self.table_disallowed_context
6676                    .push("aggregate function calls");
6677
6678                self.visit_function_args_mut(args);
6679
6680                self.within_aggregate = old_within_aggregate;
6681                self.table_disallowed_context.pop();
6682            }
6683            Ok(Func::Table { .. }) => {
6684                self.table_disallowed_context.push("other table functions");
6685                visit_mut::visit_function_mut(self, func);
6686                self.table_disallowed_context.pop();
6687            }
6688            _ => visit_mut::visit_function_mut(self, func),
6689        }
6690    }
6691
6692    fn visit_query_mut(&mut self, _query: &mut Query<Aug>) {
6693        // Don't go into subqueries.
6694    }
6695
6696    fn visit_expr_mut(&mut self, expr: &mut Expr<Aug>) {
6697        let (disallowed_context, func) = match expr {
6698            Expr::Case { .. } => (Some("CASE"), None),
6699            Expr::HomogenizingFunction {
6700                function: HomogenizingFunction::Coalesce,
6701                ..
6702            } => (Some("COALESCE"), None),
6703            Expr::Function(func) if self.in_select_item => {
6704                // If we're in a SELECT list, replace table functions with a uuid identifier
6705                // and save the table func so it can be planned elsewhere.
6706                let mut table_func = None;
6707                if let Ok(item) = self.scx.get_item_by_resolved_name(&func.name) {
6708                    if let Ok(Func::Table { .. }) = item.func() {
6709                        if let Some(context) = self.table_disallowed_context.last() {
6710                            self.err = Some(sql_err!(
6711                                "table functions are not allowed in {} (function {})",
6712                                context,
6713                                func.name
6714                            ));
6715                            return;
6716                        }
6717                        table_func = Some(func.clone());
6718                    }
6719                }
6720                // Since we will descend into the table func below, don't add its own disallow
6721                // context here, instead use visit_function to set that.
6722                (None, table_func)
6723            }
6724            _ => (None, None),
6725        };
6726        if let Some(func) = func {
6727            // Since we are trading out expr, we need to visit the table func here.
6728            visit_mut::visit_expr_mut(self, expr);
6729            // Don't attempt to replace table functions with unsupported syntax.
6730            if let Function {
6731                name: _,
6732                args: _,
6733                filter: None,
6734                over: None,
6735                distinct: false,
6736            } = &func
6737            {
6738                // Identical table functions can be de-duplicated.
6739                let unique_id = self.id_gen.allocate_id();
6740                let id = self
6741                    .tables
6742                    .entry(func)
6743                    .or_insert_with(|| format!("table_func_{unique_id}"));
6744                // We know this is okay because id is is 11 characters + <=20 characters, which is
6745                // less than our max length.
6746                *expr = Expr::Identifier(vec![Ident::new_unchecked(id.clone())]);
6747            }
6748        }
6749        if let Some(context) = disallowed_context {
6750            self.table_disallowed_context.push(context);
6751        }
6752
6753        visit_mut::visit_expr_mut(self, expr);
6754
6755        if disallowed_context.is_some() {
6756            self.table_disallowed_context.pop();
6757        }
6758    }
6759
6760    fn visit_select_item_mut(&mut self, si: &mut SelectItem<Aug>) {
6761        let old = self.in_select_item;
6762        self.in_select_item = true;
6763        visit_mut::visit_select_item_mut(self, si);
6764        self.in_select_item = old;
6765    }
6766}
6767
6768#[derive(Default)]
6769struct WindowFuncCollector {
6770    window_funcs: Vec<Expr<Aug>>,
6771}
6772
6773impl WindowFuncCollector {
6774    fn into_result(self) -> Vec<Expr<Aug>> {
6775        // Dedup while preserving the order.
6776        let mut seen = BTreeSet::new();
6777        let window_funcs_dedupped = self
6778            .window_funcs
6779            .into_iter()
6780            .filter(move |expr| seen.insert(expr.clone()))
6781            // Reverse the order, so that in case of a nested window function call, the
6782            // inner one is evaluated first.
6783            .rev()
6784            .collect();
6785        window_funcs_dedupped
6786    }
6787}
6788
6789impl Visit<'_, Aug> for WindowFuncCollector {
6790    fn visit_expr(&mut self, expr: &Expr<Aug>) {
6791        match expr {
6792            Expr::Function(func) => {
6793                if func.over.is_some() {
6794                    self.window_funcs.push(expr.clone());
6795                }
6796            }
6797            _ => (),
6798        }
6799        visit::visit_expr(self, expr);
6800    }
6801
6802    fn visit_query(&mut self, _query: &Query<Aug>) {
6803        // Don't go into subqueries. Those will be handled by their own `plan_query`.
6804    }
6805}
6806
6807/// Specifies how long a query will live.
6808#[derive(Debug, Eq, PartialEq, Copy, Clone)]
6809pub enum QueryLifetime {
6810    /// The query's (or the expression's) result will be computed at one point in time.
6811    OneShot,
6812    /// The query (or expression) is used in a dataflow that maintains an index.
6813    Index,
6814    /// The query (or expression) is used in a dataflow that maintains a materialized view.
6815    MaterializedView,
6816    /// The query (or expression) is used in a dataflow that maintains a SUBSCRIBE.
6817    Subscribe,
6818    /// The query (or expression) is part of a (non-materialized) view.
6819    View,
6820    /// The expression is part of a source definition.
6821    Source,
6822}
6823
6824impl QueryLifetime {
6825    /// (This used to impact whether the query is allowed to reason about the time at which it is
6826    /// running, e.g., by calling the `now()` function. Nowadays, this is decided by a different
6827    /// mechanism, see `ExprPrepStyle`.)
6828    pub fn is_one_shot(&self) -> bool {
6829        let result = match self {
6830            QueryLifetime::OneShot => true,
6831            QueryLifetime::Index => false,
6832            QueryLifetime::MaterializedView => false,
6833            QueryLifetime::Subscribe => false,
6834            QueryLifetime::View => false,
6835            QueryLifetime::Source => false,
6836        };
6837        assert_eq!(!result, self.is_maintained());
6838        result
6839    }
6840
6841    /// Maintained dataflows can't have a finishing applied directly. Therefore, the finishing is
6842    /// turned into a `TopK`.
6843    pub fn is_maintained(&self) -> bool {
6844        match self {
6845            QueryLifetime::OneShot => false,
6846            QueryLifetime::Index => true,
6847            QueryLifetime::MaterializedView => true,
6848            QueryLifetime::Subscribe => true,
6849            QueryLifetime::View => true,
6850            QueryLifetime::Source => true,
6851        }
6852    }
6853
6854    /// Most maintained dataflows don't allow SHOW commands currently. However, SUBSCRIBE does.
6855    pub fn allow_show(&self) -> bool {
6856        match self {
6857            QueryLifetime::OneShot => true,
6858            QueryLifetime::Index => false,
6859            QueryLifetime::MaterializedView => false,
6860            QueryLifetime::Subscribe => true, // SUBSCRIBE allows SHOW commands!
6861            QueryLifetime::View => false,
6862            QueryLifetime::Source => false,
6863        }
6864    }
6865}
6866
6867/// Description of a CTE sufficient for query planning.
6868#[derive(Debug, Clone)]
6869pub struct CteDesc {
6870    pub name: String,
6871    pub desc: RelationDesc,
6872}
6873
6874/// The state required when planning a `Query`.
6875#[derive(Debug, Clone)]
6876pub struct QueryContext<'a> {
6877    /// The context for the containing `Statement`.
6878    pub scx: &'a StatementContext<'a>,
6879    /// The lifetime that the planned query will have.
6880    pub lifetime: QueryLifetime,
6881    /// The scopes of the outer relation expression.
6882    pub outer_scopes: Vec<Scope>,
6883    /// The type of the outer relation expressions.
6884    pub outer_relation_types: Vec<SqlRelationType>,
6885    /// CTEs for this query, mapping their assigned LocalIds to their definition.
6886    pub ctes: BTreeMap<LocalId, CteDesc>,
6887    /// A name manager, for interning column names that will be stored in HIR and MIR.
6888    pub name_manager: Rc<RefCell<NameManager>>,
6889    pub recursion_guard: RecursionGuard,
6890}
6891
6892impl CheckedRecursion for QueryContext<'_> {
6893    fn recursion_guard(&self) -> &RecursionGuard {
6894        &self.recursion_guard
6895    }
6896}
6897
6898impl<'a> QueryContext<'a> {
6899    pub fn root(scx: &'a StatementContext, lifetime: QueryLifetime) -> QueryContext<'a> {
6900        QueryContext {
6901            scx,
6902            lifetime,
6903            outer_scopes: vec![],
6904            outer_relation_types: vec![],
6905            ctes: BTreeMap::new(),
6906            name_manager: Rc::new(RefCell::new(NameManager::new())),
6907            recursion_guard: RecursionGuard::with_limit(1024), // chosen arbitrarily
6908        }
6909    }
6910
6911    fn relation_type(&self, expr: &HirRelationExpr) -> SqlRelationType {
6912        expr.typ(&self.outer_relation_types, &self.scx.param_types.borrow())
6913    }
6914
6915    /// Generate a new `QueryContext` appropriate to be used in subqueries of
6916    /// `self`.
6917    fn derived_context(&self, scope: Scope, relation_type: SqlRelationType) -> QueryContext<'a> {
6918        let ctes = self.ctes.clone();
6919        let outer_scopes = iter::once(scope).chain(self.outer_scopes.clone()).collect();
6920        let outer_relation_types = iter::once(relation_type)
6921            .chain(self.outer_relation_types.clone())
6922            .collect();
6923        // These shenanigans are simpler than adding `&mut NameManager` arguments everywhere.
6924        let name_manager = Rc::clone(&self.name_manager);
6925
6926        QueryContext {
6927            scx: self.scx,
6928            lifetime: self.lifetime,
6929            outer_scopes,
6930            outer_relation_types,
6931            ctes,
6932            name_manager,
6933            recursion_guard: self.recursion_guard.clone(),
6934        }
6935    }
6936
6937    /// Derives a `QueryContext` for a scope that contains no columns.
6938    fn empty_derived_context(&self) -> QueryContext<'a> {
6939        let scope = Scope::empty();
6940        let ty = SqlRelationType::empty();
6941        self.derived_context(scope, ty)
6942    }
6943
6944    /// Resolves `object` to a table expr, i.e. creating a `Get` or inlining a
6945    /// CTE.
6946    pub fn resolve_table_name(
6947        &self,
6948        object: ResolvedItemName,
6949    ) -> Result<(HirRelationExpr, Scope), PlanError> {
6950        match object {
6951            ResolvedItemName::Item {
6952                id,
6953                full_name,
6954                version,
6955                ..
6956            } => {
6957                let item = self.scx.get_item(&id).at_version(version);
6958                let desc = match item.relation_desc() {
6959                    Some(desc) => desc.clone(),
6960                    None => {
6961                        return Err(PlanError::InvalidDependency {
6962                            name: full_name.to_string(),
6963                            item_type: item.item_type().to_string(),
6964                        });
6965                    }
6966                };
6967                let expr = HirRelationExpr::Get {
6968                    id: Id::Global(item.global_id()),
6969                    typ: desc.typ().clone(),
6970                };
6971
6972                let name = full_name.into();
6973                let scope = Scope::from_source(Some(name), desc.iter_names().cloned());
6974
6975                Ok((expr, scope))
6976            }
6977            ResolvedItemName::Cte { id, name } => {
6978                let name = name.into();
6979                let cte = self.ctes.get(&id).unwrap();
6980                let expr = HirRelationExpr::Get {
6981                    id: Id::Local(id),
6982                    typ: cte.desc.typ().clone(),
6983                };
6984
6985                let scope = Scope::from_source(Some(name), cte.desc.iter_names());
6986
6987                Ok((expr, scope))
6988            }
6989            ResolvedItemName::Error => bail_internal!("should have been caught in name resolution"),
6990        }
6991    }
6992
6993    /// The returned String is more detailed when the `postgres_compat` flag is not set. However,
6994    /// the flag should be set in, e.g., the implementation of the `pg_typeof` function.
6995    pub fn humanize_sql_scalar_type(&self, typ: &SqlScalarType, postgres_compat: bool) -> String {
6996        self.scx.humanize_sql_scalar_type(typ, postgres_compat)
6997    }
6998}
6999
7000/// A bundle of unrelated things that we need for planning `Expr`s.
7001#[derive(Debug, Clone)]
7002pub struct ExprContext<'a> {
7003    pub qcx: &'a QueryContext<'a>,
7004    /// The name of this kind of expression eg "WHERE clause". Used only for error messages.
7005    pub name: &'a str,
7006    /// The context for the `Query` that contains this `Expr`.
7007    /// The current scope.
7008    pub scope: &'a Scope,
7009    /// The type of the current relation expression upon which this scalar
7010    /// expression will be evaluated.
7011    pub relation_type: &'a SqlRelationType,
7012    /// Are aggregate functions allowed in this context
7013    pub allow_aggregates: bool,
7014    /// Are subqueries allowed in this context
7015    pub allow_subqueries: bool,
7016    /// Are parameters allowed in this context.
7017    pub allow_parameters: bool,
7018    /// Are window functions allowed in this context
7019    pub allow_windows: bool,
7020}
7021
7022impl CheckedRecursion for ExprContext<'_> {
7023    fn recursion_guard(&self) -> &RecursionGuard {
7024        &self.qcx.recursion_guard
7025    }
7026}
7027
7028impl<'a> ExprContext<'a> {
7029    pub fn catalog(&self) -> &dyn SessionCatalog {
7030        self.qcx.scx.catalog
7031    }
7032
7033    pub fn with_name(&self, name: &'a str) -> ExprContext<'a> {
7034        let mut ecx = self.clone();
7035        ecx.name = name;
7036        ecx
7037    }
7038
7039    pub fn column_type<E>(&self, expr: &E) -> E::Type
7040    where
7041        E: AbstractExpr,
7042    {
7043        expr.typ(
7044            &self.qcx.outer_relation_types,
7045            self.relation_type,
7046            &self.qcx.scx.param_types.borrow(),
7047        )
7048    }
7049
7050    pub fn scalar_type<E>(&self, expr: &E) -> <E::Type as AbstractColumnType>::AbstractScalarType
7051    where
7052        E: AbstractExpr,
7053    {
7054        self.column_type(expr).scalar_type()
7055    }
7056
7057    fn derived_query_context(&self) -> QueryContext<'_> {
7058        let mut scope = self.scope.clone();
7059        scope.lateral_barrier = true;
7060        self.qcx.derived_context(scope, self.relation_type.clone())
7061    }
7062
7063    pub fn require_feature_flag(&self, flag: &'static FeatureFlag) -> Result<(), PlanError> {
7064        self.qcx.scx.require_feature_flag(flag)
7065    }
7066
7067    pub fn param_types(&self) -> &RefCell<BTreeMap<usize, SqlScalarType>> {
7068        &self.qcx.scx.param_types
7069    }
7070
7071    /// The returned String is more detailed when the `postgres_compat` flag is not set. However,
7072    /// the flag should be set in, e.g., the implementation of the `pg_typeof` function.
7073    pub fn humanize_sql_scalar_type(&self, typ: &SqlScalarType, postgres_compat: bool) -> String {
7074        self.qcx.scx.humanize_sql_scalar_type(typ, postgres_compat)
7075    }
7076
7077    pub fn intern(&self, item: &ScopeItem) -> Arc<str> {
7078        self.qcx.name_manager.borrow_mut().intern_scope_item(item)
7079    }
7080}
7081
7082/// Manages column names, doing lightweight string internment.
7083///
7084/// Names are stored in `HirScalarExpr` and `MirScalarExpr` using
7085/// `Option<Arc<str>>`; we use the `NameManager` when lowering from SQL to HIR
7086/// to ensure maximal sharing.
7087#[derive(Debug, Clone)]
7088pub struct NameManager(BTreeSet<Arc<str>>);
7089
7090impl NameManager {
7091    /// Creates a new `NameManager`, with no interned names
7092    pub fn new() -> Self {
7093        Self(BTreeSet::new())
7094    }
7095
7096    /// Interns a string, returning a reference-counted pointer to the interned
7097    /// string.
7098    fn intern<S: AsRef<str>>(&mut self, s: S) -> Arc<str> {
7099        let s = s.as_ref();
7100        if let Some(interned) = self.0.get(s) {
7101            Arc::clone(interned)
7102        } else {
7103            let interned: Arc<str> = Arc::from(s);
7104            self.0.insert(Arc::clone(&interned));
7105            interned
7106        }
7107    }
7108
7109    /// Interns a string representing a reference to a `ScopeItem`, returning a
7110    /// reference-counted pointer to the interned string.
7111    pub fn intern_scope_item(&mut self, item: &ScopeItem) -> Arc<str> {
7112        // TODO(mgree): extracting the table name from `item` leads to an issue with the catalog
7113        //
7114        // After an `ALTER ... RENAME` on a table, the catalog will have out-of-date
7115        // name information. Note that as of 2025-04-09, we don't support column
7116        // renames.
7117        //
7118        // A few bad alternatives:
7119        //
7120        // (1) Store it but don't write it down. This fails because the expression
7121        //     cache will erase our names on restart.
7122        // (2) When `ALTER ... RENAME` is run, re-optimize all downstream objects to
7123        //     get the right names. But the world now and the world when we made
7124        //     those objects may be different.
7125        // (3) Just don't write down the table name. Nothing fails... for now.
7126
7127        self.intern(item.column_name.as_str())
7128    }
7129}
7130
7131#[cfg(test)]
7132mod test {
7133    use super::*;
7134
7135    /// Ensure that `NameManager`'s string interning works as expected.
7136    ///
7137    /// In particular, structurally but not referentially identical strings should
7138    /// be interned to the same `Arc`ed pointer.
7139    #[mz_ore::test]
7140    pub fn test_name_manager_string_interning() {
7141        let mut nm = NameManager::new();
7142
7143        let orig_hi = "hi";
7144        let hi = nm.intern(orig_hi);
7145        let hello = nm.intern("hello");
7146
7147        assert_ne!(hi.as_ptr(), hello.as_ptr());
7148
7149        // this static string is _likely_ the same as `orig_hi``
7150        let hi2 = nm.intern("hi");
7151        assert_eq!(hi.as_ptr(), hi2.as_ptr());
7152
7153        // generate a "hi" string that doesn't get optimized to the same static string
7154        let s = format!(
7155            "{}{}",
7156            hi.chars().nth(0).unwrap(),
7157            hi2.chars().nth(1).unwrap()
7158        );
7159        // make sure that we're testing with a fresh string!
7160        assert_ne!(orig_hi.as_ptr(), s.as_ptr());
7161
7162        let hi3 = nm.intern(s);
7163        assert_eq!(hi.as_ptr(), hi3.as_ptr());
7164    }
7165}