schema_model/builder/
key.rs1use crate::model::key::{Key, KeyColumn};
2use crate::model::types::KeyType;
3
4#[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: key_type == KeyType::Unique,
25 include: None,
26 filter: None,
27 }
28 }
29 pub fn add_column<S: Into<String>>(mut self, name: S) -> Self {
30 self.columns.push(KeyColumn::new(name));
31 self
32 }
33 pub fn cluster(mut self, v: bool) -> Self {
34 self.cluster = v;
35 self
36 }
37 pub fn compress(mut self, v: bool) -> Self {
38 self.compress = v;
39 self
40 }
41 pub fn unique(mut self, v: bool) -> Self {
42 self.unique = v;
43 self
44 }
45 pub fn include<S: Into<String>>(mut self, s: S) -> Self {
46 self.include = Some(s.into());
47 self
48 }
49 pub fn filter<S: Into<String>>(mut self, s: S) -> Self {
50 self.filter = Some(s.into());
51 self
52 }
53
54 pub fn build(self) -> Key {
55 if self.filter.is_some() {
56 Key::new_full_with_filter(
57 self.key_type,
58 self.columns,
59 self.cluster,
60 self.compress,
61 self.unique,
62 self.include,
63 self.filter,
64 )
65 } else if self.cluster || self.compress || self.unique || self.include.is_some() {
66 Key::new_full(
67 self.key_type,
68 self.columns,
69 self.cluster,
70 self.compress,
71 self.unique,
72 self.include,
73 )
74 } else {
75 Key::new(self.key_type, self.columns)
76 }
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn build_index_with_include() {
86 let k = KeyBuilder::new(KeyType::Index)
87 .add_column("a")
88 .add_column("b")
89 .compress(true)
90 .include("x")
91 .build();
92 assert_eq!(k.columns().len(), 2);
93 assert!(k.is_compress());
94 assert_eq!(k.include(), Some("x"));
95 }
96
97 #[test]
98 fn unique_key_is_unique_without_calling_unique() {
99 let k = KeyBuilder::new(KeyType::Unique).add_column("a").build();
100 assert!(k.is_unique());
101 assert!(
102 !KeyBuilder::new(KeyType::Index)
103 .add_column("a")
104 .build()
105 .is_unique()
106 );
107 assert!(
108 !KeyBuilder::new(KeyType::Primary)
109 .add_column("a")
110 .build()
111 .is_unique()
112 );
113 }
114
115 #[test]
116 fn build_index_with_filter() {
117 let k = KeyBuilder::new(KeyType::Index)
118 .add_column("a")
119 .unique(true)
120 .filter("a is not null")
121 .build();
122 assert!(k.is_unique());
123 assert_eq!(k.filter(), Some("a is not null"));
124 }
125}