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