-
Notifications
You must be signed in to change notification settings - Fork 238
/
values.rs
1453 lines (1230 loc) Β· 41.5 KB
/
values.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::ast::*;
use crate::error::{Error, ErrorKind};
use bigdecimal::{BigDecimal, FromPrimitive, ToPrimitive};
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
use serde_json::{Number, Value as JsonValue};
use std::fmt::Display;
use std::{
borrow::{Borrow, Cow},
convert::TryFrom,
fmt,
str::FromStr,
};
use uuid::Uuid;
/// A value written to the query as-is without parameterization.
#[derive(Debug, Clone, PartialEq)]
pub struct Raw<'a>(pub(crate) Value<'a>);
/// Converts the value into a state to skip parameterization.
///
/// Must be used carefully to avoid SQL injections.
pub trait IntoRaw<'a> {
fn raw(self) -> Raw<'a>;
}
impl<'a, T> IntoRaw<'a> for T
where
T: Into<Value<'a>>,
{
fn raw(self) -> Raw<'a> {
Raw(self.into())
}
}
/// A native-column type, i.e. the connector-specific type of the column.
#[derive(Debug, Clone, PartialEq)]
pub struct NativeColumnType<'a>(Cow<'a, str>);
impl<'a> std::ops::Deref for NativeColumnType<'a> {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> From<&'a str> for NativeColumnType<'a> {
fn from(s: &'a str) -> Self {
Self(Cow::Owned(s.to_uppercase()))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Value<'a> {
pub typed: ValueType<'a>,
pub native_column_type: Option<NativeColumnType<'a>>,
}
impl<'a> Value<'a> {
/// Returns the native column type of the value, if any, in the form
/// of an UPCASE string. ex: "VARCHAR, BYTEA, DATE, TIMEZ"
pub fn native_column_type_name(&'a self) -> Option<&'a str> {
self.native_column_type.as_deref()
}
/// Changes the value to include information about the native column type
pub fn with_native_column_type<T: Into<NativeColumnType<'a>>>(mut self, column_type: Option<T>) -> Self {
self.native_column_type = column_type.map(|ct| ct.into());
self
}
/// Creates a new 32-bit signed integer.
pub fn int32<I>(value: I) -> Self
where
I: Into<i32>,
{
ValueType::int32(value).into_value()
}
/// Creates a new 64-bit signed integer.
pub fn int64<I>(value: I) -> Self
where
I: Into<i64>,
{
ValueType::int64(value).into_value()
}
/// Creates a new decimal value.
pub fn numeric(value: BigDecimal) -> Self {
ValueType::numeric(value).into_value()
}
/// Creates a new float value.
pub fn float(value: f32) -> Self {
ValueType::float(value).into_value()
}
/// Creates a new double value.
pub fn double(value: f64) -> Self {
ValueType::double(value).into_value()
}
/// Creates a new string value.
pub fn text<T>(value: T) -> Self
where
T: Into<Cow<'a, str>>,
{
ValueType::text(value).into_value()
}
/// Creates a new enum value.
pub fn enum_variant<T>(value: T) -> Self
where
T: Into<EnumVariant<'a>>,
{
ValueType::enum_variant(value).into_value()
}
/// Creates a new enum value with the name of the enum attached.
pub fn enum_variant_with_name<T, U>(value: T, name: U) -> Self
where
T: Into<EnumVariant<'a>>,
U: Into<EnumName<'a>>,
{
ValueType::enum_variant_with_name(value, name).into_value()
}
/// Creates a new enum array value
pub fn enum_array<T>(value: T) -> Self
where
T: IntoIterator<Item = EnumVariant<'a>>,
{
ValueType::enum_array(value).into_value()
}
/// Creates a new enum array value with the name of the enum attached.
pub fn enum_array_with_name<T, U>(value: T, name: U) -> Self
where
T: IntoIterator<Item = EnumVariant<'a>>,
U: Into<EnumName<'a>>,
{
ValueType::enum_array_with_name(value, name).into_value()
}
/// Creates a new bytes value.
pub fn bytes<B>(value: B) -> Self
where
B: Into<Cow<'a, [u8]>>,
{
ValueType::bytes(value).into_value()
}
/// Creates a new boolean value.
pub fn boolean<B>(value: B) -> Self
where
B: Into<bool>,
{
ValueType::boolean(value).into_value()
}
/// Creates a new character value.
pub fn character<C>(value: C) -> Self
where
C: Into<char>,
{
ValueType::character(value).into_value()
}
/// Creates a new array value.
pub fn array<I, V>(value: I) -> Self
where
I: IntoIterator<Item = V>,
V: Into<Value<'a>>,
{
ValueType::array(value).into_value()
}
/// Creates a new uuid value.
pub fn uuid(value: Uuid) -> Self {
ValueType::uuid(value).into_value()
}
/// Creates a new datetime value.
pub fn datetime(value: DateTime<Utc>) -> Self {
ValueType::datetime(value).into_value()
}
/// Creates a new date value.
pub fn date(value: NaiveDate) -> Self {
ValueType::date(value).into_value()
}
/// Creates a new time value.
pub fn time(value: NaiveTime) -> Self {
ValueType::time(value).into_value()
}
/// Creates a new JSON value.
pub fn json(value: serde_json::Value) -> Self {
ValueType::json(value).into_value()
}
/// Creates a new XML value.
pub fn xml<T>(value: T) -> Self
where
T: Into<Cow<'a, str>>,
{
ValueType::xml(value).into_value()
}
/// `true` if the `Value` is null.
pub fn is_null(&self) -> bool {
self.typed.is_null()
}
/// Returns a &str if the value is text, otherwise `None`.
pub fn as_str(&self) -> Option<&str> {
self.typed.as_str()
}
/// `true` if the `Value` is text.
pub fn is_text(&self) -> bool {
self.typed.is_text()
}
/// Returns a char if the value is a char, otherwise `None`.
pub fn as_char(&self) -> Option<char> {
self.typed.as_char()
}
/// Returns a cloned String if the value is text, otherwise `None`.
pub fn to_string(&self) -> Option<String> {
self.typed.to_string()
}
/// Transforms the `Value` to a `String` if it's text,
/// otherwise `None`.
pub fn into_string(self) -> Option<String> {
self.typed.into_string()
}
/// Returns whether this value is the `Bytes` variant.
pub fn is_bytes(&self) -> bool {
self.typed.is_bytes()
}
/// Returns a bytes slice if the value is text or a byte slice, otherwise `None`.
pub fn as_bytes(&self) -> Option<&[u8]> {
self.typed.as_bytes()
}
/// Returns a cloned `Vec<u8>` if the value is text or a byte slice, otherwise `None`.
pub fn to_bytes(&self) -> Option<Vec<u8>> {
self.typed.to_bytes()
}
/// `true` if the `Value` is a 32-bit signed integer.
pub fn is_i32(&self) -> bool {
self.typed.is_i32()
}
/// `true` if the `Value` is a 64-bit signed integer.
pub fn is_i64(&self) -> bool {
self.typed.is_i64()
}
/// `true` if the `Value` is a signed integer.
pub fn is_integer(&self) -> bool {
self.typed.is_integer()
}
/// Returns an `i64` if the value is a 64-bit signed integer, otherwise `None`.
pub fn as_i64(&self) -> Option<i64> {
self.typed.as_i64()
}
/// Returns an `i32` if the value is a 32-bit signed integer, otherwise `None`.
pub fn as_i32(&self) -> Option<i32> {
self.typed.as_i32()
}
/// Returns an `i64` if the value is a signed integer, otherwise `None`.
pub fn as_integer(&self) -> Option<i64> {
self.typed.as_integer()
}
/// Returns a `f64` if the value is a double, otherwise `None`.
pub fn as_f64(&self) -> Option<f64> {
self.typed.as_f64()
}
/// Returns a `f32` if the value is a double, otherwise `None`.
pub fn as_f32(&self) -> Option<f32> {
self.typed.as_f32()
}
/// `true` if the `Value` is a numeric value or can be converted to one.
pub fn is_numeric(&self) -> bool {
self.typed.is_numeric()
}
/// Returns a bigdecimal, if the value is a numeric, float or double value,
/// otherwise `None`.
pub fn into_numeric(self) -> Option<BigDecimal> {
self.typed.into_numeric()
}
/// Returns a reference to a bigdecimal, if the value is a numeric.
/// Otherwise `None`.
pub fn as_numeric(&self) -> Option<&BigDecimal> {
self.typed.as_numeric()
}
/// `true` if the `Value` is a boolean value.
pub fn is_bool(&self) -> bool {
self.typed.is_bool()
}
/// Returns a bool if the value is a boolean, otherwise `None`.
pub fn as_bool(&self) -> Option<bool> {
self.typed.as_bool()
}
/// `true` if the `Value` is an Array.
pub fn is_array(&self) -> bool {
self.typed.is_array()
}
/// `true` if the `Value` is of UUID type.
pub fn is_uuid(&self) -> bool {
self.typed.is_uuid()
}
/// Returns an UUID if the value is of UUID type, otherwise `None`.
pub fn as_uuid(&self) -> Option<Uuid> {
self.typed.as_uuid()
}
/// `true` if the `Value` is a DateTime.
pub fn is_datetime(&self) -> bool {
self.typed.is_datetime()
}
/// Returns a `DateTime` if the value is a `DateTime`, otherwise `None`.
pub fn as_datetime(&self) -> Option<DateTime<Utc>> {
self.typed.as_datetime()
}
/// `true` if the `Value` is a Date.
pub fn is_date(&self) -> bool {
self.typed.is_date()
}
/// Returns a `NaiveDate` if the value is a `Date`, otherwise `None`.
pub fn as_date(&self) -> Option<NaiveDate> {
self.typed.as_date()
}
/// `true` if the `Value` is a `Time`.
pub fn is_time(&self) -> bool {
self.typed.is_time()
}
/// Returns a `NaiveTime` if the value is a `Time`, otherwise `None`.
pub fn as_time(&self) -> Option<NaiveTime> {
self.typed.as_time()
}
/// `true` if the `Value` is a JSON value.
pub fn is_json(&self) -> bool {
self.typed.is_json()
}
/// Returns a reference to a JSON Value if of Json type, otherwise `None`.
pub fn as_json(&self) -> Option<&serde_json::Value> {
self.typed.as_json()
}
/// Transforms to a JSON Value if of Json type, otherwise `None`.
pub fn into_json(self) -> Option<serde_json::Value> {
self.typed.into_json()
}
/// Returns a `Vec<T>` if the value is an array of `T`, otherwise `None`.
pub fn into_vec<T>(self) -> Option<Vec<T>>
where
T: TryFrom<Value<'a>>,
{
self.typed.into_vec()
}
/// Returns a cloned Vec<T> if the value is an array of T, otherwise `None`.
pub fn to_vec<T>(&self) -> Option<Vec<T>>
where
T: TryFrom<Value<'a>>,
{
self.typed.to_vec()
}
pub fn null_int32() -> Self {
ValueType::Int32(None).into()
}
pub fn null_int64() -> Self {
ValueType::Int64(None).into()
}
pub fn null_float() -> Self {
ValueType::Float(None).into()
}
pub fn null_double() -> Self {
ValueType::Double(None).into()
}
pub fn null_text() -> Self {
ValueType::Text(None).into()
}
pub fn null_enum() -> Self {
ValueType::Enum(None, None).into()
}
pub fn null_enum_array() -> Self {
ValueType::EnumArray(None, None).into()
}
pub fn null_bytes() -> Self {
ValueType::Bytes(None).into()
}
pub fn null_boolean() -> Self {
ValueType::Boolean(None).into()
}
pub fn null_character() -> Self {
ValueType::Char(None).into()
}
pub fn null_array() -> Self {
ValueType::Array(None).into()
}
pub fn null_numeric() -> Self {
ValueType::Numeric(None).into()
}
pub fn null_json() -> Self {
ValueType::Json(None).into()
}
pub fn null_xml() -> Self {
ValueType::Xml(None).into()
}
pub fn null_uuid() -> Self {
ValueType::Uuid(None).into()
}
pub fn null_datetime() -> Self {
ValueType::DateTime(None).into()
}
pub fn null_date() -> Self {
ValueType::Date(None).into()
}
pub fn null_time() -> Self {
ValueType::Time(None).into()
}
}
impl<'a> Display for Value<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.typed.fmt(f)
}
}
impl<'a> From<ValueType<'a>> for Value<'a> {
fn from(inner: ValueType<'a>) -> Self {
Self {
typed: inner,
native_column_type: Default::default(),
}
}
}
impl<'a> From<Value<'a>> for ValueType<'a> {
fn from(val: Value<'a>) -> Self {
val.typed
}
}
/// A value we must parameterize for the prepared statement. Null values should be
/// defined by their corresponding type variants with a `None` value for best
/// compatibility.
#[derive(Debug, Clone, PartialEq)]
pub enum ValueType<'a> {
/// 32-bit signed integer.
Int32(Option<i32>),
/// 64-bit signed integer.
Int64(Option<i64>),
/// 32-bit floating point.
Float(Option<f32>),
/// 64-bit floating point.
Double(Option<f64>),
/// String value.
Text(Option<Cow<'a, str>>),
/// Database enum value.
/// The optional `EnumName` is only used on PostgreSQL.
/// Read more about it here: https://github.com/prisma/prisma-engines/pull/4280
Enum(Option<EnumVariant<'a>>, Option<EnumName<'a>>),
/// Database enum array (PostgreSQL specific).
/// We use a different variant than `ValueType::Array` to uplift the `EnumName`
/// and have it available even for empty enum arrays.
EnumArray(Option<Vec<EnumVariant<'a>>>, Option<EnumName<'a>>),
/// Bytes value.
Bytes(Option<Cow<'a, [u8]>>),
/// Boolean value.
Boolean(Option<bool>),
/// A single character.
Char(Option<char>),
/// An array value (PostgreSQL).
Array(Option<Vec<Value<'a>>>),
/// A numeric value.
Numeric(Option<BigDecimal>),
/// A JSON value.
Json(Option<serde_json::Value>),
/// A XML value.
Xml(Option<Cow<'a, str>>),
/// An UUID value.
Uuid(Option<Uuid>),
/// A datetime value.
DateTime(Option<DateTime<Utc>>),
/// A date value.
Date(Option<NaiveDate>),
/// A time value.
Time(Option<NaiveTime>),
}
pub(crate) struct Params<'a>(pub(crate) &'a [Value<'a>]);
impl<'a> Display for Params<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let len = self.0.len();
write!(f, "[")?;
for (i, val) in self.0.iter().enumerate() {
write!(f, "{val}")?;
if i < (len - 1) {
write!(f, ",")?;
}
}
write!(f, "]")
}
}
impl<'a> fmt::Display for ValueType<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res = match self {
ValueType::Int32(val) => val.map(|v| write!(f, "{v}")),
ValueType::Int64(val) => val.map(|v| write!(f, "{v}")),
ValueType::Float(val) => val.map(|v| write!(f, "{v}")),
ValueType::Double(val) => val.map(|v| write!(f, "{v}")),
ValueType::Text(val) => val.as_ref().map(|v| write!(f, "\"{v}\"")),
ValueType::Bytes(val) => val.as_ref().map(|v| write!(f, "<{} bytes blob>", v.len())),
ValueType::Enum(val, _) => val.as_ref().map(|v| write!(f, "\"{v}\"")),
ValueType::EnumArray(vals, _) => vals.as_ref().map(|vals| {
let len = vals.len();
write!(f, "[")?;
for (i, val) in vals.iter().enumerate() {
write!(f, "{val}")?;
if i < (len - 1) {
write!(f, ",")?;
}
}
write!(f, "]")
}),
ValueType::Boolean(val) => val.map(|v| write!(f, "{v}")),
ValueType::Char(val) => val.map(|v| write!(f, "'{v}'")),
ValueType::Array(vals) => vals.as_ref().map(|vals| {
let len = vals.len();
write!(f, "[")?;
for (i, val) in vals.iter().enumerate() {
write!(f, "{val}")?;
if i < (len - 1) {
write!(f, ",")?;
}
}
write!(f, "]")
}),
ValueType::Xml(val) => val.as_ref().map(|v| write!(f, "{v}")),
ValueType::Numeric(val) => val.as_ref().map(|v| write!(f, "{v}")),
ValueType::Json(val) => val.as_ref().map(|v| write!(f, "{v}")),
ValueType::Uuid(val) => val.map(|v| write!(f, "\"{v}\"")),
ValueType::DateTime(val) => val.map(|v| write!(f, "\"{v}\"")),
ValueType::Date(val) => val.map(|v| write!(f, "\"{v}\"")),
ValueType::Time(val) => val.map(|v| write!(f, "\"{v}\"")),
};
match res {
Some(r) => r,
None => write!(f, "null"),
}
}
}
impl<'a> From<Value<'a>> for serde_json::Value {
fn from(pv: Value<'a>) -> Self {
pv.typed.into()
}
}
impl<'a> From<ValueType<'a>> for serde_json::Value {
fn from(pv: ValueType<'a>) -> Self {
let res = match pv {
ValueType::Int32(i) => i.map(|i| serde_json::Value::Number(Number::from(i))),
ValueType::Int64(i) => i.map(|i| serde_json::Value::Number(Number::from(i))),
ValueType::Float(f) => f.map(|f| match Number::from_f64(f as f64) {
Some(number) => serde_json::Value::Number(number),
None => serde_json::Value::Null,
}),
ValueType::Double(f) => f.map(|f| match Number::from_f64(f) {
Some(number) => serde_json::Value::Number(number),
None => serde_json::Value::Null,
}),
ValueType::Text(cow) => cow.map(|cow| serde_json::Value::String(cow.into_owned())),
ValueType::Bytes(bytes) => bytes.map(|bytes| serde_json::Value::String(base64::encode(bytes))),
ValueType::Enum(cow, _) => cow.map(|cow| serde_json::Value::String(cow.into_owned())),
ValueType::EnumArray(values, _) => values.map(|values| {
serde_json::Value::Array(
values
.into_iter()
.map(|value| serde_json::Value::String(value.into_owned()))
.collect(),
)
}),
ValueType::Boolean(b) => b.map(serde_json::Value::Bool),
ValueType::Char(c) => c.map(|c| {
let bytes = [c as u8];
let s = std::str::from_utf8(&bytes)
.expect("interpret byte as UTF-8")
.to_string();
serde_json::Value::String(s)
}),
ValueType::Xml(cow) => cow.map(|cow| serde_json::Value::String(cow.into_owned())),
ValueType::Array(v) => {
v.map(|v| serde_json::Value::Array(v.into_iter().map(serde_json::Value::from).collect()))
}
ValueType::Numeric(d) => d.map(|d| serde_json::to_value(d.to_f64().unwrap()).unwrap()),
ValueType::Json(v) => v,
ValueType::Uuid(u) => u.map(|u| serde_json::Value::String(u.hyphenated().to_string())),
ValueType::DateTime(dt) => dt.map(|dt| serde_json::Value::String(dt.to_rfc3339())),
ValueType::Date(date) => date.map(|date| serde_json::Value::String(format!("{date}"))),
ValueType::Time(time) => time.map(|time| serde_json::Value::String(format!("{time}"))),
};
match res {
Some(val) => val,
None => serde_json::Value::Null,
}
}
}
impl<'a> ValueType<'a> {
pub fn into_value(self) -> Value<'a> {
self.into()
}
/// Creates a new 32-bit signed integer.
pub(crate) fn int32<I>(value: I) -> Self
where
I: Into<i32>,
{
Self::Int32(Some(value.into()))
}
/// Creates a new 64-bit signed integer.
pub(crate) fn int64<I>(value: I) -> Self
where
I: Into<i64>,
{
Self::Int64(Some(value.into()))
}
/// Creates a new decimal value.
pub(crate) fn numeric(value: BigDecimal) -> Self {
Self::Numeric(Some(value))
}
/// Creates a new float value.
pub(crate) fn float(value: f32) -> Self {
Self::Float(Some(value))
}
/// Creates a new double value.
pub(crate) fn double(value: f64) -> Self {
Self::Double(Some(value))
}
/// Creates a new string value.
pub(crate) fn text<T>(value: T) -> Self
where
T: Into<Cow<'a, str>>,
{
Self::Text(Some(value.into()))
}
/// Creates a new enum value.
pub(crate) fn enum_variant<T>(value: T) -> Self
where
T: Into<EnumVariant<'a>>,
{
Self::Enum(Some(value.into()), None)
}
/// Creates a new enum value with the name of the enum attached.
pub(crate) fn enum_variant_with_name<T, U>(value: T, enum_name: U) -> Self
where
T: Into<EnumVariant<'a>>,
U: Into<EnumName<'a>>,
{
Self::Enum(Some(value.into()), Some(enum_name.into()))
}
/// Creates a new enum array value
pub(crate) fn enum_array<T>(value: T) -> Self
where
T: IntoIterator<Item = EnumVariant<'a>>,
{
Self::EnumArray(Some(value.into_iter().collect()), None)
}
/// Creates a new enum array value with the name of the enum attached.
pub(crate) fn enum_array_with_name<T, U>(value: T, name: U) -> Self
where
T: IntoIterator<Item = EnumVariant<'a>>,
U: Into<EnumName<'a>>,
{
Self::EnumArray(Some(value.into_iter().collect()), Some(name.into()))
}
/// Creates a new bytes value.
pub(crate) fn bytes<B>(value: B) -> Self
where
B: Into<Cow<'a, [u8]>>,
{
Self::Bytes(Some(value.into()))
}
/// Creates a new boolean value.
pub(crate) fn boolean<B>(value: B) -> Self
where
B: Into<bool>,
{
Self::Boolean(Some(value.into()))
}
/// Creates a new character value.
pub(crate) fn character<C>(value: C) -> Self
where
C: Into<char>,
{
Self::Char(Some(value.into()))
}
/// Creates a new array value.
pub(crate) fn array<I, V>(value: I) -> Self
where
I: IntoIterator<Item = V>,
V: Into<Value<'a>>,
{
Self::Array(Some(value.into_iter().map(|v| v.into()).collect()))
}
/// Creates a new uuid value.
pub(crate) fn uuid(value: Uuid) -> Self {
Self::Uuid(Some(value))
}
/// Creates a new datetime value.
pub(crate) fn datetime(value: DateTime<Utc>) -> Self {
Self::DateTime(Some(value))
}
/// Creates a new date value.
pub(crate) fn date(value: NaiveDate) -> Self {
Self::Date(Some(value))
}
/// Creates a new time value.
pub(crate) fn time(value: NaiveTime) -> Self {
Self::Time(Some(value))
}
/// Creates a new JSON value.
pub(crate) fn json(value: serde_json::Value) -> Self {
Self::Json(Some(value))
}
/// Creates a new XML value.
pub(crate) fn xml<T>(value: T) -> Self
where
T: Into<Cow<'a, str>>,
{
Self::Xml(Some(value.into()))
}
/// `true` if the `Value` is null.
pub fn is_null(&self) -> bool {
match self {
Self::Int32(i) => i.is_none(),
Self::Int64(i) => i.is_none(),
Self::Float(i) => i.is_none(),
Self::Double(i) => i.is_none(),
Self::Text(t) => t.is_none(),
Self::Enum(e, _) => e.is_none(),
Self::EnumArray(e, _) => e.is_none(),
Self::Bytes(b) => b.is_none(),
Self::Boolean(b) => b.is_none(),
Self::Char(c) => c.is_none(),
Self::Array(v) => v.is_none(),
Self::Xml(s) => s.is_none(),
Self::Numeric(r) => r.is_none(),
Self::Uuid(u) => u.is_none(),
Self::DateTime(dt) => dt.is_none(),
Self::Date(d) => d.is_none(),
Self::Time(t) => t.is_none(),
Self::Json(json) => json.is_none(),
}
}
/// `true` if the `Value` is text.
pub(crate) fn is_text(&self) -> bool {
matches!(self, Self::Text(_))
}
/// Returns a &str if the value is text, otherwise `None`.
pub(crate) fn as_str(&self) -> Option<&str> {
match self {
Self::Text(Some(cow)) => Some(cow.borrow()),
Self::Bytes(Some(cow)) => std::str::from_utf8(cow.as_ref()).ok(),
_ => None,
}
}
/// Returns a char if the value is a char, otherwise `None`.
pub(crate) fn as_char(&self) -> Option<char> {
match self {
Self::Char(c) => *c,
_ => None,
}
}
/// Returns a cloned String if the value is text, otherwise `None`.
pub(crate) fn to_string(&self) -> Option<String> {
match self {
Self::Text(Some(cow)) => Some(cow.to_string()),
Self::Bytes(Some(cow)) => std::str::from_utf8(cow.as_ref()).map(|s| s.to_owned()).ok(),
_ => None,
}
}
/// Transforms the `Value` to a `String` if it's text,
/// otherwise `None`.
pub(crate) fn into_string(self) -> Option<String> {
match self {
Self::Text(Some(cow)) => Some(cow.into_owned()),
Self::Bytes(Some(cow)) => String::from_utf8(cow.into_owned()).ok(),
_ => None,
}
}
/// Returns whether this value is the `Bytes` variant.
pub(crate) fn is_bytes(&self) -> bool {
matches!(self, Self::Bytes(_))
}
/// Returns a bytes slice if the value is text or a byte slice, otherwise `None`.
pub(crate) fn as_bytes(&self) -> Option<&[u8]> {
match self {
Self::Text(Some(cow)) => Some(cow.as_ref().as_bytes()),
Self::Bytes(Some(cow)) => Some(cow.as_ref()),
_ => None,
}
}
/// Returns a cloned `Vec<u8>` if the value is text or a byte slice, otherwise `None`.
pub(crate) fn to_bytes(&self) -> Option<Vec<u8>> {
match self {
Self::Text(Some(cow)) => Some(cow.to_string().into_bytes()),
Self::Bytes(Some(cow)) => Some(cow.to_vec()),
_ => None,
}
}
/// `true` if the `Value` is a 32-bit signed integer.
pub(crate) fn is_i32(&self) -> bool {
matches!(self, Self::Int32(_))
}
/// `true` if the `Value` is a 64-bit signed integer.
pub(crate) fn is_i64(&self) -> bool {
matches!(self, Self::Int64(_))
}
/// `true` if the `Value` is a signed integer.
pub fn is_integer(&self) -> bool {
matches!(self, Self::Int32(_) | Self::Int64(_))
}
/// Returns an `i64` if the value is a 64-bit signed integer, otherwise `None`.
pub(crate) fn as_i64(&self) -> Option<i64> {
match self {
Self::Int64(i) => *i,
_ => None,
}
}
/// Returns an `i32` if the value is a 32-bit signed integer, otherwise `None`.
pub(crate) fn as_i32(&self) -> Option<i32> {
match self {
Self::Int32(i) => *i,
_ => None,
}
}
/// Returns an `i64` if the value is a signed integer, otherwise `None`.
pub fn as_integer(&self) -> Option<i64> {
match self {
Self::Int32(i) => i.map(|i| i as i64),
Self::Int64(i) => *i,
_ => None,
}
}
/// Returns a `f64` if the value is a double, otherwise `None`.
pub(crate) fn as_f64(&self) -> Option<f64> {
match self {
Self::Double(Some(f)) => Some(*f),
_ => None,
}
}
/// Returns a `f32` if the value is a double, otherwise `None`.
pub(crate) fn as_f32(&self) -> Option<f32> {
match self {
Self::Float(Some(f)) => Some(*f),
_ => None,
}
}
/// `true` if the `Value` is a numeric value or can be converted to one.
pub(crate) fn is_numeric(&self) -> bool {
matches!(self, Self::Numeric(_) | Self::Float(_) | Self::Double(_))
}
/// Returns a bigdecimal, if the value is a numeric, float or double value,
/// otherwise `None`.
pub(crate) fn into_numeric(self) -> Option<BigDecimal> {
match self {
Self::Numeric(d) => d,
Self::Float(f) => f.and_then(BigDecimal::from_f32),
Self::Double(f) => f.and_then(BigDecimal::from_f64),
_ => None,
}
}
/// Returns a reference to a bigdecimal, if the value is a numeric.
/// Otherwise `None`.
pub(crate) fn as_numeric(&self) -> Option<&BigDecimal> {
match self {
Self::Numeric(d) => d.as_ref(),
_ => None,
}
}
/// `true` if the `Value` is a boolean value.
pub(crate) fn is_bool(&self) -> bool {
match self {
Self::Boolean(_) => true,
// For schemas which don't tag booleans
Self::Int32(Some(i)) if *i == 0 || *i == 1 => true,
Self::Int64(Some(i)) if *i == 0 || *i == 1 => true,
_ => false,