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