1use std::collections::{BTreeMap, BTreeSet, VecDeque};
14use std::fmt::Debug;
15use std::iter;
16use std::str::FromStr;
17use std::sync::Arc;
18
19use differential_dataflow::consolidation::consolidate_updates;
20use futures::future;
21use itertools::{Either, Itertools};
22use mz_adapter_types::connection::ConnectionId;
23use mz_catalog::SYSTEM_CONN_ID;
24use mz_catalog::builtin::{
25 BUILTIN_LOG_LOOKUP, BUILTIN_LOOKUP, Builtin, BuiltinLog, BuiltinTable, BuiltinView,
26};
27use mz_catalog::durable::objects::{
28 ClusterKey, DatabaseKey, DurableType, ItemKey, NetworkPolicyKey, QueryPolicyKey, RoleAuthKey,
29 RoleKey, SchemaKey,
30};
31use mz_catalog::durable::{CatalogError, SystemObjectMapping};
32use mz_catalog::memory::error::{Error, ErrorKind};
33use mz_catalog::memory::objects::{
34 CatalogEntry, CatalogItem, Cluster, ClusterReplica, Database, Func, Index, Log, NetworkPolicy,
35 QueryPolicy, Role, RoleAuth, Schema, Source, StateDiff, StateUpdate, StateUpdateKind, Table,
36 TableDataSource, Type, UpdateFrom,
37};
38use mz_compute_types::config::ComputeReplicaConfig;
39use mz_compute_types::dataflows::DataflowDescription;
40use mz_controller::clusters::{ReplicaConfig, ReplicaLogging};
41use mz_controller_types::ClusterId;
42use mz_expr::MirScalarExpr;
43use mz_ore::collections::CollectionExt;
44use mz_ore::tracing::OpenTelemetryContext;
45use mz_ore::{
46 instrument, soft_assert_eq_or_log, soft_assert_no_log, soft_assert_or_log, soft_panic_or_log,
47};
48use mz_pgrepr::oid::INVALID_OID;
49use mz_repr::adt::mz_acl_item::{MzAclItem, PrivilegeMap};
50use mz_repr::role_id::RoleId;
51use mz_repr::{CatalogItemId, Diff, GlobalId, RelationVersion, Timestamp, VersionedRelationDesc};
52use mz_sql::catalog::CatalogError as SqlCatalogError;
53use mz_sql::catalog::{CatalogItem as SqlCatalogItem, CatalogItemType, CatalogSchema, CatalogType};
54use mz_sql::names::{
55 FullItemName, ItemQualifiers, QualifiedItemName, RawDatabaseSpecifier,
56 ResolvedDatabaseSpecifier, ResolvedIds, SchemaSpecifier,
57};
58use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
59use mz_sql::session::vars::{VarError, VarInput};
60use mz_sql::{plan, rbac};
61use mz_sql_parser::ast::Expr;
62use mz_storage_types::sources::Timeline;
63use mz_transform::dataflow::DataflowMetainfo;
64use mz_transform::notice::OptimizerNotice;
65use tracing::{info_span, warn};
66
67use crate::AdapterError;
68use crate::catalog::state::LocalExpressionCache;
69use crate::catalog::{BuiltinTableUpdate, CatalogState};
70use crate::coord::catalog_implications::parsed_state_updates::{self, ParsedStateUpdate};
71use crate::util::{index_sql, sort_topological};
72
73#[derive(Debug, Clone, Default)]
85struct InProgressRetractions {
86 roles: BTreeMap<RoleKey, Role>,
87 role_auths: BTreeMap<RoleAuthKey, RoleAuth>,
88 databases: BTreeMap<DatabaseKey, Database>,
89 schemas: BTreeMap<SchemaKey, Schema>,
90 clusters: BTreeMap<ClusterKey, Cluster>,
91 network_policies: BTreeMap<NetworkPolicyKey, NetworkPolicy>,
92 query_policies: BTreeMap<QueryPolicyKey, QueryPolicy>,
93 items: BTreeMap<ItemKey, CatalogEntry>,
94 introspection_source_indexes: BTreeMap<CatalogItemId, CatalogEntry>,
95 system_object_mappings: BTreeMap<CatalogItemId, CatalogEntry>,
96}
97
98impl CatalogState {
99 #[must_use]
103 #[instrument]
104 pub(crate) async fn apply_updates(
105 &mut self,
106 updates: Vec<StateUpdate>,
107 local_expression_cache: &mut LocalExpressionCache,
108 ) -> (
109 Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
110 Vec<ParsedStateUpdate>,
111 ) {
112 let mut builtin_table_updates = Vec::with_capacity(updates.len());
113 let mut catalog_updates = Vec::with_capacity(updates.len());
114
115 let updates = Self::consolidate_updates(updates);
120
121 let mut groups: Vec<Vec<_>> = Vec::new();
123 for (_, updates) in &updates.into_iter().chunk_by(|update| update.ts) {
124 let updates = sort_updates(updates.collect());
128 groups.push(updates);
129 }
130
131 for updates in groups {
132 let mut apply_state = ApplyState::Updates(Vec::new());
133 let mut retractions = InProgressRetractions::default();
134
135 for update in updates {
136 let (next_apply_state, (builtin_table_update, catalog_update)) = apply_state
137 .step(
138 ApplyState::new(update),
139 self,
140 &mut retractions,
141 local_expression_cache,
142 )
143 .await;
144 apply_state = next_apply_state;
145 builtin_table_updates.extend(builtin_table_update);
146 catalog_updates.extend(catalog_update);
147 }
148
149 let (builtin_table_update, catalog_update) = apply_state
151 .apply(self, &mut retractions, local_expression_cache)
152 .await;
153 builtin_table_updates.extend(builtin_table_update);
154 catalog_updates.extend(catalog_update);
155
156 let dropped_entries: Vec<CatalogEntry> = retractions.items.into_values().collect();
159 if !dropped_entries.is_empty() {
160 let dropped_notices = self.drop_optimizer_notices(dropped_entries);
161 if self.system_config().enable_mz_notices() {
162 self.pack_optimizer_notice_updates(
163 &mut builtin_table_updates,
164 dropped_notices.iter(),
165 Diff::MINUS_ONE,
166 );
167 }
168 }
169 }
170
171 (builtin_table_updates, catalog_updates)
172 }
173
174 fn consolidate_updates(updates: Vec<StateUpdate>) -> Vec<StateUpdate> {
182 let mut updates: Vec<(StateUpdateKind, Timestamp, mz_repr::Diff)> = updates
183 .into_iter()
184 .map(|update| (update.kind, update.ts, update.diff.into()))
185 .collect_vec();
186
187 consolidate_updates(&mut updates);
188
189 updates
190 .into_iter()
191 .map(|(kind, ts, diff)| StateUpdate {
192 kind,
193 ts,
194 diff: diff
195 .try_into()
196 .expect("catalog state cannot have diff other than -1 or 1"),
197 })
198 .collect_vec()
199 }
200
201 #[instrument(level = "debug")]
202 fn apply_updates_inner(
203 &mut self,
204 updates: Vec<StateUpdate>,
205 retractions: &mut InProgressRetractions,
206 local_expression_cache: &mut LocalExpressionCache,
207 ) -> Result<
208 (
209 Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
210 Vec<ParsedStateUpdate>,
211 ),
212 CatalogError,
213 > {
214 soft_assert_no_log!(
215 updates.iter().map(|update| update.ts).all_equal(),
216 "all timestamps should be equal: {updates:?}"
217 );
218
219 let mut update_system_config = false;
220
221 let mut builtin_table_updates = Vec::with_capacity(updates.len());
222 let mut catalog_updates = Vec::new();
223
224 for state_update in updates {
225 if self.is_nonlocal_ephemeral_item_update(&state_update) {
229 tracing::debug!(
230 ?state_update,
231 "skipping ephemeral item update for non-local session"
232 );
233 continue;
234 }
235
236 if matches!(state_update.kind, StateUpdateKind::SystemConfiguration(_)) {
237 update_system_config = true;
238 }
239
240 match state_update.diff {
241 StateDiff::Retraction => {
242 if let Some(update) =
246 parsed_state_updates::parse_state_update(self, state_update.clone())
247 {
248 catalog_updates.push(update);
249 }
250
251 builtin_table_updates.extend(self.generate_builtin_table_update(
254 state_update.kind.clone(),
255 state_update.diff,
256 ));
257 self.apply_update(
258 state_update.kind,
259 state_update.diff,
260 retractions,
261 local_expression_cache,
262 )?;
263 }
264 StateDiff::Addition => {
265 self.apply_update(
266 state_update.kind.clone(),
267 state_update.diff,
268 retractions,
269 local_expression_cache,
270 )?;
271 builtin_table_updates.extend(self.generate_builtin_table_update(
275 state_update.kind.clone(),
276 state_update.diff,
277 ));
278
279 if let Some(update) =
282 parsed_state_updates::parse_state_update(self, state_update.clone())
283 {
284 catalog_updates.push(update);
285 }
286 }
287 }
288 }
289
290 if update_system_config {
291 self.system_configuration.sync_dyncfgs();
292 }
293
294 Ok((builtin_table_updates, catalog_updates))
295 }
296
297 #[instrument(level = "debug")]
298 fn apply_update(
299 &mut self,
300 kind: StateUpdateKind,
301 diff: StateDiff,
302 retractions: &mut InProgressRetractions,
303 local_expression_cache: &mut LocalExpressionCache,
304 ) -> Result<(), CatalogError> {
305 match kind {
306 StateUpdateKind::Role(role) => {
307 self.apply_role_update(role, diff, retractions);
308 }
309 StateUpdateKind::RoleAuth(role_auth) => {
310 self.apply_role_auth_update(role_auth, diff, retractions);
311 }
312 StateUpdateKind::Database(database) => {
313 self.apply_database_update(database, diff, retractions);
314 }
315 StateUpdateKind::Schema(schema) => {
316 self.apply_schema_update(schema, diff, retractions);
317 }
318 StateUpdateKind::DefaultPrivilege(default_privilege) => {
319 self.apply_default_privilege_update(default_privilege, diff, retractions);
320 }
321 StateUpdateKind::SystemPrivilege(system_privilege) => {
322 self.apply_system_privilege_update(system_privilege, diff, retractions);
323 }
324 StateUpdateKind::SystemConfiguration(system_configuration) => {
325 self.apply_system_configuration_update(system_configuration, diff, retractions);
326 }
327 StateUpdateKind::ClusterSystemConfiguration(cfg) => {
328 Self::apply_scoped_system_configuration_update(
329 &mut self.scoped_system_parameters.cluster,
330 cfg.cluster_id,
331 cfg.name,
332 cfg.value,
333 diff,
334 );
335 }
336 StateUpdateKind::ReplicaSystemConfiguration(cfg) => {
337 Self::apply_scoped_system_configuration_update(
338 &mut self.scoped_system_parameters.replica,
339 cfg.replica_id,
340 cfg.name,
341 cfg.value,
342 diff,
343 );
344 }
345 StateUpdateKind::Cluster(cluster) => {
346 self.apply_cluster_update(cluster, diff, retractions);
347 }
348 StateUpdateKind::NetworkPolicy(network_policy) => {
349 self.apply_network_policy_update(network_policy, diff, retractions);
350 }
351 StateUpdateKind::ClusterReplicaSize(size) => {
352 self.apply_cluster_replica_size_update(size, diff);
353 }
354 StateUpdateKind::QueryPolicy(policy) => {
355 apply_inverted_lookup(
356 &mut self.query_policies_by_name,
357 &policy.name,
358 policy.id,
359 diff,
360 );
361 apply_with_update(
362 &mut self.query_policies_by_id,
363 policy,
364 |policy| policy.id,
365 diff,
366 &mut retractions.query_policies,
367 );
368 }
369 StateUpdateKind::IntrospectionSourceIndex(introspection_source_index) => {
370 self.apply_introspection_source_index_update(
371 introspection_source_index,
372 diff,
373 retractions,
374 );
375 }
376 StateUpdateKind::ClusterReplica(cluster_replica) => {
377 self.apply_cluster_replica_update(cluster_replica, diff, retractions);
378 }
379 StateUpdateKind::SystemObjectMapping(system_object_mapping) => {
380 self.apply_system_object_mapping_update(
381 system_object_mapping,
382 diff,
383 retractions,
384 local_expression_cache,
385 );
386 }
387 StateUpdateKind::Item(item) => {
388 self.apply_item_update(item, diff, retractions, local_expression_cache)?;
389 }
390 StateUpdateKind::Comment(comment) => {
391 self.apply_comment_update(comment, diff, retractions);
392 }
393 StateUpdateKind::SourceReferences(source_reference) => {
394 self.apply_source_references_update(source_reference, diff, retractions);
395 }
396 StateUpdateKind::AuditLog(_audit_log) => {
397 }
399 StateUpdateKind::StorageCollectionMetadata(storage_collection_metadata) => {
400 self.apply_storage_collection_metadata_update(
401 storage_collection_metadata,
402 diff,
403 retractions,
404 );
405 }
406 StateUpdateKind::UnfinalizedShard(unfinalized_shard) => {
407 self.apply_unfinalized_shard_update(unfinalized_shard, diff, retractions);
408 }
409 }
410
411 Ok(())
412 }
413
414 #[instrument(level = "debug")]
415 fn apply_role_auth_update(
416 &mut self,
417 role_auth: mz_catalog::durable::RoleAuth,
418 diff: StateDiff,
419 retractions: &mut InProgressRetractions,
420 ) {
421 apply_with_update(
422 &mut self.role_auth_by_id,
423 role_auth,
424 |role_auth| role_auth.role_id,
425 diff,
426 &mut retractions.role_auths,
427 );
428 }
429
430 #[instrument(level = "debug")]
431 fn apply_role_update(
432 &mut self,
433 role: mz_catalog::durable::Role,
434 diff: StateDiff,
435 retractions: &mut InProgressRetractions,
436 ) {
437 apply_inverted_lookup(&mut self.roles_by_name, &role.name, role.id, diff);
438 apply_with_update(
439 &mut self.roles_by_id,
440 role,
441 |role| role.id,
442 diff,
443 &mut retractions.roles,
444 );
445 }
446
447 #[instrument(level = "debug")]
448 fn apply_database_update(
449 &mut self,
450 database: mz_catalog::durable::Database,
451 diff: StateDiff,
452 retractions: &mut InProgressRetractions,
453 ) {
454 apply_inverted_lookup(
455 &mut self.database_by_name,
456 &database.name,
457 database.id,
458 diff,
459 );
460 apply_with_update(
461 &mut self.database_by_id,
462 database,
463 |database| database.id,
464 diff,
465 &mut retractions.databases,
466 );
467 }
468
469 #[instrument(level = "debug")]
470 fn apply_schema_update(
471 &mut self,
472 schema: mz_catalog::durable::Schema,
473 diff: StateDiff,
474 retractions: &mut InProgressRetractions,
475 ) {
476 match &schema.database_id {
477 Some(database_id) => {
478 let db = self
479 .database_by_id
480 .get_mut(database_id)
481 .expect("catalog out of sync");
482 apply_inverted_lookup(&mut db.schemas_by_name, &schema.name, schema.id, diff);
483 apply_with_update(
484 &mut db.schemas_by_id,
485 schema,
486 |schema| schema.id,
487 diff,
488 &mut retractions.schemas,
489 );
490 }
491 None => {
492 apply_inverted_lookup(
493 &mut self.ambient_schemas_by_name,
494 &schema.name,
495 schema.id,
496 diff,
497 );
498 apply_with_update(
499 &mut self.ambient_schemas_by_id,
500 schema,
501 |schema| schema.id,
502 diff,
503 &mut retractions.schemas,
504 );
505 }
506 }
507 }
508
509 #[instrument(level = "debug")]
510 fn apply_default_privilege_update(
511 &mut self,
512 default_privilege: mz_catalog::durable::DefaultPrivilege,
513 diff: StateDiff,
514 _retractions: &mut InProgressRetractions,
515 ) {
516 match diff {
517 StateDiff::Addition => Arc::make_mut(&mut self.default_privileges)
518 .grant(default_privilege.object, default_privilege.acl_item),
519 StateDiff::Retraction => Arc::make_mut(&mut self.default_privileges)
520 .revoke(&default_privilege.object, &default_privilege.acl_item),
521 }
522 }
523
524 #[instrument(level = "debug")]
525 fn apply_system_privilege_update(
526 &mut self,
527 system_privilege: MzAclItem,
528 diff: StateDiff,
529 _retractions: &mut InProgressRetractions,
530 ) {
531 match diff {
532 StateDiff::Addition => {
533 Arc::make_mut(&mut self.system_privileges).grant(system_privilege)
534 }
535 StateDiff::Retraction => {
536 Arc::make_mut(&mut self.system_privileges).revoke(&system_privilege)
537 }
538 }
539 }
540
541 #[instrument(level = "debug")]
542 fn apply_system_configuration_update(
543 &mut self,
544 system_configuration: mz_catalog::durable::SystemConfiguration,
545 diff: StateDiff,
546 _retractions: &mut InProgressRetractions,
547 ) {
548 let res = match diff {
549 StateDiff::Addition => self.insert_system_configuration(
550 &system_configuration.name,
551 VarInput::Flat(&system_configuration.value),
552 ),
553 StateDiff::Retraction => self.remove_system_configuration(&system_configuration.name),
554 };
555 match res {
556 Ok(_) => (),
557 Err(Error {
561 kind: ErrorKind::VarError(VarError::UnknownParameter(name)),
562 }) => {
563 warn!(%name, "unknown system parameter from catalog storage");
564 }
565 Err(e) => panic!("unable to update system variable: {e:?}"),
566 }
567 }
568
569 fn apply_scoped_system_configuration_update<Id: Ord>(
583 map: &mut BTreeMap<Id, BTreeMap<String, String>>,
584 id: Id,
585 name: String,
586 value: String,
587 diff: StateDiff,
588 ) {
589 match diff {
590 StateDiff::Addition => {
591 map.entry(id).or_default().insert(name, value);
592 }
593 StateDiff::Retraction => {
594 if let Some(values) = map.get_mut(&id) {
595 if values.get(&name) == Some(&value) {
596 values.remove(&name);
597 if values.is_empty() {
598 map.remove(&id);
599 }
600 }
601 }
602 }
603 }
604 }
605
606 #[instrument(level = "debug")]
607 fn apply_cluster_update(
608 &mut self,
609 cluster: mz_catalog::durable::Cluster,
610 diff: StateDiff,
611 retractions: &mut InProgressRetractions,
612 ) {
613 if matches!(diff, StateDiff::Addition) {
620 if let mz_catalog::durable::ClusterVariant::Managed(managed) = &cluster.config.variant {
621 if !self.cluster_replica_sizes.0.contains_key(&managed.size) {
622 soft_panic_or_log!(
623 "managed cluster {} ({}) references unknown replica size {:?}; \
624 mz_clusters.disk will resolve to false",
625 cluster.name,
626 cluster.id,
627 managed.size,
628 );
629 }
630 }
631 }
632 apply_inverted_lookup(&mut self.clusters_by_name, &cluster.name, cluster.id, diff);
633 apply_with_update(
634 &mut self.clusters_by_id,
635 cluster,
636 |cluster| cluster.id,
637 diff,
638 &mut retractions.clusters,
639 );
640 }
641
642 #[instrument(level = "debug")]
643 fn apply_network_policy_update(
644 &mut self,
645 policy: mz_catalog::durable::NetworkPolicy,
646 diff: StateDiff,
647 retractions: &mut InProgressRetractions,
648 ) {
649 apply_inverted_lookup(
650 &mut self.network_policies_by_name,
651 &policy.name,
652 policy.id,
653 diff,
654 );
655 apply_with_update(
656 &mut self.network_policies_by_id,
657 policy,
658 |policy| policy.id,
659 diff,
660 &mut retractions.network_policies,
661 );
662 }
663
664 #[instrument(level = "debug")]
665 fn apply_cluster_replica_size_update(
666 &mut self,
667 size: mz_catalog::durable::ClusterReplicaSize,
668 diff: StateDiff,
669 ) {
670 let sizes = &mut self.cluster_replica_sizes.0;
671 match diff {
672 StateDiff::Addition => {
673 sizes.insert(size.name, size.allocation);
674 }
675 StateDiff::Retraction => {
676 sizes.remove(&size.name);
677 }
678 }
679 }
680
681 #[instrument(level = "debug")]
682 fn apply_introspection_source_index_update(
683 &mut self,
684 introspection_source_index: mz_catalog::durable::IntrospectionSourceIndex,
685 diff: StateDiff,
686 retractions: &mut InProgressRetractions,
687 ) {
688 let cluster = self
689 .clusters_by_id
690 .get_mut(&introspection_source_index.cluster_id)
691 .expect("catalog out of sync");
692 let log = BUILTIN_LOG_LOOKUP
693 .get(introspection_source_index.name.as_str())
694 .expect("missing log");
695 apply_inverted_lookup(
696 &mut cluster.log_indexes,
697 &log.variant,
698 introspection_source_index.index_id,
699 diff,
700 );
701
702 match diff {
703 StateDiff::Addition => {
704 if let Some(mut entry) = retractions
705 .introspection_source_indexes
706 .remove(&introspection_source_index.item_id)
707 {
708 let (index_name, index) = self.create_introspection_source_index(
711 introspection_source_index.cluster_id,
712 log,
713 introspection_source_index.index_id,
714 );
715 assert_eq!(entry.id, introspection_source_index.item_id);
716 assert_eq!(entry.oid, introspection_source_index.oid);
717 assert_eq!(entry.name, index_name);
718 entry.item = index;
719 self.insert_entry(entry);
720 } else {
721 self.insert_introspection_source_index(
722 introspection_source_index.cluster_id,
723 log,
724 introspection_source_index.item_id,
725 introspection_source_index.index_id,
726 introspection_source_index.oid,
727 );
728 }
729 }
730 StateDiff::Retraction => {
731 let entry = self.drop_item(introspection_source_index.item_id);
732 retractions
733 .introspection_source_indexes
734 .insert(entry.id, entry);
735 }
736 }
737 }
738
739 #[instrument(level = "debug")]
740 fn apply_cluster_replica_update(
741 &mut self,
742 cluster_replica: mz_catalog::durable::ClusterReplica,
743 diff: StateDiff,
744 _retractions: &mut InProgressRetractions,
745 ) {
746 let cluster = self
747 .clusters_by_id
748 .get(&cluster_replica.cluster_id)
749 .expect("catalog out of sync");
750
751 if let mz_catalog::durable::ReplicaLocation::Managed { size, .. } =
760 &cluster_replica.config.location
761 {
762 if !self.cluster_replica_sizes.0.contains_key(size) {
763 soft_panic_or_log!(
764 "cluster replica {}.{} ({}) references unknown replica size {:?}; \
765 skipping in-memory registration",
766 cluster.name,
767 cluster_replica.name,
768 cluster_replica.replica_id,
769 size,
770 );
771 return;
772 }
773 }
774
775 let location = self
781 .concretize_replica_location(cluster_replica.config.location, &vec![], None, true)
782 .expect("catalog in unexpected state");
783 let cluster = self
784 .clusters_by_id
785 .get_mut(&cluster_replica.cluster_id)
786 .expect("catalog out of sync");
787 apply_inverted_lookup(
788 &mut cluster.replica_id_by_name_,
789 &cluster_replica.name,
790 cluster_replica.replica_id,
791 diff,
792 );
793 match diff {
794 StateDiff::Retraction => {
795 let prev = cluster.replicas_by_id_.remove(&cluster_replica.replica_id);
796 assert!(
797 prev.is_some(),
798 "retraction does not match existing value: {:?}",
799 cluster_replica.replica_id
800 );
801 }
802 StateDiff::Addition => {
803 let logging = ReplicaLogging {
804 log_logging: cluster_replica.config.logging.log_logging,
805 interval: cluster_replica.config.logging.interval,
806 };
807 let config = ReplicaConfig {
808 location,
809 compute: ComputeReplicaConfig {
810 logging,
811 arrangement_compression: cluster_replica.config.arrangement_compression,
812 },
813 };
814 let mem_cluster_replica = ClusterReplica {
815 name: cluster_replica.name.clone(),
816 cluster_id: cluster_replica.cluster_id,
817 replica_id: cluster_replica.replica_id,
818 config,
819 owner_id: cluster_replica.owner_id,
820 };
821 let prev = cluster
822 .replicas_by_id_
823 .insert(cluster_replica.replica_id, mem_cluster_replica);
824 assert_eq!(
825 prev, None,
826 "values must be explicitly retracted before inserting a new value: {:?}",
827 cluster_replica.replica_id
828 );
829 }
830 }
831 }
832
833 #[instrument(level = "debug")]
834 fn apply_system_object_mapping_update(
835 &mut self,
836 system_object_mapping: mz_catalog::durable::SystemObjectMapping,
837 diff: StateDiff,
838 retractions: &mut InProgressRetractions,
839 local_expression_cache: &mut LocalExpressionCache,
840 ) {
841 let item_id = system_object_mapping.unique_identifier.catalog_id;
842 let global_id = system_object_mapping.unique_identifier.global_id;
843
844 if system_object_mapping.unique_identifier.runtime_alterable() {
845 return;
849 }
850
851 if let StateDiff::Retraction = diff {
852 let entry = self.drop_item(item_id);
853 retractions.system_object_mappings.insert(item_id, entry);
854 return;
855 }
856
857 if let Some(entry) = retractions.system_object_mappings.remove(&item_id) {
858 self.insert_entry(entry);
863 return;
864 }
865
866 let builtin = BUILTIN_LOOKUP
867 .get(&system_object_mapping.description)
868 .expect("missing builtin")
869 .1;
870 let schema_name = builtin.schema();
871 let schema_id = self
872 .ambient_schemas_by_name
873 .get(schema_name)
874 .unwrap_or_else(|| panic!("unknown ambient schema: {schema_name}"));
875 let name = QualifiedItemName {
876 qualifiers: ItemQualifiers {
877 database_spec: ResolvedDatabaseSpecifier::Ambient,
878 schema_spec: SchemaSpecifier::Id(*schema_id),
879 },
880 item: builtin.name().into(),
881 };
882 match builtin {
883 Builtin::Log(log) => {
884 let mut acl_items = vec![rbac::owner_privilege(
885 mz_sql::catalog::ObjectType::Source,
886 MZ_SYSTEM_ROLE_ID,
887 )];
888 acl_items.extend_from_slice(&log.access);
889 self.insert_item(
890 item_id,
891 log.oid,
892 name.clone(),
893 CatalogItem::Log(Log {
894 variant: log.variant,
895 global_id,
896 }),
897 MZ_SYSTEM_ROLE_ID,
898 PrivilegeMap::from_mz_acl_items(acl_items),
899 );
900 }
901
902 Builtin::Table(table) => {
903 let mut acl_items = vec![rbac::owner_privilege(
904 mz_sql::catalog::ObjectType::Table,
905 MZ_SYSTEM_ROLE_ID,
906 )];
907 acl_items.extend_from_slice(&table.access);
908
909 self.insert_item(
910 item_id,
911 table.oid,
912 name.clone(),
913 CatalogItem::Table(Table {
914 create_sql: None,
915 desc: VersionedRelationDesc::new(table.desc.clone()),
916 collections: [(RelationVersion::root(), global_id)].into_iter().collect(),
917 conn_id: None,
918 resolved_ids: ResolvedIds::empty(),
919 custom_logical_compaction_window: table.is_retained_metrics_object.then(
920 || {
921 self.system_config()
922 .metrics_retention()
923 .try_into()
924 .expect("invalid metrics retention")
925 },
926 ),
927 is_retained_metrics_object: table.is_retained_metrics_object,
928 data_source: TableDataSource::TableWrites {
929 defaults: vec![Expr::null(); table.desc.arity()],
930 },
931 }),
932 MZ_SYSTEM_ROLE_ID,
933 PrivilegeMap::from_mz_acl_items(acl_items),
934 );
935 }
936 Builtin::Index(index) => {
937 let custom_logical_compaction_window =
938 index.is_retained_metrics_object.then(|| {
939 self.system_config()
940 .metrics_retention()
941 .try_into()
942 .expect("invalid metrics retention")
943 });
944 let versions = BTreeMap::new();
946
947 let item = self
948 .parse_item(
949 global_id,
950 &index.create_sql(),
951 &versions,
952 None,
953 index.is_retained_metrics_object,
954 custom_logical_compaction_window,
955 local_expression_cache,
956 None,
957 )
958 .unwrap_or_else(|e| {
959 panic!(
960 "internal error: failed to load bootstrap index:\n\
961 {}\n\
962 error:\n\
963 {:?}\n\n\
964 make sure that the schema name is specified in the builtin index's create sql statement.",
965 index.name, e
966 )
967 });
968 let CatalogItem::Index(_) = item else {
969 panic!(
970 "internal error: builtin index {}'s SQL does not begin with \"CREATE INDEX\".",
971 index.name
972 );
973 };
974
975 self.insert_item(
976 item_id,
977 index.oid,
978 name,
979 item,
980 MZ_SYSTEM_ROLE_ID,
981 PrivilegeMap::default(),
982 );
983 }
984 Builtin::View(_) => {
985 unreachable!("views added elsewhere");
987 }
988
989 Builtin::Type(typ) => {
991 let typ = self.resolve_builtin_type_references(typ);
992 if let CatalogType::Array { element_reference } = typ.details.typ {
993 let entry = self.get_entry_mut(&element_reference);
994 let item_type = match &mut entry.item {
995 CatalogItem::Type(item_type) => item_type,
996 _ => unreachable!("types can only reference other types"),
997 };
998 item_type.details.array_id = Some(item_id);
999 }
1000
1001 let schema_id = self.resolve_system_schema(typ.schema);
1002
1003 self.insert_item(
1004 item_id,
1005 typ.oid,
1006 QualifiedItemName {
1007 qualifiers: ItemQualifiers {
1008 database_spec: ResolvedDatabaseSpecifier::Ambient,
1009 schema_spec: SchemaSpecifier::Id(schema_id),
1010 },
1011 item: typ.name.to_owned(),
1012 },
1013 CatalogItem::Type(Type {
1014 create_sql: None,
1015 global_id,
1016 details: typ.details.clone(),
1017 resolved_ids: ResolvedIds::empty(),
1018 }),
1019 MZ_SYSTEM_ROLE_ID,
1020 PrivilegeMap::from_mz_acl_items(vec![
1021 rbac::default_builtin_object_privilege(mz_sql::catalog::ObjectType::Type),
1022 rbac::owner_privilege(mz_sql::catalog::ObjectType::Type, MZ_SYSTEM_ROLE_ID),
1023 ]),
1024 );
1025 }
1026
1027 Builtin::Func(func) => {
1028 let oid = INVALID_OID;
1032 self.insert_item(
1033 item_id,
1034 oid,
1035 name.clone(),
1036 CatalogItem::Func(Func {
1037 inner: func.inner,
1038 global_id,
1039 }),
1040 MZ_SYSTEM_ROLE_ID,
1041 PrivilegeMap::default(),
1042 );
1043 }
1044
1045 Builtin::Source(coll) => {
1046 let mut acl_items = vec![rbac::owner_privilege(
1047 mz_sql::catalog::ObjectType::Source,
1048 MZ_SYSTEM_ROLE_ID,
1049 )];
1050 acl_items.extend_from_slice(&coll.access);
1051
1052 self.insert_item(
1053 item_id,
1054 coll.oid,
1055 name.clone(),
1056 CatalogItem::Source(Source {
1057 create_sql: None,
1058 data_source: coll.data_source.clone(),
1059 desc: coll.desc.clone(),
1060 global_id,
1061 timeline: Timeline::EpochMilliseconds,
1062 resolved_ids: ResolvedIds::empty(),
1063 custom_logical_compaction_window: coll.is_retained_metrics_object.then(
1064 || {
1065 self.system_config()
1066 .metrics_retention()
1067 .try_into()
1068 .expect("invalid metrics retention")
1069 },
1070 ),
1071 is_retained_metrics_object: coll.is_retained_metrics_object,
1072 }),
1073 MZ_SYSTEM_ROLE_ID,
1074 PrivilegeMap::from_mz_acl_items(acl_items),
1075 );
1076 }
1077 Builtin::MaterializedView(mv) => {
1078 let mut acl_items = vec![rbac::owner_privilege(
1079 mz_sql::catalog::ObjectType::MaterializedView,
1080 MZ_SYSTEM_ROLE_ID,
1081 )];
1082 acl_items.extend_from_slice(&mv.access);
1083
1084 let custom_logical_compaction_window = mv.is_retained_metrics_object.then(|| {
1085 self.system_config()
1086 .metrics_retention()
1087 .try_into()
1088 .expect("invalid metrics retention")
1089 });
1090
1091 let versions = BTreeMap::new();
1093
1094 let mut item = self
1095 .parse_item(
1096 global_id,
1097 &mv.create_sql(),
1098 &versions,
1099 None,
1100 mv.is_retained_metrics_object,
1101 custom_logical_compaction_window,
1102 local_expression_cache,
1103 None,
1104 )
1105 .unwrap_or_else(|e| {
1106 panic!(
1107 "internal error: failed to load bootstrap materialized view:\n\
1108 {}\n\
1109 error:\n\
1110 {e:?}\n\n\
1111 make sure that the schema name is specified in the builtin \
1112 materialized view's create sql statement.",
1113 mv.name,
1114 )
1115 });
1116 let CatalogItem::MaterializedView(catalog_mv) = &mut item else {
1117 panic!(
1118 "internal error: builtin materialized view {}'s SQL does not begin \
1119 with \"CREATE MATERIALIZED VIEW\".",
1120 mv.name,
1121 );
1122 };
1123
1124 let mut desc = catalog_mv.desc.latest();
1128 for key in &mv.desc.typ().keys {
1129 desc = desc.with_key(key.clone());
1130 }
1131 catalog_mv.desc = VersionedRelationDesc::new(desc);
1132
1133 self.insert_item(
1134 item_id,
1135 mv.oid,
1136 name,
1137 item,
1138 MZ_SYSTEM_ROLE_ID,
1139 PrivilegeMap::from_mz_acl_items(acl_items),
1140 );
1141 }
1142 Builtin::Connection(connection) => {
1143 let versions = BTreeMap::new();
1145 let mut item = self
1146 .parse_item(
1147 global_id,
1148 connection.sql,
1149 &versions,
1150 None,
1151 false,
1152 None,
1153 local_expression_cache,
1154 None,
1155 )
1156 .unwrap_or_else(|e| {
1157 panic!(
1158 "internal error: failed to load bootstrap connection:\n\
1159 {}\n\
1160 error:\n\
1161 {:?}\n\n\
1162 make sure that the schema name is specified in the builtin connection's create sql statement.",
1163 connection.name, e
1164 )
1165 });
1166 let CatalogItem::Connection(_) = &mut item else {
1167 panic!(
1168 "internal error: builtin connection {}'s SQL does not begin with \"CREATE CONNECTION\".",
1169 connection.name
1170 );
1171 };
1172
1173 let mut acl_items = vec![rbac::owner_privilege(
1174 mz_sql::catalog::ObjectType::Connection,
1175 connection.owner_id.clone(),
1176 )];
1177 acl_items.extend_from_slice(connection.access);
1178
1179 self.insert_item(
1180 item_id,
1181 connection.oid,
1182 name.clone(),
1183 item,
1184 connection.owner_id.clone(),
1185 PrivilegeMap::from_mz_acl_items(acl_items),
1186 );
1187 }
1188 }
1189 }
1190
1191 fn is_nonlocal_ephemeral_item_update(&self, update: &StateUpdate) -> bool {
1194 let StateUpdateKind::Item(item) = &update.kind else {
1195 return false;
1196 };
1197 let Some(owner) = item.ephemeral_owner_session else {
1199 return false;
1200 };
1201 match update.diff {
1202 StateDiff::Addition => !self.temporary_namespaces.contains_uuid(&owner),
1204 StateDiff::Retraction => !self.entry_by_id.contains_key(&item.id),
1207 }
1208 }
1209
1210 #[instrument(level = "debug")]
1211 fn apply_item_update(
1212 &mut self,
1213 item: mz_catalog::durable::Item,
1214 diff: StateDiff,
1215 retractions: &mut InProgressRetractions,
1216 local_expression_cache: &mut LocalExpressionCache,
1217 ) -> Result<(), CatalogError> {
1218 match diff {
1219 StateDiff::Addition => {
1220 let key = item.key();
1221 let mz_catalog::durable::Item {
1222 id,
1223 oid,
1224 global_id,
1225 schema_id,
1226 name,
1227 create_sql,
1228 owner_id,
1229 privileges,
1230 extra_versions,
1231 ephemeral_owner_session,
1232 } = item;
1233
1234 let conn_id = ephemeral_owner_session.map(|owner| {
1241 self.temporary_namespaces
1242 .conn_for_uuid(&owner)
1243 .cloned()
1244 .unwrap_or_else(|| {
1245 panic!("no session record applied for temporary item owner {owner}")
1246 })
1247 });
1248 let name = match &conn_id {
1249 Some(_) => QualifiedItemName {
1250 qualifiers: ItemQualifiers {
1251 database_spec: ResolvedDatabaseSpecifier::Ambient,
1252 schema_spec: SchemaSpecifier::Temporary,
1253 },
1254 item: name.clone(),
1255 },
1256 None => {
1257 let schema = self.find_non_temp_schema(&schema_id);
1258 QualifiedItemName {
1259 qualifiers: ItemQualifiers {
1260 database_spec: schema.database().clone(),
1261 schema_spec: schema.id().clone(),
1262 },
1263 item: name.clone(),
1264 }
1265 }
1266 };
1267 let entry = match retractions.items.remove(&key) {
1268 Some(mut retraction) => {
1269 assert_eq!(retraction.id, id);
1270
1271 if retraction.create_sql() != create_sql {
1276 let mut catalog_item = self
1277 .deserialize_item(
1278 global_id,
1279 &create_sql,
1280 &extra_versions,
1281 local_expression_cache,
1282 Some(retraction.item),
1283 )
1284 .unwrap_or_else(|e| {
1285 panic!("{e:?}: invalid persisted SQL: {create_sql}")
1286 });
1287 if conn_id.is_some() {
1288 catalog_item.set_conn_id(conn_id.clone());
1296 catalog_item.set_create_sql(create_sql);
1308 }
1309 retraction.item = catalog_item;
1310 }
1311
1312 retraction.id = id;
1313 retraction.oid = oid;
1314 retraction.name = name;
1315 retraction.owner_id = owner_id;
1316 retraction.privileges = PrivilegeMap::from_mz_acl_items(privileges);
1317 retraction
1318 }
1319 None => {
1320 let mut catalog_item = self
1321 .deserialize_item(
1322 global_id,
1323 &create_sql,
1324 &extra_versions,
1325 local_expression_cache,
1326 None,
1327 )
1328 .unwrap_or_else(|e| {
1329 panic!("{e:?}: invalid persisted SQL: {create_sql}")
1330 });
1331
1332 if conn_id.is_some() {
1333 catalog_item.set_conn_id(conn_id.clone());
1335 catalog_item.set_create_sql(create_sql);
1336 }
1337
1338 CatalogEntry {
1339 item: catalog_item,
1340 referenced_by: Vec::new(),
1341 used_by: Vec::new(),
1342 id,
1343 oid,
1344 name,
1345 owner_id,
1346 privileges: PrivilegeMap::from_mz_acl_items(privileges),
1347 }
1348 }
1349 };
1350
1351 self.insert_entry(entry);
1352 }
1353 StateDiff::Retraction => {
1354 let entry = self.drop_item(item.id);
1355 let key = item.into_key_value().0;
1356 retractions.items.insert(key, entry);
1357 }
1358 }
1359 Ok(())
1360 }
1361
1362 #[instrument(level = "debug")]
1363 fn apply_comment_update(
1364 &mut self,
1365 comment: mz_catalog::durable::Comment,
1366 diff: StateDiff,
1367 _retractions: &mut InProgressRetractions,
1368 ) {
1369 match diff {
1370 StateDiff::Addition => {
1371 let prev = Arc::make_mut(&mut self.comments).update_comment(
1372 comment.object_id,
1373 comment.sub_component,
1374 Some(comment.comment),
1375 );
1376 assert_eq!(
1377 prev, None,
1378 "values must be explicitly retracted before inserting a new value"
1379 );
1380 }
1381 StateDiff::Retraction => {
1382 let prev = Arc::make_mut(&mut self.comments).update_comment(
1383 comment.object_id,
1384 comment.sub_component,
1385 None,
1386 );
1387 assert_eq!(
1388 prev,
1389 Some(comment.comment),
1390 "retraction does not match existing value: ({:?}, {:?})",
1391 comment.object_id,
1392 comment.sub_component,
1393 );
1394 }
1395 }
1396 }
1397
1398 #[instrument(level = "debug")]
1399 fn apply_source_references_update(
1400 &mut self,
1401 source_references: mz_catalog::durable::SourceReferences,
1402 diff: StateDiff,
1403 _retractions: &mut InProgressRetractions,
1404 ) {
1405 match diff {
1406 StateDiff::Addition => {
1407 let prev = self
1408 .source_references
1409 .insert(source_references.source_id, source_references.into());
1410 assert!(
1411 prev.is_none(),
1412 "values must be explicitly retracted before inserting a new value: {prev:?}"
1413 );
1414 }
1415 StateDiff::Retraction => {
1416 let prev = self.source_references.remove(&source_references.source_id);
1417 assert!(
1418 prev.is_some(),
1419 "retraction for a non-existent existing value: {source_references:?}"
1420 );
1421 }
1422 }
1423 }
1424
1425 #[instrument(level = "debug")]
1426 fn apply_storage_collection_metadata_update(
1427 &mut self,
1428 storage_collection_metadata: mz_catalog::durable::StorageCollectionMetadata,
1429 diff: StateDiff,
1430 _retractions: &mut InProgressRetractions,
1431 ) {
1432 apply_inverted_lookup(
1433 &mut Arc::make_mut(&mut self.storage_metadata).collection_metadata,
1434 &storage_collection_metadata.id,
1435 storage_collection_metadata.shard,
1436 diff,
1437 );
1438 }
1439
1440 #[instrument(level = "debug")]
1441 fn apply_unfinalized_shard_update(
1442 &mut self,
1443 unfinalized_shard: mz_catalog::durable::UnfinalizedShard,
1444 diff: StateDiff,
1445 _retractions: &mut InProgressRetractions,
1446 ) {
1447 match diff {
1448 StateDiff::Addition => {
1449 let newly_inserted = Arc::make_mut(&mut self.storage_metadata)
1450 .unfinalized_shards
1451 .insert(unfinalized_shard.shard);
1452 assert!(
1453 newly_inserted,
1454 "values must be explicitly retracted before inserting a new value: {unfinalized_shard:?}",
1455 );
1456 }
1457 StateDiff::Retraction => {
1458 let removed = Arc::make_mut(&mut self.storage_metadata)
1459 .unfinalized_shards
1460 .remove(&unfinalized_shard.shard);
1461 assert!(
1462 removed,
1463 "retraction does not match existing value: {unfinalized_shard:?}"
1464 );
1465 }
1466 }
1467 }
1468
1469 #[instrument(level = "debug")]
1472 pub(crate) fn generate_builtin_table_update(
1473 &self,
1474 kind: StateUpdateKind,
1475 diff: StateDiff,
1476 ) -> Vec<BuiltinTableUpdate<&'static BuiltinTable>> {
1477 let diff = diff.into();
1478 match kind {
1479 StateUpdateKind::Role(_) => Vec::new(),
1483 StateUpdateKind::RoleAuth(role_auth) => {
1484 vec![self.pack_role_auth_update(role_auth.role_id, diff)]
1485 }
1486 StateUpdateKind::DefaultPrivilege(_) => Vec::new(),
1490 StateUpdateKind::SystemPrivilege(_) => Vec::new(),
1491 StateUpdateKind::SystemConfiguration(_) => Vec::new(),
1492 StateUpdateKind::ClusterSystemConfiguration(_) => Vec::new(),
1498 StateUpdateKind::ReplicaSystemConfiguration(_) => Vec::new(),
1499 StateUpdateKind::Cluster(_) => Vec::new(),
1503 StateUpdateKind::IntrospectionSourceIndex(introspection_source_index) => {
1504 self.pack_item_update(introspection_source_index.item_id, diff)
1505 }
1506 StateUpdateKind::ClusterReplica(_) => Vec::new(),
1509 StateUpdateKind::ClusterReplicaSize(size) => {
1510 Self::pack_replica_size_update(&size.name, &size.allocation, diff)
1511 }
1512 StateUpdateKind::SystemObjectMapping(system_object_mapping) => {
1513 if !system_object_mapping.unique_identifier.runtime_alterable() {
1517 self.pack_item_update(system_object_mapping.unique_identifier.catalog_id, diff)
1518 } else {
1519 vec![]
1520 }
1521 }
1522 StateUpdateKind::Item(item) => self.pack_item_update(item.id, diff),
1523 StateUpdateKind::Comment(_) => Vec::new(),
1524 StateUpdateKind::SourceReferences(_) => Vec::new(),
1525 StateUpdateKind::AuditLog(_) => Vec::new(),
1529 StateUpdateKind::Database(_)
1530 | StateUpdateKind::Schema(_)
1531 | StateUpdateKind::NetworkPolicy(_)
1532 | StateUpdateKind::QueryPolicy(_)
1533 | StateUpdateKind::StorageCollectionMetadata(_)
1534 | StateUpdateKind::UnfinalizedShard(_) => Vec::new(),
1535 }
1536 }
1537
1538 fn get_entry_mut(&mut self, id: &CatalogItemId) -> &mut CatalogEntry {
1539 self.entry_by_id
1540 .get_mut(id)
1541 .unwrap_or_else(|| panic!("catalog out of sync, missing id {id}"))
1542 }
1543
1544 pub(super) fn set_optimized_plan(
1549 &mut self,
1550 id: GlobalId,
1551 plan: DataflowDescription<mz_expr::OptimizedMirRelationExpr>,
1552 ) {
1553 let item_id = self.entry_by_global_id[&id];
1554 let entry = self.get_entry_mut(&item_id);
1555 match entry.item_mut() {
1556 CatalogItem::Index(idx) => idx.optimized_plan = Some(Arc::new(plan)),
1557 CatalogItem::MaterializedView(mv) => mv.optimized_plan = Some(Arc::new(plan)),
1558 CatalogItem::MetricSink(ms) => ms.optimized_plan = Some(Arc::new(plan)),
1559 other => panic!("set_optimized_plan called on {} ({:?})", id, other.typ()),
1560 }
1561 }
1562
1563 pub(super) fn set_physical_plan(
1568 &mut self,
1569 id: GlobalId,
1570 plan: mz_compute_types::dataflows::LirDataflowDescription,
1571 ) {
1572 let item_id = self.entry_by_global_id[&id];
1573 let entry = self.get_entry_mut(&item_id);
1574 match entry.item_mut() {
1575 CatalogItem::Index(idx) => idx.physical_plan = Some(Arc::new(plan)),
1576 CatalogItem::MaterializedView(mv) => mv.physical_plan = Some(Arc::new(plan)),
1577 CatalogItem::MetricSink(ms) => ms.physical_plan = Some(Arc::new(plan)),
1578 other => panic!("set_physical_plan called on {} ({:?})", id, other.typ()),
1579 }
1580 }
1581
1582 pub(super) fn set_dataflow_metainfo(
1587 &mut self,
1588 id: GlobalId,
1589 metainfo: DataflowMetainfo<Arc<OptimizerNotice>>,
1590 ) {
1591 for notice in metainfo.optimizer_notices.iter() {
1593 for dep_id in notice.dependencies.iter() {
1594 self.notices_by_dep_id
1595 .entry(*dep_id)
1596 .or_default()
1597 .push(Arc::clone(notice));
1598 }
1599 if let Some(item_id) = notice.item_id {
1600 soft_assert_eq_or_log!(
1601 item_id,
1602 id,
1603 "notice.item_id should match the id for whom we are saving the notice"
1604 );
1605 }
1606 }
1607 let item_id = self.entry_by_global_id[&id];
1609 let entry = self.get_entry_mut(&item_id);
1610 match entry.item_mut() {
1611 CatalogItem::Index(idx) => idx.dataflow_metainfo = Some(metainfo),
1612 CatalogItem::MaterializedView(mv) => mv.dataflow_metainfo = Some(metainfo),
1613 CatalogItem::MetricSink(ms) => ms.dataflow_metainfo = Some(metainfo),
1614 other => panic!("set_dataflow_metainfo called on {} ({:?})", id, other.typ()),
1615 }
1616 }
1617
1618 #[mz_ore::instrument(level = "trace")]
1629 pub(super) fn drop_optimizer_notices(
1630 &mut self,
1631 dropped_entries: Vec<CatalogEntry>,
1632 ) -> BTreeSet<Arc<OptimizerNotice>> {
1633 let mut dropped_notices = BTreeSet::new();
1634 let mut drop_ids = BTreeSet::new();
1635
1636 for mut entry in dropped_entries {
1638 drop_ids.extend(entry.global_ids());
1639 if let Some(metainfo) = entry.item_mut().dataflow_metainfo_mut() {
1640 soft_assert_or_log!(
1641 metainfo.optimizer_notices.iter().all_unique(),
1642 "should have been pushed there by \
1643 `push_optimizer_notice_dedup`"
1644 );
1645 for n in metainfo.optimizer_notices.drain(..) {
1646 for dep_id in n.dependencies.iter() {
1649 if let Some(notices) = self.notices_by_dep_id.get_mut(dep_id) {
1650 notices.retain(|x| &n != x);
1651 if notices.is_empty() {
1652 self.notices_by_dep_id.remove(dep_id);
1653 }
1654 }
1655 }
1656 dropped_notices.insert(n);
1657 }
1658 }
1659 }
1660
1661 for id in &drop_ids {
1665 if let Some(notices) = self.notices_by_dep_id.remove(id) {
1666 for n in notices.into_iter() {
1667 if let Some(item_id) = n.item_id.as_ref() {
1672 if let Some(entry) = self.try_get_entry_by_global_id(item_id) {
1673 let catalog_item_id = entry.id();
1674 let entry = self.get_entry_mut(&catalog_item_id);
1675 if let Some(m) = entry.item_mut().dataflow_metainfo_mut() {
1676 m.optimizer_notices.retain(|x| &n != x);
1677 }
1678 }
1679 }
1680 dropped_notices.insert(n);
1681 }
1682 }
1683 }
1684
1685 let todo_dep_ids: BTreeSet<GlobalId> = dropped_notices
1688 .iter()
1689 .flat_map(|n| n.dependencies.iter())
1690 .filter(|dep_id| !drop_ids.contains(dep_id))
1691 .copied()
1692 .collect();
1693 for id in todo_dep_ids {
1694 if let Some(notices) = self.notices_by_dep_id.get_mut(&id) {
1695 notices.retain(|n| !dropped_notices.contains(n));
1696 if notices.is_empty() {
1697 self.notices_by_dep_id.remove(&id);
1698 }
1699 }
1700 }
1701
1702 dropped_notices
1703 }
1704
1705 fn get_schema_mut(
1706 &mut self,
1707 database_spec: &ResolvedDatabaseSpecifier,
1708 schema_spec: &SchemaSpecifier,
1709 conn_id: &ConnectionId,
1710 ) -> &mut Schema {
1711 match (database_spec, schema_spec) {
1713 (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Temporary) => self
1714 .temporary_namespaces
1715 .schema_mut(conn_id)
1716 .expect("catalog out of sync"),
1717 (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Id(id)) => self
1718 .ambient_schemas_by_id
1719 .get_mut(id)
1720 .expect("catalog out of sync"),
1721 (ResolvedDatabaseSpecifier::Id(database_id), SchemaSpecifier::Id(schema_id)) => self
1722 .database_by_id
1723 .get_mut(database_id)
1724 .expect("catalog out of sync")
1725 .schemas_by_id
1726 .get_mut(schema_id)
1727 .expect("catalog out of sync"),
1728 (ResolvedDatabaseSpecifier::Id(_), SchemaSpecifier::Temporary) => {
1729 unreachable!("temporary schemas are in the ambient database")
1730 }
1731 }
1732 }
1733
1734 #[instrument(name = "catalog::parse_views")]
1744 async fn parse_builtin_views(
1745 state: &mut CatalogState,
1746 builtin_views: Vec<(&'static BuiltinView, CatalogItemId, GlobalId)>,
1747 retractions: &mut InProgressRetractions,
1748 local_expression_cache: &mut LocalExpressionCache,
1749 ) -> Vec<BuiltinTableUpdate<&'static BuiltinTable>> {
1750 let mut builtin_table_updates = Vec::with_capacity(builtin_views.len());
1751 let (updates, additions): (Vec<_>, Vec<_>) =
1752 builtin_views
1753 .into_iter()
1754 .partition_map(|(view, item_id, gid)| {
1755 match retractions.system_object_mappings.remove(&item_id) {
1756 Some(entry) => Either::Left(entry),
1757 None => Either::Right((view, item_id, gid)),
1758 }
1759 });
1760
1761 for entry in updates {
1762 let item_id = entry.id();
1767 state.insert_entry(entry);
1768 builtin_table_updates.extend(state.pack_item_update(item_id, Diff::ONE));
1769 }
1770
1771 let mut handles = Vec::new();
1772 let mut awaiting_id_dependencies: BTreeMap<CatalogItemId, Vec<CatalogItemId>> =
1773 BTreeMap::new();
1774 let mut awaiting_name_dependencies: BTreeMap<String, Vec<CatalogItemId>> = BTreeMap::new();
1775 let mut awaiting_all = Vec::new();
1778 let mut completed_ids: BTreeSet<CatalogItemId> = BTreeSet::new();
1780 let mut completed_names: BTreeSet<String> = BTreeSet::new();
1781
1782 let mut views: BTreeMap<CatalogItemId, (&BuiltinView, GlobalId)> = additions
1784 .into_iter()
1785 .map(|(view, item_id, gid)| (item_id, (view, gid)))
1786 .collect();
1787 let item_ids: Vec<_> = views.keys().copied().collect();
1788
1789 let mut ready: VecDeque<CatalogItemId> = views.keys().cloned().collect();
1790 while !handles.is_empty() || !ready.is_empty() || !awaiting_all.is_empty() {
1791 if handles.is_empty() && ready.is_empty() {
1792 ready.extend(awaiting_all.drain(..));
1794 }
1795
1796 if !ready.is_empty() {
1798 let spawn_state = Arc::new(state.clone());
1799 while let Some(id) = ready.pop_front() {
1800 let (view, global_id) = views.get(&id).expect("must exist");
1801 let global_id = *global_id;
1802 let create_sql = view.create_sql();
1803 let versions = BTreeMap::new();
1805
1806 let span = info_span!(parent: None, "parse builtin view", name = view.name);
1807 OpenTelemetryContext::obtain().attach_as_parent_to(&span);
1808 let task_state = Arc::clone(&spawn_state);
1809 let cached_expr = local_expression_cache.remove_cached_expression(&global_id);
1810 let handle = mz_ore::task::spawn_blocking(
1811 || "parse view",
1812 move || {
1813 span.in_scope(|| {
1814 let res = task_state.parse_item_inner(
1815 global_id,
1816 &create_sql,
1817 &versions,
1818 None,
1819 false,
1820 None,
1821 cached_expr,
1822 None,
1823 );
1824 (id, global_id, res)
1825 })
1826 },
1827 );
1828 handles.push(handle);
1829 }
1830 }
1831
1832 let (selected, _idx, remaining) = future::select_all(handles).await;
1834 handles = remaining;
1835 let (id, global_id, res) = selected;
1836 let mut insert_cached_expr = |cached_expr| {
1837 if let Some(cached_expr) = cached_expr {
1838 local_expression_cache.insert_cached_expression(global_id, cached_expr);
1839 }
1840 };
1841 match res {
1842 Ok((item, uncached_expr)) => {
1843 if let Some((uncached_expr, optimizer_features)) = uncached_expr {
1844 local_expression_cache.insert_uncached_expression(
1845 global_id,
1846 uncached_expr,
1847 optimizer_features,
1848 RelationVersion::root(),
1849 );
1850 }
1851 let (view, _gid) = views.remove(&id).expect("must exist");
1853 let schema_id = state
1854 .ambient_schemas_by_name
1855 .get(view.schema)
1856 .unwrap_or_else(|| panic!("unknown ambient schema: {}", view.schema));
1857 let qname = QualifiedItemName {
1858 qualifiers: ItemQualifiers {
1859 database_spec: ResolvedDatabaseSpecifier::Ambient,
1860 schema_spec: SchemaSpecifier::Id(*schema_id),
1861 },
1862 item: view.name.into(),
1863 };
1864 let mut acl_items = vec![rbac::owner_privilege(
1865 mz_sql::catalog::ObjectType::View,
1866 MZ_SYSTEM_ROLE_ID,
1867 )];
1868 acl_items.extend_from_slice(&view.access);
1869
1870 state.insert_item(
1871 id,
1872 view.oid,
1873 qname,
1874 item,
1875 MZ_SYSTEM_ROLE_ID,
1876 PrivilegeMap::from_mz_acl_items(acl_items),
1877 );
1878
1879 let mut resolved_dependent_items = Vec::new();
1881 if let Some(dependent_items) = awaiting_id_dependencies.remove(&id) {
1882 resolved_dependent_items.extend(dependent_items);
1883 }
1884 let entry = state.get_entry(&id);
1885 let full_name = state.resolve_full_name(entry.name(), None).to_string();
1886 if let Some(dependent_items) = awaiting_name_dependencies.remove(&full_name) {
1887 resolved_dependent_items.extend(dependent_items);
1888 }
1889 ready.extend(resolved_dependent_items);
1890
1891 completed_ids.insert(id);
1892 completed_names.insert(full_name);
1893 }
1894 Err((
1896 AdapterError::PlanError(plan::PlanError::InvalidId(missing_dep)),
1897 cached_expr,
1898 )) => {
1899 insert_cached_expr(cached_expr);
1900 if completed_ids.contains(&missing_dep) {
1901 ready.push_back(id);
1902 } else {
1903 awaiting_id_dependencies
1904 .entry(missing_dep)
1905 .or_default()
1906 .push(id);
1907 }
1908 }
1909 Err((
1911 AdapterError::PlanError(plan::PlanError::Catalog(
1912 SqlCatalogError::UnknownItem(missing_dep),
1913 )),
1914 cached_expr,
1915 )) => {
1916 insert_cached_expr(cached_expr);
1917 match CatalogItemId::from_str(&missing_dep) {
1918 Ok(missing_dep) => {
1919 if completed_ids.contains(&missing_dep) {
1920 ready.push_back(id);
1921 } else {
1922 awaiting_id_dependencies
1923 .entry(missing_dep)
1924 .or_default()
1925 .push(id);
1926 }
1927 }
1928 Err(_) => {
1929 if completed_names.contains(&missing_dep) {
1930 ready.push_back(id);
1931 } else {
1932 awaiting_name_dependencies
1933 .entry(missing_dep)
1934 .or_default()
1935 .push(id);
1936 }
1937 }
1938 }
1939 }
1940 Err((
1941 AdapterError::PlanError(plan::PlanError::InvalidCast { .. }),
1942 cached_expr,
1943 )) => {
1944 insert_cached_expr(cached_expr);
1945 awaiting_all.push(id);
1946 }
1947 Err((e, _)) => {
1948 let (bad_view, _gid) = views.get(&id).expect("must exist");
1949 panic!(
1950 "internal error: failed to load bootstrap view:\n\
1951 {name}\n\
1952 error:\n\
1953 {e:?}\n\n\
1954 Make sure that the schema name is specified in the builtin view's create sql statement.
1955 ",
1956 name = bad_view.name,
1957 )
1958 }
1959 }
1960 }
1961
1962 assert!(awaiting_id_dependencies.is_empty());
1963 assert!(
1964 awaiting_name_dependencies.is_empty(),
1965 "awaiting_name_dependencies: {awaiting_name_dependencies:?}"
1966 );
1967 assert!(awaiting_all.is_empty());
1968 assert!(views.is_empty());
1969
1970 builtin_table_updates.extend(
1972 item_ids
1973 .into_iter()
1974 .flat_map(|id| state.pack_item_update(id, Diff::ONE)),
1975 );
1976
1977 builtin_table_updates
1978 }
1979
1980 fn insert_entry(&mut self, entry: CatalogEntry) {
1982 if !entry.id.is_system() {
1983 if let Some(cluster_id) = entry.item.cluster_id() {
1984 self.clusters_by_id
1985 .get_mut(&cluster_id)
1986 .expect("catalog out of sync")
1987 .bound_objects
1988 .insert(entry.id);
1989 };
1990 }
1991
1992 for u in entry.references().items() {
1993 match self.entry_by_id.get_mut(u) {
1994 Some(metadata) => metadata.referenced_by.push(entry.id()),
1995 None => panic!(
1996 "Catalog: missing dependent catalog item {} while installing {}",
1997 u,
1998 self.resolve_full_name(entry.name(), entry.conn_id())
1999 ),
2000 }
2001 }
2002 for u in entry.uses() {
2003 if u == entry.id() {
2006 continue;
2007 }
2008 match self.entry_by_id.get_mut(&u) {
2009 Some(metadata) => metadata.used_by.push(entry.id()),
2010 None => panic!(
2011 "Catalog: missing dependent catalog item {} while installing {}",
2012 u,
2013 self.resolve_full_name(entry.name(), entry.conn_id())
2014 ),
2015 }
2016 }
2017 for gid in entry.item.global_ids() {
2018 self.entry_by_global_id.insert(gid, entry.id());
2019 }
2020 let conn_id = entry.item().conn_id().unwrap_or(&SYSTEM_CONN_ID);
2021 if entry.name().qualifiers.schema_spec == SchemaSpecifier::Temporary {
2024 self.temporary_namespaces
2025 .ensure_schema(conn_id, entry.owner_id);
2026 }
2027 let schema = self.get_schema_mut(
2028 &entry.name().qualifiers.database_spec,
2029 &entry.name().qualifiers.schema_spec,
2030 conn_id,
2031 );
2032
2033 let prev_id = match entry.item() {
2034 CatalogItem::Func(_) => schema
2035 .functions
2036 .insert(entry.name().item.clone(), entry.id()),
2037 CatalogItem::Type(_) => schema.types.insert(entry.name().item.clone(), entry.id()),
2038 _ => schema.items.insert(entry.name().item.clone(), entry.id()),
2039 };
2040
2041 assert!(
2042 prev_id.is_none(),
2043 "builtin name collision on {:?}",
2044 entry.name().item.clone()
2045 );
2046
2047 self.entry_by_id.insert(entry.id(), entry.clone());
2048 }
2049
2050 fn insert_item(
2052 &mut self,
2053 id: CatalogItemId,
2054 oid: u32,
2055 name: QualifiedItemName,
2056 item: CatalogItem,
2057 owner_id: RoleId,
2058 privileges: PrivilegeMap,
2059 ) {
2060 let entry = CatalogEntry {
2061 item,
2062 name,
2063 id,
2064 oid,
2065 used_by: Vec::new(),
2066 referenced_by: Vec::new(),
2067 owner_id,
2068 privileges,
2069 };
2070
2071 self.insert_entry(entry);
2072 }
2073
2074 #[mz_ore::instrument(level = "trace")]
2075 fn drop_item(&mut self, id: CatalogItemId) -> CatalogEntry {
2076 let metadata = self.entry_by_id.remove(&id).expect("catalog out of sync");
2077 for u in metadata.references().items() {
2078 if let Some(dep_metadata) = self.entry_by_id.get_mut(u) {
2079 dep_metadata.referenced_by.retain(|u| *u != metadata.id())
2080 }
2081 }
2082 for u in metadata.uses() {
2083 if let Some(dep_metadata) = self.entry_by_id.get_mut(&u) {
2084 dep_metadata.used_by.retain(|u| *u != metadata.id())
2085 }
2086 }
2087 for gid in metadata.global_ids() {
2088 self.entry_by_global_id.remove(&gid);
2089 }
2090
2091 let conn_id = metadata.item().conn_id().unwrap_or(&SYSTEM_CONN_ID);
2092 let schema = self.get_schema_mut(
2093 &metadata.name().qualifiers.database_spec,
2094 &metadata.name().qualifiers.schema_spec,
2095 conn_id,
2096 );
2097 if metadata.item_type() == CatalogItemType::Type {
2098 schema
2099 .types
2100 .remove(&metadata.name().item)
2101 .expect("catalog out of sync");
2102 } else {
2103 assert_ne!(metadata.item_type(), CatalogItemType::Func);
2106
2107 schema
2108 .items
2109 .remove(&metadata.name().item)
2110 .expect("catalog out of sync");
2111 };
2112
2113 if !id.is_system() {
2114 if let Some(cluster_id) = metadata.item().cluster_id() {
2115 assert!(
2116 self.clusters_by_id
2117 .get_mut(&cluster_id)
2118 .expect("catalog out of sync")
2119 .bound_objects
2120 .remove(&id),
2121 "catalog out of sync"
2122 );
2123 }
2124 }
2125
2126 metadata
2127 }
2128
2129 fn insert_introspection_source_index(
2130 &mut self,
2131 cluster_id: ClusterId,
2132 log: &'static BuiltinLog,
2133 item_id: CatalogItemId,
2134 global_id: GlobalId,
2135 oid: u32,
2136 ) {
2137 let (index_name, index) =
2138 self.create_introspection_source_index(cluster_id, log, global_id);
2139 self.insert_item(
2140 item_id,
2141 oid,
2142 index_name,
2143 index,
2144 MZ_SYSTEM_ROLE_ID,
2145 PrivilegeMap::default(),
2146 );
2147 }
2148
2149 fn create_introspection_source_index(
2150 &self,
2151 cluster_id: ClusterId,
2152 log: &'static BuiltinLog,
2153 global_id: GlobalId,
2154 ) -> (QualifiedItemName, CatalogItem) {
2155 let source_name = FullItemName {
2156 database: RawDatabaseSpecifier::Ambient,
2157 schema: log.schema.into(),
2158 item: log.name.into(),
2159 };
2160 let index_name = format!("{}_{}_primary_idx", log.name, cluster_id);
2161 let mut index_name = QualifiedItemName {
2162 qualifiers: ItemQualifiers {
2163 database_spec: ResolvedDatabaseSpecifier::Ambient,
2164 schema_spec: SchemaSpecifier::Id(self.get_mz_introspection_schema_id()),
2165 },
2166 item: index_name.clone(),
2167 };
2168 index_name = self.find_available_name(index_name, &SYSTEM_CONN_ID);
2169 let index_item_name = index_name.item.clone();
2170 let (log_item_id, log_global_id) = self.resolve_builtin_log(log);
2171 let index = CatalogItem::Index(Index {
2172 global_id,
2173 on: log_global_id,
2174 keys: log
2175 .variant
2176 .index_by()
2177 .into_iter()
2178 .map(MirScalarExpr::column)
2179 .collect(),
2180 create_sql: index_sql(
2181 index_item_name,
2182 cluster_id,
2183 source_name,
2184 &log.variant.desc(),
2185 &log.variant.index_by(),
2186 ),
2187 conn_id: None,
2188 resolved_ids: [(log_item_id, log_global_id)].into_iter().collect(),
2189 cluster_id,
2190 is_retained_metrics_object: false,
2191 custom_logical_compaction_window: None,
2192 optimized_plan: None,
2193 physical_plan: None,
2194 dataflow_metainfo: None,
2195 });
2196 (index_name, index)
2197 }
2198
2199 fn insert_system_configuration(&mut self, name: &str, value: VarInput) -> Result<bool, Error> {
2204 Ok(Arc::make_mut(&mut self.system_configuration).set(name, value)?)
2205 }
2206
2207 fn remove_system_configuration(&mut self, name: &str) -> Result<bool, Error> {
2212 Ok(Arc::make_mut(&mut self.system_configuration).reset(name)?)
2213 }
2214}
2215
2216fn sort_updates(updates: Vec<StateUpdate>) -> Vec<StateUpdate> {
2224 fn push_update<T>(
2225 update: T,
2226 diff: StateDiff,
2227 retractions: &mut Vec<T>,
2228 additions: &mut Vec<T>,
2229 ) {
2230 match diff {
2231 StateDiff::Retraction => retractions.push(update),
2232 StateDiff::Addition => additions.push(update),
2233 }
2234 }
2235
2236 soft_assert_no_log!(
2237 updates.iter().map(|update| update.ts).all_equal(),
2238 "all timestamps should be equal: {updates:?}"
2239 );
2240 soft_assert_no_log!(
2241 {
2242 let mut dedup = BTreeSet::new();
2243 updates.iter().all(|update| dedup.insert(&update.kind))
2244 },
2245 "updates should be consolidated: {updates:?}"
2246 );
2247
2248 let mut pre_cluster_retractions = Vec::new();
2250 let mut pre_cluster_additions = Vec::new();
2251 let mut cluster_retractions = Vec::new();
2252 let mut cluster_additions = Vec::new();
2253 let mut builtin_item_updates = Vec::new();
2254 let mut item_retractions = Vec::new();
2255 let mut item_additions = Vec::new();
2256 let mut post_item_retractions = Vec::new();
2257 let mut post_item_additions = Vec::new();
2258 for update in updates {
2259 let diff = update.diff.clone();
2260 match update.kind {
2261 StateUpdateKind::Role(_)
2262 | StateUpdateKind::RoleAuth(_)
2263 | StateUpdateKind::Database(_)
2264 | StateUpdateKind::Schema(_)
2265 | StateUpdateKind::DefaultPrivilege(_)
2266 | StateUpdateKind::SystemPrivilege(_)
2267 | StateUpdateKind::SystemConfiguration(_)
2268 | StateUpdateKind::QueryPolicy(_)
2269 | StateUpdateKind::NetworkPolicy(_)
2270 | StateUpdateKind::ClusterReplicaSize(_) => push_update(
2271 update,
2272 diff,
2273 &mut pre_cluster_retractions,
2274 &mut pre_cluster_additions,
2275 ),
2276 StateUpdateKind::Cluster(_)
2277 | StateUpdateKind::ClusterSystemConfiguration(_)
2278 | StateUpdateKind::IntrospectionSourceIndex(_)
2279 | StateUpdateKind::ClusterReplica(_)
2280 | StateUpdateKind::ReplicaSystemConfiguration(_) => push_update(
2281 update,
2282 diff,
2283 &mut cluster_retractions,
2284 &mut cluster_additions,
2285 ),
2286 StateUpdateKind::SystemObjectMapping(system_object_mapping) => {
2287 builtin_item_updates.push((system_object_mapping, update.ts, update.diff))
2288 }
2289 StateUpdateKind::Item(item) => push_update(
2290 (item, update.ts, update.diff),
2291 diff,
2292 &mut item_retractions,
2293 &mut item_additions,
2294 ),
2295 StateUpdateKind::Comment(_)
2296 | StateUpdateKind::SourceReferences(_)
2297 | StateUpdateKind::AuditLog(_)
2298 | StateUpdateKind::StorageCollectionMetadata(_)
2299 | StateUpdateKind::UnfinalizedShard(_) => push_update(
2300 update,
2301 diff,
2302 &mut post_item_retractions,
2303 &mut post_item_additions,
2304 ),
2305 }
2306 }
2307
2308 let builtin_item_updates = builtin_item_updates
2311 .into_iter()
2312 .map(|(system_object_mapping, ts, diff)| {
2313 let idx = BUILTIN_LOOKUP
2314 .get(&system_object_mapping.description)
2315 .expect("missing builtin")
2316 .0;
2317 (idx, system_object_mapping, ts, diff)
2318 })
2319 .sorted_by_key(|(idx, _, _, _)| *idx)
2320 .map(|(_, system_object_mapping, ts, diff)| (system_object_mapping, ts, diff));
2321
2322 let mut builtin_source_retractions = Vec::new();
2326 let mut builtin_source_additions = Vec::new();
2327 let mut other_builtin_retractions = Vec::new();
2328 let mut other_builtin_additions = Vec::new();
2329 for (builtin_item_update, ts, diff) in builtin_item_updates {
2330 let object_type = builtin_item_update.description.object_type;
2331 let update = StateUpdate {
2332 kind: StateUpdateKind::SystemObjectMapping(builtin_item_update),
2333 ts,
2334 diff,
2335 };
2336 if object_type == CatalogItemType::Source {
2337 push_update(
2338 update,
2339 diff,
2340 &mut builtin_source_retractions,
2341 &mut builtin_source_additions,
2342 );
2343 } else {
2344 push_update(
2345 update,
2346 diff,
2347 &mut other_builtin_retractions,
2348 &mut other_builtin_additions,
2349 );
2350 }
2351 }
2352
2353 fn sort_items_topological(items: &mut Vec<(mz_catalog::durable::Item, Timestamp, StateDiff)>) {
2359 tracing::debug!(?items, "sorting items by dependencies");
2360
2361 let key_fn = |item: &(mz_catalog::durable::Item, _, _)| item.0.id;
2362 let dependencies_fn = |item: &(mz_catalog::durable::Item, _, _)| {
2363 let statement = mz_sql::parse::parse(&item.0.create_sql)
2364 .expect("valid create_sql")
2365 .into_element()
2366 .ast;
2367 mz_sql::names::dependencies(&statement).expect("failed to find dependencies of item")
2368 };
2369 sort_topological(items, key_fn, dependencies_fn);
2370 }
2371
2372 fn sort_item_updates(
2388 item_updates: Vec<(mz_catalog::durable::Item, Timestamp, StateDiff)>,
2389 ) -> VecDeque<(mz_catalog::durable::Item, Timestamp, StateDiff)> {
2390 let mut types = Vec::new();
2393 let mut funcs = Vec::new();
2396 let mut secrets = Vec::new();
2397 let mut connections = Vec::new();
2398 let mut sources = Vec::new();
2399 let mut tables = Vec::new();
2400 let mut derived_items = Vec::new();
2401 let mut sinks = Vec::new();
2402 for update in item_updates {
2403 match update.0.item_type() {
2404 CatalogItemType::Type => types.push(update),
2405 CatalogItemType::Func => funcs.push(update),
2406 CatalogItemType::Secret => secrets.push(update),
2407 CatalogItemType::Connection => connections.push(update),
2408 CatalogItemType::Source => sources.push(update),
2409 CatalogItemType::Table => tables.push(update),
2410 CatalogItemType::View
2411 | CatalogItemType::MaterializedView
2412 | CatalogItemType::Index
2413 | CatalogItemType::MetricSink => derived_items.push(update),
2414 CatalogItemType::Sink => sinks.push(update),
2415 }
2416 }
2417
2418 sort_items_topological(&mut connections);
2422 sort_items_topological(&mut derived_items);
2423
2424 for group in [
2426 &mut types,
2427 &mut funcs,
2428 &mut secrets,
2429 &mut sources,
2430 &mut tables,
2431 &mut sinks,
2432 ] {
2433 group.sort_by_key(|(item, _, _)| item.id);
2434 }
2435
2436 iter::empty()
2437 .chain(types)
2438 .chain(funcs)
2439 .chain(secrets)
2440 .chain(connections)
2441 .chain(sources)
2442 .chain(tables)
2443 .chain(derived_items)
2444 .chain(sinks)
2445 .collect()
2446 }
2447
2448 fn into_state_updates(
2452 item_updates: VecDeque<(mz_catalog::durable::Item, Timestamp, StateDiff)>,
2453 ) -> Vec<StateUpdate> {
2454 item_updates
2455 .into_iter()
2456 .map(|(item, ts, diff)| StateUpdate {
2457 kind: StateUpdateKind::Item(item),
2458 ts,
2459 diff,
2460 })
2461 .collect()
2462 }
2463 let item_retractions = into_state_updates(sort_item_updates(item_retractions));
2464 let item_additions = into_state_updates(sort_item_updates(item_additions));
2465
2466 iter::empty()
2468 .chain(post_item_retractions.into_iter().rev())
2470 .chain(item_retractions.into_iter().rev())
2471 .chain(other_builtin_retractions.into_iter().rev())
2472 .chain(cluster_retractions.into_iter().rev())
2473 .chain(builtin_source_retractions.into_iter().rev())
2474 .chain(pre_cluster_retractions.into_iter().rev())
2475 .chain(pre_cluster_additions)
2476 .chain(builtin_source_additions)
2477 .chain(cluster_additions)
2478 .chain(other_builtin_additions)
2479 .chain(item_additions)
2480 .chain(post_item_additions)
2481 .collect()
2482}
2483
2484enum ApplyState {
2489 BuiltinViewAdditions(Vec<(&'static BuiltinView, CatalogItemId, GlobalId)>),
2491 Items(Vec<StateUpdate>),
2497 Updates(Vec<StateUpdate>),
2499}
2500
2501impl ApplyState {
2502 fn new(update: StateUpdate) -> Self {
2503 use StateUpdateKind::*;
2504 match &update.kind {
2505 SystemObjectMapping(som)
2506 if som.description.object_type == CatalogItemType::View
2507 && update.diff == StateDiff::Addition =>
2508 {
2509 let view_addition = lookup_builtin_view_addition(som.clone());
2510 Self::BuiltinViewAdditions(vec![view_addition])
2511 }
2512
2513 IntrospectionSourceIndex(_) | SystemObjectMapping(_) | Item(_) => {
2514 Self::Items(vec![update])
2515 }
2516
2517 Role(_)
2518 | RoleAuth(_)
2519 | Database(_)
2520 | Schema(_)
2521 | DefaultPrivilege(_)
2522 | SystemPrivilege(_)
2523 | SystemConfiguration(_)
2524 | ClusterSystemConfiguration(_)
2525 | ReplicaSystemConfiguration(_)
2526 | Cluster(_)
2527 | NetworkPolicy(_)
2528 | ClusterReplicaSize(_)
2529 | QueryPolicy(_)
2530 | ClusterReplica(_)
2531 | SourceReferences(_)
2532 | Comment(_)
2533 | AuditLog(_)
2534 | StorageCollectionMetadata(_)
2535 | UnfinalizedShard(_) => Self::Updates(vec![update]),
2536 }
2537 }
2538
2539 async fn apply(
2545 self,
2546 state: &mut CatalogState,
2547 retractions: &mut InProgressRetractions,
2548 local_expression_cache: &mut LocalExpressionCache,
2549 ) -> (
2550 Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
2551 Vec<ParsedStateUpdate>,
2552 ) {
2553 match self {
2554 Self::BuiltinViewAdditions(builtin_view_additions) => {
2555 let restore = Arc::clone(&state.system_configuration);
2556 Arc::make_mut(&mut state.system_configuration).enable_for_item_parsing();
2557 let builtin_table_updates = CatalogState::parse_builtin_views(
2558 state,
2559 builtin_view_additions,
2560 retractions,
2561 local_expression_cache,
2562 )
2563 .await;
2564 state.system_configuration = restore;
2565 (builtin_table_updates, Vec::new())
2566 }
2567 Self::Items(updates) => state.with_enable_for_item_parsing(|state| {
2568 state
2569 .apply_updates_inner(updates, retractions, local_expression_cache)
2570 .expect("corrupt catalog")
2571 }),
2572 Self::Updates(updates) => state
2573 .apply_updates_inner(updates, retractions, local_expression_cache)
2574 .expect("corrupt catalog"),
2575 }
2576 }
2577
2578 async fn step(
2579 self,
2580 next: Self,
2581 state: &mut CatalogState,
2582 retractions: &mut InProgressRetractions,
2583 local_expression_cache: &mut LocalExpressionCache,
2584 ) -> (
2585 Self,
2586 (
2587 Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
2588 Vec<ParsedStateUpdate>,
2589 ),
2590 ) {
2591 match (self, next) {
2592 (
2593 Self::BuiltinViewAdditions(mut builtin_view_additions),
2594 Self::BuiltinViewAdditions(next_builtin_view_additions),
2595 ) => {
2596 builtin_view_additions.extend(next_builtin_view_additions);
2598 (
2599 Self::BuiltinViewAdditions(builtin_view_additions),
2600 (Vec::new(), Vec::new()),
2601 )
2602 }
2603 (Self::Items(mut updates), Self::Items(next_updates)) => {
2604 updates.extend(next_updates);
2606 (Self::Items(updates), (Vec::new(), Vec::new()))
2607 }
2608 (Self::Updates(mut updates), Self::Updates(next_updates)) => {
2609 updates.extend(next_updates);
2611 (Self::Updates(updates), (Vec::new(), Vec::new()))
2612 }
2613 (apply_state, next_apply_state) => {
2614 let updates = apply_state
2616 .apply(state, retractions, local_expression_cache)
2617 .await;
2618 (next_apply_state, updates)
2619 }
2620 }
2621 }
2622}
2623
2624trait MutableMap<K, V> {
2627 fn insert(&mut self, key: K, value: V) -> Option<V>;
2628 fn remove(&mut self, key: &K) -> Option<V>;
2629}
2630
2631impl<K: Ord, V> MutableMap<K, V> for BTreeMap<K, V> {
2632 fn insert(&mut self, key: K, value: V) -> Option<V> {
2633 BTreeMap::insert(self, key, value)
2634 }
2635 fn remove(&mut self, key: &K) -> Option<V> {
2636 BTreeMap::remove(self, key)
2637 }
2638}
2639
2640impl<K: Ord + Clone, V: Clone> MutableMap<K, V> for imbl::OrdMap<K, V> {
2641 fn insert(&mut self, key: K, value: V) -> Option<V> {
2642 imbl::OrdMap::insert(self, key, value)
2643 }
2644 fn remove(&mut self, key: &K) -> Option<V> {
2645 imbl::OrdMap::remove(self, key)
2646 }
2647}
2648
2649fn apply_inverted_lookup<K, V>(map: &mut impl MutableMap<K, V>, key: &K, value: V, diff: StateDiff)
2654where
2655 K: Ord + Clone + Debug,
2656 V: PartialEq + Debug,
2657{
2658 match diff {
2659 StateDiff::Retraction => {
2660 let prev = map.remove(key);
2661 assert_eq!(
2662 prev,
2663 Some(value),
2664 "retraction does not match existing value: {key:?}"
2665 );
2666 }
2667 StateDiff::Addition => {
2668 let prev = map.insert(key.clone(), value);
2669 assert_eq!(
2670 prev, None,
2671 "values must be explicitly retracted before inserting a new value: {key:?}"
2672 );
2673 }
2674 }
2675}
2676
2677fn apply_with_update<K, V, D>(
2680 map: &mut impl MutableMap<K, V>,
2681 durable: D,
2682 key_fn: impl FnOnce(&D) -> K,
2683 diff: StateDiff,
2684 retractions: &mut BTreeMap<D::Key, V>,
2685) where
2686 K: Ord,
2687 V: UpdateFrom<D> + PartialEq + Debug,
2688 D: DurableType,
2689 D::Key: Ord,
2690{
2691 match diff {
2692 StateDiff::Retraction => {
2693 let mem_key = key_fn(&durable);
2694 let value = map
2695 .remove(&mem_key)
2696 .expect("retraction does not match existing value: {key:?}");
2697 let durable_key = durable.into_key_value().0;
2698 retractions.insert(durable_key, value);
2699 }
2700 StateDiff::Addition => {
2701 let mem_key = key_fn(&durable);
2702 let durable_key = durable.key();
2703 let value = match retractions.remove(&durable_key) {
2704 Some(mut retraction) => {
2705 retraction.update_from(durable);
2706 retraction
2707 }
2708 None => durable.into(),
2709 };
2710 let prev = map.insert(mem_key, value);
2711 assert_eq!(
2712 prev, None,
2713 "values must be explicitly retracted before inserting a new value"
2714 );
2715 }
2716 }
2717}
2718
2719fn lookup_builtin_view_addition(
2721 mapping: SystemObjectMapping,
2722) -> (&'static BuiltinView, CatalogItemId, GlobalId) {
2723 let (_, builtin) = BUILTIN_LOOKUP
2724 .get(&mapping.description)
2725 .expect("missing builtin view");
2726 let Builtin::View(view) = builtin else {
2727 unreachable!("programming error, expected BuiltinView found {builtin:?}");
2728 };
2729
2730 (
2731 view,
2732 mapping.unique_identifier.catalog_id,
2733 mapping.unique_identifier.global_id,
2734 )
2735}