mybatis_core/postgres/
sqlx_value.rs

1use rbson::{bson, to_bson, Bson};
2use sqlx_core::column::Column;
3use sqlx_core::decode::Decode;
4use sqlx_core::error::BoxDynError;
5use sqlx_core::postgres::types::{PgMoney, PgTimeTz};
6use sqlx_core::postgres::PgRow;
7use sqlx_core::postgres::{PgValue, PgValueRef, Postgres};
8use sqlx_core::row::Row;
9use sqlx_core::type_info::TypeInfo;
10use sqlx_core::types::chrono::{FixedOffset, NaiveTime};
11use sqlx_core::types::time::Time;
12use sqlx_core::types::{BigDecimal, Json, Uuid};
13use sqlx_core::value::ValueRef;
14
15use crate::convert::{JsonCodec, RefJsonCodec, ResultCodec};
16use crate::postgres::PgInterval;
17use chrono::Utc;
18
19use crate::db::db_adapter::DataDecoder;
20use crate::to_bson_macro;
21use rbson::spec::BinarySubtype;
22use std::option::Option::Some;
23
24impl<'c> JsonCodec for PgValueRef<'c> {
25    fn try_to_bson(self) -> crate::Result<Bson> {
26        match self.type_info().name() {
27            "VOID" => {
28                return Ok(Bson::Null);
29            }
30            "NUMERIC" => {
31                //decimal
32                let r: Option<BigDecimal> = Decode::<'_, Postgres>::decode(self)?;
33                if let Some(date) = r {
34                    return Ok(Bson::String(date.to_string()));
35                }
36                return Ok(Bson::Null);
37            }
38            "NUMERIC[]" => {
39                //decimal
40                let r: Option<Vec<BigDecimal>> = Decode::<'_, Postgres>::decode(self)?;
41                if let Some(r) = r {
42                    return Ok(to_bson(&r).unwrap_or_default());
43                }
44                return Ok(Bson::Null);
45            }
46            "MONEY" => {
47                //decimal
48                let r: Option<String> = Decode::<'_, Postgres>::decode(self)?;
49                return Ok(to_bson_macro!(r));
50            }
51            "MONEY[]" => {
52                //decimal
53                let r: Option<Vec<String>> = Decode::<'_, Postgres>::decode(self)?;
54                return Ok(to_bson_macro!(r));
55            }
56            "BOOL" => {
57                let r: Option<bool> = Decode::<'_, Postgres>::decode(self)?;
58                return Ok(to_bson_macro!(r));
59            }
60            "BOOL[]" => {
61                let r: Vec<bool> = Decode::<'_, Postgres>::decode(self)?;
62                return Ok(r.into());
63            }
64            "BYTEA" | "BYTEA[]" => {
65                let r: Option<Vec<u8>> = Decode::<'_, Postgres>::decode(self)?;
66                if let Some(r) = r {
67                    return Ok(Bson::Binary(rbson::Binary {
68                        subtype: BinarySubtype::Generic,
69                        bytes: r,
70                    }));
71                }
72                return Ok(Bson::Null);
73            }
74            "FLOAT4" => {
75                let r: Option<f32> = Decode::<'_, Postgres>::decode(self)?;
76                return Ok(to_bson_macro!(r));
77            }
78            "FLOAT4[]" => {
79                let r: Option<Vec<f32>> = Decode::<'_, Postgres>::decode(self)?;
80                return Ok(to_bson_macro!(r));
81            }
82            "FLOAT8" => {
83                let r: Option<f64> = Decode::<'_, Postgres>::decode(self)?;
84                return Ok(to_bson_macro!(r));
85            }
86            "FLOAT8[]" => {
87                let r: Option<Vec<f64>> = Decode::<'_, Postgres>::decode(self)?;
88                return Ok(to_bson_macro!(r));
89            }
90            "INT2" => {
91                let r: Option<i16> = Decode::<'_, Postgres>::decode(self)?;
92                if let Some(r) = r {
93                    return Ok(bson!(r as i32));
94                }
95                return Ok(Bson::Null);
96            }
97            "INT2[]" => {
98                let r: Option<Vec<i16>> = Decode::<'_, Postgres>::decode(self)?;
99                if let Some(r) = r {
100                    return Ok(to_bson(&r).unwrap_or_default());
101                }
102                return Ok(Bson::Null);
103            }
104            "INT4" => {
105                let r: Option<i32> = Decode::<'_, Postgres>::decode(self)?;
106                return Ok(to_bson_macro!(r));
107            }
108            "INT4[]" => {
109                let r: Option<Vec<i32>> = Decode::<'_, Postgres>::decode(self)?;
110
111                return Ok(to_bson_macro!(r));
112            }
113            "INT8" => {
114                let r: Option<i64> = Decode::<'_, Postgres>::decode(self)?;
115                return Ok(to_bson_macro!(r));
116            }
117            "INT8[]" => {
118                let r: Option<Vec<i64>> = Decode::<'_, Postgres>::decode(self)?;
119                return Ok(to_bson_macro!(r));
120            }
121            "OID" => {
122                let r: Option<u32> = Decode::<'_, Postgres>::decode(self)?;
123                return Ok(to_bson_macro!(r));
124            }
125            "OID[]" => {
126                let r: Option<Vec<u32>> = Decode::<'_, Postgres>::decode(self)?;
127                return Ok(to_bson_macro!(r));
128            }
129            "TEXT" | "NAME" | "VARCHAR" | "BPCHAR" | "CHAR" | "\"CHAR\"" | "UNKNOWN" => {
130                let r: Option<String> = Decode::<'_, Postgres>::decode(self)?;
131                return Ok(to_bson_macro!(r));
132            }
133            "TEXT[]" | "CHAR[]" | "VARCHAR[]" | "\"CHAR\"[]" | "NAME[]" => {
134                let r: Option<Vec<String>> = Decode::<'_, Postgres>::decode(self)?;
135                return Ok(to_bson_macro!(r));
136            }
137            "UUID" => {
138                let r: Option<Uuid> = Decode::<'_, Postgres>::decode(self)?;
139                if let Some(r) = r {
140                    return Ok(to_bson(&r).unwrap_or_default());
141                }
142                return Ok(Bson::Null);
143            }
144            "UUID[]" => {
145                let r: Option<Vec<Uuid>> = Decode::<'_, Postgres>::decode(self)?;
146                if let Some(r) = r {
147                    let mut arr = vec![];
148                    for x in r {
149                        arr.push(to_bson(&x).unwrap_or_default());
150                    }
151                    return Ok(Bson::from(arr));
152                }
153                return Ok(Bson::Null);
154            }
155            "JSON" | "JSONB" => {
156                let r: Option<Json<serde_json::Value>> = Decode::<'_, Postgres>::decode(self)?;
157                if let Some(r) = r {
158                    return Ok(to_bson(&r.0).unwrap_or_default());
159                }
160                return Ok(Bson::Null);
161            }
162            "JSON[]" | "JSONB[]" => {
163                let r: Option<Vec<Json<serde_json::Value>>> = Decode::<'_, Postgres>::decode(self)?;
164                if let Some(r) = r {
165                    let mut arr = Vec::with_capacity(r.capacity());
166                    for x in r {
167                        arr.push(x.0);
168                    }
169                    return Ok(to_bson(&arr).unwrap_or_default());
170                }
171                return Ok(Bson::Null);
172            }
173            "TIME" => {
174                let r: Option<NaiveTime> = Decode::<'_, Postgres>::decode(self)?;
175                return Ok(to_bson(&r).unwrap_or_default());
176            }
177            "TIME[]" => {
178                let r: Option<Vec<NaiveTime>> = Decode::<'_, Postgres>::decode(self)?;
179                return Ok(to_bson(&r).unwrap_or_default());
180            }
181            "DATE" => {
182                let r: Option<chrono::NaiveDate> = Decode::<'_, Postgres>::decode(self)?;
183                return Ok(to_bson(&r).unwrap_or_default());
184            }
185            "DATE[]" => {
186                let r: Option<Vec<chrono::NaiveDate>> = Decode::<'_, Postgres>::decode(self)?;
187                return Ok(to_bson(&r).unwrap_or_default());
188            }
189            "TIMESTAMP" => {
190                let r: Option<chrono::NaiveDateTime> = Decode::<'_, Postgres>::decode(self)?;
191                if let Some(dt) = r {
192                    return Ok(Bson::String(dt.format("%Y-%m-%dT%H:%M:%S").to_string()));
193                }
194                return Ok(Bson::Null);
195            }
196            "TIMESTAMP[]" => {
197                let r: Option<Vec<chrono::NaiveDateTime>> = Decode::<'_, Postgres>::decode(self)?;
198                if let Some(r) = r {
199                    let mut dts = vec![];
200                    for dt in r {
201                        dts.push(Bson::String(dt.format("%Y-%m-%dT%H:%M:%S").to_string()));
202                    }
203                    return Ok(Bson::Array(dts));
204                }
205                return Ok(Bson::Null);
206            }
207            "TIMESTAMPTZ" => {
208                let r: Option<chrono::DateTime<Utc>> = Decode::<'_, Postgres>::decode(self)?;
209                if let Some(dt) = r {
210                    return Ok(Bson::String(dt.to_string()));
211                }
212                return Ok(Bson::Null);
213            }
214            "TIMESTAMPTZ[]" => {
215                let r: Option<Vec<chrono::DateTime<Utc>>> = Decode::<'_, Postgres>::decode(self)?;
216                if let Some(r) = r {
217                    let mut dts = vec![];
218                    for x in r {
219                        let dt = rbson::DateTime::from_chrono(x);
220                        dts.push(Bson::String(dt.to_string()));
221                    }
222                    return Ok(Bson::Array(dts));
223                }
224                return Ok(Bson::Null);
225            }
226            "INTERVAL" => {
227                let r: Option<sqlx_core::postgres::types::PgInterval> =
228                    Decode::<'_, Postgres>::decode(self)?;
229                if r.is_none() {
230                    return Ok(Bson::Null);
231                }
232                return Ok(to_bson(&PgInterval::from(r.unwrap())).unwrap_or_default());
233            }
234            "VARBIT" | "BIT" => {
235                let r: Option<bit_vec::BitVec> = Decode::<'_, Postgres>::decode(self)?;
236                return Ok(to_bson(&r).unwrap_or_default());
237            }
238            "VARBIT[]" | "BIT[]" => {
239                let r: Option<Vec<bit_vec::BitVec>> = Decode::<'_, Postgres>::decode(self)?;
240                return Ok(to_bson(&r).unwrap_or_default());
241            }
242            _ => {
243                //TODO
244                //"CIDR" | "INET"
245                //"CIDR[]" | "INET[]"
246                // "JSONPATH","JSONPATH[]",
247                // "INT8RANGE","INT8RANGE[]",
248                // "DATERANGE","DATERANGE[]",
249                // "TSTZRANGE","TSTZRANGE[]",
250                // "TSRANGE","TSRANGE[]",
251                // "NUMRANGE","NUMRANGE[]",
252                // "INT4RANGE","INT4RANGE[]",
253                // "RECORD","RECORD[]"
254                // "TIMETZ" "TIMETZ[]"
255                // "INTERVAL[]"
256                // "POINT","POINT[],"
257                // LSEG","LSEG[]",
258                // "PATH","PATH[]",
259                // "BOX","BOX[]",
260                // "POLYGON","POLYGON[]",
261                // "LINE","LINE[]",
262                // "CIRCLE", "CIRCLE[]",
263                // "MACADDR8","MACADDR8[]",
264                // "MACADDR","MACADDR[]",
265                //  you can use already Vec<u8> types to decode this
266                let r: Option<Vec<u8>> = Decode::<'_, Postgres>::decode(self)?;
267                if let Some(r) = r {
268                    return Ok(Bson::Binary(rbson::Binary {
269                        subtype: BinarySubtype::Generic,
270                        bytes: r,
271                    }));
272                }
273                return Ok(Bson::Null);
274            }
275        }
276    }
277}
278
279impl RefJsonCodec for Vec<PgRow> {
280    fn try_to_bson(&self, decoder: &dyn DataDecoder) -> crate::Result<Bson> {
281        let mut arr = Vec::with_capacity(self.len());
282        for row in self {
283            let mut m = rbson::Document::new();
284            let columns = row.columns();
285            for x in columns {
286                let key = x.name();
287                let v: PgValueRef = row.try_get_raw(key)?;
288                let mut bson = v.try_to_bson()?;
289                decoder.decode(key, &mut bson)?;
290                m.insert(key.to_owned(), bson);
291            }
292            arr.push(Bson::Document(m));
293        }
294        Ok(Bson::from(arr))
295    }
296}