1use crate::Field;
2use json::{object, JsonValue};
3
4pub struct Float {
5 pub require: bool,
6 pub field: String,
7 pub mode: String,
8 pub title: String,
9 pub def: String,
10 pub length: i32,
11 pub dec: usize,
12 pub show: bool,
13 pub describe: String,
14 pub example: JsonValue,
15}
16
17impl Float {
18 pub fn new(
27 require: bool,
28 field: &str,
29 title: &str,
30 length: i32,
31 dec: usize,
32 default: f64,
33 ) -> Self {
34 let def = format!("{0:.width$}", default, width = dec);
35 Self {
36 require,
37 field: field.to_string(),
38 mode: "float".to_string(),
39 title: title.to_string(),
40 def,
41 length,
42 dec,
43 show: true,
44 describe: "".to_string(),
45 example: JsonValue::Null,
46 }
47 }
48}
49
50impl Field for Float {
51 fn sql(&mut self, model: &str) -> String {
52 let sql = format!(
53 "`{}` decimal({},{}) default {}",
54 self.field, self.length, self.dec, self.def
55 );
56 match model {
57 "sqlite" => sql,
58 "pgsql" => {
59 let sql = format!(
60 "{} decimal({},{}) default {}",
61 self.field, self.length, self.dec, self.def
62 );
63 format!(
64 "{} comment '{}|{}|{}|{}|{}|{}'",
65 sql.clone(),
66 self.title,
67 self.mode,
68 self.require,
69 self.length,
70 self.dec,
71 self.def
72 )
73 }
74 _ => {
75 let sql = format!(
76 "`{}` decimal({},{}) default {}",
77 self.field, self.length, self.dec, self.def
78 );
79 format!(
80 "{} comment '{}|{}|{}|{}|{}|{}'",
81 sql.clone(),
82 self.title,
83 self.mode,
84 self.require,
85 self.length,
86 self.dec,
87 self.def
88 )
89 }
90 }
91 }
92 fn hide(&mut self) -> &mut Self {
93 self.show = false;
94 self
95 }
96
97 fn describe(&mut self, text: &str) -> &mut Self {
98 self.describe = text.to_string();
99 self
100 }
101
102 fn field(&mut self) -> JsonValue {
103 let mut field = object! {};
104 field
105 .insert("require", JsonValue::from(self.require))
106 .unwrap();
107 field
108 .insert("field", JsonValue::from(self.field.clone()))
109 .unwrap();
110 field
111 .insert("mode", JsonValue::from(self.mode.clone()))
112 .unwrap();
113 field
114 .insert("title", JsonValue::from(self.title.clone()))
115 .unwrap();
116 field
117 .insert("length", JsonValue::from(self.length))
118 .unwrap();
119 field.insert("dec", JsonValue::from(self.dec)).unwrap();
120 field
121 .insert("def", JsonValue::from(self.def.clone()))
122 .unwrap();
123 field.insert("show", JsonValue::from(self.show)).unwrap();
124 field
125 .insert("describe", JsonValue::from(self.describe.clone()))
126 .unwrap();
127 field.insert("example", self.example.clone()).unwrap();
128 field
129 }
130
131 fn swagger(&mut self) -> JsonValue {
132 object! {
133 "type": self.mode.clone(),
134 "example": self.example.clone(),
135 }
136 }
137
138 fn example(&mut self, data: JsonValue) -> &mut Self {
139 self.example = data.clone();
140 self
141 }
142}