Skip to main content

mz_sql/plan/statement/
dml.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//! Data manipulation language (DML).
11//!
12//! This module houses the handlers for statements that manipulate data, like
13//! `INSERT`, `SELECT`, `SUBSCRIBE`, and `COPY`.
14
15use std::borrow::Cow;
16use std::collections::{BTreeMap, BTreeSet};
17
18use itertools::Itertools;
19use mz_arrow_util::builder::ArrowBuilder;
20use mz_expr::{ColumnOrder, RowSetFinishing};
21use mz_ore::error::ErrorExt;
22use mz_ore::num::NonNeg;
23use mz_ore::soft_panic_or_log;
24use mz_ore::str::separated;
25use mz_pgcopy::{CopyCsvFormatParams, CopyFormatParams, CopyTextFormatParams};
26use mz_repr::adt::numeric::NumericMaxScale;
27use mz_repr::bytes::ByteSize;
28use mz_repr::explain::{ExplainConfig, ExplainFormat};
29use mz_repr::optimize::OptimizerFeatureOverrides;
30use mz_repr::{CatalogItemId, Datum, RelationDesc, Row, SqlRelationType, SqlScalarType};
31use mz_sql_parser::ast::{
32    CteBlock, ExplainAnalyzeClusterStatement, ExplainAnalyzeComputationProperties,
33    ExplainAnalyzeComputationProperty, ExplainAnalyzeObjectStatement, ExplainAnalyzeProperty,
34    ExplainPlanOption, ExplainPlanOptionName, ExplainPushdownStatement, ExplainSinkSchemaFor,
35    ExplainSinkSchemaStatement, ExplainTimestampStatement, Expr, IfExistsBehavior, OrderByExpr,
36    SetExpr, SubscribeOutput, UnresolvedItemName,
37};
38use mz_sql_parser::ident;
39use mz_storage_types::sinks::{
40    KafkaSinkConnection, KafkaSinkFormat, KafkaSinkFormatType, MAX_S3_SINK_FILE_SIZE,
41    MIN_S3_SINK_FILE_SIZE, S3SinkFormat, StorageSinkConnection,
42};
43
44use crate::ast::display::{AstDisplay, escaped_string_literal};
45use crate::ast::{
46    AstInfo, CopyDirection, CopyOption, CopyOptionName, CopyRelation, CopyStatement, CopyTarget,
47    DeleteStatement, ExplainPlanStatement, ExplainStage, Explainee, Ident, InsertStatement, Query,
48    SelectStatement, SubscribeOption, SubscribeOptionName, SubscribeRelation, SubscribeStatement,
49    UpdateStatement,
50};
51use crate::catalog::CatalogItemType;
52use crate::names::{Aug, ResolvedItemName};
53use crate::normalize;
54use crate::plan::query::{
55    ExprContext, QueryLifetime, negative_offset_error, offset_into_value, plan_as_of_or_up_to,
56    plan_expr,
57};
58use crate::plan::scope::Scope;
59use crate::plan::statement::show::ShowSelect;
60use crate::plan::statement::{StatementContext, StatementDesc, ddl};
61use crate::plan::{
62    self, CopyFromFilter, CopyToPlan, CreateSinkPlan, ExplainPushdownPlan, ExplainSinkSchemaPlan,
63    ExplainTimestampPlan, HirRelationExpr, side_effecting_func, transform_ast,
64};
65use crate::plan::{
66    CopyFormat, CopyFromPlan, ExplainPlanPlan, InsertPlan, MutationKind, Params, Plan, PlanError,
67    QueryContext, ReadThenWritePlan, SelectPlan, SubscribeFrom, SubscribePlan, query,
68};
69use crate::plan::{CopyFromSource, with_options};
70use crate::session::vars::{self, DISALLOW_UNMATERIALIZABLE_FUNCTIONS_AS_OF};
71
72// TODO(benesch): currently, describing a `SELECT` or `INSERT` query
73// plans the whole query to determine its shape and parameter types,
74// and then throws away that plan. If we were smarter, we'd stash that
75// plan somewhere so we don't have to recompute it when the query is
76// executed.
77
78pub fn describe_insert(
79    scx: &StatementContext,
80    InsertStatement {
81        table_name,
82        columns,
83        source,
84        returning,
85    }: InsertStatement<Aug>,
86) -> Result<StatementDesc, PlanError> {
87    let (_, _, returning) = query::plan_insert_query(scx, table_name, columns, source, returning)?;
88    let desc = if returning.expr.is_empty() {
89        None
90    } else {
91        Some(returning.desc)
92    };
93    Ok(StatementDesc::new(desc))
94}
95
96pub fn plan_insert(
97    scx: &StatementContext,
98    InsertStatement {
99        table_name,
100        columns,
101        source,
102        returning,
103    }: InsertStatement<Aug>,
104    params: &Params,
105) -> Result<Plan, PlanError> {
106    let (id, mut expr, returning) =
107        query::plan_insert_query(scx, table_name, columns, source, returning)?;
108    expr.bind_parameters_and_simplify_offset(scx, QueryLifetime::OneShot, params)?;
109    let returning = returning
110        .expr
111        .into_iter()
112        .map(|mut expr| {
113            expr.bind_parameters_and_simplify_offset(scx, QueryLifetime::OneShot, params)?;
114            expr.lower_uncorrelated(scx.catalog.system_vars())
115        })
116        .collect::<Result<Vec<_>, _>>()?;
117    // `RETURNING` is evaluated in `environmentd`.
118    if let Some(func) = returning.iter().find_map(|e| e.unbounded_func()) {
119        bail_unsupported!(format!(
120            "{} in a RETURNING clause",
121            mz_expr::func_for_error(func)
122        ));
123    }
124
125    Ok(Plan::Insert(InsertPlan {
126        id,
127        values: expr,
128        returning,
129    }))
130}
131
132pub fn describe_delete(
133    scx: &StatementContext,
134    stmt: DeleteStatement<Aug>,
135) -> Result<StatementDesc, PlanError> {
136    query::plan_delete_query(scx, stmt)?;
137    Ok(StatementDesc::new(None))
138}
139
140pub fn plan_delete(
141    scx: &StatementContext,
142    stmt: DeleteStatement<Aug>,
143    params: &Params,
144) -> Result<Plan, PlanError> {
145    let rtw_plan = query::plan_delete_query(scx, stmt)?;
146    plan_read_then_write(scx, MutationKind::Delete, params, rtw_plan)
147}
148
149pub fn describe_update(
150    scx: &StatementContext,
151    stmt: UpdateStatement<Aug>,
152) -> Result<StatementDesc, PlanError> {
153    query::plan_update_query(scx, stmt)?;
154    Ok(StatementDesc::new(None))
155}
156
157pub fn plan_update(
158    scx: &StatementContext,
159    stmt: UpdateStatement<Aug>,
160    params: &Params,
161) -> Result<Plan, PlanError> {
162    let rtw_plan = query::plan_update_query(scx, stmt)?;
163    plan_read_then_write(scx, MutationKind::Update, params, rtw_plan)
164}
165
166pub fn plan_read_then_write(
167    scx: &StatementContext,
168    kind: MutationKind,
169    params: &Params,
170    query::ReadThenWritePlan {
171        id,
172        mut selection,
173        finishing,
174        assignments,
175    }: query::ReadThenWritePlan,
176) -> Result<Plan, PlanError> {
177    selection.bind_parameters_and_simplify_offset(scx, QueryLifetime::OneShot, params)?;
178    let mut assignments_outer = BTreeMap::new();
179    for (idx, mut set) in assignments {
180        set.bind_parameters_and_simplify_offset(scx, QueryLifetime::OneShot, params)?;
181        let set = set.lower_uncorrelated(scx.catalog.system_vars())?;
182        assignments_outer.insert(idx, set);
183    }
184
185    Ok(Plan::ReadThenWrite(ReadThenWritePlan {
186        id,
187        selection,
188        finishing,
189        assignments: assignments_outer,
190        kind,
191        returning: Vec::new(),
192    }))
193}
194
195pub fn describe_select(
196    scx: &StatementContext,
197    stmt: SelectStatement<Aug>,
198) -> Result<StatementDesc, PlanError> {
199    if let Some(desc) = side_effecting_func::describe_select_if_side_effecting(scx, &stmt)? {
200        return Ok(StatementDesc::new(Some(desc)));
201    }
202
203    let query::PlannedRootQuery { desc, .. } =
204        query::plan_root_query(scx, stmt.query, QueryLifetime::OneShot)?;
205    Ok(StatementDesc::new(Some(desc)))
206}
207
208pub fn plan_select(
209    scx: &StatementContext,
210    select: SelectStatement<Aug>,
211    params: &Params,
212    copy_to: Option<CopyFormat>,
213) -> Result<Plan, PlanError> {
214    if let Some(f) = side_effecting_func::plan_select_if_side_effecting(scx, &select, params)? {
215        return Ok(Plan::SideEffectingFunc(f));
216    }
217
218    let (plan, _desc) = plan_select_inner(scx, select, params, copy_to)?;
219    Ok(Plan::Select(plan))
220}
221
222fn plan_select_inner(
223    scx: &StatementContext,
224    select: SelectStatement<Aug>,
225    params: &Params,
226    copy_to: Option<CopyFormat>,
227) -> Result<(SelectPlan, RelationDesc), PlanError> {
228    let when = query::plan_as_of(scx, select.as_of.clone())?;
229    let lifetime = QueryLifetime::OneShot;
230    let query::PlannedRootQuery {
231        mut expr,
232        desc,
233        finishing,
234        scope: _,
235    } = query::plan_root_query(scx, select.query.clone(), lifetime)?;
236    expr.bind_parameters_and_simplify_offset(scx, lifetime, params)?;
237
238    // We need to concretize the `limit` and `offset` of the RowSetFinishing, so that we go from
239    // `RowSetFinishing<HirScalarExpr, HirScalarExpr>` to `RowSetFinishing`.
240    // This involves binding parameters and evaluating each expression to a number.
241    // (This should be possible even for `limit` here, because we are at the top level of a SELECT,
242    // so this `limit` has to be a constant.)
243    let limit = match finishing.limit {
244        None => None,
245        Some(mut limit) => {
246            limit.bind_parameters_and_simplify_offset(scx, lifetime, params)?;
247            // Evaluate the expression to a literal instead of matching on a bare literal
248            // node. Parameter binding can leave the bound value wrapped in casts, e.g.
249            // `integer_to_bigint($1)`.
250            match limit
251                .try_into_nullable_literal_int64()
252                .map_err(|err| PlanError::InvalidLimit(err.to_string_with_causes()))?
253            {
254                None => None,
255                Some(v) if v >= 0 => NonNeg::<i64>::try_from(v).ok(),
256                Some(_) => sql_bail!("LIMIT must not be negative"),
257            }
258        }
259    };
260    let offset = {
261        let mut offset = finishing.offset.clone();
262        offset.bind_parameters_and_simplify_offset(scx, lifetime, params)?;
263        let offset = offset_into_value(offset.take())?;
264        offset.try_into().map_err(|_| {
265            // We already checked in bind_parameters_and_simplify_offset / offset_into_value.
266            soft_panic_or_log!("unexpectedly negative OFFSET");
267            negative_offset_error(offset)
268        })?
269    };
270
271    // Unmaterializable functions are evaluated based on various information (e.g., the catalog)
272    // during sequencing, without taking AS OF into account. This would be hard to fix, so for now
273    // we just disallow AS OF when there is an unmaterializable function in a query (except mz_now).
274    if scx.is_feature_flag_enabled(&DISALLOW_UNMATERIALIZABLE_FUNCTIONS_AS_OF)
275        && select.as_of.is_some()
276        && expr.contains_unmaterializable_except_temporal()
277    {
278        bail_unsupported!("unmaterializable function (except `mz_now`) in an AS OF query");
279    }
280
281    let plan = SelectPlan {
282        source: expr,
283        when,
284        finishing: RowSetFinishing {
285            limit,
286            offset,
287            project: finishing.project,
288            order_by: finishing.order_by,
289        },
290        copy_to,
291        select: Some(Box::new(select)),
292    };
293
294    Ok((plan, desc))
295}
296
297pub fn describe_explain_plan(
298    scx: &StatementContext,
299    explain: ExplainPlanStatement<Aug>,
300) -> Result<StatementDesc, PlanError> {
301    let mut relation_desc = RelationDesc::builder();
302
303    match explain.stage() {
304        ExplainStage::RawPlan => {
305            let name = "Raw Plan";
306            relation_desc = relation_desc.with_column(name, SqlScalarType::String.nullable(false));
307        }
308        ExplainStage::DecorrelatedPlan => {
309            let name = "Decorrelated Plan";
310            relation_desc = relation_desc.with_column(name, SqlScalarType::String.nullable(false));
311        }
312        ExplainStage::LocalPlan => {
313            let name = "Locally Optimized Plan";
314            relation_desc = relation_desc.with_column(name, SqlScalarType::String.nullable(false));
315        }
316        ExplainStage::GlobalPlan => {
317            let name = "Optimized Plan";
318            relation_desc = relation_desc.with_column(name, SqlScalarType::String.nullable(false));
319        }
320        ExplainStage::PhysicalPlan => {
321            let name = "Physical Plan";
322            relation_desc = relation_desc.with_column(name, SqlScalarType::String.nullable(false));
323        }
324        ExplainStage::Trace => {
325            relation_desc = relation_desc
326                .with_column("Time", SqlScalarType::UInt64.nullable(false))
327                .with_column("Path", SqlScalarType::String.nullable(false))
328                .with_column("Plan", SqlScalarType::String.nullable(false));
329        }
330        ExplainStage::PlanInsights => {
331            let name = "Plan Insights";
332            relation_desc = relation_desc.with_column(name, SqlScalarType::String.nullable(false));
333        }
334    };
335    let relation_desc = relation_desc.finish();
336
337    Ok(
338        StatementDesc::new(Some(relation_desc)).with_params(match explain.explainee {
339            Explainee::Select(select, _) => describe_select(scx, *select)?.param_types,
340            _ => vec![],
341        }),
342    )
343}
344
345pub fn describe_explain_pushdown(
346    scx: &StatementContext,
347    statement: ExplainPushdownStatement<Aug>,
348) -> Result<StatementDesc, PlanError> {
349    let relation_desc = RelationDesc::builder()
350        .with_column("Source", SqlScalarType::String.nullable(false))
351        .with_column("Total Bytes", SqlScalarType::UInt64.nullable(false))
352        .with_column("Selected Bytes", SqlScalarType::UInt64.nullable(false))
353        .with_column("Total Parts", SqlScalarType::UInt64.nullable(false))
354        .with_column("Selected Parts", SqlScalarType::UInt64.nullable(false))
355        .finish();
356
357    Ok(
358        StatementDesc::new(Some(relation_desc)).with_params(match statement.explainee {
359            Explainee::Select(select, _) => describe_select(scx, *select)?.param_types,
360            _ => vec![],
361        }),
362    )
363}
364
365pub fn describe_explain_analyze_object(
366    _scx: &StatementContext,
367    statement: ExplainAnalyzeObjectStatement<Aug>,
368) -> Result<StatementDesc, PlanError> {
369    if statement.as_sql {
370        let relation_desc = RelationDesc::builder()
371            .with_column("SQL", SqlScalarType::String.nullable(false))
372            .finish();
373        return Ok(StatementDesc::new(Some(relation_desc)));
374    }
375
376    match statement.properties {
377        ExplainAnalyzeProperty::Computation(ExplainAnalyzeComputationProperties {
378            properties,
379            skew,
380        }) => {
381            let mut relation_desc = RelationDesc::builder()
382                .with_column("operator", SqlScalarType::String.nullable(false));
383
384            if skew {
385                relation_desc =
386                    relation_desc.with_column("worker_id", SqlScalarType::UInt64.nullable(true));
387            }
388
389            let mut seen_properties = BTreeSet::new();
390            for property in properties {
391                // handle each property only once (belt and suspenders)
392                if !seen_properties.insert(property) {
393                    continue;
394                }
395
396                match property {
397                    ExplainAnalyzeComputationProperty::Memory if skew => {
398                        let numeric = SqlScalarType::Numeric { max_scale: None }.nullable(true);
399                        relation_desc = relation_desc
400                            .with_column("memory_ratio", numeric.clone())
401                            .with_column("worker_memory", SqlScalarType::String.nullable(true))
402                            .with_column("avg_memory", SqlScalarType::String.nullable(true))
403                            .with_column("total_memory", SqlScalarType::String.nullable(true))
404                            .with_column("records_ratio", numeric.clone())
405                            .with_column("worker_records", numeric.clone())
406                            .with_column("avg_records", numeric.clone())
407                            .with_column("total_records", numeric);
408                    }
409                    ExplainAnalyzeComputationProperty::Memory => {
410                        relation_desc = relation_desc
411                            .with_column("total_memory", SqlScalarType::String.nullable(true))
412                            .with_column(
413                                "total_records",
414                                SqlScalarType::Numeric { max_scale: None }.nullable(true),
415                            );
416                    }
417                    ExplainAnalyzeComputationProperty::Cpu => {
418                        if skew {
419                            relation_desc = relation_desc
420                                .with_column(
421                                    "cpu_ratio",
422                                    SqlScalarType::Numeric { max_scale: None }.nullable(true),
423                                )
424                                .with_column(
425                                    "worker_elapsed",
426                                    SqlScalarType::Interval.nullable(true),
427                                )
428                                .with_column("avg_elapsed", SqlScalarType::Interval.nullable(true));
429                        }
430                        relation_desc = relation_desc
431                            .with_column("total_elapsed", SqlScalarType::Interval.nullable(true));
432                    }
433                }
434            }
435
436            let relation_desc = relation_desc.finish();
437            Ok(StatementDesc::new(Some(relation_desc)))
438        }
439        ExplainAnalyzeProperty::Hints => {
440            let relation_desc = RelationDesc::builder()
441                .with_column("operator", SqlScalarType::String.nullable(true))
442                .with_column("levels", SqlScalarType::Int64.nullable(true))
443                .with_column("to_cut", SqlScalarType::Int64.nullable(true))
444                .with_column("hint", SqlScalarType::Float64.nullable(true))
445                .with_column("savings", SqlScalarType::String.nullable(true))
446                .finish();
447            Ok(StatementDesc::new(Some(relation_desc)))
448        }
449    }
450}
451
452pub fn describe_explain_analyze_cluster(
453    _scx: &StatementContext,
454    statement: ExplainAnalyzeClusterStatement,
455) -> Result<StatementDesc, PlanError> {
456    if statement.as_sql {
457        let relation_desc = RelationDesc::builder()
458            .with_column("SQL", SqlScalarType::String.nullable(false))
459            .finish();
460        return Ok(StatementDesc::new(Some(relation_desc)));
461    }
462
463    let ExplainAnalyzeComputationProperties { properties, skew } = statement.properties;
464
465    let mut relation_desc = RelationDesc::builder()
466        .with_column("object", SqlScalarType::String.nullable(false))
467        .with_column("global_id", SqlScalarType::String.nullable(false));
468
469    if skew {
470        relation_desc =
471            relation_desc.with_column("worker_id", SqlScalarType::UInt64.nullable(true));
472    }
473
474    let mut seen_properties = BTreeSet::new();
475    for property in properties {
476        // handle each property only once (belt and suspenders)
477        if !seen_properties.insert(property) {
478            continue;
479        }
480
481        match property {
482            ExplainAnalyzeComputationProperty::Memory if skew => {
483                let numeric = SqlScalarType::Numeric { max_scale: None }.nullable(true);
484                relation_desc = relation_desc
485                    .with_column("max_operator_memory_ratio", numeric.clone())
486                    .with_column("worker_memory", SqlScalarType::String.nullable(true))
487                    .with_column("avg_memory", SqlScalarType::String.nullable(true))
488                    .with_column("total_memory", SqlScalarType::String.nullable(true))
489                    .with_column("max_operator_records_ratio", numeric.clone())
490                    .with_column("worker_records", numeric.clone())
491                    .with_column("avg_records", numeric.clone())
492                    .with_column("total_records", numeric);
493            }
494            ExplainAnalyzeComputationProperty::Memory => {
495                relation_desc = relation_desc
496                    .with_column("total_memory", SqlScalarType::String.nullable(true))
497                    .with_column(
498                        "total_records",
499                        SqlScalarType::Numeric { max_scale: None }.nullable(true),
500                    );
501            }
502            ExplainAnalyzeComputationProperty::Cpu if skew => {
503                relation_desc = relation_desc
504                    .with_column(
505                        "max_operator_cpu_ratio",
506                        SqlScalarType::Numeric { max_scale: None }.nullable(true),
507                    )
508                    .with_column("worker_elapsed", SqlScalarType::Interval.nullable(true))
509                    .with_column("avg_elapsed", SqlScalarType::Interval.nullable(true))
510                    .with_column("total_elapsed", SqlScalarType::Interval.nullable(true));
511            }
512            ExplainAnalyzeComputationProperty::Cpu => {
513                relation_desc = relation_desc
514                    .with_column("total_elapsed", SqlScalarType::Interval.nullable(true));
515            }
516        }
517    }
518
519    Ok(StatementDesc::new(Some(relation_desc.finish())))
520}
521
522pub fn describe_explain_timestamp(
523    scx: &StatementContext,
524    ExplainTimestampStatement { select, .. }: ExplainTimestampStatement<Aug>,
525) -> Result<StatementDesc, PlanError> {
526    let relation_desc = RelationDesc::builder()
527        .with_column("Timestamp", SqlScalarType::String.nullable(false))
528        .finish();
529
530    Ok(StatementDesc::new(Some(relation_desc))
531        .with_params(describe_select(scx, select)?.param_types))
532}
533
534pub fn describe_explain_schema(
535    _: &StatementContext,
536    ExplainSinkSchemaStatement { .. }: ExplainSinkSchemaStatement<Aug>,
537) -> Result<StatementDesc, PlanError> {
538    let relation_desc = RelationDesc::builder()
539        .with_column("Schema", SqlScalarType::String.nullable(false))
540        .finish();
541    Ok(StatementDesc::new(Some(relation_desc)))
542}
543
544// Currently, there are two reasons for why a flag should be `Option<bool>` instead of simply
545// `bool`:
546// - When it's an override of a global feature flag, for example optimizer feature flags. In this
547//   case, we need not just false and true, but also None to say "take the value of the global
548//   flag".
549// - When it's an override of whether SOFT_ASSERTIONS are enabled. For example, when `Arity` is not
550//   explicitly given in the EXPLAIN command, then we'd like staging and prod to default to true,
551//   but otherwise we'd like to default to false.
552generate_extracted_config!(
553    ExplainPlanOption,
554    (Arity, Option<bool>, Default(None)),
555    (Cardinality, bool, Default(false)),
556    (ColumnNames, bool, Default(false)),
557    (FilterPushdown, Option<bool>, Default(None)),
558    (HumanizedExpressions, Option<bool>, Default(None)),
559    (JoinImplementations, bool, Default(false)),
560    (Keys, bool, Default(false)),
561    (LinearChains, bool, Default(false)),
562    (NoFastPath, bool, Default(false)),
563    (NonNegative, bool, Default(false)),
564    (NoNotices, bool, Default(false)),
565    (NodeIdentifiers, bool, Default(false)),
566    (Raw, bool, Default(false)),
567    (RawPlans, bool, Default(false)),
568    (RawSyntax, bool, Default(false)),
569    (Redacted, bool, Default(false)),
570    (SubtreeSize, bool, Default(false)),
571    (Timing, bool, Default(false)),
572    (Types, bool, Default(false)),
573    (Equivalences, bool, Default(false)),
574    (ReoptimizeImportedViews, Option<bool>, Default(None)),
575    (EnableNewOuterJoinLowering, Option<bool>, Default(None)),
576    (EnableEagerDeltaJoins, Option<bool>, Default(None)),
577    (EnableVariadicLeftJoinLowering, Option<bool>, Default(None)),
578    (EnableLetrecFixpointAnalysis, Option<bool>, Default(None)),
579    (EnableJoinPrioritizeArranged, Option<bool>, Default(None)),
580    (
581        EnableProjectionPushdownAfterRelationCse,
582        Option<bool>,
583        Default(None)
584    ),
585    (
586        EnableFixedCorrelatedCteLowering,
587        Option<bool>,
588        Default(None)
589    ),
590    (
591        EnableUnionCancellationAfterRelationCse,
592        Option<bool>,
593        Default(None)
594    )
595);
596
597impl TryFrom<ExplainPlanOptionExtracted> for ExplainConfig {
598    type Error = PlanError;
599
600    fn try_from(mut v: ExplainPlanOptionExtracted) -> Result<Self, Self::Error> {
601        // If `WITH(raw)` is specified, ensure that the config will be as
602        // representative for the original plan as possible.
603        if v.raw {
604            v.raw_plans = true;
605            v.raw_syntax = true;
606        }
607
608        // Certain config should default to be enabled in release builds running on
609        // staging or prod (where SOFT_ASSERTIONS are turned off).
610        let enable_on_prod = !mz_ore::assert::soft_assertions_enabled();
611
612        Ok(ExplainConfig {
613            arity: v.arity.unwrap_or(enable_on_prod),
614            cardinality: v.cardinality,
615            column_names: v.column_names,
616            filter_pushdown: v.filter_pushdown.unwrap_or(enable_on_prod),
617            humanized_exprs: !v.raw_plans && (v.humanized_expressions.unwrap_or(enable_on_prod)),
618            join_impls: v.join_implementations,
619            keys: v.keys,
620            linear_chains: !v.raw_plans && v.linear_chains,
621            no_fast_path: v.no_fast_path,
622            no_notices: v.no_notices,
623            node_ids: v.node_identifiers,
624            non_negative: v.non_negative,
625            raw_plans: v.raw_plans,
626            raw_syntax: v.raw_syntax,
627            verbose_syntax: false,
628            redacted: v.redacted,
629            subtree_size: v.subtree_size,
630            equivalences: v.equivalences,
631            timing: v.timing,
632            types: v.types,
633            // The ones that are initialized with `Default::default()` are not wired up to EXPLAIN.
634            features: OptimizerFeatureOverrides {
635                enable_eager_delta_joins: v.enable_eager_delta_joins,
636                enable_new_outer_join_lowering: v.enable_new_outer_join_lowering,
637                enable_variadic_left_join_lowering: v.enable_variadic_left_join_lowering,
638                enable_letrec_fixpoint_analysis: v.enable_letrec_fixpoint_analysis,
639                enable_reduce_mfp_fusion: Default::default(),
640                enable_cardinality_estimates: Default::default(),
641                persist_fast_path_limit: Default::default(),
642                reoptimize_imported_views: v.reoptimize_imported_views,
643                enable_join_prioritize_arranged: v.enable_join_prioritize_arranged,
644                enable_projection_pushdown_after_relation_cse: v
645                    .enable_projection_pushdown_after_relation_cse,
646                enable_union_cancellation_after_relation_cse: v
647                    .enable_union_cancellation_after_relation_cse,
648                enable_less_reduce_in_eqprop: Default::default(),
649                enable_dequadratic_eqprop_map: Default::default(),
650                enable_eq_classes_withholding_errors: Default::default(),
651                enable_fast_path_plan_insights: Default::default(),
652                enable_cast_elimination: Default::default(),
653                enable_case_literal_transform: Default::default(),
654                enable_simplify_quantified_comparisons: Default::default(),
655                enable_simplify_from_less_existence: Default::default(),
656                enable_coalesce_case_transform: Default::default(),
657                enable_will_distinct_propagation: Default::default(),
658                enable_fixed_correlated_cte_lowering: v.enable_fixed_correlated_cte_lowering,
659            },
660        })
661    }
662}
663
664fn plan_explainee(
665    scx: &StatementContext,
666    explainee: Explainee<Aug>,
667    params: &Params,
668) -> Result<plan::Explainee, PlanError> {
669    use crate::plan::ExplaineeStatement;
670
671    let is_replan = matches!(
672        explainee,
673        Explainee::ReplanView(_) | Explainee::ReplanMaterializedView(_) | Explainee::ReplanIndex(_)
674    );
675
676    let explainee = match explainee {
677        Explainee::View(name) | Explainee::ReplanView(name) => {
678            let item = scx.get_item_by_resolved_name(&name)?;
679            let item_type = item.item_type();
680            if item_type != CatalogItemType::View {
681                sql_bail!("Expected {name} to be a view, not a {item_type}");
682            }
683            match is_replan {
684                true => crate::plan::Explainee::ReplanView(item.id()),
685                false => crate::plan::Explainee::View(item.id()),
686            }
687        }
688        Explainee::MaterializedView(name) | Explainee::ReplanMaterializedView(name) => {
689            let item = scx.get_item_by_resolved_name(&name)?;
690            let item_type = item.item_type();
691            if item_type != CatalogItemType::MaterializedView {
692                sql_bail!("Expected {name} to be a materialized view, not a {item_type}");
693            }
694            match is_replan {
695                true => crate::plan::Explainee::ReplanMaterializedView(item.id()),
696                false => crate::plan::Explainee::MaterializedView(item.id()),
697            }
698        }
699        Explainee::Index(name) | Explainee::ReplanIndex(name) => {
700            let item = scx.get_item_by_resolved_name(&name)?;
701            let item_type = item.item_type();
702            if item_type != CatalogItemType::Index {
703                sql_bail!("Expected {name} to be an index, not a {item_type}");
704            }
705            match is_replan {
706                true => crate::plan::Explainee::ReplanIndex(item.id()),
707                false => crate::plan::Explainee::Index(item.id()),
708            }
709        }
710        Explainee::Select(select, broken) => {
711            let (plan, desc) = plan_select_inner(scx, *select, params, None)?;
712            crate::plan::Explainee::Statement(ExplaineeStatement::Select { broken, plan, desc })
713        }
714        Explainee::CreateView(mut stmt, broken) => {
715            if stmt.if_exists != IfExistsBehavior::Skip {
716                // If we don't force this parameter to Skip planning will
717                // fail for names that already exist in the catalog. This
718                // can happen even in `Replace` mode if the existing item
719                // has dependencies.
720                stmt.if_exists = IfExistsBehavior::Skip;
721            } else {
722                sql_bail!(
723                    "Cannot EXPLAIN a CREATE VIEW that explictly sets IF NOT EXISTS \
724                     (the behavior is implied within the scope of an enclosing EXPLAIN)"
725                );
726            }
727
728            let Plan::CreateView(plan) = ddl::plan_create_view(scx, *stmt)? else {
729                sql_bail!("expected CreateViewPlan plan");
730            };
731
732            crate::plan::Explainee::Statement(ExplaineeStatement::CreateView { broken, plan })
733        }
734        Explainee::CreateMaterializedView(mut stmt, broken) => {
735            if stmt.if_exists != IfExistsBehavior::Skip {
736                // If we don't force this parameter to Skip planning will
737                // fail for names that already exist in the catalog. This
738                // can happen even in `Replace` mode if the existing item
739                // has dependencies.
740                stmt.if_exists = IfExistsBehavior::Skip;
741            } else {
742                sql_bail!(
743                    "Cannot EXPLAIN a CREATE MATERIALIZED VIEW that explictly sets IF NOT EXISTS \
744                     (the behavior is implied within the scope of an enclosing EXPLAIN)"
745                );
746            }
747
748            let Plan::CreateMaterializedView(plan) =
749                ddl::plan_create_materialized_view(scx, *stmt)?
750            else {
751                sql_bail!("expected CreateMaterializedViewPlan plan");
752            };
753
754            crate::plan::Explainee::Statement(ExplaineeStatement::CreateMaterializedView {
755                broken,
756                plan,
757            })
758        }
759        Explainee::CreateIndex(mut stmt, broken) => {
760            if !stmt.if_not_exists {
761                // If we don't force this parameter to true planning will
762                // fail for index items that already exist in the catalog.
763                stmt.if_not_exists = true;
764            } else {
765                sql_bail!(
766                    "Cannot EXPLAIN a CREATE INDEX that explictly sets IF NOT EXISTS \
767                     (the behavior is implied within the scope of an enclosing EXPLAIN)"
768                );
769            }
770
771            let Plan::CreateIndex(plan) = ddl::plan_create_index(scx, *stmt)? else {
772                sql_bail!("expected CreateIndexPlan plan");
773            };
774
775            crate::plan::Explainee::Statement(ExplaineeStatement::CreateIndex { broken, plan })
776        }
777        Explainee::Subscribe(stmt, broken) => {
778            let Plan::Subscribe(plan) = plan_subscribe(scx, *stmt, params, None)? else {
779                sql_bail!("expected SubscribePlan");
780            };
781            crate::plan::Explainee::Statement(ExplaineeStatement::Subscribe { broken, plan })
782        }
783    };
784
785    Ok(explainee)
786}
787
788pub fn plan_explain_plan(
789    scx: &StatementContext,
790    explain: ExplainPlanStatement<Aug>,
791    params: &Params,
792) -> Result<Plan, PlanError> {
793    let (format, verbose_syntax) = match explain.format() {
794        mz_sql_parser::ast::ExplainFormat::Text => (ExplainFormat::Text, false),
795        mz_sql_parser::ast::ExplainFormat::VerboseText => (ExplainFormat::Text, true),
796        mz_sql_parser::ast::ExplainFormat::Json => (ExplainFormat::Json, false),
797        mz_sql_parser::ast::ExplainFormat::Dot => (ExplainFormat::Dot, false),
798    };
799    let stage = explain.stage();
800
801    // Plan ExplainConfig.
802    let mut config = {
803        let mut with_options = ExplainPlanOptionExtracted::try_from(explain.with_options)?;
804
805        if !scx.catalog.system_vars().persist_stats_filter_enabled() {
806            // If filtering is disabled, explain plans should not include pushdown info.
807            with_options.filter_pushdown = Some(false);
808        }
809
810        ExplainConfig::try_from(with_options)?
811    };
812    config.verbose_syntax = verbose_syntax;
813
814    let explainee = plan_explainee(scx, explain.explainee, params)?;
815
816    Ok(Plan::ExplainPlan(ExplainPlanPlan {
817        stage,
818        format,
819        config,
820        explainee,
821    }))
822}
823
824pub fn plan_explain_schema(
825    scx: &StatementContext,
826    explain_schema: ExplainSinkSchemaStatement<Aug>,
827) -> Result<Plan, PlanError> {
828    let ExplainSinkSchemaStatement {
829        schema_for,
830        // Parser limits to JSON.
831        format: _,
832        mut statement,
833    } = explain_schema;
834
835    // Force the sink's name to one that's guaranteed not to exist, by virtue of
836    // being a non-existent item in a schema under the system's control, so that
837    // `plan_create_sink` doesn't complain about the name already existing.
838    statement.name = Some(UnresolvedItemName::qualified(&[
839        ident!("mz_catalog"),
840        ident!("mz_explain_schema"),
841    ]));
842
843    crate::pure::purify_create_sink_avro_doc_on_options(
844        scx.catalog,
845        *statement.from.item_id(),
846        &mut statement.format,
847    )?;
848
849    match ddl::plan_create_sink(scx, statement)? {
850        Plan::CreateSink(CreateSinkPlan { sink, .. }) => match sink.connection {
851            StorageSinkConnection::Kafka(KafkaSinkConnection {
852                format:
853                    KafkaSinkFormat {
854                        key_format,
855                        value_format:
856                            KafkaSinkFormatType::Avro {
857                                schema: value_schema,
858                                ..
859                            },
860                        ..
861                    },
862                ..
863            }) => {
864                let schema = match schema_for {
865                    ExplainSinkSchemaFor::Key => key_format
866                        .and_then(|f| match f {
867                            KafkaSinkFormatType::Avro { schema, .. } => Some(schema),
868                            _ => None,
869                        })
870                        .ok_or_else(|| sql_err!("CREATE SINK does not have a key"))?,
871                    ExplainSinkSchemaFor::Value => value_schema,
872                };
873
874                Ok(Plan::ExplainSinkSchema(ExplainSinkSchemaPlan {
875                    sink_from: sink.from,
876                    json_schema: schema,
877                }))
878            }
879            _ => bail_unsupported!(
880                "EXPLAIN SCHEMA is only available for Kafka sinks with Avro schemas"
881            ),
882        },
883        _ => bail_internal!("plan_sink did not produce a CreateSink plan"),
884    }
885}
886
887pub fn plan_explain_pushdown(
888    scx: &StatementContext,
889    statement: ExplainPushdownStatement<Aug>,
890    params: &Params,
891) -> Result<Plan, PlanError> {
892    scx.require_feature_flag(&vars::ENABLE_EXPLAIN_PUSHDOWN)?;
893    let explainee = plan_explainee(scx, statement.explainee, params)?;
894    Ok(Plan::ExplainPushdown(ExplainPushdownPlan { explainee }))
895}
896
897// The `EXPLAIN ANALYZE ... CPU` queries attribute scheduling time to LIR nodes through each
898// node's operator span in `mz_lir_mapping`. A span includes the regions the node renders into,
899// and a region's `elapsed_ns` already contains the time of the operators inside it, so only the
900// span's outermost operators count: its operators at the smallest address depth. Channels have
901// their scope's address and no elapsed time, so the join with `mz_dataflow_operators` keeps them
902// out of the depth comparison. This relies on each span being recorded at a single scope level,
903// see `render_letfree_plan` in mz-compute.
904const LIR_SPAN_OPERATORS_CTE: (&str, &str) = (
905    "lir_span_operators",
906    r#"
907  SELECT mlm.global_id AS global_id,
908         mlm.lir_id AS lir_id,
909         valid_id AS id,
910         list_length(mda.address) AS depth
911    FROM            mz_introspection.mz_lir_mapping mlm
912         CROSS JOIN generate_series((mlm.operator_id_start) :: int8, (mlm.operator_id_end - 1) :: int8) AS valid_id
913               JOIN mz_introspection.mz_dataflow_operators mdo
914                 ON (mdo.id = valid_id)
915               JOIN mz_introspection.mz_dataflow_addresses mda
916                 ON (mda.id = valid_id)"#,
917);
918
919/// Per LIR node and worker, the scheduling time of the node's outermost operators. Reads
920/// `LIR_SPAN_OPERATORS_CTE`, which must precede it.
921const LIR_CPU_PER_WORKER_CTE: (&str, &str) = (
922    "lir_cpu_per_worker",
923    r#"
924  SELECT lso.global_id AS global_id,
925         lso.lir_id AS lir_id,
926         mse.worker_id AS worker_id,
927         SUM(mse.elapsed_ns) AS worker_ns
928    FROM            lir_span_operators lso
929               JOIN mz_introspection.mz_scheduling_elapsed_per_worker mse
930                 ON (mse.id = lso.id)
931   WHERE (lso.global_id, lso.lir_id, lso.depth) IN
932         (SELECT global_id, lir_id, MIN(depth) FROM lir_span_operators GROUP BY global_id, lir_id)
933GROUP BY lso.global_id, lso.lir_id, mse.worker_id"#,
934);
935
936pub fn plan_explain_analyze_object(
937    scx: &StatementContext,
938    statement: ExplainAnalyzeObjectStatement<Aug>,
939    params: &Params,
940) -> Result<Plan, PlanError> {
941    let explainee_name = statement
942        .explainee
943        .name()
944        .ok_or_else(|| sql_err!("EXPLAIN ANALYZE on anonymous dataflows",))?
945        .full_name_str();
946    let explainee = plan_explainee(scx, statement.explainee, params)?;
947
948    let check_ownership = |item_id: &CatalogItemId, item_type: &str| -> Result<(), PlanError> {
949        if scx.catalog.restrict_to_user_objects() {
950            let item = scx.catalog.get_item(item_id);
951            if item.owner_id() != *scx.catalog.active_role_id() {
952                let full_name = scx.catalog.resolve_full_name(item.name());
953                return Err(sql_err!("must be owner of {item_type} {full_name}"));
954            }
955        }
956        Ok(())
957    };
958    match &explainee {
959        plan::Explainee::Index(item_id) => check_ownership(item_id, "INDEX")?,
960        plan::Explainee::MaterializedView(item_id) => {
961            check_ownership(item_id, "MATERIALIZED VIEW")?
962        }
963        _ => return Err(sql_err!("EXPLAIN ANALYZE queries for this explainee type",)),
964    };
965
966    // generate SQL query
967
968    /* WITH {CTEs}
969       SELECT REPEAT(' ', nesting * 2) || operator AS operator
970             {columns}
971        FROM      mz_introspection.mz_lir_mapping mlm
972             JOIN {from} USING (lir_id)
973             JOIN mz_introspection.mz_mappable_objects mo
974               ON (mlm.global_id = mo.global_id)
975       WHERE     mo.name = {escaped explainee_name}
976             AND {predicates}
977       ORDER BY lir_id DESC
978    */
979    let mut ctes = Vec::with_capacity(5); // max 3 per ExplainAnalyzeComputationProperty
980    let mut columns = vec!["REPEAT(' ', nesting * 2) || operator AS operator"];
981    let mut from = vec!["mz_introspection.mz_lir_mapping mlm"];
982    let mut predicates = vec![format!(
983        "mo.name = {}",
984        escaped_string_literal(&explainee_name)
985    )];
986    let mut order_by = vec!["mlm.lir_id DESC"];
987
988    match statement.properties {
989        ExplainAnalyzeProperty::Computation(ExplainAnalyzeComputationProperties {
990            properties,
991            skew,
992        }) => {
993            let mut worker_id = None;
994            let mut seen_properties = BTreeSet::new();
995            for property in properties {
996                // handle each property only once (belt and suspenders)
997                if !seen_properties.insert(property) {
998                    continue;
999                }
1000
1001                match property {
1002                    ExplainAnalyzeComputationProperty::Memory => {
1003                        ctes.push((
1004                            "summary_memory",
1005                            r#"
1006  SELECT mlm.global_id AS global_id,
1007         mlm.lir_id AS lir_id,
1008         SUM(mas.size) AS total_memory,
1009         SUM(mas.records) AS total_records,
1010         CASE WHEN COUNT(DISTINCT mas.worker_id) <> 0 THEN SUM(mas.size) / COUNT(DISTINCT mas.worker_id) ELSE NULL END AS avg_memory,
1011         CASE WHEN COUNT(DISTINCT mas.worker_id) <> 0 THEN SUM(mas.records) / COUNT(DISTINCT mas.worker_id) ELSE NULL END AS avg_records
1012    FROM            mz_introspection.mz_lir_mapping mlm
1013         CROSS JOIN generate_series((mlm.operator_id_start) :: int8, (mlm.operator_id_end - 1) :: int8) AS valid_id
1014               JOIN mz_introspection.mz_arrangement_sizes_per_worker mas
1015                 ON (mas.operator_id = valid_id)
1016GROUP BY mlm.global_id, mlm.lir_id"#,
1017                        ));
1018                        from.push("LEFT JOIN summary_memory sm USING (global_id, lir_id)");
1019
1020                        if skew {
1021                            ctes.push((
1022                                "per_worker_memory",
1023                                r#"
1024  SELECT mlm.global_id AS global_id,
1025         mlm.lir_id AS lir_id,
1026         mas.worker_id AS worker_id,
1027         SUM(mas.size) AS worker_memory,
1028         SUM(mas.records) AS worker_records
1029    FROM            mz_introspection.mz_lir_mapping mlm
1030         CROSS JOIN generate_series((mlm.operator_id_start) :: int8, (mlm.operator_id_end - 1) :: int8) AS valid_id
1031               JOIN mz_introspection.mz_arrangement_sizes_per_worker mas
1032                 ON (mas.operator_id = valid_id)
1033GROUP BY mlm.global_id, mlm.lir_id, mas.worker_id"#,
1034                            ));
1035                            from.push("LEFT JOIN per_worker_memory pwm USING (global_id, lir_id)");
1036
1037                            if let Some(worker_id) = worker_id {
1038                                predicates.push(format!(
1039                                    "(pwm.worker_id = {worker_id} OR pwm.worker_id IS NULL OR {worker_id} IS NULL)"
1040                                ));
1041                            } else {
1042                                worker_id = Some("pwm.worker_id");
1043                                columns.push("pwm.worker_id AS worker_id");
1044                                order_by.push("worker_id");
1045                            }
1046
1047                            columns.extend([
1048                                "CASE WHEN pwm.worker_id IS NOT NULL AND sm.avg_memory <> 0 THEN ROUND(pwm.worker_memory / sm.avg_memory, 2) ELSE NULL END AS memory_ratio",
1049                                "pg_size_pretty(pwm.worker_memory) AS worker_memory",
1050                                "pg_size_pretty(sm.avg_memory) AS avg_memory",
1051                                "pg_size_pretty(sm.total_memory) AS total_memory",
1052                                "CASE WHEN pwm.worker_id IS NOT NULL AND sm.avg_records <> 0 THEN ROUND(pwm.worker_records / sm.avg_records, 2) ELSE NULL END AS records_ratio",
1053                                "pwm.worker_records AS worker_records",
1054                                "sm.avg_records AS avg_records",
1055                                "sm.total_records AS total_records",
1056                            ]);
1057                        } else {
1058                            columns.extend([
1059                                "pg_size_pretty(sm.total_memory) AS total_memory",
1060                                "sm.total_records AS total_records",
1061                            ]);
1062                        }
1063                    }
1064                    ExplainAnalyzeComputationProperty::Cpu => {
1065                        ctes.extend([LIR_SPAN_OPERATORS_CTE, LIR_CPU_PER_WORKER_CTE]);
1066                        ctes.push((
1067                            "summary_cpu",
1068                            r#"
1069  SELECT global_id,
1070         lir_id,
1071         SUM(worker_ns) AS total_ns,
1072         SUM(worker_ns) / COUNT(*) AS avg_ns
1073    FROM lir_cpu_per_worker
1074GROUP BY global_id, lir_id"#,
1075                        ));
1076                        from.push("LEFT JOIN summary_cpu sc USING (global_id, lir_id)");
1077
1078                        if skew {
1079                            from.push("LEFT JOIN lir_cpu_per_worker pwc USING (global_id, lir_id)");
1080
1081                            if let Some(worker_id) = worker_id {
1082                                predicates.push(format!(
1083                                    "(pwc.worker_id = {worker_id} OR pwc.worker_id IS NULL OR {worker_id} IS NULL)"
1084                                ));
1085                            } else {
1086                                worker_id = Some("pwc.worker_id");
1087                                columns.push("pwc.worker_id AS worker_id");
1088                                order_by.push("worker_id");
1089                            }
1090
1091                            columns.extend([
1092                                "CASE WHEN pwc.worker_id IS NOT NULL AND sc.avg_ns <> 0 THEN ROUND(pwc.worker_ns / sc.avg_ns, 2) ELSE NULL END AS cpu_ratio",
1093                                "pwc.worker_ns / 1000 * '1 microsecond'::INTERVAL AS worker_elapsed",
1094                                "sc.avg_ns / 1000 * '1 microsecond'::INTERVAL AS avg_elapsed",
1095                            ]);
1096                        }
1097                        columns.push(
1098                            "sc.total_ns / 1000 * '1 microsecond'::INTERVAL AS total_elapsed",
1099                        );
1100                    }
1101                }
1102            }
1103        }
1104        ExplainAnalyzeProperty::Hints => {
1105            columns.extend([
1106                "megsa.levels AS levels",
1107                "megsa.to_cut AS to_cut",
1108                "megsa.hint AS hint",
1109                "pg_size_pretty(megsa.savings) AS savings",
1110            ]);
1111            from.extend(["JOIN mz_introspection.mz_dataflow_global_ids mdgi ON (mlm.global_id = mdgi.global_id)",
1112            "LEFT JOIN (generate_series((mlm.operator_id_start) :: int8, (mlm.operator_id_end - 1) :: int8) AS valid_id JOIN \
1113             mz_introspection.mz_expected_group_size_advice megsa ON (megsa.region_id = valid_id)) ON (megsa.dataflow_id = mdgi.id)"]);
1114        }
1115    }
1116
1117    from.push("JOIN mz_introspection.mz_mappable_objects mo ON (mlm.global_id = mo.global_id)");
1118
1119    let ctes = if !ctes.is_empty() {
1120        format!(
1121            "WITH {}",
1122            separated(
1123                ",\n",
1124                ctes.iter()
1125                    .map(|(name, defn)| format!("{name} AS ({defn})"))
1126            )
1127        )
1128    } else {
1129        String::new()
1130    };
1131    let columns = separated(", ", columns);
1132    let from = separated(" ", from);
1133    let predicates = separated(" AND ", predicates);
1134    let order_by = separated(", ", order_by);
1135    let query = format!(
1136        r#"{ctes}
1137SELECT {columns}
1138FROM {from}
1139WHERE {predicates}
1140ORDER BY {order_by}"#
1141    );
1142
1143    if statement.as_sql {
1144        let rows = vec![Row::pack_slice(&[Datum::String(
1145            &mz_sql_pretty::pretty_str_simple(&query, 80).map_err(|e| {
1146                PlanError::Unstructured(format!("internal error parsing our own SQL: {e}"))
1147            })?,
1148        )])];
1149        let typ = SqlRelationType::new(vec![SqlScalarType::String.nullable(false)]);
1150
1151        Ok(Plan::Select(SelectPlan::immediate(rows, typ)))
1152    } else {
1153        let (show_select, resolved_ids) = ShowSelect::new_from_bare_query(scx, query)?;
1154        scx.record_sql_impl_ids(&resolved_ids);
1155        show_select.plan()
1156    }
1157}
1158
1159pub fn plan_explain_analyze_cluster(
1160    scx: &StatementContext,
1161    statement: ExplainAnalyzeClusterStatement,
1162    _params: &Params,
1163) -> Result<Plan, PlanError> {
1164    // object string
1165    // worker_id uint64        (if           skew)
1166    // memory_ratio numeric    (if memory && skew)
1167    // worker_memory string    (if memory && skew)
1168    // avg_memory string       (if memory && skew)
1169    // total_memory string     (if memory)
1170    // records_ratio numeric   (if memory && skew)
1171    // worker_records          (if memory && skew)
1172    // avg_records numeric     (if memory && skew)
1173    // total_records numeric   (if memory)
1174    // cpu_ratio numeric       (if cpu    && skew)
1175    // worker_elapsed interval (if cpu    && skew)
1176    // avg_elapsed interval    (if cpu    && skew)
1177    // total_elapsed interval  (if cpu)
1178
1179    /* WITH {CTEs}
1180       SELECT mo.name AS object
1181             {columns}
1182        FROM mz_introspection.mz_mappable_objects mo
1183             {from}
1184       WHERE {predicates}
1185       ORDER BY {order_by}, mo.name DESC
1186    */
1187    let mut ctes = Vec::with_capacity(4); // max 2 per ExplainAnalyzeComputationProperty
1188    let mut columns = vec!["mo.name AS object", "mo.global_id AS global_id"];
1189    let mut from = vec!["mz_introspection.mz_mappable_objects mo"];
1190    let mut predicates = vec![];
1191    let mut order_by = vec![];
1192
1193    let ExplainAnalyzeComputationProperties { properties, skew } = statement.properties;
1194    let mut worker_id = None;
1195    let mut seen_properties = BTreeSet::new();
1196    for property in properties {
1197        // handle each property only once (belt and suspenders)
1198        if !seen_properties.insert(property) {
1199            continue;
1200        }
1201
1202        match property {
1203            ExplainAnalyzeComputationProperty::Memory => {
1204                if skew {
1205                    let mut set_worker_id = false;
1206                    if let Some(worker_id) = worker_id {
1207                        // join condition if we're showing skew for more than one property
1208                        predicates.push(format!(
1209                            "(om.worker_id = {worker_id} OR om.worker_id IS NULL OR {worker_id} IS NULL)"
1210                        ));
1211                    } else {
1212                        worker_id = Some("om.worker_id");
1213                        columns.push("om.worker_id AS worker_id");
1214                        set_worker_id = true; // we'll add ourselves to `order_by` later
1215                    };
1216
1217                    // computes the average memory per LIR operator (for per operator ratios)
1218                    ctes.push((
1219                    "per_operator_memory_summary",
1220                    r#"
1221SELECT mlm.global_id AS global_id,
1222       mlm.lir_id AS lir_id,
1223       SUM(mas.size) AS total_memory,
1224       SUM(mas.records) AS total_records,
1225       CASE WHEN COUNT(DISTINCT mas.worker_id) <> 0 THEN SUM(mas.size) / COUNT(DISTINCT mas.worker_id) ELSE NULL END AS avg_memory,
1226       CASE WHEN COUNT(DISTINCT mas.worker_id) <> 0 THEN SUM(mas.records) / COUNT(DISTINCT mas.worker_id) ELSE NULL END AS avg_records
1227FROM        mz_introspection.mz_lir_mapping mlm
1228 CROSS JOIN generate_series((mlm.operator_id_start) :: int8, (mlm.operator_id_end - 1) :: int8) AS valid_id
1229       JOIN mz_introspection.mz_arrangement_sizes_per_worker mas
1230         ON (mas.operator_id = valid_id)
1231GROUP BY mlm.global_id, mlm.lir_id"#,
1232                ));
1233
1234                    // computes the memory per worker in a per operator way
1235                    ctes.push((
1236                    "per_operator_memory_per_worker",
1237                    r#"
1238SELECT mlm.global_id AS global_id,
1239       mlm.lir_id AS lir_id,
1240       mas.worker_id AS worker_id,
1241       SUM(mas.size) AS worker_memory,
1242       SUM(mas.records) AS worker_records
1243FROM        mz_introspection.mz_lir_mapping mlm
1244 CROSS JOIN generate_series((mlm.operator_id_start) :: int8, (mlm.operator_id_end - 1) :: int8) AS valid_id
1245       JOIN mz_introspection.mz_arrangement_sizes_per_worker mas
1246         ON (mas.operator_id = valid_id)
1247GROUP BY mlm.global_id, mlm.lir_id, mas.worker_id"#,
1248                    ));
1249
1250                    // computes memory ratios per worker per operator
1251                    ctes.push((
1252                    "per_operator_memory_ratios",
1253                    r#"
1254SELECT pompw.global_id AS global_id,
1255       pompw.lir_id AS lir_id,
1256       pompw.worker_id AS worker_id,
1257       CASE WHEN pompw.worker_id IS NOT NULL AND poms.avg_memory <> 0 THEN ROUND(pompw.worker_memory / poms.avg_memory, 2) ELSE NULL END AS memory_ratio,
1258       CASE WHEN pompw.worker_id IS NOT NULL AND poms.avg_records <> 0 THEN ROUND(pompw.worker_records / poms.avg_records, 2) ELSE NULL END AS records_ratio
1259  FROM      per_operator_memory_per_worker pompw
1260       JOIN per_operator_memory_summary poms
1261         USING (global_id, lir_id)
1262"#,
1263                    ));
1264
1265                    // summarizes each object, per worker
1266                    ctes.push((
1267                        "object_memory",
1268                        r#"
1269SELECT pompw.global_id AS global_id,
1270       pompw.worker_id AS worker_id,
1271       MAX(pomr.memory_ratio) AS max_operator_memory_ratio,
1272       MAX(pomr.records_ratio) AS max_operator_records_ratio,
1273       SUM(pompw.worker_memory) AS worker_memory,
1274       SUM(pompw.worker_records) AS worker_records
1275FROM        per_operator_memory_per_worker pompw
1276     JOIN   per_operator_memory_ratios pomr
1277     USING (global_id, worker_id, lir_id)
1278GROUP BY pompw.global_id, pompw.worker_id
1279"#,
1280                    ));
1281
1282                    // summarizes each worker
1283                    ctes.push(("object_average_memory", r#"
1284SELECT om.global_id AS global_id,
1285       SUM(om.worker_memory) AS total_memory,
1286       CASE WHEN COUNT(DISTINCT om.worker_id) <> 0 THEN SUM(om.worker_memory) / COUNT(DISTINCT om.worker_id) ELSE NULL END AS avg_memory,
1287       SUM(om.worker_records) AS total_records,
1288       CASE WHEN COUNT(DISTINCT om.worker_id) <> 0 THEN SUM(om.worker_records) / COUNT(DISTINCT om.worker_id) ELSE NULL END AS avg_records
1289  FROM object_memory om
1290GROUP BY om.global_id"#));
1291
1292                    from.push("LEFT JOIN object_memory om USING (global_id)");
1293                    from.push("LEFT JOIN object_average_memory oam USING (global_id)");
1294
1295                    columns.extend([
1296                        "om.max_operator_memory_ratio AS max_operator_memory_ratio",
1297                        "pg_size_pretty(om.worker_memory) AS worker_memory",
1298                        "pg_size_pretty(oam.avg_memory) AS avg_memory",
1299                        "pg_size_pretty(oam.total_memory) AS total_memory",
1300                        "om.max_operator_records_ratio AS max_operator_records_ratio",
1301                        "om.worker_records AS worker_records",
1302                        "oam.avg_records AS avg_records",
1303                        "oam.total_records AS total_records",
1304                    ]);
1305
1306                    order_by.extend([
1307                        "max_operator_memory_ratio DESC NULLS LAST",
1308                        "max_operator_records_ratio DESC NULLS LAST",
1309                        "om.worker_memory DESC NULLS LAST",
1310                        "worker_records DESC NULLS LAST",
1311                    ]);
1312
1313                    if set_worker_id {
1314                        order_by.push("worker_id");
1315                    }
1316                } else {
1317                    // no skew, so just compute totals
1318                    ctes.push((
1319                        "per_operator_memory_totals",
1320                        r#"
1321    SELECT mlm.global_id AS global_id,
1322           mlm.lir_id AS lir_id,
1323           SUM(mas.size) AS total_memory,
1324           SUM(mas.records) AS total_records
1325    FROM        mz_introspection.mz_lir_mapping mlm
1326     CROSS JOIN generate_series((mlm.operator_id_start) :: int8, (mlm.operator_id_end - 1) :: int8) AS valid_id
1327           JOIN mz_introspection.mz_arrangement_sizes_per_worker mas
1328             ON (mas.operator_id = valid_id)
1329    GROUP BY mlm.global_id, mlm.lir_id"#,
1330                    ));
1331
1332                    ctes.push((
1333                        "object_memory_totals",
1334                        r#"
1335SELECT pomt.global_id AS global_id,
1336       SUM(pomt.total_memory) AS total_memory,
1337       SUM(pomt.total_records) AS total_records
1338FROM per_operator_memory_totals pomt
1339GROUP BY pomt.global_id
1340"#,
1341                    ));
1342
1343                    from.push("LEFT JOIN object_memory_totals omt USING (global_id)");
1344                    columns.extend([
1345                        "pg_size_pretty(omt.total_memory) AS total_memory",
1346                        "omt.total_records AS total_records",
1347                    ]);
1348                    order_by.extend([
1349                        "omt.total_memory DESC NULLS LAST",
1350                        "total_records DESC NULLS LAST",
1351                    ]);
1352                }
1353            }
1354            ExplainAnalyzeComputationProperty::Cpu => {
1355                ctes.extend([LIR_SPAN_OPERATORS_CTE, LIR_CPU_PER_WORKER_CTE]);
1356                if skew {
1357                    let mut set_worker_id = false;
1358                    if let Some(worker_id) = worker_id {
1359                        // join condition if we're showing skew for more than one property
1360                        predicates.push(format!(
1361                            "(oc.worker_id = {worker_id} OR oc.worker_id IS NULL OR {worker_id} IS NULL)"
1362                        ));
1363                    } else {
1364                        worker_id = Some("oc.worker_id");
1365                        columns.push("oc.worker_id AS worker_id");
1366                        set_worker_id = true; // we'll add ourselves to `order_by` later
1367                    };
1368
1369                    // computes the average CPU per LIR operator (for per operator ratios)
1370                    ctes.push((
1371                        "per_operator_cpu_summary",
1372                        r#"
1373SELECT global_id,
1374       lir_id,
1375       SUM(worker_ns) AS total_ns,
1376       SUM(worker_ns) / COUNT(*) AS avg_ns
1377FROM lir_cpu_per_worker
1378GROUP BY global_id, lir_id"#,
1379                    ));
1380
1381                    // computes CPU ratios per worker per operator
1382                    ctes.push((
1383                        "per_operator_cpu_ratios",
1384                        r#"
1385SELECT pocpw.global_id AS global_id,
1386       pocpw.lir_id AS lir_id,
1387       pocpw.worker_id AS worker_id,
1388       CASE WHEN pocpw.worker_id IS NOT NULL AND pocs.avg_ns <> 0 THEN ROUND(pocpw.worker_ns / pocs.avg_ns, 2) ELSE NULL END AS cpu_ratio
1389FROM      lir_cpu_per_worker pocpw
1390     JOIN per_operator_cpu_summary pocs
1391     USING (global_id, lir_id)
1392"#,
1393                    ));
1394
1395                    // summarizes each object, per worker
1396                    ctes.push((
1397                        "object_cpu",
1398                        r#"
1399SELECT pocpw.global_id AS global_id,
1400       pocpw.worker_id AS worker_id,
1401       MAX(pomr.cpu_ratio) AS max_operator_cpu_ratio,
1402       SUM(pocpw.worker_ns) AS worker_ns
1403FROM      lir_cpu_per_worker pocpw
1404     JOIN per_operator_cpu_ratios pomr
1405     USING (global_id, worker_id, lir_id)
1406GROUP BY pocpw.global_id, pocpw.worker_id
1407"#,
1408                    ));
1409
1410                    // summarizes each worker
1411                    ctes.push((
1412                        "object_average_cpu",
1413                        r#"
1414SELECT oc.global_id AS global_id,
1415       SUM(oc.worker_ns) AS total_ns,
1416       CASE WHEN COUNT(DISTINCT oc.worker_id) <> 0 THEN SUM(oc.worker_ns) / COUNT(DISTINCT oc.worker_id) ELSE NULL END AS avg_ns
1417  FROM object_cpu oc
1418GROUP BY oc.global_id"#,));
1419
1420                    from.push("LEFT JOIN object_cpu oc USING (global_id)");
1421                    from.push("LEFT JOIN object_average_cpu oac USING (global_id)");
1422
1423                    columns.extend([
1424                        "oc.max_operator_cpu_ratio AS max_operator_cpu_ratio",
1425                        "oc.worker_ns / 1000 * '1 microsecond'::interval AS worker_elapsed",
1426                        "oac.avg_ns / 1000 * '1 microsecond'::interval AS avg_elapsed",
1427                        "oac.total_ns / 1000 * '1 microsecond'::interval AS total_elapsed",
1428                    ]);
1429
1430                    order_by.extend([
1431                        "max_operator_cpu_ratio DESC NULLS LAST",
1432                        "worker_elapsed DESC NULLS LAST",
1433                    ]);
1434
1435                    if set_worker_id {
1436                        order_by.push("worker_id");
1437                    }
1438                } else {
1439                    // no skew, so just compute totals
1440                    ctes.push((
1441                        "per_operator_cpu_totals",
1442                        r#"
1443SELECT global_id, lir_id, SUM(worker_ns) AS total_ns
1444FROM lir_cpu_per_worker
1445GROUP BY global_id, lir_id"#,
1446                    ));
1447
1448                    ctes.push((
1449                        "object_cpu_totals",
1450                        r#"
1451SELECT poct.global_id AS global_id,
1452       SUM(poct.total_ns) AS total_ns
1453FROM per_operator_cpu_totals poct
1454GROUP BY poct.global_id
1455"#,
1456                    ));
1457
1458                    from.push("LEFT JOIN object_cpu_totals oct USING (global_id)");
1459                    columns
1460                        .push("oct.total_ns / 1000 * '1 microsecond'::interval AS total_elapsed");
1461                    order_by.extend(["total_elapsed DESC NULLS LAST"]);
1462                }
1463            }
1464        }
1465    }
1466
1467    // generate SQL query text
1468    let ctes = if !ctes.is_empty() {
1469        format!(
1470            "WITH {}",
1471            separated(
1472                ",\n",
1473                ctes.iter()
1474                    .map(|(name, defn)| format!("{name} AS ({defn})"))
1475            )
1476        )
1477    } else {
1478        String::new()
1479    };
1480    let columns = separated(", ", columns);
1481    let from = separated(" ", from);
1482    let predicates = if !predicates.is_empty() {
1483        format!("WHERE {}", separated(" AND ", predicates))
1484    } else {
1485        String::new()
1486    };
1487    // add mo.name last, to break ties only
1488    order_by.push("mo.name DESC");
1489    let order_by = separated(", ", order_by);
1490    let query = format!(
1491        r#"{ctes}
1492SELECT {columns}
1493FROM {from}
1494{predicates}
1495ORDER BY {order_by}"#
1496    );
1497
1498    if statement.as_sql {
1499        let rows = vec![Row::pack_slice(&[Datum::String(
1500            &mz_sql_pretty::pretty_str_simple(&query, 80).map_err(|e| {
1501                PlanError::Unstructured(format!("internal error parsing our own SQL: {e}"))
1502            })?,
1503        )])];
1504        let typ = SqlRelationType::new(vec![SqlScalarType::String.nullable(false)]);
1505
1506        Ok(Plan::Select(SelectPlan::immediate(rows, typ)))
1507    } else {
1508        let (show_select, resolved_ids) = ShowSelect::new_from_bare_query(scx, query)?;
1509        scx.record_sql_impl_ids(&resolved_ids);
1510        show_select.plan()
1511    }
1512}
1513
1514pub fn plan_explain_timestamp(
1515    scx: &StatementContext,
1516    explain: ExplainTimestampStatement<Aug>,
1517) -> Result<Plan, PlanError> {
1518    let (format, _verbose_syntax) = match explain.format() {
1519        mz_sql_parser::ast::ExplainFormat::Text => (ExplainFormat::Text, false),
1520        mz_sql_parser::ast::ExplainFormat::VerboseText => (ExplainFormat::Text, true),
1521        mz_sql_parser::ast::ExplainFormat::Json => (ExplainFormat::Json, false),
1522        mz_sql_parser::ast::ExplainFormat::Dot => (ExplainFormat::Dot, false),
1523    };
1524
1525    let raw_plan = {
1526        let query::PlannedRootQuery {
1527            expr: raw_plan,
1528            desc: _,
1529            finishing: _,
1530            scope: _,
1531        } = query::plan_root_query(scx, explain.select.query, QueryLifetime::OneShot)?;
1532        if raw_plan.contains_parameters()? {
1533            return Err(PlanError::ParameterNotAllowed(
1534                "EXPLAIN TIMESTAMP".to_string(),
1535            ));
1536        }
1537
1538        raw_plan
1539    };
1540    let when = query::plan_as_of(scx, explain.select.as_of)?;
1541
1542    Ok(Plan::ExplainTimestamp(ExplainTimestampPlan {
1543        format,
1544        raw_plan,
1545        when,
1546    }))
1547}
1548
1549generate_extracted_config!(SubscribeOption, (Snapshot, bool), (Progress, bool));
1550
1551pub fn describe_subscribe(
1552    scx: &StatementContext,
1553    stmt: SubscribeStatement<Aug>,
1554) -> Result<StatementDesc, PlanError> {
1555    let relation_desc = match stmt.relation {
1556        SubscribeRelation::Name(name) => {
1557            let item = scx.get_item_by_resolved_name(&name)?;
1558            match item.relation_desc() {
1559                Some(desc) => desc.into_owned(),
1560                None => sql_bail!(
1561                    "'{}' cannot be subscribed to because it is a {}",
1562                    name.full_name_str(),
1563                    item.item_type(),
1564                ),
1565            }
1566        }
1567        SubscribeRelation::Query(query) => {
1568            let query::PlannedRootQuery { desc, .. } =
1569                query::plan_root_query(scx, query, QueryLifetime::Subscribe)?;
1570            desc
1571        }
1572    };
1573    let SubscribeOptionExtracted { progress, .. } = stmt.options.try_into()?;
1574    let progress = progress.unwrap_or(false);
1575    let mut desc = RelationDesc::builder().with_column(
1576        "mz_timestamp",
1577        SqlScalarType::Numeric {
1578            max_scale: Some(NumericMaxScale::ZERO),
1579        }
1580        .nullable(false),
1581    );
1582    if progress {
1583        desc = desc.with_column("mz_progressed", SqlScalarType::Bool.nullable(false));
1584    }
1585
1586    let debezium = matches!(stmt.output, SubscribeOutput::EnvelopeDebezium { .. });
1587    match stmt.output {
1588        SubscribeOutput::Diffs | SubscribeOutput::WithinTimestampOrderBy { .. } => {
1589            desc = desc.with_column("mz_diff", SqlScalarType::Int64.nullable(true));
1590            for (name, mut ty) in relation_desc.into_iter() {
1591                if progress {
1592                    ty.nullable = true;
1593                }
1594                desc = desc.with_column(name, ty);
1595            }
1596        }
1597        SubscribeOutput::EnvelopeUpsert { key_columns }
1598        | SubscribeOutput::EnvelopeDebezium { key_columns } => {
1599            desc = desc.with_column("mz_state", SqlScalarType::String.nullable(true));
1600            let key_columns = key_columns
1601                .into_iter()
1602                .map(normalize::column_name)
1603                .collect_vec();
1604            let mut before_values_desc = RelationDesc::builder();
1605            let mut after_values_desc = RelationDesc::builder();
1606
1607            // Add the key columns in the order that they're specified.
1608            for column_name in &key_columns {
1609                let mut column_ty = relation_desc
1610                    .get_by_name(column_name)
1611                    .map(|(_pos, ty)| ty.clone())
1612                    .ok_or_else(|| PlanError::UnknownColumn {
1613                        table: None,
1614                        column: column_name.clone(),
1615                        similar: Box::new([]),
1616                    })?;
1617                if progress {
1618                    column_ty.nullable = true;
1619                }
1620                desc = desc.with_column(column_name, column_ty);
1621            }
1622
1623            // Then add the remaining columns in the order from the original
1624            // table, filtering out the key columns since we added those above.
1625            for (mut name, mut ty) in relation_desc
1626                .into_iter()
1627                .filter(|(name, _ty)| !key_columns.contains(name))
1628            {
1629                ty.nullable = true;
1630                before_values_desc =
1631                    before_values_desc.with_column(format!("before_{}", name), ty.clone());
1632                if debezium {
1633                    name = format!("after_{}", name).into();
1634                }
1635                after_values_desc = after_values_desc.with_column(name, ty);
1636            }
1637
1638            if debezium {
1639                desc = desc.concat(before_values_desc);
1640            }
1641            desc = desc.concat(after_values_desc);
1642        }
1643    }
1644    Ok(StatementDesc::new(Some(desc.finish())))
1645}
1646
1647pub fn plan_subscribe(
1648    scx: &StatementContext,
1649    SubscribeStatement {
1650        relation,
1651        options,
1652        as_of,
1653        up_to,
1654        output,
1655    }: SubscribeStatement<Aug>,
1656    params: &Params,
1657    copy_to: Option<CopyFormat>,
1658) -> Result<Plan, PlanError> {
1659    let (from, desc, scope) = match relation {
1660        SubscribeRelation::Name(name) => {
1661            let item = scx.get_item_by_resolved_name(&name)?;
1662            let Some(desc) = item.relation_desc() else {
1663                sql_bail!(
1664                    "'{}' cannot be subscribed to because it is a {}",
1665                    name.full_name_str(),
1666                    item.item_type(),
1667                );
1668            };
1669            let item_name = match name {
1670                ResolvedItemName::Item { full_name, .. } => Some(full_name.into()),
1671                _ => None,
1672            };
1673            let scope = Scope::from_source(item_name, desc.iter().map(|(name, _type)| name));
1674            (
1675                SubscribeFrom::Id(item.global_id()),
1676                desc.into_owned(),
1677                scope,
1678            )
1679        }
1680        SubscribeRelation::Query(query) => {
1681            #[allow(deprecated)] // TODO(aalexandrov): Use HirRelationExpr in Subscribe
1682            let query::PlannedRootQuery {
1683                mut expr,
1684                desc,
1685                finishing,
1686                scope,
1687            } = query::plan_root_query(scx, query, QueryLifetime::Subscribe)?;
1688            expr.bind_parameters_and_simplify_offset(scx, QueryLifetime::Subscribe, params)?;
1689            let query = query::PlannedRootQuery {
1690                expr,
1691                desc,
1692                finishing,
1693                scope,
1694            };
1695            // There's no way to apply finishing operations to a `SUBSCRIBE` directly, so the
1696            // finishing should have already been turned into a `TopK` by
1697            // `plan_query` / `plan_root_query`, upon seeing the `QueryLifetime::Subscribe`.
1698            assert!(HirRelationExpr::is_trivial_row_set_finishing_hir(
1699                &query.finishing,
1700                query.desc.arity()
1701            ));
1702            let desc = query.desc.clone();
1703            (
1704                SubscribeFrom::Query {
1705                    expr: query.expr,
1706                    desc: query.desc,
1707                },
1708                desc,
1709                query.scope,
1710            )
1711        }
1712    };
1713
1714    let when = query::plan_as_of(scx, as_of)?;
1715    let up_to = up_to
1716        .map(|up_to| plan_as_of_or_up_to(scx, up_to))
1717        .transpose()?;
1718
1719    let qcx = QueryContext::root(scx, QueryLifetime::Subscribe);
1720    let ecx = ExprContext {
1721        qcx: &qcx,
1722        name: "",
1723        scope: &scope,
1724        relation_type: desc.typ(),
1725        allow_aggregates: false,
1726        allow_subqueries: true,
1727        allow_parameters: true,
1728        allow_windows: false,
1729    };
1730
1731    let output_columns: Vec<_> = scope.column_names().enumerate().collect();
1732    let output = match output {
1733        SubscribeOutput::Diffs => plan::SubscribeOutput::Diffs,
1734        SubscribeOutput::EnvelopeUpsert { key_columns } => {
1735            let order_by = key_columns
1736                .iter()
1737                .map(|ident| OrderByExpr {
1738                    expr: Expr::Identifier(vec![ident.clone()]),
1739                    asc: None,
1740                    nulls_last: None,
1741                })
1742                .collect_vec();
1743            let (order_by, map_exprs) = query::plan_order_by_exprs(
1744                &ExprContext {
1745                    name: "ENVELOPE UPSERT KEY clause",
1746                    ..ecx
1747                },
1748                &order_by[..],
1749                &output_columns[..],
1750            )?;
1751            if !map_exprs.is_empty() {
1752                return Err(PlanError::InvalidKeysInSubscribeEnvelopeUpsert);
1753            }
1754            check_distinct_key_columns(&order_by, &output_columns)?;
1755            plan::SubscribeOutput::EnvelopeUpsert {
1756                order_by_keys: order_by,
1757            }
1758        }
1759        SubscribeOutput::EnvelopeDebezium { key_columns } => {
1760            scx.require_feature_flag(&vars::ENABLE_ENVELOPE_DEBEZIUM_IN_SUBSCRIBE)?;
1761            let order_by = key_columns
1762                .iter()
1763                .map(|ident| OrderByExpr {
1764                    expr: Expr::Identifier(vec![ident.clone()]),
1765                    asc: None,
1766                    nulls_last: None,
1767                })
1768                .collect_vec();
1769            let (order_by, map_exprs) = query::plan_order_by_exprs(
1770                &ExprContext {
1771                    name: "ENVELOPE DEBEZIUM KEY clause",
1772                    ..ecx
1773                },
1774                &order_by[..],
1775                &output_columns[..],
1776            )?;
1777            if !map_exprs.is_empty() {
1778                return Err(PlanError::InvalidKeysInSubscribeEnvelopeDebezium);
1779            }
1780            check_distinct_key_columns(&order_by, &output_columns)?;
1781            plan::SubscribeOutput::EnvelopeDebezium {
1782                order_by_keys: order_by,
1783            }
1784        }
1785        SubscribeOutput::WithinTimestampOrderBy { order_by } => {
1786            scx.require_feature_flag(&vars::ENABLE_WITHIN_TIMESTAMP_ORDER_BY_IN_SUBSCRIBE)?;
1787            let mz_diff = "mz_diff".into();
1788            let output_columns = std::iter::once((0, &mz_diff))
1789                .chain(output_columns.into_iter().map(|(i, c)| (i + 1, c)))
1790                .collect_vec();
1791            match query::plan_order_by_exprs(
1792                &ExprContext {
1793                    name: "WITHIN TIMESTAMP ORDER BY clause",
1794                    ..ecx
1795                },
1796                &order_by[..],
1797                &output_columns[..],
1798            ) {
1799                Err(PlanError::UnknownColumn {
1800                    table: None,
1801                    column,
1802                    similar: _,
1803                }) if &column == &mz_diff => {
1804                    // mz_diff is being used in an expression. Since mz_diff isn't part of the table
1805                    // it looks like an unknown column. Instead, return a better error
1806                    return Err(PlanError::InvalidOrderByInSubscribeWithinTimestampOrderBy);
1807                }
1808                Err(e) => return Err(e),
1809                Ok((order_by, map_exprs)) => {
1810                    if !map_exprs.is_empty() {
1811                        return Err(PlanError::InvalidOrderByInSubscribeWithinTimestampOrderBy);
1812                    }
1813
1814                    plan::SubscribeOutput::WithinTimestampOrderBy { order_by }
1815                }
1816            }
1817        }
1818    };
1819
1820    let SubscribeOptionExtracted {
1821        progress, snapshot, ..
1822    } = options.try_into()?;
1823    Ok(Plan::Subscribe(SubscribePlan {
1824        from,
1825        when,
1826        up_to,
1827        with_snapshot: snapshot.unwrap_or(true),
1828        copy_to,
1829        emit_progress: progress.unwrap_or(false),
1830        output,
1831    }))
1832}
1833
1834/// Ensures each `ColumnOrder` in `order_by` references a distinct column,
1835/// returning `DuplicateKeyColumnInSubscribeEnvelope` on the first repeat.
1836fn check_distinct_key_columns(
1837    order_by: &[ColumnOrder],
1838    output_columns: &[(usize, &mz_repr::ColumnName)],
1839) -> Result<(), PlanError> {
1840    let mut seen = BTreeSet::new();
1841    for co in order_by {
1842        if !seen.insert(co.column) {
1843            return Err(PlanError::DuplicateKeyColumnInSubscribeEnvelope {
1844                column_name: output_columns[co.column].1.to_string(),
1845            });
1846        }
1847    }
1848    Ok(())
1849}
1850
1851pub fn describe_copy_from_table(
1852    scx: &StatementContext,
1853    table_name: <Aug as AstInfo>::ItemName,
1854    columns: Vec<Ident>,
1855) -> Result<StatementDesc, PlanError> {
1856    let (_, desc, _, _) = query::plan_copy_from(scx, table_name, columns)?;
1857    Ok(StatementDesc::new(Some(desc)))
1858}
1859
1860pub fn describe_copy_item(
1861    scx: &StatementContext,
1862    object_name: <Aug as AstInfo>::ItemName,
1863    columns: Vec<Ident>,
1864) -> Result<StatementDesc, PlanError> {
1865    let (_, desc, _, _) = query::plan_copy_item(scx, object_name, columns)?;
1866    Ok(StatementDesc::new(Some(desc)))
1867}
1868
1869pub fn describe_copy(
1870    scx: &StatementContext,
1871    CopyStatement {
1872        relation,
1873        direction,
1874        ..
1875    }: CopyStatement<Aug>,
1876) -> Result<StatementDesc, PlanError> {
1877    Ok(match (relation, direction) {
1878        (CopyRelation::Named { name, columns }, CopyDirection::To) => {
1879            describe_copy_item(scx, name, columns)?
1880        }
1881        (CopyRelation::Named { name, columns }, CopyDirection::From) => {
1882            describe_copy_from_table(scx, name, columns)?
1883        }
1884        (CopyRelation::Select(stmt), _) => describe_select(scx, stmt)?,
1885        (CopyRelation::Subscribe(stmt), _) => describe_subscribe(scx, stmt)?,
1886    }
1887    .with_is_copy())
1888}
1889
1890fn plan_copy_to_expr(
1891    scx: &StatementContext,
1892    select_plan: SelectPlan,
1893    desc: RelationDesc,
1894    to: &Expr<Aug>,
1895    format: CopyFormat,
1896    options: CopyOptionExtracted,
1897) -> Result<Plan, PlanError> {
1898    let conn_id = match options.aws_connection {
1899        Some(conn_id) => CatalogItemId::from(conn_id),
1900        None => sql_bail!("AWS CONNECTION is required for COPY ... TO <expr>"),
1901    };
1902    let connection = scx.get_item(&conn_id).connection()?;
1903
1904    match connection {
1905        mz_storage_types::connections::Connection::Aws(_) => {}
1906        _ => sql_bail!("only AWS CONNECTION is supported for COPY ... TO <expr>"),
1907    }
1908
1909    let format = match format {
1910        CopyFormat::Csv => {
1911            let quote = extract_byte_param_value(options.quote, "quote")?;
1912            let escape = extract_byte_param_value(options.escape, "escape")?;
1913            let delimiter = extract_byte_param_value(options.delimiter, "delimiter")?;
1914            S3SinkFormat::PgCopy(CopyFormatParams::Csv(
1915                CopyCsvFormatParams::try_new(
1916                    delimiter,
1917                    quote,
1918                    escape,
1919                    options.header,
1920                    options.null,
1921                )
1922                .map_err(|e| sql_err!("{}", e))?,
1923            ))
1924        }
1925        CopyFormat::Parquet => {
1926            // Validate that the output desc can be formatted as parquet.
1927            // COPY TO does not apply any type overrides, so pass `|_| None`.
1928            ArrowBuilder::validate_desc_for_parquet(&desc, |_| None)
1929                .map_err(|e| sql_err!("{}", e))?;
1930            S3SinkFormat::Parquet
1931        }
1932        CopyFormat::Binary => bail_unsupported!("FORMAT BINARY"),
1933        CopyFormat::Text => bail_unsupported!("FORMAT TEXT"),
1934    };
1935
1936    // Converting the to expr to a HirScalarExpr
1937    let mut to_expr = to.clone();
1938    transform_ast::transform(scx, &mut to_expr)?;
1939    let relation_type = RelationDesc::empty();
1940    let ecx = &ExprContext {
1941        qcx: &QueryContext::root(scx, QueryLifetime::OneShot),
1942        name: "COPY TO target",
1943        scope: &Scope::empty(),
1944        relation_type: relation_type.typ(),
1945        allow_aggregates: false,
1946        allow_subqueries: false,
1947        allow_parameters: false,
1948        allow_windows: false,
1949    };
1950
1951    let to = plan_expr(ecx, &to_expr)?.type_as(ecx, &SqlScalarType::String)?;
1952
1953    if options.max_file_size.as_bytes() < MIN_S3_SINK_FILE_SIZE.as_bytes() {
1954        sql_bail!(
1955            "MAX FILE SIZE cannot be less than {}",
1956            MIN_S3_SINK_FILE_SIZE
1957        );
1958    }
1959    if options.max_file_size.as_bytes() > MAX_S3_SINK_FILE_SIZE.as_bytes() {
1960        sql_bail!(
1961            "MAX FILE SIZE cannot be greater than {}",
1962            MAX_S3_SINK_FILE_SIZE
1963        );
1964    }
1965
1966    Ok(Plan::CopyTo(CopyToPlan {
1967        select_plan,
1968        desc,
1969        to,
1970        connection: connection.to_owned(),
1971        connection_id: conn_id,
1972        format,
1973        max_file_size: options.max_file_size.as_bytes(),
1974    }))
1975}
1976
1977fn plan_copy_from(
1978    scx: &StatementContext,
1979    target: &CopyTarget<Aug>,
1980    table_name: ResolvedItemName,
1981    columns: Vec<Ident>,
1982    format: Option<CopyFormat>,
1983    options: CopyOptionExtracted,
1984) -> Result<Plan, PlanError> {
1985    fn only_available_with_csv<T>(option: Option<T>, param: &str) -> Result<(), PlanError> {
1986        match option {
1987            Some(_) => sql_bail!("COPY {} available only in CSV mode", param),
1988            None => Ok(()),
1989        }
1990    }
1991
1992    let source = match target {
1993        CopyTarget::Stdin => CopyFromSource::Stdin,
1994        CopyTarget::Expr(from) => {
1995            // Converting the expr to an HirScalarExpr
1996            let mut from_expr = from.clone();
1997            transform_ast::transform(scx, &mut from_expr)?;
1998            let relation_type = RelationDesc::empty();
1999            let ecx = &ExprContext {
2000                qcx: &QueryContext::root(scx, QueryLifetime::OneShot),
2001                name: "COPY FROM target",
2002                scope: &Scope::empty(),
2003                relation_type: relation_type.typ(),
2004                allow_aggregates: false,
2005                allow_subqueries: false,
2006                allow_parameters: false,
2007                allow_windows: false,
2008            };
2009            let from = plan_expr(ecx, &from_expr)?.type_as(ecx, &SqlScalarType::String)?;
2010
2011            match options.aws_connection {
2012                Some(conn_id) => {
2013                    let conn_id = CatalogItemId::from(conn_id);
2014
2015                    // Validate the connection type is one we expect.
2016                    let connection = match scx.get_item(&conn_id).connection()? {
2017                        mz_storage_types::connections::Connection::Aws(conn) => conn,
2018                        _ => sql_bail!("only AWS CONNECTION is supported in COPY ... FROM"),
2019                    };
2020
2021                    CopyFromSource::AwsS3 {
2022                        uri: from,
2023                        connection,
2024                        connection_id: conn_id,
2025                    }
2026                }
2027                None => CopyFromSource::Url(from),
2028            }
2029        }
2030        CopyTarget::Stdout => bail_never_supported!("COPY FROM {} not supported", target),
2031    };
2032
2033    // COPY FROM a URL or S3 bucket only supports CSV and Parquet. Unlike COPY
2034    // FROM STDIN there's no sensible default format, so one must be specified
2035    // explicitly. Reject unsupported formats here in planning; the coordinator
2036    // relies on this and would otherwise soft-panic.
2037    let format = match &source {
2038        CopyFromSource::Stdin => format.unwrap_or(CopyFormat::Text),
2039        CopyFromSource::Url(_) | CopyFromSource::AwsS3 { .. } => match format {
2040            None => sql_bail!("COPY FROM <expr> requires a FORMAT option"),
2041            Some(CopyFormat::Text) => bail_unsupported!("FORMAT TEXT"),
2042            Some(CopyFormat::Binary) => bail_unsupported!("FORMAT BINARY"),
2043            Some(format @ (CopyFormat::Csv | CopyFormat::Parquet)) => format,
2044        },
2045    };
2046
2047    let params = match format {
2048        CopyFormat::Text => {
2049            only_available_with_csv(options.quote, "quote")?;
2050            only_available_with_csv(options.escape, "escape")?;
2051            only_available_with_csv(options.header, "HEADER")?;
2052            let delimiter =
2053                extract_byte_param_value(options.delimiter, "delimiter")?.unwrap_or(b'\t');
2054            let null = match options.null {
2055                Some(null) => Cow::from(null),
2056                None => Cow::from("\\N"),
2057            };
2058            CopyFormatParams::Text(CopyTextFormatParams { null, delimiter })
2059        }
2060        CopyFormat::Csv => {
2061            let quote = extract_byte_param_value(options.quote, "quote")?;
2062            let escape = extract_byte_param_value(options.escape, "escape")?;
2063            let delimiter = extract_byte_param_value(options.delimiter, "delimiter")?;
2064            CopyFormatParams::Csv(
2065                CopyCsvFormatParams::try_new(
2066                    delimiter,
2067                    quote,
2068                    escape,
2069                    options.header,
2070                    options.null,
2071                )
2072                .map_err(|e| sql_err!("{}", e))?,
2073            )
2074        }
2075        CopyFormat::Binary => bail_unsupported!("FORMAT BINARY"),
2076        CopyFormat::Parquet => CopyFormatParams::Parquet,
2077    };
2078
2079    let filter = match (options.files, options.pattern) {
2080        (Some(_), Some(_)) => bail_unsupported!("must specify one of FILES or PATTERN"),
2081        (Some(files), None) => Some(CopyFromFilter::Files(files)),
2082        (None, Some(pattern)) => Some(CopyFromFilter::Pattern(pattern)),
2083        (None, None) => None,
2084    };
2085
2086    if filter.is_some() && matches!(source, CopyFromSource::Stdin) {
2087        bail_unsupported!("COPY FROM ... WITH (FILES ...) only supported from a URL")
2088    }
2089
2090    // The STDIN decoder reads a CR or LF at the start of a record as a blank
2091    // line, so neither can open a quoted field there.
2092    if let (CopyFromSource::Stdin, CopyFormatParams::Csv(csv)) = (&source, &params)
2093        && matches!(csv.quote, b'\r' | b'\n')
2094    {
2095        sql_bail!("COPY CSV quote cannot be a line feed or carriage return");
2096    }
2097
2098    let table_name_string = table_name.full_name_str();
2099
2100    let (id, source_desc, columns, maybe_mfp) = query::plan_copy_from(scx, table_name, columns)?;
2101
2102    let Some(mfp) = maybe_mfp else {
2103        sql_bail!("[internal error] COPY FROM ... expects an MFP to be produced");
2104    };
2105
2106    Ok(Plan::CopyFrom(CopyFromPlan {
2107        target_id: id,
2108        target_name: table_name_string,
2109        source,
2110        columns,
2111        source_desc,
2112        mfp,
2113        params,
2114        filter,
2115    }))
2116}
2117
2118fn extract_byte_param_value(v: Option<String>, param_name: &str) -> Result<Option<u8>, PlanError> {
2119    match v {
2120        Some(v) if v.len() == 1 => Ok(Some(v.as_bytes()[0])),
2121        Some(..) => sql_bail!("COPY {} must be a single one-byte character", param_name),
2122        None => Ok(None),
2123    }
2124}
2125
2126generate_extracted_config!(
2127    CopyOption,
2128    (Format, String),
2129    (Delimiter, String),
2130    (Null, String),
2131    (Escape, String),
2132    (Quote, String),
2133    (Header, bool),
2134    (AwsConnection, with_options::Object),
2135    (MaxFileSize, ByteSize, Default(ByteSize::mb(256))),
2136    (Files, Vec<String>),
2137    (Pattern, String)
2138);
2139
2140pub fn plan_copy(
2141    scx: &StatementContext,
2142    CopyStatement {
2143        relation,
2144        direction,
2145        target,
2146        options,
2147    }: CopyStatement<Aug>,
2148) -> Result<Plan, PlanError> {
2149    let options = CopyOptionExtracted::try_from(options)?;
2150    // Parse any user-provided FORMAT option. If not provided, will default to
2151    // Text for COPY TO STDOUT and COPY FROM STDIN, but will error for COPY TO <expr>.
2152    let format = options
2153        .format
2154        .as_ref()
2155        .map(|format| match format.to_lowercase().as_str() {
2156            "text" => Ok(CopyFormat::Text),
2157            "csv" => Ok(CopyFormat::Csv),
2158            "binary" => Ok(CopyFormat::Binary),
2159            "parquet" => Ok(CopyFormat::Parquet),
2160            _ => sql_bail!("unknown FORMAT: {}", format),
2161        })
2162        .transpose()?;
2163
2164    match (&direction, &target) {
2165        (CopyDirection::To, CopyTarget::Stdout) => {
2166            if options.delimiter.is_some() {
2167                sql_bail!("COPY TO does not support DELIMITER option yet");
2168            }
2169            if options.quote.is_some() {
2170                sql_bail!("COPY TO does not support QUOTE option yet");
2171            }
2172            if options.escape.is_some() {
2173                sql_bail!("COPY TO does not support ESCAPE option yet");
2174            }
2175            if options.null.is_some() {
2176                sql_bail!("COPY TO does not support NULL option yet");
2177            }
2178            // `HEADER false` is the default and already honored; only an
2179            // enabled header is unimplemented. Silently accepting it would
2180            // make clients strip the first data row as a presumed header.
2181            if options.header == Some(true) {
2182                sql_bail!("COPY TO does not support HEADER option yet");
2183            }
2184            match relation {
2185                CopyRelation::Named { .. } => sql_bail!("named with COPY TO STDOUT unsupported"),
2186                CopyRelation::Select(stmt) => Ok(plan_select(
2187                    scx,
2188                    stmt,
2189                    &Params::empty(),
2190                    Some(format.unwrap_or(CopyFormat::Text)),
2191                )?),
2192                CopyRelation::Subscribe(stmt) => Ok(plan_subscribe(
2193                    scx,
2194                    stmt,
2195                    &Params::empty(),
2196                    Some(format.unwrap_or(CopyFormat::Text)),
2197                )?),
2198            }
2199        }
2200        (CopyDirection::From, target) => match relation {
2201            CopyRelation::Named { name, columns } => {
2202                plan_copy_from(scx, target, name, columns, format, options)
2203            }
2204            _ => sql_bail!("COPY FROM {} not supported", target),
2205        },
2206        (CopyDirection::To, CopyTarget::Expr(to_expr)) => {
2207            let format = match format {
2208                Some(inner) => inner,
2209                _ => sql_bail!("COPY TO <expr> requires a FORMAT option"),
2210            };
2211
2212            let stmt = match relation {
2213                CopyRelation::Named { name, columns } => {
2214                    if !columns.is_empty() {
2215                        // TODO(mouli): Add support for this
2216                        sql_bail!(
2217                            "specifying columns for COPY <table_name> TO commands not yet supported; use COPY (SELECT...) TO ... instead"
2218                        );
2219                    }
2220                    // Generate a synthetic SELECT query that just gets the table
2221                    let query = Query {
2222                        ctes: CteBlock::empty(),
2223                        body: SetExpr::Table(name),
2224                        order_by: vec![],
2225                        limit: None,
2226                        offset: None,
2227                    };
2228                    SelectStatement { query, as_of: None }
2229                }
2230                CopyRelation::Select(stmt) => {
2231                    if !stmt.query.order_by.is_empty() {
2232                        sql_bail!("ORDER BY is not supported in SELECT query for COPY statements")
2233                    }
2234                    stmt
2235                }
2236                CopyRelation::Subscribe(_) => {
2237                    sql_bail!("COPY {} {} not supported", direction, target)
2238                }
2239            };
2240
2241            let (plan, desc) = plan_select_inner(scx, stmt, &Params::empty(), None)?;
2242            plan_copy_to_expr(scx, plan, desc, to_expr, format, options)
2243        }
2244        _ => sql_bail!("COPY {} {} not supported", direction, target),
2245    }
2246}