Skip to main content

br_fields/
datetime.rs

1use crate::Field;
2use chrono::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime};
3use json::{object, JsonValue};
4use std::time::{Duration, UNIX_EPOCH};
5
6pub struct Year {
7    pub require: bool,
8    pub field: String,
9    pub mode: String,
10    pub title: String,
11    pub def: String,
12    pub show: bool,
13    pub describe: String,
14    pub example: JsonValue,
15}
16
17impl Year {
18    pub fn new(require: bool, field: &str, title: &str, default: &str) -> Self {
19        Self {
20            field: field.to_string(),
21            mode: "year".to_string(),
22            title: title.to_string(),
23            def: default.to_string(),
24            require,
25            show: true,
26            describe: String::new(),
27            example: JsonValue::Null,
28        }
29    }
30    pub fn year() -> String {
31        let now: DateTime<Local> = Local::now();
32        let dft = now.format("%Y");
33        dft.to_string()
34    }
35    pub fn timestamp_to_year(timestamp: i64) -> String {
36        let d = UNIX_EPOCH + Duration::from_secs(timestamp as u64);
37        let datetime = DateTime::<Local>::from(d);
38        let timestamp_str = datetime.format("%Y").to_string();
39        timestamp_str
40    }
41}
42
43impl Field for Year {
44    fn sql(&mut self, model: &str) -> String {
45        let not_null = if self.require { " not null" } else { "" };
46        match model {
47            "sqlite" => format!(
48                "{} INTEGER{} default '{}'",
49                self.field, not_null, self.def
50            ),
51            "pgsql" => {
52                format!(
53                    r#""{}" SMALLINT{} default '{}'"#,
54                    self.field, not_null, self.def
55                )
56            }
57            _ => {
58                let sql = format!(
59                    "`{}` year{} default '{}'",
60                    self.field, not_null, self.def
61                );
62                format!(
63                    "{} comment '{}|{}|{}|{}'",
64                    sql.clone(),
65                    self.title,
66                    self.mode,
67                    self.require,
68                    self.def
69                )
70            }
71        }
72    }
73    fn hide(&mut self) -> &mut Self {
74        self.show = false;
75        self
76    }
77
78    fn describe(&mut self, text: &str) -> &mut Self {
79        self.describe = text.to_string();
80        self
81    }
82
83    fn field(&mut self) -> JsonValue {
84        let mut field = object! {};
85        field.insert("require", JsonValue::from(self.require)).unwrap();
86        field.insert("field", JsonValue::from(self.field.clone())).unwrap();
87        field.insert("mode", JsonValue::from(self.mode.clone())).unwrap();
88        field.insert("title", JsonValue::from(self.title.clone())).unwrap();
89        field.insert("def", JsonValue::from(self.def.clone())).unwrap();
90        field.insert("show", JsonValue::from(self.show)).unwrap();
91        field.insert("describe", JsonValue::from(self.describe.clone())).unwrap();
92        field.insert("example", self.example.clone()).unwrap();
93        field
94    }
95
96    fn swagger(&mut self) -> JsonValue {
97        object! {
98            "type": self.mode.clone(),
99            "example": self.example.clone(),
100        }
101    }
102    fn example(&mut self, data: JsonValue) -> &mut Self {
103        self.example = data.clone();
104        self
105    }
106}
107
108pub struct Datetime {
109    pub require: bool,
110    pub field: String,
111    pub mode: String,
112    pub title: String,
113    pub def: String,
114    pub show: bool,
115    pub describe: String,
116    pub example: JsonValue,
117}
118
119impl Datetime {
120    pub fn new(require: bool, field: &str, title: &str, mut default: &str) -> Self {
121        if default.is_empty() {
122            default = "0001-01-01 00:00:00";
123        }
124        Self {
125            field: field.to_string(),
126            mode: "datetime".to_string(),
127            title: title.to_string(),
128            def: default.to_string(),
129            require,
130            show: true,
131            describe: String::new(),
132            example: JsonValue::Null,
133        }
134    }
135    pub fn datetime() -> String {
136        let now: DateTime<Local> = Local::now();
137        let dft = now.format("%Y-%m-%d %H:%M:%S");
138        dft.to_string()
139    }
140    pub fn timestamp_to_datetime(timestamp: i64) -> String {
141        let d = UNIX_EPOCH + Duration::from_secs(timestamp as u64);
142        let datetime = DateTime::<Local>::from(d);
143        let timestamp_str = datetime.format("%Y-%m-%d %H:%M:%S").to_string();
144        timestamp_str
145    }
146    pub fn datetime_format(format: &str) -> String {
147        let now: DateTime<Local> = Local::now();
148        let dft = now.format(format);
149        dft.to_string()
150    }
151}
152
153impl Field for Datetime {
154    fn sql(&mut self, model: &str) -> String {
155        let not_null = if self.require { " not null" } else { "" };
156        match model {
157            "sqlite" => format!(
158                "{} datetime{} default '{}'",
159                self.field, not_null, self.def
160            ),
161            "pgsql" => {
162                format!(
163                    r#""{}" timestamp{} default '{}'"#,
164                    self.field, not_null, self.def
165                )
166            }
167            _ => {
168                let sql = format!(
169                    "`{}` datetime{} default '{}'",
170                    self.field, not_null, self.def
171                );
172                format!(
173                    "{} comment '{}|{}|{}|{}'",
174                    sql.clone(),
175                    self.title,
176                    self.mode,
177                    self.require,
178                    self.def
179                )
180            }
181        }
182    }
183    fn hide(&mut self) -> &mut Self {
184        self.show = false;
185        self
186    }
187    fn describe(&mut self, text: &str) -> &mut Self {
188        self.describe = text.to_string();
189        self
190    }
191
192    fn field(&mut self) -> JsonValue {
193        let mut field = object! {};
194        field.insert("require", JsonValue::from(self.require)).unwrap();
195        field.insert("field", JsonValue::from(self.field.clone())).unwrap();
196        field.insert("mode", JsonValue::from(self.mode.clone())).unwrap();
197        field.insert("title", JsonValue::from(self.title.clone())).unwrap();
198        field.insert("def", JsonValue::from(self.def.clone())).unwrap();
199
200        field.insert("show", JsonValue::from(self.show)).unwrap();
201        field.insert("describe", JsonValue::from(self.describe.clone())).unwrap();
202        field.insert("example", self.example.clone()).unwrap();
203        field
204    }
205
206    fn swagger(&mut self) -> JsonValue {
207        object! {
208            "type": self.mode.clone(),
209            "example": self.example.clone(),
210        }
211    }
212    fn example(&mut self, data: JsonValue) -> &mut Self {
213        self.example = data.clone();
214        self
215    }
216}
217#[derive(Debug, Clone)]
218pub struct Time {
219    pub require: bool,
220    pub field: String,
221    pub mode: String,
222    pub title: String,
223    pub def: String,
224    pub show: bool,
225    pub describe: String,
226    pub example: JsonValue,
227}
228
229impl Time {
230    pub fn new(require: bool, field: &str, title: &str, default: &str) -> Self {
231        Self {
232            field: field.to_string(),
233            mode: "time".to_string(),
234            title: title.to_string(),
235            def: default.to_string(),
236            require,
237            show: true,
238            describe: String::new(),
239            example: JsonValue::Null,
240        }
241    }
242    pub fn time() -> String {
243        let now: DateTime<Local> = Local::now();
244        let dft = now.format("%H:%M:%S");
245        dft.to_string()
246    }
247}
248
249impl Field for Time {
250    fn sql(&mut self, model: &str) -> String {
251        let not_null = if self.require { " not null" } else { "" };
252        match model {
253            "sqlite" => format!(
254                "{} time{} default '{}'",
255                self.field, not_null, self.def
256            ),
257            "pgsql" => {
258                format!(
259                    r#""{}" time{} default '{}'"#,
260                    self.field, not_null, self.def
261                )
262            }
263            _ => {
264                let sql = format!(
265                    "`{}` time{} default '{}'",
266                    self.field, not_null, self.def
267                );
268                format!(
269                    "{} comment '{}|{}|{}|{}'",
270                    sql.clone(),
271                    self.title,
272                    self.mode,
273                    self.require,
274                    self.def
275                )
276            }
277        }
278    }
279    fn hide(&mut self) -> &mut Self {
280        self.show = false;
281        self
282    }
283
284    fn describe(&mut self, text: &str) -> &mut Self {
285        self.describe = text.to_string();
286        self
287    }
288
289    fn field(&mut self) -> JsonValue {
290        let mut field = object! {};
291        field.insert("require", JsonValue::from(self.require)).unwrap();
292        field.insert("field", JsonValue::from(self.field.clone())).unwrap();
293        field.insert("mode", JsonValue::from(self.mode.clone())).unwrap();
294        field.insert("title", JsonValue::from(self.title.clone())).unwrap();
295        field.insert("def", JsonValue::from(self.def.clone())).unwrap();
296
297        field.insert("show", JsonValue::from(self.show)).unwrap();
298        field.insert("describe", JsonValue::from(self.describe.clone())).unwrap();
299        field.insert("example", self.example.clone()).unwrap();
300        field
301    }
302
303    fn swagger(&mut self) -> JsonValue {
304        object! {
305            "type": self.mode.clone(),
306            "example": self.example.clone(),
307        }
308    }
309    fn example(&mut self, data: JsonValue) -> &mut Self {
310        self.example = data.clone();
311        self
312    }
313}
314#[derive(Debug, Clone)]
315pub struct Date {
316    pub require: bool,
317    pub field: String,
318    pub mode: String,
319    pub title: String,
320    pub def: String,
321    pub show: bool,
322    pub describe: String,
323    pub example: JsonValue,
324}
325
326impl Date {
327    pub fn new(require: bool, field: &str, title: &str, default: &str) -> Self {
328        let def = {
329            if default.is_empty() {
330                "0001-01-01"
331            } else {
332                default
333            }
334        };
335        Self {
336            field: field.to_string(),
337            mode: "date".to_string(),
338            title: title.to_string(),
339            def: def.parse().unwrap(),
340            require,
341            show: true,
342            describe: "".to_string(),
343            example: JsonValue::Null,
344        }
345    }
346    /// 默认值 2023-01-01
347    pub fn date() -> String {
348        let now: DateTime<Local> = Local::now();
349        let dft = now.format("%Y-%m-%d");
350        dft.to_string()
351    }
352    pub fn timestamp_to_date(timestamp: i64) -> String {
353        let d = UNIX_EPOCH + Duration::from_secs(timestamp as u64);
354        let datetime = DateTime::<Local>::from(d);
355        let timestamp_str = datetime.format("%Y-%m-%d").to_string();
356        timestamp_str
357    }
358}
359
360impl Field for Date {
361    fn sql(&mut self, model: &str) -> String {
362        let not_null = if self.require { " not null" } else { "" };
363        match model {
364            "sqlite" => format!(
365                "{} date{} default '{}'",
366                self.field, not_null, self.def
367            ),
368            "pgsql" => {
369                format!(
370                    r#""{}" date{} default '{}'"#,
371                    self.field, not_null, self.def
372                )
373            }
374            _ => {
375                let sql = format!(
376                    "`{}` date{} default '{}'",
377                    self.field, not_null, self.def
378                );
379                format!(
380                    "{} comment '{}|{}|{}|{}'",
381                    sql.clone(),
382                    self.title,
383                    self.mode,
384                    self.require,
385                    self.def
386                )
387            }
388        }
389    }
390    fn hide(&mut self) -> &mut Self {
391        self.show = false;
392        self
393    }
394
395    fn describe(&mut self, text: &str) -> &mut Self {
396        self.describe = text.to_string();
397        self
398    }
399
400    fn field(&mut self) -> JsonValue {
401        let mut field = object! {};
402        field.insert("require", JsonValue::from(self.require)).unwrap();
403        field.insert("field", JsonValue::from(self.field.clone())).unwrap();
404        field.insert("mode", JsonValue::from(self.mode.clone())).unwrap();
405        field.insert("title", JsonValue::from(self.title.clone())).unwrap();
406        field.insert("def", JsonValue::from(self.def.clone())).unwrap();
407
408        field.insert("show", JsonValue::from(self.show)).unwrap();
409        field.insert("describe", JsonValue::from(self.describe.clone())).unwrap();
410        field.insert("example", self.example.clone()).unwrap();
411        field
412    }
413    fn swagger(&mut self) -> JsonValue {
414        object! {
415            "type": self.mode.clone(),
416            "example": self.example.clone(),
417        }
418    }
419    fn example(&mut self, data: JsonValue) -> &mut Self {
420        self.example = data.clone();
421        self
422    }
423}
424#[derive(Debug, Clone)]
425pub struct Timestamp {
426    pub require: bool,
427    pub field: String,
428    pub mode: String,
429    pub title: String,
430    pub def: f64,
431    pub dec: i32,
432    pub show: bool,
433    pub describe: String,
434    pub example: JsonValue,
435}
436
437impl Timestamp {
438    pub fn new(require: bool, field: &str, title: &str, dec: i32, default: f64) -> Self {
439        Self {
440            require,
441            field: field.to_string(),
442            mode: "timestamp".to_string(),
443            title: title.to_string(),
444            def: default,
445            dec,
446            show: true,
447            describe: "".to_string(),
448            example: JsonValue::Null,
449        }
450    }
451    /// 默认值 秒 10位
452    pub fn timestamp() -> i64 {
453        Local::now().timestamp()
454    }
455    /// 毫秒 13位
456    pub fn timestamp_ms() -> i64 {
457        Local::now().timestamp_millis()
458    }
459    /// 毫秒 10位+3位
460    pub fn timestamp_ms_f64() -> f64 {
461        Local::now().timestamp_millis() as f64 / 1000.0
462    }
463    /// 微秒 16位
464    pub fn timestamp_μs() -> i64 {
465        Local::now().timestamp_micros()
466    }
467    /// 微秒 16位
468    pub fn timestamp_μs_f64() -> f64 {
469        Local::now().timestamp_micros() as f64 / 1000.0 / 1000.0
470    }
471    /// 纳秒 19位
472    pub fn timestamp_ns() -> i64 {
473        Local::now().timestamp_nanos_opt().unwrap()
474    }
475
476    /// 日期转时间戳
477    pub fn date_to_timestamp(date: &str) -> i64 {
478        let t = NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap();
479        let tz = FixedOffset::east_opt(Local::now().offset().local_minus_utc()).unwrap();
480        t.and_hms_opt(0, 0, 0).unwrap().and_local_timezone(tz).unwrap().timestamp()
481    }
482    /// 日期时间转rfc2822 Thu, 3 Jul 2014 17:43:58 +0000
483    pub fn datetime_to_rfc2822(datetime: &str) -> String {
484        let t = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S").unwrap();
485        let tz = FixedOffset::east_opt(Local::now().offset().local_minus_utc()).unwrap();
486        t.and_local_timezone(tz).unwrap().to_rfc2822()
487    }
488    pub fn datetime_utc_rfc2822(datetime: &str) -> String {
489        let t = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S").unwrap();
490        t.and_utc().to_rfc2822()
491    }
492    pub fn datetime_to_fmt(datetime: &str, fmt: &str) -> String {
493        let t = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S").unwrap();
494        let tz = FixedOffset::east_opt(Local::now().offset().local_minus_utc()).unwrap();
495        t.and_local_timezone(tz).unwrap().format(fmt).to_string()
496    }
497    pub fn datetime_to_timestamp(datetime: &str, fmt: &str) -> i64 {
498        let t = NaiveDateTime::parse_from_str(datetime, fmt).unwrap();
499        let tz = FixedOffset::east_opt(Local::now().offset().local_minus_utc()).unwrap();
500        t.and_local_timezone(tz).unwrap().timestamp()
501    }
502    pub fn datetime_timestamp(datetime: &str) -> i64 {
503        let t = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S").unwrap();
504        let tz = FixedOffset::east_opt(Local::now().offset().local_minus_utc()).unwrap();
505        t.and_local_timezone(tz).unwrap().timestamp()
506    }
507}
508
509impl Field for Timestamp {
510    fn sql(&mut self, model: &str) -> String {
511        let not_null = if self.require { " not null" } else { "" };
512        let max = 10 + self.dec;
513        match model {
514            "sqlite" => {
515                let def = format!("{0:.width$}", self.def, width = self.dec as usize).parse::<f64>().unwrap();
516                format!("{} REAL{} default {}", self.field, not_null, def)
517            }
518            "pgsql" => {
519                let def = format!("{0:.width$}", self.def, width = self.dec as usize);
520                let def_value = def.parse::<f64>().unwrap();
521                format!(
522                    r#""{}" decimal({},{}){} default {}"#,
523                    self.field, max, self.dec, not_null, def_value
524                )
525            }
526            _ => {
527                let def = format!("{0:.width$}", self.def, width = self.dec as usize);
528                let def_value = def.parse::<f64>().unwrap();
529                let sql = format!("`{}` decimal({},{}){} default {}", self.field, max, self.dec, not_null, def_value);
530                format!(
531                    "{} comment '{}|{}|{}|{}|{}'",
532                    sql.clone(),
533                    self.title,
534                    self.mode,
535                    self.require,
536                    self.dec,
537                    def_value
538                )
539            }
540        }
541    }
542    fn hide(&mut self) -> &mut Self {
543        self.show = false;
544        self
545    }
546
547    fn describe(&mut self, text: &str) -> &mut Self {
548        self.describe = text.to_string();
549        self
550    }
551
552    fn field(&mut self) -> JsonValue {
553        let mut field = object! {};
554        field.insert("require", JsonValue::from(self.require)).unwrap();
555        field.insert("field", JsonValue::from(self.field.clone())).unwrap();
556        field.insert("mode", JsonValue::from(self.mode.clone())).unwrap();
557        field.insert("title", JsonValue::from(self.title.clone())).unwrap();
558        field.insert("def", JsonValue::from(self.def)).unwrap();
559        field.insert("dec", JsonValue::from(self.dec)).unwrap();
560        field.insert("show", JsonValue::from(self.show)).unwrap();
561        field.insert("describe", JsonValue::from(self.describe.clone())).unwrap();
562        field.insert("example", self.example.clone()).unwrap();
563        field
564    }
565
566    fn swagger(&mut self) -> JsonValue {
567        object! {
568            "type": self.mode.clone(),
569            "example": self.example.clone(),
570        }
571    }
572
573    fn example(&mut self, data: JsonValue) -> &mut Self {
574        self.example = data.clone();
575        self
576    }
577}