Skip to main content

mz_sql/
plan.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//! SQL planning.
11//!
12//! SQL planning is the process of taking the abstract syntax tree of a
13//! [`Statement`] and turning it into a [`Plan`] that the dataflow layer can
14//! execute.
15//!
16//! Statements must be purified before they can be planned. See the
17//! [`pure`](crate::pure) module for details.
18
19// Internal module layout.
20//
21// The entry point for planning is `statement::handle_statement`. That function
22// dispatches to a more specific `handle` function for the particular statement
23// type. For most statements, this `handle` function is uninteresting and short,
24// but anything involving a `SELECT` statement gets complicated. `SELECT`
25// queries wind through the functions in the `query` module, starting with
26// `plan_root_query` and fanning out based on the contents of the `SELECT`
27// statement.
28
29use std::collections::{BTreeMap, BTreeSet};
30use std::num::NonZeroUsize;
31use std::str::FromStr;
32use std::time::Duration;
33
34use chrono::{DateTime, Utc};
35use enum_kinds::EnumKind;
36use ipnet::IpNet;
37use maplit::btreeset;
38use mz_adapter_types::compaction::CompactionWindow;
39use mz_controller_types::{ClusterId, ReplicaId};
40use mz_expr::{CollectionPlan, ColumnOrder, MapFilterProject, MirScalarExpr, RowSetFinishing};
41use mz_ore::now::{self, NOW_ZERO};
42use mz_pgcopy::CopyFormatParams;
43use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
44use mz_repr::explain::{ExplainConfig, ExplainFormat};
45use mz_repr::network_policy_id::NetworkPolicyId;
46use mz_repr::optimize::OptimizerFeatureOverrides;
47use mz_repr::query_policy_id::QueryPolicyId;
48use mz_repr::refresh_schedule::RefreshSchedule;
49use mz_repr::role_id::RoleId;
50use mz_repr::{
51    CatalogItemId, ColumnIndex, ColumnName, Diff, GlobalId, RelationDesc, ReprColumnType, Row,
52    SqlColumnType, SqlRelationType, SqlScalarType, Timestamp, VersionedRelationDesc,
53};
54use mz_sql_parser::ast::{
55    AlterSourceAddSubsourceOption, ClusterAlterOptionValue, ConnectionOptionName, CreateSinkOption,
56    CreateSinkOptionName, QualifiedReplica, RawDataType, SelectStatement,
57    TransactionIsolationLevel, TransactionMode, UnresolvedItemName, Value, WithOptionValue,
58};
59use mz_ssh_util::keys::SshKeyPair;
60use mz_storage_types::connections::aws::AwsConnection;
61use mz_storage_types::connections::gcp::{GcpConnection, GcpServiceAccountKeyTokenUri};
62use mz_storage_types::connections::inline::ReferencedConnection;
63use mz_storage_types::connections::{
64    AwsPrivatelinkConnection, CsrConnection, GlueSchemaRegistryConnection,
65    IcebergCatalogConnection, KafkaConnection, MySqlConnection, PostgresConnection,
66    SqlServerConnectionDetails, SshConnection,
67};
68use mz_storage_types::instances::StorageInstanceId;
69use mz_storage_types::sinks::{S3SinkFormat, SinkEnvelope, StorageSinkConnection};
70use mz_storage_types::sources::{
71    SourceDesc, SourceExportDataConfig, SourceExportDetails, Timeline,
72};
73use proptest_derive::Arbitrary;
74use serde::{Deserialize, Serialize};
75
76use crate::ast::{
77    ExplainStage, Expr, FetchDirection, NoticeSeverity, Raw, Statement, StatementKind,
78    TransactionAccessMode,
79};
80use crate::catalog::{
81    CatalogType, DefaultPrivilegeAclItem, DefaultPrivilegeObject, IdReference, ObjectType,
82    RoleAttributesRaw,
83};
84use crate::names::{
85    Aug, CommentObjectId, DependencyIds, FullItemName, ObjectId, QualifiedItemName,
86    ResolvedDatabaseSpecifier, ResolvedIds, SchemaSpecifier, SystemObjectId,
87};
88
89pub(crate) mod error;
90pub(crate) mod explain;
91pub(crate) mod hir;
92pub(crate) mod literal;
93pub(crate) mod lowering;
94pub(crate) mod notice;
95pub(crate) mod plan_utils;
96pub(crate) mod query;
97pub(crate) mod scope;
98pub(crate) mod side_effecting_func;
99pub(crate) mod statement;
100pub(crate) mod transform_ast;
101pub(crate) mod transform_hir;
102pub(crate) mod typeconv;
103pub use typeconv::{
104    CastContext, plan_hypothetical_cast_with_failure_mode, valid_cast_base_type_pairs,
105};
106pub(crate) mod with_options;
107
108use crate::plan;
109use crate::plan::statement::ddl::ClusterAlterUntilReadyOptionExtracted;
110use crate::plan::with_options::OptionalDuration;
111pub use error::PlanError;
112pub use explain::normalize_subqueries;
113pub use hir::{
114    AggregateExpr, CoercibleScalarExpr, Hir, HirRelationExpr, HirScalarExpr, JoinKind,
115    WindowExprType,
116};
117pub use lowering::Config as HirToMirConfig;
118pub use notice::PlanNotice;
119pub use query::{
120    ExprContext, QueryContext, QueryLifetime, is_supported_collation, scalar_type_from_catalog,
121};
122pub use scope::Scope;
123pub use side_effecting_func::SideEffectingFunc;
124pub use statement::ddl::{
125    AlterSourceAddSubsourceOptionExtracted, METRIC_SINK_CURATED_PREFIX_MARKER,
126    MySqlConfigOptionExtracted, PgConfigOptionExtracted, PlannedAlterRoleOption,
127    PlannedRoleAttributes, PlannedRoleVariable, SqlServerConfigOptionExtracted,
128    validate_metric_sink_desc, validate_metric_sink_prefix, validate_user_metric_sink_prefix,
129};
130pub use statement::{
131    StatementClassification, StatementContext, StatementDesc, describe, plan, plan_copy_from,
132    resolve_cluster_for_materialized_view,
133};
134pub use with_options::TryFromValue;
135
136use self::statement::ddl::ClusterAlterOptionExtracted;
137
138/// Instructions for executing a SQL query.
139#[derive(Debug, EnumKind)]
140#[enum_kind(PlanKind)]
141pub enum Plan {
142    CreateConnection(CreateConnectionPlan),
143    CreateDatabase(CreateDatabasePlan),
144    CreateSchema(CreateSchemaPlan),
145    CreateRole(CreateRolePlan),
146    CreateCluster(CreateClusterPlan),
147    CreateClusterReplica(CreateClusterReplicaPlan),
148    CreateSource(CreateSourcePlan),
149    CreateSources(Vec<CreateSourcePlanBundle>),
150    CreateSecret(CreateSecretPlan),
151    CreateSink(CreateSinkPlan),
152    CreateTable(CreateTablePlan),
153    CreateView(CreateViewPlan),
154    CreateMaterializedView(CreateMaterializedViewPlan),
155    CreateNetworkPolicy(CreateNetworkPolicyPlan),
156    CreateQueryPolicy(CreateQueryPolicyPlan),
157    CreateIndex(CreateIndexPlan),
158    CreateMetricSink(CreateMetricSinkPlan),
159    CreateType(CreateTypePlan),
160    Comment(CommentPlan),
161    DiscardTemp,
162    DiscardAll,
163    DropObjects(DropObjectsPlan),
164    DropOwned(DropOwnedPlan),
165    EmptyQuery,
166    ShowAllVariables,
167    ShowCreate(ShowCreatePlan),
168    ShowColumns(ShowColumnsPlan),
169    ShowVariable(ShowVariablePlan),
170    InspectShard(InspectShardPlan),
171    SetVariable(SetVariablePlan),
172    ResetVariable(ResetVariablePlan),
173    SetTransaction(SetTransactionPlan),
174    StartTransaction(StartTransactionPlan),
175    CommitTransaction(CommitTransactionPlan),
176    AbortTransaction(AbortTransactionPlan),
177    Select(SelectPlan),
178    Subscribe(SubscribePlan),
179    CopyFrom(CopyFromPlan),
180    CopyTo(CopyToPlan),
181    ExplainPlan(ExplainPlanPlan),
182    ExplainPushdown(ExplainPushdownPlan),
183    ExplainTimestamp(ExplainTimestampPlan),
184    ExplainSinkSchema(ExplainSinkSchemaPlan),
185    Insert(InsertPlan),
186    AlterCluster(AlterClusterPlan),
187    AlterClusterSwap(AlterClusterSwapPlan),
188    AlterNoop(AlterNoopPlan),
189    AlterSetCluster(AlterSetClusterPlan),
190    AlterConnection(AlterConnectionPlan),
191    AlterSource(AlterSourcePlan),
192    AlterClusterRename(AlterClusterRenamePlan),
193    AlterClusterReplicaRename(AlterClusterReplicaRenamePlan),
194    AlterItemRename(AlterItemRenamePlan),
195    AlterSchemaRename(AlterSchemaRenamePlan),
196    AlterSchemaSwap(AlterSchemaSwapPlan),
197    AlterSecret(AlterSecretPlan),
198    AlterSink(AlterSinkPlan),
199    AlterSystemSet(AlterSystemSetPlan),
200    AlterSystemReset(AlterSystemResetPlan),
201    AlterSystemResetAll(AlterSystemResetAllPlan),
202    AlterRole(AlterRolePlan),
203    AlterOwner(AlterOwnerPlan),
204    AlterTableAddColumn(AlterTablePlan),
205    AlterMaterializedViewApplyReplacement(AlterMaterializedViewApplyReplacementPlan),
206    AlterNetworkPolicy(AlterNetworkPolicyPlan),
207    AlterQueryPolicy(AlterQueryPolicyPlan),
208    Declare(DeclarePlan),
209    Fetch(FetchPlan),
210    Close(ClosePlan),
211    ReadThenWrite(ReadThenWritePlan),
212    Prepare(PreparePlan),
213    Execute(ExecutePlan),
214    Deallocate(DeallocatePlan),
215    Raise(RaisePlan),
216    GrantRole(GrantRolePlan),
217    RevokeRole(RevokeRolePlan),
218    GrantPrivileges(GrantPrivilegesPlan),
219    RevokePrivileges(RevokePrivilegesPlan),
220    AlterDefaultPrivileges(AlterDefaultPrivilegesPlan),
221    ReassignOwned(ReassignOwnedPlan),
222    SideEffectingFunc(SideEffectingFunc),
223    ValidateConnection(ValidateConnectionPlan),
224    AlterRetainHistory(AlterRetainHistoryPlan),
225    AlterSourceTimestampInterval(AlterSourceTimestampIntervalPlan),
226}
227
228impl Plan {
229    /// Expresses which [`StatementKind`] can generate which set of
230    /// [`PlanKind`].
231    pub fn generated_from(stmt: &StatementKind) -> &'static [PlanKind] {
232        match stmt {
233            StatementKind::AlterCluster => &[PlanKind::AlterNoop, PlanKind::AlterCluster],
234            StatementKind::AlterConnection => &[PlanKind::AlterNoop, PlanKind::AlterConnection],
235            StatementKind::AlterDefaultPrivileges => &[PlanKind::AlterDefaultPrivileges],
236            StatementKind::AlterIndex => &[PlanKind::AlterRetainHistory, PlanKind::AlterNoop],
237            StatementKind::AlterObjectRename => &[
238                PlanKind::AlterClusterRename,
239                PlanKind::AlterClusterReplicaRename,
240                PlanKind::AlterItemRename,
241                PlanKind::AlterSchemaRename,
242                PlanKind::AlterNoop,
243            ],
244            StatementKind::AlterObjectSwap => &[
245                PlanKind::AlterClusterSwap,
246                PlanKind::AlterSchemaSwap,
247                PlanKind::AlterNoop,
248            ],
249            StatementKind::AlterRole => &[PlanKind::AlterRole],
250            StatementKind::AlterNetworkPolicy => &[PlanKind::AlterNetworkPolicy],
251            StatementKind::AlterQueryPolicy => &[PlanKind::AlterQueryPolicy, PlanKind::AlterOwner],
252            StatementKind::AlterSecret => &[PlanKind::AlterNoop, PlanKind::AlterSecret],
253            StatementKind::AlterSetCluster => &[PlanKind::AlterNoop, PlanKind::AlterSetCluster],
254            StatementKind::AlterSink => &[PlanKind::AlterNoop, PlanKind::AlterSink],
255            StatementKind::AlterSource => &[
256                PlanKind::AlterNoop,
257                PlanKind::AlterSource,
258                PlanKind::AlterRetainHistory,
259                PlanKind::AlterSourceTimestampInterval,
260            ],
261            StatementKind::AlterSystemReset => &[PlanKind::AlterNoop, PlanKind::AlterSystemReset],
262            StatementKind::AlterSystemResetAll => {
263                &[PlanKind::AlterNoop, PlanKind::AlterSystemResetAll]
264            }
265            StatementKind::AlterSystemSet => &[PlanKind::AlterNoop, PlanKind::AlterSystemSet],
266            StatementKind::AlterOwner => &[PlanKind::AlterNoop, PlanKind::AlterOwner],
267            StatementKind::AlterTableAddColumn => {
268                &[PlanKind::AlterNoop, PlanKind::AlterTableAddColumn]
269            }
270            StatementKind::AlterMaterializedViewApplyReplacement => &[
271                PlanKind::AlterNoop,
272                PlanKind::AlterMaterializedViewApplyReplacement,
273            ],
274            StatementKind::Close => &[PlanKind::Close],
275            StatementKind::Comment => &[PlanKind::Comment],
276            StatementKind::Commit => &[PlanKind::CommitTransaction],
277            StatementKind::Copy => &[
278                PlanKind::CopyFrom,
279                PlanKind::Select,
280                PlanKind::Subscribe,
281                PlanKind::CopyTo,
282            ],
283            StatementKind::CreateCluster => &[PlanKind::CreateCluster],
284            StatementKind::CreateClusterReplica => &[PlanKind::CreateClusterReplica],
285            StatementKind::CreateConnection => &[PlanKind::CreateConnection],
286            StatementKind::CreateDatabase => &[PlanKind::CreateDatabase],
287            StatementKind::CreateIndex => &[PlanKind::CreateIndex],
288            StatementKind::CreateNetworkPolicy => &[PlanKind::CreateNetworkPolicy],
289            StatementKind::CreateQueryPolicy => &[PlanKind::CreateQueryPolicy],
290            StatementKind::CreateMaterializedView => &[PlanKind::CreateMaterializedView],
291            StatementKind::CreateRole => &[PlanKind::CreateRole],
292            StatementKind::CreateSchema => &[PlanKind::CreateSchema],
293            StatementKind::CreateSecret => &[PlanKind::CreateSecret],
294            StatementKind::CreateSink => &[PlanKind::CreateSink],
295            StatementKind::CreateMetricSink => &[PlanKind::CreateMetricSink],
296            StatementKind::CreateSource | StatementKind::CreateSubsource => {
297                &[PlanKind::CreateSource]
298            }
299            StatementKind::CreateWebhookSource => &[PlanKind::CreateSource, PlanKind::CreateTable],
300            StatementKind::CreateTable => &[PlanKind::CreateTable],
301            StatementKind::CreateTableFromSource => &[PlanKind::CreateTable],
302            StatementKind::CreateType => &[PlanKind::CreateType],
303            StatementKind::CreateView => &[PlanKind::CreateView],
304            StatementKind::Deallocate => &[PlanKind::Deallocate],
305            StatementKind::Declare => &[PlanKind::Declare],
306            StatementKind::Delete => &[PlanKind::ReadThenWrite],
307            StatementKind::Discard => &[PlanKind::DiscardAll, PlanKind::DiscardTemp],
308            StatementKind::DropObjects => &[PlanKind::DropObjects],
309            StatementKind::DropOwned => &[PlanKind::DropOwned],
310            StatementKind::Execute => &[PlanKind::Execute],
311            StatementKind::ExplainPlan => &[PlanKind::ExplainPlan],
312            StatementKind::ExplainPushdown => &[PlanKind::ExplainPushdown],
313            StatementKind::ExplainAnalyzeObject => &[PlanKind::Select],
314            StatementKind::ExplainAnalyzeCluster => &[PlanKind::Select],
315            StatementKind::ExplainTimestamp => &[PlanKind::ExplainTimestamp],
316            StatementKind::ExplainSinkSchema => &[PlanKind::ExplainSinkSchema],
317            StatementKind::Fetch => &[PlanKind::Fetch],
318            StatementKind::GrantPrivileges => &[PlanKind::GrantPrivileges],
319            StatementKind::GrantRole => &[PlanKind::GrantRole],
320            StatementKind::Insert => &[PlanKind::Insert],
321            StatementKind::Prepare => &[PlanKind::Prepare],
322            StatementKind::Raise => &[PlanKind::Raise],
323            StatementKind::ReassignOwned => &[PlanKind::ReassignOwned],
324            StatementKind::ResetVariable => &[PlanKind::ResetVariable],
325            StatementKind::RevokePrivileges => &[PlanKind::RevokePrivileges],
326            StatementKind::RevokeRole => &[PlanKind::RevokeRole],
327            StatementKind::Rollback => &[PlanKind::AbortTransaction],
328            StatementKind::Select => &[PlanKind::Select, PlanKind::SideEffectingFunc],
329            StatementKind::SetTransaction => &[PlanKind::SetTransaction],
330            StatementKind::SetVariable => &[PlanKind::SetVariable],
331            StatementKind::Show => &[
332                PlanKind::Select,
333                PlanKind::ShowVariable,
334                PlanKind::ShowCreate,
335                PlanKind::ShowColumns,
336                PlanKind::ShowAllVariables,
337                PlanKind::InspectShard,
338            ],
339            StatementKind::StartTransaction => &[PlanKind::StartTransaction],
340            StatementKind::Subscribe => &[PlanKind::Subscribe],
341            StatementKind::Update => &[PlanKind::ReadThenWrite],
342            StatementKind::ValidateConnection => &[PlanKind::ValidateConnection],
343            StatementKind::AlterRetainHistory => &[PlanKind::AlterRetainHistory],
344            StatementKind::ExecuteUnitTest => &[],
345        }
346    }
347
348    /// Returns a human readable name of the plan. Meant for use in messages sent back to a user.
349    pub fn name(&self) -> &str {
350        match self {
351            Plan::CreateConnection(_) => "create connection",
352            Plan::CreateDatabase(_) => "create database",
353            Plan::CreateSchema(_) => "create schema",
354            Plan::CreateRole(_) => "create role",
355            Plan::CreateCluster(_) => "create cluster",
356            Plan::CreateClusterReplica(_) => "create cluster replica",
357            Plan::CreateSource(_) => "create source",
358            Plan::CreateSources(_) => "create source",
359            Plan::CreateSecret(_) => "create secret",
360            Plan::CreateSink(_) => "create sink",
361            Plan::CreateTable(_) => "create table",
362            Plan::CreateView(_) => "create view",
363            Plan::CreateMaterializedView(_) => "create materialized view",
364            Plan::CreateIndex(_) => "create index",
365            Plan::CreateMetricSink(_) => "create metric sink",
366            Plan::CreateType(_) => "create type",
367            Plan::CreateNetworkPolicy(_) => "create network policy",
368            Plan::CreateQueryPolicy(_) => "create query policy",
369            Plan::Comment(_) => "comment",
370            Plan::DiscardTemp => "discard temp",
371            Plan::DiscardAll => "discard all",
372            Plan::DropObjects(plan) => match plan.object_type {
373                ObjectType::Table => "drop table",
374                ObjectType::View => "drop view",
375                ObjectType::MaterializedView => "drop materialized view",
376                ObjectType::Source => "drop source",
377                ObjectType::Sink => "drop sink",
378                ObjectType::MetricSink => "drop metric sink",
379                ObjectType::Index => "drop index",
380                ObjectType::Type => "drop type",
381                ObjectType::Role => "drop roles",
382                ObjectType::Cluster => "drop clusters",
383                ObjectType::ClusterReplica => "drop cluster replicas",
384                ObjectType::Secret => "drop secret",
385                ObjectType::Connection => "drop connection",
386                ObjectType::Database => "drop database",
387                ObjectType::Schema => "drop schema",
388                ObjectType::Func => "drop function",
389                ObjectType::NetworkPolicy => "drop network policy",
390                ObjectType::QueryPolicy => "drop query policy",
391            },
392            Plan::DropOwned(_) => "drop owned",
393            Plan::EmptyQuery => "do nothing",
394            Plan::ShowAllVariables => "show all variables",
395            Plan::ShowCreate(_) => "show create",
396            Plan::ShowColumns(_) => "show columns",
397            Plan::ShowVariable(_) => "show variable",
398            Plan::InspectShard(_) => "inspect shard",
399            Plan::SetVariable(_) => "set variable",
400            Plan::ResetVariable(_) => "reset variable",
401            Plan::SetTransaction(_) => "set transaction",
402            Plan::StartTransaction(_) => "start transaction",
403            Plan::CommitTransaction(_) => "commit",
404            Plan::AbortTransaction(_) => "abort",
405            Plan::Select(_) => "select",
406            Plan::Subscribe(_) => "subscribe",
407            Plan::CopyFrom(_) => "copy from",
408            Plan::CopyTo(_) => "copy to",
409            Plan::ExplainPlan(_) => "explain plan",
410            Plan::ExplainPushdown(_) => "EXPLAIN FILTER PUSHDOWN",
411            Plan::ExplainTimestamp(_) => "explain timestamp",
412            Plan::ExplainSinkSchema(_) => "explain schema",
413            Plan::Insert(_) => "insert",
414            Plan::AlterNoop(plan) => match plan.object_type {
415                ObjectType::Table => "alter table",
416                ObjectType::View => "alter view",
417                ObjectType::MaterializedView => "alter materialized view",
418                ObjectType::Source => "alter source",
419                ObjectType::Sink => "alter sink",
420                ObjectType::MetricSink => "alter metric sink",
421                ObjectType::Index => "alter index",
422                ObjectType::Type => "alter type",
423                ObjectType::Role => "alter role",
424                ObjectType::Cluster => "alter cluster",
425                ObjectType::ClusterReplica => "alter cluster replica",
426                ObjectType::Secret => "alter secret",
427                ObjectType::Connection => "alter connection",
428                ObjectType::Database => "alter database",
429                ObjectType::Schema => "alter schema",
430                ObjectType::Func => "alter function",
431                ObjectType::NetworkPolicy => "alter network policy",
432                ObjectType::QueryPolicy => "alter query policy",
433            },
434            Plan::AlterCluster(_) => "alter cluster",
435            Plan::AlterClusterRename(_) => "alter cluster rename",
436            Plan::AlterClusterSwap(_) => "alter cluster swap",
437            Plan::AlterClusterReplicaRename(_) => "alter cluster replica rename",
438            Plan::AlterSetCluster(_) => "alter set cluster",
439            Plan::AlterConnection(_) => "alter connection",
440            Plan::AlterSource(_) => "alter source",
441            Plan::AlterItemRename(_) => "rename item",
442            Plan::AlterSchemaRename(_) => "alter rename schema",
443            Plan::AlterSchemaSwap(_) => "alter swap schema",
444            Plan::AlterSecret(_) => "alter secret",
445            Plan::AlterSink(_) => "alter sink",
446            Plan::AlterSystemSet(_) => "alter system",
447            Plan::AlterSystemReset(_) => "alter system",
448            Plan::AlterSystemResetAll(_) => "alter system",
449            Plan::AlterRole(_) => "alter role",
450            Plan::AlterNetworkPolicy(_) => "alter network policy",
451            Plan::AlterQueryPolicy(_) => "alter query policy",
452            Plan::AlterOwner(plan) => match plan.object_type {
453                ObjectType::Table => "alter table owner",
454                ObjectType::View => "alter view owner",
455                ObjectType::MaterializedView => "alter materialized view owner",
456                ObjectType::Source => "alter source owner",
457                ObjectType::Sink => "alter sink owner",
458                ObjectType::MetricSink => "alter metric sink owner",
459                ObjectType::Index => "alter index owner",
460                ObjectType::Type => "alter type owner",
461                ObjectType::Role => "alter role owner",
462                ObjectType::Cluster => "alter cluster owner",
463                ObjectType::ClusterReplica => "alter cluster replica owner",
464                ObjectType::Secret => "alter secret owner",
465                ObjectType::Connection => "alter connection owner",
466                ObjectType::Database => "alter database owner",
467                ObjectType::Schema => "alter schema owner",
468                ObjectType::Func => "alter function owner",
469                ObjectType::NetworkPolicy => "alter network policy owner",
470                ObjectType::QueryPolicy => "alter query policy owner",
471            },
472            Plan::AlterTableAddColumn(_) => "alter table add column",
473            Plan::AlterMaterializedViewApplyReplacement(_) => {
474                "alter materialized view apply replacement"
475            }
476            Plan::Declare(_) => "declare",
477            Plan::Fetch(_) => "fetch",
478            Plan::Close(_) => "close",
479            Plan::ReadThenWrite(plan) => match plan.kind {
480                MutationKind::Insert => "insert into select",
481                MutationKind::Update => "update",
482                MutationKind::Delete => "delete",
483            },
484            Plan::Prepare(_) => "prepare",
485            Plan::Execute(_) => "execute",
486            Plan::Deallocate(_) => "deallocate",
487            Plan::Raise(_) => "raise",
488            Plan::GrantRole(_) => "grant role",
489            Plan::RevokeRole(_) => "revoke role",
490            Plan::GrantPrivileges(_) => "grant privilege",
491            Plan::RevokePrivileges(_) => "revoke privilege",
492            Plan::AlterDefaultPrivileges(_) => "alter default privileges",
493            Plan::ReassignOwned(_) => "reassign owned",
494            Plan::SideEffectingFunc(_) => "side effecting func",
495            Plan::ValidateConnection(_) => "validate connection",
496            Plan::AlterRetainHistory(_) => "alter retain history",
497            Plan::AlterSourceTimestampInterval(_) => "alter source timestamp interval",
498        }
499    }
500
501    /// Returns `true` iff this `Plan` is allowed to be executed in read-only
502    /// mode.
503    ///
504    /// We use an explicit allow-list, to avoid future additions automatically
505    /// falling into the `true` category.
506    pub fn allowed_in_read_only(&self) -> bool {
507        match self {
508            // These two set non-durable session variables, so are okay in
509            // read-only mode.
510            Plan::SetVariable(_) => true,
511            Plan::ResetVariable(_) => true,
512            Plan::SetTransaction(_) => true,
513            Plan::StartTransaction(_) => true,
514            Plan::CommitTransaction(_) => true,
515            Plan::AbortTransaction(_) => true,
516            Plan::Select(_) => true,
517            Plan::EmptyQuery => true,
518            Plan::ShowAllVariables => true,
519            Plan::ShowCreate(_) => true,
520            Plan::ShowColumns(_) => true,
521            Plan::ShowVariable(_) => true,
522            Plan::InspectShard(_) => true,
523            Plan::Subscribe(_) => true,
524            Plan::CopyTo(_) => true,
525            Plan::ExplainPlan(_) => true,
526            Plan::ExplainPushdown(_) => true,
527            Plan::ExplainTimestamp(_) => true,
528            Plan::ExplainSinkSchema(_) => true,
529            Plan::ValidateConnection(_) => true,
530            _ => false,
531        }
532    }
533}
534
535#[derive(Debug)]
536pub struct StartTransactionPlan {
537    pub access: Option<TransactionAccessMode>,
538    pub isolation_level: Option<TransactionIsolationLevel>,
539}
540
541#[derive(Debug)]
542pub enum TransactionType {
543    Explicit,
544    Implicit,
545}
546
547impl TransactionType {
548    pub fn is_explicit(&self) -> bool {
549        matches!(self, TransactionType::Explicit)
550    }
551
552    pub fn is_implicit(&self) -> bool {
553        matches!(self, TransactionType::Implicit)
554    }
555}
556
557#[derive(Debug)]
558pub struct CommitTransactionPlan {
559    pub transaction_type: TransactionType,
560}
561
562#[derive(Debug)]
563pub struct AbortTransactionPlan {
564    pub transaction_type: TransactionType,
565}
566
567#[derive(Debug)]
568pub struct CreateDatabasePlan {
569    pub name: String,
570    pub if_not_exists: bool,
571}
572
573#[derive(Debug)]
574pub struct CreateSchemaPlan {
575    pub database_spec: ResolvedDatabaseSpecifier,
576    pub schema_name: String,
577    pub if_not_exists: bool,
578}
579
580#[derive(Debug)]
581pub struct CreateRolePlan {
582    pub name: String,
583    pub attributes: RoleAttributesRaw,
584}
585
586#[derive(Debug, PartialEq, Eq, Clone)]
587pub struct CreateClusterPlan {
588    pub name: String,
589    pub variant: CreateClusterVariant,
590    pub workload_class: Option<String>,
591    pub if_not_exists: bool,
592    pub query_policy: Option<QueryPolicyId>,
593}
594
595#[derive(Debug, PartialEq, Eq, Clone)]
596pub enum CreateClusterVariant {
597    Managed(CreateClusterManagedPlan),
598    Unmanaged(CreateClusterUnmanagedPlan),
599}
600
601#[derive(Debug, PartialEq, Eq, Clone)]
602pub struct CreateClusterUnmanagedPlan {
603    pub replicas: Vec<(String, ReplicaConfig)>,
604}
605
606#[derive(Debug, PartialEq, Eq, Clone)]
607pub struct CreateClusterManagedPlan {
608    pub replication_factor: u32,
609    pub size: String,
610    pub availability_zones: Vec<String>,
611    pub compute: ComputeReplicaConfig,
612    pub optimizer_feature_overrides: OptimizerFeatureOverrides,
613    pub schedule: ClusterSchedule,
614    /// The user-configured autoscaling policy, or `None` if autoscaling is
615    /// disabled for the cluster.
616    pub auto_scaling_strategy: Option<AutoScalingStrategy>,
617}
618
619#[derive(Debug)]
620pub struct CreateClusterReplicaPlan {
621    pub cluster_id: ClusterId,
622    pub name: String,
623    pub config: ReplicaConfig,
624    pub if_not_exists: bool,
625}
626
627/// Configuration of introspection for a cluster replica.
628#[derive(
629    Clone,
630    Copy,
631    Debug,
632    Serialize,
633    Deserialize,
634    PartialOrd,
635    Ord,
636    PartialEq,
637    Eq
638)]
639pub struct ComputeReplicaIntrospectionConfig {
640    /// Whether to introspect the introspection.
641    pub debugging: bool,
642    /// The interval at which to introspect.
643    pub interval: Duration,
644}
645
646#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
647pub struct ComputeReplicaConfig {
648    pub introspection: Option<ComputeReplicaIntrospectionConfig>,
649    /// Whether arrangements on this replica request dictionary compression. The
650    /// gating feature flag decides whether a replica honors this value at
651    /// creation time.
652    pub arrangement_compression: bool,
653}
654
655#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
656pub enum ReplicaConfig {
657    Unorchestrated {
658        storagectl_addrs: Vec<String>,
659        computectl_addrs: Vec<String>,
660        compute: ComputeReplicaConfig,
661    },
662    Orchestrated {
663        size: String,
664        availability_zone: Option<String>,
665        compute: ComputeReplicaConfig,
666        internal: bool,
667        billed_as: Option<String>,
668    },
669}
670
671#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
672pub enum ClusterSchedule {
673    /// The system won't automatically turn the cluster On or Off.
674    Manual,
675    /// The cluster will be On when a REFRESH materialized view on it needs to refresh.
676    /// `hydration_time_estimate` determines how much time before a refresh to turn the
677    /// cluster On, so that it can rehydrate already before the refresh time.
678    Refresh { hydration_time_estimate: Duration },
679}
680
681impl Default for ClusterSchedule {
682    fn default() -> Self {
683        // (Has to be consistent with `impl Default for ClusterScheduleOptionValue`.)
684        ClusterSchedule::Manual
685    }
686}
687
688/// The user-configured autoscaling policy of a managed cluster.
689///
690/// Extensible: future strategies are added as additional optional sub-policies,
691/// so the block as a whole can grow without changing existing ones.
692#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
693pub struct AutoScalingStrategy {
694    pub on_hydration: Option<OnHydration>,
695}
696
697/// The `ON HYDRATION` autoscaling sub-policy: while objects are un-hydrated, run
698/// an extra replica at `hydration_size` to accelerate hydration.
699#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
700pub struct OnHydration {
701    pub hydration_size: String,
702    /// How long the burst replica lingers after the steady-state replicas
703    /// hydrate. `None` falls back to the system default at the controller.
704    pub linger_duration: Option<Duration>,
705}
706
707#[derive(Clone, Debug)]
708pub struct CreateSourcePlan {
709    pub name: QualifiedItemName,
710    pub source: Source,
711    pub if_not_exists: bool,
712    pub timeline: Timeline,
713    // None for subsources, which run on the parent cluster.
714    pub in_cluster: Option<ClusterId>,
715}
716
717#[derive(Clone, Debug, PartialEq, Eq)]
718pub struct SourceReferences {
719    pub updated_at: u64,
720    pub references: Vec<SourceReference>,
721}
722
723/// An available external reference for a source and if possible to retrieve,
724/// any column names it contains.
725#[derive(Clone, Debug, PartialEq, Eq)]
726pub struct SourceReference {
727    pub name: String,
728    pub namespace: Option<String>,
729    pub columns: Vec<String>,
730}
731
732/// A [`CreateSourcePlan`] and the metadata necessary to sequence it.
733#[derive(Debug)]
734pub struct CreateSourcePlanBundle {
735    /// ID of this source in the Catalog.
736    pub item_id: CatalogItemId,
737    /// ID used to reference this source from outside the catalog, e.g. compute.
738    pub global_id: GlobalId,
739    /// Details of the source to create.
740    pub plan: CreateSourcePlan,
741    /// Other catalog objects that are referenced by this source, determined at name resolution.
742    pub resolved_ids: ResolvedIds,
743    /// All the available upstream references for this source.
744    /// Populated for top-level sources that can contain subsources/tables
745    /// and used during sequencing to populate the appropriate catalog fields.
746    pub available_source_references: Option<SourceReferences>,
747}
748
749#[derive(Debug)]
750pub struct CreateConnectionPlan {
751    pub name: QualifiedItemName,
752    pub if_not_exists: bool,
753    pub connection: Connection,
754    pub validate: bool,
755}
756
757#[derive(Debug)]
758pub struct ValidateConnectionPlan {
759    /// ID of the connection in the Catalog.
760    pub id: CatalogItemId,
761    /// The connection to validate.
762    pub connection: mz_storage_types::connections::Connection<ReferencedConnection>,
763}
764
765#[derive(Debug)]
766pub struct CreateSecretPlan {
767    pub name: QualifiedItemName,
768    pub secret: Secret,
769    pub if_not_exists: bool,
770}
771
772#[derive(Debug)]
773pub struct CreateSinkPlan {
774    pub name: QualifiedItemName,
775    pub sink: Sink,
776    pub with_snapshot: bool,
777    pub if_not_exists: bool,
778    pub in_cluster: ClusterId,
779}
780
781#[derive(Debug)]
782pub struct CreateTablePlan {
783    pub name: QualifiedItemName,
784    pub table: Table,
785    pub if_not_exists: bool,
786}
787
788#[derive(Debug, Clone)]
789pub struct CreateViewPlan {
790    pub name: QualifiedItemName,
791    pub view: View,
792    /// The Catalog objects that this view is replacing, if any.
793    pub replace: Option<CatalogItemId>,
794    /// The Catalog objects that need to be dropped. This includes `replace` and any dependents.
795    pub drop_ids: Vec<CatalogItemId>,
796    pub if_not_exists: bool,
797    /// True if the view contains an expression that can make the exact column list
798    /// ambiguous. For example `NATURAL JOIN` or `SELECT *`.
799    pub ambiguous_columns: bool,
800}
801
802#[derive(Debug, Clone)]
803pub struct CreateMaterializedViewPlan {
804    pub name: QualifiedItemName,
805    pub materialized_view: MaterializedView,
806    /// The Catalog objects that this materialized view is replacing, if any.
807    pub replace: Option<CatalogItemId>,
808    /// The Catalog objects that need to be dropped. This includes `replace` and any dependents.
809    pub drop_ids: Vec<CatalogItemId>,
810    pub if_not_exists: bool,
811    /// True if the materialized view contains an expression that can make the exact column list
812    /// ambiguous. For example `NATURAL JOIN` or `SELECT *`.
813    pub ambiguous_columns: bool,
814}
815
816#[derive(Debug, Clone)]
817pub struct CreateQueryPolicyPlan {
818    pub name: String,
819    pub mode: QueryPolicyMode,
820    pub rules: Vec<QueryPolicyRule>,
821}
822
823#[derive(Debug, Clone)]
824pub struct AlterQueryPolicyPlan {
825    pub id: QueryPolicyId,
826    pub name: String,
827    pub mode: QueryPolicyMode,
828    pub rules: Vec<QueryPolicyRule>,
829}
830
831#[derive(Debug, Clone)]
832pub struct CreateNetworkPolicyPlan {
833    pub name: String,
834    pub rules: Vec<NetworkPolicyRule>,
835}
836
837#[derive(Debug, Clone)]
838pub struct AlterNetworkPolicyPlan {
839    pub id: NetworkPolicyId,
840    pub name: String,
841    pub rules: Vec<NetworkPolicyRule>,
842}
843
844#[derive(Debug, Clone)]
845pub struct CreateIndexPlan {
846    pub name: QualifiedItemName,
847    pub index: Index,
848    pub if_not_exists: bool,
849}
850
851#[derive(Debug, Clone)]
852pub struct CreateMetricSinkPlan {
853    pub name: QualifiedItemName,
854    pub metric_sink: MetricSink,
855    pub if_not_exists: bool,
856}
857
858#[derive(Debug)]
859pub struct CreateTypePlan {
860    pub name: QualifiedItemName,
861    pub typ: Type,
862}
863
864#[derive(Debug)]
865pub struct DropObjectsPlan {
866    pub cascade: bool,
867    /// The IDs of only the objects directly referenced in the `DROP` statement.
868    pub referenced_ids: Vec<ObjectId>,
869    /// All object IDs to drop. Includes `referenced_ids` and all descendants.
870    pub drop_ids: Vec<ObjectId>,
871    /// The type of object that was dropped explicitly in the DROP statement. `ids` may contain
872    /// objects of different types due to CASCADE.
873    pub object_type: ObjectType,
874}
875
876#[derive(Debug)]
877pub struct DropOwnedPlan {
878    pub cascade: bool,
879    /// The role IDs that own the objects.
880    pub role_ids: Vec<RoleId>,
881    /// All object IDs to drop.
882    pub drop_ids: Vec<ObjectId>,
883    /// The privileges to revoke.
884    pub privilege_revokes: Vec<(SystemObjectId, MzAclItem)>,
885    /// The default privileges to revoke.
886    pub default_privilege_revokes: Vec<(DefaultPrivilegeObject, DefaultPrivilegeAclItem)>,
887}
888
889#[derive(Debug)]
890pub struct ShowVariablePlan {
891    pub name: String,
892}
893
894#[derive(Debug)]
895pub struct InspectShardPlan {
896    /// ID of the storage collection to inspect.
897    pub id: GlobalId,
898}
899
900#[derive(Debug)]
901pub struct SetVariablePlan {
902    pub name: String,
903    pub value: VariableValue,
904    pub local: bool,
905}
906
907#[derive(Debug)]
908pub enum VariableValue {
909    Default,
910    Values(Vec<String>),
911}
912
913#[derive(Debug)]
914pub struct ResetVariablePlan {
915    pub name: String,
916}
917
918#[derive(Debug)]
919pub struct SetTransactionPlan {
920    pub local: bool,
921    pub modes: Vec<TransactionMode>,
922}
923
924/// A plan for select statements.
925#[derive(Clone, Debug)]
926pub struct SelectPlan {
927    /// The `SELECT` statement itself. Used for explain/notices, but not otherwise
928    /// load-bearing. Boxed to save stack space.
929    pub select: Option<Box<SelectStatement<Aug>>>,
930    /// The plan as a HIR.
931    pub source: HirRelationExpr,
932    /// At what time should this select happen?
933    pub when: QueryWhen,
934    /// Instructions how to form the result set.
935    pub finishing: RowSetFinishing,
936    /// For `COPY TO STDOUT`, the format to use.
937    pub copy_to: Option<CopyFormat>,
938}
939
940impl SelectPlan {
941    pub fn immediate(rows: Vec<Row>, typ: SqlRelationType) -> Self {
942        let arity = typ.arity();
943        SelectPlan {
944            select: None,
945            source: HirRelationExpr::Constant { rows, typ },
946            when: QueryWhen::Immediately,
947            finishing: RowSetFinishing::trivial(arity),
948            copy_to: None,
949        }
950    }
951}
952
953#[derive(Debug, Clone)]
954pub enum SubscribeOutput {
955    Diffs,
956    WithinTimestampOrderBy {
957        /// We pretend that mz_diff is prepended to the normal columns, making it index 0
958        order_by: Vec<ColumnOrder>,
959    },
960    EnvelopeUpsert {
961        /// Order by with just keys
962        order_by_keys: Vec<ColumnOrder>,
963    },
964    EnvelopeDebezium {
965        /// Order by with just keys
966        order_by_keys: Vec<ColumnOrder>,
967    },
968}
969
970impl SubscribeOutput {
971    pub fn row_order(&self) -> &[ColumnOrder] {
972        match self {
973            SubscribeOutput::Diffs => &[],
974            // This ordering prepends the diff, so its `order_by` field cannot be applied to rows.
975            SubscribeOutput::WithinTimestampOrderBy { .. } => &[],
976            SubscribeOutput::EnvelopeUpsert { order_by_keys } => order_by_keys,
977            SubscribeOutput::EnvelopeDebezium { order_by_keys } => order_by_keys,
978        }
979    }
980}
981
982#[derive(Debug, Clone)]
983pub struct SubscribePlan {
984    pub from: SubscribeFrom,
985    pub with_snapshot: bool,
986    pub when: QueryWhen,
987    pub up_to: Option<Timestamp>,
988    pub copy_to: Option<CopyFormat>,
989    pub emit_progress: bool,
990    pub output: SubscribeOutput,
991}
992
993#[derive(Debug, Clone)]
994pub enum SubscribeFrom {
995    /// ID of the collection to subscribe to.
996    Id(GlobalId),
997    /// Query to subscribe to.
998    Query {
999        expr: HirRelationExpr,
1000        desc: RelationDesc,
1001    },
1002}
1003
1004impl SubscribeFrom {
1005    pub fn depends_on(&self) -> BTreeSet<GlobalId> {
1006        match self {
1007            SubscribeFrom::Id(id) => BTreeSet::from([*id]),
1008            SubscribeFrom::Query { expr, .. } => expr.depends_on(),
1009        }
1010    }
1011
1012    pub fn contains_temporal(&self) -> bool {
1013        match self {
1014            SubscribeFrom::Id(_) => false,
1015            SubscribeFrom::Query { expr, .. } => expr.contains_temporal(),
1016        }
1017    }
1018}
1019
1020#[derive(Debug)]
1021pub struct ShowCreatePlan {
1022    pub id: ObjectId,
1023    pub row: Row,
1024}
1025
1026#[derive(Debug)]
1027pub struct ShowColumnsPlan {
1028    pub id: CatalogItemId,
1029    pub select_plan: SelectPlan,
1030    pub new_resolved_ids: ResolvedIds,
1031}
1032
1033#[derive(Debug)]
1034pub struct CopyFromPlan {
1035    /// Table we're copying into.
1036    pub target_id: CatalogItemId,
1037    /// Human-readable full name of the target table.
1038    pub target_name: String,
1039    /// Source we're copying data from.
1040    pub source: CopyFromSource,
1041    /// How input columns map to those on the destination table.
1042    ///
1043    /// TODO(cf2): Remove this field in favor of the mfp.
1044    pub columns: Vec<ColumnIndex>,
1045    /// [`RelationDesc`] describing the input data.
1046    pub source_desc: RelationDesc,
1047    /// Changes the shape of the input data to match the destination table.
1048    pub mfp: MapFilterProject,
1049    /// Format specific params for copying the input data.
1050    pub params: CopyFormatParams<'static>,
1051    /// Filter for the source files we're copying from, e.g. an S3 prefix.
1052    pub filter: Option<CopyFromFilter>,
1053}
1054
1055#[derive(Debug)]
1056pub enum CopyFromSource {
1057    /// Copying from a file local to the user, transmitted via pgwire.
1058    Stdin,
1059    /// A remote resource, e.g. HTTP file.
1060    ///
1061    /// The contained [`HirScalarExpr`] evaluates to the Url for the remote resource.
1062    Url(HirScalarExpr),
1063    /// A file in an S3 bucket.
1064    AwsS3 {
1065        /// Expression that evaluates to the file we want to copy.
1066        uri: HirScalarExpr,
1067        /// Details for how we connect to AWS S3.
1068        connection: AwsConnection,
1069        /// ID of the connection object.
1070        connection_id: CatalogItemId,
1071    },
1072}
1073
1074#[derive(Debug)]
1075pub enum CopyFromFilter {
1076    Files(Vec<String>),
1077    Pattern(String),
1078}
1079
1080/// `COPY TO S3`
1081///
1082/// (This is a completely different thing from `COPY TO STDOUT`. That is a `Plan::Select` with
1083/// `copy_to` set.)
1084#[derive(Debug, Clone)]
1085pub struct CopyToPlan {
1086    /// The select query plan whose data will be copied to destination uri.
1087    pub select_plan: SelectPlan,
1088    pub desc: RelationDesc,
1089    /// The scalar expression to be resolved to get the destination uri.
1090    pub to: HirScalarExpr,
1091    pub connection: mz_storage_types::connections::Connection<ReferencedConnection>,
1092    /// The ID of the connection.
1093    pub connection_id: CatalogItemId,
1094    pub format: S3SinkFormat,
1095    pub max_file_size: u64,
1096}
1097
1098#[derive(Clone, Debug)]
1099pub struct ExplainPlanPlan {
1100    pub stage: ExplainStage,
1101    pub format: ExplainFormat,
1102    pub config: ExplainConfig,
1103    pub explainee: Explainee,
1104}
1105
1106/// The type of object to be explained
1107#[derive(Clone, Debug)]
1108pub enum Explainee {
1109    /// Lookup and explain a plan saved for an view.
1110    View(CatalogItemId),
1111    /// Lookup and explain a plan saved for an existing materialized view.
1112    MaterializedView(CatalogItemId),
1113    /// Lookup and explain a plan saved for an existing index.
1114    Index(CatalogItemId),
1115    /// Replan an existing view.
1116    ReplanView(CatalogItemId),
1117    /// Replan an existing materialized view.
1118    ReplanMaterializedView(CatalogItemId),
1119    /// Replan an existing index.
1120    ReplanIndex(CatalogItemId),
1121    /// A SQL statement.
1122    Statement(ExplaineeStatement),
1123}
1124
1125/// Explainee types that are statements.
1126#[derive(Clone, Debug, EnumKind)]
1127#[enum_kind(ExplaineeStatementKind)]
1128pub enum ExplaineeStatement {
1129    /// The object to be explained is a SELECT statement.
1130    Select {
1131        /// Broken flag (see [`ExplaineeStatement::broken()`]).
1132        broken: bool,
1133        plan: plan::SelectPlan,
1134        desc: RelationDesc,
1135    },
1136    /// The object to be explained is a CREATE VIEW.
1137    CreateView {
1138        /// Broken flag (see [`ExplaineeStatement::broken()`]).
1139        broken: bool,
1140        plan: plan::CreateViewPlan,
1141    },
1142    /// The object to be explained is a CREATE MATERIALIZED VIEW.
1143    CreateMaterializedView {
1144        /// Broken flag (see [`ExplaineeStatement::broken()`]).
1145        broken: bool,
1146        plan: plan::CreateMaterializedViewPlan,
1147    },
1148    /// The object to be explained is a CREATE INDEX.
1149    CreateIndex {
1150        /// Broken flag (see [`ExplaineeStatement::broken()`]).
1151        broken: bool,
1152        plan: plan::CreateIndexPlan,
1153    },
1154    /// The object to be explained is a SUBSCRIBE statement.
1155    Subscribe {
1156        /// Broken flag (see [`ExplaineeStatement::broken()`]).
1157        broken: bool,
1158        plan: plan::SubscribePlan,
1159    },
1160}
1161
1162impl ExplaineeStatement {
1163    pub fn depends_on(&self) -> BTreeSet<GlobalId> {
1164        match self {
1165            Self::Select { plan, .. } => plan.source.depends_on(),
1166            Self::CreateView { plan, .. } => plan.view.expr.depends_on(),
1167            Self::CreateMaterializedView { plan, .. } => plan.materialized_view.expr.depends_on(),
1168            Self::CreateIndex { plan, .. } => btreeset! {plan.index.on},
1169            Self::Subscribe { plan, .. } => plan.from.depends_on(),
1170        }
1171    }
1172
1173    /// Statements that have their `broken` flag set are expected to cause a
1174    /// panic in the optimizer code. In this case:
1175    ///
1176    /// 1. The optimizer pipeline execution will stop, but the panic will be
1177    ///    intercepted and will not propagate to the caller. The partial
1178    ///    optimizer trace collected until this point will be available.
1179    /// 2. The optimizer trace tracing subscriber will delegate regular tracing
1180    ///    spans and events to the default subscriber.
1181    ///
1182    /// This is useful when debugging queries that cause panics.
1183    pub fn broken(&self) -> bool {
1184        match self {
1185            Self::Select { broken, .. } => *broken,
1186            Self::CreateView { broken, .. } => *broken,
1187            Self::CreateMaterializedView { broken, .. } => *broken,
1188            Self::CreateIndex { broken, .. } => *broken,
1189            Self::Subscribe { broken, .. } => *broken,
1190        }
1191    }
1192}
1193
1194impl ExplaineeStatementKind {
1195    pub fn supports(&self, stage: &ExplainStage) -> bool {
1196        use ExplainStage::*;
1197        match self {
1198            Self::Select => true,
1199            Self::CreateView => ![GlobalPlan, PhysicalPlan].contains(stage),
1200            Self::CreateMaterializedView => true,
1201            Self::CreateIndex => ![RawPlan, DecorrelatedPlan, LocalPlan].contains(stage),
1202            // SUBSCRIBE doesn't support RAW, DECORRELATED, or LOCAL stages because
1203            // it takes MIR directly rather than going through HIR lowering.
1204            Self::Subscribe => ![RawPlan, DecorrelatedPlan, LocalPlan].contains(stage),
1205        }
1206    }
1207}
1208
1209impl std::fmt::Display for ExplaineeStatementKind {
1210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1211        match self {
1212            Self::Select => write!(f, "SELECT"),
1213            Self::CreateView => write!(f, "CREATE VIEW"),
1214            Self::CreateMaterializedView => write!(f, "CREATE MATERIALIZED VIEW"),
1215            Self::CreateIndex => write!(f, "CREATE INDEX"),
1216            Self::Subscribe => write!(f, "SUBSCRIBE"),
1217        }
1218    }
1219}
1220
1221#[derive(Clone, Debug)]
1222pub struct ExplainPushdownPlan {
1223    pub explainee: Explainee,
1224}
1225
1226#[derive(Clone, Debug)]
1227pub struct ExplainTimestampPlan {
1228    pub format: ExplainFormat,
1229    pub raw_plan: HirRelationExpr,
1230    pub when: QueryWhen,
1231}
1232
1233#[derive(Debug)]
1234pub struct ExplainSinkSchemaPlan {
1235    pub sink_from: GlobalId,
1236    pub json_schema: String,
1237}
1238
1239#[derive(Debug)]
1240pub struct SendDiffsPlan {
1241    pub id: CatalogItemId,
1242    pub updates: Vec<(Row, Diff)>,
1243    pub kind: MutationKind,
1244    pub returning: Vec<(Row, NonZeroUsize)>,
1245    pub max_result_size: u64,
1246}
1247
1248#[derive(Debug)]
1249pub struct InsertPlan {
1250    pub id: CatalogItemId,
1251    pub values: HirRelationExpr,
1252    pub returning: Vec<mz_expr::MirScalarExpr>,
1253}
1254
1255#[derive(Debug)]
1256pub struct ReadThenWritePlan {
1257    pub id: CatalogItemId,
1258    pub selection: HirRelationExpr,
1259    pub finishing: RowSetFinishing,
1260    pub assignments: BTreeMap<usize, mz_expr::MirScalarExpr>,
1261    pub kind: MutationKind,
1262    pub returning: Vec<mz_expr::MirScalarExpr>,
1263}
1264
1265/// Generated by `ALTER ... IF EXISTS` if the named object did not exist.
1266#[derive(Debug)]
1267pub struct AlterNoopPlan {
1268    pub object_type: ObjectType,
1269}
1270
1271#[derive(Debug)]
1272pub struct AlterSetClusterPlan {
1273    pub id: CatalogItemId,
1274    pub set_cluster: ClusterId,
1275}
1276
1277#[derive(Debug)]
1278pub struct AlterRetainHistoryPlan {
1279    pub id: CatalogItemId,
1280    pub value: Option<Value>,
1281    pub window: CompactionWindow,
1282    pub object_type: ObjectType,
1283}
1284
1285#[derive(Debug)]
1286pub struct AlterSourceTimestampIntervalPlan {
1287    pub id: CatalogItemId,
1288    pub value: Option<Value>,
1289    pub interval: Duration,
1290}
1291
1292#[derive(Debug, Clone)]
1293
1294pub enum AlterOptionParameter<T = String> {
1295    Set(T),
1296    Reset,
1297    Unchanged,
1298}
1299
1300#[derive(Debug)]
1301pub enum AlterConnectionAction {
1302    RotateKeys,
1303    AlterOptions {
1304        set_options: BTreeMap<ConnectionOptionName, Option<WithOptionValue<Aug>>>,
1305        drop_options: BTreeSet<ConnectionOptionName>,
1306        validate: bool,
1307    },
1308}
1309
1310#[derive(Debug)]
1311pub struct AlterConnectionPlan {
1312    pub id: CatalogItemId,
1313    pub action: AlterConnectionAction,
1314}
1315
1316#[derive(Debug)]
1317pub enum AlterSourceAction {
1318    AddSubsourceExports {
1319        subsources: Vec<CreateSourcePlanBundle>,
1320        options: Vec<AlterSourceAddSubsourceOption<Aug>>,
1321    },
1322    RefreshReferences {
1323        references: SourceReferences,
1324    },
1325}
1326
1327#[derive(Debug)]
1328pub struct AlterSourcePlan {
1329    pub item_id: CatalogItemId,
1330    pub ingestion_id: GlobalId,
1331    pub action: AlterSourceAction,
1332}
1333
1334#[derive(Debug, Clone)]
1335pub struct AlterSinkPlan {
1336    pub item_id: CatalogItemId,
1337    pub global_id: GlobalId,
1338    pub sink: Sink,
1339    pub with_snapshot: bool,
1340    pub in_cluster: ClusterId,
1341    /// The with-option edit requested by the `ALTER SINK`. Sequencing must
1342    /// re-apply it to the catalog's `create_sql` (via
1343    /// [`apply_sink_option_edits`]) because the `create_sql` may have changed
1344    /// since planning, for example due to a schema swap.
1345    pub set_options: Vec<CreateSinkOption<Aug>>,
1346    pub reset_options: Vec<CreateSinkOptionName>,
1347}
1348
1349/// Applies the option edits of an `ALTER SINK ... SET/RESET (...)` to the
1350/// with-options of a `CREATE SINK` statement.
1351pub fn apply_sink_option_edits<T: mz_sql_parser::ast::AstInfo>(
1352    with_options: &mut Vec<CreateSinkOption<T>>,
1353    set_options: &[CreateSinkOption<T>],
1354    reset_options: &[CreateSinkOptionName],
1355) where
1356    CreateSinkOption<T>: Clone,
1357{
1358    with_options.retain(|o| {
1359        set_options.iter().all(|s| s.name != o.name) && !reset_options.contains(&o.name)
1360    });
1361    with_options.extend(set_options.iter().cloned());
1362}
1363
1364#[derive(Debug, Clone)]
1365pub struct AlterClusterPlan {
1366    pub id: ClusterId,
1367    pub name: String,
1368    pub options: PlanClusterOption,
1369    pub strategy: AlterClusterPlanStrategy,
1370}
1371
1372#[derive(Debug)]
1373pub struct AlterClusterRenamePlan {
1374    pub id: ClusterId,
1375    pub name: String,
1376    pub to_name: String,
1377}
1378
1379#[derive(Debug)]
1380pub struct AlterClusterReplicaRenamePlan {
1381    pub cluster_id: ClusterId,
1382    pub replica_id: ReplicaId,
1383    pub name: QualifiedReplica,
1384    pub to_name: String,
1385}
1386
1387#[derive(Debug)]
1388pub struct AlterItemRenamePlan {
1389    pub id: CatalogItemId,
1390    pub current_full_name: FullItemName,
1391    pub to_name: String,
1392    pub object_type: ObjectType,
1393}
1394
1395#[derive(Debug)]
1396pub struct AlterSchemaRenamePlan {
1397    pub cur_schema_spec: (ResolvedDatabaseSpecifier, SchemaSpecifier),
1398    pub new_schema_name: String,
1399}
1400
1401#[derive(Debug)]
1402pub struct AlterSchemaSwapPlan {
1403    pub schema_a_spec: (ResolvedDatabaseSpecifier, SchemaSpecifier),
1404    pub schema_a_name: String,
1405    pub schema_b_spec: (ResolvedDatabaseSpecifier, SchemaSpecifier),
1406    pub schema_b_name: String,
1407    pub name_temp: String,
1408}
1409
1410#[derive(Debug)]
1411pub struct AlterClusterSwapPlan {
1412    pub id_a: ClusterId,
1413    pub id_b: ClusterId,
1414    pub name_a: String,
1415    pub name_b: String,
1416    pub name_temp: String,
1417}
1418
1419#[derive(Debug)]
1420pub struct AlterSecretPlan {
1421    pub id: CatalogItemId,
1422    pub secret_as: MirScalarExpr,
1423}
1424
1425#[derive(Debug)]
1426pub struct AlterSystemSetPlan {
1427    pub name: String,
1428    pub value: VariableValue,
1429}
1430
1431#[derive(Debug)]
1432pub struct AlterSystemResetPlan {
1433    pub name: String,
1434}
1435
1436#[derive(Debug)]
1437pub struct AlterSystemResetAllPlan {}
1438
1439#[derive(Debug)]
1440pub struct AlterRolePlan {
1441    pub id: RoleId,
1442    pub name: String,
1443    pub option: PlannedAlterRoleOption,
1444}
1445
1446#[derive(Debug)]
1447pub struct AlterOwnerPlan {
1448    pub id: ObjectId,
1449    pub object_type: ObjectType,
1450    pub new_owner: RoleId,
1451}
1452
1453#[derive(Debug)]
1454pub struct AlterTablePlan {
1455    pub relation_id: CatalogItemId,
1456    pub column_name: ColumnName,
1457    pub column_type: SqlColumnType,
1458    pub raw_sql_type: RawDataType,
1459}
1460
1461#[derive(Debug, Clone)]
1462pub struct AlterMaterializedViewApplyReplacementPlan {
1463    pub id: CatalogItemId,
1464    pub replacement_id: CatalogItemId,
1465}
1466
1467#[derive(Debug)]
1468pub struct DeclarePlan {
1469    pub name: String,
1470    pub stmt: Statement<Raw>,
1471    pub sql: String,
1472    pub params: Params,
1473}
1474
1475#[derive(Debug)]
1476pub struct FetchPlan {
1477    pub name: String,
1478    pub count: Option<FetchDirection>,
1479    pub timeout: ExecuteTimeout,
1480}
1481
1482#[derive(Debug)]
1483pub struct ClosePlan {
1484    pub name: String,
1485}
1486
1487#[derive(Debug)]
1488pub struct PreparePlan {
1489    pub name: String,
1490    pub stmt: Statement<Raw>,
1491    pub sql: String,
1492    pub desc: StatementDesc,
1493}
1494
1495#[derive(Debug)]
1496pub struct ExecutePlan {
1497    pub name: String,
1498    pub params: Params,
1499}
1500
1501#[derive(Debug)]
1502pub struct DeallocatePlan {
1503    pub name: Option<String>,
1504}
1505
1506#[derive(Debug)]
1507pub struct RaisePlan {
1508    pub severity: NoticeSeverity,
1509}
1510
1511#[derive(Debug)]
1512pub struct GrantRolePlan {
1513    /// The roles that are gaining members.
1514    pub role_ids: Vec<RoleId>,
1515    /// The roles that will be added to `role_id`.
1516    pub member_ids: Vec<RoleId>,
1517    /// The role that granted the membership.
1518    pub grantor_id: RoleId,
1519}
1520
1521#[derive(Debug)]
1522pub struct RevokeRolePlan {
1523    /// The roles that are losing members.
1524    pub role_ids: Vec<RoleId>,
1525    /// The roles that will be removed from `role_id`.
1526    pub member_ids: Vec<RoleId>,
1527    /// The role that revoked the membership.
1528    pub grantor_id: RoleId,
1529}
1530
1531#[derive(Debug)]
1532pub struct UpdatePrivilege {
1533    /// The privileges being granted/revoked on an object.
1534    pub acl_mode: AclMode,
1535    /// The ID of the object receiving privileges.
1536    pub target_id: SystemObjectId,
1537    /// The role that is granting the privileges.
1538    pub grantor: RoleId,
1539    /// Whether `acl_mode` was derived from the `ALL [PRIVILEGES]` shorthand.
1540    /// Used to suppress the `NonApplicablePrivilegeTypes` notice in that
1541    /// case: the shorthand is not the user explicitly naming a privilege
1542    /// that doesn't apply to the object type, so warning would be noisy.
1543    pub acl_from_all: bool,
1544}
1545
1546#[derive(Debug)]
1547pub struct GrantPrivilegesPlan {
1548    /// Description of each privilege being granted.
1549    pub update_privileges: Vec<UpdatePrivilege>,
1550    /// The roles that will granted the privileges.
1551    pub grantees: Vec<RoleId>,
1552}
1553
1554#[derive(Debug)]
1555pub struct RevokePrivilegesPlan {
1556    /// Description of each privilege being revoked.
1557    pub update_privileges: Vec<UpdatePrivilege>,
1558    /// The roles that will have privileges revoked.
1559    pub revokees: Vec<RoleId>,
1560}
1561#[derive(Debug)]
1562pub struct AlterDefaultPrivilegesPlan {
1563    /// Description of objects that match this default privilege.
1564    pub privilege_objects: Vec<DefaultPrivilegeObject>,
1565    /// The privilege to be granted/revoked from the matching objects.
1566    pub privilege_acl_items: Vec<DefaultPrivilegeAclItem>,
1567    /// Whether this is a grant or revoke.
1568    pub is_grant: bool,
1569}
1570
1571#[derive(Debug)]
1572pub struct ReassignOwnedPlan {
1573    /// The roles whose owned objects are being reassigned.
1574    pub old_roles: Vec<RoleId>,
1575    /// The new owner of the objects.
1576    pub new_role: RoleId,
1577    /// All object IDs to reassign.
1578    pub reassign_ids: Vec<ObjectId>,
1579}
1580
1581#[derive(Debug)]
1582pub struct CommentPlan {
1583    /// The object that this comment is associated with.
1584    pub object_id: CommentObjectId,
1585    /// A sub-component of the object that this comment is associated with, e.g. a column.
1586    ///
1587    /// TODO(parkmycar): <https://github.com/MaterializeInc/database-issues/issues/6711>.
1588    pub sub_component: Option<usize>,
1589    /// The comment itself. If `None` that indicates we should clear the existing comment.
1590    pub comment: Option<String>,
1591}
1592
1593#[derive(Clone, Debug)]
1594pub enum TableDataSource {
1595    /// The table owns data created via INSERT/UPDATE/DELETE statements.
1596    TableWrites { defaults: Vec<Expr<Aug>> },
1597
1598    /// The table receives its data from the identified `DataSourceDesc`.
1599    /// This table type does not support INSERT/UPDATE/DELETE statements.
1600    DataSource {
1601        desc: DataSourceDesc,
1602        timeline: Timeline,
1603    },
1604}
1605
1606#[derive(Clone, Debug)]
1607pub struct Table {
1608    pub create_sql: String,
1609    pub desc: VersionedRelationDesc,
1610    pub temporary: bool,
1611    pub compaction_window: Option<CompactionWindow>,
1612    pub data_source: TableDataSource,
1613}
1614
1615#[derive(Clone, Debug)]
1616pub struct Source {
1617    pub create_sql: String,
1618    pub data_source: DataSourceDesc,
1619    pub desc: RelationDesc,
1620    pub compaction_window: Option<CompactionWindow>,
1621}
1622
1623#[derive(Debug, Clone)]
1624pub enum DataSourceDesc {
1625    /// Receives data from an external system.
1626    Ingestion(SourceDesc<ReferencedConnection>),
1627    /// Receives data from an external system.
1628    OldSyntaxIngestion {
1629        desc: SourceDesc<ReferencedConnection>,
1630        // If we're dealing with an old syntax ingestion the progress id will be some other collection
1631        // and the ingestion itself will have the data from a default external reference
1632        progress_subsource: CatalogItemId,
1633        data_config: SourceExportDataConfig<ReferencedConnection>,
1634        details: SourceExportDetails,
1635    },
1636    /// This source receives its data from the identified ingestion,
1637    /// specifically the output identified by `external_reference`.
1638    IngestionExport {
1639        ingestion_id: CatalogItemId,
1640        external_reference: UnresolvedItemName,
1641        details: SourceExportDetails,
1642        data_config: SourceExportDataConfig<ReferencedConnection>,
1643    },
1644    /// Receives data from the source's reclocking/remapping operations.
1645    Progress,
1646    /// Receives data from HTTP post requests.
1647    Webhook {
1648        validate_using: Option<WebhookValidation>,
1649        body_format: WebhookBodyFormat,
1650        headers: WebhookHeaders,
1651        /// Only `Some` when created via `CREATE TABLE ... FROM WEBHOOK`.
1652        cluster_id: Option<StorageInstanceId>,
1653    },
1654}
1655
1656#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
1657pub struct WebhookValidation {
1658    /// The expression used to validate a request.
1659    pub expression: MirScalarExpr,
1660    /// Description of the source that will be created.
1661    pub relation_desc: RelationDesc,
1662    /// The column index to provide the request body and whether to provide it as bytes.
1663    pub bodies: Vec<(usize, bool)>,
1664    /// The column index to provide the request headers and whether to provide the values as bytes.
1665    pub headers: Vec<(usize, bool)>,
1666    /// Any secrets that are used in that validation.
1667    pub secrets: Vec<WebhookValidationSecret>,
1668}
1669
1670impl WebhookValidation {
1671    const MAX_REDUCE_TIME: Duration = Duration::from_secs(60);
1672
1673    /// Attempt to reduce the internal [`MirScalarExpr`] into a simpler expression.
1674    ///
1675    /// The reduction happens on a separate thread, we also only wait for
1676    /// `WebhookValidation::MAX_REDUCE_TIME` before timing out and returning an error.
1677    pub async fn reduce_expression(&mut self) -> Result<(), &'static str> {
1678        let WebhookValidation {
1679            expression,
1680            relation_desc,
1681            ..
1682        } = self;
1683
1684        // On a different thread, attempt to reduce the expression.
1685        let mut expression_ = expression.clone();
1686        let desc_ = relation_desc.clone();
1687        let reduce_task = mz_ore::task::spawn_blocking(
1688            || "webhook-validation-reduce",
1689            move || {
1690                let repr_col_types: Vec<ReprColumnType> = desc_
1691                    .typ()
1692                    .column_types
1693                    .iter()
1694                    .map(ReprColumnType::from)
1695                    .collect();
1696                expression_.reduce(&repr_col_types);
1697                expression_
1698            },
1699        );
1700
1701        match tokio::time::timeout(Self::MAX_REDUCE_TIME, reduce_task).await {
1702            Ok(reduced_expr) => {
1703                *expression = reduced_expr;
1704                Ok(())
1705            }
1706            Err(_) => Err("timeout"),
1707        }
1708    }
1709}
1710
1711#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1712pub struct WebhookHeaders {
1713    /// Optionally include a column named `headers` whose content is possibly filtered.
1714    pub header_column: Option<WebhookHeaderFilters>,
1715    /// The column index to provide the specific request header, and whether to provide it as bytes.
1716    pub mapped_headers: BTreeMap<usize, (String, bool)>,
1717}
1718
1719impl WebhookHeaders {
1720    /// Returns the number of columns needed to represent our headers.
1721    pub fn num_columns(&self) -> usize {
1722        let header_column = self.header_column.as_ref().map(|_| 1).unwrap_or(0);
1723        let mapped_headers = self.mapped_headers.len();
1724
1725        header_column + mapped_headers
1726    }
1727}
1728
1729#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1730pub struct WebhookHeaderFilters {
1731    pub block: BTreeSet<String>,
1732    pub allow: BTreeSet<String>,
1733}
1734
1735#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Arbitrary)]
1736pub enum WebhookBodyFormat {
1737    Json { array: bool },
1738    Bytes,
1739    Text,
1740}
1741
1742impl From<WebhookBodyFormat> for SqlScalarType {
1743    fn from(value: WebhookBodyFormat) -> Self {
1744        match value {
1745            WebhookBodyFormat::Json { .. } => SqlScalarType::Jsonb,
1746            WebhookBodyFormat::Bytes => SqlScalarType::Bytes,
1747            WebhookBodyFormat::Text => SqlScalarType::String,
1748        }
1749    }
1750}
1751
1752#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
1753pub struct WebhookValidationSecret {
1754    /// Identifies the secret by [`CatalogItemId`].
1755    pub id: CatalogItemId,
1756    /// Column index for the expression context that this secret was originally evaluated in.
1757    pub column_idx: usize,
1758    /// Whether or not this secret should be provided to the expression as Bytes or a String.
1759    pub use_bytes: bool,
1760}
1761
1762#[derive(Clone, Debug)]
1763pub struct Connection {
1764    pub create_sql: String,
1765    pub details: ConnectionDetails,
1766}
1767
1768#[derive(Clone, Debug, Serialize)]
1769pub enum ConnectionDetails {
1770    Kafka(KafkaConnection<ReferencedConnection>),
1771    Csr(CsrConnection<ReferencedConnection>),
1772    GlueSchemaRegistry(GlueSchemaRegistryConnection<ReferencedConnection>),
1773    Postgres(PostgresConnection<ReferencedConnection>),
1774    Ssh {
1775        connection: SshConnection,
1776        key_1: SshKey,
1777        key_2: SshKey,
1778    },
1779    Aws(AwsConnection),
1780    AwsPrivatelink(AwsPrivatelinkConnection),
1781    Gcp(GcpConnection),
1782    MySql(MySqlConnection<ReferencedConnection>),
1783    SqlServer(SqlServerConnectionDetails<ReferencedConnection>),
1784    IcebergCatalog(IcebergCatalogConnection<ReferencedConnection>),
1785}
1786
1787impl ConnectionDetails {
1788    pub fn to_connection(&self) -> mz_storage_types::connections::Connection<ReferencedConnection> {
1789        match self {
1790            ConnectionDetails::Kafka(c) => {
1791                mz_storage_types::connections::Connection::Kafka(c.clone())
1792            }
1793            ConnectionDetails::Csr(c) => mz_storage_types::connections::Connection::Csr(c.clone()),
1794            ConnectionDetails::GlueSchemaRegistry(c) => {
1795                mz_storage_types::connections::Connection::GlueSchemaRegistry(c.clone())
1796            }
1797            ConnectionDetails::Postgres(c) => {
1798                mz_storage_types::connections::Connection::Postgres(c.clone())
1799            }
1800            ConnectionDetails::Ssh { connection, .. } => {
1801                mz_storage_types::connections::Connection::Ssh(connection.clone())
1802            }
1803            ConnectionDetails::Aws(c) => mz_storage_types::connections::Connection::Aws(c.clone()),
1804            ConnectionDetails::AwsPrivatelink(c) => {
1805                mz_storage_types::connections::Connection::AwsPrivatelink(c.clone())
1806            }
1807            ConnectionDetails::Gcp(c) => mz_storage_types::connections::Connection::Gcp(c.clone()),
1808            ConnectionDetails::MySql(c) => {
1809                mz_storage_types::connections::Connection::MySql(c.clone())
1810            }
1811            ConnectionDetails::SqlServer(c) => {
1812                mz_storage_types::connections::Connection::SqlServer(c.clone())
1813            }
1814            ConnectionDetails::IcebergCatalog(c) => {
1815                mz_storage_types::connections::Connection::IcebergCatalog(c.clone())
1816            }
1817        }
1818    }
1819
1820    /// Secrets whose *contents* this connection places requirements on, paired
1821    /// with the check to apply. Callers must re-apply these checks whenever the
1822    /// connection is created or altered, and whenever the contents of one of
1823    /// the returned secrets change (e.g. `ALTER SECRET`).
1824    ///
1825    /// We rely on the caller to actually execute these checks because we don't know:
1826    /// - which secrets the caller cares about
1827    /// - which secrets require an async operation to fetch
1828    ///
1829    /// For example, the ALTER SECRET caller should only perform checks on its own secret,
1830    /// while the ALTER CONNECTION caller fetches and checks every secret from its connection.
1831    pub fn secret_content_guards(
1832        &self,
1833    ) -> Vec<(CatalogItemId, fn(&str) -> Result<(), anyhow::Error>)> {
1834        match self {
1835            // A service-account key defines its own OAuth2 token URI. We only
1836            // want to send requests to the actual Google OAuth2 token API.
1837            ConnectionDetails::Gcp(gcp) => vec![(
1838                gcp.credentials_json,
1839                GcpServiceAccountKeyTokenUri::validate_json,
1840            )],
1841            _ => vec![],
1842        }
1843    }
1844}
1845
1846/// Query policy behavior when a rule matches an admitted query plan.
1847#[derive(
1848    Debug,
1849    Default,
1850    Clone,
1851    Copy,
1852    Serialize,
1853    Deserialize,
1854    PartialEq,
1855    Eq,
1856    Ord,
1857    PartialOrd,
1858    Hash
1859)]
1860pub enum QueryPolicyMode {
1861    #[default]
1862    Warn,
1863    Enforce,
1864}
1865
1866impl std::fmt::Display for QueryPolicyMode {
1867    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1868        f.write_str(match self {
1869            Self::Warn => "warn",
1870            Self::Enforce => "enforce",
1871        })
1872    }
1873}
1874
1875/// The plan features supported by `metric = 'query_plan_includes'`.
1876#[derive(
1877    Debug,
1878    Clone,
1879    Copy,
1880    Serialize,
1881    Deserialize,
1882    PartialEq,
1883    Eq,
1884    Ord,
1885    PartialOrd,
1886    Hash
1887)]
1888pub enum QueryPlanFeature {
1889    TemporaryDataflow,
1890    StorageRead,
1891}
1892
1893impl std::fmt::Display for QueryPlanFeature {
1894    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1895        f.write_str(match self {
1896            Self::TemporaryDataflow => "temporary_dataflow",
1897            Self::StorageRead => "storage_read",
1898        })
1899    }
1900}
1901
1902/// A validated query-policy rule. Its action is reject and its metric is
1903/// query_plan_includes. Unsupported actions and metrics cannot reach admission.
1904#[derive(
1905    Debug,
1906    Clone,
1907    Serialize,
1908    Deserialize,
1909    PartialEq,
1910    Eq,
1911    Ord,
1912    PartialOrd,
1913    Hash
1914)]
1915pub struct QueryPolicyRule {
1916    pub name: String,
1917    pub value: QueryPlanFeature,
1918}
1919
1920#[derive(Debug, Clone, Serialize, PartialEq, Eq, Ord, PartialOrd, Hash)]
1921pub struct NetworkPolicyRule {
1922    pub name: String,
1923    pub action: NetworkPolicyRuleAction,
1924    pub address: PolicyAddress,
1925    pub direction: NetworkPolicyRuleDirection,
1926}
1927
1928#[derive(
1929    Debug,
1930    Clone,
1931    Serialize,
1932    Deserialize,
1933    PartialEq,
1934    Eq,
1935    Ord,
1936    PartialOrd,
1937    Hash
1938)]
1939pub enum NetworkPolicyRuleAction {
1940    Allow,
1941}
1942
1943impl std::fmt::Display for NetworkPolicyRuleAction {
1944    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1945        match self {
1946            Self::Allow => write!(f, "allow"),
1947        }
1948    }
1949}
1950impl TryFrom<&str> for NetworkPolicyRuleAction {
1951    type Error = PlanError;
1952    fn try_from(value: &str) -> Result<Self, Self::Error> {
1953        match value.to_uppercase().as_str() {
1954            "ALLOW" => Ok(Self::Allow),
1955            _ => Err(PlanError::Unstructured(
1956                "Allow is the only valid option".into(),
1957            )),
1958        }
1959    }
1960}
1961
1962#[derive(Debug, Clone, Serialize, PartialEq, Eq, Ord, PartialOrd, Hash)]
1963pub enum NetworkPolicyRuleDirection {
1964    Ingress,
1965}
1966impl std::fmt::Display for NetworkPolicyRuleDirection {
1967    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1968        match self {
1969            Self::Ingress => write!(f, "ingress"),
1970        }
1971    }
1972}
1973impl TryFrom<&str> for NetworkPolicyRuleDirection {
1974    type Error = PlanError;
1975    fn try_from(value: &str) -> Result<Self, Self::Error> {
1976        match value.to_uppercase().as_str() {
1977            "INGRESS" => Ok(Self::Ingress),
1978            _ => Err(PlanError::Unstructured(
1979                "Ingress is the only valid option".into(),
1980            )),
1981        }
1982    }
1983}
1984
1985#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
1986pub struct PolicyAddress(pub IpNet);
1987impl std::fmt::Display for PolicyAddress {
1988    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1989        write!(f, "{}", self.0)
1990    }
1991}
1992impl From<String> for PolicyAddress {
1993    fn from(value: String) -> Self {
1994        Self(IpNet::from_str(&value).expect("expected value to be IpNet"))
1995    }
1996}
1997impl TryFrom<&str> for PolicyAddress {
1998    type Error = PlanError;
1999    fn try_from(value: &str) -> Result<Self, Self::Error> {
2000        let net = IpNet::from_str(value)
2001            .map_err(|_| PlanError::Unstructured("Value must be valid IPV4 or IPV6 CIDR".into()))?;
2002        Ok(Self(net))
2003    }
2004}
2005
2006impl Serialize for PolicyAddress {
2007    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2008    where
2009        S: serde::Serializer,
2010    {
2011        serializer.serialize_str(&format!("{}", self.0))
2012    }
2013}
2014
2015#[derive(Clone, Debug, Serialize)]
2016pub enum SshKey {
2017    PublicOnly(String),
2018    Both(SshKeyPair),
2019}
2020
2021impl SshKey {
2022    pub fn as_key_pair(&self) -> Option<&SshKeyPair> {
2023        match self {
2024            SshKey::PublicOnly(_) => None,
2025            SshKey::Both(key_pair) => Some(key_pair),
2026        }
2027    }
2028
2029    pub fn public_key(&self) -> String {
2030        match self {
2031            SshKey::PublicOnly(s) => s.into(),
2032            SshKey::Both(p) => p.ssh_public_key(),
2033        }
2034    }
2035}
2036
2037#[derive(Clone, Debug)]
2038pub struct Secret {
2039    pub create_sql: String,
2040    pub secret_as: MirScalarExpr,
2041}
2042
2043#[derive(Clone, Debug)]
2044pub struct Sink {
2045    /// Parse-able SQL that is stored durably and defines this sink.
2046    pub create_sql: String,
2047    /// Collection we read into this sink.
2048    pub from: GlobalId,
2049    /// Type of connection to the external service we sink into.
2050    pub connection: StorageSinkConnection<ReferencedConnection>,
2051    // TODO(guswynn): this probably should just be in the `connection`.
2052    pub envelope: SinkEnvelope,
2053    pub version: u64,
2054    pub commit_interval: Option<Duration>,
2055}
2056
2057#[derive(Clone, Debug)]
2058pub struct View {
2059    /// Parse-able SQL that is stored durably and defines this view.
2060    pub create_sql: String,
2061    /// Unoptimized high-level expression from parsing the `create_sql`.
2062    pub expr: HirRelationExpr,
2063    /// All of the catalog objects that are referenced by this view, according to the `expr`.
2064    pub dependencies: DependencyIds,
2065    /// Columns of this view.
2066    pub column_names: Vec<ColumnName>,
2067    /// If this view is created in the temporary schema, e.g. `CREATE TEMPORARY ...`.
2068    pub temporary: bool,
2069}
2070
2071#[derive(Clone, Debug)]
2072pub struct MaterializedView {
2073    /// Parse-able SQL that is stored durably and defines this materialized view.
2074    pub create_sql: String,
2075    /// Unoptimized high-level expression from parsing the `create_sql`.
2076    pub expr: HirRelationExpr,
2077    /// All of the catalog objects that are referenced by this materialized view, according to the `expr`.
2078    pub dependencies: DependencyIds,
2079    /// Columns of this view.
2080    pub column_names: Vec<ColumnName>,
2081    pub replacement_target: Option<CatalogItemId>,
2082    /// Cluster this materialized view will get installed on.
2083    pub cluster_id: ClusterId,
2084    /// If set, only install this materialized view's dataflow on the specified replica.
2085    pub target_replica: Option<ReplicaId>,
2086    pub non_null_assertions: Vec<usize>,
2087    pub compaction_window: Option<CompactionWindow>,
2088    pub refresh_schedule: Option<RefreshSchedule>,
2089    pub as_of: Option<Timestamp>,
2090}
2091
2092#[derive(Clone, Debug)]
2093pub struct Index {
2094    /// Parse-able SQL that is stored durably and defines this index.
2095    pub create_sql: String,
2096    /// Collection this index is on top of.
2097    pub on: GlobalId,
2098    pub keys: Vec<mz_expr::MirScalarExpr>,
2099    pub compaction_window: Option<CompactionWindow>,
2100    pub cluster_id: ClusterId,
2101}
2102
2103#[derive(Clone, Debug)]
2104pub struct MetricSink {
2105    /// Parse-able SQL that defines this metric sink.
2106    pub create_sql: String,
2107    /// Collection we read into this metric sink.
2108    pub from: GlobalId,
2109    pub cluster_id: ClusterId,
2110    /// Prepended to every metric name this sink publishes, so that the families it registers
2111    /// cannot collide with another sink's or with the platform's own.
2112    pub prefix: String,
2113}
2114
2115#[derive(Clone, Debug)]
2116pub struct Type {
2117    pub create_sql: String,
2118    pub inner: CatalogType<IdReference>,
2119}
2120
2121/// Specifies when a `Peek` or `Subscribe` should occur.
2122#[derive(Deserialize, Clone, Debug, PartialEq)]
2123pub enum QueryWhen {
2124    /// The peek should occur at the latest possible timestamp that allows the
2125    /// peek to complete immediately.
2126    Immediately,
2127    /// The peek should occur at a timestamp that allows the peek to see all
2128    /// data written to tables within Materialize.
2129    FreshestTableWrite,
2130    /// The peek should occur at the timestamp described by the specified
2131    /// expression.
2132    ///
2133    /// The expression may have any type.
2134    AtTimestamp(Timestamp),
2135    /// Same as Immediately, but will also advance to at least the specified
2136    /// expression.
2137    AtLeastTimestamp(Timestamp),
2138}
2139
2140impl QueryWhen {
2141    /// Returns a timestamp to which the candidate must be advanced.
2142    pub fn advance_to_timestamp(&self) -> Option<Timestamp> {
2143        match self {
2144            QueryWhen::AtTimestamp(t) | QueryWhen::AtLeastTimestamp(t) => Some(t.clone()),
2145            QueryWhen::Immediately | QueryWhen::FreshestTableWrite => None,
2146        }
2147    }
2148    /// Returns whether the candidate's upper bound is constrained.
2149    /// This is only true for `AtTimestamp` since it is the only variant that
2150    /// specifies a timestamp.
2151    pub fn constrains_upper(&self) -> bool {
2152        match self {
2153            QueryWhen::AtTimestamp(_) => true,
2154            QueryWhen::AtLeastTimestamp(_)
2155            | QueryWhen::Immediately
2156            | QueryWhen::FreshestTableWrite => false,
2157        }
2158    }
2159    /// Returns whether the candidate must be advanced to the since.
2160    pub fn advance_to_since(&self) -> bool {
2161        match self {
2162            QueryWhen::Immediately
2163            | QueryWhen::AtLeastTimestamp(_)
2164            | QueryWhen::FreshestTableWrite => true,
2165            QueryWhen::AtTimestamp(_) => false,
2166        }
2167    }
2168    /// Returns whether the candidate can be advanced to the upper.
2169    pub fn can_advance_to_upper(&self) -> bool {
2170        match self {
2171            QueryWhen::Immediately => true,
2172            QueryWhen::FreshestTableWrite
2173            | QueryWhen::AtTimestamp(_)
2174            | QueryWhen::AtLeastTimestamp(_) => false,
2175        }
2176    }
2177
2178    /// Returns whether the candidate can be advanced to the timeline's timestamp.
2179    pub fn can_advance_to_timeline_ts(&self) -> bool {
2180        match self {
2181            QueryWhen::Immediately | QueryWhen::FreshestTableWrite => true,
2182            QueryWhen::AtTimestamp(_) | QueryWhen::AtLeastTimestamp(_) => false,
2183        }
2184    }
2185    /// Returns whether the candidate must be advanced to the timeline's timestamp.
2186    pub fn must_advance_to_timeline_ts(&self) -> bool {
2187        match self {
2188            QueryWhen::FreshestTableWrite => true,
2189            QueryWhen::Immediately | QueryWhen::AtLeastTimestamp(_) | QueryWhen::AtTimestamp(_) => {
2190                false
2191            }
2192        }
2193    }
2194    /// Returns whether the selected timestamp should be tracked within the current transaction.
2195    pub fn is_transactional(&self) -> bool {
2196        match self {
2197            QueryWhen::Immediately | QueryWhen::FreshestTableWrite => true,
2198            QueryWhen::AtLeastTimestamp(_) | QueryWhen::AtTimestamp(_) => false,
2199        }
2200    }
2201}
2202
2203#[derive(Debug, Copy, Clone)]
2204pub enum MutationKind {
2205    Insert,
2206    Update,
2207    Delete,
2208}
2209
2210#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
2211pub enum CopyFormat {
2212    Text,
2213    Csv,
2214    Binary,
2215    Parquet,
2216}
2217
2218#[derive(Debug, Copy, Clone)]
2219pub enum ExecuteTimeout {
2220    None,
2221    Seconds(f64),
2222    WaitOnce,
2223}
2224
2225#[derive(Clone, Debug)]
2226pub enum IndexOption {
2227    /// Configures the logical compaction window for an index.
2228    RetainHistory(CompactionWindow),
2229}
2230
2231#[derive(Clone, Debug)]
2232pub enum TableOption {
2233    /// Configures the logical compaction window for a table.
2234    RetainHistory(CompactionWindow),
2235}
2236
2237#[derive(Clone, Debug)]
2238pub struct PlanClusterOption {
2239    pub availability_zones: AlterOptionParameter<Vec<String>>,
2240    pub introspection_debugging: AlterOptionParameter<bool>,
2241    pub introspection_interval: AlterOptionParameter<OptionalDuration>,
2242    pub arrangement_compression: AlterOptionParameter<bool>,
2243    pub managed: AlterOptionParameter<bool>,
2244    pub replicas: AlterOptionParameter<Vec<(String, ReplicaConfig)>>,
2245    pub replication_factor: AlterOptionParameter<u32>,
2246    pub size: AlterOptionParameter,
2247    pub schedule: AlterOptionParameter<ClusterSchedule>,
2248    pub workload_class: AlterOptionParameter<Option<String>>,
2249    /// The autoscaling policy block. `Set(None)` disables autoscaling (an empty
2250    /// `AUTO SCALING STRATEGY = ()` or `RESET (AUTO SCALING STRATEGY)`).
2251    pub auto_scaling_strategy: AlterOptionParameter<Option<AutoScalingStrategy>>,
2252    pub query_policy: AlterOptionParameter<Option<QueryPolicyId>>,
2253}
2254
2255impl Default for PlanClusterOption {
2256    fn default() -> Self {
2257        Self {
2258            availability_zones: AlterOptionParameter::Unchanged,
2259            introspection_debugging: AlterOptionParameter::Unchanged,
2260            introspection_interval: AlterOptionParameter::Unchanged,
2261            arrangement_compression: AlterOptionParameter::Unchanged,
2262            managed: AlterOptionParameter::Unchanged,
2263            replicas: AlterOptionParameter::Unchanged,
2264            replication_factor: AlterOptionParameter::Unchanged,
2265            size: AlterOptionParameter::Unchanged,
2266            schedule: AlterOptionParameter::Unchanged,
2267            workload_class: AlterOptionParameter::Unchanged,
2268            auto_scaling_strategy: AlterOptionParameter::Unchanged,
2269            query_policy: AlterOptionParameter::Unchanged,
2270        }
2271    }
2272}
2273
2274#[derive(Clone, Debug, PartialEq, Eq)]
2275pub enum AlterClusterPlanStrategy {
2276    None,
2277    For(Duration),
2278    UntilReady {
2279        /// `None` when the `ALTER` omits `ON TIMEOUT`. The executing path
2280        /// supplies the implicit action.
2281        on_timeout: Option<OnTimeoutAction>,
2282        timeout: Duration,
2283    },
2284}
2285
2286#[derive(
2287    Clone,
2288    Copy,
2289    Debug,
2290    Deserialize,
2291    Serialize,
2292    PartialOrd,
2293    PartialEq,
2294    Eq,
2295    Ord
2296)]
2297pub enum OnTimeoutAction {
2298    /// Cut over to the target shape even though it has not hydrated.
2299    Commit,
2300    /// Drop the target replicas and keep the pre-reconfiguration set.
2301    Rollback,
2302}
2303
2304impl TryFrom<&str> for OnTimeoutAction {
2305    type Error = PlanError;
2306    fn try_from(value: &str) -> Result<Self, Self::Error> {
2307        match value.to_uppercase().as_str() {
2308            "COMMIT" => Ok(Self::Commit),
2309            "ROLLBACK" => Ok(Self::Rollback),
2310            _ => Err(PlanError::Unstructured(
2311                "Valid options are COMMIT, ROLLBACK".into(),
2312            )),
2313        }
2314    }
2315}
2316
2317impl AlterClusterPlanStrategy {
2318    pub fn is_none(&self) -> bool {
2319        matches!(self, Self::None)
2320    }
2321    pub fn is_some(&self) -> bool {
2322        !matches!(self, Self::None)
2323    }
2324}
2325
2326impl TryFrom<ClusterAlterOptionExtracted> for AlterClusterPlanStrategy {
2327    type Error = PlanError;
2328
2329    fn try_from(value: ClusterAlterOptionExtracted) -> Result<Self, Self::Error> {
2330        Ok(match value.wait {
2331            Some(ClusterAlterOptionValue::For(d)) => Self::For(Duration::try_from_value(d)?),
2332            Some(ClusterAlterOptionValue::UntilReady(options)) => {
2333                let extracted = ClusterAlterUntilReadyOptionExtracted::try_from(options)?;
2334                Self::UntilReady {
2335                    timeout: match extracted.timeout {
2336                        Some(d) => d,
2337                        None => Err(PlanError::UntilReadyTimeoutRequired)?,
2338                    },
2339                    on_timeout: match extracted.on_timeout {
2340                        Some(v) => Some(OnTimeoutAction::try_from(v.as_str()).map_err(|e| {
2341                            PlanError::InvalidOptionValue {
2342                                option_name: "ON TIMEOUT".into(),
2343                                err: Box::new(e),
2344                            }
2345                        })?),
2346                        None => None,
2347                    },
2348                }
2349            }
2350            None => Self::None,
2351        })
2352    }
2353}
2354
2355/// A vector of values to which parameter references should be bound.
2356#[derive(Debug, Clone)]
2357pub struct Params {
2358    /// The datums that were provided in the EXECUTE statement.
2359    pub datums: Row,
2360    /// The types of the datums provided in the EXECUTE statement.
2361    pub execute_types: Vec<SqlScalarType>,
2362    /// The types that the prepared statement expects based on its definition.
2363    pub expected_types: Vec<SqlScalarType>,
2364}
2365
2366impl Params {
2367    /// Returns a `Params` with no parameters.
2368    pub fn empty() -> Params {
2369        Params {
2370            datums: Row::pack_slice(&[]),
2371            execute_types: vec![],
2372            expected_types: vec![],
2373        }
2374    }
2375}
2376
2377/// Controls planning of a SQL query.
2378#[derive(
2379    Ord,
2380    PartialOrd,
2381    Clone,
2382    Debug,
2383    Eq,
2384    PartialEq,
2385    Serialize,
2386    Deserialize,
2387    Hash,
2388    Copy
2389)]
2390pub struct PlanContext {
2391    pub wall_time: DateTime<Utc>,
2392    pub ignore_if_exists_errors: bool,
2393}
2394
2395impl PlanContext {
2396    pub fn new(wall_time: DateTime<Utc>) -> Self {
2397        Self {
2398            wall_time,
2399            ignore_if_exists_errors: false,
2400        }
2401    }
2402
2403    /// Return a PlanContext with zero values. This should only be used when
2404    /// planning is required but unused (like in `plan_create_table()`) or in
2405    /// tests.
2406    pub fn zero() -> Self {
2407        PlanContext {
2408            wall_time: now::to_datetime(NOW_ZERO()),
2409            ignore_if_exists_errors: false,
2410        }
2411    }
2412
2413    pub fn with_ignore_if_exists_errors(mut self, value: bool) -> Self {
2414        self.ignore_if_exists_errors = value;
2415        self
2416    }
2417}