rbatis_core/postgres/
sqlx_value.rs

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