1use std::collections::{BTreeMap, BTreeSet};
11use std::fmt::Debug;
12use std::num::NonZeroU32;
13use std::time::Duration;
14
15use anyhow::anyhow;
16use derivative::Derivative;
17use itertools::Itertools;
18use mz_audit_log::VersionedEvent;
19use mz_compute_client::logging::{ComputeLog, DifferentialLog, LogVariant, TimelyLog};
20use mz_controller::clusters::ReplicaAllocation;
21use mz_controller_types::{ClusterId, ReplicaId};
22use mz_ore::cast::{u64_to_usize, usize_to_u64};
23use mz_ore::collections::{CollectionExt, HashSet};
24use mz_ore::now::SYSTEM_TIME;
25use mz_ore::vec::VecExt;
26use mz_ore::{soft_assert_no_log, soft_assert_or_log, soft_panic_or_log};
27use mz_persist_types::ShardId;
28use mz_pgrepr::oid::FIRST_USER_OID;
29use mz_proto::TryFromProtoError;
30use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
31use mz_repr::cluster_replica_size_id::ClusterReplicaSizeId;
32use mz_repr::network_policy_id::NetworkPolicyId;
33use mz_repr::query_policy_id::QueryPolicyId;
34use mz_repr::role_id::RoleId;
35use mz_repr::{CatalogItemId, Diff, GlobalId, RelationVersion};
36use mz_sql::catalog::{
37 CatalogError as SqlCatalogError, CatalogItemType, ObjectType, PasswordAction,
38 RoleAttributesRaw, RoleMembership, RoleVars,
39};
40use mz_sql::names::{CommentObjectId, DatabaseId, ResolvedDatabaseSpecifier, SchemaId};
41use mz_sql::plan::NetworkPolicyRule;
42use mz_sql::plan::{QueryPolicyMode, QueryPolicyRule};
43use mz_sql_parser::ast::QualifiedReplica;
44use mz_storage_client::controller::StorageTxn;
45use mz_storage_types::controller::StorageError;
46use tracing::warn;
47use uuid::Uuid;
48
49use crate::builtin::BuiltinLog;
50use crate::durable::initialize::{
51 ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT, SYSTEM_CONFIG_SYNCED_KEY,
52 WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL, WITH_0DT_DEPLOYMENT_MAX_WAIT,
53};
54use crate::durable::objects::serialization::{RustType, proto};
55use crate::durable::objects::{
56 AuditLogKey, Cluster, ClusterConfig, ClusterIntrospectionSourceIndexKey,
57 ClusterIntrospectionSourceIndexValue, ClusterKey, ClusterReplica, ClusterReplicaKey,
58 ClusterReplicaSize, ClusterReplicaSizeKey, ClusterReplicaSizeValue, ClusterReplicaValue,
59 ClusterSystemConfiguration, ClusterSystemConfigurationKey, ClusterSystemConfigurationValue,
60 ClusterValue, CommentKey, CommentValue, Config, ConfigKey, ConfigValue, Database, DatabaseKey,
61 DatabaseValue, DefaultPrivilegesKey, DefaultPrivilegesValue, DurableType, GidMappingKey,
62 GidMappingValue, IdAllocKey, IdAllocValue, IndexColumnsKey, IndexColumnsValue,
63 IntrospectionSourceIndex, Item, ItemColumnsKey, ItemColumnsValue, ItemKey, ItemMetadata,
64 ItemValue, NetworkPolicyKey, NetworkPolicyValue, QueryPolicy, QueryPolicyKey, QueryPolicyValue,
65 ReplicaConfig, ReplicaSystemConfiguration, ReplicaSystemConfigurationKey,
66 ReplicaSystemConfigurationValue, Role, RoleKey, RoleValue, Schema, SchemaKey, SchemaValue,
67 ServerConfigurationKey, ServerConfigurationValue, SettingKey, SettingValue, SourceReference,
68 SourceReferencesKey, SourceReferencesValue, StorageCollectionMetadataKey,
69 StorageCollectionMetadataValue, SystemObjectDescription, SystemObjectMapping,
70 SystemPrivilegesKey, SystemPrivilegesValue, TxnWalShardValue, UnfinalizedShardKey,
71};
72use crate::durable::{
73 AUDIT_LOG_ID_ALLOC_KEY, BUILTIN_MIGRATION_SHARD_KEY, CATALOG_CONTENT_VERSION_KEY, CatalogError,
74 DATABASE_ID_ALLOC_KEY, DefaultPrivilege, DurableCatalogError, DurableCatalogState,
75 EXPRESSION_CACHE_SHARD_KEY, MOCK_AUTHENTICATION_NONCE_KEY, NetworkPolicy, OID_ALLOC_KEY,
76 SCHEMA_ID_ALLOC_KEY, SYSTEM_CLUSTER_ID_ALLOC_KEY, SYSTEM_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY,
77 SYSTEM_ITEM_ALLOC_KEY, SYSTEM_REPLICA_ID_ALLOC_KEY, Snapshot, SystemConfiguration,
78 USER_ITEM_ALLOC_KEY, USER_NETWORK_POLICY_ID_ALLOC_KEY, USER_QUERY_POLICY_ID_ALLOC_KEY,
79 USER_ROLE_ID_ALLOC_KEY,
80};
81use crate::memory::objects::{StateDiff, StateUpdate, StateUpdateKind};
82
83type Timestamp = u64;
84
85#[derive(Debug, PartialEq)]
86struct CommitCapability;
87
88#[derive(Derivative)]
91#[derivative(Debug)]
92pub struct Transaction<'a> {
93 #[derivative(Debug = "ignore")]
94 #[derivative(PartialEq = "ignore")]
95 durable_catalog: &'a mut dyn DurableCatalogState,
96 databases: TableTransaction<DatabaseKey, DatabaseValue>,
97 schemas: TableTransaction<SchemaKey, SchemaValue>,
98 items: TableTransaction<ItemKey, ItemValue>,
99 item_columns: TableTransaction<ItemColumnsKey, ItemColumnsValue>,
100 index_columns: TableTransaction<IndexColumnsKey, IndexColumnsValue>,
101 comments: TableTransaction<CommentKey, CommentValue>,
102 roles: TableTransaction<RoleKey, RoleValue>,
103 role_auth: TableTransaction<RoleAuthKey, RoleAuthValue>,
104 clusters: TableTransaction<ClusterKey, ClusterValue>,
105 cluster_replicas: TableTransaction<ClusterReplicaKey, ClusterReplicaValue>,
106 introspection_sources:
107 TableTransaction<ClusterIntrospectionSourceIndexKey, ClusterIntrospectionSourceIndexValue>,
108 id_allocator: TableTransaction<IdAllocKey, IdAllocValue>,
109 configs: TableTransaction<ConfigKey, ConfigValue>,
110 settings: TableTransaction<SettingKey, SettingValue>,
111 system_gid_mapping: TableTransaction<GidMappingKey, GidMappingValue>,
112 system_configurations: TableTransaction<ServerConfigurationKey, ServerConfigurationValue>,
113 cluster_system_configurations:
114 TableTransaction<ClusterSystemConfigurationKey, ClusterSystemConfigurationValue>,
115 replica_system_configurations:
116 TableTransaction<ReplicaSystemConfigurationKey, ReplicaSystemConfigurationValue>,
117 default_privileges: TableTransaction<DefaultPrivilegesKey, DefaultPrivilegesValue>,
118 source_references: TableTransaction<SourceReferencesKey, SourceReferencesValue>,
119 system_privileges: TableTransaction<SystemPrivilegesKey, SystemPrivilegesValue>,
120 network_policies: TableTransaction<NetworkPolicyKey, NetworkPolicyValue>,
121 cluster_replica_sizes: TableTransaction<ClusterReplicaSizeKey, ClusterReplicaSizeValue>,
122 query_policies: TableTransaction<QueryPolicyKey, QueryPolicyValue>,
123 storage_collection_metadata:
124 TableTransaction<StorageCollectionMetadataKey, StorageCollectionMetadataValue>,
125 unfinalized_shards: TableTransaction<UnfinalizedShardKey, ()>,
126 txn_wal_shard: TableTransaction<(), TxnWalShardValue>,
127 audit_log_updates: Vec<(AuditLogKey, Diff, Timestamp)>,
130 upper: mz_repr::Timestamp,
132 op_id: Timestamp,
134 commit_capability: Option<CommitCapability>,
138}
139
140#[derive(Debug)]
142pub struct DryRunTransaction<'a> {
143 transaction: Transaction<'a>,
144}
145
146impl<'a> DryRunTransaction<'a> {
147 pub fn new(mut transaction: Transaction<'a>) -> Self {
149 transaction.commit_capability = None;
150 Self { transaction }
151 }
152
153 pub fn transaction_mut(&mut self) -> &mut Transaction<'a> {
155 &mut self.transaction
156 }
157
158 pub fn current_snapshot(&self) -> Snapshot {
160 self.transaction.current_snapshot()
161 }
162}
163
164impl<'a> Transaction<'a> {
165 pub(super) fn new(
166 durable_catalog: &'a mut dyn DurableCatalogState,
167 Snapshot {
168 databases,
169 schemas,
170 roles,
171 role_auth,
172 items,
173 item_columns,
174 index_columns,
175 comments,
176 clusters,
177 network_policies,
178 cluster_replica_sizes,
179 query_policies,
180 cluster_replicas,
181 introspection_sources,
182 id_allocator,
183 configs,
184 settings,
185 source_references,
186 system_object_mappings,
187 system_configurations,
188 cluster_system_configurations,
189 replica_system_configurations,
190 default_privileges,
191 system_privileges,
192 storage_collection_metadata,
193 unfinalized_shards,
194 txn_wal_shard,
195 }: Snapshot,
196 upper: mz_repr::Timestamp,
197 ) -> Result<Transaction<'a>, CatalogError> {
198 let database_unique_fn: fn(&DatabaseValue, &DatabaseValue) -> bool =
201 |a, b| a.name == b.name;
202 let schema_unique_fn: fn(&SchemaValue, &SchemaValue) -> bool =
203 |a, b| a.database_id == b.database_id && a.name == b.name;
204 let role_key: fn(&RoleValue, &RoleValue) -> bool = |a, b| a.name == b.name;
205 let cluster_unique_fn: fn(&ClusterValue, &ClusterValue) -> bool = |a, b| a.name == b.name;
206 let network_policy_unique_fn: fn(&NetworkPolicyValue, &NetworkPolicyValue) -> bool =
207 |a, b| a.name == b.name;
208 let cluster_replica_size_unique_fn: fn(
209 &ClusterReplicaSizeValue,
210 &ClusterReplicaSizeValue,
211 ) -> bool = |a, b| a.name == b.name;
212 let cluster_replica_unique_fn: fn(&ClusterReplicaValue, &ClusterReplicaValue) -> bool =
213 |a, b| a.cluster_id == b.cluster_id && a.name == b.name;
214
215 Ok(Transaction {
216 durable_catalog,
217 databases: TableTransaction::new_with_uniqueness_fn(
218 databases,
219 database_unique_fn,
220 database_unique_fn,
221 )?,
222 schemas: TableTransaction::new_with_uniqueness_fn(
223 schemas,
224 schema_unique_fn,
225 schema_unique_fn,
226 )?,
227 items: TableTransaction::new_with_uniqueness_fn(
232 items,
233 |a: &ItemValue, b| {
234 a.schema_id == b.schema_id
235 && a.name == b.name
236 && a.ephemeral_owner_session == b.ephemeral_owner_session
237 && {
238 let a_type = a.item_type();
240 let b_type = b.item_type();
241 (a_type != CatalogItemType::Type && b_type != CatalogItemType::Type)
242 || (a_type == CatalogItemType::Type && b_type.conflicts_with_type())
243 || (b_type == CatalogItemType::Type && a_type.conflicts_with_type())
244 }
245 },
246 |prev: &ItemValue, next| {
247 prev.schema_id == next.schema_id
248 && prev.name == next.name
249 && prev.ephemeral_owner_session == next.ephemeral_owner_session
250 && prev.item_type() == next.item_type()
252 },
253 )?,
254 item_columns: TableTransaction::new(item_columns)?,
255 index_columns: TableTransaction::new(index_columns)?,
256 comments: TableTransaction::new(comments)?,
257 roles: TableTransaction::new_with_uniqueness_fn(roles, role_key, role_key)?,
258 role_auth: TableTransaction::new(role_auth)?,
259 clusters: TableTransaction::new_with_uniqueness_fn(
260 clusters,
261 cluster_unique_fn,
262 cluster_unique_fn,
263 )?,
264 network_policies: TableTransaction::new_with_uniqueness_fn(
265 network_policies,
266 network_policy_unique_fn,
267 network_policy_unique_fn,
268 )?,
269 cluster_replica_sizes: TableTransaction::new_with_uniqueness_fn(
270 cluster_replica_sizes,
271 cluster_replica_size_unique_fn,
272 cluster_replica_size_unique_fn,
273 )?,
274 query_policies: TableTransaction::new_with_uniqueness_fn(
275 query_policies,
276 |a: &QueryPolicyValue, b| a.name == b.name,
277 |prev: &QueryPolicyValue, next| prev.name == next.name,
278 )?,
279 cluster_replicas: TableTransaction::new_with_uniqueness_fn(
280 cluster_replicas,
281 cluster_replica_unique_fn,
282 cluster_replica_unique_fn,
283 )?,
284 introspection_sources: TableTransaction::new(introspection_sources)?,
285 id_allocator: TableTransaction::new(id_allocator)?,
286 configs: TableTransaction::new(configs)?,
287 settings: TableTransaction::new(settings)?,
288 source_references: TableTransaction::new(source_references)?,
289 system_gid_mapping: TableTransaction::new(system_object_mappings)?,
290 system_configurations: TableTransaction::new(system_configurations)?,
291 cluster_system_configurations: TableTransaction::new(cluster_system_configurations)?,
292 replica_system_configurations: TableTransaction::new(replica_system_configurations)?,
293 default_privileges: TableTransaction::new(default_privileges)?,
294 system_privileges: TableTransaction::new(system_privileges)?,
295 storage_collection_metadata: TableTransaction::new(storage_collection_metadata)?,
296 unfinalized_shards: TableTransaction::new(unfinalized_shards)?,
297 txn_wal_shard: TableTransaction::new(txn_wal_shard)?,
301 audit_log_updates: Vec::new(),
302 upper,
303 op_id: 0,
304 commit_capability: Some(CommitCapability),
305 })
306 }
307
308 pub fn get_item(&self, id: &CatalogItemId) -> Option<Item> {
309 let key = ItemKey { id: *id };
310 self.items
311 .get(&key)
312 .map(|v| DurableType::from_key_value(key, v.clone()))
313 }
314
315 pub fn get_items(&self) -> impl Iterator<Item = Item> + use<> {
316 self.items
317 .items()
318 .into_iter()
319 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
320 .sorted_by_key(|Item { id, .. }| *id)
321 }
322
323 pub fn insert_audit_log_event(&mut self, event: VersionedEvent) {
324 self.insert_audit_log_events([event]);
325 }
326
327 pub fn insert_audit_log_events(&mut self, events: impl IntoIterator<Item = VersionedEvent>) {
328 let events = events
329 .into_iter()
330 .map(|event| (AuditLogKey { event }, Diff::ONE, self.op_id));
331 self.audit_log_updates.extend(events);
332 }
333
334 pub fn insert_user_database(
335 &mut self,
336 database_name: &str,
337 owner_id: RoleId,
338 privileges: Vec<MzAclItem>,
339 temporary_oids: &HashSet<u32>,
340 ) -> Result<(DatabaseId, u32), CatalogError> {
341 let id = self.get_and_increment_id(DATABASE_ID_ALLOC_KEY.to_string())?;
342 let id = DatabaseId::User(id);
343 let oid = self.allocate_oid(temporary_oids)?;
344 self.insert_database(id, database_name, owner_id, privileges, oid)?;
345 Ok((id, oid))
346 }
347
348 pub(crate) fn insert_database(
349 &mut self,
350 id: DatabaseId,
351 database_name: &str,
352 owner_id: RoleId,
353 privileges: Vec<MzAclItem>,
354 oid: u32,
355 ) -> Result<u32, CatalogError> {
356 match self.databases.insert(
357 DatabaseKey { id },
358 DatabaseValue {
359 name: database_name.to_string(),
360 owner_id,
361 privileges,
362 oid,
363 },
364 self.op_id,
365 ) {
366 Ok(_) => Ok(oid),
367 Err(_) => Err(SqlCatalogError::DatabaseAlreadyExists(database_name.to_owned()).into()),
368 }
369 }
370
371 pub fn insert_user_schema(
372 &mut self,
373 database_id: DatabaseId,
374 schema_name: &str,
375 owner_id: RoleId,
376 privileges: Vec<MzAclItem>,
377 temporary_oids: &HashSet<u32>,
378 ) -> Result<(SchemaId, u32), CatalogError> {
379 let id = self.get_and_increment_id(SCHEMA_ID_ALLOC_KEY.to_string())?;
380 let id = SchemaId::User(id);
381 let oid = self.allocate_oid(temporary_oids)?;
382 self.insert_schema(
383 id,
384 Some(database_id),
385 schema_name.to_string(),
386 owner_id,
387 privileges,
388 oid,
389 )?;
390 Ok((id, oid))
391 }
392
393 pub fn insert_system_schema(
394 &mut self,
395 schema_id: u64,
396 schema_name: &str,
397 owner_id: RoleId,
398 privileges: Vec<MzAclItem>,
399 oid: u32,
400 ) -> Result<(), CatalogError> {
401 let id = SchemaId::System(schema_id);
402 self.insert_schema(id, None, schema_name.to_string(), owner_id, privileges, oid)
403 }
404
405 pub(crate) fn insert_schema(
406 &mut self,
407 schema_id: SchemaId,
408 database_id: Option<DatabaseId>,
409 schema_name: String,
410 owner_id: RoleId,
411 privileges: Vec<MzAclItem>,
412 oid: u32,
413 ) -> Result<(), CatalogError> {
414 match self.schemas.insert(
415 SchemaKey { id: schema_id },
416 SchemaValue {
417 database_id,
418 name: schema_name.clone(),
419 owner_id,
420 privileges,
421 oid,
422 },
423 self.op_id,
424 ) {
425 Ok(_) => Ok(()),
426 Err(_) => Err(SqlCatalogError::SchemaAlreadyExists(schema_name).into()),
427 }
428 }
429
430 pub fn insert_builtin_role(
431 &mut self,
432 id: RoleId,
433 name: String,
434 attributes: RoleAttributesRaw,
435 membership: RoleMembership,
436 vars: RoleVars,
437 oid: u32,
438 ) -> Result<RoleId, CatalogError> {
439 soft_assert_or_log!(id.is_builtin(), "ID {id:?} is not builtin");
440 self.insert_role(id, name, attributes, membership, vars, oid)?;
441 Ok(id)
442 }
443
444 pub fn insert_user_role(
445 &mut self,
446 name: String,
447 attributes: RoleAttributesRaw,
448 membership: RoleMembership,
449 vars: RoleVars,
450 temporary_oids: &HashSet<u32>,
451 ) -> Result<(RoleId, u32), CatalogError> {
452 let id = self.get_and_increment_id(USER_ROLE_ID_ALLOC_KEY.to_string())?;
453 let id = RoleId::User(id);
454 let oid = self.allocate_oid(temporary_oids)?;
455 self.insert_role(id, name, attributes, membership, vars, oid)?;
456 Ok((id, oid))
457 }
458
459 fn insert_role(
460 &mut self,
461 id: RoleId,
462 name: String,
463 attributes: RoleAttributesRaw,
464 membership: RoleMembership,
465 vars: RoleVars,
466 oid: u32,
467 ) -> Result<(), CatalogError> {
468 if let Some(ref password) = attributes.password {
469 let hash = mz_auth::hash::scram256_hash(
470 password,
471 &attributes
472 .scram_iterations
473 .or_else(|| {
474 soft_panic_or_log!(
475 "Hash iterations must be set if a password is provided."
476 );
477 None
478 })
479 .unwrap_or_else(|| NonZeroU32::new(600_000).expect("known valid")),
482 )
483 .expect("password hash should be valid");
484 match self.role_auth.insert(
485 RoleAuthKey { role_id: id },
486 RoleAuthValue {
487 password_hash: Some(hash),
488 updated_at: SYSTEM_TIME(),
489 },
490 self.op_id,
491 ) {
492 Ok(_) => {}
493 Err(_) => {
494 return Err(SqlCatalogError::RoleAlreadyExists(name).into());
495 }
496 }
497 }
498
499 match self.roles.insert(
500 RoleKey { id },
501 RoleValue {
502 name: name.clone(),
503 attributes: attributes.into(),
504 membership,
505 vars,
506 oid,
507 },
508 self.op_id,
509 ) {
510 Ok(_) => Ok(()),
511 Err(_) => Err(SqlCatalogError::RoleAlreadyExists(name).into()),
512 }
513 }
514
515 pub fn insert_user_cluster(
517 &mut self,
518 cluster_id: ClusterId,
519 cluster_name: &str,
520 introspection_source_indexes: Vec<(&'static BuiltinLog, CatalogItemId, GlobalId)>,
521 owner_id: RoleId,
522 privileges: Vec<MzAclItem>,
523 config: ClusterConfig,
524 temporary_oids: &HashSet<u32>,
525 ) -> Result<(), CatalogError> {
526 self.insert_cluster(
527 cluster_id,
528 cluster_name,
529 introspection_source_indexes,
530 owner_id,
531 privileges,
532 config,
533 temporary_oids,
534 )
535 }
536
537 pub fn insert_system_cluster(
539 &mut self,
540 cluster_name: &str,
541 introspection_source_indexes: Vec<(&'static BuiltinLog, CatalogItemId, GlobalId)>,
542 privileges: Vec<MzAclItem>,
543 owner_id: RoleId,
544 config: ClusterConfig,
545 temporary_oids: &HashSet<u32>,
546 ) -> Result<ClusterId, CatalogError> {
547 let cluster_id = self.get_and_increment_id(SYSTEM_CLUSTER_ID_ALLOC_KEY.to_string())?;
548 let cluster_id = ClusterId::system(cluster_id).ok_or(SqlCatalogError::IdExhaustion)?;
549 self.insert_cluster(
550 cluster_id,
551 cluster_name,
552 introspection_source_indexes,
553 owner_id,
554 privileges,
555 config,
556 temporary_oids,
557 )?;
558 Ok(cluster_id)
559 }
560
561 fn insert_cluster(
562 &mut self,
563 cluster_id: ClusterId,
564 cluster_name: &str,
565 introspection_source_indexes: Vec<(&'static BuiltinLog, CatalogItemId, GlobalId)>,
566 owner_id: RoleId,
567 privileges: Vec<MzAclItem>,
568 config: ClusterConfig,
569 temporary_oids: &HashSet<u32>,
570 ) -> Result<(), CatalogError> {
571 self.validate_query_policy_reference(config.query_policy)?;
572 if let Err(_) = self.clusters.insert(
573 ClusterKey { id: cluster_id },
574 ClusterValue {
575 name: cluster_name.to_string(),
576 owner_id,
577 privileges,
578 config,
579 },
580 self.op_id,
581 ) {
582 return Err(SqlCatalogError::ClusterAlreadyExists(cluster_name.to_owned()).into());
583 };
584
585 let amount = usize_to_u64(introspection_source_indexes.len());
586 let oids = self.allocate_oids(amount, temporary_oids)?;
587 let introspection_source_indexes: Vec<_> = introspection_source_indexes
588 .into_iter()
589 .zip_eq(oids)
590 .map(|((builtin, item_id, index_id), oid)| (builtin, item_id, index_id, oid))
591 .collect();
592 for (builtin, item_id, index_id, oid) in introspection_source_indexes {
593 let introspection_source_index = IntrospectionSourceIndex {
594 cluster_id,
595 name: builtin.name.to_string(),
596 item_id,
597 index_id,
598 oid,
599 };
600 let (key, value) = introspection_source_index.into_key_value();
601 self.introspection_sources
602 .insert(key, value, self.op_id)
603 .expect("no uniqueness violation");
604 }
605
606 Ok(())
607 }
608
609 pub fn rename_cluster(
610 &mut self,
611 cluster_id: ClusterId,
612 cluster_name: &str,
613 cluster_to_name: &str,
614 ) -> Result<(), CatalogError> {
615 let key = ClusterKey { id: cluster_id };
616
617 match self.clusters.update(
618 |k, v| {
619 if *k == key {
620 let mut value = v.clone();
621 value.name = cluster_to_name.to_string();
622 Some(value)
623 } else {
624 None
625 }
626 },
627 self.op_id,
628 )? {
629 Diff::ZERO => Err(SqlCatalogError::UnknownCluster(cluster_name.to_string()).into()),
630 Diff::ONE => Ok(()),
631 n => panic!(
632 "Expected to update single cluster {cluster_name} ({cluster_id}), updated {n}"
633 ),
634 }
635 }
636
637 pub fn rename_cluster_replica(
638 &mut self,
639 replica_id: ReplicaId,
640 replica_name: &QualifiedReplica,
641 replica_to_name: &str,
642 ) -> Result<(), CatalogError> {
643 let key = ClusterReplicaKey { id: replica_id };
644
645 match self.cluster_replicas.update(
646 |k, v| {
647 if *k == key {
648 let mut value = v.clone();
649 value.name = replica_to_name.to_string();
650 Some(value)
651 } else {
652 None
653 }
654 },
655 self.op_id,
656 )? {
657 Diff::ZERO => {
658 Err(SqlCatalogError::UnknownClusterReplica(replica_name.to_string()).into())
659 }
660 Diff::ONE => Ok(()),
661 n => panic!(
662 "Expected to update single cluster replica {replica_name} ({replica_id}), updated {n}"
663 ),
664 }
665 }
666
667 pub fn insert_cluster_replica_with_id(
668 &mut self,
669 cluster_id: ClusterId,
670 replica_id: ReplicaId,
671 replica_name: &str,
672 config: ReplicaConfig,
673 owner_id: RoleId,
674 ) -> Result<(), CatalogError> {
675 if let Err(_) = self.cluster_replicas.insert(
676 ClusterReplicaKey { id: replica_id },
677 ClusterReplicaValue {
678 cluster_id,
679 name: replica_name.into(),
680 config,
681 owner_id,
682 },
683 self.op_id,
684 ) {
685 let cluster = self
686 .clusters
687 .get(&ClusterKey { id: cluster_id })
688 .expect("cluster exists");
689 return Err(SqlCatalogError::DuplicateReplica(
690 replica_name.to_string(),
691 cluster.name.to_string(),
692 )
693 .into());
694 };
695 Ok(())
696 }
697
698 pub fn insert_user_query_policy(
699 &mut self,
700 name: String,
701 mode: QueryPolicyMode,
702 rules: Vec<QueryPolicyRule>,
703 privileges: Vec<MzAclItem>,
704 owner_id: RoleId,
705 temporary_oids: &HashSet<u32>,
706 ) -> Result<QueryPolicyId, CatalogError> {
707 let oid = self.allocate_oid(temporary_oids)?;
708 let id = QueryPolicyId::User(
709 self.get_and_increment_id(USER_QUERY_POLICY_ID_ALLOC_KEY.to_string())?,
710 );
711 self.query_policies
712 .insert(
713 QueryPolicyKey { id },
714 QueryPolicyValue {
715 name: name.clone(),
716 mode,
717 rules,
718 privileges,
719 owner_id,
720 oid,
721 },
722 self.op_id,
723 )
724 .map_err(|_| SqlCatalogError::QueryPolicyAlreadyExists(name))?;
725 Ok(id)
726 }
727
728 pub fn update_query_policy(&mut self, policy: QueryPolicy) -> Result<(), CatalogError> {
729 let id = policy.id;
730 let (key, value) = policy.into_key_value();
731 if self.query_policies.update_by_key(key, value, self.op_id)? {
732 Ok(())
733 } else {
734 Err(SqlCatalogError::UnknownQueryPolicy(id.to_string()).into())
735 }
736 }
737
738 pub fn remove_query_policies(
740 &mut self,
741 ids: &BTreeSet<QueryPolicyId>,
742 cascade: bool,
743 ) -> Result<Vec<ClusterId>, CatalogError> {
744 let mut detached_clusters = Vec::new();
745 if ids.is_empty() {
746 return Ok(detached_clusters);
747 }
748 if !cascade {
749 for policy in self
752 .clusters
753 .items()
754 .values()
755 .filter_map(|c| c.config.query_policy)
756 {
757 if ids.contains(&policy) {
758 let policy = self
759 .query_policies
760 .get(&QueryPolicyKey { id: policy })
761 .expect("referenced query policy exists");
762 return Err(SqlCatalogError::QueryPolicyInUse(policy.name.clone()).into());
763 }
764 }
765 } else {
766 let clusters: Vec<_> = self
767 .clusters
768 .items()
769 .into_iter()
770 .filter_map(|(key, value)| {
771 value
772 .config
773 .query_policy
774 .filter(|id| ids.contains(id))
775 .map(|_| {
776 let mut value = value.clone();
777 value.config.query_policy = None;
778 (key.clone(), value)
779 })
780 })
781 .collect();
782 detached_clusters = clusters.iter().map(|(key, _)| key.id).collect();
783 self.clusters.update_by_keys(clusters, self.op_id)?;
784 }
785 let to_remove = ids
786 .iter()
787 .map(|id| (QueryPolicyKey { id: *id }, None))
788 .collect();
789 let previous = self.query_policies.set_many(to_remove, self.op_id)?;
790 for (key, value) in previous {
791 assert!(key.id.is_user(), "cannot delete non-user query policy");
792 if value.is_none() {
793 return Err(SqlCatalogError::UnknownQueryPolicy(key.id.to_string()).into());
794 }
795 }
796 Ok(detached_clusters)
797 }
798
799 fn validate_query_policy_reference(
800 &self,
801 id: Option<QueryPolicyId>,
802 ) -> Result<(), CatalogError> {
803 if let Some(id) = id {
804 if self.query_policies.get(&QueryPolicyKey { id }).is_none() {
805 return Err(SqlCatalogError::UnknownQueryPolicy(id.to_string()).into());
806 }
807 }
808 Ok(())
809 }
810
811 pub fn insert_user_network_policy(
812 &mut self,
813 name: String,
814 rules: Vec<NetworkPolicyRule>,
815 privileges: Vec<MzAclItem>,
816 owner_id: RoleId,
817 temporary_oids: &HashSet<u32>,
818 ) -> Result<NetworkPolicyId, CatalogError> {
819 let oid = self.allocate_oid(temporary_oids)?;
820 let id = self.get_and_increment_id(USER_NETWORK_POLICY_ID_ALLOC_KEY.to_string())?;
821 let id = NetworkPolicyId::User(id);
822 self.insert_network_policy(id, name, rules, privileges, owner_id, oid)
823 }
824
825 pub fn insert_network_policy(
826 &mut self,
827 id: NetworkPolicyId,
828 name: String,
829 rules: Vec<NetworkPolicyRule>,
830 privileges: Vec<MzAclItem>,
831 owner_id: RoleId,
832 oid: u32,
833 ) -> Result<NetworkPolicyId, CatalogError> {
834 match self.network_policies.insert(
835 NetworkPolicyKey { id },
836 NetworkPolicyValue {
837 name: name.clone(),
838 rules,
839 privileges,
840 owner_id,
841 oid,
842 },
843 self.op_id,
844 ) {
845 Ok(_) => Ok(id),
846 Err(_) => Err(SqlCatalogError::NetworkPolicyAlreadyExists(name).into()),
847 }
848 }
849
850 pub fn update_introspection_source_index_gids(
855 &mut self,
856 mappings: impl Iterator<
857 Item = (
858 ClusterId,
859 impl Iterator<Item = (String, CatalogItemId, GlobalId, u32)>,
860 ),
861 >,
862 ) -> Result<(), CatalogError> {
863 for (cluster_id, updates) in mappings {
864 for (name, item_id, index_id, oid) in updates {
865 let introspection_source_index = IntrospectionSourceIndex {
866 cluster_id,
867 name,
868 item_id,
869 index_id,
870 oid,
871 };
872 let (key, value) = introspection_source_index.into_key_value();
873
874 let prev = self
875 .introspection_sources
876 .set(key, Some(value), self.op_id)?;
877 if prev.is_none() {
878 return Err(SqlCatalogError::FailedBuiltinSchemaMigration(format!(
879 "{index_id}"
880 ))
881 .into());
882 }
883 }
884 }
885 Ok(())
886 }
887
888 pub fn insert_user_item(
889 &mut self,
890 id: CatalogItemId,
891 global_id: GlobalId,
892 schema_id: SchemaId,
893 item_name: &str,
894 create_sql: String,
895 owner_id: RoleId,
896 privileges: Vec<MzAclItem>,
897 temporary_oids: &HashSet<u32>,
898 versions: BTreeMap<RelationVersion, GlobalId>,
899 ephemeral_owner_session: Option<Uuid>,
900 ) -> Result<u32, CatalogError> {
901 let oid = self.allocate_oid(temporary_oids)?;
902 self.insert_item(
903 id,
904 oid,
905 global_id,
906 schema_id,
907 item_name,
908 create_sql,
909 owner_id,
910 privileges,
911 versions,
912 ephemeral_owner_session,
913 )?;
914 Ok(oid)
915 }
916
917 pub fn insert_item(
918 &mut self,
919 id: CatalogItemId,
920 oid: u32,
921 global_id: GlobalId,
922 schema_id: SchemaId,
923 item_name: &str,
924 create_sql: String,
925 owner_id: RoleId,
926 privileges: Vec<MzAclItem>,
927 extra_versions: BTreeMap<RelationVersion, GlobalId>,
928 ephemeral_owner_session: Option<Uuid>,
929 ) -> Result<(), CatalogError> {
930 match self.items.insert(
931 ItemKey { id },
932 ItemValue {
933 schema_id,
934 name: item_name.to_string(),
935 create_sql,
936 owner_id,
937 privileges,
938 oid,
939 global_id,
940 extra_versions,
941 ephemeral_owner_session,
942 },
943 self.op_id,
944 ) {
945 Ok(_) => Ok(()),
946 Err(_) => Err(SqlCatalogError::ItemAlreadyExists(id, item_name.to_owned()).into()),
947 }
948 }
949
950 pub fn set_item_metadata(
953 &mut self,
954 id: CatalogItemId,
955 metadata: ItemMetadata,
956 ) -> Result<(), CatalogError> {
957 let ItemMetadata {
958 columns,
959 index_columns,
960 } = metadata;
961 let columns = (!columns.is_empty()).then_some(ItemColumnsValue { columns });
964 let key = ItemColumnsKey { id };
965 if self.item_columns.get(&key) != columns.as_ref() {
966 self.item_columns.set(key, columns, self.op_id)?;
967 }
968 let index_columns = (!index_columns.is_empty()).then_some(IndexColumnsValue {
969 columns: index_columns,
970 });
971 let key = IndexColumnsKey { id };
972 if self.index_columns.get(&key) != index_columns.as_ref() {
973 self.index_columns.set(key, index_columns, self.op_id)?;
974 }
975 Ok(())
976 }
977
978 fn delete_item_metadata(&mut self, id: CatalogItemId) {
980 self.item_columns
981 .delete_by_key(ItemColumnsKey { id }, self.op_id);
982 self.index_columns
983 .delete_by_key(IndexColumnsKey { id }, self.op_id);
984 }
985
986 pub fn remove_ephemeral_items(&mut self) {
1002 let mut keys = Vec::new();
1003 let mut item_ids = BTreeSet::new();
1004 let mut global_ids = BTreeSet::new();
1005 for (key, value) in self.items.items() {
1006 if value.ephemeral_owner_session.is_none() {
1007 continue;
1008 }
1009 item_ids.insert(key.id);
1010 global_ids.insert(value.global_id);
1011 global_ids.extend(value.extra_versions.values().copied());
1012 keys.push(key.clone());
1013 }
1014 self.items.delete_by_keys(keys, self.op_id);
1015 for id in &item_ids {
1016 self.delete_item_metadata(*id);
1017 }
1018
1019 let dropped_mappings = self.delete_collection_metadata(global_ids);
1027 let mut dropped_shards: BTreeSet<_> = dropped_mappings
1028 .into_iter()
1029 .map(|(_, shard)| shard)
1030 .collect();
1031 let live_shards: BTreeSet<_> = self.get_collection_metadata().into_values().collect();
1032 dropped_shards.retain(|shard| {
1033 let live = live_shards.contains(shard);
1034 if live {
1035 soft_panic_or_log!(
1036 "shard {shard} of a reclaimed ephemeral item is still referenced by a \
1037 live collection, not finalizing it"
1038 );
1039 }
1040 !live
1041 });
1042 self.insert_unfinalized_shards(dropped_shards).expect(
1043 "inserting unfinalized shards only fails on duplicate values, which it ignores",
1044 );
1045
1046 self.comments.delete(
1049 |key, _value| match key.object_id {
1050 CommentObjectId::Table(item_id)
1051 | CommentObjectId::View(item_id)
1052 | CommentObjectId::MaterializedView(item_id)
1053 | CommentObjectId::Source(item_id)
1054 | CommentObjectId::Sink(item_id)
1055 | CommentObjectId::MetricSink(item_id)
1056 | CommentObjectId::Index(item_id)
1057 | CommentObjectId::Func(item_id)
1058 | CommentObjectId::Connection(item_id)
1059 | CommentObjectId::Type(item_id)
1060 | CommentObjectId::Secret(item_id) => item_ids.contains(&item_id),
1061 CommentObjectId::Role(_)
1062 | CommentObjectId::Database(_)
1063 | CommentObjectId::Schema(_)
1064 | CommentObjectId::Cluster(_)
1065 | CommentObjectId::ClusterReplica(_)
1066 | CommentObjectId::QueryPolicy(_)
1067 | CommentObjectId::NetworkPolicy(_) => false,
1068 },
1069 self.op_id,
1070 );
1071
1072 self.source_references
1075 .delete(|key, _value| item_ids.contains(&key.source_id), self.op_id);
1076 }
1077
1078 pub fn get_and_increment_id(&mut self, key: String) -> Result<u64, CatalogError> {
1079 Ok(self.get_and_increment_id_by(key, 1)?.into_element())
1080 }
1081
1082 pub fn get_and_increment_id_by(
1083 &mut self,
1084 key: String,
1085 amount: u64,
1086 ) -> Result<Vec<u64>, CatalogError> {
1087 assert!(
1088 key != SYSTEM_ITEM_ALLOC_KEY || !self.durable_catalog.is_bootstrap_complete(),
1089 "system item IDs cannot be allocated outside of bootstrap"
1090 );
1091
1092 let current_id = self
1093 .id_allocator
1094 .items()
1095 .get(&IdAllocKey { name: key.clone() })
1096 .unwrap_or_else(|| panic!("{key} id allocator missing"))
1097 .next_id;
1098 let next_id = current_id
1099 .checked_add(amount)
1100 .ok_or(SqlCatalogError::IdExhaustion)?;
1101 let prev = self.id_allocator.set(
1102 IdAllocKey { name: key },
1103 Some(IdAllocValue { next_id }),
1104 self.op_id,
1105 )?;
1106 assert_eq!(
1107 prev,
1108 Some(IdAllocValue {
1109 next_id: current_id
1110 })
1111 );
1112 Ok((current_id..next_id).collect())
1113 }
1114
1115 pub fn allocate_system_item_ids(
1116 &mut self,
1117 amount: u64,
1118 ) -> Result<Vec<(CatalogItemId, GlobalId)>, CatalogError> {
1119 assert!(
1120 !self.durable_catalog.is_bootstrap_complete(),
1121 "we can only allocate system item IDs during bootstrap"
1122 );
1123 Ok(self
1124 .get_and_increment_id_by(SYSTEM_ITEM_ALLOC_KEY.to_string(), amount)?
1125 .into_iter()
1126 .map(|x| (CatalogItemId::System(x), GlobalId::System(x)))
1128 .collect())
1129 }
1130
1131 pub fn allocate_introspection_source_index_id(
1163 cluster_id: &ClusterId,
1164 log_variant: LogVariant,
1165 ) -> (CatalogItemId, GlobalId) {
1166 let cluster_variant: u8 = match cluster_id {
1167 ClusterId::System(_) => 1,
1168 ClusterId::User(_) => 2,
1169 };
1170 let cluster_id: u64 = cluster_id.inner_id();
1171 const CLUSTER_ID_MASK: u64 = 0xFFFF << 48;
1172 assert_eq!(
1173 CLUSTER_ID_MASK & cluster_id,
1174 0,
1175 "invalid cluster ID: {cluster_id}"
1176 );
1177 let log_variant: u8 = match log_variant {
1178 LogVariant::Timely(TimelyLog::Operates) => 1,
1179 LogVariant::Timely(TimelyLog::Channels) => 2,
1180 LogVariant::Timely(TimelyLog::Elapsed) => 3,
1181 LogVariant::Timely(TimelyLog::Histogram) => 4,
1182 LogVariant::Timely(TimelyLog::Addresses) => 5,
1183 LogVariant::Timely(TimelyLog::Parks) => 6,
1184 LogVariant::Timely(TimelyLog::MessagesSent) => 7,
1185 LogVariant::Timely(TimelyLog::MessagesReceived) => 8,
1186 LogVariant::Timely(TimelyLog::Reachability) => 9,
1187 LogVariant::Timely(TimelyLog::BatchesSent) => 10,
1188 LogVariant::Timely(TimelyLog::BatchesReceived) => 11,
1189 LogVariant::Differential(DifferentialLog::ArrangementBatches) => 12,
1190 LogVariant::Differential(DifferentialLog::ArrangementRecords) => 13,
1191 LogVariant::Differential(DifferentialLog::Sharing) => 14,
1192 LogVariant::Differential(DifferentialLog::BatcherRecords) => 15,
1193 LogVariant::Differential(DifferentialLog::BatcherSize) => 16,
1194 LogVariant::Differential(DifferentialLog::BatcherCapacity) => 17,
1195 LogVariant::Differential(DifferentialLog::BatcherAllocations) => 18,
1196 LogVariant::Compute(ComputeLog::DataflowCurrent) => 19,
1197 LogVariant::Compute(ComputeLog::FrontierCurrent) => 20,
1198 LogVariant::Compute(ComputeLog::PeekCurrent) => 21,
1199 LogVariant::Compute(ComputeLog::PeekDuration) => 22,
1200 LogVariant::Compute(ComputeLog::ImportFrontierCurrent) => 23,
1201 LogVariant::Compute(ComputeLog::ArrangementHeapSize) => 24,
1202 LogVariant::Compute(ComputeLog::ArrangementHeapCapacity) => 25,
1203 LogVariant::Compute(ComputeLog::ArrangementHeapAllocations) => 26,
1204 LogVariant::Compute(ComputeLog::ErrorCount) => 28,
1205 LogVariant::Compute(ComputeLog::HydrationTime) => 29,
1206 LogVariant::Compute(ComputeLog::LirMapping) => 30,
1207 LogVariant::Compute(ComputeLog::DataflowGlobal) => 31,
1208 LogVariant::Compute(ComputeLog::OperatorHydrationStatus) => 32,
1209 LogVariant::Compute(ComputeLog::PrometheusMetrics) => 33,
1210 LogVariant::Compute(ComputeLog::ResourceUsage) => 34,
1211 };
1212
1213 let mut id: u64 = u64::from(cluster_variant) << 56;
1214 id |= cluster_id << 8;
1215 id |= u64::from(log_variant);
1216
1217 (
1218 CatalogItemId::IntrospectionSourceIndex(id),
1219 GlobalId::IntrospectionSourceIndex(id),
1220 )
1221 }
1222
1223 pub fn allocate_user_item_ids(
1224 &mut self,
1225 amount: u64,
1226 ) -> Result<Vec<(CatalogItemId, GlobalId)>, CatalogError> {
1227 Ok(self
1228 .get_and_increment_id_by(USER_ITEM_ALLOC_KEY.to_string(), amount)?
1229 .into_iter()
1230 .map(|x| (CatalogItemId::User(x), GlobalId::User(x)))
1232 .collect())
1233 }
1234
1235 pub fn allocate_system_replica_id(&mut self) -> Result<ReplicaId, CatalogError> {
1236 let id = self.get_and_increment_id(SYSTEM_REPLICA_ID_ALLOC_KEY.to_string())?;
1237 Ok(ReplicaId::System(id))
1238 }
1239
1240 pub fn allocate_audit_log_id(&mut self) -> Result<u64, CatalogError> {
1241 self.get_and_increment_id(AUDIT_LOG_ID_ALLOC_KEY.to_string())
1242 }
1243
1244 #[mz_ore::instrument]
1247 fn allocate_oids(
1248 &mut self,
1249 amount: u64,
1250 temporary_oids: &HashSet<u32>,
1251 ) -> Result<Vec<u32>, CatalogError> {
1252 struct UserOid(u32);
1255
1256 impl UserOid {
1257 fn new(oid: u32) -> Result<UserOid, anyhow::Error> {
1258 if oid < FIRST_USER_OID {
1259 Err(anyhow!("invalid user OID {oid}"))
1260 } else {
1261 Ok(UserOid(oid))
1262 }
1263 }
1264 }
1265
1266 impl std::ops::AddAssign<u32> for UserOid {
1267 fn add_assign(&mut self, rhs: u32) {
1268 let (res, overflow) = self.0.overflowing_add(rhs);
1269 self.0 = if overflow { FIRST_USER_OID + res } else { res };
1270 }
1271 }
1272
1273 if amount > u32::MAX.into() {
1274 return Err(CatalogError::Catalog(SqlCatalogError::OidExhaustion));
1275 }
1276
1277 let mut allocated_oids = HashSet::with_capacity(
1283 self.databases.len()
1284 + self.schemas.len()
1285 + self.roles.len()
1286 + self.query_policies.len()
1287 + self.items.len()
1288 + self.introspection_sources.len()
1289 + temporary_oids.len(),
1290 );
1291 self.databases.for_values(|_, value| {
1292 allocated_oids.insert(value.oid);
1293 });
1294 self.schemas.for_values(|_, value| {
1295 allocated_oids.insert(value.oid);
1296 });
1297 self.roles.for_values(|_, value| {
1298 allocated_oids.insert(value.oid);
1299 });
1300 self.query_policies.for_values(|_, value| {
1301 allocated_oids.insert(value.oid);
1302 });
1303 self.items.for_values(|_, value| {
1304 allocated_oids.insert(value.oid);
1305 });
1306 self.introspection_sources.for_values(|_, value| {
1307 allocated_oids.insert(value.oid);
1308 });
1309
1310 let is_allocated = |oid| allocated_oids.contains(&oid) || temporary_oids.contains(&oid);
1311
1312 let start_oid: u32 = self
1313 .id_allocator
1314 .items()
1315 .get(&IdAllocKey {
1316 name: OID_ALLOC_KEY.to_string(),
1317 })
1318 .unwrap_or_else(|| panic!("{OID_ALLOC_KEY} id allocator missing"))
1319 .next_id
1320 .try_into()
1321 .expect("we should never persist an oid outside of the u32 range");
1322 let mut current_oid = UserOid::new(start_oid)
1323 .expect("we should never persist an oid outside of user OID range");
1324 let mut oids = Vec::new();
1325 while oids.len() < u64_to_usize(amount) {
1326 if !is_allocated(current_oid.0) {
1327 oids.push(current_oid.0);
1328 }
1329 current_oid += 1;
1330
1331 if current_oid.0 == start_oid && oids.len() < u64_to_usize(amount) {
1332 return Err(CatalogError::Catalog(SqlCatalogError::OidExhaustion));
1334 }
1335 }
1336
1337 let next_id = current_oid.0;
1338 let prev = self.id_allocator.set(
1339 IdAllocKey {
1340 name: OID_ALLOC_KEY.to_string(),
1341 },
1342 Some(IdAllocValue {
1343 next_id: next_id.into(),
1344 }),
1345 self.op_id,
1346 )?;
1347 assert_eq!(
1348 prev,
1349 Some(IdAllocValue {
1350 next_id: start_oid.into(),
1351 })
1352 );
1353
1354 Ok(oids)
1355 }
1356
1357 pub fn allocate_oid(&mut self, temporary_oids: &HashSet<u32>) -> Result<u32, CatalogError> {
1360 self.allocate_oids(1, temporary_oids)
1361 .map(|oids| oids.into_element())
1362 }
1363
1364 pub fn fork_dry_run(&mut self) -> Result<DryRunTransaction<'_>, CatalogError> {
1369 let snapshot = self.current_snapshot();
1370 let upper = self.upper;
1371 Transaction::new(&mut *self.durable_catalog, snapshot, upper).map(DryRunTransaction::new)
1372 }
1373
1374 pub fn current_snapshot(&self) -> Snapshot {
1382 Snapshot {
1383 databases: self.databases.current_items_proto(),
1384 schemas: self.schemas.current_items_proto(),
1385 roles: self.roles.current_items_proto(),
1386 role_auth: self.role_auth.current_items_proto(),
1387 items: self.items.current_items_proto(),
1388 item_columns: self.item_columns.current_items_proto(),
1389 index_columns: self.index_columns.current_items_proto(),
1390 comments: self.comments.current_items_proto(),
1391 clusters: self.clusters.current_items_proto(),
1392 network_policies: self.network_policies.current_items_proto(),
1393 cluster_replica_sizes: self.cluster_replica_sizes.current_items_proto(),
1394 query_policies: self.query_policies.current_items_proto(),
1395 cluster_replicas: self.cluster_replicas.current_items_proto(),
1396 introspection_sources: self.introspection_sources.current_items_proto(),
1397 id_allocator: self.id_allocator.current_items_proto(),
1398 configs: self.configs.current_items_proto(),
1399 settings: self.settings.current_items_proto(),
1400 system_object_mappings: self.system_gid_mapping.current_items_proto(),
1401 system_configurations: self.system_configurations.current_items_proto(),
1402 cluster_system_configurations: self.cluster_system_configurations.current_items_proto(),
1403 replica_system_configurations: self.replica_system_configurations.current_items_proto(),
1404 default_privileges: self.default_privileges.current_items_proto(),
1405 source_references: self.source_references.current_items_proto(),
1406 system_privileges: self.system_privileges.current_items_proto(),
1407 storage_collection_metadata: self.storage_collection_metadata.current_items_proto(),
1408 unfinalized_shards: self.unfinalized_shards.current_items_proto(),
1409 txn_wal_shard: self.txn_wal_shard.current_items_proto(),
1410 }
1411 }
1412
1413 pub(crate) fn insert_id_allocator(
1414 &mut self,
1415 name: String,
1416 next_id: u64,
1417 ) -> Result<(), CatalogError> {
1418 match self.id_allocator.insert(
1419 IdAllocKey { name: name.clone() },
1420 IdAllocValue { next_id },
1421 self.op_id,
1422 ) {
1423 Ok(_) => Ok(()),
1424 Err(_) => Err(SqlCatalogError::IdAllocatorAlreadyExists(name).into()),
1425 }
1426 }
1427
1428 pub fn remove_database(&mut self, id: &DatabaseId) -> Result<(), CatalogError> {
1435 let prev = self
1436 .databases
1437 .set(DatabaseKey { id: *id }, None, self.op_id)?;
1438 if prev.is_some() {
1439 Ok(())
1440 } else {
1441 Err(SqlCatalogError::UnknownDatabase(id.to_string()).into())
1442 }
1443 }
1444
1445 pub fn remove_databases(
1452 &mut self,
1453 databases: &BTreeSet<DatabaseId>,
1454 ) -> Result<(), CatalogError> {
1455 if databases.is_empty() {
1456 return Ok(());
1457 }
1458
1459 let to_remove = databases
1460 .iter()
1461 .map(|id| (DatabaseKey { id: *id }, None))
1462 .collect();
1463 let mut prev = self.databases.set_many(to_remove, self.op_id)?;
1464 prev.retain(|_k, val| val.is_none());
1465
1466 if !prev.is_empty() {
1467 let err = prev.keys().map(|k| k.id.to_string()).join(", ");
1468 return Err(SqlCatalogError::UnknownDatabase(err).into());
1469 }
1470
1471 Ok(())
1472 }
1473
1474 pub fn remove_schema(
1481 &mut self,
1482 database_id: &Option<DatabaseId>,
1483 schema_id: &SchemaId,
1484 ) -> Result<(), CatalogError> {
1485 let prev = self
1486 .schemas
1487 .set(SchemaKey { id: *schema_id }, None, self.op_id)?;
1488 if prev.is_some() {
1489 Ok(())
1490 } else {
1491 let database_name = match database_id {
1492 Some(id) => format!("{id}."),
1493 None => "".to_string(),
1494 };
1495 Err(SqlCatalogError::UnknownSchema(format!("{}.{}", database_name, schema_id)).into())
1496 }
1497 }
1498
1499 pub fn remove_schemas(
1506 &mut self,
1507 schemas: &BTreeMap<SchemaId, ResolvedDatabaseSpecifier>,
1508 ) -> Result<(), CatalogError> {
1509 if schemas.is_empty() {
1510 return Ok(());
1511 }
1512
1513 let to_remove = schemas
1514 .iter()
1515 .map(|(schema_id, _)| (SchemaKey { id: *schema_id }, None))
1516 .collect();
1517 let mut prev = self.schemas.set_many(to_remove, self.op_id)?;
1518 prev.retain(|_k, v| v.is_none());
1519
1520 if !prev.is_empty() {
1521 let err = prev
1522 .keys()
1523 .map(|k| {
1524 let db_spec = schemas.get(&k.id).expect("should_exist");
1525 let db_name = match db_spec {
1526 ResolvedDatabaseSpecifier::Id(id) => format!("{id}."),
1527 ResolvedDatabaseSpecifier::Ambient => "".to_string(),
1528 };
1529 format!("{}.{}", db_name, k.id)
1530 })
1531 .join(", ");
1532
1533 return Err(SqlCatalogError::UnknownSchema(err).into());
1534 }
1535
1536 Ok(())
1537 }
1538
1539 pub fn remove_source_references(
1540 &mut self,
1541 source_id: CatalogItemId,
1542 ) -> Result<(), CatalogError> {
1543 let deleted = self
1544 .source_references
1545 .delete_by_key(SourceReferencesKey { source_id }, self.op_id)
1546 .is_some();
1547 if deleted {
1548 Ok(())
1549 } else {
1550 Err(SqlCatalogError::UnknownItem(source_id.to_string()).into())
1551 }
1552 }
1553
1554 pub fn remove_user_roles(&mut self, roles: &BTreeSet<RoleId>) -> Result<(), CatalogError> {
1561 assert!(
1562 roles.iter().all(|id| id.is_user()),
1563 "cannot delete non-user roles"
1564 );
1565 self.remove_roles(roles)
1566 }
1567
1568 pub fn remove_roles(&mut self, roles: &BTreeSet<RoleId>) -> Result<(), CatalogError> {
1575 if roles.is_empty() {
1576 return Ok(());
1577 }
1578
1579 let to_remove_keys = roles
1580 .iter()
1581 .map(|role_id| RoleKey { id: *role_id })
1582 .collect::<Vec<_>>();
1583
1584 let to_remove_roles = to_remove_keys
1585 .iter()
1586 .map(|role_key| (role_key.clone(), None))
1587 .collect();
1588
1589 let mut prev = self.roles.set_many(to_remove_roles, self.op_id)?;
1590
1591 let to_remove_role_auth = to_remove_keys
1592 .iter()
1593 .map(|role_key| {
1594 (
1595 RoleAuthKey {
1596 role_id: role_key.id,
1597 },
1598 None,
1599 )
1600 })
1601 .collect();
1602
1603 let mut role_auth_prev = self.role_auth.set_many(to_remove_role_auth, self.op_id)?;
1604
1605 prev.retain(|_k, v| v.is_none());
1606 if !prev.is_empty() {
1607 let err = prev.keys().map(|k| k.id.to_string()).join(", ");
1608 return Err(SqlCatalogError::UnknownRole(err).into());
1609 }
1610
1611 role_auth_prev.retain(|_k, v| v.is_none());
1612 Ok(())
1616 }
1617
1618 pub fn remove_clusters(&mut self, clusters: &BTreeSet<ClusterId>) -> Result<(), CatalogError> {
1625 if clusters.is_empty() {
1626 return Ok(());
1627 }
1628
1629 let to_remove = clusters
1630 .iter()
1631 .map(|cluster_id| (ClusterKey { id: *cluster_id }, None))
1632 .collect();
1633 let mut prev = self.clusters.set_many(to_remove, self.op_id)?;
1634
1635 prev.retain(|_k, v| v.is_none());
1636 if !prev.is_empty() {
1637 let err = prev.keys().map(|k| k.id.to_string()).join(", ");
1638 return Err(SqlCatalogError::UnknownCluster(err).into());
1639 }
1640
1641 self.cluster_replicas
1647 .delete(|_k, v| clusters.contains(&v.cluster_id), self.op_id);
1648 self.introspection_sources
1649 .delete(|k, _v| clusters.contains(&k.cluster_id), self.op_id);
1650
1651 Ok(())
1652 }
1653
1654 pub fn remove_cluster_replica(&mut self, id: ReplicaId) -> Result<(), CatalogError> {
1661 let deleted = self
1662 .cluster_replicas
1663 .delete_by_key(ClusterReplicaKey { id }, self.op_id)
1664 .is_some();
1665 if deleted {
1666 Ok(())
1667 } else {
1668 Err(SqlCatalogError::UnknownClusterReplica(id.to_string()).into())
1669 }
1670 }
1671
1672 pub fn remove_cluster_replicas(
1679 &mut self,
1680 replicas: &BTreeSet<ReplicaId>,
1681 ) -> Result<(), CatalogError> {
1682 if replicas.is_empty() {
1683 return Ok(());
1684 }
1685
1686 let to_remove = replicas
1687 .iter()
1688 .map(|replica_id| (ClusterReplicaKey { id: *replica_id }, None))
1689 .collect();
1690 let mut prev = self.cluster_replicas.set_many(to_remove, self.op_id)?;
1691
1692 prev.retain(|_k, v| v.is_none());
1693 if !prev.is_empty() {
1694 let err = prev.keys().map(|k| k.id.to_string()).join(", ");
1695 return Err(SqlCatalogError::UnknownClusterReplica(err).into());
1696 }
1697
1698 Ok(())
1699 }
1700
1701 pub fn remove_item(&mut self, id: CatalogItemId) -> Result<(), CatalogError> {
1708 let prev = self.items.set(ItemKey { id }, None, self.op_id)?;
1709 if prev.is_some() {
1710 self.delete_item_metadata(id);
1711 Ok(())
1712 } else {
1713 Err(SqlCatalogError::UnknownItem(id.to_string()).into())
1714 }
1715 }
1716
1717 pub fn remove_items(&mut self, ids: &BTreeSet<CatalogItemId>) -> Result<(), CatalogError> {
1724 if ids.is_empty() {
1725 return Ok(());
1726 }
1727
1728 let ks: Vec<_> = ids.clone().into_iter().map(|id| ItemKey { id }).collect();
1729 let n = self.items.delete_by_keys(ks, self.op_id).len();
1730 for id in ids {
1731 self.delete_item_metadata(*id);
1732 }
1733 if n == ids.len() {
1734 Ok(())
1735 } else {
1736 let item_ids = self.items.items().keys().map(|k| k.id).collect();
1737 let mut unknown = ids.difference(&item_ids);
1738 Err(SqlCatalogError::UnknownItem(unknown.join(", ")).into())
1739 }
1740 }
1741
1742 pub fn remove_system_object_mappings(
1749 &mut self,
1750 descriptions: BTreeSet<SystemObjectDescription>,
1751 ) -> Result<(), CatalogError> {
1752 if descriptions.is_empty() {
1753 return Ok(());
1754 }
1755
1756 let ks: Vec<_> = descriptions
1757 .clone()
1758 .into_iter()
1759 .map(|desc| GidMappingKey {
1760 schema_name: desc.schema_name,
1761 object_type: desc.object_type,
1762 object_name: desc.object_name,
1763 })
1764 .collect();
1765 let n = self.system_gid_mapping.delete_by_keys(ks, self.op_id).len();
1766
1767 if n == descriptions.len() {
1768 Ok(())
1769 } else {
1770 let item_descriptions = self
1771 .system_gid_mapping
1772 .items()
1773 .keys()
1774 .map(|k| SystemObjectDescription {
1775 schema_name: k.schema_name.clone(),
1776 object_type: k.object_type.clone(),
1777 object_name: k.object_name.clone(),
1778 })
1779 .collect();
1780 let mut unknown = descriptions.difference(&item_descriptions).map(|desc| {
1781 format!(
1782 "{} {}.{}",
1783 desc.object_type, desc.schema_name, desc.object_name
1784 )
1785 });
1786 Err(SqlCatalogError::UnknownItem(unknown.join(", ")).into())
1787 }
1788 }
1789
1790 pub fn remove_introspection_source_indexes(
1797 &mut self,
1798 introspection_source_indexes: BTreeSet<(ClusterId, String)>,
1799 ) -> Result<(), CatalogError> {
1800 if introspection_source_indexes.is_empty() {
1801 return Ok(());
1802 }
1803
1804 let ks: Vec<_> = introspection_source_indexes
1805 .clone()
1806 .into_iter()
1807 .map(|(cluster_id, name)| ClusterIntrospectionSourceIndexKey { cluster_id, name })
1808 .collect();
1809 let n = self
1810 .introspection_sources
1811 .delete_by_keys(ks, self.op_id)
1812 .len();
1813 if n == introspection_source_indexes.len() {
1814 Ok(())
1815 } else {
1816 let txn_indexes = self
1817 .introspection_sources
1818 .items()
1819 .keys()
1820 .map(|k| (k.cluster_id, k.name.clone()))
1821 .collect();
1822 let mut unknown = introspection_source_indexes
1823 .difference(&txn_indexes)
1824 .map(|(cluster_id, name)| format!("{cluster_id} {name}"));
1825 Err(SqlCatalogError::UnknownItem(unknown.join(", ")).into())
1826 }
1827 }
1828
1829 pub fn update_item(&mut self, id: CatalogItemId, item: Item) -> Result<(), CatalogError> {
1836 let updated =
1837 self.items
1838 .update_by_key(ItemKey { id }, item.into_key_value().1, self.op_id)?;
1839 if updated {
1840 Ok(())
1841 } else {
1842 Err(SqlCatalogError::UnknownItem(id.to_string()).into())
1843 }
1844 }
1845
1846 pub fn update_items(
1854 &mut self,
1855 items: BTreeMap<CatalogItemId, Item>,
1856 ) -> Result<(), CatalogError> {
1857 if items.is_empty() {
1858 return Ok(());
1859 }
1860
1861 let update_ids: BTreeSet<_> = items.keys().cloned().collect();
1862 let kvs: Vec<_> = items
1863 .clone()
1864 .into_iter()
1865 .map(|(id, item)| (ItemKey { id }, item.into_key_value().1))
1866 .collect();
1867 let n = self.items.update_by_keys(kvs, self.op_id)?;
1868 let n = usize::try_from(n.into_inner()).expect("Must be positive and fit in usize");
1869 if n == update_ids.len() {
1870 Ok(())
1871 } else {
1872 let item_ids: BTreeSet<_> = self.items.items().keys().map(|k| k.id).collect();
1873 let mut unknown = update_ids.difference(&item_ids);
1874 Err(SqlCatalogError::UnknownItem(unknown.join(", ")).into())
1875 }
1876 }
1877
1878 pub fn update_role(
1886 &mut self,
1887 id: RoleId,
1888 role: Role,
1889 password: PasswordAction,
1890 ) -> Result<(), CatalogError> {
1891 let key = RoleKey { id };
1892 if self.roles.get(&key).is_some() {
1893 let auth_key = RoleAuthKey { role_id: id };
1894
1895 match password {
1896 PasswordAction::Set(new_password) => {
1897 let hash = mz_auth::hash::scram256_hash(
1898 &new_password.password,
1899 &new_password.scram_iterations,
1900 )
1901 .expect("password hash should be valid");
1902 let value = RoleAuthValue {
1903 password_hash: Some(hash),
1904 updated_at: SYSTEM_TIME(),
1905 };
1906
1907 if self.role_auth.get(&auth_key).is_some() {
1908 self.role_auth
1909 .update_by_key(auth_key.clone(), value, self.op_id)?;
1910 } else {
1911 self.role_auth.insert(auth_key.clone(), value, self.op_id)?;
1912 }
1913 }
1914 PasswordAction::Clear => {
1915 let value = RoleAuthValue {
1916 password_hash: None,
1917 updated_at: SYSTEM_TIME(),
1918 };
1919 if self.role_auth.get(&auth_key).is_some() {
1920 self.role_auth
1921 .update_by_key(auth_key.clone(), value, self.op_id)?;
1922 }
1923 }
1924 PasswordAction::NoChange => {}
1925 }
1926
1927 self.roles
1928 .update_by_key(key, role.into_key_value().1, self.op_id)?;
1929
1930 Ok(())
1931 } else {
1932 Err(SqlCatalogError::UnknownRole(id.to_string()).into())
1933 }
1934 }
1935
1936 pub fn update_roles_without_auth(
1947 &mut self,
1948 roles: BTreeMap<RoleId, Role>,
1949 ) -> Result<(), CatalogError> {
1950 if roles.is_empty() {
1951 return Ok(());
1952 }
1953
1954 let update_role_ids: BTreeSet<_> = roles.keys().cloned().collect();
1955 let kvs: Vec<_> = roles
1956 .into_iter()
1957 .map(|(id, role)| (RoleKey { id }, role.into_key_value().1))
1958 .collect();
1959 let n = self.roles.update_by_keys(kvs, self.op_id)?;
1960 let n = usize::try_from(n.into_inner()).expect("Must be positive and fit in usize");
1961
1962 if n == update_role_ids.len() {
1963 Ok(())
1964 } else {
1965 let role_ids: BTreeSet<_> = self.roles.items().keys().map(|k| k.id).collect();
1966 let mut unknown = update_role_ids.difference(&role_ids);
1967 Err(SqlCatalogError::UnknownRole(unknown.join(", ")).into())
1968 }
1969 }
1970
1971 pub fn update_system_object_mappings(
1976 &mut self,
1977 mappings: BTreeMap<CatalogItemId, SystemObjectMapping>,
1978 ) -> Result<(), CatalogError> {
1979 if mappings.is_empty() {
1980 return Ok(());
1981 }
1982
1983 let n = self.system_gid_mapping.update(
1984 |_k, v| {
1985 if let Some(mapping) = mappings.get(&CatalogItemId::from(v.catalog_id)) {
1986 let (_, new_value) = mapping.clone().into_key_value();
1987 Some(new_value)
1988 } else {
1989 None
1990 }
1991 },
1992 self.op_id,
1993 )?;
1994
1995 if usize::try_from(n.into_inner()).expect("update diff should fit into usize")
1996 != mappings.len()
1997 {
1998 let id_str = mappings.keys().map(|id| id.to_string()).join(",");
1999 return Err(SqlCatalogError::FailedBuiltinSchemaMigration(id_str).into());
2000 }
2001
2002 Ok(())
2003 }
2004
2005 pub fn update_cluster(&mut self, id: ClusterId, cluster: Cluster) -> Result<(), CatalogError> {
2012 self.validate_query_policy_reference(cluster.config.query_policy)?;
2013 let updated = self.clusters.update_by_key(
2014 ClusterKey { id },
2015 cluster.into_key_value().1,
2016 self.op_id,
2017 )?;
2018 if updated {
2019 Ok(())
2020 } else {
2021 Err(SqlCatalogError::UnknownCluster(id.to_string()).into())
2022 }
2023 }
2024
2025 pub fn update_cluster_replica(
2032 &mut self,
2033 replica_id: ReplicaId,
2034 replica: ClusterReplica,
2035 ) -> Result<(), CatalogError> {
2036 let updated = self.cluster_replicas.update_by_key(
2037 ClusterReplicaKey { id: replica_id },
2038 replica.into_key_value().1,
2039 self.op_id,
2040 )?;
2041 if updated {
2042 Ok(())
2043 } else {
2044 Err(SqlCatalogError::UnknownClusterReplica(replica_id.to_string()).into())
2045 }
2046 }
2047
2048 pub fn update_database(
2055 &mut self,
2056 id: DatabaseId,
2057 database: Database,
2058 ) -> Result<(), CatalogError> {
2059 let updated = self.databases.update_by_key(
2060 DatabaseKey { id },
2061 database.into_key_value().1,
2062 self.op_id,
2063 )?;
2064 if updated {
2065 Ok(())
2066 } else {
2067 Err(SqlCatalogError::UnknownDatabase(id.to_string()).into())
2068 }
2069 }
2070
2071 pub fn update_schema(
2078 &mut self,
2079 schema_id: SchemaId,
2080 schema: Schema,
2081 ) -> Result<(), CatalogError> {
2082 let updated = self.schemas.update_by_key(
2083 SchemaKey { id: schema_id },
2084 schema.into_key_value().1,
2085 self.op_id,
2086 )?;
2087 if updated {
2088 Ok(())
2089 } else {
2090 Err(SqlCatalogError::UnknownSchema(schema_id.to_string()).into())
2091 }
2092 }
2093
2094 pub fn update_network_policy(
2101 &mut self,
2102 id: NetworkPolicyId,
2103 network_policy: NetworkPolicy,
2104 ) -> Result<(), CatalogError> {
2105 let updated = self.network_policies.update_by_key(
2106 NetworkPolicyKey { id },
2107 network_policy.into_key_value().1,
2108 self.op_id,
2109 )?;
2110 if updated {
2111 Ok(())
2112 } else {
2113 Err(SqlCatalogError::UnknownNetworkPolicy(id.to_string()).into())
2114 }
2115 }
2116 pub fn remove_network_policies(
2123 &mut self,
2124 network_policies: &BTreeSet<NetworkPolicyId>,
2125 ) -> Result<(), CatalogError> {
2126 if network_policies.is_empty() {
2127 return Ok(());
2128 }
2129
2130 let to_remove = network_policies
2131 .iter()
2132 .map(|policy_id| (NetworkPolicyKey { id: *policy_id }, None))
2133 .collect();
2134 let mut prev = self.network_policies.set_many(to_remove, self.op_id)?;
2135 assert!(
2136 prev.iter().all(|(k, _)| k.id.is_user()),
2137 "cannot delete non-user network policy"
2138 );
2139
2140 prev.retain(|_k, v| v.is_none());
2141 if !prev.is_empty() {
2142 let err = prev.keys().map(|k| k.id.to_string()).join(", ");
2143 return Err(SqlCatalogError::UnknownNetworkPolicy(err).into());
2144 }
2145
2146 Ok(())
2147 }
2148 pub fn set_default_privilege(
2152 &mut self,
2153 role_id: RoleId,
2154 database_id: Option<DatabaseId>,
2155 schema_id: Option<SchemaId>,
2156 object_type: ObjectType,
2157 grantee: RoleId,
2158 privileges: Option<AclMode>,
2159 ) -> Result<(), CatalogError> {
2160 self.default_privileges.set(
2161 DefaultPrivilegesKey {
2162 role_id,
2163 database_id,
2164 schema_id,
2165 object_type,
2166 grantee,
2167 },
2168 privileges.map(|privileges| DefaultPrivilegesValue { privileges }),
2169 self.op_id,
2170 )?;
2171 Ok(())
2172 }
2173
2174 pub fn set_default_privileges(
2176 &mut self,
2177 default_privileges: Vec<DefaultPrivilege>,
2178 ) -> Result<(), CatalogError> {
2179 if default_privileges.is_empty() {
2180 return Ok(());
2181 }
2182
2183 let default_privileges = default_privileges
2184 .into_iter()
2185 .map(DurableType::into_key_value)
2186 .map(|(k, v)| (k, Some(v)))
2187 .collect();
2188 self.default_privileges
2189 .set_many(default_privileges, self.op_id)?;
2190 Ok(())
2191 }
2192
2193 pub fn set_system_privilege(
2197 &mut self,
2198 grantee: RoleId,
2199 grantor: RoleId,
2200 acl_mode: Option<AclMode>,
2201 ) -> Result<(), CatalogError> {
2202 self.system_privileges.set(
2203 SystemPrivilegesKey { grantee, grantor },
2204 acl_mode.map(|acl_mode| SystemPrivilegesValue { acl_mode }),
2205 self.op_id,
2206 )?;
2207 Ok(())
2208 }
2209
2210 pub fn set_system_privileges(
2212 &mut self,
2213 system_privileges: Vec<MzAclItem>,
2214 ) -> Result<(), CatalogError> {
2215 if system_privileges.is_empty() {
2216 return Ok(());
2217 }
2218
2219 let system_privileges = system_privileges
2220 .into_iter()
2221 .map(DurableType::into_key_value)
2222 .map(|(k, v)| (k, Some(v)))
2223 .collect();
2224 self.system_privileges
2225 .set_many(system_privileges, self.op_id)?;
2226 Ok(())
2227 }
2228
2229 pub fn set_setting(&mut self, name: String, value: Option<String>) -> Result<(), CatalogError> {
2231 self.settings.set(
2232 SettingKey { name },
2233 value.map(|value| SettingValue { value }),
2234 self.op_id,
2235 )?;
2236 Ok(())
2237 }
2238
2239 pub fn set_catalog_content_version(&mut self, version: String) -> Result<(), CatalogError> {
2240 self.set_setting(CATALOG_CONTENT_VERSION_KEY.to_string(), Some(version))
2241 }
2242
2243 pub fn insert_introspection_source_indexes(
2245 &mut self,
2246 introspection_source_indexes: Vec<(ClusterId, String, CatalogItemId, GlobalId)>,
2247 temporary_oids: &HashSet<u32>,
2248 ) -> Result<(), CatalogError> {
2249 if introspection_source_indexes.is_empty() {
2250 return Ok(());
2251 }
2252
2253 let amount = usize_to_u64(introspection_source_indexes.len());
2254 let oids = self.allocate_oids(amount, temporary_oids)?;
2255 let introspection_source_indexes: Vec<_> = introspection_source_indexes
2256 .into_iter()
2257 .zip_eq(oids)
2258 .map(
2259 |((cluster_id, name, item_id, index_id), oid)| IntrospectionSourceIndex {
2260 cluster_id,
2261 name,
2262 item_id,
2263 index_id,
2264 oid,
2265 },
2266 )
2267 .collect();
2268
2269 for introspection_source_index in introspection_source_indexes {
2270 let (key, value) = introspection_source_index.into_key_value();
2271 self.introspection_sources.insert(key, value, self.op_id)?;
2272 }
2273
2274 Ok(())
2275 }
2276
2277 pub fn set_system_object_mappings(
2279 &mut self,
2280 mappings: Vec<SystemObjectMapping>,
2281 ) -> Result<(), CatalogError> {
2282 if mappings.is_empty() {
2283 return Ok(());
2284 }
2285
2286 let mappings = mappings
2287 .into_iter()
2288 .map(DurableType::into_key_value)
2289 .map(|(k, v)| (k, Some(v)))
2290 .collect();
2291 self.system_gid_mapping.set_many(mappings, self.op_id)?;
2292 Ok(())
2293 }
2294
2295 pub fn set_replicas(&mut self, replicas: Vec<ClusterReplica>) -> Result<(), CatalogError> {
2297 if replicas.is_empty() {
2298 return Ok(());
2299 }
2300
2301 let replicas = replicas
2302 .into_iter()
2303 .map(DurableType::into_key_value)
2304 .map(|(k, v)| (k, Some(v)))
2305 .collect();
2306 self.cluster_replicas.set_many(replicas, self.op_id)?;
2307 Ok(())
2308 }
2309
2310 pub fn set_config(&mut self, key: String, value: Option<u64>) -> Result<(), CatalogError> {
2312 match value {
2313 Some(value) => {
2314 let config = Config { key, value };
2315 let (key, value) = config.into_key_value();
2316 self.configs.set(key, Some(value), self.op_id)?;
2317 }
2318 None => {
2319 self.configs.set(ConfigKey { key }, None, self.op_id)?;
2320 }
2321 }
2322 Ok(())
2323 }
2324
2325 pub fn get_config(&self, key: String) -> Option<u64> {
2327 self.configs
2328 .get(&ConfigKey { key })
2329 .map(|entry| entry.value)
2330 }
2331
2332 pub fn get_setting(&self, name: String) -> Option<&str> {
2334 self.settings
2335 .get(&SettingKey { name })
2336 .map(|entry| &*entry.value)
2337 }
2338
2339 pub fn get_builtin_migration_shard(&self) -> Option<ShardId> {
2340 self.get_setting(BUILTIN_MIGRATION_SHARD_KEY.to_string())
2341 .map(|shard_id| shard_id.parse().expect("valid ShardId"))
2342 }
2343
2344 pub fn set_builtin_migration_shard(&mut self, shard_id: ShardId) -> Result<(), CatalogError> {
2345 self.set_setting(
2346 BUILTIN_MIGRATION_SHARD_KEY.to_string(),
2347 Some(shard_id.to_string()),
2348 )
2349 }
2350
2351 pub fn get_expression_cache_shard(&self) -> Option<ShardId> {
2352 self.get_setting(EXPRESSION_CACHE_SHARD_KEY.to_string())
2353 .map(|shard_id| shard_id.parse().expect("valid ShardId"))
2354 }
2355
2356 pub fn set_expression_cache_shard(&mut self, shard_id: ShardId) -> Result<(), CatalogError> {
2357 self.set_setting(
2358 EXPRESSION_CACHE_SHARD_KEY.to_string(),
2359 Some(shard_id.to_string()),
2360 )
2361 }
2362
2363 pub fn set_0dt_deployment_max_wait(&mut self, value: Duration) -> Result<(), CatalogError> {
2369 self.set_config(
2370 WITH_0DT_DEPLOYMENT_MAX_WAIT.into(),
2371 Some(
2372 value
2373 .as_millis()
2374 .try_into()
2375 .expect("max wait fits into u64"),
2376 ),
2377 )
2378 }
2379
2380 pub fn set_0dt_deployment_ddl_check_interval(
2387 &mut self,
2388 value: Duration,
2389 ) -> Result<(), CatalogError> {
2390 self.set_config(
2391 WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.into(),
2392 Some(
2393 value
2394 .as_millis()
2395 .try_into()
2396 .expect("ddl check interval fits into u64"),
2397 ),
2398 )
2399 }
2400
2401 pub fn set_enable_0dt_deployment_panic_after_timeout(
2407 &mut self,
2408 value: bool,
2409 ) -> Result<(), CatalogError> {
2410 self.set_config(
2411 ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.into(),
2412 Some(u64::from(value)),
2413 )
2414 }
2415
2416 pub fn reset_0dt_deployment_max_wait(&mut self) -> Result<(), CatalogError> {
2422 self.set_config(WITH_0DT_DEPLOYMENT_MAX_WAIT.into(), None)
2423 }
2424
2425 pub fn reset_0dt_deployment_ddl_check_interval(&mut self) -> Result<(), CatalogError> {
2432 self.set_config(WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.into(), None)
2433 }
2434
2435 pub fn reset_enable_0dt_deployment_panic_after_timeout(&mut self) -> Result<(), CatalogError> {
2442 self.set_config(ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.into(), None)
2443 }
2444
2445 pub fn set_system_config_synced_once(&mut self) -> Result<(), CatalogError> {
2447 self.set_config(SYSTEM_CONFIG_SYNCED_KEY.into(), Some(1))
2448 }
2449
2450 pub fn update_comment(
2451 &mut self,
2452 object_id: CommentObjectId,
2453 sub_component: Option<usize>,
2454 comment: Option<String>,
2455 ) -> Result<(), CatalogError> {
2456 let key = CommentKey {
2457 object_id,
2458 sub_component,
2459 };
2460 let value = comment.map(|c| CommentValue { comment: c });
2461 self.comments.set(key, value, self.op_id)?;
2462
2463 Ok(())
2464 }
2465
2466 pub fn drop_comments(
2467 &mut self,
2468 object_ids: &BTreeSet<CommentObjectId>,
2469 ) -> Result<(), CatalogError> {
2470 if object_ids.is_empty() {
2471 return Ok(());
2472 }
2473
2474 self.comments
2475 .delete(|k, _v| object_ids.contains(&k.object_id), self.op_id);
2476 Ok(())
2477 }
2478
2479 pub fn update_source_references(
2480 &mut self,
2481 source_id: CatalogItemId,
2482 references: Vec<SourceReference>,
2483 updated_at: u64,
2484 ) -> Result<(), CatalogError> {
2485 let key = SourceReferencesKey { source_id };
2486 let value = SourceReferencesValue {
2487 references,
2488 updated_at,
2489 };
2490 self.source_references.set(key, Some(value), self.op_id)?;
2491 Ok(())
2492 }
2493
2494 pub fn upsert_system_config(&mut self, name: &str, value: String) -> Result<(), CatalogError> {
2496 let key = ServerConfigurationKey {
2497 name: name.to_string(),
2498 };
2499 let value = ServerConfigurationValue { value };
2500 self.system_configurations
2501 .set(key, Some(value), self.op_id)?;
2502 Ok(())
2503 }
2504
2505 pub fn remove_system_config(&mut self, name: &str) {
2507 let key = ServerConfigurationKey {
2508 name: name.to_string(),
2509 };
2510 self.system_configurations
2511 .set(key, None, self.op_id)
2512 .expect("cannot have uniqueness violation");
2513 }
2514
2515 pub fn clear_system_configs(&mut self) {
2517 self.system_configurations.delete(|_k, _v| true, self.op_id);
2518 }
2519
2520 pub fn get_cluster_system_configurations(
2522 &self,
2523 ) -> impl Iterator<Item = ClusterSystemConfiguration> + use<'_> {
2524 self.cluster_system_configurations
2525 .items()
2526 .into_iter()
2527 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2528 }
2529
2530 pub fn upsert_cluster_system_config(
2533 &mut self,
2534 cluster_id: ClusterId,
2535 name: &str,
2536 value: String,
2537 ) -> Result<(), CatalogError> {
2538 let key = ClusterSystemConfigurationKey {
2539 cluster_id,
2540 name: name.to_string(),
2541 };
2542 let value = ClusterSystemConfigurationValue { value };
2543 self.cluster_system_configurations
2544 .set(key, Some(value), self.op_id)?;
2545 Ok(())
2546 }
2547
2548 pub fn remove_cluster_system_config(&mut self, cluster_id: ClusterId, name: &str) {
2551 let key = ClusterSystemConfigurationKey {
2552 cluster_id,
2553 name: name.to_string(),
2554 };
2555 self.cluster_system_configurations
2556 .set(key, None, self.op_id)
2557 .expect("cannot have uniqueness violation");
2558 }
2559
2560 pub fn get_replica_system_configurations(
2562 &self,
2563 ) -> impl Iterator<Item = ReplicaSystemConfiguration> + use<'_> {
2564 self.replica_system_configurations
2565 .items()
2566 .into_iter()
2567 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2568 }
2569
2570 pub fn upsert_replica_system_config(
2573 &mut self,
2574 replica_id: ReplicaId,
2575 name: &str,
2576 value: String,
2577 ) -> Result<(), CatalogError> {
2578 let key = ReplicaSystemConfigurationKey {
2579 replica_id,
2580 name: name.to_string(),
2581 };
2582 let value = ReplicaSystemConfigurationValue { value };
2583 self.replica_system_configurations
2584 .set(key, Some(value), self.op_id)?;
2585 Ok(())
2586 }
2587
2588 pub fn remove_replica_system_config(&mut self, replica_id: ReplicaId, name: &str) {
2591 let key = ReplicaSystemConfigurationKey {
2592 replica_id,
2593 name: name.to_string(),
2594 };
2595 self.replica_system_configurations
2596 .set(key, None, self.op_id)
2597 .expect("cannot have uniqueness violation");
2598 }
2599
2600 pub(crate) fn insert_config(&mut self, key: String, value: u64) -> Result<(), CatalogError> {
2601 match self.configs.insert(
2602 ConfigKey { key: key.clone() },
2603 ConfigValue { value },
2604 self.op_id,
2605 ) {
2606 Ok(_) => Ok(()),
2607 Err(_) => Err(SqlCatalogError::ConfigAlreadyExists(key).into()),
2608 }
2609 }
2610
2611 pub fn get_clusters(&self) -> impl Iterator<Item = Cluster> + use<'_> {
2612 self.clusters
2613 .items()
2614 .into_iter()
2615 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2616 }
2617
2618 pub fn get_cluster_replicas(&self) -> impl Iterator<Item = ClusterReplica> + use<'_> {
2619 self.cluster_replicas
2620 .items()
2621 .into_iter()
2622 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2623 }
2624
2625 pub fn get_databases(&self) -> impl Iterator<Item = Database> + use<'_> {
2626 self.databases
2627 .items()
2628 .into_iter()
2629 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2630 }
2631
2632 pub fn get_roles(&self) -> impl Iterator<Item = Role> + use<'_> {
2633 self.roles
2634 .items()
2635 .into_iter()
2636 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2637 }
2638
2639 pub fn get_query_policies(&self) -> impl Iterator<Item = QueryPolicy> + use<'_> {
2640 self.query_policies
2641 .items()
2642 .into_iter()
2643 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2644 }
2645
2646 pub fn get_network_policies(&self) -> impl Iterator<Item = NetworkPolicy> + use<'_> {
2647 self.network_policies
2648 .items()
2649 .into_iter()
2650 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2651 }
2652
2653 pub fn get_cluster_replica_sizes(&self) -> impl Iterator<Item = ClusterReplicaSize> + use<'_> {
2654 self.cluster_replica_sizes
2655 .items()
2656 .into_iter()
2657 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2658 }
2659
2660 pub fn insert_system_cluster_replica_size(
2661 &mut self,
2662 name: String,
2663 allocation: ReplicaAllocation,
2664 ) -> Result<ClusterReplicaSizeId, CatalogError> {
2665 let id = self.get_and_increment_id(SYSTEM_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY.to_string())?;
2666 let id = ClusterReplicaSizeId::System(id);
2667 let (key, value) = ClusterReplicaSize {
2668 id,
2669 name,
2670 allocation,
2671 }
2672 .into_key_value();
2673 self.cluster_replica_sizes.insert(key, value, self.op_id)?;
2674 Ok(id)
2675 }
2676
2677 pub fn update_cluster_replica_size(
2678 &mut self,
2679 size: ClusterReplicaSize,
2680 ) -> Result<(), CatalogError> {
2681 let id = size.id;
2682 let (key, value) = size.into_key_value();
2683 if self
2684 .cluster_replica_sizes
2685 .update_by_key(key, value, self.op_id)?
2686 {
2687 Ok(())
2688 } else {
2689 Err(SqlCatalogError::UnknownClusterReplicaSize(id.to_string()).into())
2690 }
2691 }
2692
2693 pub fn remove_cluster_replica_size(
2694 &mut self,
2695 id: ClusterReplicaSizeId,
2696 ) -> Result<(), CatalogError> {
2697 match self
2698 .cluster_replica_sizes
2699 .delete_by_key(ClusterReplicaSizeKey { id }, self.op_id)
2700 {
2701 Some(_) => Ok(()),
2702 None => Err(SqlCatalogError::UnknownClusterReplicaSize(id.to_string()).into()),
2703 }
2704 }
2705
2706 pub fn get_system_object_mappings(
2707 &self,
2708 ) -> impl Iterator<Item = SystemObjectMapping> + use<'_> {
2709 self.system_gid_mapping
2710 .items()
2711 .into_iter()
2712 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2713 }
2714
2715 pub fn get_schemas(&self) -> impl Iterator<Item = Schema> + use<'_> {
2716 self.schemas
2717 .items()
2718 .into_iter()
2719 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2720 }
2721
2722 pub fn get_system_configurations(&self) -> impl Iterator<Item = SystemConfiguration> + use<'_> {
2723 self.system_configurations
2724 .items()
2725 .into_iter()
2726 .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2727 }
2728
2729 pub fn get_schema(&self, id: &SchemaId) -> Option<Schema> {
2730 let key = SchemaKey { id: *id };
2731 self.schemas
2732 .get(&key)
2733 .map(|v| DurableType::from_key_value(key, v.clone()))
2734 }
2735
2736 pub fn get_introspection_source_indexes(
2737 &self,
2738 cluster_id: ClusterId,
2739 ) -> BTreeMap<&str, (GlobalId, u32)> {
2740 self.introspection_sources
2741 .items()
2742 .into_iter()
2743 .filter(|(k, _v)| k.cluster_id == cluster_id)
2744 .map(|(k, v)| (k.name.as_str(), (v.global_id.into(), v.oid)))
2745 .collect()
2746 }
2747
2748 pub fn get_catalog_content_version(&self) -> Option<&str> {
2749 self.settings
2750 .get(&SettingKey {
2751 name: CATALOG_CONTENT_VERSION_KEY.to_string(),
2752 })
2753 .map(|value| &*value.value)
2754 }
2755
2756 pub fn get_authentication_mock_nonce(&self) -> Option<String> {
2757 self.settings
2758 .get(&SettingKey {
2759 name: MOCK_AUTHENTICATION_NONCE_KEY.to_string(),
2760 })
2761 .map(|value| value.value.clone())
2762 }
2763
2764 #[must_use]
2770 pub fn get_and_commit_op_updates(&mut self) -> Vec<StateUpdate> {
2771 let updates = self.get_op_updates();
2772 self.commit_op();
2773 updates
2774 }
2775
2776 fn get_op_updates(&self) -> Vec<StateUpdate> {
2777 fn get_collection_op_updates<'a, T>(
2778 table_txn: &'a TableTransaction<T::Key, T::Value>,
2779 kind_fn: impl Fn(T) -> StateUpdateKind + 'a,
2780 op: Timestamp,
2781 ) -> impl Iterator<Item = (StateUpdateKind, StateDiff)> + 'a
2782 where
2783 T::Key: Ord + Eq + Clone + Debug,
2784 T::Value: Ord + Clone + Debug,
2785 T: DurableType,
2786 {
2787 table_txn
2788 .pending
2789 .iter()
2790 .flat_map(|(k, vs)| vs.into_iter().map(move |v| (k, v)))
2791 .filter_map(move |(k, v)| {
2792 if v.ts == op {
2793 let key = k.clone();
2794 let value = v.value.clone();
2795 let diff = v.diff.clone().try_into().expect("invalid diff");
2796 let update = DurableType::from_key_value(key, value);
2797 let kind = kind_fn(update);
2798 Some((kind, diff))
2799 } else {
2800 None
2801 }
2802 })
2803 }
2804
2805 fn get_large_collection_op_updates<'a, T>(
2806 collection: &'a Vec<(T::Key, Diff, Timestamp)>,
2807 kind_fn: impl Fn(T) -> StateUpdateKind + 'a,
2808 op: Timestamp,
2809 ) -> impl Iterator<Item = (StateUpdateKind, StateDiff)> + 'a
2810 where
2811 T::Key: Ord + Eq + Clone + Debug,
2812 T: DurableType<Value = ()>,
2813 {
2814 collection.iter().filter_map(move |(k, diff, ts)| {
2815 if *ts == op {
2816 let key = k.clone();
2817 let diff = diff.clone().try_into().expect("invalid diff");
2818 let update = DurableType::from_key_value(key, ());
2819 let kind = kind_fn(update);
2820 Some((kind, diff))
2821 } else {
2822 None
2823 }
2824 })
2825 }
2826
2827 let Transaction {
2828 durable_catalog: _,
2829 databases,
2830 schemas,
2831 items,
2832 comments,
2833 roles,
2834 role_auth,
2835 clusters,
2836 network_policies,
2837 cluster_replica_sizes,
2838 query_policies,
2839 cluster_replicas,
2840 introspection_sources,
2841 system_gid_mapping,
2842 system_configurations,
2843 cluster_system_configurations,
2844 replica_system_configurations,
2845 default_privileges,
2846 source_references,
2847 system_privileges,
2848 audit_log_updates,
2849 storage_collection_metadata,
2850 unfinalized_shards,
2851 id_allocator: _,
2853 configs: _,
2854 settings: _,
2855 txn_wal_shard: _,
2856 item_columns: _,
2858 index_columns: _,
2859 upper,
2860 op_id: _,
2861 commit_capability: _,
2862 } = &self;
2863
2864 let updates = std::iter::empty()
2865 .chain(get_collection_op_updates(
2866 roles,
2867 StateUpdateKind::Role,
2868 self.op_id,
2869 ))
2870 .chain(get_collection_op_updates(
2871 role_auth,
2872 StateUpdateKind::RoleAuth,
2873 self.op_id,
2874 ))
2875 .chain(get_collection_op_updates(
2876 databases,
2877 StateUpdateKind::Database,
2878 self.op_id,
2879 ))
2880 .chain(get_collection_op_updates(
2881 schemas,
2882 StateUpdateKind::Schema,
2883 self.op_id,
2884 ))
2885 .chain(get_collection_op_updates(
2886 default_privileges,
2887 StateUpdateKind::DefaultPrivilege,
2888 self.op_id,
2889 ))
2890 .chain(get_collection_op_updates(
2891 system_privileges,
2892 StateUpdateKind::SystemPrivilege,
2893 self.op_id,
2894 ))
2895 .chain(get_collection_op_updates(
2896 system_configurations,
2897 StateUpdateKind::SystemConfiguration,
2898 self.op_id,
2899 ))
2900 .chain(get_collection_op_updates(
2901 cluster_system_configurations,
2902 StateUpdateKind::ClusterSystemConfiguration,
2903 self.op_id,
2904 ))
2905 .chain(get_collection_op_updates(
2906 replica_system_configurations,
2907 StateUpdateKind::ReplicaSystemConfiguration,
2908 self.op_id,
2909 ))
2910 .chain(get_collection_op_updates(
2911 clusters,
2912 StateUpdateKind::Cluster,
2913 self.op_id,
2914 ))
2915 .chain(get_collection_op_updates(
2916 network_policies,
2917 StateUpdateKind::NetworkPolicy,
2918 self.op_id,
2919 ))
2920 .chain(get_collection_op_updates(
2921 cluster_replica_sizes,
2922 StateUpdateKind::ClusterReplicaSize,
2923 self.op_id,
2924 ))
2925 .chain(get_collection_op_updates(
2926 query_policies,
2927 StateUpdateKind::QueryPolicy,
2928 self.op_id,
2929 ))
2930 .chain(get_collection_op_updates(
2931 introspection_sources,
2932 StateUpdateKind::IntrospectionSourceIndex,
2933 self.op_id,
2934 ))
2935 .chain(get_collection_op_updates(
2936 cluster_replicas,
2937 StateUpdateKind::ClusterReplica,
2938 self.op_id,
2939 ))
2940 .chain(get_collection_op_updates(
2941 system_gid_mapping,
2942 StateUpdateKind::SystemObjectMapping,
2943 self.op_id,
2944 ))
2945 .chain(get_collection_op_updates(
2946 items,
2947 StateUpdateKind::Item,
2948 self.op_id,
2949 ))
2950 .chain(get_collection_op_updates(
2951 comments,
2952 StateUpdateKind::Comment,
2953 self.op_id,
2954 ))
2955 .chain(get_collection_op_updates(
2956 source_references,
2957 StateUpdateKind::SourceReferences,
2958 self.op_id,
2959 ))
2960 .chain(get_collection_op_updates(
2961 storage_collection_metadata,
2962 StateUpdateKind::StorageCollectionMetadata,
2963 self.op_id,
2964 ))
2965 .chain(get_collection_op_updates(
2966 unfinalized_shards,
2967 StateUpdateKind::UnfinalizedShard,
2968 self.op_id,
2969 ))
2970 .chain(get_large_collection_op_updates(
2971 audit_log_updates,
2972 StateUpdateKind::AuditLog,
2973 self.op_id,
2974 ))
2975 .map(|(kind, diff)| StateUpdate {
2976 kind,
2977 ts: upper.clone(),
2978 diff,
2979 })
2980 .collect();
2981
2982 updates
2983 }
2984
2985 pub fn is_savepoint(&self) -> bool {
2986 self.durable_catalog.is_savepoint()
2987 }
2988
2989 pub fn is_read_only(&self) -> bool {
2990 self.durable_catalog.is_read_only()
2991 }
2992
2993 fn commit_op(&mut self) {
2994 self.op_id += 1;
2995 }
2996
2997 pub fn op_id(&self) -> Timestamp {
2998 self.op_id
2999 }
3000
3001 pub fn upper(&self) -> mz_repr::Timestamp {
3002 self.upper
3003 }
3004
3005 fn ensure_committable(&self) -> Result<(), CatalogError> {
3006 match self.commit_capability {
3007 Some(_) => Ok(()),
3008 None => Err(DurableCatalogError::DryRunTransaction.into()),
3009 }
3010 }
3011
3012 pub(super) async fn ensure_not_out_of_sync(&mut self) -> Result<(), CatalogError> {
3014 self.durable_catalog
3015 .ensure_not_out_of_sync(self.upper)
3016 .await
3017 }
3018
3019 pub(crate) fn into_parts(
3020 self,
3021 ) -> Result<(TransactionBatch, &'a mut dyn DurableCatalogState), CatalogError> {
3022 let commit_capability = self
3023 .commit_capability
3024 .ok_or(DurableCatalogError::DryRunTransaction)?;
3025 let audit_log_updates = self
3026 .audit_log_updates
3027 .into_iter()
3028 .map(|(k, diff, _op)| (k.into_proto(), (), diff))
3029 .collect();
3030
3031 let txn_batch = TransactionBatch {
3032 databases: self.databases.pending(),
3033 schemas: self.schemas.pending(),
3034 items: self.items.pending(),
3035 item_columns: self.item_columns.pending(),
3036 index_columns: self.index_columns.pending(),
3037 comments: self.comments.pending(),
3038 roles: self.roles.pending(),
3039 role_auth: self.role_auth.pending(),
3040 clusters: self.clusters.pending(),
3041 cluster_replicas: self.cluster_replicas.pending(),
3042 network_policies: self.network_policies.pending(),
3043 cluster_replica_sizes: self.cluster_replica_sizes.pending(),
3044 query_policies: self.query_policies.pending(),
3045 introspection_sources: self.introspection_sources.pending(),
3046 id_allocator: self.id_allocator.pending(),
3047 configs: self.configs.pending(),
3048 source_references: self.source_references.pending(),
3049 settings: self.settings.pending(),
3050 system_gid_mapping: self.system_gid_mapping.pending(),
3051 system_configurations: self.system_configurations.pending(),
3052 cluster_system_configurations: self.cluster_system_configurations.pending(),
3053 replica_system_configurations: self.replica_system_configurations.pending(),
3054 default_privileges: self.default_privileges.pending(),
3055 system_privileges: self.system_privileges.pending(),
3056 storage_collection_metadata: self.storage_collection_metadata.pending(),
3057 unfinalized_shards: self.unfinalized_shards.pending(),
3058 txn_wal_shard: self.txn_wal_shard.pending(),
3059 audit_log_updates,
3060 upper: self.upper,
3061 _commit_capability: commit_capability,
3062 };
3063 Ok((txn_batch, self.durable_catalog))
3064 }
3065
3066 #[mz_ore::instrument(level = "debug")]
3082 pub(crate) async fn commit_internal(
3083 self,
3084 commit_ts: mz_repr::Timestamp,
3085 ) -> Result<(&'a mut dyn DurableCatalogState, mz_repr::Timestamp), CatalogError> {
3086 self.ensure_committable()?;
3087 let (mut txn_batch, durable_catalog) = self.into_parts()?;
3088 let TransactionBatch {
3089 databases,
3090 schemas,
3091 items,
3092 item_columns,
3093 index_columns,
3094 comments,
3095 roles,
3096 role_auth,
3097 clusters,
3098 cluster_replicas,
3099 network_policies,
3100 cluster_replica_sizes,
3101 query_policies,
3102 introspection_sources,
3103 id_allocator,
3104 configs,
3105 source_references,
3106 settings,
3107 system_gid_mapping,
3108 system_configurations,
3109 cluster_system_configurations,
3110 replica_system_configurations,
3111 default_privileges,
3112 system_privileges,
3113 storage_collection_metadata,
3114 unfinalized_shards,
3115 txn_wal_shard,
3116 audit_log_updates,
3117 upper: _,
3118 _commit_capability: _,
3119 } = &mut txn_batch;
3120 differential_dataflow::consolidation::consolidate_updates(databases);
3123 differential_dataflow::consolidation::consolidate_updates(schemas);
3124 differential_dataflow::consolidation::consolidate_updates(items);
3125 differential_dataflow::consolidation::consolidate_updates(item_columns);
3126 differential_dataflow::consolidation::consolidate_updates(index_columns);
3127 differential_dataflow::consolidation::consolidate_updates(comments);
3128 differential_dataflow::consolidation::consolidate_updates(roles);
3129 differential_dataflow::consolidation::consolidate_updates(role_auth);
3130 differential_dataflow::consolidation::consolidate_updates(clusters);
3131 differential_dataflow::consolidation::consolidate_updates(cluster_replicas);
3132 differential_dataflow::consolidation::consolidate_updates(network_policies);
3133 differential_dataflow::consolidation::consolidate_updates(cluster_replica_sizes);
3134 differential_dataflow::consolidation::consolidate_updates(query_policies);
3135 differential_dataflow::consolidation::consolidate_updates(introspection_sources);
3136 differential_dataflow::consolidation::consolidate_updates(id_allocator);
3137 differential_dataflow::consolidation::consolidate_updates(configs);
3138 differential_dataflow::consolidation::consolidate_updates(settings);
3139 differential_dataflow::consolidation::consolidate_updates(source_references);
3140 differential_dataflow::consolidation::consolidate_updates(system_gid_mapping);
3141 differential_dataflow::consolidation::consolidate_updates(system_configurations);
3142 differential_dataflow::consolidation::consolidate_updates(cluster_system_configurations);
3143 differential_dataflow::consolidation::consolidate_updates(replica_system_configurations);
3144 differential_dataflow::consolidation::consolidate_updates(default_privileges);
3145 differential_dataflow::consolidation::consolidate_updates(system_privileges);
3146 differential_dataflow::consolidation::consolidate_updates(storage_collection_metadata);
3147 differential_dataflow::consolidation::consolidate_updates(unfinalized_shards);
3148 differential_dataflow::consolidation::consolidate_updates(txn_wal_shard);
3149 differential_dataflow::consolidation::consolidate_updates(audit_log_updates);
3150
3151 let upper = durable_catalog
3152 .commit_transaction(txn_batch, commit_ts)
3153 .await?;
3154 Ok((durable_catalog, upper))
3155 }
3156
3157 #[mz_ore::instrument(level = "debug")]
3178 pub async fn commit(self, commit_ts: mz_repr::Timestamp) -> Result<(), CatalogError> {
3179 self.ensure_committable()?;
3180 let op_updates = self.get_op_updates();
3181 assert!(
3182 op_updates.is_empty(),
3183 "unconsumed transaction updates: {op_updates:?}"
3184 );
3185
3186 let (durable_storage, upper) = self.commit_internal(commit_ts).await?;
3187 let updates = durable_storage.sync_updates(upper).await?;
3189 soft_assert_no_log!(
3198 durable_storage.is_read_only()
3199 || updates
3200 .iter()
3201 .all(|update| update.ts >= commit_ts && update.ts < upper),
3202 "unconsumed updates existed before transaction commit: commit_ts={commit_ts:?}, upper={upper:?}, updates:{updates:?}"
3203 );
3204 Ok(())
3205 }
3206}
3207
3208use crate::durable::async_trait;
3209
3210use super::objects::{RoleAuthKey, RoleAuthValue};
3211
3212#[async_trait]
3213impl StorageTxn for Transaction<'_> {
3214 fn get_collection_metadata(&self) -> BTreeMap<GlobalId, ShardId> {
3215 self.storage_collection_metadata
3216 .items()
3217 .into_iter()
3218 .map(
3219 |(
3220 StorageCollectionMetadataKey { id },
3221 StorageCollectionMetadataValue { shard },
3222 )| { (*id, shard.clone()) },
3223 )
3224 .collect()
3225 }
3226
3227 fn insert_collection_metadata(
3228 &mut self,
3229 metadata: BTreeMap<GlobalId, ShardId>,
3230 ) -> Result<(), StorageError> {
3231 for (id, shard) in metadata {
3232 self.storage_collection_metadata
3233 .insert(
3234 StorageCollectionMetadataKey { id },
3235 StorageCollectionMetadataValue {
3236 shard: shard.clone(),
3237 },
3238 self.op_id,
3239 )
3240 .map_err(|err| match err {
3241 DurableCatalogError::DuplicateKey => {
3242 StorageError::CollectionMetadataAlreadyExists(id)
3243 }
3244 DurableCatalogError::UniquenessViolation => {
3245 StorageError::PersistShardAlreadyInUse(shard)
3246 }
3247 err => StorageError::Generic(anyhow::anyhow!(err)),
3248 })?;
3249 }
3250 Ok(())
3251 }
3252
3253 fn delete_collection_metadata(&mut self, ids: BTreeSet<GlobalId>) -> Vec<(GlobalId, ShardId)> {
3254 let ks: Vec<_> = ids
3255 .into_iter()
3256 .map(|id| StorageCollectionMetadataKey { id })
3257 .collect();
3258 self.storage_collection_metadata
3259 .delete_by_keys(ks, self.op_id)
3260 .into_iter()
3261 .map(
3262 |(
3263 StorageCollectionMetadataKey { id },
3264 StorageCollectionMetadataValue { shard },
3265 )| (id, shard),
3266 )
3267 .collect()
3268 }
3269
3270 fn get_unfinalized_shards(&self) -> BTreeSet<ShardId> {
3271 self.unfinalized_shards
3272 .items()
3273 .into_iter()
3274 .map(|(UnfinalizedShardKey { shard }, ())| *shard)
3275 .collect()
3276 }
3277
3278 fn insert_unfinalized_shards(&mut self, s: BTreeSet<ShardId>) -> Result<(), StorageError> {
3279 for shard in s {
3280 match self
3281 .unfinalized_shards
3282 .insert(UnfinalizedShardKey { shard }, (), self.op_id)
3283 {
3284 Ok(()) | Err(DurableCatalogError::DuplicateKey) => {}
3286 Err(e) => Err(StorageError::Generic(anyhow::anyhow!(e)))?,
3287 };
3288 }
3289 Ok(())
3290 }
3291
3292 fn remove_unfinalized_shards(&mut self, shards: BTreeSet<ShardId>) {
3293 let ks: Vec<_> = shards
3294 .into_iter()
3295 .map(|shard| UnfinalizedShardKey { shard })
3296 .collect();
3297 let _ = self.unfinalized_shards.delete_by_keys(ks, self.op_id);
3298 }
3299
3300 fn get_txn_wal_shard(&self) -> Option<ShardId> {
3301 self.txn_wal_shard
3302 .values()
3303 .iter()
3304 .next()
3305 .map(|TxnWalShardValue { shard }| *shard)
3306 }
3307
3308 fn write_txn_wal_shard(&mut self, shard: ShardId) -> Result<(), StorageError> {
3309 self.txn_wal_shard
3310 .insert((), TxnWalShardValue { shard }, self.op_id)
3311 .map_err(|err| match err {
3312 DurableCatalogError::DuplicateKey => StorageError::TxnWalShardAlreadyExists,
3313 err => StorageError::Generic(anyhow::anyhow!(err)),
3314 })
3315 }
3316}
3317
3318#[derive(Debug, PartialEq)]
3320pub struct TransactionBatch {
3321 pub(crate) databases: Vec<(proto::DatabaseKey, proto::DatabaseValue, Diff)>,
3322 pub(crate) schemas: Vec<(proto::SchemaKey, proto::SchemaValue, Diff)>,
3323 pub(crate) items: Vec<(proto::ItemKey, proto::ItemValue, Diff)>,
3324 pub(crate) item_columns: Vec<(proto::ItemColumnsKey, proto::ItemColumnsValue, Diff)>,
3325 pub(crate) index_columns: Vec<(proto::IndexColumnsKey, proto::IndexColumnsValue, Diff)>,
3326 pub(crate) comments: Vec<(proto::CommentKey, proto::CommentValue, Diff)>,
3327 pub(crate) roles: Vec<(proto::RoleKey, proto::RoleValue, Diff)>,
3328 pub(crate) role_auth: Vec<(proto::RoleAuthKey, proto::RoleAuthValue, Diff)>,
3329 pub(crate) clusters: Vec<(proto::ClusterKey, proto::ClusterValue, Diff)>,
3330 pub(crate) cluster_replicas: Vec<(proto::ClusterReplicaKey, proto::ClusterReplicaValue, Diff)>,
3331 pub(crate) network_policies: Vec<(proto::NetworkPolicyKey, proto::NetworkPolicyValue, Diff)>,
3332 pub(crate) cluster_replica_sizes: Vec<(
3333 proto::ClusterReplicaSizeKey,
3334 proto::ClusterReplicaSizeValue,
3335 Diff,
3336 )>,
3337 pub(crate) query_policies: Vec<(proto::QueryPolicyKey, proto::QueryPolicyValue, Diff)>,
3338 pub(crate) introspection_sources: Vec<(
3339 proto::ClusterIntrospectionSourceIndexKey,
3340 proto::ClusterIntrospectionSourceIndexValue,
3341 Diff,
3342 )>,
3343 pub(crate) id_allocator: Vec<(proto::IdAllocKey, proto::IdAllocValue, Diff)>,
3344 pub(crate) configs: Vec<(proto::ConfigKey, proto::ConfigValue, Diff)>,
3345 pub(crate) settings: Vec<(proto::SettingKey, proto::SettingValue, Diff)>,
3346 pub(crate) system_gid_mapping: Vec<(proto::GidMappingKey, proto::GidMappingValue, Diff)>,
3347 pub(crate) system_configurations: Vec<(
3348 proto::ServerConfigurationKey,
3349 proto::ServerConfigurationValue,
3350 Diff,
3351 )>,
3352 pub(crate) cluster_system_configurations: Vec<(
3353 proto::ClusterSystemConfigurationKey,
3354 proto::ClusterSystemConfigurationValue,
3355 Diff,
3356 )>,
3357 pub(crate) replica_system_configurations: Vec<(
3358 proto::ReplicaSystemConfigurationKey,
3359 proto::ReplicaSystemConfigurationValue,
3360 Diff,
3361 )>,
3362 pub(crate) default_privileges: Vec<(
3363 proto::DefaultPrivilegesKey,
3364 proto::DefaultPrivilegesValue,
3365 Diff,
3366 )>,
3367 pub(crate) source_references: Vec<(
3368 proto::SourceReferencesKey,
3369 proto::SourceReferencesValue,
3370 Diff,
3371 )>,
3372 pub(crate) system_privileges: Vec<(
3373 proto::SystemPrivilegesKey,
3374 proto::SystemPrivilegesValue,
3375 Diff,
3376 )>,
3377 pub(crate) storage_collection_metadata: Vec<(
3378 proto::StorageCollectionMetadataKey,
3379 proto::StorageCollectionMetadataValue,
3380 Diff,
3381 )>,
3382 pub(crate) unfinalized_shards: Vec<(proto::UnfinalizedShardKey, (), Diff)>,
3383 pub(crate) txn_wal_shard: Vec<((), proto::TxnWalShardValue, Diff)>,
3384 pub(crate) audit_log_updates: Vec<(proto::AuditLogKey, (), Diff)>,
3385 pub(crate) upper: mz_repr::Timestamp,
3387 _commit_capability: CommitCapability,
3390}
3391
3392impl TransactionBatch {
3393 pub fn is_empty(&self) -> bool {
3394 let TransactionBatch {
3395 databases,
3396 schemas,
3397 items,
3398 item_columns,
3399 index_columns,
3400 comments,
3401 roles,
3402 role_auth,
3403 clusters,
3404 cluster_replicas,
3405 network_policies,
3406 cluster_replica_sizes,
3407 query_policies,
3408 introspection_sources,
3409 id_allocator,
3410 configs,
3411 settings,
3412 source_references,
3413 system_gid_mapping,
3414 system_configurations,
3415 cluster_system_configurations,
3416 replica_system_configurations,
3417 default_privileges,
3418 system_privileges,
3419 storage_collection_metadata,
3420 unfinalized_shards,
3421 txn_wal_shard,
3422 audit_log_updates,
3423 upper: _,
3424 _commit_capability: _,
3425 } = self;
3426 databases.is_empty()
3427 && schemas.is_empty()
3428 && items.is_empty()
3429 && item_columns.is_empty()
3430 && index_columns.is_empty()
3431 && comments.is_empty()
3432 && roles.is_empty()
3433 && role_auth.is_empty()
3434 && clusters.is_empty()
3435 && cluster_replicas.is_empty()
3436 && network_policies.is_empty()
3437 && cluster_replica_sizes.is_empty()
3438 && query_policies.is_empty()
3439 && introspection_sources.is_empty()
3440 && id_allocator.is_empty()
3441 && configs.is_empty()
3442 && settings.is_empty()
3443 && source_references.is_empty()
3444 && system_gid_mapping.is_empty()
3445 && system_configurations.is_empty()
3446 && cluster_system_configurations.is_empty()
3447 && replica_system_configurations.is_empty()
3448 && default_privileges.is_empty()
3449 && system_privileges.is_empty()
3450 && storage_collection_metadata.is_empty()
3451 && unfinalized_shards.is_empty()
3452 && txn_wal_shard.is_empty()
3453 && audit_log_updates.is_empty()
3454 }
3455}
3456
3457#[derive(Debug, Clone, PartialEq, Eq)]
3458struct TransactionUpdate<V> {
3459 value: V,
3460 ts: Timestamp,
3461 diff: Diff,
3462}
3463
3464trait UniqueName {
3466 const HAS_UNIQUE_NAME: bool;
3469 fn unique_name(&self) -> &str;
3471}
3472
3473mod unique_name {
3474 use crate::durable::objects::*;
3475
3476 macro_rules! impl_unique_name {
3477 ($($t:ty),* $(,)?) => {
3478 $(
3479 impl crate::durable::transaction::UniqueName for $t {
3480 const HAS_UNIQUE_NAME: bool = true;
3481 fn unique_name(&self) -> &str {
3482 &self.name
3483 }
3484 }
3485 )*
3486 };
3487 }
3488
3489 macro_rules! impl_no_unique_name {
3490 ($($t:ty),* $(,)?) => {
3491 $(
3492 impl crate::durable::transaction::UniqueName for $t {
3493 const HAS_UNIQUE_NAME: bool = false;
3494 fn unique_name(&self) -> &str {
3495 ""
3496 }
3497 }
3498 )*
3499 };
3500 }
3501
3502 impl_unique_name! {
3503 ClusterReplicaSizeValue,
3504 ClusterReplicaValue,
3505 ClusterValue,
3506 DatabaseValue,
3507 ItemValue,
3508 NetworkPolicyValue,
3509 QueryPolicyValue,
3510 RoleValue,
3511 SchemaValue,
3512 }
3513
3514 impl_no_unique_name!(
3515 (),
3516 ClusterIntrospectionSourceIndexValue,
3517 ClusterSystemConfigurationValue,
3518 CommentValue,
3519 ConfigValue,
3520 DefaultPrivilegesValue,
3521 GidMappingValue,
3522 IdAllocValue,
3523 IndexColumnsValue,
3524 ItemColumnsValue,
3525 ReplicaSystemConfigurationValue,
3526 ServerConfigurationValue,
3527 SettingValue,
3528 SourceReferencesValue,
3529 StorageCollectionMetadataValue,
3530 SystemPrivilegesValue,
3531 TxnWalShardValue,
3532 RoleAuthValue,
3533 );
3534
3535 #[cfg(test)]
3536 mod test {
3537 impl_no_unique_name!(String,);
3538 }
3539}
3540
3541#[derive(Debug)]
3549struct UniquenessCheck<V> {
3550 violation: fn(a: &V, b: &V) -> bool,
3551 is_unique_key_unchanged_after_update: fn(prev: &V, next: &V) -> bool,
3552}
3553
3554#[derive(Debug)]
3564struct TableTransaction<K, V> {
3565 initial: BTreeMap<K, V>,
3566 pending: BTreeMap<K, Vec<TransactionUpdate<V>>>,
3569 uniqueness_check: Option<UniquenessCheck<V>>,
3571}
3572
3573impl<K, V> TableTransaction<K, V>
3574where
3575 K: Ord + Eq + Clone + Debug,
3576 V: Ord + Clone + Debug + UniqueName,
3577{
3578 fn new<KP, VP>(initial: BTreeMap<KP, VP>) -> Result<Self, TryFromProtoError>
3585 where
3586 K: RustType<KP>,
3587 V: RustType<VP>,
3588 {
3589 let initial = initial
3590 .into_iter()
3591 .map(RustType::from_proto)
3592 .collect::<Result<_, _>>()?;
3593
3594 Ok(Self {
3595 initial,
3596 pending: BTreeMap::new(),
3597 uniqueness_check: None,
3598 })
3599 }
3600
3601 fn new_with_uniqueness_fn<KP, VP>(
3604 initial: BTreeMap<KP, VP>,
3605 uniqueness_violation: fn(a: &V, b: &V) -> bool,
3606 is_unique_key_unchanged_after_update: fn(prev: &V, next: &V) -> bool,
3607 ) -> Result<Self, TryFromProtoError>
3608 where
3609 K: RustType<KP>,
3610 V: RustType<VP>,
3611 {
3612 let initial = initial
3613 .into_iter()
3614 .map(RustType::from_proto)
3615 .collect::<Result<_, _>>()?;
3616
3617 Ok(Self {
3618 initial,
3619 pending: BTreeMap::new(),
3620 uniqueness_check: Some(UniquenessCheck {
3621 violation: uniqueness_violation,
3622 is_unique_key_unchanged_after_update,
3623 }),
3624 })
3625 }
3626
3627 fn pending<KP, VP>(self) -> Vec<(KP, VP, Diff)>
3630 where
3631 K: RustType<KP>,
3632 V: RustType<VP>,
3633 {
3634 soft_assert_no_log!(self.verify().is_ok());
3635 self.pending
3638 .into_iter()
3639 .flat_map(|(k, v)| {
3640 let mut v: Vec<_> = v
3641 .into_iter()
3642 .map(|TransactionUpdate { value, ts: _, diff }| (value, diff))
3643 .collect();
3644 differential_dataflow::consolidation::consolidate(&mut v);
3645 v.into_iter().map(move |(v, diff)| (k.clone(), v, diff))
3646 })
3647 .map(|(key, val, diff)| (key.into_proto(), val.into_proto(), diff))
3648 .collect()
3649 }
3650
3651 fn verify(&self) -> Result<(), DurableCatalogError> {
3656 if let Some(check) = &self.uniqueness_check {
3657 let items = self.values();
3659 if V::HAS_UNIQUE_NAME {
3660 let by_name: BTreeMap<_, _> = items
3661 .iter()
3662 .enumerate()
3663 .map(|(v, vi)| (vi.unique_name(), (v, vi)))
3664 .collect();
3665 for (i, vi) in items.iter().enumerate() {
3666 if let Some((j, vj)) = by_name.get(vi.unique_name()) {
3667 if i != *j && (check.violation)(vi, *vj) {
3668 return Err(DurableCatalogError::UniquenessViolation);
3669 }
3670 }
3671 }
3672 } else {
3673 for (i, vi) in items.iter().enumerate() {
3674 for (j, vj) in items.iter().enumerate() {
3675 if i != j && (check.violation)(vi, vj) {
3676 return Err(DurableCatalogError::UniquenessViolation);
3677 }
3678 }
3679 }
3680 }
3681 }
3682 soft_assert_no_log!(
3683 self.pending
3684 .values()
3685 .all(|pending| { pending.is_sorted_by(|a, b| a.ts <= b.ts) }),
3686 "pending should be sorted by timestamp: {:?}",
3687 self.pending
3688 );
3689 Ok(())
3690 }
3691
3692 fn verify_keys<'a>(
3697 &self,
3698 keys: impl IntoIterator<Item = &'a K>,
3699 ) -> Result<(), DurableCatalogError>
3700 where
3701 K: 'a,
3702 {
3703 if let Some(check) = &self.uniqueness_check {
3704 let entries: Vec<_> = keys
3705 .into_iter()
3706 .filter_map(|key| self.get(key).map(|value| (key, value)))
3707 .collect();
3708 for (ki, vi) in self.items() {
3710 for (kj, vj) in &entries {
3711 if ki != *kj && (check.violation)(vi, vj) {
3712 return Err(DurableCatalogError::UniquenessViolation);
3713 }
3714 }
3715 }
3716 }
3717 soft_assert_no_log!(self.verify().is_ok());
3718 Ok(())
3719 }
3720
3721 fn for_values<'a, F: FnMut(&'a K, &'a V)>(&'a self, mut f: F) {
3724 let mut seen = BTreeSet::new();
3725 for k in self.pending.keys() {
3726 seen.insert(k);
3727 let v = self.get(k);
3728 if let Some(v) = v {
3731 f(k, v);
3732 }
3733 }
3734 for (k, v) in self.initial.iter() {
3735 if !seen.contains(k) {
3737 f(k, v);
3738 }
3739 }
3740 }
3741
3742 fn get(&self, k: &K) -> Option<&V> {
3744 let pending = self.pending.get(k).map(Vec::as_slice).unwrap_or_default();
3745 let mut updates = Vec::with_capacity(pending.len() + 1);
3746 if let Some(initial) = self.initial.get(k) {
3747 updates.push((initial, Diff::ONE));
3748 }
3749 updates.extend(
3750 pending
3751 .into_iter()
3752 .map(|TransactionUpdate { value, ts: _, diff }| (value, *diff)),
3753 );
3754
3755 differential_dataflow::consolidation::consolidate(&mut updates);
3756 assert!(updates.len() <= 1);
3757 updates.into_iter().next().map(|(v, _)| v)
3758 }
3759
3760 #[cfg(test)]
3765 fn items_cloned(&self) -> BTreeMap<K, V> {
3766 let mut items = BTreeMap::new();
3767 self.for_values(|k, v| {
3768 items.insert(k.clone(), v.clone());
3769 });
3770 items
3771 }
3772
3773 fn current_items_proto<KP, VP>(&self) -> BTreeMap<KP, VP>
3777 where
3778 K: RustType<KP>,
3779 V: RustType<VP>,
3780 KP: Ord,
3781 {
3782 let mut items = BTreeMap::new();
3783 self.for_values(|k, v| {
3784 items.insert(k.into_proto(), v.into_proto());
3785 });
3786 items
3787 }
3788
3789 fn items(&self) -> BTreeMap<&K, &V> {
3792 let mut items = BTreeMap::new();
3793 self.for_values(|k, v| {
3794 items.insert(k, v);
3795 });
3796 items
3797 }
3798
3799 fn values(&self) -> BTreeSet<&V> {
3801 let mut items = BTreeSet::new();
3802 self.for_values(|_, v| {
3803 items.insert(v);
3804 });
3805 items
3806 }
3807
3808 fn len(&self) -> usize {
3810 let mut count = 0;
3811 self.for_values(|_, _| {
3812 count += 1;
3813 });
3814 count
3815 }
3816
3817 fn for_values_mut<F: FnMut(&mut BTreeMap<K, Vec<TransactionUpdate<V>>>, &K, &V)>(
3821 &mut self,
3822 mut f: F,
3823 ) {
3824 let mut pending = BTreeMap::new();
3825 self.for_values(|k, v| f(&mut pending, k, v));
3826 for (k, updates) in pending {
3827 self.pending.entry(k).or_default().extend(updates);
3828 }
3829 }
3830
3831 fn insert(&mut self, k: K, v: V, ts: Timestamp) -> Result<(), DurableCatalogError> {
3835 let mut violation = None;
3836 let uniqueness_violation = self.uniqueness_check.as_ref().map(|check| check.violation);
3837 self.for_values(|for_k, for_v| {
3838 if &k == for_k {
3839 violation = Some(DurableCatalogError::DuplicateKey);
3840 }
3841 if let Some(uniqueness_violation) = uniqueness_violation {
3842 if uniqueness_violation(for_v, &v) {
3843 violation = Some(DurableCatalogError::UniquenessViolation);
3844 }
3845 }
3846 });
3847 if let Some(violation) = violation {
3848 return Err(violation);
3849 }
3850 self.pending.entry(k).or_default().push(TransactionUpdate {
3851 value: v,
3852 ts,
3853 diff: Diff::ONE,
3854 });
3855 soft_assert_no_log!(self.verify().is_ok());
3856 Ok(())
3857 }
3858
3859 fn update<F: Fn(&K, &V) -> Option<V>>(
3868 &mut self,
3869 f: F,
3870 ts: Timestamp,
3871 ) -> Result<Diff, DurableCatalogError> {
3872 let mut changed = Diff::ZERO;
3873 let mut keys = BTreeSet::new();
3874 let pending = self.pending.clone();
3876 self.for_values_mut(|p, k, v| {
3877 if let Some(next) = f(k, v) {
3878 changed += Diff::ONE;
3879 keys.insert(k.clone());
3880 let updates = p.entry(k.clone()).or_default();
3881 updates.push(TransactionUpdate {
3882 value: v.clone(),
3883 ts,
3884 diff: Diff::MINUS_ONE,
3885 });
3886 updates.push(TransactionUpdate {
3887 value: next,
3888 ts,
3889 diff: Diff::ONE,
3890 });
3891 }
3892 });
3893 if let Err(err) = self.verify_keys(&keys) {
3895 self.pending = pending;
3896 Err(err)
3897 } else {
3898 Ok(changed)
3899 }
3900 }
3901
3902 fn update_by_key(&mut self, k: K, v: V, ts: Timestamp) -> Result<bool, DurableCatalogError> {
3907 if let Some(cur_v) = self.get(&k) {
3908 if v != *cur_v {
3909 self.set(k, Some(v), ts)?;
3910 }
3911 Ok(true)
3912 } else {
3913 Ok(false)
3914 }
3915 }
3916
3917 fn update_by_keys(
3922 &mut self,
3923 kvs: impl IntoIterator<Item = (K, V)>,
3924 ts: Timestamp,
3925 ) -> Result<Diff, DurableCatalogError> {
3926 let kvs: Vec<_> = kvs
3927 .into_iter()
3928 .filter_map(|(k, v)| match self.get(&k) {
3929 Some(cur_v) => Some((*cur_v == v, k, v)),
3931 None => None,
3932 })
3933 .collect();
3934 let changed = kvs.len();
3935 let changed =
3936 Diff::try_from(changed).map_err(|e| DurableCatalogError::Internal(e.to_string()))?;
3937 let kvs = kvs
3938 .into_iter()
3939 .filter(|(no_op, _, _)| !no_op)
3941 .map(|(_, k, v)| (k, Some(v)))
3942 .collect();
3943 self.set_many(kvs, ts)?;
3944 Ok(changed)
3945 }
3946
3947 fn update_needs_uniqueness_check(&self, prev: Option<&V>, next: Option<&V>) -> bool {
3949 match (&self.uniqueness_check, prev, next) {
3950 (None, _, _) | (_, _, None) => false,
3952 (Some(check), Some(prev), Some(next)) => {
3954 !(check.is_unique_key_unchanged_after_update)(prev, next)
3955 }
3956 (Some(_), None, Some(_)) => true,
3958 }
3959 }
3960
3961 fn set(&mut self, k: K, v: Option<V>, ts: Timestamp) -> Result<Option<V>, DurableCatalogError> {
3968 let prev = self.get(&k).cloned();
3969 let needs_uniqueness_check = self.update_needs_uniqueness_check(prev.as_ref(), v.as_ref());
3970 let entry = self.pending.entry(k.clone()).or_default();
3971 let restore_len = entry.len();
3972
3973 match (v, prev.clone()) {
3974 (Some(v), Some(prev)) => {
3975 entry.push(TransactionUpdate {
3976 value: prev,
3977 ts,
3978 diff: Diff::MINUS_ONE,
3979 });
3980 entry.push(TransactionUpdate {
3981 value: v,
3982 ts,
3983 diff: Diff::ONE,
3984 });
3985 }
3986 (Some(v), None) => {
3987 entry.push(TransactionUpdate {
3988 value: v,
3989 ts,
3990 diff: Diff::ONE,
3991 });
3992 }
3993 (None, Some(prev)) => {
3994 entry.push(TransactionUpdate {
3995 value: prev,
3996 ts,
3997 diff: Diff::MINUS_ONE,
3998 });
3999 }
4000 (None, None) => {}
4001 }
4002
4003 if needs_uniqueness_check {
4005 if let Err(err) = self.verify_keys([&k]) {
4006 let pending = self.pending.get_mut(&k).expect("inserted above");
4009 pending.truncate(restore_len);
4010 return Err(err);
4011 }
4012 }
4013 Ok(prev)
4014 }
4015
4016 fn set_many(
4021 &mut self,
4022 kvs: BTreeMap<K, Option<V>>,
4023 ts: Timestamp,
4024 ) -> Result<BTreeMap<K, Option<V>>, DurableCatalogError> {
4025 if kvs.is_empty() {
4026 return Ok(BTreeMap::new());
4027 }
4028
4029 let mut prevs = BTreeMap::new();
4030 let mut restores = BTreeMap::new();
4031 let mut keys_to_verify_uniqueness = Vec::new();
4033
4034 for (k, v) in kvs {
4035 let prev = self.get(&k).cloned();
4036 if self.update_needs_uniqueness_check(prev.as_ref(), v.as_ref()) {
4037 keys_to_verify_uniqueness.push(k.clone());
4038 }
4039 let entry = self.pending.entry(k.clone()).or_default();
4040 restores.insert(k.clone(), entry.len());
4041
4042 match (v, prev.clone()) {
4043 (Some(v), Some(prev)) => {
4044 entry.push(TransactionUpdate {
4045 value: prev,
4046 ts,
4047 diff: Diff::MINUS_ONE,
4048 });
4049 entry.push(TransactionUpdate {
4050 value: v,
4051 ts,
4052 diff: Diff::ONE,
4053 });
4054 }
4055 (Some(v), None) => {
4056 entry.push(TransactionUpdate {
4057 value: v,
4058 ts,
4059 diff: Diff::ONE,
4060 });
4061 }
4062 (None, Some(prev)) => {
4063 entry.push(TransactionUpdate {
4064 value: prev,
4065 ts,
4066 diff: Diff::MINUS_ONE,
4067 });
4068 }
4069 (None, None) => {}
4070 }
4071
4072 prevs.insert(k, prev);
4073 }
4074
4075 if let Err(err) = self.verify_keys(keys_to_verify_uniqueness.iter()) {
4077 for (k, restore_len) in restores {
4078 let pending = self.pending.get_mut(&k).expect("inserted above");
4081 pending.truncate(restore_len);
4082 }
4083 Err(err)
4084 } else {
4085 Ok(prevs)
4086 }
4087 }
4088
4089 fn delete<F: Fn(&K, &V) -> bool>(&mut self, f: F, ts: Timestamp) -> Vec<(K, V)> {
4095 let mut deleted = Vec::new();
4096 self.for_values_mut(|p, k, v| {
4097 if f(k, v) {
4098 deleted.push((k.clone(), v.clone()));
4099 p.entry(k.clone()).or_default().push(TransactionUpdate {
4100 value: v.clone(),
4101 ts,
4102 diff: Diff::MINUS_ONE,
4103 });
4104 }
4105 });
4106 soft_assert_no_log!(self.verify().is_ok());
4107 deleted
4108 }
4109
4110 fn delete_by_key(&mut self, k: K, ts: Timestamp) -> Option<V> {
4114 self.set(k, None, ts)
4115 .expect("deleting an entry cannot violate uniqueness")
4116 }
4117
4118 fn delete_by_keys(&mut self, ks: impl IntoIterator<Item = K>, ts: Timestamp) -> Vec<(K, V)> {
4122 let kvs = ks.into_iter().map(|k| (k, None)).collect();
4123 let prevs = self
4124 .set_many(kvs, ts)
4125 .expect("deleting entries cannot violate uniqueness");
4126 prevs
4127 .into_iter()
4128 .filter_map(|(k, v)| v.map(|v| (k, v)))
4129 .collect()
4130 }
4131}
4132
4133#[cfg(test)]
4134#[allow(clippy::unwrap_used)]
4135mod tests {
4136 use super::*;
4137
4138 use mz_controller::clusters::ReplicaLogging;
4139 use mz_ore::now::SYSTEM_TIME;
4140 use mz_ore::{assert_none, assert_ok};
4141 use mz_persist_client::cache::PersistClientCache;
4142 use mz_persist_types::PersistLocation;
4143 use semver::Version;
4144
4145 use crate::durable::{
4146 ReplicaConfig, ReplicaLocation, TestCatalogStateBuilder, test_bootstrap_args,
4147 };
4148 use crate::memory;
4149
4150 #[mz_ore::test]
4151 fn test_table_transaction_simple() {
4152 fn uniqueness_violation(a: &String, b: &String) -> bool {
4153 a == b
4154 }
4155 let mut table = TableTransaction::new_with_uniqueness_fn(
4156 BTreeMap::from([(1i64.to_le_bytes().to_vec(), "a".to_string())]),
4157 uniqueness_violation,
4158 uniqueness_violation,
4159 )
4160 .unwrap();
4161
4162 assert_ok!(table.insert(2i64.to_le_bytes().to_vec(), "b".to_string(), 0));
4165 assert_ok!(table.insert(3i64.to_le_bytes().to_vec(), "c".to_string(), 0));
4166 assert!(
4167 table
4168 .insert(1i64.to_le_bytes().to_vec(), "c".to_string(), 0)
4169 .is_err()
4170 );
4171 assert!(
4172 table
4173 .insert(4i64.to_le_bytes().to_vec(), "c".to_string(), 0)
4174 .is_err()
4175 );
4176 }
4177
4178 #[mz_ore::test]
4179 fn test_skip_scan_when_unique_key_unchanged() {
4180 fn first_char_same(prev: &String, next: &String) -> bool {
4181 prev.chars().next() == next.chars().next()
4182 }
4183
4184 fn panic_uniqueness_violation(_: &String, _: &String) -> bool {
4186 panic!("uniqueness scan ran for an update that kept the same unique key");
4187 }
4188 let mut table = TableTransaction::new_with_uniqueness_fn(
4189 BTreeMap::from([
4190 (1i64.to_le_bytes().to_vec(), "a1".to_string()),
4191 (2i64.to_le_bytes().to_vec(), "b1".to_string()),
4192 ]),
4193 panic_uniqueness_violation,
4194 first_char_same,
4196 )
4197 .unwrap();
4198 assert!(
4201 table
4202 .update_by_key(1i64.to_le_bytes().to_vec(), "a2".to_string(), 0)
4203 .unwrap()
4204 );
4205
4206 fn real_uniqueness_violation(a: &String, b: &String) -> bool {
4208 a.chars().next() == b.chars().next()
4209 }
4210 let mut table = TableTransaction::new_with_uniqueness_fn(
4211 BTreeMap::from([
4212 (1i64.to_le_bytes().to_vec(), "a1".to_string()),
4213 (2i64.to_le_bytes().to_vec(), "b1".to_string()),
4214 ]),
4215 real_uniqueness_violation,
4216 first_char_same,
4217 )
4218 .unwrap();
4219 assert!(
4222 table
4223 .update_by_key(1i64.to_le_bytes().to_vec(), "b2".to_string(), 0)
4224 .is_err()
4225 );
4226 }
4227
4228 #[mz_ore::test]
4229 fn test_table_transaction() {
4230 fn uniqueness_violation(a: &String, b: &String) -> bool {
4231 a == b
4232 }
4233 let mut table: BTreeMap<Vec<u8>, String> = BTreeMap::new();
4234
4235 fn commit(
4236 table: &mut BTreeMap<Vec<u8>, String>,
4237 mut pending: Vec<(Vec<u8>, String, Diff)>,
4238 ) {
4239 pending.sort_by(|a, b| a.2.cmp(&b.2));
4241 for (k, v, diff) in pending {
4242 if diff == Diff::MINUS_ONE {
4243 let prev = table.remove(&k);
4244 assert_eq!(prev, Some(v));
4245 } else if diff == Diff::ONE {
4246 let prev = table.insert(k, v);
4247 assert_eq!(prev, None);
4248 } else {
4249 panic!("unexpected diff: {diff}");
4250 }
4251 }
4252 }
4253
4254 table.insert(1i64.to_le_bytes().to_vec(), "v1".to_string());
4255 table.insert(2i64.to_le_bytes().to_vec(), "v2".to_string());
4256 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4257 table.clone(),
4258 uniqueness_violation,
4259 uniqueness_violation,
4260 )
4261 .unwrap();
4262 assert_eq!(table_txn.items_cloned(), table);
4263 assert_eq!(table_txn.delete(|_k, _v| false, 0).len(), 0);
4264 assert_eq!(table_txn.delete(|_k, v| v == "v2", 1).len(), 1);
4265 assert_eq!(
4266 table_txn.items_cloned(),
4267 BTreeMap::from([(1i64.to_le_bytes().to_vec(), "v1".to_string())])
4268 );
4269 assert_eq!(
4270 table_txn
4271 .update(|_k, _v| Some("v3".to_string()), 2)
4272 .unwrap(),
4273 Diff::ONE
4274 );
4275
4276 table_txn
4278 .insert(3i64.to_le_bytes().to_vec(), "v3".to_string(), 3)
4279 .unwrap_err();
4280
4281 table_txn
4282 .insert(3i64.to_le_bytes().to_vec(), "v4".to_string(), 4)
4283 .unwrap();
4284 assert_eq!(
4285 table_txn.items_cloned(),
4286 BTreeMap::from([
4287 (1i64.to_le_bytes().to_vec(), "v3".to_string()),
4288 (3i64.to_le_bytes().to_vec(), "v4".to_string()),
4289 ])
4290 );
4291 let err = table_txn
4292 .update(|_k, _v| Some("v1".to_string()), 5)
4293 .unwrap_err();
4294 assert!(
4295 matches!(err, DurableCatalogError::UniquenessViolation),
4296 "unexpected err: {err:?}"
4297 );
4298 let pending = table_txn.pending();
4299 assert_eq!(
4300 pending,
4301 vec![
4302 (
4303 1i64.to_le_bytes().to_vec(),
4304 "v1".to_string(),
4305 Diff::MINUS_ONE
4306 ),
4307 (1i64.to_le_bytes().to_vec(), "v3".to_string(), Diff::ONE),
4308 (
4309 2i64.to_le_bytes().to_vec(),
4310 "v2".to_string(),
4311 Diff::MINUS_ONE
4312 ),
4313 (3i64.to_le_bytes().to_vec(), "v4".to_string(), Diff::ONE),
4314 ]
4315 );
4316 commit(&mut table, pending);
4317 assert_eq!(
4318 table,
4319 BTreeMap::from([
4320 (1i64.to_le_bytes().to_vec(), "v3".to_string()),
4321 (3i64.to_le_bytes().to_vec(), "v4".to_string())
4322 ])
4323 );
4324
4325 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4326 table.clone(),
4327 uniqueness_violation,
4328 uniqueness_violation,
4329 )
4330 .unwrap();
4331 assert_eq!(
4333 table_txn.delete(|k, _v| k == &1i64.to_le_bytes(), 0).len(),
4334 1
4335 );
4336 table_txn
4337 .insert(1i64.to_le_bytes().to_vec(), "v3".to_string(), 0)
4338 .unwrap();
4339 table_txn
4341 .insert(5i64.to_le_bytes().to_vec(), "v3".to_string(), 0)
4342 .unwrap_err();
4343 table_txn
4345 .insert(1i64.to_le_bytes().to_vec(), "v5".to_string(), 0)
4346 .unwrap_err();
4347 assert_eq!(
4348 table_txn.delete(|k, _v| k == &1i64.to_le_bytes(), 0).len(),
4349 1
4350 );
4351 table_txn
4353 .insert(5i64.to_le_bytes().to_vec(), "v3".to_string(), 0)
4354 .unwrap();
4355 table_txn
4356 .insert(1i64.to_le_bytes().to_vec(), "v5".to_string(), 0)
4357 .unwrap();
4358 let pending = table_txn.pending();
4359 assert_eq!(
4360 pending,
4361 vec![
4362 (
4363 1i64.to_le_bytes().to_vec(),
4364 "v3".to_string(),
4365 Diff::MINUS_ONE
4366 ),
4367 (1i64.to_le_bytes().to_vec(), "v5".to_string(), Diff::ONE),
4368 (5i64.to_le_bytes().to_vec(), "v3".to_string(), Diff::ONE),
4369 ]
4370 );
4371 commit(&mut table, pending);
4372 assert_eq!(
4373 table,
4374 BTreeMap::from([
4375 (1i64.to_le_bytes().to_vec(), "v5".to_string()),
4376 (3i64.to_le_bytes().to_vec(), "v4".to_string()),
4377 (5i64.to_le_bytes().to_vec(), "v3".to_string()),
4378 ])
4379 );
4380
4381 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4382 table.clone(),
4383 uniqueness_violation,
4384 uniqueness_violation,
4385 )
4386 .unwrap();
4387 assert_eq!(table_txn.delete(|_k, _v| true, 0).len(), 3);
4388 table_txn
4389 .insert(1i64.to_le_bytes().to_vec(), "v1".to_string(), 0)
4390 .unwrap();
4391
4392 commit(&mut table, table_txn.pending());
4393 assert_eq!(
4394 table,
4395 BTreeMap::from([(1i64.to_le_bytes().to_vec(), "v1".to_string()),])
4396 );
4397
4398 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4399 table.clone(),
4400 uniqueness_violation,
4401 uniqueness_violation,
4402 )
4403 .unwrap();
4404 assert_eq!(table_txn.delete(|_k, _v| true, 0).len(), 1);
4405 table_txn
4406 .insert(1i64.to_le_bytes().to_vec(), "v2".to_string(), 0)
4407 .unwrap();
4408 commit(&mut table, table_txn.pending());
4409 assert_eq!(
4410 table,
4411 BTreeMap::from([(1i64.to_le_bytes().to_vec(), "v2".to_string()),])
4412 );
4413
4414 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4416 table.clone(),
4417 uniqueness_violation,
4418 uniqueness_violation,
4419 )
4420 .unwrap();
4421 assert_eq!(table_txn.delete(|_k, _v| true, 0).len(), 1);
4422 table_txn
4423 .insert(1i64.to_le_bytes().to_vec(), "v3".to_string(), 0)
4424 .unwrap();
4425 table_txn
4426 .insert(1i64.to_le_bytes().to_vec(), "v4".to_string(), 1)
4427 .unwrap_err();
4428 assert_eq!(table_txn.delete(|_k, _v| true, 1).len(), 1);
4429 table_txn
4430 .insert(1i64.to_le_bytes().to_vec(), "v5".to_string(), 1)
4431 .unwrap();
4432 commit(&mut table, table_txn.pending());
4433 assert_eq!(
4434 table.clone().into_iter().collect::<Vec<_>>(),
4435 vec![(1i64.to_le_bytes().to_vec(), "v5".to_string())]
4436 );
4437
4438 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4440 table.clone(),
4441 uniqueness_violation,
4442 uniqueness_violation,
4443 )
4444 .unwrap();
4445 table_txn
4447 .set(2i64.to_le_bytes().to_vec(), Some("v5".to_string()), 0)
4448 .unwrap_err();
4449 table_txn
4450 .set(3i64.to_le_bytes().to_vec(), Some("v6".to_string()), 1)
4451 .unwrap();
4452 table_txn.set(2i64.to_le_bytes().to_vec(), None, 2).unwrap();
4453 table_txn.set(1i64.to_le_bytes().to_vec(), None, 2).unwrap();
4454 let pending = table_txn.pending();
4455 assert_eq!(
4456 pending,
4457 vec![
4458 (
4459 1i64.to_le_bytes().to_vec(),
4460 "v5".to_string(),
4461 Diff::MINUS_ONE
4462 ),
4463 (3i64.to_le_bytes().to_vec(), "v6".to_string(), Diff::ONE),
4464 ]
4465 );
4466 commit(&mut table, pending);
4467 assert_eq!(
4468 table,
4469 BTreeMap::from([(3i64.to_le_bytes().to_vec(), "v6".to_string())])
4470 );
4471
4472 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4474 table.clone(),
4475 uniqueness_violation,
4476 uniqueness_violation,
4477 )
4478 .unwrap();
4479 table_txn
4480 .set(3i64.to_le_bytes().to_vec(), Some("v6".to_string()), 0)
4481 .unwrap();
4482 let pending = table_txn.pending::<Vec<u8>, String>();
4483 assert!(pending.is_empty());
4484
4485 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4487 table.clone(),
4488 uniqueness_violation,
4489 uniqueness_violation,
4490 )
4491 .unwrap();
4492 table_txn
4494 .set_many(
4495 BTreeMap::from([
4496 (1i64.to_le_bytes().to_vec(), Some("v6".to_string())),
4497 (42i64.to_le_bytes().to_vec(), Some("v1".to_string())),
4498 ]),
4499 0,
4500 )
4501 .unwrap_err();
4502 table_txn
4503 .set_many(
4504 BTreeMap::from([
4505 (1i64.to_le_bytes().to_vec(), Some("v6".to_string())),
4506 (3i64.to_le_bytes().to_vec(), Some("v1".to_string())),
4507 ]),
4508 1,
4509 )
4510 .unwrap();
4511 table_txn
4512 .set_many(
4513 BTreeMap::from([
4514 (42i64.to_le_bytes().to_vec(), Some("v7".to_string())),
4515 (3i64.to_le_bytes().to_vec(), None),
4516 ]),
4517 2,
4518 )
4519 .unwrap();
4520 let pending = table_txn.pending();
4521 assert_eq!(
4522 pending,
4523 vec![
4524 (1i64.to_le_bytes().to_vec(), "v6".to_string(), Diff::ONE),
4525 (
4526 3i64.to_le_bytes().to_vec(),
4527 "v6".to_string(),
4528 Diff::MINUS_ONE
4529 ),
4530 (42i64.to_le_bytes().to_vec(), "v7".to_string(), Diff::ONE),
4531 ]
4532 );
4533 commit(&mut table, pending);
4534 assert_eq!(
4535 table,
4536 BTreeMap::from([
4537 (1i64.to_le_bytes().to_vec(), "v6".to_string()),
4538 (42i64.to_le_bytes().to_vec(), "v7".to_string())
4539 ])
4540 );
4541
4542 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4544 table.clone(),
4545 uniqueness_violation,
4546 uniqueness_violation,
4547 )
4548 .unwrap();
4549 table_txn
4550 .set_many(
4551 BTreeMap::from([
4552 (1i64.to_le_bytes().to_vec(), Some("v6".to_string())),
4553 (42i64.to_le_bytes().to_vec(), Some("v7".to_string())),
4554 ]),
4555 0,
4556 )
4557 .unwrap();
4558 let pending = table_txn.pending::<Vec<u8>, String>();
4559 assert!(pending.is_empty());
4560 commit(&mut table, pending);
4561 assert_eq!(
4562 table,
4563 BTreeMap::from([
4564 (1i64.to_le_bytes().to_vec(), "v6".to_string()),
4565 (42i64.to_le_bytes().to_vec(), "v7".to_string())
4566 ])
4567 );
4568
4569 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4571 table.clone(),
4572 uniqueness_violation,
4573 uniqueness_violation,
4574 )
4575 .unwrap();
4576 table_txn
4578 .update_by_key(1i64.to_le_bytes().to_vec(), "v7".to_string(), 0)
4579 .unwrap_err();
4580 assert!(
4581 table_txn
4582 .update_by_key(1i64.to_le_bytes().to_vec(), "v8".to_string(), 1)
4583 .unwrap()
4584 );
4585 assert!(
4586 !table_txn
4587 .update_by_key(5i64.to_le_bytes().to_vec(), "v8".to_string(), 2)
4588 .unwrap()
4589 );
4590 let pending = table_txn.pending();
4591 assert_eq!(
4592 pending,
4593 vec![
4594 (
4595 1i64.to_le_bytes().to_vec(),
4596 "v6".to_string(),
4597 Diff::MINUS_ONE
4598 ),
4599 (1i64.to_le_bytes().to_vec(), "v8".to_string(), Diff::ONE),
4600 ]
4601 );
4602 commit(&mut table, pending);
4603 assert_eq!(
4604 table,
4605 BTreeMap::from([
4606 (1i64.to_le_bytes().to_vec(), "v8".to_string()),
4607 (42i64.to_le_bytes().to_vec(), "v7".to_string())
4608 ])
4609 );
4610
4611 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4613 table.clone(),
4614 uniqueness_violation,
4615 uniqueness_violation,
4616 )
4617 .unwrap();
4618 assert!(
4619 table_txn
4620 .update_by_key(1i64.to_le_bytes().to_vec(), "v8".to_string(), 0)
4621 .unwrap()
4622 );
4623 let pending = table_txn.pending::<Vec<u8>, String>();
4624 assert!(pending.is_empty());
4625 commit(&mut table, pending);
4626 assert_eq!(
4627 table,
4628 BTreeMap::from([
4629 (1i64.to_le_bytes().to_vec(), "v8".to_string()),
4630 (42i64.to_le_bytes().to_vec(), "v7".to_string())
4631 ])
4632 );
4633
4634 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4636 table.clone(),
4637 uniqueness_violation,
4638 uniqueness_violation,
4639 )
4640 .unwrap();
4641 table_txn
4643 .update_by_keys(
4644 [
4645 (1i64.to_le_bytes().to_vec(), "v7".to_string()),
4646 (5i64.to_le_bytes().to_vec(), "v7".to_string()),
4647 ],
4648 0,
4649 )
4650 .unwrap_err();
4651 let n = table_txn
4652 .update_by_keys(
4653 [
4654 (1i64.to_le_bytes().to_vec(), "v9".to_string()),
4655 (5i64.to_le_bytes().to_vec(), "v7".to_string()),
4656 ],
4657 1,
4658 )
4659 .unwrap();
4660 assert_eq!(n, Diff::ONE);
4661 let n = table_txn
4662 .update_by_keys(
4663 [
4664 (15i64.to_le_bytes().to_vec(), "v9".to_string()),
4665 (5i64.to_le_bytes().to_vec(), "v7".to_string()),
4666 ],
4667 2,
4668 )
4669 .unwrap();
4670 assert_eq!(n, Diff::ZERO);
4671 let pending = table_txn.pending();
4672 assert_eq!(
4673 pending,
4674 vec![
4675 (
4676 1i64.to_le_bytes().to_vec(),
4677 "v8".to_string(),
4678 Diff::MINUS_ONE
4679 ),
4680 (1i64.to_le_bytes().to_vec(), "v9".to_string(), Diff::ONE),
4681 ]
4682 );
4683 commit(&mut table, pending);
4684 assert_eq!(
4685 table,
4686 BTreeMap::from([
4687 (1i64.to_le_bytes().to_vec(), "v9".to_string()),
4688 (42i64.to_le_bytes().to_vec(), "v7".to_string())
4689 ])
4690 );
4691
4692 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4694 table.clone(),
4695 uniqueness_violation,
4696 uniqueness_violation,
4697 )
4698 .unwrap();
4699 let n = table_txn
4700 .update_by_keys(
4701 [
4702 (1i64.to_le_bytes().to_vec(), "v9".to_string()),
4703 (42i64.to_le_bytes().to_vec(), "v7".to_string()),
4704 ],
4705 0,
4706 )
4707 .unwrap();
4708 assert_eq!(n, Diff::from(2));
4709 let pending = table_txn.pending::<Vec<u8>, String>();
4710 assert!(pending.is_empty());
4711 commit(&mut table, pending);
4712 assert_eq!(
4713 table,
4714 BTreeMap::from([
4715 (1i64.to_le_bytes().to_vec(), "v9".to_string()),
4716 (42i64.to_le_bytes().to_vec(), "v7".to_string())
4717 ])
4718 );
4719
4720 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4722 table.clone(),
4723 uniqueness_violation,
4724 uniqueness_violation,
4725 )
4726 .unwrap();
4727 let prev = table_txn.delete_by_key(1i64.to_le_bytes().to_vec(), 0);
4728 assert_eq!(prev, Some("v9".to_string()));
4729 let prev = table_txn.delete_by_key(5i64.to_le_bytes().to_vec(), 1);
4730 assert_none!(prev);
4731 let prev = table_txn.delete_by_key(1i64.to_le_bytes().to_vec(), 2);
4732 assert_none!(prev);
4733 let pending = table_txn.pending();
4734 assert_eq!(
4735 pending,
4736 vec![(
4737 1i64.to_le_bytes().to_vec(),
4738 "v9".to_string(),
4739 Diff::MINUS_ONE
4740 ),]
4741 );
4742 commit(&mut table, pending);
4743 assert_eq!(
4744 table,
4745 BTreeMap::from([(42i64.to_le_bytes().to_vec(), "v7".to_string())])
4746 );
4747
4748 let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4750 table.clone(),
4751 uniqueness_violation,
4752 uniqueness_violation,
4753 )
4754 .unwrap();
4755 let prevs = table_txn.delete_by_keys(
4756 [42i64.to_le_bytes().to_vec(), 55i64.to_le_bytes().to_vec()],
4757 0,
4758 );
4759 assert_eq!(
4760 prevs,
4761 vec![(42i64.to_le_bytes().to_vec(), "v7".to_string())]
4762 );
4763 let prevs = table_txn.delete_by_keys(
4764 [42i64.to_le_bytes().to_vec(), 55i64.to_le_bytes().to_vec()],
4765 1,
4766 );
4767 assert_eq!(prevs, vec![]);
4768 let prevs = table_txn.delete_by_keys(
4769 [10i64.to_le_bytes().to_vec(), 55i64.to_le_bytes().to_vec()],
4770 2,
4771 );
4772 assert_eq!(prevs, vec![]);
4773 let pending = table_txn.pending();
4774 assert_eq!(
4775 pending,
4776 vec![(
4777 42i64.to_le_bytes().to_vec(),
4778 "v7".to_string(),
4779 Diff::MINUS_ONE
4780 ),]
4781 );
4782 commit(&mut table, pending);
4783 assert_eq!(table, BTreeMap::new());
4784 }
4785
4786 #[mz_ore::test(tokio::test)]
4787 #[cfg_attr(miri, ignore)] async fn test_savepoint() {
4789 const VERSION: Version = Version::new(26, 0, 0);
4790 let mut persist_cache = PersistClientCache::new_no_metrics();
4791 persist_cache.cfg.build_version = VERSION;
4792 let persist_client = persist_cache
4793 .open(PersistLocation::new_in_mem())
4794 .await
4795 .unwrap();
4796 let state_builder = TestCatalogStateBuilder::new(persist_client)
4797 .with_default_deploy_generation()
4798 .with_version(VERSION);
4799
4800 let _ = state_builder
4802 .clone()
4803 .unwrap_build()
4804 .await
4805 .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4806 .await
4807 .unwrap();
4808 let mut savepoint_state = state_builder
4809 .unwrap_build()
4810 .await
4811 .open_savepoint(SYSTEM_TIME().into(), &test_bootstrap_args())
4812 .await
4813 .unwrap();
4814
4815 let initial_snapshot = savepoint_state.sync_to_current_updates().await.unwrap();
4816 assert!(!initial_snapshot.is_empty());
4817
4818 let db_name = "db";
4819 let db_owner = RoleId::User(42);
4820 let db_privileges = Vec::new();
4821 let mut txn = savepoint_state.transaction().await.unwrap();
4822 let (db_id, db_oid) = txn
4823 .insert_user_database(db_name, db_owner, db_privileges.clone(), &HashSet::new())
4824 .unwrap();
4825 let commit_ts = txn.upper();
4826 txn.commit_internal(commit_ts).await.unwrap();
4827 let updates = savepoint_state.sync_to_current_updates().await.unwrap();
4828 let update = updates.into_element();
4829
4830 assert_eq!(update.diff, StateDiff::Addition);
4831
4832 let db = match update.kind {
4833 memory::objects::StateUpdateKind::Database(db) => db,
4834 update => panic!("unexpected update: {update:?}"),
4835 };
4836
4837 assert_eq!(db_id, db.id);
4838 assert_eq!(db_oid, db.oid);
4839 assert_eq!(db_name, db.name);
4840 assert_eq!(db_owner, db.owner_id);
4841 assert_eq!(db_privileges, db.privileges);
4842 }
4843
4844 #[mz_ore::test(tokio::test)]
4845 #[cfg_attr(miri, ignore)] async fn test_dry_run_transaction_rejects_internal_commit() {
4847 const VERSION: Version = Version::new(26, 0, 0);
4848 let mut persist_cache = PersistClientCache::new_no_metrics();
4849 persist_cache.cfg.build_version = VERSION;
4850 let persist_client = persist_cache
4851 .open(PersistLocation::new_in_mem())
4852 .await
4853 .unwrap();
4854 let mut state = TestCatalogStateBuilder::new(persist_client)
4855 .with_default_deploy_generation()
4856 .with_version(VERSION)
4857 .unwrap_build()
4858 .await
4859 .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4860 .await
4861 .unwrap();
4862 let _ = state.sync_to_current_updates().await.unwrap();
4863
4864 let initial_id = state.get_next_id(USER_ITEM_ALLOC_KEY).await.unwrap();
4865 let initial_upper = state.current_upper().await;
4866 let snapshot = state.snapshot().await.unwrap();
4867 let mut dry_run = state.transaction_from_snapshot(snapshot).unwrap();
4868 let ids = dry_run
4869 .transaction_mut()
4870 .get_and_increment_id_by(USER_ITEM_ALLOC_KEY.to_string(), 1)
4871 .unwrap();
4872 assert_eq!(ids, vec![initial_id]);
4873
4874 let transaction = dry_run.transaction;
4875 let err = transaction
4876 .commit_internal(initial_upper)
4877 .await
4878 .unwrap_err();
4879 assert!(matches!(
4880 err,
4881 CatalogError::Durable(DurableCatalogError::DryRunTransaction)
4882 ));
4883 assert_eq!(state.current_upper().await, initial_upper);
4884 assert_eq!(
4885 state.get_next_id(USER_ITEM_ALLOC_KEY).await.unwrap(),
4886 initial_id
4887 );
4888 }
4889
4890 #[mz_ore::test(tokio::test)]
4891 #[cfg_attr(miri, ignore)] async fn test_dry_run_transaction_rejects_into_parts_escape() {
4893 const VERSION: Version = Version::new(26, 0, 0);
4894 let mut persist_cache = PersistClientCache::new_no_metrics();
4895 persist_cache.cfg.build_version = VERSION;
4896 let persist_client = persist_cache
4897 .open(PersistLocation::new_in_mem())
4898 .await
4899 .unwrap();
4900 let mut dry_run_state = TestCatalogStateBuilder::new(persist_client.clone())
4901 .with_default_deploy_generation()
4902 .with_version(VERSION)
4903 .unwrap_build()
4904 .await
4905 .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4906 .await
4907 .unwrap();
4908 let mut replacement_state = TestCatalogStateBuilder::new(persist_client)
4909 .with_default_deploy_generation()
4910 .with_version(VERSION)
4911 .unwrap_build()
4912 .await
4913 .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4914 .await
4915 .unwrap();
4916 let _ = dry_run_state.sync_to_current_updates().await.unwrap();
4917 let _ = replacement_state.sync_to_current_updates().await.unwrap();
4918
4919 let initial_id = dry_run_state
4920 .get_next_id(USER_ITEM_ALLOC_KEY)
4921 .await
4922 .unwrap();
4923 let initial_upper = dry_run_state.current_upper().await;
4924 let snapshot = dry_run_state.snapshot().await.unwrap();
4925 let mut dry_run = dry_run_state.transaction_from_snapshot(snapshot).unwrap();
4926 let ids = dry_run
4927 .transaction_mut()
4928 .get_and_increment_id_by(USER_ITEM_ALLOC_KEY.to_string(), 1)
4929 .unwrap();
4930 assert_eq!(ids, vec![initial_id]);
4931
4932 let replacement = replacement_state.transaction().await.unwrap();
4933 let escaped = std::mem::replace(dry_run.transaction_mut(), replacement);
4934 drop(dry_run);
4935
4936 let err = match escaped.into_parts() {
4937 Ok(_) => panic!("dry-run transaction decomposed into committable parts"),
4938 Err(err) => err,
4939 };
4940 assert!(matches!(
4941 err,
4942 CatalogError::Durable(DurableCatalogError::DryRunTransaction)
4943 ));
4944 assert_eq!(dry_run_state.current_upper().await, initial_upper);
4945 assert_eq!(
4946 dry_run_state
4947 .get_next_id(USER_ITEM_ALLOC_KEY)
4948 .await
4949 .unwrap(),
4950 initial_id
4951 );
4952 }
4953
4954 #[mz_ore::test(tokio::test)]
4958 #[cfg_attr(miri, ignore)] async fn test_insert_replica_with_id_does_not_consume_allocator() {
4960 const VERSION: Version = Version::new(26, 0, 0);
4961 let mut persist_cache = PersistClientCache::new_no_metrics();
4962 persist_cache.cfg.build_version = VERSION;
4963 let persist_client = persist_cache
4964 .open(PersistLocation::new_in_mem())
4965 .await
4966 .unwrap();
4967 let state_builder = TestCatalogStateBuilder::new(persist_client)
4968 .with_default_deploy_generation()
4969 .with_version(VERSION);
4970 let mut state = state_builder
4971 .unwrap_build()
4972 .await
4973 .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4974 .await
4975 .unwrap();
4976
4977 let cluster_id = ClusterId::User(1);
4980 let owner_id = RoleId::User(1);
4981 let config = ReplicaConfig {
4982 location: ReplicaLocation::Managed {
4983 size: "1".to_string(),
4984 availability_zones: Vec::new(),
4985 internal: false,
4986 billed_as: None,
4987 pending: false,
4988 },
4989 logging: ReplicaLogging {
4990 log_logging: false,
4991 interval: Some(Duration::from_secs(1)),
4992 },
4993 arrangement_compression: false,
4994 };
4995
4996 let commit_ts = state.current_upper().await;
4998 let a = state
4999 .allocate_user_replica_ids(1, commit_ts)
5000 .await
5001 .unwrap()
5002 .into_element();
5003 assert!(a.is_user());
5004
5005 let initial_updates = state.sync_to_current_updates().await.unwrap();
5006 assert!(!initial_updates.is_empty());
5007
5008 let mut txn = state.transaction().await.unwrap();
5010 txn.insert_cluster_replica_with_id(cluster_id, a, "explicit", config, owner_id)
5011 .unwrap();
5012 let commit_ts = txn.upper();
5013 txn.commit_internal(commit_ts).await.unwrap();
5014 let _ = state.sync_to_current_updates().await.unwrap();
5015
5016 let commit_ts = state.current_upper().await;
5018 let b = state
5019 .allocate_user_replica_ids(1, commit_ts)
5020 .await
5021 .unwrap()
5022 .into_element();
5023
5024 assert_eq!(b.inner_id(), a.inner_id() + 1);
5027
5028 let txn = state.transaction().await.unwrap();
5030 let found = txn
5031 .get_cluster_replicas()
5032 .any(|replica| replica.replica_id == a);
5033 assert!(found, "explicitly inserted replica {a} not found");
5034 }
5035
5036 #[mz_ore::test]
5037 fn test_allocate_introspection_source_index_id() {
5038 let cluster_variant: u8 = 0b0000_0001;
5039 let cluster_id_inner: u64 =
5040 0b0000_0000_1100_0101_1100_0011_1010_1101_0000_1011_1111_1001_0110_1010;
5041 let timely_messages_received_log_variant: u8 = 0b0000_1000;
5042
5043 let cluster_id = ClusterId::System(cluster_id_inner);
5044 let log_variant = LogVariant::Timely(TimelyLog::MessagesReceived);
5045
5046 let introspection_source_index_id: u64 =
5047 0b0000_0001_1100_0101_1100_0011_1010_1101_0000_1011_1111_1001_0110_1010_0000_1000;
5048
5049 {
5051 let mut cluster_variant_mask = 0xFF << 56;
5052 cluster_variant_mask &= introspection_source_index_id;
5053 cluster_variant_mask >>= 56;
5054 assert_eq!(cluster_variant_mask, u64::from(cluster_variant));
5055 }
5056
5057 {
5059 let mut cluster_id_inner_mask = 0xFFFF_FFFF_FFFF << 8;
5060 cluster_id_inner_mask &= introspection_source_index_id;
5061 cluster_id_inner_mask >>= 8;
5062 assert_eq!(cluster_id_inner_mask, cluster_id_inner);
5063 }
5064
5065 {
5067 let mut log_variant_mask = 0xFF;
5068 log_variant_mask &= introspection_source_index_id;
5069 assert_eq!(
5070 log_variant_mask,
5071 u64::from(timely_messages_received_log_variant)
5072 );
5073 }
5074
5075 let (catalog_item_id, global_id) =
5076 Transaction::allocate_introspection_source_index_id(&cluster_id, log_variant);
5077
5078 assert_eq!(
5079 catalog_item_id,
5080 CatalogItemId::IntrospectionSourceIndex(introspection_source_index_id)
5081 );
5082 assert_eq!(
5083 global_id,
5084 GlobalId::IntrospectionSourceIndex(introspection_source_index_id)
5085 );
5086 }
5087}