1use super::super::*;
2use super::*;
3use serde::{
4 de::{self, DeserializeSeed, IntoDeserializer, Visitor},
5 forward_to_deserialize_any,
6};
7
8impl<'de, 'v> serde::de::EnumAccess<'de> for &'v 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<'v> {
29 value: &'v Value,
30}
31
32impl<'v, 'de> serde::de::EnumAccess<'de> for EnumTimestampDeserializer<'v> {
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<'v> {
72 value: &'v 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, 'v: 'de> serde::de::EnumAccess<'de> for EnumValueDeserializer<'v> {
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, 'v: 'de> de::VariantAccess<'de> for EnumValueDeserializer<'v> {
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, 'v: 'de> serde::de::Deserializer<'de> for &'v 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_borrowed_str(v),
173 NChar(v) => visitor.visit_borrowed_str(v),
174 Json(v) => v
175 .clone()
176 .into_deserializer()
177 .deserialize_any(visitor)
178 .map_err(<Self::Error as de::Error>::custom),
179 Timestamp(v) => visitor.visit_i64(v.as_raw_i64()),
180 Blob(v) | MediumBlob(v) => visitor.visit_borrowed_bytes(v),
181 VarBinary(v) | Geometry(v) => visitor.visit_borrowed_bytes(v),
182 _ => Err(<Self::Error as de::Error>::custom(
183 "un supported type to deserialize",
184 )),
185 }
186 }
187
188 serde::forward_to_deserialize_any! {bool i8 u8 i16 u16 i32 u32 i64 u64 f32 f64 char}
189
190 serde::forward_to_deserialize_any! {
191 unit
192 bytes byte_buf unit_struct
193 tuple_struct tuple identifier ignored_any
194 }
195
196 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
197 where
198 V: serde::de::Visitor<'de>,
199 {
200 use Value::*;
201 match self {
202 Null(_) => visitor.visit_borrowed_str(""), Bool(v) => visitor.visit_bool(*v),
204 TinyInt(v) => visitor.visit_i8(*v),
205 SmallInt(v) => visitor.visit_i16(*v),
206 Int(v) => visitor.visit_i32(*v),
207 BigInt(v) => visitor.visit_i64(*v),
208 UTinyInt(v) => visitor.visit_u8(*v),
209 USmallInt(v) => visitor.visit_u16(*v),
210 UInt(v) => visitor.visit_u32(*v),
211 UBigInt(v) => visitor.visit_u64(*v),
212 Float(v) => visitor.visit_f32(*v),
213 Double(v) => visitor.visit_f64(*v),
214 VarChar(v) | NChar(v) => visitor.visit_borrowed_str(v),
215 Json(v) => visitor.visit_string(v.to_string()),
216 Timestamp(v) => visitor.visit_string(
217 v.to_naive_datetime()
218 .format("%Y-%m-%dT%H:%M:%S%.f")
219 .to_string(),
220 ),
221 _ => Err(<Self::Error as de::Error>::custom(
222 "un supported type to deserialize",
223 )),
224 }
225 }
226
227 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
228 where
229 V: serde::de::Visitor<'de>,
230 {
231 self.deserialize_str(visitor)
232 }
233
234 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
235 where
236 V: serde::de::Visitor<'de>,
237 {
238 if self.is_null() {
239 visitor.visit_none()
240 } else {
241 visitor.visit_some(self)
242 }
243 }
244
245 fn deserialize_newtype_struct<V>(
246 self,
247 _name: &'static str,
248 visitor: V,
249 ) -> Result<V::Value, Self::Error>
250 where
251 V: Visitor<'de>,
252 {
253 use Value::*;
254 macro_rules! _v_ {
255 ($v:expr) => {
256 visitor.visit_newtype_struct($v.into_deserializer())
257 };
258 }
259 match self {
260 Null(_) => visitor.visit_none(),
261 Bool(v) => _v_!(v),
262 TinyInt(v) => _v_!(v),
263 SmallInt(v) => _v_!(v),
264 Int(v) => _v_!(v),
265 BigInt(v) => _v_!(v),
266 UTinyInt(v) => _v_!(v),
267 USmallInt(v) => _v_!(v),
268 UInt(v) => _v_!(v),
269 UBigInt(v) => _v_!(v),
270 Float(v) => _v_!(v),
271 Double(v) => _v_!(v),
272 VarChar(v) | NChar(v) => visitor.visit_newtype_struct(v.as_str().into_deserializer()),
273 Json(v) => visitor
274 .visit_newtype_struct(v.clone().into_deserializer())
275 .map_err(<Self::Error as de::Error>::custom),
276 Timestamp(v) => _v_!(v.as_raw_i64()),
277 Blob(v) | MediumBlob(v) => {
278 visitor.visit_newtype_struct(v.as_slice().into_deserializer())
279 }
280 VarBinary(v) | Geometry(v) => visitor.visit_bytes(v),
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 .clone()
305 .into_deserializer()
306 .deserialize_seq(visitor)
307 .map_err(<Self::Error as de::Error>::custom),
308 VarChar(v) | NChar(v) => v
309 .as_bytes()
310 .to_vec()
311 .into_deserializer()
312 .deserialize_seq(visitor),
313 Blob(v) | MediumBlob(v) => v.clone().into_deserializer().deserialize_any(visitor),
314 VarBinary(v) | Geometry(v) => v.as_ref().into_deserializer().deserialize_seq(visitor),
315 _ => self.deserialize_any(visitor),
316 }
317 }
318
319 fn deserialize_enum<V>(
320 self,
321 name: &'static str,
322 variants: &'static [&'static str],
323 visitor: V,
324 ) -> Result<V::Value, Self::Error>
325 where
326 V: Visitor<'de>,
327 {
328 if name == "Timestamp" && variants == TIMESTAMP_VARIANTS {
329 return visitor.visit_enum(EnumTimestampDeserializer { value: self });
330 }
331 if name == "Value" && variants == VALUE_VARIANTS {
332 return visitor.visit_enum(EnumValueDeserializer {
333 value: self,
335 });
336 }
337
338 visitor.visit_enum(self)
339 }
340
341 fn deserialize_struct<V>(
342 self,
343 name: &'static str,
344 fields: &'static [&'static str],
345 visitor: V,
346 ) -> Result<V::Value, Self::Error>
347 where
348 V: Visitor<'de>,
349 {
350 match self {
351 Value::Json(json) => json
352 .clone()
353 .into_deserializer()
354 .deserialize_struct(name, fields, visitor)
355 .map_err(<Self::Error as serde::de::Error>::custom),
356 _ => self.deserialize_any(visitor),
357 }
358 }
359}
360
361impl<'de, 'b: 'de> serde::de::IntoDeserializer<'de, Error> for &'b Value {
362 type Deserializer = Self;
363
364 fn into_deserializer(self) -> Self::Deserializer {
365 self
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 use serde_json::json;
374
375 #[test]
376 fn value_de_value_ref() {
377 use std::cmp::PartialEq;
378 use Value::*;
379 macro_rules! _de_value {
380 ($($v:expr) *) => {
381 $(
382 {
383 let v = &$v;
384 let d = Value::deserialize(v.into_deserializer()).expect("");
385 assert!(dbg!(d).eq(&$v));
386 }
387 )*
388 }
389 }
390 _de_value!(
391 Bool(true) TinyInt(0xf) SmallInt(0xfff) Int(0xffff) BigInt(-1) Float(1.0) Double(1.0)
392 UTinyInt(0xf) USmallInt(0xfff) UInt(0xffff) UBigInt(0xffffffff)
393 Timestamp(crate::common::timestamp::Timestamp::Milliseconds(0)) VarChar("anything".to_string())
394 NChar("你好,世界".to_string()) VarBinary(Bytes::from(vec![1,2,3])) Blob(vec![1,2, 3]) MediumBlob(vec![1,2,3])
395 Json(serde_json::json!({"name": "ABC"}))
396 );
397 }
398
399 #[test]
400 fn de_value_as_inner() {
401 use Value::*;
402 macro_rules! _de_value {
403 ($($v:expr, $ty:ty, $tv:expr) *) => {
404 $(
405 {
406 let v = &$v;
407 let d = <$ty>::deserialize(v.into_deserializer()).expect("");
408 assert_eq!(d, $tv);
409 }
410 )*
411 }
412 }
413
414 _de_value!(
415 Null(Ty::USmallInt), Option<u8>, None
416 TinyInt(-1), i8, -1
417 SmallInt(-1), i16, -1
418 Int(0x0fff_ffff), i32, 0x0fff_ffff
419 BigInt(0xffffffff), i64, 0xffffffff
420 UTinyInt(0xff), u8, 0xff
421 USmallInt(0xffff), u16, 0xffff
422 UInt(0x_ffff_ffff), u32, 0x_ffff_ffff
423 UBigInt(0x_ffff_ffff_ffff_ffff), u64, 0x_ffff_ffff_ffff_ffff
424 Float(1.0), f32, 1.0
425 Double(f64::MAX), f64, f64::MAX
426 VarChar("".to_string()), String, "".to_string()
427 NChar("".to_string()), String, "".to_string()
428 Timestamp(crate::Timestamp::Milliseconds(1)), crate::Timestamp, crate::Timestamp::Milliseconds(1)
429 VarBinary(Bytes::from(vec![0, 1,2])), Bytes, Bytes::from(vec![0, 1,2])
430 Blob(vec![0, 1,2]), Vec<u8>, vec![0, 1, 2]
431 MediumBlob(vec![0, 1,2]), Vec<u8>, vec![0, 1, 2]
432 );
433 }
434
435 #[test]
436 fn de_borrowed_str() {
437 use serde_json::json;
438 use Value::*;
439
440 macro_rules! _de_str {
441 ($v:expr, is_err) => {
442 assert!(<&str>::deserialize((&$v).into_deserializer()).is_err());
443 };
444 ($v:expr, $tv:expr) => {
445 assert_eq!(<&str>::deserialize((&$v).into_deserializer()).expect("str"), $tv);
446 };
447 ($($v:expr, $c:ident) *) => {
448 $(
449 {
450 assert!(<&str>::deserialize(($v).into_deserializer()).$c());
451 }
452 )*
453 };
454 ($($v2:expr, is_err) +; $($v:expr, $tv:expr) + ) => {
455 $(
456 _de_str!($v2, is_err);
457 )*
458 $(
459 _de_str!($v, $tv);
460 )*
461 }
462 }
463 _de_str! {
464 TinyInt(-1), is_err
465 SmallInt(-1), is_err
466 Int(-1), is_err
467 BigInt(-1), is_err
468 UTinyInt(1), is_err
469 USmallInt(1), is_err
470 UInt(1), is_err
471 UBigInt(1), is_err
472 Json(json!({ "name": "abc"})), is_err
473 Json(json!(1)), is_err
474 Json(json!(null)), is_err
475 Json(json!("abc")), is_err
476 Timestamp(crate::Timestamp::Milliseconds(0)), is_err
477 ;
478 Null(Ty::VarChar), ""
479 VarChar("String".to_string()), "String"
480 VarChar("你好,世界".to_string()), "你好,世界"
481 };
482 }
483 #[test]
484 fn de_string() {
485 use serde_json::json;
486 use Value::*;
487
488 macro_rules! _de_str {
489 ($v:expr, is_err) => {
490 assert!(String::deserialize((&$v).into_deserializer()).is_err());
491 };
492 ($v:expr, $tv:expr) => {
493 assert_eq!(String::deserialize((&$v).into_deserializer()).expect("str"), $tv);
494 };
495 ($($v:expr, $c:ident) *) => {
496 $(
497 {
498 assert!(String::deserialize(($v).into_deserializer()).$c());
499 }
500 )*
501 };
502 ($($v2:expr, is_err) +; $($v:expr, $tv:expr) + ) => {
503 $(
504 _de_str!($v2, is_err);
505 )*
506 $(
507 _de_str!($v, $tv);
508 )*
509 }
510 }
511 _de_str! {
512
513 TinyInt(-1), is_err
514 SmallInt(-1), is_err
515 Int(-1), is_err
516 BigInt(-1), is_err
517 UTinyInt(1), is_err
518 USmallInt(1), is_err
519 UInt(1), is_err
520 UBigInt(1), is_err
521 ;
522
523 Null(Ty::VarChar), ""
524 Timestamp(crate::Timestamp::Milliseconds(0)), "1970-01-01T00:00:00"
525 VarChar("String".to_string()), "String"
526 VarChar("你好,世界".to_string()), "你好,世界"
527 Json(json!("abc")), json!("abc").to_string()
528 Json(json!({ "name": "abc"})), json!({ "name": "abc"}).to_string()
529 Json(json!(1)), json!(1).to_string()
530 Json(json!(null)), json!(null).to_string()
531 };
532 }
533
534 #[test]
535 fn de_json() {
536 use Value::*;
537
538 macro_rules! _de_json {
539 ($v:expr, $ty:ty, $tv:expr) => {{
540 let v = &Json($v);
541 let d = <$ty>::deserialize(v.into_deserializer()).expect("de json");
542 assert_eq!(d, $tv);
543 }};
544 }
545
546 _de_json!(
547 serde_json::json!("string"),
548 String,
549 "\"string\"".to_string()
550 );
551
552 #[derive(Debug, PartialEq, Eq, Deserialize)]
553 struct Obj {
554 name: String,
555 }
556 _de_json!(
557 serde_json::json!({ "name": "string" }),
558 Obj,
559 Obj {
560 name: "string".to_string()
561 }
562 );
563 }
564
565 #[test]
566 fn de_newtype_struct() {
567 use serde_json::json;
568 use Value::*;
569
570 macro_rules! _de_ty {
571 ($v:expr, $ty:ty, $tv:expr) => {{
572 let d = <$ty>::deserialize((&$v).into_deserializer()).expect("de type");
573 assert_eq!(d, $tv);
574 }};
575 }
576 #[derive(Debug, PartialEq, Eq, Deserialize)]
577 struct JsonStr(String);
578 _de_ty!(
579 Json(json!("string")),
580 JsonStr,
581 JsonStr("string".to_string())
582 );
583
584 #[derive(Debug, PartialEq, Eq, Deserialize)]
585 struct Primi<T>(T);
586 _de_ty!(Json(json!(1)), Primi<i32>, Primi(1));
587 _de_ty!(TinyInt(1), Primi<i8>, Primi(1));
588 _de_ty!(SmallInt(1), Primi<i64>, Primi(1));
589 _de_ty!(Int(1), Primi<i64>, Primi(1));
590 _de_ty!(BigInt(1), Primi<i64>, Primi(1));
591
592 macro_rules! _de_prim {
593 ($v:ident, $ty:ty, $inner:literal) => {
594 log::trace!(
595 "ty: {}, prim: {}",
596 stringify!($v),
597 std::any::type_name::<$ty>()
598 );
599 _de_ty!($v($inner), Primi<$ty>, Primi($inner));
600 };
601 }
602
603 macro_rules! _de_prim_cross {
604 ($($vty:ident) +, $tt:ty) => {
605 $(
606 _de_prim!($vty, $tt, 1);
607 )*
608 };
609 ($($ty:ty) +) => {
610 $(
611 _de_prim_cross!(TinyInt SmallInt Int BigInt UTinyInt USmallInt UInt UBigInt, $ty);
612 )*
613 };
614 () => {
615 _de_prim_cross!(i8 i16 i32 i64 u8 u16 u32 u64);
616 };
617 }
618 _de_prim_cross!();
619 }
620}