Skip to main content

mz_sql/plan/
statement.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//! Statement planning.
11//!
12//! This module houses the entry points for planning a SQL statement.
13
14use std::cell::RefCell;
15use std::collections::{BTreeMap, BTreeSet};
16use std::sync::{Arc, Mutex};
17
18use mz_repr::namespaces::is_system_schema;
19use mz_repr::{
20    CatalogItemId, ColumnIndex, RelationDesc, RelationVersionSelector, SqlColumnType, SqlScalarType,
21};
22use mz_sql_parser::ast::{
23    ColumnDef, ColumnName, CreateMaterializedViewStatement, RawItemName, ShowStatement,
24    StatementKind, TableConstraint, UnresolvedDatabaseName, UnresolvedSchemaName,
25};
26use mz_storage_types::connections::Connection;
27
28use crate::ast::{Ident, Statement, UnresolvedItemName};
29use crate::catalog::{
30    CatalogCluster, CatalogCollectionItem, CatalogDatabase, CatalogItem, CatalogItemType,
31    CatalogSchema, ObjectType, SessionCatalog, SystemObjectType,
32};
33use crate::names::{
34    self, Aug, DatabaseId, FullItemName, ItemQualifiers, ObjectId, PartialItemName,
35    QualifiedItemName, RawDatabaseSpecifier, ResolvedColumnReference, ResolvedDataType,
36    ResolvedDatabaseSpecifier, ResolvedIds, ResolvedItemName, ResolvedSchemaName, SchemaSpecifier,
37    SystemObjectId,
38};
39use crate::normalize;
40use crate::plan::error::PlanError;
41use crate::plan::{Params, Plan, PlanContext, PlanKind, query};
42use crate::session::vars::FeatureFlag;
43
44mod acl;
45pub(crate) mod ddl;
46mod dml;
47mod raise;
48mod scl;
49pub(crate) mod show;
50mod tcl;
51mod validate;
52
53use crate::session::vars;
54pub(crate) use ddl::PgConfigOptionExtracted;
55use mz_controller_types::ClusterId;
56use mz_pgrepr::oid::{FIRST_MATERIALIZE_OID, FIRST_USER_OID};
57use mz_repr::role_id::RoleId;
58
59/// Describes the output of a SQL statement.
60#[derive(Debug, Clone, Eq, PartialEq)]
61pub struct StatementDesc {
62    /// The shape of the rows produced by the statement, if the statement
63    /// produces rows.
64    pub relation_desc: Option<RelationDesc>,
65    /// The determined types of the parameters in the statement, if any.
66    pub param_types: Vec<SqlScalarType>,
67    /// Whether the statement is a `COPY` statement.
68    pub is_copy: bool,
69}
70
71impl StatementDesc {
72    pub fn new(relation_desc: Option<RelationDesc>) -> Self {
73        StatementDesc {
74            relation_desc,
75            param_types: vec![],
76            is_copy: false,
77        }
78    }
79
80    /// Reports the number of columns in the statement's result set, or zero if
81    /// the statement does not return rows.
82    pub fn arity(&self) -> usize {
83        self.relation_desc
84            .as_ref()
85            .map(|desc| desc.typ().column_types.len())
86            .unwrap_or(0)
87    }
88
89    fn with_params(mut self, param_types: Vec<SqlScalarType>) -> Self {
90        self.param_types = param_types;
91        self
92    }
93
94    fn with_is_copy(mut self) -> Self {
95        self.is_copy = true;
96        self
97    }
98}
99
100/// Creates a description of the purified statement `stmt`.
101///
102/// See the documentation of [`StatementDesc`] for details.
103pub fn describe(
104    pcx: &PlanContext,
105    catalog: &dyn SessionCatalog,
106    stmt: Statement<Aug>,
107    param_types_in: &[Option<SqlScalarType>],
108) -> Result<StatementDesc, PlanError> {
109    let mut param_types = BTreeMap::new();
110    for (i, ty) in param_types_in.iter().enumerate() {
111        if let Some(ty) = ty {
112            param_types.insert(i + 1, ty.clone());
113        }
114    }
115
116    let scx = StatementContext {
117        pcx: Some(pcx),
118        catalog,
119        param_types: RefCell::new(param_types),
120        ambiguous_columns: RefCell::new(false),
121        sql_impl_resolved_ids: Arc::new(Mutex::new(ResolvedIds::empty())),
122    };
123
124    let desc = match stmt {
125        // DDL statements.
126        Statement::AlterCluster(stmt) => ddl::describe_alter_cluster_set_options(&scx, stmt)?,
127        Statement::AlterConnection(stmt) => ddl::describe_alter_connection(&scx, stmt)?,
128        Statement::AlterIndex(stmt) => ddl::describe_alter_index_options(&scx, stmt)?,
129        Statement::AlterMaterializedViewApplyReplacement(stmt) => {
130            ddl::describe_alter_materialized_view_apply_replacement(&scx, stmt)?
131        }
132        Statement::AlterObjectRename(stmt) => ddl::describe_alter_object_rename(&scx, stmt)?,
133        Statement::AlterObjectSwap(stmt) => ddl::describe_alter_object_swap(&scx, stmt)?,
134        Statement::AlterRetainHistory(stmt) => ddl::describe_alter_retain_history(&scx, stmt)?,
135        Statement::AlterRole(stmt) => ddl::describe_alter_role(&scx, stmt)?,
136        Statement::AlterSecret(stmt) => ddl::describe_alter_secret_options(&scx, stmt)?,
137        Statement::AlterSetCluster(stmt) => ddl::describe_alter_set_cluster(&scx, stmt)?,
138        Statement::AlterSink(stmt) => ddl::describe_alter_sink(&scx, stmt)?,
139        Statement::AlterSource(stmt) => ddl::describe_alter_source(&scx, stmt)?,
140        Statement::AlterSystemSet(stmt) => ddl::describe_alter_system_set(&scx, stmt)?,
141        Statement::AlterSystemReset(stmt) => ddl::describe_alter_system_reset(&scx, stmt)?,
142        Statement::AlterSystemResetAll(stmt) => ddl::describe_alter_system_reset_all(&scx, stmt)?,
143        Statement::AlterTableAddColumn(stmt) => ddl::describe_alter_table_add_column(&scx, stmt)?,
144        Statement::AlterNetworkPolicy(stmt) => ddl::describe_alter_network_policy(&scx, stmt)?,
145        Statement::Comment(stmt) => ddl::describe_comment(&scx, stmt)?,
146        Statement::CreateCluster(stmt) => ddl::describe_create_cluster(&scx, stmt)?,
147        Statement::CreateClusterReplica(stmt) => ddl::describe_create_cluster_replica(&scx, stmt)?,
148        Statement::CreateConnection(stmt) => ddl::describe_create_connection(&scx, stmt)?,
149        Statement::CreateDatabase(stmt) => ddl::describe_create_database(&scx, stmt)?,
150        Statement::CreateIndex(stmt) => ddl::describe_create_index(&scx, stmt)?,
151        Statement::CreateRole(stmt) => ddl::describe_create_role(&scx, stmt)?,
152        Statement::CreateSchema(stmt) => ddl::describe_create_schema(&scx, stmt)?,
153        Statement::CreateSecret(stmt) => ddl::describe_create_secret(&scx, stmt)?,
154        Statement::CreateSink(stmt) => ddl::describe_create_sink(&scx, stmt)?,
155        Statement::CreateMetricSink(stmt) => ddl::describe_create_metric_sink(&scx, stmt)?,
156        Statement::CreateWebhookSource(stmt) => ddl::describe_create_webhook_source(&scx, stmt)?,
157        Statement::CreateSource(stmt) => ddl::describe_create_source(&scx, stmt)?,
158        Statement::CreateSubsource(stmt) => ddl::describe_create_subsource(&scx, stmt)?,
159        Statement::CreateTable(stmt) => ddl::describe_create_table(&scx, stmt)?,
160        Statement::CreateTableFromSource(stmt) => {
161            ddl::describe_create_table_from_source(&scx, stmt)?
162        }
163        Statement::CreateType(stmt) => ddl::describe_create_type(&scx, stmt)?,
164        Statement::CreateView(stmt) => ddl::describe_create_view(&scx, stmt)?,
165        Statement::CreateMaterializedView(stmt) => {
166            ddl::describe_create_materialized_view(&scx, stmt)?
167        }
168        Statement::CreateNetworkPolicy(stmt) => ddl::describe_create_network_policy(&scx, stmt)?,
169        Statement::DropObjects(stmt) => ddl::describe_drop_objects(&scx, stmt)?,
170        Statement::DropOwned(stmt) => ddl::describe_drop_owned(&scx, stmt)?,
171
172        // `ACL` statements.
173        Statement::AlterOwner(stmt) => acl::describe_alter_owner(&scx, stmt)?,
174        Statement::GrantRole(stmt) => acl::describe_grant_role(&scx, stmt)?,
175        Statement::RevokeRole(stmt) => acl::describe_revoke_role(&scx, stmt)?,
176        Statement::GrantPrivileges(stmt) => acl::describe_grant_privileges(&scx, stmt)?,
177        Statement::RevokePrivileges(stmt) => acl::describe_revoke_privileges(&scx, stmt)?,
178        Statement::AlterDefaultPrivileges(stmt) => {
179            acl::describe_alter_default_privileges(&scx, stmt)?
180        }
181        Statement::ReassignOwned(stmt) => acl::describe_reassign_owned(&scx, stmt)?,
182
183        // `SHOW` statements.
184        Statement::Show(ShowStatement::ShowColumns(stmt)) => {
185            show::show_columns(&scx, stmt)?.describe()?
186        }
187        Statement::Show(ShowStatement::ShowCreateConnection(stmt)) => {
188            show::describe_show_create_connection(&scx, stmt)?
189        }
190        Statement::Show(ShowStatement::ShowCreateCluster(stmt)) => {
191            show::describe_show_create_cluster(&scx, stmt)?
192        }
193        Statement::Show(ShowStatement::ShowCreateIndex(stmt)) => {
194            show::describe_show_create_index(&scx, stmt)?
195        }
196        Statement::Show(ShowStatement::ShowCreateSink(stmt)) => {
197            show::describe_show_create_sink(&scx, stmt)?
198        }
199        Statement::Show(ShowStatement::ShowCreateSource(stmt)) => {
200            show::describe_show_create_source(&scx, stmt)?
201        }
202        Statement::Show(ShowStatement::ShowCreateTable(stmt)) => {
203            show::describe_show_create_table(&scx, stmt)?
204        }
205        Statement::Show(ShowStatement::ShowCreateView(stmt)) => {
206            show::describe_show_create_view(&scx, stmt)?
207        }
208        Statement::Show(ShowStatement::ShowCreateMaterializedView(stmt)) => {
209            show::describe_show_create_materialized_view(&scx, stmt)?
210        }
211        Statement::Show(ShowStatement::ShowCreateType(stmt)) => {
212            show::describe_show_create_type(&scx, stmt)?
213        }
214        Statement::Show(ShowStatement::ShowObjects(stmt)) => {
215            show::show_objects(&scx, stmt)?.describe()?
216        }
217
218        // SCL statements.
219        Statement::Close(stmt) => scl::describe_close(&scx, stmt)?,
220        Statement::Deallocate(stmt) => scl::describe_deallocate(&scx, stmt)?,
221        Statement::Declare(stmt) => scl::describe_declare(&scx, stmt, param_types_in)?,
222        Statement::Discard(stmt) => scl::describe_discard(&scx, stmt)?,
223        Statement::Execute(stmt) => scl::describe_execute(&scx, stmt)?,
224        Statement::Fetch(stmt) => scl::describe_fetch(&scx, stmt)?,
225        Statement::Prepare(stmt) => scl::describe_prepare(&scx, stmt)?,
226        Statement::ResetVariable(stmt) => scl::describe_reset_variable(&scx, stmt)?,
227        Statement::SetVariable(stmt) => scl::describe_set_variable(&scx, stmt)?,
228        Statement::Show(ShowStatement::ShowVariable(stmt)) => {
229            scl::describe_show_variable(&scx, stmt)?
230        }
231
232        // DML statements.
233        Statement::Copy(stmt) => dml::describe_copy(&scx, stmt)?,
234        Statement::Delete(stmt) => dml::describe_delete(&scx, stmt)?,
235        Statement::ExplainPlan(stmt) => dml::describe_explain_plan(&scx, stmt)?,
236        Statement::ExplainPushdown(stmt) => dml::describe_explain_pushdown(&scx, stmt)?,
237        Statement::ExplainAnalyzeObject(stmt) => dml::describe_explain_analyze_object(&scx, stmt)?,
238        Statement::ExplainAnalyzeCluster(stmt) => {
239            dml::describe_explain_analyze_cluster(&scx, stmt)?
240        }
241        Statement::ExplainTimestamp(stmt) => dml::describe_explain_timestamp(&scx, stmt)?,
242        Statement::ExplainSinkSchema(stmt) => dml::describe_explain_schema(&scx, stmt)?,
243        Statement::Insert(stmt) => dml::describe_insert(&scx, stmt)?,
244        Statement::Select(stmt) => dml::describe_select(&scx, stmt)?,
245        Statement::Subscribe(stmt) => dml::describe_subscribe(&scx, stmt)?,
246        Statement::Update(stmt) => dml::describe_update(&scx, stmt)?,
247
248        // TCL statements.
249        Statement::Commit(stmt) => tcl::describe_commit(&scx, stmt)?,
250        Statement::Rollback(stmt) => tcl::describe_rollback(&scx, stmt)?,
251        Statement::SetTransaction(stmt) => tcl::describe_set_transaction(&scx, stmt)?,
252        Statement::StartTransaction(stmt) => tcl::describe_start_transaction(&scx, stmt)?,
253
254        // Other statements.
255        Statement::Raise(stmt) => raise::describe_raise(&scx, stmt)?,
256        Statement::Show(ShowStatement::InspectShard(stmt)) => {
257            scl::describe_inspect_shard(&scx, stmt)?
258        }
259        Statement::ValidateConnection(stmt) => validate::describe_validate_connection(&scx, stmt)?,
260        Statement::ExecuteUnitTest(_) => {
261            return Err(PlanError::Unsupported {
262                feature: "EXECUTE UNIT TEST statement".to_string(),
263                discussion_no: None,
264            });
265        }
266    };
267
268    let desc = desc.with_params(scx.finalize_param_types()?);
269    Ok(desc)
270}
271
272/// Produces a [`Plan`] from the purified statement `stmt`.
273///
274/// Planning is a pure, synchronous function and so requires that the provided
275/// `stmt` does does not depend on any external state. Statements that rely on
276/// external state must remove that state prior to calling this function via
277/// [`crate::pure::purify_statement`] or
278/// [`crate::pure::purify_create_materialized_view_options`].
279///
280/// The returned plan is tied to the state of the provided catalog. If the state
281/// of the catalog changes after planning, the validity of the plan is not
282/// guaranteed.
283///
284/// Note that if you want to do something else asynchronously (e.g. validating
285/// connections), these might want to take different code paths than
286/// `purify_statement`. Feel free to rationalize this by thinking of those
287/// statements as not necessarily depending on external state.
288#[mz_ore::instrument(level = "debug")]
289pub fn plan(
290    pcx: Option<&PlanContext>,
291    catalog: &dyn SessionCatalog,
292    stmt: Statement<Aug>,
293    params: &Params,
294    resolved_ids: &ResolvedIds,
295) -> Result<(Plan, ResolvedIds), PlanError> {
296    let param_types = params
297        // We need the `expected_types` here, not the `actual_types`! This is because
298        // `expected_types` is how the parameter expression (e.g. `$1`) looks "from the outside":
299        // `bind_parameters` will insert a cast from the actual type to the expected type.
300        .expected_types
301        .iter()
302        .enumerate()
303        .map(|(i, ty)| (i + 1, ty.clone()))
304        .collect();
305
306    let kind: StatementKind = (&stmt).into();
307    let permitted_plans = Plan::generated_from(&kind);
308
309    let scx = &mut StatementContext {
310        pcx,
311        catalog,
312        param_types: RefCell::new(param_types),
313        ambiguous_columns: RefCell::new(false),
314        sql_impl_resolved_ids: Arc::new(Mutex::new(ResolvedIds::empty())),
315    };
316
317    if resolved_ids
318        .items()
319        // Filter out items that may not have been created yet, such as sub-sources.
320        .filter_map(|id| catalog.try_get_item(id))
321        .any(|item| {
322            item.func().is_ok()
323                && item.name().qualifiers.schema_spec
324                    == SchemaSpecifier::Id(catalog.get_mz_unsafe_schema_id())
325        })
326    {
327        scx.require_feature_flag(&vars::UNSAFE_ENABLE_UNSAFE_FUNCTIONS)?;
328    }
329
330    let plan = match stmt {
331        // DDL statements.
332        Statement::AlterCluster(stmt) => ddl::plan_alter_cluster(scx, stmt),
333        Statement::AlterConnection(stmt) => ddl::plan_alter_connection(scx, stmt),
334        Statement::AlterIndex(stmt) => ddl::plan_alter_index_options(scx, stmt),
335        Statement::AlterMaterializedViewApplyReplacement(stmt) => {
336            ddl::plan_alter_materialized_view_apply_replacement(scx, stmt)
337        }
338        Statement::AlterObjectRename(stmt) => ddl::plan_alter_object_rename(scx, stmt),
339        Statement::AlterObjectSwap(stmt) => ddl::plan_alter_object_swap(scx, stmt),
340        Statement::AlterRetainHistory(stmt) => ddl::plan_alter_retain_history(scx, stmt),
341        Statement::AlterRole(stmt) => ddl::plan_alter_role(scx, stmt),
342        Statement::AlterSecret(stmt) => ddl::plan_alter_secret(scx, stmt),
343        Statement::AlterSetCluster(stmt) => ddl::plan_alter_item_set_cluster(scx, stmt),
344        Statement::AlterSink(stmt) => ddl::plan_alter_sink(scx, stmt),
345        Statement::AlterSource(stmt) => ddl::plan_alter_source(scx, stmt),
346        Statement::AlterSystemSet(stmt) => ddl::plan_alter_system_set(scx, stmt),
347        Statement::AlterSystemReset(stmt) => ddl::plan_alter_system_reset(scx, stmt),
348        Statement::AlterSystemResetAll(stmt) => ddl::plan_alter_system_reset_all(scx, stmt),
349        Statement::AlterTableAddColumn(stmt) => ddl::plan_alter_table_add_column(scx, stmt),
350        Statement::AlterNetworkPolicy(stmt) => ddl::plan_alter_network_policy(scx, stmt),
351        Statement::Comment(stmt) => ddl::plan_comment(scx, stmt),
352        Statement::CreateCluster(stmt) => ddl::plan_create_cluster(scx, stmt),
353        Statement::CreateClusterReplica(stmt) => ddl::plan_create_cluster_replica(scx, stmt),
354        Statement::CreateConnection(stmt) => ddl::plan_create_connection(scx, stmt),
355        Statement::CreateDatabase(stmt) => ddl::plan_create_database(scx, stmt),
356        Statement::CreateIndex(stmt) => ddl::plan_create_index(scx, stmt),
357        Statement::CreateRole(stmt) => ddl::plan_create_role(scx, stmt),
358        Statement::CreateSchema(stmt) => ddl::plan_create_schema(scx, stmt),
359        Statement::CreateSecret(stmt) => ddl::plan_create_secret(scx, stmt),
360        Statement::CreateSink(stmt) => ddl::plan_create_sink(scx, stmt),
361        Statement::CreateMetricSink(stmt) => ddl::plan_create_metric_sink(scx, stmt),
362        Statement::CreateWebhookSource(stmt) => ddl::plan_create_webhook_source(scx, stmt),
363        Statement::CreateSource(stmt) => ddl::plan_create_source(scx, stmt),
364        Statement::CreateSubsource(stmt) => ddl::plan_create_subsource(scx, stmt),
365        Statement::CreateTable(stmt) => ddl::plan_create_table(scx, stmt),
366        Statement::CreateTableFromSource(stmt) => ddl::plan_create_table_from_source(scx, stmt),
367        Statement::CreateType(stmt) => ddl::plan_create_type(scx, stmt),
368        Statement::CreateView(stmt) => ddl::plan_create_view(scx, stmt),
369        Statement::CreateMaterializedView(stmt) => ddl::plan_create_materialized_view(scx, stmt),
370        Statement::CreateNetworkPolicy(stmt) => ddl::plan_create_network_policy(scx, stmt),
371        Statement::DropObjects(stmt) => ddl::plan_drop_objects(scx, stmt),
372        Statement::DropOwned(stmt) => ddl::plan_drop_owned(scx, stmt),
373
374        // `ACL` statements.
375        Statement::AlterOwner(stmt) => acl::plan_alter_owner(scx, stmt),
376        Statement::GrantRole(stmt) => acl::plan_grant_role(scx, stmt),
377        Statement::RevokeRole(stmt) => acl::plan_revoke_role(scx, stmt),
378        Statement::GrantPrivileges(stmt) => acl::plan_grant_privileges(scx, stmt),
379        Statement::RevokePrivileges(stmt) => acl::plan_revoke_privileges(scx, stmt),
380        Statement::AlterDefaultPrivileges(stmt) => acl::plan_alter_default_privileges(scx, stmt),
381        Statement::ReassignOwned(stmt) => acl::plan_reassign_owned(scx, stmt),
382
383        // DML statements.
384        Statement::Copy(stmt) => dml::plan_copy(scx, stmt),
385        Statement::Delete(stmt) => dml::plan_delete(scx, stmt, params),
386        Statement::ExplainPlan(stmt) => dml::plan_explain_plan(scx, stmt, params),
387        Statement::ExplainPushdown(stmt) => dml::plan_explain_pushdown(scx, stmt, params),
388        Statement::ExplainAnalyzeObject(stmt) => {
389            dml::plan_explain_analyze_object(scx, stmt, params)
390        }
391        Statement::ExplainAnalyzeCluster(stmt) => {
392            dml::plan_explain_analyze_cluster(scx, stmt, params)
393        }
394        Statement::ExplainTimestamp(stmt) => dml::plan_explain_timestamp(scx, stmt),
395        Statement::ExplainSinkSchema(stmt) => dml::plan_explain_schema(scx, stmt),
396        Statement::Insert(stmt) => dml::plan_insert(scx, stmt, params),
397        Statement::Select(stmt) => dml::plan_select(scx, stmt, params, None),
398        Statement::Subscribe(stmt) => dml::plan_subscribe(scx, stmt, params, None),
399        Statement::Update(stmt) => dml::plan_update(scx, stmt, params),
400
401        // `SHOW` statements.
402        Statement::Show(ShowStatement::ShowColumns(stmt)) => show::show_columns(scx, stmt)?.plan(),
403        Statement::Show(ShowStatement::ShowCreateConnection(stmt)) => {
404            show::plan_show_create_connection(scx, stmt).map(Plan::ShowCreate)
405        }
406        Statement::Show(ShowStatement::ShowCreateCluster(stmt)) => {
407            show::plan_show_create_cluster(scx, stmt).map(Plan::ShowCreate)
408        }
409        Statement::Show(ShowStatement::ShowCreateIndex(stmt)) => {
410            show::plan_show_create_index(scx, stmt).map(Plan::ShowCreate)
411        }
412        Statement::Show(ShowStatement::ShowCreateSink(stmt)) => {
413            show::plan_show_create_sink(scx, stmt).map(Plan::ShowCreate)
414        }
415        Statement::Show(ShowStatement::ShowCreateSource(stmt)) => {
416            show::plan_show_create_source(scx, stmt).map(Plan::ShowCreate)
417        }
418        Statement::Show(ShowStatement::ShowCreateTable(stmt)) => {
419            show::plan_show_create_table(scx, stmt).map(Plan::ShowCreate)
420        }
421        Statement::Show(ShowStatement::ShowCreateView(stmt)) => {
422            show::plan_show_create_view(scx, stmt).map(Plan::ShowCreate)
423        }
424        Statement::Show(ShowStatement::ShowCreateMaterializedView(stmt)) => {
425            show::plan_show_create_materialized_view(scx, stmt).map(Plan::ShowCreate)
426        }
427        Statement::Show(ShowStatement::ShowCreateType(stmt)) => {
428            show::plan_show_create_type(scx, stmt).map(Plan::ShowCreate)
429        }
430        Statement::Show(ShowStatement::ShowObjects(stmt)) => show::show_objects(scx, stmt)?.plan(),
431
432        // SCL statements.
433        Statement::Close(stmt) => scl::plan_close(scx, stmt),
434        Statement::Deallocate(stmt) => scl::plan_deallocate(scx, stmt),
435        Statement::Declare(stmt) => scl::plan_declare(scx, stmt, params),
436        Statement::Discard(stmt) => scl::plan_discard(scx, stmt),
437        Statement::Execute(stmt) => scl::plan_execute(scx, stmt),
438        Statement::Fetch(stmt) => scl::plan_fetch(scx, stmt),
439        Statement::Prepare(stmt) => scl::plan_prepare(scx, stmt),
440        Statement::ResetVariable(stmt) => scl::plan_reset_variable(scx, stmt),
441        Statement::SetVariable(stmt) => scl::plan_set_variable(scx, stmt),
442        Statement::Show(ShowStatement::ShowVariable(stmt)) => scl::plan_show_variable(scx, stmt),
443
444        // TCL statements.
445        Statement::Commit(stmt) => tcl::plan_commit(scx, stmt),
446        Statement::Rollback(stmt) => tcl::plan_rollback(scx, stmt),
447        Statement::SetTransaction(stmt) => tcl::plan_set_transaction(scx, stmt),
448        Statement::StartTransaction(stmt) => tcl::plan_start_transaction(scx, stmt),
449
450        // Other statements.
451        Statement::Raise(stmt) => raise::plan_raise(scx, stmt),
452        Statement::Show(ShowStatement::InspectShard(stmt)) => scl::plan_inspect_shard(scx, stmt),
453        Statement::ValidateConnection(stmt) => validate::plan_validate_connection(scx, stmt),
454        Statement::ExecuteUnitTest(_) => {
455            return Err(PlanError::Unsupported {
456                feature: "EXECUTE UNIT TEST statement".to_string(),
457                discussion_no: None,
458            });
459        }
460    };
461
462    if let Ok(plan) = &plan {
463        mz_ore::soft_assert_no_log!(
464            permitted_plans.contains(&PlanKind::from(plan)),
465            "plan {:?}, permitted plans {:?}",
466            plan,
467            permitted_plans
468        );
469    }
470
471    // Return the plan along with any resolved IDs accumulated from sql_impl
472    // function bodies. These are kept separate from the main resolved_ids
473    // because they are implementation details of the functions, not real
474    // dependencies of the statement. They should only be used for the
475    // restrict_to_user_objects RBAC check.
476    let sql_impl_ids = scx
477        .sql_impl_resolved_ids
478        .lock()
479        .expect("planning is single-threaded")
480        .clone();
481    plan.map(|p| (p, sql_impl_ids))
482}
483
484pub fn plan_copy_from(
485    pcx: &PlanContext,
486    catalog: &dyn SessionCatalog,
487    target_id: CatalogItemId,
488    target_name: String,
489    columns: Vec<ColumnIndex>,
490    rows: Vec<mz_repr::Row>,
491) -> Result<super::HirRelationExpr, PlanError> {
492    query::plan_copy_from_rows(pcx, catalog, target_id, target_name, columns, rows)
493}
494
495/// Whether a SQL object type can be interpreted as matching the type of the given catalog item.
496/// For example, if `v` is a view, `DROP SOURCE v` should not work, since Source and View
497/// are non-matching types.
498///
499/// For now tables are treated as a special kind of source in Materialize, so just
500/// allow `TABLE` to refer to either.
501impl PartialEq<ObjectType> for CatalogItemType {
502    fn eq(&self, other: &ObjectType) -> bool {
503        match (self, other) {
504            (CatalogItemType::Source, ObjectType::Source)
505            | (CatalogItemType::Table, ObjectType::Table)
506            | (CatalogItemType::Sink, ObjectType::Sink)
507            | (CatalogItemType::MetricSink, ObjectType::MetricSink)
508            | (CatalogItemType::View, ObjectType::View)
509            | (CatalogItemType::MaterializedView, ObjectType::MaterializedView)
510            | (CatalogItemType::Index, ObjectType::Index)
511            | (CatalogItemType::Type, ObjectType::Type)
512            | (CatalogItemType::Secret, ObjectType::Secret)
513            | (CatalogItemType::Connection, ObjectType::Connection) => true,
514            (_, _) => false,
515        }
516    }
517}
518
519impl PartialEq<CatalogItemType> for ObjectType {
520    fn eq(&self, other: &CatalogItemType) -> bool {
521        other == self
522    }
523}
524
525/// Immutable state that applies to the planning of an entire `Statement`.
526#[derive(Debug, Clone)]
527pub struct StatementContext<'a> {
528    /// The optional PlanContext, which will be present for statements that execute
529    /// within the OneShot QueryLifetime and None otherwise (views). This is an
530    /// awkward field and should probably be relocated to a place that fits our
531    /// execution model more closely.
532    pcx: Option<&'a PlanContext>,
533    pub catalog: &'a dyn SessionCatalog,
534    /// The types of the parameters in the query. This is filled in as planning
535    /// occurs.
536    pub param_types: RefCell<BTreeMap<usize, SqlScalarType>>,
537    /// Whether the statement contains an expression that can make the exact column list
538    /// ambiguous. For example `NATURAL JOIN` or `SELECT *`. This is filled in as planning occurs.
539    pub ambiguous_columns: RefCell<bool>,
540    /// Accumulates resolved IDs from SQL-implemented function bodies (`sql_impl_func`,
541    /// `sql_impl_table_func`). These are kept separate from the statement's main
542    /// `resolved_ids` because they are implementation details of the functions, not
543    /// real dependencies of the statement. They are only used for the
544    /// `restrict_to_user_objects` RBAC check.
545    ///
546    /// Uses `Arc<Mutex<_>>` so that cloned `StatementContext`s (as in `sql_impl`)
547    /// share the same underlying storage. `Arc` (vs `Rc`) is needed because
548    /// `StatementContext` must be `Send`.
549    pub sql_impl_resolved_ids: Arc<Mutex<ResolvedIds>>,
550}
551
552impl<'a> StatementContext<'a> {
553    pub fn new(
554        pcx: Option<&'a PlanContext>,
555        catalog: &'a dyn SessionCatalog,
556    ) -> StatementContext<'a> {
557        StatementContext {
558            pcx,
559            catalog,
560            param_types: Default::default(),
561            ambiguous_columns: RefCell::new(false),
562            sql_impl_resolved_ids: Arc::new(Mutex::new(ResolvedIds::empty())),
563        }
564    }
565
566    /// Returns the schemas in order of search_path that exist in the catalog.
567    pub fn current_schemas(&self) -> &[(ResolvedDatabaseSpecifier, SchemaSpecifier)] {
568        self.catalog.search_path()
569    }
570
571    /// Returns the first schema from the search_path that exist in the catalog,
572    /// or None if there are none.
573    pub fn current_schema(&self) -> Option<&(ResolvedDatabaseSpecifier, SchemaSpecifier)> {
574        self.current_schemas().into_iter().next()
575    }
576
577    pub fn pcx(&self) -> Result<&PlanContext, PlanError> {
578        self.pcx.ok_or_else(|| sql_err!("no plan context"))
579    }
580
581    /// Records resolved IDs from a SQL-implemented expression body (e.g. a SHOW
582    /// command's inner query or an EXPLAIN ANALYZE query) into the accumulator
583    /// checked by `restrict_to_user_objects`. These are kept separate from the
584    /// statement's main `resolved_ids` because they are implementation details,
585    /// not real dependencies.
586    pub(crate) fn record_sql_impl_ids(&self, ids: &ResolvedIds) {
587        self.sql_impl_resolved_ids
588            .lock()
589            .expect("planning is single-threaded")
590            .extend_from(ids);
591    }
592
593    pub fn allocate_full_name(&self, name: PartialItemName) -> Result<FullItemName, PlanError> {
594        let (database, schema): (RawDatabaseSpecifier, String) = match (name.database, name.schema)
595        {
596            (None, None) => {
597                let Some((database, schema)) = self.current_schema() else {
598                    return Err(PlanError::InvalidSchemaName);
599                };
600                let schema = self.get_schema(database, schema);
601                let database = match schema.database() {
602                    ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
603                    ResolvedDatabaseSpecifier::Id(id) => {
604                        RawDatabaseSpecifier::Name(self.catalog.get_database(id).name().to_string())
605                    }
606                };
607                (database, schema.name().schema.clone())
608            }
609            (None, Some(schema)) => {
610                if is_system_schema(&schema) {
611                    (RawDatabaseSpecifier::Ambient, schema)
612                } else {
613                    match self.catalog.active_database_name() {
614                        Some(name) => (RawDatabaseSpecifier::Name(name.to_string()), schema),
615                        None => {
616                            sql_bail!(
617                                "no database specified for non-system schema and no active database"
618                            )
619                        }
620                    }
621                }
622            }
623            (Some(_database), None) => {
624                // This shouldn't be possible. Refactor the datastructure to
625                // make it not exist.
626                sql_bail!("unreachable: specified the database but no schema")
627            }
628            (Some(database), Some(schema)) => (RawDatabaseSpecifier::Name(database), schema),
629        };
630        let item = name.item;
631        Ok(FullItemName {
632            database,
633            schema,
634            item,
635        })
636    }
637
638    pub fn allocate_qualified_name(
639        &self,
640        name: PartialItemName,
641    ) -> Result<QualifiedItemName, PlanError> {
642        let full_name = self.allocate_full_name(name)?;
643        let database_spec = match full_name.database {
644            RawDatabaseSpecifier::Ambient => ResolvedDatabaseSpecifier::Ambient,
645            RawDatabaseSpecifier::Name(name) => ResolvedDatabaseSpecifier::Id(
646                self.resolve_database(&UnresolvedDatabaseName(Ident::new(name)?))?
647                    .id(),
648            ),
649        };
650        let schema_spec = self
651            .resolve_schema_in_database(&database_spec, &Ident::new(full_name.schema)?)?
652            .id()
653            .clone();
654        Ok(QualifiedItemName {
655            qualifiers: ItemQualifiers {
656                database_spec,
657                schema_spec,
658            },
659            item: full_name.item,
660        })
661    }
662
663    pub fn allocate_temporary_full_name(&self, name: PartialItemName) -> FullItemName {
664        FullItemName {
665            database: RawDatabaseSpecifier::Ambient,
666            schema: name
667                .schema
668                .unwrap_or_else(|| mz_repr::namespaces::MZ_TEMP_SCHEMA.to_owned()),
669            item: name.item,
670        }
671    }
672
673    pub fn allocate_temporary_qualified_name(
674        &self,
675        name: PartialItemName,
676    ) -> Result<QualifiedItemName, PlanError> {
677        // Compare against the MZ_TEMP_SCHEMA constant directly instead of calling
678        // get_schema(), because with lazy temporary schema creation, the temp
679        // schema may not exist yet. (This is similar to what `allocate_temporary_full_name` was
680        // doing already before making temporary schemas lazy.)
681        if let Some(schema_name) = name.schema {
682            if schema_name != mz_repr::namespaces::MZ_TEMP_SCHEMA {
683                return Err(PlanError::InvalidTemporarySchema);
684            }
685        }
686
687        Ok(QualifiedItemName {
688            qualifiers: ItemQualifiers {
689                database_spec: ResolvedDatabaseSpecifier::Ambient,
690                schema_spec: SchemaSpecifier::Temporary,
691            },
692            item: name.item,
693        })
694    }
695
696    // Creates a `ResolvedItemName::Item` from a `GlobalId` and an
697    // `UnresolvedItemName`.
698    pub fn allocate_resolved_item_name(
699        &self,
700        id: CatalogItemId,
701        name: UnresolvedItemName,
702    ) -> Result<ResolvedItemName, PlanError> {
703        let partial = normalize::unresolved_item_name(name)?;
704        let qualified = self.allocate_qualified_name(partial.clone())?;
705        let full_name = self.allocate_full_name(partial)?;
706        Ok(ResolvedItemName::Item {
707            id,
708            qualifiers: qualified.qualifiers,
709            full_name,
710            print_id: true,
711            version: RelationVersionSelector::Latest,
712        })
713    }
714
715    pub fn active_database(&self) -> Option<&DatabaseId> {
716        self.catalog.active_database()
717    }
718
719    pub fn resolve_optional_schema(
720        &self,
721        schema_name: &Option<ResolvedSchemaName>,
722    ) -> Result<SchemaSpecifier, PlanError> {
723        match schema_name {
724            Some(ResolvedSchemaName::Schema { schema_spec, .. }) => Ok(schema_spec.clone()),
725            None => self.resolve_active_schema().map(|spec| spec.clone()),
726            Some(ResolvedSchemaName::Error) => {
727                unreachable!("should have been handled by name resolution")
728            }
729        }
730    }
731
732    pub fn resolve_active_schema(&self) -> Result<&SchemaSpecifier, PlanError> {
733        match self.current_schema() {
734            Some((_db, schema)) => Ok(schema),
735            None => Err(PlanError::InvalidSchemaName),
736        }
737    }
738
739    pub fn get_cluster(&self, id: &ClusterId) -> &dyn CatalogCluster<'_> {
740        self.catalog.get_cluster(*id)
741    }
742
743    pub fn resolve_database(
744        &self,
745        name: &UnresolvedDatabaseName,
746    ) -> Result<&dyn CatalogDatabase, PlanError> {
747        let name = normalize::ident_ref(&name.0);
748        Ok(self.catalog.resolve_database(name)?)
749    }
750
751    pub fn get_database(&self, id: &DatabaseId) -> &dyn CatalogDatabase {
752        self.catalog.get_database(id)
753    }
754
755    pub fn resolve_schema_in_database(
756        &self,
757        database_spec: &ResolvedDatabaseSpecifier,
758        schema: &Ident,
759    ) -> Result<&dyn CatalogSchema, PlanError> {
760        let schema = normalize::ident_ref(schema);
761        Ok(self
762            .catalog
763            .resolve_schema_in_database(database_spec, schema)?)
764    }
765
766    pub fn resolve_schema(
767        &self,
768        name: UnresolvedSchemaName,
769    ) -> Result<&dyn CatalogSchema, PlanError> {
770        let name = normalize::unresolved_schema_name(name)?;
771        Ok(self
772            .catalog
773            .resolve_schema(name.database.as_deref(), &name.schema)?)
774    }
775
776    pub fn get_schema(
777        &self,
778        database_spec: &ResolvedDatabaseSpecifier,
779        schema_spec: &SchemaSpecifier,
780    ) -> &dyn CatalogSchema {
781        self.catalog.get_schema(database_spec, schema_spec)
782    }
783
784    pub fn resolve_item(&self, name: RawItemName) -> Result<&dyn CatalogItem, PlanError> {
785        match name {
786            RawItemName::Name(name) => {
787                let name = normalize::unresolved_item_name(name)?;
788                Ok(self.catalog.resolve_item(&name)?)
789            }
790            RawItemName::Id(id, _, _) => {
791                let gid = id.parse()?;
792                Ok(self.catalog.get_item(&gid))
793            }
794        }
795    }
796
797    pub fn get_item(&self, id: &CatalogItemId) -> &dyn CatalogItem {
798        self.catalog.get_item(id)
799    }
800
801    pub fn get_item_by_resolved_name(
802        &self,
803        name: &ResolvedItemName,
804    ) -> Result<Box<dyn CatalogCollectionItem + '_>, PlanError> {
805        match name {
806            ResolvedItemName::Item { id, version, .. } => {
807                Ok(self.get_item(id).at_version(*version))
808            }
809            ResolvedItemName::Cte { .. } => sql_bail!("non-user item"),
810            ResolvedItemName::Error => unreachable!("should have been caught in name resolution"),
811        }
812    }
813
814    pub fn get_column_by_resolved_name(
815        &self,
816        name: &ColumnName<Aug>,
817    ) -> Result<(Box<dyn CatalogCollectionItem + '_>, usize), PlanError> {
818        match (&name.relation, &name.column) {
819            (
820                ResolvedItemName::Item { id, version, .. },
821                ResolvedColumnReference::Column { index, .. },
822            ) => {
823                let item = self.get_item(id).at_version(*version);
824                Ok((item, *index))
825            }
826            _ => unreachable!(
827                "get_column_by_resolved_name errors should have been caught in name resolution"
828            ),
829        }
830    }
831
832    pub fn resolve_function(
833        &self,
834        name: UnresolvedItemName,
835    ) -> Result<&dyn CatalogItem, PlanError> {
836        let name = normalize::unresolved_item_name(name)?;
837        Ok(self.catalog.resolve_function(&name)?)
838    }
839
840    pub fn resolve_cluster(
841        &self,
842        name: Option<&Ident>,
843    ) -> Result<&dyn CatalogCluster<'_>, PlanError> {
844        let name = name.map(|name| name.as_str());
845        Ok(self.catalog.resolve_cluster(name)?)
846    }
847
848    pub fn resolve_type(&self, mut ty: mz_pgrepr::Type) -> Result<ResolvedDataType, PlanError> {
849        // Ignore precision constraints on date/time types until we support
850        // it. This should be safe enough because our types are wide enough
851        // to support the maximum possible precision.
852        //
853        // See: https://github.com/MaterializeInc/database-issues/issues/3179
854        match &mut ty {
855            mz_pgrepr::Type::Interval { constraints } => *constraints = None,
856            mz_pgrepr::Type::Time { precision } => *precision = None,
857            mz_pgrepr::Type::TimeTz { precision } => *precision = None,
858            mz_pgrepr::Type::Timestamp { precision } => *precision = None,
859            mz_pgrepr::Type::TimestampTz { precision } => *precision = None,
860            _ => (),
861        }
862        // NOTE(benesch): this *looks* gross, but it is
863        // safe enough. The `fmt::Display`
864        // representation on `pgrepr::Type` promises to
865        // produce an unqualified type name that does
866        // not require quoting.
867        let mut ty = if ty.oid() >= FIRST_USER_OID {
868            sql_bail!("internal error, unexpected user type: {ty:?} ");
869        } else if ty.oid() < FIRST_MATERIALIZE_OID {
870            format!("pg_catalog.{}", ty)
871        } else {
872            // This relies on all non-PG types existing in `mz_catalog`, which is annoying.
873            format!("mz_catalog.{}", ty)
874        };
875        // TODO(benesch): converting `json` to `jsonb`
876        // is wrong. We ought to support the `json` type
877        // directly.
878        if ty == "pg_catalog.json" {
879            ty = "pg_catalog.jsonb".into();
880        }
881        let data_type = mz_sql_parser::parser::parse_data_type(&ty)?;
882        let (data_type, _) = names::resolve(self.catalog, data_type)?;
883        Ok(data_type)
884    }
885
886    pub fn get_object_type(&self, id: &ObjectId) -> ObjectType {
887        self.catalog.get_object_type(id)
888    }
889
890    pub fn get_system_object_type(&self, id: &SystemObjectId) -> SystemObjectType {
891        match id {
892            SystemObjectId::Object(id) => SystemObjectType::Object(self.get_object_type(id)),
893            SystemObjectId::System => SystemObjectType::System,
894        }
895    }
896
897    /// Returns an error if the named `FeatureFlag` is not set to `on`.
898    pub fn require_feature_flag(&self, flag: &'static FeatureFlag) -> Result<(), PlanError> {
899        flag.require(self.catalog.system_vars())?;
900        Ok(())
901    }
902
903    /// Returns true if the named [`FeatureFlag`] is set to `on`, returns false otherwise.
904    pub fn is_feature_flag_enabled(&self, flag: &'static FeatureFlag) -> bool {
905        self.require_feature_flag(flag).is_ok()
906    }
907
908    pub fn finalize_param_types(self) -> Result<Vec<SqlScalarType>, PlanError> {
909        let param_types = self.param_types.into_inner();
910        let mut out = vec![];
911        for (i, (n, typ)) in param_types.into_iter().enumerate() {
912            if n != i + 1 {
913                sql_bail!("unable to infer type for parameter ${}", i + 1);
914            }
915            out.push(typ);
916        }
917        Ok(out)
918    }
919
920    /// The returned String is more detailed when the `postgres_compat` flag is not set. However,
921    /// the flag should be set in, e.g., the implementation of the `pg_typeof` function.
922    pub fn humanize_sql_scalar_type(&self, typ: &SqlScalarType, postgres_compat: bool) -> String {
923        self.catalog.humanize_sql_scalar_type(typ, postgres_compat)
924    }
925
926    /// The returned String is more detailed when the `postgres_compat` flag is not set. However,
927    /// the flag should be set in, e.g., the implementation of the `pg_typeof` function.
928    pub fn humanize_column_type(&self, typ: &SqlColumnType, postgres_compat: bool) -> String {
929        self.catalog.humanize_sql_column_type(typ, postgres_compat)
930    }
931
932    pub fn relation_desc_into_table_defs(
933        &self,
934        desc: &RelationDesc,
935    ) -> Result<(Vec<ColumnDef<Aug>>, Vec<TableConstraint<Aug>>), PlanError> {
936        let mut columns = vec![];
937        let mut null_cols = BTreeSet::new();
938        for (column_name, column_type) in desc.iter() {
939            let name = Ident::new(column_name.as_str().to_owned())?;
940
941            let ty = mz_pgrepr::Type::from(&column_type.scalar_type);
942            let data_type = self.resolve_type(ty)?;
943
944            let options = if !column_type.nullable {
945                null_cols.insert(columns.len());
946                vec![mz_sql_parser::ast::ColumnOptionDef {
947                    name: None,
948                    option: mz_sql_parser::ast::ColumnOption::NotNull,
949                }]
950            } else {
951                vec![]
952            };
953
954            columns.push(ColumnDef {
955                name,
956                data_type,
957                collation: None,
958                options,
959            });
960        }
961
962        let mut table_constraints = vec![];
963        for key in desc.typ().keys.iter() {
964            let mut col_names = vec![];
965            for col_idx in key {
966                if !null_cols.contains(col_idx) {
967                    // Note that alternatively we could support NULL values in keys with `NULLS NOT
968                    // DISTINCT` semantics, which treats `NULL` as a distinct value.
969                    sql_bail!(
970                        "[internal error] key columns must be NOT NULL when generating table constraints"
971                    );
972                }
973                col_names.push(columns[*col_idx].name.clone());
974            }
975            table_constraints.push(TableConstraint::Unique {
976                name: None,
977                columns: col_names,
978                is_primary: false,
979                nulls_not_distinct: false,
980            });
981        }
982
983        Ok((columns, table_constraints))
984    }
985
986    pub fn get_owner_id(&self, id: &ObjectId) -> Option<RoleId> {
987        self.catalog.get_owner_id(id)
988    }
989
990    pub fn humanize_resolved_name(
991        &self,
992        name: &ResolvedItemName,
993    ) -> Result<PartialItemName, PlanError> {
994        let item = self.get_item_by_resolved_name(name)?;
995        Ok(self.catalog.minimal_qualification(item.name()))
996    }
997
998    /// WARNING! This style of name resolution assumes the referred-to objects exists (i.e. panics
999    /// if objects do not exist) so should never be used to handle user input.
1000    pub fn dangerous_resolve_name(&self, name: Vec<&str>) -> ResolvedItemName {
1001        tracing::trace!("dangerous_resolve_name {:?}", name);
1002        // Note: Using unchecked here is okay because this function is already dangerous.
1003        let name: Vec<_> = name.into_iter().map(Ident::new_unchecked).collect();
1004        let name = UnresolvedItemName::qualified(&name);
1005        let entry = match self.resolve_item(RawItemName::Name(name.clone())) {
1006            Ok(entry) => entry,
1007            Err(_) => self
1008                .resolve_function(name.clone())
1009                .expect("name referred to an existing object"),
1010        };
1011
1012        let partial = normalize::unresolved_item_name(name).unwrap();
1013        let full_name = self.allocate_full_name(partial).unwrap();
1014
1015        ResolvedItemName::Item {
1016            id: entry.id(),
1017            qualifiers: entry.name().qualifiers.clone(),
1018            full_name,
1019            print_id: true,
1020            version: RelationVersionSelector::Latest,
1021        }
1022    }
1023}
1024
1025pub fn resolve_cluster_for_materialized_view<'a>(
1026    catalog: &'a dyn SessionCatalog,
1027    stmt: &CreateMaterializedViewStatement<Aug>,
1028) -> Result<ClusterId, PlanError> {
1029    Ok(match &stmt.in_cluster {
1030        None => catalog.resolve_cluster(None)?.id(),
1031        Some(in_cluster) => in_cluster.id,
1032    })
1033}
1034
1035/// Statement classification as documented by [`plan`].
1036#[derive(Debug, Clone, Copy)]
1037pub enum StatementClassification {
1038    ACL,
1039    DDL,
1040    DML,
1041    Other,
1042    SCL,
1043    Show,
1044    TCL,
1045}
1046
1047impl StatementClassification {
1048    pub fn is_ddl(&self) -> bool {
1049        matches!(self, StatementClassification::DDL)
1050    }
1051}
1052
1053impl<T: mz_sql_parser::ast::AstInfo> From<&Statement<T>> for StatementClassification {
1054    fn from(value: &Statement<T>) -> Self {
1055        use StatementClassification::*;
1056
1057        match value {
1058            // DDL statements.
1059            Statement::AlterCluster(_) => DDL,
1060            Statement::AlterConnection(_) => DDL,
1061            Statement::AlterIndex(_) => DDL,
1062            Statement::AlterMaterializedViewApplyReplacement(_) => DDL,
1063            Statement::AlterObjectRename(_) => DDL,
1064            Statement::AlterObjectSwap(_) => DDL,
1065            Statement::AlterNetworkPolicy(_) => DDL,
1066            Statement::AlterRetainHistory(_) => DDL,
1067            Statement::AlterRole(_) => DDL,
1068            Statement::AlterSecret(_) => DDL,
1069            Statement::AlterSetCluster(_) => DDL,
1070            Statement::AlterSink(_) => DDL,
1071            Statement::AlterSource(_) => DDL,
1072            Statement::AlterSystemSet(_) => DDL,
1073            Statement::AlterSystemReset(_) => DDL,
1074            Statement::AlterSystemResetAll(_) => DDL,
1075            Statement::AlterTableAddColumn(_) => DDL,
1076            Statement::Comment(_) => DDL,
1077            Statement::CreateCluster(_) => DDL,
1078            Statement::CreateClusterReplica(_) => DDL,
1079            Statement::CreateConnection(_) => DDL,
1080            Statement::CreateDatabase(_) => DDL,
1081            Statement::CreateIndex(_) => DDL,
1082            Statement::CreateRole(_) => DDL,
1083            Statement::CreateSchema(_) => DDL,
1084            Statement::CreateSecret(_) => DDL,
1085            Statement::CreateSink(_) => DDL,
1086            Statement::CreateMetricSink(_) => DDL,
1087            Statement::CreateWebhookSource(_) => DDL,
1088            Statement::CreateSource(_) => DDL,
1089            Statement::CreateSubsource(_) => DDL,
1090            Statement::CreateTable(_) => DDL,
1091            Statement::CreateTableFromSource(_) => DDL,
1092            Statement::CreateType(_) => DDL,
1093            Statement::CreateView(_) => DDL,
1094            Statement::CreateMaterializedView(_) => DDL,
1095            Statement::CreateNetworkPolicy(_) => DDL,
1096            Statement::DropObjects(_) => DDL,
1097            Statement::DropOwned(_) => DDL,
1098
1099            // `ACL` statements.
1100            Statement::AlterOwner(_) => ACL,
1101            Statement::GrantRole(_) => ACL,
1102            Statement::RevokeRole(_) => ACL,
1103            Statement::GrantPrivileges(_) => ACL,
1104            Statement::RevokePrivileges(_) => ACL,
1105            Statement::AlterDefaultPrivileges(_) => ACL,
1106            Statement::ReassignOwned(_) => ACL,
1107
1108            // DML statements.
1109            Statement::Copy(_) => DML,
1110            Statement::Delete(_) => DML,
1111            Statement::ExplainPlan(_) => DML,
1112            Statement::ExplainPushdown(_) => DML,
1113            Statement::ExplainAnalyzeObject(_) => DML,
1114            Statement::ExplainAnalyzeCluster(_) => DML,
1115            Statement::ExplainTimestamp(_) => DML,
1116            Statement::ExplainSinkSchema(_) => DML,
1117            Statement::Insert(_) => DML,
1118            Statement::Select(_) => DML,
1119            Statement::Subscribe(_) => DML,
1120            Statement::Update(_) => DML,
1121
1122            // `SHOW` statements.
1123            Statement::Show(ShowStatement::ShowColumns(_)) => Show,
1124            Statement::Show(ShowStatement::ShowCreateConnection(_)) => Show,
1125            Statement::Show(ShowStatement::ShowCreateCluster(_)) => Show,
1126            Statement::Show(ShowStatement::ShowCreateIndex(_)) => Show,
1127            Statement::Show(ShowStatement::ShowCreateSink(_)) => Show,
1128            Statement::Show(ShowStatement::ShowCreateSource(_)) => Show,
1129            Statement::Show(ShowStatement::ShowCreateTable(_)) => Show,
1130            Statement::Show(ShowStatement::ShowCreateView(_)) => Show,
1131            Statement::Show(ShowStatement::ShowCreateMaterializedView(_)) => Show,
1132            Statement::Show(ShowStatement::ShowCreateType(_)) => Show,
1133            Statement::Show(ShowStatement::ShowObjects(_)) => Show,
1134
1135            // SCL statements.
1136            Statement::Close(_) => SCL,
1137            Statement::Deallocate(_) => SCL,
1138            Statement::Declare(_) => SCL,
1139            Statement::Discard(_) => SCL,
1140            Statement::Execute(_) => SCL,
1141            Statement::Fetch(_) => SCL,
1142            Statement::Prepare(_) => SCL,
1143            Statement::ResetVariable(_) => SCL,
1144            Statement::SetVariable(_) => SCL,
1145            Statement::Show(ShowStatement::ShowVariable(_)) => SCL,
1146
1147            // TCL statements.
1148            Statement::Commit(_) => TCL,
1149            Statement::Rollback(_) => TCL,
1150            Statement::SetTransaction(_) => TCL,
1151            Statement::StartTransaction(_) => TCL,
1152
1153            // Other statements.
1154            Statement::Raise(_) => Other,
1155            Statement::Show(ShowStatement::InspectShard(_)) => Other,
1156            Statement::ValidateConnection(_) => Other,
1157            Statement::ExecuteUnitTest(_) => Other,
1158        }
1159    }
1160}