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}
14
15impl KeyBuilder {
16    pub fn new(key_type: KeyType) -> Self {
17        Self {
18            key_type,
19            columns: Vec::new(),
20            cluster: false,
21            compress: false,
22            unique: false,
23            include: None,
24        }
25    }
26    pub fn add_column<S: Into<String>>(mut self, name: S) -> Self {
27        self.columns.push(KeyColumn::new(name));
28        self
29    }
30    pub fn cluster(mut self, v: bool) -> Self {
31        self.cluster = v;
32        self
33    }
34    pub fn compress(mut self, v: bool) -> Self {
35        self.compress = v;
36        self
37    }
38    pub fn unique(mut self, v: bool) -> Self {
39        self.unique = v;
40        self
41    }
42    pub fn include<S: Into<String>>(mut self, s: S) -> Self {
43        self.include = Some(s.into());
44        self
45    }
46
47    pub fn build(self) -> Key {
48        if self.cluster || self.compress || self.unique || self.include.is_some() {
49            Key::new_full(
50                self.key_type,
51                self.columns,
52                self.cluster,
53                self.compress,
54                self.unique,
55                self.include,
56            )
57        } else {
58            Key::new(self.key_type, self.columns)
59        }
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn build_index_with_include() {
69        let k = KeyBuilder::new(KeyType::Index)
70            .add_column("a")
71            .add_column("b")
72            .compress(true)
73            .include("x")
74            .build();
75        assert_eq!(k.columns().len(), 2);
76        assert!(k.is_compress());
77        assert_eq!(k.include(), Some("x"));
78    }
79}