Skip to main content

mz_adapter/catalog/
state.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//! In-memory metadata storage for the coordinator.
11
12use std::borrow::Cow;
13use std::collections::{BTreeMap, BTreeSet, VecDeque};
14use std::fmt::Debug;
15use std::sync::Arc;
16use std::sync::LazyLock;
17use std::time::Instant;
18
19use ipnet::IpNet;
20use itertools::Itertools;
21use mz_adapter_types::compaction::CompactionWindow;
22use mz_adapter_types::connection::ConnectionId;
23use mz_audit_log::{EventDetails, EventType, ObjectType, VersionedEvent};
24use mz_build_info::DUMMY_BUILD_INFO;
25use mz_catalog::SYSTEM_CONN_ID;
26use mz_catalog::builtin::{
27    BUILTINS, Builtin, BuiltinCluster, BuiltinLog, BuiltinSource, BuiltinTable, BuiltinType,
28};
29use mz_catalog::config::{AwsPrincipalContext, ClusterReplicaSizeMap};
30use mz_catalog::expr_cache::{LocalExpressions, latest_item_version};
31use mz_catalog::memory::error::{Error, ErrorKind};
32use mz_catalog::memory::objects::{
33    CatalogCollectionEntry, CatalogEntry, CatalogItem, Cluster, ClusterReplica, CommentsMap,
34    Connection, DataSourceDesc, Database, DefaultPrivileges, Index, MaterializedView, MetricSink,
35    NetworkPolicy, QueryPolicy, Role, RoleAuth, Schema, Secret, Sink, Source, SourceReferences,
36    Table, TableDataSource, Type, View,
37};
38use mz_controller::clusters::{
39    ManagedReplicaLocation, ReplicaAllocation, ReplicaLocation, UnmanagedReplicaLocation,
40};
41use mz_controller_types::{ClusterId, ReplicaId};
42use mz_expr::{CollectionPlan, MirScalarExpr, OptimizedMirRelationExpr};
43use mz_license_keys::ValidatedLicenseKey;
44use mz_ore::collections::CollectionExt;
45use mz_ore::now::NOW_ZERO;
46use mz_ore::soft_assert_no_log;
47use mz_ore::str::StrExt;
48use mz_pgrepr::oid::INVALID_OID;
49use mz_repr::adt::mz_acl_item::PrivilegeMap;
50use mz_repr::namespaces::{
51    INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_CATALOG_UNSTABLE_SCHEMA, MZ_INTERNAL_SCHEMA,
52    MZ_INTROSPECTION_SCHEMA, MZ_TEMP_SCHEMA, MZ_UNSAFE_SCHEMA, PG_CATALOG_SCHEMA, SYSTEM_SCHEMAS,
53    UNSTABLE_SCHEMAS,
54};
55use mz_repr::network_policy_id::NetworkPolicyId;
56use mz_repr::optimize::{OptimizerFeatureOverrides, OptimizerFeatures, OverrideFrom};
57use mz_repr::query_policy_id::QueryPolicyId;
58use mz_repr::role_id::RoleId;
59use mz_repr::{
60    CatalogItemId, GlobalId, RelationDesc, RelationVersion, RelationVersionSelector,
61    ReprColumnType, SqlScalarType, VersionedRelationDesc,
62};
63use mz_secrets::InMemorySecretsController;
64use mz_sql::ast::Ident;
65use mz_sql::catalog::{
66    CatalogCluster, CatalogClusterReplica, CatalogDatabase, CatalogError as SqlCatalogError,
67    CatalogItem as SqlCatalogItem, CatalogItemType, CatalogRecordField, CatalogRole, CatalogSchema,
68    CatalogType, CatalogTypeDetails, IdReference, NameReference, SessionCatalog, SystemObjectType,
69    TypeReference,
70};
71use mz_sql::catalog::{CatalogConfig, EnvironmentId};
72use mz_sql::names::{
73    CommentObjectId, DatabaseId, DependencyIds, FullItemName, FullSchemaName, ObjectId,
74    PartialItemName, QualifiedItemName, QualifiedSchemaName, RawDatabaseSpecifier,
75    ResolvedDatabaseSpecifier, ResolvedIds, SchemaId, SchemaSpecifier, SystemObjectId,
76};
77use mz_sql::plan::{
78    CreateConnectionPlan, CreateIndexPlan, CreateMaterializedViewPlan, CreateMetricSinkPlan,
79    CreateSecretPlan, CreateSinkPlan, CreateSourcePlan, CreateTablePlan, CreateTypePlan,
80    CreateViewPlan, Params, Plan, PlanContext,
81};
82use mz_sql::rbac;
83use mz_sql::session::metadata::SessionMetadata;
84use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
85use mz_sql::session::vars::{DEFAULT_DATABASE_NAME, SystemVars, Var, VarInput};
86use mz_sql_parser::ast::QualifiedReplica;
87use mz_storage_client::controller::StorageMetadata;
88use mz_storage_types::connections::ConnectionContext;
89use mz_storage_types::connections::inline::{
90    ConnectionResolver, InlinedConnection, IntoInlineConnection,
91};
92use mz_transform::notice::OptimizerNotice;
93use serde::Serialize;
94use timely::progress::Antichain;
95use tokio::sync::mpsc;
96use tracing::{debug, warn};
97use uuid::Uuid;
98
99// DO NOT add any more imports from `crate` outside of `crate::catalog`.
100use crate::AdapterError;
101use crate::catalog::{Catalog, ConnCatalog};
102use crate::config::ScopedParameters;
103use crate::coord::{ConnMeta, infer_sql_type_for_catalog};
104use crate::optimize::{self, Optimize, OptimizerCatalog};
105use crate::session::Session;
106
107/// The in-memory representation of the Catalog. This struct is not directly used to persist
108/// metadata to persistent storage. For persistent metadata see
109/// [`mz_catalog::durable::DurableCatalogState`].
110///
111/// [`Serialize`] is implemented to create human readable dumps of the in-memory state, not for
112/// storing the contents of this struct on disk.
113#[derive(Debug, Clone, Serialize)]
114pub struct CatalogState {
115    // State derived from the durable catalog. These fields should only be mutated in `open.rs` or
116    // `apply.rs`. Some of these fields are not 100% derived from the durable catalog. Those
117    // include:
118    //  - Temporary items.
119    //  - Certain objects are partially derived from read-only state.
120    pub(super) database_by_name: imbl::OrdMap<String, DatabaseId>,
121    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
122    pub(super) database_by_id: imbl::OrdMap<DatabaseId, Database>,
123    #[serde(serialize_with = "skip_temp_items")]
124    pub(super) entry_by_id: imbl::OrdMap<CatalogItemId, CatalogEntry>,
125    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
126    pub(super) entry_by_global_id: imbl::OrdMap<GlobalId, CatalogItemId>,
127    pub(super) ambient_schemas_by_name: imbl::OrdMap<String, SchemaId>,
128    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
129    pub(super) ambient_schemas_by_id: imbl::OrdMap<SchemaId, Schema>,
130    pub(super) clusters_by_name: imbl::OrdMap<String, ClusterId>,
131    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
132    pub(super) clusters_by_id: imbl::OrdMap<ClusterId, Cluster>,
133    pub(super) roles_by_name: imbl::OrdMap<String, RoleId>,
134    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
135    pub(super) roles_by_id: imbl::OrdMap<RoleId, Role>,
136    pub(super) network_policies_by_name: imbl::OrdMap<String, NetworkPolicyId>,
137    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
138    pub(super) network_policies_by_id: imbl::OrdMap<NetworkPolicyId, NetworkPolicy>,
139    pub(super) query_policies_by_name: imbl::OrdMap<String, QueryPolicyId>,
140    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
141    pub(super) query_policies_by_id: imbl::OrdMap<QueryPolicyId, QueryPolicy>,
142    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
143    pub(super) role_auth_by_id: imbl::OrdMap<RoleId, RoleAuth>,
144
145    #[serde(skip)]
146    pub(super) system_configuration: Arc<SystemVars>,
147    /// In-memory mirror of the durable scoped (per-cluster and per-replica)
148    /// system-parameter cache, maintained by `apply.rs` from the durable
149    /// collections. Resolution reads from here: the optimizer's per-cluster
150    /// feature overrides (`cluster_scoped_optimizer_overrides`) and the
151    /// coordinator's per-replica dyncfg push. See the scoped feature flags
152    /// design. Skipped in the consistency-check snapshot because it is fully
153    /// derived from the durable catalog.
154    #[serde(skip)]
155    pub(super) scoped_system_parameters: ScopedParameters,
156    pub(super) default_privileges: Arc<DefaultPrivileges>,
157    pub(super) system_privileges: Arc<PrivilegeMap>,
158    pub(super) comments: Arc<CommentsMap>,
159    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
160    pub(super) source_references: imbl::OrdMap<CatalogItemId, SourceReferences>,
161    pub(super) storage_metadata: Arc<StorageMetadata>,
162    pub(super) mock_authentication_nonce: Option<String>,
163
164    // Mutable state not derived from the durable catalog. Populated
165    // during dataflow bootstrapping (`bootstrap_dataflow_plans`), which
166    // doesn't run in Testdrive's read-only consistency check, so this
167    // must be `#[serde(skip)]`.
168    #[serde(skip)]
169    pub(super) notices_by_dep_id: imbl::OrdMap<GlobalId, Vec<Arc<OptimizerNotice>>>,
170
171    // Populated by active connections creating temporary objects. The
172    // read-only catalog opened by Testdrive's consistency check has no
173    // active connections, so this must be `#[serde(skip)]`.
174    #[serde(skip)]
175    pub(super) temporary_namespaces: TemporaryNamespaces,
176
177    // Read-only state not derived from the durable catalog.
178    #[serde(skip)]
179    pub(super) config: mz_sql::catalog::CatalogConfig,
180    pub(super) cluster_replica_sizes: ClusterReplicaSizeMap,
181    #[serde(skip)]
182    pub(crate) availability_zones: Vec<String>,
183
184    // Read-only not derived from the durable catalog.
185    #[serde(skip)]
186    pub(super) egress_addresses: Vec<IpNet>,
187    pub(super) aws_principal_context: Option<AwsPrincipalContext>,
188    pub(super) aws_privatelink_availability_zones: Option<BTreeSet<String>>,
189    pub(super) http_host_name: Option<String>,
190
191    // Read-only not derived from the durable catalog.
192    #[serde(skip)]
193    pub(super) license_key: ValidatedLicenseKey,
194}
195
196/// The temporary namespaces of the sessions connected to this process: for
197/// each session that has created a temporary item, the ephemeral-owner
198/// mapping between the session's UUID (stamped on its durable temporary
199/// items) and its connection, together with the session's `mz_temp`
200/// [`Schema`] once it has materialized.
201///
202/// The coordinator registers a namespace at a session's first
203/// temporary-item creation, and unregisters it when the session terminates.
204#[derive(Debug, Clone, Default)]
205pub(super) struct TemporaryNamespaces {
206    by_conn: imbl::OrdMap<ConnectionId, TemporaryNamespace>,
207    // For resolving a durable item's owner UUID to its connection in
208    // the apply path.
209    conns_by_uuid: imbl::OrdMap<Uuid, ConnectionId>,
210}
211
212#[derive(Debug, Clone)]
213struct TemporaryNamespace {
214    uuid: Uuid,
215    // Instantiated by `ensure_schema` at the first applied temporary item
216    schema: Option<Schema>,
217}
218
219impl TemporaryNamespaces {
220    /// Registers `conn_id` as the connection of the session `uuid`.
221    ///
222    /// Callers guard on [`CatalogState::has_temporary_namespace`], so
223    /// registering an already-registered connection is a bug.
224    pub(super) fn register(&mut self, conn_id: ConnectionId, uuid: Uuid) {
225        let prev_conn = self.conns_by_uuid.insert(uuid, conn_id.clone());
226        mz_ore::soft_assert_or_log!(
227            prev_conn.is_none(),
228            "duplicate temporary namespace registration for {uuid}"
229        );
230        let prev_ns = self
231            .by_conn
232            .insert(conn_id, TemporaryNamespace { uuid, schema: None });
233        mz_ore::soft_assert_or_log!(
234            prev_ns.is_none(),
235            "duplicate temporary namespace registration for the connection of {uuid}"
236        );
237    }
238
239    /// Returns `conn_id`'s `mz_temp` schema, creating an empty one owned by
240    /// `owner_id` if one hasn't been instantiated yet.
241    pub(super) fn ensure_schema(
242        &mut self,
243        conn_id: &ConnectionId,
244        owner_id: RoleId,
245    ) -> &mut Schema {
246        let namespace = self
247            .by_conn
248            .get_mut(conn_id)
249            .expect("temporary namespace must be registered before items are applied");
250        namespace.schema.get_or_insert_with(|| {
251            // Temporary schema OIDs are never used, and it's therefore wasteful to go to the
252            // durable catalog to allocate a new OID for every temporary schema. Instead, we give
253            // them all the same invalid OID. This matches the semantics of temporary schema
254            // `GlobalId`s which are all -1.
255            let oid = INVALID_OID;
256            Schema {
257                name: QualifiedSchemaName {
258                    database: ResolvedDatabaseSpecifier::Ambient,
259                    schema: MZ_TEMP_SCHEMA.into(),
260                },
261                id: SchemaSpecifier::Temporary,
262                oid,
263                items: BTreeMap::new(),
264                functions: BTreeMap::new(),
265                types: BTreeMap::new(),
266                owner_id,
267                privileges: PrivilegeMap::from_mz_acl_items(vec![rbac::owner_privilege(
268                    mz_sql::catalog::ObjectType::Schema,
269                    owner_id,
270                )]),
271            }
272        })
273    }
274
275    /// Removes `conn_id`'s temporary namespace.
276    pub(super) fn unregister(&mut self, conn_id: &ConnectionId) {
277        let Some(namespace) = self.by_conn.get(conn_id) else {
278            return;
279        };
280        // A non-empty schema here means temporary items (and
281        // possibly their storage shards) weren't cleaned up, so we surface the
282        // invariant violation and keep the namespace registered.
283        if namespace
284            .schema
285            .as_ref()
286            .is_some_and(|schema| !schema.items.is_empty())
287        {
288            mz_ore::soft_panic_or_log!(
289                "temporary namespace for connection {conn_id} still has items at unregistration"
290            );
291            return;
292        }
293        let uuid = namespace.uuid;
294        self.by_conn.remove(conn_id);
295        self.conns_by_uuid.remove(&uuid);
296    }
297
298    pub(super) fn schema(&self, conn_id: &ConnectionId) -> Option<&Schema> {
299        self.by_conn
300            .get(conn_id)
301            .and_then(|namespace| namespace.schema.as_ref())
302    }
303
304    pub(super) fn schema_mut(&mut self, conn_id: &ConnectionId) -> Option<&mut Schema> {
305        self.by_conn
306            .get_mut(conn_id)
307            .and_then(|namespace| namespace.schema.as_mut())
308    }
309
310    pub(super) fn schemas(&self) -> impl Iterator<Item = &Schema> {
311        self.by_conn
312            .values()
313            .filter_map(|namespace| namespace.schema.as_ref())
314    }
315
316    pub(super) fn conn_for_uuid(&self, uuid: &Uuid) -> Option<&ConnectionId> {
317        self.conns_by_uuid.get(uuid)
318    }
319
320    pub(super) fn uuid_for_conn(&self, conn_id: &ConnectionId) -> Option<Uuid> {
321        self.by_conn.get(conn_id).map(|namespace| namespace.uuid)
322    }
323
324    pub(super) fn contains_conn(&self, conn_id: &ConnectionId) -> bool {
325        self.by_conn.contains_key(conn_id)
326    }
327
328    pub(super) fn contains_uuid(&self, uuid: &Uuid) -> bool {
329        self.conns_by_uuid.contains_key(uuid)
330    }
331}
332
333/// Keeps track of what expressions are cached or not during startup.
334/// It's also used during catalog transactions to avoid re-optimizing CREATE VIEW / CREATE MAT VIEW
335/// statements when going back and forth between durable catalog operations and in-memory catalog
336/// operations.
337#[derive(Debug, Clone, Serialize)]
338pub(crate) enum LocalExpressionCache {
339    /// The cache is being used.
340    Open {
341        /// The local expressions that were cached in the expression cache.
342        cached_exprs: BTreeMap<GlobalId, LocalExpressions>,
343        /// The local expressions that were NOT cached in the expression cache.
344        uncached_exprs: BTreeMap<GlobalId, LocalExpressions>,
345    },
346    /// The cache is not being used.
347    Closed,
348}
349
350impl LocalExpressionCache {
351    pub(super) fn new(cached_exprs: BTreeMap<GlobalId, LocalExpressions>) -> Self {
352        Self::Open {
353            cached_exprs,
354            uncached_exprs: BTreeMap::new(),
355        }
356    }
357
358    pub(super) fn remove_cached_expression(&mut self, id: &GlobalId) -> Option<LocalExpressions> {
359        match self {
360            LocalExpressionCache::Open { cached_exprs, .. } => cached_exprs.remove(id),
361            LocalExpressionCache::Closed => None,
362        }
363    }
364
365    /// Insert an expression that was cached, back into the cache. This is generally needed when
366    /// parsing/planning an expression fails, but we don't want to lose the cached expression.
367    pub(super) fn insert_cached_expression(
368        &mut self,
369        id: GlobalId,
370        local_expressions: LocalExpressions,
371    ) {
372        match self {
373            LocalExpressionCache::Open { cached_exprs, .. } => {
374                cached_exprs.insert(id, local_expressions);
375            }
376            LocalExpressionCache::Closed => {}
377        }
378    }
379
380    /// Inform the cache that `id` was not found in the cache and that we should add it as
381    /// `local_mir` and `optimizer_features`, recorded at `item_version`.
382    pub(super) fn insert_uncached_expression(
383        &mut self,
384        id: GlobalId,
385        local_mir: OptimizedMirRelationExpr,
386        optimizer_features: OptimizerFeatures,
387        item_version: RelationVersion,
388    ) {
389        match self {
390            LocalExpressionCache::Open { uncached_exprs, .. } => {
391                let local_expr = LocalExpressions {
392                    local_mir,
393                    optimizer_features,
394                    item_version,
395                };
396                // If we are trying to cache the same item a second time, with a different
397                // expression, then we must be migrating the object or doing something else weird.
398                // Caching the unmigrated expression may cause us to incorrectly use the unmigrated
399                // version after a restart. Caching the migrated version may cause us to incorrectly
400                // think that the object has already been migrated. To simplify things, we cache
401                // neither.
402                let prev = uncached_exprs.remove(&id);
403                match prev {
404                    Some(prev) if prev == local_expr => {
405                        uncached_exprs.insert(id, local_expr);
406                    }
407                    None => {
408                        uncached_exprs.insert(id, local_expr);
409                    }
410                    Some(_) => {}
411                }
412            }
413            LocalExpressionCache::Closed => {}
414        }
415    }
416
417    pub(super) fn into_uncached_exprs(self) -> BTreeMap<GlobalId, LocalExpressions> {
418        match self {
419            LocalExpressionCache::Open { uncached_exprs, .. } => uncached_exprs,
420            LocalExpressionCache::Closed => BTreeMap::new(),
421        }
422    }
423}
424
425fn skip_temp_items<S>(
426    entries: &imbl::OrdMap<CatalogItemId, CatalogEntry>,
427    serializer: S,
428) -> Result<S::Ok, S::Error>
429where
430    S: serde::Serializer,
431{
432    mz_ore::serde::map_key_to_string(
433        entries.iter().filter(|(_k, v)| v.conn_id().is_none()),
434        serializer,
435    )
436}
437
438impl CatalogState {
439    pub fn entries(&self) -> impl Iterator<Item = &CatalogEntry> {
440        self.entry_by_id.values()
441    }
442
443    pub fn user_connections(&self) -> impl Iterator<Item = &CatalogEntry> {
444        self.entries()
445            .filter(|entry| entry.is_connection() && entry.id().is_user())
446    }
447
448    pub fn user_tables(&self) -> impl Iterator<Item = &CatalogEntry> {
449        self.entries()
450            .filter(|entry| entry.is_table() && entry.id().is_user())
451    }
452
453    pub fn user_sources(&self) -> impl Iterator<Item = &CatalogEntry> {
454        self.entries()
455            .filter(|entry| entry.is_source() && entry.id().is_user())
456    }
457
458    pub fn user_sinks(&self) -> impl Iterator<Item = &CatalogEntry> {
459        self.entries()
460            .filter(|entry| entry.is_sink() && entry.id().is_user())
461    }
462
463    pub fn user_materialized_views(&self) -> impl Iterator<Item = &CatalogEntry> {
464        self.entries()
465            .filter(|entry| entry.is_materialized_view() && entry.id().is_user())
466    }
467
468    pub fn user_secrets(&self) -> impl Iterator<Item = &CatalogEntry> {
469        self.entries()
470            .filter(|entry| entry.is_secret() && entry.id().is_user())
471    }
472
473    pub fn clusters(&self) -> impl Iterator<Item = &Cluster> {
474        self.clusters_by_id.values()
475    }
476
477    pub fn user_clusters(&self) -> impl Iterator<Item = &Cluster> {
478        self.clusters().filter(|cluster| cluster.id.is_user())
479    }
480
481    pub fn user_cluster_replicas(&self) -> impl Iterator<Item = &ClusterReplica> {
482        self.user_clusters()
483            .flat_map(|cluster| cluster.user_replicas())
484    }
485
486    pub fn databases(&self) -> impl Iterator<Item = &Database> {
487        self.database_by_id.values()
488    }
489
490    pub fn user_roles(&self) -> impl Iterator<Item = &Role> {
491        self.roles_by_id.values().filter(|role| role.is_user())
492    }
493
494    pub fn user_network_policies(&self) -> impl Iterator<Item = &NetworkPolicy> {
495        self.network_policies_by_id
496            .iter()
497            .filter(|(id, _)| id.is_user())
498            .map(|(_, policy)| policy)
499    }
500
501    pub fn user_query_policies(&self) -> impl Iterator<Item = &QueryPolicy> {
502        self.query_policies_by_id
503            .iter()
504            .filter(|(id, _)| id.is_user())
505            .map(|(_, policy)| policy)
506    }
507
508    pub fn cluster_replica_sizes(&self) -> &ClusterReplicaSizeMap {
509        &self.cluster_replica_sizes
510    }
511
512    /// Returns an empty [`CatalogState`] that can be used in tests.
513    // TODO: Ideally we'd mark this as `#[cfg(test)]`, but that doesn't work with the way
514    // tests are structured in this repository.
515    pub fn empty_test() -> Self {
516        CatalogState {
517            database_by_name: Default::default(),
518            database_by_id: Default::default(),
519            entry_by_id: Default::default(),
520            entry_by_global_id: Default::default(),
521            notices_by_dep_id: Default::default(),
522            ambient_schemas_by_name: Default::default(),
523            ambient_schemas_by_id: Default::default(),
524            temporary_namespaces: Default::default(),
525            clusters_by_id: Default::default(),
526            clusters_by_name: Default::default(),
527            network_policies_by_name: Default::default(),
528            roles_by_name: Default::default(),
529            roles_by_id: Default::default(),
530            network_policies_by_id: Default::default(),
531            query_policies_by_name: Default::default(),
532            query_policies_by_id: Default::default(),
533            role_auth_by_id: Default::default(),
534            config: CatalogConfig {
535                start_time: Default::default(),
536                start_instant: Instant::now(),
537                nonce: Default::default(),
538                environment_id: EnvironmentId::for_tests(),
539                session_id: Default::default(),
540                build_info: &DUMMY_BUILD_INFO,
541                now: NOW_ZERO.clone(),
542                connection_context: ConnectionContext::for_tests(Arc::new(
543                    InMemorySecretsController::new(),
544                )),
545                aws_account_id: None,
546                helm_chart_version: None,
547            },
548            cluster_replica_sizes: ClusterReplicaSizeMap::for_tests(),
549            availability_zones: Default::default(),
550            system_configuration: Arc::new(SystemVars::default()),
551            scoped_system_parameters: Default::default(),
552            egress_addresses: Default::default(),
553            aws_principal_context: Default::default(),
554            aws_privatelink_availability_zones: Default::default(),
555            http_host_name: Default::default(),
556            default_privileges: Arc::new(DefaultPrivileges::default()),
557            system_privileges: Arc::new(PrivilegeMap::default()),
558            comments: Arc::new(CommentsMap::default()),
559            source_references: Default::default(),
560            storage_metadata: Arc::new(StorageMetadata::default()),
561            license_key: ValidatedLicenseKey::for_tests(),
562            mock_authentication_nonce: Default::default(),
563        }
564    }
565
566    pub fn for_session<'a>(&'a self, session: &'a Session) -> ConnCatalog<'a> {
567        let state = session.transaction().catalog_state().unwrap_or(self);
568        let mut catalog = state.for_session_metadata(session, session.retain_notice_transmitter());
569        catalog.prepared_statements = Some(session.prepared_statements());
570        catalog.portals = Some(session.portals());
571        catalog
572    }
573
574    /// Binds statement context to this state without substituting a transaction snapshot.
575    pub(crate) fn for_session_metadata(
576        &self,
577        session: &dyn SessionMetadata,
578        notices_tx: mpsc::UnboundedSender<crate::AdapterNotice>,
579    ) -> ConnCatalog<'_> {
580        let search_path = self.resolve_search_path(session);
581        let database = self
582            .database_by_name
583            .get(session.vars().database())
584            .map(|id| id.clone());
585        ConnCatalog {
586            state: Cow::Borrowed(self),
587            unresolvable_ids: BTreeSet::new(),
588            conn_id: session.conn_id().clone(),
589            cluster: session.vars().cluster().into(),
590            database,
591            search_path,
592            role_id: session.current_role_id().clone(),
593            prepared_statements: None,
594            portals: None,
595            notices_tx,
596            restrict_to_user_objects: session.vars().restrict_to_user_objects(),
597        }
598    }
599
600    pub fn for_sessionless_user(&self, role_id: RoleId) -> ConnCatalog<'_> {
601        let (notices_tx, _notices_rx) = mpsc::unbounded_channel();
602        let cluster = self.system_configuration.default_cluster();
603
604        ConnCatalog {
605            state: Cow::Borrowed(self),
606            unresolvable_ids: BTreeSet::new(),
607            conn_id: SYSTEM_CONN_ID.clone(),
608            cluster,
609            database: self
610                .resolve_database(DEFAULT_DATABASE_NAME)
611                .ok()
612                .map(|db| db.id()),
613            // Leaving the system's search path empty allows us to catch issues
614            // where catalog object names have not been normalized correctly.
615            search_path: Vec::new(),
616            role_id,
617            prepared_statements: None,
618            portals: None,
619            notices_tx,
620            restrict_to_user_objects: false,
621        }
622    }
623
624    pub fn for_system_session(&self) -> ConnCatalog<'_> {
625        self.for_sessionless_user(MZ_SYSTEM_ROLE_ID)
626    }
627
628    /// Returns an iterator over the deduplicated identifiers of all
629    /// objects this catalog entry transitively depends on (where
630    /// "depends on" is meant in the sense of [`CatalogItem::uses`], rather than
631    /// [`CatalogItem::references`]).
632    pub fn transitive_uses(&self, id: CatalogItemId) -> impl Iterator<Item = CatalogItemId> + '_ {
633        struct I<'a> {
634            queue: VecDeque<CatalogItemId>,
635            seen: BTreeSet<CatalogItemId>,
636            this: &'a CatalogState,
637        }
638        impl<'a> Iterator for I<'a> {
639            type Item = CatalogItemId;
640            fn next(&mut self) -> Option<Self::Item> {
641                if let Some(next) = self.queue.pop_front() {
642                    for child in self.this.get_entry(&next).item().uses() {
643                        if !self.seen.contains(&child) {
644                            self.queue.push_back(child);
645                            self.seen.insert(child);
646                        }
647                    }
648                    Some(next)
649                } else {
650                    None
651                }
652            }
653        }
654
655        I {
656            queue: [id].into_iter().collect(),
657            seen: [id].into_iter().collect(),
658            this: self,
659        }
660    }
661
662    /// Computes the IDs of any log sources this catalog entry transitively
663    /// depends on.
664    pub fn introspection_dependencies(&self, id: CatalogItemId) -> Vec<CatalogItemId> {
665        let mut out = Vec::new();
666
667        // Iterative worklist traversal rather than recursion. The dependency
668        // chain is user controlled and can be arbitrarily deep.
669        let mut queue: VecDeque<CatalogItemId> = [id].into_iter().collect();
670        let mut seen: BTreeSet<CatalogItemId> = [id].into_iter().collect();
671        while let Some(id) = queue.pop_front() {
672            match self.get_entry(&id).item() {
673                CatalogItem::Log(_) => out.push(id),
674                item @ (CatalogItem::View(_)
675                | CatalogItem::MaterializedView(_)
676                | CatalogItem::Connection(_)) => {
677                    // TODO Unclear if this table wants to include all uses or only references.
678                    for item_id in item.references().items() {
679                        if seen.insert(*item_id) {
680                            queue.push_back(*item_id);
681                        }
682                    }
683                }
684                CatalogItem::Sink(sink) => {
685                    let from_item_id = self.get_entry_by_global_id(&sink.from).id();
686                    if seen.insert(from_item_id) {
687                        queue.push_back(from_item_id);
688                    }
689                }
690                CatalogItem::MetricSink(metric_sink) => {
691                    let from_item_id = self.get_entry_by_global_id(&metric_sink.from).id();
692                    if seen.insert(from_item_id) {
693                        queue.push_back(from_item_id);
694                    }
695                }
696                CatalogItem::Index(idx) => {
697                    let on_item_id = self.get_entry_by_global_id(&idx.on).id();
698                    if seen.insert(on_item_id) {
699                        queue.push_back(on_item_id);
700                    }
701                }
702                CatalogItem::Table(_)
703                | CatalogItem::Source(_)
704                | CatalogItem::Type(_)
705                | CatalogItem::Func(_)
706                | CatalogItem::Secret(_) => (),
707            }
708        }
709
710        out
711    }
712
713    /// Returns all the IDs of all objects that depend on `ids`, including `ids` themselves.
714    ///
715    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
716    /// earlier in the list than the roots. This is particularly useful for the order to drop
717    /// objects.
718    pub(super) fn object_dependents(
719        &self,
720        object_ids: &Vec<ObjectId>,
721        conn_id: &ConnectionId,
722        seen: &mut BTreeSet<ObjectId>,
723    ) -> Vec<ObjectId> {
724        let mut dependents = Vec::new();
725        for object_id in object_ids {
726            match object_id {
727                ObjectId::Cluster(id) => {
728                    dependents.extend_from_slice(&self.cluster_dependents(*id, seen));
729                }
730                ObjectId::ClusterReplica((cluster_id, replica_id)) => dependents.extend_from_slice(
731                    &self.cluster_replica_dependents(*cluster_id, *replica_id, seen),
732                ),
733                ObjectId::Database(id) => {
734                    dependents.extend_from_slice(&self.database_dependents(*id, conn_id, seen))
735                }
736                ObjectId::Schema((database_spec, schema_spec)) => {
737                    dependents.extend_from_slice(&self.schema_dependents(
738                        database_spec.clone(),
739                        schema_spec.clone(),
740                        conn_id,
741                        seen,
742                    ));
743                }
744                ObjectId::NetworkPolicy(id) => {
745                    dependents.extend_from_slice(&self.network_policy_dependents(*id, seen));
746                }
747                id @ (ObjectId::Role(_) | ObjectId::QueryPolicy(_)) => {
748                    let unseen = seen.insert(id.clone());
749                    if unseen {
750                        dependents.push(id.clone());
751                    }
752                }
753                ObjectId::Item(id) => {
754                    dependents.extend_from_slice(&self.item_dependents(*id, seen))
755                }
756            }
757        }
758        dependents
759    }
760
761    /// Returns all the IDs of all objects that depend on `cluster_id`, including `cluster_id`
762    /// itself.
763    ///
764    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
765    /// earlier in the list than the roots. This is particularly useful for the order to drop
766    /// objects.
767    fn cluster_dependents(
768        &self,
769        cluster_id: ClusterId,
770        seen: &mut BTreeSet<ObjectId>,
771    ) -> Vec<ObjectId> {
772        let mut dependents = Vec::new();
773        let object_id = ObjectId::Cluster(cluster_id);
774        if !seen.contains(&object_id) {
775            seen.insert(object_id.clone());
776            let cluster = self.get_cluster(cluster_id);
777            for item_id in cluster.bound_objects() {
778                dependents.extend_from_slice(&self.item_dependents(*item_id, seen));
779            }
780            for replica_id in cluster.replica_ids().values() {
781                dependents.extend_from_slice(&self.cluster_replica_dependents(
782                    cluster_id,
783                    *replica_id,
784                    seen,
785                ));
786            }
787            dependents.push(object_id);
788        }
789        dependents
790    }
791
792    /// Returns all the IDs of all objects that depend on `replica_id`, including `replica_id`
793    /// itself.
794    ///
795    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
796    /// earlier in the list than the roots. This is particularly useful for the order to drop
797    /// objects.
798    pub(super) fn cluster_replica_dependents(
799        &self,
800        cluster_id: ClusterId,
801        replica_id: ReplicaId,
802        seen: &mut BTreeSet<ObjectId>,
803    ) -> Vec<ObjectId> {
804        let mut dependents = Vec::new();
805        let object_id = ObjectId::ClusterReplica((cluster_id, replica_id));
806        if !seen.contains(&object_id) {
807            seen.insert(object_id.clone());
808            // Materialized views that target this replica are implicitly
809            // dropped with it, so cascade to their dependents to avoid leaving
810            // dangling references.
811            let cluster = self.get_cluster(cluster_id);
812            for item_id in cluster.bound_objects() {
813                if let CatalogItem::MaterializedView(mv) = self.get_entry(item_id).item()
814                    && mv.target_replica == Some(replica_id)
815                {
816                    dependents.extend_from_slice(&self.item_dependents(*item_id, seen));
817                }
818            }
819            dependents.push(object_id);
820        }
821        dependents
822    }
823
824    /// Returns all the IDs of all objects that depend on `database_id`, including `database_id`
825    /// itself.
826    ///
827    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
828    /// earlier in the list than the roots. This is particularly useful for the order to drop
829    /// objects.
830    fn database_dependents(
831        &self,
832        database_id: DatabaseId,
833        conn_id: &ConnectionId,
834        seen: &mut BTreeSet<ObjectId>,
835    ) -> Vec<ObjectId> {
836        let mut dependents = Vec::new();
837        let object_id = ObjectId::Database(database_id);
838        if !seen.contains(&object_id) {
839            seen.insert(object_id.clone());
840            let database = self.get_database(&database_id);
841            for schema_id in database.schema_ids().values() {
842                dependents.extend_from_slice(&self.schema_dependents(
843                    ResolvedDatabaseSpecifier::Id(database_id),
844                    SchemaSpecifier::Id(*schema_id),
845                    conn_id,
846                    seen,
847                ));
848            }
849            dependents.push(object_id);
850        }
851        dependents
852    }
853
854    /// Returns all the IDs of all objects that depend on `schema_id`, including `schema_id`
855    /// itself.
856    ///
857    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
858    /// earlier in the list than the roots. This is particularly useful for the order to drop
859    /// objects.
860    fn schema_dependents(
861        &self,
862        database_spec: ResolvedDatabaseSpecifier,
863        schema_spec: SchemaSpecifier,
864        conn_id: &ConnectionId,
865        seen: &mut BTreeSet<ObjectId>,
866    ) -> Vec<ObjectId> {
867        let mut dependents = Vec::new();
868        let object_id = ObjectId::Schema((database_spec, schema_spec.clone()));
869        if !seen.contains(&object_id) {
870            seen.insert(object_id.clone());
871            let schema = self.get_schema(&database_spec, &schema_spec, conn_id);
872            for item_id in schema.item_ids() {
873                dependents.extend_from_slice(&self.item_dependents(item_id, seen));
874            }
875            dependents.push(object_id)
876        }
877        dependents
878    }
879
880    /// Returns all the IDs of all objects that depend on `item_id`, including `item_id`
881    /// itself.
882    ///
883    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
884    /// earlier in the list than the roots. This is particularly useful for the order to drop
885    /// objects.
886    pub(super) fn item_dependents(
887        &self,
888        item_id: CatalogItemId,
889        seen: &mut BTreeSet<ObjectId>,
890    ) -> Vec<ObjectId> {
891        let mut dependents = Vec::new();
892
893        // Iterative post-order traversal rather than recursion. Dependency
894        // chains are user controlled and can be arbitrarily deep (e.g. a long
895        // chain of stacked views), so recursing risks a stack overflow.
896        enum Work {
897            Enter(CatalogItemId),
898            Emit(ObjectId),
899        }
900        let mut stack = vec![Work::Enter(item_id)];
901        while let Some(work) = stack.pop() {
902            match work {
903                Work::Enter(item_id) => {
904                    let object_id = ObjectId::Item(item_id);
905                    if !seen.insert(object_id.clone()) {
906                        continue;
907                    }
908                    let entry = self.get_entry(&item_id);
909                    // Pushed in reverse of the desired output order: dependents
910                    // first, then self, then the progress collection. We treat
911                    // the progress collection as if it depends on the source
912                    // for dropping. We have additional code in planning to
913                    // create a kind of special-case "CASCADE" for this
914                    // dependency.
915                    if let Some(progress_id) = entry.progress_id() {
916                        stack.push(Work::Enter(progress_id));
917                    }
918                    stack.push(Work::Emit(object_id));
919                    for dependent_id in entry.used_by().iter().rev() {
920                        stack.push(Work::Enter(*dependent_id));
921                    }
922                }
923                Work::Emit(object_id) => dependents.push(object_id),
924            }
925        }
926
927        dependents
928    }
929
930    /// Returns all the IDs of all objects that depend on `network_policy_id`, including `network_policy_id`
931    /// itself.
932    ///
933    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
934    /// earlier in the list than the roots. This is particularly useful for the order to drop
935    /// objects.
936    pub(super) fn network_policy_dependents(
937        &self,
938        network_policy_id: NetworkPolicyId,
939        _seen: &mut BTreeSet<ObjectId>,
940    ) -> Vec<ObjectId> {
941        let object_id = ObjectId::NetworkPolicy(network_policy_id);
942        // Currently network policies have no dependents
943        // when we add the ability for users or sources/sinks to have policies
944        // this method will need to be updated.
945        vec![object_id]
946    }
947
948    /// Indicates whether the indicated item is considered stable or not.
949    ///
950    /// Only stable items can be used as dependencies of other catalog items.
951    fn is_stable(&self, id: CatalogItemId) -> bool {
952        let spec = self.get_entry(&id).name().qualifiers.schema_spec;
953        !self.is_unstable_schema_specifier(spec)
954    }
955
956    pub(super) fn check_unstable_dependencies(&self, item: &CatalogItem) -> Result<(), Error> {
957        if self.system_config().unsafe_enable_unstable_dependencies() {
958            return Ok(());
959        }
960
961        let unstable_dependencies: Vec<_> = item
962            .references()
963            .items()
964            .filter(|id| !self.is_stable(**id))
965            .map(|id| self.get_entry(id).name().item.clone())
966            .collect();
967
968        // It's okay to create a temporary object with unstable
969        // dependencies, since we will never need to reboot a catalog
970        // that contains it.
971        if unstable_dependencies.is_empty() || item.is_temporary() {
972            Ok(())
973        } else {
974            let object_type = item.typ().to_string();
975            Err(Error {
976                kind: ErrorKind::UnstableDependency {
977                    object_type,
978                    unstable_dependencies,
979                },
980            })
981        }
982    }
983
984    pub fn resolve_full_name(
985        &self,
986        name: &QualifiedItemName,
987        conn_id: Option<&ConnectionId>,
988    ) -> FullItemName {
989        let conn_id = conn_id.unwrap_or(&SYSTEM_CONN_ID);
990
991        let database = match &name.qualifiers.database_spec {
992            ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
993            ResolvedDatabaseSpecifier::Id(id) => {
994                RawDatabaseSpecifier::Name(self.get_database(id).name().to_string())
995            }
996        };
997        // For temporary schemas, we know the name is always MZ_TEMP_SCHEMA,
998        // and the schema may not exist yet if no temporary items have been created.
999        let schema = match &name.qualifiers.schema_spec {
1000            SchemaSpecifier::Temporary => MZ_TEMP_SCHEMA.to_string(),
1001            SchemaSpecifier::Id(_) => self
1002                .get_schema(
1003                    &name.qualifiers.database_spec,
1004                    &name.qualifiers.schema_spec,
1005                    conn_id,
1006                )
1007                .name()
1008                .schema
1009                .clone(),
1010        };
1011        FullItemName {
1012            database,
1013            schema,
1014            item: name.item.clone(),
1015        }
1016    }
1017
1018    pub(super) fn resolve_full_schema_name(&self, name: &QualifiedSchemaName) -> FullSchemaName {
1019        let database = match &name.database {
1020            ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
1021            ResolvedDatabaseSpecifier::Id(id) => {
1022                RawDatabaseSpecifier::Name(self.get_database(id).name().to_string())
1023            }
1024        };
1025        FullSchemaName {
1026            database,
1027            schema: name.schema.clone(),
1028        }
1029    }
1030
1031    pub fn get_entry(&self, id: &CatalogItemId) -> &CatalogEntry {
1032        self.entry_by_id
1033            .get(id)
1034            .unwrap_or_else(|| panic!("catalog out of sync, missing id {id:?}"))
1035    }
1036
1037    pub fn get_entry_by_global_id(&self, id: &GlobalId) -> CatalogCollectionEntry {
1038        let item_id = self
1039            .entry_by_global_id
1040            .get(id)
1041            .unwrap_or_else(|| panic!("catalog out of sync, missing id {id:?}"));
1042
1043        let entry = self.get_entry(item_id).clone();
1044        let version = match entry.item() {
1045            CatalogItem::Table(table) => {
1046                let (version, _) = table
1047                    .collections
1048                    .iter()
1049                    .find(|(_verison, gid)| *gid == id)
1050                    .expect("version to exist");
1051                RelationVersionSelector::Specific(*version)
1052            }
1053            _ => RelationVersionSelector::Latest,
1054        };
1055        CatalogCollectionEntry { entry, version }
1056    }
1057
1058    pub fn get_entries(&self) -> impl Iterator<Item = (&CatalogItemId, &CatalogEntry)> + '_ {
1059        self.entry_by_id.iter()
1060    }
1061
1062    pub fn get_temp_items(&self, conn: &ConnectionId) -> impl Iterator<Item = ObjectId> + '_ {
1063        // A temporary namespace is registered at the connection's first
1064        // temporary-item creation, so it's valid for one to not exist yet.
1065        self.temporary_namespaces
1066            .schema(conn)
1067            .into_iter()
1068            .flat_map(|schema| schema.items.values().copied().map(ObjectId::from))
1069    }
1070
1071    /// Returns true if a temporary namespace is registered for the given
1072    /// connection, i.e. it has (or has had) temporary items.
1073    ///
1074    /// The namespace is registered at the connection's first temporary-item
1075    /// creation, so this returns false for connections that never created
1076    /// any temporary objects.
1077    pub fn has_temporary_namespace(&self, conn: &ConnectionId) -> bool {
1078        self.temporary_namespaces.contains_conn(conn)
1079    }
1080
1081    /// Converts an in-memory catalog entry into its durable representation.
1082    ///
1083    /// The durable owner of a temporary entry is the session whose connection
1084    /// currently holds it, resolved from the temporary namespace
1085    /// registered at the session's first temporary-item creation.
1086    pub(super) fn durable_item(
1087        &self,
1088        entry: CatalogEntry,
1089    ) -> Result<mz_catalog::durable::Item, AdapterError> {
1090        let ephemeral_owner_session = entry
1091            .conn_id()
1092            .map(|conn_id| {
1093                self.temporary_namespaces
1094                    .uuid_for_conn(conn_id)
1095                    .ok_or_else(|| {
1096                        AdapterError::Internal(format!(
1097                            "no session record for connection {conn_id} owning temporary item"
1098                        ))
1099                    })
1100            })
1101            .transpose()?;
1102        let (create_sql, global_id, extra_versions) = entry.item.into_serialized();
1103        Ok(mz_catalog::durable::Item {
1104            id: entry.id,
1105            oid: entry.oid,
1106            global_id,
1107            schema_id: entry.name.qualifiers.schema_spec.into(),
1108            name: entry.name.item,
1109            create_sql,
1110            owner_id: entry.owner_id,
1111            privileges: entry.privileges.into_all_values().collect(),
1112            extra_versions,
1113            ephemeral_owner_session,
1114        })
1115    }
1116
1117    /// Records in `tx` the planner-resolved metadata of all items in
1118    /// the current transaction.
1119    pub(super) fn refresh_item_metadata(
1120        &self,
1121        tx: &mut mz_catalog::durable::Transaction<'_>,
1122    ) -> Result<(), mz_catalog::durable::CatalogError> {
1123        let ids: Vec<_> = tx.get_items().map(|item| item.id).collect();
1124        self.record_item_metadata(tx, ids)
1125    }
1126
1127    /// Records in `tx` the planner-resolved metadata of every item in `ids`
1128    /// that this catalog has loaded.
1129    pub(super) fn record_item_metadata(
1130        &self,
1131        tx: &mut mz_catalog::durable::Transaction<'_>,
1132        ids: impl IntoIterator<Item = CatalogItemId>,
1133    ) -> Result<(), mz_catalog::durable::CatalogError> {
1134        for id in ids {
1135            // An id this catalog does not know, such as an item of a
1136            // temporary schema owned by a session that is not connected to this process,
1137            // is skipped.
1138            let Some(entry) = self.try_get_entry(&id) else {
1139                continue;
1140            };
1141            tx.set_item_metadata(id, self.durable_item_metadata(entry.item()))?;
1142        }
1143        Ok(())
1144    }
1145
1146    /// The planner-resolved metadata the durable catalog records for `item`:
1147    /// the columns of a relation, each by the identity its type presents as,
1148    /// and the keys of an index. See `mz_catalog::durable::ItemMetadata`.
1149    ///
1150    /// An index's keys are typed against the version of the indexed relation
1151    /// it was created on, which must be in this catalog.
1152    pub(super) fn durable_item_metadata(
1153        &self,
1154        item: &CatalogItem,
1155    ) -> mz_catalog::durable::ItemMetadata {
1156        let columns = item
1157            .relation_desc(RelationVersionSelector::Latest)
1158            .map(|desc| {
1159                desc.iter()
1160                    .map(|(name, typ)| {
1161                        let pg_type = mz_pgrepr::Type::from(&typ.scalar_type);
1162                        let custom_type = match &typ.scalar_type {
1163                            SqlScalarType::List {
1164                                custom_id: Some(id),
1165                                ..
1166                            }
1167                            | SqlScalarType::Map {
1168                                custom_id: Some(id),
1169                                ..
1170                            }
1171                            | SqlScalarType::Record {
1172                                custom_id: Some(id),
1173                                ..
1174                            } => Some(*id),
1175                            _ => None,
1176                        };
1177                        mz_catalog::durable::ItemColumn {
1178                            name: name.clone(),
1179                            nullable: typ.nullable,
1180                            type_oid: pg_type.oid(),
1181                            type_mod: pg_type.typmod(),
1182                            custom_type,
1183                        }
1184                    })
1185                    .collect()
1186            })
1187            .unwrap_or_default();
1188        let index_columns = match item {
1189            CatalogItem::Index(index) => {
1190                let on_entry = self.get_entry_by_global_id(&index.on);
1191                let on_desc = on_entry
1192                    .relation_desc()
1193                    .expect("indexes are built on relations");
1194                let column_types: Vec<ReprColumnType> = on_desc
1195                    .typ()
1196                    .column_types
1197                    .iter()
1198                    .map(ReprColumnType::from)
1199                    .collect();
1200                index
1201                    .keys
1202                    .iter()
1203                    .map(|key| mz_catalog::durable::IndexColumn {
1204                        column: match key {
1205                            MirScalarExpr::Column(column, _) => Some(*column),
1206                            _ => None,
1207                        },
1208                        nullable: key.typ(&column_types).nullable,
1209                    })
1210                    .collect()
1211            }
1212            _ => Vec::new(),
1213        };
1214        mz_catalog::durable::ItemMetadata {
1215            columns,
1216            index_columns,
1217        }
1218    }
1219
1220    /// Gets a type named `name` from exactly one of the system schemas.
1221    ///
1222    /// # Panics
1223    /// - If `name` is not an entry in any system schema
1224    /// - If more than one system schema has an entry named `name`.
1225    pub(super) fn get_system_type(&self, name: &str) -> &CatalogEntry {
1226        let mut res = None;
1227        for schema_id in self.system_schema_ids() {
1228            let schema = &self.ambient_schemas_by_id[&schema_id];
1229            if let Some(global_id) = schema.types.get(name) {
1230                match res {
1231                    None => res = Some(self.get_entry(global_id)),
1232                    Some(_) => panic!(
1233                        "only call get_system_type on objects uniquely identifiable in one system schema"
1234                    ),
1235                }
1236            }
1237        }
1238
1239        res.unwrap_or_else(|| panic!("cannot find type {} in system schema", name))
1240    }
1241
1242    pub fn get_item_by_name(
1243        &self,
1244        name: &QualifiedItemName,
1245        conn_id: &ConnectionId,
1246    ) -> Option<&CatalogEntry> {
1247        self.get_schema(
1248            &name.qualifiers.database_spec,
1249            &name.qualifiers.schema_spec,
1250            conn_id,
1251        )
1252        .items
1253        .get(&name.item)
1254        .and_then(|id| self.try_get_entry(id))
1255    }
1256
1257    pub fn get_type_by_name(
1258        &self,
1259        name: &QualifiedItemName,
1260        conn_id: &ConnectionId,
1261    ) -> Option<&CatalogEntry> {
1262        self.get_schema(
1263            &name.qualifiers.database_spec,
1264            &name.qualifiers.schema_spec,
1265            conn_id,
1266        )
1267        .types
1268        .get(&name.item)
1269        .and_then(|id| self.try_get_entry(id))
1270    }
1271
1272    pub(super) fn find_available_name(
1273        &self,
1274        mut name: QualifiedItemName,
1275        conn_id: &ConnectionId,
1276    ) -> QualifiedItemName {
1277        let mut i = 0;
1278        let orig_item_name = name.item.clone();
1279        while self.get_item_by_name(&name, conn_id).is_some() {
1280            i += 1;
1281            name.item = format!("{}{}", orig_item_name, i);
1282        }
1283        name
1284    }
1285
1286    pub fn try_get_entry(&self, id: &CatalogItemId) -> Option<&CatalogEntry> {
1287        self.entry_by_id.get(id)
1288    }
1289
1290    pub fn try_get_entry_by_global_id(&self, id: &GlobalId) -> Option<&CatalogEntry> {
1291        let item_id = self.entry_by_global_id.get(id)?;
1292        self.try_get_entry(item_id)
1293    }
1294
1295    /// Returns the [`RelationDesc`] for a [`GlobalId`], if the provided [`GlobalId`] refers to an
1296    /// object that returns rows.
1297    pub fn try_get_desc_by_global_id(&self, id: &GlobalId) -> Option<Cow<'_, RelationDesc>> {
1298        let entry = self.try_get_entry_by_global_id(id)?;
1299        let desc = match entry.item() {
1300            CatalogItem::Table(table) => Cow::Owned(table.desc_for(id)),
1301            // TODO(alter_table): Support schema evolution on sources.
1302            other => other.relation_desc(RelationVersionSelector::Latest)?,
1303        };
1304        Some(desc)
1305    }
1306
1307    pub(crate) fn get_cluster(&self, cluster_id: ClusterId) -> &Cluster {
1308        self.try_get_cluster(cluster_id)
1309            .unwrap_or_else(|| panic!("unknown cluster {cluster_id}"))
1310    }
1311
1312    pub(super) fn try_get_cluster(&self, cluster_id: ClusterId) -> Option<&Cluster> {
1313        self.clusters_by_id.get(&cluster_id)
1314    }
1315
1316    pub(super) fn try_get_role(&self, id: &RoleId) -> Option<&Role> {
1317        self.roles_by_id.get(id)
1318    }
1319
1320    pub fn get_role(&self, id: &RoleId) -> &Role {
1321        self.roles_by_id.get(id).expect("catalog out of sync")
1322    }
1323
1324    pub fn get_roles(&self) -> impl Iterator<Item = &RoleId> {
1325        self.roles_by_id.keys()
1326    }
1327
1328    pub(super) fn try_get_role_by_name(&self, role_name: &str) -> Option<&Role> {
1329        self.roles_by_name
1330            .get(role_name)
1331            .map(|id| &self.roles_by_id[id])
1332    }
1333
1334    pub(super) fn get_role_auth(&self, id: &RoleId) -> &RoleAuth {
1335        self.role_auth_by_id
1336            .get(id)
1337            .unwrap_or_else(|| panic!("catalog out of sync, missing role auth for {id}"))
1338    }
1339
1340    pub(super) fn try_get_role_auth_by_id(&self, id: &RoleId) -> Option<&RoleAuth> {
1341        self.role_auth_by_id.get(id)
1342    }
1343
1344    pub(super) fn try_get_network_policy_by_name(
1345        &self,
1346        policy_name: &str,
1347    ) -> Option<&NetworkPolicy> {
1348        self.network_policies_by_name
1349            .get(policy_name)
1350            .map(|id| &self.network_policies_by_id[id])
1351    }
1352
1353    pub(crate) fn collect_role_membership(&self, id: &RoleId) -> BTreeSet<RoleId> {
1354        let mut membership = BTreeSet::new();
1355        let mut queue = VecDeque::from(vec![id]);
1356        while let Some(cur_id) = queue.pop_front() {
1357            if !membership.contains(cur_id) {
1358                membership.insert(cur_id.clone());
1359                let role = self.get_role(cur_id);
1360                soft_assert_no_log!(
1361                    !role.membership().keys().contains(id),
1362                    "circular membership exists in the catalog"
1363                );
1364                queue.extend(role.membership().keys());
1365            }
1366        }
1367        membership.insert(RoleId::Public);
1368        membership
1369    }
1370
1371    pub fn get_network_policy(&self, id: &NetworkPolicyId) -> &NetworkPolicy {
1372        self.network_policies_by_id
1373            .get(id)
1374            .expect("catalog out of sync")
1375    }
1376
1377    pub fn get_network_policies(&self) -> impl Iterator<Item = &NetworkPolicyId> {
1378        self.network_policies_by_id.keys()
1379    }
1380
1381    pub fn get_query_policy(&self, id: &QueryPolicyId) -> &QueryPolicy {
1382        self.query_policies_by_id
1383            .get(id)
1384            .expect("catalog out of sync")
1385    }
1386
1387    pub(super) fn try_get_query_policy_by_name(&self, name: &str) -> Option<&QueryPolicy> {
1388        self.query_policies_by_name
1389            .get(name)
1390            .map(|id| self.get_query_policy(id))
1391    }
1392
1393    /// Returns the query policy attached to the executing cluster.
1394    pub fn query_policy_for(&self, cluster_id: ClusterId) -> Option<&QueryPolicy> {
1395        self.get_cluster(cluster_id)
1396            .config
1397            .query_policy
1398            .map(|id| self.get_query_policy(&id))
1399    }
1400
1401    /// Returns the URL for POST-ing data to a webhook source, if `id` corresponds to a webhook
1402    /// source.
1403    ///
1404    /// Note: Identifiers for the source, e.g. item name, are URL encoded.
1405    pub fn try_get_webhook_url(&self, id: &CatalogItemId) -> Option<url::Url> {
1406        let entry = self.try_get_entry(id)?;
1407        // Note: Webhook sources can never be created in the temporary schema, hence passing None.
1408        let name = self.resolve_full_name(entry.name(), None);
1409        let host_name = self
1410            .http_host_name
1411            .as_ref()
1412            .map(|x| x.as_str())
1413            .unwrap_or_else(|| "HOST");
1414
1415        let RawDatabaseSpecifier::Name(database) = name.database else {
1416            return None;
1417        };
1418
1419        let mut url = url::Url::parse(&format!("https://{host_name}/api/webhook")).ok()?;
1420        url.path_segments_mut()
1421            .ok()?
1422            .push(&database)
1423            .push(&name.schema)
1424            .push(&name.item);
1425
1426        Some(url)
1427    }
1428
1429    /// Parses the given SQL string into a pair of [`Plan`] and a [`ResolvedIds`].
1430    ///
1431    /// This function will temporarily enable all "enable_for_item_parsing" feature flags. See
1432    /// [`CatalogState::with_enable_for_item_parsing`] for more details.
1433    ///
1434    /// NOTE: While this method takes a `&mut self`, all mutations are temporary and restored to
1435    /// their original state before the method returns.
1436    pub(crate) fn deserialize_plan_with_enable_for_item_parsing(
1437        // DO NOT add any additional mutations to this method. It would be fairly surprising to the
1438        // caller if this method changed the state of the catalog.
1439        &mut self,
1440        create_sql: &str,
1441        force_if_exists_skip: bool,
1442    ) -> Result<(Plan, ResolvedIds), AdapterError> {
1443        self.with_enable_for_item_parsing(|state| {
1444            let pcx = PlanContext::zero().with_ignore_if_exists_errors(force_if_exists_skip);
1445            let pcx = Some(&pcx);
1446            let session_catalog = state.for_system_session();
1447
1448            let stmt = mz_sql::parse::parse(create_sql)?.into_element().ast;
1449            let (stmt, resolved_ids) = mz_sql::names::resolve(&session_catalog, stmt)?;
1450            let (plan, _sql_impl_ids) =
1451                mz_sql::plan::plan(pcx, &session_catalog, stmt, &Params::empty(), &resolved_ids)?;
1452
1453            Ok((plan, resolved_ids))
1454        })
1455    }
1456
1457    /// Parses the given SQL string into a pair of [`Plan`] and a [`ResolvedIds`].
1458    #[mz_ore::instrument]
1459    pub(crate) fn parse_plan(
1460        create_sql: &str,
1461        pcx: Option<&PlanContext>,
1462        catalog: &ConnCatalog,
1463    ) -> Result<(Plan, ResolvedIds), AdapterError> {
1464        let stmt = mz_sql::parse::parse(create_sql)?.into_element().ast;
1465        let (stmt, resolved_ids) = mz_sql::names::resolve(catalog, stmt)?;
1466        let (plan, _sql_impl_ids) =
1467            mz_sql::plan::plan(pcx, catalog, stmt, &Params::empty(), &resolved_ids)?;
1468
1469        Ok((plan, resolved_ids))
1470    }
1471
1472    /// Parses the given SQL string into a pair of [`CatalogItem`].
1473    pub(crate) fn deserialize_item(
1474        &self,
1475        global_id: GlobalId,
1476        create_sql: &str,
1477        extra_versions: &BTreeMap<RelationVersion, GlobalId>,
1478        local_expression_cache: &mut LocalExpressionCache,
1479        previous_item: Option<CatalogItem>,
1480    ) -> Result<CatalogItem, AdapterError> {
1481        self.parse_item(
1482            global_id,
1483            create_sql,
1484            extra_versions,
1485            None,
1486            false,
1487            None,
1488            local_expression_cache,
1489            previous_item,
1490        )
1491    }
1492
1493    /// Parses the given SQL string into a `CatalogItem`.
1494    #[mz_ore::instrument]
1495    pub(crate) fn parse_item(
1496        &self,
1497        global_id: GlobalId,
1498        create_sql: &str,
1499        extra_versions: &BTreeMap<RelationVersion, GlobalId>,
1500        pcx: Option<&PlanContext>,
1501        is_retained_metrics_object: bool,
1502        custom_logical_compaction_window: Option<CompactionWindow>,
1503        local_expression_cache: &mut LocalExpressionCache,
1504        previous_item: Option<CatalogItem>,
1505    ) -> Result<CatalogItem, AdapterError> {
1506        let cached_expr = local_expression_cache.remove_cached_expression(&global_id);
1507        match self.parse_item_inner(
1508            global_id,
1509            create_sql,
1510            extra_versions,
1511            pcx,
1512            is_retained_metrics_object,
1513            custom_logical_compaction_window,
1514            cached_expr,
1515            previous_item,
1516        ) {
1517            Ok((item, uncached_expr)) => {
1518                if let Some((uncached_expr, optimizer_features)) = uncached_expr {
1519                    local_expression_cache.insert_uncached_expression(
1520                        global_id,
1521                        uncached_expr,
1522                        optimizer_features,
1523                        latest_item_version(extra_versions),
1524                    );
1525                }
1526                Ok(item)
1527            }
1528            Err((err, cached_expr)) => {
1529                if let Some(local_expr) = cached_expr {
1530                    local_expression_cache.insert_cached_expression(global_id, local_expr);
1531                }
1532                Err(err)
1533            }
1534        }
1535    }
1536
1537    /// Parses the given SQL string into a `CatalogItem`, using `cached_expr` if it's Some.
1538    ///
1539    /// On success returns the `CatalogItem` and an optimized expression iff the expression was
1540    /// not cached.
1541    ///
1542    /// On failure returns an error and `cached_expr` so it can be used later.
1543    #[mz_ore::instrument]
1544    pub(crate) fn parse_item_inner(
1545        &self,
1546        global_id: GlobalId,
1547        create_sql: &str,
1548        extra_versions: &BTreeMap<RelationVersion, GlobalId>,
1549        pcx: Option<&PlanContext>,
1550        is_retained_metrics_object: bool,
1551        custom_logical_compaction_window: Option<CompactionWindow>,
1552        cached_expr: Option<LocalExpressions>,
1553        previous_item: Option<CatalogItem>,
1554    ) -> Result<
1555        (
1556            CatalogItem,
1557            Option<(OptimizedMirRelationExpr, OptimizerFeatures)>,
1558        ),
1559        (AdapterError, Option<LocalExpressions>),
1560    > {
1561        let session_catalog = self.for_system_session();
1562
1563        let (plan, resolved_ids) = match Self::parse_plan(create_sql, pcx, &session_catalog) {
1564            Ok((plan, resolved_ids)) => (plan, resolved_ids),
1565            Err(err) => return Err((err, cached_expr)),
1566        };
1567
1568        let mut uncached_expr = None;
1569
1570        // Carry over the plans (`optimized_plan`, `physical_plan`,
1571        // `dataflow_metainfo`) from the previous incarnation of this item when
1572        // re-parsing an existing item (e.g. after a RENAME). These fields live
1573        // on the `CatalogItem` since #35834, but are not reconstructable from
1574        // `create_sql` alone — they are populated by the sequencer `_finish`
1575        // paths at create time, and by the expression-cache / bootstrap
1576        // rendering path on boot. If we don't preserve them here, a RENAME
1577        // silently drops the plans and dataflow metainfo for the affected
1578        // MV/Index/CT.
1579        let previous_plans = previous_item.as_ref().map(|item| {
1580            (
1581                item.optimized_plan().cloned(),
1582                item.physical_plan().cloned(),
1583                item.dataflow_metainfo().cloned(),
1584            )
1585        });
1586
1587        let mut item = match plan {
1588            Plan::CreateTable(CreateTablePlan { table, .. }) => {
1589                let collections = extra_versions
1590                    .iter()
1591                    .map(|(version, gid)| (*version, *gid))
1592                    .chain([(RelationVersion::root(), global_id)].into_iter())
1593                    .collect();
1594
1595                CatalogItem::Table(Table {
1596                    create_sql: Some(table.create_sql),
1597                    desc: table.desc,
1598                    collections,
1599                    conn_id: None,
1600                    resolved_ids,
1601                    custom_logical_compaction_window: custom_logical_compaction_window
1602                        .or(table.compaction_window),
1603                    is_retained_metrics_object,
1604                    data_source: match table.data_source {
1605                        mz_sql::plan::TableDataSource::TableWrites { defaults } => {
1606                            TableDataSource::TableWrites { defaults }
1607                        }
1608                        mz_sql::plan::TableDataSource::DataSource {
1609                            desc: data_source_desc,
1610                            timeline,
1611                        } => match data_source_desc {
1612                            mz_sql::plan::DataSourceDesc::IngestionExport {
1613                                ingestion_id,
1614                                external_reference,
1615                                details,
1616                                data_config,
1617                            } => TableDataSource::DataSource {
1618                                desc: DataSourceDesc::IngestionExport {
1619                                    ingestion_id,
1620                                    external_reference,
1621                                    details,
1622                                    data_config,
1623                                },
1624                                timeline,
1625                            },
1626                            mz_sql::plan::DataSourceDesc::Webhook {
1627                                validate_using,
1628                                body_format,
1629                                headers,
1630                                cluster_id,
1631                            } => TableDataSource::DataSource {
1632                                desc: DataSourceDesc::Webhook {
1633                                    validate_using,
1634                                    body_format,
1635                                    headers,
1636                                    cluster_id: cluster_id
1637                                        .expect("Webhook Tables must have a cluster_id set"),
1638                                },
1639                                timeline,
1640                            },
1641                            _ => {
1642                                return Err((
1643                                    AdapterError::Unstructured(anyhow::anyhow!(
1644                                        "unsupported data source for table"
1645                                    )),
1646                                    cached_expr,
1647                                ));
1648                            }
1649                        },
1650                    },
1651                })
1652            }
1653            Plan::CreateSource(CreateSourcePlan {
1654                source,
1655                timeline,
1656                in_cluster,
1657                ..
1658            }) => CatalogItem::Source(Source {
1659                create_sql: Some(source.create_sql),
1660                data_source: match source.data_source {
1661                    mz_sql::plan::DataSourceDesc::Ingestion(desc) => DataSourceDesc::Ingestion {
1662                        desc,
1663                        cluster_id: match in_cluster {
1664                            Some(id) => id,
1665                            None => {
1666                                return Err((
1667                                    AdapterError::Unstructured(anyhow::anyhow!(
1668                                        "ingestion-based sources must have cluster specified"
1669                                    )),
1670                                    cached_expr,
1671                                ));
1672                            }
1673                        },
1674                    },
1675                    mz_sql::plan::DataSourceDesc::OldSyntaxIngestion {
1676                        desc,
1677                        progress_subsource,
1678                        data_config,
1679                        details,
1680                    } => DataSourceDesc::OldSyntaxIngestion {
1681                        desc,
1682                        progress_subsource,
1683                        data_config,
1684                        details,
1685                        cluster_id: match in_cluster {
1686                            Some(id) => id,
1687                            None => {
1688                                return Err((
1689                                    AdapterError::Unstructured(anyhow::anyhow!(
1690                                        "ingestion-based sources must have cluster specified"
1691                                    )),
1692                                    cached_expr,
1693                                ));
1694                            }
1695                        },
1696                    },
1697                    mz_sql::plan::DataSourceDesc::IngestionExport {
1698                        ingestion_id,
1699                        external_reference,
1700                        details,
1701                        data_config,
1702                    } => DataSourceDesc::IngestionExport {
1703                        ingestion_id,
1704                        external_reference,
1705                        details,
1706                        data_config,
1707                    },
1708                    mz_sql::plan::DataSourceDesc::Progress => DataSourceDesc::Progress,
1709                    mz_sql::plan::DataSourceDesc::Webhook {
1710                        validate_using,
1711                        body_format,
1712                        headers,
1713                        cluster_id,
1714                    } => {
1715                        mz_ore::soft_assert_or_log!(
1716                            cluster_id.is_none(),
1717                            "cluster_id set at Source level for Webhooks"
1718                        );
1719                        DataSourceDesc::Webhook {
1720                            validate_using,
1721                            body_format,
1722                            headers,
1723                            cluster_id: in_cluster
1724                                .expect("webhook sources must use an existing cluster"),
1725                        }
1726                    }
1727                },
1728                desc: source.desc,
1729                global_id,
1730                timeline,
1731                resolved_ids,
1732                custom_logical_compaction_window: source
1733                    .compaction_window
1734                    .or(custom_logical_compaction_window),
1735                is_retained_metrics_object,
1736            }),
1737            Plan::CreateView(CreateViewPlan { view, .. }) => {
1738                // Collect optimizer parameters.
1739                let optimizer_config =
1740                    optimize::OptimizerConfig::from(session_catalog.system_vars());
1741                let previous_exprs = previous_item.map(|item| match item {
1742                    CatalogItem::View(view) => Some((view.raw_expr, view.locally_optimized_expr)),
1743                    _ => None,
1744                });
1745
1746                let (raw_expr, optimized_expr) = match (cached_expr, previous_exprs) {
1747                    (Some(local_expr), _)
1748                        if local_expr.optimizer_features == optimizer_config.features =>
1749                    {
1750                        debug!("local expression cache hit for {global_id:?}");
1751                        (Arc::new(view.expr), Arc::new(local_expr.local_mir))
1752                    }
1753                    // If the new expr is equivalent to the old expr, then we don't need to re-optimize.
1754                    (_, Some(Some((raw_expr, optimized_expr)))) if *raw_expr == view.expr => {
1755                        (Arc::clone(&raw_expr), Arc::clone(&optimized_expr))
1756                    }
1757                    (cached_expr, _) => {
1758                        let optimizer_features = optimizer_config.features.clone();
1759                        // Build an optimizer for this VIEW.
1760                        let mut optimizer = optimize::view::Optimizer::new(optimizer_config, None);
1761
1762                        // HIR ⇒ MIR lowering and MIR ⇒ MIR optimization (local)
1763                        let raw_expr = view.expr;
1764                        let optimized_expr = match optimizer.optimize(raw_expr.clone()) {
1765                            Ok(optimzed_expr) => optimzed_expr,
1766                            Err(err) => return Err((err.into(), cached_expr)),
1767                        };
1768
1769                        uncached_expr = Some((optimized_expr.clone(), optimizer_features));
1770
1771                        (Arc::new(raw_expr), Arc::new(optimized_expr))
1772                    }
1773                };
1774
1775                // Resolve all item dependencies from the HIR expression.
1776                let dependencies: BTreeSet<_> = raw_expr
1777                    .depends_on()
1778                    .into_iter()
1779                    .map(|gid| self.get_entry_by_global_id(&gid).id())
1780                    .collect();
1781
1782                let typ = infer_sql_type_for_catalog(&raw_expr, &optimized_expr);
1783                CatalogItem::View(View {
1784                    create_sql: view.create_sql,
1785                    global_id,
1786                    raw_expr,
1787                    desc: RelationDesc::new(typ, view.column_names),
1788                    locally_optimized_expr: optimized_expr,
1789                    conn_id: None,
1790                    resolved_ids,
1791                    dependencies: DependencyIds(dependencies),
1792                })
1793            }
1794            Plan::CreateMaterializedView(CreateMaterializedViewPlan {
1795                materialized_view, ..
1796            }) => {
1797                let collections = extra_versions
1798                    .iter()
1799                    .map(|(version, gid)| (*version, *gid))
1800                    .chain([(RelationVersion::root(), global_id)].into_iter())
1801                    .collect();
1802
1803                // Collect optimizer parameters.
1804                let system_vars = session_catalog.system_vars();
1805                let overrides = self
1806                    .get_cluster(materialized_view.cluster_id)
1807                    .config
1808                    .features();
1809                let optimizer_config =
1810                    optimize::OptimizerConfig::from(system_vars).override_from(&overrides);
1811                let previous_exprs = previous_item.map(|item| match item {
1812                    CatalogItem::MaterializedView(materialized_view) => (
1813                        materialized_view.raw_expr,
1814                        materialized_view.locally_optimized_expr,
1815                    ),
1816                    item => unreachable!("expected materialized view, found: {item:#?}"),
1817                });
1818
1819                let (raw_expr, optimized_expr) = match (cached_expr, previous_exprs) {
1820                    (Some(local_expr), _)
1821                        if local_expr.optimizer_features == optimizer_config.features =>
1822                    {
1823                        debug!("local expression cache hit for {global_id:?}");
1824                        (
1825                            Arc::new(materialized_view.expr),
1826                            Arc::new(local_expr.local_mir),
1827                        )
1828                    }
1829                    // If the new expr is equivalent to the old expr, then we don't need to re-optimize.
1830                    (_, Some((raw_expr, optimized_expr)))
1831                        if *raw_expr == materialized_view.expr =>
1832                    {
1833                        (Arc::clone(&raw_expr), Arc::clone(&optimized_expr))
1834                    }
1835                    (cached_expr, _) => {
1836                        let optimizer_features = optimizer_config.features.clone();
1837                        // TODO(aalexandrov): ideally this should be a materialized_view::Optimizer.
1838                        let mut optimizer = optimize::view::Optimizer::new(optimizer_config, None);
1839
1840                        let raw_expr = materialized_view.expr;
1841                        let optimized_expr = match optimizer.optimize(raw_expr.clone()) {
1842                            Ok(optimized_expr) => optimized_expr,
1843                            Err(err) => return Err((err.into(), cached_expr)),
1844                        };
1845
1846                        uncached_expr = Some((optimized_expr.clone(), optimizer_features));
1847
1848                        (Arc::new(raw_expr), Arc::new(optimized_expr))
1849                    }
1850                };
1851                let mut typ = infer_sql_type_for_catalog(&raw_expr, &optimized_expr);
1852
1853                for &i in &materialized_view.non_null_assertions {
1854                    typ.column_types[i].nullable = false;
1855                }
1856                let desc = RelationDesc::new(typ, materialized_view.column_names);
1857                let desc = VersionedRelationDesc::new(desc);
1858
1859                let initial_as_of = materialized_view.as_of.map(Antichain::from_elem);
1860
1861                // Resolve all item dependencies from the HIR expression.
1862                let dependencies = raw_expr
1863                    .depends_on()
1864                    .into_iter()
1865                    .map(|gid| self.get_entry_by_global_id(&gid).id())
1866                    .collect();
1867
1868                CatalogItem::MaterializedView(MaterializedView {
1869                    create_sql: materialized_view.create_sql,
1870                    collections,
1871                    raw_expr,
1872                    locally_optimized_expr: optimized_expr,
1873                    desc,
1874                    resolved_ids,
1875                    dependencies,
1876                    replacement_target: materialized_view.replacement_target,
1877                    cluster_id: materialized_view.cluster_id,
1878                    target_replica: materialized_view.target_replica,
1879                    non_null_assertions: materialized_view.non_null_assertions,
1880                    custom_logical_compaction_window: materialized_view.compaction_window,
1881                    refresh_schedule: materialized_view.refresh_schedule,
1882                    initial_as_of,
1883                    optimized_plan: None,
1884                    physical_plan: None,
1885                    dataflow_metainfo: None,
1886                })
1887            }
1888            Plan::CreateIndex(CreateIndexPlan { index, .. }) => CatalogItem::Index(Index {
1889                create_sql: index.create_sql,
1890                global_id,
1891                on: index.on,
1892                keys: index.keys.into(),
1893                conn_id: None,
1894                resolved_ids,
1895                cluster_id: index.cluster_id,
1896                custom_logical_compaction_window: custom_logical_compaction_window
1897                    .or(index.compaction_window),
1898                is_retained_metrics_object,
1899                optimized_plan: None,
1900                physical_plan: None,
1901                dataflow_metainfo: None,
1902            }),
1903            Plan::CreateMetricSink(CreateMetricSinkPlan { metric_sink, .. }) => {
1904                CatalogItem::MetricSink(MetricSink {
1905                    create_sql: metric_sink.create_sql,
1906                    global_id,
1907                    from: metric_sink.from,
1908                    resolved_ids,
1909                    cluster_id: metric_sink.cluster_id,
1910                    prefix: metric_sink.prefix,
1911                    optimized_plan: None,
1912                    physical_plan: None,
1913                    dataflow_metainfo: None,
1914                })
1915            }
1916            Plan::CreateSink(CreateSinkPlan {
1917                sink,
1918                with_snapshot,
1919                in_cluster,
1920                ..
1921            }) => CatalogItem::Sink(Sink {
1922                create_sql: sink.create_sql,
1923                global_id,
1924                from: sink.from,
1925                connection: sink.connection,
1926                envelope: sink.envelope,
1927                version: sink.version,
1928                with_snapshot,
1929                resolved_ids,
1930                cluster_id: in_cluster,
1931                commit_interval: sink.commit_interval,
1932            }),
1933            Plan::CreateType(CreateTypePlan { typ, .. }) => {
1934                // Even if we don't need the `RelationDesc` here, error out
1935                // early and eagerly, as a kind of soft assertion that we _can_
1936                // build the `RelationDesc` when needed.
1937                if let Err(err) = typ.inner.desc(&session_catalog) {
1938                    return Err((err.into(), cached_expr));
1939                }
1940                CatalogItem::Type(Type {
1941                    create_sql: Some(typ.create_sql),
1942                    global_id,
1943                    details: CatalogTypeDetails {
1944                        array_id: None,
1945                        typ: typ.inner,
1946                        pg_metadata: None,
1947                    },
1948                    resolved_ids,
1949                })
1950            }
1951            Plan::CreateSecret(CreateSecretPlan { secret, .. }) => CatalogItem::Secret(Secret {
1952                create_sql: secret.create_sql,
1953                global_id,
1954            }),
1955            Plan::CreateConnection(CreateConnectionPlan {
1956                connection:
1957                    mz_sql::plan::Connection {
1958                        create_sql,
1959                        details,
1960                    },
1961                ..
1962            }) => CatalogItem::Connection(Connection {
1963                create_sql,
1964                global_id,
1965                details,
1966                resolved_ids,
1967            }),
1968            _ => {
1969                return Err((
1970                    Error::new(ErrorKind::Corruption {
1971                        detail: "catalog entry generated inappropriate plan".to_string(),
1972                    })
1973                    .into(),
1974                    cached_expr,
1975                ));
1976            }
1977        };
1978
1979        // Carry over the plans (`optimized_plan`, `physical_plan`,
1980        // `dataflow_metainfo`) from the previous incarnation of this item, if
1981        // any. See the comment on `previous_plans` above.
1982        if let Some((prev_optimized, prev_physical, prev_metainfo)) = previous_plans {
1983            if let Some((optimized_plan, physical_plan, dataflow_metainfo)) = item.plan_fields_mut()
1984            {
1985                *optimized_plan = prev_optimized;
1986                *physical_plan = prev_physical;
1987                *dataflow_metainfo = prev_metainfo;
1988            }
1989        }
1990
1991        Ok((item, uncached_expr))
1992    }
1993
1994    /// Execute function `f` on `self`, with all "enable_for_item_parsing" feature flags enabled.
1995    /// Calling this method will not permanently modify any system configuration variables.
1996    ///
1997    /// WARNING:
1998    /// Any modifications made to the system configuration variables in `f`, will be lost.
1999    pub fn with_enable_for_item_parsing<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
2000        // Enable catalog features that might be required during planning existing
2001        // catalog items. Existing catalog items might have been created while
2002        // a specific feature flag was turned on, so we need to ensure that this
2003        // is also the case during catalog rehydration in order to avoid panics.
2004        //
2005        // WARNING / CONTRACT:
2006        // 1. Features used in this method that related to parsing / planning
2007        //    should be `enable_for_item_parsing` set to `true`.
2008        // 2. After this step, feature flag configuration must not be
2009        //    overridden.
2010        // 3. We don't notify `SystemVars` callbacks here, neither for the
2011        //    flags this enables nor for the `Arc` restore that undoes them
2012        //    afterwards. A callback on a `feature_flags!` var therefore won't
2013        //    observe this transient flip, only committed changes to it. See
2014        //    `SystemVars::register_callback`.
2015        let restore = Arc::clone(&self.system_configuration);
2016        Arc::make_mut(&mut self.system_configuration).enable_for_item_parsing();
2017        let res = f(self);
2018        self.system_configuration = restore;
2019        res
2020    }
2021
2022    /// Returns all indexes on the given object and cluster known in the catalog.
2023    pub fn get_indexes_on(
2024        &self,
2025        id: GlobalId,
2026        cluster: ClusterId,
2027    ) -> impl Iterator<Item = (GlobalId, &Index)> {
2028        let index_matches = move |idx: &Index| idx.on == id && idx.cluster_id == cluster;
2029
2030        self.try_get_entry_by_global_id(&id)
2031            .into_iter()
2032            .map(move |e| {
2033                e.used_by()
2034                    .iter()
2035                    .filter_map(move |uses_id| match self.get_entry(uses_id).item() {
2036                        CatalogItem::Index(index) if index_matches(index) => {
2037                            Some((index.global_id(), index))
2038                        }
2039                        _ => None,
2040                    })
2041            })
2042            .flatten()
2043    }
2044
2045    pub(super) fn get_database(&self, database_id: &DatabaseId) -> &Database {
2046        &self.database_by_id[database_id]
2047    }
2048
2049    /// Gets a reference to the specified replica of the specified cluster.
2050    ///
2051    /// Returns `None` if either the cluster or the replica does not
2052    /// exist.
2053    pub(super) fn try_get_cluster_replica(
2054        &self,
2055        id: ClusterId,
2056        replica_id: ReplicaId,
2057    ) -> Option<&ClusterReplica> {
2058        self.try_get_cluster(id)
2059            .and_then(|cluster| cluster.replica(replica_id))
2060    }
2061
2062    /// Gets a reference to the specified replica of the specified cluster.
2063    ///
2064    /// Panics if either the cluster or the replica does not exist.
2065    pub(crate) fn get_cluster_replica(
2066        &self,
2067        cluster_id: ClusterId,
2068        replica_id: ReplicaId,
2069    ) -> &ClusterReplica {
2070        self.try_get_cluster_replica(cluster_id, replica_id)
2071            .unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"))
2072    }
2073
2074    pub(super) fn resolve_replica_in_cluster(
2075        &self,
2076        cluster_id: &ClusterId,
2077        replica_name: &str,
2078    ) -> Result<&ClusterReplica, SqlCatalogError> {
2079        let cluster = self.get_cluster(*cluster_id);
2080        let replica_id = cluster
2081            .replica_id_by_name_
2082            .get(replica_name)
2083            .ok_or_else(|| SqlCatalogError::UnknownClusterReplica(replica_name.to_string()))?;
2084        Ok(&cluster.replicas_by_id_[replica_id])
2085    }
2086
2087    /// Get system configuration `name`.
2088    pub fn get_system_configuration(&self, name: &str) -> Result<&dyn Var, Error> {
2089        Ok(self.system_configuration.get(name)?)
2090    }
2091
2092    /// Parse system configuration `name` with `value` int.
2093    ///
2094    /// Returns the parsed value as a string.
2095    pub(super) fn parse_system_configuration(
2096        &self,
2097        name: &str,
2098        value: VarInput,
2099    ) -> Result<String, Error> {
2100        let value = self.system_configuration.parse(name, value)?;
2101        Ok(value.format())
2102    }
2103
2104    /// Gets the schema map for the database matching `database_spec`.
2105    pub(super) fn resolve_schema_in_database(
2106        &self,
2107        database_spec: &ResolvedDatabaseSpecifier,
2108        schema_name: &str,
2109        conn_id: &ConnectionId,
2110    ) -> Result<&Schema, SqlCatalogError> {
2111        let schema = match database_spec {
2112            ResolvedDatabaseSpecifier::Ambient if schema_name == MZ_TEMP_SCHEMA => {
2113                self.temporary_namespaces.schema(conn_id)
2114            }
2115            ResolvedDatabaseSpecifier::Ambient => self
2116                .ambient_schemas_by_name
2117                .get(schema_name)
2118                .and_then(|id| self.ambient_schemas_by_id.get(id)),
2119            ResolvedDatabaseSpecifier::Id(id) => self.database_by_id.get(id).and_then(|db| {
2120                db.schemas_by_name
2121                    .get(schema_name)
2122                    .and_then(|id| db.schemas_by_id.get(id))
2123            }),
2124        };
2125        schema.ok_or_else(|| SqlCatalogError::UnknownSchema(schema_name.into()))
2126    }
2127
2128    /// Try to get a schema, returning `None` if it doesn't exist.
2129    ///
2130    /// For temporary schemas, returns `None` if the connection's temporary
2131    /// namespace hasn't been registered yet (that happens at its first
2132    /// temporary-item creation).
2133    pub fn try_get_schema(
2134        &self,
2135        database_spec: &ResolvedDatabaseSpecifier,
2136        schema_spec: &SchemaSpecifier,
2137        conn_id: &ConnectionId,
2138    ) -> Option<&Schema> {
2139        // Keep in sync with `get_schema` and `get_schemas_mut`
2140        match (database_spec, schema_spec) {
2141            (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Temporary) => {
2142                self.temporary_namespaces.schema(conn_id)
2143            }
2144            (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Id(id)) => {
2145                self.ambient_schemas_by_id.get(id)
2146            }
2147            (ResolvedDatabaseSpecifier::Id(database_id), SchemaSpecifier::Id(schema_id)) => self
2148                .database_by_id
2149                .get(database_id)
2150                .and_then(|db| db.schemas_by_id.get(schema_id)),
2151            (ResolvedDatabaseSpecifier::Id(_), SchemaSpecifier::Temporary) => {
2152                unreachable!("temporary schemas are in the ambient database")
2153            }
2154        }
2155    }
2156
2157    pub fn get_schema(
2158        &self,
2159        database_spec: &ResolvedDatabaseSpecifier,
2160        schema_spec: &SchemaSpecifier,
2161        conn_id: &ConnectionId,
2162    ) -> &Schema {
2163        // Keep in sync with `try_get_schema` and `get_schemas_mut`
2164        self.try_get_schema(database_spec, schema_spec, conn_id)
2165            .expect("schema must exist")
2166    }
2167
2168    pub(super) fn find_non_temp_schema(&self, schema_id: &SchemaId) -> &Schema {
2169        self.database_by_id
2170            .values()
2171            .filter_map(|database| database.schemas_by_id.get(schema_id))
2172            .chain(self.ambient_schemas_by_id.values())
2173            .filter(|schema| schema.id() == &SchemaSpecifier::from(*schema_id))
2174            .into_first()
2175    }
2176
2177    pub fn get_mz_catalog_schema_id(&self) -> SchemaId {
2178        self.ambient_schemas_by_name[MZ_CATALOG_SCHEMA]
2179    }
2180
2181    pub fn get_mz_catalog_unstable_schema_id(&self) -> SchemaId {
2182        self.ambient_schemas_by_name[MZ_CATALOG_UNSTABLE_SCHEMA]
2183    }
2184
2185    pub fn get_pg_catalog_schema_id(&self) -> SchemaId {
2186        self.ambient_schemas_by_name[PG_CATALOG_SCHEMA]
2187    }
2188
2189    pub fn get_information_schema_id(&self) -> SchemaId {
2190        self.ambient_schemas_by_name[INFORMATION_SCHEMA]
2191    }
2192
2193    pub fn get_mz_internal_schema_id(&self) -> SchemaId {
2194        self.ambient_schemas_by_name[MZ_INTERNAL_SCHEMA]
2195    }
2196
2197    pub fn get_mz_introspection_schema_id(&self) -> SchemaId {
2198        self.ambient_schemas_by_name[MZ_INTROSPECTION_SCHEMA]
2199    }
2200
2201    pub fn get_mz_unsafe_schema_id(&self) -> SchemaId {
2202        self.ambient_schemas_by_name[MZ_UNSAFE_SCHEMA]
2203    }
2204
2205    pub fn system_schema_ids(&self) -> impl Iterator<Item = SchemaId> + '_ {
2206        SYSTEM_SCHEMAS
2207            .iter()
2208            .map(|name| self.ambient_schemas_by_name[*name])
2209    }
2210
2211    pub fn is_system_schema_id(&self, id: SchemaId) -> bool {
2212        self.system_schema_ids().contains(&id)
2213    }
2214
2215    pub fn is_system_schema_specifier(&self, spec: SchemaSpecifier) -> bool {
2216        match spec {
2217            SchemaSpecifier::Temporary => false,
2218            SchemaSpecifier::Id(id) => self.is_system_schema_id(id),
2219        }
2220    }
2221
2222    pub fn unstable_schema_ids(&self) -> impl Iterator<Item = SchemaId> + '_ {
2223        UNSTABLE_SCHEMAS
2224            .iter()
2225            .map(|name| self.ambient_schemas_by_name[*name])
2226    }
2227
2228    pub fn is_unstable_schema_id(&self, id: SchemaId) -> bool {
2229        self.unstable_schema_ids().contains(&id)
2230    }
2231
2232    pub fn is_unstable_schema_specifier(&self, spec: SchemaSpecifier) -> bool {
2233        match spec {
2234            SchemaSpecifier::Temporary => false,
2235            SchemaSpecifier::Id(id) => self.is_unstable_schema_id(id),
2236        }
2237    }
2238
2239    /// Return all OIDs that are allocated to temporary objects.
2240    pub(crate) fn get_temporary_oids(&self) -> impl Iterator<Item = u32> + '_ {
2241        std::iter::empty()
2242            .chain(self.ambient_schemas_by_id.values().filter_map(|schema| {
2243                if schema.id.is_temporary() {
2244                    Some(schema.oid)
2245                } else {
2246                    None
2247                }
2248            }))
2249            .chain(self.entry_by_id.values().filter_map(|entry| {
2250                if entry.item().is_temporary() {
2251                    Some(entry.oid)
2252                } else {
2253                    None
2254                }
2255            }))
2256    }
2257
2258    /// Optimized lookup for a builtin table.
2259    ///
2260    /// Panics if the builtin table doesn't exist in the catalog.
2261    pub fn resolve_builtin_table(&self, builtin: &'static BuiltinTable) -> CatalogItemId {
2262        self.resolve_builtin_object(&Builtin::<IdReference>::Table(builtin))
2263    }
2264
2265    /// Optimized lookup for a builtin log.
2266    ///
2267    /// Panics if the builtin log doesn't exist in the catalog.
2268    pub fn resolve_builtin_log(&self, builtin: &'static BuiltinLog) -> (CatalogItemId, GlobalId) {
2269        let item_id = self.resolve_builtin_object(&Builtin::<IdReference>::Log(builtin));
2270        let log = match self.get_entry(&item_id).item() {
2271            CatalogItem::Log(log) => log,
2272            other => unreachable!("programming error, expected BuiltinLog, found {other:?}"),
2273        };
2274        (item_id, log.global_id)
2275    }
2276
2277    /// Optimized lookup for a builtin storage collection.
2278    ///
2279    /// Panics if the builtin storage collection doesn't exist in the catalog.
2280    pub fn resolve_builtin_source(&self, builtin: &'static BuiltinSource) -> CatalogItemId {
2281        self.resolve_builtin_object(&Builtin::<IdReference>::Source(builtin))
2282    }
2283
2284    /// Optimized lookup for a builtin object.
2285    ///
2286    /// Panics if the builtin object doesn't exist in the catalog.
2287    pub fn resolve_builtin_object<T: TypeReference>(&self, builtin: &Builtin<T>) -> CatalogItemId {
2288        let schema_id = &self.ambient_schemas_by_name[builtin.schema()];
2289        let schema = &self.ambient_schemas_by_id[schema_id];
2290        match builtin.catalog_item_type() {
2291            CatalogItemType::Type => schema.types[builtin.name()],
2292            CatalogItemType::Func => schema.functions[builtin.name()],
2293            CatalogItemType::Table
2294            | CatalogItemType::Source
2295            | CatalogItemType::Sink
2296            | CatalogItemType::MetricSink
2297            | CatalogItemType::View
2298            | CatalogItemType::MaterializedView
2299            | CatalogItemType::Index
2300            | CatalogItemType::Secret
2301            | CatalogItemType::Connection => schema.items[builtin.name()],
2302        }
2303    }
2304
2305    /// Resolve a [`BuiltinType<NameReference>`] to a [`BuiltinType<IdReference>`].
2306    pub fn resolve_builtin_type_references(
2307        &self,
2308        builtin: &BuiltinType<NameReference>,
2309    ) -> BuiltinType<IdReference> {
2310        let typ: CatalogType<IdReference> = match &builtin.details.typ {
2311            CatalogType::AclItem => CatalogType::AclItem,
2312            CatalogType::Array { element_reference } => CatalogType::Array {
2313                element_reference: self.get_system_type(element_reference).id,
2314            },
2315            CatalogType::List {
2316                element_reference,
2317                element_modifiers,
2318            } => CatalogType::List {
2319                element_reference: self.get_system_type(element_reference).id,
2320                element_modifiers: element_modifiers.clone(),
2321            },
2322            CatalogType::Map {
2323                key_reference,
2324                value_reference,
2325                key_modifiers,
2326                value_modifiers,
2327            } => CatalogType::Map {
2328                key_reference: self.get_system_type(key_reference).id,
2329                value_reference: self.get_system_type(value_reference).id,
2330                key_modifiers: key_modifiers.clone(),
2331                value_modifiers: value_modifiers.clone(),
2332            },
2333            CatalogType::Range { element_reference } => CatalogType::Range {
2334                element_reference: self.get_system_type(element_reference).id,
2335            },
2336            CatalogType::Record { fields } => CatalogType::Record {
2337                fields: fields
2338                    .into_iter()
2339                    .map(|f| CatalogRecordField {
2340                        name: f.name.clone(),
2341                        type_reference: self.get_system_type(f.type_reference).id,
2342                        type_modifiers: f.type_modifiers.clone(),
2343                    })
2344                    .collect(),
2345            },
2346            CatalogType::Bool => CatalogType::Bool,
2347            CatalogType::Bytes => CatalogType::Bytes,
2348            CatalogType::Char => CatalogType::Char,
2349            CatalogType::Date => CatalogType::Date,
2350            CatalogType::Float32 => CatalogType::Float32,
2351            CatalogType::Float64 => CatalogType::Float64,
2352            CatalogType::Int16 => CatalogType::Int16,
2353            CatalogType::Int32 => CatalogType::Int32,
2354            CatalogType::Int64 => CatalogType::Int64,
2355            CatalogType::UInt16 => CatalogType::UInt16,
2356            CatalogType::UInt32 => CatalogType::UInt32,
2357            CatalogType::UInt64 => CatalogType::UInt64,
2358            CatalogType::MzTimestamp => CatalogType::MzTimestamp,
2359            CatalogType::Interval => CatalogType::Interval,
2360            CatalogType::Jsonb => CatalogType::Jsonb,
2361            CatalogType::Numeric => CatalogType::Numeric,
2362            CatalogType::Oid => CatalogType::Oid,
2363            CatalogType::PgLegacyChar => CatalogType::PgLegacyChar,
2364            CatalogType::PgLegacyName => CatalogType::PgLegacyName,
2365            CatalogType::Pseudo => CatalogType::Pseudo,
2366            CatalogType::RegClass => CatalogType::RegClass,
2367            CatalogType::RegProc => CatalogType::RegProc,
2368            CatalogType::RegType => CatalogType::RegType,
2369            CatalogType::String => CatalogType::String,
2370            CatalogType::Time => CatalogType::Time,
2371            CatalogType::Timestamp => CatalogType::Timestamp,
2372            CatalogType::TimestampTz => CatalogType::TimestampTz,
2373            CatalogType::Uuid => CatalogType::Uuid,
2374            CatalogType::VarChar => CatalogType::VarChar,
2375            CatalogType::Int2Vector => CatalogType::Int2Vector,
2376            CatalogType::MzAclItem => CatalogType::MzAclItem,
2377        };
2378
2379        BuiltinType {
2380            name: builtin.name,
2381            schema: builtin.schema,
2382            oid: builtin.oid,
2383            details: CatalogTypeDetails {
2384                array_id: builtin.details.array_id,
2385                typ,
2386                pg_metadata: builtin.details.pg_metadata.clone(),
2387            },
2388        }
2389    }
2390
2391    pub fn config(&self) -> &mz_sql::catalog::CatalogConfig {
2392        &self.config
2393    }
2394
2395    pub fn resolve_database(&self, database_name: &str) -> Result<&Database, SqlCatalogError> {
2396        match self.database_by_name.get(database_name) {
2397            Some(id) => Ok(&self.database_by_id[id]),
2398            None => Err(SqlCatalogError::UnknownDatabase(database_name.into())),
2399        }
2400    }
2401
2402    pub fn resolve_schema(
2403        &self,
2404        current_database: Option<&DatabaseId>,
2405        database_name: Option<&str>,
2406        schema_name: &str,
2407        conn_id: &ConnectionId,
2408    ) -> Result<&Schema, SqlCatalogError> {
2409        let database_spec = match database_name {
2410            // If a database is explicitly specified, validate it. Note that we
2411            // intentionally do not validate `current_database` to permit
2412            // querying `mz_catalog` with an invalid session database, e.g., so
2413            // that you can run `SHOW DATABASES` to *find* a valid database.
2414            Some(database) => Some(ResolvedDatabaseSpecifier::Id(
2415                self.resolve_database(database)?.id().clone(),
2416            )),
2417            None => current_database.map(|id| ResolvedDatabaseSpecifier::Id(id.clone())),
2418        };
2419
2420        // First try to find the schema in the named database.
2421        if let Some(database_spec) = database_spec {
2422            if let Ok(schema) =
2423                self.resolve_schema_in_database(&database_spec, schema_name, conn_id)
2424            {
2425                return Ok(schema);
2426            }
2427        }
2428
2429        // Then fall back to the ambient database.
2430        if let Ok(schema) = self.resolve_schema_in_database(
2431            &ResolvedDatabaseSpecifier::Ambient,
2432            schema_name,
2433            conn_id,
2434        ) {
2435            return Ok(schema);
2436        }
2437
2438        Err(SqlCatalogError::UnknownSchema(schema_name.into()))
2439    }
2440
2441    /// Optimized lookup for a system schema.
2442    ///
2443    /// Panics if the system schema doesn't exist in the catalog.
2444    pub fn resolve_system_schema(&self, name: &'static str) -> SchemaId {
2445        self.ambient_schemas_by_name[name]
2446    }
2447
2448    pub fn resolve_search_path(
2449        &self,
2450        session: &dyn SessionMetadata,
2451    ) -> Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)> {
2452        let database = self
2453            .database_by_name
2454            .get(session.database())
2455            .map(|id| id.clone());
2456
2457        // NOTE: This drops schemas that don't resolve, and consumers rely on
2458        // every returned entry existing (e.g. `allocate_full_name` and the
2459        // `current_schemas` evaluation look schemas up infallibly). In
2460        // particular, `mz_temp` is dropped until the session's temporary
2461        // namespace is registered at its first temporary-item creation.
2462        session
2463            .search_path()
2464            .iter()
2465            .map(|schema| {
2466                self.resolve_schema(database.as_ref(), None, schema.as_str(), session.conn_id())
2467            })
2468            .filter_map(|schema| schema.ok())
2469            .map(|schema| (schema.name().database.clone(), schema.id().clone()))
2470            .collect()
2471    }
2472
2473    pub fn effective_search_path(
2474        &self,
2475        search_path: &[(ResolvedDatabaseSpecifier, SchemaSpecifier)],
2476        include_temp_schema: bool,
2477    ) -> Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)> {
2478        let mut v = Vec::with_capacity(search_path.len() + 3);
2479        // Temp schema is only included for relations and data types, not for functions and operators
2480        let temp_schema = (
2481            ResolvedDatabaseSpecifier::Ambient,
2482            SchemaSpecifier::Temporary,
2483        );
2484        if include_temp_schema && !search_path.contains(&temp_schema) {
2485            v.push(temp_schema);
2486        }
2487        let default_schemas = [
2488            (
2489                ResolvedDatabaseSpecifier::Ambient,
2490                SchemaSpecifier::Id(self.get_mz_catalog_schema_id()),
2491            ),
2492            (
2493                ResolvedDatabaseSpecifier::Ambient,
2494                SchemaSpecifier::Id(self.get_pg_catalog_schema_id()),
2495            ),
2496        ];
2497        for schema in default_schemas.into_iter() {
2498            if !search_path.contains(&schema) {
2499                v.push(schema);
2500            }
2501        }
2502        v.extend_from_slice(search_path);
2503        v
2504    }
2505
2506    pub fn resolve_cluster(&self, name: &str) -> Result<&Cluster, SqlCatalogError> {
2507        let id = self
2508            .clusters_by_name
2509            .get(name)
2510            .ok_or_else(|| SqlCatalogError::UnknownCluster(name.to_string()))?;
2511        Ok(&self.clusters_by_id[id])
2512    }
2513
2514    pub fn resolve_builtin_cluster(&self, cluster: &BuiltinCluster) -> &Cluster {
2515        let id = self
2516            .clusters_by_name
2517            .get(cluster.name)
2518            .expect("failed to lookup BuiltinCluster by name");
2519        self.clusters_by_id
2520            .get(id)
2521            .expect("failed to lookup BuiltinCluster by ID")
2522    }
2523
2524    pub fn resolve_cluster_replica(
2525        &self,
2526        cluster_replica_name: &QualifiedReplica,
2527    ) -> Result<&ClusterReplica, SqlCatalogError> {
2528        let cluster = self.resolve_cluster(cluster_replica_name.cluster.as_str())?;
2529        let replica_name = cluster_replica_name.replica.as_str();
2530        let replica_id = cluster
2531            .replica_id(replica_name)
2532            .ok_or_else(|| SqlCatalogError::UnknownClusterReplica(replica_name.to_string()))?;
2533        Ok(cluster.replica(replica_id).expect("Must exist"))
2534    }
2535
2536    /// Resolves [`PartialItemName`] into a [`CatalogEntry`].
2537    ///
2538    /// If `name` does not specify a database, the `current_database` is used.
2539    /// If `name` does not specify a schema, then the schemas in `search_path`
2540    /// are searched in order.
2541    #[allow(clippy::useless_let_if_seq)]
2542    pub fn resolve(
2543        &self,
2544        get_schema_entries: fn(&Schema) -> &BTreeMap<String, CatalogItemId>,
2545        current_database: Option<&DatabaseId>,
2546        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
2547        name: &PartialItemName,
2548        conn_id: &ConnectionId,
2549        err_gen: fn(String) -> SqlCatalogError,
2550    ) -> Result<&CatalogEntry, SqlCatalogError> {
2551        // If a schema name was specified, just try to find the item in that
2552        // schema. If no schema was specified, try to find the item in the connection's
2553        // temporary schema. If the item is not found, try to find the item in every
2554        // schema in the search path.
2555        let schemas = match &name.schema {
2556            Some(schema_name) => {
2557                match self.resolve_schema(
2558                    current_database,
2559                    name.database.as_deref(),
2560                    schema_name,
2561                    conn_id,
2562                ) {
2563                    Ok(schema) => vec![(schema.name.database.clone(), schema.id.clone())],
2564                    Err(e) => return Err(e),
2565                }
2566            }
2567            None => match self
2568                .try_get_schema(
2569                    &ResolvedDatabaseSpecifier::Ambient,
2570                    &SchemaSpecifier::Temporary,
2571                    conn_id,
2572                )
2573                .and_then(|schema| schema.items.get(&name.item))
2574            {
2575                Some(id) => return Ok(self.get_entry(id)),
2576                None => search_path.to_vec(),
2577            },
2578        };
2579
2580        for (database_spec, schema_spec) in &schemas {
2581            // Use try_get_schema because the temp schema might not exist yet
2582            // (it's created lazily when the first temp object is created).
2583            let Some(schema) = self.try_get_schema(database_spec, schema_spec, conn_id) else {
2584                continue;
2585            };
2586
2587            if let Some(id) = get_schema_entries(schema).get(&name.item) {
2588                return Ok(&self.entry_by_id[id]);
2589            }
2590        }
2591
2592        // Some relations that have previously lived in the `mz_internal` schema have been moved to
2593        // `mz_catalog_unstable` or `mz_introspection`. To simplify the transition for users, we
2594        // automatically let uses of the old schema resolve to the new ones as well.
2595        // TODO(database-issues#8173) remove this after sufficient time has passed
2596        let mz_internal_schema = SchemaSpecifier::Id(self.get_mz_internal_schema_id());
2597        if schemas.iter().any(|(_, spec)| *spec == mz_internal_schema) {
2598            for schema_id in [
2599                self.get_mz_catalog_unstable_schema_id(),
2600                self.get_mz_introspection_schema_id(),
2601            ] {
2602                let schema = self.get_schema(
2603                    &ResolvedDatabaseSpecifier::Ambient,
2604                    &SchemaSpecifier::Id(schema_id),
2605                    conn_id,
2606                );
2607
2608                if let Some(id) = get_schema_entries(schema).get(&name.item) {
2609                    debug!(
2610                        github_27831 = true,
2611                        "encountered use of outdated schema `mz_internal` for relation: {name}",
2612                    );
2613                    return Ok(&self.entry_by_id[id]);
2614                }
2615            }
2616        }
2617
2618        Err(err_gen(name.to_string()))
2619    }
2620
2621    /// Resolves `name` to a non-function [`CatalogEntry`].
2622    pub fn resolve_entry(
2623        &self,
2624        current_database: Option<&DatabaseId>,
2625        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
2626        name: &PartialItemName,
2627        conn_id: &ConnectionId,
2628    ) -> Result<&CatalogEntry, SqlCatalogError> {
2629        self.resolve(
2630            |schema| &schema.items,
2631            current_database,
2632            search_path,
2633            name,
2634            conn_id,
2635            SqlCatalogError::UnknownItem,
2636        )
2637    }
2638
2639    /// Resolves `name` to a function [`CatalogEntry`].
2640    pub fn resolve_function(
2641        &self,
2642        current_database: Option<&DatabaseId>,
2643        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
2644        name: &PartialItemName,
2645        conn_id: &ConnectionId,
2646    ) -> Result<&CatalogEntry, SqlCatalogError> {
2647        self.resolve(
2648            |schema| &schema.functions,
2649            current_database,
2650            search_path,
2651            name,
2652            conn_id,
2653            |name| SqlCatalogError::UnknownFunction {
2654                name,
2655                alternative: None,
2656            },
2657        )
2658    }
2659
2660    /// Resolves `name` to a type [`CatalogEntry`].
2661    pub fn resolve_type(
2662        &self,
2663        current_database: Option<&DatabaseId>,
2664        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
2665        name: &PartialItemName,
2666        conn_id: &ConnectionId,
2667    ) -> Result<&CatalogEntry, SqlCatalogError> {
2668        static NON_PG_CATALOG_TYPES: LazyLock<
2669            BTreeMap<&'static str, &'static BuiltinType<NameReference>>,
2670        > = LazyLock::new(|| {
2671            BUILTINS::types()
2672                .filter(|typ| typ.schema != PG_CATALOG_SCHEMA)
2673                .map(|typ| (typ.name, typ))
2674                .collect()
2675        });
2676
2677        let entry = self.resolve(
2678            |schema| &schema.types,
2679            current_database,
2680            search_path,
2681            name,
2682            conn_id,
2683            |name| SqlCatalogError::UnknownType { name },
2684        )?;
2685
2686        if conn_id != &SYSTEM_CONN_ID && name.schema.as_deref() == Some(PG_CATALOG_SCHEMA) {
2687            if let Some(typ) = NON_PG_CATALOG_TYPES.get(entry.name().item.as_str()) {
2688                warn!(
2689                    "user specified an incorrect schema of {} for the type {}, which should be in \
2690                    the {} schema. This works now due to a bug but will be fixed in a later release.",
2691                    PG_CATALOG_SCHEMA.quoted(),
2692                    typ.name.quoted(),
2693                    typ.schema.quoted(),
2694                )
2695            }
2696        }
2697
2698        Ok(entry)
2699    }
2700
2701    /// For an [`ObjectId`] gets the corresponding [`CommentObjectId`].
2702    pub(super) fn get_comment_id(&self, object_id: ObjectId) -> CommentObjectId {
2703        match object_id {
2704            ObjectId::Item(item_id) => self.get_entry(&item_id).comment_object_id(),
2705            ObjectId::Role(role_id) => CommentObjectId::Role(role_id),
2706            ObjectId::Database(database_id) => CommentObjectId::Database(database_id),
2707            ObjectId::Schema((database, schema)) => CommentObjectId::Schema((database, schema)),
2708            ObjectId::Cluster(cluster_id) => CommentObjectId::Cluster(cluster_id),
2709            ObjectId::ClusterReplica(cluster_replica_id) => {
2710                CommentObjectId::ClusterReplica(cluster_replica_id)
2711            }
2712            ObjectId::NetworkPolicy(network_policy_id) => {
2713                CommentObjectId::NetworkPolicy(network_policy_id)
2714            }
2715            ObjectId::QueryPolicy(id) => CommentObjectId::QueryPolicy(id),
2716        }
2717    }
2718
2719    /// Return current system configuration.
2720    pub fn system_config(&self) -> &SystemVars {
2721        &self.system_configuration
2722    }
2723
2724    /// Returns the cluster-coherent scoped optimizer-feature overrides for
2725    /// `cluster_id` from the in-memory scoped-parameter working copy, or empty
2726    /// if the cluster has none.
2727    pub fn cluster_scoped_optimizer_overrides(
2728        &self,
2729        cluster_id: ClusterId,
2730    ) -> OptimizerFeatureOverrides {
2731        self.scoped_system_parameters
2732            .cluster
2733            .get(&cluster_id)
2734            .cloned()
2735            .map(OptimizerFeatureOverrides::from)
2736            .unwrap_or_default()
2737    }
2738
2739    /// Returns the entire scoped system-parameter working copy, read by the
2740    /// coordinator's scoped-parameter reconcile path.
2741    pub fn scoped_system_parameters(&self) -> &ScopedParameters {
2742        &self.scoped_system_parameters
2743    }
2744
2745    /// Return a mutable reference to the current system configuration.
2746    pub fn system_config_mut(&mut self) -> &mut SystemVars {
2747        Arc::make_mut(&mut self.system_configuration)
2748    }
2749
2750    /// Serializes the catalog's in-memory state.
2751    ///
2752    /// There are no guarantees about the format of the serialized state, except
2753    /// that the serialized state for two identical catalogs will compare
2754    /// identically.
2755    ///
2756    /// Some consumers would like the ability to overwrite the `unfinalized_shards` catalog field,
2757    /// which they can accomplish by passing in a value of `Some` for the `unfinalized_shards`
2758    /// argument.
2759    pub fn dump(&self, unfinalized_shards: Option<BTreeSet<String>>) -> Result<String, Error> {
2760        // Dump the base catalog.
2761        let mut dump = serde_json::to_value(&self).map_err(|e| {
2762            Error::new(ErrorKind::Unstructured(format!(
2763                // Don't panic here because we don't have compile-time failures for maps with
2764                // non-string keys.
2765                "internal error: could not dump catalog: {}",
2766                e
2767            )))
2768        })?;
2769
2770        let dump_obj = dump.as_object_mut().expect("state must have been dumped");
2771        // Stitch in system parameter defaults.
2772        dump_obj.insert(
2773            "system_parameter_defaults".into(),
2774            serde_json::json!(self.system_config().defaults()),
2775        );
2776        // Potentially overwrite unfinalized shards.
2777        if let Some(unfinalized_shards) = unfinalized_shards {
2778            dump_obj
2779                .get_mut("storage_metadata")
2780                .expect("known to exist")
2781                .as_object_mut()
2782                .expect("storage_metadata is an object")
2783                .insert(
2784                    "unfinalized_shards".into(),
2785                    serde_json::json!(unfinalized_shards),
2786                );
2787        }
2788        // Remove GlobalIds for temporary objects from the mapping.
2789        //
2790        // Post-test consistency checks with the durable catalog don't know about temporary items
2791        // since they're kept entirely in memory.
2792        let temporary_gids: Vec<_> = self
2793            .entry_by_global_id
2794            .iter()
2795            .filter(|(_gid, item_id)| self.get_entry(item_id).conn_id().is_some())
2796            .map(|(gid, _item_id)| *gid)
2797            .collect();
2798        if !temporary_gids.is_empty() {
2799            let gids = dump_obj
2800                .get_mut("entry_by_global_id")
2801                .expect("known_to_exist")
2802                .as_object_mut()
2803                .expect("entry_by_global_id is an object");
2804            for gid in temporary_gids {
2805                gids.remove(&gid.to_string());
2806            }
2807        }
2808        // We exclude role_auth_by_id because it contains password information
2809        // which should not be included in the dump.
2810        dump_obj.remove("role_auth_by_id");
2811        // The mock authentication nonce is a server-wide secret used to derive
2812        // deterministic mock SASL challenges for absent or password-less roles.
2813        // Leaking it would re-enable the username enumeration the mock challenge
2814        // defends against, so it must not appear in the dump either.
2815        dump_obj.remove("mock_authentication_nonce");
2816
2817        // Emit as pretty-printed JSON.
2818        Ok(serde_json::to_string_pretty(&dump).expect("cannot fail on serde_json::Value"))
2819    }
2820
2821    pub fn availability_zones(&self) -> &[String] {
2822        &self.availability_zones
2823    }
2824
2825    pub fn concretize_replica_location(
2826        &self,
2827        location: mz_catalog::durable::ReplicaLocation,
2828        allowed_sizes: &Vec<String>,
2829        allowed_availability_zones: Option<&[String]>,
2830        allow_disabled: bool,
2831    ) -> Result<ReplicaLocation, Error> {
2832        let location = match location {
2833            mz_catalog::durable::ReplicaLocation::Unmanaged {
2834                storagectl_addrs,
2835                computectl_addrs,
2836            } => {
2837                if allowed_availability_zones.is_some() {
2838                    return Err(Error {
2839                        kind: ErrorKind::Internal(
2840                            "tried concretize unmanaged replica with specific availability_zones"
2841                                .to_string(),
2842                        ),
2843                    });
2844                }
2845                ReplicaLocation::Unmanaged(UnmanagedReplicaLocation {
2846                    storagectl_addrs,
2847                    computectl_addrs,
2848                })
2849            }
2850            mz_catalog::durable::ReplicaLocation::Managed {
2851                size,
2852                // The AZ list the replica was provisioned under: provisioning
2853                // paths pass the cluster's pool as `allowed_availability_zones`
2854                // to stamp it, while rebuilds from durable state pass `None` to
2855                // keep it. For an unmanaged cluster's replica it is the single
2856                // user-pinned AZ.
2857                availability_zones,
2858                billed_as,
2859                internal,
2860                pending,
2861            } => {
2862                self.ensure_valid_replica_size(allowed_sizes, &size, allow_disabled)?;
2863                let cluster_replica_sizes = &self.cluster_replica_sizes;
2864
2865                ReplicaLocation::Managed(ManagedReplicaLocation {
2866                    allocation: cluster_replica_sizes
2867                        .0
2868                        .get(&size)
2869                        .expect("catalog out of sync")
2870                        .clone(),
2871                    availability_zones: match allowed_availability_zones {
2872                        Some(azs) => azs.to_vec(),
2873                        None => availability_zones,
2874                    },
2875                    size,
2876                    billed_as,
2877                    internal,
2878                    pending,
2879                })
2880            }
2881        };
2882        Ok(location)
2883    }
2884
2885    pub(crate) fn ensure_valid_replica_size(
2886        &self,
2887        allowed_sizes: &[String],
2888        size: &String,
2889        allow_disabled: bool,
2890    ) -> Result<(), Error> {
2891        let cluster_replica_sizes = &self.cluster_replica_sizes;
2892
2893        if !cluster_replica_sizes.0.contains_key(size)
2894            || (!allowed_sizes.is_empty() && !allowed_sizes.contains(size))
2895            || (!allow_disabled && cluster_replica_sizes.0[size].disabled)
2896        {
2897            let mut entries = cluster_replica_sizes
2898                .enabled_allocations()
2899                .collect::<Vec<_>>();
2900
2901            if !allowed_sizes.is_empty() {
2902                let allowed_sizes = BTreeSet::<&String>::from_iter(allowed_sizes.iter());
2903                entries.retain(|(name, _)| allowed_sizes.contains(name));
2904            }
2905
2906            entries.sort_by_key(
2907                |(
2908                    _name,
2909                    ReplicaAllocation {
2910                        scale, cpu_limit, ..
2911                    },
2912                )| (scale, cpu_limit),
2913            );
2914
2915            Err(Error {
2916                kind: ErrorKind::InvalidClusterReplicaSize {
2917                    size: size.to_owned(),
2918                    expected: entries.into_iter().map(|(name, _)| name.clone()).collect(),
2919                },
2920            })
2921        } else {
2922            Ok(())
2923        }
2924    }
2925
2926    pub fn ensure_not_reserved_role(&self, role_id: &RoleId) -> Result<(), Error> {
2927        if role_id.is_builtin() {
2928            let role = self.get_role(role_id);
2929            Err(Error::new(ErrorKind::ReservedRoleName(
2930                role.name().to_string(),
2931            )))
2932        } else {
2933            Ok(())
2934        }
2935    }
2936
2937    pub fn ensure_not_reserved_network_policy(
2938        &self,
2939        network_policy_id: &NetworkPolicyId,
2940    ) -> Result<(), Error> {
2941        if network_policy_id.is_builtin() {
2942            let policy = self.get_network_policy(network_policy_id);
2943            Err(Error::new(ErrorKind::ReservedNetworkPolicyName(
2944                policy.name.clone(),
2945            )))
2946        } else {
2947            Ok(())
2948        }
2949    }
2950
2951    pub fn ensure_grantable_role(&self, role_id: &RoleId) -> Result<(), Error> {
2952        let is_grantable = !role_id.is_public() && !role_id.is_system();
2953        if is_grantable {
2954            Ok(())
2955        } else {
2956            let role = self.get_role(role_id);
2957            Err(Error::new(ErrorKind::UngrantableRoleName(
2958                role.name().to_string(),
2959            )))
2960        }
2961    }
2962
2963    pub fn ensure_not_system_role(&self, role_id: &RoleId) -> Result<(), Error> {
2964        if role_id.is_system() {
2965            let role = self.get_role(role_id);
2966            Err(Error::new(ErrorKind::ReservedSystemRoleName(
2967                role.name().to_string(),
2968            )))
2969        } else {
2970            Ok(())
2971        }
2972    }
2973
2974    pub fn ensure_not_predefined_role(&self, role_id: &RoleId) -> Result<(), Error> {
2975        if role_id.is_predefined() {
2976            let role = self.get_role(role_id);
2977            Err(Error::new(ErrorKind::ReservedSystemRoleName(
2978                role.name().to_string(),
2979            )))
2980        } else {
2981            Ok(())
2982        }
2983    }
2984
2985    // TODO(mjibson): Is there a way to make this a closure to avoid explicitly
2986    // passing tx, and session?
2987    pub(crate) fn add_to_audit_log(
2988        system_configuration: &SystemVars,
2989        oracle_write_ts: mz_repr::Timestamp,
2990        session: Option<&ConnMeta>,
2991        tx: &mut mz_catalog::durable::Transaction,
2992        audit_events: &mut Vec<VersionedEvent>,
2993        event_type: EventType,
2994        object_type: ObjectType,
2995        details: EventDetails,
2996    ) -> Result<(), Error> {
2997        let user = session.map(|session| session.user().name.to_string());
2998
2999        // unsafe_mock_audit_event_timestamp can only be set to Some when running in unsafe mode.
3000
3001        let occurred_at = match system_configuration.unsafe_mock_audit_event_timestamp() {
3002            Some(ts) => ts.into(),
3003            _ => oracle_write_ts.into(),
3004        };
3005        let id = tx.allocate_audit_log_id()?;
3006        let event = VersionedEvent::new(id, event_type, object_type, details, user, occurred_at);
3007        audit_events.push(event.clone());
3008        tx.insert_audit_log_event(event);
3009        Ok(())
3010    }
3011
3012    pub(super) fn get_owner_id(&self, id: &ObjectId, conn_id: &ConnectionId) -> Option<RoleId> {
3013        match id {
3014            ObjectId::Cluster(id) => Some(self.get_cluster(*id).owner_id()),
3015            ObjectId::ClusterReplica((cluster_id, replica_id)) => Some(
3016                self.get_cluster_replica(*cluster_id, *replica_id)
3017                    .owner_id(),
3018            ),
3019            ObjectId::Database(id) => Some(self.get_database(id).owner_id()),
3020            ObjectId::Schema((database_spec, schema_spec)) => Some(
3021                self.get_schema(database_spec, schema_spec, conn_id)
3022                    .owner_id(),
3023            ),
3024            ObjectId::Item(id) => Some(*self.get_entry(id).owner_id()),
3025            ObjectId::Role(_) => None,
3026            ObjectId::NetworkPolicy(id) => Some(self.get_network_policy(id).owner_id.clone()),
3027            ObjectId::QueryPolicy(id) => Some(self.get_query_policy(id).owner_id),
3028        }
3029    }
3030
3031    pub(super) fn get_object_type(&self, object_id: &ObjectId) -> mz_sql::catalog::ObjectType {
3032        match object_id {
3033            ObjectId::Cluster(_) => mz_sql::catalog::ObjectType::Cluster,
3034            ObjectId::ClusterReplica(_) => mz_sql::catalog::ObjectType::ClusterReplica,
3035            ObjectId::Database(_) => mz_sql::catalog::ObjectType::Database,
3036            ObjectId::Schema(_) => mz_sql::catalog::ObjectType::Schema,
3037            ObjectId::Role(_) => mz_sql::catalog::ObjectType::Role,
3038            ObjectId::Item(id) => self.get_entry(id).item_type().into(),
3039            ObjectId::NetworkPolicy(_) => mz_sql::catalog::ObjectType::NetworkPolicy,
3040            ObjectId::QueryPolicy(_) => mz_sql::catalog::ObjectType::QueryPolicy,
3041        }
3042    }
3043
3044    pub(super) fn get_system_object_type(
3045        &self,
3046        id: &SystemObjectId,
3047    ) -> mz_sql::catalog::SystemObjectType {
3048        match id {
3049            SystemObjectId::Object(object_id) => {
3050                SystemObjectType::Object(self.get_object_type(object_id))
3051            }
3052            SystemObjectId::System => SystemObjectType::System,
3053        }
3054    }
3055
3056    /// Returns a read-only view of the current [`StorageMetadata`].
3057    ///
3058    /// To write to this struct, you must use a catalog transaction.
3059    pub fn storage_metadata(&self) -> &StorageMetadata {
3060        &self.storage_metadata
3061    }
3062
3063    /// For the Sources ids in `ids`, return their compaction windows.
3064    pub fn source_compaction_windows(
3065        &self,
3066        ids: impl IntoIterator<Item = CatalogItemId>,
3067    ) -> BTreeMap<CompactionWindow, BTreeSet<CatalogItemId>> {
3068        let mut cws: BTreeMap<CompactionWindow, BTreeSet<CatalogItemId>> = BTreeMap::new();
3069        let mut seen = BTreeSet::new();
3070        for item_id in ids {
3071            if !seen.insert(item_id) {
3072                continue;
3073            }
3074            let entry = self.get_entry(&item_id);
3075            match entry.item() {
3076                CatalogItem::Source(source) => {
3077                    let source_cw = source.custom_logical_compaction_window.unwrap_or_default();
3078                    cws.entry(source_cw).or_default().insert(item_id);
3079                }
3080                CatalogItem::Table(table) => {
3081                    let table_cw = table.custom_logical_compaction_window.unwrap_or_default();
3082                    match &table.data_source {
3083                        TableDataSource::DataSource {
3084                            desc:
3085                                DataSourceDesc::IngestionExport { .. }
3086                                // Also match webhook tables (source-to-table migration).
3087                                | DataSourceDesc::Webhook { .. },
3088                            timeline: _,
3089                        } => {
3090                            cws.entry(table_cw).or_default().insert(item_id);
3091                        }
3092                        // Regular tables handle compaction directly in
3093                        // catalog_implications, not through this function.
3094                        TableDataSource::TableWrites { .. } => {}
3095                        TableDataSource::DataSource {
3096                            desc:
3097                                DataSourceDesc::Ingestion { .. }
3098                                | DataSourceDesc::OldSyntaxIngestion { .. }
3099                                | DataSourceDesc::Introspection(_)
3100                                | DataSourceDesc::Progress
3101                                | DataSourceDesc::Catalog,
3102                            ..
3103                        } => {
3104                            unreachable!(
3105                                "unexpected DataSourceDesc for table {item_id}: {:?}",
3106                                table.data_source
3107                            )
3108                        }
3109                    }
3110                }
3111                _ => {
3112                    // Views could depend on sources, so ignore them if added by used_by above.
3113                    continue;
3114                }
3115            }
3116        }
3117        cws
3118    }
3119
3120    pub fn comment_id_to_item_id(id: &CommentObjectId) -> Option<CatalogItemId> {
3121        match id {
3122            CommentObjectId::Table(id)
3123            | CommentObjectId::View(id)
3124            | CommentObjectId::MaterializedView(id)
3125            | CommentObjectId::Source(id)
3126            | CommentObjectId::Sink(id)
3127            | CommentObjectId::MetricSink(id)
3128            | CommentObjectId::Index(id)
3129            | CommentObjectId::Func(id)
3130            | CommentObjectId::Connection(id)
3131            | CommentObjectId::Type(id)
3132            | CommentObjectId::Secret(id) => Some(*id),
3133            CommentObjectId::Role(_)
3134            | CommentObjectId::Database(_)
3135            | CommentObjectId::Schema(_)
3136            | CommentObjectId::Cluster(_)
3137            | CommentObjectId::ClusterReplica(_)
3138            | CommentObjectId::QueryPolicy(_)
3139            | CommentObjectId::NetworkPolicy(_) => None,
3140        }
3141    }
3142
3143    pub fn get_comment_id_entry(&self, id: &CommentObjectId) -> Option<&CatalogEntry> {
3144        Self::comment_id_to_item_id(id).map(|id| self.get_entry(&id))
3145    }
3146
3147    pub fn comment_id_to_audit_log_name(
3148        &self,
3149        id: CommentObjectId,
3150        conn_id: &ConnectionId,
3151    ) -> String {
3152        match id {
3153            CommentObjectId::Table(id)
3154            | CommentObjectId::View(id)
3155            | CommentObjectId::MaterializedView(id)
3156            | CommentObjectId::Source(id)
3157            | CommentObjectId::Sink(id)
3158            | CommentObjectId::MetricSink(id)
3159            | CommentObjectId::Index(id)
3160            | CommentObjectId::Func(id)
3161            | CommentObjectId::Connection(id)
3162            | CommentObjectId::Type(id)
3163            | CommentObjectId::Secret(id) => {
3164                let item = self.get_entry(&id);
3165                let name = self.resolve_full_name(item.name(), Some(conn_id));
3166                name.to_string()
3167            }
3168            CommentObjectId::Role(id) => self.get_role(&id).name.clone(),
3169            CommentObjectId::Database(id) => self.get_database(&id).name.clone(),
3170            CommentObjectId::Schema((spec, schema_id)) => {
3171                let schema = self.get_schema(&spec, &schema_id, conn_id);
3172                self.resolve_full_schema_name(&schema.name).to_string()
3173            }
3174            CommentObjectId::Cluster(id) => self.get_cluster(id).name.clone(),
3175            CommentObjectId::ClusterReplica((cluster_id, replica_id)) => {
3176                let cluster = self.get_cluster(cluster_id);
3177                let replica = self.get_cluster_replica(cluster_id, replica_id);
3178                QualifiedReplica {
3179                    cluster: Ident::new_unchecked(cluster.name.clone()),
3180                    replica: Ident::new_unchecked(replica.name.clone()),
3181                }
3182                .to_string()
3183            }
3184            CommentObjectId::NetworkPolicy(id) => self.get_network_policy(&id).name.clone(),
3185            CommentObjectId::QueryPolicy(id) => self.get_query_policy(&id).name.clone(),
3186        }
3187    }
3188
3189    pub fn mock_authentication_nonce(&self) -> String {
3190        self.mock_authentication_nonce.clone().unwrap_or_default()
3191    }
3192}
3193
3194impl ConnectionResolver for CatalogState {
3195    fn resolve_connection(
3196        &self,
3197        id: CatalogItemId,
3198    ) -> mz_storage_types::connections::Connection<InlinedConnection> {
3199        use mz_storage_types::connections::Connection::*;
3200        match self
3201            .get_entry(&id)
3202            .connection()
3203            .expect("catalog out of sync")
3204            .details
3205            .to_connection()
3206        {
3207            Kafka(conn) => Kafka(conn.into_inline_connection(self)),
3208            Postgres(conn) => Postgres(conn.into_inline_connection(self)),
3209            Csr(conn) => Csr(conn.into_inline_connection(self)),
3210            GlueSchemaRegistry(conn) => GlueSchemaRegistry(conn.into_inline_connection(self)),
3211            Ssh(conn) => Ssh(conn),
3212            Aws(conn) => Aws(conn),
3213            AwsPrivatelink(conn) => AwsPrivatelink(conn),
3214            Gcp(conn) => Gcp(conn),
3215            MySql(conn) => MySql(conn.into_inline_connection(self)),
3216            SqlServer(conn) => SqlServer(conn.into_inline_connection(self)),
3217            IcebergCatalog(conn) => IcebergCatalog(conn.into_inline_connection(self)),
3218        }
3219    }
3220}
3221
3222impl OptimizerCatalog for CatalogState {
3223    fn get_entry(&self, id: &GlobalId) -> CatalogCollectionEntry {
3224        CatalogState::get_entry_by_global_id(self, id)
3225    }
3226    fn get_entry_by_item_id(&self, id: &CatalogItemId) -> &CatalogEntry {
3227        CatalogState::get_entry(self, id)
3228    }
3229    fn resolve_full_name(
3230        &self,
3231        name: &QualifiedItemName,
3232        conn_id: Option<&ConnectionId>,
3233    ) -> FullItemName {
3234        CatalogState::resolve_full_name(self, name, conn_id)
3235    }
3236    fn get_indexes_on(
3237        &self,
3238        id: GlobalId,
3239        cluster: ClusterId,
3240    ) -> Box<dyn Iterator<Item = (GlobalId, &Index)> + '_> {
3241        Box::new(CatalogState::get_indexes_on(self, id, cluster))
3242    }
3243}
3244
3245impl OptimizerCatalog for Catalog {
3246    fn get_entry(&self, id: &GlobalId) -> CatalogCollectionEntry {
3247        self.state.get_entry_by_global_id(id)
3248    }
3249
3250    fn get_entry_by_item_id(&self, id: &CatalogItemId) -> &CatalogEntry {
3251        self.state.get_entry(id)
3252    }
3253
3254    fn resolve_full_name(
3255        &self,
3256        name: &QualifiedItemName,
3257        conn_id: Option<&ConnectionId>,
3258    ) -> FullItemName {
3259        self.state.resolve_full_name(name, conn_id)
3260    }
3261
3262    fn get_indexes_on(
3263        &self,
3264        id: GlobalId,
3265        cluster: ClusterId,
3266    ) -> Box<dyn Iterator<Item = (GlobalId, &Index)> + '_> {
3267        Box::new(self.state.get_indexes_on(id, cluster))
3268    }
3269}
3270
3271impl Catalog {
3272    pub fn as_optimizer_catalog(self: Arc<Self>) -> Arc<dyn OptimizerCatalog> {
3273        self
3274    }
3275}
3276
3277#[cfg(test)]
3278mod tests {
3279    use super::*;
3280
3281    /// A deep dependency chain (a long chain of stacked views) must not
3282    /// overflow the stack when computing its dependents, and the dependents
3283    /// must come out in reverse-dependency order (deepest dependent first,
3284    /// root last) so that `DROP ... CASCADE` drops them in a valid order.
3285    #[mz_ore::test(tokio::test)]
3286    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
3287    async fn item_dependents_deep_chain_no_stack_overflow() {
3288        use mz_ore::cast::CastFrom;
3289
3290        Catalog::with_debug(|mut catalog| async move {
3291            // Deep enough that the previous recursive implementation overflowed
3292            // the stack.
3293            const DEPTH: usize = 100_000;
3294            // Well above any id the debug catalog assigns, so the synthetic
3295            // chain does not collide with real entries.
3296            const BASE: u64 = 1 << 40;
3297
3298            // Clone a builtin log entry as a template so we don't have to
3299            // construct a `CatalogItem` by hand. `item_dependents` only reads
3300            // `used_by`/`progress_id`, and a log's `progress_id` is `None`.
3301            let template = catalog
3302                .state
3303                .entry_by_id
3304                .values()
3305                .find(|entry| matches!(entry.item(), CatalogItem::Log(_)))
3306                .expect("debug catalog has log sources")
3307                .clone();
3308
3309            // Build a chain where entry `BASE + i` is used by `BASE + i + 1`.
3310            for i in 0..=DEPTH {
3311                let id = CatalogItemId::User(BASE + u64::cast_from(i));
3312                let mut entry = template.clone();
3313                entry.id = id;
3314                entry.referenced_by = Vec::new();
3315                entry.used_by = if i < DEPTH {
3316                    vec![CatalogItemId::User(BASE + u64::cast_from(i + 1))]
3317                } else {
3318                    Vec::new()
3319                };
3320                catalog.state.entry_by_id.insert(id, entry);
3321            }
3322
3323            let mut seen = BTreeSet::new();
3324            let dependents = catalog
3325                .state
3326                .item_dependents(CatalogItemId::User(BASE), &mut seen);
3327
3328            // Every element of the chain appears exactly once.
3329            assert_eq!(dependents.len(), DEPTH + 1);
3330            // Reverse-dependency order: the deepest dependent is first and the
3331            // root we asked about is last.
3332            for (offset, dependent) in dependents.iter().enumerate() {
3333                let expected = CatalogItemId::User(BASE + u64::cast_from(DEPTH - offset));
3334                assert_eq!(dependent, &ObjectId::Item(expected));
3335            }
3336
3337            catalog.expire().await;
3338        })
3339        .await
3340    }
3341
3342    /// Read-then-write dependency validation walks the transitive `uses()` of
3343    /// the read set. A deep chain of stacked views (user controlled, arbitrarily
3344    /// deep) must be validated without overflowing the coordinator thread's
3345    /// stack, so the traversal must not recurse.
3346    #[mz_ore::test(tokio::test)]
3347    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
3348    async fn validate_read_then_write_deep_chain_no_stack_overflow() {
3349        use crate::coord::read_then_write::{
3350            DependencyPolicy, validate_read_then_write_dependencies,
3351        };
3352
3353        Catalog::with_debug(|mut catalog| async move {
3354            // Deep enough that the previous recursive implementation overflowed
3355            // the stack.
3356            const DEPTH: usize = 100_000;
3357            const BASE: u64 = 1 << 40;
3358            insert_synthetic_view_chain(&mut catalog, BASE, DEPTH);
3359
3360            // A generous bound so this test isolates the no-overflow property
3361            // rather than the dependency limit.
3362            validate_read_then_write_dependencies(
3363                &catalog,
3364                [CatalogItemId::User(BASE)],
3365                usize::MAX,
3366                DependencyPolicy::UserDml,
3367            )
3368            .expect("deep chain of user views is valid for read-then-write");
3369
3370            catalog.expire().await;
3371        })
3372        .await
3373    }
3374
3375    /// Read-then-write dependency validation is bounded: a read set with more
3376    /// transitive dependencies than the limit is rejected with a clean error
3377    /// rather than walking an unbounded graph.
3378    #[mz_ore::test(tokio::test)]
3379    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
3380    async fn validate_read_then_write_dependency_limit() {
3381        use crate::coord::read_then_write::{
3382            DependencyPolicy, validate_read_then_write_dependencies,
3383        };
3384        use crate::error::AdapterError;
3385
3386        Catalog::with_debug(|mut catalog| async move {
3387            const DEPTH: usize = 100;
3388            const BASE: u64 = 1 << 40;
3389            insert_synthetic_view_chain(&mut catalog, BASE, DEPTH);
3390
3391            // The chain has DEPTH + 1 distinct objects (root plus DEPTH links).
3392            const OBJECTS: usize = DEPTH + 1;
3393
3394            // Exactly at the limit is allowed.
3395            validate_read_then_write_dependencies(
3396                &catalog,
3397                [CatalogItemId::User(BASE)],
3398                OBJECTS,
3399                DependencyPolicy::UserDml,
3400            )
3401            .expect("chain at the limit is valid");
3402
3403            // One below the limit is rejected with a clean error.
3404            let err = validate_read_then_write_dependencies(
3405                &catalog,
3406                [CatalogItemId::User(BASE)],
3407                OBJECTS - 1,
3408                DependencyPolicy::UserDml,
3409            )
3410            .expect_err("chain over the limit is rejected");
3411            assert!(matches!(
3412                err,
3413                AdapterError::ReadThenWriteDependencyLimitExceeded {
3414                    max_rw_dependencies
3415                } if max_rw_dependencies == OBJECTS - 1
3416            ));
3417
3418            catalog.expire().await;
3419        })
3420        .await
3421    }
3422
3423    /// Inserts a synthetic chain of `depth + 1` user views into `catalog` where
3424    /// view `base + i` reads from `base + i + 1`. Ids start well above any id
3425    /// the debug catalog assigns so they do not collide with real entries.
3426    ///
3427    /// Clones a builtin view as a template rather than constructing a `View` by
3428    /// hand. Read-then-write validation only reads the item type, `uses()`, and
3429    /// the optimized expression's temporal-ness, all of which a builtin view
3430    /// satisfies (user id + non-temporal).
3431    fn insert_synthetic_view_chain(catalog: &mut Catalog, base: u64, depth: usize) {
3432        use mz_ore::cast::CastFrom;
3433        use mz_sql::names::{DependencyIds, ResolvedIds};
3434
3435        let template = catalog
3436            .state
3437            .entry_by_id
3438            .values()
3439            .find(|entry| matches!(entry.item(), CatalogItem::View(_)))
3440            .expect("debug catalog has builtin views")
3441            .clone();
3442
3443        // `uses()` for a view unions `resolved_ids` and `dependencies`, so clear
3444        // both and point only at the next link.
3445        for i in 0..=depth {
3446            let id = CatalogItemId::User(base + u64::cast_from(i));
3447            let mut entry = template.clone();
3448            entry.id = id;
3449            entry.referenced_by = Vec::new();
3450            entry.used_by = Vec::new();
3451            let mut resolved_ids = ResolvedIds::empty();
3452            if i < depth {
3453                resolved_ids.add_item(CatalogItemId::User(base + u64::cast_from(i + 1)));
3454            }
3455            match &mut entry.item {
3456                CatalogItem::View(view) => {
3457                    view.resolved_ids = resolved_ids;
3458                    view.dependencies = DependencyIds(BTreeSet::new());
3459                }
3460                _ => unreachable!("template is a view"),
3461            }
3462            catalog.state.entry_by_id.insert(id, entry);
3463        }
3464    }
3465}