Skip to main content

glacier/db/
value.rs

1//! Values bound into queries, and the types columns decode into.
2
3use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
4
5/// A point in time, stored as `TIMESTAMPTZ` (Postgres) or ISO-8601 text
6/// (SQLite).
7pub type Timestamp = DateTime<Utc>;
8
9/// A time without a zone, for `timestamp without time zone` columns such
10/// as Rails' `created_at`. Taken to be UTC when written.
11pub type NaiveTimestamp = NaiveDateTime;
12
13/// A calendar day, for `date` columns: `field due_on: Date`.
14pub type Date = NaiveDate;
15
16/// A JSON document, for `json`/`jsonb` columns (JSON text on SQLite):
17/// `field cache: JsonValue`.
18pub type JsonValue = serde_json::Value;
19
20/// A JSON column a model's `store` reads typed settings from.
21#[doc(hidden)]
22pub trait StoreSource {
23    fn store_value(&self, key: &str) -> Option<&JsonValue>;
24}
25
26impl StoreSource for JsonValue {
27    fn store_value(&self, key: &str) -> Option<&JsonValue> {
28        self.get(key).filter(|v| !v.is_null())
29    }
30}
31
32impl StoreSource for Option<JsonValue> {
33    fn store_value(&self, key: &str) -> Option<&JsonValue> {
34        self.as_ref()?.store_value(key)
35    }
36}
37
38/// A JSON column a model's `store` writes settings into.
39#[doc(hidden)]
40pub trait StoreTarget {
41    fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue>;
42}
43
44impl StoreTarget for JsonValue {
45    fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue> {
46        if !self.is_object() {
47            *self = JsonValue::Object(serde_json::Map::new());
48        }
49        self.as_object_mut().expect("made an object above")
50    }
51}
52
53impl StoreTarget for Option<JsonValue> {
54    fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue> {
55        self.get_or_insert_with(|| JsonValue::Object(serde_json::Map::new()))
56            .store_object()
57    }
58}
59
60/// Sets a setting in a JSON column, as Rails' `store_accessor` writes it.
61#[doc(hidden)]
62pub fn store_set(store: &mut impl StoreTarget, key: &str, value: impl serde::Serialize) {
63    let value = serde_json::to_value(value).unwrap_or(JsonValue::Null);
64    store.store_object().insert(key.to_owned(), value);
65}
66
67/// A setting from a JSON column, as Rails' `store_accessor` reads it:
68/// `None` when it's missing, null, or not a `T`.
69#[doc(hidden)]
70pub fn store_get<T: serde::de::DeserializeOwned>(store: &impl StoreSource, key: &str) -> Option<T> {
71    serde_json::from_value(store.store_value(key)?.clone()).ok()
72}
73
74/// A value sent to the database.
75#[derive(Debug, Clone, PartialEq)]
76pub enum Value {
77    Null,
78    Bool(bool),
79    Int(i64),
80    Float(f64),
81    Text(String),
82    Bytes(Vec<u8>),
83    Timestamp(Timestamp),
84    Date(Date),
85    Json(JsonValue),
86    Decimal(super::Decimal),
87    Uuid(uuid::Uuid),
88    /// Values bound as one Postgres array, for `column = ANY($1)`: made by
89    /// `IN` lists, never by hand.
90    #[doc(hidden)]
91    List(Vec<Value>),
92}
93
94impl Value {
95    pub fn is_null(&self) -> bool {
96        matches!(self, Value::Null)
97    }
98
99    /// The value as text, e.g. to refill a form field. `Null` is empty.
100    pub fn to_text(&self) -> String {
101        match self {
102            Value::Null => String::new(),
103            Value::Bool(v) => v.to_string(),
104            Value::Int(v) => v.to_string(),
105            Value::Float(v) => v.to_string(),
106            Value::Text(v) => v.clone(),
107            Value::Bytes(v) => String::from_utf8_lossy(v).into_owned(),
108            Value::Timestamp(v) => v.to_rfc3339(),
109            Value::Date(v) => v.to_string(),
110            Value::Json(v) => v.to_string(),
111            Value::Decimal(v) => v.to_string(),
112            Value::Uuid(v) => v.to_string(),
113            Value::List(items) => items
114                .iter()
115                .map(Value::to_text)
116                .collect::<Vec<_>>()
117                .join(", "),
118        }
119    }
120}
121
122/// Rust values that can be bound into a query, and (for a model's fields)
123/// read back from one.
124pub trait ToValue {
125    fn to_value(&self) -> Value;
126
127    /// The field's value from a column's `Value`, the reverse of
128    /// [`to_value`](Self::to_value): how a record is made from a
129    /// changeset, for its callbacks. `None` when it doesn't fit (the
130    /// default, for types that can't say).
131    fn from_value(value: Value) -> Option<Self>
132    where
133        Self: Sized,
134    {
135        let _ = value;
136        None
137    }
138}
139
140impl<T: ToValue + ?Sized> ToValue for &T {
141    fn to_value(&self) -> Value {
142        (**self).to_value()
143    }
144}
145
146impl<T: ToValue> ToValue for Option<T> {
147    fn to_value(&self) -> Value {
148        self.as_ref().map_or(Value::Null, ToValue::to_value)
149    }
150
151    fn from_value(value: Value) -> Option<Self> {
152        match value {
153            Value::Null => Some(None),
154            value => T::from_value(value).map(Some),
155        }
156    }
157}
158
159impl ToValue for Value {
160    fn to_value(&self) -> Value {
161        self.clone()
162    }
163
164    fn from_value(value: Value) -> Option<Self> {
165        Some(value)
166    }
167}
168
169macro_rules! int_value {
170    ($($t:ty),*) => {$(
171        impl ToValue for $t {
172            fn to_value(&self) -> Value {
173                Value::Int((*self).into())
174            }
175
176            fn from_value(value: Value) -> Option<Self> {
177                match value {
178                    Value::Int(n) => n.try_into().ok(),
179                    _ => None,
180                }
181            }
182        }
183    )*};
184}
185
186int_value!(i8, i16, i32, i64, u8, u16, u32);
187
188impl ToValue for f32 {
189    fn to_value(&self) -> Value {
190        Value::Float((*self).into())
191    }
192
193    fn from_value(value: Value) -> Option<Self> {
194        f64::from_value(value).map(|n| n as f32)
195    }
196}
197
198impl ToValue for f64 {
199    fn to_value(&self) -> Value {
200        Value::Float(*self)
201    }
202
203    fn from_value(value: Value) -> Option<Self> {
204        match value {
205            Value::Float(n) => Some(n),
206            Value::Int(n) => Some(n as f64),
207            _ => None,
208        }
209    }
210}
211
212impl ToValue for bool {
213    fn to_value(&self) -> Value {
214        Value::Bool(*self)
215    }
216
217    fn from_value(value: Value) -> Option<Self> {
218        match value {
219            Value::Bool(b) => Some(b),
220            Value::Int(n) => Some(n != 0),
221            _ => None,
222        }
223    }
224}
225
226impl ToValue for Timestamp {
227    fn to_value(&self) -> Value {
228        Value::Timestamp(*self)
229    }
230
231    fn from_value(value: Value) -> Option<Self> {
232        match value {
233            Value::Timestamp(t) => Some(t),
234            _ => None,
235        }
236    }
237}
238
239impl ToValue for NaiveTimestamp {
240    fn to_value(&self) -> Value {
241        Value::Timestamp(self.and_utc())
242    }
243
244    fn from_value(value: Value) -> Option<Self> {
245        Timestamp::from_value(value).map(|t| t.naive_utc())
246    }
247}
248
249impl ToValue for Date {
250    fn to_value(&self) -> Value {
251        Value::Date(*self)
252    }
253
254    fn from_value(value: Value) -> Option<Self> {
255        match value {
256            Value::Date(d) => Some(d),
257            _ => None,
258        }
259    }
260}
261
262impl ToValue for str {
263    fn to_value(&self) -> Value {
264        Value::Text(self.to_owned())
265    }
266}
267
268impl ToValue for String {
269    fn to_value(&self) -> Value {
270        Value::Text(self.clone())
271    }
272
273    fn from_value(value: Value) -> Option<Self> {
274        match value {
275            Value::Text(t) => Some(t),
276            _ => None,
277        }
278    }
279}
280
281impl ToValue for uuid::Uuid {
282    fn to_value(&self) -> Value {
283        Value::Uuid(*self)
284    }
285
286    fn from_value(value: Value) -> Option<Self> {
287        match value {
288            Value::Uuid(u) => Some(u),
289            Value::Text(t) => t.parse().ok(),
290            _ => None,
291        }
292    }
293}
294
295impl ToValue for super::Decimal {
296    fn to_value(&self) -> Value {
297        Value::Decimal(self.clone())
298    }
299
300    fn from_value(value: Value) -> Option<Self> {
301        match value {
302            Value::Decimal(d) => Some(d),
303            _ => None,
304        }
305    }
306}
307
308impl ToValue for JsonValue {
309    fn to_value(&self) -> Value {
310        Value::Json(self.clone())
311    }
312
313    fn from_value(value: Value) -> Option<Self> {
314        match value {
315            Value::Json(j) => Some(j),
316            _ => None,
317        }
318    }
319}
320
321impl ToValue for Vec<u8> {
322    fn to_value(&self) -> Value {
323        Value::Bytes(self.clone())
324    }
325
326    fn from_value(value: Value) -> Option<Self> {
327        match value {
328            Value::Bytes(b) => Some(b),
329            _ => None,
330        }
331    }
332}
333
334#[cfg(feature = "postgres")]
335mod pg {
336    pub trait Decode:
337        for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres>
338    {
339    }
340    impl<T> Decode for T where T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> {}
341}
342
343#[cfg(not(feature = "postgres"))]
344mod pg {
345    pub trait Decode {}
346    impl<T> Decode for T {}
347}
348
349#[cfg(feature = "sqlite")]
350mod sqlite {
351    pub trait Decode: for<'r> sqlx::Decode<'r, sqlx::Sqlite> + sqlx::Type<sqlx::Sqlite> {}
352    impl<T> Decode for T where T: for<'r> sqlx::Decode<'r, sqlx::Sqlite> + sqlx::Type<sqlx::Sqlite> {}
353}
354
355#[cfg(not(feature = "sqlite"))]
356mod sqlite {
357    pub trait Decode {}
358    impl<T> Decode for T {}
359}
360
361/// Types a column can be read into, on every enabled database. Covers
362/// `i16`/`i32`/`i64`, `f32`/`f64`, `bool`, `String`, `Vec<u8>`,
363/// [`Timestamp`], [`JsonValue`] and `Option` of those.
364pub trait FromColumn: pg::Decode + sqlite::Decode + Send + 'static {}
365
366impl<T> FromColumn for T where T: pg::Decode + sqlite::Decode + Send + 'static {}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    #[test]
373    fn reads_store_settings() {
374        let cache = serde_json::json!({"days": 3, "text": "Hi", "gone": null, "wrong": "x"});
375        assert_eq!(store_get::<i64>(&cache, "days"), Some(3));
376        assert_eq!(store_get::<String>(&cache, "text").as_deref(), Some("Hi"));
377        assert_eq!(
378            store_get::<String>(&cache, "gone"),
379            None,
380            "null reads as unset"
381        );
382        assert_eq!(store_get::<i64>(&cache, "missing"), None);
383        assert_eq!(
384            store_get::<i64>(&cache, "wrong"),
385            None,
386            "the wrong type reads as unset"
387        );
388        assert_eq!(store_get::<i64>(&None::<JsonValue>, "days"), None);
389
390        let mut empty: Option<JsonValue> = None;
391        store_set(&mut empty, "days", 4);
392        assert_eq!(empty, Some(serde_json::json!({"days": 4})));
393        let mut cache = cache;
394        store_set(&mut cache, "text", "Bye");
395        assert_eq!(cache["text"], "Bye");
396        assert_eq!(cache["days"], 3, "other settings stay");
397    }
398}