Skip to main content

mz_sql/plan/statement/
show.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//! Queries that show the state of the database system.
11//!
12//! This module houses the handlers for the `SHOW` suite of statements, like
13//! `SHOW CREATE TABLE` and `SHOW VIEWS`. Note that `SHOW <var>` is considered
14//! an SCL statement.
15
16use std::collections::{BTreeMap, BTreeSet};
17use std::fmt::Write;
18
19use mz_ore::collections::CollectionExt;
20use mz_repr::{CatalogItemId, Datum, RelationDesc, Row, SqlScalarType};
21use mz_sql_parser::ast::display::{AstDisplay, FormatMode};
22use mz_sql_parser::ast::{
23    CreateSinkOptionName, CreateSubsourceOptionName, ExternalReferenceExport, ExternalReferences,
24    ObjectType, ShowCreateClusterStatement, ShowCreateConnectionStatement,
25    ShowCreateMaterializedViewStatement, ShowCreateTypeStatement, ShowObjectType,
26    SqlServerConfigOptionName, SystemObjectType, UnresolvedItemName, WithOptionValue,
27};
28use mz_sql_pretty::PrettyConfig;
29use query::QueryContext;
30
31use crate::ast::display::escaped_string_literal;
32use crate::ast::visit_mut::VisitMut;
33use crate::ast::{
34    SelectStatement, ShowColumnsStatement, ShowCreateIndexStatement, ShowCreateMetricSinkStatement,
35    ShowCreateSinkStatement, ShowCreateSourceStatement, ShowCreateTableStatement,
36    ShowCreateViewStatement, ShowObjectsStatement, ShowStatementFilter, Statement, Value,
37};
38use crate::catalog::{CatalogItemType, SessionCatalog};
39use crate::names::{
40    self, Aug, NameSimplifier, ObjectId, ResolvedClusterName, ResolvedDataType,
41    ResolvedDatabaseName, ResolvedIds, ResolvedItemName, ResolvedRoleName, ResolvedSchemaName,
42};
43use crate::parse;
44use crate::plan::scope::Scope;
45use crate::plan::statement::ddl::unplan_create_cluster;
46use crate::plan::statement::{StatementContext, StatementDesc, dml};
47use crate::plan::{
48    HirRelationExpr, Params, Plan, PlanError, ShowColumnsPlan, ShowCreatePlan, query, transform_ast,
49};
50use crate::session::vars::ENABLE_METRIC_SINK;
51
52pub fn describe_show_create_view(
53    _: &StatementContext,
54    _: ShowCreateViewStatement<Aug>,
55) -> Result<StatementDesc, PlanError> {
56    Ok(StatementDesc::new(Some(
57        RelationDesc::builder()
58            .with_column("name", SqlScalarType::String.nullable(false))
59            .with_column("create_sql", SqlScalarType::String.nullable(false))
60            .finish(),
61    )))
62}
63
64pub fn plan_show_create_view(
65    scx: &StatementContext,
66    ShowCreateViewStatement {
67        view_name,
68        redacted,
69    }: ShowCreateViewStatement<Aug>,
70) -> Result<ShowCreatePlan, PlanError> {
71    plan_show_create_item(scx, &view_name, CatalogItemType::View, redacted)
72}
73
74pub fn describe_show_create_materialized_view(
75    _: &StatementContext,
76    _: ShowCreateMaterializedViewStatement<Aug>,
77) -> Result<StatementDesc, PlanError> {
78    Ok(StatementDesc::new(Some(
79        RelationDesc::builder()
80            .with_column("name", SqlScalarType::String.nullable(false))
81            .with_column("create_sql", SqlScalarType::String.nullable(false))
82            .finish(),
83    )))
84}
85
86pub fn plan_show_create_materialized_view(
87    scx: &StatementContext,
88    ShowCreateMaterializedViewStatement {
89        materialized_view_name,
90        redacted,
91    }: ShowCreateMaterializedViewStatement<Aug>,
92) -> Result<ShowCreatePlan, PlanError> {
93    plan_show_create_item(
94        scx,
95        &materialized_view_name,
96        CatalogItemType::MaterializedView,
97        redacted,
98    )
99}
100
101pub fn describe_show_create_table(
102    _: &StatementContext,
103    _: ShowCreateTableStatement<Aug>,
104) -> Result<StatementDesc, PlanError> {
105    Ok(StatementDesc::new(Some(
106        RelationDesc::builder()
107            .with_column("name", SqlScalarType::String.nullable(false))
108            .with_column("create_sql", SqlScalarType::String.nullable(false))
109            .finish(),
110    )))
111}
112
113fn plan_show_create_item(
114    scx: &StatementContext,
115    name: &ResolvedItemName,
116    expect_type: CatalogItemType,
117    redacted: bool,
118) -> Result<ShowCreatePlan, PlanError> {
119    let item = scx.get_item_by_resolved_name(name)?;
120    let name = name.full_name_str();
121    if item.id().is_system()
122        && matches!(
123            expect_type,
124            CatalogItemType::Table | CatalogItemType::Source
125        )
126    {
127        sql_bail!("cannot show create for system object {name}");
128    }
129    if item.item_type() == CatalogItemType::MaterializedView && expect_type == CatalogItemType::View
130    {
131        return Err(PlanError::ShowCreateViewOnMaterializedView(name));
132    }
133    if item.item_type() != expect_type {
134        sql_bail!("{name} is not a {expect_type}");
135    }
136    let create_sql =
137        humanize_sql_for_show_create(scx.catalog, item.id(), item.create_sql(), redacted)?;
138    Ok(ShowCreatePlan {
139        id: ObjectId::Item(item.id()),
140        row: Row::pack_slice(&[Datum::String(&name), Datum::String(&create_sql)]),
141    })
142}
143
144pub fn plan_show_create_table(
145    scx: &StatementContext,
146    ShowCreateTableStatement {
147        table_name,
148        redacted,
149    }: ShowCreateTableStatement<Aug>,
150) -> Result<ShowCreatePlan, PlanError> {
151    plan_show_create_item(scx, &table_name, CatalogItemType::Table, redacted)
152}
153
154pub fn describe_show_create_source(
155    _: &StatementContext,
156    _: ShowCreateSourceStatement<Aug>,
157) -> Result<StatementDesc, PlanError> {
158    Ok(StatementDesc::new(Some(
159        RelationDesc::builder()
160            .with_column("name", SqlScalarType::String.nullable(false))
161            .with_column("create_sql", SqlScalarType::String.nullable(false))
162            .finish(),
163    )))
164}
165
166pub fn plan_show_create_source(
167    scx: &StatementContext,
168    ShowCreateSourceStatement {
169        source_name,
170        redacted,
171    }: ShowCreateSourceStatement<Aug>,
172) -> Result<ShowCreatePlan, PlanError> {
173    plan_show_create_item(scx, &source_name, CatalogItemType::Source, redacted)
174}
175
176pub fn describe_show_create_sink(
177    _: &StatementContext,
178    _: ShowCreateSinkStatement<Aug>,
179) -> Result<StatementDesc, PlanError> {
180    Ok(StatementDesc::new(Some(
181        RelationDesc::builder()
182            .with_column("name", SqlScalarType::String.nullable(false))
183            .with_column("create_sql", SqlScalarType::String.nullable(false))
184            .finish(),
185    )))
186}
187
188pub fn plan_show_create_sink(
189    scx: &StatementContext,
190    ShowCreateSinkStatement {
191        sink_name,
192        redacted,
193    }: ShowCreateSinkStatement<Aug>,
194) -> Result<ShowCreatePlan, PlanError> {
195    plan_show_create_item(scx, &sink_name, CatalogItemType::Sink, redacted)
196}
197
198pub fn describe_show_create_metric_sink(
199    _: &StatementContext,
200    _: ShowCreateMetricSinkStatement<Aug>,
201) -> Result<StatementDesc, PlanError> {
202    Ok(StatementDesc::new(Some(
203        RelationDesc::builder()
204            .with_column("name", SqlScalarType::String.nullable(false))
205            .with_column("create_sql", SqlScalarType::String.nullable(false))
206            .finish(),
207    )))
208}
209
210pub fn plan_show_create_metric_sink(
211    scx: &StatementContext,
212    ShowCreateMetricSinkStatement {
213        metric_sink_name,
214        redacted,
215    }: ShowCreateMetricSinkStatement<Aug>,
216) -> Result<ShowCreatePlan, PlanError> {
217    scx.require_feature_flag(&ENABLE_METRIC_SINK)?;
218    plan_show_create_item(
219        scx,
220        &metric_sink_name,
221        CatalogItemType::MetricSink,
222        redacted,
223    )
224}
225
226pub fn describe_show_create_index(
227    _: &StatementContext,
228    _: ShowCreateIndexStatement<Aug>,
229) -> Result<StatementDesc, PlanError> {
230    Ok(StatementDesc::new(Some(
231        RelationDesc::builder()
232            .with_column("name", SqlScalarType::String.nullable(false))
233            .with_column("create_sql", SqlScalarType::String.nullable(false))
234            .finish(),
235    )))
236}
237
238pub fn plan_show_create_index(
239    scx: &StatementContext,
240    ShowCreateIndexStatement {
241        index_name,
242        redacted,
243    }: ShowCreateIndexStatement<Aug>,
244) -> Result<ShowCreatePlan, PlanError> {
245    plan_show_create_item(scx, &index_name, CatalogItemType::Index, redacted)
246}
247
248pub fn describe_show_create_connection(
249    _: &StatementContext,
250    _: ShowCreateConnectionStatement<Aug>,
251) -> Result<StatementDesc, PlanError> {
252    Ok(StatementDesc::new(Some(
253        RelationDesc::builder()
254            .with_column("name", SqlScalarType::String.nullable(false))
255            .with_column("create_sql", SqlScalarType::String.nullable(false))
256            .finish(),
257    )))
258}
259
260pub fn plan_show_create_cluster(
261    scx: &StatementContext,
262    ShowCreateClusterStatement { cluster_name }: ShowCreateClusterStatement<Aug>,
263) -> Result<ShowCreatePlan, PlanError> {
264    let cluster = scx.get_cluster(&cluster_name.id);
265    let name = cluster.name().to_string();
266    let plan = cluster.try_to_plan()?;
267    let stmt = unplan_create_cluster(scx, plan)?;
268    let create_sql = stmt.to_ast_string_stable();
269    Ok(ShowCreatePlan {
270        id: ObjectId::Cluster(cluster_name.id),
271        row: Row::pack_slice(&[Datum::String(&name), Datum::String(&create_sql)]),
272    })
273}
274
275pub fn describe_show_create_cluster(
276    _: &StatementContext,
277    _: ShowCreateClusterStatement<Aug>,
278) -> Result<StatementDesc, PlanError> {
279    Ok(StatementDesc::new(Some(
280        RelationDesc::builder()
281            .with_column("name", SqlScalarType::String.nullable(false))
282            .with_column("create_sql", SqlScalarType::String.nullable(false))
283            .finish(),
284    )))
285}
286
287pub fn plan_show_create_type(
288    scx: &StatementContext,
289    ShowCreateTypeStatement {
290        type_name,
291        redacted,
292    }: ShowCreateTypeStatement<Aug>,
293) -> Result<ShowCreatePlan, PlanError> {
294    let ResolvedDataType::Named { id, full_name, .. } = type_name else {
295        sql_bail!("{type_name} is not a named type");
296    };
297
298    let type_item = scx.get_item(&id);
299
300    if id.is_system() {
301        sql_bail!("cannot show create for system type {full_name}");
302    }
303
304    let name = full_name.to_string();
305
306    let create_sql = humanize_sql_for_show_create(
307        scx.catalog,
308        type_item.id(),
309        type_item.create_sql(),
310        redacted,
311    )?;
312
313    Ok(ShowCreatePlan {
314        id: ObjectId::Item(id),
315        row: Row::pack_slice(&[Datum::String(&name), Datum::String(&create_sql)]),
316    })
317}
318
319pub fn describe_show_create_type(
320    _: &StatementContext,
321    _: ShowCreateTypeStatement<Aug>,
322) -> Result<StatementDesc, PlanError> {
323    Ok(StatementDesc::new(Some(
324        RelationDesc::builder()
325            .with_column("name", SqlScalarType::String.nullable(false))
326            .with_column("create_sql", SqlScalarType::String.nullable(false))
327            .finish(),
328    )))
329}
330
331pub fn plan_show_create_connection(
332    scx: &StatementContext,
333    ShowCreateConnectionStatement {
334        connection_name,
335        redacted,
336    }: ShowCreateConnectionStatement<Aug>,
337) -> Result<ShowCreatePlan, PlanError> {
338    plan_show_create_item(scx, &connection_name, CatalogItemType::Connection, redacted)
339}
340
341pub fn show_databases<'a>(
342    scx: &'a StatementContext<'a>,
343    filter: Option<ShowStatementFilter<Aug>>,
344) -> Result<ShowSelect<'a>, PlanError> {
345    let query = "SELECT name, comment FROM mz_internal.mz_show_databases".to_string();
346    ShowSelect::new(scx, query, filter, None, Some(&["name", "comment"]))
347}
348
349pub fn show_schemas<'a>(
350    scx: &'a StatementContext<'a>,
351    from: Option<ResolvedDatabaseName>,
352    filter: Option<ShowStatementFilter<Aug>>,
353) -> Result<ShowSelect<'a>, PlanError> {
354    let database_id = match from {
355        Some(ResolvedDatabaseName::Database { id, .. }) => id.to_string(),
356        None => match scx.active_database() {
357            Some(id) => id.to_string(),
358            None => sql_bail!("no database specified and no active database"),
359        },
360        Some(ResolvedDatabaseName::Error) => {
361            bail_internal!("unresolved database name")
362        }
363    };
364    let query = format!(
365        "SELECT name, comment
366        FROM mz_internal.mz_show_schemas
367        WHERE database_id IS NULL OR database_id = '{database_id}'",
368    );
369    ShowSelect::new(scx, query, filter, None, Some(&["name", "comment"]))
370}
371
372pub fn show_roles<'a>(
373    scx: &'a StatementContext<'a>,
374    filter: Option<ShowStatementFilter<Aug>>,
375) -> Result<ShowSelect<'a>, PlanError> {
376    let query = "SELECT name, comment FROM mz_internal.mz_show_roles".to_string();
377    ShowSelect::new(scx, query, filter, None, Some(&["name", "comment"]))
378}
379
380pub fn show_network_policies<'a>(
381    scx: &'a StatementContext<'a>,
382    filter: Option<ShowStatementFilter<Aug>>,
383) -> Result<ShowSelect<'a>, PlanError> {
384    let query = "SELECT name, rules, comment FROM mz_internal.mz_show_network_policies".to_string();
385    ShowSelect::new(
386        scx,
387        query,
388        filter,
389        None,
390        Some(&["name", "rules", "comment"]),
391    )
392}
393
394/// Ensures that the `FROM` clause was not provided for `SHOW` commands that
395/// don't accept it. The parser is supposed to reject such cases, so this is an
396/// internal-only invariant.
397fn ensure_no_from<T>(from: Option<T>) -> Result<(), PlanError> {
398    if from.is_some() {
399        bail_internal!("FROM not supported for this SHOW command");
400    }
401    Ok(())
402}
403
404pub fn show_objects<'a>(
405    scx: &'a StatementContext<'a>,
406    ShowObjectsStatement {
407        object_type,
408        from,
409        filter,
410    }: ShowObjectsStatement<Aug>,
411) -> Result<ShowSelect<'a>, PlanError> {
412    match object_type {
413        ShowObjectType::Table { on_source } => show_tables(scx, from, on_source, filter),
414        ShowObjectType::Source { in_cluster } => show_sources(scx, from, in_cluster, filter),
415        ShowObjectType::Subsource { on_source } => show_subsources(scx, from, on_source, filter),
416        ShowObjectType::View => show_views(scx, from, filter),
417        ShowObjectType::Sink { in_cluster } => show_sinks(scx, from, in_cluster, filter),
418        ShowObjectType::MetricSink { in_cluster } => {
419            show_metric_sinks(scx, from, in_cluster, filter)
420        }
421        ShowObjectType::Type => show_types(scx, from, filter),
422        ShowObjectType::Object => show_all_objects(scx, from, filter),
423        ShowObjectType::Role => {
424            ensure_no_from(from)?;
425            show_roles(scx, filter)
426        }
427        ShowObjectType::Cluster => {
428            ensure_no_from(from)?;
429            show_clusters(scx, filter)
430        }
431        ShowObjectType::ClusterReplica => {
432            ensure_no_from(from)?;
433            show_cluster_replicas(scx, filter)
434        }
435        ShowObjectType::Secret => show_secrets(scx, from, filter),
436        ShowObjectType::Connection => show_connections(scx, from, filter),
437        ShowObjectType::MaterializedView { in_cluster } => {
438            show_materialized_views(scx, from, in_cluster, filter)
439        }
440        ShowObjectType::Index {
441            in_cluster,
442            on_object,
443        } => show_indexes(scx, from, on_object, in_cluster, filter),
444        ShowObjectType::Database => {
445            ensure_no_from(from)?;
446            show_databases(scx, filter)
447        }
448        ShowObjectType::Schema { from: db_from } => {
449            ensure_no_from(from)?;
450            show_schemas(scx, db_from, filter)
451        }
452        ShowObjectType::Privileges { object_type, role } => {
453            ensure_no_from(from)?;
454            show_privileges(scx, object_type, role, filter)
455        }
456        ShowObjectType::DefaultPrivileges { object_type, role } => {
457            ensure_no_from(from)?;
458            show_default_privileges(scx, object_type, role, filter)
459        }
460        ShowObjectType::RoleMembership { role } => {
461            ensure_no_from(from)?;
462            show_role_membership(scx, role, filter)
463        }
464        ShowObjectType::NetworkPolicy => {
465            ensure_no_from(from)?;
466            show_network_policies(scx, filter)
467        }
468        ShowObjectType::QueryPolicy => {
469            ensure_no_from(from)?;
470            ShowSelect::new(
471                scx,
472                "SELECT name, mode, rules, comment FROM mz_internal.mz_show_query_policies"
473                    .to_string(),
474                filter,
475                None,
476                Some(&["name", "mode", "rules", "comment"]),
477            )
478        }
479    }
480}
481
482fn show_connections<'a>(
483    scx: &'a StatementContext<'a>,
484    from: Option<ResolvedSchemaName>,
485    filter: Option<ShowStatementFilter<Aug>>,
486) -> Result<ShowSelect<'a>, PlanError> {
487    let schema_spec = scx.resolve_optional_schema(&from)?;
488    let query = format!(
489        "SELECT name, type, comment
490        FROM mz_internal.mz_show_connections connections
491        WHERE schema_id = '{schema_spec}'",
492    );
493    ShowSelect::new(scx, query, filter, None, Some(&["name", "type", "comment"]))
494}
495
496fn show_tables<'a>(
497    scx: &'a StatementContext<'a>,
498    from: Option<ResolvedSchemaName>,
499    on_source: Option<ResolvedItemName>,
500    filter: Option<ShowStatementFilter<Aug>>,
501) -> Result<ShowSelect<'a>, PlanError> {
502    let schema_spec = scx.resolve_optional_schema(&from)?;
503    let mut query = format!(
504        "SELECT name, comment
505        FROM mz_internal.mz_show_tables tables
506        WHERE tables.schema_id = '{schema_spec}'",
507    );
508    if let Some(on_source) = &on_source {
509        let on_item = scx.get_item_by_resolved_name(on_source)?;
510        if on_item.item_type() != CatalogItemType::Source {
511            sql_bail!(
512                "cannot show tables on {} because it is a {}",
513                on_source.full_name_str(),
514                on_item.item_type(),
515            );
516        }
517        query += &format!(" AND tables.source_id = '{}'", on_item.id());
518    }
519    ShowSelect::new(scx, query, filter, None, Some(&["name", "comment"]))
520}
521
522fn show_sources<'a>(
523    scx: &'a StatementContext<'a>,
524    from: Option<ResolvedSchemaName>,
525    in_cluster: Option<ResolvedClusterName>,
526    filter: Option<ShowStatementFilter<Aug>>,
527) -> Result<ShowSelect<'a>, PlanError> {
528    let schema_spec = scx.resolve_optional_schema(&from)?;
529    let mut where_clause = format!("schema_id = '{schema_spec}'");
530
531    if let Some(cluster) = in_cluster {
532        write!(where_clause, " AND cluster_id = '{}'", cluster.id)
533            .expect("write on string cannot fail");
534    }
535
536    let query = format!(
537        "SELECT name, type, cluster, comment
538        FROM mz_internal.mz_show_sources
539        WHERE {where_clause}"
540    );
541    ShowSelect::new(
542        scx,
543        query,
544        filter,
545        None,
546        Some(&["name", "type", "cluster", "comment"]),
547    )
548}
549
550fn show_subsources<'a>(
551    scx: &'a StatementContext<'a>,
552    from_schema: Option<ResolvedSchemaName>,
553    on_source: Option<ResolvedItemName>,
554    filter: Option<ShowStatementFilter<Aug>>,
555) -> Result<ShowSelect<'a>, PlanError> {
556    let mut query_filter = Vec::new();
557
558    if on_source.is_none() && from_schema.is_none() {
559        query_filter.push("subsources.id NOT LIKE 's%'".into());
560        let schema_spec = scx.resolve_active_schema().map(|spec| spec.clone())?;
561        query_filter.push(format!("subsources.schema_id = '{schema_spec}'"));
562    }
563
564    if let Some(on_source) = &on_source {
565        let on_item = scx.get_item_by_resolved_name(on_source)?;
566        if on_item.item_type() != CatalogItemType::Source {
567            sql_bail!(
568                "cannot show subsources on {} because it is a {}",
569                on_source.full_name_str(),
570                on_item.item_type(),
571            );
572        }
573        query_filter.push(format!("sources.id = '{}'", on_item.id()));
574    }
575
576    if let Some(schema) = from_schema {
577        let schema_spec = schema.schema_spec();
578        query_filter.push(format!("subsources.schema_id = '{schema_spec}'"));
579    }
580
581    // TODO(database-issues#8322): this looks in both directions for subsources as long as
582    // progress collections still exist
583    let query = format!(
584        "SELECT DISTINCT
585            subsources.name AS name,
586            subsources.type AS type
587        FROM
588            mz_sources AS subsources
589            JOIN mz_internal.mz_object_dependencies deps ON (subsources.id = deps.object_id OR subsources.id = deps.referenced_object_id)
590            JOIN mz_sources AS sources ON (sources.id = deps.object_id OR sources.id = deps.referenced_object_id)
591        WHERE (subsources.type = 'subsource' OR subsources.type = 'progress') AND {}",
592        itertools::join(query_filter, " AND "),
593    );
594    ShowSelect::new(scx, query, filter, None, None)
595}
596
597fn show_views<'a>(
598    scx: &'a StatementContext<'a>,
599    from: Option<ResolvedSchemaName>,
600    filter: Option<ShowStatementFilter<Aug>>,
601) -> Result<ShowSelect<'a>, PlanError> {
602    let schema_spec = scx.resolve_optional_schema(&from)?;
603    let query = format!(
604        "SELECT name, comment
605        FROM mz_internal.mz_show_views
606        WHERE schema_id = '{schema_spec}'"
607    );
608    ShowSelect::new(scx, query, filter, None, Some(&["name", "comment"]))
609}
610
611fn show_materialized_views<'a>(
612    scx: &'a StatementContext<'a>,
613    from: Option<ResolvedSchemaName>,
614    in_cluster: Option<ResolvedClusterName>,
615    filter: Option<ShowStatementFilter<Aug>>,
616) -> Result<ShowSelect<'a>, PlanError> {
617    let schema_spec = scx.resolve_optional_schema(&from)?;
618    let mut where_clause = format!("schema_id = '{schema_spec}'");
619
620    if let Some(cluster) = in_cluster {
621        write!(where_clause, " AND cluster_id = '{}'", cluster.id)
622            .expect("write on string cannot fail");
623    }
624
625    let query = format!(
626        "SELECT name, cluster, comment
627            FROM mz_internal.mz_show_materialized_views
628            WHERE {where_clause}"
629    );
630
631    let projection = vec!["name", "cluster", "comment"];
632
633    ShowSelect::new(scx, query, filter, None, Some(&projection))
634}
635
636fn show_sinks<'a>(
637    scx: &'a StatementContext<'a>,
638    from: Option<ResolvedSchemaName>,
639    in_cluster: Option<ResolvedClusterName>,
640    filter: Option<ShowStatementFilter<Aug>>,
641) -> Result<ShowSelect<'a>, PlanError> {
642    let schema_spec = if let Some(ResolvedSchemaName::Schema { schema_spec, .. }) = from {
643        schema_spec.to_string()
644    } else {
645        scx.resolve_active_schema()?.to_string()
646    };
647
648    let mut where_clause = format!("schema_id = '{schema_spec}'");
649
650    if let Some(cluster) = in_cluster {
651        write!(where_clause, " AND cluster_id = '{}'", cluster.id)
652            .expect("write on string cannot fail");
653    }
654
655    let query = format!(
656        "SELECT name, type, cluster, comment
657        FROM mz_internal.mz_show_sinks sinks
658        WHERE {where_clause}"
659    );
660    ShowSelect::new(
661        scx,
662        query,
663        filter,
664        None,
665        Some(&["name", "type", "cluster", "comment"]),
666    )
667}
668
669/// `SHOW METRIC SINKS` reports the `FROM` relation rather than a connection or format, since a
670/// metric sink publishes into the replica's registry and has neither.
671fn show_metric_sinks<'a>(
672    scx: &'a StatementContext<'a>,
673    from: Option<ResolvedSchemaName>,
674    in_cluster: Option<ResolvedClusterName>,
675    filter: Option<ShowStatementFilter<Aug>>,
676) -> Result<ShowSelect<'a>, PlanError> {
677    // `ENABLE_METRIC_SINK` gates the DDL and these SHOW verbs, not the catalog
678    // surface. `mz_metric_sinks` is `PUBLIC_SELECT` and its rows flow into
679    // `mz_objects` unconditionally, so with the flag off both are simply empty,
680    // because no metric sink can exist yet. Gating the verbs keeps them
681    // unavailable until the feature ships while the relation stays a stable
682    // always-on shape.
683    scx.require_feature_flag(&ENABLE_METRIC_SINK)?;
684    let schema_spec = scx.resolve_optional_schema(&from)?;
685
686    let mut where_clause = format!("metric_sinks.schema_id = '{schema_spec}'");
687    if let Some(cluster) = in_cluster {
688        write!(
689            where_clause,
690            " AND metric_sinks.cluster_id = '{}'",
691            cluster.id
692        )
693        .expect("write on string cannot fail");
694    }
695
696    let query = format!(
697        "SELECT metric_sinks.name, objs.name AS relation, clusters.name AS cluster
698        FROM mz_internal.mz_metric_sinks AS metric_sinks
699        JOIN mz_catalog.mz_objects AS objs ON objs.id = metric_sinks.from_id
700        JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = metric_sinks.cluster_id
701        WHERE {where_clause}"
702    );
703    ShowSelect::new(
704        scx,
705        query,
706        filter,
707        None,
708        Some(&["name", "relation", "cluster"]),
709    )
710}
711
712fn show_types<'a>(
713    scx: &'a StatementContext<'a>,
714    from: Option<ResolvedSchemaName>,
715    filter: Option<ShowStatementFilter<Aug>>,
716) -> Result<ShowSelect<'a>, PlanError> {
717    let schema_spec = scx.resolve_optional_schema(&from)?;
718    let query = format!(
719        "SELECT name, comment
720        FROM mz_internal.mz_show_types
721        WHERE schema_id = '{schema_spec}'"
722    );
723    ShowSelect::new(scx, query, filter, None, Some(&["name", "comment"]))
724}
725
726fn show_all_objects<'a>(
727    scx: &'a StatementContext<'a>,
728    from: Option<ResolvedSchemaName>,
729    filter: Option<ShowStatementFilter<Aug>>,
730) -> Result<ShowSelect<'a>, PlanError> {
731    let schema_spec = scx.resolve_optional_schema(&from)?;
732    let query = format!(
733        "SELECT name, type, comment
734         FROM mz_internal.mz_show_all_objects
735         WHERE schema_id = '{schema_spec}'",
736    );
737    ShowSelect::new(scx, query, filter, None, Some(&["name", "type", "comment"]))
738}
739
740pub fn show_indexes<'a>(
741    scx: &'a StatementContext<'a>,
742    from_schema: Option<ResolvedSchemaName>,
743    on_object: Option<ResolvedItemName>,
744    in_cluster: Option<ResolvedClusterName>,
745    filter: Option<ShowStatementFilter<Aug>>,
746) -> Result<ShowSelect<'a>, PlanError> {
747    let mut query_filter = Vec::new();
748
749    if on_object.is_none() && from_schema.is_none() && in_cluster.is_none() {
750        query_filter.push("on_id NOT LIKE 's%'".into());
751        let schema_spec = scx.resolve_active_schema().map(|spec| spec.clone())?;
752        query_filter.push(format!("schema_id = '{schema_spec}'"));
753    }
754
755    if let Some(on_object) = &on_object {
756        let on_item = scx.get_item_by_resolved_name(on_object)?;
757        if on_item.item_type() != CatalogItemType::View
758            && on_item.item_type() != CatalogItemType::MaterializedView
759            && on_item.item_type() != CatalogItemType::Source
760            && on_item.item_type() != CatalogItemType::Table
761        {
762            sql_bail!(
763                "cannot show indexes on {} because it is a {}",
764                on_object.full_name_str(),
765                on_item.item_type(),
766            );
767        }
768        query_filter.push(format!("on_id = '{}'", on_item.id()));
769    }
770
771    if let Some(schema) = from_schema {
772        let schema_spec = schema.schema_spec();
773        query_filter.push(format!("schema_id = '{schema_spec}'"));
774    }
775
776    if let Some(cluster) = in_cluster {
777        query_filter.push(format!("cluster_id = '{}'", cluster.id))
778    };
779
780    let query = format!(
781        "SELECT name, on, cluster, key, comment
782        FROM mz_internal.mz_show_indexes
783        WHERE {}",
784        itertools::join(query_filter.iter(), " AND ")
785    );
786
787    ShowSelect::new(
788        scx,
789        query,
790        filter,
791        None,
792        Some(&["name", "on", "cluster", "key", "comment"]),
793    )
794}
795
796pub fn show_columns<'a>(
797    scx: &'a StatementContext<'a>,
798    ShowColumnsStatement { table_name, filter }: ShowColumnsStatement<Aug>,
799) -> Result<ShowColumnsSelect<'a>, PlanError> {
800    let entry = scx.get_item_by_resolved_name(&table_name)?;
801    let full_name = scx.catalog.resolve_full_name(entry.name());
802
803    match entry.item_type() {
804        CatalogItemType::Source
805        | CatalogItemType::Table
806        | CatalogItemType::View
807        | CatalogItemType::MaterializedView => (),
808        ty @ CatalogItemType::Connection
809        | ty @ CatalogItemType::Index
810        | ty @ CatalogItemType::Func
811        | ty @ CatalogItemType::Secret
812        | ty @ CatalogItemType::Type
813        | ty @ CatalogItemType::Sink
814        | ty @ CatalogItemType::MetricSink => {
815            sql_bail!("{full_name} is a {ty} and so does not have columns");
816        }
817    }
818
819    let query = format!(
820        "SELECT name, nullable, type, position, comment
821         FROM mz_internal.mz_show_columns columns
822         WHERE columns.id = '{}'",
823        entry.id(),
824    );
825    let (show_select, new_resolved_ids) = ShowSelect::new_with_resolved_ids(
826        scx,
827        query,
828        filter,
829        Some("position"),
830        Some(&["name", "nullable", "type", "comment"]),
831    )?;
832    scx.record_sql_impl_ids(&new_resolved_ids);
833    Ok(ShowColumnsSelect {
834        id: entry.id(),
835        show_select,
836        new_resolved_ids,
837    })
838}
839
840// The rationale for which fields to include in the tuples are those
841// that are mandatory when creating a replica as part of the CREATE
842// CLUSTER command, i.e., name and size.
843pub fn show_clusters<'a>(
844    scx: &'a StatementContext<'a>,
845    filter: Option<ShowStatementFilter<Aug>>,
846) -> Result<ShowSelect<'a>, PlanError> {
847    let query =
848        "SELECT name, replicas, activity, comment FROM mz_internal.mz_show_clusters".to_string();
849    ShowSelect::new(
850        scx,
851        query,
852        filter,
853        None,
854        Some(&["name", "replicas", "activity", "comment"]),
855    )
856}
857
858pub fn show_cluster_replicas<'a>(
859    scx: &'a StatementContext<'a>,
860    filter: Option<ShowStatementFilter<Aug>>,
861) -> Result<ShowSelect<'a>, PlanError> {
862    let query = "
863    SELECT cluster, replica, size, ready, comment
864    FROM mz_internal.mz_show_cluster_replicas
865    "
866    .to_string();
867
868    ShowSelect::new(
869        scx,
870        query,
871        filter,
872        None,
873        Some(&["cluster", "replica", "size", "ready", "comment"]),
874    )
875}
876
877pub fn show_secrets<'a>(
878    scx: &'a StatementContext<'a>,
879    from: Option<ResolvedSchemaName>,
880    filter: Option<ShowStatementFilter<Aug>>,
881) -> Result<ShowSelect<'a>, PlanError> {
882    let schema_spec = scx.resolve_optional_schema(&from)?;
883
884    let query = format!(
885        "SELECT name, comment
886        FROM mz_internal.mz_show_secrets
887        WHERE schema_id = '{schema_spec}'",
888    );
889
890    ShowSelect::new(scx, query, filter, None, Some(&["name", "comment"]))
891}
892
893pub fn show_privileges<'a>(
894    scx: &'a StatementContext<'a>,
895    object_type: Option<SystemObjectType>,
896    role: Option<ResolvedRoleName>,
897    filter: Option<ShowStatementFilter<Aug>>,
898) -> Result<ShowSelect<'a>, PlanError> {
899    let mut query_filter = Vec::new();
900    if let Some(object_type) = object_type {
901        query_filter.push(format!(
902            "object_type = '{}'",
903            object_type.to_string().to_lowercase()
904        ));
905    }
906    if let Some(role) = role {
907        let name = escaped_string_literal(&role.name);
908        query_filter.push(format!(
909            "CASE WHEN grantee = 'PUBLIC' THEN true ELSE pg_has_role({name}, grantee, 'USAGE') END"
910        ));
911    }
912    let query_filter = if query_filter.len() > 0 {
913        format!("WHERE {}", itertools::join(query_filter, " AND "))
914    } else {
915        "".to_string()
916    };
917
918    let query = format!(
919        "SELECT grantor, grantee, database, schema, name, object_type, privilege_type
920        FROM mz_internal.mz_show_all_privileges
921        {query_filter}",
922    );
923
924    ShowSelect::new(
925        scx,
926        query,
927        filter,
928        None,
929        Some(&[
930            "grantor",
931            "grantee",
932            "database",
933            "schema",
934            "name",
935            "object_type",
936            "privilege_type",
937        ]),
938    )
939}
940
941pub fn show_default_privileges<'a>(
942    scx: &'a StatementContext<'a>,
943    object_type: Option<ObjectType>,
944    role: Option<ResolvedRoleName>,
945    filter: Option<ShowStatementFilter<Aug>>,
946) -> Result<ShowSelect<'a>, PlanError> {
947    let mut query_filter = Vec::new();
948    if let Some(object_type) = object_type {
949        query_filter.push(format!(
950            "object_type = '{}'",
951            object_type.to_string().to_lowercase()
952        ));
953    }
954    if let Some(role) = role {
955        let name = escaped_string_literal(&role.name);
956        query_filter.push(format!(
957            "CASE WHEN grantee = 'PUBLIC' THEN true ELSE pg_has_role({name}, grantee, 'USAGE') END"
958        ));
959    }
960    let query_filter = if query_filter.len() > 0 {
961        format!("WHERE {}", itertools::join(query_filter, " AND "))
962    } else {
963        "".to_string()
964    };
965
966    let query = format!(
967        "SELECT object_owner, database, schema, object_type, grantee, privilege_type
968        FROM mz_internal.mz_show_default_privileges
969        {query_filter}",
970    );
971
972    ShowSelect::new(
973        scx,
974        query,
975        filter,
976        None,
977        Some(&[
978            "object_owner",
979            "database",
980            "schema",
981            "object_type",
982            "grantee",
983            "privilege_type",
984        ]),
985    )
986}
987
988pub fn show_role_membership<'a>(
989    scx: &'a StatementContext<'a>,
990    role: Option<ResolvedRoleName>,
991    filter: Option<ShowStatementFilter<Aug>>,
992) -> Result<ShowSelect<'a>, PlanError> {
993    let mut query_filter = Vec::new();
994    if let Some(role) = role {
995        let name = escaped_string_literal(&role.name);
996        query_filter.push(format!("pg_has_role({name}, member, 'USAGE')"));
997    }
998    let query_filter = if query_filter.len() > 0 {
999        format!("WHERE {}", itertools::join(query_filter, " AND "))
1000    } else {
1001        "".to_string()
1002    };
1003
1004    let query = format!(
1005        "SELECT role, member, grantor
1006        FROM mz_internal.mz_show_role_members
1007        {query_filter}",
1008    );
1009
1010    ShowSelect::new(
1011        scx,
1012        query,
1013        filter,
1014        None,
1015        Some(&["role", "member", "grantor"]),
1016    )
1017}
1018
1019/// An intermediate result when planning a `SHOW` query.
1020///
1021/// Can be interrogated for its columns, or converted into a proper [`Plan`].
1022pub struct ShowSelect<'a> {
1023    scx: &'a StatementContext<'a>,
1024    pub(crate) stmt: SelectStatement<Aug>,
1025}
1026
1027impl<'a> ShowSelect<'a> {
1028    /// Constructs a new [`ShowSelect`] from a query that provides the base
1029    /// data and an optional user-supplied filter, order column, and
1030    /// projection on that data.
1031    ///
1032    /// Note that the query must return a column named `name`, as the filter
1033    /// may implicitly reference this column. Any `ORDER BY` in the query is
1034    /// ignored. `ShowSelects`s are always ordered in ascending order by all
1035    /// columns from left to right unless an order field is supplied.
1036    fn new(
1037        scx: &'a StatementContext,
1038        query: String,
1039        filter: Option<ShowStatementFilter<Aug>>,
1040        order: Option<&str>,
1041        projection: Option<&[&str]>,
1042    ) -> Result<ShowSelect<'a>, PlanError> {
1043        let (show_select, new_resolved_ids) =
1044            Self::new_with_resolved_ids(scx, query, filter, order, projection)?;
1045        scx.sql_impl_resolved_ids
1046            .lock()
1047            .expect("planning is single-threaded")
1048            .extend_from(&new_resolved_ids);
1049        Ok(show_select)
1050    }
1051
1052    fn new_with_resolved_ids(
1053        scx: &'a StatementContext,
1054        query: String,
1055        filter: Option<ShowStatementFilter<Aug>>,
1056        order: Option<&str>,
1057        projection: Option<&[&str]>,
1058    ) -> Result<(ShowSelect<'a>, ResolvedIds), PlanError> {
1059        let filter = match filter {
1060            Some(ShowStatementFilter::Like(like)) => format!("name LIKE {}", Value::String(like)),
1061            Some(ShowStatementFilter::Where(expr)) => expr.to_string(),
1062            None => "true".to_string(),
1063        };
1064        let query = format!(
1065            "SELECT {} FROM ({}) q WHERE {} ORDER BY {}",
1066            projection
1067                .map(|ps| ps.join(", "))
1068                .unwrap_or_else(|| "*".into()),
1069            query,
1070            filter,
1071            order.unwrap_or("q.*")
1072        );
1073
1074        Self::new_from_bare_query(scx, query)
1075    }
1076
1077    pub fn new_from_bare_query(
1078        scx: &'a StatementContext,
1079        query: String,
1080    ) -> Result<(ShowSelect<'a>, ResolvedIds), PlanError> {
1081        let stmts = parse::parse(&query)
1082            .map_err(|e| internal_err!("failed to parse generated SHOW query: {}", e))?;
1083        let stmt = match stmts.into_element().ast {
1084            Statement::Select(select) => select,
1085            _ => bail_internal!("generated SHOW query was not a SELECT statement"),
1086        };
1087        let (mut stmt, new_resolved_ids) = names::resolve(scx.catalog, stmt)?;
1088        transform_ast::transform(scx, &mut stmt)?;
1089        Ok((ShowSelect { scx, stmt }, new_resolved_ids))
1090    }
1091
1092    /// Computes the shape of this `ShowSelect`.
1093    pub fn describe(self) -> Result<StatementDesc, PlanError> {
1094        dml::describe_select(self.scx, self.stmt)
1095    }
1096
1097    /// Converts this `ShowSelect` into a [`Plan`].
1098    pub fn plan(self) -> Result<Plan, PlanError> {
1099        dml::plan_select(self.scx, self.stmt, &Params::empty(), None)
1100    }
1101
1102    /// Converts this `ShowSelect` into a [`(HirRelationExpr, Scope)`].
1103    pub fn plan_hir(self, qcx: &QueryContext) -> Result<(HirRelationExpr, Scope), PlanError> {
1104        query::plan_nested_query(&mut qcx.clone(), &self.stmt.query)
1105    }
1106}
1107
1108pub struct ShowColumnsSelect<'a> {
1109    id: CatalogItemId,
1110    new_resolved_ids: ResolvedIds,
1111    show_select: ShowSelect<'a>,
1112}
1113
1114impl<'a> ShowColumnsSelect<'a> {
1115    pub fn describe(self) -> Result<StatementDesc, PlanError> {
1116        self.show_select.describe()
1117    }
1118
1119    pub fn plan(self) -> Result<Plan, PlanError> {
1120        let select_plan = self.show_select.plan()?;
1121        match select_plan {
1122            Plan::Select(select_plan) => Ok(Plan::ShowColumns(ShowColumnsPlan {
1123                id: self.id,
1124                select_plan,
1125                new_resolved_ids: self.new_resolved_ids,
1126            })),
1127            _ => {
1128                tracing::error!(
1129                    "SHOW COLUMNS produced a non select plan. plan: {:?}",
1130                    select_plan
1131                );
1132                Err(PlanError::Unstructured(
1133                    "SHOW COLUMNS produced an unexpected plan. Please file a bug.".to_string(),
1134                ))
1135            }
1136        }
1137    }
1138
1139    pub fn plan_hir(self, qcx: &QueryContext) -> Result<(HirRelationExpr, Scope), PlanError> {
1140        self.show_select.plan_hir(qcx)
1141    }
1142}
1143
1144/// Convert a SQL statement into a form that could be used as input, as well as
1145/// is more amenable to human consumption.
1146///
1147/// Note that the bits we omit here (e.g. the internal `AS OF` of a materialized
1148/// view, or the `DETAILS` of a `CREATE TABLE ... FROM SOURCE`) are not
1149/// user-typeable, but remain accessible for debugging in the raw `create_sql`
1150/// (and `redacted_create_sql`) column of catalog builtins like
1151/// `mz_catalog.mz_materialized_views` and `mz_catalog.mz_tables`. They are not
1152/// in the `definition` column, which is parsed back out of `create_sql` and only
1153/// retains the inner query.
1154fn humanize_sql_for_show_create(
1155    catalog: &dyn SessionCatalog,
1156    id: CatalogItemId,
1157    sql: &str,
1158    redacted: bool,
1159) -> Result<String, PlanError> {
1160    use mz_sql_parser::ast::{
1161        CreateSourceConnection, MySqlConfigOptionName, PgConfigOptionName, TableFromSourceColumns,
1162        TableFromSourceOptionName,
1163    };
1164
1165    let parsed = parse::parse(sql)?.into_element().ast;
1166    let (mut resolved, _) = names::resolve(catalog, parsed)?;
1167
1168    // Simplify names.
1169    let mut simplifier = NameSimplifier { catalog };
1170    simplifier.visit_statement_mut(&mut resolved);
1171
1172    match &mut resolved {
1173        // Strip internal `AS OF` syntax.
1174        Statement::CreateMaterializedView(stmt) => stmt.as_of = None,
1175        // Strip the internal `DETAILS` option, which is not user-typeable and
1176        // does not roundtrip.
1177        Statement::CreateTableFromSource(stmt) => {
1178            stmt.with_options.retain_mut(|o| match o.name {
1179                TableFromSourceOptionName::TextColumns => true,
1180                TableFromSourceOptionName::ExcludeColumns => true,
1181                TableFromSourceOptionName::ExcludeConstraints => true,
1182                TableFromSourceOptionName::ExcludeAllConstraints => true,
1183                TableFromSourceOptionName::ExcludeAllNotNullConstraints => true,
1184                // Drop details, which does not roundtrip.
1185                TableFromSourceOptionName::Details => false,
1186                TableFromSourceOptionName::PartitionBy => true,
1187                TableFromSourceOptionName::RetainHistory => true,
1188            });
1189            // The `Defined` column list and constraints are populated during
1190            // purification (from the upstream schema), and `CREATE TABLE ... FROM
1191            // SOURCE` rejects them as input. Omit them so the statement
1192            // roundtrips; purification re-derives them from the source on replay,
1193            // and the schema-affecting `TEXT COLUMNS` / `EXCLUDE COLUMNS` options
1194            // are retained above so the re-derived schema matches. A user-typed
1195            // `Named` column list is left intact, since it does roundtrip.
1196            if matches!(stmt.columns, TableFromSourceColumns::Defined(_)) {
1197                stmt.columns = TableFromSourceColumns::NotSpecified;
1198            }
1199            // Constraints are never valid input here (purification populates them
1200            // alongside `Defined` columns), so always drop them.
1201            stmt.constraints = Vec::new();
1202        }
1203        // `CREATE SOURCE` statements should roundtrip. However, sources and
1204        // their subsources have a complex relationship, so we need to do a lot
1205        // of work to reconstruct the statement for multi-output sources.
1206        //
1207        // For instance, `DROP SOURCE` statements can leave dangling references
1208        // to subsources that must be filtered out here, that, due to catalog
1209        // transaction limitations, can only be cleaned up when a top-level
1210        // source is altered.
1211        Statement::CreateSource(stmt) => {
1212            // Collect all current subsource references.
1213            let mut curr_references: BTreeMap<UnresolvedItemName, Vec<UnresolvedItemName>> =
1214                catalog
1215                    .get_item(&id)
1216                    .used_by()
1217                    .into_iter()
1218                    .filter_map(|subsource| {
1219                        let item = catalog.get_item(subsource);
1220                        item.subsource_details().map(|(_id, reference, _details)| {
1221                            let name = item.name();
1222                            let subsource_name = catalog.resolve_full_name(name);
1223                            let subsource_name = UnresolvedItemName::from(subsource_name);
1224                            (reference.clone(), subsource_name)
1225                        })
1226                    })
1227                    .fold(BTreeMap::new(), |mut map, (reference, subsource_name)| {
1228                        map.entry(reference)
1229                            .or_insert_with(Vec::new)
1230                            .push(subsource_name);
1231                        map
1232                    });
1233
1234            match &mut stmt.connection {
1235                CreateSourceConnection::Postgres { options, .. } => {
1236                    options.retain_mut(|o| {
1237                        match o.name {
1238                            // Dropping a subsource does not remove any `TEXT
1239                            // COLUMNS` values that refer to the table it
1240                            // ingests, which we'll handle below.
1241                            PgConfigOptionName::TextColumns => {}
1242                            // Drop details, which does not roundtrip.
1243                            PgConfigOptionName::Details => return false,
1244                            _ => return true,
1245                        };
1246                        match &mut o.value {
1247                            Some(WithOptionValue::Sequence(text_cols)) => {
1248                                text_cols.retain(|v| match v {
1249                                    WithOptionValue::UnresolvedItemName(n) => {
1250                                        let mut name = n.clone();
1251                                        // Remove the column reference.
1252                                        name.0.truncate(3);
1253                                        curr_references.contains_key(&name)
1254                                    }
1255                                    _ => unreachable!(
1256                                        "TEXT COLUMNS must be sequence of unresolved item names"
1257                                    ),
1258                                });
1259                                !text_cols.is_empty()
1260                            }
1261                            _ => unreachable!(
1262                                "TEXT COLUMNS must be sequence of unresolved item names"
1263                            ),
1264                        }
1265                    });
1266                }
1267                CreateSourceConnection::SqlServer { options, .. } => {
1268                    // TODO(sql_server2): TEXT and EXCLUDE columns are represented by
1269                    // `schema.table.column` whereas our external table references are
1270                    // `database.schema.table`. We handle the mismatch here but should
1271                    // probably fully qualify our TEXT and EXCLUDE column references.
1272                    let adjusted_references: BTreeSet<_> = curr_references
1273                        .keys()
1274                        .map(|name| {
1275                            if name.0.len() == 3 {
1276                                // Strip the database component of the name.
1277                                let adjusted_name = name.0[1..].to_vec();
1278                                UnresolvedItemName(adjusted_name)
1279                            } else {
1280                                name.clone()
1281                            }
1282                        })
1283                        .collect();
1284
1285                    options.retain_mut(|o| {
1286                        match o.name {
1287                            // Dropping a subsource does not remove any `TEXT COLUMNS`
1288                            // values that refer to the table it ingests, which we'll
1289                            // handle below.
1290                            SqlServerConfigOptionName::TextColumns
1291                            | SqlServerConfigOptionName::ExcludeColumns => {}
1292                            // Drop details, which does not roundtrip.
1293                            SqlServerConfigOptionName::Details => return false,
1294                        };
1295
1296                        match &mut o.value {
1297                            Some(WithOptionValue::Sequence(seq_unresolved_item_names)) => {
1298                                seq_unresolved_item_names.retain(|v| match v {
1299                                    WithOptionValue::UnresolvedItemName(n) => {
1300                                        let mut name = n.clone();
1301                                        // Remove column reference.
1302                                        name.0.truncate(2);
1303                                        adjusted_references.contains(&name)
1304                                    }
1305                                    _ => unreachable!(
1306                                        "TEXT COLUMNS + EXCLUDE COLUMNS must be sequence of unresolved item names"
1307                                    ),
1308                                });
1309                                !seq_unresolved_item_names.is_empty()
1310                            }
1311                            _ => unreachable!(
1312                                "TEXT COLUMNS + EXCLUDE COLUMNS must be sequence of unresolved item names"
1313                            ),
1314                        }
1315                    });
1316                }
1317                CreateSourceConnection::MySql { options, .. } => {
1318                    options.retain_mut(|o| {
1319                        match o.name {
1320                            // Dropping a subsource does not remove any `TEXT
1321                            // COLUMNS` values that refer to the table it
1322                            // ingests, which we'll handle below.
1323                            MySqlConfigOptionName::TextColumns
1324                            | MySqlConfigOptionName::ExcludeColumns => {}
1325                            // Drop details, which does not roundtrip.
1326                            MySqlConfigOptionName::Details => return false,
1327                        };
1328
1329                        match &mut o.value {
1330                            Some(WithOptionValue::Sequence(seq_unresolved_item_names)) => {
1331                                seq_unresolved_item_names.retain(|v| match v {
1332                                    WithOptionValue::UnresolvedItemName(n) => {
1333                                        let mut name = n.clone();
1334                                        // Remove column reference.
1335                                        name.0.truncate(2);
1336                                        curr_references.contains_key(&name)
1337                                    }
1338                                    _ => unreachable!(
1339                                        "TEXT COLUMNS + EXCLUDE COLUMNS must be sequence of unresolved item names"
1340                                    ),
1341                                });
1342                                !seq_unresolved_item_names.is_empty()
1343                            }
1344                            _ => unreachable!(
1345                                "TEXT COLUMNS + EXCLUDE COLUMNS must be sequence of unresolved item names"
1346                            ),
1347                        }
1348                    });
1349                }
1350                CreateSourceConnection::LoadGenerator { .. } if !curr_references.is_empty() => {
1351                    // Load generator sources with any references only support
1352                    // `FOR ALL TABLES`. However, this would change if database-issues#7911
1353                    // landed.
1354                    curr_references.clear();
1355                    stmt.external_references = Some(ExternalReferences::All);
1356                }
1357                CreateSourceConnection::Kafka { .. }
1358                | CreateSourceConnection::LoadGenerator { .. } => {}
1359            }
1360
1361            // If this source has any references, reconstruct them.
1362            if !curr_references.is_empty() {
1363                let mut subsources: Vec<_> = curr_references
1364                    .into_iter()
1365                    .flat_map(|(reference, names)| {
1366                        names.into_iter().map(move |name| ExternalReferenceExport {
1367                            reference: reference.clone(),
1368                            alias: Some(name),
1369                        })
1370                    })
1371                    .collect();
1372                subsources.sort();
1373                stmt.external_references = Some(ExternalReferences::SubsetTables(subsources));
1374            }
1375        }
1376        Statement::CreateSubsource(stmt) => {
1377            stmt.with_options.retain_mut(|o| {
1378                match o.name {
1379                    CreateSubsourceOptionName::TextColumns => true,
1380                    CreateSubsourceOptionName::RetainHistory => true,
1381                    CreateSubsourceOptionName::ExcludeColumns => true,
1382                    // Drop details, which does not roundtrip.
1383                    CreateSubsourceOptionName::Details => false,
1384                    CreateSubsourceOptionName::ExternalReference => true,
1385                    CreateSubsourceOptionName::Progress => true,
1386                }
1387            });
1388        }
1389        Statement::CreateSink(stmt) => {
1390            stmt.with_options.retain_mut(|o| {
1391                match o.name {
1392                    CreateSinkOptionName::CommitInterval => true,
1393                    CreateSinkOptionName::PartitionStrategy => true,
1394                    CreateSinkOptionName::Snapshot => true,
1395                    // Drop version, which does not roundtrip.
1396                    CreateSinkOptionName::Version => false,
1397                }
1398            });
1399        }
1400        _ => (),
1401    }
1402
1403    Ok(mz_sql_pretty::to_pretty(
1404        &resolved,
1405        PrettyConfig {
1406            width: mz_sql_pretty::DEFAULT_WIDTH,
1407            format_mode: if redacted {
1408                FormatMode::SimpleRedacted
1409            } else {
1410                FormatMode::Simple
1411            },
1412        },
1413    ))
1414}