Skip to main content

mz_adapter/catalog/
consistency.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Internal consistency checks that validate invariants of [`CatalogState`].
11//!
12//! Note: the implementation of consistency checks should favor simplicity over performance, to
13//! make it as easy as possible to understand what a given check is doing. The exception is the
14//! [`CheckedCreateSql`] cache in `check_items`, which skips re-parsing unchanged `create_sql`
15//! because the check runs after every catalog transaction in tests.
16
17use std::collections::BTreeMap;
18
19use mz_controller_types::{ClusterId, ReplicaId};
20use mz_ore::collections::HashSet;
21use mz_repr::role_id::RoleId;
22use mz_repr::{CatalogItemId, GlobalId};
23use mz_sql::catalog::{CatalogItem, DefaultPrivilegeObject};
24use mz_sql::names::{
25    CommentObjectId, DatabaseId, QualifiedItemName, ResolvedDatabaseSpecifier, SchemaId,
26    SchemaSpecifier,
27};
28use mz_sql_parser::ast::{self, Statement};
29use mz_sql_parser::parser::ParserStatementError;
30use serde::Serialize;
31
32// DO NOT add any more imports from `crate` outside of `crate::catalog`.
33use super::CatalogState;
34
35#[derive(Debug, Default, Clone, Serialize, PartialEq)]
36pub struct CatalogInconsistencies {
37    /// Inconsistencies found with internal fields, if any.
38    internal_fields: Vec<InternalFieldsInconsistency>,
39    /// Inconsistencies found with roles, if any.
40    roles: Vec<RoleInconsistency>,
41    /// Inconsistencies found with comments, if any.
42    comments: Vec<CommentInconsistency>,
43    /// Inconsistencies found with object dependencies, if any.
44    object_dependencies: Vec<ObjectDependencyInconsistency>,
45    /// Inconsistencies found with items in the catalog, if any.
46    items: Vec<ItemInconsistency>,
47}
48
49impl CatalogInconsistencies {
50    pub fn is_empty(&self) -> bool {
51        let CatalogInconsistencies {
52            internal_fields,
53            roles,
54            comments,
55            object_dependencies,
56            items,
57        } = self;
58        internal_fields.is_empty()
59            && roles.is_empty()
60            && comments.is_empty()
61            && object_dependencies.is_empty()
62            && items.is_empty()
63    }
64}
65
66/// For each item, the inputs of its last passing `check_create_sql`, in that function's argument
67/// order.
68pub(crate) type CheckedCreateSql = BTreeMap<CatalogItemId, [String; 4]>;
69
70impl CatalogState {
71    /// Checks the [`CatalogState`] to make sure we're internally consistent.
72    pub fn check_consistency(&self) -> Result<(), Box<CatalogInconsistencies>> {
73        self.check_consistency_with_cache(None)
74    }
75
76    pub(crate) fn check_consistency_with_cache(
77        &self,
78        checked_sql: Option<&mut CheckedCreateSql>,
79    ) -> Result<(), Box<CatalogInconsistencies>> {
80        let mut inconsistencies = CatalogInconsistencies::default();
81
82        if let Err(internal_fields) = self.check_internal_fields() {
83            inconsistencies.internal_fields = internal_fields;
84        }
85        if let Err(roles) = self.check_roles() {
86            inconsistencies.roles = roles;
87        }
88        if let Err(comments) = self.check_comments() {
89            inconsistencies.comments = comments;
90        }
91        if let Err(dependencies) = self.check_object_dependencies() {
92            inconsistencies.object_dependencies = dependencies;
93        }
94        if let Err(items) = self.check_items(checked_sql) {
95            inconsistencies.items = items;
96        }
97
98        if inconsistencies.is_empty() {
99            Ok(())
100        } else {
101            Err(Box::new(inconsistencies))
102        }
103    }
104
105    /// # Invariants:
106    ///
107    /// * Any fields within [`CatalogState`] that reference another field need to be kept in sync.
108    ///
109    /// TODO(parkmycar): Check the reverse direction for these collections, e.g. all of the
110    /// `DatabaseId`s in `database_by_id` also exist in `database_by_name`.
111    fn check_internal_fields(&self) -> Result<(), Vec<InternalFieldsInconsistency>> {
112        let mut inconsistencies = Vec::new();
113        for (name, id) in &self.database_by_name {
114            if !self.database_by_id.contains_key(id) {
115                inconsistencies.push(InternalFieldsInconsistency::Database(name.clone(), *id));
116            }
117        }
118        for (name, id) in &self.ambient_schemas_by_name {
119            if !self.ambient_schemas_by_id.contains_key(id) {
120                inconsistencies.push(InternalFieldsInconsistency::AmbientSchema(
121                    name.clone(),
122                    *id,
123                ));
124            }
125        }
126        for (name, id) in &self.clusters_by_name {
127            if !self.clusters_by_id.contains_key(id) {
128                inconsistencies.push(InternalFieldsInconsistency::Cluster(name.clone(), *id));
129            }
130        }
131        for (name, role_id) in &self.roles_by_name {
132            if !self.roles_by_id.contains_key(role_id) {
133                inconsistencies.push(InternalFieldsInconsistency::Role(name.clone(), *role_id))
134            }
135        }
136
137        for (source_id, _references) in &self.source_references {
138            if !self.entry_by_id.contains_key(source_id) {
139                inconsistencies.push(InternalFieldsInconsistency::SourceReferences(*source_id));
140            }
141        }
142
143        for (item_id, entry) in &self.entry_by_id {
144            let missing_gids: Vec<_> = entry
145                .global_ids()
146                .filter(|gid| !self.entry_by_global_id.contains_key(gid))
147                .collect();
148            if !missing_gids.is_empty() {
149                inconsistencies.push(InternalFieldsInconsistency::EntryMissingGlobalIds(
150                    *item_id,
151                    missing_gids,
152                ));
153            }
154        }
155        for (gid, item_id) in &self.entry_by_global_id {
156            if !self.entry_by_id.contains_key(item_id) {
157                inconsistencies.push(InternalFieldsInconsistency::GlobalIdsMissingEntry(
158                    *gid, *item_id,
159                ));
160            }
161        }
162
163        if inconsistencies.is_empty() {
164            Ok(())
165        } else {
166            Err(inconsistencies)
167        }
168    }
169
170    /// # Invariants:
171    ///
172    /// * All RoleIds referenced from other objects must exist.
173    ///
174    fn check_roles(&self) -> Result<(), Vec<RoleInconsistency>> {
175        let mut inconsistencies = Vec::new();
176        for (database_id, database) in &self.database_by_id {
177            if !self.roles_by_id.contains_key(&database.owner_id) {
178                inconsistencies.push(RoleInconsistency::Database(*database_id, database.owner_id));
179            }
180            for (schema_id, schema) in &database.schemas_by_id {
181                if !self.roles_by_id.contains_key(&schema.owner_id) {
182                    inconsistencies.push(RoleInconsistency::Schema(*schema_id, schema.owner_id));
183                }
184            }
185        }
186        for (item_id, entry) in &self.entry_by_id {
187            if !self.roles_by_id.contains_key(entry.owner_id()) {
188                inconsistencies.push(RoleInconsistency::Entry(*item_id, entry.owner_id().clone()));
189            }
190        }
191        for (cluster_id, cluster) in &self.clusters_by_id {
192            if !self.roles_by_id.contains_key(&cluster.owner_id) {
193                inconsistencies.push(RoleInconsistency::Cluster(*cluster_id, cluster.owner_id));
194            }
195            for replica in cluster.replicas() {
196                if !self.roles_by_id.contains_key(&replica.owner_id) {
197                    inconsistencies.push(RoleInconsistency::ClusterReplica(
198                        *cluster_id,
199                        replica.replica_id,
200                        cluster.owner_id,
201                    ));
202                }
203            }
204        }
205        for (role_id, _) in &self.role_auth_by_id {
206            if !self.roles_by_id.contains_key(role_id) {
207                inconsistencies.push(RoleInconsistency::RoleAuth(role_id.clone()));
208            }
209        }
210        for (default_priv, privileges) in self.default_privileges.iter() {
211            if !self.roles_by_id.contains_key(&default_priv.role_id) {
212                inconsistencies.push(RoleInconsistency::DefaultPrivilege(default_priv.clone()));
213            }
214            for acl_item in privileges {
215                if !self.roles_by_id.contains_key(&acl_item.grantee) {
216                    inconsistencies.push(RoleInconsistency::DefaultPrivilegeItem {
217                        grantor: default_priv.role_id,
218                        grantee: acl_item.grantee,
219                    });
220                }
221            }
222        }
223        for acl in self.system_privileges.all_values() {
224            let grantor = self.roles_by_id.get(&acl.grantor);
225            let grantee = self.roles_by_id.get(&acl.grantee);
226
227            let inconsistency = match (grantor, grantee) {
228                (None, None) => RoleInconsistency::SystemPrivilege {
229                    grantor: Some(acl.grantor),
230                    grantee: Some(acl.grantee),
231                },
232                (Some(_), None) => RoleInconsistency::SystemPrivilege {
233                    grantor: None,
234                    grantee: Some(acl.grantee),
235                },
236                (None, Some(_)) => RoleInconsistency::SystemPrivilege {
237                    grantor: Some(acl.grantor),
238                    grantee: None,
239                },
240                (Some(_), Some(_)) => continue,
241            };
242            inconsistencies.push(inconsistency);
243        }
244        for role in self.roles_by_id.values() {
245            for (parent_id, grantor_id) in &role.membership.map {
246                let parent = self.roles_by_id.get(parent_id);
247                let grantor = self.roles_by_id.get(grantor_id);
248                let inconsistency = match (parent, grantor) {
249                    (None, None) => RoleInconsistency::Membership {
250                        parent: Some(*parent_id),
251                        grantor: Some(*grantor_id),
252                    },
253                    (Some(_), None) => RoleInconsistency::Membership {
254                        parent: None,
255                        grantor: Some(*grantor_id),
256                    },
257                    (None, Some(_)) => RoleInconsistency::Membership {
258                        parent: Some(*parent_id),
259                        grantor: None,
260                    },
261                    (Some(_), Some(_)) => continue,
262                };
263                inconsistencies.push(inconsistency);
264            }
265        }
266
267        if inconsistencies.is_empty() {
268            Ok(())
269        } else {
270            Err(inconsistencies)
271        }
272    }
273
274    /// # Invariants:
275    ///
276    /// * Comments should only reference existing objects.
277    /// * A comment should only have a column position if it references a relation.
278    ///
279    fn check_comments(&self) -> Result<(), Vec<CommentInconsistency>> {
280        let mut comment_inconsistencies = Vec::new();
281        for (comment_object_id, col_pos, _comment) in self.comments.iter() {
282            match comment_object_id {
283                CommentObjectId::Table(item_id)
284                | CommentObjectId::View(item_id)
285                | CommentObjectId::MaterializedView(item_id)
286                | CommentObjectId::Source(item_id)
287                | CommentObjectId::Sink(item_id)
288                | CommentObjectId::MetricSink(item_id)
289                | CommentObjectId::Index(item_id)
290                | CommentObjectId::Func(item_id)
291                | CommentObjectId::Connection(item_id)
292                | CommentObjectId::Type(item_id)
293                | CommentObjectId::Secret(item_id) => {
294                    let entry = self.entry_by_id.get(&item_id);
295                    match entry {
296                        None => comment_inconsistencies
297                            .push(CommentInconsistency::Dangling(comment_object_id)),
298                        Some(entry) => {
299                            // TODO: Refactor this to use if-let chains, once they're stable.
300                            #[allow(clippy::unnecessary_unwrap)]
301                            if !entry.has_columns() && col_pos.is_some() {
302                                let col_pos = col_pos.expect("checked above");
303                                comment_inconsistencies.push(CommentInconsistency::NonRelation(
304                                    comment_object_id,
305                                    col_pos,
306                                ));
307                            }
308                        }
309                    }
310                }
311                CommentObjectId::NetworkPolicy(network_policy_id) => {
312                    if !self.network_policies_by_id.contains_key(&network_policy_id) {
313                        comment_inconsistencies
314                            .push(CommentInconsistency::Dangling(comment_object_id));
315                    }
316                }
317                CommentObjectId::QueryPolicy(id) => {
318                    if !self.query_policies_by_id.contains_key(&id) {
319                        comment_inconsistencies
320                            .push(CommentInconsistency::Dangling(comment_object_id));
321                    }
322                }
323
324                CommentObjectId::Role(role_id) => {
325                    if !self.roles_by_id.contains_key(&role_id) {
326                        comment_inconsistencies
327                            .push(CommentInconsistency::Dangling(comment_object_id));
328                    }
329                }
330                CommentObjectId::Database(database_id) => {
331                    if !self.database_by_id.contains_key(&database_id) {
332                        comment_inconsistencies
333                            .push(CommentInconsistency::Dangling(comment_object_id));
334                    }
335                }
336                CommentObjectId::Schema((database, schema)) => {
337                    match (database, schema) {
338                        (
339                            ResolvedDatabaseSpecifier::Id(database_id),
340                            SchemaSpecifier::Id(schema_id),
341                        ) => {
342                            let schema = self
343                                .database_by_id
344                                .get(&database_id)
345                                .and_then(|database| database.schemas_by_id.get(&schema_id));
346                            if schema.is_none() {
347                                comment_inconsistencies
348                                    .push(CommentInconsistency::Dangling(comment_object_id));
349                            }
350                        }
351                        (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Id(schema_id)) => {
352                            if !self.ambient_schemas_by_id.contains_key(&schema_id) {
353                                comment_inconsistencies
354                                    .push(CommentInconsistency::Dangling(comment_object_id));
355                            }
356                        }
357                        // Temporary schemas are in the ambient database.
358                        (ResolvedDatabaseSpecifier::Id(_id), SchemaSpecifier::Temporary) => (),
359                        // TODO: figure out how to check for consistency in this case.
360                        (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Temporary) => (),
361                    }
362                }
363                CommentObjectId::Cluster(cluster_id) => {
364                    if !self.clusters_by_id.contains_key(&cluster_id) {
365                        comment_inconsistencies
366                            .push(CommentInconsistency::Dangling(comment_object_id));
367                    }
368                }
369                CommentObjectId::ClusterReplica((cluster_id, replica_id)) => {
370                    let replica = self
371                        .clusters_by_id
372                        .get(&cluster_id)
373                        .and_then(|cluster| cluster.replica(replica_id));
374                    if replica.is_none() {
375                        comment_inconsistencies
376                            .push(CommentInconsistency::Dangling(comment_object_id));
377                    }
378                }
379            }
380        }
381
382        if comment_inconsistencies.is_empty() {
383            Ok(())
384        } else {
385            Err(comment_inconsistencies)
386        }
387    }
388
389    /// # Invariants:
390    ///
391    /// * All of the objects in the "uses" collection of a CatalogEntry, should contain said
392    ///   CatalogEntry in their own "used_by" collection.
393    /// * All of the objects in the "used_by" collection of a CatalogEntry, should contain said
394    ///   CatalogEntry in their own "uses" collection.
395    ///
396    fn check_object_dependencies(&self) -> Result<(), Vec<ObjectDependencyInconsistency>> {
397        let mut dependency_inconsistencies = vec![];
398
399        // Many views can depend on one table. Index its reverse edges once per check.
400        let mut references = HashSet::new();
401        let mut uses = HashSet::new();
402        for (&id, entry) in &self.entry_by_id {
403            for &dependent in entry.referenced_by() {
404                references.insert((id, dependent));
405            }
406            for &dependent in entry.used_by() {
407                uses.insert((id, dependent));
408            }
409        }
410
411        for (id, entry) in &self.entry_by_id {
412            for referenced_id in entry.references().items() {
413                let Some(referenced_entry) = self.entry_by_id.get(referenced_id) else {
414                    dependency_inconsistencies.push(ObjectDependencyInconsistency::MissingUses {
415                        object_a: *id,
416                        object_b: *referenced_id,
417                    });
418                    continue;
419                };
420                if !references.contains(&(*referenced_id, *id)) && referenced_entry.id() != *id {
421                    dependency_inconsistencies.push(
422                        ObjectDependencyInconsistency::InconsistentUsedBy {
423                            object_a: *id,
424                            object_b: *referenced_id,
425                        },
426                    );
427                }
428            }
429            for used_id in entry.uses() {
430                let Some(used_entry) = self.entry_by_id.get(&used_id) else {
431                    dependency_inconsistencies.push(ObjectDependencyInconsistency::MissingUses {
432                        object_a: *id,
433                        object_b: used_id,
434                    });
435                    continue;
436                };
437                if !uses.contains(&(used_id, *id)) && used_entry.id() != *id {
438                    dependency_inconsistencies.push(
439                        ObjectDependencyInconsistency::InconsistentUsedBy {
440                            object_a: *id,
441                            object_b: used_id,
442                        },
443                    );
444                }
445            }
446
447            for referenced_by in entry.referenced_by() {
448                let Some(referenced_by_entry) = self.entry_by_id.get(referenced_by) else {
449                    dependency_inconsistencies.push(ObjectDependencyInconsistency::MissingUsedBy {
450                        object_a: *id,
451                        object_b: *referenced_by,
452                    });
453                    continue;
454                };
455                if !referenced_by_entry.references().contains_item(id) {
456                    dependency_inconsistencies.push(
457                        ObjectDependencyInconsistency::InconsistentUses {
458                            object_a: *id,
459                            object_b: *referenced_by,
460                        },
461                    );
462                }
463            }
464            for used_by in entry.used_by() {
465                let Some(used_by_entry) = self.entry_by_id.get(used_by) else {
466                    dependency_inconsistencies.push(ObjectDependencyInconsistency::MissingUsedBy {
467                        object_a: *id,
468                        object_b: *used_by,
469                    });
470                    continue;
471                };
472                if !used_by_entry.uses().contains(id) {
473                    dependency_inconsistencies.push(
474                        ObjectDependencyInconsistency::InconsistentUses {
475                            object_a: *id,
476                            object_b: *used_by,
477                        },
478                    );
479                }
480            }
481        }
482
483        if dependency_inconsistencies.is_empty() {
484            Ok(())
485        } else {
486            Err(dependency_inconsistencies)
487        }
488    }
489
490    /// # Invariants
491    ///
492    /// * Every schema that exists in the `schemas_by_name` map, also exists in `schemas_by_id`.
493    /// * The name present in the `schemas_by_name` map matches the name in the associated `Schema`
494    ///   struct.
495    /// * All items that exist in a `Schema` struct, also exist in the `entries_by_id` map.
496    /// * Parsing the `create_sql` string from an `Entry` succeeds.
497    /// * The result of parsing the `create_sql` must return a single `Statement`.
498    /// * The names in the returned `Statement`, must match that of the parent struct.
499    /// * The item from the parsed `create_sql` must be fully qualified.
500    ///
501    fn check_items(
502        &self,
503        mut checked_sql: Option<&mut CheckedCreateSql>,
504    ) -> Result<(), Vec<ItemInconsistency>> {
505        if let Some(cache) = checked_sql.as_deref_mut() {
506            cache.retain(|id, _| self.entry_by_id.contains_key(id));
507        }
508        let mut item_inconsistencies = vec![];
509
510        for (db_id, db) in &self.database_by_id {
511            for (schema_name, schema_id) in &db.schemas_by_name {
512                // Make sure the schema themselves are consistent.
513                let Some(schema) = db.schemas_by_id.get(schema_id) else {
514                    item_inconsistencies.push(ItemInconsistency::MissingSchema {
515                        db_id: *db_id,
516                        schema_name: schema_name.clone(),
517                    });
518                    continue;
519                };
520                if schema_name != &schema.name.schema {
521                    item_inconsistencies.push(ItemInconsistency::KeyedName {
522                        db_schema_by_name: schema_name.clone(),
523                        struct_name: schema.name.schema.clone(),
524                    });
525                }
526
527                // Make sure the items in the schema are consistent. A schema
528                // holds items, types, and functions in separate maps, and the
529                // create_sql of all three must stay consistent, e.g. after a
530                // schema rename.
531                for (item_name, item_id) in schema
532                    .items
533                    .iter()
534                    .chain(schema.types.iter())
535                    .chain(schema.functions.iter())
536                {
537                    let Some(entry) = self.entry_by_id.get(item_id) else {
538                        item_inconsistencies.push(ItemInconsistency::NonExistentItem {
539                            db_id: *db_id,
540                            schema_id: schema.id,
541                            item_id: *item_id,
542                        });
543                        continue;
544                    };
545                    if item_name != &entry.name().item {
546                        item_inconsistencies.push(ItemInconsistency::ItemNameMismatch {
547                            item_id: *item_id,
548                            map_name: item_name.clone(),
549                            entry_name: entry.name().clone(),
550                        });
551                    }
552                    let inputs = [
553                        db.name.as_str(),
554                        &schema.name.schema,
555                        &entry.name().item,
556                        entry.create_sql(),
557                    ];
558                    if let Some(inconsistency) =
559                        check_create_sql_cached(checked_sql.as_deref_mut(), *item_id, inputs)
560                    {
561                        item_inconsistencies.push(inconsistency);
562                    }
563                }
564            }
565        }
566
567        if item_inconsistencies.is_empty() {
568            Ok(())
569        } else {
570            Err(item_inconsistencies)
571        }
572    }
573}
574
575/// [`check_create_sql`], skipped when `cache` holds the same `inputs` for `id` from an earlier
576/// check that passed. Records `inputs` for `id` when the check passes.
577fn check_create_sql_cached(
578    cache: Option<&mut CheckedCreateSql>,
579    id: CatalogItemId,
580    inputs: [&str; 4],
581) -> Option<ItemInconsistency> {
582    let Some(cache) = cache else {
583        return check_create_sql(inputs);
584    };
585    if cache.get(&id).is_some_and(|previous| previous == &inputs) {
586        return None;
587    }
588    let inconsistency = check_create_sql(inputs);
589    if inconsistency.is_none() {
590        cache.insert(id, inputs.map(str::to_owned));
591    }
592    inconsistency
593}
594
595/// Checks that `create_sql` parses to a single statement and, for the statement kinds matched
596/// below, that its name is fully qualified and matches the given names.
597fn check_create_sql(
598    [db_name, schema_name, item_name, create_sql]: [&str; 4],
599) -> Option<ItemInconsistency> {
600    let statement = match mz_sql::parse::parse(create_sql) {
601        Ok(mut statements) if statements.len() == 1 => {
602            statements.pop().expect("checked length").ast
603        }
604        Ok(_) => {
605            return Some(ItemInconsistency::MultiCreateStatement {
606                create_sql: create_sql.to_string(),
607            });
608        }
609        Err(e) => {
610            return Some(ItemInconsistency::StatementParseFailure {
611                create_sql: create_sql.to_string(),
612                e,
613            });
614        }
615    };
616    match statement {
617        Statement::CreateConnection(ast::CreateConnectionStatement { name, .. })
618        | Statement::CreateWebhookSource(ast::CreateWebhookSourceStatement { name, .. })
619        | Statement::CreateSource(ast::CreateSourceStatement { name, .. })
620        | Statement::CreateSubsource(ast::CreateSubsourceStatement { name, .. })
621        | Statement::CreateSink(ast::CreateSinkStatement {
622            name: Some(name), ..
623        })
624        | Statement::CreateView(ast::CreateViewStatement {
625            definition: ast::ViewDefinition { name, .. },
626            ..
627        })
628        | Statement::CreateMaterializedView(ast::CreateMaterializedViewStatement {
629            name, ..
630        })
631        | Statement::CreateTable(ast::CreateTableStatement { name, .. })
632        | Statement::CreateType(ast::CreateTypeStatement { name, .. })
633        | Statement::CreateSecret(ast::CreateSecretStatement { name, .. }) => {
634            let [db_component, schema_component, item_component] = &name.0[..] else {
635                let name = name.0.into_iter().map(|ident| ident.to_string()).collect();
636                return Some(ItemInconsistency::NonFullyQualifiedItemName {
637                    create_sql: create_sql.to_string(),
638                    name,
639                });
640            };
641            if db_component.as_str() != db_name
642                || schema_component.as_str() != schema_name
643                || item_component.as_str() != item_name
644            {
645                return Some(ItemInconsistency::CreateSqlItemNameMismatch {
646                    item_name: vec![
647                        db_name.to_string(),
648                        schema_name.to_string(),
649                        item_name.to_string(),
650                    ],
651                    create_sql: create_sql.to_string(),
652                });
653            }
654        }
655        Statement::CreateSchema(ast::CreateSchemaStatement { name, .. }) => {
656            let [db_component, schema_component] = &name.0[..] else {
657                let name = name.0.into_iter().map(|ident| ident.to_string()).collect();
658                return Some(ItemInconsistency::NonFullyQualifiedSchemaName {
659                    create_sql: create_sql.to_string(),
660                    name,
661                });
662            };
663            if db_component.as_str() != db_name || schema_component.as_str() != schema_name {
664                return Some(ItemInconsistency::CreateSqlSchemaNameMismatch {
665                    schema_name: vec![db_name.to_string(), schema_name.to_string()],
666                    create_sql: create_sql.to_string(),
667                });
668            }
669        }
670        Statement::CreateDatabase(ast::CreateDatabaseStatement { name, .. }) => {
671            if db_name != name.0.as_str() {
672                return Some(ItemInconsistency::CreateSqlDatabaseNameMismatch {
673                    database_name: db_name.to_string(),
674                    create_sql: create_sql.to_string(),
675                });
676            }
677        }
678        _ => (),
679    }
680    None
681}
682
683#[derive(Debug, Serialize, Clone, PartialEq)]
684enum InternalFieldsInconsistency {
685    Database(String, DatabaseId),
686    AmbientSchema(String, SchemaId),
687    Cluster(String, ClusterId),
688    Role(String, RoleId),
689    SourceReferences(CatalogItemId),
690    EntryMissingGlobalIds(CatalogItemId, Vec<GlobalId>),
691    GlobalIdsMissingEntry(GlobalId, CatalogItemId),
692}
693
694#[derive(Debug, Serialize, Clone, PartialEq)]
695enum RoleInconsistency {
696    Database(DatabaseId, RoleId),
697    Schema(SchemaId, RoleId),
698    Entry(CatalogItemId, RoleId),
699    Cluster(ClusterId, RoleId),
700    ClusterReplica(ClusterId, ReplicaId, RoleId),
701    DefaultPrivilege(DefaultPrivilegeObject),
702    RoleAuth(RoleId),
703    DefaultPrivilegeItem {
704        grantor: RoleId,
705        grantee: RoleId,
706    },
707    SystemPrivilege {
708        grantor: Option<RoleId>,
709        grantee: Option<RoleId>,
710    },
711    Membership {
712        parent: Option<RoleId>,
713        grantor: Option<RoleId>,
714    },
715}
716
717#[derive(Debug, Serialize, Clone, PartialEq)]
718enum CommentInconsistency {
719    /// A comment was found for an object that no longer exists.
720    Dangling(CommentObjectId),
721    /// A comment with a column position was found on a non-relation.
722    NonRelation(CommentObjectId, usize),
723}
724
725#[derive(Debug, Serialize, Clone, PartialEq)]
726enum ObjectDependencyInconsistency {
727    /// Object A uses Object B, but Object B does not exist.
728    MissingUses {
729        object_a: CatalogItemId,
730        object_b: CatalogItemId,
731    },
732    /// Object A is used by Object B, but Object B does not exist.
733    MissingUsedBy {
734        object_a: CatalogItemId,
735        object_b: CatalogItemId,
736    },
737    /// Object A uses Object B, but Object B does not record that it is used by Object A.
738    InconsistentUsedBy {
739        object_a: CatalogItemId,
740        object_b: CatalogItemId,
741    },
742    /// Object B is used by Object A, but Object B does not record that is uses Object A.
743    InconsistentUses {
744        object_a: CatalogItemId,
745        object_b: CatalogItemId,
746    },
747}
748
749#[derive(Debug, Serialize, Clone, PartialEq)]
750enum ItemInconsistency {
751    /// The name in a `Database` `schemas_by_name` does not match the name on the `Schema` struct.
752    KeyedName {
753        db_schema_by_name: String,
754        struct_name: String,
755    },
756    /// A schema present in a `Database` `schemas_by_name` map is not in the `schema_by_id` map.
757    MissingSchema {
758        db_id: DatabaseId,
759        schema_name: String,
760    },
761    /// An item in a `Schema` `items` collection does not exist.
762    NonExistentItem {
763        db_id: DatabaseId,
764        schema_id: SchemaSpecifier,
765        item_id: CatalogItemId,
766    },
767    /// An item in the `Schema` `items` collection has a mismatched name.
768    ItemNameMismatch {
769        item_id: CatalogItemId,
770        /// Name from the `items` map.
771        map_name: String,
772        /// Name on the entry itself.
773        entry_name: QualifiedItemName,
774    },
775    /// Failed to parse the `create_sql` persisted with an item.
776    StatementParseFailure {
777        create_sql: String,
778        e: ParserStatementError,
779    },
780    /// Parsing the `create_sql` returned multiple Statements.
781    MultiCreateStatement { create_sql: String },
782    /// The name from a parsed `create_sql` statement, is not fully qualified.
783    NonFullyQualifiedItemName {
784        create_sql: String,
785        name: Vec<String>,
786    },
787    /// The name from a parsed `create_sql` statement, is not fully qualified.
788    NonFullyQualifiedSchemaName {
789        create_sql: String,
790        name: Vec<String>,
791    },
792    /// The name from a parsed `create_sql` statement, did not match that from the parent item.
793    CreateSqlItemNameMismatch {
794        item_name: Vec<String>,
795        create_sql: String,
796    },
797    /// The name from a parsed `create_sql` statement, did not match that from the parent schema.
798    CreateSqlSchemaNameMismatch {
799        schema_name: Vec<String>,
800        create_sql: String,
801    },
802    /// The name from a parsed `create_sql` statement, did not match that from the parent database.
803    CreateSqlDatabaseNameMismatch {
804        database_name: String,
805        create_sql: String,
806    },
807}
808
809#[cfg(test)]
810mod tests {
811    use super::*;
812
813    const VIEW: &str = "CREATE VIEW materialize.public.v AS SELECT 1";
814
815    #[mz_ore::test]
816    fn create_sql_must_parse_to_one_statement_with_matching_names() {
817        assert_eq!(check_create_sql(["materialize", "public", "v", VIEW]), None);
818        assert!(matches!(
819            check_create_sql(["materialize", "public", "w", VIEW]),
820            Some(ItemInconsistency::CreateSqlItemNameMismatch { .. })
821        ));
822        assert!(matches!(
823            check_create_sql(["materialize", "public", "v", "CREATE VIEW v AS SELECT 1"]),
824            Some(ItemInconsistency::NonFullyQualifiedItemName { .. })
825        ));
826        assert!(matches!(
827            check_create_sql(["materialize", "public", "v", "SELECT 1; SELECT 2"]),
828            Some(ItemInconsistency::MultiCreateStatement { .. })
829        ));
830        assert!(matches!(
831            check_create_sql(["materialize", "public", "v", "CREATE VIEW"]),
832            Some(ItemInconsistency::StatementParseFailure { .. })
833        ));
834    }
835
836    #[mz_ore::test]
837    fn create_sql_cache_skips_only_unchanged_inputs_that_passed() {
838        let id = CatalogItemId::User(1);
839        let mut cache = CheckedCreateSql::new();
840        assert_eq!(
841            check_create_sql_cached(Some(&mut cache), id, ["materialize", "public", "v", VIEW]),
842            None
843        );
844        // A rename that did not rewrite `create_sql`.
845        let renamed = ["materialize", "public", "w", VIEW];
846        for _ in 0..2 {
847            assert!(
848                check_create_sql_cached(Some(&mut cache), id, renamed).is_some(),
849                "a changed name must be re-checked, and a failing check must not be cached",
850            );
851        }
852    }
853}