-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathstate.rs
More file actions
2840 lines (2640 loc) · 112 KB
/
Copy pathstate.rs
File metadata and controls
2840 lines (2640 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! In-memory metadata storage for the coordinator.
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fmt::Debug;
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::Instant;
use ipnet::IpNet;
use itertools::Itertools;
use mz_adapter_types::compaction::CompactionWindow;
use mz_adapter_types::connection::ConnectionId;
use mz_audit_log::{EventDetails, EventType, ObjectType, VersionedEvent};
use mz_build_info::DUMMY_BUILD_INFO;
use mz_catalog::SYSTEM_CONN_ID;
use mz_catalog::builtin::{
BUILTINS, Builtin, BuiltinCluster, BuiltinLog, BuiltinSource, BuiltinTable, BuiltinType,
};
use mz_catalog::config::{AwsPrincipalContext, ClusterReplicaSizeMap};
use mz_catalog::expr_cache::LocalExpressions;
use mz_catalog::memory::error::{Error, ErrorKind};
use mz_catalog::memory::objects::{
CatalogCollectionEntry, CatalogEntry, CatalogItem, Cluster, ClusterReplica, CommentsMap,
Connection, DataSourceDesc, Database, DefaultPrivileges, Index, MaterializedView,
NetworkPolicy, Role, RoleAuth, Schema, Secret, Sink, Source, SourceReferences, Table,
TableDataSource, Type, View,
};
use mz_controller::clusters::{
ManagedReplicaAvailabilityZones, ManagedReplicaLocation, ReplicaAllocation, ReplicaLocation,
UnmanagedReplicaLocation,
};
use mz_controller_types::{ClusterId, ReplicaId};
use mz_expr::{CollectionPlan, OptimizedMirRelationExpr};
use mz_license_keys::ValidatedLicenseKey;
use mz_orchestrator::DiskLimit;
use mz_ore::collections::CollectionExt;
use mz_ore::now::NOW_ZERO;
use mz_ore::soft_assert_no_log;
use mz_ore::str::StrExt;
use mz_pgrepr::oid::INVALID_OID;
use mz_repr::adt::mz_acl_item::PrivilegeMap;
use mz_repr::namespaces::{
INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_CATALOG_UNSTABLE_SCHEMA, MZ_INTERNAL_SCHEMA,
MZ_INTROSPECTION_SCHEMA, MZ_TEMP_SCHEMA, MZ_UNSAFE_SCHEMA, PG_CATALOG_SCHEMA, SYSTEM_SCHEMAS,
UNSTABLE_SCHEMAS,
};
use mz_repr::network_policy_id::NetworkPolicyId;
use mz_repr::optimize::{OptimizerFeatures, OverrideFrom};
use mz_repr::role_id::RoleId;
use mz_repr::{
CatalogItemId, GlobalId, RelationDesc, RelationVersion, RelationVersionSelector,
VersionedRelationDesc,
};
use mz_secrets::InMemorySecretsController;
use mz_sql::ast::Ident;
use mz_sql::catalog::{
CatalogCluster, CatalogClusterReplica, CatalogDatabase, CatalogError as SqlCatalogError,
CatalogItem as SqlCatalogItem, CatalogItemType, CatalogRecordField, CatalogRole, CatalogSchema,
CatalogType, CatalogTypeDetails, IdReference, NameReference, SessionCatalog, SystemObjectType,
TypeReference,
};
use mz_sql::catalog::{CatalogConfig, EnvironmentId};
use mz_sql::names::{
CommentObjectId, DatabaseId, DependencyIds, FullItemName, FullSchemaName, ObjectId,
PartialItemName, QualifiedItemName, QualifiedSchemaName, RawDatabaseSpecifier,
ResolvedDatabaseSpecifier, ResolvedIds, SchemaId, SchemaSpecifier, SystemObjectId,
};
use mz_sql::plan::{
CreateConnectionPlan, CreateIndexPlan, CreateMaterializedViewPlan, CreateSecretPlan,
CreateSinkPlan, CreateSourcePlan, CreateTablePlan, CreateTypePlan, CreateViewPlan, Params,
Plan, PlanContext,
};
use mz_sql::rbac;
use mz_sql::session::metadata::SessionMetadata;
use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
use mz_sql::session::vars::{DEFAULT_DATABASE_NAME, SystemVars, Var, VarInput};
use mz_sql_parser::ast::QualifiedReplica;
use mz_storage_client::controller::StorageMetadata;
use mz_storage_types::connections::ConnectionContext;
use mz_storage_types::connections::inline::{
ConnectionResolver, InlinedConnection, IntoInlineConnection,
};
use mz_transform::notice::OptimizerNotice;
use serde::Serialize;
use timely::progress::Antichain;
use tokio::sync::mpsc;
use tracing::{debug, warn};
// DO NOT add any more imports from `crate` outside of `crate::catalog`.
use crate::AdapterError;
use crate::catalog::{Catalog, ConnCatalog};
use crate::coord::{ConnMeta, infer_sql_type_for_catalog};
use crate::optimize::{self, Optimize, OptimizerCatalog};
use crate::session::Session;
/// The in-memory representation of the Catalog. This struct is not directly used to persist
/// metadata to persistent storage. For persistent metadata see
/// [`mz_catalog::durable::DurableCatalogState`].
///
/// [`Serialize`] is implemented to create human readable dumps of the in-memory state, not for
/// storing the contents of this struct on disk.
#[derive(Debug, Clone, Serialize)]
pub struct CatalogState {
// State derived from the durable catalog. These fields should only be mutated in `open.rs` or
// `apply.rs`. Some of these fields are not 100% derived from the durable catalog. Those
// include:
// - Temporary items.
// - Certain objects are partially derived from read-only state.
pub(super) database_by_name: imbl::OrdMap<String, DatabaseId>,
#[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
pub(super) database_by_id: imbl::OrdMap<DatabaseId, Database>,
#[serde(serialize_with = "skip_temp_items")]
pub(super) entry_by_id: imbl::OrdMap<CatalogItemId, CatalogEntry>,
#[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
pub(super) entry_by_global_id: imbl::OrdMap<GlobalId, CatalogItemId>,
pub(super) ambient_schemas_by_name: imbl::OrdMap<String, SchemaId>,
#[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
pub(super) ambient_schemas_by_id: imbl::OrdMap<SchemaId, Schema>,
pub(super) clusters_by_name: imbl::OrdMap<String, ClusterId>,
#[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
pub(super) clusters_by_id: imbl::OrdMap<ClusterId, Cluster>,
pub(super) roles_by_name: imbl::OrdMap<String, RoleId>,
#[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
pub(super) roles_by_id: imbl::OrdMap<RoleId, Role>,
pub(super) network_policies_by_name: imbl::OrdMap<String, NetworkPolicyId>,
#[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
pub(super) network_policies_by_id: imbl::OrdMap<NetworkPolicyId, NetworkPolicy>,
#[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
pub(super) role_auth_by_id: imbl::OrdMap<RoleId, RoleAuth>,
#[serde(skip)]
pub(super) system_configuration: Arc<SystemVars>,
pub(super) default_privileges: Arc<DefaultPrivileges>,
pub(super) system_privileges: Arc<PrivilegeMap>,
pub(super) comments: Arc<CommentsMap>,
#[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
pub(super) source_references: imbl::OrdMap<CatalogItemId, SourceReferences>,
pub(super) storage_metadata: Arc<StorageMetadata>,
pub(super) mock_authentication_nonce: Option<String>,
// Mutable state not derived from the durable catalog. Populated
// during dataflow bootstrapping (`bootstrap_dataflow_plans`), which
// doesn't run in Testdrive's read-only consistency check, so this
// must be `#[serde(skip)]`.
#[serde(skip)]
pub(super) notices_by_dep_id: imbl::OrdMap<GlobalId, Vec<Arc<OptimizerNotice>>>,
// Populated by active connections creating temporary objects. The
// read-only catalog opened by Testdrive's consistency check has no
// active connections, so this must be `#[serde(skip)]`.
#[serde(skip)]
pub(super) temporary_schemas: imbl::OrdMap<ConnectionId, Schema>,
// Read-only state not derived from the durable catalog.
#[serde(skip)]
pub(super) config: mz_sql::catalog::CatalogConfig,
pub(super) cluster_replica_sizes: ClusterReplicaSizeMap,
#[serde(skip)]
pub(crate) availability_zones: Vec<String>,
// Read-only not derived from the durable catalog.
#[serde(skip)]
pub(super) egress_addresses: Vec<IpNet>,
pub(super) aws_principal_context: Option<AwsPrincipalContext>,
pub(super) aws_privatelink_availability_zones: Option<BTreeSet<String>>,
pub(super) http_host_name: Option<String>,
// Read-only not derived from the durable catalog.
#[serde(skip)]
pub(super) license_key: ValidatedLicenseKey,
}
/// Keeps track of what expressions are cached or not during startup.
/// It's also used during catalog transactions to avoid re-optimizing CREATE VIEW / CREATE MAT VIEW
/// statements when going back and forth between durable catalog operations and in-memory catalog
/// operations.
#[derive(Debug, Clone, Serialize)]
pub(crate) enum LocalExpressionCache {
/// The cache is being used.
Open {
/// The local expressions that were cached in the expression cache.
cached_exprs: BTreeMap<GlobalId, LocalExpressions>,
/// The local expressions that were NOT cached in the expression cache.
uncached_exprs: BTreeMap<GlobalId, LocalExpressions>,
},
/// The cache is not being used.
Closed,
}
impl LocalExpressionCache {
pub(super) fn new(cached_exprs: BTreeMap<GlobalId, LocalExpressions>) -> Self {
Self::Open {
cached_exprs,
uncached_exprs: BTreeMap::new(),
}
}
pub(super) fn remove_cached_expression(&mut self, id: &GlobalId) -> Option<LocalExpressions> {
match self {
LocalExpressionCache::Open { cached_exprs, .. } => cached_exprs.remove(id),
LocalExpressionCache::Closed => None,
}
}
/// Insert an expression that was cached, back into the cache. This is generally needed when
/// parsing/planning an expression fails, but we don't want to lose the cached expression.
pub(super) fn insert_cached_expression(
&mut self,
id: GlobalId,
local_expressions: LocalExpressions,
) {
match self {
LocalExpressionCache::Open { cached_exprs, .. } => {
cached_exprs.insert(id, local_expressions);
}
LocalExpressionCache::Closed => {}
}
}
/// Inform the cache that `id` was not found in the cache and that we should add it as
/// `local_mir` and `optimizer_features`.
pub(super) fn insert_uncached_expression(
&mut self,
id: GlobalId,
local_mir: OptimizedMirRelationExpr,
optimizer_features: OptimizerFeatures,
) {
match self {
LocalExpressionCache::Open { uncached_exprs, .. } => {
let local_expr = LocalExpressions {
local_mir,
optimizer_features,
};
// If we are trying to cache the same item a second time, with a different
// expression, then we must be migrating the object or doing something else weird.
// Caching the unmigrated expression may cause us to incorrectly use the unmigrated
// version after a restart. Caching the migrated version may cause us to incorrectly
// think that the object has already been migrated. To simplify things, we cache
// neither.
let prev = uncached_exprs.remove(&id);
match prev {
Some(prev) if prev == local_expr => {
uncached_exprs.insert(id, local_expr);
}
None => {
uncached_exprs.insert(id, local_expr);
}
Some(_) => {}
}
}
LocalExpressionCache::Closed => {}
}
}
pub(super) fn into_uncached_exprs(self) -> BTreeMap<GlobalId, LocalExpressions> {
match self {
LocalExpressionCache::Open { uncached_exprs, .. } => uncached_exprs,
LocalExpressionCache::Closed => BTreeMap::new(),
}
}
}
fn skip_temp_items<S>(
entries: &imbl::OrdMap<CatalogItemId, CatalogEntry>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
mz_ore::serde::map_key_to_string(
entries.iter().filter(|(_k, v)| v.conn_id().is_none()),
serializer,
)
}
impl CatalogState {
/// Returns an empty [`CatalogState`] that can be used in tests.
// TODO: Ideally we'd mark this as `#[cfg(test)]`, but that doesn't work with the way
// tests are structured in this repository.
pub fn empty_test() -> Self {
CatalogState {
database_by_name: Default::default(),
database_by_id: Default::default(),
entry_by_id: Default::default(),
entry_by_global_id: Default::default(),
notices_by_dep_id: Default::default(),
ambient_schemas_by_name: Default::default(),
ambient_schemas_by_id: Default::default(),
temporary_schemas: Default::default(),
clusters_by_id: Default::default(),
clusters_by_name: Default::default(),
network_policies_by_name: Default::default(),
roles_by_name: Default::default(),
roles_by_id: Default::default(),
network_policies_by_id: Default::default(),
role_auth_by_id: Default::default(),
config: CatalogConfig {
start_time: Default::default(),
start_instant: Instant::now(),
nonce: Default::default(),
environment_id: EnvironmentId::for_tests(),
session_id: Default::default(),
build_info: &DUMMY_BUILD_INFO,
now: NOW_ZERO.clone(),
connection_context: ConnectionContext::for_tests(Arc::new(
InMemorySecretsController::new(),
)),
helm_chart_version: None,
},
cluster_replica_sizes: ClusterReplicaSizeMap::for_tests(),
availability_zones: Default::default(),
system_configuration: Arc::new(SystemVars::default()),
egress_addresses: Default::default(),
aws_principal_context: Default::default(),
aws_privatelink_availability_zones: Default::default(),
http_host_name: Default::default(),
default_privileges: Arc::new(DefaultPrivileges::default()),
system_privileges: Arc::new(PrivilegeMap::default()),
comments: Arc::new(CommentsMap::default()),
source_references: Default::default(),
storage_metadata: Arc::new(StorageMetadata::default()),
license_key: ValidatedLicenseKey::for_tests(),
mock_authentication_nonce: Default::default(),
}
}
pub fn for_session<'a>(&'a self, session: &'a Session) -> ConnCatalog<'a> {
let search_path = self.resolve_search_path(session);
let database = self
.database_by_name
.get(session.vars().database())
.map(|id| id.clone());
let state = match session.transaction().catalog_state() {
Some(txn_catalog_state) => Cow::Borrowed(txn_catalog_state),
None => Cow::Borrowed(self),
};
ConnCatalog {
state,
unresolvable_ids: BTreeSet::new(),
conn_id: session.conn_id().clone(),
cluster: session.vars().cluster().into(),
database,
search_path,
role_id: session.current_role_id().clone(),
prepared_statements: Some(session.prepared_statements()),
portals: Some(session.portals()),
notices_tx: session.retain_notice_transmitter(),
restrict_to_user_objects: session.vars().restrict_to_user_objects(),
}
}
pub fn for_sessionless_user(&self, role_id: RoleId) -> ConnCatalog<'_> {
let (notices_tx, _notices_rx) = mpsc::unbounded_channel();
let cluster = self.system_configuration.default_cluster();
ConnCatalog {
state: Cow::Borrowed(self),
unresolvable_ids: BTreeSet::new(),
conn_id: SYSTEM_CONN_ID.clone(),
cluster,
database: self
.resolve_database(DEFAULT_DATABASE_NAME)
.ok()
.map(|db| db.id()),
// Leaving the system's search path empty allows us to catch issues
// where catalog object names have not been normalized correctly.
search_path: Vec::new(),
role_id,
prepared_statements: None,
portals: None,
notices_tx,
restrict_to_user_objects: false,
}
}
pub fn for_system_session(&self) -> ConnCatalog<'_> {
self.for_sessionless_user(MZ_SYSTEM_ROLE_ID)
}
/// Returns an iterator over the deduplicated identifiers of all
/// objects this catalog entry transitively depends on (where
/// "depends on" is meant in the sense of [`CatalogItem::uses`], rather than
/// [`CatalogItem::references`]).
pub fn transitive_uses(&self, id: CatalogItemId) -> impl Iterator<Item = CatalogItemId> + '_ {
struct I<'a> {
queue: VecDeque<CatalogItemId>,
seen: BTreeSet<CatalogItemId>,
this: &'a CatalogState,
}
impl<'a> Iterator for I<'a> {
type Item = CatalogItemId;
fn next(&mut self) -> Option<Self::Item> {
if let Some(next) = self.queue.pop_front() {
for child in self.this.get_entry(&next).item().uses() {
if !self.seen.contains(&child) {
self.queue.push_back(child);
self.seen.insert(child);
}
}
Some(next)
} else {
None
}
}
}
I {
queue: [id].into_iter().collect(),
seen: [id].into_iter().collect(),
this: self,
}
}
/// Computes the IDs of any log sources this catalog entry transitively
/// depends on.
pub fn introspection_dependencies(&self, id: CatalogItemId) -> Vec<CatalogItemId> {
let mut out = Vec::new();
self.introspection_dependencies_inner(id, &mut out);
out
}
fn introspection_dependencies_inner(&self, id: CatalogItemId, out: &mut Vec<CatalogItemId>) {
match self.get_entry(&id).item() {
CatalogItem::Log(_) => out.push(id),
item @ (CatalogItem::View(_)
| CatalogItem::MaterializedView(_)
| CatalogItem::Connection(_)) => {
// TODO(jkosh44) Unclear if this table wants to include all uses or only references.
for item_id in item.references().items() {
self.introspection_dependencies_inner(*item_id, out);
}
}
CatalogItem::Sink(sink) => {
let from_item_id = self.get_entry_by_global_id(&sink.from).id();
self.introspection_dependencies_inner(from_item_id, out)
}
CatalogItem::Index(idx) => {
let on_item_id = self.get_entry_by_global_id(&idx.on).id();
self.introspection_dependencies_inner(on_item_id, out)
}
CatalogItem::Table(_)
| CatalogItem::Source(_)
| CatalogItem::Type(_)
| CatalogItem::Func(_)
| CatalogItem::Secret(_) => (),
}
}
/// Returns all the IDs of all objects that depend on `ids`, including `ids` themselves.
///
/// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
/// earlier in the list than the roots. This is particularly useful for the order to drop
/// objects.
pub(super) fn object_dependents(
&self,
object_ids: &Vec<ObjectId>,
conn_id: &ConnectionId,
seen: &mut BTreeSet<ObjectId>,
) -> Vec<ObjectId> {
let mut dependents = Vec::new();
for object_id in object_ids {
match object_id {
ObjectId::Cluster(id) => {
dependents.extend_from_slice(&self.cluster_dependents(*id, seen));
}
ObjectId::ClusterReplica((cluster_id, replica_id)) => dependents.extend_from_slice(
&self.cluster_replica_dependents(*cluster_id, *replica_id, seen),
),
ObjectId::Database(id) => {
dependents.extend_from_slice(&self.database_dependents(*id, conn_id, seen))
}
ObjectId::Schema((database_spec, schema_spec)) => {
dependents.extend_from_slice(&self.schema_dependents(
database_spec.clone(),
schema_spec.clone(),
conn_id,
seen,
));
}
ObjectId::NetworkPolicy(id) => {
dependents.extend_from_slice(&self.network_policy_dependents(*id, seen));
}
id @ ObjectId::Role(_) => {
let unseen = seen.insert(id.clone());
if unseen {
dependents.push(id.clone());
}
}
ObjectId::Item(id) => {
dependents.extend_from_slice(&self.item_dependents(*id, seen))
}
}
}
dependents
}
/// Returns all the IDs of all objects that depend on `cluster_id`, including `cluster_id`
/// itself.
///
/// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
/// earlier in the list than the roots. This is particularly useful for the order to drop
/// objects.
fn cluster_dependents(
&self,
cluster_id: ClusterId,
seen: &mut BTreeSet<ObjectId>,
) -> Vec<ObjectId> {
let mut dependents = Vec::new();
let object_id = ObjectId::Cluster(cluster_id);
if !seen.contains(&object_id) {
seen.insert(object_id.clone());
let cluster = self.get_cluster(cluster_id);
for item_id in cluster.bound_objects() {
dependents.extend_from_slice(&self.item_dependents(*item_id, seen));
}
for replica_id in cluster.replica_ids().values() {
dependents.extend_from_slice(&self.cluster_replica_dependents(
cluster_id,
*replica_id,
seen,
));
}
dependents.push(object_id);
}
dependents
}
/// Returns all the IDs of all objects that depend on `replica_id`, including `replica_id`
/// itself.
///
/// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
/// earlier in the list than the roots. This is particularly useful for the order to drop
/// objects.
pub(super) fn cluster_replica_dependents(
&self,
cluster_id: ClusterId,
replica_id: ReplicaId,
seen: &mut BTreeSet<ObjectId>,
) -> Vec<ObjectId> {
let mut dependents = Vec::new();
let object_id = ObjectId::ClusterReplica((cluster_id, replica_id));
if !seen.contains(&object_id) {
seen.insert(object_id.clone());
// Materialized views that target this replica are implicitly
// dropped with it, so cascade to their dependents to avoid leaving
// dangling references.
let cluster = self.get_cluster(cluster_id);
for item_id in cluster.bound_objects() {
if let CatalogItem::MaterializedView(mv) = self.get_entry(item_id).item()
&& mv.target_replica == Some(replica_id)
{
dependents.extend_from_slice(&self.item_dependents(*item_id, seen));
}
}
dependents.push(object_id);
}
dependents
}
/// Returns all the IDs of all objects that depend on `database_id`, including `database_id`
/// itself.
///
/// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
/// earlier in the list than the roots. This is particularly useful for the order to drop
/// objects.
fn database_dependents(
&self,
database_id: DatabaseId,
conn_id: &ConnectionId,
seen: &mut BTreeSet<ObjectId>,
) -> Vec<ObjectId> {
let mut dependents = Vec::new();
let object_id = ObjectId::Database(database_id);
if !seen.contains(&object_id) {
seen.insert(object_id.clone());
let database = self.get_database(&database_id);
for schema_id in database.schema_ids().values() {
dependents.extend_from_slice(&self.schema_dependents(
ResolvedDatabaseSpecifier::Id(database_id),
SchemaSpecifier::Id(*schema_id),
conn_id,
seen,
));
}
dependents.push(object_id);
}
dependents
}
/// Returns all the IDs of all objects that depend on `schema_id`, including `schema_id`
/// itself.
///
/// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
/// earlier in the list than the roots. This is particularly useful for the order to drop
/// objects.
fn schema_dependents(
&self,
database_spec: ResolvedDatabaseSpecifier,
schema_spec: SchemaSpecifier,
conn_id: &ConnectionId,
seen: &mut BTreeSet<ObjectId>,
) -> Vec<ObjectId> {
let mut dependents = Vec::new();
let object_id = ObjectId::Schema((database_spec, schema_spec.clone()));
if !seen.contains(&object_id) {
seen.insert(object_id.clone());
let schema = self.get_schema(&database_spec, &schema_spec, conn_id);
for item_id in schema.item_ids() {
dependents.extend_from_slice(&self.item_dependents(item_id, seen));
}
dependents.push(object_id)
}
dependents
}
/// Returns all the IDs of all objects that depend on `item_id`, including `item_id`
/// itself.
///
/// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
/// earlier in the list than the roots. This is particularly useful for the order to drop
/// objects.
pub(super) fn item_dependents(
&self,
item_id: CatalogItemId,
seen: &mut BTreeSet<ObjectId>,
) -> Vec<ObjectId> {
let mut dependents = Vec::new();
let object_id = ObjectId::Item(item_id);
if !seen.contains(&object_id) {
seen.insert(object_id.clone());
let entry = self.get_entry(&item_id);
for dependent_id in entry.used_by() {
dependents.extend_from_slice(&self.item_dependents(*dependent_id, seen));
}
dependents.push(object_id);
// We treat the progress collection as if it depends on the source
// for dropping. We have additional code in planning to create a
// kind of special-case "CASCADE" for this dependency.
if let Some(progress_id) = entry.progress_id() {
dependents.extend_from_slice(&self.item_dependents(progress_id, seen));
}
}
dependents
}
/// Returns all the IDs of all objects that depend on `network_policy_id`, including `network_policy_id`
/// itself.
///
/// The order is guaranteed to be in reverse dependency order, i.e. the leafs will appear
/// earlier in the list than the roots. This is particularly useful for the order to drop
/// objects.
pub(super) fn network_policy_dependents(
&self,
network_policy_id: NetworkPolicyId,
_seen: &mut BTreeSet<ObjectId>,
) -> Vec<ObjectId> {
let object_id = ObjectId::NetworkPolicy(network_policy_id);
// Currently network policies have no dependents
// when we add the ability for users or sources/sinks to have policies
// this method will need to be updated.
vec![object_id]
}
/// Indicates whether the indicated item is considered stable or not.
///
/// Only stable items can be used as dependencies of other catalog items.
fn is_stable(&self, id: CatalogItemId) -> bool {
let spec = self.get_entry(&id).name().qualifiers.schema_spec;
!self.is_unstable_schema_specifier(spec)
}
pub(super) fn check_unstable_dependencies(&self, item: &CatalogItem) -> Result<(), Error> {
if self.system_config().unsafe_enable_unstable_dependencies() {
return Ok(());
}
let unstable_dependencies: Vec<_> = item
.references()
.items()
.filter(|id| !self.is_stable(**id))
.map(|id| self.get_entry(id).name().item.clone())
.collect();
// It's okay to create a temporary object with unstable
// dependencies, since we will never need to reboot a catalog
// that contains it.
if unstable_dependencies.is_empty() || item.is_temporary() {
Ok(())
} else {
let object_type = item.typ().to_string();
Err(Error {
kind: ErrorKind::UnstableDependency {
object_type,
unstable_dependencies,
},
})
}
}
pub fn resolve_full_name(
&self,
name: &QualifiedItemName,
conn_id: Option<&ConnectionId>,
) -> FullItemName {
let conn_id = conn_id.unwrap_or(&SYSTEM_CONN_ID);
let database = match &name.qualifiers.database_spec {
ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
ResolvedDatabaseSpecifier::Id(id) => {
RawDatabaseSpecifier::Name(self.get_database(id).name().to_string())
}
};
// For temporary schemas, we know the name is always MZ_TEMP_SCHEMA,
// and the schema may not exist yet if no temporary items have been created.
let schema = match &name.qualifiers.schema_spec {
SchemaSpecifier::Temporary => MZ_TEMP_SCHEMA.to_string(),
SchemaSpecifier::Id(_) => self
.get_schema(
&name.qualifiers.database_spec,
&name.qualifiers.schema_spec,
conn_id,
)
.name()
.schema
.clone(),
};
FullItemName {
database,
schema,
item: name.item.clone(),
}
}
pub(super) fn resolve_full_schema_name(&self, name: &QualifiedSchemaName) -> FullSchemaName {
let database = match &name.database {
ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
ResolvedDatabaseSpecifier::Id(id) => {
RawDatabaseSpecifier::Name(self.get_database(id).name().to_string())
}
};
FullSchemaName {
database,
schema: name.schema.clone(),
}
}
pub fn get_entry(&self, id: &CatalogItemId) -> &CatalogEntry {
self.entry_by_id
.get(id)
.unwrap_or_else(|| panic!("catalog out of sync, missing id {id:?}"))
}
pub fn get_entry_by_global_id(&self, id: &GlobalId) -> CatalogCollectionEntry {
let item_id = self
.entry_by_global_id
.get(id)
.unwrap_or_else(|| panic!("catalog out of sync, missing id {id:?}"));
let entry = self.get_entry(item_id).clone();
let version = match entry.item() {
CatalogItem::Table(table) => {
let (version, _) = table
.collections
.iter()
.find(|(_verison, gid)| *gid == id)
.expect("version to exist");
RelationVersionSelector::Specific(*version)
}
_ => RelationVersionSelector::Latest,
};
CatalogCollectionEntry { entry, version }
}
pub fn get_entries(&self) -> impl Iterator<Item = (&CatalogItemId, &CatalogEntry)> + '_ {
self.entry_by_id.iter()
}
pub fn get_temp_items(&self, conn: &ConnectionId) -> impl Iterator<Item = ObjectId> + '_ {
// Temporary schemas are created lazily, so it's valid for one to not exist yet.
self.temporary_schemas
.get(conn)
.into_iter()
.flat_map(|schema| schema.items.values().copied().map(ObjectId::from))
}
/// Returns true if a temporary schema exists for the given connection.
///
/// Temporary schemas are created lazily when the first temporary object is created
/// for a connection, so this may return false for connections that haven't created
/// any temporary objects.
pub fn has_temporary_schema(&self, conn: &ConnectionId) -> bool {
self.temporary_schemas.contains_key(conn)
}
/// Gets a type named `name` from exactly one of the system schemas.
///
/// # Panics
/// - If `name` is not an entry in any system schema
/// - If more than one system schema has an entry named `name`.
pub(super) fn get_system_type(&self, name: &str) -> &CatalogEntry {
let mut res = None;
for schema_id in self.system_schema_ids() {
let schema = &self.ambient_schemas_by_id[&schema_id];
if let Some(global_id) = schema.types.get(name) {
match res {
None => res = Some(self.get_entry(global_id)),
Some(_) => panic!(
"only call get_system_type on objects uniquely identifiable in one system schema"
),
}
}
}
res.unwrap_or_else(|| panic!("cannot find type {} in system schema", name))
}
pub fn get_item_by_name(
&self,
name: &QualifiedItemName,
conn_id: &ConnectionId,
) -> Option<&CatalogEntry> {
self.get_schema(
&name.qualifiers.database_spec,
&name.qualifiers.schema_spec,
conn_id,
)
.items
.get(&name.item)
.and_then(|id| self.try_get_entry(id))
}
pub fn get_type_by_name(
&self,
name: &QualifiedItemName,
conn_id: &ConnectionId,
) -> Option<&CatalogEntry> {
self.get_schema(
&name.qualifiers.database_spec,
&name.qualifiers.schema_spec,
conn_id,
)
.types
.get(&name.item)
.and_then(|id| self.try_get_entry(id))
}
pub(super) fn find_available_name(
&self,
mut name: QualifiedItemName,
conn_id: &ConnectionId,
) -> QualifiedItemName {
let mut i = 0;
let orig_item_name = name.item.clone();
while self.get_item_by_name(&name, conn_id).is_some() {
i += 1;
name.item = format!("{}{}", orig_item_name, i);
}
name
}
pub fn try_get_entry(&self, id: &CatalogItemId) -> Option<&CatalogEntry> {
self.entry_by_id.get(id)
}
pub fn try_get_entry_by_global_id(&self, id: &GlobalId) -> Option<&CatalogEntry> {
let item_id = self.entry_by_global_id.get(id)?;
self.try_get_entry(item_id)
}
/// Returns the [`RelationDesc`] for a [`GlobalId`], if the provided [`GlobalId`] refers to an
/// object that returns rows.
pub fn try_get_desc_by_global_id(&self, id: &GlobalId) -> Option<Cow<'_, RelationDesc>> {
let entry = self.try_get_entry_by_global_id(id)?;
let desc = match entry.item() {
CatalogItem::Table(table) => Cow::Owned(table.desc_for(id)),
// TODO(alter_table): Support schema evolution on sources.
other => other.relation_desc(RelationVersionSelector::Latest)?,
};
Some(desc)
}
pub(crate) fn get_cluster(&self, cluster_id: ClusterId) -> &Cluster {
self.try_get_cluster(cluster_id)
.unwrap_or_else(|| panic!("unknown cluster {cluster_id}"))
}
pub(super) fn try_get_cluster(&self, cluster_id: ClusterId) -> Option<&Cluster> {
self.clusters_by_id.get(&cluster_id)
}
pub(super) fn try_get_role(&self, id: &RoleId) -> Option<&Role> {
self.roles_by_id.get(id)
}
pub fn get_role(&self, id: &RoleId) -> &Role {
self.roles_by_id.get(id).expect("catalog out of sync")
}
pub fn get_roles(&self) -> impl Iterator<Item = &RoleId> {
self.roles_by_id.keys()
}
pub(super) fn try_get_role_by_name(&self, role_name: &str) -> Option<&Role> {
self.roles_by_name
.get(role_name)
.map(|id| &self.roles_by_id[id])
}
pub(super) fn get_role_auth(&self, id: &RoleId) -> &RoleAuth {
self.role_auth_by_id
.get(id)
.unwrap_or_else(|| panic!("catalog out of sync, missing role auth for {id}"))
}
pub(super) fn try_get_role_auth_by_id(&self, id: &RoleId) -> Option<&RoleAuth> {
self.role_auth_by_id.get(id)
}
pub(super) fn try_get_network_policy_by_name(
&self,
policy_name: &str,
) -> Option<&NetworkPolicy> {
self.network_policies_by_name
.get(policy_name)
.map(|id| &self.network_policies_by_id[id])
}
pub(crate) fn collect_role_membership(&self, id: &RoleId) -> BTreeSet<RoleId> {
let mut membership = BTreeSet::new();
let mut queue = VecDeque::from(vec![id]);
while let Some(cur_id) = queue.pop_front() {
if !membership.contains(cur_id) {
membership.insert(cur_id.clone());
let role = self.get_role(cur_id);
soft_assert_no_log!(
!role.membership().keys().contains(id),
"circular membership exists in the catalog"
);
queue.extend(role.membership().keys());
}
}
membership.insert(RoleId::Public);
membership
}
pub fn get_network_policy(&self, id: &NetworkPolicyId) -> &NetworkPolicy {
self.network_policies_by_id
.get(id)
.expect("catalog out of sync")
}
pub fn get_network_policies(&self) -> impl Iterator<Item = &NetworkPolicyId> {
self.network_policies_by_id.keys()
}
/// Returns the URL for POST-ing data to a webhook source, if `id` corresponds to a webhook
/// source.
///
/// Note: Identifiers for the source, e.g. item name, are URL encoded.
pub fn try_get_webhook_url(&self, id: &CatalogItemId) -> Option<url::Url> {
let entry = self.try_get_entry(id)?;
// Note: Webhook sources can never be created in the temporary schema, hence passing None.
let name = self.resolve_full_name(entry.name(), None);
let host_name = self
.http_host_name
.as_ref()
.map(|x| x.as_str())
.unwrap_or_else(|| "HOST");
let RawDatabaseSpecifier::Name(database) = name.database else {
return None;
};
let mut url = url::Url::parse(&format!("https://{host_name}/api/webhook")).ok()?;
url.path_segments_mut()
.ok()?
.push(&database)
.push(&name.schema)
.push(&name.item);
Some(url)
}
/// Parses the given SQL string into a pair of [`Plan`] and a [`ResolvedIds`].
///
/// This function will temporarily enable all "enable_for_item_parsing" feature flags. See
/// [`CatalogState::with_enable_for_item_parsing`] for more details.
///
/// NOTE: While this method takes a `&mut self`, all mutations are temporary and restored to
/// their original state before the method returns.