1use super::super::*;
2use super::*;
3use serde::{
4 de::{self, DeserializeSeed, IntoDeserializer, Visitor},
5 forward_to_deserialize_any,
6};
7
8impl<'b, 'de: 'b> serde::de::EnumAccess<'de> for BorrowedValue<'b> {
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 d = self.strict_as_str().into_deserializer();
18 seed.deserialize(d).map(|v| (v, UnitOnly))
19 }
20}
21
22#[derive(Debug, Clone)]
23struct EnumTimestampDeserializer<'b> {
24 value: BorrowedValue<'b>,
25}
26
27#[derive(Debug, Clone)]
28struct EnumValueDeserializer<'b> {
29 value: BorrowedValue<'b>,
30}
31
32impl<'de, 'b: 'de> serde::de::EnumAccess<'de> for EnumValueDeserializer<'b> {
33 type Error = Error;
34
35 type Variant = Self;
36
37 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
38 where
39 V: DeserializeSeed<'de>,
40 {
41 return seed
42 .deserialize(self.value.ty().as_variant_str().into_deserializer())
43 .map(|v| (v, self));
44 }
45}
46
47impl<'de, 'b: 'de> de::VariantAccess<'de> for EnumValueDeserializer<'b> {
48 type Error = Error;
49
50 fn unit_variant(self) -> Result<(), Self::Error> {
51 Ok(())
52 }
53
54 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
55 where
56 T: DeserializeSeed<'de>,
57 {
58 seed.deserialize(self.value)
59 }
60
61 fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
62 where
63 V: Visitor<'de>,
64 {
65 todo!()
66 }
67
68 fn struct_variant<V>(
69 self,
70 _fields: &'static [&'static str],
71 _visitor: V,
72 ) -> Result<V::Value, Self::Error>
73 where
74 V: Visitor<'de>,
75 {
76 todo!()
77 }
78}
79
80impl<'b, 'de> serde::de::EnumAccess<'de> for EnumTimestampDeserializer<'b> {
81 type Error = Error;
82
83 type Variant = VariantTimestampDeserializer;
84
85 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
86 where
87 V: de::DeserializeSeed<'de>,
88 {
89 match &self.value {
93 BorrowedValue::Timestamp(Timestamp::Microseconds(v)) => Ok((
94 seed.deserialize("Microseconds".into_deserializer())?,
95 VariantTimestampDeserializer { value: *v },
96 )),
97 BorrowedValue::Timestamp(Timestamp::Milliseconds(v)) => Ok((
98 seed.deserialize("Milliseconds".into_deserializer())?,
99 VariantTimestampDeserializer { value: *v },
100 )),
101 BorrowedValue::Timestamp(Timestamp::Nanoseconds(v)) => Ok((
102 seed.deserialize("Nanoseconds".into_deserializer())?,
103 VariantTimestampDeserializer { value: *v },
104 )),
105 _ => todo!(),
106 }
107 }
108}
109
110impl<'de, 'b: 'de> serde::de::Deserializer<'de> for BorrowedValue<'de> {
111 type Error = Error;
112
113 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
114 where
115 V: serde::de::Visitor<'de>,
116 {
117 use BorrowedValue::*;
118 match self {
120 Null(_) => visitor.visit_none(),
121 Bool(v) => visitor.visit_bool(v),
122 TinyInt(v) => visitor.visit_i8(v),
123 SmallInt(v) => visitor.visit_i16(v),
124 Int(v) => visitor.visit_i32(v),
125 BigInt(v) => visitor.visit_i64(v),
126 UTinyInt(v) => visitor.visit_u8(v),
127 USmallInt(v) => visitor.visit_u16(v),
128 UInt(v) => visitor.visit_u32(v),
129 UBigInt(v) => visitor.visit_u64(v),
130 Float(v) => visitor.visit_f32(v),
131 Double(v) => visitor.visit_f64(v),
132 VarChar(v) => visitor.visit_borrowed_str(v),
133 NChar(v) => match v {
134 Cow::Borrowed(v) => visitor.visit_borrowed_str(v),
135 Cow::Owned(v) => visitor.visit_string(v),
136 },
137 Json(v) => match v {
138 Cow::Borrowed(v) => serde_json::Deserializer::from_slice(v)
139 .deserialize_any(visitor)
140 .map_err(<Self::Error as de::Error>::custom),
141 Cow::Owned(v) => serde_json::from_slice::<serde_json::Value>(&v)
142 .map_err(<Self::Error as de::Error>::custom)?
143 .into_deserializer()
144 .deserialize_any(visitor)
145 .map_err(<Self::Error as de::Error>::custom),
146 },
147 Timestamp(v) => visitor.visit_i64(v.as_raw_i64()),
148 Blob(v) | MediumBlob(v) => visitor.visit_borrowed_bytes(v),
149 VarBinary(v) | Geometry(v) => match v {
150 Cow::Borrowed(v) => visitor.visit_borrowed_bytes(v),
151 Cow::Owned(v) => visitor.visit_bytes(v.as_slice()),
152 },
153 _ => Err(<Self::Error as de::Error>::custom(
154 "un supported type to deserialize",
155 )),
156 }
157 }
158
159 forward_to_deserialize_any! {bool i8 u8 i16 u16 i32 u32 i64 u64 f32 f64 char}
160
161 forward_to_deserialize_any! {
162 bytes byte_buf
164 tuple identifier
165 }
166
167 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
168 where
169 V: serde::de::Visitor<'de>,
170 {
171 use BorrowedValue::*;
172 match self {
173 Null(_) => visitor.visit_borrowed_str(""), Bool(v) => visitor.visit_string(format!("{v}")),
175 TinyInt(v) => visitor.visit_string(format!("{v}")),
176 SmallInt(v) => visitor.visit_string(format!("{v}")),
177 Int(v) => visitor.visit_string(format!("{v}")),
178 BigInt(v) => visitor.visit_string(format!("{v}")),
179 UTinyInt(v) => visitor.visit_string(format!("{v}")),
180 USmallInt(v) => visitor.visit_string(format!("{v}")),
181 UInt(v) => visitor.visit_string(format!("{v}")),
182 UBigInt(v) => visitor.visit_string(format!("{v}")),
183 Float(v) => visitor.visit_string(format!("{v}")),
184 Double(v) => visitor.visit_string(format!("{v}")),
185 Json(v) => match v {
186 Cow::Borrowed(v) => std::str::from_utf8(v)
187 .map_err(<Self::Error as serde::de::Error>::custom)
188 .and_then(|s| visitor.visit_borrowed_str(s)),
189 Cow::Owned(v) => String::from_utf8(v)
190 .map_err(<Self::Error as serde::de::Error>::custom)
191 .and_then(|s| visitor.visit_string(s)),
192 },
193 VarChar(v) => visitor.visit_borrowed_str(v),
194 NChar(v) => match v {
195 Cow::Borrowed(v) => visitor.visit_borrowed_str(v),
196 Cow::Owned(v) => visitor.visit_str(&v),
197 },
198 Timestamp(v) => visitor.visit_string(v.to_datetime_with_tz().to_rfc3339()),
199 _ => Err(<Self::Error as de::Error>::custom(
200 "unsupported type to deserialize",
201 )),
202 }
203 }
204
205 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
206 where
207 V: serde::de::Visitor<'de>,
208 {
209 self.deserialize_str(visitor)
210 }
211
212 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
213 where
214 V: serde::de::Visitor<'de>,
215 {
216 if self.is_null() {
217 visitor.visit_none()
218 } else {
219 visitor.visit_some(self)
220 }
221 }
222
223 fn deserialize_newtype_struct<V>(
224 self,
225 _name: &'static str,
226 visitor: V,
227 ) -> Result<V::Value, Self::Error>
228 where
229 V: Visitor<'de>,
230 {
231 use BorrowedValue::*;
232 macro_rules! _v_ {
233 ($v:expr) => {
234 visitor.visit_newtype_struct($v.into_deserializer())
235 };
236 }
237 match self {
239 Null(_) => visitor.visit_none(),
240 Bool(v) => _v_!(v),
241 TinyInt(v) => _v_!(v),
242 SmallInt(v) => _v_!(v),
243 Int(v) => _v_!(v),
244 BigInt(v) => _v_!(v),
245 UTinyInt(v) => _v_!(v),
246 USmallInt(v) => _v_!(v),
247 UInt(v) => _v_!(v),
248 UBigInt(v) => _v_!(v),
249 Float(v) => _v_!(v),
250 Double(v) => _v_!(v),
251 VarChar(v) => _v_!(v),
252 NChar(v) => _v_!(v),
253 Json(v) => match v {
254 Cow::Borrowed(v) => serde_json::Deserializer::from_slice(v)
255 .deserialize_newtype_struct(_name, visitor)
256 .map_err(<Self::Error as de::Error>::custom),
257 Cow::Owned(v) => serde_json::from_slice::<serde_json::Value>(&v)
258 .map_err(<Self::Error as de::Error>::custom)?
259 .into_deserializer()
260 .deserialize_newtype_struct(_name, visitor)
261 .map_err(<Self::Error as de::Error>::custom),
262 },
263 Timestamp(v) => visitor.visit_i64(v.as_raw_i64()),
264 Blob(v) | MediumBlob(v) => visitor.visit_borrowed_bytes(v),
265 VarBinary(v) | Geometry(v) => match v {
266 Cow::Borrowed(v) => visitor.visit_borrowed_bytes(v),
267 Cow::Owned(v) => visitor.visit_bytes(v.as_slice()),
268 },
269 _ => Err(<Self::Error as de::Error>::custom(
270 "un supported type to deserialize",
271 )),
272 }
273 }
274
275 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
276 where
277 V: serde::de::Visitor<'de>,
278 {
279 self.deserialize_any(visitor)
280 }
281
282 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
283 where
284 V: serde::de::Visitor<'de>,
285 {
286 use BorrowedValue::*;
287 match self {
288 Null(_) => Vec::<u8>::new()
289 .into_deserializer()
290 .deserialize_seq(visitor),
291 Json(v) => v.to_vec().into_deserializer().deserialize_seq(visitor),
292 Timestamp(_) => todo!(),
293 VarChar(v) => v
294 .as_bytes()
295 .to_vec()
296 .into_deserializer()
297 .deserialize_seq(visitor),
298 NChar(v) => v
299 .as_bytes()
300 .to_vec()
301 .into_deserializer()
302 .deserialize_seq(visitor),
303 Blob(v) | MediumBlob(v) => v.to_vec().into_deserializer().deserialize_seq(visitor),
304 _ => todo!(),
305 }
306 }
307
308 fn deserialize_enum<V>(
309 self,
310 name: &'static str,
311 variants: &'static [&'static str],
312 visitor: V,
313 ) -> Result<V::Value, Self::Error>
314 where
315 V: Visitor<'de>,
316 {
317 if name == "Timestamp" && variants == TIMESTAMP_VARIANTS {
318 return visitor.visit_enum(EnumTimestampDeserializer { value: self });
319 }
320 if name == "Value" && variants == VALUE_VARIANTS {
321 return visitor.visit_enum(EnumValueDeserializer {
322 value: self,
324 });
325 }
326
327 visitor.visit_enum(self)
328 }
329
330 fn deserialize_struct<V>(
331 self,
332 name: &'static str,
333 fields: &'static [&'static str],
334 visitor: V,
335 ) -> Result<V::Value, Self::Error>
336 where
337 V: Visitor<'de>,
338 {
339 match self {
340 BorrowedValue::Json(v) => match v {
341 Cow::Borrowed(v) => serde_json::Deserializer::from_slice(v)
342 .deserialize_struct(name, fields, visitor)
343 .map_err(<Self::Error as serde::de::Error>::custom),
344 Cow::Owned(v) => serde_json::from_slice::<serde_json::Value>(&v)
345 .map_err(<Self::Error as de::Error>::custom)?
346 .into_deserializer()
347 .deserialize_struct(name, fields, visitor)
348 .map_err(<Self::Error as de::Error>::custom),
349 },
350 _ => self.deserialize_any(visitor),
351 }
352 }
353
354 fn deserialize_tuple_struct<V>(
355 self,
356 name: &'static str,
357 len: usize,
358 visitor: V,
359 ) -> Result<V::Value, Self::Error>
360 where
361 V: Visitor<'de>,
362 {
363 match self {
364 BorrowedValue::Json(v) => match v {
365 Cow::Borrowed(v) => serde_json::Deserializer::from_slice(v)
366 .deserialize_tuple_struct(name, len, visitor)
367 .map_err(<Self::Error as serde::de::Error>::custom),
368 Cow::Owned(v) => serde_json::from_slice::<serde_json::Value>(&v)
369 .map_err(<Self::Error as de::Error>::custom)?
370 .into_deserializer()
371 .deserialize_tuple_struct(name, len, visitor)
372 .map_err(<Self::Error as de::Error>::custom),
373 },
374 _ => self.deserialize_any(visitor),
375 }
376 }
377
378 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
391 where
392 V: Visitor<'de>,
393 {
394 visitor.visit_unit()
395 }
396
397 fn deserialize_unit_struct<V>(
398 self,
399 _: &'static str,
400 visitor: V,
401 ) -> Result<V::Value, Self::Error>
402 where
403 V: Visitor<'de>,
404 {
405 visitor.visit_unit()
406 }
407
408 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
421 where
422 V: Visitor<'de>,
423 {
424 visitor.visit_unit()
425 }
426}
427
428impl<'de> serde::de::IntoDeserializer<'de, Error> for BorrowedValue<'de> {
429 type Deserializer = Self;
430
431 fn into_deserializer(self) -> Self::Deserializer {
432 self
433 }
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439
440 use serde_json::json;
441
442 #[test]
443 fn de_value_as_inner() {
444 use BorrowedValue::*;
445 macro_rules! _de_value {
446 ($($v:expr, $ty:ty, $tv:expr) *) => {
447 $(
448 {
449 let d = <$ty>::deserialize($v.into_deserializer()).expect("");
450 assert_eq!(d, $tv);
451 }
452 )*
453 }
454 }
455
456 _de_value!(
457 Null(Ty::UTinyInt), Option<u8>, None
458 TinyInt(-1), i8, -1
459 SmallInt(-1), i16, -1
460 Int(0x0fff_ffff), i32, 0x0fff_ffff
461 BigInt(0xffffffff), i64, 0xffffffff
462 UTinyInt(0xff), u8, 0xff
463 USmallInt(0xffff), u16, 0xffff
464 UInt(0x_ffff_ffff), u32, 0x_ffff_ffff
465 UBigInt(0x_ffff_ffff_ffff_ffff), u64, 0x_ffff_ffff_ffff_ffff
466 Float(1.0), f32, 1.0
467 Double(f64::MAX), f64, f64::MAX
468 VarChar(""), String, "".to_string()
469 NChar("".into()), String, "".to_string()
470 Timestamp(crate::Timestamp::Milliseconds(1)), crate::Timestamp, crate::Timestamp::Milliseconds(1)
471 Blob(&[0, 1,2]), Vec<u8>, vec![0, 1, 2]
472 MediumBlob(&[0, 1,2]), Vec<u8>, vec![0, 1, 2]
473 );
474 }
475
476 #[test]
477 fn de_borrowed_str() {
478 use serde_json::json;
479 use BorrowedValue::*;
480
481 macro_rules! _de_str {
482 ($v:expr, is_err) => {
483 assert!(<&str>::deserialize(($v).into_deserializer()).is_err());
484 };
485 ($v:expr, $tv:expr) => {
486 assert_eq!(<&str>::deserialize(($v).into_deserializer()).expect("str"), $tv);
487 };
488 ($($v:expr, $c:ident) *) => {
489 $(
490 {
491 assert!(<&str>::deserialize(($v).into_deserializer()).$c());
492 }
493 )*
494 };
495 ($($v2:expr, is_err) +; $($v:expr, $tv:expr) + ) => {
496 $(
497 _de_str!($v2, is_err);
498 )*
499 $(
500 _de_str!($v, $tv);
501 )*
502 }
503 }
504 _de_str! {
505 TinyInt(-1), is_err
506 SmallInt(-1), is_err
507 Int(-1), is_err
508 BigInt(-1), is_err
509 UTinyInt(1), is_err
510 USmallInt(1), is_err
511 UInt(1), is_err
512 UBigInt(1), is_err
513 Json(json!({ "name": "abc"}).to_string().into_bytes().into()), is_err
514 Json(json!(1).to_string().into_bytes().into()), is_err
515 Json(json!(null).to_string().into_bytes().into()), is_err
516 Json(json!("abc").to_string().into_bytes().into()), is_err
517 Timestamp(crate::Timestamp::Milliseconds(0)), is_err
518 ;
519 Null(Ty::VarChar), ""
520 VarChar("String"), "String"
521 VarChar("你好,世界"), "你好,世界"
522 };
523 }
524 #[test]
525 fn de_string() {
526 use serde_json::json;
527 use BorrowedValue::*;
528
529 macro_rules! _de_str {
530 ($v:expr, is_err) => {
531 assert!(String::deserialize(($v).into_deserializer()).is_err());
532 };
533 ($v:expr, $tv:expr) => {
534 assert_eq!(String::deserialize(($v).into_deserializer()).expect("str"), $tv);
535 };
536 ($($v:expr, $tv:expr) *) => {
537 $(_de_str!($v, $tv);)*
538 };
539 ($($v2:expr, is_err) *; $($v:expr, $tv:expr) * ) => {
540 $(
541 _de_str!($v2, is_err);
542 )*
543 $(
544 _de_str!($v, $tv);
545 )*
546 }
547 }
548 _de_str! {
549
550 Null(Ty::VarChar), ""
561 TinyInt(-1), "-1"
562 Timestamp(crate::Timestamp::Milliseconds(0)), "1970-01-01T08:00:00+08:00"
563 VarChar("String"), "String"
564 VarChar("你好,世界"), "你好,世界"
565 Json(json!("abc").to_string().into_bytes().into()), json!("abc").to_string()
566 Json(json!({ "name": "abc"}).to_string().into_bytes().into()), json!({ "name": "abc"}).to_string()
567 Json(json!(1).to_string().into_bytes().into()), json!(1).to_string()
568 Json(json!(null).to_string().into_bytes().into()), json!(null).to_string()
569 };
570 }
571
572 #[test]
573 fn de_json() {
574 use serde_json::json;
575 use BorrowedValue::*;
576
577 macro_rules! _de_json {
578 ($v:expr, $ty:ty, $tv:expr) => {{
579 let d = <$ty>::deserialize(
580 Json($v.to_string().into_bytes().into()).into_deserializer(),
581 )
582 .expect("de json");
583 assert_eq!(d, $tv);
584 }};
585 }
586
587 _de_json!(json!("string"), String, json!("string").to_string());
588
589 #[derive(Debug, PartialEq, Eq, Deserialize)]
590 struct Obj {
591 name: String,
592 }
593 _de_json!(
594 json!({ "name": "string" }),
595 Obj,
596 Obj {
597 name: "string".to_string()
598 }
599 );
600
601 #[derive(Debug, PartialEq, Eq, Deserialize)]
602 struct JsonStr(String);
603 _de_json!(json!("string"), JsonStr, JsonStr("string".to_string()));
604 }
605
606 #[test]
607 fn de_newtype_struct() {
608 use serde_json::json;
609 use BorrowedValue::*;
610 macro_rules! _de_ty {
611 ($v:expr, $ty:ty, $tv:expr) => {{
612 let d = <$ty>::deserialize($v.into_deserializer()).expect("de type");
613 assert_eq!(d, $tv);
614 }};
615 }
616 #[derive(Debug, PartialEq, Eq, Deserialize)]
617 struct JsonStr(String);
618 _de_ty!(
619 Json(json!("string").to_string().into_bytes().into()),
620 JsonStr,
621 JsonStr("string".to_string())
622 );
623
624 #[derive(Debug, PartialEq, Eq, Deserialize)]
625 struct Primi<T>(T);
626 _de_ty!(
627 Json(json!(1).to_string().into_bytes().into()),
628 Primi<i32>,
629 Primi(1)
630 );
631 _de_ty!(TinyInt(1), Primi<i8>, Primi(1));
632 _de_ty!(SmallInt(1), Primi<i64>, Primi(1));
633 _de_ty!(Int(1), Primi<i64>, Primi(1));
634 _de_ty!(BigInt(1), Primi<i64>, Primi(1));
635
636 macro_rules! _de_prim {
637 ($v:ident, $ty:ty, $inner:literal) => {
638 println!(
639 "ty: {}, prim: {}",
640 stringify!($v),
641 std::any::type_name::<$ty>()
642 );
643 _de_ty!($v($inner), Primi<$ty>, Primi($inner));
644 };
645 }
646
647 macro_rules! _de_prim_cross {
648 ($($vty:ident) +, $tt:ty) => {
649 $(
650 _de_prim!($vty, $tt, 1);
651 )*
652 };
653 ($($ty:ty) +) => {
654 $(
655 _de_prim_cross!(TinyInt SmallInt Int BigInt UTinyInt USmallInt UInt UBigInt, $ty);
656 )*
657 };
658 () => {
659 _de_prim_cross!(i8 i16 i32 i64 u8 u16 u32 u64);
660 };
661 }
662 _de_prim_cross!();
663 }
664}