Skip to main content

bios_basic/helper/
db_helper.rs

1//! Database operations helper
2//!
3//! 数据库操作辅助操作
4use tardis::{
5    chrono::{DateTime, ParseError, Utc},
6    db::sea_orm,
7    log::warn,
8    serde_json,
9};
10
11use crate::enumeration::BasicQueryOpKind;
12
13/// Convert JSON value to SeaORM value.
14///
15/// When the JSON value is a string, you can specify whether to add % on both sides of the string through the ``like_by_str`` parameter.
16pub fn json_to_sea_orm_value(json_value: &serde_json::Value, like_kind: &BasicQueryOpKind) -> Option<Vec<sea_orm::Value>> {
17    match json_value {
18        serde_json::Value::Null => None,
19        serde_json::Value::Bool(val) => Some(vec![sea_orm::Value::from(*val)]),
20        serde_json::Value::Number(val) if val.is_i64() => Some(vec![sea_orm::Value::from(val.as_i64())]),
21        serde_json::Value::Number(val) if val.is_u64() => Some(vec![sea_orm::Value::from(val.as_u64())]),
22        serde_json::Value::Number(val) if val.is_f64() => Some(vec![sea_orm::Value::from(val.as_f64())]),
23        serde_json::Value::Object(_) => Some(vec![sea_orm::Value::from(json_value.clone())]),
24        serde_json::Value::String(val) => match str_to_datetime(val) {
25            Ok(val) => Some(vec![sea_orm::Value::from(val)]),
26            Err(_) => {
27                if like_kind == &BasicQueryOpKind::Like || like_kind == &BasicQueryOpKind::NotLike {
28                    Some(vec![sea_orm::Value::from(format!("%{val}%"))])
29                } else if like_kind == &BasicQueryOpKind::LLike || like_kind == &BasicQueryOpKind::NotLLike {
30                    Some(vec![sea_orm::Value::from(format!("%{val}"))])
31                } else if like_kind == &BasicQueryOpKind::RLike || like_kind == &BasicQueryOpKind::NotRLike {
32                    Some(vec![sea_orm::Value::from(format!("{val}%"))])
33                } else {
34                    Some(vec![sea_orm::Value::from(val)])
35                }
36            }
37        },
38        serde_json::Value::Array(val) => {
39            // If the array is empty, return None.
40            if val.is_empty() {
41                return None;
42            }
43            // Convert each element in the array to SeaORM value.
44            let vals = val.iter().map(|json| json_to_sea_orm_value(json, like_kind)).collect::<Vec<Option<Vec<sea_orm::Value>>>>();
45            if vals.iter().any(|v| v.is_none()) {
46                warn!("[Basic] json_to_sea_orm_value: json array conversion failed.");
47                return None;
48            }
49            let vals = vals.into_iter().flat_map(|v| v.expect("ignore").into_iter()).collect::<Vec<sea_orm::Value>>();
50            Some(vals)
51        }
52        _ => {
53            warn!("[Basic] json_to_sea_orm_value: json conversion failed.");
54            None
55        }
56    }
57}
58
59/// Convert string to ``DateTime<Utc>``
60pub fn str_to_datetime(input: &str) -> Result<DateTime<Utc>, ParseError> {
61    DateTime::parse_from_rfc3339(input).map(|dt| dt.with_timezone(&Utc))
62}