1#![warn(missing_docs)]
11
12use 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
62pub trait SessionCatalog: fmt::Debug + ExprHumanizer + Send + Sync + ConnectionResolver {
91 fn active_role_id(&self) -> &RoleId;
93
94 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 fn active_database(&self) -> Option<&DatabaseId>;
103
104 fn active_cluster(&self) -> &str;
106
107 fn search_path(&self) -> &[(ResolvedDatabaseSpecifier, SchemaSpecifier)];
109
110 fn get_prepared_statement_desc(&self, name: &str) -> Option<&StatementDesc>;
113
114 fn get_portal_desc_unverified(&self, portal_name: &str) -> Option<&StatementDesc>;
118
119 fn resolve_database(&self, database_name: &str) -> Result<&dyn CatalogDatabase, CatalogError>;
124
125 fn get_database(&self, id: &DatabaseId) -> &dyn CatalogDatabase;
129
130 fn get_databases(&self) -> Vec<&dyn CatalogDatabase>;
132
133 fn resolve_schema(
138 &self,
139 database_name: Option<&str>,
140 schema_name: &str,
141 ) -> Result<&dyn CatalogSchema, CatalogError>;
142
143 fn resolve_schema_in_database(
148 &self,
149 database_spec: &ResolvedDatabaseSpecifier,
150 schema_name: &str,
151 ) -> Result<&dyn CatalogSchema, CatalogError>;
152
153 fn get_schema(
157 &self,
158 database_spec: &ResolvedDatabaseSpecifier,
159 schema_spec: &SchemaSpecifier,
160 ) -> &dyn CatalogSchema;
161
162 fn get_schemas(&self) -> Vec<&dyn CatalogSchema>;
164
165 fn get_mz_internal_schema_id(&self) -> SchemaId;
167
168 fn get_mz_unsafe_schema_id(&self) -> SchemaId;
170
171 fn is_system_schema_specifier(&self, schema: SchemaSpecifier) -> bool;
173
174 fn resolve_role(&self, role_name: &str) -> Result<&dyn CatalogRole, CatalogError>;
176
177 fn resolve_network_policy(
179 &self,
180 network_policy_name: &str,
181 ) -> Result<&dyn CatalogNetworkPolicy, CatalogError>;
182
183 fn resolve_query_policy(&self, name: &str) -> Result<&dyn CatalogQueryPolicy, CatalogError>;
185 fn get_query_policy(&self, id: &QueryPolicyId) -> &dyn CatalogQueryPolicy;
187 fn get_query_policies(&self) -> Vec<&dyn CatalogQueryPolicy>;
189
190 fn try_get_role(&self, id: &RoleId) -> Option<&dyn CatalogRole>;
192
193 fn get_role(&self, id: &RoleId) -> &dyn CatalogRole;
197
198 fn get_roles(&self) -> Vec<&dyn CatalogRole>;
200
201 fn mz_system_role_id(&self) -> RoleId;
203
204 fn collect_role_membership(&self, id: &RoleId) -> BTreeSet<RoleId>;
206
207 fn get_network_policy(&self, id: &NetworkPolicyId) -> &dyn CatalogNetworkPolicy;
212
213 fn get_network_policies(&self) -> Vec<&dyn CatalogNetworkPolicy>;
215
216 fn resolve_cluster<'a, 'b>(
219 &'a self,
220 cluster_name: Option<&'b str>,
221 ) -> Result<&'a dyn CatalogCluster<'a>, CatalogError>;
222
223 fn resolve_cluster_replica<'a, 'b>(
225 &'a self,
226 cluster_replica_name: &'b QualifiedReplica,
227 ) -> Result<&'a dyn CatalogClusterReplica<'a>, CatalogError>;
228
229 fn resolve_item(&self, item_name: &PartialItemName) -> Result<&dyn CatalogItem, CatalogError>;
244
245 fn resolve_function(
248 &self,
249 item_name: &PartialItemName,
250 ) -> Result<&dyn CatalogItem, CatalogError>;
251
252 fn resolve_type(&self, item_name: &PartialItemName) -> Result<&dyn CatalogItem, CatalogError>;
255
256 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 fn get_system_type(&self, name: &str) -> &dyn CatalogItem;
273
274 fn try_get_item(&self, id: &CatalogItemId) -> Option<&dyn CatalogItem>;
276
277 fn try_get_item_by_global_id<'a>(
282 &'a self,
283 id: &GlobalId,
284 ) -> Option<Box<dyn CatalogCollectionItem + 'a>>;
285
286 fn get_item(&self, id: &CatalogItemId) -> &dyn CatalogItem;
290
291 fn get_item_by_global_id<'a>(&'a self, id: &GlobalId) -> Box<dyn CatalogCollectionItem + 'a>;
297
298 fn get_items(&self) -> Vec<&dyn CatalogItem>;
300
301 fn get_item_by_name(&self, name: &QualifiedItemName) -> Option<&dyn CatalogItem>;
303
304 fn get_type_by_name(&self, name: &QualifiedItemName) -> Option<&dyn CatalogItem>;
306
307 fn get_cluster(&self, id: ClusterId) -> &dyn CatalogCluster<'_>;
309
310 fn get_clusters(&self) -> Vec<&dyn CatalogCluster<'_>>;
312
313 fn get_cluster_replica(
315 &self,
316 cluster_id: ClusterId,
317 replica_id: ReplicaId,
318 ) -> &dyn CatalogClusterReplica<'_>;
319
320 fn get_cluster_replicas(&self) -> Vec<&dyn CatalogClusterReplica<'_>>;
322
323 fn get_system_privileges(&self) -> &PrivilegeMap;
325
326 fn get_default_privileges(
328 &self,
329 ) -> Vec<(&DefaultPrivilegeObject, Vec<&DefaultPrivilegeAclItem>)>;
330
331 fn find_available_name(&self, name: QualifiedItemName) -> QualifiedItemName;
335
336 fn resolve_full_name(&self, name: &QualifiedItemName) -> FullItemName;
338
339 fn resolve_full_schema_name(&self, name: &QualifiedSchemaName) -> FullSchemaName;
342
343 fn resolve_item_id(&self, global_id: &GlobalId) -> CatalogItemId;
345
346 fn resolve_global_id(
348 &self,
349 item_id: &CatalogItemId,
350 version: RelationVersionSelector,
351 ) -> GlobalId;
352
353 fn config(&self) -> &CatalogConfig;
355
356 fn now(&self) -> EpochMillis;
360
361 fn aws_privatelink_availability_zones(&self) -> Option<BTreeSet<String>>;
363
364 fn restrict_to_user_objects(&self) -> bool {
369 false
370 }
371
372 fn system_vars(&self) -> &SystemVars;
374
375 fn system_vars_mut(&mut self) -> &mut SystemVars;
382
383 fn get_owner_id(&self, id: &ObjectId) -> Option<RoleId>;
385
386 fn get_privileges(&self, id: &SystemObjectId) -> Option<&PrivilegeMap>;
388
389 fn object_dependents(&self, ids: &Vec<ObjectId>) -> Vec<ObjectId>;
395
396 fn item_dependents(&self, id: CatalogItemId) -> Vec<ObjectId>;
402
403 fn all_object_privileges(&self, object_type: SystemObjectType) -> AclMode;
405
406 fn get_object_type(&self, object_id: &ObjectId) -> ObjectType;
408
409 fn get_system_object_type(&self, id: &SystemObjectId) -> SystemObjectType;
411
412 fn minimal_qualification(&self, qualified_name: &QualifiedItemName) -> PartialItemName;
415
416 fn add_notice(&self, notice: PlanNotice);
419
420 fn get_item_comments(&self, id: &CatalogItemId) -> Option<&BTreeMap<Option<usize>, String>>;
422
423 fn is_cluster_size_cc(&self, size: &str) -> bool;
426}
427
428#[derive(Debug, Clone)]
430pub struct CatalogConfig {
431 pub start_time: DateTime<Utc>,
433 pub start_instant: Instant,
435 pub nonce: u64,
440 pub environment_id: EnvironmentId,
442 pub session_id: Uuid,
444 pub build_info: &'static BuildInfo,
446 pub now: NowFn,
449 pub connection_context: ConnectionContext,
451 pub aws_account_id: Option<String>,
460 pub helm_chart_version: Option<String>,
462}
463
464pub trait CatalogDatabase {
466 fn name(&self) -> &str;
468
469 fn id(&self) -> DatabaseId;
471
472 fn has_schemas(&self) -> bool;
474
475 fn schema_ids(&self) -> &BTreeMap<String, SchemaId>;
478
479 fn schemas(&self) -> Vec<&dyn CatalogSchema>;
481
482 fn owner_id(&self) -> RoleId;
484
485 fn privileges(&self) -> &PrivilegeMap;
487}
488
489pub trait CatalogSchema {
491 fn database(&self) -> &ResolvedDatabaseSpecifier;
493
494 fn name(&self) -> &QualifiedSchemaName;
496
497 fn id(&self) -> &SchemaSpecifier;
499
500 fn has_items(&self) -> bool;
502
503 fn item_ids(&self) -> Box<dyn Iterator<Item = CatalogItemId> + '_>;
505
506 fn owner_id(&self) -> RoleId;
508
509 fn privileges(&self) -> &PrivilegeMap;
511}
512
513#[derive(Debug, Clone, Eq, PartialEq, Arbitrary)]
515pub struct PasswordConfig {
516 pub password: Password,
518 pub scram_iterations: NonZeroU32,
520}
521
522#[derive(Debug, Clone, Eq, PartialEq, Arbitrary)]
524pub enum PasswordAction {
525 Set(PasswordConfig),
527 Clear,
529 NoChange,
531}
532
533#[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 Oidc,
549 Frontegg,
551 None,
553}
554
555#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Arbitrary)]
560pub struct RoleAttributesRaw {
561 pub inherit: bool,
563 pub password: Option<Password>,
565 pub scram_iterations: Option<NonZeroU32>,
567 pub superuser: Option<bool>,
569 pub login: Option<bool>,
571 pub auto_provision_source: Option<AutoProvisionSource>,
573 _private: (),
575}
576
577#[derive(
579 Debug,
580 Clone,
581 Eq,
582 Serialize,
583 Deserialize,
584 PartialEq,
585 Ord,
586 PartialOrd,
587 Arbitrary
588)]
589pub struct RoleAttributes {
590 pub inherit: bool,
592 pub superuser: Option<bool>,
594 pub login: Option<bool>,
596 pub auto_provision_source: Option<AutoProvisionSource>,
598 _private: (),
600}
601
602impl RoleAttributesRaw {
603 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 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 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 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 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#[derive(Default, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
719pub struct RoleVars {
720 pub map: BTreeMap<String, OwnedVarInput>,
722}
723
724pub trait CatalogRole {
726 fn name(&self) -> &str;
728
729 fn id(&self) -> RoleId;
731
732 fn membership(&self) -> &BTreeMap<RoleId, RoleId>;
737
738 fn attributes(&self) -> &RoleAttributes;
740
741 fn vars(&self) -> &BTreeMap<String, OwnedVarInput>;
743}
744
745pub trait CatalogQueryPolicy {
747 fn name(&self) -> &str;
749 fn id(&self) -> QueryPolicyId;
751 fn owner_id(&self) -> RoleId;
753 fn privileges(&self) -> &PrivilegeMap;
755 fn mode(&self) -> crate::plan::QueryPolicyMode;
757 fn rules(&self) -> &[crate::plan::QueryPolicyRule];
759}
760
761pub trait CatalogNetworkPolicy {
763 fn name(&self) -> &str;
765
766 fn id(&self) -> NetworkPolicyId;
768
769 fn owner_id(&self) -> RoleId;
771
772 fn privileges(&self) -> &PrivilegeMap;
774}
775
776pub trait CatalogCluster<'a> {
778 fn name(&self) -> &str;
780
781 fn id(&self) -> ClusterId;
783
784 fn bound_objects(&self) -> &BTreeSet<CatalogItemId>;
786
787 fn replica_ids(&self) -> &BTreeMap<String, ReplicaId>;
790
791 fn replicas(&self) -> Vec<&dyn CatalogClusterReplica<'_>>;
793
794 fn replica(&self, id: ReplicaId) -> &dyn CatalogClusterReplica<'_>;
796
797 fn owner_id(&self) -> RoleId;
799
800 fn privileges(&self) -> &PrivilegeMap;
802
803 fn is_managed(&self) -> bool;
805
806 fn managed_size(&self) -> Option<&str>;
808
809 fn schedule(&self) -> Option<&ClusterSchedule>;
811
812 fn replication_factor(&self) -> Option<u32>;
814
815 fn auto_scaling_strategy(&self) -> Option<&AutoScalingStrategy>;
818 fn try_to_plan(&self) -> Result<CreateClusterPlan, PlanError>;
821}
822
823pub trait CatalogClusterReplica<'a>: Debug {
825 fn name(&self) -> &str;
827
828 fn cluster_id(&self) -> ClusterId;
830
831 fn replica_id(&self) -> ReplicaId;
833
834 fn owner_id(&self) -> RoleId;
836
837 fn internal(&self) -> bool;
839}
840
841pub trait CatalogItem {
846 fn name(&self) -> &QualifiedItemName;
848
849 fn id(&self) -> CatalogItemId;
851
852 fn global_ids(&self) -> Box<dyn Iterator<Item = GlobalId> + '_>;
854
855 fn oid(&self) -> u32;
857
858 fn func(&self) -> Result<&'static Func, CatalogError>;
863
864 fn source_desc(&self) -> Result<Option<&SourceDesc<ReferencedConnection>>, CatalogError>;
869
870 fn connection(&self) -> Result<Connection<ReferencedConnection>, CatalogError>;
874
875 fn item_type(&self) -> CatalogItemType;
877
878 fn create_sql(&self) -> &str;
881
882 fn references(&self) -> &ResolvedIds;
885
886 fn uses(&self) -> BTreeSet<CatalogItemId>;
889
890 fn referenced_by(&self) -> &[CatalogItemId];
892
893 fn used_by(&self) -> &[CatalogItemId];
895
896 fn subsource_details(
899 &self,
900 ) -> Option<(CatalogItemId, &UnresolvedItemName, &SourceExportDetails)>;
901
902 fn source_export_details(
905 &self,
906 ) -> Option<(
907 CatalogItemId,
908 &UnresolvedItemName,
909 &SourceExportDetails,
910 &SourceExportDataConfig<ReferencedConnection>,
911 )>;
912
913 fn is_progress_source(&self) -> bool;
915
916 fn progress_id(&self) -> Option<CatalogItemId>;
918
919 fn index_details(&self) -> Option<(&[MirScalarExpr], GlobalId)>;
922
923 fn writable_table_details(&self) -> Option<&[Expr<Aug>]>;
926
927 fn replacement_target(&self) -> Option<CatalogItemId>;
929
930 fn type_details(&self) -> Option<&CatalogTypeDetails<IdReference>>;
933
934 fn owner_id(&self) -> RoleId;
936
937 fn privileges(&self) -> &PrivilegeMap;
939
940 fn cluster_id(&self) -> Option<ClusterId>;
942
943 fn at_version(&self, version: RelationVersionSelector) -> Box<dyn CatalogCollectionItem>;
946
947 fn latest_version(&self) -> Option<RelationVersion>;
949}
950
951pub trait CatalogCollectionItem: CatalogItem + Send + Sync {
954 fn relation_desc(&self) -> Option<Cow<'_, RelationDesc>>;
959
960 fn global_id(&self) -> GlobalId;
962}
963
964#[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 Table,
980 Source,
982 Sink,
984 View,
986 MaterializedView,
988 Index,
990 Type,
992 Func,
994 Secret,
996 Connection,
998 MetricSink,
1000}
1001
1002impl CatalogItemType {
1003 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#[derive(Clone, Debug, Eq, PartialEq)]
1094pub struct CatalogTypeDetails<T: TypeReference> {
1095 pub array_id: Option<CatalogItemId>,
1097 pub typ: CatalogType<T>,
1099 pub pg_metadata: Option<CatalogTypePgMetadata>,
1101}
1102
1103#[derive(Clone, Debug, Eq, PartialEq)]
1105pub struct CatalogTypePgMetadata {
1106 pub typinput_oid: u32,
1108 pub typreceive_oid: u32,
1110 pub typsend_oid: u32,
1112}
1113
1114pub trait TypeReference {
1116 type Reference: Clone + Debug + Eq + PartialEq;
1118}
1119
1120#[derive(Clone, Debug, Eq, PartialEq)]
1122pub struct NameReference;
1123
1124impl TypeReference for NameReference {
1125 type Reference = &'static str;
1126}
1127
1128#[derive(Clone, Debug, Eq, PartialEq)]
1130pub struct IdReference;
1131
1132impl TypeReference for IdReference {
1133 type Reference = CatalogItemId;
1134}
1135
1136#[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 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 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 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#[derive(Clone, Debug, Eq, PartialEq)]
1226pub struct CatalogRecordField<T: TypeReference> {
1227 pub name: ColumnName,
1229 pub type_reference: T::Reference,
1231 pub type_modifiers: Vec<i64>,
1233}
1234
1235#[derive(Clone, Debug, Eq, PartialEq)]
1236pub enum TypeCategory {
1244 Array,
1246 BitString,
1248 Boolean,
1250 Composite,
1252 DateTime,
1254 Enum,
1256 Geometric,
1258 List,
1260 NetworkAddress,
1262 Numeric,
1264 Pseudo,
1266 Range,
1268 String,
1270 Timespan,
1272 UserDefined,
1274 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#[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 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 pub fn cloud_provider(&self) -> &CloudProvider {
1345 &self.cloud_provider
1346 }
1347
1348 pub fn cloud_provider_region(&self) -> &str {
1350 &self.cloud_provider_region
1351 }
1352
1353 pub fn region(&self) -> String {
1358 format!("{}/{}", self.cloud_provider, self.cloud_provider_region)
1359 }
1360
1361 pub fn organization_id(&self) -> Uuid {
1363 self.organization_id
1364 }
1365
1366 pub fn ordinal(&self) -> u64 {
1368 self.ordinal
1369 }
1370}
1371
1372impl 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#[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#[derive(Clone, Debug, Eq, PartialEq)]
1433pub enum CatalogError {
1434 UnknownDatabase(String),
1436 DatabaseAlreadyExists(String),
1438 UnknownSchema(String),
1440 SchemaAlreadyExists(String),
1442 UnknownRole(String),
1444 RoleAlreadyExists(String),
1446 NetworkPolicyAlreadyExists(String),
1448 QueryPolicyAlreadyExists(String),
1450 UnknownQueryPolicy(String),
1452 QueryPolicyInUse(String),
1454 UnknownCluster(String),
1456 UnexpectedBuiltinCluster(String),
1458 UnexpectedBuiltinClusterType(String),
1460 ClusterAlreadyExists(String),
1462 UnknownClusterReplica(String),
1464 UnknownClusterReplicaSize(String),
1466 DuplicateReplica(String, String),
1468 UnknownItem(String),
1470 ItemAlreadyExists(CatalogItemId, String),
1472 UnknownFunction {
1474 name: String,
1476 alternative: Option<String>,
1478 },
1479 UnknownType {
1481 name: String,
1483 },
1484 UnknownConnection(String),
1486 UnknownNetworkPolicy(String),
1488 UnexpectedType {
1490 name: String,
1492 actual_type: CatalogItemType,
1494 expected_type: CatalogItemType,
1496 },
1497 IdExhaustion,
1499 OidExhaustion,
1501 TimelineAlreadyExists(String),
1503 IdAllocatorAlreadyExists(String),
1505 ConfigAlreadyExists(String),
1507 FailedBuiltinSchemaMigration(String),
1509 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 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#[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)]
1613pub 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 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)]
1749pub enum SystemObjectType {
1751 Object(ObjectType),
1753 System,
1755}
1756
1757impl SystemObjectType {
1758 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#[derive(Debug, Clone, PartialEq, Eq)]
1778pub enum ErrorMessageObjectDescription {
1779 Object {
1781 object_type: ObjectType,
1783 object_name: Option<String>,
1785 },
1786 System,
1788}
1789
1790impl ErrorMessageObjectDescription {
1791 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 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 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#[serde(into = "BTreeMap<String, RoleId>")]
1871#[serde(try_from = "BTreeMap<String, RoleId>")]
1872pub struct RoleMembership {
1874 pub map: BTreeMap<RoleId, RoleId>,
1880}
1881
1882impl RoleMembership {
1883 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#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
1916pub struct DefaultPrivilegeObject {
1917 pub role_id: RoleId,
1919 pub database_id: Option<DatabaseId>,
1921 pub schema_id: Option<SchemaId>,
1923 pub object_type: ObjectType,
1925}
1926
1927impl DefaultPrivilegeObject {
1928 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 write!(f, "{self:?}")
1948 }
1949}
1950
1951#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
1953pub struct DefaultPrivilegeAclItem {
1954 pub grantee: RoleId,
1956 pub acl_mode: AclMode,
1958}
1959
1960impl DefaultPrivilegeAclItem {
1961 pub fn new(grantee: RoleId, acl_mode: AclMode) -> DefaultPrivilegeAclItem {
1963 DefaultPrivilegeAclItem { grantee, acl_mode }
1964 }
1965
1966 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}