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 { 2 } else { 2 + n * 2 + (n - 1) + total_chars };
208        let default_val = if self.def.is_empty() {
209            "".to_string()
210        } else {
211            self.def.join(",")
212        };
213        match model {
214            "sqlite" => {
215                format!(
216                    "{} varchar({}){} default '{}'",
217                    self.field, length, not_null, default_val
218                )
219            }
220            "pgsql" => {
221                let json_default = "[]";
222                let sql = format!(
223                    r#""{}" TEXT default '{}'"#,
224                    self.field, json_default
225                );
226                format!(
227                    "{} --{}|{}|{}|{}|{}|{}",
228                    sql,
229                    self.mode,
230                    self.require,
231                    self.title,
232                    self.length,
233                    self.def.join("|"),
234                    self.option.join("|")
235                )
236            }
237            _ => {
238                let json_default = if self.def.is_empty() {
239                    "('[]')".to_string()
240                } else {
241                    format!("('[\"{}\"]')", self.def.join("\",\""))
242                };
243                let sql = format!("`{}` json default {}", self.field, json_default);
244                format!(
245                    "{} comment '{}|{}|{}|{}|{}|{}'",
246                    sql,
247                    self.mode,
248                    self.require,
249                    self.title,
250                    self.length,
251                    self.def.join("|"),
252                    self.option.join("|")
253                )
254            }
255        }
256    }
257    fn hide(&mut self) -> &mut Self {
258        self.show = false;
259        self
260    }
261    fn describe(&mut self, text: &str) -> &mut Self {
262        self.describe = text.to_string();
263        self
264    }
265
266    fn field(&mut self) -> JsonValue {
267        let mut field = object! {};
268        field
269            .insert("require", JsonValue::from(self.require))
270            .unwrap();
271        field
272            .insert("field", JsonValue::from(self.field.clone()))
273            .unwrap();
274        field
275            .insert("mode", JsonValue::from(self.mode.clone()))
276            .unwrap();
277        field
278            .insert("title", JsonValue::from(self.title.clone()))
279            .unwrap();
280        field
281            .insert("length", JsonValue::from(self.length))
282            .unwrap();
283
284        field
285            .insert("def", JsonValue::from(self.def.clone()))
286            .unwrap();
287        field
288            .insert("option", JsonValue::from(self.option.clone()))
289            .unwrap();
290
291        field.insert("show", JsonValue::from(self.show)).unwrap();
292        field
293            .insert("describe", JsonValue::from(self.describe.clone()))
294            .unwrap();
295        field.insert("example", self.example.clone()).unwrap();
296        field
297    }
298
299    fn swagger(&mut self) -> JsonValue {
300        object! {
301            "type": self.mode.clone(),
302            "example": self.example.clone(),
303        }
304    }
305
306    fn example(&mut self, data: JsonValue) -> &mut Self {
307        self.example = data.clone();
308        self
309    }
310}