1use super::super::*;
2use super::*;
3use serde::{
4 de::{self, DeserializeSeed, IntoDeserializer, Visitor},
5 forward_to_deserialize_any,
6};
7
8impl<'de> serde::de::EnumAccess<'de> for Value {
9 type Error = Error;
10
11 type Variant = UnitOnly;
12
13 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
14 where
15 V: de::DeserializeSeed<'de>,
16 {
17 let s = self.strict_as_str();
18 Ok((
19 seed.deserialize(StringDeserializer {
20 input: s.to_string(),
21 })?,
22 UnitOnly,
23 ))
24 }
25}
26
27#[derive(Debug, Clone)]
28struct EnumTimestampDeserializer {
29 value: Value,
30}
31
32impl<'de> serde::de::EnumAccess<'de> for EnumTimestampDeserializer {
33 type Error = Error;
34
35 type Variant = VariantTimestampDeserializer;
36
37 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
38 where
39 V: DeserializeSeed<'de>,
40 {
41 match self.value {
44 Value::Timestamp(Timestamp::Microseconds(v)) => Ok((
45 seed.deserialize(StringDeserializer {
46 input: "Microseconds".to_string(),
47 })
48 .expect(""),
49 VariantTimestampDeserializer { value: v },
50 )),
51 Value::Timestamp(Timestamp::Milliseconds(v)) => Ok((
52 seed.deserialize(StringDeserializer {
53 input: "Milliseconds".to_string(),
54 })
55 .expect(""),
56 VariantTimestampDeserializer { value: v },
57 )),
58 Value::Timestamp(Timestamp::Nanoseconds(v)) => Ok((
59 seed.deserialize(StringDeserializer {
60 input: "Nanoseconds".to_string(),
61 })
62 .expect(""),
63 VariantTimestampDeserializer { value: v },
64 )),
65 _ => todo!(),
66 }
67 }
68}
69
70#[derive(Debug, Clone)]
71struct EnumValueDeserializer {
72 value: Value,
73}
74
75#[derive(Clone)]
76struct StringDeserializer {
77 input: String,
78}
79
80impl<'de> de::Deserializer<'de> for StringDeserializer {
81 type Error = Error;
82
83 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
84 where
85 V: Visitor<'de>,
86 {
87 visitor.visit_string(self.input)
88 }
89
90 forward_to_deserialize_any! {
91 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
92 seq bytes byte_buf map unit_struct newtype_struct
93 tuple_struct struct tuple enum identifier ignored_any
94 }
95}
96impl<'de, 'b: 'de> serde::de::EnumAccess<'de> for EnumValueDeserializer {
97 type Error = Error;
98
99 type Variant = Self;
100
101 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
102 where
103 V: DeserializeSeed<'de>,
104 {
105 let variant = self.value.ty().as_variant_str();
106
107 Ok((
108 seed.deserialize(StringDeserializer {
109 input: variant.to_string(),
110 })
111 .expect(""),
112 self,
113 ))
114 }
115}
116
117impl<'de, 'b: 'de> de::VariantAccess<'de> for EnumValueDeserializer {
118 type Error = Error;
119
120 fn unit_variant(self) -> Result<(), Self::Error> {
121 Ok(())
122 }
123
124 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
125 where
126 T: DeserializeSeed<'de>,
127 {
128 seed.deserialize(self.value)
129 }
130
131 fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
132 where
133 V: Visitor<'de>,
134 {
135 todo!()
136 }
137
138 fn struct_variant<V>(
139 self,
140 _fields: &'static [&'static str],
141 _visitor: V,
142 ) -> Result<V::Value, Self::Error>
143 where
144 V: Visitor<'de>,
145 {
146 todo!()
147 }
148}
149
150impl<'de, 'b: 'de> serde::de::Deserializer<'de> for Value {
151 type Error = Error;
152
153 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
154 where
155 V: serde::de::Visitor<'de>,
156 {
157 use Value::*;
158 match self {
160 Null(_) => visitor.visit_none(),
161 Bool(v) => visitor.visit_bool(v),
162 TinyInt(v) => visitor.visit_i8(v),
163 SmallInt(v) => visitor.visit_i16(v),
164 Int(v) => visitor.visit_i32(v),
165 BigInt(v) => visitor.visit_i64(v),
166 UTinyInt(v) => visitor.visit_u8(v),
167 USmallInt(v) => visitor.visit_u16(v),
168 UInt(v) => visitor.visit_u32(v),
169 UBigInt(v) => visitor.visit_u64(v),
170 Float(v) => visitor.visit_f32(v),
171 Double(v) => visitor.visit_f64(v),
172 VarChar(v) => visitor.visit_string(v),
173 NChar(v) => visitor.visit_string(v),
174 Json(v) => v
175 .into_deserializer()
176 .deserialize_any(visitor)
177 .map_err(<Self::Error as de::Error>::custom),
178 Timestamp(v) => visitor.visit_i64(v.as_raw_i64()),
179 Blob(v) | MediumBlob(v) => v.into_deserializer().deserialize_any(visitor),
180 VarBinary(v) | Geometry(v) => v.into_deserializer().deserialize_any(visitor),
181 _ => Err(<Self::Error as de::Error>::custom(
182 "un supported type to deserialize",
183 )),
184 }
185 }
186
187 serde::forward_to_deserialize_any! {bool i8 u8 i16 u16 i32 u32 i64 u64 f32 f64 char}
188
189 serde::forward_to_deserialize_any! {
190 unit
191 bytes byte_buf unit_struct
192 tuple_struct tuple identifier ignored_any
193 }
194
195 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
196 where
197 V: serde::de::Visitor<'de>,
198 {
199 use Value::*;
200 match self {
201 Null(_) => visitor.visit_str(""), Bool(v) => visitor.visit_bool(v),
206 TinyInt(v) => visitor.visit_i8(v),
207 SmallInt(v) => visitor.visit_i16(v),
208 Int(v) => visitor.visit_i32(v),
209 BigInt(v) => visitor.visit_i64(v),
210 UTinyInt(v) => visitor.visit_u8(v),
211 USmallInt(v) => visitor.visit_u16(v),
212 UInt(v) => visitor.visit_u32(v),
213 UBigInt(v) => visitor.visit_u64(v),
214 Float(v) => visitor.visit_f32(v),
215 Double(v) => visitor.visit_f64(v),
216 VarChar(v) | NChar(v) => visitor.visit_string(v),
217 Json(v) => visitor.visit_string(v.to_string()),
218 Timestamp(v) => visitor.visit_string(v.to_datetime_with_tz().to_rfc3339().to_string()),
219 _ => Err(<Self::Error as de::Error>::custom(
220 "un supported type to deserialize",
221 )),
222 }
223 }
224
225 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
226 where
227 V: serde::de::Visitor<'de>,
228 {
229 self.deserialize_str(visitor)
230 }
231
232 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
233 where
234 V: serde::de::Visitor<'de>,
235 {
236 if self.is_null() {
237 visitor.visit_none()
238 } else {
239 visitor.visit_some(self)
240 }
241 }
242
243 fn deserialize_newtype_struct<V>(
244 self,
245 _name: &'static str,
246 visitor: V,
247 ) -> Result<V::Value, Self::Error>
248 where
249 V: Visitor<'de>,
250 {
251 use Value::*;
252 macro_rules! _v_ {
253 ($v:expr) => {
254 visitor.visit_newtype_struct($v.into_deserializer())
255 };
256 }
257 match self {
258 Null(_) => visitor.visit_none(),
259 Bool(v) => _v_!(v),
260 TinyInt(v) => _v_!(v),
261 SmallInt(v) => _v_!(v),
262 Int(v) => _v_!(v),
263 BigInt(v) => _v_!(v),
264 UTinyInt(v) => _v_!(v),
265 USmallInt(v) => _v_!(v),
266 UInt(v) => _v_!(v),
267 UBigInt(v) => _v_!(v),
268 Float(v) => _v_!(v),
269 Double(v) => _v_!(v),
270 VarChar(v) | NChar(v) => visitor.visit_newtype_struct(v.as_str().into_deserializer()),
271 Json(v) => visitor
272 .visit_newtype_struct(v.into_deserializer())
273 .map_err(<Self::Error as de::Error>::custom),
274 Timestamp(v) => _v_!(v.as_raw_i64()),
275 Blob(v) | MediumBlob(v) => {
276 visitor.visit_newtype_struct(v.as_slice().into_deserializer())
277 }
278 VarBinary(_v) | Geometry(_v) => {
279 todo!()
280 }
281 _ => Err(<Self::Error as de::Error>::custom(
282 "un supported type to deserialize",
283 )),
284 }
285 }
286
287 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
288 where
289 V: serde::de::Visitor<'de>,
290 {
291 self.deserialize_any(visitor)
292 }
293
294 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
295 where
296 V: serde::de::Visitor<'de>,
297 {
298 use Value::*;
299 match self {
300 Null(_) => Vec::<u8>::new()
301 .into_deserializer()
302 .deserialize_seq(visitor),
303 Json(v) => v
304 .into_deserializer()
305 .deserialize_seq(visitor)
306 .map_err(<Self::Error as de::Error>::custom),
307 VarChar(v) | NChar(v) => v
308 .as_bytes()
309 .to_vec()
310 .into_deserializer()
311 .deserialize_seq(visitor),
312 Blob(v) | MediumBlob(v) => v.into_deserializer().deserialize_seq(visitor),
313 VarBinary(v) | Geometry(v) => v.into_deserializer().deserialize_seq(visitor),
314 _ => todo!(),
315 }
316 }
317
318 fn deserialize_enum<V>(
319 self,
320 name: &'static str,
321 variants: &'static [&'static str],
322 visitor: V,
323 ) -> Result<V::Value, Self::Error>
324 where
325 V: Visitor<'de>,
326 {
327 if name == "Timestamp" && variants == TIMESTAMP_VARIANTS {
328 return visitor.visit_enum(EnumTimestampDeserializer { value: self });
329 }
330 if name == "Value" && variants == VALUE_VARIANTS {
331 return visitor.visit_enum(EnumValueDeserializer {
332 value: self,
334 });
335 }
336
337 visitor.visit_enum(self)
338 }
339
340 fn deserialize_struct<V>(
341 self,
342 name: &'static str,
343 fields: &'static [&'static str],
344 visitor: V,
345 ) -> Result<V::Value, Self::Error>
346 where
347 V: Visitor<'de>,
348 {
349 match self {
350 Value::Json(json) => json
351 .into_deserializer()
352 .deserialize_struct(name, fields, visitor)
353 .map_err(<Self::Error as serde::de::Error>::custom),
354 _ => self.deserialize_any(visitor),
355 }
356 }
357}
358
359impl<'de, 'b: 'de> serde::de::IntoDeserializer<'de, Error> for Value {
360 type Deserializer = Self;
361
362 fn into_deserializer(self) -> Self::Deserializer {
363 self
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 use serde_json::json;
372
373 #[test]
374 fn value_de_value() {
375 use std::cmp::PartialEq;
376 use Value::*;
377 macro_rules! _de_value {
378 ($($v:expr) *) => {
379 $(
380 {
381 let v = $v;
382 let d = Value::deserialize(v.clone().into_deserializer()).expect("");
383 assert!(v.eq(&d));
384 }
385 )*
386 }
387 }
388 _de_value!(
389 Bool(true) TinyInt(0xf) SmallInt(0xfff) Int(0xffff) BigInt(-1) Float(1.0) Double(1.0)
390 UTinyInt(0xf) USmallInt(0xfff) UInt(0xffff) UBigInt(0xffffffff)
391 Timestamp(crate::common::timestamp::Timestamp::Milliseconds(0)) VarChar("anything".to_string())
392 NChar("你好,世界".to_string()) VarBinary(Bytes::from(vec![1,2,3])) Blob(vec![1,2, 3]) MediumBlob(vec![1,2,3])
393 Json(serde_json::json!({"name": "ABC"}))
394 );
395 }
396
397 #[test]
398 fn de_value_as_inner() {
399 use Value::*;
400 macro_rules! _de_value {
401 ($($v:expr, $ty:ty, $tv:expr) *) => {
402 $(
403 {
404 let d = <$ty>::deserialize($v.into_deserializer()).expect("");
405 assert_eq!(d, $tv);
406 }
407 )*
408 }
409 }
410
411 _de_value!(
412 Null(Ty::UTinyInt), Option<u8>, None
413 TinyInt(-1), i8, -1
414 SmallInt(-1), i16, -1
415 Int(0x0fff_ffff), i32, 0x0fff_ffff
416 BigInt(0xffffffff), i64, 0xffffffff
417 UTinyInt(0xff), u8, 0xff
418 USmallInt(0xffff), u16, 0xffff
419 UInt(0x_ffff_ffff), u32, 0x_ffff_ffff
420 UBigInt(0x_ffff_ffff_ffff_ffff), u64, 0x_ffff_ffff_ffff_ffff
421 Float(1.0), f32, 1.0
422 Double(f64::MAX), f64, f64::MAX
423 VarChar("".to_string()), String, "".to_string()
424 NChar("".to_string()), String, "".to_string()
425 Timestamp(crate::Timestamp::Milliseconds(1)), crate::Timestamp, crate::Timestamp::Milliseconds(1)
426 VarBinary(Bytes::from(vec![0, 1,2])), Bytes, Bytes::from(vec![0, 1,2])
427 Blob(vec![0, 1,2]), Vec<u8>, vec![0, 1, 2]
428 MediumBlob(vec![0, 1,2]), Vec<u8>, vec![0, 1, 2]
429 );
430 }
431
432 #[test]
433 fn de_str() {
434 use serde_json::json;
435 use Value::*;
436
437 macro_rules! _de_str {
438 ($v:expr, is_err) => {
439 assert!(String::deserialize($v.into_deserializer()).is_err());
440 };
441 ($v:expr, $tv:expr) => {
442 assert_eq!(String::deserialize($v.into_deserializer()).expect("str"), $tv);
443 };
444 ($($v:expr, $c:ident) *) => {
445 $(
446 {
447 assert!(String::deserialize($v.into_deserializer()).$c());
448 }
449 )*
450 };
451 ($($v2:expr, is_err) +; $($v:expr, $tv:expr) + ) => {
452 $(
453 _de_str!($v2, is_err);
454 )*
455 $(
456 _de_str!($v, $tv);
457 )*
458 }
459 }
460 _de_str! {
461 TinyInt(-1), is_err
462 SmallInt(-1), is_err
463 Int(-1), is_err
464 BigInt(-1), is_err
465 UTinyInt(1), is_err
466 USmallInt(1), is_err
467 UInt(1), is_err
468 UBigInt(1), is_err
469 ;
470
471 Null(Ty::VarChar), ""
472 Timestamp(crate::Timestamp::Milliseconds(0)), "1970-01-01T08:00:00+08:00"
473 VarChar("String".to_string()), "String"
474 VarChar("你好,世界".to_string()), "你好,世界"
475 Json(json!("abc")), json!("abc").to_string()
476 Json(json!({ "name": "abc"})), json!({ "name": "abc"}).to_string()
477 Json(json!(1)), json!(1).to_string()
478 Json(json!(null)), json!(null).to_string()
479 };
480 }
481
482 #[test]
483 fn de_json() {
484 use Value::*;
485
486 macro_rules! _de_json {
487 ($v:expr, $ty:ty, $tv:expr) => {{
488 let v = Json($v);
489 let d = <$ty>::deserialize(v.clone().into_deserializer()).expect("de json");
490 assert_eq!(d, $tv);
491 }};
492 }
493
494 _de_json!(
495 serde_json::json!("string"),
496 String,
497 "\"string\"".to_string()
498 );
499
500 #[derive(Debug, PartialEq, Eq, Deserialize)]
501 struct Obj {
502 name: String,
503 }
504 _de_json!(
505 serde_json::json!({ "name": "string" }),
506 Obj,
507 Obj {
508 name: "string".to_string()
509 }
510 );
511 }
512
513 #[test]
514 fn de_newtype_struct() {
515 use serde_json::json;
516 use Value::*;
517
518 macro_rules! _de_ty {
519 ($v:expr, $ty:ty, $tv:expr) => {{
520 let d = <$ty>::deserialize($v.into_deserializer()).expect("de type");
521 assert_eq!(d, $tv);
522 }};
523 }
524 #[derive(Debug, PartialEq, Eq, Deserialize)]
525 struct JsonStr(String);
526 _de_ty!(
527 Json(json!("string")),
528 JsonStr,
529 JsonStr("string".to_string())
530 );
531
532 #[derive(Debug, PartialEq, Eq, Deserialize)]
533 struct Primi<T>(T);
534 _de_ty!(Json(json!(1)), Primi<i32>, Primi(1));
535 _de_ty!(TinyInt(1), Primi<i8>, Primi(1));
536 _de_ty!(SmallInt(1), Primi<i64>, Primi(1));
537 _de_ty!(Int(1), Primi<i64>, Primi(1));
538 _de_ty!(BigInt(1), Primi<i64>, Primi(1));
539
540 macro_rules! _de_prim {
541 ($v:ident, $ty:ty, $inner:literal) => {
542 log::trace!(
543 "ty: {}, prim: {}",
544 stringify!($v),
545 std::any::type_name::<$ty>()
546 );
547 _de_ty!($v($inner), Primi<$ty>, Primi($inner));
548 };
549 }
550
551 macro_rules! _de_prim_cross {
552 ($($vty:ident) +, $tt:ty) => {
553 $(
554 _de_prim!($vty, $tt, 1);
555 )*
556 };
557 ($($ty:ty) +) => {
558 $(
559 _de_prim_cross!(TinyInt SmallInt Int BigInt UTinyInt USmallInt UInt UBigInt, $ty);
560 )*
561 };
562 () => {
563 _de_prim_cross!(i8 i16 i32 i64 u8 u16 u32 u64);
564 };
565 }
566 _de_prim_cross!();
567 }
568}