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
// 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.

use std::collections::BTreeMap;

use mz_ore::cast::CastFrom;
use mz_repr::explain::{DummyHumanizer, ExprHumanizer};
use mz_repr::{GlobalId, RelationType, ScalarType};

/// A catalog that holds types of objects previously created for the unit test.
///
/// This is for the purpose of allowing `MirRelationExpr`s to refer to them
/// later.
#[derive(Debug, Default)]
pub struct TestCatalog {
    objects: BTreeMap<String, (GlobalId, Vec<String>, RelationType)>,
    names: BTreeMap<GlobalId, String>,
}

impl<'a> TestCatalog {
    /// Registers an object in the catalog.
    ///
    /// Specifying `transient` as true allows the object to be deleted by
    /// [Self::remove_transient_objects].
    ///
    /// Returns the GlobalId assigned by the catalog to the object.
    ///
    /// Errors if an object of the same name is already in the catalog.
    pub fn insert(
        &mut self,
        name: &str,
        cols: Vec<String>,
        typ: RelationType,
        transient: bool,
    ) -> Result<GlobalId, String> {
        if self.objects.contains_key(name) {
            return Err(format!("Object {name} already exists in catalog"));
        }
        let id = if transient {
            GlobalId::Transient(u64::cast_from(self.objects.len()))
        } else {
            GlobalId::User(u64::cast_from(self.objects.len()))
        };
        self.objects.insert(name.to_string(), (id, cols, typ));
        self.names.insert(id, name.to_string());
        Ok(id)
    }

    pub fn get(&'a self, name: &str) -> Option<&'a (GlobalId, Vec<String>, RelationType)> {
        self.objects.get(name)
    }

    /// Looks up the name of the object referred to as `id`.
    pub fn get_source_name(&'a self, id: &GlobalId) -> Option<&'a String> {
        self.names.get(id)
    }

    /// Clears all transient objects from the catalog.
    pub fn remove_transient_objects(&mut self) {
        self.objects
            .retain(|_, (id, _, _)| !matches!(id, GlobalId::Transient(_)));
        self.names
            .retain(|k, _| !matches!(k, GlobalId::Transient(_)));
    }
}

impl ExprHumanizer for TestCatalog {
    fn humanize_id(&self, id: GlobalId) -> Option<String> {
        self.names.get(&id).map(|s| s.to_string())
    }

    fn humanize_id_unqualified(&self, id: GlobalId) -> Option<String> {
        self.names.get(&id).map(|s| s.to_string())
    }

    fn humanize_id_parts(&self, id: GlobalId) -> Option<Vec<String>> {
        self.humanize_id_unqualified(id).map(|name| vec![name])
    }

    fn humanize_scalar_type(&self, ty: &ScalarType) -> String {
        DummyHumanizer.humanize_scalar_type(ty)
    }

    fn column_names_for_id(&self, id: GlobalId) -> Option<Vec<String>> {
        let src_name = self.get_source_name(&id)?;
        self.objects.get(src_name).map(|(_, cols, _)| cols.clone())
    }

    fn humanize_column(&self, id: GlobalId, column: usize) -> Option<String> {
        let src_name = self.get_source_name(&id)?;
        self.objects
            .get(src_name)
            .map(|(_, cols, _)| cols[column].clone())
    }

    fn id_exists(&self, id: GlobalId) -> bool {
        self.names.contains_key(&id)
    }
}