Skip to main content

br_fields/
select.rs

1use crate::Field;
2use json::{object, JsonValue};
3
4pub struct Radio {
5    pub require: bool,
6    pub field: String,
7    pub mode: String,
8    pub title: String,
9    pub def: String,
10    pub option: Vec<String>,
11    pub length: i32,
12    pub show: bool,
13    pub describe: String,
14    pub example: JsonValue,
15    table_name: String,
16}
17
18impl Radio {
19    pub fn new(
20        require: bool,
21        field: &str,
22        title: &str,
23        mut option: Vec<&str>,
24        default: &str,
25    ) -> Self {
26        if !require && default.is_empty() && !option.contains(&"") {
27            option.push("")
28        }
29        Self {
30            require,
31            field: field.to_string(),
32            mode: "radio".to_string(),
33            title: title.to_string(),
34            def: default.to_string(),
35            option: option.iter().map(|c| c.to_string()).collect(),
36            length: 0,
37            show: true,
38            describe: "".to_string(),
39            example: JsonValue::Null,
40            table_name: "".to_string(),
41        }
42    }
43    pub fn table_name(&mut self, table_name: &str) -> &mut Self {
44        self.table_name = table_name.to_string();
45        self
46    }
47}
48
49impl Field for Radio {
50    fn sql(&mut self, model: &str) -> String {
51        let not_null = if self.require { " not null" } else { "" };
52        let length = self.option.iter().map(|o| o.len()).max().unwrap_or(1);
53        match model {
54            "sqlite" => {
55                format!(
56                    "`{}` varchar({}){} default '{}'",
57                    self.field, length, not_null, self.def
58                )
59            }
60            "pgsql" => {
61                let sql = format!(
62                    r#""{}" varchar({}) default '{}'"#,
63                    self.field, length, self.def
64                );
65                format!(
66                    "{} --{}|{}|{}|{}|{}|{}",
67                    sql,
68                    self.mode,
69                    self.require,
70                    self.title,
71                    self.length,
72                    self.def,
73                    self.option.join("|")
74                )
75            }
76            _ => {
77                let sql = format!(
78                    "`{}` set('{}'){} default '{}'",
79                    self.field,
80                    self.option.join("','"),
81                    not_null,
82                    self.def
83                );
84                format!(
85                    "{} comment '{}|{}|{}|{}|{}|{}'",
86                    sql,
87                    self.mode,
88                    self.require,
89                    self.title,
90                    self.length,
91                    self.def,
92                    self.option.join("|")
93                )
94            }
95        }
96    }
97    fn hide(&mut self) -> &mut Self {
98        self.show = false;
99        self
100    }
101    fn describe(&mut self, text: &str) -> &mut Self {
102        self.describe = text.to_string();
103        self
104    }
105    fn field(&mut self) -> JsonValue {
106        let mut field = object! {};
107        field
108            .insert("require", JsonValue::from(self.require))
109            .unwrap();
110        field
111            .insert("field", JsonValue::from(self.field.clone()))
112            .unwrap();
113        field
114            .insert("mode", JsonValue::from(self.mode.clone()))
115            .unwrap();
116        field
117            .insert("title", JsonValue::from(self.title.clone()))
118            .unwrap();
119        field
120            .insert("length", JsonValue::from(self.length))
121            .unwrap();
122        field
123            .insert("def", JsonValue::from(self.def.clone()))
124            .unwrap();
125
126        field
127            .insert("option", JsonValue::from(self.option.clone()))
128            .unwrap();
129
130        field.insert("show", JsonValue::from(self.show)).unwrap();
131        field
132            .insert("describe", JsonValue::from(self.describe.clone()))
133            .unwrap();
134        field.insert("example", self.example.clone()).unwrap();
135        field
136    }
137
138    fn swagger(&mut self) -> JsonValue {
139        self.mode = match self.mode.as_str() {
140            "radio" => "string",
141            _ => self.mode.as_str(),
142        }
143        .to_string();
144        object! {
145            "type": self.mode.clone(),
146            "example": self.example.clone(),
147        }
148    }
149
150    fn example(&mut self, data: JsonValue) -> &mut Self {
151        self.example = data.clone();
152        self
153    }
154}
155
156pub struct Select {
157    pub require: bool,
158    pub field: String,
159    pub mode: String,
160    pub title: String,
161    pub option: Vec<String>,
162    pub def: Vec<String>,
163    pub length: i32,
164    pub show: bool,
165    pub describe: String,
166    pub example: JsonValue,
167    pub table_name: String,
168}
169
170impl Select {
171    pub fn new(
172        require: bool,
173        field: &str,
174        title: &str,
175        mut option: Vec<&str>,
176        default: Vec<&str>,
177    ) -> Self {
178        if !require && default.is_empty() && !option.contains(&"") {
179            option.push("")
180        }
181        Self {
182            require,
183            field: field.to_string(),
184            mode: "select".to_string(),
185            title: title.to_string(),
186            def: default.iter().map(|c| c.to_string()).collect(),
187            option: option.iter().map(|c| c.to_string()).collect(),
188            length: 0,
189            show: true,
190            describe: "".to_string(),
191            example: JsonValue::Null,
192            table_name: String::new(),
193        }
194    }
195    pub fn table_name(&mut self, table_name: &str) -> &mut Self {
196        self.table_name = table_name.to_string();
197        self
198    }
199}
200
201impl Field for Select {
202    fn sql(&mut self, model: &str) -> String {
203        let not_null = if self.require { " not null" } else { "" };
204        // JSON array format: ["opt1","opt2",...] = 2 (brackets) + N*2 (quotes) + (N-1) (commas) + total_chars
205        let n = self.option.len();
206        let total_chars: usize = self.option.iter().map(|o| o.len()).sum();
207        let length = if n == 0 {
208            2
209        } else {
210            2 + n * 2 + (n - 1) + total_chars
211        };
212        let default_val = if self.def.is_empty() {
213            "".to_string()
214        } else {
215            self.def.join(",")
216        };
217        match model {
218            "sqlite" => {
219                format!(
220                    "{} varchar({}){} default '{}'",
221                    self.field, length, not_null, default_val
222                )
223            }
224            "pgsql" => {
225                let json_default = "[]";
226                let sql = format!(r#""{}" TEXT default '{}'"#, self.field, json_default);
227                format!(
228                    "{} --{}|{}|{}|{}|{}|{}",
229                    sql,
230                    self.mode,
231                    self.require,
232                    self.title,
233                    self.length,
234                    self.def.join("|"),
235                    self.option.join("|")
236                )
237            }
238            _ => {
239                let json_default = if self.def.is_empty() {
240                    "('[]')".to_string()
241                } else {
242                    format!("('[\"{}\"]')", self.def.join("\",\""))
243                };
244                let sql = format!("`{}` json default {}", self.field, json_default);
245                format!(
246                    "{} comment '{}|{}|{}|{}|{}|{}'",
247                    sql,
248                    self.mode,
249                    self.require,
250                    self.title,
251                    self.length,
252                    self.def.join("|"),
253                    self.option.join("|")
254                )
255            }
256        }
257    }
258    fn hide(&mut self) -> &mut Self {
259        self.show = false;
260        self
261    }
262    fn describe(&mut self, text: &str) -> &mut Self {
263        self.describe = text.to_string();
264        self
265    }
266
267    fn field(&mut self) -> JsonValue {
268        let mut field = object! {};
269        field
270            .insert("require", JsonValue::from(self.require))
271            .unwrap();
272        field
273            .insert("field", JsonValue::from(self.field.clone()))
274            .unwrap();
275        field
276            .insert("mode", JsonValue::from(self.mode.clone()))
277            .unwrap();
278        field
279            .insert("title", JsonValue::from(self.title.clone()))
280            .unwrap();
281        field
282            .insert("length", JsonValue::from(self.length))
283            .unwrap();
284
285        field
286            .insert("def", JsonValue::from(self.def.clone()))
287            .unwrap();
288        field
289            .insert("option", JsonValue::from(self.option.clone()))
290            .unwrap();
291
292        field.insert("show", JsonValue::from(self.show)).unwrap();
293        field
294            .insert("describe", JsonValue::from(self.describe.clone()))
295            .unwrap();
296        field.insert("example", self.example.clone()).unwrap();
297        field
298    }
299
300    fn swagger(&mut self) -> JsonValue {
301        object! {
302            "type": self.mode.clone(),
303            "example": self.example.clone(),
304        }
305    }
306
307    fn example(&mut self, data: JsonValue) -> &mut Self {
308        self.example = data.clone();
309        self
310    }
311}