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