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