1#[cfg(feature = "unstable-time")]
16use crate::value::SPANNER_DATE_FORMAT;
17use crate::value::SPANNER_TIMESTAMP_FORMAT;
18pub use crate::value::Value;
19use base64::Engine;
20use base64::prelude::BASE64_STANDARD;
21use bytes::Bytes;
22use google_cloud_type::model::Date;
23use prost_types::Value as ProtoValue;
24use prost_types::value::Kind as ProtoKind;
25use rust_decimal::Decimal;
26use serde_json::Value as JsonValue;
27use std::time::SystemTime;
28#[cfg(feature = "unstable-time")]
29use time::Date as TimeDate;
30use time::OffsetDateTime;
31use time::UtcOffset;
32use uuid::Uuid;
33use wkt::Timestamp;
34
35pub trait ToValue {
44 fn to_value(&self) -> Value;
49}
50
51impl<T> ToValue for Option<T>
52where
53 T: ToValue,
54{
55 fn to_value(&self) -> Value {
56 match self {
57 Some(v) => v.to_value(),
58 None => Value::null(),
59 }
60 }
61}
62
63impl<T: Into<Value>> From<Option<T>> for Value {
65 fn from(opt: Option<T>) -> Self {
66 match opt {
67 Some(v) => v.into(),
68 None => Value::null(),
69 }
70 }
71}
72
73impl ToValue for () {
74 fn to_value(&self) -> Value {
75 Value::null()
76 }
77}
78
79impl From<()> for Value {
80 fn from(_: ()) -> Self {
81 Value::null()
82 }
83}
84
85impl ToValue for Value {
86 fn to_value(&self) -> Value {
87 self.clone()
88 }
89}
90
91impl ToValue for String {
92 fn to_value(&self) -> Value {
93 self.as_str().to_value()
94 }
95}
96
97impl From<String> for Value {
98 fn from(s: String) -> Self {
99 Value(ProtoValue {
100 kind: Some(prost_types::value::Kind::StringValue(s)),
101 })
102 }
103}
104
105impl ToValue for str {
106 fn to_value(&self) -> Value {
107 Value(ProtoValue {
108 kind: Some(prost_types::value::Kind::StringValue(self.to_string())),
109 })
110 }
111}
112
113impl ToValue for i64 {
114 fn to_value(&self) -> Value {
115 (*self).into()
116 }
117}
118
119impl From<i64> for Value {
120 fn from(i: i64) -> Self {
121 Value(ProtoValue {
122 kind: Some(prost_types::value::Kind::StringValue(i.to_string())),
123 })
124 }
125}
126
127impl ToValue for i32 {
128 fn to_value(&self) -> Value {
129 (*self).into()
130 }
131}
132
133impl From<i32> for Value {
134 fn from(i: i32) -> Self {
135 Value(ProtoValue {
136 kind: Some(prost_types::value::Kind::StringValue(i.to_string())),
137 })
138 }
139}
140
141impl ToValue for Decimal {
142 fn to_value(&self) -> Value {
143 (*self).into()
144 }
145}
146
147impl From<Decimal> for Value {
148 fn from(d: Decimal) -> Self {
149 Value(ProtoValue {
150 kind: Some(prost_types::value::Kind::StringValue(d.to_string())),
151 })
152 }
153}
154
155const SENTINEL_MAX_TIMESTAMP: &str = "999999-12-31T23:59:59Z";
156const SENTINEL_MIN_TIMESTAMP: &str = "-999999-01-01T00:00:00Z";
157
158fn out_of_range_sentinel(is_non_negative: bool) -> &'static str {
165 if is_non_negative {
166 SENTINEL_MAX_TIMESTAMP
167 } else {
168 SENTINEL_MIN_TIMESTAMP
169 }
170}
171
172fn format_offset_date_time(date_time: OffsetDateTime) -> String {
180 date_time
181 .checked_to_offset(UtcOffset::UTC)
182 .and_then(|utc_date_time| utc_date_time.format(SPANNER_TIMESTAMP_FORMAT).ok())
183 .unwrap_or_else(|| out_of_range_sentinel(date_time.year() >= 0).to_string())
184}
185
186fn format_date(year: i32, month: i32, day: i32) -> String {
190 if year < 0 {
191 format!("-{:04}-{:02}-{:02}", year.unsigned_abs(), month, day)
192 } else {
193 format!("{:04}-{:02}-{:02}", year, month, day)
194 }
195}
196
197impl ToValue for SystemTime {
198 fn to_value(&self) -> Value {
199 (*self).into()
200 }
201}
202
203impl From<SystemTime> for Value {
204 fn from(system_time: SystemTime) -> Self {
205 let nanos = match system_time.duration_since(SystemTime::UNIX_EPOCH) {
207 Ok(duration) => i128::try_from(duration.as_nanos()).ok(),
208 Err(error) => i128::try_from(error.duration().as_nanos())
209 .ok()
210 .map(|nanos| -nanos),
211 };
212
213 let string_value = nanos
218 .and_then(|nanos| OffsetDateTime::from_unix_timestamp_nanos(nanos).ok())
219 .map(format_offset_date_time)
220 .unwrap_or_else(|| {
221 out_of_range_sentinel(system_time >= SystemTime::UNIX_EPOCH).to_string()
222 });
223
224 Value(ProtoValue {
225 kind: Some(ProtoKind::StringValue(string_value)),
226 })
227 }
228}
229
230#[cfg(feature = "unstable-time")]
231#[cfg_attr(docsrs, doc(cfg(feature = "unstable-time")))]
232impl ToValue for OffsetDateTime {
233 fn to_value(&self) -> Value {
234 (*self).into()
235 }
236}
237
238#[cfg(feature = "unstable-time")]
239#[cfg_attr(docsrs, doc(cfg(feature = "unstable-time")))]
240impl From<OffsetDateTime> for Value {
241 fn from(date_time: OffsetDateTime) -> Self {
242 Value(ProtoValue {
243 kind: Some(ProtoKind::StringValue(format_offset_date_time(date_time))),
244 })
245 }
246}
247
248impl ToValue for Timestamp {
249 fn to_value(&self) -> Value {
250 (*self).into()
251 }
252}
253
254impl From<Timestamp> for Value {
258 fn from(timestamp: Timestamp) -> Self {
259 let nanos = timestamp.seconds() as i128 * 1_000_000_000 + timestamp.nanos() as i128;
260 let string_value = OffsetDateTime::from_unix_timestamp_nanos(nanos)
261 .map(format_offset_date_time)
262 .unwrap_or_else(|_| out_of_range_sentinel(timestamp.seconds() >= 0).to_string());
263 Value(ProtoValue {
264 kind: Some(ProtoKind::StringValue(string_value)),
265 })
266 }
267}
268
269impl ToValue for Date {
270 fn to_value(&self) -> Value {
271 Value(ProtoValue {
272 kind: Some(ProtoKind::StringValue(format_date(
273 self.year, self.month, self.day,
274 ))),
275 })
276 }
277}
278
279impl From<Date> for Value {
280 fn from(date: Date) -> Self {
281 date.to_value()
282 }
283}
284
285#[cfg(feature = "unstable-time")]
286#[cfg_attr(docsrs, doc(cfg(feature = "unstable-time")))]
287impl ToValue for TimeDate {
288 fn to_value(&self) -> Value {
289 (*self).into()
290 }
291}
292
293#[cfg(feature = "unstable-time")]
294#[cfg_attr(docsrs, doc(cfg(feature = "unstable-time")))]
295impl From<TimeDate> for Value {
296 fn from(date: TimeDate) -> Self {
297 let string_value = date
299 .format(SPANNER_DATE_FORMAT)
300 .unwrap_or_else(|_| format_date(date.year(), date.month() as i32, date.day() as i32));
301 Value(ProtoValue {
302 kind: Some(ProtoKind::StringValue(string_value)),
303 })
304 }
305}
306
307impl ToValue for bool {
308 fn to_value(&self) -> Value {
309 (*self).into()
310 }
311}
312
313impl From<bool> for Value {
314 fn from(b: bool) -> Self {
315 Value(ProtoValue {
316 kind: Some(prost_types::value::Kind::BoolValue(b)),
317 })
318 }
319}
320
321impl ToValue for f64 {
322 fn to_value(&self) -> Value {
323 (*self).into()
324 }
325}
326
327impl From<f64> for Value {
328 fn from(float_value: f64) -> Self {
329 let kind = if float_value.is_finite() {
330 prost_types::value::Kind::NumberValue(float_value)
331 } else if float_value.is_nan() {
332 prost_types::value::Kind::StringValue("NaN".to_string())
333 } else if float_value.is_sign_positive() {
334 prost_types::value::Kind::StringValue("Infinity".to_string())
335 } else {
336 prost_types::value::Kind::StringValue("-Infinity".to_string())
337 };
338 Value(ProtoValue { kind: Some(kind) })
339 }
340}
341
342impl ToValue for f32 {
343 fn to_value(&self) -> Value {
344 (*self).into()
345 }
346}
347
348impl From<f32> for Value {
349 fn from(float_value: f32) -> Self {
350 let kind = if float_value.is_finite() {
351 prost_types::value::Kind::NumberValue(float_value as f64)
352 } else if float_value.is_nan() {
353 prost_types::value::Kind::StringValue("NaN".to_string())
354 } else if float_value.is_sign_positive() {
355 prost_types::value::Kind::StringValue("Infinity".to_string())
356 } else {
357 prost_types::value::Kind::StringValue("-Infinity".to_string())
358 };
359 Value(ProtoValue { kind: Some(kind) })
360 }
361}
362
363impl ToValue for Vec<u8> {
364 fn to_value(&self) -> Value {
365 self.as_slice().to_value()
366 }
367}
368
369impl From<Vec<u8>> for Value {
370 fn from(v: Vec<u8>) -> Self {
371 Value(ProtoValue {
372 kind: Some(prost_types::value::Kind::StringValue(
373 BASE64_STANDARD.encode(v),
374 )),
375 })
376 }
377}
378
379impl ToValue for [u8] {
380 fn to_value(&self) -> Value {
381 Value(ProtoValue {
382 kind: Some(prost_types::value::Kind::StringValue(
383 BASE64_STANDARD.encode(self),
384 )),
385 })
386 }
387}
388
389impl<const N: usize> ToValue for [u8; N] {
393 fn to_value(&self) -> Value {
394 self.as_slice().to_value()
395 }
396}
397
398impl<const N: usize> From<[u8; N]> for Value {
400 fn from(bytes_array: [u8; N]) -> Self {
401 bytes_array.as_slice().to_value()
402 }
403}
404
405impl ToValue for Bytes {
409 fn to_value(&self) -> Value {
410 (**self).to_value()
411 }
412}
413
414impl From<Bytes> for Value {
416 fn from(byte_buffer: Bytes) -> Self {
417 byte_buffer.to_value()
418 }
419}
420
421impl ToValue for Uuid {
425 fn to_value(&self) -> Value {
426 Value(ProtoValue {
427 kind: Some(ProtoKind::StringValue(self.to_string())),
428 })
429 }
430}
431
432impl From<Uuid> for Value {
434 fn from(uuid: Uuid) -> Self {
435 uuid.to_value()
436 }
437}
438
439impl ToValue for JsonValue {
453 fn to_value(&self) -> Value {
454 Value(ProtoValue {
455 kind: Some(ProtoKind::StringValue(self.to_string())),
456 })
457 }
458}
459
460impl From<JsonValue> for Value {
466 fn from(json: JsonValue) -> Self {
467 json.to_value()
468 }
469}
470
471impl<T> ToValue for Vec<T>
472where
473 T: ToValue,
474{
475 fn to_value(&self) -> Value {
476 Value(ProtoValue {
477 kind: Some(prost_types::value::Kind::ListValue(
478 prost_types::ListValue {
479 values: self.iter().map(|v| v.to_value().0).collect(),
480 },
481 )),
482 })
483 }
484}
485
486impl<T: Into<Value>> From<Vec<T>> for Value {
488 fn from(v: Vec<T>) -> Self {
489 Value(ProtoValue {
490 kind: Some(prost_types::value::Kind::ListValue(
491 prost_types::ListValue {
492 values: v.into_iter().map(|item| item.into().0).collect(),
493 },
494 )),
495 })
496 }
497}
498
499impl<T: ToValue + ?Sized> ToValue for &T {
501 fn to_value(&self) -> Value {
502 T::to_value(*self)
503 }
504}
505
506impl<T: ToValue + ?Sized> ToValue for &mut T {
508 fn to_value(&self) -> Value {
509 T::to_value(*self)
510 }
511}
512
513impl<T: ToValue + ?Sized> From<&T> for Value {
516 fn from(reference: &T) -> Self {
517 reference.to_value()
518 }
519}
520
521impl<T: ToValue + ?Sized> From<&mut T> for Value {
524 fn from(reference: &mut T) -> Self {
525 reference.to_value()
526 }
527}
528
529#[cfg(test)]
530mod tests {
531 use super::*;
532 use crate::from_value::{ConvertError, FromValue};
533 use crate::key;
534 use crate::mutation::Mutation;
535 use crate::statement::Statement;
536 use crate::types;
537 use crate::value::Kind;
538 use serde_json::json;
539 use static_assertions::assert_impl_all;
540 use std::str::FromStr;
541 use std::time::Duration;
542 #[cfg(feature = "unstable-time")]
543 use time::Month;
544 #[cfg(feature = "unstable-time")]
545 use time::format_description::well_known::Rfc3339;
546
547 #[test]
548 fn null_value_conversions() {
549 let null_value = Value::null();
550 assert_eq!(null_value.kind(), Kind::Null);
551
552 let unit_value = ().to_value();
553 assert_eq!(unit_value, null_value);
554
555 let unit_ref_value: Value = (&()).into();
556 assert_eq!(unit_ref_value, null_value);
557
558 let some_unit_value = Some(()).to_value();
559 assert_eq!(some_unit_value, null_value);
560
561 let opt_unit_value: Value = None::<()>.into();
562 assert_eq!(opt_unit_value, null_value);
563
564 let opt_value: Value = None::<Value>.into();
565 assert_eq!(opt_value, null_value);
566
567 let opt_i64_value: Value = None::<i64>.into();
568 assert_eq!(opt_i64_value, null_value);
569 }
570
571 #[test]
572 fn from_value_conversions() {
573 let value: Value = "hello".to_string().into();
574 assert_eq!(value.as_str(), Some("hello"));
575
576 let value: Value = "world".into();
577 assert_eq!(value.as_str(), Some("world"));
578
579 let value: Value = 42i64.into();
580 assert_eq!(value.as_str(), Some("42"));
581
582 let value: Value = 42i32.into();
583 assert_eq!(value.as_str(), Some("42"));
584
585 let value: Value = true.into();
586 assert_eq!(value.as_bool(), Some(true));
587
588 let value: Value = 42.5f64.into();
589 assert_eq!(value.as_f64(), Some(42.5));
590
591 let value: Value = 42.5f32.into();
592 assert_eq!(value.as_f64(), Some(42.5));
593
594 let value: Value = vec![1u8, 2, 3].into();
595 assert_eq!(value.as_str(), Some("AQID"));
596
597 let value: Value = (&[1u8, 2, 3][..]).into();
598 assert_eq!(value.as_str(), Some("AQID"));
599
600 let decimal = Decimal::from_str("123.456").expect("valid decimal");
601 let value: Value = decimal.into();
602 assert_eq!(value.as_str(), Some("123.456"));
603
604 #[cfg(feature = "unstable-time")]
605 {
606 let date_time = OffsetDateTime::parse("2023-10-27T10:00:00Z", &Rfc3339)
607 .expect("valid RFC 3339 format");
608 let value: Value = date_time.into();
609 assert_eq!(value.as_str(), Some("2023-10-27T10:00:00.000000000Z"));
610
611 let time_date = TimeDate::from_calendar_date(2023, Month::October, 27)
612 .expect("valid calendar date");
613 let value: Value = time_date.into();
614 assert_eq!(value.as_str(), Some("2023-10-27"));
615 }
616
617 let system_time = SystemTime::UNIX_EPOCH + Duration::from_secs(1698400800);
618 let value: Value = system_time.into();
619 assert_eq!(value.as_str(), Some("2023-10-27T10:00:00.000000000Z"));
620
621 let timestamp = Timestamp::clamp(1698400800, 0);
622 let value: Value = timestamp.into();
623 assert_eq!(value.as_str(), Some("2023-10-27T10:00:00.000000000Z"));
624
625 let google_date = Date::new().set_year(2023).set_month(10).set_day(27);
626 let value: Value = (&google_date).into();
627 assert_eq!(value.as_str(), Some("2023-10-27"));
628
629 let list: Value = vec![1i64, 2i64].into();
630 assert_eq!(list.kind(), Kind::List);
631 assert_eq!(list.as_list().expect("list should exist").len(), 2);
632
633 let opt_some_value: Value = Some(42i64).into();
634 assert_eq!(opt_some_value.as_str(), Some("42"));
635 let opt_none_value: Value = None::<i64>.into();
636 assert_eq!(opt_none_value.kind(), Kind::Null);
637
638 let unit_value: Value = ().into();
639 assert_eq!(unit_value.kind(), Kind::Null);
640
641 let borrowed_i64: Value = (&42i64).into();
642 assert_eq!(borrowed_i64.as_str(), Some("42"));
643 let borrowed_bool: Value = (&true).into();
644 assert_eq!(borrowed_bool.as_bool(), Some(true));
645 let borrowed_float: Value = (&42.5f64).into();
646 assert_eq!(borrowed_float.as_f64(), Some(42.5));
647 let borrowed_date: Value = google_date.into();
648 assert_eq!(borrowed_date.as_str(), Some("2023-10-27"));
649
650 let vec_opt_value: Value = vec![Some(1_i64), None].into();
651 assert_eq!(vec_opt_value.kind(), Kind::List);
652 assert_eq!(vec_opt_value.as_list().expect("list should exist").len(), 2);
653 }
654
655 #[test]
656 fn to_value_string() {
657 let value = "hello".to_string().to_value();
658 assert_eq!(value.kind(), Kind::String);
659 assert_eq!(value.as_str(), Some("hello"));
660
661 let value = "world".to_value();
662 assert_eq!(value.kind(), Kind::String);
663 assert_eq!(value.as_str(), Some("world"));
664 }
665
666 #[test]
667 fn to_value_str_trait_bound() {
668 fn bind_param<T: ToValue + ?Sized>(val: &T) -> Value {
669 val.to_value()
670 }
671
672 let value = bind_param("hello");
673 assert_eq!(value.kind(), Kind::String);
674 assert_eq!(value.as_str(), Some("hello"));
675
676 let owned: String = "hello".to_string();
677 assert_eq!(bind_param(&owned), value);
678 let borrowed: &str = &owned;
679 assert_eq!(bind_param(&borrowed), value);
680 }
681
682 #[test]
683 fn to_value_reference_types() {
684 let integer_value: i64 = 42;
685 let integer_reference: &i64 = &integer_value;
686 let integer_double_reference: &&i64 = &integer_reference;
687 assert_eq!(
688 integer_reference.to_value(),
689 Value::from(42_i64),
690 "single reference to integer must encode correctly"
691 );
692 assert_eq!(
693 integer_double_reference.to_value(),
694 Value::from(42_i64),
695 "double reference to integer must encode correctly"
696 );
697
698 let mut mutable_integer: i64 = 99;
699 let mutable_reference: &mut i64 = &mut mutable_integer;
700 assert_eq!(
701 mutable_reference.to_value(),
702 Value::from(99_i64),
703 "mutable reference to integer must encode correctly"
704 );
705
706 let string_value: String = "test".to_string();
707 let string_reference: &String = &string_value;
708 let string_double_reference: &&String = &string_reference;
709 assert_eq!(
710 string_reference.to_value(),
711 Value::from("test"),
712 "single reference to string must encode correctly"
713 );
714 assert_eq!(
715 string_double_reference.to_value(),
716 Value::from("test"),
717 "double reference to string must encode correctly"
718 );
719
720 let str_slice: &str = "slice";
721 let str_reference: &&str = &str_slice;
722 assert_eq!(
723 str_slice.to_value(),
724 Value::from("slice"),
725 "str slice must encode correctly"
726 );
727 assert_eq!(
728 str_reference.to_value(),
729 Value::from("slice"),
730 "reference to str slice must encode correctly"
731 );
732
733 let mut mutable_string: String = "mutable".to_string();
734 let mutable_str: &mut str = mutable_string.as_mut_str();
735 assert_eq!(
736 mutable_str.to_value(),
737 Value::from("mutable"),
738 "mutable str slice must encode correctly"
739 );
740
741 let mut mutable_byte_array = [1_u8, 2, 3];
742 let mutable_byte_slice: &mut [u8] = &mut mutable_byte_array;
743 assert_eq!(
744 mutable_byte_slice.to_value(),
745 Value::from(&[1_u8, 2, 3][..]),
746 "mutable byte slice must encode correctly"
747 );
748
749 let fixed_bytes_array = [10_u8, 20, 30];
750 assert_eq!(
751 fixed_bytes_array.to_value(),
752 Value::from(&[10_u8, 20, 30][..]),
753 "owned fixed-size byte array must encode correctly"
754 );
755 assert_impl_all!(&i64: ToValue);
756 assert_impl_all!(&&i64: ToValue);
757 assert_impl_all!(&mut i64: ToValue);
758 assert_impl_all!(&bool: ToValue);
759 assert_impl_all!(&f64: ToValue);
760 assert_impl_all!(&str: ToValue);
761 assert_impl_all!(&mut str: ToValue);
762 assert_impl_all!(&[u8]: ToValue);
763 assert_impl_all!(&mut [u8]: ToValue);
764 assert_impl_all!([u8; 3]: ToValue);
765 assert_impl_all!(&[u8; 3]: ToValue);
766 assert_impl_all!(&mut [u8; 3]: ToValue);
767 assert_impl_all!(&String: ToValue);
768 assert_impl_all!(&Decimal: ToValue);
769 assert_impl_all!(&Timestamp: ToValue);
770 assert_impl_all!(&Date: ToValue);
771 assert_impl_all!(&Uuid: ToValue);
772 assert_impl_all!(JsonValue: ToValue);
773 assert_impl_all!(&JsonValue: ToValue);
774 assert_impl_all!(&mut JsonValue: ToValue);
775 assert_impl_all!(Option<JsonValue>: ToValue);
776 assert_impl_all!(Option<&JsonValue>: ToValue);
777 assert_impl_all!(Vec<JsonValue>: ToValue);
778 assert_impl_all!(Vec<&JsonValue>: ToValue);
779 assert_impl_all!(&Option<i64>: ToValue);
780 assert_impl_all!(Option<&str>: ToValue);
781
782 let from_array_value: Value = fixed_bytes_array.into();
783 assert_eq!(
784 from_array_value,
785 Value::from(&[10_u8, 20, 30][..]),
786 "From<[u8; N]> for Value must encode correctly"
787 );
788
789 let from_array_ref_value = Value::from(&fixed_bytes_array);
790 assert_eq!(
791 from_array_ref_value,
792 Value::from(&[10_u8, 20, 30][..]),
793 "From<&[u8; N]> for Value must encode correctly"
794 );
795
796 let mut mutable_bytes_array = [10_u8, 20, 30];
797 let from_mut_array_value = Value::from(&mut mutable_bytes_array);
798 assert_eq!(
799 from_mut_array_value,
800 Value::from(&[10_u8, 20, 30][..]),
801 "From<&mut [u8; N]> for Value must encode correctly"
802 );
803
804 let empty_bytes_array: [u8; 0] = [];
805 assert_eq!(
806 empty_bytes_array.to_value(),
807 Value::from(&[][..]),
808 "empty fixed-size byte array must encode as empty bytes"
809 );
810
811 let mut mutable_for_from = 55_i64;
812 let from_mut_value = Value::from(&mut mutable_for_from);
813 assert_eq!(
814 from_mut_value,
815 Value::from(55_i64),
816 "From<&mut T> for Value via Value::from must encode correctly"
817 );
818
819 let optional_str_none: Option<&str> = None;
820 assert_eq!(
821 optional_str_none.to_value(),
822 Value::null(),
823 "Option<&str>::None must encode as null"
824 );
825
826 let optional_str_some: Option<&str> = Some("hello");
827 assert_eq!(
828 optional_str_some.to_value(),
829 Value::from("hello"),
830 "Option<&str>::Some must encode correctly"
831 );
832 }
833
834 #[test]
835 fn to_value_int() {
836 let value = 42i64.to_value();
837 assert_eq!(value.kind(), Kind::String);
838 assert_eq!(value.as_str(), Some("42"));
839
840 let value = 42i32.to_value();
841 assert_eq!(value.kind(), Kind::String);
842 assert_eq!(value.as_str(), Some("42"));
843 }
844
845 #[test]
846 fn to_value_float() {
847 let value = 42.5f64.to_value();
848 assert_eq!(value.kind(), Kind::Number);
849 assert_eq!(value.as_f64(), Some(42.5));
850
851 let value = 42.5f32.to_value();
852 assert_eq!(value.kind(), Kind::Number);
853 assert_eq!(value.as_f64(), Some(42.5));
854 }
855
856 #[test]
857 fn to_value_bool() {
858 let value = true.to_value();
859 assert_eq!(value.kind(), Kind::Bool);
860 assert_eq!(value.as_bool(), Some(true));
861
862 let value = false.to_value();
863 assert_eq!(value.kind(), Kind::Bool);
864 assert_eq!(value.as_bool(), Some(false));
865 }
866
867 #[test]
868 fn to_value_bytes() {
869 let bytes: Vec<u8> = vec![1, 2, 3];
870 let value = bytes.to_value();
871 assert_eq!(value.kind(), Kind::String);
872 assert_eq!(value.as_str(), Some("AQID")); let slice_value: Value = (&[1u8, 2, 3][..]).into();
875 assert_eq!(slice_value.kind(), Kind::String);
876 assert_eq!(slice_value.as_str(), Some("AQID"));
877 }
878
879 #[test]
880 fn to_value_slice_trait_bound() {
881 fn bind_param<T: ToValue + ?Sized>(val: &T) -> Value {
882 val.to_value()
883 }
884
885 let slice: &[u8] = &[1, 2, 3];
886 let value = bind_param(slice);
887 assert_eq!(value.kind(), Kind::String, "slice must serialize to string");
888 assert_eq!(value.as_str(), Some("AQID"), "expected base64 encoding");
889 }
890
891 #[test]
892 fn to_value_bytes_crate() {
893 let byte_buffer = Bytes::from_static(b"hello world");
894 let value = byte_buffer.to_value();
895 assert_eq!(value.kind(), Kind::String, "bytes must serialize to string");
896 assert_eq!(
897 value.as_str(),
898 Some("aGVsbG8gd29ybGQ="),
899 "expected base64 representation"
900 );
901
902 let into_value: Value = byte_buffer.clone().into();
903 assert_eq!(into_value, value, "Into<Value> must match to_value");
904
905 let reference_value: Value = (&byte_buffer).into();
906 assert_eq!(
907 reference_value, value,
908 "&Bytes Into<Value> must match to_value"
909 );
910 }
911
912 #[test]
913 fn to_value_uuid() {
914 let uuid_string = "123e4567-e89b-12d3-a456-426614174000";
915 let uuid = Uuid::parse_str(uuid_string).expect("valid uuid string");
916 let value = uuid.to_value();
917 assert_eq!(value.kind(), Kind::String, "uuid must serialize to string");
918 assert_eq!(
919 value.as_str(),
920 Some(uuid_string),
921 "expected uuid string representation"
922 );
923
924 let into_value: Value = uuid.into();
925 assert_eq!(into_value, value, "Into<Value> must match to_value");
926
927 let reference_value: Value = (&uuid).into();
928 assert_eq!(
929 reference_value, value,
930 "&Uuid Into<Value> must match to_value"
931 );
932 }
933
934 #[test]
935 fn to_value_decimal() {
936 let decimal = Decimal::from_str("123.456").expect("valid decimal");
937 let value = decimal.to_value();
938 assert_eq!(value.kind(), Kind::String);
939 assert_eq!(value.as_str(), Some("123.456"));
940 }
941
942 #[test]
943 fn to_value_google_date() {
944 let date = Date::new().set_year(2023).set_month(10).set_day(27);
945 let value = date.to_value();
946 assert_eq!(value.kind(), Kind::String);
947 assert_eq!(value.as_str(), Some("2023-10-27"));
948 }
949
950 #[cfg(feature = "unstable-time")]
951 #[test]
952 fn to_value_time_date() {
953 let date =
954 TimeDate::from_calendar_date(2023, Month::October, 27).expect("valid calendar date");
955 let value = date.to_value();
956 assert_eq!(value.kind(), Kind::String);
957 assert_eq!(value.as_str(), Some("2023-10-27"));
958 }
959
960 #[test]
961 fn to_value_system_time() {
962 let system_time = SystemTime::UNIX_EPOCH + Duration::from_secs(1698400800);
963 let value = system_time.to_value();
964 assert_eq!(
965 value.kind(),
966 Kind::String,
967 "expected SystemTime to encode as String"
968 );
969 assert_eq!(
970 value.as_str(),
971 Some("2023-10-27T10:00:00.000000000Z"),
972 "expected valid RFC 3339 timestamp"
973 );
974 }
975
976 #[test]
977 fn to_value_system_time_out_of_range() {
978 if let Some(extreme_future) = SystemTime::UNIX_EPOCH
980 .checked_add(Duration::from_secs(i64::MAX as u64))
981 .or_else(|| SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(300_000_000_000)))
982 {
983 let max_value = extreme_future.to_value();
984 assert_eq!(
985 max_value.kind(),
986 Kind::String,
987 "expected extreme future SystemTime to encode as String"
988 );
989 let max_str = max_value
990 .as_str()
991 .expect("expected non-empty string for extreme future SystemTime");
992 assert_eq!(
993 max_str, "999999-12-31T23:59:59Z",
994 "expected extreme future timestamp to produce sentinel out-of-range timestamp"
995 );
996 }
997
998 if let Some(extreme_past) = SystemTime::UNIX_EPOCH
1000 .checked_sub(Duration::from_secs(i64::MAX as u64))
1001 .or_else(|| SystemTime::UNIX_EPOCH.checked_sub(Duration::from_secs(400_000_000_000)))
1002 {
1003 let min_value = extreme_past.to_value();
1004 assert_eq!(
1005 min_value.kind(),
1006 Kind::String,
1007 "expected extreme past SystemTime to encode as String"
1008 );
1009 let min_str = min_value
1010 .as_str()
1011 .expect("expected non-empty string for extreme past SystemTime");
1012 assert_eq!(
1013 min_str, "-999999-01-01T00:00:00Z",
1014 "expected extreme past timestamp to produce negative sentinel out-of-range timestamp"
1015 );
1016 }
1017
1018 let post_9999_system_time = SystemTime::UNIX_EPOCH + Duration::from_secs(253_402_300_800);
1021 let post_9999_value = post_9999_system_time.to_value();
1022 assert_eq!(
1023 post_9999_value.kind(),
1024 Kind::String,
1025 "expected post-9999 SystemTime to encode as String"
1026 );
1027 assert_eq!(
1028 post_9999_value.as_str(),
1029 Some("999999-12-31T23:59:59Z"),
1030 "expected post-9999 timestamp to emit sentinel out-of-range timestamp"
1031 );
1032
1033 if let Some(pre_0001_system_time) =
1036 SystemTime::UNIX_EPOCH.checked_sub(Duration::from_secs(62_135_596_801))
1037 {
1038 let pre_0001_value = pre_0001_system_time.to_value();
1039 assert_eq!(
1040 pre_0001_value.kind(),
1041 Kind::String,
1042 "expected pre-0001 SystemTime to encode as String"
1043 );
1044 assert_eq!(
1045 pre_0001_value.as_str(),
1046 Some("0000-12-31T23:59:59.000000000Z"),
1047 "expected pre-0001 timestamp to preserve exact calendar components"
1048 );
1049 }
1050
1051 if let Some(pre_epoch_nanos) =
1053 SystemTime::UNIX_EPOCH.checked_sub(Duration::new(62_135_596_801, 500_000_000))
1054 {
1055 let pre_epoch_value = pre_epoch_nanos.to_value();
1056 assert_eq!(
1057 pre_epoch_value.as_str(),
1058 Some("0000-12-31T23:59:58.500000000Z"),
1059 "expected pre-0001 SystemTime with subseconds to format accurately"
1060 );
1061 }
1062 }
1063
1064 #[cfg(feature = "unstable-time")]
1065 #[test]
1066 fn to_value_offset_date_time() {
1067 let date_time = OffsetDateTime::parse("2023-10-27T10:00:00Z", &Rfc3339)
1068 .expect("valid date time parsing");
1069 let value = date_time.to_value();
1070 assert_eq!(
1071 value.kind(),
1072 Kind::String,
1073 "expected OffsetDateTime to encode as String"
1074 );
1075 assert_eq!(
1076 value.as_str(),
1077 Some("2023-10-27T10:00:00.000000000Z"),
1078 "expected valid RFC 3339 timestamp"
1079 );
1080
1081 let non_utc = OffsetDateTime::parse("2023-10-27T12:00:00+02:00", &Rfc3339)
1083 .expect("valid non-utc date time");
1084 let non_utc_value = non_utc.to_value();
1085 assert_eq!(
1086 non_utc_value.kind(),
1087 Kind::String,
1088 "expected non-UTC OffsetDateTime to encode as String"
1089 );
1090 assert_eq!(
1091 non_utc_value.as_str(),
1092 Some("2023-10-27T10:00:00.000000000Z"),
1093 "expected non-UTC timestamp to normalize to UTC instant"
1094 );
1095
1096 let year_zero = TimeDate::from_calendar_date(0, Month::January, 1)
1098 .expect("valid year 0")
1099 .with_hms(0, 0, 0)
1100 .expect("valid time")
1101 .assume_utc();
1102 let year_zero_value = year_zero.to_value();
1103 assert_eq!(
1104 year_zero_value.kind(),
1105 Kind::String,
1106 "expected year 0 OffsetDateTime to encode as String"
1107 );
1108 assert_eq!(
1109 year_zero_value.as_str(),
1110 Some("0000-01-01T00:00:00.000000000Z"),
1111 "expected year 0 to be preserved for Spanner to reject"
1112 );
1113
1114 let negative_year = TimeDate::from_calendar_date(-50, Month::January, 1)
1115 .expect("valid negative year")
1116 .with_hms(0, 0, 0)
1117 .expect("valid time")
1118 .assume_utc();
1119 let negative_value = negative_year.to_value();
1120 assert_eq!(
1121 negative_value.kind(),
1122 Kind::String,
1123 "expected negative year OffsetDateTime to encode as String"
1124 );
1125 assert_eq!(
1126 negative_value.as_str(),
1127 Some("-0050-01-01T00:00:00.000000000Z"),
1128 "expected negative year to format with proper zero padding"
1129 );
1130
1131 let max_date_time = TimeDate::from_calendar_date(9999, Month::December, 31)
1133 .expect("valid year 9999 date")
1134 .with_hms_nano(23, 59, 59, 999_999_999)
1135 .expect("valid max time")
1136 .assume_utc();
1137 let max_value = max_date_time.to_value();
1138 assert_eq!(
1139 max_value.as_str(),
1140 Some("9999-12-31T23:59:59.999999999Z"),
1141 "expected year 9999 to format with 4-digit year"
1142 );
1143
1144 let min_date_time = TimeDate::from_calendar_date(-9999, Month::January, 1)
1145 .expect("valid year -9999 date")
1146 .with_hms_nano(0, 0, 0, 0)
1147 .expect("valid min time")
1148 .assume_utc();
1149 let min_value = min_date_time.to_value();
1150 assert_eq!(
1151 min_value.as_str(),
1152 Some("-9999-01-01T00:00:00.000000000Z"),
1153 "expected year -9999 to format with negative 4-digit year"
1154 );
1155
1156 let offset = UtcOffset::from_hms(-12, 0, 0).expect("valid negative UTC offset");
1158 let overflow_date_time = TimeDate::MAX
1159 .with_hms_nano(23, 59, 59, 999_999_999)
1160 .expect("valid max time")
1161 .assume_offset(offset);
1162 let overflow_value = overflow_date_time.to_value();
1163 assert_eq!(
1164 overflow_value.as_str(),
1165 Some("999999-12-31T23:59:59Z"),
1166 "expected boundary overflow on UTC conversion to emit out-of-range sentinel"
1167 );
1168
1169 let underflow_offset = UtcOffset::from_hms(12, 0, 0).expect("valid positive UTC offset");
1170 let underflow_date_time = TimeDate::MIN
1171 .with_hms_nano(0, 0, 0, 0)
1172 .expect("valid min time")
1173 .assume_offset(underflow_offset);
1174 let underflow_value = underflow_date_time.to_value();
1175 assert_eq!(
1176 underflow_value.as_str(),
1177 Some("-999999-01-01T00:00:00Z"),
1178 "expected boundary underflow on UTC conversion to emit negative out-of-range sentinel"
1179 );
1180 }
1181
1182 #[test]
1183 fn to_value_timestamp() {
1184 let timestamp = Timestamp::clamp(1698400800, 0);
1185 let value = timestamp.to_value();
1186 assert_eq!(
1187 value.kind(),
1188 Kind::String,
1189 "expected Timestamp to encode as String"
1190 );
1191 assert_eq!(
1192 value.as_str(),
1193 Some("2023-10-27T10:00:00.000000000Z"),
1194 "expected valid RFC 3339 timestamp"
1195 );
1196
1197 let min_timestamp = Timestamp::clamp(Timestamp::MIN_SECONDS, 0);
1199 let min_value = min_timestamp.to_value();
1200 assert_eq!(
1201 min_value.kind(),
1202 Kind::String,
1203 "expected min Timestamp to encode as String"
1204 );
1205 assert_eq!(
1206 min_value.as_str(),
1207 Some("0001-01-01T00:00:00.000000000Z"),
1208 "expected 0001-01-01T00:00:00.000000000Z"
1209 );
1210
1211 let max_timestamp = Timestamp::clamp(Timestamp::MAX_SECONDS, 999_999_999);
1212 let max_value = max_timestamp.to_value();
1213 assert_eq!(
1214 max_value.kind(),
1215 Kind::String,
1216 "expected max Timestamp to encode as String"
1217 );
1218 assert_eq!(
1219 max_value.as_str(),
1220 Some("9999-12-31T23:59:59.999999999Z"),
1221 "expected 9999-12-31T23:59:59.999999999Z"
1222 );
1223 }
1224
1225 #[test]
1226 fn to_value_google_date_out_of_range() {
1227 let default_date = Date::default();
1228 let value = default_date.to_value();
1229 assert_eq!(
1230 value.kind(),
1231 Kind::String,
1232 "expected Date::default() to encode as String"
1233 );
1234 assert_eq!(
1235 value.as_str(),
1236 Some("0000-00-00"),
1237 "expected Date::default() to format as 0000-00-00 for Spanner to reject"
1238 );
1239
1240 let post_9999_date = Date::new().set_year(10000).set_month(1).set_day(1);
1241 let value = post_9999_date.to_value();
1242 assert_eq!(
1243 value.kind(),
1244 Kind::String,
1245 "expected post-9999 Date to encode as String"
1246 );
1247 assert_eq!(
1248 value.as_str(),
1249 Some("10000-01-01"),
1250 "expected year 10000 date to format accurately for Spanner to reject"
1251 );
1252
1253 let negative_year_date = Date::new().set_year(-50).set_month(1).set_day(1);
1254 let value = negative_year_date.to_value();
1255 assert_eq!(
1256 value.kind(),
1257 Kind::String,
1258 "expected negative year Date to encode as String"
1259 );
1260 assert_eq!(
1261 value.as_str(),
1262 Some("-0050-01-01"),
1263 "expected negative year Date to format with 4-digit zero-padding"
1264 );
1265
1266 let min_year_date = Date::new().set_year(i32::MIN).set_month(1).set_day(1);
1267 let min_year_value = min_year_date.to_value();
1268 assert_eq!(
1269 min_year_value.as_str(),
1270 Some("-2147483648-01-01"),
1271 "expected i32::MIN year Date to format without integer overflow"
1272 );
1273 }
1274
1275 #[cfg(feature = "unstable-time")]
1276 #[test]
1277 fn to_value_time_date_out_of_range() {
1278 let year_zero_date =
1279 TimeDate::from_calendar_date(0, Month::January, 1).expect("valid year 0 date");
1280 let value = year_zero_date.to_value();
1281 assert_eq!(
1282 value.kind(),
1283 Kind::String,
1284 "expected year 0 TimeDate to encode as String"
1285 );
1286 assert_eq!(
1287 value.as_str(),
1288 Some("0000-01-01"),
1289 "expected year 0 to format accurately without 'invalid date'"
1290 );
1291
1292 let negative_date =
1293 TimeDate::from_calendar_date(-50, Month::January, 1).expect("valid negative date");
1294 let value = negative_date.to_value();
1295 assert_eq!(
1296 value.kind(),
1297 Kind::String,
1298 "expected negative TimeDate to encode as String"
1299 );
1300 assert_eq!(
1301 value.as_str(),
1302 Some("-0050-01-01"),
1303 "expected negative year to format with proper zero padding"
1304 );
1305
1306 let min_time_date = TimeDate::MIN;
1307 let min_value = min_time_date.to_value();
1308 assert_eq!(
1309 min_value.as_str(),
1310 Some("-9999-01-01"),
1311 "expected TimeDate::MIN to format as -9999-01-01"
1312 );
1313
1314 let max_time_date = TimeDate::MAX;
1315 let max_value = max_time_date.to_value();
1316 assert_eq!(
1317 max_value.as_str(),
1318 Some("9999-12-31"),
1319 "expected TimeDate::MAX to format as 9999-12-31"
1320 );
1321 }
1322
1323 #[test]
1324 fn to_value_option() {
1325 let some_value: Option<i32> = Some(42);
1326 let value = some_value.to_value();
1327 assert_eq!(value.kind(), Kind::String);
1328 assert_eq!(value.as_str(), Some("42"));
1329
1330 let none_value: Option<i32> = None;
1331 let value = none_value.to_value();
1332 assert_eq!(value.kind(), Kind::Null);
1333 }
1334
1335 #[test]
1336 fn to_value_value() {
1337 let original_value = 42i32.to_value();
1338 let value = original_value.to_value();
1339 assert_eq!(value, original_value);
1340 }
1341
1342 #[test]
1343 fn to_value_array() {
1344 let string_array = vec!["one".to_string(), "two".to_string()];
1345 let value = string_array.to_value();
1346 assert_eq!(value.kind(), Kind::List);
1347 let list = value.as_list().expect("list should exist");
1348 assert_eq!(list.len(), 2);
1349 assert_eq!(
1350 list.get(0).expect("element 0 should exist").as_str(),
1351 Some("one")
1352 );
1353 assert_eq!(
1354 list.get(1).expect("element 1 should exist").as_str(),
1355 Some("two")
1356 );
1357
1358 let int_array = vec![42i64, 100i64];
1359 let value = int_array.to_value();
1360 assert_eq!(value.kind(), Kind::List);
1361 let list = value.as_list().expect("list should exist");
1362 assert_eq!(list.len(), 2);
1363 assert_eq!(
1364 list.get(0).expect("element 0 should exist").as_str(),
1365 Some("42")
1366 );
1367 assert_eq!(
1368 list.get(1).expect("element 1 should exist").as_str(),
1369 Some("100")
1370 );
1371
1372 let bool_array = vec![true, false];
1373 let value = bool_array.to_value();
1374 assert_eq!(value.kind(), Kind::List);
1375 let list = value.as_list().expect("list should exist");
1376 assert_eq!(list.len(), 2);
1377 assert_eq!(
1378 list.get(0).expect("element 0 should exist").as_bool(),
1379 Some(true)
1380 );
1381 assert_eq!(
1382 list.get(1).expect("element 1 should exist").as_bool(),
1383 Some(false)
1384 );
1385
1386 let float_array = vec![9.9f64, -2.5f64];
1387 let value = float_array.to_value();
1388 assert_eq!(value.kind(), Kind::List);
1389 let list = value.as_list().expect("list should exist");
1390 assert_eq!(list.len(), 2);
1391 assert_eq!(
1392 list.get(0).expect("element 0 should exist").as_f64(),
1393 Some(9.9)
1394 );
1395 assert_eq!(
1396 list.get(1).expect("element 1 should exist").as_f64(),
1397 Some(-2.5)
1398 );
1399
1400 let empty_array: Vec<f64> = vec![];
1401 let value = empty_array.to_value();
1402 assert_eq!(value.kind(), Kind::List);
1403 assert_eq!(value.as_list().expect("list should exist").len(), 0);
1404
1405 let null_array: Option<Vec<i64>> = None;
1406 let value = null_array.to_value();
1407 assert_eq!(value.kind(), Kind::Null);
1408
1409 let opt_array: Vec<Option<i64>> = vec![Some(42), None, Some(100)];
1410 let value = opt_array.to_value();
1411 assert_eq!(value.kind(), Kind::List);
1412 let list = value.as_list().expect("list should exist");
1413 assert_eq!(list.len(), 3);
1414 assert_eq!(
1415 list.get(0).expect("element 0 should exist").as_str(),
1416 Some("42")
1417 );
1418 assert_eq!(
1419 list.get(1).expect("element 1 should exist").kind(),
1420 Kind::Null
1421 );
1422 assert_eq!(
1423 list.get(2).expect("element 2 should exist").as_str(),
1424 Some("100")
1425 );
1426 }
1427
1428 #[test]
1429 fn to_value_non_finite_floats() {
1430 let f64_nan_value = f64::NAN.to_value();
1431 assert_eq!(f64_nan_value.kind(), Kind::String);
1432 assert_eq!(f64_nan_value.as_str(), Some("NaN"));
1433
1434 let f64_infinity_value = f64::INFINITY.to_value();
1435 assert_eq!(f64_infinity_value.kind(), Kind::String);
1436 assert_eq!(f64_infinity_value.as_str(), Some("Infinity"));
1437
1438 let f64_neg_infinity_value = f64::NEG_INFINITY.to_value();
1439 assert_eq!(f64_neg_infinity_value.kind(), Kind::String);
1440 assert_eq!(f64_neg_infinity_value.as_str(), Some("-Infinity"));
1441
1442 let f64_finite_value = 42.5f64.to_value();
1443 assert_eq!(f64_finite_value.kind(), Kind::Number);
1444 assert_eq!(f64_finite_value.as_f64(), Some(42.5));
1445
1446 let f32_nan_value = f32::NAN.to_value();
1447 assert_eq!(f32_nan_value.kind(), Kind::String);
1448 assert_eq!(f32_nan_value.as_str(), Some("NaN"));
1449
1450 let f32_infinity_value = f32::INFINITY.to_value();
1451 assert_eq!(f32_infinity_value.kind(), Kind::String);
1452 assert_eq!(f32_infinity_value.as_str(), Some("Infinity"));
1453
1454 let f32_neg_infinity_value = f32::NEG_INFINITY.to_value();
1455 assert_eq!(f32_neg_infinity_value.kind(), Kind::String);
1456 assert_eq!(f32_neg_infinity_value.as_str(), Some("-Infinity"));
1457
1458 let f32_finite_value = 12.5f32.to_value();
1459 assert_eq!(f32_finite_value.kind(), Kind::Number);
1460 assert_eq!(f32_finite_value.as_f64(), Some(12.5));
1461 }
1462
1463 #[test]
1464 fn to_value_json() {
1465 let object_json = json!({"color": "red", "value": "#f00"});
1466 let object_value = object_json.to_value();
1467 assert_eq!(
1468 object_value.kind(),
1469 Kind::String,
1470 "json object must encode as string"
1471 );
1472 assert_eq!(
1473 object_value.as_str(),
1474 Some(r##"{"color":"red","value":"#f00"}"##),
1475 "serialized json object string must match"
1476 );
1477
1478 let array_json = json!([1, 2, 3]);
1479 let array_value = array_json.to_value();
1480 assert_eq!(
1481 array_value.kind(),
1482 Kind::String,
1483 "json array must encode as string"
1484 );
1485 assert_eq!(
1486 array_value.as_str(),
1487 Some("[1,2,3]"),
1488 "serialized json array string must match"
1489 );
1490
1491 let string_json = json!("hello world");
1492 let string_value = string_json.to_value();
1493 assert_eq!(
1494 string_value.kind(),
1495 Kind::String,
1496 "json string must encode as string"
1497 );
1498 assert_eq!(
1499 string_value.as_str(),
1500 Some(r#""hello world""#),
1501 "serialized json string must match"
1502 );
1503
1504 let number_json = json!(42);
1505 let number_value = number_json.to_value();
1506 assert_eq!(
1507 number_value.kind(),
1508 Kind::String,
1509 "json number must encode as string"
1510 );
1511 assert_eq!(
1512 number_value.as_str(),
1513 Some("42"),
1514 "serialized json number string must match"
1515 );
1516
1517 let bool_json = json!(true);
1518 let bool_value = bool_json.to_value();
1519 assert_eq!(
1520 bool_value.kind(),
1521 Kind::String,
1522 "json boolean must encode as string"
1523 );
1524 assert_eq!(
1525 bool_value.as_str(),
1526 Some("true"),
1527 "serialized json boolean string must match"
1528 );
1529
1530 let null_json = json!(null);
1531 let null_json_value = null_json.to_value();
1532 assert_eq!(
1533 null_json_value.kind(),
1534 Kind::String,
1535 "json null literal must encode as string 'null'"
1536 );
1537 assert_eq!(
1538 null_json_value.as_str(),
1539 Some("null"),
1540 "json null literal string must be 'null'"
1541 );
1542
1543 let borrowed_json: &JsonValue = &object_json;
1544 let borrowed_object_value = Value::from(borrowed_json);
1545 assert_eq!(
1546 borrowed_object_value, object_value,
1547 "borrowed json reference must encode identically to owned json"
1548 );
1549
1550 let mut mutable_object_json = json!({"mutable": true});
1551 let mutable_ref_value = Value::from(&mut mutable_object_json);
1552 assert_eq!(
1553 mutable_ref_value.as_str(),
1554 Some(r#"{"mutable":true}"#),
1555 "mutable json reference must encode correctly"
1556 );
1557
1558 let none_json: Option<JsonValue> = None;
1559 let none_value = none_json.to_value();
1560 assert_eq!(
1561 none_value.kind(),
1562 Kind::Null,
1563 "Option::<JsonValue>::None must encode as SQL null"
1564 );
1565 assert!(none_value.is_null(), "None must be null");
1566
1567 let some_null_json = Some(json!(null)).to_value();
1568 assert_eq!(
1569 some_null_json.kind(),
1570 Kind::String,
1571 "Some(json!(null)) must encode as JSON null string"
1572 );
1573 assert_eq!(
1574 some_null_json.as_str(),
1575 Some("null"),
1576 "Some(json!(null)) string must be 'null'"
1577 );
1578
1579 let some_object_json = Some(json!({"x": 1})).to_value();
1580 assert_eq!(
1581 some_object_json.kind(),
1582 Kind::String,
1583 "Some(json!(...)) must encode as JSON string"
1584 );
1585 assert_eq!(
1586 some_object_json.as_str(),
1587 Some(r#"{"x":1}"#),
1588 "Some(json!(...)) string must match"
1589 );
1590 }
1591
1592 #[test]
1593 fn from_json_for_value() {
1594 let payload = json!({"id": "item-123", "tags": ["a", "b"]});
1595
1596 let owned_value: Value = payload.clone().into();
1597 assert_eq!(
1598 owned_value.kind(),
1599 Kind::String,
1600 "From<JsonValue> must produce a String value"
1601 );
1602 assert_eq!(
1603 owned_value.as_str(),
1604 Some(r#"{"id":"item-123","tags":["a","b"]}"#),
1605 "owned json string must match"
1606 );
1607
1608 let borrowed_value: Value = (&payload).into();
1609 assert_eq!(
1610 borrowed_value, owned_value,
1611 "From<&JsonValue> must produce identical value to owned"
1612 );
1613
1614 let mut mutable_payload = payload.clone();
1615 let mutable_value: Value = (&mut mutable_payload).into();
1616 assert_eq!(
1617 mutable_value, owned_value,
1618 "From<&mut JsonValue> must produce identical value to owned"
1619 );
1620
1621 let none_value: Value = Option::<JsonValue>::None.into();
1622 assert_eq!(
1623 none_value.kind(),
1624 Kind::Null,
1625 "From<Option::None> must produce SQL null"
1626 );
1627
1628 let some_value: Value = Some(payload.clone()).into();
1629 assert_eq!(
1630 some_value, owned_value,
1631 "From<Option::Some> must produce JSON value"
1632 );
1633
1634 let array_payload = vec![json!({"x": 1}), json!({"y": 2})];
1635 let list_value: Value = array_payload.into();
1636 assert_eq!(
1637 list_value.kind(),
1638 Kind::List,
1639 "From<Vec<JsonValue>> must produce a List value"
1640 );
1641 let list = list_value.as_list().expect("list should be present");
1642 assert_eq!(list.len(), 2, "array list must contain 2 elements");
1643 assert_eq!(
1644 list.get(0).expect("element 0 should exist").as_str(),
1645 Some(r#"{"x":1}"#),
1646 "first element must be serialized json string"
1647 );
1648 assert_eq!(
1649 list.get(1).expect("element 1 should exist").as_str(),
1650 Some(r#"{"y":2}"#),
1651 "second element must be serialized json string"
1652 );
1653 }
1654
1655 #[test]
1656 fn json_in_statements_mutations_and_keys() {
1657 let profile = json!({"user": "alice", "roles": ["admin"]});
1658
1659 let borrowed_statement = Statement::builder("SELECT * FROM users WHERE profile = @profile")
1661 .add_param("profile", &profile)
1662 .build();
1663 assert_eq!(
1664 borrowed_statement.params.get("profile"),
1665 Some(&Value::from(&profile)),
1666 "statement params must contain profile parameter from borrowed json"
1667 );
1668
1669 let owned_statement = Statement::builder("SELECT * FROM users WHERE profile = @profile")
1670 .add_param("profile", profile.clone())
1671 .build();
1672 assert_eq!(
1673 owned_statement.params.get("profile"),
1674 Some(&Value::from(&profile)),
1675 "statement params must contain profile parameter from owned json"
1676 );
1677
1678 let typed_statement = Statement::builder("SELECT * FROM users WHERE profile = @profile")
1680 .add_typed_param("profile", &profile, types::json())
1681 .build();
1682 assert_eq!(
1683 typed_statement.params.get("profile"),
1684 Some(&Value::from(&profile)),
1685 "typed statement params must contain profile"
1686 );
1687 assert_eq!(
1688 typed_statement.param_types.get("profile"),
1689 Some(&types::json()),
1690 "typed statement param_types must contain TypeCode::Json"
1691 );
1692
1693 let borrowed_mutation = Mutation::new_insert_builder("Users")
1695 .set("UserId")
1696 .to(1i64)
1697 .set("Profile")
1698 .to(&profile)
1699 .build();
1700 let owned_mutation = Mutation::new_insert_builder("Users")
1701 .set("UserId")
1702 .to(1i64)
1703 .set("Profile")
1704 .to(profile.clone())
1705 .build();
1706 assert_eq!(
1707 borrowed_mutation, owned_mutation,
1708 "borrowed and owned mutations with json must be identical"
1709 );
1710
1711 let owned_key = key![profile.clone()];
1713 let borrowed_key = key![&profile];
1714 assert_eq!(
1715 owned_key, borrowed_key,
1716 "owned and borrowed key macro expansions with json must match"
1717 );
1718 assert_eq!(
1719 owned_key.values,
1720 vec![Value::from(&profile)],
1721 "key values must match json value"
1722 );
1723 }
1724
1725 #[test]
1726 fn to_value_json_all_permutations() {
1727 let test_cases = [
1728 json!(true),
1730 json!(false),
1731 json!(0),
1733 json!(42),
1734 json!(-42),
1735 json!(i64::MIN),
1736 json!(i64::MAX),
1737 json!(0.0),
1739 json!(123.456),
1740 json!(-99.99),
1741 json!(""),
1743 json!("hello world"),
1744 json!("quotes \" and \n and \t and \\"),
1745 json!("unicode: こんにちは 🌍"),
1746 json!([]),
1748 json!([1, 2, 3]),
1749 json!([1, "two", true, null, [2], {"k": "v"}]),
1750 json!([[1, 2], [3, 4]]),
1751 json!({}),
1753 json!({"color": "red", "value": "#f00"}),
1754 json!({"nested": {"id": 1, "items": ["a", "b"]}}),
1755 json!({"field_with_null": null}),
1756 json!({"キー": "値"}),
1757 json!(null),
1759 ];
1760
1761 let json_type = types::json();
1762
1763 for original_json in test_cases {
1764 let encoded_value = original_json.to_value();
1765 assert_eq!(
1766 encoded_value.kind(),
1767 Kind::String,
1768 "encoded JSON must have Kind::String for: {original_json}"
1769 );
1770 assert_eq!(
1771 encoded_value.as_str(),
1772 Some(original_json.to_string().as_str()),
1773 "encoded string must match to_string() for: {original_json}"
1774 );
1775
1776 let from_owned_value = Value::from(original_json.clone());
1778 assert_eq!(
1779 from_owned_value, encoded_value,
1780 "Value::from(owned) must match to_value() for: {original_json}"
1781 );
1782
1783 let from_borrowed_value = Value::from(&original_json);
1785 assert_eq!(
1786 from_borrowed_value, encoded_value,
1787 "Value::from(&borrowed) must match to_value() for: {original_json}"
1788 );
1789
1790 let roundtripped_borrowed = JsonValue::from_value(&encoded_value, &json_type)
1792 .expect("borrowed roundtrip deserialization must succeed");
1793 assert_eq!(
1794 roundtripped_borrowed, original_json,
1795 "borrowed roundtrip must preserve exact JSON structure for: {original_json}"
1796 );
1797
1798 let roundtripped_owned = JsonValue::from_owned_value(encoded_value, &json_type)
1800 .expect("owned roundtrip deserialization must succeed");
1801 assert_eq!(
1802 roundtripped_owned, original_json,
1803 "owned roundtrip must preserve exact JSON structure for: {original_json}"
1804 );
1805 }
1806 }
1807
1808 #[test]
1809 fn to_value_json_container_permutations() {
1810 let json_type = types::json();
1811
1812 let none_json: Option<JsonValue> = None;
1814 let none_value = none_json.to_value();
1815 assert_eq!(
1816 none_value.kind(),
1817 Kind::Null,
1818 "Option::<JsonValue>::None must encode as SQL null"
1819 );
1820 let roundtrip_none = <Option<JsonValue>>::from_value(&none_value, &json_type)
1821 .expect("Option::from_value for SQL null must succeed");
1822 assert_eq!(roundtrip_none, None, "SQL null must deserialize as None");
1823
1824 let some_null_json = Some(json!(null));
1825 let some_null_value = some_null_json.to_value();
1826 assert_eq!(
1827 some_null_value.kind(),
1828 Kind::String,
1829 "Some(json!(null)) must encode as JSON null string"
1830 );
1831 let roundtrip_some_null = <Option<JsonValue>>::from_value(&some_null_value, &json_type)
1832 .expect("Option::from_value for JSON null must succeed");
1833 assert_eq!(
1834 roundtrip_some_null,
1835 Some(JsonValue::Null),
1836 "JSON null must deserialize as Some(JsonValue::Null)"
1837 );
1838
1839 let some_object_json = Some(json!({"id": 100}));
1840 let some_object_value = some_object_json.to_value();
1841 let roundtrip_some_object = <Option<JsonValue>>::from_value(&some_object_value, &json_type)
1842 .expect("Option::from_value for JSON object must succeed");
1843 assert_eq!(
1844 roundtrip_some_object,
1845 Some(json!({"id": 100})),
1846 "JSON object must deserialize as Some(object)"
1847 );
1848
1849 let payload = json!({"key": "value"});
1851 let none_ref: Option<&JsonValue> = None;
1852 assert_eq!(
1853 none_ref.to_value().kind(),
1854 Kind::Null,
1855 "Option::<&JsonValue>::None must encode as SQL null"
1856 );
1857 let some_ref: Option<&JsonValue> = Some(&payload);
1858 assert_eq!(
1859 some_ref.to_value().as_str(),
1860 Some(r#"{"key":"value"}"#),
1861 "Option::<&JsonValue>::Some must encode as JSON string"
1862 );
1863
1864 let empty_vec: Vec<JsonValue> = Vec::new();
1866 let empty_list_value = empty_vec.to_value();
1867 assert_eq!(
1868 empty_list_value.kind(),
1869 Kind::List,
1870 "empty Vec<JsonValue> must encode as Kind::List"
1871 );
1872 let empty_list = empty_list_value
1873 .as_list()
1874 .expect("empty list must be present");
1875 assert_eq!(empty_list.len(), 0, "empty list must have length 0");
1876
1877 let json_a = json!({"a": 1});
1879 let json_b = json!({"b": 2});
1880 let borrowed_vec: Vec<&JsonValue> = vec![&json_a, &json_b];
1881 let borrowed_list_value = borrowed_vec.to_value();
1882 assert_eq!(
1883 borrowed_list_value.kind(),
1884 Kind::List,
1885 "Vec<&JsonValue> must encode as Kind::List"
1886 );
1887 let borrowed_list = borrowed_list_value
1888 .as_list()
1889 .expect("borrowed list must be present");
1890 assert_eq!(borrowed_list.len(), 2, "borrowed list must have 2 elements");
1891
1892 let array_with_nulls: Vec<Option<JsonValue>> =
1894 vec![Some(json!({"x": 1})), None, Some(json!(null))];
1895 let array_with_nulls_value = array_with_nulls.to_value();
1896 assert_eq!(
1897 array_with_nulls_value.kind(),
1898 Kind::List,
1899 "Vec<Option<JsonValue>> must encode as Kind::List"
1900 );
1901 let list_with_nulls = array_with_nulls_value
1902 .as_list()
1903 .expect("list with nulls must be present");
1904 assert_eq!(
1905 list_with_nulls.len(),
1906 3,
1907 "list with nulls must have 3 elements"
1908 );
1909 assert_eq!(
1910 list_with_nulls
1911 .get(0)
1912 .expect("element 0 should exist")
1913 .kind(),
1914 Kind::String,
1915 "element 0 must be Kind::String"
1916 );
1917 assert_eq!(
1918 list_with_nulls
1919 .get(0)
1920 .expect("element 0 should exist")
1921 .as_str(),
1922 Some(r#"{"x":1}"#),
1923 "element 0 string must match"
1924 );
1925 assert_eq!(
1926 list_with_nulls
1927 .get(1)
1928 .expect("element 1 should exist")
1929 .kind(),
1930 Kind::Null,
1931 "element 1 must be SQL NULL (Kind::Null)"
1932 );
1933 assert_eq!(
1934 list_with_nulls
1935 .get(2)
1936 .expect("element 2 should exist")
1937 .kind(),
1938 Kind::String,
1939 "element 2 must be JSON null (Kind::String)"
1940 );
1941 assert_eq!(
1942 list_with_nulls
1943 .get(2)
1944 .expect("element 2 should exist")
1945 .as_str(),
1946 Some("null"),
1947 "element 2 string must be 'null'"
1948 );
1949 }
1950
1951 #[test]
1952 fn from_json_unhappy_paths() {
1953 let json_type = types::json();
1954
1955 let malformed_value = Value::from("{not valid json");
1957 let malformed_error = JsonValue::from_value(&malformed_value, &json_type)
1958 .expect_err("malformed JSON string must fail to deserialize");
1959 assert!(
1960 matches!(malformed_error, ConvertError::Convert(_)),
1961 "expected ConvertError::Convert for malformed JSON string"
1962 );
1963
1964 let unterminated_value = Value::from("{\"key\":");
1966 let unterminated_error = JsonValue::from_value(&unterminated_value, &json_type)
1967 .expect_err("unterminated JSON must fail to deserialize");
1968 assert!(
1969 matches!(unterminated_error, ConvertError::Convert(_)),
1970 "expected ConvertError::Convert for unterminated JSON"
1971 );
1972
1973 let empty_str_value = Value::from("");
1975 let empty_str_error = JsonValue::from_value(&empty_str_value, &json_type)
1976 .expect_err("empty string must fail to deserialize as JSON");
1977 assert!(
1978 matches!(empty_str_error, ConvertError::Convert(_)),
1979 "expected ConvertError::Convert for empty string"
1980 );
1981
1982 let struct_wire_value = Value(prost_types::Value {
1984 kind: Some(prost_types::value::Kind::StructValue(
1985 prost_types::Struct::default(),
1986 )),
1987 });
1988 let struct_wire_error = JsonValue::from_value(&struct_wire_value, &json_type)
1989 .expect_err("unexpected StructValue on wire must be rejected");
1990 assert!(
1991 matches!(
1992 &struct_wire_error,
1993 ConvertError::Convert(source_error)
1994 if source_error.to_string().contains("unexpected protobuf StructValue")
1995 ),
1996 "expected ConvertError::Convert mentioning 'unexpected protobuf StructValue', got: {struct_wire_error:?}"
1997 );
1998
1999 let bad_array_value = Value(prost_types::Value {
2001 kind: Some(prost_types::value::Kind::ListValue(
2002 prost_types::ListValue {
2003 values: vec![prost_types::Value {
2004 kind: Some(prost_types::value::Kind::StringValue(
2005 "{invalid".to_string(),
2006 )),
2007 }],
2008 },
2009 )),
2010 });
2011 let array_type = types::array(types::json());
2012 let bad_array_error = <Vec<JsonValue>>::from_value(&bad_array_value, &array_type)
2013 .expect_err("array with invalid JSON element must fail");
2014 assert!(
2015 matches!(bad_array_error, ConvertError::Convert(_)),
2016 "expected ConvertError::Convert for bad element in array"
2017 );
2018 }
2019}