Skip to main content

mz_adapter/
catalog.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// TODO(jkosh44) Move to mz_catalog crate.
11
12//! Persistent metadata storage for the coordinator.
13
14use std::borrow::Cow;
15use std::collections::{BTreeMap, BTreeSet};
16use std::convert;
17use std::sync::Arc;
18use std::sync::atomic::AtomicU64;
19
20use futures::future::BoxFuture;
21use futures::{Future, FutureExt};
22use itertools::Itertools;
23use mz_adapter_types::bootstrap_builtin_cluster_config::{
24    ANALYTICS_CLUSTER_DEFAULT_REPLICATION_FACTOR, BootstrapBuiltinClusterConfig,
25    CATALOG_SERVER_CLUSTER_DEFAULT_REPLICATION_FACTOR, PROBE_CLUSTER_DEFAULT_REPLICATION_FACTOR,
26    SUPPORT_CLUSTER_DEFAULT_REPLICATION_FACTOR, SYSTEM_CLUSTER_DEFAULT_REPLICATION_FACTOR,
27};
28use mz_adapter_types::connection::ConnectionId;
29use mz_audit_log::{EventType, FullNameV1, ObjectType, VersionedStorageUsage};
30use mz_build_info::{BuildInfo, DUMMY_BUILD_INFO};
31use mz_catalog::builtin::{
32    BUILTIN_PREFIXES, BuiltinCluster, BuiltinLog, BuiltinSource, BuiltinTable,
33    MZ_CATALOG_SERVER_CLUSTER,
34};
35use mz_catalog::config::{
36    AwsPrincipalContext, BuiltinItemMigrationConfig, ClusterReplicaSizeMap, Config, StateConfig,
37};
38#[cfg(test)]
39use mz_catalog::durable::CatalogError;
40use mz_catalog::durable::{
41    BootstrapArgs, DurableCatalogState, STORAGE_USAGE_ID_ALLOC_KEY, TestCatalogStateBuilder,
42    test_bootstrap_args,
43};
44use mz_catalog::expr_cache::{ExpressionCacheHandle, GlobalExpressions, LocalExpressions};
45use mz_catalog::memory::error::{Error, ErrorKind};
46use mz_catalog::memory::objects::{
47    CatalogCollectionEntry, CatalogEntry, CatalogItem, Cluster, ClusterReplica, Database,
48    NetworkPolicy, QueryPolicy, Role, RoleAuth, Schema,
49};
50use mz_cloud_resources::AwsExternalIdPrefix;
51use mz_compute_types::dataflows::DataflowDescription;
52use mz_controller::clusters::ReplicaLocation;
53use mz_controller_types::{ClusterId, ReplicaId};
54use mz_expr::OptimizedMirRelationExpr;
55use mz_license_keys::ValidatedLicenseKey;
56use mz_ore::metrics::MetricsRegistry;
57use mz_ore::now::{EpochMillis, NowFn, SYSTEM_TIME};
58use mz_ore::result::ResultExt as _;
59use mz_persist_client::PersistClient;
60use mz_repr::adt::mz_acl_item::{AclMode, PrivilegeMap};
61use mz_repr::explain::ExprHumanizer;
62use mz_repr::network_policy_id::NetworkPolicyId;
63use mz_repr::optimize::OptimizerFeatures;
64use mz_repr::query_policy_id::QueryPolicyId;
65use mz_repr::role_id::RoleId;
66use mz_repr::{
67    CatalogItemId, Diff, GlobalId, RelationVersion, RelationVersionSelector, SqlScalarType,
68};
69use mz_secrets::InMemorySecretsController;
70use mz_sql::catalog::{
71    CatalogCluster, CatalogClusterReplica, CatalogDatabase, CatalogError as SqlCatalogError,
72    CatalogItem as SqlCatalogItem, CatalogItemType as SqlCatalogItemType, CatalogNetworkPolicy,
73    CatalogRole, CatalogSchema, DefaultPrivilegeAclItem, DefaultPrivilegeObject, EnvironmentId,
74    SessionCatalog, SystemObjectType,
75};
76use mz_sql::names::{
77    CommentObjectId, DatabaseId, FullItemName, FullSchemaName, ItemQualifiers, ObjectId,
78    PUBLIC_ROLE_NAME, PartialItemName, QualifiedItemName, QualifiedSchemaName,
79    ResolvedDatabaseSpecifier, ResolvedIds, SchemaId, SchemaSpecifier, SystemObjectId,
80};
81use mz_sql::plan::{Plan, PlanNotice, StatementDesc};
82use mz_sql::rbac;
83use mz_sql::session::metadata::SessionMetadata;
84use mz_sql::session::user::{MZ_SYSTEM_ROLE_ID, SUPPORT_USER, SYSTEM_USER};
85use mz_sql::session::vars::SystemVars;
86use mz_sql_parser::ast::QualifiedReplica;
87use mz_storage_types::connections::ConnectionContext;
88use mz_storage_types::connections::inline::{ConnectionResolver, InlinedConnection};
89use mz_transform::dataflow::DataflowMetainfo;
90use mz_transform::notice::OptimizerNotice;
91use tokio::sync::MutexGuard;
92use tokio::sync::mpsc::UnboundedSender;
93use uuid::Uuid;
94
95// DO NOT add any more imports from `crate` outside of `crate::catalog`.
96pub use crate::catalog::builtin_table_updates::BuiltinTableUpdate;
97pub use crate::catalog::open::{InitializeStateResult, OpenCatalogResult};
98pub use crate::catalog::state::CatalogState;
99#[cfg(test)]
100pub(crate) use crate::catalog::state::LocalExpressionCache;
101pub(crate) use crate::catalog::transact::{CommandExecutionError, CommandResponse, CommandWork};
102pub use crate::catalog::transact::{
103    DropObjectInfo, InjectedAuditEvent, Op, ReplicaCreateDropReason, TransactionResult,
104};
105use crate::command::CatalogDump;
106use crate::coord::TargetCluster;
107#[cfg(test)]
108use crate::coord::catalog_implications::parsed_state_updates::ParsedStateUpdate;
109use crate::session::{Portal, PreparedStatement, Session};
110use crate::util::ResultExt;
111use crate::{AdapterError, AdapterNotice, ExecuteResponse};
112
113mod builtin_table_updates;
114pub(crate) mod command;
115pub(crate) mod consistency;
116mod limits;
117mod migrate;
118
119mod apply;
120pub(crate) mod cluster_state;
121mod open;
122mod state;
123mod timeline;
124mod transact;
125
126/// A `Catalog` keeps track of the SQL objects known to the planner.
127///
128/// For each object, it keeps track of both forward and reverse dependencies:
129/// i.e., which objects are depended upon by the object, and which objects
130/// depend upon the object. It enforces the SQL rules around dropping: an object
131/// cannot be dropped until all of the objects that depend upon it are dropped.
132/// It also enforces uniqueness of names.
133///
134/// SQL mandates a hierarchy of exactly three layers. A catalog contains
135/// databases, databases contain schemas, and schemas contain catalog items,
136/// like sources, sinks, view, and indexes.
137///
138/// To the outside world, databases, schemas, and items are all identified by
139/// name. Items can be referred to by their [`FullItemName`], which fully and
140/// unambiguously specifies the item, or a [`PartialItemName`], which can omit the
141/// database name and/or the schema name. Partial names can be converted into
142/// full names via a complicated resolution process documented by the
143/// [`CatalogState::resolve`] method.
144///
145/// The catalog also maintains special "ambient schemas": virtual schemas,
146/// implicitly present in all databases, that house various system views.
147/// The big examples of ambient schemas are `pg_catalog` and `mz_catalog`.
148#[derive(Debug)]
149pub struct Catalog {
150    state: CatalogState,
151    expr_cache_handle: Option<ExpressionCacheHandle>,
152    storage: Arc<tokio::sync::Mutex<Box<dyn mz_catalog::durable::DurableCatalogState>>>,
153    transient_revision: u64,
154    /// The latest `transient_revision`, shared by all clones of this catalog.
155    /// While `transient_revision` is this clone's own revision, frozen when
156    /// the snapshot was taken, this field always tracks the latest revision
157    /// across all clones. Comparing the two lets a snapshot holder detect
158    /// from off-thread whether its snapshot is still current, via
159    /// [`Catalog::transient_revision_is_current`], without a Coordinator
160    /// round-trip (see `PeekClient::catalog_snapshot`).
161    ///
162    /// The store happens in `transact`, before the transaction's effects can
163    /// be observed anywhere (responses, notices, builtin table writes), so a
164    /// session that has observed any evidence of a catalog change is
165    /// guaranteed to see the corresponding bump.
166    shared_transient_revision: Arc<AtomicU64>,
167}
168
169/// A handle for advancing the durable catalog upper off the coordinator loop.
170#[derive(Debug, Clone)]
171pub struct CatalogUpperHandle {
172    storage: Arc<tokio::sync::Mutex<Box<dyn mz_catalog::durable::DurableCatalogState>>>,
173}
174
175impl CatalogUpperHandle {
176    /// Advances the durable catalog upper to at least `new_upper`.
177    pub async fn advance_upper(
178        &self,
179        new_upper: mz_repr::Timestamp,
180    ) -> Result<(), mz_catalog::durable::CatalogError> {
181        self.storage.lock().await.advance_upper(new_upper).await
182    }
183}
184
185// Implement our own Clone because derive can't unless S is Clone, which it's
186// not (hence the Arc).
187impl Clone for Catalog {
188    fn clone(&self) -> Self {
189        Self {
190            state: self.state.clone(),
191            expr_cache_handle: self.expr_cache_handle.clone(),
192            storage: Arc::clone(&self.storage),
193            transient_revision: self.transient_revision,
194            shared_transient_revision: Arc::clone(&self.shared_transient_revision),
195        }
196    }
197}
198
199impl Catalog {
200    /// Set the optimized plan for the item identified by `id`.
201    ///
202    /// # Panics
203    /// If the item is not an `Index`, `MaterializedView`, or
204    /// `ContinualTask`.
205    #[mz_ore::instrument(level = "trace")]
206    pub fn set_optimized_plan(
207        &mut self,
208        id: GlobalId,
209        plan: DataflowDescription<OptimizedMirRelationExpr>,
210    ) {
211        self.state.set_optimized_plan(id, plan);
212    }
213
214    /// Set the physical plan for the item identified by `id`.
215    ///
216    /// # Panics
217    /// If the item is not an `Index`, `MaterializedView`, or
218    /// `ContinualTask`.
219    #[mz_ore::instrument(level = "trace")]
220    pub fn set_physical_plan(
221        &mut self,
222        id: GlobalId,
223        plan: mz_compute_types::dataflows::LirDataflowDescription,
224    ) {
225        self.state.set_physical_plan(id, plan);
226    }
227
228    /// Try to get the optimized plan for the item identified by `id`.
229    #[mz_ore::instrument(level = "trace")]
230    pub fn try_get_optimized_plan(
231        &self,
232        id: &GlobalId,
233    ) -> Option<&DataflowDescription<OptimizedMirRelationExpr>> {
234        let entry = self.state.try_get_entry_by_global_id(id)?;
235        entry.item().optimized_plan().map(AsRef::as_ref)
236    }
237
238    /// Try to get the physical plan for the item identified by `id`.
239    #[mz_ore::instrument(level = "trace")]
240    pub fn try_get_physical_plan(
241        &self,
242        id: &GlobalId,
243    ) -> Option<&mz_compute_types::dataflows::LirDataflowDescription> {
244        let entry = self.state.try_get_entry_by_global_id(id)?;
245        entry.item().physical_plan().map(AsRef::as_ref)
246    }
247
248    /// Set the `DataflowMetainfo` for the item identified by `id`.
249    ///
250    /// # Panics
251    /// If the item is not an `Index`, `MaterializedView`, or
252    /// `ContinualTask`.
253    #[mz_ore::instrument(level = "trace")]
254    pub fn set_dataflow_metainfo(
255        &mut self,
256        id: GlobalId,
257        metainfo: DataflowMetainfo<Arc<OptimizerNotice>>,
258    ) {
259        self.state.set_dataflow_metainfo(id, metainfo);
260    }
261
262    /// Try to get the `DataflowMetainfo` for the item identified by `id`.
263    #[mz_ore::instrument(level = "trace")]
264    pub fn try_get_dataflow_metainfo(
265        &self,
266        id: &GlobalId,
267    ) -> Option<&DataflowMetainfo<Arc<OptimizerNotice>>> {
268        let entry = self.state.try_get_entry_by_global_id(id)?;
269        entry.item().dataflow_metainfo()
270    }
271}
272
273#[derive(Debug)]
274pub struct ConnCatalog<'a> {
275    state: Cow<'a, CatalogState>,
276    /// Because we don't have any way of removing items from the catalog
277    /// temporarily, we allow the ConnCatalog to pretend that a set of items
278    /// don't exist during resolution.
279    ///
280    /// This feature is necessary to allow re-planning of statements, which is
281    /// either incredibly useful or required when altering item definitions.
282    ///
283    /// Note that uses of this field should be used by short-lived
284    /// catalogs.
285    unresolvable_ids: BTreeSet<CatalogItemId>,
286    conn_id: ConnectionId,
287    cluster: String,
288    database: Option<DatabaseId>,
289    search_path: Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
290    role_id: RoleId,
291    prepared_statements: Option<&'a BTreeMap<String, PreparedStatement>>,
292    portals: Option<&'a BTreeMap<String, Portal>>,
293    notices_tx: UnboundedSender<AdapterNotice>,
294    restrict_to_user_objects: bool,
295}
296
297impl ConnCatalog<'_> {
298    pub fn conn_id(&self) -> &ConnectionId {
299        &self.conn_id
300    }
301
302    pub fn state(&self) -> &CatalogState {
303        &*self.state
304    }
305
306    /// Returns a system-role view of this catalog snapshot.
307    pub fn for_system_session(&self) -> ConnCatalog<'_> {
308        self.state.for_system_session()
309    }
310
311    /// Prevent planning from resolving item with the provided ID. Instead,
312    /// return an error as if the item did not exist.
313    ///
314    /// This feature is meant exclusively to permit re-planning statements
315    /// during update operations and should not be used otherwise given its
316    /// extremely "powerful" semantics.
317    ///
318    /// # Panics
319    /// If the catalog's role ID is not [`MZ_SYSTEM_ROLE_ID`].
320    pub fn mark_id_unresolvable_for_replanning(&mut self, id: CatalogItemId) {
321        assert_eq!(
322            self.role_id, MZ_SYSTEM_ROLE_ID,
323            "only the system role can mark IDs unresolvable",
324        );
325        self.unresolvable_ids.insert(id);
326    }
327
328    /// Returns the schemas:
329    /// - mz_catalog
330    /// - pg_catalog
331    /// - temp (if requested)
332    /// - all schemas from the session's search_path var that exist
333    pub fn effective_search_path(
334        &self,
335        include_temp_schema: bool,
336    ) -> Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)> {
337        self.state
338            .effective_search_path(&self.search_path, include_temp_schema)
339    }
340}
341
342impl ConnectionResolver for ConnCatalog<'_> {
343    fn resolve_connection(
344        &self,
345        id: CatalogItemId,
346    ) -> mz_storage_types::connections::Connection<InlinedConnection> {
347        self.state().resolve_connection(id)
348    }
349}
350
351/// AWS environment context for a debug catalog.
352///
353/// The `mz_aws_connections` and `mz_aws_privatelink_connections` builtin
354/// materialized views fold `mz_aws_account_id()`, `mz_aws_external_id_prefix()`,
355/// and `mz_aws_connection_role_arn()` into their optimized expressions. A debug
356/// catalog opened to be compared against a live environment (the testdrive
357/// consistency check) must fold those functions to the same values the live
358/// environment used, otherwise the optimized expressions diverge. This mirrors
359/// how `environment_id` is threaded into the catalog copy. Fields left `None`
360/// fold to SQL NULL, matching an environment without that context.
361#[derive(Debug, Clone, Default)]
362pub struct DebugAwsContext {
363    pub aws_account_id: Option<String>,
364    pub aws_external_id_prefix: Option<String>,
365    pub aws_connection_role_arn: Option<String>,
366}
367
368impl Catalog {
369    /// Returns the catalog's transient revision, which starts at 1 and is
370    /// incremented on every change. This is not persisted to disk, and will
371    /// restart on every load.
372    pub fn transient_revision(&self) -> u64 {
373        self.transient_revision
374    }
375
376    /// Reports whether this catalog's transient revision is still the latest,
377    /// i.e., whether no catalog transaction has committed since this snapshot
378    /// was taken. Can be called on a snapshot from off-thread, without a
379    /// Coordinator round-trip. See the field documentation on
380    /// `shared_transient_revision`.
381    pub fn transient_revision_is_current(&self) -> bool {
382        self.transient_revision
383            == self
384                .shared_transient_revision
385                .load(std::sync::atomic::Ordering::SeqCst)
386    }
387
388    /// Creates a debug catalog from the current
389    /// `METADATA_BACKEND_URL` with parameters set appropriately for debug contexts,
390    /// like in tests.
391    ///
392    /// WARNING! This function can arbitrarily fail because it does not make any
393    /// effort to adjust the catalog's contents' structure or semantics to the
394    /// currently running version, i.e. it does not apply any migrations.
395    ///
396    /// This function must not be called in production contexts. Use
397    /// [`Catalog::open`] with appropriately set configuration parameters
398    /// instead.
399    pub async fn with_debug<F, Fut, T>(f: F) -> T
400    where
401        F: FnOnce(Catalog) -> Fut,
402        Fut: Future<Output = T>,
403    {
404        let persist_client = PersistClient::new_for_tests().await;
405        let organization_id = Uuid::new_v4();
406        let bootstrap_args = test_bootstrap_args();
407        let catalog = Self::open_debug_catalog(persist_client, organization_id, &bootstrap_args)
408            .await
409            .expect("can open debug catalog");
410        f(catalog).await
411    }
412
413    /// Like [`Catalog::with_debug`], but folds the given AWS context into the
414    /// catalog. Used to exercise builtin materialized views that reproduce AWS
415    /// environment context in SQL (see [`DebugAwsContext`]).
416    pub async fn with_debug_aws_context<F, Fut, T>(aws_context: DebugAwsContext, f: F) -> T
417    where
418        F: FnOnce(Catalog) -> Fut,
419        Fut: Future<Output = T>,
420    {
421        let persist_client = PersistClient::new_for_tests().await;
422        let organization_id = Uuid::new_v4();
423        let bootstrap_args = test_bootstrap_args();
424        let catalog = Self::open_debug_catalog_with_aws_context(
425            persist_client,
426            organization_id,
427            &bootstrap_args,
428            Some(aws_context),
429        )
430        .await
431        .expect("can open debug catalog");
432        f(catalog).await
433    }
434
435    /// Like [`Catalog::with_debug`], but the catalog created believes that bootstrap is still
436    /// in progress.
437    pub async fn with_debug_in_bootstrap<F, Fut, T>(f: F) -> T
438    where
439        F: FnOnce(Catalog) -> Fut,
440        Fut: Future<Output = T>,
441    {
442        let persist_client = PersistClient::new_for_tests().await;
443        let organization_id = Uuid::new_v4();
444        let bootstrap_args = test_bootstrap_args();
445        let mut catalog =
446            Self::open_debug_catalog(persist_client.clone(), organization_id, &bootstrap_args)
447                .await
448                .expect("can open debug catalog");
449
450        // Replace `storage` in `catalog` with one that doesn't think bootstrap is over.
451        let now = SYSTEM_TIME.clone();
452        let openable_storage = TestCatalogStateBuilder::new(persist_client)
453            .with_organization_id(organization_id)
454            .with_default_deploy_generation()
455            .build()
456            .await
457            .expect("can create durable catalog");
458        let mut storage = openable_storage
459            .open(now().into(), &bootstrap_args)
460            .await
461            .expect("can open durable catalog");
462        // Drain updates.
463        let _ = storage
464            .sync_to_current_updates()
465            .await
466            .expect("can sync to current updates");
467        catalog.storage = Arc::new(tokio::sync::Mutex::new(storage));
468
469        f(catalog).await
470    }
471
472    /// Opens a debug catalog.
473    ///
474    /// See [`Catalog::with_debug`].
475    pub async fn open_debug_catalog(
476        persist_client: PersistClient,
477        organization_id: Uuid,
478        bootstrap_args: &BootstrapArgs,
479    ) -> Result<Catalog, anyhow::Error> {
480        let now = SYSTEM_TIME.clone();
481        let environment_id = None;
482        let openable_storage = TestCatalogStateBuilder::new(persist_client.clone())
483            .with_organization_id(organization_id)
484            .with_default_deploy_generation()
485            .build()
486            .await?;
487        let storage = openable_storage.open(now().into(), bootstrap_args).await?;
488        let system_parameter_defaults = BTreeMap::default();
489        Self::open_debug_catalog_inner(
490            persist_client,
491            storage,
492            now,
493            environment_id,
494            &DUMMY_BUILD_INFO,
495            system_parameter_defaults,
496            bootstrap_args,
497            None,
498            None,
499        )
500        .await
501    }
502
503    /// Like [`Catalog::open_debug_catalog`], but folds `aws_context` into the
504    /// catalog (see [`DebugAwsContext`]).
505    ///
506    /// Calls `open_debug_catalog_inner` directly rather than delegating through
507    /// [`Catalog::open_debug_catalog`], to avoid adding an `async fn` layer to
508    /// the returned future. The catalog-open future is close to the crate
509    /// `recursion_limit`, and the extra nesting overflows it when computing the
510    /// layout of callers such as the `catalog` benchmark.
511    pub async fn open_debug_catalog_with_aws_context(
512        persist_client: PersistClient,
513        organization_id: Uuid,
514        bootstrap_args: &BootstrapArgs,
515        aws_context: Option<DebugAwsContext>,
516    ) -> Result<Catalog, anyhow::Error> {
517        let now = SYSTEM_TIME.clone();
518        let environment_id = None;
519        let openable_storage = TestCatalogStateBuilder::new(persist_client.clone())
520            .with_organization_id(organization_id)
521            .with_default_deploy_generation()
522            .build()
523            .await?;
524        let storage = openable_storage.open(now().into(), bootstrap_args).await?;
525        let system_parameter_defaults = BTreeMap::default();
526        Self::open_debug_catalog_inner(
527            persist_client,
528            storage,
529            now,
530            environment_id,
531            &DUMMY_BUILD_INFO,
532            system_parameter_defaults,
533            bootstrap_args,
534            None,
535            aws_context,
536        )
537        .await
538    }
539
540    /// Opens a read only debug persist backed catalog defined by `persist_client` and
541    /// `organization_id`.
542    ///
543    /// See [`Catalog::with_debug`].
544    pub async fn open_debug_read_only_catalog(
545        persist_client: PersistClient,
546        organization_id: Uuid,
547        bootstrap_args: &BootstrapArgs,
548    ) -> Result<Catalog, anyhow::Error> {
549        let now = SYSTEM_TIME.clone();
550        let environment_id = None;
551        let openable_storage = TestCatalogStateBuilder::new(persist_client.clone())
552            .with_organization_id(organization_id)
553            .build()
554            .await?;
555        let storage = openable_storage
556            .open_read_only(&test_bootstrap_args())
557            .await?;
558        let system_parameter_defaults = BTreeMap::default();
559        Self::open_debug_catalog_inner(
560            persist_client,
561            storage,
562            now,
563            environment_id,
564            &DUMMY_BUILD_INFO,
565            system_parameter_defaults,
566            bootstrap_args,
567            None,
568            None,
569        )
570        .await
571    }
572
573    /// Opens a read only debug persist backed catalog defined by `persist_client` and
574    /// `organization_id`.
575    ///
576    /// See [`Catalog::with_debug`].
577    pub async fn open_debug_read_only_persist_catalog_config(
578        persist_client: PersistClient,
579        now: NowFn,
580        environment_id: EnvironmentId,
581        system_parameter_defaults: BTreeMap<String, String>,
582        build_info: &'static BuildInfo,
583        bootstrap_args: &BootstrapArgs,
584        enable_expression_cache_override: Option<bool>,
585        aws_context: Option<DebugAwsContext>,
586    ) -> Result<Catalog, anyhow::Error> {
587        let openable_storage = TestCatalogStateBuilder::new(persist_client.clone())
588            .with_organization_id(environment_id.organization_id())
589            .with_version(
590                build_info
591                    .version
592                    .parse()
593                    .expect("build version is parseable"),
594            )
595            .build()
596            .await?;
597        let storage = openable_storage.open_read_only(bootstrap_args).await?;
598        Self::open_debug_catalog_inner(
599            persist_client,
600            storage,
601            now,
602            Some(environment_id),
603            build_info,
604            system_parameter_defaults,
605            bootstrap_args,
606            enable_expression_cache_override,
607            aws_context,
608        )
609        .await
610    }
611
612    async fn open_debug_catalog_inner(
613        persist_client: PersistClient,
614        storage: Box<dyn DurableCatalogState>,
615        now: NowFn,
616        environment_id: Option<EnvironmentId>,
617        build_info: &'static BuildInfo,
618        system_parameter_defaults: BTreeMap<String, String>,
619        bootstrap_args: &BootstrapArgs,
620        enable_expression_cache_override: Option<bool>,
621        aws_context: Option<DebugAwsContext>,
622    ) -> Result<Catalog, anyhow::Error> {
623        let metrics_registry = &MetricsRegistry::new();
624        let secrets_reader = Arc::new(InMemorySecretsController::new());
625        // Used as a lower boundary of the boot_ts, but it's ok to use now() for
626        // debugging/testing.
627        let previous_ts = now().into();
628        let replica_size = &bootstrap_args.default_cluster_replica_size;
629        let read_only = false;
630
631        // Fold the requested AWS context into the connection context and
632        // principal context. The builtin AWS connection views reproduce these
633        // values in SQL, so a catalog compared against a live environment must
634        // resolve them identically. When `aws_context` is `None` the default
635        // `for_tests` context is used unchanged.
636        let mut connection_context = ConnectionContext::for_tests(secrets_reader);
637        let aws_principal_context = match aws_context {
638            None => None,
639            Some(aws_context) => {
640                connection_context.aws_external_id_prefix =
641                    aws_context.aws_external_id_prefix.as_deref().map(|prefix| {
642                        AwsExternalIdPrefix::new_from_cli_argument_or_environment_variable(prefix)
643                            .expect("infallible")
644                    });
645                connection_context.aws_connection_role_arn = aws_context.aws_connection_role_arn;
646                aws_context.aws_account_id.map(|aws_account_id| {
647                    AwsPrincipalContext {
648                        aws_account_id,
649                        // Only `aws_account_id` reaches the `mz_aws_account_id()`
650                        // fold. The external id prefix is read from the connection
651                        // context above, so any placeholder works here.
652                        aws_external_id_prefix:
653                            AwsExternalIdPrefix::new_from_cli_argument_or_environment_variable(
654                                "debug",
655                            )
656                            .expect("infallible"),
657                    }
658                })
659            }
660        };
661
662        let OpenCatalogResult {
663            catalog,
664            last_seen_version: _,
665            migrated_storage_collections_0dt: _,
666            new_builtin_collections: _,
667            builtin_table_updates: _,
668            cached_global_exprs: _,
669            uncached_local_exprs: _,
670        } = Catalog::open(Config {
671            storage,
672            metrics_registry,
673            state: StateConfig {
674                unsafe_mode: true,
675                all_features: false,
676                build_info,
677                environment_id: environment_id.unwrap_or_else(EnvironmentId::for_tests),
678                read_only,
679                now,
680                boot_ts: previous_ts,
681                skip_migrations: true,
682                cluster_replica_sizes: bootstrap_args.cluster_replica_size_map.clone(),
683                builtin_system_cluster_config: BootstrapBuiltinClusterConfig {
684                    size: replica_size.clone(),
685                    replication_factor: SYSTEM_CLUSTER_DEFAULT_REPLICATION_FACTOR,
686                },
687                builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig {
688                    size: replica_size.clone(),
689                    replication_factor: CATALOG_SERVER_CLUSTER_DEFAULT_REPLICATION_FACTOR,
690                },
691                builtin_probe_cluster_config: BootstrapBuiltinClusterConfig {
692                    size: replica_size.clone(),
693                    replication_factor: PROBE_CLUSTER_DEFAULT_REPLICATION_FACTOR,
694                },
695                builtin_support_cluster_config: BootstrapBuiltinClusterConfig {
696                    size: replica_size.clone(),
697                    replication_factor: SUPPORT_CLUSTER_DEFAULT_REPLICATION_FACTOR,
698                },
699                builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig {
700                    size: replica_size.clone(),
701                    replication_factor: ANALYTICS_CLUSTER_DEFAULT_REPLICATION_FACTOR,
702                },
703                system_parameter_defaults,
704                remote_system_parameters: None,
705                availability_zones: vec![],
706                egress_addresses: vec![],
707                aws_principal_context,
708                aws_privatelink_availability_zones: None,
709                http_host_name: None,
710                connection_context,
711                builtin_item_migration_config: BuiltinItemMigrationConfig {
712                    persist_client: persist_client.clone(),
713                    read_only,
714                    force_migration: None,
715                },
716                persist_client,
717                enable_expression_cache_override,
718                helm_chart_version: None,
719                external_login_password_mz_system: None,
720                license_key: ValidatedLicenseKey::for_tests(),
721            },
722        })
723        .await?;
724        Ok(catalog)
725    }
726
727    pub fn for_session<'a>(&'a self, session: &'a Session) -> ConnCatalog<'a> {
728        self.state.for_session(session)
729    }
730
731    pub fn for_sessionless_user(&self, role_id: RoleId) -> ConnCatalog<'_> {
732        self.state.for_sessionless_user(role_id)
733    }
734
735    pub fn for_system_session(&self) -> ConnCatalog<'_> {
736        self.state.for_system_session()
737    }
738
739    async fn storage<'a>(
740        &'a self,
741    ) -> MutexGuard<'a, Box<dyn mz_catalog::durable::DurableCatalogState>> {
742        self.storage.lock().await
743    }
744
745    pub async fn current_upper(&self) -> mz_repr::Timestamp {
746        self.storage().await.current_upper().await
747    }
748
749    /// Allocates and returns both a user [`CatalogItemId`] and [`GlobalId`], delegating to
750    /// [`DurableCatalogState::allocate_user_id`].
751    pub async fn allocate_user_id(
752        &self,
753        commit_ts: mz_repr::Timestamp,
754    ) -> Result<(CatalogItemId, GlobalId), Error> {
755        Ok(self
756            .storage()
757            .await
758            .allocate_user_id(commit_ts)
759            .await
760            .maybe_terminate("allocating user ids")?)
761    }
762
763    /// Allocate `amount` many user IDs. See [`DurableCatalogState::allocate_user_ids`].
764    pub async fn allocate_user_ids(
765        &self,
766        amount: u64,
767        commit_ts: mz_repr::Timestamp,
768    ) -> Result<Vec<(CatalogItemId, GlobalId)>, Error> {
769        Ok(self
770            .storage()
771            .await
772            .allocate_user_ids(amount, commit_ts)
773            .await
774            .maybe_terminate("allocating user ids")?)
775    }
776
777    pub async fn allocate_user_id_for_test(&self) -> Result<(CatalogItemId, GlobalId), Error> {
778        let commit_ts = self.storage().await.current_upper().await;
779        self.allocate_user_id(commit_ts).await
780    }
781
782    /// Allocates a single durable id for a storage usage collection batch.
783    ///
784    /// Bumps the durable `STORAGE_USAGE_ID_ALLOC_KEY` allocator by one and
785    /// returns the previous value. The bump is committed at `commit_ts`.
786    /// One id is shared by every row produced by a collection cycle (see
787    /// `Coordinator::storage_usage_update`), so the durable cost is one
788    /// allocator round-trip per cycle, not per shard.
789    pub async fn allocate_storage_usage_id(
790        &self,
791        commit_ts: mz_repr::Timestamp,
792    ) -> Result<u64, Error> {
793        use mz_ore::collections::CollectionExt;
794
795        self.storage()
796            .await
797            .allocate_id(STORAGE_USAGE_ID_ALLOC_KEY, 1, commit_ts)
798            .await
799            .maybe_terminate("allocating storage usage id")
800            .map(|ids| ids.into_element())
801            .err_into()
802    }
803
804    /// Get the next user item ID without allocating it.
805    pub async fn get_next_user_item_id(&self) -> Result<u64, Error> {
806        self.storage()
807            .await
808            .get_next_user_item_id()
809            .await
810            .err_into()
811    }
812
813    #[cfg(test)]
814    pub async fn allocate_system_id(
815        &self,
816        commit_ts: mz_repr::Timestamp,
817    ) -> Result<(CatalogItemId, GlobalId), Error> {
818        use mz_ore::collections::CollectionExt;
819
820        let mut storage = self.storage().await;
821        let mut txn = storage.transaction().await?;
822        let id = txn
823            .allocate_system_item_ids(1)
824            .maybe_terminate("allocating system ids")?
825            .into_element();
826        // Drain transaction.
827        let _ = txn.get_and_commit_op_updates();
828        txn.commit(commit_ts).await?;
829        Ok(id)
830    }
831
832    /// Records a fresh shard for the storage collection `id`, as the storage
833    /// controller does for collections a test catalog creates without one.
834    #[cfg(test)]
835    pub async fn register_collection_shard(
836        &mut self,
837        id: GlobalId,
838    ) -> Result<mz_persist_types::ShardId, Error> {
839        use mz_storage_client::controller::StorageTxn;
840
841        let shard_id = mz_persist_types::ShardId::new();
842        let mut storage = self.storage().await;
843        let mut txn = storage.transaction().await?;
844        txn.insert_collection_metadata([(id, shard_id)].into())
845            .expect("a fresh shard for an unregistered collection");
846        let updates = txn.get_and_commit_op_updates();
847        let commit_ts = txn.upper();
848        txn.commit(commit_ts).await?;
849        drop(storage);
850        let (_builtin_updates, _catalog_updates) = self
851            .state
852            .apply_updates(updates, &mut LocalExpressionCache::Closed)
853            .await;
854        Ok(shard_id)
855    }
856
857    /// Get the next system item ID without allocating it.
858    pub async fn get_next_system_item_id(&self) -> Result<u64, Error> {
859        self.storage()
860            .await
861            .get_next_system_item_id()
862            .await
863            .err_into()
864    }
865
866    /// Allocates and returns a user [`ClusterId`], delegating to
867    /// [`DurableCatalogState::allocate_user_cluster_id`].
868    pub async fn allocate_user_cluster_id(
869        &self,
870        commit_ts: mz_repr::Timestamp,
871    ) -> Result<ClusterId, Error> {
872        Ok(self
873            .storage()
874            .await
875            .allocate_user_cluster_id(commit_ts)
876            .await
877            .maybe_terminate("allocating user cluster ids")?)
878    }
879
880    /// Allocate `amount` many user replica IDs. See
881    /// [`DurableCatalogState::allocate_user_replica_ids`].
882    pub async fn allocate_user_replica_ids(
883        &self,
884        amount: u64,
885        commit_ts: mz_repr::Timestamp,
886    ) -> Result<Vec<ReplicaId>, Error> {
887        Ok(self
888            .storage()
889            .await
890            .allocate_user_replica_ids(amount, commit_ts)
891            .await
892            .maybe_terminate("allocating user replica ids")?)
893    }
894
895    /// Allocate `amount` many system replica IDs. See
896    /// [`DurableCatalogState::allocate_system_replica_ids`].
897    pub async fn allocate_system_replica_ids(
898        &self,
899        amount: u64,
900        commit_ts: mz_repr::Timestamp,
901    ) -> Result<Vec<ReplicaId>, Error> {
902        Ok(self
903            .storage()
904            .await
905            .allocate_system_replica_ids(amount, commit_ts)
906            .await
907            .maybe_terminate("allocating system replica ids")?)
908    }
909
910    /// Allocate `amount` many replica IDs for `cluster_id`, picking user or
911    /// system IDs based on the cluster's ID type.
912    pub async fn allocate_replica_ids(
913        &self,
914        cluster_id: ClusterId,
915        amount: u64,
916        commit_ts: mz_repr::Timestamp,
917    ) -> Result<Vec<ReplicaId>, Error> {
918        if cluster_id.is_system() {
919            self.allocate_system_replica_ids(amount, commit_ts).await
920        } else {
921            self.allocate_user_replica_ids(amount, commit_ts).await
922        }
923    }
924
925    /// Get the next system replica id without allocating it.
926    pub async fn get_next_system_replica_id(&self) -> Result<u64, Error> {
927        self.storage()
928            .await
929            .get_next_system_replica_id()
930            .await
931            .err_into()
932    }
933
934    /// Get the next user replica id without allocating it.
935    pub async fn get_next_user_replica_id(&self) -> Result<u64, Error> {
936        self.storage()
937            .await
938            .get_next_user_replica_id()
939            .await
940            .err_into()
941    }
942
943    pub fn resolve_database(&self, database_name: &str) -> Result<&Database, SqlCatalogError> {
944        self.state.resolve_database(database_name)
945    }
946
947    pub fn resolve_schema(
948        &self,
949        current_database: Option<&DatabaseId>,
950        database_name: Option<&str>,
951        schema_name: &str,
952        conn_id: &ConnectionId,
953    ) -> Result<&Schema, SqlCatalogError> {
954        self.state
955            .resolve_schema(current_database, database_name, schema_name, conn_id)
956    }
957
958    pub fn resolve_schema_in_database(
959        &self,
960        database_spec: &ResolvedDatabaseSpecifier,
961        schema_name: &str,
962        conn_id: &ConnectionId,
963    ) -> Result<&Schema, SqlCatalogError> {
964        self.state
965            .resolve_schema_in_database(database_spec, schema_name, conn_id)
966    }
967
968    pub fn resolve_replica_in_cluster(
969        &self,
970        cluster_id: &ClusterId,
971        replica_name: &str,
972    ) -> Result<&ClusterReplica, SqlCatalogError> {
973        self.state
974            .resolve_replica_in_cluster(cluster_id, replica_name)
975    }
976
977    pub fn resolve_system_schema(&self, name: &'static str) -> SchemaId {
978        self.state.resolve_system_schema(name)
979    }
980
981    pub fn resolve_search_path(
982        &self,
983        session: &Session,
984    ) -> Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)> {
985        self.state.resolve_search_path(session)
986    }
987
988    /// Resolves `name` to a non-function [`CatalogEntry`].
989    pub fn resolve_entry(
990        &self,
991        current_database: Option<&DatabaseId>,
992        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
993        name: &PartialItemName,
994        conn_id: &ConnectionId,
995    ) -> Result<&CatalogEntry, SqlCatalogError> {
996        self.state
997            .resolve_entry(current_database, search_path, name, conn_id)
998    }
999
1000    /// Resolves a `BuiltinTable`.
1001    pub fn resolve_builtin_table(&self, builtin: &'static BuiltinTable) -> CatalogItemId {
1002        self.state.resolve_builtin_table(builtin)
1003    }
1004
1005    /// Resolves a `BuiltinLog`.
1006    pub fn resolve_builtin_log(&self, builtin: &'static BuiltinLog) -> CatalogItemId {
1007        self.state.resolve_builtin_log(builtin).0
1008    }
1009
1010    /// Resolves a `BuiltinSource`.
1011    pub fn resolve_builtin_storage_collection(
1012        &self,
1013        builtin: &'static BuiltinSource,
1014    ) -> CatalogItemId {
1015        self.state.resolve_builtin_source(builtin)
1016    }
1017
1018    /// Resolves `name` to a function [`CatalogEntry`].
1019    pub fn resolve_function(
1020        &self,
1021        current_database: Option<&DatabaseId>,
1022        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
1023        name: &PartialItemName,
1024        conn_id: &ConnectionId,
1025    ) -> Result<&CatalogEntry, SqlCatalogError> {
1026        self.state
1027            .resolve_function(current_database, search_path, name, conn_id)
1028    }
1029
1030    /// Resolves `name` to a type [`CatalogEntry`].
1031    pub fn resolve_type(
1032        &self,
1033        current_database: Option<&DatabaseId>,
1034        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
1035        name: &PartialItemName,
1036        conn_id: &ConnectionId,
1037    ) -> Result<&CatalogEntry, SqlCatalogError> {
1038        self.state
1039            .resolve_type(current_database, search_path, name, conn_id)
1040    }
1041
1042    pub fn resolve_cluster(&self, name: &str) -> Result<&Cluster, SqlCatalogError> {
1043        self.state.resolve_cluster(name)
1044    }
1045
1046    /// Resolves a [`Cluster`] for a [`BuiltinCluster`].
1047    ///
1048    /// # Panics
1049    /// * If the [`BuiltinCluster`] doesn't exist.
1050    ///
1051    pub fn resolve_builtin_cluster(&self, cluster: &BuiltinCluster) -> &Cluster {
1052        self.state.resolve_builtin_cluster(cluster)
1053    }
1054
1055    pub fn get_mz_catalog_server_cluster_id(&self) -> &ClusterId {
1056        &self.resolve_builtin_cluster(&MZ_CATALOG_SERVER_CLUSTER).id
1057    }
1058
1059    /// Resolves a [`Cluster`] for a TargetCluster.
1060    pub fn resolve_target_cluster(
1061        &self,
1062        target_cluster: TargetCluster,
1063        session: &Session,
1064    ) -> Result<&Cluster, AdapterError> {
1065        match target_cluster {
1066            TargetCluster::CatalogServer => {
1067                Ok(self.resolve_builtin_cluster(&MZ_CATALOG_SERVER_CLUSTER))
1068            }
1069            TargetCluster::Active => self.active_cluster(session),
1070            TargetCluster::Transaction(cluster_id) => self
1071                .try_get_cluster(cluster_id)
1072                .ok_or(AdapterError::ConcurrentClusterDrop),
1073        }
1074    }
1075
1076    pub fn active_cluster(&self, session: &Session) -> Result<&Cluster, AdapterError> {
1077        // TODO(benesch): this check here is not sufficiently protective. It'd
1078        // be very easy for a code path to accidentally avoid this check by
1079        // calling `resolve_cluster(session.vars().cluster())`.
1080        if session.user().name != SYSTEM_USER.name
1081            && session.user().name != SUPPORT_USER.name
1082            && session.vars().cluster() == SYSTEM_USER.name
1083        {
1084            coord_bail!(
1085                "system cluster '{}' cannot execute user queries",
1086                SYSTEM_USER.name
1087            );
1088        }
1089        let cluster = self.resolve_cluster(session.vars().cluster())?;
1090        Ok(cluster)
1091    }
1092
1093    pub fn state(&self) -> &CatalogState {
1094        &self.state
1095    }
1096
1097    pub fn resolve_full_name(
1098        &self,
1099        name: &QualifiedItemName,
1100        conn_id: Option<&ConnectionId>,
1101    ) -> FullItemName {
1102        self.state.resolve_full_name(name, conn_id)
1103    }
1104
1105    pub fn try_get_entry(&self, id: &CatalogItemId) -> Option<&CatalogEntry> {
1106        self.state.try_get_entry(id)
1107    }
1108
1109    pub fn try_get_entry_by_global_id(&self, id: &GlobalId) -> Option<&CatalogEntry> {
1110        self.state.try_get_entry_by_global_id(id)
1111    }
1112
1113    pub fn get_entry(&self, id: &CatalogItemId) -> &CatalogEntry {
1114        self.state.get_entry(id)
1115    }
1116
1117    pub fn get_entry_by_global_id(&self, id: &GlobalId) -> CatalogCollectionEntry {
1118        self.state.get_entry_by_global_id(id)
1119    }
1120
1121    pub fn get_global_ids<'a>(
1122        &'a self,
1123        id: &CatalogItemId,
1124    ) -> impl Iterator<Item = GlobalId> + use<'a> {
1125        self.get_entry(id).global_ids()
1126    }
1127
1128    pub fn resolve_item_id(&self, id: &GlobalId) -> CatalogItemId {
1129        self.get_entry_by_global_id(id).id()
1130    }
1131
1132    pub fn try_resolve_item_id(&self, id: &GlobalId) -> Option<CatalogItemId> {
1133        let item = self.try_get_entry_by_global_id(id)?;
1134        Some(item.id())
1135    }
1136
1137    pub fn get_schema(
1138        &self,
1139        database_spec: &ResolvedDatabaseSpecifier,
1140        schema_spec: &SchemaSpecifier,
1141        conn_id: &ConnectionId,
1142    ) -> &Schema {
1143        self.state.get_schema(database_spec, schema_spec, conn_id)
1144    }
1145
1146    pub fn try_get_schema(
1147        &self,
1148        database_spec: &ResolvedDatabaseSpecifier,
1149        schema_spec: &SchemaSpecifier,
1150        conn_id: &ConnectionId,
1151    ) -> Option<&Schema> {
1152        self.state
1153            .try_get_schema(database_spec, schema_spec, conn_id)
1154    }
1155
1156    pub fn get_mz_catalog_schema_id(&self) -> SchemaId {
1157        self.state.get_mz_catalog_schema_id()
1158    }
1159
1160    pub fn get_pg_catalog_schema_id(&self) -> SchemaId {
1161        self.state.get_pg_catalog_schema_id()
1162    }
1163
1164    pub fn get_information_schema_id(&self) -> SchemaId {
1165        self.state.get_information_schema_id()
1166    }
1167
1168    pub fn get_mz_internal_schema_id(&self) -> SchemaId {
1169        self.state.get_mz_internal_schema_id()
1170    }
1171
1172    pub fn get_mz_introspection_schema_id(&self) -> SchemaId {
1173        self.state.get_mz_introspection_schema_id()
1174    }
1175
1176    pub fn get_mz_unsafe_schema_id(&self) -> SchemaId {
1177        self.state.get_mz_unsafe_schema_id()
1178    }
1179
1180    pub fn system_schema_ids(&self) -> impl Iterator<Item = SchemaId> + '_ {
1181        self.state.system_schema_ids()
1182    }
1183
1184    pub fn get_database(&self, id: &DatabaseId) -> &Database {
1185        self.state.get_database(id)
1186    }
1187
1188    pub fn try_get_role(&self, id: &RoleId) -> Option<&Role> {
1189        self.state.try_get_role(id)
1190    }
1191
1192    pub fn get_role(&self, id: &RoleId) -> &Role {
1193        self.state.get_role(id)
1194    }
1195
1196    pub fn try_get_role_by_name(&self, role_name: &str) -> Option<&Role> {
1197        self.state.try_get_role_by_name(role_name)
1198    }
1199
1200    pub fn try_get_role_auth_by_id(&self, id: &RoleId) -> Option<&RoleAuth> {
1201        self.state.try_get_role_auth_by_id(id)
1202    }
1203
1204    /// Registers the connection's temporary namespace: the `uuid` <->
1205    /// `conn_id` mapping used to stamp and apply durable temporary items
1206    /// owned by the session. The `mz_temp` schema itself is created when
1207    /// the first temporary item is applied.
1208    ///
1209    /// The coordinator calls this at a session's first temporary-item
1210    /// creation, strictly before the transaction that persists the item, and
1211    /// guards on [`CatalogState::has_temporary_namespace`], so registering
1212    /// an already-registered namespace is a bug.
1213    pub fn register_temporary_namespace(&mut self, conn_id: &ConnectionId, uuid: Uuid) {
1214        self.state
1215            .temporary_namespaces
1216            .register(conn_id.clone(), uuid);
1217    }
1218
1219    fn item_exists_in_temp_schemas(&self, conn_id: &ConnectionId, item_name: &str) -> bool {
1220        // A temporary namespace is registered at the connection's first
1221        // temporary-item creation, so it's valid for one to not exist yet.
1222        self.state
1223            .temporary_namespaces
1224            .schema(conn_id)
1225            .map(|schema| schema.items.contains_key(item_name))
1226            .unwrap_or(false)
1227    }
1228
1229    /// Removes the connection's temporary namespace, if it has one.
1230    pub fn drop_temporary_namespace(&mut self, conn_id: &ConnectionId) {
1231        self.state.temporary_namespaces.unregister(conn_id)
1232    }
1233
1234    pub(crate) fn object_dependents(
1235        &self,
1236        object_ids: &Vec<ObjectId>,
1237        conn_id: &ConnectionId,
1238    ) -> Vec<ObjectId> {
1239        let mut seen = BTreeSet::new();
1240        self.state.object_dependents(object_ids, conn_id, &mut seen)
1241    }
1242
1243    fn full_name_detail(name: &FullItemName) -> FullNameV1 {
1244        FullNameV1 {
1245            database: name.database.to_string(),
1246            schema: name.schema.clone(),
1247            item: name.item.clone(),
1248        }
1249    }
1250
1251    pub fn find_available_cluster_name(&self, name: &str) -> String {
1252        let mut i = 0;
1253        let mut candidate = name.to_string();
1254        while self.state.clusters_by_name.contains_key(&candidate) {
1255            i += 1;
1256            candidate = format!("{}{}", name, i);
1257        }
1258        candidate
1259    }
1260
1261    pub fn get_role_allowed_cluster_sizes(&self, role_id: &Option<RoleId>) -> Vec<String> {
1262        // Disabled sizes are included; `ensure_valid_replica_size` decides
1263        // whether those are allowed.
1264        if role_id == &Some(MZ_SYSTEM_ROLE_ID) {
1265            self.cluster_replica_sizes().0.keys().cloned().collect()
1266        } else {
1267            self.system_config().allowed_cluster_replica_sizes()
1268        }
1269    }
1270
1271    pub fn concretize_replica_location(
1272        &self,
1273        location: mz_catalog::durable::ReplicaLocation,
1274        allowed_sizes: &Vec<String>,
1275        allowed_availability_zones: Option<&[String]>,
1276        allow_disabled: bool,
1277    ) -> Result<ReplicaLocation, Error> {
1278        self.state.concretize_replica_location(
1279            location,
1280            allowed_sizes,
1281            allowed_availability_zones,
1282            allow_disabled,
1283        )
1284    }
1285
1286    pub(crate) fn ensure_valid_replica_size(
1287        &self,
1288        allowed_sizes: &[String],
1289        size: &String,
1290        allow_disabled: bool,
1291    ) -> Result<(), Error> {
1292        self.state
1293            .ensure_valid_replica_size(allowed_sizes, size, allow_disabled)
1294    }
1295
1296    pub fn cluster_replica_sizes(&self) -> &ClusterReplicaSizeMap {
1297        self.state.cluster_replica_sizes()
1298    }
1299
1300    /// Returns the privileges of an object by its ID.
1301    pub fn get_privileges(
1302        &self,
1303        id: &SystemObjectId,
1304        conn_id: &ConnectionId,
1305    ) -> Option<&PrivilegeMap> {
1306        match id {
1307            SystemObjectId::Object(id) => match id {
1308                ObjectId::Cluster(id) => Some(self.get_cluster(*id).privileges()),
1309                ObjectId::Database(id) => Some(self.get_database(id).privileges()),
1310                ObjectId::Schema((database_spec, schema_spec)) => Some(
1311                    self.get_schema(database_spec, schema_spec, conn_id)
1312                        .privileges(),
1313                ),
1314                ObjectId::Item(id) => Some(self.get_entry(id).privileges()),
1315                ObjectId::ClusterReplica(_) | ObjectId::Role(_) => None,
1316                ObjectId::NetworkPolicy(id) => Some(self.get_network_policy(*id).privileges()),
1317                ObjectId::QueryPolicy(id) => Some(&self.state.get_query_policy(id).privileges),
1318            },
1319            SystemObjectId::System => Some(&self.state.system_privileges),
1320        }
1321    }
1322
1323    /// Advances the catalog upper to at least `new_upper`.
1324    ///
1325    /// Empty progress can overtake `new_upper`. A durable upper mismatch with content returns
1326    /// `CatalogOutOfSync`. See [`mz_catalog::durable::DurableCatalogState::advance_upper`] for
1327    /// fencing semantics.
1328    #[mz_ore::instrument(level = "debug")]
1329    pub async fn advance_upper(&self, new_upper: mz_repr::Timestamp) -> Result<(), AdapterError> {
1330        Ok(self.storage().await.advance_upper(new_upper).await?)
1331    }
1332
1333    /// Returns a durable-upper handle that shares the catalog storage mutex.
1334    pub fn upper_handle(&self) -> CatalogUpperHandle {
1335        CatalogUpperHandle {
1336            storage: Arc::clone(&self.storage),
1337        }
1338    }
1339
1340    /// Return the ids of all log sources the given object depends on.
1341    pub fn introspection_dependencies(&self, id: CatalogItemId) -> Vec<CatalogItemId> {
1342        self.state.introspection_dependencies(id)
1343    }
1344
1345    /// Serializes the catalog's in-memory state.
1346    ///
1347    /// There are no guarantees about the format of the serialized state, except
1348    /// that the serialized state for two identical catalogs will compare
1349    /// identically.
1350    pub fn dump(&self) -> Result<CatalogDump, Error> {
1351        Ok(CatalogDump::new(self.state.dump(None)?))
1352    }
1353
1354    /// Checks the [`Catalog`]s internal consistency.
1355    ///
1356    /// Returns a JSON object describing the inconsistencies, if there are any.
1357    pub fn check_consistency(&self) -> Result<(), serde_json::Value> {
1358        self.state.check_consistency().map_err(|inconsistencies| {
1359            serde_json::to_value(inconsistencies).unwrap_or_else(|_| {
1360                serde_json::Value::String("failed to serialize inconsistencies".to_string())
1361            })
1362        })
1363    }
1364
1365    pub fn config(&self) -> &mz_sql::catalog::CatalogConfig {
1366        self.state.config()
1367    }
1368
1369    pub fn entries(&self) -> impl Iterator<Item = &CatalogEntry> {
1370        self.state.entries()
1371    }
1372
1373    pub fn user_connections(&self) -> impl Iterator<Item = &CatalogEntry> {
1374        self.state.user_connections()
1375    }
1376
1377    pub fn user_tables(&self) -> impl Iterator<Item = &CatalogEntry> {
1378        self.state.user_tables()
1379    }
1380
1381    pub fn user_sources(&self) -> impl Iterator<Item = &CatalogEntry> {
1382        self.state.user_sources()
1383    }
1384
1385    pub fn user_sinks(&self) -> impl Iterator<Item = &CatalogEntry> {
1386        self.state.user_sinks()
1387    }
1388
1389    pub fn user_materialized_views(&self) -> impl Iterator<Item = &CatalogEntry> {
1390        self.state.user_materialized_views()
1391    }
1392
1393    pub fn user_secrets(&self) -> impl Iterator<Item = &CatalogEntry> {
1394        self.state.user_secrets()
1395    }
1396
1397    pub fn get_network_policy(&self, network_policy_id: NetworkPolicyId) -> &NetworkPolicy {
1398        self.state.get_network_policy(&network_policy_id)
1399    }
1400
1401    pub fn get_network_policy_by_name(&self, name: &str) -> Option<&NetworkPolicy> {
1402        self.state.try_get_network_policy_by_name(name)
1403    }
1404
1405    pub fn get_query_policy(&self, id: QueryPolicyId) -> &QueryPolicy {
1406        self.state.get_query_policy(&id)
1407    }
1408
1409    pub fn clusters(&self) -> impl Iterator<Item = &Cluster> {
1410        self.state.clusters()
1411    }
1412
1413    pub fn get_cluster(&self, cluster_id: ClusterId) -> &Cluster {
1414        self.state.get_cluster(cluster_id)
1415    }
1416
1417    pub fn try_get_cluster(&self, cluster_id: ClusterId) -> Option<&Cluster> {
1418        self.state.try_get_cluster(cluster_id)
1419    }
1420
1421    pub fn user_clusters(&self) -> impl Iterator<Item = &Cluster> {
1422        self.state.user_clusters()
1423    }
1424
1425    pub fn get_cluster_replica(
1426        &self,
1427        cluster_id: ClusterId,
1428        replica_id: ReplicaId,
1429    ) -> &ClusterReplica {
1430        self.state.get_cluster_replica(cluster_id, replica_id)
1431    }
1432
1433    pub fn try_get_cluster_replica(
1434        &self,
1435        cluster_id: ClusterId,
1436        replica_id: ReplicaId,
1437    ) -> Option<&ClusterReplica> {
1438        self.state.try_get_cluster_replica(cluster_id, replica_id)
1439    }
1440
1441    pub fn user_cluster_replicas(&self) -> impl Iterator<Item = &ClusterReplica> {
1442        self.state.user_cluster_replicas()
1443    }
1444
1445    pub fn databases(&self) -> impl Iterator<Item = &Database> {
1446        self.state.databases()
1447    }
1448
1449    pub fn user_roles(&self) -> impl Iterator<Item = &Role> {
1450        self.state.user_roles()
1451    }
1452
1453    pub fn user_network_policies(&self) -> impl Iterator<Item = &NetworkPolicy> {
1454        self.state.user_network_policies()
1455    }
1456
1457    pub fn user_query_policies(&self) -> impl Iterator<Item = &QueryPolicy> {
1458        self.state.user_query_policies()
1459    }
1460
1461    pub fn system_privileges(&self) -> &PrivilegeMap {
1462        &self.state.system_privileges
1463    }
1464
1465    pub fn default_privileges(
1466        &self,
1467    ) -> impl Iterator<
1468        Item = (
1469            &DefaultPrivilegeObject,
1470            impl Iterator<Item = &DefaultPrivilegeAclItem>,
1471        ),
1472    > {
1473        self.state.default_privileges.iter()
1474    }
1475
1476    pub fn pack_item_update(&self, id: CatalogItemId, diff: Diff) -> Vec<BuiltinTableUpdate> {
1477        self.state
1478            .resolve_builtin_table_updates(self.state.pack_item_update(id, diff))
1479    }
1480
1481    pub fn pack_storage_usage_update(
1482        &self,
1483        event: VersionedStorageUsage,
1484        diff: Diff,
1485    ) -> BuiltinTableUpdate {
1486        self.state
1487            .resolve_builtin_table_update(self.state.pack_storage_usage_update(event, diff))
1488    }
1489
1490    pub fn system_config(&self) -> &SystemVars {
1491        self.state.system_config()
1492    }
1493
1494    pub fn system_config_mut(&mut self) -> &mut SystemVars {
1495        self.state.system_config_mut()
1496    }
1497
1498    pub fn ensure_not_reserved_role(&self, role_id: &RoleId) -> Result<(), Error> {
1499        self.state.ensure_not_reserved_role(role_id)
1500    }
1501
1502    pub fn ensure_grantable_role(&self, role_id: &RoleId) -> Result<(), Error> {
1503        self.state.ensure_grantable_role(role_id)
1504    }
1505
1506    pub fn ensure_not_system_role(&self, role_id: &RoleId) -> Result<(), Error> {
1507        self.state.ensure_not_system_role(role_id)
1508    }
1509
1510    pub fn ensure_not_predefined_role(&self, role_id: &RoleId) -> Result<(), Error> {
1511        self.state.ensure_not_predefined_role(role_id)
1512    }
1513
1514    pub fn ensure_not_reserved_network_policy(
1515        &self,
1516        network_policy_id: &NetworkPolicyId,
1517    ) -> Result<(), Error> {
1518        self.state
1519            .ensure_not_reserved_network_policy(network_policy_id)
1520    }
1521
1522    pub fn ensure_not_reserved_object(
1523        &self,
1524        object_id: &ObjectId,
1525        conn_id: &ConnectionId,
1526    ) -> Result<(), Error> {
1527        match object_id {
1528            ObjectId::Cluster(cluster_id) => {
1529                if cluster_id.is_system() {
1530                    let cluster = self.get_cluster(*cluster_id);
1531                    Err(Error::new(ErrorKind::ReadOnlyCluster(
1532                        cluster.name().to_string(),
1533                    )))
1534                } else {
1535                    Ok(())
1536                }
1537            }
1538            ObjectId::ClusterReplica((cluster_id, replica_id)) => {
1539                if replica_id.is_system() {
1540                    let replica = self.get_cluster_replica(*cluster_id, *replica_id);
1541                    Err(Error::new(ErrorKind::ReadOnlyClusterReplica(
1542                        replica.name().to_string(),
1543                    )))
1544                } else {
1545                    Ok(())
1546                }
1547            }
1548            ObjectId::Database(database_id) => {
1549                if database_id.is_system() {
1550                    let database = self.get_database(database_id);
1551                    Err(Error::new(ErrorKind::ReadOnlyDatabase(
1552                        database.name().to_string(),
1553                    )))
1554                } else {
1555                    Ok(())
1556                }
1557            }
1558            ObjectId::Schema((database_spec, schema_spec)) => {
1559                if schema_spec.is_system() {
1560                    let schema = self.get_schema(database_spec, schema_spec, conn_id);
1561                    Err(Error::new(ErrorKind::ReadOnlySystemSchema(
1562                        schema.name().schema.clone(),
1563                    )))
1564                } else {
1565                    Ok(())
1566                }
1567            }
1568            ObjectId::Role(role_id) => self.ensure_not_reserved_role(role_id),
1569            ObjectId::Item(item_id) => {
1570                if item_id.is_system() {
1571                    let item = self.get_entry(item_id);
1572                    let name = self.resolve_full_name(item.name(), Some(conn_id));
1573                    Err(Error::new(ErrorKind::ReadOnlyItem(name.to_string())))
1574                } else {
1575                    Ok(())
1576                }
1577            }
1578            ObjectId::NetworkPolicy(network_policy_id) => {
1579                self.ensure_not_reserved_network_policy(network_policy_id)
1580            }
1581            ObjectId::QueryPolicy(id) => {
1582                if id.is_builtin() {
1583                    Err(Error::new(ErrorKind::ReservedQueryPolicyName(
1584                        self.state.get_query_policy(id).name.clone(),
1585                    )))
1586                } else {
1587                    Ok(())
1588                }
1589            }
1590        }
1591    }
1592
1593    /// See [`CatalogState::deserialize_plan_with_enable_for_item_parsing`].
1594    pub(crate) fn deserialize_plan_with_enable_for_item_parsing(
1595        &mut self,
1596        create_sql: &str,
1597        force_if_exists_skip: bool,
1598    ) -> Result<(Plan, ResolvedIds), AdapterError> {
1599        self.state
1600            .deserialize_plan_with_enable_for_item_parsing(create_sql, force_if_exists_skip)
1601    }
1602
1603    /// Cache global and, optionally, local expressions for the given
1604    /// `GlobalId` of an item being created, whose only version is therefore
1605    /// the root [`RelationVersion`].
1606    ///
1607    /// Takes the plans and metainfo directly as parameters (rather than
1608    /// fishing them out of catalog state), so this can be called **before**
1609    /// the catalog transaction that creates the item. Returns the future
1610    /// returned by [`Catalog::update_expression_cache`]; callers should
1611    /// `.await` it before the catalog transaction commits, so the durable
1612    /// expression cache is observed to contain the entries by the time any
1613    /// other process (or a subsequent bootstrap on this process) reads them.
1614    pub(crate) fn cache_expressions(
1615        &self,
1616        id: GlobalId,
1617        local_mir: Option<OptimizedMirRelationExpr>,
1618        mut global_mir: DataflowDescription<OptimizedMirRelationExpr>,
1619        mut physical_plan: mz_compute_types::dataflows::LirDataflowDescription,
1620        dataflow_metainfos: DataflowMetainfo<Arc<OptimizerNotice>>,
1621        optimizer_features: OptimizerFeatures,
1622    ) -> BoxFuture<'static, ()> {
1623        // Make sure we're not caching the result of timestamp selection, as
1624        // it will almost certainly be wrong if we re-install the dataflow at
1625        // a later time.
1626        global_mir.as_of = None;
1627        global_mir.until = Default::default();
1628        physical_plan.as_of = None;
1629        physical_plan.until = Default::default();
1630
1631        let mut local_exprs = Vec::new();
1632        if let Some(local_mir) = local_mir {
1633            local_exprs.push((
1634                id,
1635                LocalExpressions {
1636                    local_mir,
1637                    optimizer_features: optimizer_features.clone(),
1638                    item_version: RelationVersion::root(),
1639                },
1640            ));
1641        }
1642        let global_exprs = vec![(
1643            id,
1644            GlobalExpressions {
1645                global_mir,
1646                physical_plan,
1647                dataflow_metainfos,
1648                optimizer_features,
1649                item_version: RelationVersion::root(),
1650            },
1651        )];
1652        self.update_expression_cache(local_exprs, global_exprs, Default::default())
1653    }
1654
1655    /// Cache the local expression for the given `GlobalId` of an item being
1656    /// created, which has no dataflow, such as a view. Otherwise the same as
1657    /// [`Catalog::cache_expressions`].
1658    pub(crate) fn cache_local_expression(
1659        &self,
1660        id: GlobalId,
1661        local_mir: OptimizedMirRelationExpr,
1662        optimizer_features: OptimizerFeatures,
1663    ) -> BoxFuture<'static, ()> {
1664        let local_exprs = vec![(
1665            id,
1666            LocalExpressions {
1667                local_mir,
1668                optimizer_features,
1669                item_version: RelationVersion::root(),
1670            },
1671        )];
1672        self.update_expression_cache(local_exprs, Vec::new(), Default::default())
1673    }
1674
1675    pub(crate) fn update_expression_cache<'a, 'b>(
1676        &'a self,
1677        new_local_expressions: Vec<(GlobalId, LocalExpressions)>,
1678        new_global_expressions: Vec<(GlobalId, GlobalExpressions)>,
1679        invalidate_ids: BTreeSet<GlobalId>,
1680    ) -> BoxFuture<'b, ()> {
1681        if let Some(expr_cache) = &self.expr_cache_handle {
1682            expr_cache
1683                .update(
1684                    new_local_expressions,
1685                    new_global_expressions,
1686                    invalidate_ids,
1687                )
1688                .boxed()
1689        } else {
1690            async {}.boxed()
1691        }
1692    }
1693
1694    /// Listen for and apply all unconsumed updates to the durable catalog state.
1695    // TODO(jkosh44) When this method is actually used outside of a test we can remove the
1696    // `#[cfg(test)]` annotation.
1697    #[cfg(test)]
1698    async fn sync_to_current_updates(
1699        &mut self,
1700    ) -> Result<
1701        (
1702            Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
1703            Vec<ParsedStateUpdate>,
1704        ),
1705        CatalogError,
1706    > {
1707        let updates = self.storage().await.sync_to_current_updates().await?;
1708        let (builtin_table_updates, catalog_updates) = self
1709            .state
1710            .apply_updates(updates, &mut state::LocalExpressionCache::Closed)
1711            .await;
1712        Ok((builtin_table_updates, catalog_updates))
1713    }
1714}
1715
1716pub fn is_reserved_name(name: &str) -> bool {
1717    BUILTIN_PREFIXES
1718        .iter()
1719        .any(|prefix| name.starts_with(prefix))
1720}
1721
1722/// Role names that PostgreSQL reserves for role specifications in statements
1723/// like `GRANT ... TO CURRENT_USER` and `SET ROLE NONE`. A role with such a
1724/// name would be ambiguous there, so creating one is not allowed.
1725///
1726/// PostgreSQL rejects most of these at parse time, only when they appear as
1727/// unquoted keywords. Our parser does not track whether an identifier was
1728/// quoted, so we instead reject the names themselves. Only the lowercase
1729/// spellings are reserved, which is what the unquoted forms normalize to, so
1730/// quoted names like `"CURRENT_USER"` remain valid, as in PostgreSQL.
1731const RESERVED_ROLE_SPECIFICATION_NAMES: [&str; 5] = [
1732    "current_user",
1733    "current_role",
1734    "session_user",
1735    "user",
1736    "none",
1737];
1738
1739pub fn is_reserved_role_name(name: &str) -> bool {
1740    is_reserved_name(name)
1741        || is_public_role(name)
1742        || RESERVED_ROLE_SPECIFICATION_NAMES.contains(&name)
1743}
1744
1745pub fn is_public_role(name: &str) -> bool {
1746    name == &*PUBLIC_ROLE_NAME
1747}
1748
1749pub(crate) fn catalog_type_to_audit_object_type(sql_type: SqlCatalogItemType) -> ObjectType {
1750    object_type_to_audit_object_type(sql_type.into())
1751}
1752
1753pub(crate) fn comment_id_to_audit_object_type(id: CommentObjectId) -> ObjectType {
1754    match id {
1755        CommentObjectId::Table(_) => ObjectType::Table,
1756        CommentObjectId::View(_) => ObjectType::View,
1757        CommentObjectId::MaterializedView(_) => ObjectType::MaterializedView,
1758        CommentObjectId::Source(_) => ObjectType::Source,
1759        CommentObjectId::Sink(_) => ObjectType::Sink,
1760        // Unreachable by construction: `COMMENT ON METRIC SINK` is rejected at parse, so no
1761        // metric-sink comment id is ever built. The arm exists only for exhaustiveness.
1762        CommentObjectId::MetricSink(_) => ObjectType::MetricSink,
1763        CommentObjectId::Index(_) => ObjectType::Index,
1764        CommentObjectId::Func(_) => ObjectType::Func,
1765        CommentObjectId::Connection(_) => ObjectType::Connection,
1766        CommentObjectId::Type(_) => ObjectType::Type,
1767        CommentObjectId::Secret(_) => ObjectType::Secret,
1768        CommentObjectId::Role(_) => ObjectType::Role,
1769        CommentObjectId::Database(_) => ObjectType::Database,
1770        CommentObjectId::Schema(_) => ObjectType::Schema,
1771        CommentObjectId::Cluster(_) => ObjectType::Cluster,
1772        CommentObjectId::ClusterReplica(_) => ObjectType::ClusterReplica,
1773        CommentObjectId::NetworkPolicy(_) => ObjectType::NetworkPolicy,
1774        CommentObjectId::QueryPolicy(_) => ObjectType::QueryPolicy,
1775    }
1776}
1777
1778pub(crate) fn object_type_to_audit_object_type(
1779    object_type: mz_sql::catalog::ObjectType,
1780) -> ObjectType {
1781    system_object_type_to_audit_object_type(&SystemObjectType::Object(object_type))
1782}
1783
1784pub(crate) fn system_object_type_to_audit_object_type(
1785    system_type: &SystemObjectType,
1786) -> ObjectType {
1787    match system_type {
1788        SystemObjectType::Object(object_type) => match object_type {
1789            mz_sql::catalog::ObjectType::Table => ObjectType::Table,
1790            mz_sql::catalog::ObjectType::View => ObjectType::View,
1791            mz_sql::catalog::ObjectType::MaterializedView => ObjectType::MaterializedView,
1792            mz_sql::catalog::ObjectType::Source => ObjectType::Source,
1793            mz_sql::catalog::ObjectType::Sink => ObjectType::Sink,
1794            mz_sql::catalog::ObjectType::MetricSink => ObjectType::MetricSink,
1795            mz_sql::catalog::ObjectType::Index => ObjectType::Index,
1796            mz_sql::catalog::ObjectType::Type => ObjectType::Type,
1797            mz_sql::catalog::ObjectType::Role => ObjectType::Role,
1798            mz_sql::catalog::ObjectType::Cluster => ObjectType::Cluster,
1799            mz_sql::catalog::ObjectType::ClusterReplica => ObjectType::ClusterReplica,
1800            mz_sql::catalog::ObjectType::Secret => ObjectType::Secret,
1801            mz_sql::catalog::ObjectType::Connection => ObjectType::Connection,
1802            mz_sql::catalog::ObjectType::Database => ObjectType::Database,
1803            mz_sql::catalog::ObjectType::Schema => ObjectType::Schema,
1804            mz_sql::catalog::ObjectType::Func => ObjectType::Func,
1805            mz_sql::catalog::ObjectType::NetworkPolicy => ObjectType::NetworkPolicy,
1806            mz_sql::catalog::ObjectType::QueryPolicy => ObjectType::QueryPolicy,
1807        },
1808        SystemObjectType::System => ObjectType::System,
1809    }
1810}
1811
1812#[derive(Debug, Copy, Clone)]
1813pub enum UpdatePrivilegeVariant {
1814    Grant,
1815    Revoke,
1816}
1817
1818impl From<UpdatePrivilegeVariant> for ExecuteResponse {
1819    fn from(variant: UpdatePrivilegeVariant) -> Self {
1820        match variant {
1821            UpdatePrivilegeVariant::Grant => ExecuteResponse::GrantedPrivilege,
1822            UpdatePrivilegeVariant::Revoke => ExecuteResponse::RevokedPrivilege,
1823        }
1824    }
1825}
1826
1827impl From<UpdatePrivilegeVariant> for EventType {
1828    fn from(variant: UpdatePrivilegeVariant) -> Self {
1829        match variant {
1830            UpdatePrivilegeVariant::Grant => EventType::Grant,
1831            UpdatePrivilegeVariant::Revoke => EventType::Revoke,
1832        }
1833    }
1834}
1835
1836impl ConnCatalog<'_> {
1837    fn resolve_item_name(
1838        &self,
1839        name: &PartialItemName,
1840    ) -> Result<&QualifiedItemName, SqlCatalogError> {
1841        self.resolve_item(name).map(|entry| entry.name())
1842    }
1843
1844    fn resolve_function_name(
1845        &self,
1846        name: &PartialItemName,
1847    ) -> Result<&QualifiedItemName, SqlCatalogError> {
1848        self.resolve_function(name).map(|entry| entry.name())
1849    }
1850
1851    fn resolve_type_name(
1852        &self,
1853        name: &PartialItemName,
1854    ) -> Result<&QualifiedItemName, SqlCatalogError> {
1855        self.resolve_type(name).map(|entry| entry.name())
1856    }
1857}
1858
1859impl ExprHumanizer for ConnCatalog<'_> {
1860    fn humanize_id(&self, id: GlobalId) -> Option<String> {
1861        let entry = self.state.try_get_entry_by_global_id(&id)?;
1862        Some(self.resolve_full_name(entry.name()).to_string())
1863    }
1864
1865    fn humanize_id_unqualified(&self, id: GlobalId) -> Option<String> {
1866        let entry = self.state.try_get_entry_by_global_id(&id)?;
1867        Some(entry.name().item.clone())
1868    }
1869
1870    fn humanize_id_parts(&self, id: GlobalId) -> Option<Vec<String>> {
1871        let entry = self.state.try_get_entry_by_global_id(&id)?;
1872        Some(self.resolve_full_name(entry.name()).into_parts())
1873    }
1874
1875    fn humanize_sql_scalar_type(&self, typ: &SqlScalarType, postgres_compat: bool) -> String {
1876        use SqlScalarType::*;
1877
1878        match typ {
1879            Array(t) => format!("{}[]", self.humanize_sql_scalar_type(t, postgres_compat)),
1880            List {
1881                custom_id: Some(item_id),
1882                ..
1883            }
1884            | Map {
1885                custom_id: Some(item_id),
1886                ..
1887            } => {
1888                let item = self.get_item(item_id);
1889                self.minimal_qualification(item.name()).to_string()
1890            }
1891            List { element_type, .. } => {
1892                format!(
1893                    "{} list",
1894                    self.humanize_sql_scalar_type(element_type, postgres_compat)
1895                )
1896            }
1897            Map { value_type, .. } => format!(
1898                "map[{}=>{}]",
1899                self.humanize_sql_scalar_type(&SqlScalarType::String, postgres_compat),
1900                self.humanize_sql_scalar_type(value_type, postgres_compat)
1901            ),
1902            Record {
1903                custom_id: Some(item_id),
1904                ..
1905            } => {
1906                let item = self.get_item(item_id);
1907                self.minimal_qualification(item.name()).to_string()
1908            }
1909            Record { fields, .. } => format!(
1910                "record({})",
1911                fields
1912                    .iter()
1913                    .map(|f| format!(
1914                        "{}: {}",
1915                        f.0,
1916                        self.humanize_sql_column_type(&f.1, postgres_compat)
1917                    ))
1918                    .join(",")
1919            ),
1920            PgLegacyChar => "\"char\"".into(),
1921            Char { length } if !postgres_compat => match length {
1922                None => "char".into(),
1923                Some(length) => format!("char({})", length.into_u32()),
1924            },
1925            VarChar { max_length } if !postgres_compat => match max_length {
1926                None => "varchar".into(),
1927                Some(length) => format!("varchar({})", length.into_u32()),
1928            },
1929            UInt16 => "uint2".into(),
1930            UInt32 => "uint4".into(),
1931            UInt64 => "uint8".into(),
1932            ty => {
1933                let pgrepr_type = mz_pgrepr::Type::from(ty);
1934                let pg_catalog_schema = SchemaSpecifier::Id(self.state.get_pg_catalog_schema_id());
1935
1936                let res = if self
1937                    .effective_search_path(true)
1938                    .iter()
1939                    .any(|(_, schema)| schema == &pg_catalog_schema)
1940                {
1941                    pgrepr_type.name().to_string()
1942                } else {
1943                    // If PG_CATALOG_SCHEMA is not in search path, you need
1944                    // qualified object name to refer to type.
1945                    let name = QualifiedItemName {
1946                        qualifiers: ItemQualifiers {
1947                            database_spec: ResolvedDatabaseSpecifier::Ambient,
1948                            schema_spec: pg_catalog_schema,
1949                        },
1950                        item: pgrepr_type.name().to_string(),
1951                    };
1952                    self.resolve_full_name(&name).to_string()
1953                };
1954                res
1955            }
1956        }
1957    }
1958
1959    fn column_names_for_id(&self, id: GlobalId) -> Option<Vec<String>> {
1960        let entry = self.state.try_get_entry_by_global_id(&id)?;
1961
1962        match entry.index() {
1963            Some(index) => {
1964                let on_desc = self.state.try_get_desc_by_global_id(&index.on)?;
1965                let mut on_names = on_desc
1966                    .iter_names()
1967                    .map(|col_name| col_name.to_string())
1968                    .collect::<Vec<_>>();
1969
1970                let (p, _) = mz_expr::permutation_for_arrangement(&index.keys, on_desc.arity());
1971
1972                // Init ix_names with unknown column names. Unknown columns are
1973                // represented as an empty String and rendered as `#c` by the
1974                // Display::fmt implementation for HumanizedExpr<'a, usize, M>.
1975                let ix_arity = p.iter().map(|x| *x + 1).max().unwrap_or(0);
1976                let mut ix_names = vec![String::new(); ix_arity];
1977
1978                // Apply the permutation by swapping on_names with ix_names.
1979                for (on_pos, ix_pos) in p.into_iter().enumerate() {
1980                    let on_name = on_names.get_mut(on_pos).expect("on_name");
1981                    let ix_name = ix_names.get_mut(ix_pos).expect("ix_name");
1982                    std::mem::swap(on_name, ix_name);
1983                }
1984
1985                Some(ix_names) // Return the updated ix_names vector.
1986            }
1987            None => {
1988                let desc = self.state.try_get_desc_by_global_id(&id)?;
1989                let column_names = desc
1990                    .iter_names()
1991                    .map(|col_name| col_name.to_string())
1992                    .collect();
1993
1994                Some(column_names)
1995            }
1996        }
1997    }
1998
1999    fn humanize_column(&self, id: GlobalId, column: usize) -> Option<String> {
2000        let desc = self.state.try_get_desc_by_global_id(&id)?;
2001        Some(desc.get_name(column).to_string())
2002    }
2003
2004    fn id_exists(&self, id: GlobalId) -> bool {
2005        self.state.entry_by_global_id.contains_key(&id)
2006    }
2007}
2008
2009impl SessionCatalog for ConnCatalog<'_> {
2010    fn active_role_id(&self) -> &RoleId {
2011        &self.role_id
2012    }
2013
2014    fn restrict_to_user_objects(&self) -> bool {
2015        self.restrict_to_user_objects
2016    }
2017
2018    fn get_prepared_statement_desc(&self, name: &str) -> Option<&StatementDesc> {
2019        self.prepared_statements
2020            .as_ref()
2021            .map(|ps| ps.get(name).map(|ps| ps.desc()))
2022            .flatten()
2023    }
2024
2025    fn get_portal_desc_unverified(&self, portal_name: &str) -> Option<&StatementDesc> {
2026        self.portals
2027            .and_then(|portals| portals.get(portal_name).map(|portal| &portal.desc))
2028    }
2029
2030    fn active_database(&self) -> Option<&DatabaseId> {
2031        self.database.as_ref()
2032    }
2033
2034    fn active_cluster(&self) -> &str {
2035        &self.cluster
2036    }
2037
2038    fn search_path(&self) -> &[(ResolvedDatabaseSpecifier, SchemaSpecifier)] {
2039        &self.search_path
2040    }
2041
2042    fn resolve_database(
2043        &self,
2044        database_name: &str,
2045    ) -> Result<&dyn mz_sql::catalog::CatalogDatabase, SqlCatalogError> {
2046        Ok(self.state.resolve_database(database_name)?)
2047    }
2048
2049    fn get_database(&self, id: &DatabaseId) -> &dyn mz_sql::catalog::CatalogDatabase {
2050        self.state
2051            .database_by_id
2052            .get(id)
2053            .expect("database doesn't exist")
2054    }
2055
2056    // `as` is ok to use to cast to a trait object.
2057    #[allow(clippy::as_conversions)]
2058    fn get_databases(&self) -> Vec<&dyn CatalogDatabase> {
2059        self.state
2060            .database_by_id
2061            .values()
2062            .map(|database| database as &dyn CatalogDatabase)
2063            .collect()
2064    }
2065
2066    fn resolve_schema(
2067        &self,
2068        database_name: Option<&str>,
2069        schema_name: &str,
2070    ) -> Result<&dyn mz_sql::catalog::CatalogSchema, SqlCatalogError> {
2071        Ok(self.state.resolve_schema(
2072            self.database.as_ref(),
2073            database_name,
2074            schema_name,
2075            &self.conn_id,
2076        )?)
2077    }
2078
2079    fn resolve_schema_in_database(
2080        &self,
2081        database_spec: &ResolvedDatabaseSpecifier,
2082        schema_name: &str,
2083    ) -> Result<&dyn mz_sql::catalog::CatalogSchema, SqlCatalogError> {
2084        Ok(self
2085            .state
2086            .resolve_schema_in_database(database_spec, schema_name, &self.conn_id)?)
2087    }
2088
2089    fn get_schema(
2090        &self,
2091        database_spec: &ResolvedDatabaseSpecifier,
2092        schema_spec: &SchemaSpecifier,
2093    ) -> &dyn CatalogSchema {
2094        self.state
2095            .get_schema(database_spec, schema_spec, &self.conn_id)
2096    }
2097
2098    // `as` is ok to use to cast to a trait object.
2099    #[allow(clippy::as_conversions)]
2100    fn get_schemas(&self) -> Vec<&dyn CatalogSchema> {
2101        self.get_databases()
2102            .into_iter()
2103            .flat_map(|database| database.schemas().into_iter())
2104            .chain(
2105                self.state
2106                    .ambient_schemas_by_id
2107                    .values()
2108                    .chain(self.state.temporary_namespaces.schemas())
2109                    .map(|schema| schema as &dyn CatalogSchema),
2110            )
2111            .collect()
2112    }
2113
2114    fn get_mz_internal_schema_id(&self) -> SchemaId {
2115        self.state().get_mz_internal_schema_id()
2116    }
2117
2118    fn get_mz_unsafe_schema_id(&self) -> SchemaId {
2119        self.state().get_mz_unsafe_schema_id()
2120    }
2121
2122    fn is_system_schema_specifier(&self, schema: SchemaSpecifier) -> bool {
2123        self.state.is_system_schema_specifier(schema)
2124    }
2125
2126    fn resolve_role(
2127        &self,
2128        role_name: &str,
2129    ) -> Result<&dyn mz_sql::catalog::CatalogRole, SqlCatalogError> {
2130        match self.state.try_get_role_by_name(role_name) {
2131            Some(role) => Ok(role),
2132            None => Err(SqlCatalogError::UnknownRole(role_name.into())),
2133        }
2134    }
2135
2136    fn resolve_network_policy(
2137        &self,
2138        policy_name: &str,
2139    ) -> Result<&dyn mz_sql::catalog::CatalogNetworkPolicy, SqlCatalogError> {
2140        match self.state.try_get_network_policy_by_name(policy_name) {
2141            Some(policy) => Ok(policy),
2142            None => Err(SqlCatalogError::UnknownNetworkPolicy(policy_name.into())),
2143        }
2144    }
2145
2146    fn try_get_role(&self, id: &RoleId) -> Option<&dyn CatalogRole> {
2147        Some(self.state.roles_by_id.get(id)?)
2148    }
2149
2150    fn get_role(&self, id: &RoleId) -> &dyn mz_sql::catalog::CatalogRole {
2151        self.state.get_role(id)
2152    }
2153
2154    fn get_roles(&self) -> Vec<&dyn CatalogRole> {
2155        // `as` is ok to use to cast to a trait object.
2156        #[allow(clippy::as_conversions)]
2157        self.state
2158            .roles_by_id
2159            .values()
2160            .map(|role| role as &dyn CatalogRole)
2161            .collect()
2162    }
2163
2164    fn mz_system_role_id(&self) -> RoleId {
2165        MZ_SYSTEM_ROLE_ID
2166    }
2167
2168    fn collect_role_membership(&self, id: &RoleId) -> BTreeSet<RoleId> {
2169        self.state.collect_role_membership(id)
2170    }
2171
2172    fn get_network_policy(
2173        &self,
2174        id: &NetworkPolicyId,
2175    ) -> &dyn mz_sql::catalog::CatalogNetworkPolicy {
2176        self.state.get_network_policy(id)
2177    }
2178
2179    fn get_network_policies(&self) -> Vec<&dyn mz_sql::catalog::CatalogNetworkPolicy> {
2180        // `as` is ok to use to cast to a trait object.
2181        #[allow(clippy::as_conversions)]
2182        self.state
2183            .network_policies_by_id
2184            .values()
2185            .map(|policy| policy as &dyn CatalogNetworkPolicy)
2186            .collect()
2187    }
2188
2189    fn resolve_query_policy(
2190        &self,
2191        name: &str,
2192    ) -> Result<&dyn mz_sql::catalog::CatalogQueryPolicy, SqlCatalogError> {
2193        Ok(self
2194            .state
2195            .try_get_query_policy_by_name(name)
2196            .ok_or_else(|| SqlCatalogError::UnknownQueryPolicy(name.into()))?)
2197    }
2198
2199    fn get_query_policy(&self, id: &QueryPolicyId) -> &dyn mz_sql::catalog::CatalogQueryPolicy {
2200        self.state.get_query_policy(id)
2201    }
2202
2203    fn get_query_policies(&self) -> Vec<&dyn mz_sql::catalog::CatalogQueryPolicy> {
2204        self.state
2205            .query_policies_by_id
2206            .values()
2207            .map(|policy| -> &dyn mz_sql::catalog::CatalogQueryPolicy { policy })
2208            .collect()
2209    }
2210
2211    fn resolve_cluster(
2212        &self,
2213        cluster_name: Option<&str>,
2214    ) -> Result<&dyn mz_sql::catalog::CatalogCluster<'_>, SqlCatalogError> {
2215        Ok(self
2216            .state
2217            .resolve_cluster(cluster_name.unwrap_or_else(|| self.active_cluster()))?)
2218    }
2219
2220    fn resolve_cluster_replica(
2221        &self,
2222        cluster_replica_name: &QualifiedReplica,
2223    ) -> Result<&dyn CatalogClusterReplica<'_>, SqlCatalogError> {
2224        Ok(self.state.resolve_cluster_replica(cluster_replica_name)?)
2225    }
2226
2227    fn resolve_item(
2228        &self,
2229        name: &PartialItemName,
2230    ) -> Result<&dyn mz_sql::catalog::CatalogItem, SqlCatalogError> {
2231        let r = self.state.resolve_entry(
2232            self.database.as_ref(),
2233            &self.effective_search_path(true),
2234            name,
2235            &self.conn_id,
2236        )?;
2237        if self.unresolvable_ids.contains(&r.id()) {
2238            Err(SqlCatalogError::UnknownItem(name.to_string()))
2239        } else {
2240            Ok(r)
2241        }
2242    }
2243
2244    fn resolve_function(
2245        &self,
2246        name: &PartialItemName,
2247    ) -> Result<&dyn mz_sql::catalog::CatalogItem, SqlCatalogError> {
2248        let r = self.state.resolve_function(
2249            self.database.as_ref(),
2250            &self.effective_search_path(false),
2251            name,
2252            &self.conn_id,
2253        )?;
2254
2255        if self.unresolvable_ids.contains(&r.id()) {
2256            Err(SqlCatalogError::UnknownFunction {
2257                name: name.to_string(),
2258                alternative: None,
2259            })
2260        } else {
2261            Ok(r)
2262        }
2263    }
2264
2265    fn resolve_type(
2266        &self,
2267        name: &PartialItemName,
2268    ) -> Result<&dyn mz_sql::catalog::CatalogItem, SqlCatalogError> {
2269        let r = self.state.resolve_type(
2270            self.database.as_ref(),
2271            &self.effective_search_path(false),
2272            name,
2273            &self.conn_id,
2274        )?;
2275
2276        if self.unresolvable_ids.contains(&r.id()) {
2277            Err(SqlCatalogError::UnknownType {
2278                name: name.to_string(),
2279            })
2280        } else {
2281            Ok(r)
2282        }
2283    }
2284
2285    fn get_system_type(&self, name: &str) -> &dyn mz_sql::catalog::CatalogItem {
2286        self.state.get_system_type(name)
2287    }
2288
2289    fn try_get_item(&self, id: &CatalogItemId) -> Option<&dyn mz_sql::catalog::CatalogItem> {
2290        Some(self.state.try_get_entry(id)?)
2291    }
2292
2293    fn try_get_item_by_global_id(
2294        &self,
2295        id: &GlobalId,
2296    ) -> Option<Box<dyn mz_sql::catalog::CatalogCollectionItem>> {
2297        let entry = self.state.try_get_entry_by_global_id(id)?;
2298        let entry = match &entry.item {
2299            CatalogItem::Table(table) => {
2300                let (version, _gid) = table
2301                    .collections
2302                    .iter()
2303                    .find(|(_version, gid)| *gid == id)
2304                    .expect("catalog out of sync, mismatched GlobalId");
2305                entry.at_version(RelationVersionSelector::Specific(*version))
2306            }
2307            _ => entry.at_version(RelationVersionSelector::Latest),
2308        };
2309        Some(entry)
2310    }
2311
2312    fn get_item(&self, id: &CatalogItemId) -> &dyn mz_sql::catalog::CatalogItem {
2313        self.state.get_entry(id)
2314    }
2315
2316    fn get_item_by_global_id(
2317        &self,
2318        id: &GlobalId,
2319    ) -> Box<dyn mz_sql::catalog::CatalogCollectionItem> {
2320        let entry = self.state.get_entry_by_global_id(id);
2321        let entry = match &entry.item {
2322            CatalogItem::Table(table) => {
2323                let (version, _gid) = table
2324                    .collections
2325                    .iter()
2326                    .find(|(_version, gid)| *gid == id)
2327                    .expect("catalog out of sync, mismatched GlobalId");
2328                entry.at_version(RelationVersionSelector::Specific(*version))
2329            }
2330            _ => entry.at_version(RelationVersionSelector::Latest),
2331        };
2332        entry
2333    }
2334
2335    fn get_items(&self) -> Vec<&dyn mz_sql::catalog::CatalogItem> {
2336        self.get_schemas()
2337            .into_iter()
2338            .flat_map(|schema| schema.item_ids())
2339            .map(|id| self.get_item(&id))
2340            .collect()
2341    }
2342
2343    fn get_item_by_name(&self, name: &QualifiedItemName) -> Option<&dyn SqlCatalogItem> {
2344        self.state
2345            .get_item_by_name(name, &self.conn_id)
2346            .map(|item| convert::identity::<&dyn SqlCatalogItem>(item))
2347    }
2348
2349    fn get_type_by_name(&self, name: &QualifiedItemName) -> Option<&dyn SqlCatalogItem> {
2350        self.state
2351            .get_type_by_name(name, &self.conn_id)
2352            .map(|item| convert::identity::<&dyn SqlCatalogItem>(item))
2353    }
2354
2355    fn get_cluster(&self, id: ClusterId) -> &dyn mz_sql::catalog::CatalogCluster<'_> {
2356        &self.state.clusters_by_id[&id]
2357    }
2358
2359    fn get_clusters(&self) -> Vec<&dyn mz_sql::catalog::CatalogCluster<'_>> {
2360        self.state
2361            .clusters_by_id
2362            .values()
2363            .map(|cluster| convert::identity::<&dyn mz_sql::catalog::CatalogCluster>(cluster))
2364            .collect()
2365    }
2366
2367    fn get_cluster_replica(
2368        &self,
2369        cluster_id: ClusterId,
2370        replica_id: ReplicaId,
2371    ) -> &dyn mz_sql::catalog::CatalogClusterReplica<'_> {
2372        let cluster = self.get_cluster(cluster_id);
2373        cluster.replica(replica_id)
2374    }
2375
2376    fn get_cluster_replicas(&self) -> Vec<&dyn mz_sql::catalog::CatalogClusterReplica<'_>> {
2377        self.get_clusters()
2378            .into_iter()
2379            .flat_map(|cluster| cluster.replicas().into_iter())
2380            .collect()
2381    }
2382
2383    fn get_system_privileges(&self) -> &PrivilegeMap {
2384        &self.state.system_privileges
2385    }
2386
2387    fn get_default_privileges(
2388        &self,
2389    ) -> Vec<(&DefaultPrivilegeObject, Vec<&DefaultPrivilegeAclItem>)> {
2390        self.state
2391            .default_privileges
2392            .iter()
2393            .map(|(object, acl_items)| (object, acl_items.collect()))
2394            .collect()
2395    }
2396
2397    fn find_available_name(&self, name: QualifiedItemName) -> QualifiedItemName {
2398        self.state.find_available_name(name, &self.conn_id)
2399    }
2400
2401    fn resolve_full_name(&self, name: &QualifiedItemName) -> FullItemName {
2402        self.state.resolve_full_name(name, Some(&self.conn_id))
2403    }
2404
2405    fn resolve_full_schema_name(&self, name: &QualifiedSchemaName) -> FullSchemaName {
2406        self.state.resolve_full_schema_name(name)
2407    }
2408
2409    fn resolve_item_id(&self, global_id: &GlobalId) -> CatalogItemId {
2410        self.state.get_entry_by_global_id(global_id).id()
2411    }
2412
2413    fn resolve_global_id(
2414        &self,
2415        item_id: &CatalogItemId,
2416        version: RelationVersionSelector,
2417    ) -> GlobalId {
2418        self.state
2419            .get_entry(item_id)
2420            .at_version(version)
2421            .global_id()
2422    }
2423
2424    fn config(&self) -> &mz_sql::catalog::CatalogConfig {
2425        self.state.config()
2426    }
2427
2428    fn now(&self) -> EpochMillis {
2429        (self.state.config().now)()
2430    }
2431
2432    fn aws_privatelink_availability_zones(&self) -> Option<BTreeSet<String>> {
2433        self.state.aws_privatelink_availability_zones.clone()
2434    }
2435
2436    fn system_vars(&self) -> &SystemVars {
2437        &self.state.system_configuration
2438    }
2439
2440    fn system_vars_mut(&mut self) -> &mut SystemVars {
2441        Arc::make_mut(&mut self.state.to_mut().system_configuration)
2442    }
2443
2444    fn get_owner_id(&self, id: &ObjectId) -> Option<RoleId> {
2445        self.state().get_owner_id(id, self.conn_id())
2446    }
2447
2448    fn get_privileges(&self, id: &SystemObjectId) -> Option<&PrivilegeMap> {
2449        match id {
2450            SystemObjectId::System => Some(&self.state.system_privileges),
2451            SystemObjectId::Object(ObjectId::Cluster(id)) => {
2452                Some(self.get_cluster(*id).privileges())
2453            }
2454            SystemObjectId::Object(ObjectId::Database(id)) => {
2455                Some(self.get_database(id).privileges())
2456            }
2457            SystemObjectId::Object(ObjectId::Schema((database_spec, schema_spec))) => {
2458                // For temporary schemas that haven't been created yet (lazy creation),
2459                // we return None - the RBAC check will need to handle this case.
2460                self.state
2461                    .try_get_schema(database_spec, schema_spec, &self.conn_id)
2462                    .map(|schema| schema.privileges())
2463            }
2464            SystemObjectId::Object(ObjectId::Item(id)) => Some(self.get_item(id).privileges()),
2465            SystemObjectId::Object(ObjectId::NetworkPolicy(id)) => {
2466                Some(self.get_network_policy(id).privileges())
2467            }
2468            SystemObjectId::Object(ObjectId::QueryPolicy(id)) => {
2469                Some(&self.state.get_query_policy(id).privileges)
2470            }
2471            SystemObjectId::Object(ObjectId::ClusterReplica(_))
2472            | SystemObjectId::Object(ObjectId::Role(_)) => None,
2473        }
2474    }
2475
2476    fn object_dependents(&self, ids: &Vec<ObjectId>) -> Vec<ObjectId> {
2477        let mut seen = BTreeSet::new();
2478        self.state.object_dependents(ids, &self.conn_id, &mut seen)
2479    }
2480
2481    fn item_dependents(&self, id: CatalogItemId) -> Vec<ObjectId> {
2482        let mut seen = BTreeSet::new();
2483        self.state.item_dependents(id, &mut seen)
2484    }
2485
2486    fn all_object_privileges(&self, object_type: mz_sql::catalog::SystemObjectType) -> AclMode {
2487        rbac::all_object_privileges(object_type)
2488    }
2489
2490    fn get_object_type(&self, object_id: &ObjectId) -> mz_sql::catalog::ObjectType {
2491        self.state.get_object_type(object_id)
2492    }
2493
2494    fn get_system_object_type(&self, id: &SystemObjectId) -> mz_sql::catalog::SystemObjectType {
2495        self.state.get_system_object_type(id)
2496    }
2497
2498    /// Returns a [`PartialItemName`] with the minimum amount of qualifiers to unambiguously resolve
2499    /// the object.
2500    ///
2501    /// Warning: This is broken for temporary objects. Don't use this function for serious stuff,
2502    /// i.e., don't expect that what you get back is a thing you can resolve. Current usages are
2503    /// only for error msgs and other humanizations.
2504    fn minimal_qualification(&self, qualified_name: &QualifiedItemName) -> PartialItemName {
2505        if qualified_name.qualifiers.schema_spec.is_temporary() {
2506            // All bets are off. Just give up and return the qualified name as is.
2507            // TODO: Figure out what's going on with temporary objects.
2508
2509            // See e.g. `temporary_objects.slt` fail if you comment this out, which has the repro
2510            // from https://github.com/MaterializeInc/database-issues/issues/9973#issuecomment-3646382143
2511            // There is also https://github.com/MaterializeInc/database-issues/issues/9974, for
2512            // which we don't have a simple repro.
2513            return qualified_name.item.clone().into();
2514        }
2515
2516        let database_id = match &qualified_name.qualifiers.database_spec {
2517            ResolvedDatabaseSpecifier::Ambient => None,
2518            ResolvedDatabaseSpecifier::Id(id)
2519                if self.database.is_some() && self.database == Some(*id) =>
2520            {
2521                None
2522            }
2523            ResolvedDatabaseSpecifier::Id(id) => Some(id.clone()),
2524        };
2525
2526        let schema_spec = if database_id.is_none()
2527            && self.resolve_item_name(&PartialItemName {
2528                database: None,
2529                schema: None,
2530                item: qualified_name.item.clone(),
2531            }) == Ok(qualified_name)
2532            || self.resolve_function_name(&PartialItemName {
2533                database: None,
2534                schema: None,
2535                item: qualified_name.item.clone(),
2536            }) == Ok(qualified_name)
2537            || self.resolve_type_name(&PartialItemName {
2538                database: None,
2539                schema: None,
2540                item: qualified_name.item.clone(),
2541            }) == Ok(qualified_name)
2542        {
2543            None
2544        } else {
2545            // If `search_path` does not contain `full_name.schema`, the
2546            // `PartialName` must contain it.
2547            Some(qualified_name.qualifiers.schema_spec.clone())
2548        };
2549
2550        let res = PartialItemName {
2551            database: database_id.map(|id| self.get_database(&id).name().to_string()),
2552            schema: schema_spec.map(|spec| {
2553                self.get_schema(&qualified_name.qualifiers.database_spec, &spec)
2554                    .name()
2555                    .schema
2556                    .clone()
2557            }),
2558            item: qualified_name.item.clone(),
2559        };
2560        assert!(
2561            self.resolve_item_name(&res) == Ok(qualified_name)
2562                || self.resolve_function_name(&res) == Ok(qualified_name)
2563                || self.resolve_type_name(&res) == Ok(qualified_name)
2564        );
2565        res
2566    }
2567
2568    fn add_notice(&self, notice: PlanNotice) {
2569        let _ = self.notices_tx.send(notice.into());
2570    }
2571
2572    fn get_item_comments(&self, id: &CatalogItemId) -> Option<&BTreeMap<Option<usize>, String>> {
2573        let comment_id = self.state.get_comment_id(ObjectId::Item(*id));
2574        self.state.comments.get_object_comments(comment_id)
2575    }
2576
2577    fn is_cluster_size_cc(&self, size: &str) -> bool {
2578        self.state
2579            .cluster_replica_sizes
2580            .0
2581            .get(size)
2582            .map_or(false, |a| a.is_cc)
2583    }
2584}
2585
2586#[cfg(test)]
2587mod source_preparation_tests;
2588
2589#[cfg(test)]
2590mod try_cast_tests;
2591
2592#[cfg(test)]
2593mod tests {
2594    use std::collections::{BTreeMap, BTreeSet};
2595    use std::sync::Arc;
2596    use std::{env, iter};
2597
2598    use itertools::Itertools;
2599    use mz_catalog::memory::objects::{
2600        CatalogItem, ClusterConfig, ClusterVariant, ClusterVariantManaged, ReconfigurationState,
2601        ReconfigurationStatus, ReconfigurationTarget,
2602    };
2603    use mz_controller::clusters::ReplicaLogging;
2604    use mz_postgres_util::{query, sql};
2605    use tokio_postgres::NoTls;
2606    use tokio_postgres::types::Type;
2607    use uuid::Uuid;
2608
2609    use mz_catalog::SYSTEM_CONN_ID;
2610    use mz_catalog::builtin::{BUILTINS, Builtin, BuiltinType};
2611    use mz_catalog::durable::{CatalogError, DurableCatalogError, FenceError, test_bootstrap_args};
2612    use mz_controller_types::{ClusterId, ReplicaId};
2613    use mz_expr::{Eval, MirScalarExpr};
2614    use mz_ore::now::to_datetime;
2615    use mz_ore::{assert_err, assert_ok, soft_assert_eq_or_log, task};
2616    use mz_persist_client::PersistClient;
2617    use mz_pgrepr::oid::{FIRST_MATERIALIZE_OID, FIRST_UNPINNED_OID, FIRST_USER_OID};
2618    use mz_repr::namespaces::{INFORMATION_SCHEMA, PG_CATALOG_SCHEMA};
2619    use mz_repr::role_id::RoleId;
2620    use mz_repr::{
2621        CatalogItemId, Datum, GlobalId, RelationVersionSelector, Row, RowArena, SqlRelationType,
2622        SqlScalarType, Timestamp,
2623    };
2624    use mz_sql::catalog::{CatalogSchema, CatalogType, SessionCatalog};
2625    use mz_sql::func::{Func, FuncImpl, OP_IMPLS, Operation};
2626    use mz_sql::names::{
2627        self, DatabaseId, ItemQualifiers, ObjectId, PartialItemName, QualifiedItemName,
2628        ResolvedDatabaseSpecifier, SchemaId, SchemaSpecifier, SystemObjectId,
2629    };
2630    use mz_sql::plan::{
2631        AutoScalingStrategy, CoercibleScalarExpr, ExprContext, HirScalarExpr, HirToMirConfig,
2632        OnHydration, OnTimeoutAction, PlanContext, QueryContext, QueryLifetime, Scope,
2633        StatementContext,
2634    };
2635    use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
2636    use mz_sql::session::vars::{SystemVars, VarInput};
2637
2638    use crate::catalog::state::LocalExpressionCache;
2639    use crate::catalog::{Catalog, DebugAwsContext, Op};
2640    use crate::optimize::dataflows::{EvalTime, ExprPrep, ExprPrepOneShot};
2641    use crate::session::Session;
2642
2643    /// System sessions have an empty `search_path` so it's necessary to
2644    /// schema-qualify all referenced items.
2645    ///
2646    /// Dummy (and ostensibly client) sessions contain system schemas in their
2647    /// search paths, so do not require schema qualification on system objects such
2648    /// as types.
2649    #[mz_ore::test(tokio::test)]
2650    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
2651    async fn test_minimal_qualification() {
2652        Catalog::with_debug(|catalog| async move {
2653            struct TestCase {
2654                input: QualifiedItemName,
2655                system_output: PartialItemName,
2656                normal_output: PartialItemName,
2657            }
2658
2659            let test_cases = vec![
2660                TestCase {
2661                    input: QualifiedItemName {
2662                        qualifiers: ItemQualifiers {
2663                            database_spec: ResolvedDatabaseSpecifier::Ambient,
2664                            schema_spec: SchemaSpecifier::Id(catalog.get_pg_catalog_schema_id()),
2665                        },
2666                        item: "numeric".to_string(),
2667                    },
2668                    system_output: PartialItemName {
2669                        database: None,
2670                        schema: None,
2671                        item: "numeric".to_string(),
2672                    },
2673                    normal_output: PartialItemName {
2674                        database: None,
2675                        schema: None,
2676                        item: "numeric".to_string(),
2677                    },
2678                },
2679                TestCase {
2680                    input: QualifiedItemName {
2681                        qualifiers: ItemQualifiers {
2682                            database_spec: ResolvedDatabaseSpecifier::Ambient,
2683                            schema_spec: SchemaSpecifier::Id(catalog.get_mz_catalog_schema_id()),
2684                        },
2685                        item: "mz_array_types".to_string(),
2686                    },
2687                    system_output: PartialItemName {
2688                        database: None,
2689                        schema: None,
2690                        item: "mz_array_types".to_string(),
2691                    },
2692                    normal_output: PartialItemName {
2693                        database: None,
2694                        schema: None,
2695                        item: "mz_array_types".to_string(),
2696                    },
2697                },
2698            ];
2699
2700            for tc in test_cases {
2701                assert_eq!(
2702                    catalog
2703                        .for_system_session()
2704                        .minimal_qualification(&tc.input),
2705                    tc.system_output
2706                );
2707                assert_eq!(
2708                    catalog
2709                        .for_session(&Session::dummy())
2710                        .minimal_qualification(&tc.input),
2711                    tc.normal_output
2712                );
2713            }
2714            catalog.expire().await;
2715        })
2716        .await
2717    }
2718
2719    #[mz_ore::test(tokio::test)]
2720    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
2721    async fn test_catalog_revision() {
2722        let persist_client = PersistClient::new_for_tests().await;
2723        let organization_id = Uuid::new_v4();
2724        let bootstrap_args = test_bootstrap_args();
2725        {
2726            let mut catalog = Catalog::open_debug_catalog(
2727                persist_client.clone(),
2728                organization_id.clone(),
2729                &bootstrap_args,
2730            )
2731            .await
2732            .expect("unable to open debug catalog");
2733            assert_eq!(catalog.transient_revision(), 1);
2734            assert!(catalog.transient_revision_is_current());
2735            let snapshot = catalog.clone();
2736            let commit_ts = catalog.current_upper().await;
2737            catalog
2738                .transact(
2739                    None,
2740                    commit_ts,
2741                    None,
2742                    vec![Op::CreateDatabase {
2743                        name: "test".to_string(),
2744                        owner_id: MZ_SYSTEM_ROLE_ID,
2745                    }],
2746                )
2747                .await
2748                .expect("failed to transact");
2749            assert_eq!(catalog.transient_revision(), 2);
2750            assert!(catalog.transient_revision_is_current());
2751            // The pre-transaction snapshot detects its own staleness through
2752            // the shared latest revision.
2753            assert!(!snapshot.transient_revision_is_current());
2754            catalog.expire().await;
2755        }
2756        {
2757            let catalog =
2758                Catalog::open_debug_catalog(persist_client, organization_id, &bootstrap_args)
2759                    .await
2760                    .expect("unable to open debug catalog");
2761            // Re-opening the same catalog resets the transient_revision to 1.
2762            assert_eq!(catalog.transient_revision(), 1);
2763            catalog.expire().await;
2764        }
2765    }
2766
2767    #[mz_ore::test(tokio::test)]
2768    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
2769    async fn test_builtin_cluster_replica_size_sync() {
2770        let persist_client = PersistClient::new_for_tests().await;
2771        let organization_id = Uuid::new_v4();
2772        let mut bootstrap_args = test_bootstrap_args();
2773        // Builtin cluster replicas use the default size.
2774        let in_use = bootstrap_args.default_cluster_replica_size.clone();
2775        let unused = "scale=1,workers=2".to_string();
2776        let changed = "scale=1,workers=4".to_string();
2777        let cluster_only = "scale=1,workers=8".to_string();
2778        let hydration = "scale=1,workers=16".to_string();
2779        let timed_out_target = "scale=1,workers=32".to_string();
2780
2781        let mut catalog =
2782            Catalog::open_debug_catalog(persist_client.clone(), organization_id, &bootstrap_args)
2783                .await
2784                .expect("unable to open debug catalog");
2785        assert_eq!(
2786            catalog.cluster_replica_sizes().0,
2787            bootstrap_args.cluster_replica_size_map.0
2788        );
2789        // A managed cluster with no replicas still depends on its size and
2790        // hydration size, but not on a settled reconfiguration's target.
2791        let commit_ts = catalog.current_upper().await;
2792        let cluster_id = catalog
2793            .allocate_user_cluster_id(commit_ts)
2794            .await
2795            .expect("allocate cluster id");
2796        let config = ClusterConfig {
2797            variant: ClusterVariant::Managed(ClusterVariantManaged {
2798                size: cluster_only.clone(),
2799                availability_zones: Vec::new(),
2800                logging: ReplicaLogging {
2801                    log_logging: false,
2802                    interval: None,
2803                },
2804                arrangement_compression: false,
2805                replication_factor: 0,
2806                optimizer_feature_overrides: Default::default(),
2807                schedule: Default::default(),
2808                auto_scaling_strategy: Some(AutoScalingStrategy {
2809                    on_hydration: Some(OnHydration {
2810                        hydration_size: hydration.clone(),
2811                        linger_duration: None,
2812                    }),
2813                }),
2814                reconfiguration: Some(ReconfigurationState {
2815                    target: ReconfigurationTarget {
2816                        size: timed_out_target.clone(),
2817                        replication_factor: 1,
2818                        availability_zones: Vec::new(),
2819                        logging: ReplicaLogging {
2820                            log_logging: false,
2821                            interval: None,
2822                        },
2823                        arrangement_compression: false,
2824                    },
2825                    deadline: Timestamp::MIN,
2826                    on_timeout: OnTimeoutAction::Rollback,
2827                    status: ReconfigurationStatus::TimedOut,
2828                }),
2829                burst: None,
2830            }),
2831            workload_class: None,
2832            query_policy: None,
2833        };
2834        let commit_ts = catalog.current_upper().await;
2835        catalog
2836            .transact(
2837                None,
2838                commit_ts,
2839                None,
2840                vec![Op::CreateCluster {
2841                    id: cluster_id,
2842                    name: "no_replicas".into(),
2843                    introspection_sources: Vec::new(),
2844                    owner_id: MZ_SYSTEM_ROLE_ID,
2845                    config,
2846                }],
2847            )
2848            .await
2849            .expect("create cluster");
2850        catalog.expire().await;
2851
2852        let config_sizes = &mut bootstrap_args.cluster_replica_size_map.0;
2853        config_sizes.remove(&in_use);
2854        config_sizes.remove(&unused);
2855        config_sizes.remove(&cluster_only);
2856        config_sizes.remove(&hydration);
2857        config_sizes.remove(&timed_out_target);
2858        config_sizes
2859            .get_mut(&changed)
2860            .expect("test size")
2861            .cpu_exclusive = true;
2862        let catalog =
2863            Catalog::open_debug_catalog(persist_client.clone(), organization_id, &bootstrap_args)
2864                .await
2865                .expect("unable to open debug catalog");
2866        let sizes = &catalog.cluster_replica_sizes().0;
2867        assert!(sizes[&in_use].disabled);
2868        assert!(sizes[&cluster_only].disabled);
2869        assert!(sizes[&hydration].disabled);
2870        assert!(!sizes.contains_key(&unused));
2871        assert!(!sizes.contains_key(&timed_out_target));
2872        assert_eq!(
2873            sizes[&changed],
2874            bootstrap_args.cluster_replica_size_map.0[&changed]
2875        );
2876        let durable_sizes = catalog.cluster_replica_sizes().clone();
2877        catalog.expire().await;
2878
2879        // A read-only open with a different size config uses the durable sizes.
2880        bootstrap_args
2881            .cluster_replica_size_map
2882            .0
2883            .insert(unused.clone(), durable_sizes.0[&changed].clone());
2884        let catalog =
2885            Catalog::open_debug_read_only_catalog(persist_client, organization_id, &bootstrap_args)
2886                .await
2887                .expect("unable to open read-only debug catalog");
2888        assert_eq!(catalog.cluster_replica_sizes().0, durable_sizes.0);
2889        catalog.expire().await;
2890    }
2891
2892    #[mz_ore::test(tokio::test)]
2893    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
2894    async fn test_effective_search_path() {
2895        Catalog::with_debug(|catalog| async move {
2896            let mz_catalog_schema = (
2897                ResolvedDatabaseSpecifier::Ambient,
2898                SchemaSpecifier::Id(catalog.state().get_mz_catalog_schema_id()),
2899            );
2900            let pg_catalog_schema = (
2901                ResolvedDatabaseSpecifier::Ambient,
2902                SchemaSpecifier::Id(catalog.state().get_pg_catalog_schema_id()),
2903            );
2904            let mz_temp_schema = (
2905                ResolvedDatabaseSpecifier::Ambient,
2906                SchemaSpecifier::Temporary,
2907            );
2908
2909            // Behavior with the default search_schema (public)
2910            let session = Session::dummy();
2911            let conn_catalog = catalog.for_session(&session);
2912            assert_ne!(
2913                conn_catalog.effective_search_path(false),
2914                conn_catalog.search_path
2915            );
2916            assert_ne!(
2917                conn_catalog.effective_search_path(true),
2918                conn_catalog.search_path
2919            );
2920            assert_eq!(
2921                conn_catalog.effective_search_path(false),
2922                vec![
2923                    mz_catalog_schema.clone(),
2924                    pg_catalog_schema.clone(),
2925                    conn_catalog.search_path[0].clone()
2926                ]
2927            );
2928            assert_eq!(
2929                conn_catalog.effective_search_path(true),
2930                vec![
2931                    mz_temp_schema.clone(),
2932                    mz_catalog_schema.clone(),
2933                    pg_catalog_schema.clone(),
2934                    conn_catalog.search_path[0].clone()
2935                ]
2936            );
2937
2938            // missing schemas are added when missing
2939            let mut session = Session::dummy();
2940            session
2941                .vars_mut()
2942                .set(
2943                    &SystemVars::new(),
2944                    "search_path",
2945                    VarInput::Flat(mz_repr::namespaces::PG_CATALOG_SCHEMA),
2946                    false,
2947                )
2948                .expect("failed to set search_path");
2949            let conn_catalog = catalog.for_session(&session);
2950            assert_ne!(
2951                conn_catalog.effective_search_path(false),
2952                conn_catalog.search_path
2953            );
2954            assert_ne!(
2955                conn_catalog.effective_search_path(true),
2956                conn_catalog.search_path
2957            );
2958            assert_eq!(
2959                conn_catalog.effective_search_path(false),
2960                vec![mz_catalog_schema.clone(), pg_catalog_schema.clone()]
2961            );
2962            assert_eq!(
2963                conn_catalog.effective_search_path(true),
2964                vec![
2965                    mz_temp_schema.clone(),
2966                    mz_catalog_schema.clone(),
2967                    pg_catalog_schema.clone()
2968                ]
2969            );
2970
2971            let mut session = Session::dummy();
2972            session
2973                .vars_mut()
2974                .set(
2975                    &SystemVars::new(),
2976                    "search_path",
2977                    VarInput::Flat(mz_repr::namespaces::MZ_CATALOG_SCHEMA),
2978                    false,
2979                )
2980                .expect("failed to set search_path");
2981            let conn_catalog = catalog.for_session(&session);
2982            assert_ne!(
2983                conn_catalog.effective_search_path(false),
2984                conn_catalog.search_path
2985            );
2986            assert_ne!(
2987                conn_catalog.effective_search_path(true),
2988                conn_catalog.search_path
2989            );
2990            assert_eq!(
2991                conn_catalog.effective_search_path(false),
2992                vec![pg_catalog_schema.clone(), mz_catalog_schema.clone()]
2993            );
2994            assert_eq!(
2995                conn_catalog.effective_search_path(true),
2996                vec![
2997                    mz_temp_schema.clone(),
2998                    pg_catalog_schema.clone(),
2999                    mz_catalog_schema.clone()
3000                ]
3001            );
3002
3003            let mut session = Session::dummy();
3004            session
3005                .vars_mut()
3006                .set(
3007                    &SystemVars::new(),
3008                    "search_path",
3009                    VarInput::Flat(mz_repr::namespaces::MZ_TEMP_SCHEMA),
3010                    false,
3011                )
3012                .expect("failed to set search_path");
3013            let conn_catalog = catalog.for_session(&session);
3014            assert_ne!(
3015                conn_catalog.effective_search_path(false),
3016                conn_catalog.search_path
3017            );
3018            assert_ne!(
3019                conn_catalog.effective_search_path(true),
3020                conn_catalog.search_path
3021            );
3022            // Because we lazily initialize the `mz_temp` schema,
3023            // an explicit `mz_temp` search path before the first
3024            // temporary item creation gets filtered out in
3025            // `effective_search_path`.
3026            assert_eq!(
3027                conn_catalog.effective_search_path(false),
3028                vec![mz_catalog_schema.clone(), pg_catalog_schema.clone(),]
3029            );
3030            assert_eq!(
3031                conn_catalog.effective_search_path(true),
3032                vec![mz_temp_schema, mz_catalog_schema, pg_catalog_schema]
3033            );
3034            catalog.expire().await;
3035        })
3036        .await
3037    }
3038
3039    #[mz_ore::test(tokio::test)]
3040    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
3041    async fn test_normalized_create() {
3042        use mz_ore::collections::CollectionExt;
3043        Catalog::with_debug(|catalog| async move {
3044            let conn_catalog = catalog.for_system_session();
3045            let scx = &mut StatementContext::new(None, &conn_catalog);
3046
3047            let parsed = mz_sql_parser::parser::parse_statements(
3048                "create view public.foo as select 1 as bar",
3049            )
3050            .expect("")
3051            .into_element()
3052            .ast;
3053
3054            let (stmt, _) = names::resolve(scx.catalog, parsed).expect("");
3055
3056            // Ensure that all identifiers are quoted.
3057            assert_eq!(
3058                r#"CREATE VIEW "materialize"."public"."foo" AS SELECT 1 AS "bar""#,
3059                mz_sql::normalize::create_statement(scx, stmt).expect(""),
3060            );
3061            catalog.expire().await;
3062        })
3063        .await;
3064    }
3065
3066    /// Resolving a statement and resolving its normalized `create_sql` must
3067    /// yield the same `ResolvedIds`.
3068    ///
3069    /// The in-memory catalog records the ids from the first resolution, while
3070    /// a catalog reload re-derives them from the stored `create_sql`. Any
3071    /// disagreement makes the reloaded catalog differ from the in-memory one.
3072    #[mz_ore::test(tokio::test)]
3073    #[cfg_attr(miri, ignore)] // slow
3074    async fn test_resolved_ids_survive_create_sql_round_trip() {
3075        use mz_ore::collections::CollectionExt;
3076        Catalog::with_debug(|catalog| async move {
3077            let conn_catalog = catalog.for_system_session();
3078            let scx = &mut StatementContext::new(None, &conn_catalog);
3079
3080            let resolve_and_normalize = |scx: &mut StatementContext, sql: &str| {
3081                let parsed = mz_sql_parser::parser::parse_statements(sql)
3082                    .expect("parses")
3083                    .into_element()
3084                    .ast;
3085                let (stmt, ids) = names::resolve(scx.catalog, parsed).expect("resolves");
3086                let normalized =
3087                    mz_sql::normalize::create_statement(scx, stmt).expect("normalizes");
3088                (ids, normalized)
3089            };
3090
3091            const ARRAY_SUFFIX: &str = "create table public.t (a pg_catalog.int4[])";
3092            const ARRAY_TYPE: &str = "create table public.t (a pg_catalog._int4)";
3093            const ELEMENT_TYPE: &str = "create table public.t (a pg_catalog.int4)";
3094
3095            let mut ids_by_spelling: BTreeMap<&str, Vec<CatalogItemId>> = BTreeMap::new();
3096            for sql in [
3097                ARRAY_SUFFIX,
3098                ARRAY_TYPE,
3099                ELEMENT_TYPE,
3100                "create table public.t (a pg_catalog.int4 list)",
3101                "create view public.v as select null::pg_catalog.text[]",
3102            ] {
3103                let (ids, normalized) = resolve_and_normalize(scx, sql);
3104                let (round_tripped_ids, _) = resolve_and_normalize(scx, &normalized);
3105                assert_eq!(
3106                    ids.items().collect::<Vec<_>>(),
3107                    round_tripped_ids.items().collect::<Vec<_>>(),
3108                    "resolving {normalized:?} produced different ids than {sql:?}",
3109                );
3110                ids_by_spelling.insert(sql, ids.items().copied().collect());
3111            }
3112
3113            // `int4[]` and `_int4` name the same type, so both spellings must
3114            // record the same ids. `int4[]` is only ever stored as `_int4`,
3115            // so this is what keeps the reloaded catalog identical to the
3116            // in-memory one.
3117            assert_eq!(
3118                ids_by_spelling[ARRAY_SUFFIX], ids_by_spelling[ARRAY_TYPE],
3119                "{ARRAY_SUFFIX:?} and {ARRAY_TYPE:?} must resolve to the same ids",
3120            );
3121
3122            // Neither spelling records the element type: an array reference
3123            // names the array type alone.
3124            let element_ids = &ids_by_spelling[ELEMENT_TYPE];
3125            assert!(
3126                ids_by_spelling[ARRAY_SUFFIX]
3127                    .iter()
3128                    .all(|id| !element_ids.contains(id)),
3129                "{ARRAY_SUFFIX:?} recorded an element type id from {ELEMENT_TYPE:?}",
3130            );
3131
3132            catalog.expire().await;
3133        })
3134        .await;
3135    }
3136
3137    // Test that if a large catalog item is somehow committed, then we can still load the catalog.
3138    #[mz_ore::test(tokio::test)]
3139    #[cfg_attr(miri, ignore)] // slow
3140    async fn test_large_catalog_item() {
3141        let view_def = "CREATE VIEW \"materialize\".\"public\".\"v\" AS SELECT 1 FROM (SELECT 1";
3142        let column = ", 1";
3143        let view_def_size = view_def.bytes().count();
3144        let column_size = column.bytes().count();
3145        let column_count =
3146            (mz_sql_parser::parser::MAX_STATEMENT_BATCH_SIZE - view_def_size) / column_size + 1;
3147        let columns = iter::repeat(column).take(column_count).join("");
3148        let create_sql = format!("{view_def}{columns})");
3149        let create_sql_check = create_sql.clone();
3150        assert_ok!(mz_sql_parser::parser::parse_statements(&create_sql));
3151        assert_err!(mz_sql_parser::parser::parse_statements_with_limit(
3152            &create_sql
3153        ));
3154
3155        let persist_client = PersistClient::new_for_tests().await;
3156        let organization_id = Uuid::new_v4();
3157        let id = CatalogItemId::User(1);
3158        let gid = GlobalId::User(1);
3159        let bootstrap_args = test_bootstrap_args();
3160        {
3161            let mut catalog = Catalog::open_debug_catalog(
3162                persist_client.clone(),
3163                organization_id.clone(),
3164                &bootstrap_args,
3165            )
3166            .await
3167            .expect("unable to open debug catalog");
3168            let item = catalog
3169                .state()
3170                .deserialize_item(
3171                    gid,
3172                    &create_sql,
3173                    &BTreeMap::new(),
3174                    &mut LocalExpressionCache::Closed,
3175                    None,
3176                )
3177                .expect("unable to parse view");
3178            let commit_ts = catalog.current_upper().await;
3179            catalog
3180                .transact(
3181                    None,
3182                    commit_ts,
3183                    None,
3184                    vec![Op::CreateItem {
3185                        item,
3186                        name: QualifiedItemName {
3187                            qualifiers: ItemQualifiers {
3188                                database_spec: ResolvedDatabaseSpecifier::Id(DatabaseId::User(1)),
3189                                schema_spec: SchemaSpecifier::Id(SchemaId::User(3)),
3190                            },
3191                            item: "v".to_string(),
3192                        },
3193                        id,
3194                        owner_id: MZ_SYSTEM_ROLE_ID,
3195                    }],
3196                )
3197                .await
3198                .expect("failed to transact");
3199            catalog.expire().await;
3200        }
3201        {
3202            let catalog =
3203                Catalog::open_debug_catalog(persist_client, organization_id, &bootstrap_args)
3204                    .await
3205                    .expect("unable to open debug catalog");
3206            let view = catalog.get_entry(&id);
3207            assert_eq!("v", view.name.item);
3208            match &view.item {
3209                CatalogItem::View(view) => assert_eq!(create_sql_check, view.create_sql),
3210                item => panic!("expected view, got {}", item.typ()),
3211            }
3212            catalog.expire().await;
3213        }
3214    }
3215
3216    #[mz_ore::test(tokio::test)]
3217    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
3218    async fn test_object_type() {
3219        Catalog::with_debug(|catalog| async move {
3220            let conn_catalog = catalog.for_system_session();
3221
3222            assert_eq!(
3223                mz_sql::catalog::ObjectType::ClusterReplica,
3224                conn_catalog.get_object_type(&ObjectId::ClusterReplica((
3225                    ClusterId::user(1).expect("1 is a valid ID"),
3226                    ReplicaId::User(1)
3227                )))
3228            );
3229            assert_eq!(
3230                mz_sql::catalog::ObjectType::Role,
3231                conn_catalog.get_object_type(&ObjectId::Role(RoleId::User(1)))
3232            );
3233            catalog.expire().await;
3234        })
3235        .await;
3236    }
3237
3238    #[mz_ore::test(tokio::test)]
3239    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
3240    async fn test_get_privileges() {
3241        Catalog::with_debug(|catalog| async move {
3242            let conn_catalog = catalog.for_system_session();
3243
3244            assert_eq!(
3245                None,
3246                conn_catalog.get_privileges(&SystemObjectId::Object(ObjectId::ClusterReplica((
3247                    ClusterId::user(1).expect("1 is a valid ID"),
3248                    ReplicaId::User(1),
3249                ))))
3250            );
3251            assert_eq!(
3252                None,
3253                conn_catalog
3254                    .get_privileges(&SystemObjectId::Object(ObjectId::Role(RoleId::User(1))))
3255            );
3256            catalog.expire().await;
3257        })
3258        .await;
3259    }
3260
3261    #[mz_ore::test(tokio::test)]
3262    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
3263    async fn verify_builtin_descs() {
3264        // Provide a full AWS context so the builtin AWS connection views resolve
3265        // as they do in a cloud environment. Without an account id,
3266        // `mz_aws_privatelink_connections.principal` folds to NULL, its
3267        // `WHERE principal IS NOT NULL` filter is statically unsatisfiable, and
3268        // the optimizer infers an extra empty key that the declared desc, which
3269        // describes the cloud shape, does not carry.
3270        let aws_context = DebugAwsContext {
3271            aws_account_id: Some("123456789000".to_string()),
3272            aws_external_id_prefix: Some("eb5cb59b-e2fe-41f3-87ca-d2176a495345".to_string()),
3273            aws_connection_role_arn: Some(
3274                "arn:aws:iam::123456789000:role/MaterializeConnection".to_string(),
3275            ),
3276        };
3277        Catalog::with_debug_aws_context(aws_context, |catalog| async move {
3278            let conn_catalog = catalog.for_system_session();
3279
3280            for builtin in BUILTINS::iter() {
3281                let (schema, name, expected_desc, shard_backed) = match builtin {
3282                    Builtin::Table(t) => (&t.schema, &t.name, &t.desc, true),
3283                    Builtin::View(v) => (&v.schema, &v.name, &v.desc, false),
3284                    Builtin::MaterializedView(mv) => (&mv.schema, &mv.name, &mv.desc, true),
3285                    Builtin::Source(s) => (&s.schema, &s.name, &s.desc, true),
3286                    Builtin::Log(_)
3287                    | Builtin::Type(_)
3288                    | Builtin::Func(_)
3289                    | Builtin::Index(_)
3290                    | Builtin::Connection(_) => continue,
3291                };
3292                // A shard-backed builtin registers `desc` as its persist shard's
3293                // schema, so a type change in `desc` needs a `MigrationStep`. Tables
3294                // and sources carry `desc` into the catalog verbatim and cannot fail
3295                // here. A materialized view is planned, and its fingerprint is its
3296                // SQL, so nothing else detects a `desc` change at upgrade. See the
3297                // `Fingerprint` impl for `BuiltinMaterializedView`.
3298                let migration_hint = if shard_backed {
3299                    format!(
3300                        "; {schema}.{name} is backed by a persist shard, so after updating its \
3301                         `desc` also add a `MigrationStep` for it to `MIGRATIONS` in \
3302                         `src/adapter/src/catalog/open/builtin_schema_migration.rs`"
3303                    )
3304                } else {
3305                    String::new()
3306                };
3307                let item = conn_catalog
3308                    .resolve_item(&PartialItemName {
3309                        database: None,
3310                        schema: Some(schema.to_string()),
3311                        item: name.to_string(),
3312                    })
3313                    .expect("unable to resolve item")
3314                    .at_version(RelationVersionSelector::Latest);
3315
3316                let actual_desc = item.relation_desc().expect("invalid item type");
3317                assert_eq!(
3318                    actual_desc.arity(),
3319                    expected_desc.arity(),
3320                    "item {schema}.{name} column count did not match its expected column count{migration_hint}"
3321                );
3322                for (index, ((actual_name, actual_typ), (expected_name, expected_typ))) in
3323                    actual_desc.iter().zip_eq(expected_desc.iter()).enumerate()
3324                {
3325                    assert_eq!(
3326                        actual_name, expected_name,
3327                        "item {schema}.{name} column {index} name did not match its expected name{migration_hint}"
3328                    );
3329                    assert_eq!(
3330                        actual_typ, expected_typ,
3331                        "item {schema}.{name} column {index} ('{actual_name}') type did not match its expected type{migration_hint}"
3332                    );
3333                }
3334                // Keys never reach the shard schema, so a key mismatch needs no
3335                // migration, only a corrected `desc`.
3336                assert_eq!(
3337                    actual_desc.typ().keys,
3338                    expected_desc.typ().keys,
3339                    "item {schema}.{name} keys did not match its expected keys"
3340                );
3341                assert_eq!(
3342                    &*actual_desc, expected_desc,
3343                    "item {schema}.{name} did not match its expected RelationDesc"
3344                );
3345            }
3346            catalog.expire().await;
3347        })
3348        .await
3349    }
3350
3351    // Connect to a running Postgres server and verify that our builtin
3352    // types and functions match it, in addition to some other things.
3353    #[mz_ore::test(tokio::test)]
3354    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
3355    async fn test_compare_builtins_postgres() {
3356        async fn inner(catalog: Catalog) {
3357            // Verify that all builtin functions:
3358            // - have a unique OID
3359            // - if they have a postgres counterpart (same oid) then they have matching name
3360            let (client, connection) = tokio_postgres::connect(
3361                &env::var("POSTGRES_URL").unwrap_or_else(|_| "host=localhost user=postgres".into()),
3362                NoTls,
3363            )
3364            .await
3365            .expect("failed to connect to Postgres");
3366
3367            task::spawn(|| "compare_builtin_postgres", async move {
3368                if let Err(e) = connection.await {
3369                    panic!("connection error: {}", e);
3370                }
3371            });
3372
3373            struct PgProc {
3374                name: String,
3375                arg_oids: Vec<u32>,
3376                ret_oid: Option<u32>,
3377                ret_set: bool,
3378            }
3379
3380            struct PgType {
3381                name: String,
3382                ty: String,
3383                elem: u32,
3384                array: u32,
3385                input: u32,
3386                receive: u32,
3387                send: u32,
3388                len: i16,
3389            }
3390
3391            struct PgOper {
3392                oprresult: u32,
3393                name: String,
3394            }
3395
3396            let pg_proc: BTreeMap<_, _> = query(
3397                &client,
3398                sql!(
3399                    "SELECT
3400                    p.oid,
3401                    proname,
3402                    proargtypes,
3403                    prorettype,
3404                    proretset
3405                FROM pg_proc p
3406                JOIN pg_namespace n ON p.pronamespace = n.oid"
3407                ),
3408                &[],
3409            )
3410            .await
3411            .expect("pg query failed")
3412            .into_iter()
3413            .map(|row| {
3414                let oid: u32 = row.get("oid");
3415                let pg_proc = PgProc {
3416                    name: row.get("proname"),
3417                    arg_oids: row.get("proargtypes"),
3418                    ret_oid: row.get("prorettype"),
3419                    ret_set: row.get("proretset"),
3420                };
3421                (oid, pg_proc)
3422            })
3423            .collect();
3424
3425            let pg_type: BTreeMap<_, _> = query(
3426                &client,
3427                sql!(
3428                    "SELECT oid, typname, typtype::text, typelem, typarray, typinput::oid, typreceive::oid as typreceive, typsend::oid as typsend, typlen FROM pg_type"
3429                ),
3430                &[],
3431            )
3432            .await
3433                .expect("pg query failed")
3434                .into_iter()
3435                .map(|row| {
3436                    let oid: u32 = row.get("oid");
3437                    let pg_type = PgType {
3438                        name: row.get("typname"),
3439                        ty: row.get("typtype"),
3440                        elem: row.get("typelem"),
3441                        array: row.get("typarray"),
3442                        input: row.get("typinput"),
3443                        receive: row.get("typreceive"),
3444                        send: row.get("typsend"),
3445                        len: row.get("typlen"),
3446                    };
3447                    (oid, pg_type)
3448                })
3449                .collect();
3450
3451            let pg_oper: BTreeMap<_, _> = query(
3452                &client,
3453                sql!("SELECT oid, oprname, oprresult FROM pg_operator"),
3454                &[],
3455            )
3456            .await
3457            .expect("pg query failed")
3458            .into_iter()
3459            .map(|row| {
3460                let oid: u32 = row.get("oid");
3461                let pg_oper = PgOper {
3462                    name: row.get("oprname"),
3463                    oprresult: row.get("oprresult"),
3464                };
3465                (oid, pg_oper)
3466            })
3467            .collect();
3468
3469            let conn_catalog = catalog.for_system_session();
3470            let resolve_type_oid = |item: &str| {
3471                conn_catalog
3472                    .resolve_type(&PartialItemName {
3473                        database: None,
3474                        // All functions we check exist in PG, so the types must, as
3475                        // well
3476                        schema: Some(PG_CATALOG_SCHEMA.into()),
3477                        item: item.to_string(),
3478                    })
3479                    .expect("unable to resolve type")
3480                    .oid()
3481            };
3482
3483            let func_oids: BTreeSet<_> = BUILTINS::funcs()
3484                .flat_map(|f| f.inner.func_impls().into_iter().map(|f| f.oid))
3485                .collect();
3486
3487            let mut all_oids = BTreeSet::new();
3488
3489            // A function to determine if two oids are equivalent enough for these tests. We don't
3490            // support some types, so map exceptions here.
3491            let equivalent_types: BTreeSet<(Option<u32>, Option<u32>)> = BTreeSet::from_iter(
3492                [
3493                    // We don't support NAME.
3494                    (Type::NAME, Type::TEXT),
3495                    (Type::NAME_ARRAY, Type::TEXT_ARRAY),
3496                    // We don't support time with time zone.
3497                    (Type::TIME, Type::TIMETZ),
3498                    (Type::TIME_ARRAY, Type::TIMETZ_ARRAY),
3499                ]
3500                .map(|(a, b)| (Some(a.oid()), Some(b.oid()))),
3501            );
3502            let ignore_return_types: BTreeSet<u32> = BTreeSet::from([
3503                1619, // pg_typeof: TODO: We now have regtype and can correctly implement this.
3504            ]);
3505            let is_same_type = |fn_oid: u32, a: Option<u32>, b: Option<u32>| -> bool {
3506                if ignore_return_types.contains(&fn_oid) {
3507                    return true;
3508                }
3509                if equivalent_types.contains(&(a, b)) || equivalent_types.contains(&(b, a)) {
3510                    return true;
3511                }
3512                a == b
3513            };
3514
3515            for builtin in BUILTINS::iter() {
3516                match builtin {
3517                    Builtin::Type(ty) => {
3518                        assert!(all_oids.insert(ty.oid), "{} reused oid {}", ty.name, ty.oid);
3519
3520                        if ty.oid >= FIRST_MATERIALIZE_OID {
3521                            // High OIDs are reserved in Materialize and don't have
3522                            // PostgreSQL counterparts.
3523                            continue;
3524                        }
3525
3526                        // For types that have a PostgreSQL counterpart, verify that
3527                        // the name and oid match.
3528                        let pg_ty = pg_type.get(&ty.oid).unwrap_or_else(|| {
3529                            panic!("pg_proc missing type {}: oid {}", ty.name, ty.oid)
3530                        });
3531                        assert_eq!(
3532                            ty.name, pg_ty.name,
3533                            "oid {} has name {} in postgres; expected {}",
3534                            ty.oid, pg_ty.name, ty.name,
3535                        );
3536
3537                        let (typinput_oid, typreceive_oid, typsend_oid) =
3538                            match &ty.details.pg_metadata {
3539                                None => (0, 0, 0),
3540                                Some(pgmeta) => (
3541                                    pgmeta.typinput_oid,
3542                                    pgmeta.typreceive_oid,
3543                                    pgmeta.typsend_oid,
3544                                ),
3545                            };
3546                        assert_eq!(
3547                            typinput_oid, pg_ty.input,
3548                            "type {} has typinput OID {:?} in mz but {:?} in pg",
3549                            ty.name, typinput_oid, pg_ty.input,
3550                        );
3551                        assert_eq!(
3552                            typreceive_oid, pg_ty.receive,
3553                            "type {} has typreceive OID {:?} in mz but {:?} in pg",
3554                            ty.name, typreceive_oid, pg_ty.receive,
3555                        );
3556                        // Unlike typinput and typreceive below, typsend is not also
3557                        // checked against `func_oids`. Nothing resolves a typsend OID
3558                        // to a name, so the corresponding `*send` functions are
3559                        // deliberately not registered as builtins.
3560                        assert_eq!(
3561                            typsend_oid, pg_ty.send,
3562                            "type {} has typsend OID {:?} in mz but {:?} in pg",
3563                            ty.name, typsend_oid, pg_ty.send,
3564                        );
3565                        if typinput_oid != 0 {
3566                            assert!(
3567                                func_oids.contains(&typinput_oid),
3568                                "type {} has typinput OID {} that does not exist in pg_proc",
3569                                ty.name,
3570                                typinput_oid,
3571                            );
3572                        }
3573                        if typreceive_oid != 0 {
3574                            assert!(
3575                                func_oids.contains(&typreceive_oid),
3576                                "type {} has typreceive OID {} that does not exist in pg_proc",
3577                                ty.name,
3578                                typreceive_oid,
3579                            );
3580                        }
3581                        let id = conn_catalog
3582                            .resolve_type(&PartialItemName {
3583                                database: None,
3584                                schema: Some(ty.schema.into()),
3585                                item: ty.name.to_string(),
3586                            })
3587                            .expect("unable to resolve type")
3588                            .id();
3589                        // Types with no scalar type report an unknown typlen.
3590                        if let Ok(scalar_type) =
3591                            mz_sql::plan::scalar_type_from_catalog(&conn_catalog, id, &[])
3592                        {
3593                            let typlen = mz_pgrepr::Type::from(&scalar_type).typlen();
3594                            assert_eq!(
3595                                typlen, pg_ty.len,
3596                                "type {} has typlen {} in mz but {} in pg",
3597                                ty.name, typlen, pg_ty.len,
3598                            );
3599                        }
3600
3601                        // Ensure the type matches.
3602                        match &ty.details.typ {
3603                            CatalogType::Array { element_reference } => {
3604                                let elem_ty = BUILTINS::iter()
3605                                    .filter_map(|builtin| match builtin {
3606                                        Builtin::Type(ty @ BuiltinType { name, .. })
3607                                            if element_reference == name =>
3608                                        {
3609                                            Some(ty)
3610                                        }
3611                                        _ => None,
3612                                    })
3613                                    .next();
3614                                let elem_ty = match elem_ty {
3615                                    Some(ty) => ty,
3616                                    None => {
3617                                        panic!("{} is unexpectedly not a type", element_reference)
3618                                    }
3619                                };
3620                                assert_eq!(
3621                                    pg_ty.elem, elem_ty.oid,
3622                                    "type {} has mismatched element OIDs",
3623                                    ty.name
3624                                )
3625                            }
3626                            CatalogType::Pseudo => {
3627                                assert_eq!(
3628                                    pg_ty.ty, "p",
3629                                    "type {} is not a pseudo type as expected",
3630                                    ty.name
3631                                )
3632                            }
3633                            CatalogType::Range { .. } => {
3634                                assert_eq!(
3635                                    pg_ty.ty, "r",
3636                                    "type {} is not a range type as expected",
3637                                    ty.name
3638                                );
3639                            }
3640                            _ => {
3641                                assert_eq!(
3642                                    pg_ty.ty, "b",
3643                                    "type {} is not a base type as expected",
3644                                    ty.name
3645                                )
3646                            }
3647                        }
3648
3649                        // Ensure the array type reference is correct.
3650                        let schema = catalog
3651                            .resolve_schema_in_database(
3652                                &ResolvedDatabaseSpecifier::Ambient,
3653                                ty.schema,
3654                                &SYSTEM_CONN_ID,
3655                            )
3656                            .expect("unable to resolve schema");
3657                        let allocated_type = catalog
3658                            .resolve_type(
3659                                None,
3660                                &vec![(ResolvedDatabaseSpecifier::Ambient, schema.id().clone())],
3661                                &PartialItemName {
3662                                    database: None,
3663                                    schema: Some(schema.name().schema.clone()),
3664                                    item: ty.name.to_string(),
3665                                },
3666                                &SYSTEM_CONN_ID,
3667                            )
3668                            .expect("unable to resolve type");
3669                        let ty = if let CatalogItem::Type(ty) = &allocated_type.item {
3670                            ty
3671                        } else {
3672                            panic!("unexpectedly not a type")
3673                        };
3674                        match ty.details.array_id {
3675                            Some(array_id) => {
3676                                let array_ty = catalog.get_entry(&array_id);
3677                                assert_eq!(
3678                                    pg_ty.array, array_ty.oid,
3679                                    "type {} has mismatched array OIDs",
3680                                    allocated_type.name.item,
3681                                );
3682                            }
3683                            None => assert_eq!(
3684                                pg_ty.array, 0,
3685                                "type {} does not have an array type in mz but does in pg",
3686                                allocated_type.name.item,
3687                            ),
3688                        }
3689                    }
3690                    Builtin::Func(func) => {
3691                        for imp in func.inner.func_impls() {
3692                            assert!(
3693                                all_oids.insert(imp.oid),
3694                                "{} reused oid {}",
3695                                func.name,
3696                                imp.oid
3697                            );
3698
3699                            assert!(
3700                                imp.oid < FIRST_USER_OID,
3701                                "built-in function {} erroneously has OID in user space ({})",
3702                                func.name,
3703                                imp.oid,
3704                            );
3705
3706                            // For functions that have a postgres counterpart, verify that the name and
3707                            // oid match.
3708                            let pg_fn = if imp.oid >= FIRST_UNPINNED_OID {
3709                                continue;
3710                            } else {
3711                                pg_proc.get(&imp.oid).unwrap_or_else(|| {
3712                                    panic!(
3713                                        "pg_proc missing function {}: oid {}",
3714                                        func.name, imp.oid
3715                                    )
3716                                })
3717                            };
3718                            assert_eq!(
3719                                func.name, pg_fn.name,
3720                                "funcs with oid {} don't match names: {} in mz, {} in pg",
3721                                imp.oid, func.name, pg_fn.name
3722                            );
3723
3724                            // Complain, but don't fail, if argument oids don't match.
3725                            // TODO: make these match.
3726                            let imp_arg_oids = imp
3727                                .arg_typs
3728                                .iter()
3729                                .map(|item| resolve_type_oid(item))
3730                                .collect::<Vec<_>>();
3731
3732                            if imp_arg_oids != pg_fn.arg_oids {
3733                                println!(
3734                                    "funcs with oid {} ({}) don't match arguments: {:?} in mz, {:?} in pg",
3735                                    imp.oid, func.name, imp_arg_oids, pg_fn.arg_oids
3736                                );
3737                            }
3738
3739                            let imp_return_oid = imp.return_typ.map(resolve_type_oid);
3740
3741                            assert!(
3742                                is_same_type(imp.oid, imp_return_oid, pg_fn.ret_oid),
3743                                "funcs with oid {} ({}) don't match return types: {:?} in mz, {:?} in pg",
3744                                imp.oid,
3745                                func.name,
3746                                imp_return_oid,
3747                                pg_fn.ret_oid
3748                            );
3749
3750                            assert_eq!(
3751                                imp.return_is_set, pg_fn.ret_set,
3752                                "funcs with oid {} ({}) don't match set-returning value: {:?} in mz, {:?} in pg",
3753                                imp.oid, func.name, imp.return_is_set, pg_fn.ret_set
3754                            );
3755                        }
3756                    }
3757                    _ => (),
3758                }
3759            }
3760
3761            for (op, func) in OP_IMPLS.iter() {
3762                for imp in func.func_impls() {
3763                    assert!(all_oids.insert(imp.oid), "{} reused oid {}", op, imp.oid);
3764
3765                    // For operators that have a postgres counterpart, verify that the name and oid match.
3766                    let pg_op = if imp.oid >= FIRST_UNPINNED_OID {
3767                        continue;
3768                    } else {
3769                        pg_oper.get(&imp.oid).unwrap_or_else(|| {
3770                            panic!("pg_operator missing operator {}: oid {}", op, imp.oid)
3771                        })
3772                    };
3773
3774                    assert_eq!(*op, pg_op.name);
3775
3776                    let imp_return_oid =
3777                        imp.return_typ.map(resolve_type_oid).expect("must have oid");
3778                    if imp_return_oid != pg_op.oprresult {
3779                        panic!(
3780                            "operators with oid {} ({}) don't match return typs: {} in mz, {} in pg",
3781                            imp.oid, op, imp_return_oid, pg_op.oprresult
3782                        );
3783                    }
3784                }
3785            }
3786            catalog.expire().await;
3787        }
3788
3789        Catalog::with_debug(inner).await
3790    }
3791
3792    // Execute all builtin functions with all combinations of arguments from interesting datums.
3793    #[mz_ore::test(tokio::test)]
3794    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
3795    async fn test_smoketest_all_builtins() {
3796        fn inner(catalog: Catalog) -> Vec<mz_ore::task::JoinHandle<()>> {
3797            let catalog = Arc::new(catalog);
3798            let conn_catalog = catalog.for_system_session();
3799
3800            let resolve_type_oid = |item: &str| conn_catalog.state().get_system_type(item).oid();
3801            let mut handles = Vec::new();
3802
3803            // Extracted during planning; always panics when executed.
3804            let ignore_names = BTreeSet::from([
3805                "avg",
3806                "avg_internal_v1",
3807                "bool_and",
3808                "bool_or",
3809                "has_table_privilege", // > 3 s each
3810                "has_type_privilege",  // > 3 s each
3811                "mod",
3812                "mz_panic",
3813                "mz_sleep",
3814                "pow",
3815                "stddev_pop",
3816                "stddev_samp",
3817                "stddev",
3818                "var_pop",
3819                "var_samp",
3820                "variance",
3821            ]);
3822
3823            let fns = BUILTINS::funcs()
3824                .map(|func| (&func.name, func.inner))
3825                .chain(OP_IMPLS.iter());
3826
3827            for (name, func) in fns {
3828                if ignore_names.contains(name) {
3829                    continue;
3830                }
3831                let Func::Scalar(impls) = func else {
3832                    continue;
3833                };
3834
3835                'outer: for imp in impls {
3836                    let details = imp.details();
3837                    let mut styps = Vec::new();
3838                    for item in details.arg_typs.iter() {
3839                        let oid = resolve_type_oid(item);
3840                        let Ok(pgtyp) = mz_pgrepr::Type::from_oid(oid) else {
3841                            continue 'outer;
3842                        };
3843                        styps.push(SqlScalarType::try_from(&pgtyp).expect("must exist"));
3844                    }
3845                    let datums = styps
3846                        .iter()
3847                        .map(|styp| {
3848                            let mut datums = vec![Datum::Null];
3849                            datums.extend(styp.interesting_datums());
3850                            datums
3851                        })
3852                        .collect::<Vec<_>>();
3853                    // Skip nullary fns.
3854                    if datums.is_empty() {
3855                        continue;
3856                    }
3857
3858                    let return_oid = details
3859                        .return_typ
3860                        .map(resolve_type_oid)
3861                        .expect("must exist");
3862                    let return_styp = mz_pgrepr::Type::from_oid(return_oid)
3863                        .ok()
3864                        .map(|typ| SqlScalarType::try_from(&typ).expect("must exist"));
3865
3866                    let mut idxs = vec![0; datums.len()];
3867                    while idxs[0] < datums[0].len() {
3868                        let mut args = Vec::with_capacity(idxs.len());
3869                        for i in 0..(datums.len()) {
3870                            args.push(datums[i][idxs[i]]);
3871                        }
3872
3873                        let op = &imp.op;
3874                        let scalars = args
3875                            .iter()
3876                            .enumerate()
3877                            .map(|(i, datum)| {
3878                                CoercibleScalarExpr::Coerced(HirScalarExpr::literal(
3879                                    datum.clone(),
3880                                    styps[i].clone(),
3881                                ))
3882                            })
3883                            .collect();
3884
3885                        let call_name = format!(
3886                            "{name}({}) (oid: {})",
3887                            args.iter()
3888                                .map(|d| d.to_string())
3889                                .collect::<Vec<_>>()
3890                                .join(", "),
3891                            imp.oid
3892                        );
3893                        let catalog = Arc::clone(&catalog);
3894                        let call_name_fn = call_name.clone();
3895                        let return_styp = return_styp.clone();
3896                        let handle = task::spawn_blocking(
3897                            || call_name,
3898                            move || {
3899                                smoketest_fn(
3900                                    name,
3901                                    call_name_fn,
3902                                    op,
3903                                    imp,
3904                                    args,
3905                                    catalog,
3906                                    scalars,
3907                                    return_styp,
3908                                )
3909                            },
3910                        );
3911                        handles.push(handle);
3912
3913                        // Advance to the next datum combination.
3914                        for i in (0..datums.len()).rev() {
3915                            idxs[i] += 1;
3916                            if idxs[i] >= datums[i].len() {
3917                                if i == 0 {
3918                                    break;
3919                                }
3920                                idxs[i] = 0;
3921                                continue;
3922                            } else {
3923                                break;
3924                            }
3925                        }
3926                    }
3927                }
3928            }
3929            handles
3930        }
3931
3932        let handles = Catalog::with_debug(|catalog| async { inner(catalog) }).await;
3933        for handle in handles {
3934            handle.await;
3935        }
3936    }
3937
3938    fn smoketest_fn(
3939        name: &&str,
3940        call_name: String,
3941        op: &Operation<HirScalarExpr>,
3942        imp: &FuncImpl<HirScalarExpr>,
3943        args: Vec<Datum<'_>>,
3944        catalog: Arc<Catalog>,
3945        scalars: Vec<CoercibleScalarExpr>,
3946        return_styp: Option<SqlScalarType>,
3947    ) {
3948        let conn_catalog = catalog.for_system_session();
3949        let pcx = PlanContext::zero();
3950        let scx = StatementContext::new(Some(&pcx), &conn_catalog);
3951        let qcx = QueryContext::root(&scx, QueryLifetime::OneShot);
3952        let ecx = ExprContext {
3953            qcx: &qcx,
3954            name: "smoketest",
3955            scope: &Scope::empty(),
3956            relation_type: &SqlRelationType::empty(),
3957            allow_aggregates: false,
3958            allow_subqueries: false,
3959            allow_parameters: false,
3960            allow_windows: false,
3961        };
3962        let arena = RowArena::new();
3963        let mut session = Session::dummy();
3964        session
3965            .start_transaction(to_datetime(0), None, None)
3966            .expect("must succeed");
3967        let prep_style = ExprPrepOneShot {
3968            logical_time: EvalTime::Time(Timestamp::MIN),
3969            session: &session,
3970            catalog_state: &catalog.state,
3971        };
3972
3973        // Execute the function as much as possible, ensuring no panics occur, but
3974        // otherwise ignoring eval errors. We also do various other checks.
3975        let res = (op.0)(&ecx, scalars, &imp.params, vec![]);
3976        if let Ok(hir) = res {
3977            let uneliminated_result_row = {
3978                if let HirScalarExpr::CallUnary { func, .. } = &hir
3979                    && func.is_eliminable_cast()
3980                {
3981                    let mut uneliminated_mir = hir
3982                        .clone()
3983                        .lower_uncorrelated(HirToMirConfig {
3984                            enable_cast_elimination: false,
3985                            ..catalog.system_config().into()
3986                        })
3987                        .expect("lowering eliminable cast should always succeed");
3988                    prep_style
3989                        .prep_scalar_expr(&mut uneliminated_mir)
3990                        .expect("must succeed");
3991
3992                    // Pack the row, to avoid lifetime issues with the MIR we lowered here
3993                    uneliminated_mir
3994                        .eval(&[], &arena)
3995                        .ok()
3996                        .map(|datum| Row::pack([datum]))
3997                } else {
3998                    None
3999                }
4000            };
4001
4002            if let Ok(mut mir) = hir.lower_uncorrelated(catalog.system_config()) {
4003                // Populate unmaterialized functions.
4004                prep_style.prep_scalar_expr(&mut mir).expect("must succeed");
4005
4006                if let Ok(eval_result_datum) = mir.eval(&[], &arena) {
4007                    if let Some(return_styp) = return_styp {
4008                        let mir_typ = mir.typ(&[]);
4009                        // MIR type inference should be consistent with the type
4010                        // we get from the catalog.
4011                        soft_assert_eq_or_log!(
4012                            mir_typ.scalar_type,
4013                            (&return_styp).into(),
4014                            "MIR type did not match the catalog type (cast elimination/repr type error)"
4015                        );
4016                        // The following will check not just that the scalar type
4017                        // is ok, but also catches if the function returned a null
4018                        // but the MIR type inference said "non-nullable".
4019                        if !eval_result_datum.is_instance_of(&mir_typ) {
4020                            panic!(
4021                                "{call_name}: expected return type of {return_styp:?}, got {eval_result_datum}"
4022                            );
4023                        }
4024                        // Check the consistency of `is_eliminable_cast`---we should get the same datum either way.
4025                        if let Some(row) = uneliminated_result_row {
4026                            let uneliminated_result_datum = row.unpack_first();
4027                            assert_eq!(
4028                                uneliminated_result_datum, eval_result_datum,
4029                                "datums should not change if cast is eliminable"
4030                            );
4031                        }
4032                        // Check the consistency of `introduces_nulls` and
4033                        // `propagates_nulls` with `MirScalarExpr::typ`.
4034                        if let Some((introduces_nulls, propagates_nulls)) =
4035                            call_introduces_propagates_nulls(&mir)
4036                        {
4037                            if introduces_nulls {
4038                                // If the function introduces_nulls, then the return
4039                                // type should always be nullable, regardless of
4040                                // the nullability of the input types.
4041                                assert!(
4042                                    mir_typ.nullable,
4043                                    "fn named `{}` called on args `{:?}` (lowered to `{}`) yielded mir_typ.nullable: {}",
4044                                    name, args, mir, mir_typ.nullable
4045                                );
4046                            } else {
4047                                let any_input_null = args.iter().any(|arg| arg.is_null());
4048                                if !any_input_null {
4049                                    assert!(
4050                                        !mir_typ.nullable,
4051                                        "fn named `{}` called on args `{:?}` (lowered to `{}`) yielded mir_typ.nullable: {}",
4052                                        name, args, mir, mir_typ.nullable
4053                                    );
4054                                } else if propagates_nulls {
4055                                    // propagates_nulls means the optimizer short-circuits
4056                                    // all-null inputs, so the output must be nullable.
4057                                    assert!(
4058                                        mir_typ.nullable,
4059                                        "fn named `{}` called on args `{:?}` (lowered to `{}`) yielded mir_typ.nullable: {}",
4060                                        name, args, mir, mir_typ.nullable
4061                                    );
4062                                }
4063                                // When propagates_nulls is false, the output may still
4064                                // be nullable if a non-nullable parameter received a null
4065                                // input (per-position null rejection). The is_instance_of
4066                                // check above ensures type consistency.
4067                            }
4068                        }
4069                        // Check that `MirScalarExpr::reduce` yields the same result
4070                        // as the real evaluation.
4071                        let mut reduced = mir.clone();
4072                        reduced.reduce(&[]);
4073                        match reduced {
4074                            MirScalarExpr::Literal(reduce_result, ctyp) => {
4075                                match reduce_result {
4076                                    Ok(reduce_result_row) => {
4077                                        let reduce_result_datum = reduce_result_row.unpack_first();
4078                                        assert_eq!(
4079                                            reduce_result_datum,
4080                                            eval_result_datum,
4081                                            "eval/reduce datum mismatch: fn named `{}` called on args `{:?}` (lowered to `{}`) evaluated to `{}` with typ `{:?}`, but reduced to `{}` with typ `{:?}`",
4082                                            name,
4083                                            args,
4084                                            mir,
4085                                            eval_result_datum,
4086                                            mir_typ.scalar_type,
4087                                            reduce_result_datum,
4088                                            ctyp.scalar_type
4089                                        );
4090                                        // Let's check that the types also match.
4091                                        // (We are not checking nullability here,
4092                                        // because it's ok when we know a more
4093                                        // precise nullability after actually
4094                                        // evaluating a function than before.)
4095                                        assert_eq!(
4096                                            ctyp.scalar_type,
4097                                            mir_typ.scalar_type,
4098                                            "eval/reduce type mismatch: fn named `{}` called on args `{:?}` (lowered to `{}`) evaluated to `{}` with typ `{:?}`, but reduced to `{}` with typ `{:?}`",
4099                                            name,
4100                                            args,
4101                                            mir,
4102                                            eval_result_datum,
4103                                            mir_typ.scalar_type,
4104                                            reduce_result_datum,
4105                                            ctyp.scalar_type
4106                                        );
4107                                    }
4108                                    Err(..) => {} // It's ok, we might have given invalid args to the function
4109                                }
4110                            }
4111                            // Constant folding never evaluates an unbounded call.
4112                            _ if mir.contains_unbounded() => {}
4113                            _ => unreachable!(
4114                                "all args are literals, so should have reduced to a literal"
4115                            ),
4116                        }
4117                    }
4118                }
4119            }
4120        }
4121    }
4122
4123    /// If the given MirScalarExpr
4124    ///  - is a function call, and
4125    ///  - all arguments are literals
4126    /// then it returns whether the called function (introduces_nulls, propagates_nulls).
4127    fn call_introduces_propagates_nulls(mir_func_call: &MirScalarExpr) -> Option<(bool, bool)> {
4128        match mir_func_call {
4129            MirScalarExpr::CallUnary { func, expr } => {
4130                if expr.is_literal() {
4131                    Some((func.introduces_nulls(), func.propagates_nulls()))
4132                } else {
4133                    None
4134                }
4135            }
4136            MirScalarExpr::CallBinary { func, expr1, expr2 } => {
4137                if expr1.is_literal() && expr2.is_literal() {
4138                    Some((func.introduces_nulls(), func.propagates_nulls()))
4139                } else {
4140                    None
4141                }
4142            }
4143            MirScalarExpr::CallVariadic { func, exprs } => {
4144                if exprs.iter().all(|arg| arg.is_literal()) {
4145                    Some((func.introduces_nulls(), func.propagates_nulls()))
4146                } else {
4147                    None
4148                }
4149            }
4150            _ => None,
4151        }
4152    }
4153
4154    // Make sure pg views don't use types that only exist in Materialize.
4155    #[mz_ore::test(tokio::test)]
4156    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
4157    async fn test_pg_views_forbidden_types() {
4158        Catalog::with_debug(|catalog| async move {
4159            let conn_catalog = catalog.for_system_session();
4160
4161            for view in BUILTINS::views().filter(|view| {
4162                view.schema == PG_CATALOG_SCHEMA || view.schema == INFORMATION_SCHEMA
4163            }) {
4164                let item = conn_catalog
4165                    .resolve_item(&PartialItemName {
4166                        database: None,
4167                        schema: Some(view.schema.to_string()),
4168                        item: view.name.to_string(),
4169                    })
4170                    .expect("unable to resolve view")
4171                    // TODO(alter_table)
4172                    .at_version(RelationVersionSelector::Latest);
4173                let full_name = conn_catalog.resolve_full_name(item.name());
4174                let desc = item.relation_desc().expect("invalid item type");
4175                for col_type in desc.iter_types() {
4176                    match &col_type.scalar_type {
4177                        typ @ SqlScalarType::UInt16
4178                        | typ @ SqlScalarType::UInt32
4179                        | typ @ SqlScalarType::UInt64
4180                        | typ @ SqlScalarType::MzTimestamp
4181                        | typ @ SqlScalarType::List { .. }
4182                        | typ @ SqlScalarType::Map { .. }
4183                        | typ @ SqlScalarType::MzAclItem => {
4184                            panic!("{typ:?} type found in {full_name}");
4185                        }
4186                        SqlScalarType::AclItem
4187                        | SqlScalarType::Bool
4188                        | SqlScalarType::Int16
4189                        | SqlScalarType::Int32
4190                        | SqlScalarType::Int64
4191                        | SqlScalarType::Float32
4192                        | SqlScalarType::Float64
4193                        | SqlScalarType::Numeric { .. }
4194                        | SqlScalarType::Date
4195                        | SqlScalarType::Time
4196                        | SqlScalarType::Timestamp { .. }
4197                        | SqlScalarType::TimestampTz { .. }
4198                        | SqlScalarType::Interval
4199                        | SqlScalarType::PgLegacyChar
4200                        | SqlScalarType::Bytes
4201                        | SqlScalarType::String
4202                        | SqlScalarType::Char { .. }
4203                        | SqlScalarType::VarChar { .. }
4204                        | SqlScalarType::Jsonb
4205                        | SqlScalarType::Uuid
4206                        | SqlScalarType::Array(_)
4207                        | SqlScalarType::Record { .. }
4208                        | SqlScalarType::Oid
4209                        | SqlScalarType::RegProc
4210                        | SqlScalarType::RegType
4211                        | SqlScalarType::RegClass
4212                        | SqlScalarType::Int2Vector
4213                        | SqlScalarType::Range { .. }
4214                        | SqlScalarType::PgLegacyName => {}
4215                    }
4216                }
4217            }
4218            catalog.expire().await;
4219        })
4220        .await
4221    }
4222
4223    // Make sure objects reside in the `mz_introspection` schema iff they depend on per-replica
4224    // introspection relations.
4225    #[mz_ore::test(tokio::test)]
4226    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
4227    async fn test_mz_introspection_builtins() {
4228        Catalog::with_debug(|catalog| async move {
4229            let conn_catalog = catalog.for_system_session();
4230
4231            let introspection_schema_id = catalog.get_mz_introspection_schema_id();
4232            let introspection_schema_spec = SchemaSpecifier::Id(introspection_schema_id);
4233
4234            for entry in catalog.entries() {
4235                let schema_spec = entry.name().qualifiers.schema_spec;
4236                let introspection_deps = catalog.introspection_dependencies(entry.id);
4237                if introspection_deps.is_empty() {
4238                    assert!(
4239                        schema_spec != introspection_schema_spec,
4240                        "entry does not depend on introspection sources but is in \
4241                         `mz_introspection`: {}",
4242                        conn_catalog.resolve_full_name(entry.name()),
4243                    );
4244                } else {
4245                    assert!(
4246                        schema_spec == introspection_schema_spec,
4247                        "entry depends on introspection sources but is not in \
4248                         `mz_introspection`: {}",
4249                        conn_catalog.resolve_full_name(entry.name()),
4250                    );
4251                }
4252            }
4253        })
4254        .await
4255    }
4256
4257    #[mz_ore::test(tokio::test)]
4258    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
4259    async fn test_multi_subscriber_catalog() {
4260        let persist_client = PersistClient::new_for_tests().await;
4261        let bootstrap_args = test_bootstrap_args();
4262        let organization_id = Uuid::new_v4();
4263        let db_name = "DB";
4264
4265        let mut writer_catalog = Catalog::open_debug_catalog(
4266            persist_client.clone(),
4267            organization_id.clone(),
4268            &bootstrap_args,
4269        )
4270        .await
4271        .expect("open_debug_catalog");
4272        let mut read_only_catalog = Catalog::open_debug_read_only_catalog(
4273            persist_client.clone(),
4274            organization_id.clone(),
4275            &bootstrap_args,
4276        )
4277        .await
4278        .expect("open_debug_read_only_catalog");
4279        assert_err!(writer_catalog.resolve_database(db_name));
4280        assert_err!(read_only_catalog.resolve_database(db_name));
4281
4282        let commit_ts = writer_catalog.current_upper().await;
4283        writer_catalog
4284            .transact(
4285                None,
4286                commit_ts,
4287                None,
4288                vec![Op::CreateDatabase {
4289                    name: db_name.to_string(),
4290                    owner_id: MZ_SYSTEM_ROLE_ID,
4291                }],
4292            )
4293            .await
4294            .expect("failed to transact");
4295
4296        let write_db = writer_catalog
4297            .resolve_database(db_name)
4298            .expect("resolve_database");
4299        read_only_catalog
4300            .sync_to_current_updates()
4301            .await
4302            .expect("sync_to_current_updates");
4303        let read_db = read_only_catalog
4304            .resolve_database(db_name)
4305            .expect("resolve_database");
4306
4307        assert_eq!(write_db, read_db);
4308
4309        let writer_catalog_fencer =
4310            Catalog::open_debug_catalog(persist_client, organization_id, &bootstrap_args)
4311                .await
4312                .expect("open_debug_catalog for fencer");
4313        let fencer_db = writer_catalog_fencer
4314            .resolve_database(db_name)
4315            .expect("resolve_database for fencer");
4316        assert_eq!(fencer_db, read_db);
4317
4318        let write_fence_err = writer_catalog
4319            .sync_to_current_updates()
4320            .await
4321            .expect_err("sync_to_current_updates for fencer");
4322        assert!(matches!(
4323            write_fence_err,
4324            CatalogError::Durable(DurableCatalogError::Fence(FenceError::Epoch { .. }))
4325        ));
4326        let read_fence_err = read_only_catalog
4327            .sync_to_current_updates()
4328            .await
4329            .expect_err("sync_to_current_updates after fencer");
4330        assert!(matches!(
4331            read_fence_err,
4332            CatalogError::Durable(DurableCatalogError::Fence(FenceError::Epoch { .. }))
4333        ));
4334
4335        writer_catalog.expire().await;
4336        read_only_catalog.expire().await;
4337        writer_catalog_fencer.expire().await;
4338    }
4339}