1use std::cell::RefCell;
15use std::collections::{BTreeMap, BTreeSet};
16
17use mz_repr::namespaces::is_system_schema;
18use mz_repr::{
19 CatalogItemId, ColumnIndex, ColumnType, RelationDesc, RelationVersionSelector, ScalarType,
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#[derive(Debug, Clone, Eq, PartialEq)]
62pub struct StatementDesc {
63 pub relation_desc: Option<RelationDesc>,
66 pub param_types: Vec<ScalarType>,
68 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 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<ScalarType>) -> 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
101pub fn describe(
105 pcx: &PlanContext,
106 catalog: &dyn SessionCatalog,
107 stmt: Statement<Aug>,
108 param_types_in: &[Option<ScalarType>],
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 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 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 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 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 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 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 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#[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 .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_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 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 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 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 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 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 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 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 id: CatalogItemId,
445 columns: Vec<ColumnIndex>,
446 rows: Vec<mz_repr::Row>,
447) -> Result<super::HirRelationExpr, PlanError> {
448 query::plan_copy_from_rows(pcx, catalog, id, columns, rows)
449}
450
451impl PartialEq<ObjectType> for CatalogItemType {
458 fn eq(&self, other: &ObjectType) -> bool {
459 match (self, other) {
460 (CatalogItemType::Source, ObjectType::Source)
461 | (CatalogItemType::Table, ObjectType::Table)
462 | (CatalogItemType::Sink, ObjectType::Sink)
463 | (CatalogItemType::View, ObjectType::View)
464 | (CatalogItemType::MaterializedView, ObjectType::MaterializedView)
465 | (CatalogItemType::Index, ObjectType::Index)
466 | (CatalogItemType::Type, ObjectType::Type)
467 | (CatalogItemType::Secret, ObjectType::Secret)
468 | (CatalogItemType::Connection, ObjectType::Connection) => true,
469 (_, _) => false,
470 }
471 }
472}
473
474impl PartialEq<CatalogItemType> for ObjectType {
475 fn eq(&self, other: &CatalogItemType) -> bool {
476 other == self
477 }
478}
479
480#[derive(Debug, Clone)]
482pub struct StatementContext<'a> {
483 pcx: Option<&'a PlanContext>,
488 pub catalog: &'a dyn SessionCatalog,
489 pub param_types: RefCell<BTreeMap<usize, ScalarType>>,
492 pub ambiguous_columns: RefCell<bool>,
495}
496
497impl<'a> StatementContext<'a> {
498 pub fn new(
499 pcx: Option<&'a PlanContext>,
500 catalog: &'a dyn SessionCatalog,
501 ) -> StatementContext<'a> {
502 StatementContext {
503 pcx,
504 catalog,
505 param_types: Default::default(),
506 ambiguous_columns: RefCell::new(false),
507 }
508 }
509
510 pub fn current_schemas(&self) -> &[(ResolvedDatabaseSpecifier, SchemaSpecifier)] {
512 self.catalog.search_path()
513 }
514
515 pub fn current_schema(&self) -> Option<&(ResolvedDatabaseSpecifier, SchemaSpecifier)> {
518 self.current_schemas().into_iter().next()
519 }
520
521 pub fn pcx(&self) -> Result<&PlanContext, PlanError> {
522 self.pcx.ok_or_else(|| sql_err!("no plan context"))
523 }
524
525 pub fn allocate_full_name(&self, name: PartialItemName) -> Result<FullItemName, PlanError> {
526 let (database, schema): (RawDatabaseSpecifier, String) = match (name.database, name.schema)
527 {
528 (None, None) => {
529 let Some((database, schema)) = self.current_schema() else {
530 return Err(PlanError::InvalidSchemaName);
531 };
532 let schema = self.get_schema(database, schema);
533 let database = match schema.database() {
534 ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
535 ResolvedDatabaseSpecifier::Id(id) => {
536 RawDatabaseSpecifier::Name(self.catalog.get_database(id).name().to_string())
537 }
538 };
539 (database, schema.name().schema.clone())
540 }
541 (None, Some(schema)) => {
542 if is_system_schema(&schema) {
543 (RawDatabaseSpecifier::Ambient, schema)
544 } else {
545 match self.catalog.active_database_name() {
546 Some(name) => (RawDatabaseSpecifier::Name(name.to_string()), schema),
547 None => {
548 sql_bail!(
549 "no database specified for non-system schema and no active database"
550 )
551 }
552 }
553 }
554 }
555 (Some(_database), None) => {
556 sql_bail!("unreachable: specified the database but no schema")
559 }
560 (Some(database), Some(schema)) => (RawDatabaseSpecifier::Name(database), schema),
561 };
562 let item = name.item;
563 Ok(FullItemName {
564 database,
565 schema,
566 item,
567 })
568 }
569
570 pub fn allocate_qualified_name(
571 &self,
572 name: PartialItemName,
573 ) -> Result<QualifiedItemName, PlanError> {
574 let full_name = self.allocate_full_name(name)?;
575 let database_spec = match full_name.database {
576 RawDatabaseSpecifier::Ambient => ResolvedDatabaseSpecifier::Ambient,
577 RawDatabaseSpecifier::Name(name) => ResolvedDatabaseSpecifier::Id(
578 self.resolve_database(&UnresolvedDatabaseName(Ident::new(name)?))?
579 .id(),
580 ),
581 };
582 let schema_spec = self
583 .resolve_schema_in_database(&database_spec, &Ident::new(full_name.schema)?)?
584 .id()
585 .clone();
586 Ok(QualifiedItemName {
587 qualifiers: ItemQualifiers {
588 database_spec,
589 schema_spec,
590 },
591 item: full_name.item,
592 })
593 }
594
595 pub fn allocate_temporary_full_name(&self, name: PartialItemName) -> FullItemName {
596 FullItemName {
597 database: RawDatabaseSpecifier::Ambient,
598 schema: name
599 .schema
600 .unwrap_or_else(|| mz_repr::namespaces::MZ_TEMP_SCHEMA.to_owned()),
601 item: name.item,
602 }
603 }
604
605 pub fn allocate_temporary_qualified_name(
606 &self,
607 name: PartialItemName,
608 ) -> Result<QualifiedItemName, PlanError> {
609 if let Some(name) = name.schema {
610 if name
611 != self
612 .get_schema(
613 &ResolvedDatabaseSpecifier::Ambient,
614 &SchemaSpecifier::Temporary,
615 )
616 .name()
617 .schema
618 {
619 return Err(PlanError::InvalidTemporarySchema);
620 }
621 }
622
623 Ok(QualifiedItemName {
624 qualifiers: ItemQualifiers {
625 database_spec: ResolvedDatabaseSpecifier::Ambient,
626 schema_spec: SchemaSpecifier::Temporary,
627 },
628 item: name.item,
629 })
630 }
631
632 pub fn allocate_resolved_item_name(
635 &self,
636 id: CatalogItemId,
637 name: UnresolvedItemName,
638 ) -> Result<ResolvedItemName, PlanError> {
639 let partial = normalize::unresolved_item_name(name)?;
640 let qualified = self.allocate_qualified_name(partial.clone())?;
641 let full_name = self.allocate_full_name(partial)?;
642 Ok(ResolvedItemName::Item {
643 id,
644 qualifiers: qualified.qualifiers,
645 full_name,
646 print_id: true,
647 version: RelationVersionSelector::Latest,
648 })
649 }
650
651 pub fn active_database(&self) -> Option<&DatabaseId> {
652 self.catalog.active_database()
653 }
654
655 pub fn resolve_optional_schema(
656 &self,
657 schema_name: &Option<ResolvedSchemaName>,
658 ) -> Result<SchemaSpecifier, PlanError> {
659 match schema_name {
660 Some(ResolvedSchemaName::Schema { schema_spec, .. }) => Ok(schema_spec.clone()),
661 None => self.resolve_active_schema().map(|spec| spec.clone()),
662 Some(ResolvedSchemaName::Error) => {
663 unreachable!("should have been handled by name resolution")
664 }
665 }
666 }
667
668 pub fn resolve_active_schema(&self) -> Result<&SchemaSpecifier, PlanError> {
669 match self.current_schema() {
670 Some((_db, schema)) => Ok(schema),
671 None => Err(PlanError::InvalidSchemaName),
672 }
673 }
674
675 pub fn get_cluster(&self, id: &ClusterId) -> &dyn CatalogCluster {
676 self.catalog.get_cluster(*id)
677 }
678
679 pub fn resolve_database(
680 &self,
681 name: &UnresolvedDatabaseName,
682 ) -> Result<&dyn CatalogDatabase, PlanError> {
683 let name = normalize::ident_ref(&name.0);
684 Ok(self.catalog.resolve_database(name)?)
685 }
686
687 pub fn get_database(&self, id: &DatabaseId) -> &dyn CatalogDatabase {
688 self.catalog.get_database(id)
689 }
690
691 pub fn resolve_schema_in_database(
692 &self,
693 database_spec: &ResolvedDatabaseSpecifier,
694 schema: &Ident,
695 ) -> Result<&dyn CatalogSchema, PlanError> {
696 let schema = normalize::ident_ref(schema);
697 Ok(self
698 .catalog
699 .resolve_schema_in_database(database_spec, schema)?)
700 }
701
702 pub fn resolve_schema(
703 &self,
704 name: UnresolvedSchemaName,
705 ) -> Result<&dyn CatalogSchema, PlanError> {
706 let name = normalize::unresolved_schema_name(name)?;
707 Ok(self
708 .catalog
709 .resolve_schema(name.database.as_deref(), &name.schema)?)
710 }
711
712 pub fn get_schema(
713 &self,
714 database_spec: &ResolvedDatabaseSpecifier,
715 schema_spec: &SchemaSpecifier,
716 ) -> &dyn CatalogSchema {
717 self.catalog.get_schema(database_spec, schema_spec)
718 }
719
720 pub fn resolve_item(&self, name: RawItemName) -> Result<&dyn CatalogItem, PlanError> {
721 match name {
722 RawItemName::Name(name) => {
723 let name = normalize::unresolved_item_name(name)?;
724 Ok(self.catalog.resolve_item(&name)?)
725 }
726 RawItemName::Id(id, _, _) => {
727 let gid = id.parse()?;
728 Ok(self.catalog.get_item(&gid))
729 }
730 }
731 }
732
733 pub fn get_item(&self, id: &CatalogItemId) -> &dyn CatalogItem {
734 self.catalog.get_item(id)
735 }
736
737 pub fn get_item_by_resolved_name(
738 &self,
739 name: &ResolvedItemName,
740 ) -> Result<Box<dyn CatalogCollectionItem + '_>, PlanError> {
741 match name {
742 ResolvedItemName::Item { id, version, .. } => {
743 Ok(self.get_item(id).at_version(*version))
744 }
745 ResolvedItemName::Cte { .. } => sql_bail!("non-user item"),
746 ResolvedItemName::ContinualTask { .. } => sql_bail!("non-user item"),
747 ResolvedItemName::Error => unreachable!("should have been caught in name resolution"),
748 }
749 }
750
751 pub fn get_column_by_resolved_name(
752 &self,
753 name: &ColumnName<Aug>,
754 ) -> Result<(Box<dyn CatalogCollectionItem + '_>, usize), PlanError> {
755 match (&name.relation, &name.column) {
756 (
757 ResolvedItemName::Item { id, version, .. },
758 ResolvedColumnReference::Column { index, .. },
759 ) => {
760 let item = self.get_item(id).at_version(*version);
761 Ok((item, *index))
762 }
763 _ => unreachable!(
764 "get_column_by_resolved_name errors should have been caught in name resolution"
765 ),
766 }
767 }
768
769 pub fn resolve_function(
770 &self,
771 name: UnresolvedItemName,
772 ) -> Result<&dyn CatalogItem, PlanError> {
773 let name = normalize::unresolved_item_name(name)?;
774 Ok(self.catalog.resolve_function(&name)?)
775 }
776
777 pub fn resolve_cluster(&self, name: Option<&Ident>) -> Result<&dyn CatalogCluster, PlanError> {
778 let name = name.map(|name| name.as_str());
779 Ok(self.catalog.resolve_cluster(name)?)
780 }
781
782 pub fn resolve_type(&self, mut ty: mz_pgrepr::Type) -> Result<ResolvedDataType, PlanError> {
783 match &mut ty {
789 mz_pgrepr::Type::Interval { constraints } => *constraints = None,
790 mz_pgrepr::Type::Time { precision } => *precision = None,
791 mz_pgrepr::Type::TimeTz { precision } => *precision = None,
792 mz_pgrepr::Type::Timestamp { precision } => *precision = None,
793 mz_pgrepr::Type::TimestampTz { precision } => *precision = None,
794 _ => (),
795 }
796 let mut ty = if ty.oid() >= FIRST_USER_OID {
802 sql_bail!("internal error, unexpected user type: {ty:?} ");
803 } else if ty.oid() < FIRST_MATERIALIZE_OID {
804 format!("pg_catalog.{}", ty)
805 } else {
806 format!("mz_catalog.{}", ty)
808 };
809 if ty == "pg_catalog.json" {
813 ty = "pg_catalog.jsonb".into();
814 }
815 let data_type = mz_sql_parser::parser::parse_data_type(&ty)?;
816 let (data_type, _) = names::resolve(self.catalog, data_type)?;
817 Ok(data_type)
818 }
819
820 pub fn get_object_type(&self, id: &ObjectId) -> ObjectType {
821 self.catalog.get_object_type(id)
822 }
823
824 pub fn get_system_object_type(&self, id: &SystemObjectId) -> SystemObjectType {
825 match id {
826 SystemObjectId::Object(id) => SystemObjectType::Object(self.get_object_type(id)),
827 SystemObjectId::System => SystemObjectType::System,
828 }
829 }
830
831 pub fn require_feature_flag(&self, flag: &'static FeatureFlag) -> Result<(), PlanError> {
833 flag.require(self.catalog.system_vars())?;
834 Ok(())
835 }
836
837 pub fn is_feature_flag_enabled(&self, flag: &'static FeatureFlag) -> bool {
839 self.require_feature_flag(flag).is_ok()
840 }
841
842 pub fn finalize_param_types(self) -> Result<Vec<ScalarType>, PlanError> {
843 let param_types = self.param_types.into_inner();
844 let mut out = vec![];
845 for (i, (n, typ)) in param_types.into_iter().enumerate() {
846 if n != i + 1 {
847 sql_bail!("unable to infer type for parameter ${}", i + 1);
848 }
849 out.push(typ);
850 }
851 Ok(out)
852 }
853
854 pub fn humanize_scalar_type(&self, typ: &ScalarType, postgres_compat: bool) -> String {
857 self.catalog.humanize_scalar_type(typ, postgres_compat)
858 }
859
860 pub fn humanize_column_type(&self, typ: &ColumnType, postgres_compat: bool) -> String {
863 self.catalog.humanize_column_type(typ, postgres_compat)
864 }
865
866 pub(crate) fn build_tunnel_definition(
867 &self,
868 ssh_tunnel: Option<with_options::Object>,
869 aws_privatelink: Option<ConnectionDefaultAwsPrivatelink<Aug>>,
870 ) -> Result<Tunnel<ReferencedConnection>, PlanError> {
871 match (ssh_tunnel, aws_privatelink) {
872 (None, None) => Ok(Tunnel::Direct),
873 (Some(ssh_tunnel), None) => {
874 let id = CatalogItemId::from(ssh_tunnel);
875 let ssh_tunnel = self.catalog.get_item(&id);
876 match ssh_tunnel.connection()? {
877 Connection::Ssh(_connection) => Ok(Tunnel::Ssh(SshTunnel {
878 connection_id: id,
879 connection: id,
880 })),
881 _ => sql_bail!("{} is not an SSH connection", ssh_tunnel.name().item),
882 }
883 }
884 (None, Some(aws_privatelink)) => {
885 let id = aws_privatelink.connection.item_id().clone();
886 let entry = self.catalog.get_item(&id);
887 match entry.connection()? {
888 Connection::AwsPrivatelink(_) => Ok(Tunnel::AwsPrivatelink(AwsPrivatelink {
889 connection_id: id,
890 availability_zone: None,
892 port: aws_privatelink.port,
894 })),
895 _ => sql_bail!("{} is not an AWS PRIVATELINK connection", entry.name().item),
896 }
897 }
898 (Some(_), Some(_)) => {
899 sql_bail!("cannot specify both SSH TUNNEL and AWS PRIVATELINK");
900 }
901 }
902 }
903
904 pub fn relation_desc_into_table_defs(
905 &self,
906 desc: &RelationDesc,
907 ) -> Result<(Vec<ColumnDef<Aug>>, Vec<TableConstraint<Aug>>), PlanError> {
908 let mut columns = vec![];
909 let mut null_cols = BTreeSet::new();
910 for (column_name, column_type) in desc.iter() {
911 let name = Ident::new(column_name.as_str().to_owned())?;
912
913 let ty = mz_pgrepr::Type::from(&column_type.scalar_type);
914 let data_type = self.resolve_type(ty)?;
915
916 let options = if !column_type.nullable {
917 null_cols.insert(columns.len());
918 vec![mz_sql_parser::ast::ColumnOptionDef {
919 name: None,
920 option: mz_sql_parser::ast::ColumnOption::NotNull,
921 }]
922 } else {
923 vec![]
924 };
925
926 columns.push(ColumnDef {
927 name,
928 data_type,
929 collation: None,
930 options,
931 });
932 }
933
934 let mut table_constraints = vec![];
935 for key in desc.typ().keys.iter() {
936 let mut col_names = vec![];
937 for col_idx in key {
938 if !null_cols.contains(col_idx) {
939 sql_bail!(
942 "[internal error] key columns must be NOT NULL when generating table constraints"
943 );
944 }
945 col_names.push(columns[*col_idx].name.clone());
946 }
947 table_constraints.push(TableConstraint::Unique {
948 name: None,
949 columns: col_names,
950 is_primary: false,
951 nulls_not_distinct: false,
952 });
953 }
954
955 Ok((columns, table_constraints))
956 }
957
958 pub fn get_owner_id(&self, id: &ObjectId) -> Option<RoleId> {
959 self.catalog.get_owner_id(id)
960 }
961
962 pub fn humanize_resolved_name(
963 &self,
964 name: &ResolvedItemName,
965 ) -> Result<PartialItemName, PlanError> {
966 let item = self.get_item_by_resolved_name(name)?;
967 Ok(self.catalog.minimal_qualification(item.name()))
968 }
969
970 pub fn dangerous_resolve_name(&self, name: Vec<&str>) -> ResolvedItemName {
973 tracing::trace!("dangerous_resolve_name {:?}", name);
974 let name: Vec<_> = name.into_iter().map(Ident::new_unchecked).collect();
976 let name = UnresolvedItemName::qualified(&name);
977 let entry = match self.resolve_item(RawItemName::Name(name.clone())) {
978 Ok(entry) => entry,
979 Err(_) => self
980 .resolve_function(name.clone())
981 .expect("name referred to an existing object"),
982 };
983
984 let partial = normalize::unresolved_item_name(name).unwrap();
985 let full_name = self.allocate_full_name(partial).unwrap();
986
987 ResolvedItemName::Item {
988 id: entry.id(),
989 qualifiers: entry.name().qualifiers.clone(),
990 full_name,
991 print_id: true,
992 version: RelationVersionSelector::Latest,
993 }
994 }
995}
996
997pub fn resolve_cluster_for_materialized_view<'a>(
998 catalog: &'a dyn SessionCatalog,
999 stmt: &CreateMaterializedViewStatement<Aug>,
1000) -> Result<ClusterId, PlanError> {
1001 Ok(match &stmt.in_cluster {
1002 None => catalog.resolve_cluster(None)?.id(),
1003 Some(in_cluster) => in_cluster.id,
1004 })
1005}
1006
1007#[derive(Debug, Clone, Copy)]
1009pub enum StatementClassification {
1010 ACL,
1011 DDL,
1012 DML,
1013 Other,
1014 SCL,
1015 Show,
1016 TCL,
1017}
1018
1019impl StatementClassification {
1020 pub fn is_ddl(&self) -> bool {
1021 matches!(self, StatementClassification::DDL)
1022 }
1023}
1024
1025impl<T: mz_sql_parser::ast::AstInfo> From<&Statement<T>> for StatementClassification {
1026 fn from(value: &Statement<T>) -> Self {
1027 use StatementClassification::*;
1028
1029 match value {
1030 Statement::AlterCluster(_) => DDL,
1032 Statement::AlterConnection(_) => DDL,
1033 Statement::AlterIndex(_) => DDL,
1034 Statement::AlterObjectRename(_) => DDL,
1035 Statement::AlterObjectSwap(_) => DDL,
1036 Statement::AlterNetworkPolicy(_) => DDL,
1037 Statement::AlterRetainHistory(_) => DDL,
1038 Statement::AlterRole(_) => DDL,
1039 Statement::AlterSecret(_) => DDL,
1040 Statement::AlterSetCluster(_) => DDL,
1041 Statement::AlterSink(_) => DDL,
1042 Statement::AlterSource(_) => DDL,
1043 Statement::AlterSystemSet(_) => DDL,
1044 Statement::AlterSystemReset(_) => DDL,
1045 Statement::AlterSystemResetAll(_) => DDL,
1046 Statement::AlterTableAddColumn(_) => DDL,
1047 Statement::Comment(_) => DDL,
1048 Statement::CreateCluster(_) => DDL,
1049 Statement::CreateClusterReplica(_) => DDL,
1050 Statement::CreateConnection(_) => DDL,
1051 Statement::CreateContinualTask(_) => DDL,
1052 Statement::CreateDatabase(_) => DDL,
1053 Statement::CreateIndex(_) => DDL,
1054 Statement::CreateRole(_) => DDL,
1055 Statement::CreateSchema(_) => DDL,
1056 Statement::CreateSecret(_) => DDL,
1057 Statement::CreateSink(_) => DDL,
1058 Statement::CreateWebhookSource(_) => DDL,
1059 Statement::CreateSource(_) => DDL,
1060 Statement::CreateSubsource(_) => DDL,
1061 Statement::CreateTable(_) => DDL,
1062 Statement::CreateTableFromSource(_) => DDL,
1063 Statement::CreateType(_) => DDL,
1064 Statement::CreateView(_) => DDL,
1065 Statement::CreateMaterializedView(_) => DDL,
1066 Statement::CreateNetworkPolicy(_) => DDL,
1067 Statement::DropObjects(_) => DDL,
1068 Statement::DropOwned(_) => DDL,
1069
1070 Statement::AlterOwner(_) => ACL,
1072 Statement::GrantRole(_) => ACL,
1073 Statement::RevokeRole(_) => ACL,
1074 Statement::GrantPrivileges(_) => ACL,
1075 Statement::RevokePrivileges(_) => ACL,
1076 Statement::AlterDefaultPrivileges(_) => ACL,
1077 Statement::ReassignOwned(_) => ACL,
1078
1079 Statement::Copy(_) => DML,
1081 Statement::Delete(_) => DML,
1082 Statement::ExplainPlan(_) => DML,
1083 Statement::ExplainPushdown(_) => DML,
1084 Statement::ExplainAnalyze(_) => DML,
1085 Statement::ExplainTimestamp(_) => DML,
1086 Statement::ExplainSinkSchema(_) => DML,
1087 Statement::Insert(_) => DML,
1088 Statement::Select(_) => DML,
1089 Statement::Subscribe(_) => DML,
1090 Statement::Update(_) => DML,
1091
1092 Statement::Show(ShowStatement::ShowColumns(_)) => Show,
1094 Statement::Show(ShowStatement::ShowCreateConnection(_)) => Show,
1095 Statement::Show(ShowStatement::ShowCreateCluster(_)) => Show,
1096 Statement::Show(ShowStatement::ShowCreateIndex(_)) => Show,
1097 Statement::Show(ShowStatement::ShowCreateSink(_)) => Show,
1098 Statement::Show(ShowStatement::ShowCreateSource(_)) => Show,
1099 Statement::Show(ShowStatement::ShowCreateTable(_)) => Show,
1100 Statement::Show(ShowStatement::ShowCreateView(_)) => Show,
1101 Statement::Show(ShowStatement::ShowCreateMaterializedView(_)) => Show,
1102 Statement::Show(ShowStatement::ShowObjects(_)) => Show,
1103
1104 Statement::Close(_) => SCL,
1106 Statement::Deallocate(_) => SCL,
1107 Statement::Declare(_) => SCL,
1108 Statement::Discard(_) => SCL,
1109 Statement::Execute(_) => SCL,
1110 Statement::Fetch(_) => SCL,
1111 Statement::Prepare(_) => SCL,
1112 Statement::ResetVariable(_) => SCL,
1113 Statement::SetVariable(_) => SCL,
1114 Statement::Show(ShowStatement::ShowVariable(_)) => SCL,
1115
1116 Statement::Commit(_) => TCL,
1118 Statement::Rollback(_) => TCL,
1119 Statement::SetTransaction(_) => TCL,
1120 Statement::StartTransaction(_) => TCL,
1121
1122 Statement::Raise(_) => Other,
1124 Statement::Show(ShowStatement::InspectShard(_)) => Other,
1125 Statement::ValidateConnection(_) => Other,
1126 }
1127 }
1128}