Skip to main content

mycommon_utils/database/
mod.rs

1use serde::de::{Error, Visitor};
2use std::fmt;
3use std::fmt::{Display, Formatter};
4use std::str::FromStr;
5use redis::{ErrorKind, FromRedisValue, RedisError, RedisResult, RedisWrite, ToRedisArgs,Value as RedisValue};
6use sea_orm::{DbErr, DeriveValueType, TryFromU64};
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9pub mod config;
10pub mod redis_util;
11pub mod database_util;
12pub mod common;
13
14
15// 自定义数据库组件,主要是解决网页前端解析19位数字精度问题
16// 自定义主键对外序列化是字符串,内部使用的i64类型
17#[derive(Clone, Debug, PartialEq, Eq, DeriveValueType, Copy, PartialOrd, Default)]
18pub struct BigIntPrimaryKey(pub i64);
19
20impl BigIntPrimaryKey {
21    pub fn new (inner: i64) ->Self{
22        BigIntPrimaryKey(inner)
23    }
24    pub fn inner (&self) ->i64{
25        self.0
26    }
27}
28
29impl Display for BigIntPrimaryKey {
30    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
31        write!(f, "{}", self.0)
32    }
33}
34
35impl TryFromU64 for BigIntPrimaryKey {
36    fn try_from_u64(n: u64) -> Result<Self, DbErr> {
37        Ok(Self::new(n as i64))
38    }
39}
40
41struct BigKeyVisitor;
42impl<'de> Visitor<'de> for BigKeyVisitor {
43    type Value = i64;
44
45    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
46        formatter.write_str("Parsing parameters failed")
47    }
48    fn visit_i8<E>(self, s: i8) -> Result<Self::Value, E>
49    where E: Error
50    {
51        Ok(s as i64)
52    }
53    fn visit_i16<E>(self, s: i16) -> Result<Self::Value, E>
54    where E: Error
55    {
56        Ok(s as i64)
57    }
58    fn visit_i32<E>(self, s: i32) -> Result<Self::Value, E>
59    where E: Error
60    {
61        Ok(s as i64)
62    }
63    fn visit_i64<E>(self, s: i64) -> Result<Self::Value, E>
64    where E: Error
65    {
66        Ok(s)
67    }
68    fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E> where E: Error {
69        Ok(v as i64)
70    }
71    fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E> where E: Error {
72        Ok(v as i64)
73    }
74    fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E> where E: Error {
75        Ok(v as i64)
76    }
77    fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E> where E: Error {
78        Ok(v as i64)
79    }
80    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: Error {
81        Ok(v as i64)
82    }
83    fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E> where E: Error {
84        Ok(v as i64)
85    }
86    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
87    where E: Error
88    {
89        i64::from_str(s).map_err(Error::custom)
90    }
91    fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: Error {
92        i64::from_str(v.as_str()).map_err(Error::custom)
93    }
94}
95
96impl<'de> Deserialize<'de> for BigIntPrimaryKey {
97    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
98        let inner = deserializer.deserialize_any(BigKeyVisitor)?;
99        return  Ok(Self(inner))
100    }
101}
102
103impl Serialize for BigIntPrimaryKey {
104    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
105        let j = format!("{}",self.inner());
106        j.serialize(serializer)
107    }
108}
109
110impl From<String> for BigIntPrimaryKey {
111    fn from(arg: String) -> Self {
112        let result = arg.parse::<i64>();
113        if let Ok(i) = result {
114            return Self(i);
115        }
116        return Self(-1);
117    }
118}
119
120impl From<i64> for BigIntPrimaryKey {
121    fn from(i: i64) -> Self {
122        return Self(i)
123    }
124}
125
126
127impl ToRedisArgs for BigIntPrimaryKey {
128    fn write_redis_args<W>(&self, out: &mut W) where W: ?Sized + RedisWrite,
129    {
130        out.write_arg(self.0.to_string().as_bytes())
131    }
132}
133impl FromRedisValue for BigIntPrimaryKey {
134    fn from_redis_value(v: &RedisValue) -> RedisResult<BigIntPrimaryKey> {
135        match *v {
136            RedisValue::BulkString(ref bytes) => {
137                let data = String::from_utf8(bytes.to_vec());
138                if let Ok(content) = data {
139                    let id = content.parse::<i64>();
140                    if id.is_err() {
141                        return Err(RedisError::from((
142                            ErrorKind::ParseError,
143                            "接续数据失败",
144                            "BigIntPrimaryKey 数据序列化错误".to_string(),
145                        )));
146                    }
147                    return Ok(BigIntPrimaryKey(id.unwrap()));
148                }
149                Err(RedisError::from((
150                    ErrorKind::TypeError,
151                    "序列化失败",
152                    "数据序列化错误".to_string(),
153                )))
154            }
155            _ => {
156                Err(RedisError::from((
157                    ErrorKind::TypeError,
158                    "TypeError Error",
159                    "数据类型错误".to_string(),
160                )))
161            }
162        }
163    }
164}