Skip to main content

narwhal_core/
value.rs

1use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
2use serde::{Deserialize, Serialize};
3
4/// Engine-agnostic representation of a database value.
5///
6/// Drivers convert their native types into [`Value`] when reading rows and
7/// in the opposite direction when binding parameters. Values that cannot be
8/// expressed in one of the structured variants are preserved in
9/// [`Value::Unknown`] as their textual rendering.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11#[non_exhaustive]
12pub enum Value {
13    Null,
14    Bool(bool),
15    Int(i64),
16    Float(f64),
17    String(String),
18    Bytes(Vec<u8>),
19    Date(NaiveDate),
20    Time(NaiveTime),
21    DateTime(NaiveDateTime),
22    Timestamp(DateTime<Utc>),
23    Uuid(uuid::Uuid),
24    Json(serde_json::Value),
25    Unknown(String),
26}
27
28impl Value {
29    pub const fn is_null(&self) -> bool {
30        matches!(self, Self::Null)
31    }
32
33    /// Render the value as a plain string suitable for display in a grid.
34    ///
35    /// Delegates to [`std::fmt::Display`] which writes straight to the
36    /// formatter — no intermediate allocation for the integer/float/date
37    /// paths (L1).
38    pub fn render(&self) -> String {
39        self.to_string()
40    }
41}
42
43impl std::fmt::Display for Value {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Self::Null => f.write_str("NULL"),
47            Self::Bool(b) => write!(f, "{b}"),
48            Self::Int(i) => write!(f, "{i}"),
49            Self::Float(v) => write!(f, "{v}"),
50            Self::String(s) => f.write_str(s),
51            Self::Bytes(b) => write!(f, "<{} bytes>", b.len()),
52            Self::Date(d) => write!(f, "{d}"),
53            Self::Time(t) => write!(f, "{t}"),
54            Self::DateTime(dt) => write!(f, "{dt}"),
55            Self::Timestamp(ts) => f.write_str(&ts.to_rfc3339()),
56            Self::Uuid(u) => write!(f, "{u}"),
57            Self::Json(v) => write!(f, "{v}"),
58            Self::Unknown(s) => f.write_str(s),
59        }
60    }
61}