Skip to main content

navree_orm/
value.rs

1//! [`Value`], [`Field`] and the conversions between Rust types and column
2//! values.
3//!
4//! [`Value`] is navree-db's value: what statements bind and rows hold, a
5//! NULL keeping its [`Kind`] (PostgreSQL needs the type of a NULL
6//! parameter). The enum is non-exhaustive, so code matching on it keeps a
7//! `_` arm.
8//!
9//! [`Field`] is implemented by every Rust type a model field can have
10//! without a cast. Reading a column takes the value navree-db's row reads
11//! by the column's own type ([`navree_db::Row::value`]), then converts it
12//! leniently between representations of the same thing: `NUMERIC` 42 reads
13//! as an `i64`, the text `2026-10-27 08:00:00+00:00` (SQLite's date-times)
14//! as a [`Timestamp`], MySQL's `TINYINT(1)` as a `bool`. Document rows,
15//! aggregates and dynamic columns convert the same way.
16
17use 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/// Why a column value could not become a field.
29#[derive(Clone, Debug, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum FieldError {
32    /// The value is NULL and the field is not an `Option`.
33    Null,
34    /// The row has no such column.
35    Missing,
36    /// The value has another type, or does not fit the field.
37    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/// What a field's values are, as JSON and OpenAPI see them: the shape
53/// serialized records write and schemas describe. A nullable field has the
54/// kind of its inner type.
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56#[non_exhaustive]
57pub enum FieldKind {
58    /// `true` / `false`.
59    Bool,
60    /// An integer of `bits` bits.
61    Integer {
62        /// 8, 16, 32 or 64.
63        bits: u8,
64        /// Whether it can be negative.
65        signed: bool,
66    },
67    /// A floating-point number of `bits` bits (32 or 64).
68    Float {
69        /// 32 or 64.
70        bits: u8,
71    },
72    /// An exact decimal, written as a string (`"12.50"`).
73    Decimal,
74    /// Text.
75    Text,
76    /// Bytes, written as an array of numbers.
77    Bytes,
78    /// A UUID, written as its hyphenated text.
79    Uuid,
80    /// A ULID, written as its 26-character text.
81    Ulid,
82    /// A date, `YYYY-MM-DD`.
83    Date,
84    /// A time of day, `HH:MM:SS`.
85    Time,
86    /// A date-time, written in RFC 3339.
87    DateTime,
88    /// Any JSON value.
89    Json,
90    /// A URL, written as text.
91    Url,
92    /// A vector of numbers.
93    Vector,
94    /// Anything else (no known shape).
95    Any,
96}
97
98/// A Rust type a model field (or a column read with
99/// [`Row::get`](crate::Row::get)) can have.
100///
101/// Implemented for `bool`, `i8`..`i64`, `u8`..`u64`, `f32`, `f64`,
102/// [`Decimal`], `String`, `Vec<u8>`, `Uuid`, [`Ulid`](crate::Ulid),
103/// [`Date`], [`Time`], [`DateTime`], [`Timestamp`] and [`Zoned`],
104/// `serde_json::Value`, [`Value`] (any
105/// column, decoded dynamically) and `Option<T>` of any of them. Other
106/// types (enums, serde structs) use a [cast](crate::cast).
107///
108/// ```
109/// use navree_orm::{Field, Kind, Value};
110///
111/// assert_eq!(42_i64.to_value(), Value::I64(42));
112/// assert_eq!(<Option<i64>>::null(), Value::Null(Kind::I64));
113/// // Lenient between representations of the same number:
114/// assert_eq!(i64::from_value(Value::F64(42.0)).unwrap(), 42);
115/// assert!(i64::from_value(Value::F64(4.2)).is_err());
116/// assert_eq!(<Option<i64>>::from_value(Value::Null(Kind::I64)).unwrap(), None);
117/// ```
118pub trait Field: Sized + Send + Sync + 'static {
119    /// What the values are as JSON (for serialization and OpenAPI
120    /// schemas); [`FieldKind::Any`] unless the type says.
121    const KIND: FieldKind = FieldKind::Any;
122
123    /// The column value of `self`.
124    fn to_value(&self) -> Value;
125
126    /// A NULL of this field's type.
127    fn null() -> Value;
128
129    /// Reads the field from column `column` of a row: by default the value
130    /// navree-db reads by the column's type ([`navree_db::Row::value`]),
131    /// converted with [`from_value`](Field::from_value). A missing column
132    /// is [`FieldError::Missing`].
133    fn from_sql(row: &navree_db::Row, column: &str) -> Result<Self, FieldError> {
134        Self::from_value(column_value(row, column)?)
135    }
136
137    /// Converts a value: a column of a row, a document field, an aggregate,
138    /// an assignment.
139    fn from_value(value: Value) -> Result<Self, FieldError>;
140
141    /// Converts untyped JSON input (mass assignment with `fill`, a request
142    /// body) as leniently as [`from_value`](Field::from_value): numbers and
143    /// numeric strings for numbers, RFC 3339 and database text for
144    /// date-times, the text form of UUIDs. `null` is `None` for an
145    /// `Option`, an error otherwise. JSON fields take the JSON as it is,
146    /// decimals read a number's exact text, bytes an array of numbers.
147    ///
148    /// ```
149    /// use navree_orm::{Decimal, Field};
150    /// use serde_json::json;
151    ///
152    /// assert_eq!(i32::from_json(json!(7)).unwrap(), 7);
153    /// assert_eq!(Decimal::from_json(json!(12.10)).unwrap().to_string(), "12.1");
154    /// assert_eq!(Decimal::from_json(json!("12.10")).unwrap().to_string(), "12.10");
155    /// assert_eq!(<Option<String>>::from_json(json!(null)).unwrap(), None);
156    /// assert_eq!(serde_json::Value::from_json(json!("text")).unwrap(), json!("text"));
157    /// assert!(bool::from_json(json!("maybe")).is_err());
158    /// ```
159    fn from_json(json: serde_json::Value) -> Result<Self, FieldError> {
160        Self::from_value(json_to_value(json))
161    }
162
163    /// The type's name in error messages, e.g. `i64` or `Option<String>`.
164    fn type_name() -> Cow<'static, str>;
165}
166
167/// Column `column` of `row` as navree-db reads it by the column's type:
168/// [`FieldError::Missing`] when the row has no such column, the driver's
169/// message when the column cannot be read.
170pub(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
178/// JSON input as the [`Value`] it most naturally is: `null` a NULL,
179/// booleans and strings themselves, integers `BIGINT` (or `BIGINT
180/// UNSIGNED` above `i64`), other numbers `DOUBLE`, arrays and objects JSON.
181pub(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
198/// Whether `value` is a NULL (of any kind).
199///
200/// ```
201/// use navree_orm::{Kind, Value, is_null};
202///
203/// assert!(is_null(&Value::Null(Kind::Uuid)));
204/// assert!(!is_null(&Value::Bool(false)));
205/// ```
206pub fn is_null(value: &Value) -> bool {
207    value.is_null()
208}
209
210/// `value` as JSON, the way the field would serialize: numbers as numbers,
211/// decimals as exact strings (`"12.50"`), UUIDs and date-times as their
212/// serde text (RFC 3339), JSON as itself, bytes and vectors as arrays of
213/// numbers, an enum value as its text, NULL as `null`. Non-finite floats
214/// become `null`.
215///
216/// ```
217/// use navree_orm::{Decimal, Kind, Value, to_json};
218///
219/// assert_eq!(to_json(&Value::from(42_i64)), serde_json::json!(42));
220/// assert_eq!(to_json(&Value::Decimal(Decimal::new(1250, 2))), serde_json::json!("12.50"));
221/// assert_eq!(to_json(&Value::Null(Kind::String)), serde_json::Value::Null);
222/// ```
223pub 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        // Enums (their text), vectors (arrays of numbers) and what later
257        // versions add.
258        other => other.to_json(),
259    }
260}
261
262/// Whether two stored values of a column hold the same thing (what dirty
263/// tracking asks): NULLs are equal whatever their kind, floats within a
264/// small relative tolerance, decimals numerically (`12.5` and `12.50`),
265/// date-times by instant, JSON structurally, anything else exactly.
266///
267/// ```
268/// use navree_orm::{Decimal, Kind, Value, same_value};
269///
270/// assert!(same_value(&Value::F64(0.1 + 0.2), &Value::F64(0.3)));
271/// assert!(same_value(
272///     &Value::Decimal(Decimal::new(125, 1)),
273///     &Value::Decimal(Decimal::new(1250, 2)),
274/// ));
275/// assert!(same_value(&Value::Null(Kind::String), &Value::Null(Kind::I64)));
276/// assert!(!same_value(&Value::from("a"), &Value::from("b")));
277/// ```
278pub 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
305/// A short description of a value's type for error messages.
306pub(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
345/// An integer in `value`, from any integer, an integral float or decimal,
346/// a boolean or a numeric string.
347fn 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        // In range and integral: the cast is exact.
381        #[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
388/// A float in `value`, from any number or a numeric string.
389fn 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            // Integers from the database fit an f64 closely enough for a float field.
405            #[allow(clippy::cast_precision_loss)]
406            Ok(int as f64)
407        }
408    }
409}
410
411/// A decimal in `value`, from any number or a numeric string.
412fn 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
515/// The text formats date-times come back in: RFC 3339, and the
516/// space-separated form SQLite and MySQL use, with or without an offset.
517const 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        // A boolean is never a moment in time.
552        Value::Bool(_) => Err(mismatch(&value, "a date-time")),
553        other => match integer(&other) {
554            // Unix seconds (timestamps stored as integers).
555            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
618/// `Field` for a type read with a lenient conversion from values.
619macro_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
643/// `Field` for an integer type: any integer column width (and whole
644/// decimals, floats and numeric text), range-checked.
645macro_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        // Narrowing to the field's own precision.
704        #[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
740/// Bytes: JSON input is an array of numbers (what serde writes for a
741/// `Vec<u8>`) or a string (its UTF-8 bytes).
742impl 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
779/// `Uuid`: native on PostgreSQL, 16 bytes on SQLite and MySQL; also read
780/// from text columns holding the hyphenated form (`CHAR(36)`).
781impl 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
801/// `Field` for a type read as the column's own type, or parsed from text
802/// when the column holds text (SQLite's date-times).
803macro_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
827/// JSON: read as it is from JSON columns, parsed from text columns; JSON
828/// input is taken as it is (`null` included).
829impl 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
889/// [`Decimal`]: exact on PostgreSQL and MySQL; on SQLite, whose `NUMERIC`
890/// columns keep numbers as integers or floats, read from those or from
891/// text.
892impl 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    /// A JSON number is read from its exact text (`12.10` stays `12.1`, not
908    /// the nearest binary float).
909    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/// A value a column holding `T` accepts in conditions and assignments
965/// (`Deal::TITLE.eq("Renewal")`, `Company::COUNTRY.eq("US")`,
966/// `Deal::AMOUNT_CENTS.gte(10_000)`).
967///
968/// Implemented for:
969///
970/// - `T` itself, and `T` for a nullable column (`Option<T>`);
971/// - text (`&str`, `&String`, `Cow<str>`) for `String` and `Option<String>`
972///   columns;
973/// - lossless widenings of integers (`i32` for an `i64` column, ...) and
974///   floats (`f32` for an `f64` column);
975/// - everything a [`Value`] is built from, for untyped columns
976///   ([`col`](crate::col)).
977///
978/// ```
979/// use navree_orm::{Value, ValueFor};
980///
981/// let title: String = "Renewal".into_value_for();
982/// let country: Option<String> = "US".into_value_for();
983/// let cents: i64 = 12_i32.into_value_for();
984/// let closed: Option<i64> = 7_i64.into_value_for();
985/// let any: Value = 42_u8.into_value_for();
986/// assert_eq!((title.as_str(), country.as_deref(), cents, closed), ("Renewal", Some("US"), 12, Some(7)));
987/// assert_eq!(any, Value::U8(42));
988/// ```
989#[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    /// The value as the column's type.
995    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
1046/// Lossless widenings: `$from` values for `$to` (and `Option<$to>`)
1047/// columns.
1048macro_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
1074/// Anything a [`Value`] is built from, for untyped columns.
1075macro_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
1118/// A nullable value for an untyped column (a typed NULL for `None`).
1119impl<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/// A number a column can be incremented or decremented by
1129/// ([`Record::increment`](crate::Record::increment),
1130/// [`Builder::increment`](crate::Builder::increment)).
1131///
1132/// Implemented for every integer type, `f32`, `f64` and [`Decimal`].
1133#[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    /// `self + other`, `None` on overflow.
1139    fn checked_add(self, other: Self) -> Option<Self>;
1140
1141    /// `self - other`, `None` on overflow.
1142    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
1187/// Any column, decoded dynamically (the column's own type decides the
1188/// variant). For untyped columns and expressions.
1189impl 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}