1use std::borrow::Cow;
18use std::fmt;
19use std::str::FromStr;
20
21use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};
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<DateTime<FixedOffset>> {
520 let s = s.trim();
521 DateTime::parse_from_rfc3339(s)
522 .ok()
523 .or_else(|| DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f%:z").ok())
524 .or_else(|| DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f%z").ok())
525 .or_else(|| DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f %:z").ok())
526}
527
528fn parse_naive_date_time(s: &str) -> Option<NaiveDateTime> {
529 let s = s.trim();
530 DATE_TIME_FORMATS
531 .iter()
532 .find_map(|format| NaiveDateTime::parse_from_str(s, format).ok())
533 .or_else(|| {
534 NaiveDate::parse_from_str(s, "%Y-%m-%d")
535 .ok()
536 .and_then(|date| date.and_hms_opt(0, 0, 0))
537 })
538}
539
540fn date_time_utc(value: Value) -> Result<DateTime<Utc>, FieldError> {
541 null_check(&value)?;
542 match value {
543 Value::Timestamp(v) => Ok(v),
544 Value::TimestampTz(v) => Ok(v.with_timezone(&Utc)),
545 Value::DateTime(v) => Ok(Utc.from_utc_datetime(&v)),
546 Value::Date(v) => Ok(Utc.from_utc_datetime(&v.and_time(NaiveTime::MIN))),
547 Value::String(s) => parse_offset_date_time(&s)
548 .map(|v| v.with_timezone(&Utc))
549 .or_else(|| parse_naive_date_time(&s).map(|v| Utc.from_utc_datetime(&v)))
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| DateTime::from_timestamp(s, 0))
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<DateTime<FixedOffset>, 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(|| parse_naive_date_time(&s).map(|v| Utc.from_utc_datetime(&v).fixed_offset()))
570 .ok_or_else(|| FieldError::Invalid(format!("`{s}` is not a date-time"))),
571 other => date_time_utc(other).map(|v| v.fixed_offset()),
572 }
573}
574
575fn naive_date_time(value: Value) -> Result<NaiveDateTime, FieldError> {
576 null_check(&value)?;
577 match value {
578 Value::DateTime(v) => Ok(v),
579 Value::Timestamp(v) => Ok(v.naive_utc()),
580 Value::TimestampTz(v) => Ok(v.naive_utc()),
581 Value::Date(v) => Ok(v.and_time(NaiveTime::MIN)),
582 Value::String(s) => parse_naive_date_time(&s)
583 .or_else(|| parse_offset_date_time(&s).map(|v| v.naive_utc()))
584 .ok_or_else(|| FieldError::Invalid(format!("`{s}` is not a date-time"))),
585 other => Err(mismatch(&other, "a date-time")),
586 }
587}
588
589fn naive_date(value: Value) -> Result<NaiveDate, FieldError> {
590 null_check(&value)?;
591 match value {
592 Value::Date(v) => Ok(v),
593 Value::DateTime(v) => Ok(v.date()),
594 Value::Timestamp(v) => Ok(v.date_naive()),
595 Value::TimestampTz(v) => Ok(v.date_naive()),
596 Value::String(s) => NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
597 .ok()
598 .or_else(|| parse_naive_date_time(&s).map(|v| v.date()))
599 .ok_or_else(|| FieldError::Invalid(format!("`{s}` is not a date"))),
600 other => Err(mismatch(&other, "a date")),
601 }
602}
603
604fn naive_time(value: Value) -> Result<NaiveTime, FieldError> {
605 null_check(&value)?;
606 match value {
607 Value::Time(v) => Ok(v),
608 Value::DateTime(v) => Ok(v.time()),
609 Value::String(s) => NaiveTime::parse_from_str(s.trim(), "%H:%M:%S%.f")
610 .or_else(|_| NaiveTime::parse_from_str(s.trim(), "%H:%M"))
611 .map_err(|_| FieldError::Invalid(format!("`{s}` is not a time"))),
612 other => Err(mismatch(&other, "a time")),
613 }
614}
615
616macro_rules! exact_field {
618 ($ty:ty, $name:literal, $kind:expr, $null:expr, $from_value:expr) => {
619 impl Field for $ty {
620 const KIND: FieldKind = $kind;
621
622 fn to_value(&self) -> Value {
623 Value::from(self.clone())
624 }
625
626 fn null() -> Value {
627 $null
628 }
629
630 fn from_value(value: Value) -> Result<Self, FieldError> {
631 $from_value(value)
632 }
633
634 fn type_name() -> Cow<'static, str> {
635 Cow::Borrowed($name)
636 }
637 }
638 };
639}
640
641macro_rules! integer_field {
644 ($ty:ty, $name:literal, $bits:literal, $signed:literal, $null:expr) => {
645 impl Field for $ty {
646 const KIND: FieldKind = FieldKind::Integer {
647 bits: $bits,
648 signed: $signed,
649 };
650
651 fn to_value(&self) -> Value {
652 Value::from(*self)
653 }
654
655 fn null() -> Value {
656 $null
657 }
658
659 fn from_value(value: Value) -> Result<Self, FieldError> {
660 let int = integer(&value)?;
661 <$ty>::try_from(int)
662 .map_err(|_| FieldError::Invalid(format!("{int} does not fit {}", $name)))
663 }
664
665 fn type_name() -> Cow<'static, str> {
666 Cow::Borrowed($name)
667 }
668 }
669 };
670}
671
672integer_field!(i8, "i8", 8, true, Value::Null(Kind::I8));
673integer_field!(i16, "i16", 16, true, Value::Null(Kind::I16));
674integer_field!(i32, "i32", 32, true, Value::Null(Kind::I32));
675integer_field!(i64, "i64", 64, true, Value::Null(Kind::I64));
676integer_field!(u8, "u8", 8, false, Value::Null(Kind::U8));
677integer_field!(u16, "u16", 16, false, Value::Null(Kind::U16));
678integer_field!(u32, "u32", 32, false, Value::Null(Kind::U32));
679integer_field!(u64, "u64", 64, false, Value::Null(Kind::U64));
680
681exact_field!(
682 bool,
683 "bool",
684 FieldKind::Bool,
685 Value::Null(Kind::Bool),
686 |value: Value| boolean(&value)
687);
688
689impl Field for f32 {
690 const KIND: FieldKind = FieldKind::Float { bits: 32 };
691
692 fn to_value(&self) -> Value {
693 Value::F32(*self)
694 }
695
696 fn null() -> Value {
697 Value::Null(Kind::F32)
698 }
699
700 fn from_value(value: Value) -> Result<Self, FieldError> {
701 #[allow(clippy::cast_possible_truncation)]
703 float(&value).map(|v| v as f32)
704 }
705
706 fn type_name() -> Cow<'static, str> {
707 Cow::Borrowed("f32")
708 }
709}
710
711impl Field for f64 {
712 const KIND: FieldKind = FieldKind::Float { bits: 64 };
713
714 fn to_value(&self) -> Value {
715 Value::F64(*self)
716 }
717
718 fn null() -> Value {
719 Value::Null(Kind::F64)
720 }
721
722 fn from_value(value: Value) -> Result<Self, FieldError> {
723 float(&value)
724 }
725
726 fn type_name() -> Cow<'static, str> {
727 Cow::Borrowed("f64")
728 }
729}
730exact_field!(
731 String,
732 "String",
733 FieldKind::Text,
734 Value::Null(Kind::String),
735 string
736);
737
738impl Field for Vec<u8> {
741 const KIND: FieldKind = FieldKind::Bytes;
742
743 fn to_value(&self) -> Value {
744 Value::from(self.clone())
745 }
746
747 fn null() -> Value {
748 Value::Null(Kind::Bytes)
749 }
750
751 fn from_value(value: Value) -> Result<Self, FieldError> {
752 bytes(value)
753 }
754
755 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
756 match json {
757 serde_json::Value::Array(items) => items
758 .iter()
759 .map(|item| {
760 item.as_u64()
761 .and_then(|n| u8::try_from(n).ok())
762 .ok_or_else(|| {
763 FieldError::Invalid(format!("{item} is not a byte (0 to 255)"))
764 })
765 })
766 .collect(),
767 serde_json::Value::Null => Err(FieldError::Null),
768 other => bytes(json_to_value(other)),
769 }
770 }
771
772 fn type_name() -> Cow<'static, str> {
773 Cow::Borrowed("Vec<u8>")
774 }
775}
776
777impl Field for Uuid {
780 const KIND: FieldKind = FieldKind::Uuid;
781
782 fn to_value(&self) -> Value {
783 Value::Uuid(*self)
784 }
785
786 fn null() -> Value {
787 Value::Null(Kind::Uuid)
788 }
789
790 fn from_value(value: Value) -> Result<Self, FieldError> {
791 uuid(value)
792 }
793
794 fn type_name() -> Cow<'static, str> {
795 Cow::Borrowed("Uuid")
796 }
797}
798
799macro_rules! parsed_field {
802 ($ty:ty, $name:literal, $kind:expr, $null:expr, $parse:expr) => {
803 impl Field for $ty {
804 const KIND: FieldKind = $kind;
805
806 fn to_value(&self) -> Value {
807 Value::from(self.clone())
808 }
809
810 fn null() -> Value {
811 $null
812 }
813
814 fn from_value(value: Value) -> Result<Self, FieldError> {
815 $parse(value)
816 }
817
818 fn type_name() -> Cow<'static, str> {
819 Cow::Borrowed($name)
820 }
821 }
822 };
823}
824
825impl Field for serde_json::Value {
828 const KIND: FieldKind = FieldKind::Json;
829
830 fn to_value(&self) -> Value {
831 Value::from(self.clone())
832 }
833
834 fn null() -> Value {
835 Value::Null(Kind::Json)
836 }
837
838 fn from_value(value: Value) -> Result<Self, FieldError> {
839 json(value)
840 }
841
842 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
843 Ok(json)
844 }
845
846 fn type_name() -> Cow<'static, str> {
847 Cow::Borrowed("serde_json::Value")
848 }
849}
850
851parsed_field!(
852 NaiveDate,
853 "NaiveDate",
854 FieldKind::Date,
855 Value::Null(Kind::Date),
856 naive_date
857);
858parsed_field!(
859 NaiveTime,
860 "NaiveTime",
861 FieldKind::Time,
862 Value::Null(Kind::Time),
863 naive_time
864);
865parsed_field!(
866 NaiveDateTime,
867 "NaiveDateTime",
868 FieldKind::DateTime,
869 Value::Null(Kind::DateTime),
870 naive_date_time
871);
872parsed_field!(
873 DateTime<Utc>,
874 "DateTime<Utc>",
875 FieldKind::DateTime,
876 Value::Null(Kind::Timestamp),
877 date_time_utc
878);
879parsed_field!(
880 DateTime<FixedOffset>,
881 "DateTime<FixedOffset>",
882 FieldKind::DateTime,
883 Value::Null(Kind::TimestampTz),
884 date_time_offset
885);
886
887impl Field for Decimal {
891 const KIND: FieldKind = FieldKind::Decimal;
892
893 fn to_value(&self) -> Value {
894 Value::Decimal(*self)
895 }
896
897 fn null() -> Value {
898 Value::Null(Kind::Decimal)
899 }
900
901 fn from_value(value: Value) -> Result<Self, FieldError> {
902 decimal(&value)
903 }
904
905 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
908 match json {
909 serde_json::Value::Number(number) => decimal(&Value::String(number.to_string())),
910 other => decimal(&json_to_value(other)),
911 }
912 }
913
914 fn type_name() -> Cow<'static, str> {
915 Cow::Borrowed("Decimal")
916 }
917}
918
919impl<T: Field> Field for Option<T> {
920 const KIND: FieldKind = T::KIND;
921
922 fn to_value(&self) -> Value {
923 match self {
924 Some(value) => value.to_value(),
925 None => T::null(),
926 }
927 }
928
929 fn null() -> Value {
930 T::null()
931 }
932
933 fn from_sql(row: &navree_db::Row, column: &str) -> Result<Self, FieldError> {
934 match T::from_sql(row, column) {
935 Ok(value) => Ok(Some(value)),
936 Err(FieldError::Null) => Ok(None),
937 Err(error) => Err(error),
938 }
939 }
940
941 fn from_value(value: Value) -> Result<Self, FieldError> {
942 if is_null(&value) {
943 Ok(None)
944 } else {
945 T::from_value(value).map(Some)
946 }
947 }
948
949 fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
950 if json.is_null() {
951 Ok(None)
952 } else {
953 T::from_json(json).map(Some)
954 }
955 }
956
957 fn type_name() -> Cow<'static, str> {
958 Cow::Owned(format!("Option<{}>", T::type_name()))
959 }
960}
961
962#[diagnostic::on_unimplemented(
988 message = "a `{Self}` cannot be used for a column holding `{T}`",
989 note = "pass a `{T}` (or, for a nullable column, its inner type)"
990)]
991pub trait ValueFor<T> {
992 fn into_value_for(self) -> T;
994}
995
996impl<T> ValueFor<T> for T {
997 fn into_value_for(self) -> T {
998 self
999 }
1000}
1001
1002impl<T> ValueFor<Option<T>> for T {
1003 fn into_value_for(self) -> Option<T> {
1004 Some(self)
1005 }
1006}
1007
1008impl ValueFor<String> for &str {
1009 fn into_value_for(self) -> String {
1010 self.to_owned()
1011 }
1012}
1013
1014impl ValueFor<String> for &String {
1015 fn into_value_for(self) -> String {
1016 self.clone()
1017 }
1018}
1019
1020impl ValueFor<String> for Cow<'_, str> {
1021 fn into_value_for(self) -> String {
1022 self.into_owned()
1023 }
1024}
1025
1026impl ValueFor<Option<String>> for &str {
1027 fn into_value_for(self) -> Option<String> {
1028 Some(self.to_owned())
1029 }
1030}
1031
1032impl ValueFor<Option<String>> for &String {
1033 fn into_value_for(self) -> Option<String> {
1034 Some(self.clone())
1035 }
1036}
1037
1038impl ValueFor<Option<String>> for Option<&str> {
1039 fn into_value_for(self) -> Option<String> {
1040 self.map(str::to_owned)
1041 }
1042}
1043
1044macro_rules! widening {
1047 ($($from:ty => $($to:ty),+;)*) => {$($(
1048 impl ValueFor<$to> for $from {
1049 fn into_value_for(self) -> $to {
1050 <$to>::from(self)
1051 }
1052 }
1053
1054 impl ValueFor<Option<$to>> for $from {
1055 fn into_value_for(self) -> Option<$to> {
1056 Some(<$to>::from(self))
1057 }
1058 }
1059 )+)*};
1060}
1061
1062widening! {
1063 i8 => i16, i32, i64;
1064 i16 => i32, i64;
1065 i32 => i64;
1066 u8 => i16, i32, i64, u16, u32, u64;
1067 u16 => i32, i64, u32, u64;
1068 u32 => i64, u64;
1069 f32 => f64;
1070}
1071
1072macro_rules! into_value {
1074 ($($from:ty),* $(,)?) => {$(
1075 impl ValueFor<Value> for $from {
1076 fn into_value_for(self) -> Value {
1077 Value::from(self)
1078 }
1079 }
1080 )*};
1081}
1082
1083into_value!(
1084 bool,
1085 i8,
1086 i16,
1087 i32,
1088 i64,
1089 u8,
1090 u16,
1091 u32,
1092 u64,
1093 f32,
1094 f64,
1095 char,
1096 &str,
1097 String,
1098 Vec<u8>,
1099 serde_json::Value,
1100 NaiveDate,
1101 NaiveTime,
1102 NaiveDateTime,
1103 DateTime<Utc>,
1104 DateTime<FixedOffset>,
1105 Uuid,
1106 Decimal,
1107 crate::Ulid,
1108);
1109
1110impl ValueFor<Value> for &String {
1111 fn into_value_for(self) -> Value {
1112 Value::from(self.clone())
1113 }
1114}
1115
1116impl<T> ValueFor<Value> for Option<T>
1118where
1119 Option<T>: Into<Value>,
1120{
1121 fn into_value_for(self) -> Value {
1122 self.into()
1123 }
1124}
1125
1126#[diagnostic::on_unimplemented(
1132 message = "`{Self}` columns cannot be incremented",
1133 note = "increment integer, float or `Decimal` columns"
1134)]
1135pub trait Numeric: Field + Copy {
1136 fn checked_add(self, other: Self) -> Option<Self>;
1138
1139 fn checked_sub(self, other: Self) -> Option<Self>;
1141}
1142
1143macro_rules! integer_numeric {
1144 ($($ty:ty),*) => {$(
1145 impl Numeric for $ty {
1146 fn checked_add(self, other: Self) -> Option<Self> {
1147 <$ty>::checked_add(self, other)
1148 }
1149
1150 fn checked_sub(self, other: Self) -> Option<Self> {
1151 <$ty>::checked_sub(self, other)
1152 }
1153 }
1154 )*};
1155}
1156
1157integer_numeric!(i8, i16, i32, i64, u8, u16, u32, u64);
1158
1159macro_rules! float_numeric {
1160 ($($ty:ty),*) => {$(
1161 impl Numeric for $ty {
1162 fn checked_add(self, other: Self) -> Option<Self> {
1163 Some(self + other).filter(|sum| sum.is_finite())
1164 }
1165
1166 fn checked_sub(self, other: Self) -> Option<Self> {
1167 Some(self - other).filter(|difference| difference.is_finite())
1168 }
1169 }
1170 )*};
1171}
1172
1173float_numeric!(f32, f64);
1174
1175impl Numeric for Decimal {
1176 fn checked_add(self, other: Self) -> Option<Self> {
1177 Decimal::checked_add(self, other)
1178 }
1179
1180 fn checked_sub(self, other: Self) -> Option<Self> {
1181 Decimal::checked_sub(self, other)
1182 }
1183}
1184
1185impl Field for Value {
1188 fn to_value(&self) -> Value {
1189 self.clone()
1190 }
1191
1192 fn null() -> Value {
1193 Value::Null(Kind::String)
1194 }
1195
1196 fn from_value(value: Value) -> Result<Self, FieldError> {
1197 Ok(value)
1198 }
1199
1200 fn type_name() -> Cow<'static, str> {
1201 Cow::Borrowed("Value")
1202 }
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207 use super::*;
1208
1209 #[test]
1210 fn integers_convert_leniently_and_check_ranges() {
1211 assert_eq!(i32::from_value(Value::I64(7)).unwrap(), 7);
1212 assert_eq!(
1213 i64::from_value(Value::Decimal(Decimal::new(4200, 2))).unwrap(),
1214 42
1215 );
1216 assert_eq!(i64::from_value(Value::String(" 12 ".into())).unwrap(), 12);
1217 assert!(matches!(
1218 i8::from_value(Value::I64(300)),
1219 Err(FieldError::Invalid(message)) if message == "300 does not fit i8"
1220 ));
1221 assert_eq!(
1222 i64::from_value(Value::Null(Kind::I64)),
1223 Err(FieldError::Null)
1224 );
1225 assert!(i64::from_value(Value::Decimal(Decimal::new(425, 1))).is_err());
1226 assert_eq!(u64::from_value(Value::I64(5)).unwrap(), 5);
1227 assert!(u64::from_value(Value::I64(-5)).is_err());
1228 }
1229
1230 #[test]
1231 fn booleans_read_integers_and_words() {
1232 assert!(bool::from_value(Value::I64(1)).unwrap());
1233 assert!(!bool::from_value(Value::I32(0)).unwrap());
1234 assert!(bool::from_value(Value::String("true".into())).unwrap());
1235 assert!(bool::from_value(Value::I64(2)).is_err());
1236 }
1237
1238 #[test]
1239 fn floats_and_decimals() {
1240 assert_eq!(f64::from_value(Value::I64(3)).unwrap(), 3.0);
1241 assert_eq!(
1242 f64::from_value(Value::Decimal(Decimal::new(125, 2))).unwrap(),
1243 1.25
1244 );
1245 assert_eq!(
1246 Decimal::from_value(Value::String("12.50".into())).unwrap(),
1247 Decimal::new(1250, 2)
1248 );
1249 assert_eq!(
1250 Decimal::from_value(Value::I64(3)).unwrap(),
1251 Decimal::from(3)
1252 );
1253 }
1254
1255 #[test]
1256 fn date_times_parse_the_text_forms_databases_return() {
1257 let expected = Utc.with_ymd_and_hms(2026, 10, 27, 8, 30, 0).unwrap();
1258 for text in [
1259 "2026-10-27T08:30:00Z",
1260 "2026-10-27 08:30:00+00:00",
1261 "2026-10-27 08:30:00",
1262 "2026-10-27T10:30:00+02:00",
1263 ] {
1264 assert_eq!(
1265 DateTime::<Utc>::from_value(Value::String(text.into())).unwrap(),
1266 expected,
1267 "{text}"
1268 );
1269 }
1270 assert_eq!(
1271 NaiveDate::from_value(Value::String("2026-10-27".into())).unwrap(),
1272 NaiveDate::from_ymd_opt(2026, 10, 27).unwrap()
1273 );
1274 assert_eq!(
1275 NaiveTime::from_value(Value::String("08:30:15".into())).unwrap(),
1276 NaiveTime::from_hms_opt(8, 30, 15).unwrap()
1277 );
1278 assert!(DateTime::<Utc>::from_value(Value::String("soon".into())).is_err());
1279 }
1280
1281 #[test]
1282 fn options_map_nulls_to_none() {
1283 assert_eq!(<Option<String>>::null(), Value::Null(Kind::String));
1284 assert_eq!(
1285 <Option<String>>::from_value(Value::Null(Kind::String)).unwrap(),
1286 None
1287 );
1288 assert_eq!(
1289 <Option<String>>::from_value(Value::String("x".into())).unwrap(),
1290 Some("x".to_owned())
1291 );
1292 assert_eq!(
1293 <Option<Uuid>>::type_name(),
1294 Cow::<str>::Owned("Option<Uuid>".into())
1295 );
1296 assert_eq!(Some(3_i32).to_value(), Value::I32(3));
1297 assert_eq!(None::<i32>.to_value(), Value::Null(Kind::I32));
1298 }
1299
1300 #[test]
1301 fn uuids_and_json() {
1302 let id = Uuid::now_v7();
1303 assert_eq!(Uuid::from_value(Value::String(id.to_string())).unwrap(), id);
1304 assert_eq!(
1305 Uuid::from_value(Value::Bytes(id.as_bytes().to_vec())).unwrap(),
1306 id
1307 );
1308 assert_eq!(
1309 serde_json::Value::from_value(Value::String(r#"{"a":1}"#.into())).unwrap(),
1310 serde_json::json!({"a": 1})
1311 );
1312 }
1313
1314 #[test]
1315 fn nulls_of_every_type_are_detected() {
1316 assert!(is_null(&Value::Null(Kind::Uuid)));
1317 assert!(is_null(&Value::Null(Kind::Json)));
1318 assert!(!is_null(&Value::Bool(false)));
1319 }
1320}