1use std::borrow::Cow;
18use std::fmt;
19use std::str::FromStr;
20
21use navree_datetime::{Date, DateTime, Offset, Time, Timestamp, Zone, Zoned};
22use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
23use uuid::Uuid;
24
25pub use navree_db::{Kind, Value};
26pub use rust_decimal::Decimal;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum FieldError {
32 Null,
34 Missing,
36 Invalid(String),
38}
39
40impl fmt::Display for FieldError {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 match self {
43 FieldError::Null => f.write_str("the value is NULL (make the field an Option)"),
44 FieldError::Missing => f.write_str("the row has no such column"),
45 FieldError::Invalid(message) => f.write_str(message),
46 }
47 }
48}
49
50impl std::error::Error for FieldError {}
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56#[non_exhaustive]
57pub enum FieldKind {
58 Bool,
60 Integer {
62 bits: u8,
64 signed: bool,
66 },
67 Float {
69 bits: u8,
71 },
72 Decimal,
74 Text,
76 Bytes,
78 Uuid,
80 Ulid,
82 Date,
84 Time,
86 DateTime,
88 Json,
90 Url,
92 Vector,
94 Any,
96}
97
98pub trait Field: Sized + Send + Sync + 'static {
119 const KIND: FieldKind = FieldKind::Any;
122
123 fn to_value(&self) -> Value;
125
126 fn null() -> Value;
128
129 fn from_sql(row: &navree_db::Row, column: &str) -> Result<Self, FieldError> {
134 Self::from_value(column_value(row, column)?)
135 }
136
137 fn from_value(value: Value) -> Result<Self, FieldError>;
140
141 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
160 Self::from_value(json_to_value(json))
161 }
162
163 fn type_name() -> Cow<'static, str>;
165}
166
167pub(crate) fn column_value(row: &navree_db::Row, column: &str) -> Result<Value, FieldError> {
171 let Some(index) = row.column_index(column) else {
172 return Err(FieldError::Missing);
173 };
174 row.value(index)
175 .map_err(|error| FieldError::Invalid(error.to_string()))
176}
177
178pub(crate) fn json_to_value(json: serde_json::Value) -> Value {
182 use serde_json::Value as Json;
183
184 match json {
185 Json::Null => Value::Null(Kind::Json),
186 Json::Bool(b) => Value::Bool(b),
187 Json::Number(n) => match (n.as_i64(), n.as_u64(), n.as_f64()) {
188 (Some(i), _, _) => Value::I64(i),
189 (None, Some(u), _) => Value::U64(u),
190 (None, None, Some(f)) => Value::F64(f),
191 (None, None, None) => Value::String(n.to_string()),
192 },
193 Json::String(s) => Value::String(s),
194 other => Value::Json(other),
195 }
196}
197
198pub fn is_null(value: &Value) -> bool {
207 value.is_null()
208}
209
210pub fn to_json(value: &Value) -> serde_json::Value {
224 use serde_json::Value as Json;
225
226 fn serde<T: serde::Serialize>(value: &T) -> Json {
227 serde_json::to_value(value).unwrap_or(Json::Null)
228 }
229 fn float(value: f64) -> Json {
230 serde_json::Number::from_f64(value).map_or(Json::Null, Json::Number)
231 }
232
233 match value {
234 Value::Null(_) => Json::Null,
235 Value::Bool(v) => Json::Bool(*v),
236 Value::I8(v) => Json::from(*v),
237 Value::I16(v) => Json::from(*v),
238 Value::I32(v) => Json::from(*v),
239 Value::I64(v) => Json::from(*v),
240 Value::U8(v) => Json::from(*v),
241 Value::U16(v) => Json::from(*v),
242 Value::U32(v) => Json::from(*v),
243 Value::U64(v) => Json::from(*v),
244 Value::F32(v) => float(f64::from(*v)),
245 Value::F64(v) => float(*v),
246 Value::String(v) => Json::String(v.clone()),
247 Value::Bytes(v) => serde(v),
248 Value::Json(v) => v.clone(),
249 Value::Date(v) => serde(v),
250 Value::Time(v) => serde(v),
251 Value::DateTime(v) => serde(v),
252 Value::Timestamp(v) => serde(v),
253 Value::TimestampTz(v) => serde(v),
254 Value::Uuid(v) => Json::String(v.to_string()),
255 Value::Decimal(v) => Json::String(v.to_string()),
256 other => other.to_json(),
259 }
260}
261
262pub fn same_value(a: &Value, b: &Value) -> bool {
279 match (is_null(a), is_null(b)) {
280 (true, true) => return true,
281 (true, false) | (false, true) => return false,
282 (false, false) => {}
283 }
284 match (a, b) {
285 (Value::F32(_) | Value::F64(_), Value::F32(_) | Value::F64(_)) => {
286 match (float(a), float(b)) {
287 (Ok(x), Ok(y)) => {
288 x == y || (x - y).abs() <= f64::EPSILON * 4.0 * x.abs().max(y.abs()).max(1.0)
289 }
290 _ => false,
291 }
292 }
293 (Value::Decimal(x), Value::Decimal(y)) => x == y,
294 (
295 Value::Timestamp(_) | Value::TimestampTz(_),
296 Value::Timestamp(_) | Value::TimestampTz(_),
297 ) => match (date_time_utc(a.clone()), date_time_utc(b.clone())) {
298 (Ok(x), Ok(y)) => x == y,
299 _ => false,
300 },
301 _ => a == b,
302 }
303}
304
305pub(crate) fn describe(value: &Value) -> &'static str {
307 match value {
308 Value::Null(_) => "NULL",
309 Value::Bool(_) => "a boolean",
310 Value::I8(_)
311 | Value::I16(_)
312 | Value::I32(_)
313 | Value::I64(_)
314 | Value::U8(_)
315 | Value::U16(_)
316 | Value::U32(_)
317 | Value::U64(_) => "an integer",
318 Value::F32(_) | Value::F64(_) => "a float",
319 Value::Decimal(_) => "a decimal",
320 Value::String(_) => "a string",
321 Value::Bytes(_) => "bytes",
322 Value::Json(_) => "JSON",
323 Value::Date(_) => "a date",
324 Value::Time(_) => "a time",
325 Value::DateTime(_) | Value::Timestamp(_) | Value::TimestampTz(_) => "a date-time",
326 Value::Uuid(_) => "a UUID",
327 Value::Enum { .. } => "an enum value",
328 Value::Vector(_) => "a vector",
329 _ => "a value of another type",
330 }
331}
332
333fn mismatch(value: &Value, wanted: &str) -> FieldError {
334 FieldError::Invalid(format!("expected {wanted}, found {}", describe(value)))
335}
336
337fn null_check(value: &Value) -> Result<(), FieldError> {
338 if is_null(value) {
339 Err(FieldError::Null)
340 } else {
341 Ok(())
342 }
343}
344
345fn integer(value: &Value) -> Result<i128, FieldError> {
348 null_check(value)?;
349 let wanted = "an integer";
350 match value {
351 Value::Bool(b) => Ok(i128::from(*b)),
352 Value::I8(v) => Ok(i128::from(*v)),
353 Value::I16(v) => Ok(i128::from(*v)),
354 Value::I32(v) => Ok(i128::from(*v)),
355 Value::I64(v) => Ok(i128::from(*v)),
356 Value::U8(v) => Ok(i128::from(*v)),
357 Value::U16(v) => Ok(i128::from(*v)),
358 Value::U32(v) => Ok(i128::from(*v)),
359 Value::U64(v) => Ok(i128::from(*v)),
360 Value::F32(v) => integral_float(f64::from(*v)),
361 Value::F64(v) => integral_float(*v),
362 Value::Decimal(v) if v.fract().is_zero() => v
363 .to_i128()
364 .ok_or_else(|| FieldError::Invalid(format!("{v} is out of range"))),
365 Value::Decimal(v) => Err(FieldError::Invalid(format!("{v} is not a whole number"))),
366 Value::String(s) => s
367 .trim()
368 .parse::<i128>()
369 .map_err(|_| FieldError::Invalid(format!("`{s}` is not an integer"))),
370 Value::Json(json) => json
371 .as_i64()
372 .map(i128::from)
373 .ok_or_else(|| mismatch(value, wanted)),
374 other => Err(mismatch(other, wanted)),
375 }
376}
377
378fn integral_float(v: f64) -> Result<i128, FieldError> {
379 if v.is_finite() && v.fract() == 0.0 && v.abs() < 1.7e38 {
380 #[allow(clippy::cast_possible_truncation)]
382 Ok(v as i128)
383 } else {
384 Err(FieldError::Invalid(format!("{v} is not a whole number")))
385 }
386}
387
388fn float(value: &Value) -> Result<f64, FieldError> {
390 null_check(value)?;
391 match value {
392 Value::F32(v) => Ok(f64::from(*v)),
393 Value::F64(v) => Ok(*v),
394 Value::Decimal(v) => v
395 .to_f64()
396 .ok_or_else(|| FieldError::Invalid(format!("{v} does not fit a float"))),
397 Value::String(s) => s
398 .trim()
399 .parse::<f64>()
400 .map_err(|_| FieldError::Invalid(format!("`{s}` is not a number"))),
401 Value::Json(json) => json.as_f64().ok_or_else(|| mismatch(value, "a number")),
402 other => {
403 let int = integer(other).map_err(|_| mismatch(other, "a number"))?;
404 #[allow(clippy::cast_precision_loss)]
406 Ok(int as f64)
407 }
408 }
409}
410
411fn decimal(value: &Value) -> Result<Decimal, FieldError> {
413 null_check(value)?;
414 match value {
415 Value::Decimal(v) => Ok(*v),
416 Value::F32(v) => Decimal::from_f32(*v)
417 .ok_or_else(|| FieldError::Invalid(format!("{v} does not fit a decimal"))),
418 Value::F64(v) => Decimal::from_f64(*v)
419 .ok_or_else(|| FieldError::Invalid(format!("{v} does not fit a decimal"))),
420 Value::String(s) => Decimal::from_str(s.trim())
421 .or_else(|_| Decimal::from_scientific(s.trim()))
422 .map_err(|_| FieldError::Invalid(format!("`{s}` is not a decimal"))),
423 other => {
424 let int = integer(other).map_err(|_| mismatch(other, "a decimal"))?;
425 Decimal::from_i128(int)
426 .ok_or_else(|| FieldError::Invalid(format!("{int} does not fit a decimal")))
427 }
428 }
429}
430
431fn boolean(value: &Value) -> Result<bool, FieldError> {
432 null_check(value)?;
433 match value {
434 Value::Bool(b) => Ok(*b),
435 Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
436 "true" | "t" | "1" | "yes" | "y" | "on" => Ok(true),
437 "false" | "f" | "0" | "no" | "n" | "off" => Ok(false),
438 _ => Err(FieldError::Invalid(format!("`{s}` is not a boolean"))),
439 },
440 Value::Json(json) => json.as_bool().ok_or_else(|| mismatch(value, "a boolean")),
441 other => match integer(other) {
442 Ok(0) => Ok(false),
443 Ok(1) => Ok(true),
444 Ok(n) => Err(FieldError::Invalid(format!(
445 "{n} is not a boolean (0 or 1)"
446 ))),
447 Err(_) => Err(mismatch(other, "a boolean")),
448 },
449 }
450}
451
452fn string(value: Value) -> Result<String, FieldError> {
453 null_check(&value)?;
454 match value {
455 Value::String(s) => Ok(s),
456 Value::Uuid(u) => Ok(u.to_string()),
457 Value::Enum { value, .. } => Ok(value),
458 Value::Json(json) => match json {
459 serde_json::Value::String(s) => Ok(s),
460 other => Ok(other.to_string()),
461 },
462 Value::Bytes(bytes) => String::from_utf8(bytes)
463 .map_err(|_| FieldError::Invalid("the bytes are not UTF-8 text".to_owned())),
464 Value::Decimal(d) => Ok(d.to_string()),
465 other => Err(mismatch(&other, "a string")),
466 }
467}
468
469fn bytes(value: Value) -> Result<Vec<u8>, FieldError> {
470 null_check(&value)?;
471 match value {
472 Value::Bytes(b) => Ok(b),
473 Value::String(s) => Ok(s.into_bytes()),
474 Value::Uuid(u) => Ok(u.as_bytes().to_vec()),
475 other => Err(mismatch(&other, "bytes")),
476 }
477}
478
479fn uuid(value: Value) -> Result<Uuid, FieldError> {
480 null_check(&value)?;
481 match value {
482 Value::Uuid(u) => Ok(u),
483 Value::String(s) => Uuid::parse_str(s.trim())
484 .map_err(|_| FieldError::Invalid(format!("`{s}` is not a UUID"))),
485 Value::Bytes(b) if b.len() == 16 => Uuid::from_slice(&b)
486 .map_err(|_| FieldError::Invalid(format!("{} bytes are not a UUID", b.len()))),
487 Value::Bytes(b) => std::str::from_utf8(&b)
488 .ok()
489 .and_then(|text| Uuid::parse_str(text.trim()).ok())
490 .ok_or_else(|| FieldError::Invalid(format!("{} bytes are not a UUID", b.len()))),
491 Value::Json(json) => match json.as_str() {
492 Some(s) => {
493 Uuid::parse_str(s).map_err(|_| FieldError::Invalid(format!("`{s}` is not a UUID")))
494 }
495 None => Err(FieldError::Invalid(
496 "JSON that is not a UUID string".to_owned(),
497 )),
498 },
499 other => Err(mismatch(&other, "a UUID")),
500 }
501}
502
503fn json(value: Value) -> Result<serde_json::Value, FieldError> {
504 null_check(&value)?;
505 match value {
506 Value::Json(json) => Ok(json),
507 Value::String(s) => serde_json::from_str(&s)
508 .map_err(|error| FieldError::Invalid(format!("the text is not JSON: {error}"))),
509 Value::Bytes(b) => serde_json::from_slice(&b)
510 .map_err(|error| FieldError::Invalid(format!("the bytes are not JSON: {error}"))),
511 other => Ok(to_json(&other)),
512 }
513}
514
515const DATE_TIME_FORMATS: [&str; 2] = ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S%.f"];
518
519fn parse_offset_date_time(s: &str) -> Option<Zoned> {
520 let s = s.trim();
521 Zoned::parse_rfc3339(s)
522 .ok()
523 .or_else(|| Zoned::parse("%Y-%m-%d %H:%M:%S%.f%:z", s).ok())
524 .or_else(|| Zoned::parse("%Y-%m-%d %H:%M:%S%.f%z", s).ok())
525 .or_else(|| Zoned::parse("%Y-%m-%d %H:%M:%S%.f %:z", s).ok())
526}
527
528fn parse_naive_date_time(s: &str) -> Option<DateTime> {
529 let s = s.trim();
530 DATE_TIME_FORMATS
531 .iter()
532 .find_map(|format| DateTime::parse(format, s).ok())
533 .or_else(|| {
534 Date::parse("%Y-%m-%d", s)
535 .ok()
536 .map(|date| date.at(Time::MIDNIGHT))
537 })
538}
539
540fn date_time_utc(value: Value) -> Result<Timestamp, FieldError> {
541 null_check(&value)?;
542 match value {
543 Value::Timestamp(v) => Ok(v),
544 Value::TimestampTz(v) => Ok(v.timestamp()),
545 Value::DateTime(v) => Ok(v.in_utc()),
546 Value::Date(v) => Ok(v.at(Time::MIDNIGHT).in_utc()),
547 Value::String(s) => parse_offset_date_time(&s)
548 .map(|v| v.timestamp())
549 .or_else(|| parse_naive_date_time(&s).map(|v| v.in_utc()))
550 .ok_or_else(|| FieldError::Invalid(format!("`{s}` is not a date-time"))),
551 Value::Bool(_) => Err(mismatch(&value, "a date-time")),
553 other => match integer(&other) {
554 Ok(seconds) => i64::try_from(seconds)
556 .ok()
557 .and_then(|s| Timestamp::from_secs(s).ok())
558 .ok_or_else(|| FieldError::Invalid(format!("{seconds} is out of range"))),
559 Err(_) => Err(mismatch(&other, "a date-time")),
560 },
561 }
562}
563
564fn date_time_offset(value: Value) -> Result<Zoned, FieldError> {
565 null_check(&value)?;
566 match value {
567 Value::TimestampTz(v) => Ok(v),
568 Value::String(s) => parse_offset_date_time(&s)
569 .or_else(|| {
570 parse_naive_date_time(&s).map(|v| v.in_utc().in_zone(Zone::fixed(Offset::UTC)))
571 })
572 .ok_or_else(|| FieldError::Invalid(format!("`{s}` is not a date-time"))),
573 other => date_time_utc(other).map(|v| v.in_zone(Zone::fixed(Offset::UTC))),
574 }
575}
576
577fn naive_date_time(value: Value) -> Result<DateTime, FieldError> {
578 null_check(&value)?;
579 match value {
580 Value::DateTime(v) => Ok(v),
581 Value::Timestamp(v) => Ok(v.date_time_utc()),
582 Value::TimestampTz(v) => Ok(v.timestamp().date_time_utc()),
583 Value::Date(v) => Ok(v.at(Time::MIDNIGHT)),
584 Value::String(s) => parse_naive_date_time(&s)
585 .or_else(|| parse_offset_date_time(&s).map(|v| v.timestamp().date_time_utc()))
586 .ok_or_else(|| FieldError::Invalid(format!("`{s}` is not a date-time"))),
587 other => Err(mismatch(&other, "a date-time")),
588 }
589}
590
591fn naive_date(value: Value) -> Result<Date, FieldError> {
592 null_check(&value)?;
593 match value {
594 Value::Date(v) => Ok(v),
595 Value::DateTime(v) => Ok(v.date()),
596 Value::Timestamp(v) => Ok(v.date_time_utc().date()),
597 Value::TimestampTz(v) => Ok(v.timestamp().date_time_utc().date()),
598 Value::String(s) => Date::parse("%Y-%m-%d", s.trim())
599 .ok()
600 .or_else(|| parse_naive_date_time(&s).map(|v| v.date()))
601 .ok_or_else(|| FieldError::Invalid(format!("`{s}` is not a date"))),
602 other => Err(mismatch(&other, "a date")),
603 }
604}
605
606fn naive_time(value: Value) -> Result<Time, FieldError> {
607 null_check(&value)?;
608 match value {
609 Value::Time(v) => Ok(v),
610 Value::DateTime(v) => Ok(v.time()),
611 Value::String(s) => Time::parse("%H:%M:%S%.f", s.trim())
612 .or_else(|_| Time::parse("%H:%M", s.trim()))
613 .map_err(|_| FieldError::Invalid(format!("`{s}` is not a time"))),
614 other => Err(mismatch(&other, "a time")),
615 }
616}
617
618macro_rules! exact_field {
620 ($ty:ty, $name:literal, $kind:expr, $null:expr, $from_value:expr) => {
621 impl Field for $ty {
622 const KIND: FieldKind = $kind;
623
624 fn to_value(&self) -> Value {
625 Value::from(self.clone())
626 }
627
628 fn null() -> Value {
629 $null
630 }
631
632 fn from_value(value: Value) -> Result<Self, FieldError> {
633 $from_value(value)
634 }
635
636 fn type_name() -> Cow<'static, str> {
637 Cow::Borrowed($name)
638 }
639 }
640 };
641}
642
643macro_rules! integer_field {
646 ($ty:ty, $name:literal, $bits:literal, $signed:literal, $null:expr) => {
647 impl Field for $ty {
648 const KIND: FieldKind = FieldKind::Integer {
649 bits: $bits,
650 signed: $signed,
651 };
652
653 fn to_value(&self) -> Value {
654 Value::from(*self)
655 }
656
657 fn null() -> Value {
658 $null
659 }
660
661 fn from_value(value: Value) -> Result<Self, FieldError> {
662 let int = integer(&value)?;
663 <$ty>::try_from(int)
664 .map_err(|_| FieldError::Invalid(format!("{int} does not fit {}", $name)))
665 }
666
667 fn type_name() -> Cow<'static, str> {
668 Cow::Borrowed($name)
669 }
670 }
671 };
672}
673
674integer_field!(i8, "i8", 8, true, Value::Null(Kind::I8));
675integer_field!(i16, "i16", 16, true, Value::Null(Kind::I16));
676integer_field!(i32, "i32", 32, true, Value::Null(Kind::I32));
677integer_field!(i64, "i64", 64, true, Value::Null(Kind::I64));
678integer_field!(u8, "u8", 8, false, Value::Null(Kind::U8));
679integer_field!(u16, "u16", 16, false, Value::Null(Kind::U16));
680integer_field!(u32, "u32", 32, false, Value::Null(Kind::U32));
681integer_field!(u64, "u64", 64, false, Value::Null(Kind::U64));
682
683exact_field!(
684 bool,
685 "bool",
686 FieldKind::Bool,
687 Value::Null(Kind::Bool),
688 |value: Value| boolean(&value)
689);
690
691impl Field for f32 {
692 const KIND: FieldKind = FieldKind::Float { bits: 32 };
693
694 fn to_value(&self) -> Value {
695 Value::F32(*self)
696 }
697
698 fn null() -> Value {
699 Value::Null(Kind::F32)
700 }
701
702 fn from_value(value: Value) -> Result<Self, FieldError> {
703 #[allow(clippy::cast_possible_truncation)]
705 float(&value).map(|v| v as f32)
706 }
707
708 fn type_name() -> Cow<'static, str> {
709 Cow::Borrowed("f32")
710 }
711}
712
713impl Field for f64 {
714 const KIND: FieldKind = FieldKind::Float { bits: 64 };
715
716 fn to_value(&self) -> Value {
717 Value::F64(*self)
718 }
719
720 fn null() -> Value {
721 Value::Null(Kind::F64)
722 }
723
724 fn from_value(value: Value) -> Result<Self, FieldError> {
725 float(&value)
726 }
727
728 fn type_name() -> Cow<'static, str> {
729 Cow::Borrowed("f64")
730 }
731}
732exact_field!(
733 String,
734 "String",
735 FieldKind::Text,
736 Value::Null(Kind::String),
737 string
738);
739
740impl Field for Vec<u8> {
743 const KIND: FieldKind = FieldKind::Bytes;
744
745 fn to_value(&self) -> Value {
746 Value::from(self.clone())
747 }
748
749 fn null() -> Value {
750 Value::Null(Kind::Bytes)
751 }
752
753 fn from_value(value: Value) -> Result<Self, FieldError> {
754 bytes(value)
755 }
756
757 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
758 match json {
759 serde_json::Value::Array(items) => items
760 .iter()
761 .map(|item| {
762 item.as_u64()
763 .and_then(|n| u8::try_from(n).ok())
764 .ok_or_else(|| {
765 FieldError::Invalid(format!("{item} is not a byte (0 to 255)"))
766 })
767 })
768 .collect(),
769 serde_json::Value::Null => Err(FieldError::Null),
770 other => bytes(json_to_value(other)),
771 }
772 }
773
774 fn type_name() -> Cow<'static, str> {
775 Cow::Borrowed("Vec<u8>")
776 }
777}
778
779impl Field for Uuid {
782 const KIND: FieldKind = FieldKind::Uuid;
783
784 fn to_value(&self) -> Value {
785 Value::Uuid(*self)
786 }
787
788 fn null() -> Value {
789 Value::Null(Kind::Uuid)
790 }
791
792 fn from_value(value: Value) -> Result<Self, FieldError> {
793 uuid(value)
794 }
795
796 fn type_name() -> Cow<'static, str> {
797 Cow::Borrowed("Uuid")
798 }
799}
800
801macro_rules! parsed_field {
804 ($ty:ty, $name:literal, $kind:expr, $null:expr, $parse:expr) => {
805 impl Field for $ty {
806 const KIND: FieldKind = $kind;
807
808 fn to_value(&self) -> Value {
809 Value::from(self.clone())
810 }
811
812 fn null() -> Value {
813 $null
814 }
815
816 fn from_value(value: Value) -> Result<Self, FieldError> {
817 $parse(value)
818 }
819
820 fn type_name() -> Cow<'static, str> {
821 Cow::Borrowed($name)
822 }
823 }
824 };
825}
826
827impl Field for serde_json::Value {
830 const KIND: FieldKind = FieldKind::Json;
831
832 fn to_value(&self) -> Value {
833 Value::from(self.clone())
834 }
835
836 fn null() -> Value {
837 Value::Null(Kind::Json)
838 }
839
840 fn from_value(value: Value) -> Result<Self, FieldError> {
841 json(value)
842 }
843
844 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
845 Ok(json)
846 }
847
848 fn type_name() -> Cow<'static, str> {
849 Cow::Borrowed("serde_json::Value")
850 }
851}
852
853parsed_field!(
854 Date,
855 "Date",
856 FieldKind::Date,
857 Value::Null(Kind::Date),
858 naive_date
859);
860parsed_field!(
861 Time,
862 "Time",
863 FieldKind::Time,
864 Value::Null(Kind::Time),
865 naive_time
866);
867parsed_field!(
868 DateTime,
869 "DateTime",
870 FieldKind::DateTime,
871 Value::Null(Kind::DateTime),
872 naive_date_time
873);
874parsed_field!(
875 Timestamp,
876 "Timestamp",
877 FieldKind::DateTime,
878 Value::Null(Kind::Timestamp),
879 date_time_utc
880);
881parsed_field!(
882 Zoned,
883 "Zoned",
884 FieldKind::DateTime,
885 Value::Null(Kind::TimestampTz),
886 date_time_offset
887);
888
889impl Field for Decimal {
893 const KIND: FieldKind = FieldKind::Decimal;
894
895 fn to_value(&self) -> Value {
896 Value::Decimal(*self)
897 }
898
899 fn null() -> Value {
900 Value::Null(Kind::Decimal)
901 }
902
903 fn from_value(value: Value) -> Result<Self, FieldError> {
904 decimal(&value)
905 }
906
907 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
910 match json {
911 serde_json::Value::Number(number) => decimal(&Value::String(number.to_string())),
912 other => decimal(&json_to_value(other)),
913 }
914 }
915
916 fn type_name() -> Cow<'static, str> {
917 Cow::Borrowed("Decimal")
918 }
919}
920
921impl<T: Field> Field for Option<T> {
922 const KIND: FieldKind = T::KIND;
923
924 fn to_value(&self) -> Value {
925 match self {
926 Some(value) => value.to_value(),
927 None => T::null(),
928 }
929 }
930
931 fn null() -> Value {
932 T::null()
933 }
934
935 fn from_sql(row: &navree_db::Row, column: &str) -> Result<Self, FieldError> {
936 match T::from_sql(row, column) {
937 Ok(value) => Ok(Some(value)),
938 Err(FieldError::Null) => Ok(None),
939 Err(error) => Err(error),
940 }
941 }
942
943 fn from_value(value: Value) -> Result<Self, FieldError> {
944 if is_null(&value) {
945 Ok(None)
946 } else {
947 T::from_value(value).map(Some)
948 }
949 }
950
951 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
952 if json.is_null() {
953 Ok(None)
954 } else {
955 T::from_json(json).map(Some)
956 }
957 }
958
959 fn type_name() -> Cow<'static, str> {
960 Cow::Owned(format!("Option<{}>", T::type_name()))
961 }
962}
963
964#[diagnostic::on_unimplemented(
990 message = "a `{Self}` cannot be used for a column holding `{T}`",
991 note = "pass a `{T}` (or, for a nullable column, its inner type)"
992)]
993pub trait ValueFor<T> {
994 fn into_value_for(self) -> T;
996}
997
998impl<T> ValueFor<T> for T {
999 fn into_value_for(self) -> T {
1000 self
1001 }
1002}
1003
1004impl<T> ValueFor<Option<T>> for T {
1005 fn into_value_for(self) -> Option<T> {
1006 Some(self)
1007 }
1008}
1009
1010impl ValueFor<String> for &str {
1011 fn into_value_for(self) -> String {
1012 self.to_owned()
1013 }
1014}
1015
1016impl ValueFor<String> for &String {
1017 fn into_value_for(self) -> String {
1018 self.clone()
1019 }
1020}
1021
1022impl ValueFor<String> for Cow<'_, str> {
1023 fn into_value_for(self) -> String {
1024 self.into_owned()
1025 }
1026}
1027
1028impl ValueFor<Option<String>> for &str {
1029 fn into_value_for(self) -> Option<String> {
1030 Some(self.to_owned())
1031 }
1032}
1033
1034impl ValueFor<Option<String>> for &String {
1035 fn into_value_for(self) -> Option<String> {
1036 Some(self.clone())
1037 }
1038}
1039
1040impl ValueFor<Option<String>> for Option<&str> {
1041 fn into_value_for(self) -> Option<String> {
1042 self.map(str::to_owned)
1043 }
1044}
1045
1046macro_rules! widening {
1049 ($($from:ty => $($to:ty),+;)*) => {$($(
1050 impl ValueFor<$to> for $from {
1051 fn into_value_for(self) -> $to {
1052 <$to>::from(self)
1053 }
1054 }
1055
1056 impl ValueFor<Option<$to>> for $from {
1057 fn into_value_for(self) -> Option<$to> {
1058 Some(<$to>::from(self))
1059 }
1060 }
1061 )+)*};
1062}
1063
1064widening! {
1065 i8 => i16, i32, i64;
1066 i16 => i32, i64;
1067 i32 => i64;
1068 u8 => i16, i32, i64, u16, u32, u64;
1069 u16 => i32, i64, u32, u64;
1070 u32 => i64, u64;
1071 f32 => f64;
1072}
1073
1074macro_rules! into_value {
1076 ($($from:ty),* $(,)?) => {$(
1077 impl ValueFor<Value> for $from {
1078 fn into_value_for(self) -> Value {
1079 Value::from(self)
1080 }
1081 }
1082 )*};
1083}
1084
1085into_value!(
1086 bool,
1087 i8,
1088 i16,
1089 i32,
1090 i64,
1091 u8,
1092 u16,
1093 u32,
1094 u64,
1095 f32,
1096 f64,
1097 char,
1098 &str,
1099 String,
1100 Vec<u8>,
1101 serde_json::Value,
1102 Date,
1103 Time,
1104 DateTime,
1105 Timestamp,
1106 Zoned,
1107 Uuid,
1108 Decimal,
1109 crate::Ulid,
1110);
1111
1112impl ValueFor<Value> for &String {
1113 fn into_value_for(self) -> Value {
1114 Value::from(self.clone())
1115 }
1116}
1117
1118impl<T> ValueFor<Value> for Option<T>
1120where
1121 Option<T>: Into<Value>,
1122{
1123 fn into_value_for(self) -> Value {
1124 self.into()
1125 }
1126}
1127
1128#[diagnostic::on_unimplemented(
1134 message = "`{Self}` columns cannot be incremented",
1135 note = "increment integer, float or `Decimal` columns"
1136)]
1137pub trait Numeric: Field + Copy {
1138 fn checked_add(self, other: Self) -> Option<Self>;
1140
1141 fn checked_sub(self, other: Self) -> Option<Self>;
1143}
1144
1145macro_rules! integer_numeric {
1146 ($($ty:ty),*) => {$(
1147 impl Numeric for $ty {
1148 fn checked_add(self, other: Self) -> Option<Self> {
1149 <$ty>::checked_add(self, other)
1150 }
1151
1152 fn checked_sub(self, other: Self) -> Option<Self> {
1153 <$ty>::checked_sub(self, other)
1154 }
1155 }
1156 )*};
1157}
1158
1159integer_numeric!(i8, i16, i32, i64, u8, u16, u32, u64);
1160
1161macro_rules! float_numeric {
1162 ($($ty:ty),*) => {$(
1163 impl Numeric for $ty {
1164 fn checked_add(self, other: Self) -> Option<Self> {
1165 Some(self + other).filter(|sum| sum.is_finite())
1166 }
1167
1168 fn checked_sub(self, other: Self) -> Option<Self> {
1169 Some(self - other).filter(|difference| difference.is_finite())
1170 }
1171 }
1172 )*};
1173}
1174
1175float_numeric!(f32, f64);
1176
1177impl Numeric for Decimal {
1178 fn checked_add(self, other: Self) -> Option<Self> {
1179 Decimal::checked_add(self, other)
1180 }
1181
1182 fn checked_sub(self, other: Self) -> Option<Self> {
1183 Decimal::checked_sub(self, other)
1184 }
1185}
1186
1187impl Field for Value {
1190 fn to_value(&self) -> Value {
1191 self.clone()
1192 }
1193
1194 fn null() -> Value {
1195 Value::Null(Kind::String)
1196 }
1197
1198 fn from_value(value: Value) -> Result<Self, FieldError> {
1199 Ok(value)
1200 }
1201
1202 fn type_name() -> Cow<'static, str> {
1203 Cow::Borrowed("Value")
1204 }
1205}
1206
1207#[cfg(test)]
1208mod tests {
1209 use super::*;
1210
1211 #[test]
1212 fn integers_convert_leniently_and_check_ranges() {
1213 assert_eq!(i32::from_value(Value::I64(7)).unwrap(), 7);
1214 assert_eq!(
1215 i64::from_value(Value::Decimal(Decimal::new(4200, 2))).unwrap(),
1216 42
1217 );
1218 assert_eq!(i64::from_value(Value::String(" 12 ".into())).unwrap(), 12);
1219 assert!(matches!(
1220 i8::from_value(Value::I64(300)),
1221 Err(FieldError::Invalid(message)) if message == "300 does not fit i8"
1222 ));
1223 assert_eq!(
1224 i64::from_value(Value::Null(Kind::I64)),
1225 Err(FieldError::Null)
1226 );
1227 assert!(i64::from_value(Value::Decimal(Decimal::new(425, 1))).is_err());
1228 assert_eq!(u64::from_value(Value::I64(5)).unwrap(), 5);
1229 assert!(u64::from_value(Value::I64(-5)).is_err());
1230 }
1231
1232 #[test]
1233 fn booleans_read_integers_and_words() {
1234 assert!(bool::from_value(Value::I64(1)).unwrap());
1235 assert!(!bool::from_value(Value::I32(0)).unwrap());
1236 assert!(bool::from_value(Value::String("true".into())).unwrap());
1237 assert!(bool::from_value(Value::I64(2)).is_err());
1238 }
1239
1240 #[test]
1241 fn floats_and_decimals() {
1242 assert_eq!(f64::from_value(Value::I64(3)).unwrap(), 3.0);
1243 assert_eq!(
1244 f64::from_value(Value::Decimal(Decimal::new(125, 2))).unwrap(),
1245 1.25
1246 );
1247 assert_eq!(
1248 Decimal::from_value(Value::String("12.50".into())).unwrap(),
1249 Decimal::new(1250, 2)
1250 );
1251 assert_eq!(
1252 Decimal::from_value(Value::I64(3)).unwrap(),
1253 Decimal::from(3)
1254 );
1255 }
1256
1257 #[test]
1258 fn date_times_parse_the_text_forms_databases_return() {
1259 let expected = Timestamp::utc(2026, 10, 27, 8, 30, 0).unwrap();
1260 for text in [
1261 "2026-10-27T08:30:00Z",
1262 "2026-10-27 08:30:00+00:00",
1263 "2026-10-27 08:30:00",
1264 "2026-10-27T10:30:00+02:00",
1265 ] {
1266 assert_eq!(
1267 Timestamp::from_value(Value::String(text.into())).unwrap(),
1268 expected,
1269 "{text}"
1270 );
1271 }
1272 assert_eq!(
1273 Date::from_value(Value::String("2026-10-27".into())).unwrap(),
1274 Date::new(2026, 10, 27).unwrap()
1275 );
1276 assert_eq!(
1277 Time::from_value(Value::String("08:30:15".into())).unwrap(),
1278 Time::new(8, 30, 15).unwrap()
1279 );
1280 assert!(Timestamp::from_value(Value::String("soon".into())).is_err());
1281 }
1282
1283 #[test]
1284 fn options_map_nulls_to_none() {
1285 assert_eq!(<Option<String>>::null(), Value::Null(Kind::String));
1286 assert_eq!(
1287 <Option<String>>::from_value(Value::Null(Kind::String)).unwrap(),
1288 None
1289 );
1290 assert_eq!(
1291 <Option<String>>::from_value(Value::String("x".into())).unwrap(),
1292 Some("x".to_owned())
1293 );
1294 assert_eq!(
1295 <Option<Uuid>>::type_name(),
1296 Cow::<str>::Owned("Option<Uuid>".into())
1297 );
1298 assert_eq!(Some(3_i32).to_value(), Value::I32(3));
1299 assert_eq!(None::<i32>.to_value(), Value::Null(Kind::I32));
1300 }
1301
1302 #[test]
1303 fn uuids_and_json() {
1304 let id = Uuid::now_v7();
1305 assert_eq!(Uuid::from_value(Value::String(id.to_string())).unwrap(), id);
1306 assert_eq!(
1307 Uuid::from_value(Value::Bytes(id.as_bytes().to_vec())).unwrap(),
1308 id
1309 );
1310 assert_eq!(
1311 serde_json::Value::from_value(Value::String(r#"{"a":1}"#.into())).unwrap(),
1312 serde_json::json!({"a": 1})
1313 );
1314 }
1315
1316 #[test]
1317 fn nulls_of_every_type_are_detected() {
1318 assert!(is_null(&Value::Null(Kind::Uuid)));
1319 assert!(is_null(&Value::Null(Kind::Json)));
1320 assert!(!is_null(&Value::Bool(false)));
1321 }
1322}