navree_orm/cast.rs
1//! [`Cast`]: converting a field between its Rust type and its stored
2//! column value, for types that are not [`Field`]s themselves.
3//!
4//! A field opts in with `#[model(cast = ..)]`:
5//!
6//! | Attribute | Cast | Field type | Stored as |
7//! |---|---|---|---|
8//! | `cast = "json"` | [`AsJson`] | any `Serialize + DeserializeOwned` type (structs, `Vec`, maps, sets of enums) | JSON |
9//! | `cast = "string_enum"` | [`StringEnum`] | a unit enum, by its serde name | text |
10//! | `cast = "int_enum"` | [`IntEnum`] | `Copy + Into<i64> + TryFrom<i64>` (a `#[repr]` enum) | an integer |
11//! | `cast = "decimal(2)"` | [`DecimalScale`] | `Decimal`, rounded half away from zero to the scale | a decimal |
12//! | `cast = "datetime_format(\"%d/%m/%Y %H:%M\")"` | [`DateTimeFormat`] | `Timestamp`, `Zoned`, `DateTime`, `Date`, `Time` | text in that format |
13//! | `cast = "unix_timestamp"` / `"unix_timestamp_ms"` | [`UnixTimestamp`] / [`UnixTimestampMs`] | `Timestamp`, `DateTime` | integer seconds / milliseconds |
14//! | `cast = "encrypted"` | [`Encrypted`] | `String`, `Vec<u8>` | an encrypted payload (navree-crypto) |
15//! | `cast = "encrypted_json"` | [`EncryptedJson`] | any `Serialize + DeserializeOwned` type | encrypted JSON |
16//! | `cast = "hashed"` | [`Hashed`] | `String` | an Argon2id hash (navree-crypto) |
17//! | `cast = "binary_uuid"` / `"binary_ulid"` | [`BinaryUuid`] / [`BinaryUlid`] | `Uuid` / [`Ulid`](crate::Ulid) | 16 bytes |
18//! | `cast = "vector"` | [`Vector`] | `Vec<f32>` | a vector (pgvector, MySQL 9, MariaDB 11.7) |
19//! | `cast` (no value) | `<T as` [`Castable`]`>::Cast` | a type that picks its own cast | the cast's |
20//! | `cast = path::To::Cast` | yours | `T` where the cast is `Cast<T>` | `Cast::Stored` |
21//! | `cast(path::To::Cast, 2, Eur)` | `path::To::Cast<2, Eur>` | a cast with arguments | the cast's |
22//! | `inbound = path::To::Cast` | [`Inbound`] | a [`Field`] transformed on write only ([`InboundCast`]) | itself |
23//! | `cast = path, columns(a: A, b: B)` | yours ([`MultiColumnCast`]) | one field over several columns | each column |
24//!
25//! A cast on an `Option<T>` field casts the inner value; NULL stays `None`.
26//! Typed columns of cast fields encode condition values with the cast, so
27//! `Deal::STAGE.eq(Stage::Won)` compares with the stored `'won'`.
28//!
29//! Casts are static: `get` and `set` take no `self`. Casts that need an app
30//! service (the encrypter, the hasher) set [`Cast::CONTEXT`] and read it in
31//! [`Cast::get_with`] / [`Cast::set_with`] from the [`CastContext`] the ORM
32//! resolves from the executor's app (see [`CastContext`]); work that must
33//! be asynchronous (hashing a password off the async threads) happens in
34//! [`Cast::prepare`], before a record is written.
35//!
36//! ```
37//! use navree_orm::cast::{Cast, CastError};
38//!
39//! /// Cents stored as a decimal string, e.g. for a legacy column.
40//! struct CentsAsText;
41//!
42//! impl Cast<i64> for CentsAsText {
43//! type Stored = String;
44//!
45//! fn get(stored: String) -> Result<i64, CastError> {
46//! stored.parse().map_err(|_| CastError::new(format!("`{stored}` is not a number of cents")))
47//! }
48//!
49//! fn set(value: &i64) -> Result<String, CastError> {
50//! Ok(value.to_string())
51//! }
52//! }
53//!
54//! assert_eq!(CentsAsText::get("1250".into()).unwrap(), 1250);
55//! assert!(CentsAsText::get("12.5".into()).is_err());
56//! ```
57
58use std::fmt;
59
60use navree_kernel::BoxFuture;
61use serde::Serialize;
62use serde::de::DeserializeOwned;
63
64pub use crate::attributes::CastContext;
65pub use crate::attributes::casts::{
66 BinaryUlid, BinaryUuid, Castable, DateTimeFormat, DateTimeFormatSpec, DecimalScale, Encrypted,
67 EncryptedJson, EncryptedValue, FormattedDateTime, Hashed, Inbound, InboundCast,
68 MultiColumnCast, StoredColumns, StoredVector, UnixTimestamp, UnixTimestampMs, Vector,
69 is_password_hash,
70};
71use crate::row::Row;
72use crate::value::{Field, FieldError, FieldKind, Value, same_value};
73
74/// Why a cast failed.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct CastError(String);
77
78impl CastError {
79 /// An error with `message`.
80 pub fn new(message: impl Into<String>) -> Self {
81 CastError(message.into())
82 }
83}
84
85impl fmt::Display for CastError {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 f.write_str(&self.0)
88 }
89}
90
91impl std::error::Error for CastError {}
92
93impl From<FieldError> for CastError {
94 fn from(error: FieldError) -> Self {
95 CastError::new(error.to_string())
96 }
97}
98
99/// Converts fields of type `T` to and from their stored form.
100///
101/// `get` and `set` are all a cast must write. The other methods have
102/// defaults and refine how the ORM treats the field:
103///
104/// | Method | Used for | Default |
105/// |---|---|---|
106/// | [`CONTEXT`](Cast::CONTEXT), [`get_with`](Cast::get_with), [`set_with`](Cast::set_with) | casts that need an app service | `get` / `set`, no context |
107/// | [`eq_stored`](Cast::eq_stored), [`same`](Cast::same) | dirty tracking | stored values compared like other columns |
108/// | [`from_json`](Cast::from_json) | mass assignment (`fill`) of untyped input | the input is the stored form |
109/// | [`serialize`](Cast::serialize) | the value in serialized records | the field's own `Serialize` |
110/// | [`increment`](Cast::increment), [`decrement`](Cast::decrement) | `Record::increment_cast` | unsupported |
111/// | [`prepare`](Cast::prepare) | asynchronous work before a write (hashing) | nothing |
112/// | [`is_stale`](Cast::is_stale) | rewriting stored values that are outdated (old encryption keys) | never |
113pub trait Cast<T>: 'static {
114 /// The stored form (a [`Field`]: text, an integer, JSON, ...).
115 type Stored: Field;
116
117 /// Whether the cast reads services from a [`CastContext`] (the
118 /// encrypter, the hasher, the dialect, ...). When a model has such a
119 /// cast, the ORM resolves the context from the executor's app before
120 /// it reads or writes the model's records.
121 const CONTEXT: bool = false;
122
123 /// What the field's values are in serialized records (for OpenAPI
124 /// schemas and date-time formatting); [`FieldKind::Any`] unless the
125 /// cast says.
126 const KIND: FieldKind = FieldKind::Any;
127
128 /// The stored form to the field (reading from the database).
129 fn get(stored: Self::Stored) -> Result<T, CastError>;
130
131 /// The field to its stored form (writing to the database, comparing in
132 /// conditions).
133 fn set(value: &T) -> Result<Self::Stored, CastError>;
134
135 /// [`get`](Cast::get) with the services of `context`; what the ORM
136 /// calls. Casts that need a service implement this one, and `get` as
137 /// `Self::get_with(stored, &CastContext::current())`.
138 fn get_with(stored: Self::Stored, context: &CastContext) -> Result<T, CastError> {
139 let _ = context;
140 Self::get(stored)
141 }
142
143 /// [`set`](Cast::set) with the services of `context`; what the ORM
144 /// calls.
145 fn set_with(value: &T, context: &CastContext) -> Result<Self::Stored, CastError> {
146 let _ = context;
147 Self::set(value)
148 }
149
150 /// The NULL a nullable field's `None` is stored as. Defaults to the
151 /// stored type's NULL; casts whose column type differs between
152 /// databases give the NULL of `context`'s dialect (PostgreSQL checks a
153 /// NULL's type against the column's).
154 fn null_with(context: &CastContext) -> Value {
155 let _ = context;
156 <Self::Stored as Field>::null()
157 }
158
159 /// Whether two stored values hold the same thing (dirty tracking).
160 /// Defaults to the column comparison: NULLs equal, floats within a
161 /// small tolerance, decimals numerically, date-times by instant, JSON
162 /// structurally.
163 fn eq_stored(a: &Self::Stored, b: &Self::Stored) -> bool {
164 same_value(&a.to_value(), &b.to_value())
165 }
166
167 /// Whether two field values would be stored as the same thing (dirty
168 /// tracking compares a record's field with its original this way).
169 /// Defaults to encoding both and comparing them with
170 /// [`eq_stored`](Cast::eq_stored); a value that cannot be encoded
171 /// counts as different. Casts whose stored form is not deterministic
172 /// (encryption, hashing) compare the field values instead.
173 fn same(a: &T, b: &T, context: &CastContext) -> bool {
174 match (Self::set_with(a, context), Self::set_with(b, context)) {
175 (Ok(a), Ok(b)) => Self::eq_stored(&a, &b),
176 _ => false,
177 }
178 }
179
180 /// The field from untyped input (a JSON value given to `fill`, a
181 /// request body). Defaults to reading the input as the stored form, so
182 /// a JSON cast takes JSON and a string enum takes its name; casts whose
183 /// stored form is not what users send (encrypted, hashed, binary ids,
184 /// timestamps) take the plain value instead.
185 fn from_json(input: serde_json::Value, context: &CastContext) -> Result<T, CastError> {
186 let stored = Self::Stored::from_json(input)?;
187 Self::get_with(stored, context)
188 }
189
190 /// The value in serialized records, when the cast decides it; `None`
191 /// (the default) keeps what the field's own `Serialize` writes.
192 fn serialize(value: &T) -> Option<Result<serde_json::Value, CastError>> {
193 let _ = value;
194 None
195 }
196
197 /// `value + amount`, for increments through the cast
198 /// ([`Record::increment_cast`](crate::Record::increment_cast)); the
199 /// database adds `amount`'s stored form. Unsupported by default.
200 fn increment(value: &T, amount: &T) -> Result<T, CastError> {
201 let _ = (value, amount);
202 Err(CastError::new(
203 "this cast does not support increments: implement Cast::increment and Cast::decrement",
204 ))
205 }
206
207 /// `value - amount`, for decrements through the cast. Unsupported by
208 /// default.
209 fn decrement(value: &T, amount: &T) -> Result<T, CastError> {
210 let _ = (value, amount);
211 Err(CastError::new(
212 "this cast does not support decrements: implement Cast::increment and Cast::decrement",
213 ))
214 }
215
216 /// Asynchronous work on the field before the record is written (after
217 /// the `saving`, `creating` and `updating` hooks): the hashed cast
218 /// hashes a plain value here, off the async threads. Nothing by
219 /// default.
220 fn prepare<'a>(
221 value: &'a mut T,
222 context: &'a CastContext,
223 ) -> BoxFuture<'a, Result<(), CastError>> {
224 let _ = (value, context);
225 Box::pin(std::future::ready(Ok(())))
226 }
227
228 /// Whether the stored value of `column` in `row` should be rewritten
229 /// even though the field did not change: the encrypted casts report
230 /// payloads encrypted with a previous key, so the next save re-encrypts
231 /// them with the current one. Never by default.
232 fn is_stale(row: &Row, column: &str, context: &CastContext) -> bool {
233 let _ = (row, column, context);
234 false
235 }
236}
237
238/// Encodes a field through cast `C` (the encoder of a typed column), with
239/// the current [`CastContext`].
240pub fn encode<C: Cast<T>, T>(value: &T) -> Result<Value, String> {
241 CastContext::with_current(|context| C::set_with(value, context))
242 .map(|stored| stored.to_value())
243 .map_err(|error| error.to_string())
244}
245
246/// Decodes a field through cast `C` (the decoder of a typed column), with
247/// the current [`CastContext`].
248pub fn decode<C: Cast<T>, T>(row: &Row, column: &str) -> Result<T, FieldError> {
249 let stored = row.field::<C::Stored>(column)?;
250 CastContext::with_current(|context| C::get_with(stored, context))
251 .map_err(|error| FieldError::Invalid(error.to_string()))
252}
253
254/// Encodes a nullable field through cast `C` (`None` is a typed NULL).
255pub fn encode_option<C: Cast<T>, T>(value: &Option<T>) -> Result<Value, String> {
256 match value {
257 Some(value) => encode::<C, T>(value),
258 None => Ok(CastContext::with_current(C::null_with)),
259 }
260}
261
262/// Decodes a nullable field through cast `C` (NULL is `None`).
263pub fn decode_option<C: Cast<T>, T>(row: &Row, column: &str) -> Result<Option<T>, FieldError> {
264 match row.field::<Option<C::Stored>>(column)? {
265 Some(stored) => CastContext::with_current(|context| C::get_with(stored, context))
266 .map(Some)
267 .map_err(|error| FieldError::Invalid(error.to_string())),
268 None => Ok(None),
269 }
270}
271
272/// Any serde type stored as JSON (`#[model(cast = "json")]`): structs,
273/// vectors, maps, embedded documents.
274///
275/// ```
276/// use navree_orm::cast::{AsJson, Cast};
277/// use serde::{Deserialize, Serialize};
278///
279/// #[derive(Debug, PartialEq, Serialize, Deserialize)]
280/// struct Address {
281/// city: String,
282/// }
283///
284/// let stored = <AsJson as Cast<Address>>::set(&Address { city: "Oslo".into() }).unwrap();
285/// assert_eq!(stored, serde_json::json!({"city": "Oslo"}));
286/// let address: Address = AsJson::get(stored).unwrap();
287/// assert_eq!(address, Address { city: "Oslo".into() });
288/// ```
289#[derive(Clone, Copy, Debug, Default)]
290pub struct AsJson;
291
292impl<T: Serialize + DeserializeOwned> Cast<T> for AsJson {
293 type Stored = serde_json::Value;
294
295 const KIND: FieldKind = FieldKind::Json;
296
297 fn get(stored: serde_json::Value) -> Result<T, CastError> {
298 serde_json::from_value(stored)
299 .map_err(|error| CastError::new(format!("invalid JSON: {error}")))
300 }
301
302 fn set(value: &T) -> Result<serde_json::Value, CastError> {
303 serde_json::to_value(value)
304 .map_err(|error| CastError::new(format!("cannot encode as JSON: {error}")))
305 }
306}
307
308/// Any serde type stored as JSON text in a text column
309/// (`#[model(cast = navree_orm::cast::JsonText)]`), for tables whose JSON
310/// lives in `TEXT` columns rather than `JSON`/`JSONB` ones (the
311/// [`AsJson`] cast binds a JSON value, which PostgreSQL refuses for a text
312/// column). The text is serde's compact JSON; a field compares by its JSON
313/// value, and untyped input (`fill`) is the JSON value itself, not text.
314///
315/// ```
316/// use navree_orm::cast::{Cast, JsonText};
317/// use serde::{Deserialize, Serialize};
318///
319/// #[derive(Debug, PartialEq, Serialize, Deserialize)]
320/// struct Retry {
321/// attempts: u32,
322/// }
323///
324/// let stored = <JsonText as Cast<Retry>>::set(&Retry { attempts: 3 }).unwrap();
325/// assert_eq!(stored, r#"{"attempts":3}"#);
326/// let retry: Retry = JsonText::get(r#"{ "attempts": 3 }"#.to_owned()).unwrap();
327/// assert_eq!(retry, Retry { attempts: 3 });
328/// assert!(<JsonText as Cast<Retry>>::get("not json".to_owned()).is_err());
329/// ```
330#[derive(Clone, Copy, Debug, Default)]
331pub struct JsonText;
332
333impl<T: Serialize + DeserializeOwned> Cast<T> for JsonText {
334 type Stored = String;
335
336 const KIND: FieldKind = FieldKind::Json;
337
338 fn get(stored: String) -> Result<T, CastError> {
339 serde_json::from_str(&stored)
340 .map_err(|error| CastError::new(format!("invalid JSON text: {error}")))
341 }
342
343 fn set(value: &T) -> Result<String, CastError> {
344 serde_json::to_string(value)
345 .map_err(|error| CastError::new(format!("cannot encode as JSON: {error}")))
346 }
347
348 /// Texts holding the same JSON value are the same, whatever their
349 /// spacing or key order.
350 fn eq_stored(a: &String, b: &String) -> bool {
351 match (
352 serde_json::from_str::<serde_json::Value>(a),
353 serde_json::from_str::<serde_json::Value>(b),
354 ) {
355 (Ok(a), Ok(b)) => a == b,
356 _ => a == b,
357 }
358 }
359
360 fn from_json(input: serde_json::Value, _context: &CastContext) -> Result<T, CastError> {
361 serde_json::from_value(input)
362 .map_err(|error| CastError::new(format!("invalid JSON: {error}")))
363 }
364}
365
366/// A unit enum stored as its serde name (`#[model(cast = "string_enum")]`):
367/// `#[serde(rename_all = "snake_case")] enum Stage { ClosedWon }` is
368/// stored as `closed_won`.
369///
370/// ```
371/// use navree_orm::cast::{Cast, StringEnum};
372/// use serde::{Deserialize, Serialize};
373///
374/// #[derive(Debug, PartialEq, Serialize, Deserialize)]
375/// #[serde(rename_all = "snake_case")]
376/// enum Stage {
377/// Lead,
378/// ClosedWon,
379/// }
380///
381/// assert_eq!(<StringEnum as Cast<Stage>>::set(&Stage::ClosedWon).unwrap(), "closed_won");
382/// let stage: Stage = StringEnum::get("lead".into()).unwrap();
383/// assert_eq!(stage, Stage::Lead);
384/// assert!(<StringEnum as Cast<Stage>>::get("won".into()).is_err());
385/// ```
386#[derive(Clone, Copy, Debug, Default)]
387pub struct StringEnum;
388
389impl<T: Serialize + DeserializeOwned> Cast<T> for StringEnum {
390 type Stored = String;
391
392 const KIND: FieldKind = FieldKind::Text;
393
394 fn get(stored: String) -> Result<T, CastError> {
395 serde_json::from_value(serde_json::Value::String(stored.clone())).map_err(|_| {
396 CastError::new(format!(
397 "`{stored}` is not a variant of {}",
398 short_type_name::<T>()
399 ))
400 })
401 }
402
403 fn set(value: &T) -> Result<String, CastError> {
404 match serde_json::to_value(value) {
405 Ok(serde_json::Value::String(name)) => Ok(name),
406 Ok(other) => Err(CastError::new(format!(
407 "{} does not serialize as a string (found {other}); use a unit enum",
408 short_type_name::<T>()
409 ))),
410 Err(error) => Err(CastError::new(error.to_string())),
411 }
412 }
413}
414
415/// An enum stored as an integer (`#[model(cast = "int_enum")]`), through
416/// `Into<i64>` and `TryFrom<i64>` (a `#[repr(i32)]` enum with those
417/// conversions).
418///
419/// ```
420/// use navree_orm::cast::{Cast, IntEnum};
421///
422/// #[derive(Clone, Copy, Debug, PartialEq)]
423/// enum Priority {
424/// Low = 1,
425/// High = 2,
426/// }
427///
428/// impl From<Priority> for i64 {
429/// fn from(p: Priority) -> i64 {
430/// p as i64
431/// }
432/// }
433///
434/// impl TryFrom<i64> for Priority {
435/// type Error = String;
436/// fn try_from(n: i64) -> Result<Self, String> {
437/// match n {
438/// 1 => Ok(Priority::Low),
439/// 2 => Ok(Priority::High),
440/// other => Err(format!("no priority {other}")),
441/// }
442/// }
443/// }
444///
445/// assert_eq!(IntEnum::set(&Priority::High).unwrap(), 2);
446/// assert_eq!(<IntEnum as Cast<Priority>>::get(1).unwrap(), Priority::Low);
447/// assert!(<IntEnum as Cast<Priority>>::get(9).is_err());
448/// ```
449#[derive(Clone, Copy, Debug, Default)]
450pub struct IntEnum;
451
452impl<T> Cast<T> for IntEnum
453where
454 T: Copy + Into<i64> + TryFrom<i64>,
455 <T as TryFrom<i64>>::Error: fmt::Display,
456{
457 type Stored = i64;
458
459 fn get(stored: i64) -> Result<T, CastError> {
460 T::try_from(stored).map_err(|error| CastError::new(error.to_string()))
461 }
462
463 fn set(value: &T) -> Result<i64, CastError> {
464 Ok((*value).into())
465 }
466}
467
468/// `T`'s name without its module path, for messages.
469fn short_type_name<T>() -> &'static str {
470 let full = std::any::type_name::<T>();
471 let base = full.split('<').next().unwrap_or(full);
472 base.rsplit("::").next().unwrap_or(base)
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478
479 #[derive(Debug, PartialEq, Serialize, serde::Deserialize)]
480 struct Point {
481 x: i32,
482 }
483
484 #[test]
485 fn short_names() {
486 assert_eq!(short_type_name::<Point>(), "Point");
487 assert_eq!(short_type_name::<Vec<Point>>(), "Vec");
488 }
489
490 #[test]
491 fn encode_and_decode_through_a_cast() {
492 assert_eq!(
493 encode::<AsJson, Point>(&Point { x: 3 }).unwrap(),
494 Value::Json(serde_json::json!({"x": 3}))
495 );
496 let row = Row::from_values(vec![(
497 "point".into(),
498 Value::from(serde_json::json!({"x": 5})),
499 )]);
500 assert_eq!(
501 decode::<AsJson, Point>(&row, "point").unwrap(),
502 Point { x: 5 }
503 );
504 assert!(matches!(
505 decode::<AsJson, Point>(&row, "missing"),
506 Err(FieldError::Missing)
507 ));
508 }
509
510 #[test]
511 fn string_enums_reject_structs() {
512 let error = <StringEnum as Cast<Point>>::set(&Point { x: 1 }).unwrap_err();
513 assert!(
514 error.to_string().contains("does not serialize as a string"),
515 "{error}"
516 );
517 }
518
519 #[test]
520 fn json_text_is_stored_as_text_and_compared_as_json() {
521 assert_eq!(
522 encode::<JsonText, Point>(&Point { x: 3 }).unwrap(),
523 Value::String(r#"{"x":3}"#.to_owned())
524 );
525 let row = Row::from_values(vec![("point".into(), Value::from(r#"{ "x": 5 }"#))]);
526 assert_eq!(
527 decode::<JsonText, Point>(&row, "point").unwrap(),
528 Point { x: 5 }
529 );
530 let row = Row::from_values(vec![("point".into(), Value::from("{"))]);
531 assert!(matches!(
532 decode::<JsonText, Point>(&row, "point"),
533 Err(FieldError::Invalid(message)) if message.starts_with("invalid JSON text")
534 ));
535
536 let same = <JsonText as Cast<serde_json::Value>>::eq_stored;
537 assert!(same(
538 &r#"{"a":1,"b":2}"#.to_owned(),
539 &r#"{ "b": 2, "a": 1 }"#.to_owned()
540 ));
541 assert!(!same(&r#"{"a":1}"#.to_owned(), &r#"{"a":2}"#.to_owned()));
542 assert!(same(&"not json".to_owned(), &"not json".to_owned()));
543
544 let filled: Point =
545 JsonText::from_json(serde_json::json!({"x": 7}), &CastContext::new()).unwrap();
546 assert_eq!(filled, Point { x: 7 });
547 }
548}