Skip to main content

mz_sql/
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#![warn(missing_docs)]
11
12//! Catalog abstraction layer.
13
14use std::borrow::Cow;
15use std::collections::{BTreeMap, BTreeSet};
16use std::error::Error;
17use std::fmt;
18use std::fmt::{Debug, Display, Formatter};
19use std::num::NonZeroU32;
20use std::str::FromStr;
21use std::sync::LazyLock;
22use std::time::Instant;
23
24use chrono::{DateTime, Utc};
25use mz_auth::password::Password;
26use mz_build_info::BuildInfo;
27use mz_cloud_provider::{CloudProvider, InvalidCloudProviderError};
28use mz_controller_types::{ClusterId, ReplicaId};
29use mz_expr::MirScalarExpr;
30use mz_ore::now::{EpochMillis, NowFn};
31use mz_ore::str::StrExt;
32use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem, PrivilegeMap};
33use mz_repr::explain::ExprHumanizer;
34use mz_repr::network_policy_id::NetworkPolicyId;
35use mz_repr::query_policy_id::QueryPolicyId;
36use mz_repr::role_id::RoleId;
37use mz_repr::{
38    CatalogItemId, ColumnName, GlobalId, RelationDesc, RelationVersion, RelationVersionSelector,
39};
40use mz_sql_parser::ast::{Expr, QualifiedReplica, UnresolvedItemName};
41use mz_storage_types::connections::inline::{ConnectionResolver, ReferencedConnection};
42use mz_storage_types::connections::{Connection, ConnectionContext};
43use mz_storage_types::sources::{SourceDesc, SourceExportDataConfig, SourceExportDetails};
44use proptest_derive::Arbitrary;
45use regex::Regex;
46use serde::{Deserialize, Serialize};
47use uuid::Uuid;
48
49use crate::func::Func;
50use crate::names::{
51    Aug, CommentObjectId, DatabaseId, FullItemName, FullSchemaName, ObjectId, PartialItemName,
52    QualifiedItemName, QualifiedSchemaName, ResolvedDatabaseSpecifier, ResolvedIds, SchemaId,
53    SchemaSpecifier, SystemObjectId,
54};
55use crate::plan::statement::StatementDesc;
56use crate::plan::statement::ddl::PlannedRoleAttributes;
57use crate::plan::{
58    AutoScalingStrategy, ClusterSchedule, CreateClusterPlan, PlanError, PlanNotice, query,
59};
60use crate::session::vars::{OwnedVarInput, SystemVars};
61
62/// A catalog keeps track of SQL objects and session state available to the
63/// planner.
64///
65/// The `sql` crate is agnostic to any particular catalog implementation. This
66/// trait describes the required interface.
67///
68/// The SQL standard mandates a catalog hierarchy of exactly three layers. A
69/// catalog contains databases, databases contain schemas, and schemas contain
70/// catalog items, like sources, sinks, view, and indexes.
71///
72/// There are two classes of operations provided by a catalog:
73///
74///   * Resolution operations, like [`resolve_item`]. These fill in missing name
75///     components based upon connection defaults, e.g., resolving the partial
76///     name `view42` to the fully-specified name `materialize.public.view42`.
77///
78///   * Lookup operations, like [`SessionCatalog::get_item`]. These retrieve
79///     metadata about a catalog entity based on a fully-specified name that is
80///     known to be valid (i.e., because the name was successfully resolved, or
81///     was constructed based on the output of a prior lookup operation). These
82///     functions panic if called with invalid input.
83///
84///   * Session management, such as managing variables' states and adding
85///     notices to the session.
86///
87/// [`get_databases`]: SessionCatalog::get_databases
88/// [`get_item`]: SessionCatalog::get_item
89/// [`resolve_item`]: SessionCatalog::resolve_item
90pub trait SessionCatalog: fmt::Debug + ExprHumanizer + Send + Sync + ConnectionResolver {
91    /// Returns the id of the role that is issuing the query.
92    fn active_role_id(&self) -> &RoleId;
93
94    /// Returns the database to use if one is not explicitly specified.
95    fn active_database_name(&self) -> Option<&str> {
96        self.active_database()
97            .map(|id| self.get_database(id))
98            .map(|db| db.name())
99    }
100
101    /// Returns the database to use if one is not explicitly specified.
102    fn active_database(&self) -> Option<&DatabaseId>;
103
104    /// Returns the cluster to use if one is not explicitly specified.
105    fn active_cluster(&self) -> &str;
106
107    /// Returns the resolved search paths for the current user. (Invalid search paths are skipped.)
108    fn search_path(&self) -> &[(ResolvedDatabaseSpecifier, SchemaSpecifier)];
109
110    /// Returns the descriptor of the named prepared statement on the session, or
111    /// None if the prepared statement does not exist.
112    fn get_prepared_statement_desc(&self, name: &str) -> Option<&StatementDesc>;
113
114    /// Retrieves a reference to the specified portal's descriptor.
115    ///
116    /// If there is no such portal, returns `None`.
117    fn get_portal_desc_unverified(&self, portal_name: &str) -> Option<&StatementDesc>;
118
119    /// Resolves the named database.
120    ///
121    /// If `database_name` exists in the catalog, it returns a reference to the
122    /// resolved database; otherwise it returns an error.
123    fn resolve_database(&self, database_name: &str) -> Result<&dyn CatalogDatabase, CatalogError>;
124
125    /// Gets a database by its ID.
126    ///
127    /// Panics if `id` does not specify a valid database.
128    fn get_database(&self, id: &DatabaseId) -> &dyn CatalogDatabase;
129
130    /// Gets all databases.
131    fn get_databases(&self) -> Vec<&dyn CatalogDatabase>;
132
133    /// Resolves a partially-specified schema name.
134    ///
135    /// If the schema exists in the catalog, it returns a reference to the
136    /// resolved schema; otherwise it returns an error.
137    fn resolve_schema(
138        &self,
139        database_name: Option<&str>,
140        schema_name: &str,
141    ) -> Result<&dyn CatalogSchema, CatalogError>;
142
143    /// Resolves a schema name within a specified database.
144    ///
145    /// If the schema exists in the database, it returns a reference to the
146    /// resolved schema; otherwise it returns an error.
147    fn resolve_schema_in_database(
148        &self,
149        database_spec: &ResolvedDatabaseSpecifier,
150        schema_name: &str,
151    ) -> Result<&dyn CatalogSchema, CatalogError>;
152
153    /// Gets a schema by its ID.
154    ///
155    /// Panics if `id` does not specify a valid schema.
156    fn get_schema(
157        &self,
158        database_spec: &ResolvedDatabaseSpecifier,
159        schema_spec: &SchemaSpecifier,
160    ) -> &dyn CatalogSchema;
161
162    /// Gets all schemas.
163    fn get_schemas(&self) -> Vec<&dyn CatalogSchema>;
164
165    /// Gets the mz_internal schema id.
166    fn get_mz_internal_schema_id(&self) -> SchemaId;
167
168    /// Gets the mz_unsafe schema id.
169    fn get_mz_unsafe_schema_id(&self) -> SchemaId;
170
171    /// Returns true if `schema` is an internal system schema, false otherwise
172    fn is_system_schema_specifier(&self, schema: SchemaSpecifier) -> bool;
173
174    /// Resolves the named role.
175    fn resolve_role(&self, role_name: &str) -> Result<&dyn CatalogRole, CatalogError>;
176
177    /// Resolves the named network policy.
178    fn resolve_network_policy(
179        &self,
180        network_policy_name: &str,
181    ) -> Result<&dyn CatalogNetworkPolicy, CatalogError>;
182
183    /// Resolves a query policy by its environment-wide name.
184    fn resolve_query_policy(&self, name: &str) -> Result<&dyn CatalogQueryPolicy, CatalogError>;
185    /// Gets a query policy by ID. Panics if the policy does not exist.
186    fn get_query_policy(&self, id: &QueryPolicyId) -> &dyn CatalogQueryPolicy;
187    /// Returns all query policies in this catalog snapshot.
188    fn get_query_policies(&self) -> Vec<&dyn CatalogQueryPolicy>;
189
190    /// Gets a role by its ID.
191    fn try_get_role(&self, id: &RoleId) -> Option<&dyn CatalogRole>;
192
193    /// Gets a role by its ID.
194    ///
195    /// Panics if `id` does not specify a valid role.
196    fn get_role(&self, id: &RoleId) -> &dyn CatalogRole;
197
198    /// Gets all roles.
199    fn get_roles(&self) -> Vec<&dyn CatalogRole>;
200
201    /// Gets the id of the `mz_system` role.
202    fn mz_system_role_id(&self) -> RoleId;
203
204    /// Collects all role IDs that `id` is transitively a member of.
205    fn collect_role_membership(&self, id: &RoleId) -> BTreeSet<RoleId>;
206
207    /// Resolves the named cluster.
208    /// Gets a network_policy by its ID.
209    ///
210    /// Panics if `id` does not specify a valid role.
211    fn get_network_policy(&self, id: &NetworkPolicyId) -> &dyn CatalogNetworkPolicy;
212
213    /// Gets all roles.
214    fn get_network_policies(&self) -> Vec<&dyn CatalogNetworkPolicy>;
215
216    ///
217    /// If the provided name is `None`, resolves the currently active cluster.
218    fn resolve_cluster<'a, 'b>(
219        &'a self,
220        cluster_name: Option<&'b str>,
221    ) -> Result<&'a dyn CatalogCluster<'a>, CatalogError>;
222
223    /// Resolves the named cluster replica.
224    fn resolve_cluster_replica<'a, 'b>(
225        &'a self,
226        cluster_replica_name: &'b QualifiedReplica,
227    ) -> Result<&'a dyn CatalogClusterReplica<'a>, CatalogError>;
228
229    /// Resolves a partially-specified item name, that is NOT a function or
230    /// type. (For resolving functions or types, please use
231    /// [SessionCatalog::resolve_function] or [SessionCatalog::resolve_type].)
232    ///
233    /// If the partial name has a database component, it searches only the
234    /// specified database; otherwise, it searches the active database. If the
235    /// partial name has a schema component, it searches only the specified
236    /// schema; otherwise, it searches a default set of schemas within the
237    /// selected database. It returns an error if none of the searched schemas
238    /// contain an item whose name matches the item component of the partial
239    /// name.
240    ///
241    /// Note that it is not an error if the named item appears in more than one
242    /// of the search schemas. The catalog implementation must choose one.
243    fn resolve_item(&self, item_name: &PartialItemName) -> Result<&dyn CatalogItem, CatalogError>;
244
245    /// Performs the same operation as [`SessionCatalog::resolve_item`] but for
246    /// functions within the catalog.
247    fn resolve_function(
248        &self,
249        item_name: &PartialItemName,
250    ) -> Result<&dyn CatalogItem, CatalogError>;
251
252    /// Performs the same operation as [`SessionCatalog::resolve_item`] but for
253    /// types within the catalog.
254    fn resolve_type(&self, item_name: &PartialItemName) -> Result<&dyn CatalogItem, CatalogError>;
255
256    /// Resolves `name` to a type or item, preferring the type if both exist.
257    fn resolve_item_or_type(
258        &self,
259        name: &PartialItemName,
260    ) -> Result<&dyn CatalogItem, CatalogError> {
261        if let Ok(ty) = self.resolve_type(name) {
262            return Ok(ty);
263        }
264        self.resolve_item(name)
265    }
266
267    /// Gets a type named `name` from exactly one of the system schemas.
268    ///
269    /// # Panics
270    /// - If `name` is not an entry in any system schema
271    /// - If more than one system schema has an entry named `name`.
272    fn get_system_type(&self, name: &str) -> &dyn CatalogItem;
273
274    /// Gets an item by its ID.
275    fn try_get_item(&self, id: &CatalogItemId) -> Option<&dyn CatalogItem>;
276
277    /// Tries to get an item by a [`GlobalId`], returning `None` if the [`GlobalId`] does not
278    /// exist.
279    ///
280    /// Note: A single Catalog Item can have multiple [`GlobalId`]s associated with it.
281    fn try_get_item_by_global_id<'a>(
282        &'a self,
283        id: &GlobalId,
284    ) -> Option<Box<dyn CatalogCollectionItem + 'a>>;
285
286    /// Gets an item by its ID.
287    ///
288    /// Panics if `id` does not specify a valid item.
289    fn get_item(&self, id: &CatalogItemId) -> &dyn CatalogItem;
290
291    /// Gets an item by a [`GlobalId`].
292    ///
293    /// Panics if `id` does not specify a valid item.
294    ///
295    /// Note: A single Catalog Item can have multiple [`GlobalId`]s associated with it.
296    fn get_item_by_global_id<'a>(&'a self, id: &GlobalId) -> Box<dyn CatalogCollectionItem + 'a>;
297
298    /// Gets all items.
299    fn get_items(&self) -> Vec<&dyn CatalogItem>;
300
301    /// Looks up an item by its name.
302    fn get_item_by_name(&self, name: &QualifiedItemName) -> Option<&dyn CatalogItem>;
303
304    /// Looks up a type by its name.
305    fn get_type_by_name(&self, name: &QualifiedItemName) -> Option<&dyn CatalogItem>;
306
307    /// Gets a cluster by ID.
308    fn get_cluster(&self, id: ClusterId) -> &dyn CatalogCluster<'_>;
309
310    /// Gets all clusters.
311    fn get_clusters(&self) -> Vec<&dyn CatalogCluster<'_>>;
312
313    /// Gets a cluster replica by ID.
314    fn get_cluster_replica(
315        &self,
316        cluster_id: ClusterId,
317        replica_id: ReplicaId,
318    ) -> &dyn CatalogClusterReplica<'_>;
319
320    /// Gets all cluster replicas.
321    fn get_cluster_replicas(&self) -> Vec<&dyn CatalogClusterReplica<'_>>;
322
323    /// Gets all system privileges.
324    fn get_system_privileges(&self) -> &PrivilegeMap;
325
326    /// Gets all default privileges.
327    fn get_default_privileges(
328        &self,
329    ) -> Vec<(&DefaultPrivilegeObject, Vec<&DefaultPrivilegeAclItem>)>;
330
331    /// Finds a name like `name` that is not already in use.
332    ///
333    /// If `name` itself is available, it is returned unchanged.
334    fn find_available_name(&self, name: QualifiedItemName) -> QualifiedItemName;
335
336    /// Returns a fully qualified human readable name from fully qualified non-human readable name
337    fn resolve_full_name(&self, name: &QualifiedItemName) -> FullItemName;
338
339    /// Returns a fully qualified human readable schema name from fully qualified non-human
340    /// readable schema name
341    fn resolve_full_schema_name(&self, name: &QualifiedSchemaName) -> FullSchemaName;
342
343    /// Returns the [`CatalogItemId`] for from a [`GlobalId`].
344    fn resolve_item_id(&self, global_id: &GlobalId) -> CatalogItemId;
345
346    /// Returns the [`GlobalId`] for the specificed Catalog Item, at the specified version.
347    fn resolve_global_id(
348        &self,
349        item_id: &CatalogItemId,
350        version: RelationVersionSelector,
351    ) -> GlobalId;
352
353    /// Returns the configuration of the catalog.
354    fn config(&self) -> &CatalogConfig;
355
356    /// Returns the number of milliseconds since the system epoch. For normal use
357    /// this means the Unix epoch. This can safely be mocked in tests and start
358    /// at 0.
359    fn now(&self) -> EpochMillis;
360
361    /// Returns the set of supported AWS PrivateLink availability zone ids.
362    fn aws_privatelink_availability_zones(&self) -> Option<BTreeSet<String>>;
363
364    /// Returns true if the session has `restrict_to_user_objects` active.
365    ///
366    /// Defaults to false so that non-session catalog implementations (e.g. those used during
367    /// catalog rehydration) are unaffected.
368    fn restrict_to_user_objects(&self) -> bool {
369        false
370    }
371
372    /// Returns system vars
373    fn system_vars(&self) -> &SystemVars;
374
375    /// Returns mutable system vars
376    ///
377    /// Clients should use this this method carefully, as changes to the backing
378    /// state here are not guarateed to be persisted. The motivating use case
379    /// for this method was ensuring that features are temporary turned on so
380    /// catalog rehydration does not break due to unsupported SQL syntax.
381    fn system_vars_mut(&mut self) -> &mut SystemVars;
382
383    /// Returns the [`RoleId`] of the owner of an object by its ID.
384    fn get_owner_id(&self, id: &ObjectId) -> Option<RoleId>;
385
386    /// Returns the [`PrivilegeMap`] of the object.
387    fn get_privileges(&self, id: &SystemObjectId) -> Option<&PrivilegeMap>;
388
389    /// Returns all the IDs of all objects that depend on `ids`, including `ids` themselves.
390    ///
391    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
392    /// earlier in the list than the roots. This is particularly userful for the order to drop
393    /// objects.
394    fn object_dependents(&self, ids: &Vec<ObjectId>) -> Vec<ObjectId>;
395
396    /// Returns all the IDs of all objects that depend on `id`, including `id` themselves.
397    ///
398    /// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
399    /// earlier in the list than `id`. This is particularly userful for the order to drop
400    /// objects.
401    fn item_dependents(&self, id: CatalogItemId) -> Vec<ObjectId>;
402
403    /// Returns all possible privileges associated with an object type.
404    fn all_object_privileges(&self, object_type: SystemObjectType) -> AclMode;
405
406    /// Returns the object type of `object_id`.
407    fn get_object_type(&self, object_id: &ObjectId) -> ObjectType;
408
409    /// Returns the system object type of `id`.
410    fn get_system_object_type(&self, id: &SystemObjectId) -> SystemObjectType;
411
412    /// Returns the minimal qualification required to unambiguously specify
413    /// `qualified_name`.
414    fn minimal_qualification(&self, qualified_name: &QualifiedItemName) -> PartialItemName;
415
416    /// Adds a [`PlanNotice`] that will be displayed to the user if the plan
417    /// successfully executes.
418    fn add_notice(&self, notice: PlanNotice);
419
420    /// Returns the associated comments for the given `id`
421    fn get_item_comments(&self, id: &CatalogItemId) -> Option<&BTreeMap<Option<usize>, String>>;
422
423    /// Reports whether the specified cluster size is a modern "cc" size rather
424    /// than a legacy T-shirt size.
425    fn is_cluster_size_cc(&self, size: &str) -> bool;
426}
427
428/// Configuration associated with a catalog.
429#[derive(Debug, Clone)]
430pub struct CatalogConfig {
431    /// Returns the time at which the catalog booted.
432    pub start_time: DateTime<Utc>,
433    /// Returns the instant at which the catalog booted.
434    pub start_instant: Instant,
435    /// A random integer associated with this instance of the catalog.
436    ///
437    /// NOTE(benesch): this is only necessary for producing unique Kafka sink
438    /// topics. Perhaps we can remove this when database-issues#977 is complete.
439    pub nonce: u64,
440    /// A persistent ID associated with the environment.
441    pub environment_id: EnvironmentId,
442    /// A transient UUID associated with this process.
443    pub session_id: Uuid,
444    /// Information about this build of Materialize.
445    pub build_info: &'static BuildInfo,
446    /// Function that returns a wall clock now time; can safely be mocked to return
447    /// 0.
448    pub now: NowFn,
449    /// Context for source and sink connections.
450    pub connection_context: ConnectionContext,
451    /// The AWS account ID that Materialize runs under, if configured.
452    ///
453    /// This is the `aws_account_id` from the catalog's `AwsPrincipalContext`.
454    /// It is plumbed through here (rather than the whole context) because the
455    /// external-id prefix and connection role ARN already live on
456    /// [`ConnectionContext`], and because `AwsPrincipalContext` is defined in
457    /// `mz-catalog`, which cannot be a dependency of `mz-sql`. Folded into a
458    /// literal by `mz_aws_account_id()`; `None` on non-cloud/local envs.
459    pub aws_account_id: Option<String>,
460    /// Helm chart version
461    pub helm_chart_version: Option<String>,
462}
463
464/// A database in a [`SessionCatalog`].
465pub trait CatalogDatabase {
466    /// Returns a fully-specified name of the database.
467    fn name(&self) -> &str;
468
469    /// Returns a stable ID for the database.
470    fn id(&self) -> DatabaseId;
471
472    /// Returns whether the database contains schemas.
473    fn has_schemas(&self) -> bool;
474
475    /// Returns the schemas of the database as a map from schema name to
476    /// schema ID.
477    fn schema_ids(&self) -> &BTreeMap<String, SchemaId>;
478
479    /// Returns the schemas of the database.
480    fn schemas(&self) -> Vec<&dyn CatalogSchema>;
481
482    /// Returns the ID of the owning role.
483    fn owner_id(&self) -> RoleId;
484
485    /// Returns the privileges associated with the database.
486    fn privileges(&self) -> &PrivilegeMap;
487}
488
489/// A schema in a [`SessionCatalog`].
490pub trait CatalogSchema {
491    /// Returns a fully-specified id of the database
492    fn database(&self) -> &ResolvedDatabaseSpecifier;
493
494    /// Returns a fully-specified name of the schema.
495    fn name(&self) -> &QualifiedSchemaName;
496
497    /// Returns a stable ID for the schema.
498    fn id(&self) -> &SchemaSpecifier;
499
500    /// Lists the `CatalogItem`s for the schema.
501    fn has_items(&self) -> bool;
502
503    /// Returns the IDs of the items in the schema.
504    fn item_ids(&self) -> Box<dyn Iterator<Item = CatalogItemId> + '_>;
505
506    /// Returns the ID of the owning role.
507    fn owner_id(&self) -> RoleId;
508
509    /// Returns the privileges associated with the schema.
510    fn privileges(&self) -> &PrivilegeMap;
511}
512
513/// Parameters used to modify password
514#[derive(Debug, Clone, Eq, PartialEq, Arbitrary)]
515pub struct PasswordConfig {
516    /// The Password.
517    pub password: Password,
518    /// a non default iteration count for hashing the password.
519    pub scram_iterations: NonZeroU32,
520}
521
522/// A modification of a role password in the catalog
523#[derive(Debug, Clone, Eq, PartialEq, Arbitrary)]
524pub enum PasswordAction {
525    /// Set a new password.
526    Set(PasswordConfig),
527    /// Remove the existing password.
528    Clear,
529    /// Leave the existing password unchanged.
530    NoChange,
531}
532
533/// The authenticator that auto-provisioned a role on first login.
534#[derive(
535    Debug,
536    Copy,
537    Clone,
538    Eq,
539    PartialEq,
540    Ord,
541    PartialOrd,
542    Serialize,
543    Deserialize,
544    Arbitrary
545)]
546pub enum AutoProvisionSource {
547    /// Role was auto-provisioned by [`mz_auth::AuthenticatorKind::Oidc`].
548    Oidc,
549    /// Role was auto-provisioned by [`mz_auth::AuthenticatorKind::Frontegg`].
550    Frontegg,
551    /// Role was auto-provisioned by [`mz_auth::AuthenticatorKind::None`]
552    None,
553}
554
555/// A raw representation of attributes belonging to a [`CatalogRole`] that we might
556/// get as input from the user. This includes the password.
557/// This struct explicitly does not implement `Serialize` or `Deserialize` to avoid
558/// accidentally serializing passwords.
559#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Arbitrary)]
560pub struct RoleAttributesRaw {
561    /// Indicates whether the role has inheritance of privileges.
562    pub inherit: bool,
563    /// The raw password of the role. This is for self managed auth, not cloud.
564    pub password: Option<Password>,
565    /// Hash iterations used to securely store passwords. This is for self-managed auth
566    pub scram_iterations: Option<NonZeroU32>,
567    /// Whether or not this user is a superuser.
568    pub superuser: Option<bool>,
569    /// Whether this role is login
570    pub login: Option<bool>,
571    /// The authenticator that auto-provisioned this role, if any.
572    pub auto_provision_source: Option<AutoProvisionSource>,
573    // Force use of constructor.
574    _private: (),
575}
576
577/// Attributes belonging to a [`CatalogRole`].
578#[derive(
579    Debug,
580    Clone,
581    Eq,
582    Serialize,
583    Deserialize,
584    PartialEq,
585    Ord,
586    PartialOrd,
587    Arbitrary
588)]
589pub struct RoleAttributes {
590    /// Indicates whether the role has inheritance of privileges.
591    pub inherit: bool,
592    /// Whether or not this user is a superuser.
593    pub superuser: Option<bool>,
594    /// Whether this role is login
595    pub login: Option<bool>,
596    /// The authenticator that auto-provisioned this role, if any.
597    pub auto_provision_source: Option<AutoProvisionSource>,
598    // Force use of constructor.
599    _private: (),
600}
601
602impl RoleAttributesRaw {
603    /// Creates a new [`RoleAttributesRaw`] with default attributes.
604    pub const fn new() -> RoleAttributesRaw {
605        RoleAttributesRaw {
606            inherit: true,
607            password: None,
608            scram_iterations: None,
609            superuser: None,
610            login: None,
611            auto_provision_source: None,
612            _private: (),
613        }
614    }
615
616    /// Adds all attributes excluding password.
617    pub const fn with_all(mut self) -> RoleAttributesRaw {
618        self.inherit = true;
619        self.superuser = Some(true);
620        self.login = Some(true);
621        self
622    }
623}
624
625impl RoleAttributes {
626    /// Creates a new [`RoleAttributes`] with default attributes.
627    pub const fn new() -> RoleAttributes {
628        RoleAttributes {
629            inherit: true,
630            superuser: None,
631            login: None,
632            auto_provision_source: None,
633            _private: (),
634        }
635    }
636
637    /// Adds all attributes except password and auto_provision_source.
638    pub const fn with_all(mut self) -> RoleAttributes {
639        self.inherit = true;
640        self.superuser = Some(true);
641        self.login = Some(true);
642        self
643    }
644
645    /// Returns whether or not the role has inheritence of privileges.
646    pub const fn is_inherit(&self) -> bool {
647        self.inherit
648    }
649}
650
651impl From<RoleAttributesRaw> for RoleAttributes {
652    fn from(
653        RoleAttributesRaw {
654            inherit,
655            superuser,
656            login,
657            auto_provision_source,
658            ..
659        }: RoleAttributesRaw,
660    ) -> RoleAttributes {
661        RoleAttributes {
662            inherit,
663            superuser,
664            login,
665            auto_provision_source,
666            _private: (),
667        }
668    }
669}
670
671impl From<RoleAttributes> for RoleAttributesRaw {
672    fn from(
673        RoleAttributes {
674            inherit,
675            superuser,
676            login,
677            auto_provision_source,
678            ..
679        }: RoleAttributes,
680    ) -> RoleAttributesRaw {
681        RoleAttributesRaw {
682            inherit,
683            password: None,
684            scram_iterations: None,
685            superuser,
686            login,
687            auto_provision_source,
688            _private: (),
689        }
690    }
691}
692
693impl From<PlannedRoleAttributes> for RoleAttributesRaw {
694    fn from(
695        PlannedRoleAttributes {
696            inherit,
697            password,
698            scram_iterations,
699            superuser,
700            login,
701            ..
702        }: PlannedRoleAttributes,
703    ) -> RoleAttributesRaw {
704        let default_attributes = RoleAttributesRaw::new();
705        RoleAttributesRaw {
706            inherit: inherit.unwrap_or(default_attributes.inherit),
707            password,
708            scram_iterations,
709            superuser,
710            login,
711            auto_provision_source: None,
712            _private: (),
713        }
714    }
715}
716
717/// Default variable values for a [`CatalogRole`].
718#[derive(Default, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
719pub struct RoleVars {
720    /// Map of variable names to their value.
721    pub map: BTreeMap<String, OwnedVarInput>,
722}
723
724/// A role in a [`SessionCatalog`].
725pub trait CatalogRole {
726    /// Returns a fully-specified name of the role.
727    fn name(&self) -> &str;
728
729    /// Returns a stable ID for the role.
730    fn id(&self) -> RoleId;
731
732    /// Returns all role IDs that this role is an immediate a member of, and the grantor of that
733    /// membership.
734    ///
735    /// Key is the role that some role is a member of, value is the grantor role ID.
736    fn membership(&self) -> &BTreeMap<RoleId, RoleId>;
737
738    /// Returns the attributes associated with this role.
739    fn attributes(&self) -> &RoleAttributes;
740
741    /// Returns all variables that this role has a default value stored for.
742    fn vars(&self) -> &BTreeMap<String, OwnedVarInput>;
743}
744
745/// A query policy in the environment-wide namespace.
746pub trait CatalogQueryPolicy {
747    /// Returns the environment-wide policy name.
748    fn name(&self) -> &str;
749    /// Returns the policy's stable ID.
750    fn id(&self) -> QueryPolicyId;
751    /// Returns the role that owns this policy.
752    fn owner_id(&self) -> RoleId;
753    /// Returns the policy's access privileges.
754    fn privileges(&self) -> &PrivilegeMap;
755    /// Returns whether matching rules warn or reject queries.
756    fn mode(&self) -> crate::plan::QueryPolicyMode;
757    /// Returns the rules evaluated for queries subject to this policy.
758    fn rules(&self) -> &[crate::plan::QueryPolicyRule];
759}
760
761/// A network policy in a [`SessionCatalog`].
762pub trait CatalogNetworkPolicy {
763    /// Returns a fully-specified name of the NetworkPolicy.
764    fn name(&self) -> &str;
765
766    /// Returns a stable ID for the NetworkPolicy.
767    fn id(&self) -> NetworkPolicyId;
768
769    /// Returns the ID of the owning NetworkPolicy.
770    fn owner_id(&self) -> RoleId;
771
772    /// Returns the privileges associated with the NetworkPolicy.
773    fn privileges(&self) -> &PrivilegeMap;
774}
775
776/// A cluster in a [`SessionCatalog`].
777pub trait CatalogCluster<'a> {
778    /// Returns a fully-specified name of the cluster.
779    fn name(&self) -> &str;
780
781    /// Returns a stable ID for the cluster.
782    fn id(&self) -> ClusterId;
783
784    /// Returns the objects that are bound to this cluster.
785    fn bound_objects(&self) -> &BTreeSet<CatalogItemId>;
786
787    /// Returns the replicas of the cluster as a map from replica name to
788    /// replica ID.
789    fn replica_ids(&self) -> &BTreeMap<String, ReplicaId>;
790
791    /// Returns the replicas of the cluster.
792    fn replicas(&self) -> Vec<&dyn CatalogClusterReplica<'_>>;
793
794    /// Returns the replica belonging to the cluster with replica ID `id`.
795    fn replica(&self, id: ReplicaId) -> &dyn CatalogClusterReplica<'_>;
796
797    /// Returns the ID of the owning role.
798    fn owner_id(&self) -> RoleId;
799
800    /// Returns the privileges associated with the cluster.
801    fn privileges(&self) -> &PrivilegeMap;
802
803    /// Returns true if this cluster is a managed cluster.
804    fn is_managed(&self) -> bool;
805
806    /// Returns the size of the cluster, if the cluster is a managed cluster.
807    fn managed_size(&self) -> Option<&str>;
808
809    /// Returns the schedule of the cluster, if the cluster is a managed cluster.
810    fn schedule(&self) -> Option<&ClusterSchedule>;
811
812    /// Returns the replication factor of the cluster, if the cluster is a managed cluster.
813    fn replication_factor(&self) -> Option<u32>;
814
815    /// Returns the user-configured autoscaling strategy of the cluster, if the
816    /// cluster is managed and has one set.
817    fn auto_scaling_strategy(&self) -> Option<&AutoScalingStrategy>;
818    /// Try to convert this cluster into a [`CreateClusterPlan`].
819    // TODO(jkosh44) Make this infallible and convert to `to_plan`.
820    fn try_to_plan(&self) -> Result<CreateClusterPlan, PlanError>;
821}
822
823/// A cluster replica in a [`SessionCatalog`]
824pub trait CatalogClusterReplica<'a>: Debug {
825    /// Returns the name of the cluster replica.
826    fn name(&self) -> &str;
827
828    /// Returns a stable ID for the cluster that the replica belongs to.
829    fn cluster_id(&self) -> ClusterId;
830
831    /// Returns a stable ID for the replica.
832    fn replica_id(&self) -> ReplicaId;
833
834    /// Returns the ID of the owning role.
835    fn owner_id(&self) -> RoleId;
836
837    /// Returns whether or not the replica is internal
838    fn internal(&self) -> bool;
839}
840
841/// An item in a [`SessionCatalog`].
842///
843/// Note that "item" has a very specific meaning in the context of a SQL
844/// catalog, and refers to the various entities that belong to a schema.
845pub trait CatalogItem {
846    /// Returns the fully qualified name of the catalog item.
847    fn name(&self) -> &QualifiedItemName;
848
849    /// Returns the [`CatalogItemId`] for the item.
850    fn id(&self) -> CatalogItemId;
851
852    /// Returns the [`GlobalId`]s associated with this item.
853    fn global_ids(&self) -> Box<dyn Iterator<Item = GlobalId> + '_>;
854
855    /// Returns the catalog item's OID.
856    fn oid(&self) -> u32;
857
858    /// Returns the resolved function.
859    ///
860    /// If the catalog item is not of a type that produces functions (i.e.,
861    /// anything other than a function), it returns an error.
862    fn func(&self) -> Result<&'static Func, CatalogError>;
863
864    /// Returns the resolved source connection.
865    ///
866    /// If the catalog item is not of a type that contains a `SourceDesc`
867    /// (i.e., anything other than sources), it returns an error.
868    fn source_desc(&self) -> Result<Option<&SourceDesc<ReferencedConnection>>, CatalogError>;
869
870    /// Returns the resolved connection.
871    ///
872    /// If the catalog item is not a connection, it returns an error.
873    fn connection(&self) -> Result<Connection<ReferencedConnection>, CatalogError>;
874
875    /// Returns the type of the catalog item.
876    fn item_type(&self) -> CatalogItemType;
877
878    /// A normalized SQL statement that describes how to create the catalog
879    /// item.
880    fn create_sql(&self) -> &str;
881
882    /// Returns the IDs of the catalog items upon which this catalog item
883    /// directly references.
884    fn references(&self) -> &ResolvedIds;
885
886    /// Returns the IDs of the catalog items upon which this catalog item
887    /// depends.
888    fn uses(&self) -> BTreeSet<CatalogItemId>;
889
890    /// Returns the IDs of the catalog items that directly reference this catalog item.
891    fn referenced_by(&self) -> &[CatalogItemId];
892
893    /// Returns the IDs of the catalog items that depend upon this catalog item.
894    fn used_by(&self) -> &[CatalogItemId];
895
896    /// Reports whether this catalog entry is a subsource and, if it is, the
897    /// ingestion it is an export of, as well as the item it exports.
898    fn subsource_details(
899        &self,
900    ) -> Option<(CatalogItemId, &UnresolvedItemName, &SourceExportDetails)>;
901
902    /// Reports whether this catalog entry is a source export and, if it is, the
903    /// ingestion it is an export of, as well as the item it exports.
904    fn source_export_details(
905        &self,
906    ) -> Option<(
907        CatalogItemId,
908        &UnresolvedItemName,
909        &SourceExportDetails,
910        &SourceExportDataConfig<ReferencedConnection>,
911    )>;
912
913    /// Reports whether this catalog item is a progress source.
914    fn is_progress_source(&self) -> bool;
915
916    /// If this catalog item is a source, it return the IDs of its progress collection.
917    fn progress_id(&self) -> Option<CatalogItemId>;
918
919    /// Returns the index details associated with the catalog item, if the
920    /// catalog item is an index.
921    fn index_details(&self) -> Option<(&[MirScalarExpr], GlobalId)>;
922
923    /// Returns the column defaults associated with the catalog item, if the
924    /// catalog item is a table that accepts writes.
925    fn writable_table_details(&self) -> Option<&[Expr<Aug>]>;
926
927    /// The item this catalog item replaces, if any.
928    fn replacement_target(&self) -> Option<CatalogItemId>;
929
930    /// Returns the type information associated with the catalog item, if the
931    /// catalog item is a type.
932    fn type_details(&self) -> Option<&CatalogTypeDetails<IdReference>>;
933
934    /// Returns the ID of the owning role.
935    fn owner_id(&self) -> RoleId;
936
937    /// Returns the privileges associated with the item.
938    fn privileges(&self) -> &PrivilegeMap;
939
940    /// Returns the cluster the item belongs to.
941    fn cluster_id(&self) -> Option<ClusterId>;
942
943    /// Returns the [`CatalogCollectionItem`] for a specific version of this
944    /// [`CatalogItem`].
945    fn at_version(&self, version: RelationVersionSelector) -> Box<dyn CatalogCollectionItem>;
946
947    /// The latest version of this item, if it's version-able.
948    fn latest_version(&self) -> Option<RelationVersion>;
949}
950
951/// An item in a [`SessionCatalog`] and the specific "collection"/pTVC that it
952/// refers to.
953pub trait CatalogCollectionItem: CatalogItem + Send + Sync {
954    /// Returns a description of the result set produced by the catalog item.
955    ///
956    /// If the catalog item is not of a type that produces data (e.g., a sink or
957    /// an index), it returns `None`.
958    fn relation_desc(&self) -> Option<Cow<'_, RelationDesc>>;
959
960    /// The [`GlobalId`] for this item.
961    fn global_id(&self) -> GlobalId;
962}
963
964/// The type of a [`CatalogItem`].
965#[derive(
966    Debug,
967    Deserialize,
968    Clone,
969    Copy,
970    Eq,
971    Hash,
972    Ord,
973    PartialEq,
974    PartialOrd,
975    Serialize
976)]
977pub enum CatalogItemType {
978    /// A table.
979    Table,
980    /// A source.
981    Source,
982    /// A sink.
983    Sink,
984    /// A view.
985    View,
986    /// A materialized view.
987    MaterializedView,
988    /// An index.
989    Index,
990    /// A type.
991    Type,
992    /// A func.
993    Func,
994    /// A secret.
995    Secret,
996    /// A connection.
997    Connection,
998    /// A metric sink.
999    MetricSink,
1000}
1001
1002impl CatalogItemType {
1003    /// Reports whether the given type of item conflicts with items of type
1004    /// `CatalogItemType::Type`.
1005    ///
1006    /// In PostgreSQL, even though types live in a separate namespace from other
1007    /// schema objects, creating a table, view, or materialized view creates a
1008    /// type named after that relation. This prevents creating a type with the
1009    /// same name as a relational object, even though types and relational
1010    /// objects live in separate namespaces. (Indexes are even weirder; while
1011    /// they don't get a type with the same name, they get an entry in
1012    /// `pg_class` that prevents *record* types of the same name as the index,
1013    /// but not other types of types, like enums.)
1014    ///
1015    /// We don't presently construct types that mirror relational objects,
1016    /// though we likely will need to in the future for full PostgreSQL
1017    /// compatibility (see database-issues#7142). For now, we use this method to
1018    /// prevent creating types and relational objects that have the same name, so
1019    /// that it is a backwards compatible change in the future to introduce a
1020    /// type named after each relational object in the system.
1021    pub fn conflicts_with_type(&self) -> bool {
1022        match self {
1023            CatalogItemType::Table => true,
1024            CatalogItemType::Source => true,
1025            CatalogItemType::View => true,
1026            CatalogItemType::MaterializedView => true,
1027            CatalogItemType::Index => true,
1028            CatalogItemType::Type => true,
1029            CatalogItemType::Sink => false,
1030            CatalogItemType::Func => false,
1031            CatalogItemType::Secret => false,
1032            CatalogItemType::Connection => false,
1033            CatalogItemType::MetricSink => false,
1034        }
1035    }
1036}
1037
1038impl fmt::Display for CatalogItemType {
1039    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1040        match self {
1041            CatalogItemType::Table => f.write_str("table"),
1042            CatalogItemType::Source => f.write_str("source"),
1043            CatalogItemType::Sink => f.write_str("sink"),
1044            CatalogItemType::View => f.write_str("view"),
1045            CatalogItemType::MaterializedView => f.write_str("materialized view"),
1046            CatalogItemType::Index => f.write_str("index"),
1047            CatalogItemType::Type => f.write_str("type"),
1048            CatalogItemType::Func => f.write_str("func"),
1049            CatalogItemType::Secret => f.write_str("secret"),
1050            CatalogItemType::Connection => f.write_str("connection"),
1051            CatalogItemType::MetricSink => f.write_str("metric sink"),
1052        }
1053    }
1054}
1055
1056impl From<CatalogItemType> for ObjectType {
1057    fn from(value: CatalogItemType) -> Self {
1058        match value {
1059            CatalogItemType::Table => ObjectType::Table,
1060            CatalogItemType::Source => ObjectType::Source,
1061            CatalogItemType::Sink => ObjectType::Sink,
1062            CatalogItemType::View => ObjectType::View,
1063            CatalogItemType::MaterializedView => ObjectType::MaterializedView,
1064            CatalogItemType::Index => ObjectType::Index,
1065            CatalogItemType::Type => ObjectType::Type,
1066            CatalogItemType::Func => ObjectType::Func,
1067            CatalogItemType::Secret => ObjectType::Secret,
1068            CatalogItemType::Connection => ObjectType::Connection,
1069            CatalogItemType::MetricSink => ObjectType::MetricSink,
1070        }
1071    }
1072}
1073
1074impl From<CatalogItemType> for mz_audit_log::ObjectType {
1075    fn from(value: CatalogItemType) -> Self {
1076        match value {
1077            CatalogItemType::Table => mz_audit_log::ObjectType::Table,
1078            CatalogItemType::Source => mz_audit_log::ObjectType::Source,
1079            CatalogItemType::View => mz_audit_log::ObjectType::View,
1080            CatalogItemType::MaterializedView => mz_audit_log::ObjectType::MaterializedView,
1081            CatalogItemType::Index => mz_audit_log::ObjectType::Index,
1082            CatalogItemType::Type => mz_audit_log::ObjectType::Type,
1083            CatalogItemType::Sink => mz_audit_log::ObjectType::Sink,
1084            CatalogItemType::Func => mz_audit_log::ObjectType::Func,
1085            CatalogItemType::Secret => mz_audit_log::ObjectType::Secret,
1086            CatalogItemType::Connection => mz_audit_log::ObjectType::Connection,
1087            CatalogItemType::MetricSink => mz_audit_log::ObjectType::MetricSink,
1088        }
1089    }
1090}
1091
1092/// Details about a type in the catalog.
1093#[derive(Clone, Debug, Eq, PartialEq)]
1094pub struct CatalogTypeDetails<T: TypeReference> {
1095    /// The ID of the type with this type as the array element, if available.
1096    pub array_id: Option<CatalogItemId>,
1097    /// The description of this type.
1098    pub typ: CatalogType<T>,
1099    /// Additional metadata about the type in PostgreSQL, if relevant.
1100    pub pg_metadata: Option<CatalogTypePgMetadata>,
1101}
1102
1103/// Additional PostgreSQL metadata about a type.
1104#[derive(Clone, Debug, Eq, PartialEq)]
1105pub struct CatalogTypePgMetadata {
1106    /// The OID of the `typinput` function in PostgreSQL.
1107    pub typinput_oid: u32,
1108    /// The OID of the `typreceive` function in PostgreSQL.
1109    pub typreceive_oid: u32,
1110    /// The OID of the `typsend` function in PostgreSQL.
1111    pub typsend_oid: u32,
1112}
1113
1114/// Represents a reference to type in the catalog
1115pub trait TypeReference {
1116    /// The actual type used to reference a `CatalogType`
1117    type Reference: Clone + Debug + Eq + PartialEq;
1118}
1119
1120/// Reference to a type by it's name
1121#[derive(Clone, Debug, Eq, PartialEq)]
1122pub struct NameReference;
1123
1124impl TypeReference for NameReference {
1125    type Reference = &'static str;
1126}
1127
1128/// Reference to a type by it's global ID
1129#[derive(Clone, Debug, Eq, PartialEq)]
1130pub struct IdReference;
1131
1132impl TypeReference for IdReference {
1133    type Reference = CatalogItemId;
1134}
1135
1136/// A type stored in the catalog.
1137///
1138/// The variants correspond one-to-one with [`mz_repr::SqlScalarType`], but with type
1139/// modifiers removed and with embedded types replaced with references to other
1140/// types in the catalog.
1141#[allow(missing_docs)]
1142#[derive(Clone, Debug, Eq, PartialEq)]
1143pub enum CatalogType<T: TypeReference> {
1144    AclItem,
1145    Array {
1146        element_reference: T::Reference,
1147    },
1148    Bool,
1149    Bytes,
1150    Char,
1151    Date,
1152    Float32,
1153    Float64,
1154    Int16,
1155    Int32,
1156    Int64,
1157    UInt16,
1158    UInt32,
1159    UInt64,
1160    MzTimestamp,
1161    Interval,
1162    Jsonb,
1163    List {
1164        element_reference: T::Reference,
1165        element_modifiers: Vec<i64>,
1166    },
1167    Map {
1168        key_reference: T::Reference,
1169        key_modifiers: Vec<i64>,
1170        value_reference: T::Reference,
1171        value_modifiers: Vec<i64>,
1172    },
1173    Numeric,
1174    Oid,
1175    PgLegacyChar,
1176    PgLegacyName,
1177    Pseudo,
1178    Range {
1179        element_reference: T::Reference,
1180    },
1181    Record {
1182        fields: Vec<CatalogRecordField<T>>,
1183    },
1184    RegClass,
1185    RegProc,
1186    RegType,
1187    String,
1188    Time,
1189    Timestamp,
1190    TimestampTz,
1191    Uuid,
1192    VarChar,
1193    Int2Vector,
1194    MzAclItem,
1195}
1196
1197impl CatalogType<IdReference> {
1198    /// Returns the relation description for the type, if the type is a record
1199    /// type.
1200    pub fn desc(&self, catalog: &dyn SessionCatalog) -> Result<Option<RelationDesc>, PlanError> {
1201        match &self {
1202            CatalogType::Record { fields } => {
1203                let mut desc = RelationDesc::builder();
1204                // Share one budget across every field. Resolving each field with
1205                // a fresh budget would let a wide record materialize an
1206                // unbounded type tree here even though each field is individually
1207                // within the bound.
1208                let mut budget = query::TypeResolutionBudget::for_root(catalog);
1209                for f in fields {
1210                    let name = f.name.clone();
1211                    let ty = budget.resolve_child(catalog, f.type_reference, &f.type_modifiers)?;
1212                    // TODO: support plumbing `NOT NULL` constraints through
1213                    // `CREATE TYPE`.
1214                    let ty = ty.nullable(true);
1215                    desc = desc.with_column(name, ty);
1216                }
1217                Ok(Some(desc.finish()))
1218            }
1219            _ => Ok(None),
1220        }
1221    }
1222}
1223
1224/// A description of a field in a [`CatalogType::Record`].
1225#[derive(Clone, Debug, Eq, PartialEq)]
1226pub struct CatalogRecordField<T: TypeReference> {
1227    /// The name of the field.
1228    pub name: ColumnName,
1229    /// The ID of the type of the field.
1230    pub type_reference: T::Reference,
1231    /// Modifiers to apply to the type.
1232    pub type_modifiers: Vec<i64>,
1233}
1234
1235#[derive(Clone, Debug, Eq, PartialEq)]
1236/// Mirrored from [PostgreSQL's `typcategory`][typcategory].
1237///
1238/// Note that Materialize also uses a number of pseudotypes when planning, but
1239/// we have yet to need to integrate them with `TypeCategory`.
1240///
1241/// [typcategory]:
1242/// https://www.postgresql.org/docs/9.6/catalog-pg-type.html#CATALOG-TYPCATEGORY-TABLE
1243pub enum TypeCategory {
1244    /// Array type.
1245    Array,
1246    /// Bit string type.
1247    BitString,
1248    /// Boolean type.
1249    Boolean,
1250    /// Composite type.
1251    Composite,
1252    /// Date/time type.
1253    DateTime,
1254    /// Enum type.
1255    Enum,
1256    /// Geometric type.
1257    Geometric,
1258    /// List type. Materialize specific.
1259    List,
1260    /// Network address type.
1261    NetworkAddress,
1262    /// Numeric type.
1263    Numeric,
1264    /// Pseudo type.
1265    Pseudo,
1266    /// Range type.
1267    Range,
1268    /// String type.
1269    String,
1270    /// Timestamp type.
1271    Timespan,
1272    /// User-defined type.
1273    UserDefined,
1274    /// Unknown type.
1275    Unknown,
1276}
1277
1278impl fmt::Display for TypeCategory {
1279    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1280        f.write_str(match self {
1281            TypeCategory::Array => "array",
1282            TypeCategory::BitString => "bit-string",
1283            TypeCategory::Boolean => "boolean",
1284            TypeCategory::Composite => "composite",
1285            TypeCategory::DateTime => "date-time",
1286            TypeCategory::Enum => "enum",
1287            TypeCategory::Geometric => "geometric",
1288            TypeCategory::List => "list",
1289            TypeCategory::NetworkAddress => "network-address",
1290            TypeCategory::Numeric => "numeric",
1291            TypeCategory::Pseudo => "pseudo",
1292            TypeCategory::Range => "range",
1293            TypeCategory::String => "string",
1294            TypeCategory::Timespan => "timespan",
1295            TypeCategory::UserDefined => "user-defined",
1296            TypeCategory::Unknown => "unknown",
1297        })
1298    }
1299}
1300
1301/// Identifies an environment.
1302///
1303/// Outside of tests, an environment ID can be constructed only from a string of
1304/// the following form:
1305///
1306/// ```text
1307/// <CLOUD PROVIDER>-<CLOUD PROVIDER REGION>-<ORGANIZATION ID>-<ORDINAL>
1308/// ```
1309///
1310/// The fields have the following formats:
1311///
1312/// * The cloud provider consists of one or more alphanumeric characters.
1313/// * The cloud provider region consists of one or more alphanumeric or hyphen
1314///   characters.
1315/// * The organization ID is a UUID in its canonical text format.
1316/// * The ordinal is a decimal number with between one and eight digits.
1317///
1318/// There is no way to construct an environment ID from parts, to ensure that
1319/// the `Display` representation is parseable according to the above rules.
1320// NOTE(benesch): ideally we'd have accepted the components of the environment
1321// ID using separate command-line arguments, or at least a string format that
1322// used a field separator that did not appear in the fields. Alas. We can't
1323// easily change it now, as it's used as the e.g. default sink progress topic.
1324#[derive(Debug, Clone, PartialEq)]
1325pub struct EnvironmentId {
1326    cloud_provider: CloudProvider,
1327    cloud_provider_region: String,
1328    organization_id: Uuid,
1329    ordinal: u64,
1330}
1331
1332impl EnvironmentId {
1333    /// Creates a dummy `EnvironmentId` for use in tests.
1334    pub fn for_tests() -> EnvironmentId {
1335        EnvironmentId {
1336            cloud_provider: CloudProvider::Local,
1337            cloud_provider_region: "az1".into(),
1338            organization_id: Uuid::new_v4(),
1339            ordinal: 0,
1340        }
1341    }
1342
1343    /// Returns the cloud provider associated with this environment ID.
1344    pub fn cloud_provider(&self) -> &CloudProvider {
1345        &self.cloud_provider
1346    }
1347
1348    /// Returns the cloud provider region associated with this environment ID.
1349    pub fn cloud_provider_region(&self) -> &str {
1350        &self.cloud_provider_region
1351    }
1352
1353    /// Returns the name of the region associted with this environment ID.
1354    ///
1355    /// A region is a combination of [`EnvironmentId::cloud_provider`] and
1356    /// [`EnvironmentId::cloud_provider_region`].
1357    pub fn region(&self) -> String {
1358        format!("{}/{}", self.cloud_provider, self.cloud_provider_region)
1359    }
1360
1361    /// Returns the organization ID associated with this environment ID.
1362    pub fn organization_id(&self) -> Uuid {
1363        self.organization_id
1364    }
1365
1366    /// Returns the ordinal associated with this environment ID.
1367    pub fn ordinal(&self) -> u64 {
1368        self.ordinal
1369    }
1370}
1371
1372// *Warning*: once the LaunchDarkly integration is live, our contexts will be
1373// populated using this key. Consequently, any changes to that trait
1374// implementation will also have to be reflected in the existing feature
1375// targeting config in LaunchDarkly, otherwise environments might receive
1376// different configs upon restart.
1377impl fmt::Display for EnvironmentId {
1378    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1379        write!(
1380            f,
1381            "{}-{}-{}-{}",
1382            self.cloud_provider, self.cloud_provider_region, self.organization_id, self.ordinal
1383        )
1384    }
1385}
1386
1387impl FromStr for EnvironmentId {
1388    type Err = InvalidEnvironmentIdError;
1389
1390    fn from_str(s: &str) -> Result<EnvironmentId, InvalidEnvironmentIdError> {
1391        static MATCHER: LazyLock<Regex> = LazyLock::new(|| {
1392            Regex::new(
1393                "^(?P<cloud_provider>[[:alnum:]]+)-\
1394                  (?P<cloud_provider_region>[[:alnum:]\\-]+)-\
1395                  (?P<organization_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-\
1396                  (?P<ordinal>\\d{1,8})$"
1397            ).unwrap()
1398        });
1399        let captures = MATCHER.captures(s).ok_or(InvalidEnvironmentIdError)?;
1400        Ok(EnvironmentId {
1401            cloud_provider: CloudProvider::from_str(&captures["cloud_provider"])?,
1402            cloud_provider_region: captures["cloud_provider_region"].into(),
1403            organization_id: captures["organization_id"]
1404                .parse()
1405                .map_err(|_| InvalidEnvironmentIdError)?,
1406            ordinal: captures["ordinal"]
1407                .parse()
1408                .map_err(|_| InvalidEnvironmentIdError)?,
1409        })
1410    }
1411}
1412
1413/// The error type for [`EnvironmentId::from_str`].
1414#[derive(Debug, Clone, PartialEq)]
1415pub struct InvalidEnvironmentIdError;
1416
1417impl fmt::Display for InvalidEnvironmentIdError {
1418    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1419        f.write_str("invalid environment ID")
1420    }
1421}
1422
1423impl Error for InvalidEnvironmentIdError {}
1424
1425impl From<InvalidCloudProviderError> for InvalidEnvironmentIdError {
1426    fn from(_: InvalidCloudProviderError) -> Self {
1427        InvalidEnvironmentIdError
1428    }
1429}
1430
1431/// An error returned by the catalog.
1432#[derive(Clone, Debug, Eq, PartialEq)]
1433pub enum CatalogError {
1434    /// Unknown database.
1435    UnknownDatabase(String),
1436    /// Database already exists.
1437    DatabaseAlreadyExists(String),
1438    /// Unknown schema.
1439    UnknownSchema(String),
1440    /// Schema already exists.
1441    SchemaAlreadyExists(String),
1442    /// Unknown role.
1443    UnknownRole(String),
1444    /// Role already exists.
1445    RoleAlreadyExists(String),
1446    /// Network Policy already exists.
1447    NetworkPolicyAlreadyExists(String),
1448    /// A query policy with this name already exists.
1449    QueryPolicyAlreadyExists(String),
1450    /// The named or identified query policy does not exist.
1451    UnknownQueryPolicy(String),
1452    /// A query policy cannot be removed while attached to a cluster.
1453    QueryPolicyInUse(String),
1454    /// Unknown cluster.
1455    UnknownCluster(String),
1456    /// Unexpected builtin cluster.
1457    UnexpectedBuiltinCluster(String),
1458    /// Unexpected builtin cluster.
1459    UnexpectedBuiltinClusterType(String),
1460    /// Cluster already exists.
1461    ClusterAlreadyExists(String),
1462    /// Unknown cluster replica.
1463    UnknownClusterReplica(String),
1464    /// Unknown cluster replica size.
1465    UnknownClusterReplicaSize(String),
1466    /// Duplicate Replica. #[error("cannot create multiple replicas named '{0}' on cluster '{1}'")]
1467    DuplicateReplica(String, String),
1468    /// Unknown item.
1469    UnknownItem(String),
1470    /// Item already exists.
1471    ItemAlreadyExists(CatalogItemId, String),
1472    /// Unknown function.
1473    UnknownFunction {
1474        /// The identifier of the function we couldn't find
1475        name: String,
1476        /// A suggested alternative to the named function.
1477        alternative: Option<String>,
1478    },
1479    /// Unknown type.
1480    UnknownType {
1481        /// The identifier of the type we couldn't find.
1482        name: String,
1483    },
1484    /// Unknown connection.
1485    UnknownConnection(String),
1486    /// Unknown network policy.
1487    UnknownNetworkPolicy(String),
1488    /// Expected the catalog item to have the given type, but it did not.
1489    UnexpectedType {
1490        /// The item's name.
1491        name: String,
1492        /// The actual type of the item.
1493        actual_type: CatalogItemType,
1494        /// The expected type of the item.
1495        expected_type: CatalogItemType,
1496    },
1497    /// Ran out of unique IDs.
1498    IdExhaustion,
1499    /// Ran out of unique OIDs.
1500    OidExhaustion,
1501    /// Timeline already exists.
1502    TimelineAlreadyExists(String),
1503    /// Id Allocator already exists.
1504    IdAllocatorAlreadyExists(String),
1505    /// Config already exists.
1506    ConfigAlreadyExists(String),
1507    /// Builtin migrations failed.
1508    FailedBuiltinSchemaMigration(String),
1509    /// StorageCollectionMetadata already exists.
1510    StorageCollectionMetadataAlreadyExists(GlobalId),
1511}
1512
1513impl fmt::Display for CatalogError {
1514    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1515        match self {
1516            Self::UnknownDatabase(name) => write!(f, "unknown database '{}'", name),
1517            Self::DatabaseAlreadyExists(name) => write!(f, "database '{name}' already exists"),
1518            Self::UnknownFunction { name, .. } => write!(f, "function \"{}\" does not exist", name),
1519            Self::UnknownType { name, .. } => write!(f, "type \"{}\" does not exist", name),
1520            Self::UnknownConnection(name) => write!(f, "connection \"{}\" does not exist", name),
1521            Self::UnknownSchema(name) => write!(f, "unknown schema '{}'", name),
1522            Self::SchemaAlreadyExists(name) => write!(f, "schema '{name}' already exists"),
1523            Self::UnknownRole(name) => write!(f, "unknown role '{}'", name),
1524            Self::RoleAlreadyExists(name) => write!(f, "role '{name}' already exists"),
1525            Self::NetworkPolicyAlreadyExists(name) => {
1526                write!(f, "network policy '{name}' already exists")
1527            }
1528            Self::QueryPolicyAlreadyExists(name) => {
1529                write!(f, "query policy '{name}' already exists")
1530            }
1531            Self::UnknownQueryPolicy(name) => write!(f, "unknown query policy '{name}'"),
1532            Self::QueryPolicyInUse(name) => {
1533                write!(f, "query policy '{name}' is attached to a cluster")
1534            }
1535            Self::UnknownCluster(name) => write!(f, "unknown cluster '{}'", name),
1536            Self::UnknownNetworkPolicy(name) => write!(f, "unknown network policy '{}'", name),
1537            Self::UnexpectedBuiltinCluster(name) => {
1538                write!(f, "Unexpected builtin cluster '{}'", name)
1539            }
1540            Self::UnexpectedBuiltinClusterType(name) => {
1541                write!(f, "Unexpected builtin cluster type'{}'", name)
1542            }
1543            Self::ClusterAlreadyExists(name) => write!(f, "cluster '{name}' already exists"),
1544            Self::UnknownClusterReplica(name) => {
1545                write!(f, "unknown cluster replica '{}'", name)
1546            }
1547            Self::UnknownClusterReplicaSize(name) => {
1548                write!(f, "unknown cluster replica size '{}'", name)
1549            }
1550            Self::DuplicateReplica(replica_name, cluster_name) => write!(
1551                f,
1552                "cannot create multiple replicas named '{replica_name}' on cluster '{cluster_name}'"
1553            ),
1554            Self::UnknownItem(name) => write!(f, "unknown catalog item '{}'", name),
1555            Self::ItemAlreadyExists(_gid, name) => {
1556                write!(f, "catalog item '{name}' already exists")
1557            }
1558            Self::UnexpectedType {
1559                name,
1560                actual_type,
1561                expected_type,
1562            } => {
1563                write!(f, "\"{name}\" is a {actual_type} not a {expected_type}")
1564            }
1565            Self::IdExhaustion => write!(f, "id counter overflows i64"),
1566            Self::OidExhaustion => write!(f, "oid counter overflows u32"),
1567            Self::TimelineAlreadyExists(name) => write!(f, "timeline '{name}' already exists"),
1568            Self::IdAllocatorAlreadyExists(name) => {
1569                write!(f, "ID allocator '{name}' already exists")
1570            }
1571            Self::ConfigAlreadyExists(key) => write!(f, "config '{key}' already exists"),
1572            Self::FailedBuiltinSchemaMigration(objects) => {
1573                write!(f, "failed to migrate schema of builtin objects: {objects}")
1574            }
1575            Self::StorageCollectionMetadataAlreadyExists(key) => {
1576                write!(f, "storage metadata for '{key}' already exists")
1577            }
1578        }
1579    }
1580}
1581
1582impl CatalogError {
1583    /// Returns any applicable hints for [`CatalogError`].
1584    pub fn hint(&self) -> Option<String> {
1585        match self {
1586            CatalogError::UnknownFunction { alternative, .. } => {
1587                match alternative {
1588                    None => Some("No function matches the given name and argument types. You might need to add explicit type casts.".into()),
1589                    Some(alt) => Some(format!("Try using {alt}")),
1590                }
1591            }
1592            _ => None,
1593        }
1594    }
1595}
1596
1597impl Error for CatalogError {}
1598
1599// Enum variant docs would be useless here.
1600#[allow(missing_docs)]
1601#[derive(
1602    Debug,
1603    Clone,
1604    PartialOrd,
1605    Ord,
1606    PartialEq,
1607    Eq,
1608    Hash,
1609    Copy,
1610    Deserialize,
1611    Serialize
1612)]
1613/// The types of objects stored in the catalog.
1614pub enum ObjectType {
1615    Table,
1616    View,
1617    MaterializedView,
1618    Source,
1619    Sink,
1620    MetricSink,
1621    Index,
1622    Type,
1623    Role,
1624    Cluster,
1625    ClusterReplica,
1626    Secret,
1627    Connection,
1628    Database,
1629    Schema,
1630    Func,
1631    NetworkPolicy,
1632    QueryPolicy,
1633}
1634
1635impl ObjectType {
1636    /// Reports if the object type can be treated as a relation.
1637    pub fn is_relation(&self) -> bool {
1638        match self {
1639            ObjectType::Table
1640            | ObjectType::View
1641            | ObjectType::MaterializedView
1642            | ObjectType::Source => true,
1643            ObjectType::Sink
1644            | ObjectType::MetricSink
1645            | ObjectType::Index
1646            | ObjectType::Type
1647            | ObjectType::Secret
1648            | ObjectType::Connection
1649            | ObjectType::Func
1650            | ObjectType::Database
1651            | ObjectType::Schema
1652            | ObjectType::Cluster
1653            | ObjectType::ClusterReplica
1654            | ObjectType::Role
1655            | ObjectType::NetworkPolicy
1656            | ObjectType::QueryPolicy => false,
1657        }
1658    }
1659}
1660
1661impl From<mz_sql_parser::ast::ObjectType> for ObjectType {
1662    fn from(value: mz_sql_parser::ast::ObjectType) -> Self {
1663        match value {
1664            mz_sql_parser::ast::ObjectType::Table => ObjectType::Table,
1665            mz_sql_parser::ast::ObjectType::View => ObjectType::View,
1666            mz_sql_parser::ast::ObjectType::MaterializedView => ObjectType::MaterializedView,
1667            mz_sql_parser::ast::ObjectType::Source => ObjectType::Source,
1668            mz_sql_parser::ast::ObjectType::Subsource => ObjectType::Source,
1669            mz_sql_parser::ast::ObjectType::Sink => ObjectType::Sink,
1670            mz_sql_parser::ast::ObjectType::MetricSink => ObjectType::MetricSink,
1671            mz_sql_parser::ast::ObjectType::Index => ObjectType::Index,
1672            mz_sql_parser::ast::ObjectType::Type => ObjectType::Type,
1673            mz_sql_parser::ast::ObjectType::Role => ObjectType::Role,
1674            mz_sql_parser::ast::ObjectType::Cluster => ObjectType::Cluster,
1675            mz_sql_parser::ast::ObjectType::ClusterReplica => ObjectType::ClusterReplica,
1676            mz_sql_parser::ast::ObjectType::Secret => ObjectType::Secret,
1677            mz_sql_parser::ast::ObjectType::Connection => ObjectType::Connection,
1678            mz_sql_parser::ast::ObjectType::Database => ObjectType::Database,
1679            mz_sql_parser::ast::ObjectType::Schema => ObjectType::Schema,
1680            mz_sql_parser::ast::ObjectType::Func => ObjectType::Func,
1681            mz_sql_parser::ast::ObjectType::NetworkPolicy => ObjectType::NetworkPolicy,
1682            mz_sql_parser::ast::ObjectType::QueryPolicy => ObjectType::QueryPolicy,
1683        }
1684    }
1685}
1686
1687impl From<CommentObjectId> for ObjectType {
1688    fn from(value: CommentObjectId) -> ObjectType {
1689        match value {
1690            CommentObjectId::Table(_) => ObjectType::Table,
1691            CommentObjectId::View(_) => ObjectType::View,
1692            CommentObjectId::MaterializedView(_) => ObjectType::MaterializedView,
1693            CommentObjectId::Source(_) => ObjectType::Source,
1694            CommentObjectId::Sink(_) => ObjectType::Sink,
1695            CommentObjectId::MetricSink(_) => ObjectType::MetricSink,
1696            CommentObjectId::Index(_) => ObjectType::Index,
1697            CommentObjectId::Func(_) => ObjectType::Func,
1698            CommentObjectId::Connection(_) => ObjectType::Connection,
1699            CommentObjectId::Type(_) => ObjectType::Type,
1700            CommentObjectId::Secret(_) => ObjectType::Secret,
1701            CommentObjectId::Role(_) => ObjectType::Role,
1702            CommentObjectId::Database(_) => ObjectType::Database,
1703            CommentObjectId::Schema(_) => ObjectType::Schema,
1704            CommentObjectId::Cluster(_) => ObjectType::Cluster,
1705            CommentObjectId::ClusterReplica(_) => ObjectType::ClusterReplica,
1706            CommentObjectId::NetworkPolicy(_) => ObjectType::NetworkPolicy,
1707            CommentObjectId::QueryPolicy(_) => ObjectType::QueryPolicy,
1708        }
1709    }
1710}
1711
1712impl Display for ObjectType {
1713    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1714        f.write_str(match self {
1715            ObjectType::Table => "TABLE",
1716            ObjectType::View => "VIEW",
1717            ObjectType::MaterializedView => "MATERIALIZED VIEW",
1718            ObjectType::Source => "SOURCE",
1719            ObjectType::Sink => "SINK",
1720            ObjectType::MetricSink => "METRIC SINK",
1721            ObjectType::Index => "INDEX",
1722            ObjectType::Type => "TYPE",
1723            ObjectType::Role => "ROLE",
1724            ObjectType::Cluster => "CLUSTER",
1725            ObjectType::ClusterReplica => "CLUSTER REPLICA",
1726            ObjectType::Secret => "SECRET",
1727            ObjectType::Connection => "CONNECTION",
1728            ObjectType::Database => "DATABASE",
1729            ObjectType::Schema => "SCHEMA",
1730            ObjectType::Func => "FUNCTION",
1731            ObjectType::NetworkPolicy => "NETWORK POLICY",
1732            ObjectType::QueryPolicy => "QUERY POLICY",
1733        })
1734    }
1735}
1736
1737#[derive(
1738    Debug,
1739    Clone,
1740    PartialOrd,
1741    Ord,
1742    PartialEq,
1743    Eq,
1744    Hash,
1745    Copy,
1746    Deserialize,
1747    Serialize
1748)]
1749/// The types of objects in the system.
1750pub enum SystemObjectType {
1751    /// Catalog object type.
1752    Object(ObjectType),
1753    /// Entire system.
1754    System,
1755}
1756
1757impl SystemObjectType {
1758    /// Reports if the object type can be treated as a relation.
1759    pub fn is_relation(&self) -> bool {
1760        match self {
1761            SystemObjectType::Object(object_type) => object_type.is_relation(),
1762            SystemObjectType::System => false,
1763        }
1764    }
1765}
1766
1767impl Display for SystemObjectType {
1768    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1769        match self {
1770            SystemObjectType::Object(object_type) => std::fmt::Display::fmt(&object_type, f),
1771            SystemObjectType::System => f.write_str("SYSTEM"),
1772        }
1773    }
1774}
1775
1776/// Enum used to format object names in error messages.
1777#[derive(Debug, Clone, PartialEq, Eq)]
1778pub enum ErrorMessageObjectDescription {
1779    /// The name of a specific object.
1780    Object {
1781        /// Type of object.
1782        object_type: ObjectType,
1783        /// Name of object.
1784        object_name: Option<String>,
1785    },
1786    /// The name of the entire system.
1787    System,
1788}
1789
1790impl ErrorMessageObjectDescription {
1791    /// Generate a new [`ErrorMessageObjectDescription`] from an [`ObjectId`].
1792    pub fn from_id(
1793        object_id: &ObjectId,
1794        catalog: &dyn SessionCatalog,
1795    ) -> ErrorMessageObjectDescription {
1796        let object_name = match object_id {
1797            ObjectId::Cluster(cluster_id) => catalog.get_cluster(*cluster_id).name().to_string(),
1798            ObjectId::ClusterReplica((cluster_id, replica_id)) => catalog
1799                .get_cluster_replica(*cluster_id, *replica_id)
1800                .name()
1801                .to_string(),
1802            ObjectId::Database(database_id) => catalog.get_database(database_id).name().to_string(),
1803            ObjectId::Schema((database_spec, schema_spec)) => {
1804                let name = catalog.get_schema(database_spec, schema_spec).name();
1805                catalog.resolve_full_schema_name(name).to_string()
1806            }
1807            ObjectId::Role(role_id) => catalog.get_role(role_id).name().to_string(),
1808            ObjectId::Item(id) => {
1809                let name = catalog.get_item(id).name();
1810                catalog.resolve_full_name(name).to_string()
1811            }
1812            ObjectId::NetworkPolicy(network_policy_id) => catalog
1813                .get_network_policy(network_policy_id)
1814                .name()
1815                .to_string(),
1816            ObjectId::QueryPolicy(id) => catalog.get_query_policy(id).name().to_string(),
1817        };
1818        ErrorMessageObjectDescription::Object {
1819            object_type: catalog.get_object_type(object_id),
1820            object_name: Some(object_name),
1821        }
1822    }
1823
1824    /// Generate a new [`ErrorMessageObjectDescription`] from a [`SystemObjectId`].
1825    pub fn from_sys_id(
1826        object_id: &SystemObjectId,
1827        catalog: &dyn SessionCatalog,
1828    ) -> ErrorMessageObjectDescription {
1829        match object_id {
1830            SystemObjectId::Object(object_id) => {
1831                ErrorMessageObjectDescription::from_id(object_id, catalog)
1832            }
1833            SystemObjectId::System => ErrorMessageObjectDescription::System,
1834        }
1835    }
1836
1837    /// Generate a new [`ErrorMessageObjectDescription`] from a [`SystemObjectType`].
1838    pub fn from_object_type(object_type: SystemObjectType) -> ErrorMessageObjectDescription {
1839        match object_type {
1840            SystemObjectType::Object(object_type) => ErrorMessageObjectDescription::Object {
1841                object_type,
1842                object_name: None,
1843            },
1844            SystemObjectType::System => ErrorMessageObjectDescription::System,
1845        }
1846    }
1847}
1848
1849impl Display for ErrorMessageObjectDescription {
1850    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1851        match self {
1852            ErrorMessageObjectDescription::Object {
1853                object_type,
1854                object_name,
1855            } => {
1856                let object_name = object_name
1857                    .as_ref()
1858                    .map(|object_name| format!(" {}", object_name.quoted()))
1859                    .unwrap_or_else(|| "".to_string());
1860                write!(f, "{object_type}{object_name}")
1861            }
1862            ErrorMessageObjectDescription::System => f.write_str("SYSTEM"),
1863        }
1864    }
1865}
1866
1867#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
1868// These attributes are needed because the key of a map must be a string. We also
1869// get the added benefit of flattening this struct in it's serialized form.
1870#[serde(into = "BTreeMap<String, RoleId>")]
1871#[serde(try_from = "BTreeMap<String, RoleId>")]
1872/// Represents the grantee and a grantor of a role membership.
1873pub struct RoleMembership {
1874    /// Key is the role that some role is a member of, value is the grantor role ID.
1875    // TODO(jkosh44) This structure does not allow a role to have multiple of the same membership
1876    // from different grantors. This isn't a problem now since we don't implement ADMIN OPTION, but
1877    // we should figure this out before implementing ADMIN OPTION. It will likely require a messy
1878    // migration.
1879    pub map: BTreeMap<RoleId, RoleId>,
1880}
1881
1882impl RoleMembership {
1883    /// Creates a new [`RoleMembership`].
1884    pub fn new() -> RoleMembership {
1885        RoleMembership {
1886            map: BTreeMap::new(),
1887        }
1888    }
1889}
1890
1891impl From<RoleMembership> for BTreeMap<String, RoleId> {
1892    fn from(value: RoleMembership) -> Self {
1893        value
1894            .map
1895            .into_iter()
1896            .map(|(k, v)| (k.to_string(), v))
1897            .collect()
1898    }
1899}
1900
1901impl TryFrom<BTreeMap<String, RoleId>> for RoleMembership {
1902    type Error = anyhow::Error;
1903
1904    fn try_from(value: BTreeMap<String, RoleId>) -> Result<Self, Self::Error> {
1905        Ok(RoleMembership {
1906            map: value
1907                .into_iter()
1908                .map(|(k, v)| Ok((RoleId::from_str(&k)?, v)))
1909                .collect::<Result<_, anyhow::Error>>()?,
1910        })
1911    }
1912}
1913
1914/// Specification for objects that will be affected by a default privilege.
1915#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
1916pub struct DefaultPrivilegeObject {
1917    /// The role id that created the object.
1918    pub role_id: RoleId,
1919    /// The database that the object is created in if Some, otherwise all databases.
1920    pub database_id: Option<DatabaseId>,
1921    /// The schema that the object is created in if Some, otherwise all databases.
1922    pub schema_id: Option<SchemaId>,
1923    /// The type of object.
1924    pub object_type: ObjectType,
1925}
1926
1927impl DefaultPrivilegeObject {
1928    /// Creates a new [`DefaultPrivilegeObject`].
1929    pub fn new(
1930        role_id: RoleId,
1931        database_id: Option<DatabaseId>,
1932        schema_id: Option<SchemaId>,
1933        object_type: ObjectType,
1934    ) -> DefaultPrivilegeObject {
1935        DefaultPrivilegeObject {
1936            role_id,
1937            database_id,
1938            schema_id,
1939            object_type,
1940        }
1941    }
1942}
1943
1944impl std::fmt::Display for DefaultPrivilegeObject {
1945    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1946        // TODO: Don't just wrap Debug.
1947        write!(f, "{self:?}")
1948    }
1949}
1950
1951/// Specification for the privileges that will be granted from default privileges.
1952#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
1953pub struct DefaultPrivilegeAclItem {
1954    /// The role that will receive the privileges.
1955    pub grantee: RoleId,
1956    /// The specific privileges granted.
1957    pub acl_mode: AclMode,
1958}
1959
1960impl DefaultPrivilegeAclItem {
1961    /// Creates a new [`DefaultPrivilegeAclItem`].
1962    pub fn new(grantee: RoleId, acl_mode: AclMode) -> DefaultPrivilegeAclItem {
1963        DefaultPrivilegeAclItem { grantee, acl_mode }
1964    }
1965
1966    /// Converts this [`DefaultPrivilegeAclItem`] into an [`MzAclItem`].
1967    pub fn mz_acl_item(self, grantor: RoleId) -> MzAclItem {
1968        MzAclItem {
1969            grantee: self.grantee,
1970            grantor,
1971            acl_mode: self.acl_mode,
1972        }
1973    }
1974}
1975
1976#[cfg(test)]
1977mod tests {
1978    use super::{CloudProvider, EnvironmentId, InvalidEnvironmentIdError};
1979
1980    #[mz_ore::test]
1981    fn test_environment_id() {
1982        for (input, expected) in [
1983            (
1984                "local-az1-1497a3b7-a455-4fc4-8752-b44a94b5f90a-452",
1985                Ok(EnvironmentId {
1986                    cloud_provider: CloudProvider::Local,
1987                    cloud_provider_region: "az1".into(),
1988                    organization_id: "1497a3b7-a455-4fc4-8752-b44a94b5f90a".parse().unwrap(),
1989                    ordinal: 452,
1990                }),
1991            ),
1992            (
1993                "aws-us-east-1-1497a3b7-a455-4fc4-8752-b44a94b5f90a-0",
1994                Ok(EnvironmentId {
1995                    cloud_provider: CloudProvider::Aws,
1996                    cloud_provider_region: "us-east-1".into(),
1997                    organization_id: "1497a3b7-a455-4fc4-8752-b44a94b5f90a".parse().unwrap(),
1998                    ordinal: 0,
1999                }),
2000            ),
2001            (
2002                "gcp-us-central1-1497a3b7-a455-4fc4-8752-b44a94b5f90a-0",
2003                Ok(EnvironmentId {
2004                    cloud_provider: CloudProvider::Gcp,
2005                    cloud_provider_region: "us-central1".into(),
2006                    organization_id: "1497a3b7-a455-4fc4-8752-b44a94b5f90a".parse().unwrap(),
2007                    ordinal: 0,
2008                }),
2009            ),
2010            (
2011                "azure-australiaeast-1497a3b7-a455-4fc4-8752-b44a94b5f90a-0",
2012                Ok(EnvironmentId {
2013                    cloud_provider: CloudProvider::Azure,
2014                    cloud_provider_region: "australiaeast".into(),
2015                    organization_id: "1497a3b7-a455-4fc4-8752-b44a94b5f90a".parse().unwrap(),
2016                    ordinal: 0,
2017                }),
2018            ),
2019            (
2020                "generic-moon-station-11-darkside-1497a3b7-a455-4fc4-8752-b44a94b5f90a-0",
2021                Ok(EnvironmentId {
2022                    cloud_provider: CloudProvider::Generic,
2023                    cloud_provider_region: "moon-station-11-darkside".into(),
2024                    organization_id: "1497a3b7-a455-4fc4-8752-b44a94b5f90a".parse().unwrap(),
2025                    ordinal: 0,
2026                }),
2027            ),
2028            ("", Err(InvalidEnvironmentIdError)),
2029            (
2030                "local-az1-1497a3b7-a455-4fc4-8752-b44a94b5f90a-123456789",
2031                Err(InvalidEnvironmentIdError),
2032            ),
2033            (
2034                "local-1497a3b7-a455-4fc4-8752-b44a94b5f90a-452",
2035                Err(InvalidEnvironmentIdError),
2036            ),
2037            (
2038                "local-az1-1497a3b7-a455-4fc48752-b44a94b5f90a-452",
2039                Err(InvalidEnvironmentIdError),
2040            ),
2041        ] {
2042            let actual = input.parse();
2043            assert_eq!(expected, actual, "input = {}", input);
2044            if let Ok(actual) = actual {
2045                assert_eq!(input, actual.to_string(), "input = {}", input);
2046            }
2047        }
2048    }
2049}