Skip to main content

mz_catalog/memory/
objects.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//! The current types used by the in-memory Catalog. Many of the objects in this module are
11//! extremely similar to the objects found in [`crate::durable::objects`] but in a format that is
12//! easier consumed by higher layers.
13
14use std::borrow::Cow;
15use std::collections::{BTreeMap, BTreeSet};
16use std::ops::{Deref, DerefMut};
17use std::sync::{Arc, LazyLock};
18use std::time::Duration;
19
20use chrono::{DateTime, Utc};
21use mz_adapter_types::compaction::CompactionWindow;
22use mz_adapter_types::connection::ConnectionId;
23use mz_compute_client::logging::LogVariant;
24use mz_compute_types::dataflows::{DataflowDescription, LirDataflowDescription};
25use mz_controller::clusters::{ClusterRole, ClusterStatus, ReplicaConfig, ReplicaLogging};
26use mz_controller_types::{ClusterId, ReplicaId};
27use mz_expr::{MirScalarExpr, OptimizedMirRelationExpr};
28use mz_ore::collections::CollectionExt;
29use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem, PrivilegeMap};
30use mz_repr::network_policy_id::NetworkPolicyId;
31use mz_repr::optimize::OptimizerFeatureOverrides;
32use mz_repr::query_policy_id::QueryPolicyId;
33use mz_repr::refresh_schedule::RefreshSchedule;
34use mz_repr::role_id::RoleId;
35use mz_repr::{
36    CatalogItemId, ColumnName, Diff, GlobalId, RelationDesc, RelationVersion,
37    RelationVersionSelector, SqlColumnType, Timestamp, VersionedRelationDesc,
38};
39use mz_sql::ast::display::AstDisplay;
40use mz_sql::ast::{
41    ColumnDef, ColumnOption, ColumnOptionDef, ColumnVersioned, Expr, Raw, RawDataType, Statement,
42    UnresolvedItemName, Value, WithOptionValue,
43};
44use mz_sql::catalog::{
45    CatalogClusterReplica, CatalogError as SqlCatalogError, CatalogItem as SqlCatalogItem,
46    CatalogItemType as SqlCatalogItemType, CatalogItemType, CatalogSchema, CatalogType,
47    CatalogTypeDetails, DefaultPrivilegeAclItem, DefaultPrivilegeObject, IdReference,
48    RoleAttributes, RoleMembership, RoleVars, SystemObjectType,
49};
50use mz_sql::names::{
51    Aug, CommentObjectId, DatabaseId, DependencyIds, FullItemName, QualifiedItemName,
52    QualifiedSchemaName, ResolvedDatabaseSpecifier, ResolvedIds, SchemaId, SchemaSpecifier,
53};
54use mz_sql::plan::{
55    AutoScalingStrategy, ClusterSchedule, ComputeReplicaConfig, ComputeReplicaIntrospectionConfig,
56    ConnectionDetails, CreateClusterManagedPlan, CreateClusterPlan, CreateClusterVariant,
57    CreateSourcePlan, HirRelationExpr, NetworkPolicyRule, OnTimeoutAction, PlanError,
58    QueryPolicyMode, QueryPolicyRule, WebhookBodyFormat, WebhookHeaders, WebhookValidation,
59};
60use mz_sql::rbac;
61use mz_sql::session::vars::OwnedVarInput;
62use mz_storage_client::controller::IntrospectionType;
63use mz_storage_types::connections::inline::ReferencedConnection;
64use mz_storage_types::sinks::{SinkEnvelope, StorageSinkConnection};
65use mz_storage_types::sources::load_generator::LoadGenerator;
66use mz_storage_types::sources::{
67    GenericSourceConnection, SourceConnection, SourceDesc, SourceEnvelope, SourceExportDataConfig,
68    SourceExportDetails, Timeline,
69};
70use mz_transform::dataflow::DataflowMetainfo;
71use mz_transform::notice::OptimizerNotice;
72use serde::ser::SerializeSeq;
73use serde::{Deserialize, Serialize};
74use timely::progress::Antichain;
75use tracing::debug;
76
77use crate::builtin::{MZ_CATALOG_SERVER_CLUSTER, MZ_SYSTEM_CLUSTER};
78use crate::durable;
79
80/// Used to update `self` from the input value while consuming the input value.
81pub trait UpdateFrom<T>: From<T> {
82    fn update_from(&mut self, from: T);
83}
84
85#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
86pub struct Database {
87    pub name: String,
88    pub id: DatabaseId,
89    pub oid: u32,
90    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
91    pub schemas_by_id: BTreeMap<SchemaId, Schema>,
92    pub schemas_by_name: BTreeMap<String, SchemaId>,
93    pub owner_id: RoleId,
94    pub privileges: PrivilegeMap,
95}
96
97impl From<Database> for durable::Database {
98    fn from(database: Database) -> durable::Database {
99        durable::Database {
100            id: database.id,
101            oid: database.oid,
102            name: database.name,
103            owner_id: database.owner_id,
104            privileges: database.privileges.into_all_values().collect(),
105        }
106    }
107}
108
109impl From<durable::Database> for Database {
110    fn from(
111        durable::Database {
112            id,
113            oid,
114            name,
115            owner_id,
116            privileges,
117        }: durable::Database,
118    ) -> Database {
119        Database {
120            id,
121            oid,
122            schemas_by_id: BTreeMap::new(),
123            schemas_by_name: BTreeMap::new(),
124            name,
125            owner_id,
126            privileges: PrivilegeMap::from_mz_acl_items(privileges),
127        }
128    }
129}
130
131impl UpdateFrom<durable::Database> for Database {
132    fn update_from(
133        &mut self,
134        durable::Database {
135            id,
136            oid,
137            name,
138            owner_id,
139            privileges,
140        }: durable::Database,
141    ) {
142        self.id = id;
143        self.oid = oid;
144        self.name = name;
145        self.owner_id = owner_id;
146        self.privileges = PrivilegeMap::from_mz_acl_items(privileges);
147    }
148}
149
150#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
151pub struct Schema {
152    pub name: QualifiedSchemaName,
153    pub id: SchemaSpecifier,
154    pub oid: u32,
155    pub items: BTreeMap<String, CatalogItemId>,
156    pub functions: BTreeMap<String, CatalogItemId>,
157    pub types: BTreeMap<String, CatalogItemId>,
158    pub owner_id: RoleId,
159    pub privileges: PrivilegeMap,
160}
161
162impl From<Schema> for durable::Schema {
163    fn from(schema: Schema) -> durable::Schema {
164        durable::Schema {
165            id: schema.id.into(),
166            oid: schema.oid,
167            name: schema.name.schema,
168            database_id: schema.name.database.id(),
169            owner_id: schema.owner_id,
170            privileges: schema.privileges.into_all_values().collect(),
171        }
172    }
173}
174
175impl From<durable::Schema> for Schema {
176    fn from(
177        durable::Schema {
178            id,
179            oid,
180            name,
181            database_id,
182            owner_id,
183            privileges,
184        }: durable::Schema,
185    ) -> Schema {
186        Schema {
187            name: QualifiedSchemaName {
188                database: database_id.into(),
189                schema: name,
190            },
191            id: id.into(),
192            oid,
193            items: BTreeMap::new(),
194            functions: BTreeMap::new(),
195            types: BTreeMap::new(),
196            owner_id,
197            privileges: PrivilegeMap::from_mz_acl_items(privileges),
198        }
199    }
200}
201
202impl UpdateFrom<durable::Schema> for Schema {
203    fn update_from(
204        &mut self,
205        durable::Schema {
206            id,
207            oid,
208            name,
209            database_id,
210            owner_id,
211            privileges,
212        }: durable::Schema,
213    ) {
214        self.name = QualifiedSchemaName {
215            database: database_id.into(),
216            schema: name,
217        };
218        self.id = id.into();
219        self.oid = oid;
220        self.owner_id = owner_id;
221        self.privileges = PrivilegeMap::from_mz_acl_items(privileges);
222    }
223}
224
225#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
226pub struct Role {
227    pub name: String,
228    pub id: RoleId,
229    pub oid: u32,
230    pub attributes: RoleAttributes,
231    pub membership: RoleMembership,
232    pub vars: RoleVars,
233}
234
235impl Role {
236    pub fn is_user(&self) -> bool {
237        self.id.is_user()
238    }
239
240    pub fn vars<'a>(&'a self) -> impl Iterator<Item = (&'a str, &'a OwnedVarInput)> {
241        self.vars.map.iter().map(|(name, val)| (name.as_str(), val))
242    }
243}
244
245impl From<Role> for durable::Role {
246    fn from(role: Role) -> durable::Role {
247        durable::Role {
248            id: role.id,
249            oid: role.oid,
250            name: role.name,
251            attributes: role.attributes,
252            membership: role.membership,
253            vars: role.vars,
254        }
255    }
256}
257
258impl From<durable::Role> for Role {
259    fn from(
260        durable::Role {
261            id,
262            oid,
263            name,
264            attributes,
265            membership,
266            vars,
267        }: durable::Role,
268    ) -> Self {
269        Role {
270            name,
271            id,
272            oid,
273            attributes,
274            membership,
275            vars,
276        }
277    }
278}
279
280impl UpdateFrom<durable::Role> for Role {
281    fn update_from(
282        &mut self,
283        durable::Role {
284            id,
285            oid,
286            name,
287            attributes,
288            membership,
289            vars,
290        }: durable::Role,
291    ) {
292        self.id = id;
293        self.oid = oid;
294        self.name = name;
295        self.attributes = attributes;
296        self.membership = membership;
297        self.vars = vars;
298    }
299}
300
301#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
302pub struct RoleAuth {
303    pub role_id: RoleId,
304    pub password_hash: Option<String>,
305    pub updated_at: u64,
306}
307
308impl From<RoleAuth> for durable::RoleAuth {
309    fn from(role_auth: RoleAuth) -> durable::RoleAuth {
310        durable::RoleAuth {
311            role_id: role_auth.role_id,
312            password_hash: role_auth.password_hash,
313            updated_at: role_auth.updated_at,
314        }
315    }
316}
317
318impl From<durable::RoleAuth> for RoleAuth {
319    fn from(
320        durable::RoleAuth {
321            role_id,
322            password_hash,
323            updated_at,
324        }: durable::RoleAuth,
325    ) -> RoleAuth {
326        RoleAuth {
327            role_id,
328            password_hash,
329            updated_at,
330        }
331    }
332}
333
334impl UpdateFrom<durable::RoleAuth> for RoleAuth {
335    fn update_from(&mut self, from: durable::RoleAuth) {
336        self.role_id = from.role_id;
337        self.password_hash = from.password_hash;
338        self.updated_at = from.updated_at;
339    }
340}
341
342#[derive(Debug, Serialize, Clone, PartialEq)]
343pub struct Cluster {
344    pub name: String,
345    pub id: ClusterId,
346    pub config: ClusterConfig,
347    #[serde(skip)]
348    pub log_indexes: BTreeMap<LogVariant, GlobalId>,
349    /// Objects bound to this cluster. Does not include introspection source
350    /// indexes.
351    pub bound_objects: BTreeSet<CatalogItemId>,
352    pub replica_id_by_name_: BTreeMap<String, ReplicaId>,
353    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
354    pub replicas_by_id_: BTreeMap<ReplicaId, ClusterReplica>,
355    pub owner_id: RoleId,
356    pub privileges: PrivilegeMap,
357}
358
359impl Cluster {
360    /// The role of the cluster. Currently used to set alert severity.
361    pub fn role(&self) -> ClusterRole {
362        // NOTE - These roles power monitoring systems. Do not change
363        // them without talking to the cloud or observability groups.
364        if self.name == MZ_SYSTEM_CLUSTER.name {
365            ClusterRole::SystemCritical
366        } else if self.name == MZ_CATALOG_SERVER_CLUSTER.name {
367            ClusterRole::System
368        } else {
369            ClusterRole::User
370        }
371    }
372
373    /// Returns `true` if the cluster is a managed cluster.
374    pub fn is_managed(&self) -> bool {
375        matches!(self.config.variant, ClusterVariant::Managed { .. })
376    }
377
378    /// Lists the user replicas, which are those that do not have the internal flag set.
379    pub fn user_replicas(&self) -> impl Iterator<Item = &ClusterReplica> {
380        self.replicas().filter(|r| !r.config.location.internal())
381    }
382
383    /// Lists all replicas in the cluster
384    pub fn replicas(&self) -> impl Iterator<Item = &ClusterReplica> {
385        self.replicas_by_id_.values()
386    }
387
388    /// Lookup a replica by ID.
389    pub fn replica(&self, replica_id: ReplicaId) -> Option<&ClusterReplica> {
390        self.replicas_by_id_.get(&replica_id)
391    }
392
393    /// Lookup a replica ID by name.
394    pub fn replica_id(&self, name: &str) -> Option<ReplicaId> {
395        self.replica_id_by_name_.get(name).copied()
396    }
397
398    /// Returns the availability zones of this cluster, if they exist.
399    pub fn availability_zones(&self) -> Option<&[String]> {
400        match &self.config.variant {
401            ClusterVariant::Managed(managed) => Some(&managed.availability_zones),
402            ClusterVariant::Unmanaged => None,
403        }
404    }
405
406    /// Builds the plan that a `CREATE CLUSTER` statement for this cluster would
407    /// have produced.
408    ///
409    /// Clusters are stored as a structured config, not as SQL text, so `SHOW
410    /// CREATE CLUSTER` cannot just print a stored statement. It rebuilds one,
411    /// and this is the first half of that: config to plan. `unplan_create_cluster`
412    /// then turns the plan back into a statement.
413    pub fn try_to_plan(&self) -> Result<CreateClusterPlan, PlanError> {
414        let name = self.name.clone();
415        let variant = match &self.config.variant {
416            ClusterVariant::Managed(ClusterVariantManaged {
417                size,
418                availability_zones,
419                logging,
420                arrangement_compression,
421                replication_factor,
422                optimizer_feature_overrides,
423                schedule,
424                auto_scaling_strategy,
425                // In-flight runtime records, controller-managed and not part of
426                // the create statement.
427                reconfiguration: _,
428                burst: _,
429            }) => {
430                let introspection = match logging {
431                    ReplicaLogging {
432                        log_logging,
433                        interval: Some(interval),
434                    } => Some(ComputeReplicaIntrospectionConfig {
435                        debugging: *log_logging,
436                        interval: interval.clone(),
437                    }),
438                    ReplicaLogging {
439                        log_logging: _,
440                        interval: None,
441                    } => None,
442                };
443                let compute = ComputeReplicaConfig {
444                    introspection,
445                    arrangement_compression: *arrangement_compression,
446                };
447                CreateClusterVariant::Managed(CreateClusterManagedPlan {
448                    replication_factor: replication_factor.clone(),
449                    size: size.clone(),
450                    availability_zones: availability_zones.clone(),
451                    compute,
452                    optimizer_feature_overrides: optimizer_feature_overrides.clone(),
453                    schedule: schedule.clone(),
454                    auto_scaling_strategy: auto_scaling_strategy.clone(),
455                })
456            }
457            ClusterVariant::Unmanaged => {
458                // Unmanaged clusters are deprecated, so hopefully we can remove
459                // them before we have to implement this.
460                return Err(PlanError::Unsupported {
461                    feature: "SHOW CREATE for unmanaged clusters".to_string(),
462                    discussion_no: None,
463                });
464            }
465        };
466        let workload_class = self.config.workload_class.clone();
467        Ok(CreateClusterPlan {
468            name,
469            variant,
470            workload_class,
471            query_policy: self.config.query_policy,
472            // Nothing about `IF NOT EXISTS` is stored. It only ever affected how
473            // the original statement handled a name collision, so the rebuilt
474            // statement never shows it.
475            if_not_exists: false,
476        })
477    }
478}
479
480impl From<Cluster> for durable::Cluster {
481    fn from(cluster: Cluster) -> durable::Cluster {
482        durable::Cluster {
483            id: cluster.id,
484            name: cluster.name,
485            owner_id: cluster.owner_id,
486            privileges: cluster.privileges.into_all_values().collect(),
487            config: cluster.config.into(),
488        }
489    }
490}
491
492impl From<durable::Cluster> for Cluster {
493    fn from(
494        durable::Cluster {
495            id,
496            name,
497            owner_id,
498            privileges,
499            config,
500        }: durable::Cluster,
501    ) -> Self {
502        Cluster {
503            name: name.clone(),
504            id,
505            bound_objects: BTreeSet::new(),
506            log_indexes: BTreeMap::new(),
507            replica_id_by_name_: BTreeMap::new(),
508            replicas_by_id_: BTreeMap::new(),
509            owner_id,
510            privileges: PrivilegeMap::from_mz_acl_items(privileges),
511            config: config.into(),
512        }
513    }
514}
515
516impl UpdateFrom<durable::Cluster> for Cluster {
517    fn update_from(
518        &mut self,
519        durable::Cluster {
520            id,
521            name,
522            owner_id,
523            privileges,
524            config,
525        }: durable::Cluster,
526    ) {
527        self.id = id;
528        self.name = name;
529        self.owner_id = owner_id;
530        self.privileges = PrivilegeMap::from_mz_acl_items(privileges);
531        self.config = config.into();
532    }
533}
534
535#[derive(Debug, Serialize, Clone, PartialEq)]
536pub struct ClusterReplica {
537    pub name: String,
538    pub cluster_id: ClusterId,
539    pub replica_id: ReplicaId,
540    pub config: ReplicaConfig,
541    pub owner_id: RoleId,
542}
543
544impl From<ClusterReplica> for durable::ClusterReplica {
545    fn from(replica: ClusterReplica) -> durable::ClusterReplica {
546        durable::ClusterReplica {
547            cluster_id: replica.cluster_id,
548            replica_id: replica.replica_id,
549            name: replica.name,
550            config: replica.config.into(),
551            owner_id: replica.owner_id,
552        }
553    }
554}
555
556#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
557pub struct ClusterReplicaProcessStatus {
558    pub status: ClusterStatus,
559    /// Cumulative restart count of the process, mirrored from the orchestrator.
560    /// See [`mz_orchestrator::ServiceEvent::restart_count`].
561    pub restart_count: u64,
562    /// Time of the most recent change to `status` or `restart_count`.
563    pub time: DateTime<Utc>,
564}
565
566#[derive(Debug, Serialize, Clone, PartialEq)]
567pub struct SourceReferences {
568    pub updated_at: u64,
569    pub references: Vec<SourceReference>,
570}
571
572#[derive(Debug, Serialize, Clone, PartialEq)]
573pub struct SourceReference {
574    pub name: String,
575    pub namespace: Option<String>,
576    pub columns: Vec<String>,
577}
578
579impl From<SourceReference> for durable::SourceReference {
580    fn from(source_reference: SourceReference) -> durable::SourceReference {
581        durable::SourceReference {
582            name: source_reference.name,
583            namespace: source_reference.namespace,
584            columns: source_reference.columns,
585        }
586    }
587}
588
589impl SourceReferences {
590    pub fn to_durable(self, source_id: CatalogItemId) -> durable::SourceReferences {
591        durable::SourceReferences {
592            source_id,
593            updated_at: self.updated_at,
594            references: self.references.into_iter().map(Into::into).collect(),
595        }
596    }
597}
598
599impl From<durable::SourceReference> for SourceReference {
600    fn from(source_reference: durable::SourceReference) -> SourceReference {
601        SourceReference {
602            name: source_reference.name,
603            namespace: source_reference.namespace,
604            columns: source_reference.columns,
605        }
606    }
607}
608
609impl From<durable::SourceReferences> for SourceReferences {
610    fn from(source_references: durable::SourceReferences) -> SourceReferences {
611        SourceReferences {
612            updated_at: source_references.updated_at,
613            references: source_references
614                .references
615                .into_iter()
616                .map(|source_reference| source_reference.into())
617                .collect(),
618        }
619    }
620}
621
622impl From<mz_sql::plan::SourceReference> for SourceReference {
623    fn from(source_reference: mz_sql::plan::SourceReference) -> SourceReference {
624        SourceReference {
625            name: source_reference.name,
626            namespace: source_reference.namespace,
627            columns: source_reference.columns,
628        }
629    }
630}
631
632impl From<mz_sql::plan::SourceReferences> for SourceReferences {
633    fn from(source_references: mz_sql::plan::SourceReferences) -> SourceReferences {
634        SourceReferences {
635            updated_at: source_references.updated_at,
636            references: source_references
637                .references
638                .into_iter()
639                .map(|source_reference| source_reference.into())
640                .collect(),
641        }
642    }
643}
644
645impl From<SourceReferences> for mz_sql::plan::SourceReferences {
646    fn from(source_references: SourceReferences) -> mz_sql::plan::SourceReferences {
647        mz_sql::plan::SourceReferences {
648            updated_at: source_references.updated_at,
649            references: source_references
650                .references
651                .into_iter()
652                .map(|source_reference| source_reference.into())
653                .collect(),
654        }
655    }
656}
657
658impl From<SourceReference> for mz_sql::plan::SourceReference {
659    fn from(source_reference: SourceReference) -> mz_sql::plan::SourceReference {
660        mz_sql::plan::SourceReference {
661            name: source_reference.name,
662            namespace: source_reference.namespace,
663            columns: source_reference.columns,
664        }
665    }
666}
667
668#[derive(Clone, Debug, Serialize)]
669pub struct CatalogEntry {
670    pub item: CatalogItem,
671    #[serde(skip)]
672    pub referenced_by: Vec<CatalogItemId>,
673    // TODO(database-issues#7922)––this should have an invariant tied to it that all
674    // dependents (i.e. entries in this field) have IDs greater than this
675    // entry's ID.
676    #[serde(skip)]
677    pub used_by: Vec<CatalogItemId>,
678    pub id: CatalogItemId,
679    pub oid: u32,
680    pub name: QualifiedItemName,
681    pub owner_id: RoleId,
682    pub privileges: PrivilegeMap,
683}
684
685/// A [`CatalogEntry`] that is associated with a specific "collection" of data.
686/// A single item in the catalog may be associated with multiple "collections".
687///
688/// Here "collection" generally means a pTVC, e.g. a Persist Shard, an Index, a
689/// currently running dataflow, etc.
690///
691/// Items in the Catalog have a stable name -> ID mapping, in other words for
692/// the entire lifetime of an object its [`CatalogItemId`] will _never_ change.
693/// Similarly, we need to maintain a stable mapping from [`GlobalId`] to pTVC.
694/// This presents a challenge when `ALTER`-ing an object, e.g. adding columns
695/// to a table. We can't just change the schema of the underlying Persist Shard
696/// because that would be rebinding the [`GlobalId`] of the pTVC. Instead we
697/// allocate a new [`GlobalId`] to refer to the new version of the table, and
698/// then the [`CatalogEntry`] tracks the [`GlobalId`] for each version.
699#[derive(Clone, Debug)]
700pub struct CatalogCollectionEntry {
701    pub entry: CatalogEntry,
702    pub version: RelationVersionSelector,
703}
704
705impl CatalogCollectionEntry {
706    pub fn relation_desc(&self) -> Option<Cow<'_, RelationDesc>> {
707        self.item().relation_desc(self.version)
708    }
709}
710
711impl mz_sql::catalog::CatalogCollectionItem for CatalogCollectionEntry {
712    fn relation_desc(&self) -> Option<Cow<'_, RelationDesc>> {
713        self.item().relation_desc(self.version)
714    }
715
716    fn global_id(&self) -> GlobalId {
717        self.entry
718            .item()
719            .global_id_for_version(self.version)
720            .expect("catalog corruption, missing version!")
721    }
722}
723
724impl Deref for CatalogCollectionEntry {
725    type Target = CatalogEntry;
726
727    fn deref(&self) -> &CatalogEntry {
728        &self.entry
729    }
730}
731
732impl mz_sql::catalog::CatalogItem for CatalogCollectionEntry {
733    fn name(&self) -> &QualifiedItemName {
734        self.entry.name()
735    }
736
737    fn id(&self) -> CatalogItemId {
738        self.entry.id()
739    }
740
741    fn global_ids(&self) -> Box<dyn Iterator<Item = GlobalId> + '_> {
742        Box::new(self.entry.global_ids())
743    }
744
745    fn oid(&self) -> u32 {
746        self.entry.oid()
747    }
748
749    fn func(&self) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
750        self.entry.func()
751    }
752
753    fn source_desc(&self) -> Result<Option<&SourceDesc<ReferencedConnection>>, SqlCatalogError> {
754        self.entry.source_desc()
755    }
756
757    fn connection(
758        &self,
759    ) -> Result<mz_storage_types::connections::Connection<ReferencedConnection>, SqlCatalogError>
760    {
761        mz_sql::catalog::CatalogItem::connection(&self.entry)
762    }
763
764    fn create_sql(&self) -> &str {
765        self.entry.create_sql()
766    }
767
768    fn item_type(&self) -> SqlCatalogItemType {
769        self.entry.item_type()
770    }
771
772    fn index_details(&self) -> Option<(&[MirScalarExpr], GlobalId)> {
773        self.entry.index_details()
774    }
775
776    fn writable_table_details(&self) -> Option<&[Expr<Aug>]> {
777        self.entry.writable_table_details()
778    }
779
780    fn replacement_target(&self) -> Option<CatalogItemId> {
781        self.entry.replacement_target()
782    }
783
784    fn type_details(&self) -> Option<&CatalogTypeDetails<IdReference>> {
785        self.entry.type_details()
786    }
787
788    fn references(&self) -> &ResolvedIds {
789        self.entry.references()
790    }
791
792    fn uses(&self) -> BTreeSet<CatalogItemId> {
793        self.entry.uses()
794    }
795
796    fn referenced_by(&self) -> &[CatalogItemId] {
797        self.entry.referenced_by()
798    }
799
800    fn used_by(&self) -> &[CatalogItemId] {
801        self.entry.used_by()
802    }
803
804    fn subsource_details(
805        &self,
806    ) -> Option<(CatalogItemId, &UnresolvedItemName, &SourceExportDetails)> {
807        self.entry.subsource_details()
808    }
809
810    fn source_export_details(
811        &self,
812    ) -> Option<(
813        CatalogItemId,
814        &UnresolvedItemName,
815        &SourceExportDetails,
816        &SourceExportDataConfig<ReferencedConnection>,
817    )> {
818        self.entry.source_export_details()
819    }
820
821    fn is_progress_source(&self) -> bool {
822        self.entry.is_progress_source()
823    }
824
825    fn progress_id(&self) -> Option<CatalogItemId> {
826        self.entry.progress_id()
827    }
828
829    fn owner_id(&self) -> RoleId {
830        *self.entry.owner_id()
831    }
832
833    fn privileges(&self) -> &PrivilegeMap {
834        self.entry.privileges()
835    }
836
837    fn cluster_id(&self) -> Option<ClusterId> {
838        self.entry.item().cluster_id()
839    }
840
841    fn at_version(
842        &self,
843        version: RelationVersionSelector,
844    ) -> Box<dyn mz_sql::catalog::CatalogCollectionItem> {
845        Box::new(CatalogCollectionEntry {
846            entry: self.entry.clone(),
847            version,
848        })
849    }
850
851    fn latest_version(&self) -> Option<RelationVersion> {
852        self.entry.latest_version()
853    }
854}
855
856#[derive(Debug, Clone, Serialize)]
857pub enum CatalogItem {
858    Table(Table),
859    Source(Source),
860    Log(Log),
861    View(View),
862    MaterializedView(MaterializedView),
863    Sink(Sink),
864    Index(Index),
865    Type(Type),
866    Func(Func),
867    Secret(Secret),
868    Connection(Connection),
869    MetricSink(MetricSink),
870}
871
872#[derive(Debug, Clone, Serialize)]
873pub struct Table {
874    /// Parse-able SQL that defines this table.
875    pub create_sql: Option<String>,
876    /// [`VersionedRelationDesc`] of this table, derived from the `create_sql`.
877    pub desc: VersionedRelationDesc,
878    /// Versions of this table, and the [`GlobalId`]s that refer to them.
879    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
880    pub collections: BTreeMap<RelationVersion, GlobalId>,
881    /// If created in the `TEMPORARY` schema, the [`ConnectionId`] for that session.
882    #[serde(skip)]
883    pub conn_id: Option<ConnectionId>,
884    /// Other catalog objects referenced by this table, e.g. custom types.
885    pub resolved_ids: ResolvedIds,
886    /// Custom compaction window, e.g. set via `ALTER RETAIN HISTORY`.
887    pub custom_logical_compaction_window: Option<CompactionWindow>,
888    /// Whether the table's logical compaction window is controlled by the ['metrics_retention']
889    /// session variable.
890    ///
891    /// ['metrics_retention']: mz_sql::session::vars::METRICS_RETENTION
892    pub is_retained_metrics_object: bool,
893    /// Where data for this table comes from, e.g. `INSERT` statements or an upstream source.
894    pub data_source: TableDataSource,
895}
896
897impl Table {
898    /// Constructs a user table from its planned definition.
899    ///
900    /// # Panics
901    /// Panics for unsupported table data sources or webhook plans without a cluster.
902    pub fn from_plan(
903        plan: mz_sql::plan::Table,
904        global_id: GlobalId,
905        connection_id: ConnectionId,
906        resolved_ids: ResolvedIds,
907    ) -> Self {
908        let conn_id = plan.temporary.then_some(connection_id);
909        let collections = [(RelationVersion::root(), global_id)].into_iter().collect();
910        let data_source = match plan.data_source {
911            mz_sql::plan::TableDataSource::TableWrites { defaults } => {
912                TableDataSource::TableWrites { defaults }
913            }
914            mz_sql::plan::TableDataSource::DataSource {
915                desc: data_source_plan,
916                timeline,
917            } => match data_source_plan {
918                mz_sql::plan::DataSourceDesc::IngestionExport {
919                    ingestion_id,
920                    external_reference,
921                    details,
922                    data_config,
923                } => TableDataSource::DataSource {
924                    desc: DataSourceDesc::IngestionExport {
925                        ingestion_id,
926                        external_reference,
927                        details,
928                        data_config,
929                    },
930                    timeline,
931                },
932                mz_sql::plan::DataSourceDesc::Webhook {
933                    validate_using,
934                    body_format,
935                    headers,
936                    cluster_id,
937                } => TableDataSource::DataSource {
938                    desc: DataSourceDesc::Webhook {
939                        validate_using,
940                        body_format,
941                        headers,
942                        cluster_id: cluster_id.expect("Webhook Tables must have cluster_id set"),
943                    },
944                    timeline,
945                },
946                o => {
947                    unreachable!("CREATE TABLE data source got {:?}", o)
948                }
949            },
950        };
951
952        Self {
953            create_sql: Some(plan.create_sql),
954            desc: plan.desc,
955            collections,
956            conn_id,
957            resolved_ids,
958            custom_logical_compaction_window: plan.compaction_window,
959            is_retained_metrics_object: false,
960            data_source,
961        }
962    }
963
964    pub fn timeline(&self) -> Timeline {
965        match &self.data_source {
966            // The Coordinator controls insertions for writable tables
967            // (including system tables), so they are realtime.
968            TableDataSource::TableWrites { .. } => Timeline::EpochMilliseconds,
969            TableDataSource::DataSource { timeline, .. } => timeline.clone(),
970        }
971    }
972
973    /// Returns all of the [`GlobalId`]s that this [`Table`] can be referenced by.
974    pub fn global_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
975        self.collections.values().copied()
976    }
977
978    /// Returns the latest [`GlobalId`] for this [`Table`] which should be used for writes.
979    pub fn global_id_writes(&self) -> GlobalId {
980        *self
981            .collections
982            .last_key_value()
983            .expect("at least one version of a table")
984            .1
985    }
986
987    /// Returns all of the collections and their [`RelationDesc`]s associated with this [`Table`].
988    pub fn collection_descs(
989        &self,
990    ) -> impl Iterator<Item = (GlobalId, RelationVersion, RelationDesc)> + '_ {
991        self.collections.iter().map(|(version, gid)| {
992            let desc = self
993                .desc
994                .at_version(RelationVersionSelector::Specific(*version));
995            (*gid, *version, desc)
996        })
997    }
998
999    /// Returns the [`RelationDesc`] for a specific [`GlobalId`].
1000    pub fn desc_for(&self, id: &GlobalId) -> RelationDesc {
1001        let (version, _gid) = self
1002            .collections
1003            .iter()
1004            .find(|(_version, gid)| *gid == id)
1005            .expect("GlobalId to exist");
1006        self.desc
1007            .at_version(RelationVersionSelector::Specific(*version))
1008    }
1009}
1010
1011#[derive(Clone, Debug, Serialize)]
1012pub enum TableDataSource {
1013    /// The table owns data created via INSERT/UPDATE/DELETE statements.
1014    TableWrites {
1015        #[serde(skip)]
1016        defaults: Vec<Expr<Aug>>,
1017    },
1018
1019    /// The table receives its data from the identified `DataSourceDesc`.
1020    /// This table type does not support INSERT/UPDATE/DELETE statements.
1021    DataSource {
1022        desc: DataSourceDesc,
1023        timeline: Timeline,
1024    },
1025}
1026
1027#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1028pub enum DataSourceDesc {
1029    /// Receives data from an external system
1030    Ingestion {
1031        desc: SourceDesc<ReferencedConnection>,
1032        cluster_id: ClusterId,
1033    },
1034    /// Receives data from an external system
1035    OldSyntaxIngestion {
1036        desc: SourceDesc<ReferencedConnection>,
1037        cluster_id: ClusterId,
1038        // If we're dealing with an old syntax ingestion the progress id will be some other collection
1039        // and the ingestion itself will have the data from an external reference
1040        progress_subsource: CatalogItemId,
1041        data_config: SourceExportDataConfig<ReferencedConnection>,
1042        details: SourceExportDetails,
1043    },
1044    /// This source receives its data from the identified ingestion,
1045    /// specifically the output identified by `external_reference`.
1046    /// N.B. that `external_reference` should not be used to identify
1047    /// anything downstream of purification, as the purification process
1048    /// encodes source-specific identifiers into the `details` struct.
1049    /// The `external_reference` field is only used here for displaying
1050    /// human-readable names in system tables.
1051    IngestionExport {
1052        ingestion_id: CatalogItemId,
1053        external_reference: UnresolvedItemName,
1054        details: SourceExportDetails,
1055        data_config: SourceExportDataConfig<ReferencedConnection>,
1056    },
1057    /// Receives introspection data from an internal system
1058    Introspection(IntrospectionType),
1059    /// Receives data from the source's reclocking/remapping operations.
1060    Progress,
1061    /// Receives data from HTTP requests.
1062    Webhook {
1063        /// Optional components used to validation a webhook request.
1064        validate_using: Option<WebhookValidation>,
1065        /// Describes how we deserialize the body of a webhook request.
1066        body_format: WebhookBodyFormat,
1067        /// Describes whether or not to include headers and how to map them.
1068        headers: WebhookHeaders,
1069        /// The cluster which this source is associated with.
1070        cluster_id: ClusterId,
1071    },
1072    /// Exposes the contents of the catalog shard.
1073    Catalog,
1074}
1075
1076impl From<IntrospectionType> for DataSourceDesc {
1077    fn from(typ: IntrospectionType) -> Self {
1078        Self::Introspection(typ)
1079    }
1080}
1081
1082impl DataSourceDesc {
1083    /// The key and value formats of the data source.
1084    pub fn formats(&self) -> (Option<&str>, Option<&str>) {
1085        match &self {
1086            DataSourceDesc::Ingestion { .. } => (None, None),
1087            DataSourceDesc::OldSyntaxIngestion { data_config, .. } => {
1088                match &data_config.encoding.as_ref() {
1089                    Some(encoding) => match &encoding.key {
1090                        Some(key) => (Some(key.type_()), Some(encoding.value.type_())),
1091                        None => (None, Some(encoding.value.type_())),
1092                    },
1093                    None => (None, None),
1094                }
1095            }
1096            DataSourceDesc::IngestionExport { data_config, .. } => match &data_config.encoding {
1097                Some(encoding) => match &encoding.key {
1098                    Some(key) => (Some(key.type_()), Some(encoding.value.type_())),
1099                    None => (None, Some(encoding.value.type_())),
1100                },
1101                None => (None, None),
1102            },
1103            DataSourceDesc::Introspection(_)
1104            | DataSourceDesc::Webhook { .. }
1105            | DataSourceDesc::Progress
1106            | DataSourceDesc::Catalog => (None, None),
1107        }
1108    }
1109
1110    /// Envelope of the data source.
1111    pub fn envelope(&self) -> Option<&str> {
1112        // Note how "none"/"append-only" is different from `None`. Source
1113        // sources don't have an envelope (internal logs, for example), while
1114        // other sources have an envelope that we call the "NONE"-envelope.
1115
1116        fn envelope_string(envelope: &SourceEnvelope) -> &str {
1117            match envelope {
1118                SourceEnvelope::None(_) => "none",
1119                SourceEnvelope::Upsert(upsert_envelope) => match upsert_envelope.style {
1120                    mz_storage_types::sources::envelope::UpsertStyle::Default(_) => "upsert",
1121                    mz_storage_types::sources::envelope::UpsertStyle::Debezium { .. } => {
1122                        // NOTE(aljoscha): Should we somehow mark that this is
1123                        // using upsert internally? See note above about
1124                        // DEBEZIUM.
1125                        "debezium"
1126                    }
1127                    mz_storage_types::sources::envelope::UpsertStyle::ValueErrInline { .. } => {
1128                        "upsert-value-err-inline"
1129                    }
1130                },
1131                SourceEnvelope::CdcV2 => {
1132                    // TODO(aljoscha): Should we even report this? It's
1133                    // currently not exposed.
1134                    "materialize"
1135                }
1136            }
1137        }
1138
1139        match self {
1140            // NOTE(aljoscha): We could move the block for ingestions into
1141            // `SourceEnvelope` itself, but that one feels more like an internal
1142            // thing and adapter should own how we represent envelopes as a
1143            // string? It would not be hard to convince me otherwise, though.
1144            DataSourceDesc::Ingestion { .. } => None,
1145            DataSourceDesc::OldSyntaxIngestion { data_config, .. } => {
1146                Some(envelope_string(&data_config.envelope))
1147            }
1148            DataSourceDesc::IngestionExport { data_config, .. } => {
1149                Some(envelope_string(&data_config.envelope))
1150            }
1151            DataSourceDesc::Introspection(_)
1152            | DataSourceDesc::Webhook { .. }
1153            | DataSourceDesc::Progress
1154            | DataSourceDesc::Catalog => None,
1155        }
1156    }
1157}
1158
1159#[derive(Debug, Clone, Serialize)]
1160pub struct Source {
1161    /// Parse-able SQL that defines this table.
1162    pub create_sql: Option<String>,
1163    /// [`GlobalId`] used to reference this source from outside the catalog.
1164    pub global_id: GlobalId,
1165    // TODO: Unskip: currently blocked on some inner BTreeMap<X, _> problems.
1166    #[serde(skip)]
1167    pub data_source: DataSourceDesc,
1168    /// [`RelationDesc`] of this source, derived from the `create_sql`.
1169    pub desc: RelationDesc,
1170    /// The timeline this source exists on.
1171    pub timeline: Timeline,
1172    /// Other catalog objects referenced by this table, e.g. custom types.
1173    pub resolved_ids: ResolvedIds,
1174    /// This value is ignored for subsources, i.e. for
1175    /// [`DataSourceDesc::IngestionExport`]. Instead, it uses the primary
1176    /// sources logical compaction window.
1177    pub custom_logical_compaction_window: Option<CompactionWindow>,
1178    /// Whether the source's logical compaction window is controlled by
1179    /// METRICS_RETENTION
1180    pub is_retained_metrics_object: bool,
1181}
1182
1183impl Source {
1184    /// Creates a new `Source`.
1185    ///
1186    /// # Panics
1187    /// - If an ingestion-based plan is not given a cluster_id.
1188    /// - If a non-ingestion-based source has a defined cluster config in its plan.
1189    /// - If a non-ingestion-based source is given a cluster_id.
1190    pub fn new(
1191        plan: CreateSourcePlan,
1192        global_id: GlobalId,
1193        resolved_ids: ResolvedIds,
1194        custom_logical_compaction_window: Option<CompactionWindow>,
1195        is_retained_metrics_object: bool,
1196    ) -> Source {
1197        Source {
1198            create_sql: Some(plan.source.create_sql),
1199            data_source: match plan.source.data_source {
1200                mz_sql::plan::DataSourceDesc::Ingestion(desc) => DataSourceDesc::Ingestion {
1201                    desc,
1202                    cluster_id: plan
1203                        .in_cluster
1204                        .expect("ingestion-based sources must be given a cluster ID"),
1205                },
1206                mz_sql::plan::DataSourceDesc::OldSyntaxIngestion {
1207                    desc,
1208                    progress_subsource,
1209                    data_config,
1210                    details,
1211                } => DataSourceDesc::OldSyntaxIngestion {
1212                    desc,
1213                    cluster_id: plan
1214                        .in_cluster
1215                        .expect("ingestion-based sources must be given a cluster ID"),
1216                    progress_subsource,
1217                    data_config,
1218                    details,
1219                },
1220                mz_sql::plan::DataSourceDesc::Progress => {
1221                    assert!(
1222                        plan.in_cluster.is_none(),
1223                        "subsources must not have a host config or cluster_id defined"
1224                    );
1225                    DataSourceDesc::Progress
1226                }
1227                mz_sql::plan::DataSourceDesc::IngestionExport {
1228                    ingestion_id,
1229                    external_reference,
1230                    details,
1231                    data_config,
1232                } => {
1233                    assert!(
1234                        plan.in_cluster.is_none(),
1235                        "subsources must not have a host config or cluster_id defined"
1236                    );
1237                    DataSourceDesc::IngestionExport {
1238                        ingestion_id,
1239                        external_reference,
1240                        details,
1241                        data_config,
1242                    }
1243                }
1244                mz_sql::plan::DataSourceDesc::Webhook {
1245                    validate_using,
1246                    body_format,
1247                    headers,
1248                    cluster_id,
1249                } => {
1250                    mz_ore::soft_assert_or_log!(
1251                        cluster_id.is_none(),
1252                        "cluster_id set at Source level for Webhooks"
1253                    );
1254                    DataSourceDesc::Webhook {
1255                        validate_using,
1256                        body_format,
1257                        headers,
1258                        cluster_id: plan
1259                            .in_cluster
1260                            .expect("webhook sources must be given a cluster ID"),
1261                    }
1262                }
1263            },
1264            desc: plan.source.desc,
1265            global_id,
1266            timeline: plan.timeline,
1267            resolved_ids,
1268            custom_logical_compaction_window: plan
1269                .source
1270                .compaction_window
1271                .or(custom_logical_compaction_window),
1272            is_retained_metrics_object,
1273        }
1274    }
1275
1276    /// Type of the source.
1277    pub fn source_type(&self) -> &str {
1278        match &self.data_source {
1279            DataSourceDesc::Ingestion { desc, .. }
1280            | DataSourceDesc::OldSyntaxIngestion { desc, .. } => desc.connection.name(),
1281            DataSourceDesc::Progress => "progress",
1282            DataSourceDesc::IngestionExport { .. } => "subsource",
1283            DataSourceDesc::Introspection(_) | DataSourceDesc::Catalog => "source",
1284            DataSourceDesc::Webhook { .. } => "webhook",
1285        }
1286    }
1287
1288    /// Connection ID of the source, if one exists.
1289    pub fn connection_id(&self) -> Option<CatalogItemId> {
1290        match &self.data_source {
1291            DataSourceDesc::Ingestion { desc, .. }
1292            | DataSourceDesc::OldSyntaxIngestion { desc, .. } => desc.connection.connection_id(),
1293            DataSourceDesc::IngestionExport { .. }
1294            | DataSourceDesc::Introspection(_)
1295            | DataSourceDesc::Webhook { .. }
1296            | DataSourceDesc::Progress
1297            | DataSourceDesc::Catalog => None,
1298        }
1299    }
1300
1301    /// The single [`GlobalId`] that refers to this Source.
1302    pub fn global_id(&self) -> GlobalId {
1303        self.global_id
1304    }
1305
1306    /// The expensive resource that each source consumes is persist shards. To
1307    /// prevent abuse, we want to prevent users from creating sources that use an
1308    /// unbounded number of persist shards. But we also don't want to count
1309    /// persist shards that are mandated by the system (e.g., the progress
1310    /// shard) so that future versions of Materialize can introduce additional
1311    /// per-source shards (e.g., a per-source status shard) without impacting
1312    /// the limit calculation.
1313    pub fn user_controllable_persist_shard_count(&self) -> i64 {
1314        match &self.data_source {
1315            DataSourceDesc::Ingestion { .. } => 0,
1316            DataSourceDesc::OldSyntaxIngestion { desc, .. } => {
1317                match &desc.connection {
1318                    // These multi-output sources do not use their primary
1319                    // source's data shard, so we don't include it in accounting
1320                    // for users.
1321                    GenericSourceConnection::Postgres(_)
1322                    | GenericSourceConnection::MySql(_)
1323                    | GenericSourceConnection::SqlServer(_) => 0,
1324                    GenericSourceConnection::LoadGenerator(lg) => match lg.load_generator {
1325                        // Load generators that output data in their primary shard
1326                        LoadGenerator::Clock
1327                        | LoadGenerator::Counter { .. }
1328                        | LoadGenerator::Datums
1329                        | LoadGenerator::KeyValue(_) => 1,
1330                        LoadGenerator::Auction
1331                        | LoadGenerator::Marketing
1332                        | LoadGenerator::Tpch { .. } => 0,
1333                    },
1334                    GenericSourceConnection::Kafka(_) => 1,
1335                }
1336            }
1337            //  DataSourceDesc::IngestionExport represents a subsource, which
1338            //  use a data shard.
1339            DataSourceDesc::IngestionExport { .. } => 1,
1340            DataSourceDesc::Webhook { .. } => 1,
1341            // Introspection, catalog, and progress subsources are not under the user's control, so
1342            // shouldn't count toward their quota.
1343            DataSourceDesc::Introspection(_)
1344            | DataSourceDesc::Progress
1345            | DataSourceDesc::Catalog => 0,
1346        }
1347    }
1348}
1349
1350#[derive(Debug, Clone, Serialize)]
1351pub struct Log {
1352    /// The category of data this log stores.
1353    pub variant: LogVariant,
1354    /// [`GlobalId`] used to reference this log from outside the catalog.
1355    pub global_id: GlobalId,
1356}
1357
1358impl Log {
1359    /// The single [`GlobalId`] that refers to this Log.
1360    pub fn global_id(&self) -> GlobalId {
1361        self.global_id
1362    }
1363}
1364
1365#[derive(Debug, Clone, Serialize)]
1366pub struct Sink {
1367    /// Parse-able SQL that defines this sink.
1368    pub create_sql: String,
1369    /// [`GlobalId`] used to reference this sink from outside the catalog, e.g storage.
1370    pub global_id: GlobalId,
1371    /// Collection we read into this sink.
1372    pub from: GlobalId,
1373    /// Connection to the external service we're sinking into, e.g. Kafka.
1374    pub connection: StorageSinkConnection<ReferencedConnection>,
1375    /// Envelope we use to sink into the external system.
1376    ///
1377    /// TODO(guswynn): this probably should just be in the `connection`.
1378    pub envelope: SinkEnvelope,
1379    /// Emit an initial snapshot into the sink.
1380    pub with_snapshot: bool,
1381    /// Used to fence other writes into this sink as we evolve the upstream materialized view.
1382    pub version: u64,
1383    /// Other catalog objects this sink references.
1384    pub resolved_ids: ResolvedIds,
1385    /// Cluster this sink runs on.
1386    pub cluster_id: ClusterId,
1387    /// Commit interval for the sink.
1388    pub commit_interval: Option<Duration>,
1389}
1390
1391impl Sink {
1392    pub fn sink_type(&self) -> &str {
1393        self.connection.name()
1394    }
1395
1396    /// Envelope of the sink.
1397    ///
1398    /// NOTE: the `mz_sinks` view works this out from `create_sql` instead, in
1399    /// the `CreateSink` arm of `parse_catalog_create_sql`. Kafka gets it from
1400    /// `ENVELOPE` there, iceberg from `MODE`. Change both or they drift.
1401    pub fn envelope(&self) -> Option<&str> {
1402        match &self.envelope {
1403            SinkEnvelope::Debezium => Some("debezium"),
1404            SinkEnvelope::Upsert => Some("upsert"),
1405            SinkEnvelope::Append => Some("append"),
1406        }
1407    }
1408
1409    /// Output a combined format string of the sink. For legacy reasons
1410    /// if the key-format is none or the key & value formats are
1411    /// both the same (either avro or json), we return the value format name,
1412    /// otherwise we return a composite name.
1413    ///
1414    /// NOTE: `parse_catalog_create_sql` redoes this collapse for the `mz_sinks`
1415    /// `format` column. Change both or they drift.
1416    pub fn combined_format(&self) -> Option<Cow<'_, str>> {
1417        match &self.connection {
1418            StorageSinkConnection::Kafka(connection) => Some(connection.format.get_format_name()),
1419            StorageSinkConnection::Iceberg(_) => None,
1420        }
1421    }
1422
1423    /// Output distinct key_format and value_format of the sink.
1424    ///
1425    /// NOTE: also derived from `create_sql` for `mz_sinks`. Watch out that a key
1426    /// format exists only when the sink has a `KEY`, so the SQL side has to work
1427    /// that out from the statement for itself.
1428    pub fn formats(&self) -> Option<(Option<&str>, &str)> {
1429        match &self.connection {
1430            StorageSinkConnection::Kafka(connection) => {
1431                let key_format = connection
1432                    .format
1433                    .key_format
1434                    .as_ref()
1435                    .map(|f| f.get_format_name());
1436                let value_format = connection.format.value_format.get_format_name();
1437                Some((key_format, value_format))
1438            }
1439            StorageSinkConnection::Iceberg(_) => None,
1440        }
1441    }
1442
1443    pub fn connection_id(&self) -> Option<CatalogItemId> {
1444        self.connection.connection_id()
1445    }
1446
1447    /// The single [`GlobalId`] that this Sink can be referenced by.
1448    pub fn global_id(&self) -> GlobalId {
1449        self.global_id
1450    }
1451}
1452
1453#[derive(Debug, Clone, Serialize)]
1454pub struct View {
1455    /// Parse-able SQL that defines this view.
1456    pub create_sql: String,
1457    /// [`GlobalId`] used to reference this view from outside the catalog, e.g. compute.
1458    pub global_id: GlobalId,
1459    /// Unoptimized high-level expression from parsing the `create_sql`.
1460    pub raw_expr: Arc<HirRelationExpr>,
1461    /// Optimized mid-level expression from (locally) optimizing the `raw_expr`.
1462    pub locally_optimized_expr: Arc<OptimizedMirRelationExpr>,
1463    /// Columns of this view.
1464    pub desc: RelationDesc,
1465    /// If created in the `TEMPORARY` schema, the [`ConnectionId`] for that session.
1466    pub conn_id: Option<ConnectionId>,
1467    /// Other catalog objects that are referenced by this view, determined at name resolution.
1468    pub resolved_ids: ResolvedIds,
1469    /// All of the catalog objects that are referenced by this view.
1470    pub dependencies: DependencyIds,
1471}
1472
1473impl View {
1474    /// The single [`GlobalId`] this [`View`] can be referenced by.
1475    pub fn global_id(&self) -> GlobalId {
1476        self.global_id
1477    }
1478}
1479
1480#[derive(Debug, Clone, Serialize)]
1481pub struct MaterializedView {
1482    /// Parse-able SQL that defines this materialized view.
1483    pub create_sql: String,
1484    /// Versions of this materialized view, and the [`GlobalId`]s that refer to them.
1485    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
1486    pub collections: BTreeMap<RelationVersion, GlobalId>,
1487    /// Raw high-level expression from planning, derived from the `create_sql`.
1488    pub raw_expr: Arc<HirRelationExpr>,
1489    /// Optimized mid-level expression, derived from the `raw_expr`.
1490    pub locally_optimized_expr: Arc<OptimizedMirRelationExpr>,
1491    /// [`VersionedRelationDesc`] of this materialized view, derived from the `create_sql`.
1492    pub desc: VersionedRelationDesc,
1493    /// Other catalog items that this materialized view references, determined at name resolution.
1494    pub resolved_ids: ResolvedIds,
1495    /// All of the catalog objects that are referenced by this view.
1496    pub dependencies: DependencyIds,
1497    /// ID of the materialized view this materialized view is intended to replace.
1498    pub replacement_target: Option<CatalogItemId>,
1499    /// Cluster that this materialized view runs on.
1500    pub cluster_id: ClusterId,
1501    /// If set, only install this materialized view's dataflow on the specified replica.
1502    pub target_replica: Option<ReplicaId>,
1503    /// Column indexes that we assert are not `NULL`.
1504    ///
1505    /// TODO(parkmycar): Switch this to use the `ColumnIdx` type.
1506    pub non_null_assertions: Vec<usize>,
1507    /// Custom compaction window, e.g. set via `ALTER RETAIN HISTORY`.
1508    pub custom_logical_compaction_window: Option<CompactionWindow>,
1509    /// Schedule to refresh this materialized view, e.g. set via `REFRESH EVERY` option.
1510    pub refresh_schedule: Option<RefreshSchedule>,
1511    /// The initial `as_of` of the storage collection associated with the materialized view.
1512    ///
1513    /// Note: This doesn't change upon restarts.
1514    /// (The dataflow's initial `as_of` can be different.)
1515    pub initial_as_of: Option<Antichain<mz_repr::Timestamp>>,
1516    // The catalog `dump` method uses serde to serialize catalog state, e.g., Testdrive catalog
1517    // consistency checks do two dumps and compare them. One of these states comes from the durable
1518    // catalog, but the following fields are not restored when the consistency check loads the
1519    // durable catalog, hence we need `#[serde(skip)]`.
1520    /// Optimized global MIR plan, set after global optimization.
1521    #[serde(skip)]
1522    pub optimized_plan: Option<Arc<DataflowDescription<OptimizedMirRelationExpr>>>,
1523    /// Physical (LIR) plan, set after physical optimization.
1524    #[serde(skip)]
1525    pub physical_plan: Option<Arc<LirDataflowDescription>>,
1526    /// Dataflow metainfo (optimizer notices, etc.), set after optimization.
1527    #[serde(skip)]
1528    pub dataflow_metainfo: Option<DataflowMetainfo<Arc<OptimizerNotice>>>,
1529}
1530
1531impl MaterializedView {
1532    /// Returns all [`GlobalId`]s that this [`MaterializedView`] can be referenced by.
1533    pub fn global_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
1534        self.collections.values().copied()
1535    }
1536
1537    /// The latest [`GlobalId`] for this [`MaterializedView`] which represents the writing
1538    /// version.
1539    pub fn global_id_writes(&self) -> GlobalId {
1540        *self
1541            .collections
1542            .last_key_value()
1543            .expect("at least one version of a materialized view")
1544            .1
1545    }
1546
1547    /// Returns all collections and their [`RelationDesc`]s associated with this [`MaterializedView`].
1548    pub fn collection_descs(
1549        &self,
1550    ) -> impl Iterator<Item = (GlobalId, RelationVersion, RelationDesc)> + '_ {
1551        self.collections.iter().map(|(version, gid)| {
1552            let desc = self
1553                .desc
1554                .at_version(RelationVersionSelector::Specific(*version));
1555            (*gid, *version, desc)
1556        })
1557    }
1558
1559    /// Returns the [`RelationDesc`] for a specific [`GlobalId`].
1560    pub fn desc_for(&self, id: &GlobalId) -> RelationDesc {
1561        let (version, _gid) = self
1562            .collections
1563            .iter()
1564            .find(|(_version, gid)| *gid == id)
1565            .expect("GlobalId to exist");
1566        self.desc
1567            .at_version(RelationVersionSelector::Specific(*version))
1568    }
1569
1570    /// Apply the given replacement materialized view to this [`MaterializedView`].
1571    pub fn apply_replacement(&mut self, replacement: Self) {
1572        let target_id = replacement
1573            .replacement_target
1574            .expect("replacement has target");
1575
1576        fn parse(create_sql: &str) -> mz_sql::ast::CreateMaterializedViewStatement<Raw> {
1577            let res = mz_sql::parse::parse(create_sql).unwrap_or_else(|e| {
1578                panic!("invalid create_sql persisted in catalog: {e}\n{create_sql}");
1579            });
1580            if let Statement::CreateMaterializedView(cmvs) = res.into_element().ast {
1581                cmvs
1582            } else {
1583                panic!("invalid MV create_sql persisted in catalog\n{create_sql}");
1584            }
1585        }
1586
1587        let old_stmt = parse(&self.create_sql);
1588        let rpl_stmt = parse(&replacement.create_sql);
1589        let new_stmt = mz_sql::ast::CreateMaterializedViewStatement {
1590            if_exists: old_stmt.if_exists,
1591            name: old_stmt.name,
1592            columns: rpl_stmt.columns,
1593            replacement_for: None,
1594            in_cluster: rpl_stmt.in_cluster,
1595            in_cluster_replica: rpl_stmt.in_cluster_replica,
1596            query: rpl_stmt.query,
1597            as_of: rpl_stmt.as_of,
1598            with_options: rpl_stmt.with_options,
1599        };
1600        let create_sql = new_stmt.to_ast_string_stable();
1601
1602        let mut collections = std::mem::take(&mut self.collections);
1603        // Note: We can't use `self.desc.latest_version` here because a replacement doesn't
1604        // necessary evolve the relation schema, so that version might be lower than the actual
1605        // latest version.
1606        let latest_version = collections.keys().max().expect("at least one version");
1607        let new_version = latest_version.bump();
1608        collections.insert(new_version, replacement.global_id_writes());
1609
1610        let mut resolved_ids = replacement.resolved_ids;
1611        resolved_ids.remove_item(&target_id);
1612        let mut dependencies = replacement.dependencies;
1613        dependencies.0.remove(&target_id);
1614
1615        *self = Self {
1616            create_sql,
1617            collections,
1618            raw_expr: replacement.raw_expr,
1619            locally_optimized_expr: replacement.locally_optimized_expr,
1620            desc: replacement.desc,
1621            resolved_ids,
1622            dependencies,
1623            replacement_target: None,
1624            cluster_id: replacement.cluster_id,
1625            target_replica: replacement.target_replica,
1626            non_null_assertions: replacement.non_null_assertions,
1627            custom_logical_compaction_window: replacement.custom_logical_compaction_window,
1628            refresh_schedule: replacement.refresh_schedule,
1629            initial_as_of: replacement.initial_as_of,
1630            optimized_plan: replacement.optimized_plan,
1631            physical_plan: replacement.physical_plan,
1632            dataflow_metainfo: replacement.dataflow_metainfo,
1633        };
1634    }
1635}
1636
1637#[derive(Debug, Clone, Serialize)]
1638pub struct Index {
1639    /// Parse-able SQL that defines this table.
1640    pub create_sql: String,
1641    /// [`GlobalId`] used to reference this index from outside the catalog, e.g. compute.
1642    pub global_id: GlobalId,
1643    /// The [`GlobalId`] this Index is on.
1644    pub on: GlobalId,
1645    /// Keys of the index.
1646    pub keys: Arc<[MirScalarExpr]>,
1647    /// If created in the `TEMPORARY` schema, the [`ConnectionId`] for that session.
1648    pub conn_id: Option<ConnectionId>,
1649    /// Other catalog objects referenced by this index, e.g. the object we're indexing.
1650    pub resolved_ids: ResolvedIds,
1651    /// Cluster this index is installed on.
1652    pub cluster_id: ClusterId,
1653    /// Custom compaction window, e.g. set via `ALTER RETAIN HISTORY`.
1654    pub custom_logical_compaction_window: Option<CompactionWindow>,
1655    /// Whether the table's logical compaction window is controlled by the ['metrics_retention']
1656    /// session variable.
1657    ///
1658    /// ['metrics_retention']: mz_sql::session::vars::METRICS_RETENTION
1659    pub is_retained_metrics_object: bool,
1660    // The catalog `dump` method uses serde to serialize catalog state, e.g., Testdrive catalog
1661    // consistency checks do two dumps and compare them. One of these states comes from the durable
1662    // catalog, but the following fields are not restored when the consistency check loads the
1663    // durable catalog, hence we need `#[serde(skip)]`.
1664    /// Optimized global MIR plan, set after global optimization.
1665    #[serde(skip)]
1666    pub optimized_plan: Option<Arc<DataflowDescription<OptimizedMirRelationExpr>>>,
1667    /// Physical (LIR) plan, set after physical optimization.
1668    #[serde(skip)]
1669    pub physical_plan: Option<Arc<LirDataflowDescription>>,
1670    /// Dataflow metainfo (optimizer notices, etc.), set after optimization.
1671    #[serde(skip)]
1672    pub dataflow_metainfo: Option<DataflowMetainfo<Arc<OptimizerNotice>>>,
1673}
1674
1675impl Index {
1676    /// The [`GlobalId`] that refers to this Index.
1677    pub fn global_id(&self) -> GlobalId {
1678        self.global_id
1679    }
1680}
1681
1682/// A sink that exports a relation's rows as Prometheus metrics.
1683#[derive(Debug, Clone, Serialize)]
1684pub struct MetricSink {
1685    /// Parse-able SQL that defines this metric sink.
1686    pub create_sql: String,
1687    /// [`GlobalId`] used to reference this metric sink from outside the catalog, e.g. compute.
1688    pub global_id: GlobalId,
1689    /// Collection we read into this metric sink.
1690    pub from: GlobalId,
1691    /// Other catalog objects referenced by this metric sink.
1692    pub resolved_ids: ResolvedIds,
1693    /// Cluster this metric sink runs on.
1694    pub cluster_id: ClusterId,
1695    /// Prepended to every metric name this sink publishes. Not durable on its own: like `from`
1696    /// and `cluster_id`, it rides in `create_sql` and is recovered by re-parsing that on boot.
1697    pub prefix: String,
1698    /// Optimized global MIR plan, set after global optimization.
1699    #[serde(skip)]
1700    pub optimized_plan: Option<Arc<DataflowDescription<OptimizedMirRelationExpr>>>,
1701    /// Physical (LIR) plan, set after physical optimization.
1702    #[serde(skip)]
1703    pub physical_plan: Option<Arc<LirDataflowDescription>>,
1704    /// Dataflow metainfo (optimizer notices, etc.), set after optimization.
1705    #[serde(skip)]
1706    pub dataflow_metainfo: Option<DataflowMetainfo<Arc<OptimizerNotice>>>,
1707}
1708
1709impl MetricSink {
1710    /// The [`GlobalId`] that refers to this metric sink.
1711    pub fn global_id(&self) -> GlobalId {
1712        self.global_id
1713    }
1714}
1715
1716#[derive(Debug, Clone, Serialize)]
1717pub struct Type {
1718    /// Parse-able SQL that defines this type.
1719    pub create_sql: Option<String>,
1720    /// [`GlobalId`] used to reference this type from outside the catalog.
1721    pub global_id: GlobalId,
1722    #[serde(skip)]
1723    pub details: CatalogTypeDetails<IdReference>,
1724    /// Other catalog objects referenced by this type.
1725    pub resolved_ids: ResolvedIds,
1726}
1727
1728#[derive(Debug, Clone, Serialize)]
1729pub struct Func {
1730    /// Static definition of the function.
1731    #[serde(skip)]
1732    pub inner: &'static mz_sql::func::Func,
1733    /// [`GlobalId`] used to reference this function from outside the catalog.
1734    pub global_id: GlobalId,
1735}
1736
1737#[derive(Debug, Clone, Serialize)]
1738pub struct Secret {
1739    /// Parse-able SQL that defines this secret.
1740    pub create_sql: String,
1741    /// [`GlobalId`] used to reference this secret from outside the catalog.
1742    pub global_id: GlobalId,
1743}
1744
1745#[derive(Debug, Clone, Serialize)]
1746pub struct Connection {
1747    /// Parse-able SQL that defines this connection.
1748    pub create_sql: String,
1749    /// [`GlobalId`] used to reference this connection from the storage layer.
1750    pub global_id: GlobalId,
1751    /// The kind of connection.
1752    pub details: ConnectionDetails,
1753    /// Other objects this connection depends on.
1754    pub resolved_ids: ResolvedIds,
1755}
1756
1757impl Connection {
1758    /// The single [`GlobalId`] used to reference this connection.
1759    pub fn global_id(&self) -> GlobalId {
1760        self.global_id
1761    }
1762}
1763
1764#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1765pub struct QueryPolicy {
1766    pub name: String,
1767    pub id: QueryPolicyId,
1768    pub oid: u32,
1769    pub mode: QueryPolicyMode,
1770    pub rules: Vec<QueryPolicyRule>,
1771    pub owner_id: RoleId,
1772    pub privileges: PrivilegeMap,
1773}
1774
1775impl From<QueryPolicy> for durable::QueryPolicy {
1776    fn from(policy: QueryPolicy) -> Self {
1777        Self {
1778            name: policy.name,
1779            id: policy.id,
1780            oid: policy.oid,
1781            mode: policy.mode,
1782            rules: policy.rules,
1783            owner_id: policy.owner_id,
1784            privileges: policy.privileges.into_all_values().collect(),
1785        }
1786    }
1787}
1788
1789impl From<durable::QueryPolicy> for QueryPolicy {
1790    fn from(policy: durable::QueryPolicy) -> Self {
1791        Self {
1792            name: policy.name,
1793            id: policy.id,
1794            oid: policy.oid,
1795            mode: policy.mode,
1796            rules: policy.rules,
1797            owner_id: policy.owner_id,
1798            privileges: PrivilegeMap::from_mz_acl_items(policy.privileges),
1799        }
1800    }
1801}
1802
1803impl UpdateFrom<durable::QueryPolicy> for QueryPolicy {
1804    fn update_from(&mut self, policy: durable::QueryPolicy) {
1805        *self = policy.into();
1806    }
1807}
1808
1809#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1810pub struct NetworkPolicy {
1811    pub name: String,
1812    pub id: NetworkPolicyId,
1813    pub oid: u32,
1814    pub rules: Vec<NetworkPolicyRule>,
1815    pub owner_id: RoleId,
1816    pub privileges: PrivilegeMap,
1817}
1818
1819impl From<NetworkPolicy> for durable::NetworkPolicy {
1820    fn from(policy: NetworkPolicy) -> durable::NetworkPolicy {
1821        durable::NetworkPolicy {
1822            id: policy.id,
1823            oid: policy.oid,
1824            name: policy.name,
1825            rules: policy.rules,
1826            owner_id: policy.owner_id,
1827            privileges: policy.privileges.into_all_values().collect(),
1828        }
1829    }
1830}
1831
1832impl From<durable::NetworkPolicy> for NetworkPolicy {
1833    fn from(
1834        durable::NetworkPolicy {
1835            id,
1836            oid,
1837            name,
1838            rules,
1839            owner_id,
1840            privileges,
1841        }: durable::NetworkPolicy,
1842    ) -> Self {
1843        NetworkPolicy {
1844            id,
1845            oid,
1846            name,
1847            rules,
1848            owner_id,
1849            privileges: PrivilegeMap::from_mz_acl_items(privileges),
1850        }
1851    }
1852}
1853
1854impl UpdateFrom<durable::NetworkPolicy> for NetworkPolicy {
1855    fn update_from(
1856        &mut self,
1857        durable::NetworkPolicy {
1858            id,
1859            oid,
1860            name,
1861            rules,
1862            owner_id,
1863            privileges,
1864        }: durable::NetworkPolicy,
1865    ) {
1866        self.id = id;
1867        self.oid = oid;
1868        self.name = name;
1869        self.rules = rules;
1870        self.owner_id = owner_id;
1871        self.privileges = PrivilegeMap::from_mz_acl_items(privileges);
1872    }
1873}
1874
1875impl CatalogItem {
1876    /// Returns a string indicating the type of this catalog entry.
1877    pub fn typ(&self) -> mz_sql::catalog::CatalogItemType {
1878        match self {
1879            CatalogItem::Table(_) => CatalogItemType::Table,
1880            CatalogItem::Source(_) => CatalogItemType::Source,
1881            CatalogItem::Log(_) => CatalogItemType::Source,
1882            CatalogItem::Sink(_) => CatalogItemType::Sink,
1883            CatalogItem::View(_) => CatalogItemType::View,
1884            CatalogItem::MaterializedView(_) => CatalogItemType::MaterializedView,
1885            CatalogItem::Index(_) => CatalogItemType::Index,
1886            CatalogItem::Type(_) => CatalogItemType::Type,
1887            CatalogItem::Func(_) => CatalogItemType::Func,
1888            CatalogItem::Secret(_) => CatalogItemType::Secret,
1889            CatalogItem::Connection(_) => CatalogItemType::Connection,
1890            CatalogItem::MetricSink(_) => CatalogItemType::MetricSink,
1891        }
1892    }
1893
1894    /// Returns the [`GlobalId`]s that reference this item, if any.
1895    pub fn global_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
1896        let gid = match self {
1897            CatalogItem::Source(source) => source.global_id,
1898            CatalogItem::Log(log) => log.global_id,
1899            CatalogItem::Sink(sink) => sink.global_id,
1900            CatalogItem::View(view) => view.global_id,
1901            CatalogItem::MaterializedView(mv) => {
1902                return itertools::Either::Left(mv.collections.values().copied());
1903            }
1904            CatalogItem::Index(index) => index.global_id,
1905            CatalogItem::Func(func) => func.global_id,
1906            CatalogItem::Type(ty) => ty.global_id,
1907            CatalogItem::Secret(secret) => secret.global_id,
1908            CatalogItem::Connection(conn) => conn.global_id,
1909            CatalogItem::MetricSink(metric_sink) => metric_sink.global_id,
1910            CatalogItem::Table(table) => {
1911                return itertools::Either::Left(table.collections.values().copied());
1912            }
1913        };
1914        itertools::Either::Right(std::iter::once(gid))
1915    }
1916
1917    /// Returns the most up-to-date [`GlobalId`] for this item.
1918    ///
1919    /// Note: The only type of object that can have multiple [`GlobalId`]s are tables.
1920    pub fn latest_global_id(&self) -> GlobalId {
1921        match self {
1922            CatalogItem::Source(source) => source.global_id,
1923            CatalogItem::Log(log) => log.global_id,
1924            CatalogItem::Sink(sink) => sink.global_id,
1925            CatalogItem::View(view) => view.global_id,
1926            CatalogItem::MaterializedView(mv) => mv.global_id_writes(),
1927            CatalogItem::Index(index) => index.global_id,
1928            CatalogItem::Func(func) => func.global_id,
1929            CatalogItem::Type(ty) => ty.global_id,
1930            CatalogItem::Secret(secret) => secret.global_id,
1931            CatalogItem::Connection(conn) => conn.global_id,
1932            CatalogItem::MetricSink(metric_sink) => metric_sink.global_id,
1933            CatalogItem::Table(table) => table.global_id_writes(),
1934        }
1935    }
1936
1937    /// Returns the optimized global MIR plan, if this item has one.
1938    pub fn optimized_plan(&self) -> Option<&Arc<DataflowDescription<OptimizedMirRelationExpr>>> {
1939        match self {
1940            CatalogItem::Index(idx) => idx.optimized_plan.as_ref(),
1941            CatalogItem::MaterializedView(mv) => mv.optimized_plan.as_ref(),
1942            CatalogItem::MetricSink(ms) => ms.optimized_plan.as_ref(),
1943            _ => None,
1944        }
1945    }
1946
1947    /// Returns the physical (LIR) plan, if this item has one.
1948    pub fn physical_plan(&self) -> Option<&Arc<LirDataflowDescription>> {
1949        match self {
1950            CatalogItem::Index(idx) => idx.physical_plan.as_ref(),
1951            CatalogItem::MaterializedView(mv) => mv.physical_plan.as_ref(),
1952            CatalogItem::MetricSink(ms) => ms.physical_plan.as_ref(),
1953            _ => None,
1954        }
1955    }
1956
1957    /// Returns the dataflow metainfo, if this item has one.
1958    pub fn dataflow_metainfo(&self) -> Option<&DataflowMetainfo<Arc<OptimizerNotice>>> {
1959        match self {
1960            CatalogItem::Index(idx) => idx.dataflow_metainfo.as_ref(),
1961            CatalogItem::MaterializedView(mv) => mv.dataflow_metainfo.as_ref(),
1962            CatalogItem::MetricSink(ms) => ms.dataflow_metainfo.as_ref(),
1963            _ => None,
1964        }
1965    }
1966
1967    /// Returns a mutable reference to the dataflow metainfo, if this item has one.
1968    pub fn dataflow_metainfo_mut(&mut self) -> Option<&mut DataflowMetainfo<Arc<OptimizerNotice>>> {
1969        match self {
1970            CatalogItem::Index(idx) => idx.dataflow_metainfo.as_mut(),
1971            CatalogItem::MaterializedView(mv) => mv.dataflow_metainfo.as_mut(),
1972            CatalogItem::MetricSink(ms) => ms.dataflow_metainfo.as_mut(),
1973            _ => None,
1974        }
1975    }
1976
1977    /// Returns mutable references to the plan fields (`optimized_plan`,
1978    /// `physical_plan`, `dataflow_metainfo`) on plan-bearing items
1979    /// (`Index`, `MaterializedView`), or `None` for
1980    /// other item kinds.
1981    pub fn plan_fields_mut(
1982        &mut self,
1983    ) -> Option<(
1984        &mut Option<Arc<DataflowDescription<OptimizedMirRelationExpr>>>,
1985        &mut Option<Arc<LirDataflowDescription>>,
1986        &mut Option<DataflowMetainfo<Arc<OptimizerNotice>>>,
1987    )> {
1988        match self {
1989            CatalogItem::Index(idx) => Some((
1990                &mut idx.optimized_plan,
1991                &mut idx.physical_plan,
1992                &mut idx.dataflow_metainfo,
1993            )),
1994            CatalogItem::MaterializedView(mv) => Some((
1995                &mut mv.optimized_plan,
1996                &mut mv.physical_plan,
1997                &mut mv.dataflow_metainfo,
1998            )),
1999            CatalogItem::MetricSink(ms) => Some((
2000                &mut ms.optimized_plan,
2001                &mut ms.physical_plan,
2002                &mut ms.dataflow_metainfo,
2003            )),
2004            _ => None,
2005        }
2006    }
2007
2008    /// Whether this item represents a storage collection.
2009    pub fn is_storage_collection(&self) -> bool {
2010        match self {
2011            CatalogItem::Table(_)
2012            | CatalogItem::Source(_)
2013            | CatalogItem::MaterializedView(_)
2014            | CatalogItem::Sink(_) => true,
2015            CatalogItem::Log(_)
2016            | CatalogItem::View(_)
2017            | CatalogItem::Index(_)
2018            | CatalogItem::Type(_)
2019            | CatalogItem::Func(_)
2020            | CatalogItem::Secret(_)
2021            | CatalogItem::Connection(_)
2022            | CatalogItem::MetricSink(_) => false,
2023        }
2024    }
2025
2026    /// Returns the [`RelationDesc`] for items that yield rows, at the requested
2027    /// version.
2028    ///
2029    /// Some item types honor `version` so callers can ask for the schema that
2030    /// matches a specific [`GlobalId`] or historical definition. Other relation
2031    /// types ignore `version` because they have a single shape. Non-relational
2032    /// items ( for example functions, indexes, sinks, secrets, and connections)
2033    /// return `None`.
2034    pub fn relation_desc(&self, version: RelationVersionSelector) -> Option<Cow<'_, RelationDesc>> {
2035        match &self {
2036            CatalogItem::Source(src) => Some(Cow::Borrowed(&src.desc)),
2037            CatalogItem::Log(log) => Some(Cow::Owned(log.variant.desc())),
2038            CatalogItem::Table(tbl) => Some(Cow::Owned(tbl.desc.at_version(version))),
2039            CatalogItem::View(view) => Some(Cow::Borrowed(&view.desc)),
2040            CatalogItem::MaterializedView(mview) => {
2041                Some(Cow::Owned(mview.desc.at_version(version)))
2042            }
2043            CatalogItem::Func(_)
2044            | CatalogItem::Index(_)
2045            | CatalogItem::Sink(_)
2046            | CatalogItem::Secret(_)
2047            | CatalogItem::Connection(_)
2048            | CatalogItem::Type(_)
2049            | CatalogItem::MetricSink(_) => None,
2050        }
2051    }
2052
2053    pub fn func(
2054        &self,
2055        entry: &CatalogEntry,
2056    ) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
2057        match &self {
2058            CatalogItem::Func(func) => Ok(func.inner),
2059            _ => Err(SqlCatalogError::UnexpectedType {
2060                name: entry.name().item.to_string(),
2061                actual_type: entry.item_type(),
2062                expected_type: CatalogItemType::Func,
2063            }),
2064        }
2065    }
2066
2067    pub fn source_desc(
2068        &self,
2069        entry: &CatalogEntry,
2070    ) -> Result<Option<&SourceDesc<ReferencedConnection>>, SqlCatalogError> {
2071        match &self {
2072            CatalogItem::Source(source) => match &source.data_source {
2073                DataSourceDesc::Ingestion { desc, .. }
2074                | DataSourceDesc::OldSyntaxIngestion { desc, .. } => Ok(Some(desc)),
2075                DataSourceDesc::IngestionExport { .. }
2076                | DataSourceDesc::Introspection(_)
2077                | DataSourceDesc::Webhook { .. }
2078                | DataSourceDesc::Progress
2079                | DataSourceDesc::Catalog => Ok(None),
2080            },
2081            _ => Err(SqlCatalogError::UnexpectedType {
2082                name: entry.name().item.to_string(),
2083                actual_type: entry.item_type(),
2084                expected_type: CatalogItemType::Source,
2085            }),
2086        }
2087    }
2088
2089    /// Reports whether this catalog entry is a progress source.
2090    pub fn is_progress_source(&self) -> bool {
2091        matches!(
2092            self,
2093            CatalogItem::Source(Source {
2094                data_source: DataSourceDesc::Progress,
2095                ..
2096            })
2097        )
2098    }
2099
2100    /// Collects the identifiers of the objects that were encountered when resolving names in the
2101    /// item's DDL statement.
2102    pub fn references(&self) -> &ResolvedIds {
2103        static EMPTY: LazyLock<ResolvedIds> = LazyLock::new(ResolvedIds::empty);
2104        match self {
2105            CatalogItem::Func(_) => &*EMPTY,
2106            CatalogItem::Index(idx) => &idx.resolved_ids,
2107            CatalogItem::Sink(sink) => &sink.resolved_ids,
2108            CatalogItem::Source(source) => &source.resolved_ids,
2109            CatalogItem::Log(_) => &*EMPTY,
2110            CatalogItem::Table(table) => &table.resolved_ids,
2111            CatalogItem::Type(typ) => &typ.resolved_ids,
2112            CatalogItem::View(view) => &view.resolved_ids,
2113            CatalogItem::MaterializedView(mview) => &mview.resolved_ids,
2114            CatalogItem::Secret(_) => &*EMPTY,
2115            CatalogItem::Connection(connection) => &connection.resolved_ids,
2116            CatalogItem::MetricSink(metric_sink) => &metric_sink.resolved_ids,
2117        }
2118    }
2119
2120    /// Collects the identifiers of the objects used by this [`CatalogItem`].
2121    ///
2122    /// Like [`CatalogItem::references()`] but also includes objects that are not directly
2123    /// referenced. For example this will include any catalog objects used to implement functions
2124    /// and casts in the item.
2125    pub fn uses(&self) -> BTreeSet<CatalogItemId> {
2126        let mut uses: BTreeSet<_> = self.references().items().copied().collect();
2127        match self {
2128            // TODO(jkosh44) This isn't really correct for functions. They may use other objects in
2129            // their implementation. However, currently there's no way to get that information.
2130            CatalogItem::Func(_) => {}
2131            CatalogItem::Index(_) => {}
2132            CatalogItem::Sink(_) => {}
2133            CatalogItem::Source(_) => {}
2134            CatalogItem::Log(_) => {}
2135            CatalogItem::Table(_) => {}
2136            CatalogItem::Type(_) => {}
2137            CatalogItem::View(view) => uses.extend(view.dependencies.0.iter().copied()),
2138            CatalogItem::MaterializedView(mview) => {
2139                uses.extend(mview.dependencies.0.iter().copied())
2140            }
2141            CatalogItem::Secret(_) => {}
2142            CatalogItem::Connection(_) => {}
2143            CatalogItem::MetricSink(_) => {}
2144        }
2145        uses
2146    }
2147
2148    /// Returns direct dependencies to traverse when finding this item's query leaves.
2149    ///
2150    /// Functions and views return all of their uses. Materialized views do the
2151    /// same except for the replacement target, which is lifecycle metadata. All
2152    /// other items are query leaves or cannot be selected from.
2153    pub fn query_dependencies(&self) -> BTreeSet<CatalogItemId> {
2154        match self {
2155            CatalogItem::Func(_) | CatalogItem::View(_) => self.uses(),
2156            CatalogItem::MaterializedView(mv) => {
2157                let mut dependencies = self.uses();
2158                if let Some(target) = mv.replacement_target {
2159                    dependencies.remove(&target);
2160                }
2161                dependencies
2162            }
2163            CatalogItem::Index(_)
2164            | CatalogItem::Sink(_)
2165            | CatalogItem::Source(_)
2166            | CatalogItem::Log(_)
2167            | CatalogItem::Table(_)
2168            | CatalogItem::Type(_)
2169            | CatalogItem::Secret(_)
2170            | CatalogItem::Connection(_)
2171            | CatalogItem::MetricSink(_) => BTreeSet::new(),
2172        }
2173    }
2174
2175    /// Returns the connection ID that this item belongs to, if this item is
2176    /// temporary.
2177    pub fn conn_id(&self) -> Option<&ConnectionId> {
2178        match self {
2179            CatalogItem::View(view) => view.conn_id.as_ref(),
2180            CatalogItem::Index(index) => index.conn_id.as_ref(),
2181            CatalogItem::Table(table) => table.conn_id.as_ref(),
2182            CatalogItem::Log(_)
2183            | CatalogItem::Source(_)
2184            | CatalogItem::Sink(_)
2185            | CatalogItem::MaterializedView(_)
2186            | CatalogItem::Secret(_)
2187            | CatalogItem::Type(_)
2188            | CatalogItem::Func(_)
2189            | CatalogItem::Connection(_)
2190            | CatalogItem::MetricSink(_) => None,
2191        }
2192    }
2193
2194    /// Sets the connection ID that this item belongs to, which makes it a
2195    /// temporary item.
2196    pub fn set_conn_id(&mut self, conn_id: Option<ConnectionId>) {
2197        match self {
2198            CatalogItem::View(view) => view.conn_id = conn_id,
2199            CatalogItem::Index(index) => index.conn_id = conn_id,
2200            CatalogItem::Table(table) => table.conn_id = conn_id,
2201            CatalogItem::Log(_)
2202            | CatalogItem::Source(_)
2203            | CatalogItem::Sink(_)
2204            | CatalogItem::MaterializedView(_)
2205            | CatalogItem::Secret(_)
2206            | CatalogItem::Type(_)
2207            | CatalogItem::Func(_)
2208            | CatalogItem::Connection(_)
2209            | CatalogItem::MetricSink(_) => (),
2210        }
2211    }
2212
2213    /// Overwrites the `create_sql` of this item, without replanning.
2214    ///
2215    /// Only used when applying temporary item updates. A temporary item's
2216    /// in-memory `create_sql` must stay byte-identical to the update that
2217    /// created it, so that re-serializing the item, for example when a later
2218    /// op in the same transaction retracts it, yields a value that
2219    /// consolidates away against that update. Persistent items get this
2220    /// guarantee from the durable catalog, which stores the exact bytes.
2221    pub fn set_create_sql(&mut self, create_sql: String) {
2222        match self {
2223            CatalogItem::View(view) => view.create_sql = create_sql,
2224            CatalogItem::Index(index) => index.create_sql = create_sql,
2225            CatalogItem::Table(table) => table.create_sql = Some(create_sql),
2226            CatalogItem::Log(_)
2227            | CatalogItem::Source(_)
2228            | CatalogItem::Sink(_)
2229            | CatalogItem::MaterializedView(_)
2230            | CatalogItem::Secret(_)
2231            | CatalogItem::Type(_)
2232            | CatalogItem::Func(_)
2233            | CatalogItem::Connection(_)
2234            | CatalogItem::MetricSink(_) => {
2235                unreachable!("only views, indexes, and tables can be temporary")
2236            }
2237        }
2238    }
2239
2240    /// Indicates whether this item is temporary or not.
2241    pub fn is_temporary(&self) -> bool {
2242        self.conn_id().is_some()
2243    }
2244
2245    pub fn rename_schema_refs(
2246        &self,
2247        database_name: &str,
2248        cur_schema_name: &str,
2249        new_schema_name: &str,
2250    ) -> Result<CatalogItem, (String, String)> {
2251        let do_rewrite = |create_sql: String| -> Result<String, (String, String)> {
2252            let mut create_stmt = mz_sql::parse::parse(&create_sql)
2253                .expect("invalid create sql persisted to catalog")
2254                .into_element()
2255                .ast;
2256
2257            // Rename all references to cur_schema_name.
2258            mz_sql::ast::transform::create_stmt_rename_schema_refs(
2259                &mut create_stmt,
2260                database_name,
2261                cur_schema_name,
2262                new_schema_name,
2263            )?;
2264
2265            Ok(create_stmt.to_ast_string_stable())
2266        };
2267
2268        match self {
2269            CatalogItem::Table(i) => {
2270                let mut i = i.clone();
2271                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
2272                Ok(CatalogItem::Table(i))
2273            }
2274            CatalogItem::Log(i) => Ok(CatalogItem::Log(i.clone())),
2275            CatalogItem::Source(i) => {
2276                let mut i = i.clone();
2277                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
2278                Ok(CatalogItem::Source(i))
2279            }
2280            CatalogItem::Sink(i) => {
2281                let mut i = i.clone();
2282                i.create_sql = do_rewrite(i.create_sql)?;
2283                Ok(CatalogItem::Sink(i))
2284            }
2285            CatalogItem::View(i) => {
2286                let mut i = i.clone();
2287                i.create_sql = do_rewrite(i.create_sql)?;
2288                Ok(CatalogItem::View(i))
2289            }
2290            CatalogItem::MaterializedView(i) => {
2291                let mut i = i.clone();
2292                i.create_sql = do_rewrite(i.create_sql)?;
2293                Ok(CatalogItem::MaterializedView(i))
2294            }
2295            CatalogItem::Index(i) => {
2296                let mut i = i.clone();
2297                i.create_sql = do_rewrite(i.create_sql)?;
2298                Ok(CatalogItem::Index(i))
2299            }
2300            CatalogItem::Secret(i) => {
2301                let mut i = i.clone();
2302                i.create_sql = do_rewrite(i.create_sql)?;
2303                Ok(CatalogItem::Secret(i))
2304            }
2305            CatalogItem::Connection(i) => {
2306                let mut i = i.clone();
2307                i.create_sql = do_rewrite(i.create_sql)?;
2308                Ok(CatalogItem::Connection(i))
2309            }
2310            CatalogItem::Type(i) => {
2311                let mut i = i.clone();
2312                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
2313                Ok(CatalogItem::Type(i))
2314            }
2315            CatalogItem::Func(i) => Ok(CatalogItem::Func(i.clone())),
2316            CatalogItem::MetricSink(i) => {
2317                let mut i = i.clone();
2318                i.create_sql = do_rewrite(i.create_sql)?;
2319                Ok(CatalogItem::MetricSink(i))
2320            }
2321        }
2322    }
2323
2324    /// Renames this item without changing references in its definition.
2325    pub fn rename(&self, to_item_name: String) -> CatalogItem {
2326        self.rewrite_for_rename(|stmt| {
2327            mz_sql::ast::transform::create_stmt_rename(stmt, to_item_name);
2328            Ok::<_, std::convert::Infallible>(())
2329        })
2330        .unwrap_or_else(|err| match err {})
2331    }
2332
2333    /// Rewrites references to `from` or errors if those references are ambiguous.
2334    pub fn rename_item_refs(
2335        &self,
2336        from: FullItemName,
2337        to_item_name: String,
2338    ) -> Result<CatalogItem, String> {
2339        self.rewrite_for_rename(|stmt| {
2340            mz_sql::ast::transform::create_stmt_rename_refs(stmt, from, to_item_name)
2341        })
2342    }
2343
2344    fn rewrite_for_rename<E>(
2345        &self,
2346        rewrite: impl FnOnce(&mut Statement<Raw>) -> Result<(), E>,
2347    ) -> Result<CatalogItem, E> {
2348        let do_rewrite = |create_sql: String| -> Result<String, E> {
2349            let mut create_stmt = mz_sql::parse::parse(&create_sql)
2350                .expect("invalid create sql persisted to catalog")
2351                .into_element()
2352                .ast;
2353            rewrite(&mut create_stmt)?;
2354            Ok(create_stmt.to_ast_string_stable())
2355        };
2356
2357        match self {
2358            CatalogItem::Table(i) => {
2359                let mut i = i.clone();
2360                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
2361                Ok(CatalogItem::Table(i))
2362            }
2363            CatalogItem::Log(i) => Ok(CatalogItem::Log(i.clone())),
2364            CatalogItem::Source(i) => {
2365                let mut i = i.clone();
2366                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
2367                Ok(CatalogItem::Source(i))
2368            }
2369            CatalogItem::Sink(i) => {
2370                let mut i = i.clone();
2371                i.create_sql = do_rewrite(i.create_sql)?;
2372                Ok(CatalogItem::Sink(i))
2373            }
2374            CatalogItem::View(i) => {
2375                let mut i = i.clone();
2376                i.create_sql = do_rewrite(i.create_sql)?;
2377                Ok(CatalogItem::View(i))
2378            }
2379            CatalogItem::MaterializedView(i) => {
2380                let mut i = i.clone();
2381                i.create_sql = do_rewrite(i.create_sql)?;
2382                Ok(CatalogItem::MaterializedView(i))
2383            }
2384            CatalogItem::Index(i) => {
2385                let mut i = i.clone();
2386                i.create_sql = do_rewrite(i.create_sql)?;
2387                Ok(CatalogItem::Index(i))
2388            }
2389            CatalogItem::Secret(i) => {
2390                let mut i = i.clone();
2391                i.create_sql = do_rewrite(i.create_sql)?;
2392                Ok(CatalogItem::Secret(i))
2393            }
2394            CatalogItem::Func(_) | CatalogItem::Type(_) => {
2395                unreachable!("{}s cannot be renamed", self.typ())
2396            }
2397            CatalogItem::Connection(i) => {
2398                let mut i = i.clone();
2399                i.create_sql = do_rewrite(i.create_sql)?;
2400                Ok(CatalogItem::Connection(i))
2401            }
2402            CatalogItem::MetricSink(i) => {
2403                let mut i = i.clone();
2404                i.create_sql = do_rewrite(i.create_sql)?;
2405                Ok(CatalogItem::MetricSink(i))
2406            }
2407        }
2408    }
2409
2410    /// Returns a clone of `self` with all instances of `old_id` replaced with `new_id`.
2411    pub fn replace_item_refs(&self, old_id: CatalogItemId, new_id: CatalogItemId) -> CatalogItem {
2412        let do_rewrite = |create_sql: String| -> String {
2413            let mut create_stmt = mz_sql::parse::parse(&create_sql)
2414                .expect("invalid create sql persisted to catalog")
2415                .into_element()
2416                .ast;
2417            mz_sql::ast::transform::create_stmt_replace_ids(
2418                &mut create_stmt,
2419                &[(old_id, new_id)].into(),
2420            );
2421            create_stmt.to_ast_string_stable()
2422        };
2423
2424        match self {
2425            CatalogItem::Table(i) => {
2426                let mut i = i.clone();
2427                i.create_sql = i.create_sql.map(do_rewrite);
2428                CatalogItem::Table(i)
2429            }
2430            CatalogItem::Log(i) => CatalogItem::Log(i.clone()),
2431            CatalogItem::Source(i) => {
2432                let mut i = i.clone();
2433                i.create_sql = i.create_sql.map(do_rewrite);
2434                CatalogItem::Source(i)
2435            }
2436            CatalogItem::Sink(i) => {
2437                let mut i = i.clone();
2438                i.create_sql = do_rewrite(i.create_sql);
2439                CatalogItem::Sink(i)
2440            }
2441            CatalogItem::View(i) => {
2442                let mut i = i.clone();
2443                i.create_sql = do_rewrite(i.create_sql);
2444                CatalogItem::View(i)
2445            }
2446            CatalogItem::MaterializedView(i) => {
2447                let mut i = i.clone();
2448                i.create_sql = do_rewrite(i.create_sql);
2449                CatalogItem::MaterializedView(i)
2450            }
2451            CatalogItem::Index(i) => {
2452                let mut i = i.clone();
2453                i.create_sql = do_rewrite(i.create_sql);
2454                CatalogItem::Index(i)
2455            }
2456            CatalogItem::Secret(i) => {
2457                let mut i = i.clone();
2458                i.create_sql = do_rewrite(i.create_sql);
2459                CatalogItem::Secret(i)
2460            }
2461            CatalogItem::Func(_) | CatalogItem::Type(_) => {
2462                unreachable!("references of {}s cannot be replaced", self.typ())
2463            }
2464            CatalogItem::Connection(i) => {
2465                let mut i = i.clone();
2466                i.create_sql = do_rewrite(i.create_sql);
2467                CatalogItem::Connection(i)
2468            }
2469            CatalogItem::MetricSink(i) => {
2470                let mut i = i.clone();
2471                i.create_sql = do_rewrite(i.create_sql);
2472                CatalogItem::MetricSink(i)
2473            }
2474        }
2475    }
2476    /// Updates the retain history for an item. Returns the previous retain history value. Returns
2477    /// an error if this item does not support retain history.
2478    pub fn update_retain_history(
2479        &mut self,
2480        value: Option<Value>,
2481        window: CompactionWindow,
2482    ) -> Result<Option<WithOptionValue<Raw>>, ()> {
2483        let update = |mut ast: &mut Statement<Raw>| {
2484            // Each statement type has unique option types. This macro handles them commonly.
2485            macro_rules! update_retain_history {
2486                ( $stmt:ident, $opt:ident, $name:ident ) => {{
2487                    // Replace or add the option.
2488                    let pos = $stmt
2489                        .with_options
2490                        .iter()
2491                        // In case there are ever multiple, look for the last one.
2492                        .rposition(|o| o.name == mz_sql_parser::ast::$name::RetainHistory);
2493                    if let Some(value) = value {
2494                        let next = mz_sql_parser::ast::$opt {
2495                            name: mz_sql_parser::ast::$name::RetainHistory,
2496                            value: Some(WithOptionValue::RetainHistoryFor(value)),
2497                        };
2498                        if let Some(idx) = pos {
2499                            let previous = $stmt.with_options[idx].clone();
2500                            $stmt.with_options[idx] = next;
2501                            previous.value
2502                        } else {
2503                            $stmt.with_options.push(next);
2504                            None
2505                        }
2506                    } else {
2507                        if let Some(idx) = pos {
2508                            $stmt.with_options.swap_remove(idx).value
2509                        } else {
2510                            None
2511                        }
2512                    }
2513                }};
2514            }
2515            let previous = match &mut ast {
2516                Statement::CreateTable(stmt) => {
2517                    update_retain_history!(stmt, TableOption, TableOptionName)
2518                }
2519                Statement::CreateIndex(stmt) => {
2520                    update_retain_history!(stmt, IndexOption, IndexOptionName)
2521                }
2522                Statement::CreateSource(stmt) => {
2523                    update_retain_history!(stmt, CreateSourceOption, CreateSourceOptionName)
2524                }
2525                Statement::CreateMaterializedView(stmt) => {
2526                    update_retain_history!(stmt, MaterializedViewOption, MaterializedViewOptionName)
2527                }
2528                _ => {
2529                    return Err(());
2530                }
2531            };
2532            Ok(previous)
2533        };
2534
2535        let res = self.update_sql(update)?;
2536        let cw = self
2537            .custom_logical_compaction_window_mut()
2538            .expect("item must have compaction window");
2539        *cw = Some(window);
2540        Ok(res)
2541    }
2542
2543    /// Updates the timestamp interval for a source. Returns the previous timestamp interval
2544    /// value, if any. Returns an error if this item is not a source.
2545    pub fn update_timestamp_interval(
2546        &mut self,
2547        value: Option<Value>,
2548        interval: Duration,
2549    ) -> Result<Option<WithOptionValue<Raw>>, ()> {
2550        let update = |ast: &mut Statement<Raw>| match ast {
2551            Statement::CreateSource(stmt) => {
2552                let pos = stmt.with_options.iter().rposition(|o| {
2553                    o.name == mz_sql_parser::ast::CreateSourceOptionName::TimestampInterval
2554                });
2555                let previous = if let Some(value) = value {
2556                    let next = mz_sql_parser::ast::CreateSourceOption {
2557                        name: mz_sql_parser::ast::CreateSourceOptionName::TimestampInterval,
2558                        value: Some(WithOptionValue::Value(value)),
2559                    };
2560                    if let Some(idx) = pos {
2561                        let previous = stmt.with_options[idx].clone();
2562                        stmt.with_options[idx] = next;
2563                        previous.value
2564                    } else {
2565                        stmt.with_options.push(next);
2566                        None
2567                    }
2568                } else if let Some(idx) = pos {
2569                    stmt.with_options.swap_remove(idx).value
2570                } else {
2571                    None
2572                };
2573                Ok(previous)
2574            }
2575            _ => Err(()),
2576        };
2577
2578        let previous = self.update_sql(update)?;
2579
2580        // Update the in-memory SourceDesc timestamp_interval.
2581        match self {
2582            CatalogItem::Source(source) => {
2583                match &mut source.data_source {
2584                    DataSourceDesc::Ingestion { desc, .. }
2585                    | DataSourceDesc::OldSyntaxIngestion { desc, .. } => {
2586                        desc.timestamp_interval = interval;
2587                    }
2588                    _ => return Err(()),
2589                }
2590                Ok(previous)
2591            }
2592            _ => Err(()),
2593        }
2594    }
2595
2596    pub fn add_column(
2597        &mut self,
2598        name: ColumnName,
2599        typ: SqlColumnType,
2600        sql: RawDataType,
2601    ) -> Result<RelationVersion, PlanError> {
2602        let CatalogItem::Table(table) = self else {
2603            return Err(PlanError::Unsupported {
2604                feature: "adding columns to a non-Table".to_string(),
2605                discussion_no: None,
2606            });
2607        };
2608        let next_version = table.desc.add_column(name.clone(), typ);
2609
2610        let update = |mut ast: &mut Statement<Raw>| match &mut ast {
2611            Statement::CreateTable(stmt) => {
2612                let version = ColumnOptionDef {
2613                    name: None,
2614                    option: ColumnOption::Versioned {
2615                        action: ColumnVersioned::Added,
2616                        version: mz_sql::normalize::ast_version(next_version),
2617                    },
2618                };
2619                let column = ColumnDef {
2620                    name: mz_sql::normalize::column_name_ident(&name),
2621                    data_type: sql,
2622                    collation: None,
2623                    options: vec![version],
2624                };
2625                stmt.columns.push(column);
2626                Ok(())
2627            }
2628            _ => Err(()),
2629        };
2630
2631        self.update_sql(update)
2632            .map_err(|()| PlanError::Unstructured("expected CREATE TABLE statement".to_string()))?;
2633        Ok(next_version)
2634    }
2635
2636    /// Updates the create_sql field of this item. Returns an error if this is a builtin item,
2637    /// otherwise returns f's result.
2638    pub fn update_sql<F, T>(&mut self, f: F) -> Result<T, ()>
2639    where
2640        F: FnOnce(&mut Statement<Raw>) -> Result<T, ()>,
2641    {
2642        let create_sql = match self {
2643            CatalogItem::Table(Table { create_sql, .. })
2644            | CatalogItem::Type(Type { create_sql, .. })
2645            | CatalogItem::Source(Source { create_sql, .. }) => create_sql.as_mut(),
2646            CatalogItem::Sink(Sink { create_sql, .. })
2647            | CatalogItem::View(View { create_sql, .. })
2648            | CatalogItem::MaterializedView(MaterializedView { create_sql, .. })
2649            | CatalogItem::Index(Index { create_sql, .. })
2650            | CatalogItem::Secret(Secret { create_sql, .. })
2651            | CatalogItem::Connection(Connection { create_sql, .. })
2652            | CatalogItem::MetricSink(MetricSink { create_sql, .. }) => Some(create_sql),
2653            CatalogItem::Func(_) | CatalogItem::Log(_) => None,
2654        };
2655        let Some(create_sql) = create_sql else {
2656            return Err(());
2657        };
2658        let mut ast = mz_sql_parser::parser::parse_statements(create_sql)
2659            .expect("non-system items must be parseable")
2660            .into_element()
2661            .ast;
2662        debug!("rewrite: {}", ast.to_ast_string_redacted());
2663        let t = f(&mut ast)?;
2664        *create_sql = ast.to_ast_string_stable();
2665        debug!("rewrote: {}", ast.to_ast_string_redacted());
2666        Ok(t)
2667    }
2668
2669    /// If the object is considered a "compute object"
2670    /// (i.e., it is managed by the compute controller),
2671    /// this function returns its cluster ID. Otherwise, it returns nothing.
2672    ///
2673    /// This function differs from `cluster_id` because while all
2674    /// compute objects run on a cluster, the converse is not true.
2675    pub fn is_compute_object_on_cluster(&self) -> Option<ClusterId> {
2676        match self {
2677            CatalogItem::Index(index) => Some(index.cluster_id),
2678            CatalogItem::MetricSink(metric_sink) => Some(metric_sink.cluster_id),
2679            CatalogItem::Table(_)
2680            | CatalogItem::Source(_)
2681            | CatalogItem::Log(_)
2682            | CatalogItem::View(_)
2683            | CatalogItem::MaterializedView(_)
2684            | CatalogItem::Sink(_)
2685            | CatalogItem::Type(_)
2686            | CatalogItem::Func(_)
2687            | CatalogItem::Secret(_)
2688            | CatalogItem::Connection(_) => None,
2689        }
2690    }
2691
2692    /// Whether this item runs a dataflow on its cluster's replicas and so has
2693    /// hydration state: an index, materialized view, sink, or ingestion source.
2694    /// Non-ingestion sources (webhooks, ingestion exports) are bound to a
2695    /// cluster but run no dataflow on any replica.
2696    ///
2697    /// NOTE: `Coordinator::cluster_has_hydratable_objects` routes a cluster onto
2698    /// the hydration-aware scheduling and reconfiguration path off this answer,
2699    /// so an item that ships no dataflow must answer `false` even where the
2700    /// per-replica hydration check would resolve vacuously.
2701    pub fn is_hydratable(&self) -> bool {
2702        match self {
2703            CatalogItem::Index(_)
2704            | CatalogItem::MaterializedView(_)
2705            | CatalogItem::Sink(_)
2706            | CatalogItem::MetricSink(_) => true,
2707            CatalogItem::Source(source) => matches!(
2708                source.data_source,
2709                DataSourceDesc::Ingestion { .. } | DataSourceDesc::OldSyntaxIngestion { .. }
2710            ),
2711            CatalogItem::Table(_)
2712            | CatalogItem::Log(_)
2713            | CatalogItem::View(_)
2714            | CatalogItem::Type(_)
2715            | CatalogItem::Func(_)
2716            | CatalogItem::Secret(_)
2717            | CatalogItem::Connection(_) => false,
2718        }
2719    }
2720
2721    pub fn cluster_id(&self) -> Option<ClusterId> {
2722        match self {
2723            CatalogItem::MaterializedView(mv) => Some(mv.cluster_id),
2724            CatalogItem::Index(index) => Some(index.cluster_id),
2725            CatalogItem::MetricSink(metric_sink) => Some(metric_sink.cluster_id),
2726            CatalogItem::Source(source) => match &source.data_source {
2727                DataSourceDesc::Ingestion { cluster_id, .. }
2728                | DataSourceDesc::OldSyntaxIngestion { cluster_id, .. } => Some(*cluster_id),
2729                // This is somewhat of a lie because the export runs on the same
2730                // cluster as its ingestion but we don't yet have a way of
2731                // cross-referencing the items
2732                DataSourceDesc::IngestionExport { .. } => None,
2733                DataSourceDesc::Webhook { cluster_id, .. } => Some(*cluster_id),
2734                DataSourceDesc::Introspection(_)
2735                | DataSourceDesc::Progress
2736                | DataSourceDesc::Catalog => None,
2737            },
2738            CatalogItem::Sink(sink) => Some(sink.cluster_id),
2739            CatalogItem::Table(_)
2740            | CatalogItem::Log(_)
2741            | CatalogItem::View(_)
2742            | CatalogItem::Type(_)
2743            | CatalogItem::Func(_)
2744            | CatalogItem::Secret(_)
2745            | CatalogItem::Connection(_) => None,
2746        }
2747    }
2748
2749    /// The custom compaction window, if any has been set. This does not reflect any propagated
2750    /// compaction window (i.e., source -> subsource).
2751    pub fn custom_logical_compaction_window(&self) -> Option<CompactionWindow> {
2752        match self {
2753            CatalogItem::Table(table) => table.custom_logical_compaction_window,
2754            CatalogItem::Source(source) => source.custom_logical_compaction_window,
2755            CatalogItem::Index(index) => index.custom_logical_compaction_window,
2756            CatalogItem::MaterializedView(mview) => mview.custom_logical_compaction_window,
2757            CatalogItem::Log(_)
2758            | CatalogItem::View(_)
2759            | CatalogItem::Sink(_)
2760            | CatalogItem::Type(_)
2761            | CatalogItem::Func(_)
2762            | CatalogItem::Secret(_)
2763            | CatalogItem::Connection(_)
2764            | CatalogItem::MetricSink(_) => None,
2765        }
2766    }
2767
2768    /// Mutable access to the custom compaction window, or None if this type does not support custom
2769    /// compaction windows. This does not reflect any propagated compaction window (i.e., source ->
2770    /// subsource).
2771    pub fn custom_logical_compaction_window_mut(
2772        &mut self,
2773    ) -> Option<&mut Option<CompactionWindow>> {
2774        let cw = match self {
2775            CatalogItem::Table(table) => &mut table.custom_logical_compaction_window,
2776            CatalogItem::Source(source) => &mut source.custom_logical_compaction_window,
2777            CatalogItem::Index(index) => &mut index.custom_logical_compaction_window,
2778            CatalogItem::MaterializedView(mview) => &mut mview.custom_logical_compaction_window,
2779            CatalogItem::Log(_)
2780            | CatalogItem::View(_)
2781            | CatalogItem::Sink(_)
2782            | CatalogItem::Type(_)
2783            | CatalogItem::Func(_)
2784            | CatalogItem::Secret(_)
2785            | CatalogItem::Connection(_)
2786            | CatalogItem::MetricSink(_) => return None,
2787        };
2788        Some(cw)
2789    }
2790
2791    /// The initial compaction window, for objects that have one; that is, tables, sources, indexes,
2792    /// and MVs. This does not reflect any propagated compaction window (i.e., source -> subsource).
2793    ///
2794    /// If `custom_logical_compaction_window()` returns something, use that.  Otherwise, use a
2795    /// sensible default (currently 1s).
2796    ///
2797    /// For objects that do not have the concept of compaction window, return None.
2798    pub fn initial_logical_compaction_window(&self) -> Option<CompactionWindow> {
2799        let custom_logical_compaction_window = match self {
2800            CatalogItem::Table(_)
2801            | CatalogItem::Source(_)
2802            | CatalogItem::Index(_)
2803            | CatalogItem::MaterializedView(_) => self.custom_logical_compaction_window(),
2804            CatalogItem::Log(_)
2805            | CatalogItem::View(_)
2806            | CatalogItem::Sink(_)
2807            | CatalogItem::Type(_)
2808            | CatalogItem::Func(_)
2809            | CatalogItem::Secret(_)
2810            | CatalogItem::Connection(_)
2811            | CatalogItem::MetricSink(_) => return None,
2812        };
2813        Some(custom_logical_compaction_window.unwrap_or(CompactionWindow::Default))
2814    }
2815
2816    /// Whether the item's logical compaction window
2817    /// is controlled by the METRICS_RETENTION
2818    /// system var.
2819    pub fn is_retained_metrics_object(&self) -> bool {
2820        match self {
2821            CatalogItem::Table(table) => table.is_retained_metrics_object,
2822            CatalogItem::Source(source) => source.is_retained_metrics_object,
2823            CatalogItem::Index(index) => index.is_retained_metrics_object,
2824            CatalogItem::Log(_)
2825            | CatalogItem::View(_)
2826            | CatalogItem::MaterializedView(_)
2827            | CatalogItem::Sink(_)
2828            | CatalogItem::Type(_)
2829            | CatalogItem::Func(_)
2830            | CatalogItem::Secret(_)
2831            | CatalogItem::Connection(_)
2832            | CatalogItem::MetricSink(_) => false,
2833        }
2834    }
2835
2836    pub fn to_serialized(&self) -> (String, GlobalId, BTreeMap<RelationVersion, GlobalId>) {
2837        match self {
2838            CatalogItem::Table(table) => {
2839                let create_sql = table
2840                    .create_sql
2841                    .clone()
2842                    .expect("builtin tables cannot be serialized");
2843                let mut collections = table.collections.clone();
2844                let global_id = collections
2845                    .remove(&RelationVersion::root())
2846                    .expect("at least one version");
2847                (create_sql, global_id, collections)
2848            }
2849            CatalogItem::Log(_) => unreachable!("builtin logs cannot be serialized"),
2850            CatalogItem::Source(source) => {
2851                assert!(
2852                    !matches!(source.data_source, DataSourceDesc::Introspection(_)),
2853                    "cannot serialize introspection/builtin sources",
2854                );
2855                let create_sql = source
2856                    .create_sql
2857                    .clone()
2858                    .expect("builtin sources cannot be serialized");
2859                (create_sql, source.global_id, BTreeMap::new())
2860            }
2861            CatalogItem::View(view) => (view.create_sql.clone(), view.global_id, BTreeMap::new()),
2862            CatalogItem::MaterializedView(mview) => {
2863                let mut collections = mview.collections.clone();
2864                let global_id = collections
2865                    .remove(&RelationVersion::root())
2866                    .expect("at least one version");
2867                (mview.create_sql.clone(), global_id, collections)
2868            }
2869            CatalogItem::Index(index) => {
2870                (index.create_sql.clone(), index.global_id, BTreeMap::new())
2871            }
2872            CatalogItem::Sink(sink) => (sink.create_sql.clone(), sink.global_id, BTreeMap::new()),
2873            CatalogItem::Type(typ) => {
2874                let create_sql = typ
2875                    .create_sql
2876                    .clone()
2877                    .expect("builtin types cannot be serialized");
2878                (create_sql, typ.global_id, BTreeMap::new())
2879            }
2880            CatalogItem::Secret(secret) => {
2881                (secret.create_sql.clone(), secret.global_id, BTreeMap::new())
2882            }
2883            CatalogItem::Connection(connection) => (
2884                connection.create_sql.clone(),
2885                connection.global_id,
2886                BTreeMap::new(),
2887            ),
2888            CatalogItem::Func(_) => unreachable!("cannot serialize functions yet"),
2889            CatalogItem::MetricSink(ms) => (ms.create_sql.clone(), ms.global_id, BTreeMap::new()),
2890        }
2891    }
2892
2893    pub fn into_serialized(self) -> (String, GlobalId, BTreeMap<RelationVersion, GlobalId>) {
2894        match self {
2895            CatalogItem::Table(mut table) => {
2896                let create_sql = table
2897                    .create_sql
2898                    .expect("builtin tables cannot be serialized");
2899                let global_id = table
2900                    .collections
2901                    .remove(&RelationVersion::root())
2902                    .expect("at least one version");
2903                (create_sql, global_id, table.collections)
2904            }
2905            CatalogItem::Log(_) => unreachable!("builtin logs cannot be serialized"),
2906            CatalogItem::Source(source) => {
2907                assert!(
2908                    !matches!(source.data_source, DataSourceDesc::Introspection(_)),
2909                    "cannot serialize introspection/builtin sources",
2910                );
2911                let create_sql = source
2912                    .create_sql
2913                    .expect("builtin sources cannot be serialized");
2914                (create_sql, source.global_id, BTreeMap::new())
2915            }
2916            CatalogItem::View(view) => (view.create_sql, view.global_id, BTreeMap::new()),
2917            CatalogItem::MaterializedView(mut mview) => {
2918                let global_id = mview
2919                    .collections
2920                    .remove(&RelationVersion::root())
2921                    .expect("at least one version");
2922                (mview.create_sql, global_id, mview.collections)
2923            }
2924            CatalogItem::Index(index) => (index.create_sql, index.global_id, BTreeMap::new()),
2925            CatalogItem::Sink(sink) => (sink.create_sql, sink.global_id, BTreeMap::new()),
2926            CatalogItem::Type(typ) => {
2927                let create_sql = typ.create_sql.expect("builtin types cannot be serialized");
2928                (create_sql, typ.global_id, BTreeMap::new())
2929            }
2930            CatalogItem::Secret(secret) => (secret.create_sql, secret.global_id, BTreeMap::new()),
2931            CatalogItem::Connection(connection) => {
2932                (connection.create_sql, connection.global_id, BTreeMap::new())
2933            }
2934            CatalogItem::Func(_) => unreachable!("cannot serialize functions yet"),
2935            CatalogItem::MetricSink(ms) => (ms.create_sql, ms.global_id, BTreeMap::new()),
2936        }
2937    }
2938
2939    /// Returns a global ID for a specific version selector. Returns `None` if the item does
2940    /// not have versions or if the version does not exist.
2941    pub fn global_id_for_version(&self, version: RelationVersionSelector) -> Option<GlobalId> {
2942        let collections = match self {
2943            CatalogItem::MaterializedView(mv) => &mv.collections,
2944            CatalogItem::Table(table) => &table.collections,
2945            CatalogItem::Source(source) => return Some(source.global_id),
2946            CatalogItem::Log(log) => return Some(log.global_id),
2947            CatalogItem::View(view) => return Some(view.global_id),
2948            CatalogItem::Sink(sink) => return Some(sink.global_id),
2949            CatalogItem::Index(index) => return Some(index.global_id),
2950            CatalogItem::Type(ty) => return Some(ty.global_id),
2951            CatalogItem::Func(func) => return Some(func.global_id),
2952            CatalogItem::Secret(secret) => return Some(secret.global_id),
2953            CatalogItem::Connection(conn) => return Some(conn.global_id),
2954            CatalogItem::MetricSink(metric_sink) => return Some(metric_sink.global_id),
2955        };
2956        match version {
2957            RelationVersionSelector::Latest => collections.values().last().copied(),
2958            RelationVersionSelector::Specific(version) => collections.get(&version).copied(),
2959        }
2960    }
2961}
2962
2963impl CatalogEntry {
2964    /// Reports the latest [`RelationDesc`] of the rows produced by this [`CatalogEntry`], if it
2965    /// produces rows.
2966    pub fn relation_desc_latest(&self) -> Option<Cow<'_, RelationDesc>> {
2967        self.item.relation_desc(RelationVersionSelector::Latest)
2968    }
2969
2970    /// Reports if the item has columns.
2971    pub fn has_columns(&self) -> bool {
2972        match self.item() {
2973            CatalogItem::Type(Type { details, .. }) => {
2974                matches!(details.typ, CatalogType::Record { .. })
2975            }
2976            _ => self.relation_desc_latest().is_some(),
2977        }
2978    }
2979
2980    /// Returns the [`mz_sql::func::Func`] associated with this `CatalogEntry`.
2981    pub fn func(&self) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
2982        self.item.func(self)
2983    }
2984
2985    /// Returns the inner [`Index`] if this entry is an index, else `None`.
2986    pub fn index(&self) -> Option<&Index> {
2987        match self.item() {
2988            CatalogItem::Index(idx) => Some(idx),
2989            _ => None,
2990        }
2991    }
2992
2993    /// Returns the inner [`MaterializedView`] if this entry is a materialized view, else `None`.
2994    pub fn materialized_view(&self) -> Option<&MaterializedView> {
2995        match self.item() {
2996            CatalogItem::MaterializedView(mv) => Some(mv),
2997            _ => None,
2998        }
2999    }
3000
3001    /// Returns the inner [`Table`] if this entry is a table, else `None`.
3002    pub fn table(&self) -> Option<&Table> {
3003        match self.item() {
3004            CatalogItem::Table(tbl) => Some(tbl),
3005            _ => None,
3006        }
3007    }
3008
3009    /// Returns the inner [`Source`] if this entry is a source, else `None`.
3010    pub fn source(&self) -> Option<&Source> {
3011        match self.item() {
3012            CatalogItem::Source(src) => Some(src),
3013            _ => None,
3014        }
3015    }
3016
3017    /// Returns the inner [`Sink`] if this entry is a sink, else `None`.
3018    pub fn sink(&self) -> Option<&Sink> {
3019        match self.item() {
3020            CatalogItem::Sink(sink) => Some(sink),
3021            _ => None,
3022        }
3023    }
3024
3025    /// Returns the inner [`Secret`] if this entry is a secret, else `None`.
3026    pub fn secret(&self) -> Option<&Secret> {
3027        match self.item() {
3028            CatalogItem::Secret(secret) => Some(secret),
3029            _ => None,
3030        }
3031    }
3032
3033    pub fn connection(&self) -> Result<&Connection, SqlCatalogError> {
3034        match self.item() {
3035            CatalogItem::Connection(connection) => Ok(connection),
3036            _ => {
3037                let db_name = match self.name().qualifiers.database_spec {
3038                    ResolvedDatabaseSpecifier::Ambient => "".to_string(),
3039                    ResolvedDatabaseSpecifier::Id(id) => format!("{id}."),
3040                };
3041                Err(SqlCatalogError::UnknownConnection(format!(
3042                    "{}{}.{}",
3043                    db_name,
3044                    self.name().qualifiers.schema_spec,
3045                    self.name().item
3046                )))
3047            }
3048        }
3049    }
3050
3051    /// Returns the [`mz_storage_types::sources::SourceDesc`] associated with
3052    /// this `CatalogEntry`, if any.
3053    pub fn source_desc(
3054        &self,
3055    ) -> Result<Option<&SourceDesc<ReferencedConnection>>, SqlCatalogError> {
3056        self.item.source_desc(self)
3057    }
3058
3059    /// Reports whether this catalog entry is a connection.
3060    pub fn is_connection(&self) -> bool {
3061        matches!(self.item(), CatalogItem::Connection(_))
3062    }
3063
3064    /// Reports whether this catalog entry is a table.
3065    pub fn is_table(&self) -> bool {
3066        matches!(self.item(), CatalogItem::Table(_))
3067    }
3068
3069    /// Reports whether this catalog entry is a source. Note that this includes
3070    /// subsources.
3071    pub fn is_source(&self) -> bool {
3072        matches!(self.item(), CatalogItem::Source(_))
3073    }
3074
3075    /// Reports whether this catalog entry is a subsource and, if it is, the
3076    /// ingestion it is an export of, as well as the item it exports.
3077    pub fn subsource_details(
3078        &self,
3079    ) -> Option<(CatalogItemId, &UnresolvedItemName, &SourceExportDetails)> {
3080        match &self.item() {
3081            CatalogItem::Source(source) => match &source.data_source {
3082                DataSourceDesc::IngestionExport {
3083                    ingestion_id,
3084                    external_reference,
3085                    details,
3086                    data_config: _,
3087                } => Some((*ingestion_id, external_reference, details)),
3088                _ => None,
3089            },
3090            _ => None,
3091        }
3092    }
3093
3094    /// Reports whether this catalog entry is a source export and, if it is, the
3095    /// ingestion it is an export of, as well as the item it exports.
3096    pub fn source_export_details(
3097        &self,
3098    ) -> Option<(
3099        CatalogItemId,
3100        &UnresolvedItemName,
3101        &SourceExportDetails,
3102        &SourceExportDataConfig<ReferencedConnection>,
3103    )> {
3104        match &self.item() {
3105            CatalogItem::Source(source) => match &source.data_source {
3106                DataSourceDesc::IngestionExport {
3107                    ingestion_id,
3108                    external_reference,
3109                    details,
3110                    data_config,
3111                } => Some((*ingestion_id, external_reference, details, data_config)),
3112                _ => None,
3113            },
3114            CatalogItem::Table(table) => match &table.data_source {
3115                TableDataSource::DataSource {
3116                    desc:
3117                        DataSourceDesc::IngestionExport {
3118                            ingestion_id,
3119                            external_reference,
3120                            details,
3121                            data_config,
3122                        },
3123                    timeline: _,
3124                } => Some((*ingestion_id, external_reference, details, data_config)),
3125                _ => None,
3126            },
3127            _ => None,
3128        }
3129    }
3130
3131    /// Reports whether this catalog entry is a progress source.
3132    pub fn is_progress_source(&self) -> bool {
3133        self.item().is_progress_source()
3134    }
3135
3136    /// Returns the `GlobalId` of all of this entry's progress ID.
3137    pub fn progress_id(&self) -> Option<CatalogItemId> {
3138        match &self.item() {
3139            CatalogItem::Source(source) => match &source.data_source {
3140                DataSourceDesc::Ingestion { .. } => Some(self.id),
3141                DataSourceDesc::OldSyntaxIngestion {
3142                    progress_subsource, ..
3143                } => Some(*progress_subsource),
3144                DataSourceDesc::IngestionExport { .. }
3145                | DataSourceDesc::Introspection(_)
3146                | DataSourceDesc::Progress
3147                | DataSourceDesc::Webhook { .. }
3148                | DataSourceDesc::Catalog => None,
3149            },
3150            CatalogItem::Table(_)
3151            | CatalogItem::Log(_)
3152            | CatalogItem::View(_)
3153            | CatalogItem::MaterializedView(_)
3154            | CatalogItem::Sink(_)
3155            | CatalogItem::Index(_)
3156            | CatalogItem::Type(_)
3157            | CatalogItem::Func(_)
3158            | CatalogItem::Secret(_)
3159            | CatalogItem::Connection(_)
3160            | CatalogItem::MetricSink(_) => None,
3161        }
3162    }
3163
3164    /// Reports whether this catalog entry is a sink.
3165    pub fn is_sink(&self) -> bool {
3166        matches!(self.item(), CatalogItem::Sink(_))
3167    }
3168
3169    /// Reports whether this catalog entry is a materialized view.
3170    pub fn is_materialized_view(&self) -> bool {
3171        matches!(self.item(), CatalogItem::MaterializedView(_))
3172    }
3173
3174    /// Reports whether this catalog entry is a view.
3175    pub fn is_view(&self) -> bool {
3176        matches!(self.item(), CatalogItem::View(_))
3177    }
3178
3179    /// Reports whether this catalog entry is a secret.
3180    pub fn is_secret(&self) -> bool {
3181        matches!(self.item(), CatalogItem::Secret(_))
3182    }
3183
3184    /// Reports whether this catalog entry is an introspection source.
3185    pub fn is_introspection_source(&self) -> bool {
3186        matches!(self.item(), CatalogItem::Log(_))
3187    }
3188
3189    /// Reports whether this catalog entry is an index.
3190    pub fn is_index(&self) -> bool {
3191        matches!(self.item(), CatalogItem::Index(_))
3192    }
3193
3194    /// Reports whether this catalog entry is a metric sink.
3195    pub fn is_metric_sink(&self) -> bool {
3196        matches!(self.item(), CatalogItem::MetricSink(_))
3197    }
3198
3199    /// Reports whether this catalog entry can be treated as a relation, it can produce rows.
3200    pub fn is_relation(&self) -> bool {
3201        mz_sql::catalog::ObjectType::from(self.item_type()).is_relation()
3202    }
3203
3204    /// Collects the identifiers of the objects that were encountered when
3205    /// resolving names in the item's DDL statement.
3206    pub fn references(&self) -> &ResolvedIds {
3207        self.item.references()
3208    }
3209
3210    /// Collects the identifiers of the objects used by this [`CatalogEntry`].
3211    ///
3212    /// Like [`CatalogEntry::references()`] but also includes objects that are not directly
3213    /// referenced. For example this will include any catalog objects used to implement functions
3214    /// and casts in the item.
3215    pub fn uses(&self) -> BTreeSet<CatalogItemId> {
3216        self.item.uses()
3217    }
3218
3219    /// Returns the `CatalogItem` associated with this catalog entry.
3220    pub fn item(&self) -> &CatalogItem {
3221        &self.item
3222    }
3223
3224    /// Returns a mutable reference to the `CatalogItem` associated with this
3225    /// catalog entry.
3226    pub fn item_mut(&mut self) -> &mut CatalogItem {
3227        &mut self.item
3228    }
3229
3230    /// Returns the [`CatalogItemId`] of this catalog entry.
3231    pub fn id(&self) -> CatalogItemId {
3232        self.id
3233    }
3234
3235    /// Returns all of the [`GlobalId`]s associated with this item.
3236    pub fn global_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
3237        self.item().global_ids()
3238    }
3239
3240    pub fn latest_global_id(&self) -> GlobalId {
3241        self.item().latest_global_id()
3242    }
3243
3244    /// Returns the OID of this catalog entry.
3245    pub fn oid(&self) -> u32 {
3246        self.oid
3247    }
3248
3249    /// Returns the fully qualified name of this catalog entry.
3250    pub fn name(&self) -> &QualifiedItemName {
3251        &self.name
3252    }
3253
3254    /// Returns the identifiers of the dataflows that are directly referenced by this dataflow.
3255    pub fn referenced_by(&self) -> &[CatalogItemId] {
3256        &self.referenced_by
3257    }
3258
3259    /// Returns the identifiers of the dataflows that depend upon this dataflow.
3260    pub fn used_by(&self) -> &[CatalogItemId] {
3261        &self.used_by
3262    }
3263
3264    /// Returns the connection ID that this item belongs to, if this item is
3265    /// temporary.
3266    pub fn conn_id(&self) -> Option<&ConnectionId> {
3267        self.item.conn_id()
3268    }
3269
3270    /// Returns the role ID of the entry owner.
3271    pub fn owner_id(&self) -> &RoleId {
3272        &self.owner_id
3273    }
3274
3275    /// Returns the privileges of the entry.
3276    pub fn privileges(&self) -> &PrivilegeMap {
3277        &self.privileges
3278    }
3279
3280    /// Returns the comment object ID for this entry.
3281    pub fn comment_object_id(&self) -> CommentObjectId {
3282        use CatalogItemType::*;
3283        match self.item_type() {
3284            Table => CommentObjectId::Table(self.id),
3285            Source => CommentObjectId::Source(self.id),
3286            Sink => CommentObjectId::Sink(self.id),
3287            View => CommentObjectId::View(self.id),
3288            MaterializedView => CommentObjectId::MaterializedView(self.id),
3289            Index => CommentObjectId::Index(self.id),
3290            Func => CommentObjectId::Func(self.id),
3291            Connection => CommentObjectId::Connection(self.id),
3292            Type => CommentObjectId::Type(self.id),
3293            Secret => CommentObjectId::Secret(self.id),
3294            MetricSink => CommentObjectId::MetricSink(self.id),
3295        }
3296    }
3297}
3298
3299#[derive(Debug, Clone, Default)]
3300pub struct CommentsMap {
3301    map: BTreeMap<CommentObjectId, BTreeMap<Option<usize>, String>>,
3302}
3303
3304impl CommentsMap {
3305    pub fn update_comment(
3306        &mut self,
3307        object_id: CommentObjectId,
3308        sub_component: Option<usize>,
3309        comment: Option<String>,
3310    ) -> Option<String> {
3311        let object_comments = self.map.entry(object_id).or_default();
3312
3313        // Either replace the existing comment, or remove it if comment is None/NULL.
3314        let (empty, prev) = if let Some(comment) = comment {
3315            let prev = object_comments.insert(sub_component, comment);
3316            (false, prev)
3317        } else {
3318            let prev = object_comments.remove(&sub_component);
3319            (object_comments.is_empty(), prev)
3320        };
3321
3322        // Cleanup entries that are now empty.
3323        if empty {
3324            self.map.remove(&object_id);
3325        }
3326
3327        // Return the previous comment, if there was one, for easy removal.
3328        prev
3329    }
3330
3331    /// Remove all comments for `object_id` from the map.
3332    ///
3333    /// Generally there is one comment for a given [`CommentObjectId`], but in the case of
3334    /// relations you can also have comments on the individual columns. Dropping the comments for a
3335    /// relation will also drop all of the comments on any columns.
3336    pub fn drop_comments(
3337        &mut self,
3338        object_ids: &BTreeSet<CommentObjectId>,
3339    ) -> Vec<(CommentObjectId, Option<usize>, String)> {
3340        let mut removed_comments = Vec::new();
3341
3342        for object_id in object_ids {
3343            if let Some(comments) = self.map.remove(object_id) {
3344                let removed = comments
3345                    .into_iter()
3346                    .map(|(sub_comp, comment)| (object_id.clone(), sub_comp, comment));
3347                removed_comments.extend(removed);
3348            }
3349        }
3350
3351        removed_comments
3352    }
3353
3354    pub fn iter(&self) -> impl Iterator<Item = (CommentObjectId, Option<usize>, &str)> {
3355        self.map
3356            .iter()
3357            .map(|(id, comments)| {
3358                comments
3359                    .iter()
3360                    .map(|(pos, comment)| (*id, *pos, comment.as_str()))
3361            })
3362            .flatten()
3363    }
3364
3365    pub fn get_object_comments(
3366        &self,
3367        object_id: CommentObjectId,
3368    ) -> Option<&BTreeMap<Option<usize>, String>> {
3369        self.map.get(&object_id)
3370    }
3371}
3372
3373impl Serialize for CommentsMap {
3374    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3375    where
3376        S: serde::Serializer,
3377    {
3378        let comment_count = self
3379            .map
3380            .iter()
3381            .map(|(_object_id, comments)| comments.len())
3382            .sum();
3383
3384        let mut seq = serializer.serialize_seq(Some(comment_count))?;
3385        for (object_id, sub) in &self.map {
3386            for (sub_component, comment) in sub {
3387                seq.serialize_element(&(
3388                    format!("{object_id:?}"),
3389                    format!("{sub_component:?}"),
3390                    comment,
3391                ))?;
3392            }
3393        }
3394        seq.end()
3395    }
3396}
3397
3398#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Default)]
3399pub struct DefaultPrivileges {
3400    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
3401    privileges: BTreeMap<DefaultPrivilegeObject, RoleDefaultPrivileges>,
3402}
3403
3404// Use a new type here because otherwise we have two levels of BTreeMap, both needing
3405// map_key_to_string.
3406#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Default)]
3407struct RoleDefaultPrivileges(
3408    /// Denormalized, the key is the grantee Role.
3409    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
3410    BTreeMap<RoleId, DefaultPrivilegeAclItem>,
3411);
3412
3413impl Deref for RoleDefaultPrivileges {
3414    type Target = BTreeMap<RoleId, DefaultPrivilegeAclItem>;
3415
3416    fn deref(&self) -> &Self::Target {
3417        &self.0
3418    }
3419}
3420
3421impl DerefMut for RoleDefaultPrivileges {
3422    fn deref_mut(&mut self) -> &mut Self::Target {
3423        &mut self.0
3424    }
3425}
3426
3427impl DefaultPrivileges {
3428    /// Add a new default privilege into the set of all default privileges.
3429    pub fn grant(&mut self, object: DefaultPrivilegeObject, privilege: DefaultPrivilegeAclItem) {
3430        if privilege.acl_mode.is_empty() {
3431            return;
3432        }
3433
3434        let privileges = self.privileges.entry(object).or_default();
3435        if let Some(default_privilege) = privileges.get_mut(&privilege.grantee) {
3436            default_privilege.acl_mode |= privilege.acl_mode;
3437        } else {
3438            privileges.insert(privilege.grantee, privilege);
3439        }
3440    }
3441
3442    /// Revoke a default privilege from the set of all default privileges.
3443    pub fn revoke(&mut self, object: &DefaultPrivilegeObject, privilege: &DefaultPrivilegeAclItem) {
3444        if let Some(privileges) = self.privileges.get_mut(object) {
3445            if let Some(default_privilege) = privileges.get_mut(&privilege.grantee) {
3446                default_privilege.acl_mode =
3447                    default_privilege.acl_mode.difference(privilege.acl_mode);
3448                if default_privilege.acl_mode.is_empty() {
3449                    privileges.remove(&privilege.grantee);
3450                }
3451            }
3452            if privileges.is_empty() {
3453                self.privileges.remove(object);
3454            }
3455        }
3456    }
3457
3458    /// Get the privileges that will be granted on all objects matching `object` to `grantee`, if
3459    /// any exist.
3460    pub fn get_privileges_for_grantee(
3461        &self,
3462        object: &DefaultPrivilegeObject,
3463        grantee: &RoleId,
3464    ) -> Option<&AclMode> {
3465        self.privileges
3466            .get(object)
3467            .and_then(|privileges| privileges.get(grantee))
3468            .map(|privilege| &privilege.acl_mode)
3469    }
3470
3471    /// Get all default privileges that apply to the provided object details.
3472    pub fn get_applicable_privileges(
3473        &self,
3474        role_id: RoleId,
3475        database_id: Option<DatabaseId>,
3476        schema_id: Option<SchemaId>,
3477        object_type: mz_sql::catalog::ObjectType,
3478    ) -> impl Iterator<Item = DefaultPrivilegeAclItem> + '_ {
3479        // Privileges consider all relations to be of type table due to PostgreSQL compatibility. We
3480        // don't require the caller to worry about that and we will map their `object_type` to the
3481        // correct type for privileges.
3482        let privilege_object_type = if object_type.is_relation() {
3483            mz_sql::catalog::ObjectType::Table
3484        } else {
3485            object_type
3486        };
3487        let valid_acl_mode = rbac::all_object_privileges(SystemObjectType::Object(object_type));
3488
3489        // Collect all entries that apply to the provided object details.
3490        // If either `database_id` or `schema_id` are `None`, then we might end up with duplicate
3491        // entries in the vec below. That's OK because we consolidate the results after.
3492        [
3493            DefaultPrivilegeObject {
3494                role_id,
3495                database_id,
3496                schema_id,
3497                object_type: privilege_object_type,
3498            },
3499            DefaultPrivilegeObject {
3500                role_id,
3501                database_id,
3502                schema_id: None,
3503                object_type: privilege_object_type,
3504            },
3505            DefaultPrivilegeObject {
3506                role_id,
3507                database_id: None,
3508                schema_id: None,
3509                object_type: privilege_object_type,
3510            },
3511            DefaultPrivilegeObject {
3512                role_id: RoleId::Public,
3513                database_id,
3514                schema_id,
3515                object_type: privilege_object_type,
3516            },
3517            DefaultPrivilegeObject {
3518                role_id: RoleId::Public,
3519                database_id,
3520                schema_id: None,
3521                object_type: privilege_object_type,
3522            },
3523            DefaultPrivilegeObject {
3524                role_id: RoleId::Public,
3525                database_id: None,
3526                schema_id: None,
3527                object_type: privilege_object_type,
3528            },
3529        ]
3530        .into_iter()
3531        .filter_map(|object| self.privileges.get(&object))
3532        .flat_map(|acl_map| acl_map.values())
3533        // Consolidate privileges with a common grantee.
3534        .fold(
3535            BTreeMap::new(),
3536            |mut accum, DefaultPrivilegeAclItem { grantee, acl_mode }| {
3537                let accum_acl_mode = accum.entry(grantee).or_insert_with(AclMode::empty);
3538                *accum_acl_mode |= *acl_mode;
3539                accum
3540            },
3541        )
3542        .into_iter()
3543        // Restrict the acl_mode to only privileges valid for the provided object type. If the
3544        // default privilege has an object type of Table, then it may contain privileges valid for
3545        // tables but not other relations. If the passed in object type is another relation, then
3546        // we need to remove any privilege that is not valid for the specified relation.
3547        .map(move |(grantee, acl_mode)| (grantee, acl_mode & valid_acl_mode))
3548        // Filter out empty privileges.
3549        .filter(|(_, acl_mode)| !acl_mode.is_empty())
3550        .map(|(grantee, acl_mode)| DefaultPrivilegeAclItem {
3551            grantee: *grantee,
3552            acl_mode,
3553        })
3554    }
3555
3556    pub fn iter(
3557        &self,
3558    ) -> impl Iterator<
3559        Item = (
3560            &DefaultPrivilegeObject,
3561            impl Iterator<Item = &DefaultPrivilegeAclItem>,
3562        ),
3563    > {
3564        self.privileges
3565            .iter()
3566            .map(|(object, acl_map)| (object, acl_map.values()))
3567    }
3568}
3569
3570#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
3571pub struct ClusterConfig {
3572    pub variant: ClusterVariant,
3573    pub workload_class: Option<String>,
3574    #[serde(default)]
3575    pub query_policy: Option<QueryPolicyId>,
3576}
3577
3578impl ClusterConfig {
3579    pub fn features(&self) -> Option<&OptimizerFeatureOverrides> {
3580        match &self.variant {
3581            ClusterVariant::Managed(managed) => Some(&managed.optimizer_feature_overrides),
3582            ClusterVariant::Unmanaged => None,
3583        }
3584    }
3585}
3586
3587impl From<ClusterConfig> for durable::ClusterConfig {
3588    fn from(config: ClusterConfig) -> Self {
3589        Self {
3590            variant: config.variant.into(),
3591            workload_class: config.workload_class,
3592            query_policy: config.query_policy,
3593        }
3594    }
3595}
3596
3597impl From<durable::ClusterConfig> for ClusterConfig {
3598    fn from(config: durable::ClusterConfig) -> Self {
3599        Self {
3600            variant: config.variant.into(),
3601            workload_class: config.workload_class,
3602            query_policy: config.query_policy,
3603        }
3604    }
3605}
3606
3607#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
3608pub struct ClusterVariantManaged {
3609    pub size: String,
3610    pub availability_zones: Vec<String>,
3611    pub logging: ReplicaLogging,
3612    /// Whether arrangements on this cluster's replicas request dictionary compression.
3613    pub arrangement_compression: bool,
3614    pub replication_factor: u32,
3615    pub optimizer_feature_overrides: OptimizerFeatureOverrides,
3616    pub schedule: ClusterSchedule,
3617    /// User-configured autoscaling policy, distinct from the in-flight runtime
3618    /// records below. Shared with the durable layer, like [`ClusterSchedule`].
3619    pub auto_scaling_strategy: Option<AutoScalingStrategy>,
3620    /// Latest graceful reconfiguration record, if one has been written.
3621    pub reconfiguration: Option<ReconfigurationState>,
3622    /// In-flight hydration burst the controller is running.
3623    pub burst: Option<BurstState>,
3624}
3625
3626/// Per-replica config shape of a managed cluster.
3627#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3628pub struct ManagedReplicaConfigShape<'a> {
3629    pub size: &'a str,
3630    pub availability_zones: &'a [String],
3631    pub logging: &'a ReplicaLogging,
3632    pub arrangement_compression: bool,
3633}
3634
3635impl<'a> ManagedReplicaConfigShape<'a> {
3636    /// Returns a per-replica config shape from its component fields.
3637    pub fn new(
3638        size: &'a str,
3639        availability_zones: &'a [String],
3640        logging: &'a ReplicaLogging,
3641        arrangement_compression: bool,
3642    ) -> Self {
3643        Self {
3644            size,
3645            availability_zones,
3646            logging,
3647            arrangement_compression,
3648        }
3649    }
3650}
3651
3652impl ClusterVariantManaged {
3653    /// Returns the per-replica config shape of this managed cluster.
3654    pub fn replica_config_shape(&self) -> ManagedReplicaConfigShape<'_> {
3655        let ClusterVariantManaged {
3656            size,
3657            availability_zones,
3658            logging,
3659            arrangement_compression,
3660            replication_factor: _,
3661            optimizer_feature_overrides: _,
3662            schedule: _,
3663            auto_scaling_strategy: _,
3664            reconfiguration: _,
3665            burst: _,
3666        } = self;
3667        ManagedReplicaConfigShape::new(size, availability_zones, logging, *arrangement_compression)
3668    }
3669
3670    /// Returns this managed cluster's realized shape as a reconfiguration target.
3671    pub fn realized_reconfiguration_target(&self) -> ReconfigurationTarget {
3672        let ClusterVariantManaged {
3673            size,
3674            availability_zones,
3675            logging,
3676            arrangement_compression,
3677            replication_factor,
3678            optimizer_feature_overrides: _,
3679            schedule: _,
3680            auto_scaling_strategy: _,
3681            reconfiguration: _,
3682            burst: _,
3683        } = self;
3684        ReconfigurationTarget {
3685            size: size.clone(),
3686            replication_factor: *replication_factor,
3687            availability_zones: availability_zones.clone(),
3688            logging: logging.clone(),
3689            arrangement_compression: *arrangement_compression,
3690        }
3691    }
3692
3693    /// Advances this config's realized shape to `target`, the write a
3694    /// reconfiguration cut-over performs. The inverse of
3695    /// [`ClusterVariantManaged::realized_reconfiguration_target`].
3696    pub fn apply_reconfiguration_target(&mut self, target: ReconfigurationTarget) {
3697        // Destructured so a new target dimension fails to compile until it is
3698        // applied here too.
3699        let ReconfigurationTarget {
3700            size,
3701            replication_factor,
3702            availability_zones,
3703            logging,
3704            arrangement_compression,
3705        } = target;
3706        self.size = size;
3707        self.replication_factor = replication_factor;
3708        self.availability_zones = availability_zones;
3709        self.logging = logging;
3710        self.arrangement_compression = arrangement_compression;
3711    }
3712
3713    /// Whether the in-flight `burst` record is no longer warranted by this
3714    /// config: the `ON HYDRATION` policy was removed or re-sized away from the
3715    /// record's size, or the cluster was turned off (`replication_factor` 0).
3716    /// `false` when there is no record.
3717    pub fn has_unwarranted_burst_record(&self) -> bool {
3718        let Some(record) = &self.burst else {
3719            return false;
3720        };
3721        let hydration_size = self
3722            .auto_scaling_strategy
3723            .as_ref()
3724            .and_then(|strategy| strategy.on_hydration.as_ref())
3725            .map(|policy| policy.hydration_size.as_str());
3726        !mz_adapter_types::cluster_state::burst_record_warranted(
3727            &record.burst_size,
3728            self.replication_factor,
3729            hydration_size,
3730        )
3731    }
3732}
3733
3734impl From<ClusterVariantManaged> for durable::ClusterVariantManaged {
3735    fn from(managed: ClusterVariantManaged) -> Self {
3736        // Destructure the source (no `..`): a field added to either side is a
3737        // compile error here until it's carried across the boundary.
3738        let ClusterVariantManaged {
3739            size,
3740            availability_zones,
3741            logging,
3742            arrangement_compression,
3743            replication_factor,
3744            optimizer_feature_overrides,
3745            schedule,
3746            auto_scaling_strategy,
3747            reconfiguration,
3748            burst,
3749        } = managed;
3750        Self {
3751            size,
3752            availability_zones,
3753            logging,
3754            arrangement_compression,
3755            replication_factor,
3756            optimizer_feature_overrides: optimizer_feature_overrides.into(),
3757            schedule,
3758            auto_scaling_strategy,
3759            reconfiguration: reconfiguration.map(Into::into),
3760            burst: burst.map(Into::into),
3761        }
3762    }
3763}
3764
3765impl From<durable::ClusterVariantManaged> for ClusterVariantManaged {
3766    fn from(managed: durable::ClusterVariantManaged) -> Self {
3767        // Destructure the source (no `..`): a field added to either side is a
3768        // compile error here until it's carried across the boundary.
3769        let durable::ClusterVariantManaged {
3770            size,
3771            availability_zones,
3772            logging,
3773            arrangement_compression,
3774            replication_factor,
3775            optimizer_feature_overrides,
3776            schedule,
3777            auto_scaling_strategy,
3778            reconfiguration,
3779            burst,
3780        } = managed;
3781        Self {
3782            size,
3783            availability_zones,
3784            logging,
3785            arrangement_compression,
3786            replication_factor,
3787            optimizer_feature_overrides: optimizer_feature_overrides.into(),
3788            schedule,
3789            auto_scaling_strategy,
3790            reconfiguration: reconfiguration.map(Into::into),
3791            burst: burst.map(Into::into),
3792        }
3793    }
3794}
3795
3796/// In-memory mirror of [`durable::ReconfigurationState`].
3797///
3798/// This runtime state lives only in the durable layer, so the memory layer
3799/// carries its own `Serialize`/`Deserialize` mirror (to back the catalog
3800/// `dump()`) and converts across the boundary, rather than embedding the
3801/// durable-only type. The semantic contract lives on the durable type.
3802#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
3803pub struct ReconfigurationState {
3804    pub target: ReconfigurationTarget,
3805    pub deadline: Timestamp,
3806    pub on_timeout: OnTimeoutAction,
3807    pub status: ReconfigurationStatus,
3808}
3809
3810/// In-memory mirror of [`durable::ReconfigurationStatus`].
3811///
3812/// The lifecycle of a cluster's `reconfiguration` record. Writers only ever
3813/// move the record along these transitions:
3814///
3815/// | from          | to                                                    | audited as          |
3816/// |---------------|-------------------------------------------------------|---------------------|
3817/// | no record     | `InProgress`                                          | `started`           |
3818/// | `InProgress`  | `InProgress` (re-target)                              | `started`           |
3819/// | `InProgress`  | `Finalized`                                           | `finalized`         |
3820/// | `InProgress`  | `TimedOut`                                            | `timed-out`         |
3821/// | `InProgress`  | `Cancelled`                                           | `cancelled`         |
3822/// | `InProgress`  | `ResourceExhausted`                                   | `resource-exhausted`|
3823/// | any terminal  | no record (drop), or `InProgress` (fresh record)      | none / `started`    |
3824///
3825/// The terminal statuses never transition into one another and a record is
3826/// never revived in place: a new reconfiguration overwrites the settled record
3827/// with a fresh `InProgress` one.
3828#[derive(
3829    Clone,
3830    Copy,
3831    Debug,
3832    Deserialize,
3833    Serialize,
3834    PartialOrd,
3835    PartialEq,
3836    Eq,
3837    Ord
3838)]
3839pub enum ReconfigurationStatus {
3840    InProgress,
3841    Finalized,
3842    TimedOut,
3843    Cancelled,
3844    ResourceExhausted,
3845}
3846
3847impl From<ReconfigurationStatus> for durable::ReconfigurationStatus {
3848    fn from(status: ReconfigurationStatus) -> Self {
3849        match status {
3850            ReconfigurationStatus::InProgress => durable::ReconfigurationStatus::InProgress,
3851            ReconfigurationStatus::Finalized => durable::ReconfigurationStatus::Finalized,
3852            ReconfigurationStatus::TimedOut => durable::ReconfigurationStatus::TimedOut,
3853            ReconfigurationStatus::Cancelled => durable::ReconfigurationStatus::Cancelled,
3854            ReconfigurationStatus::ResourceExhausted => {
3855                durable::ReconfigurationStatus::ResourceExhausted
3856            }
3857        }
3858    }
3859}
3860
3861impl From<durable::ReconfigurationStatus> for ReconfigurationStatus {
3862    fn from(status: durable::ReconfigurationStatus) -> Self {
3863        match status {
3864            durable::ReconfigurationStatus::InProgress => ReconfigurationStatus::InProgress,
3865            durable::ReconfigurationStatus::Finalized => ReconfigurationStatus::Finalized,
3866            durable::ReconfigurationStatus::TimedOut => ReconfigurationStatus::TimedOut,
3867            durable::ReconfigurationStatus::Cancelled => ReconfigurationStatus::Cancelled,
3868            durable::ReconfigurationStatus::ResourceExhausted => {
3869                ReconfigurationStatus::ResourceExhausted
3870            }
3871        }
3872    }
3873}
3874
3875impl ReconfigurationState {
3876    pub fn is_in_progress(&self) -> bool {
3877        matches!(self.status, ReconfigurationStatus::InProgress)
3878    }
3879}
3880
3881impl From<ReconfigurationState> for durable::ReconfigurationState {
3882    fn from(state: ReconfigurationState) -> Self {
3883        // Destructure the source (no `..`): a field added to either side is a
3884        // compile error here until it's carried across the boundary.
3885        let ReconfigurationState {
3886            target,
3887            deadline,
3888            on_timeout,
3889            status,
3890        } = state;
3891        Self {
3892            target: target.into(),
3893            deadline,
3894            on_timeout,
3895            status: status.into(),
3896        }
3897    }
3898}
3899
3900impl From<durable::ReconfigurationState> for ReconfigurationState {
3901    fn from(state: durable::ReconfigurationState) -> Self {
3902        // Destructure the source (no `..`): a field added to either side is a
3903        // compile error here until it's carried across the boundary.
3904        let durable::ReconfigurationState {
3905            target,
3906            deadline,
3907            on_timeout,
3908            status,
3909        } = state;
3910        Self {
3911            target: target.into(),
3912            deadline,
3913            on_timeout,
3914            status: status.into(),
3915        }
3916    }
3917}
3918
3919/// In-memory mirror of [`durable::ReconfigurationTarget`].
3920#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
3921pub struct ReconfigurationTarget {
3922    pub size: String,
3923    pub replication_factor: u32,
3924    pub availability_zones: Vec<String>,
3925    pub logging: ReplicaLogging,
3926    pub arrangement_compression: bool,
3927}
3928
3929impl ReconfigurationTarget {
3930    /// Whether this target matches the realized config shape of `managed`.
3931    pub fn matches_realized_config(&self, managed: &ClusterVariantManaged) -> bool {
3932        self == &managed.realized_reconfiguration_target()
3933    }
3934}
3935
3936impl From<ReconfigurationTarget> for durable::ReconfigurationTarget {
3937    fn from(target: ReconfigurationTarget) -> Self {
3938        // Destructure the source (no `..`): a field added to either side is a
3939        // compile error here until it's carried across the boundary.
3940        let ReconfigurationTarget {
3941            size,
3942            replication_factor,
3943            availability_zones,
3944            logging,
3945            arrangement_compression,
3946        } = target;
3947        Self {
3948            size,
3949            replication_factor,
3950            availability_zones,
3951            logging,
3952            arrangement_compression,
3953        }
3954    }
3955}
3956
3957impl From<durable::ReconfigurationTarget> for ReconfigurationTarget {
3958    fn from(target: durable::ReconfigurationTarget) -> Self {
3959        // Destructure the source (no `..`): a field added to either side is a
3960        // compile error here until it's carried across the boundary.
3961        let durable::ReconfigurationTarget {
3962            size,
3963            replication_factor,
3964            availability_zones,
3965            logging,
3966            arrangement_compression,
3967        } = target;
3968        Self {
3969            size,
3970            replication_factor,
3971            availability_zones,
3972            logging,
3973            arrangement_compression,
3974        }
3975    }
3976}
3977
3978/// In-memory mirror of [`durable::BurstState`].
3979#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
3980pub struct BurstState {
3981    pub burst_size: String,
3982    pub linger_duration: Duration,
3983    pub steady_ready_at: Option<Timestamp>,
3984}
3985
3986impl From<BurstState> for durable::BurstState {
3987    fn from(burst: BurstState) -> Self {
3988        // Destructure the source (no `..`): a field added to either side is a
3989        // compile error here until it's carried across the boundary.
3990        let BurstState {
3991            burst_size,
3992            linger_duration,
3993            steady_ready_at,
3994        } = burst;
3995        Self {
3996            burst_size,
3997            linger_duration,
3998            steady_ready_at,
3999        }
4000    }
4001}
4002
4003impl From<durable::BurstState> for BurstState {
4004    fn from(burst: durable::BurstState) -> Self {
4005        // Destructure the source (no `..`): a field added to either side is a
4006        // compile error here until it's carried across the boundary.
4007        let durable::BurstState {
4008            burst_size,
4009            linger_duration,
4010            steady_ready_at,
4011        } = burst;
4012        Self {
4013            burst_size,
4014            linger_duration,
4015            steady_ready_at,
4016        }
4017    }
4018}
4019
4020#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
4021pub enum ClusterVariant {
4022    Managed(ClusterVariantManaged),
4023    Unmanaged,
4024}
4025
4026impl From<ClusterVariant> for durable::ClusterVariant {
4027    fn from(variant: ClusterVariant) -> Self {
4028        match variant {
4029            ClusterVariant::Managed(managed) => Self::Managed(managed.into()),
4030            ClusterVariant::Unmanaged => Self::Unmanaged,
4031        }
4032    }
4033}
4034
4035impl From<durable::ClusterVariant> for ClusterVariant {
4036    fn from(variant: durable::ClusterVariant) -> Self {
4037        match variant {
4038            durable::ClusterVariant::Managed(managed) => Self::Managed(managed.into()),
4039            durable::ClusterVariant::Unmanaged => Self::Unmanaged,
4040        }
4041    }
4042}
4043
4044impl mz_sql::catalog::CatalogDatabase for Database {
4045    fn name(&self) -> &str {
4046        &self.name
4047    }
4048
4049    fn id(&self) -> DatabaseId {
4050        self.id
4051    }
4052
4053    fn has_schemas(&self) -> bool {
4054        !self.schemas_by_name.is_empty()
4055    }
4056
4057    fn schema_ids(&self) -> &BTreeMap<String, SchemaId> {
4058        &self.schemas_by_name
4059    }
4060
4061    // `as` is ok to use to cast to a trait object.
4062    #[allow(clippy::as_conversions)]
4063    fn schemas(&self) -> Vec<&dyn CatalogSchema> {
4064        self.schemas_by_id
4065            .values()
4066            .map(|schema| schema as &dyn CatalogSchema)
4067            .collect()
4068    }
4069
4070    fn owner_id(&self) -> RoleId {
4071        self.owner_id
4072    }
4073
4074    fn privileges(&self) -> &PrivilegeMap {
4075        &self.privileges
4076    }
4077}
4078
4079impl mz_sql::catalog::CatalogSchema for Schema {
4080    fn database(&self) -> &ResolvedDatabaseSpecifier {
4081        &self.name.database
4082    }
4083
4084    fn name(&self) -> &QualifiedSchemaName {
4085        &self.name
4086    }
4087
4088    fn id(&self) -> &SchemaSpecifier {
4089        &self.id
4090    }
4091
4092    fn has_items(&self) -> bool {
4093        // A schema holds items, types, and functions in separate maps (see
4094        // `item_ids`). All three keep the schema non-empty, so e.g. DROP SCHEMA
4095        // without CASCADE must be rejected when only a type or function remains.
4096        !self.items.is_empty() || !self.types.is_empty() || !self.functions.is_empty()
4097    }
4098
4099    fn item_ids(&self) -> Box<dyn Iterator<Item = CatalogItemId> + '_> {
4100        Box::new(
4101            self.items
4102                .values()
4103                .chain(self.functions.values())
4104                .chain(self.types.values())
4105                .copied(),
4106        )
4107    }
4108
4109    fn owner_id(&self) -> RoleId {
4110        self.owner_id
4111    }
4112
4113    fn privileges(&self) -> &PrivilegeMap {
4114        &self.privileges
4115    }
4116}
4117
4118impl mz_sql::catalog::CatalogRole for Role {
4119    fn name(&self) -> &str {
4120        &self.name
4121    }
4122
4123    fn id(&self) -> RoleId {
4124        self.id
4125    }
4126
4127    fn membership(&self) -> &BTreeMap<RoleId, RoleId> {
4128        &self.membership.map
4129    }
4130
4131    fn attributes(&self) -> &RoleAttributes {
4132        &self.attributes
4133    }
4134
4135    fn vars(&self) -> &BTreeMap<String, OwnedVarInput> {
4136        &self.vars.map
4137    }
4138}
4139
4140impl mz_sql::catalog::CatalogNetworkPolicy for NetworkPolicy {
4141    fn name(&self) -> &str {
4142        &self.name
4143    }
4144
4145    fn id(&self) -> NetworkPolicyId {
4146        self.id
4147    }
4148
4149    fn owner_id(&self) -> RoleId {
4150        self.owner_id
4151    }
4152
4153    fn privileges(&self) -> &PrivilegeMap {
4154        &self.privileges
4155    }
4156}
4157
4158impl mz_sql::catalog::CatalogQueryPolicy for QueryPolicy {
4159    fn name(&self) -> &str {
4160        &self.name
4161    }
4162    fn id(&self) -> QueryPolicyId {
4163        self.id
4164    }
4165    fn owner_id(&self) -> RoleId {
4166        self.owner_id
4167    }
4168    fn privileges(&self) -> &PrivilegeMap {
4169        &self.privileges
4170    }
4171    fn mode(&self) -> QueryPolicyMode {
4172        self.mode
4173    }
4174    fn rules(&self) -> &[QueryPolicyRule] {
4175        &self.rules
4176    }
4177}
4178
4179impl mz_sql::catalog::CatalogCluster<'_> for Cluster {
4180    fn name(&self) -> &str {
4181        &self.name
4182    }
4183
4184    fn id(&self) -> ClusterId {
4185        self.id
4186    }
4187
4188    fn bound_objects(&self) -> &BTreeSet<CatalogItemId> {
4189        &self.bound_objects
4190    }
4191
4192    fn replica_ids(&self) -> &BTreeMap<String, ReplicaId> {
4193        &self.replica_id_by_name_
4194    }
4195
4196    // `as` is ok to use to cast to a trait object.
4197    #[allow(clippy::as_conversions)]
4198    fn replicas(&self) -> Vec<&dyn CatalogClusterReplica<'_>> {
4199        self.replicas()
4200            .map(|replica| replica as &dyn CatalogClusterReplica)
4201            .collect()
4202    }
4203
4204    fn replica(&self, id: ReplicaId) -> &dyn CatalogClusterReplica<'_> {
4205        self.replica(id).expect("catalog out of sync")
4206    }
4207
4208    fn owner_id(&self) -> RoleId {
4209        self.owner_id
4210    }
4211
4212    fn privileges(&self) -> &PrivilegeMap {
4213        &self.privileges
4214    }
4215
4216    fn is_managed(&self) -> bool {
4217        self.is_managed()
4218    }
4219
4220    fn managed_size(&self) -> Option<&str> {
4221        match &self.config.variant {
4222            ClusterVariant::Managed(ClusterVariantManaged { size, .. }) => Some(size),
4223            ClusterVariant::Unmanaged => None,
4224        }
4225    }
4226
4227    fn schedule(&self) -> Option<&ClusterSchedule> {
4228        match &self.config.variant {
4229            ClusterVariant::Managed(ClusterVariantManaged { schedule, .. }) => Some(schedule),
4230            ClusterVariant::Unmanaged => None,
4231        }
4232    }
4233
4234    fn replication_factor(&self) -> Option<u32> {
4235        match &self.config.variant {
4236            ClusterVariant::Managed(ClusterVariantManaged {
4237                replication_factor, ..
4238            }) => Some(*replication_factor),
4239            ClusterVariant::Unmanaged => None,
4240        }
4241    }
4242
4243    fn auto_scaling_strategy(&self) -> Option<&AutoScalingStrategy> {
4244        match &self.config.variant {
4245            ClusterVariant::Managed(ClusterVariantManaged {
4246                auto_scaling_strategy,
4247                ..
4248            }) => auto_scaling_strategy.as_ref(),
4249            ClusterVariant::Unmanaged => None,
4250        }
4251    }
4252    fn try_to_plan(&self) -> Result<CreateClusterPlan, PlanError> {
4253        self.try_to_plan()
4254    }
4255}
4256
4257impl mz_sql::catalog::CatalogClusterReplica<'_> for ClusterReplica {
4258    fn name(&self) -> &str {
4259        &self.name
4260    }
4261
4262    fn cluster_id(&self) -> ClusterId {
4263        self.cluster_id
4264    }
4265
4266    fn replica_id(&self) -> ReplicaId {
4267        self.replica_id
4268    }
4269
4270    fn owner_id(&self) -> RoleId {
4271        self.owner_id
4272    }
4273
4274    fn internal(&self) -> bool {
4275        self.config.location.internal()
4276    }
4277}
4278
4279impl mz_sql::catalog::CatalogItem for CatalogEntry {
4280    fn name(&self) -> &QualifiedItemName {
4281        self.name()
4282    }
4283
4284    fn id(&self) -> CatalogItemId {
4285        self.id()
4286    }
4287
4288    fn global_ids(&self) -> Box<dyn Iterator<Item = GlobalId> + '_> {
4289        Box::new(self.global_ids())
4290    }
4291
4292    fn oid(&self) -> u32 {
4293        self.oid()
4294    }
4295
4296    fn func(&self) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
4297        self.func()
4298    }
4299
4300    fn source_desc(&self) -> Result<Option<&SourceDesc<ReferencedConnection>>, SqlCatalogError> {
4301        self.source_desc()
4302    }
4303
4304    fn connection(
4305        &self,
4306    ) -> Result<mz_storage_types::connections::Connection<ReferencedConnection>, SqlCatalogError>
4307    {
4308        Ok(self.connection()?.details.to_connection())
4309    }
4310
4311    fn create_sql(&self) -> &str {
4312        match self.item() {
4313            CatalogItem::Table(Table { create_sql, .. }) => {
4314                create_sql.as_deref().unwrap_or("<builtin>")
4315            }
4316            CatalogItem::Source(Source { create_sql, .. }) => {
4317                create_sql.as_deref().unwrap_or("<builtin>")
4318            }
4319            CatalogItem::Sink(Sink { create_sql, .. }) => create_sql,
4320            CatalogItem::View(View { create_sql, .. }) => create_sql,
4321            CatalogItem::MaterializedView(MaterializedView { create_sql, .. }) => create_sql,
4322            CatalogItem::Index(Index { create_sql, .. }) => create_sql,
4323            CatalogItem::Type(Type { create_sql, .. }) => {
4324                create_sql.as_deref().unwrap_or("<builtin>")
4325            }
4326            CatalogItem::Secret(Secret { create_sql, .. }) => create_sql,
4327            CatalogItem::Connection(Connection { create_sql, .. }) => create_sql,
4328            CatalogItem::MetricSink(MetricSink { create_sql, .. }) => create_sql,
4329            CatalogItem::Func(_) => "<builtin>",
4330            CatalogItem::Log(_) => "<builtin>",
4331        }
4332    }
4333
4334    fn item_type(&self) -> SqlCatalogItemType {
4335        self.item().typ()
4336    }
4337
4338    fn index_details(&self) -> Option<(&[MirScalarExpr], GlobalId)> {
4339        if let CatalogItem::Index(Index { keys, on, .. }) = self.item() {
4340            Some((keys, *on))
4341        } else {
4342            None
4343        }
4344    }
4345
4346    fn writable_table_details(&self) -> Option<&[Expr<Aug>]> {
4347        if let CatalogItem::Table(Table {
4348            data_source: TableDataSource::TableWrites { defaults },
4349            ..
4350        }) = self.item()
4351        {
4352            Some(defaults.as_slice())
4353        } else {
4354            None
4355        }
4356    }
4357
4358    fn replacement_target(&self) -> Option<CatalogItemId> {
4359        if let CatalogItem::MaterializedView(mv) = self.item() {
4360            mv.replacement_target
4361        } else {
4362            None
4363        }
4364    }
4365
4366    fn type_details(&self) -> Option<&CatalogTypeDetails<IdReference>> {
4367        if let CatalogItem::Type(Type { details, .. }) = self.item() {
4368            Some(details)
4369        } else {
4370            None
4371        }
4372    }
4373
4374    fn references(&self) -> &ResolvedIds {
4375        self.references()
4376    }
4377
4378    fn uses(&self) -> BTreeSet<CatalogItemId> {
4379        self.uses()
4380    }
4381
4382    fn referenced_by(&self) -> &[CatalogItemId] {
4383        self.referenced_by()
4384    }
4385
4386    fn used_by(&self) -> &[CatalogItemId] {
4387        self.used_by()
4388    }
4389
4390    fn subsource_details(
4391        &self,
4392    ) -> Option<(CatalogItemId, &UnresolvedItemName, &SourceExportDetails)> {
4393        self.subsource_details()
4394    }
4395
4396    fn source_export_details(
4397        &self,
4398    ) -> Option<(
4399        CatalogItemId,
4400        &UnresolvedItemName,
4401        &SourceExportDetails,
4402        &SourceExportDataConfig<ReferencedConnection>,
4403    )> {
4404        self.source_export_details()
4405    }
4406
4407    fn is_progress_source(&self) -> bool {
4408        self.is_progress_source()
4409    }
4410
4411    fn progress_id(&self) -> Option<CatalogItemId> {
4412        self.progress_id()
4413    }
4414
4415    fn owner_id(&self) -> RoleId {
4416        self.owner_id
4417    }
4418
4419    fn privileges(&self) -> &PrivilegeMap {
4420        &self.privileges
4421    }
4422
4423    fn cluster_id(&self) -> Option<ClusterId> {
4424        self.item().cluster_id()
4425    }
4426
4427    fn at_version(
4428        &self,
4429        version: RelationVersionSelector,
4430    ) -> Box<dyn mz_sql::catalog::CatalogCollectionItem> {
4431        Box::new(CatalogCollectionEntry {
4432            entry: self.clone(),
4433            version,
4434        })
4435    }
4436
4437    fn latest_version(&self) -> Option<RelationVersion> {
4438        self.table().map(|t| t.desc.latest_version())
4439    }
4440}
4441
4442/// A single update to the catalog state.
4443#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
4444pub struct StateUpdate {
4445    pub kind: StateUpdateKind,
4446    pub ts: Timestamp,
4447    pub diff: StateDiff,
4448}
4449
4450/// The contents of a single state update.
4451///
4452/// Variants are listed in dependency order.
4453#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
4454pub enum StateUpdateKind {
4455    Role(durable::objects::Role),
4456    RoleAuth(durable::objects::RoleAuth),
4457    Database(durable::objects::Database),
4458    Schema(durable::objects::Schema),
4459    DefaultPrivilege(durable::objects::DefaultPrivilege),
4460    SystemPrivilege(MzAclItem),
4461    SystemConfiguration(durable::objects::SystemConfiguration),
4462    Cluster(durable::objects::Cluster),
4463    ClusterSystemConfiguration(durable::objects::ClusterSystemConfiguration),
4464    NetworkPolicy(durable::objects::NetworkPolicy),
4465    ClusterReplicaSize(durable::objects::ClusterReplicaSize),
4466    QueryPolicy(durable::objects::QueryPolicy),
4467    IntrospectionSourceIndex(durable::objects::IntrospectionSourceIndex),
4468    ClusterReplica(durable::objects::ClusterReplica),
4469    ReplicaSystemConfiguration(durable::objects::ReplicaSystemConfiguration),
4470    SourceReferences(durable::objects::SourceReferences),
4471    SystemObjectMapping(durable::objects::SystemObjectMapping),
4472    Item(durable::objects::Item),
4473    Comment(durable::objects::Comment),
4474    AuditLog(durable::objects::AuditLog),
4475    // Storage updates.
4476    StorageCollectionMetadata(durable::objects::StorageCollectionMetadata),
4477    UnfinalizedShard(durable::objects::UnfinalizedShard),
4478}
4479
4480/// Valid diffs for catalog state updates.
4481#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
4482pub enum StateDiff {
4483    Retraction,
4484    Addition,
4485}
4486
4487impl From<StateDiff> for Diff {
4488    fn from(diff: StateDiff) -> Self {
4489        match diff {
4490            StateDiff::Retraction => Diff::MINUS_ONE,
4491            StateDiff::Addition => Diff::ONE,
4492        }
4493    }
4494}
4495impl TryFrom<Diff> for StateDiff {
4496    type Error = String;
4497
4498    fn try_from(diff: Diff) -> Result<Self, Self::Error> {
4499        match diff {
4500            Diff::MINUS_ONE => Ok(Self::Retraction),
4501            Diff::ONE => Ok(Self::Addition),
4502            diff => Err(format!("invalid diff {diff}")),
4503        }
4504    }
4505}