Skip to main content

schema_model/builder/
key.rs

1use crate::model::key::{Key, KeyColumn};
2use crate::model::types::KeyType;
3
4/// KeyBuilder collects column names and attributes, producing a model::Key.
5#[derive(Debug)]
6pub struct KeyBuilder {
7    key_type: KeyType,
8    columns: Vec<KeyColumn>,
9    cluster: bool,
10    compress: bool,
11    unique: bool,
12    include: Option<String>,
13    filter: Option<String>,
14}
15
16impl KeyBuilder {
17    pub fn new(key_type: KeyType) -> Self {
18        Self {
19            key_type,
20            columns: Vec::new(),
21            cluster: false,
22            compress: false,
23            unique: false,
24            include: None,
25            filter: None,
26        }
27    }
28    pub fn add_column<S: Into<String>>(mut self, name: S) -> Self {
29        self.columns.push(KeyColumn::new(name));
30        self
31    }
32    pub fn cluster(mut self, v: bool) -> Self {
33        self.cluster = v;
34        self
35    }
36    pub fn compress(mut self, v: bool) -> Self {
37        self.compress = v;
38        self
39    }
40    pub fn unique(mut self, v: bool) -> Self {
41        self.unique = v;
42        self
43    }
44    pub fn include<S: Into<String>>(mut self, s: S) -> Self {
45        self.include = Some(s.into());
46        self
47    }
48    pub fn filter<S: Into<String>>(mut self, s: S) -> Self {
49        self.filter = Some(s.into());
50        self
51    }
52
53    pub fn build(self) -> Key {
54        if self.filter.is_some() {
55            Key::new_full_with_filter(
56                self.key_type,
57                self.columns,
58                self.cluster,
59                self.compress,
60                self.unique,
61                self.include,
62                self.filter,
63            )
64        } else if self.cluster || self.compress || self.unique || self.include.is_some() {
65            Key::new_full(
66                self.key_type,
67                self.columns,
68                self.cluster,
69                self.compress,
70                self.unique,
71                self.include,
72            )
73        } else {
74            Key::new(self.key_type, self.columns)
75        }
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn build_index_with_include() {
85        let k = KeyBuilder::new(KeyType::Index)
86            .add_column("a")
87            .add_column("b")
88            .compress(true)
89            .include("x")
90            .build();
91        assert_eq!(k.columns().len(), 2);
92        assert!(k.is_compress());
93        assert_eq!(k.include(), Some("x"));
94    }
95
96    #[test]
97    fn build_index_with_filter() {
98        let k = KeyBuilder::new(KeyType::Index)
99            .add_column("a")
100            .unique(true)
101            .filter("a is not null")
102            .build();
103        assert!(k.is_unique());
104        assert_eq!(k.filter(), Some("a is not null"));
105    }
106}