cipherstash_config/
dataset.rs

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
use crate::{errors::ConfigError, list::UniqueList, TableConfig};
use serde::{Deserialize, Serialize};

/// Struct to manage the config for a given database.
/// At connection time, the Driver will retrieve config from Vitur
/// for the currently connected database
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatasetConfig {
    pub tables: UniqueList<TableConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatasetConfigWithIndexRootKey {
    /// The "root key" used for deriving ORE and bloom filter keys used in indexes
    pub index_root_key: [u8; 32],
    #[serde(flatten)]
    pub config: DatasetConfig,
}

impl DatasetConfig {
    pub fn init() -> Self {
        Self {
            tables: Default::default(),
        }
    }

    pub fn add_table(mut self, config: TableConfig) -> Result<Self, ConfigError> {
        self.tables.try_insert(config)?;

        Ok(self)
    }

    /// Returns true if a table matches the given query
    pub fn has_table<Q>(&self, query: &Q) -> bool
    where
        TableConfig: PartialEq<Q>,
    {
        self.get_table(query).is_some()
    }

    /// Finds a table that matches `query`
    pub fn get_table<Q>(&self, query: &Q) -> Option<&TableConfig>
    where
        TableConfig: PartialEq<Q>,
    {
        self.tables.get(query)
    }

    /// Sorts all indexes by type for each field in each table. Indexes are sorted in place.
    ///
    /// This is useful for ensuring that iteration over indexes always occurs in order
    /// by type (instead of the order that they appear in a config file or the order of
    /// `ColumnConfig::add_index` calls).
    pub fn sort_indexes_by_type(mut self) -> Self {
        self.tables
            .iter_mut()
            .for_each(TableConfig::sort_indexes_by_type);

        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use indoc::indoc;
    use std::error::Error;
    use toml::to_string_pretty;

    use crate::*;

    #[test]
    fn add_and_get_table() -> Result<(), Box<dyn Error>> {
        let config = DatasetConfig::init().add_table(TableConfig::new("users")?)?;

        assert!(matches!(
            config.get_table(&"users"),
            Some(TableConfig { path, .. }) if path.as_string() == "users"
        ));

        Ok(())
    }

    #[test]
    fn add_and_get_table_with_schema() -> Result<(), Box<dyn Error>> {
        let config = DatasetConfig::init().add_table(TableConfig::new("public.users")?)?;

        assert!(matches!(
            config.get_table(&"users"),
            Some(TableConfig { path, .. }) if path.as_string() == "public.users"
        ));

        Ok(())
    }

    #[test]
    fn test_serialise_to_toml_single_table() -> Result<(), Box<dyn Error>> {
        let config = DatasetConfig::init().add_table(TableConfig::new("test")?)?;

        assert_eq!(
            to_string_pretty(&config)?,
            indoc! { r#"
                [[tables]]
                path = "test"
                fields = []
            "#}
        );

        Ok(())
    }

    #[test]
    fn test_serialise_to_toml_multiple_table() -> Result<(), Box<dyn Error>> {
        let config = DatasetConfig::init()
            .add_table(TableConfig::new("test")?)?
            .add_table(
                TableConfig::new("another")?.add_column(
                    ColumnConfig::build("great-column")
                        .add_index(column::Index::new_ore())
                        .add_index(column::Index::new_match()),
                )?,
            )?;

        assert_eq!(
            to_string_pretty(&config)?,
            indoc! { r#"
                [[tables]]
                path = "test"
                fields = []

                [[tables]]
                path = "another"

                [[tables.fields]]
                name = "great-column"
                in_place = false
                cast_type = "utf8-str"
                mode = "encrypted-duplicate"

                [[tables.fields.indexes]]
                version = 1
                kind = "ore"

                [[tables.fields.indexes]]
                version = 1
                kind = "match"
                k = 6
                m = 2048
                include_original = true

                [tables.fields.indexes.tokenizer]
                kind = "ngram"
                token_length = 3

                [[tables.fields.indexes.token_filters]]
                kind = "downcase"
            "#}
        );

        Ok(())
    }

    #[test]
    fn test_sort_indexes() -> Result<(), Box<dyn Error>> {
        let config = DatasetConfig::init()
            .add_table(
                TableConfig::new("users")?.add_column(
                    ColumnConfig::build("name")
                        .add_index(column::Index::new_ore())
                        .add_index(column::Index::new_unique())
                        .add_index(column::Index::new_match()),
                )?,
            )?
            .sort_indexes_by_type();

        let index_types = &config.tables[0].fields[0]
            .indexes
            .iter()
            .map(|index| index.as_str())
            .collect::<Vec<_>>();

        assert_eq!(index_types, &vec!["match", "ore", "unique"]);

        Ok(())
    }
}