Skip to main content

renox_core/db/
value.rs

1use chrono::{FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeZone};
2
3/// A value bound to a query parameter.
4///
5/// SQLite stores booleans as `0`/`1` and dates as text; PostgreSQL gets them
6/// with their own types (`BOOLEAN`, `TIMESTAMPTZ`, `TIMESTAMP`, `DATE`,
7/// `TIME`), so the same model works on both.
8#[derive(Debug, Clone, PartialEq)]
9#[non_exhaustive]
10pub enum DbValue {
11    /// SQL `NULL`.
12    Null,
13    /// A 64-bit integer (`INTEGER` on SQLite, `BIGINT` on PostgreSQL).
14    Integer(i64),
15    /// A 64-bit float (`REAL` on SQLite, `DOUBLE PRECISION` on PostgreSQL).
16    Real(f64),
17    /// Text.
18    Text(String),
19    /// Bytes (`BLOB` on SQLite, `BYTEA` on PostgreSQL).
20    Blob(Vec<u8>),
21    /// A boolean (`0`/`1` on SQLite, `BOOLEAN` on PostgreSQL).
22    Bool(bool),
23    /// A point in time with its offset (`TIMESTAMPTZ` on PostgreSQL).
24    DateTime(chrono::DateTime<FixedOffset>),
25    /// A date and time without a zone (`TIMESTAMP` on PostgreSQL).
26    NaiveDateTime(NaiveDateTime),
27    /// A date (`YYYY-MM-DD` text on SQLite, `DATE` on PostgreSQL).
28    Date(NaiveDate),
29    /// A time of day (text on SQLite, `TIME` on PostgreSQL).
30    Time(NaiveTime),
31    /// Text on SQLite; JSON on PostgreSQL (fits `JSONB` and `TEXT` columns).
32    Json(serde_json::Value),
33    /// A 16-byte BLOB on SQLite; `UUID` on PostgreSQL.
34    #[cfg(feature = "uuid")]
35    Uuid(uuid::Uuid),
36    /// An [`Encrypted`](super::Encrypted) field's value, sealed with the
37    /// database's key when the statement runs (text in the column).
38    Encrypted(super::encrypted::Unsealed),
39}
40
41impl DbValue {
42    /// The value as JSON, as templates and APIs would see it.
43    pub(crate) fn to_json(&self) -> serde_json::Value {
44        use serde_json::Value;
45        match self {
46            DbValue::Null => Value::Null,
47            DbValue::Integer(v) => Value::from(*v),
48            DbValue::Real(v) => Value::from(*v),
49            DbValue::Text(v) => Value::from(v.clone()),
50            DbValue::Blob(v) => Value::from(v.clone()),
51            DbValue::Bool(v) => Value::from(*v),
52            DbValue::DateTime(v) => Value::from(v.to_rfc3339()),
53            DbValue::NaiveDateTime(v) => Value::from(v.format("%Y-%m-%dT%H:%M:%S").to_string()),
54            DbValue::Date(v) => Value::from(v.to_string()),
55            DbValue::Time(v) => Value::from(v.to_string()),
56            DbValue::Json(v) => v.clone(),
57            #[cfg(feature = "uuid")]
58            DbValue::Uuid(v) => Value::from(v.to_string()),
59            DbValue::Encrypted(_) => Value::from("[encrypted]"),
60        }
61    }
62
63    /// The value as SQLite stores it: booleans as integers, dates in the text
64    /// formats sqlx uses, so values written through models and through raw
65    /// sqlx queries compare equal.
66    pub(crate) fn for_sqlite(self) -> DbValue {
67        match self {
68            DbValue::Bool(v) => DbValue::Integer(i64::from(v)),
69            DbValue::DateTime(v) => DbValue::Text(v.format("%F %T%.f%:z").to_string()),
70            DbValue::NaiveDateTime(v) => DbValue::Text(v.format("%F %T%.f").to_string()),
71            DbValue::Date(v) => DbValue::Text(v.format("%F").to_string()),
72            DbValue::Time(v) => DbValue::Text(v.format("%T%.f").to_string()),
73            DbValue::Json(v) => DbValue::Text(v.to_string()),
74            #[cfg(feature = "uuid")]
75            DbValue::Uuid(v) => DbValue::Blob(v.as_bytes().to_vec()),
76            other => other,
77        }
78    }
79}
80
81/// Converts a Rust value into a query parameter. Implemented for the usual
82/// scalar types, `Option`, chrono dates and `serde_json::Value`; implement it
83/// for your own types to use them in models and `where_*` filters.
84pub trait ToDbValue {
85    /// The value to bind for `self`.
86    fn to_db_value(&self) -> DbValue;
87}
88
89macro_rules! integer {
90    ($($t:ty),*) => {$(
91        impl ToDbValue for $t {
92            fn to_db_value(&self) -> DbValue {
93                DbValue::Integer(i64::from(*self))
94            }
95        }
96    )*};
97}
98
99integer!(i8, i16, i32, i64, u8, u16, u32);
100
101impl ToDbValue for bool {
102    fn to_db_value(&self) -> DbValue {
103        DbValue::Bool(*self)
104    }
105}
106
107impl ToDbValue for f32 {
108    fn to_db_value(&self) -> DbValue {
109        DbValue::Real(f64::from(*self))
110    }
111}
112
113impl ToDbValue for f64 {
114    fn to_db_value(&self) -> DbValue {
115        DbValue::Real(*self)
116    }
117}
118
119impl ToDbValue for str {
120    fn to_db_value(&self) -> DbValue {
121        DbValue::Text(self.to_owned())
122    }
123}
124
125impl ToDbValue for String {
126    fn to_db_value(&self) -> DbValue {
127        DbValue::Text(self.clone())
128    }
129}
130
131/// The currency's ISO 4217 code, stored as `TEXT` (`"USD"`).
132impl ToDbValue for crate::money::Currency {
133    fn to_db_value(&self) -> DbValue {
134        DbValue::Text(self.code().to_owned())
135    }
136}
137
138/// The amount in minor units, stored as `BIGINT`. The currency goes in its
139/// own column: bind `money.currency` next to it.
140impl ToDbValue for crate::money::Money {
141    fn to_db_value(&self) -> DbValue {
142        DbValue::Integer(self.minor)
143    }
144}
145
146/// The scaled integer, stored as `BIGINT`: exact on both databases. The scale
147/// lives in the Rust type, not in the schema.
148impl<const S: u32> ToDbValue for crate::quantity::Quantity<S> {
149    fn to_db_value(&self) -> DbValue {
150        DbValue::Integer(self.raw())
151    }
152}
153
154/// Reads a `Quantity` from its `BIGINT` column (`FromDb` through sqlx).
155macro_rules! quantity_column {
156    ($db:ty) => {
157        impl<const S: u32> sqlx::Type<$db> for crate::quantity::Quantity<S> {
158            fn type_info() -> <$db as sqlx::Database>::TypeInfo {
159                <i64 as sqlx::Type<$db>>::type_info()
160            }
161
162            fn compatible(ty: &<$db as sqlx::Database>::TypeInfo) -> bool {
163                <i64 as sqlx::Type<$db>>::compatible(ty)
164            }
165        }
166
167        impl<'r, const S: u32> sqlx::Decode<'r, $db> for crate::quantity::Quantity<S> {
168            fn decode(
169                value: <$db as sqlx::Database>::ValueRef<'r>,
170            ) -> Result<Self, sqlx::error::BoxDynError> {
171                Ok(Self::from_raw(<i64 as sqlx::Decode<$db>>::decode(value)?))
172            }
173        }
174    };
175}
176
177quantity_column!(sqlx::sqlite::Sqlite);
178#[cfg(feature = "postgres")]
179quantity_column!(sqlx::postgres::Postgres);
180
181impl ToDbValue for Vec<u8> {
182    fn to_db_value(&self) -> DbValue {
183        DbValue::Blob(self.clone())
184    }
185}
186
187impl ToDbValue for serde_json::Value {
188    fn to_db_value(&self) -> DbValue {
189        DbValue::Json(self.clone())
190    }
191}
192
193#[cfg(feature = "uuid")]
194impl ToDbValue for uuid::Uuid {
195    fn to_db_value(&self) -> DbValue {
196        DbValue::Uuid(*self)
197    }
198}
199
200impl<Tz: TimeZone> ToDbValue for chrono::DateTime<Tz> {
201    fn to_db_value(&self) -> DbValue {
202        DbValue::DateTime(self.fixed_offset())
203    }
204}
205
206impl ToDbValue for NaiveDateTime {
207    fn to_db_value(&self) -> DbValue {
208        DbValue::NaiveDateTime(*self)
209    }
210}
211
212impl ToDbValue for NaiveDate {
213    fn to_db_value(&self) -> DbValue {
214        DbValue::Date(*self)
215    }
216}
217
218impl ToDbValue for NaiveTime {
219    fn to_db_value(&self) -> DbValue {
220        DbValue::Time(*self)
221    }
222}
223
224impl<T: ToDbValue> ToDbValue for Option<T> {
225    fn to_db_value(&self) -> DbValue {
226        self.as_ref().map_or(DbValue::Null, ToDbValue::to_db_value)
227    }
228}
229
230impl<T: ToDbValue + ?Sized> ToDbValue for &T {
231    fn to_db_value(&self) -> DbValue {
232        (**self).to_db_value()
233    }
234}
235
236impl ToDbValue for DbValue {
237    fn to_db_value(&self) -> DbValue {
238        self.clone()
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245    use serde_json::json;
246
247    // #254: every variant as JSON (User's extra columns and the grid show
248    // them this way), and the less common ToDbValue impls.
249    #[test]
250    fn every_value_has_a_json_form() {
251        let at = chrono::DateTime::parse_from_rfc3339("2026-10-01T09:30:00Z").unwrap();
252        let local = at.naive_utc();
253        let cases = [
254            (DbValue::Null, json!(null)),
255            (DbValue::Integer(7), json!(7)),
256            (DbValue::Real(1.5), json!(1.5)),
257            (DbValue::Text("a".into()), json!("a")),
258            (DbValue::Blob(vec![1, 2]), json!([1, 2])),
259            (DbValue::Bool(true), json!(true)),
260            (DbValue::DateTime(at), json!("2026-10-01T09:30:00+00:00")),
261            (DbValue::NaiveDateTime(local), json!("2026-10-01T09:30:00")),
262            (DbValue::Date(local.date()), json!("2026-10-01")),
263            (DbValue::Time(local.time()), json!("09:30:00")),
264            (DbValue::Json(json!({"a": 1})), json!({"a": 1})),
265            (
266                DbValue::Encrypted(super::super::encrypted::Unsealed("secret".into())),
267                json!("[encrypted]"),
268            ),
269        ];
270        for (value, expected) in cases {
271            assert_eq!(value.to_json(), expected, "{value:?}");
272        }
273    }
274
275    #[test]
276    fn floats_times_and_bytes_become_values() {
277        assert!(matches!(1.5f32.to_db_value(), DbValue::Real(v) if v == 1.5));
278        let time = chrono::NaiveTime::from_hms_opt(9, 30, 0).unwrap();
279        assert!(matches!(time.to_db_value(), DbValue::Time(t) if t == time));
280        assert!(matches!(vec![1u8, 2].to_db_value(), DbValue::Blob(b) if b == [1, 2]));
281    }
282}