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::ExplainTimestamp(stmt) => dml::describe_explain_timestamp(&scx, stmt)?,
232 Statement::ExplainSinkSchema(stmt) => dml::describe_explain_schema(&scx, stmt)?,
233 Statement::Insert(stmt) => dml::describe_insert(&scx, stmt)?,
234 Statement::Select(stmt) => dml::describe_select(&scx, stmt)?,
235 Statement::Subscribe(stmt) => dml::describe_subscribe(&scx, stmt)?,
236 Statement::Update(stmt) => dml::describe_update(&scx, stmt)?,
237
238 Statement::Commit(stmt) => tcl::describe_commit(&scx, stmt)?,
240 Statement::Rollback(stmt) => tcl::describe_rollback(&scx, stmt)?,
241 Statement::SetTransaction(stmt) => tcl::describe_set_transaction(&scx, stmt)?,
242 Statement::StartTransaction(stmt) => tcl::describe_start_transaction(&scx, stmt)?,
243
244 Statement::Raise(stmt) => raise::describe_raise(&scx, stmt)?,
246 Statement::Show(ShowStatement::InspectShard(stmt)) => {
247 scl::describe_inspect_shard(&scx, stmt)?
248 }
249 Statement::ValidateConnection(stmt) => validate::describe_validate_connection(&scx, stmt)?,
250 };
251
252 let desc = desc.with_params(scx.finalize_param_types()?);
253 Ok(desc)
254}
255
256#[mz_ore::instrument(level = "debug")]
273pub fn plan(
274 pcx: Option<&PlanContext>,
275 catalog: &dyn SessionCatalog,
276 stmt: Statement<Aug>,
277 params: &Params,
278 resolved_ids: &ResolvedIds,
279) -> Result<Plan, PlanError> {
280 let param_types = params
281 .types
282 .iter()
283 .enumerate()
284 .map(|(i, ty)| (i + 1, ty.clone()))
285 .collect();
286
287 let kind: StatementKind = (&stmt).into();
288 let permitted_plans = Plan::generated_from(&kind);
289
290 let scx = &mut StatementContext {
291 pcx,
292 catalog,
293 param_types: RefCell::new(param_types),
294 ambiguous_columns: RefCell::new(false),
295 };
296
297 if resolved_ids
298 .items()
299 .filter_map(|id| catalog.try_get_item(id))
301 .any(|item| {
302 item.func().is_ok()
303 && item.name().qualifiers.schema_spec
304 == SchemaSpecifier::Id(catalog.get_mz_unsafe_schema_id())
305 })
306 {
307 scx.require_feature_flag(&vars::UNSAFE_ENABLE_UNSAFE_FUNCTIONS)?;
308 }
309
310 let plan = match stmt {
311 Statement::AlterCluster(stmt) => ddl::plan_alter_cluster(scx, stmt),
313 Statement::AlterConnection(stmt) => ddl::plan_alter_connection(scx, stmt),
314 Statement::AlterIndex(stmt) => ddl::plan_alter_index_options(scx, stmt),
315 Statement::AlterObjectRename(stmt) => ddl::plan_alter_object_rename(scx, stmt),
316 Statement::AlterObjectSwap(stmt) => ddl::plan_alter_object_swap(scx, stmt),
317 Statement::AlterRetainHistory(stmt) => ddl::plan_alter_retain_history(scx, stmt),
318 Statement::AlterRole(stmt) => ddl::plan_alter_role(scx, stmt),
319 Statement::AlterSecret(stmt) => ddl::plan_alter_secret(scx, stmt),
320 Statement::AlterSetCluster(stmt) => ddl::plan_alter_item_set_cluster(scx, stmt),
321 Statement::AlterSink(stmt) => ddl::plan_alter_sink(scx, stmt),
322 Statement::AlterSource(stmt) => ddl::plan_alter_source(scx, stmt),
323 Statement::AlterSystemSet(stmt) => ddl::plan_alter_system_set(scx, stmt),
324 Statement::AlterSystemReset(stmt) => ddl::plan_alter_system_reset(scx, stmt),
325 Statement::AlterSystemResetAll(stmt) => ddl::plan_alter_system_reset_all(scx, stmt),
326 Statement::AlterTableAddColumn(stmt) => ddl::plan_alter_table_add_column(scx, stmt),
327 Statement::AlterNetworkPolicy(stmt) => ddl::plan_alter_network_policy(scx, stmt),
328 Statement::Comment(stmt) => ddl::plan_comment(scx, stmt),
329 Statement::CreateCluster(stmt) => ddl::plan_create_cluster(scx, stmt),
330 Statement::CreateClusterReplica(stmt) => ddl::plan_create_cluster_replica(scx, stmt),
331 Statement::CreateConnection(stmt) => ddl::plan_create_connection(scx, stmt),
332 Statement::CreateDatabase(stmt) => ddl::plan_create_database(scx, stmt),
333 Statement::CreateIndex(stmt) => ddl::plan_create_index(scx, stmt),
334 Statement::CreateRole(stmt) => ddl::plan_create_role(scx, stmt),
335 Statement::CreateSchema(stmt) => ddl::plan_create_schema(scx, stmt),
336 Statement::CreateSecret(stmt) => ddl::plan_create_secret(scx, stmt),
337 Statement::CreateSink(stmt) => ddl::plan_create_sink(scx, stmt),
338 Statement::CreateWebhookSource(stmt) => ddl::plan_create_webhook_source(scx, stmt),
339 Statement::CreateSource(stmt) => ddl::plan_create_source(scx, stmt),
340 Statement::CreateSubsource(stmt) => ddl::plan_create_subsource(scx, stmt),
341 Statement::CreateTable(stmt) => ddl::plan_create_table(scx, stmt),
342 Statement::CreateTableFromSource(stmt) => ddl::plan_create_table_from_source(scx, stmt),
343 Statement::CreateType(stmt) => ddl::plan_create_type(scx, stmt),
344 Statement::CreateView(stmt) => ddl::plan_create_view(scx, stmt, params),
345 Statement::CreateMaterializedView(stmt) => {
346 ddl::plan_create_materialized_view(scx, stmt, params)
347 }
348 Statement::CreateContinualTask(stmt) => ddl::plan_create_continual_task(scx, stmt, params),
349 Statement::CreateNetworkPolicy(stmt) => ddl::plan_create_network_policy(scx, stmt),
350 Statement::DropObjects(stmt) => ddl::plan_drop_objects(scx, stmt),
351 Statement::DropOwned(stmt) => ddl::plan_drop_owned(scx, stmt),
352
353 Statement::AlterOwner(stmt) => acl::plan_alter_owner(scx, stmt),
355 Statement::GrantRole(stmt) => acl::plan_grant_role(scx, stmt),
356 Statement::RevokeRole(stmt) => acl::plan_revoke_role(scx, stmt),
357 Statement::GrantPrivileges(stmt) => acl::plan_grant_privileges(scx, stmt),
358 Statement::RevokePrivileges(stmt) => acl::plan_revoke_privileges(scx, stmt),
359 Statement::AlterDefaultPrivileges(stmt) => acl::plan_alter_default_privileges(scx, stmt),
360 Statement::ReassignOwned(stmt) => acl::plan_reassign_owned(scx, stmt),
361
362 Statement::Copy(stmt) => dml::plan_copy(scx, stmt),
364 Statement::Delete(stmt) => dml::plan_delete(scx, stmt, params),
365 Statement::ExplainPlan(stmt) => dml::plan_explain_plan(scx, stmt, params),
366 Statement::ExplainPushdown(stmt) => dml::plan_explain_pushdown(scx, stmt, params),
367 Statement::ExplainTimestamp(stmt) => dml::plan_explain_timestamp(scx, stmt, params),
368 Statement::ExplainSinkSchema(stmt) => dml::plan_explain_schema(scx, stmt),
369 Statement::Insert(stmt) => dml::plan_insert(scx, stmt, params),
370 Statement::Select(stmt) => dml::plan_select(scx, stmt, params, None),
371 Statement::Subscribe(stmt) => dml::plan_subscribe(scx, stmt, params, None),
372 Statement::Update(stmt) => dml::plan_update(scx, stmt, params),
373
374 Statement::Show(ShowStatement::ShowColumns(stmt)) => show::show_columns(scx, stmt)?.plan(),
376 Statement::Show(ShowStatement::ShowCreateConnection(stmt)) => {
377 show::plan_show_create_connection(scx, stmt).map(Plan::ShowCreate)
378 }
379 Statement::Show(ShowStatement::ShowCreateCluster(stmt)) => {
380 show::plan_show_create_cluster(scx, stmt).map(Plan::ShowCreate)
381 }
382 Statement::Show(ShowStatement::ShowCreateIndex(stmt)) => {
383 show::plan_show_create_index(scx, stmt).map(Plan::ShowCreate)
384 }
385 Statement::Show(ShowStatement::ShowCreateSink(stmt)) => {
386 show::plan_show_create_sink(scx, stmt).map(Plan::ShowCreate)
387 }
388 Statement::Show(ShowStatement::ShowCreateSource(stmt)) => {
389 show::plan_show_create_source(scx, stmt).map(Plan::ShowCreate)
390 }
391 Statement::Show(ShowStatement::ShowCreateTable(stmt)) => {
392 show::plan_show_create_table(scx, stmt).map(Plan::ShowCreate)
393 }
394 Statement::Show(ShowStatement::ShowCreateView(stmt)) => {
395 show::plan_show_create_view(scx, stmt).map(Plan::ShowCreate)
396 }
397 Statement::Show(ShowStatement::ShowCreateMaterializedView(stmt)) => {
398 show::plan_show_create_materialized_view(scx, stmt).map(Plan::ShowCreate)
399 }
400 Statement::Show(ShowStatement::ShowObjects(stmt)) => show::show_objects(scx, stmt)?.plan(),
401
402 Statement::Close(stmt) => scl::plan_close(scx, stmt),
404 Statement::Deallocate(stmt) => scl::plan_deallocate(scx, stmt),
405 Statement::Declare(stmt) => scl::plan_declare(scx, stmt, params),
406 Statement::Discard(stmt) => scl::plan_discard(scx, stmt),
407 Statement::Execute(stmt) => scl::plan_execute(scx, stmt),
408 Statement::Fetch(stmt) => scl::plan_fetch(scx, stmt),
409 Statement::Prepare(stmt) => scl::plan_prepare(scx, stmt),
410 Statement::ResetVariable(stmt) => scl::plan_reset_variable(scx, stmt),
411 Statement::SetVariable(stmt) => scl::plan_set_variable(scx, stmt),
412 Statement::Show(ShowStatement::ShowVariable(stmt)) => scl::plan_show_variable(scx, stmt),
413
414 Statement::Commit(stmt) => tcl::plan_commit(scx, stmt),
416 Statement::Rollback(stmt) => tcl::plan_rollback(scx, stmt),
417 Statement::SetTransaction(stmt) => tcl::plan_set_transaction(scx, stmt),
418 Statement::StartTransaction(stmt) => tcl::plan_start_transaction(scx, stmt),
419
420 Statement::Raise(stmt) => raise::plan_raise(scx, stmt),
422 Statement::Show(ShowStatement::InspectShard(stmt)) => scl::plan_inspect_shard(scx, stmt),
423 Statement::ValidateConnection(stmt) => validate::plan_validate_connection(scx, stmt),
424 };
425
426 if let Ok(plan) = &plan {
427 mz_ore::soft_assert_no_log!(
428 permitted_plans.contains(&PlanKind::from(plan)),
429 "plan {:?}, permitted plans {:?}",
430 plan,
431 permitted_plans
432 );
433 }
434
435 plan
436}
437
438pub fn plan_copy_from(
439 pcx: &PlanContext,
440 catalog: &dyn SessionCatalog,
441 id: CatalogItemId,
442 columns: Vec<ColumnIndex>,
443 rows: Vec<mz_repr::Row>,
444) -> Result<super::HirRelationExpr, PlanError> {
445 query::plan_copy_from_rows(pcx, catalog, id, columns, rows)
446}
447
448impl PartialEq<ObjectType> for CatalogItemType {
455 fn eq(&self, other: &ObjectType) -> bool {
456 match (self, other) {
457 (CatalogItemType::Source, ObjectType::Source)
458 | (CatalogItemType::Table, ObjectType::Table)
459 | (CatalogItemType::Sink, ObjectType::Sink)
460 | (CatalogItemType::View, ObjectType::View)
461 | (CatalogItemType::MaterializedView, ObjectType::MaterializedView)
462 | (CatalogItemType::Index, ObjectType::Index)
463 | (CatalogItemType::Type, ObjectType::Type)
464 | (CatalogItemType::Secret, ObjectType::Secret)
465 | (CatalogItemType::Connection, ObjectType::Connection) => true,
466 (_, _) => false,
467 }
468 }
469}
470
471impl PartialEq<CatalogItemType> for ObjectType {
472 fn eq(&self, other: &CatalogItemType) -> bool {
473 other == self
474 }
475}
476
477#[derive(Debug, Clone)]
479pub struct StatementContext<'a> {
480 pcx: Option<&'a PlanContext>,
485 pub catalog: &'a dyn SessionCatalog,
486 pub param_types: RefCell<BTreeMap<usize, ScalarType>>,
489 pub ambiguous_columns: RefCell<bool>,
492}
493
494impl<'a> StatementContext<'a> {
495 pub fn new(
496 pcx: Option<&'a PlanContext>,
497 catalog: &'a dyn SessionCatalog,
498 ) -> StatementContext<'a> {
499 StatementContext {
500 pcx,
501 catalog,
502 param_types: Default::default(),
503 ambiguous_columns: RefCell::new(false),
504 }
505 }
506
507 pub fn current_schemas(&self) -> &[(ResolvedDatabaseSpecifier, SchemaSpecifier)] {
509 self.catalog.search_path()
510 }
511
512 pub fn current_schema(&self) -> Option<&(ResolvedDatabaseSpecifier, SchemaSpecifier)> {
515 self.current_schemas().into_iter().next()
516 }
517
518 pub fn pcx(&self) -> Result<&PlanContext, PlanError> {
519 self.pcx.ok_or_else(|| sql_err!("no plan context"))
520 }
521
522 pub fn allocate_full_name(&self, name: PartialItemName) -> Result<FullItemName, PlanError> {
523 let (database, schema): (RawDatabaseSpecifier, String) = match (name.database, name.schema)
524 {
525 (None, None) => {
526 let Some((database, schema)) = self.current_schema() else {
527 return Err(PlanError::InvalidSchemaName);
528 };
529 let schema = self.get_schema(database, schema);
530 let database = match schema.database() {
531 ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
532 ResolvedDatabaseSpecifier::Id(id) => {
533 RawDatabaseSpecifier::Name(self.catalog.get_database(id).name().to_string())
534 }
535 };
536 (database, schema.name().schema.clone())
537 }
538 (None, Some(schema)) => {
539 if is_system_schema(&schema) {
540 (RawDatabaseSpecifier::Ambient, schema)
541 } else {
542 match self.catalog.active_database_name() {
543 Some(name) => (RawDatabaseSpecifier::Name(name.to_string()), schema),
544 None => {
545 sql_bail!(
546 "no database specified for non-system schema and no active database"
547 )
548 }
549 }
550 }
551 }
552 (Some(_database), None) => {
553 sql_bail!("unreachable: specified the database but no schema")
556 }
557 (Some(database), Some(schema)) => (RawDatabaseSpecifier::Name(database), schema),
558 };
559 let item = name.item;
560 Ok(FullItemName {
561 database,
562 schema,
563 item,
564 })
565 }
566
567 pub fn allocate_qualified_name(
568 &self,
569 name: PartialItemName,
570 ) -> Result<QualifiedItemName, PlanError> {
571 let full_name = self.allocate_full_name(name)?;
572 let database_spec = match full_name.database {
573 RawDatabaseSpecifier::Ambient => ResolvedDatabaseSpecifier::Ambient,
574 RawDatabaseSpecifier::Name(name) => ResolvedDatabaseSpecifier::Id(
575 self.resolve_database(&UnresolvedDatabaseName(Ident::new(name)?))?
576 .id(),
577 ),
578 };
579 let schema_spec = self
580 .resolve_schema_in_database(&database_spec, &Ident::new(full_name.schema)?)?
581 .id()
582 .clone();
583 Ok(QualifiedItemName {
584 qualifiers: ItemQualifiers {
585 database_spec,
586 schema_spec,
587 },
588 item: full_name.item,
589 })
590 }
591
592 pub fn allocate_temporary_full_name(&self, name: PartialItemName) -> FullItemName {
593 FullItemName {
594 database: RawDatabaseSpecifier::Ambient,
595 schema: name
596 .schema
597 .unwrap_or_else(|| mz_repr::namespaces::MZ_TEMP_SCHEMA.to_owned()),
598 item: name.item,
599 }
600 }
601
602 pub fn allocate_temporary_qualified_name(
603 &self,
604 name: PartialItemName,
605 ) -> Result<QualifiedItemName, PlanError> {
606 if let Some(name) = name.schema {
607 if name
608 != self
609 .get_schema(
610 &ResolvedDatabaseSpecifier::Ambient,
611 &SchemaSpecifier::Temporary,
612 )
613 .name()
614 .schema
615 {
616 return Err(PlanError::InvalidTemporarySchema);
617 }
618 }
619
620 Ok(QualifiedItemName {
621 qualifiers: ItemQualifiers {
622 database_spec: ResolvedDatabaseSpecifier::Ambient,
623 schema_spec: SchemaSpecifier::Temporary,
624 },
625 item: name.item,
626 })
627 }
628
629 pub fn allocate_resolved_item_name(
632 &self,
633 id: CatalogItemId,
634 name: UnresolvedItemName,
635 ) -> Result<ResolvedItemName, PlanError> {
636 let partial = normalize::unresolved_item_name(name)?;
637 let qualified = self.allocate_qualified_name(partial.clone())?;
638 let full_name = self.allocate_full_name(partial)?;
639 Ok(ResolvedItemName::Item {
640 id,
641 qualifiers: qualified.qualifiers,
642 full_name,
643 print_id: true,
644 version: RelationVersionSelector::Latest,
645 })
646 }
647
648 pub fn active_database(&self) -> Option<&DatabaseId> {
649 self.catalog.active_database()
650 }
651
652 pub fn resolve_optional_schema(
653 &self,
654 schema_name: &Option<ResolvedSchemaName>,
655 ) -> Result<SchemaSpecifier, PlanError> {
656 match schema_name {
657 Some(ResolvedSchemaName::Schema { schema_spec, .. }) => Ok(schema_spec.clone()),
658 None => self.resolve_active_schema().map(|spec| spec.clone()),
659 Some(ResolvedSchemaName::Error) => {
660 unreachable!("should have been handled by name resolution")
661 }
662 }
663 }
664
665 pub fn resolve_active_schema(&self) -> Result<&SchemaSpecifier, PlanError> {
666 match self.current_schema() {
667 Some((_db, schema)) => Ok(schema),
668 None => Err(PlanError::InvalidSchemaName),
669 }
670 }
671
672 pub fn get_cluster(&self, id: &ClusterId) -> &dyn CatalogCluster {
673 self.catalog.get_cluster(*id)
674 }
675
676 pub fn resolve_database(
677 &self,
678 name: &UnresolvedDatabaseName,
679 ) -> Result<&dyn CatalogDatabase, PlanError> {
680 let name = normalize::ident_ref(&name.0);
681 Ok(self.catalog.resolve_database(name)?)
682 }
683
684 pub fn get_database(&self, id: &DatabaseId) -> &dyn CatalogDatabase {
685 self.catalog.get_database(id)
686 }
687
688 pub fn resolve_schema_in_database(
689 &self,
690 database_spec: &ResolvedDatabaseSpecifier,
691 schema: &Ident,
692 ) -> Result<&dyn CatalogSchema, PlanError> {
693 let schema = normalize::ident_ref(schema);
694 Ok(self
695 .catalog
696 .resolve_schema_in_database(database_spec, schema)?)
697 }
698
699 pub fn resolve_schema(
700 &self,
701 name: UnresolvedSchemaName,
702 ) -> Result<&dyn CatalogSchema, PlanError> {
703 let name = normalize::unresolved_schema_name(name)?;
704 Ok(self
705 .catalog
706 .resolve_schema(name.database.as_deref(), &name.schema)?)
707 }
708
709 pub fn get_schema(
710 &self,
711 database_spec: &ResolvedDatabaseSpecifier,
712 schema_spec: &SchemaSpecifier,
713 ) -> &dyn CatalogSchema {
714 self.catalog.get_schema(database_spec, schema_spec)
715 }
716
717 pub fn resolve_item(&self, name: RawItemName) -> Result<&dyn CatalogItem, PlanError> {
718 match name {
719 RawItemName::Name(name) => {
720 let name = normalize::unresolved_item_name(name)?;
721 Ok(self.catalog.resolve_item(&name)?)
722 }
723 RawItemName::Id(id, _, _) => {
724 let gid = id.parse()?;
725 Ok(self.catalog.get_item(&gid))
726 }
727 }
728 }
729
730 pub fn get_item(&self, id: &CatalogItemId) -> &dyn CatalogItem {
731 self.catalog.get_item(id)
732 }
733
734 pub fn get_item_by_resolved_name(
735 &self,
736 name: &ResolvedItemName,
737 ) -> Result<Box<dyn CatalogCollectionItem + '_>, PlanError> {
738 match name {
739 ResolvedItemName::Item { id, version, .. } => {
740 Ok(self.get_item(id).at_version(*version))
741 }
742 ResolvedItemName::Cte { .. } => sql_bail!("non-user item"),
743 ResolvedItemName::ContinualTask { .. } => sql_bail!("non-user item"),
744 ResolvedItemName::Error => unreachable!("should have been caught in name resolution"),
745 }
746 }
747
748 pub fn get_column_by_resolved_name(
749 &self,
750 name: &ColumnName<Aug>,
751 ) -> Result<(Box<dyn CatalogCollectionItem + '_>, usize), PlanError> {
752 match (&name.relation, &name.column) {
753 (
754 ResolvedItemName::Item { id, version, .. },
755 ResolvedColumnReference::Column { index, .. },
756 ) => {
757 let item = self.get_item(id).at_version(*version);
758 Ok((item, *index))
759 }
760 _ => unreachable!(
761 "get_column_by_resolved_name errors should have been caught in name resolution"
762 ),
763 }
764 }
765
766 pub fn resolve_function(
767 &self,
768 name: UnresolvedItemName,
769 ) -> Result<&dyn CatalogItem, PlanError> {
770 let name = normalize::unresolved_item_name(name)?;
771 Ok(self.catalog.resolve_function(&name)?)
772 }
773
774 pub fn resolve_cluster(&self, name: Option<&Ident>) -> Result<&dyn CatalogCluster, PlanError> {
775 let name = name.map(|name| name.as_str());
776 Ok(self.catalog.resolve_cluster(name)?)
777 }
778
779 pub fn resolve_type(&self, mut ty: mz_pgrepr::Type) -> Result<ResolvedDataType, PlanError> {
780 match &mut ty {
786 mz_pgrepr::Type::Interval { constraints } => *constraints = None,
787 mz_pgrepr::Type::Time { precision } => *precision = None,
788 mz_pgrepr::Type::TimeTz { precision } => *precision = None,
789 mz_pgrepr::Type::Timestamp { precision } => *precision = None,
790 mz_pgrepr::Type::TimestampTz { precision } => *precision = None,
791 _ => (),
792 }
793 let mut ty = if ty.oid() >= FIRST_USER_OID {
799 sql_bail!("internal error, unexpected user type: {ty:?} ");
800 } else if ty.oid() < FIRST_MATERIALIZE_OID {
801 format!("pg_catalog.{}", ty)
802 } else {
803 format!("mz_catalog.{}", ty)
805 };
806 if ty == "pg_catalog.json" {
810 ty = "pg_catalog.jsonb".into();
811 }
812 let data_type = mz_sql_parser::parser::parse_data_type(&ty)?;
813 let (data_type, _) = names::resolve(self.catalog, data_type)?;
814 Ok(data_type)
815 }
816
817 pub fn get_object_type(&self, id: &ObjectId) -> ObjectType {
818 self.catalog.get_object_type(id)
819 }
820
821 pub fn get_system_object_type(&self, id: &SystemObjectId) -> SystemObjectType {
822 match id {
823 SystemObjectId::Object(id) => SystemObjectType::Object(self.get_object_type(id)),
824 SystemObjectId::System => SystemObjectType::System,
825 }
826 }
827
828 pub fn require_feature_flag(&self, flag: &'static FeatureFlag) -> Result<(), PlanError> {
830 flag.require(self.catalog.system_vars())?;
831 Ok(())
832 }
833
834 pub fn is_feature_flag_enabled(&self, flag: &'static FeatureFlag) -> bool {
836 self.require_feature_flag(flag).is_ok()
837 }
838
839 pub fn finalize_param_types(self) -> Result<Vec<ScalarType>, PlanError> {
840 let param_types = self.param_types.into_inner();
841 let mut out = vec![];
842 for (i, (n, typ)) in param_types.into_iter().enumerate() {
843 if n != i + 1 {
844 sql_bail!("unable to infer type for parameter ${}", i + 1);
845 }
846 out.push(typ);
847 }
848 Ok(out)
849 }
850
851 pub fn humanize_scalar_type(&self, typ: &ScalarType, postgres_compat: bool) -> String {
854 self.catalog.humanize_scalar_type(typ, postgres_compat)
855 }
856
857 pub fn humanize_column_type(&self, typ: &ColumnType, postgres_compat: bool) -> String {
860 self.catalog.humanize_column_type(typ, postgres_compat)
861 }
862
863 pub(crate) fn build_tunnel_definition(
864 &self,
865 ssh_tunnel: Option<with_options::Object>,
866 aws_privatelink: Option<ConnectionDefaultAwsPrivatelink<Aug>>,
867 ) -> Result<Tunnel<ReferencedConnection>, PlanError> {
868 match (ssh_tunnel, aws_privatelink) {
869 (None, None) => Ok(Tunnel::Direct),
870 (Some(ssh_tunnel), None) => {
871 let id = CatalogItemId::from(ssh_tunnel);
872 let ssh_tunnel = self.catalog.get_item(&id);
873 match ssh_tunnel.connection()? {
874 Connection::Ssh(_connection) => Ok(Tunnel::Ssh(SshTunnel {
875 connection_id: id,
876 connection: id,
877 })),
878 _ => sql_bail!("{} is not an SSH connection", ssh_tunnel.name().item),
879 }
880 }
881 (None, Some(aws_privatelink)) => {
882 let id = aws_privatelink.connection.item_id().clone();
883 let entry = self.catalog.get_item(&id);
884 match entry.connection()? {
885 Connection::AwsPrivatelink(_) => Ok(Tunnel::AwsPrivatelink(AwsPrivatelink {
886 connection_id: id,
887 availability_zone: None,
889 port: aws_privatelink.port,
891 })),
892 _ => sql_bail!("{} is not an AWS PRIVATELINK connection", entry.name().item),
893 }
894 }
895 (Some(_), Some(_)) => {
896 sql_bail!("cannot specify both SSH TUNNEL and AWS PRIVATELINK");
897 }
898 }
899 }
900
901 pub fn relation_desc_into_table_defs(
902 &self,
903 desc: &RelationDesc,
904 ) -> Result<(Vec<ColumnDef<Aug>>, Vec<TableConstraint<Aug>>), PlanError> {
905 let mut columns = vec![];
906 let mut null_cols = BTreeSet::new();
907 for (column_name, column_type) in desc.iter() {
908 let name = Ident::new(column_name.as_str().to_owned())?;
909
910 let ty = mz_pgrepr::Type::from(&column_type.scalar_type);
911 let data_type = self.resolve_type(ty)?;
912
913 let options = if !column_type.nullable {
914 null_cols.insert(columns.len());
915 vec![mz_sql_parser::ast::ColumnOptionDef {
916 name: None,
917 option: mz_sql_parser::ast::ColumnOption::NotNull,
918 }]
919 } else {
920 vec![]
921 };
922
923 columns.push(ColumnDef {
924 name,
925 data_type,
926 collation: None,
927 options,
928 });
929 }
930
931 let mut table_constraints = vec![];
932 for key in desc.typ().keys.iter() {
933 let mut col_names = vec![];
934 for col_idx in key {
935 if !null_cols.contains(col_idx) {
936 sql_bail!(
939 "[internal error] key columns must be NOT NULL when generating table constraints"
940 );
941 }
942 col_names.push(columns[*col_idx].name.clone());
943 }
944 table_constraints.push(TableConstraint::Unique {
945 name: None,
946 columns: col_names,
947 is_primary: false,
948 nulls_not_distinct: false,
949 });
950 }
951
952 Ok((columns, table_constraints))
953 }
954
955 pub fn get_owner_id(&self, id: &ObjectId) -> Option<RoleId> {
956 self.catalog.get_owner_id(id)
957 }
958
959 pub fn humanize_resolved_name(
960 &self,
961 name: &ResolvedItemName,
962 ) -> Result<PartialItemName, PlanError> {
963 let item = self.get_item_by_resolved_name(name)?;
964 Ok(self.catalog.minimal_qualification(item.name()))
965 }
966
967 pub fn dangerous_resolve_name(&self, name: Vec<&str>) -> ResolvedItemName {
970 tracing::trace!("dangerous_resolve_name {:?}", name);
971 let name: Vec<_> = name.into_iter().map(Ident::new_unchecked).collect();
973 let name = UnresolvedItemName::qualified(&name);
974 let entry = match self.resolve_item(RawItemName::Name(name.clone())) {
975 Ok(entry) => entry,
976 Err(_) => self
977 .resolve_function(name.clone())
978 .expect("name referred to an existing object"),
979 };
980
981 let partial = normalize::unresolved_item_name(name).unwrap();
982 let full_name = self.allocate_full_name(partial).unwrap();
983
984 ResolvedItemName::Item {
985 id: entry.id(),
986 qualifiers: entry.name().qualifiers.clone(),
987 full_name,
988 print_id: true,
989 version: RelationVersionSelector::Latest,
990 }
991 }
992}
993
994pub fn resolve_cluster_for_materialized_view<'a>(
995 catalog: &'a dyn SessionCatalog,
996 stmt: &CreateMaterializedViewStatement<Aug>,
997) -> Result<ClusterId, PlanError> {
998 Ok(match &stmt.in_cluster {
999 None => catalog.resolve_cluster(None)?.id(),
1000 Some(in_cluster) => in_cluster.id,
1001 })
1002}
1003
1004#[derive(Debug, Clone, Copy)]
1006pub enum StatementClassification {
1007 ACL,
1008 DDL,
1009 DML,
1010 Other,
1011 SCL,
1012 Show,
1013 TCL,
1014}
1015
1016impl StatementClassification {
1017 pub fn is_ddl(&self) -> bool {
1018 matches!(self, StatementClassification::DDL)
1019 }
1020}
1021
1022impl<T: mz_sql_parser::ast::AstInfo> From<&Statement<T>> for StatementClassification {
1023 fn from(value: &Statement<T>) -> Self {
1024 use StatementClassification::*;
1025
1026 match value {
1027 Statement::AlterCluster(_) => DDL,
1029 Statement::AlterConnection(_) => DDL,
1030 Statement::AlterIndex(_) => DDL,
1031 Statement::AlterObjectRename(_) => DDL,
1032 Statement::AlterObjectSwap(_) => DDL,
1033 Statement::AlterNetworkPolicy(_) => DDL,
1034 Statement::AlterRetainHistory(_) => DDL,
1035 Statement::AlterRole(_) => DDL,
1036 Statement::AlterSecret(_) => DDL,
1037 Statement::AlterSetCluster(_) => DDL,
1038 Statement::AlterSink(_) => DDL,
1039 Statement::AlterSource(_) => DDL,
1040 Statement::AlterSystemSet(_) => DDL,
1041 Statement::AlterSystemReset(_) => DDL,
1042 Statement::AlterSystemResetAll(_) => DDL,
1043 Statement::AlterTableAddColumn(_) => DDL,
1044 Statement::Comment(_) => DDL,
1045 Statement::CreateCluster(_) => DDL,
1046 Statement::CreateClusterReplica(_) => DDL,
1047 Statement::CreateConnection(_) => DDL,
1048 Statement::CreateContinualTask(_) => DDL,
1049 Statement::CreateDatabase(_) => DDL,
1050 Statement::CreateIndex(_) => DDL,
1051 Statement::CreateRole(_) => DDL,
1052 Statement::CreateSchema(_) => DDL,
1053 Statement::CreateSecret(_) => DDL,
1054 Statement::CreateSink(_) => DDL,
1055 Statement::CreateWebhookSource(_) => DDL,
1056 Statement::CreateSource(_) => DDL,
1057 Statement::CreateSubsource(_) => DDL,
1058 Statement::CreateTable(_) => DDL,
1059 Statement::CreateTableFromSource(_) => DDL,
1060 Statement::CreateType(_) => DDL,
1061 Statement::CreateView(_) => DDL,
1062 Statement::CreateMaterializedView(_) => DDL,
1063 Statement::CreateNetworkPolicy(_) => DDL,
1064 Statement::DropObjects(_) => DDL,
1065 Statement::DropOwned(_) => DDL,
1066
1067 Statement::AlterOwner(_) => ACL,
1069 Statement::GrantRole(_) => ACL,
1070 Statement::RevokeRole(_) => ACL,
1071 Statement::GrantPrivileges(_) => ACL,
1072 Statement::RevokePrivileges(_) => ACL,
1073 Statement::AlterDefaultPrivileges(_) => ACL,
1074 Statement::ReassignOwned(_) => ACL,
1075
1076 Statement::Copy(_) => DML,
1078 Statement::Delete(_) => DML,
1079 Statement::ExplainPlan(_) => DML,
1080 Statement::ExplainPushdown(_) => DML,
1081 Statement::ExplainTimestamp(_) => DML,
1082 Statement::ExplainSinkSchema(_) => DML,
1083 Statement::Insert(_) => DML,
1084 Statement::Select(_) => DML,
1085 Statement::Subscribe(_) => DML,
1086 Statement::Update(_) => DML,
1087
1088 Statement::Show(ShowStatement::ShowColumns(_)) => Show,
1090 Statement::Show(ShowStatement::ShowCreateConnection(_)) => Show,
1091 Statement::Show(ShowStatement::ShowCreateCluster(_)) => Show,
1092 Statement::Show(ShowStatement::ShowCreateIndex(_)) => Show,
1093 Statement::Show(ShowStatement::ShowCreateSink(_)) => Show,
1094 Statement::Show(ShowStatement::ShowCreateSource(_)) => Show,
1095 Statement::Show(ShowStatement::ShowCreateTable(_)) => Show,
1096 Statement::Show(ShowStatement::ShowCreateView(_)) => Show,
1097 Statement::Show(ShowStatement::ShowCreateMaterializedView(_)) => Show,
1098 Statement::Show(ShowStatement::ShowObjects(_)) => Show,
1099
1100 Statement::Close(_) => SCL,
1102 Statement::Deallocate(_) => SCL,
1103 Statement::Declare(_) => SCL,
1104 Statement::Discard(_) => SCL,
1105 Statement::Execute(_) => SCL,
1106 Statement::Fetch(_) => SCL,
1107 Statement::Prepare(_) => SCL,
1108 Statement::ResetVariable(_) => SCL,
1109 Statement::SetVariable(_) => SCL,
1110 Statement::Show(ShowStatement::ShowVariable(_)) => SCL,
1111
1112 Statement::Commit(_) => TCL,
1114 Statement::Rollback(_) => TCL,
1115 Statement::SetTransaction(_) => TCL,
1116 Statement::StartTransaction(_) => TCL,
1117
1118 Statement::Raise(_) => Other,
1120 Statement::Show(ShowStatement::InspectShard(_)) => Other,
1121 Statement::ValidateConnection(_) => Other,
1122 }
1123 }
1124}