Skip to main content

fastauth_core/
value.rs

1use std::fmt;
2use std::sync::Arc;
3
4use serde::de::DeserializeOwned;
5use serde::{Deserialize, Serialize};
6use time::OffsetDateTime;
7
8use crate::crypto::Hash;
9use crate::schema::{ColumnType, TableDef};
10
11/// A single database value as it crosses the adapter boundary.
12#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
13#[serde(tag = "t", content = "v")]
14pub enum Value {
15    Null,
16    Bool(bool),
17    Int(i64),
18    Text(String),
19    Bytes(Vec<u8>),
20    Timestamp(#[serde(with = "time::serde::rfc3339")] OffsetDateTime),
21    Json(serde_json::Value),
22}
23
24impl Value {
25    pub fn is_null(&self) -> bool {
26        matches!(self, Value::Null)
27    }
28
29    /// The JSON a client sees for this value.
30    pub fn to_json(&self) -> serde_json::Value {
31        match self {
32            Value::Null => serde_json::Value::Null,
33            Value::Bool(b) => (*b).into(),
34            Value::Int(i) => (*i).into(),
35            Value::Text(s) => s.clone().into(),
36            Value::Bytes(_) => serde_json::Value::Null,
37            Value::Timestamp(t) => t
38                .format(&time::format_description::well_known::Rfc3339)
39                .map(serde_json::Value::String)
40                .unwrap_or(serde_json::Value::Null),
41            Value::Json(j) => j.clone(),
42        }
43    }
44
45    /// Parses client JSON into a value of `ty`, for user-settable columns.
46    pub fn from_json(ty: ColumnType, json: &serde_json::Value) -> Option<Value> {
47        use serde_json::Value as J;
48        Some(match (ty, json) {
49            (_, J::Null) => Value::Null,
50            (ColumnType::Bool, J::Bool(b)) => Value::Bool(*b),
51            (ColumnType::Int, J::Number(n)) => Value::Int(n.as_i64()?),
52            (ColumnType::Text | ColumnType::Id, J::String(s)) => Value::Text(s.clone()),
53            (ColumnType::Timestamp, J::String(s)) => Value::Timestamp(
54                OffsetDateTime::parse(s, &time::format_description::well_known::Rfc3339).ok()?,
55            ),
56            (ColumnType::Json, j) => Value::Json(j.clone()),
57            _ => return None,
58        })
59    }
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
63#[error("column `{column}`: {message}")]
64pub struct DecodeError {
65    pub column: String,
66    pub message: String,
67}
68
69impl DecodeError {
70    pub fn new(column: impl Into<String>, message: impl Into<String>) -> Self {
71        Self {
72            column: column.into(),
73            message: message.into(),
74        }
75    }
76}
77
78/// Rust types that map to one column.
79pub trait ColumnValue: Sized + Send + Sync + 'static {
80    const TYPE: ColumnType;
81    const NULLABLE: bool = false;
82    fn into_value(self) -> Value;
83    fn from_value(value: Value) -> Result<Self, String>;
84}
85
86macro_rules! column_value {
87    ($ty:ty, $col:ident, $variant:ident) => {
88        impl ColumnValue for $ty {
89            const TYPE: ColumnType = ColumnType::$col;
90            fn into_value(self) -> Value {
91                Value::$variant(self)
92            }
93            fn from_value(value: Value) -> Result<Self, String> {
94                match value {
95                    Value::$variant(v) => Ok(v),
96                    other => Err(format!("expected {}, got {other:?}", stringify!($variant))),
97                }
98            }
99        }
100    };
101}
102
103column_value!(bool, Bool, Bool);
104column_value!(i64, Int, Int);
105column_value!(String, Text, Text);
106column_value!(Vec<u8>, Bytes, Bytes);
107column_value!(OffsetDateTime, Timestamp, Timestamp);
108
109impl<T: ColumnValue> ColumnValue for Option<T> {
110    const TYPE: ColumnType = T::TYPE;
111    const NULLABLE: bool = true;
112    fn into_value(self) -> Value {
113        self.map_or(Value::Null, ColumnValue::into_value)
114    }
115    fn from_value(value: Value) -> Result<Self, String> {
116        match value {
117            Value::Null => Ok(None),
118            v => T::from_value(v).map(Some),
119        }
120    }
121}
122
123/// A JSON column holding `T`.
124#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
125#[serde(transparent)]
126pub struct Json<T>(pub T);
127
128impl<T: Serialize + DeserializeOwned + Send + Sync + 'static> ColumnValue for Json<T> {
129    const TYPE: ColumnType = ColumnType::Json;
130    fn into_value(self) -> Value {
131        Value::Json(serde_json::to_value(self.0).unwrap_or(serde_json::Value::Null))
132    }
133    fn from_value(value: Value) -> Result<Self, String> {
134        match value {
135            Value::Json(j) => serde_json::from_value(j)
136                .map(Json)
137                .map_err(|e| e.to_string()),
138            Value::Text(s) => serde_json::from_str(&s)
139                .map(Json)
140                .map_err(|e| e.to_string()),
141            other => Err(format!("expected json, got {other:?}")),
142        }
143    }
144}
145
146/// A primary or foreign key: an opaque string. fastauth creates ids with the configured
147/// [`IdStrategy`](crate::config::IdStrategy) (ULIDs by default); handlers get one from
148/// `ctx.new_id()`.
149#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
150#[serde(transparent)]
151pub struct Id(String);
152
153impl Id {
154    /// A UUIDv7, whatever the configured strategy. Rows fastauth stores should get their
155    /// id from `ctx.new_id()` instead, so they match the configured strategy and storage.
156    pub fn new_v7() -> Self {
157        Id(uuid::Uuid::now_v7().to_string())
158    }
159
160    pub fn as_str(&self) -> &str {
161        &self.0
162    }
163}
164
165impl From<String> for Id {
166    fn from(s: String) -> Self {
167        Id(s)
168    }
169}
170
171impl From<&str> for Id {
172    fn from(s: &str) -> Self {
173        Id(s.to_owned())
174    }
175}
176
177impl From<&Id> for Id {
178    fn from(id: &Id) -> Self {
179        id.clone()
180    }
181}
182
183impl fmt::Display for Id {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        f.write_str(&self.0)
186    }
187}
188
189impl fmt::Debug for Id {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        write!(f, "Id({})", self.0)
192    }
193}
194
195impl ColumnValue for Id {
196    const TYPE: ColumnType = ColumnType::Id;
197    fn into_value(self) -> Value {
198        Value::Text(self.0)
199    }
200    fn from_value(value: Value) -> Result<Self, String> {
201        match value {
202            Value::Text(s) => Ok(Id(s)),
203            other => Err(format!("expected id, got {other:?}")),
204        }
205    }
206}
207
208impl ColumnValue for Hash {
209    const TYPE: ColumnType = ColumnType::Bytes;
210    fn into_value(self) -> Value {
211        Value::Bytes(self.as_bytes().to_vec())
212    }
213    fn from_value(value: Value) -> Result<Self, String> {
214        match value {
215            Value::Bytes(b) => Hash::from_slice(&b).ok_or_else(|| "expected 32 bytes".to_owned()),
216            other => Err(format!("expected hash bytes, got {other:?}")),
217        }
218    }
219}
220
221/// A row as the adapter returns it: values in the table's column order.
222#[derive(Clone, Debug)]
223pub struct Row {
224    table: Arc<TableDef>,
225    values: Vec<Value>,
226}
227
228impl Row {
229    /// `values` must be in `table`'s column order. Adapters build rows with this.
230    pub fn new(table: Arc<TableDef>, values: Vec<Value>) -> Self {
231        debug_assert_eq!(
232            table.columns.len(),
233            values.len(),
234            "row width for {}",
235            table.name
236        );
237        Self { table, values }
238    }
239
240    pub fn table(&self) -> &Arc<TableDef> {
241        &self.table
242    }
243
244    pub fn values(&self) -> &[Value] {
245        &self.values
246    }
247
248    pub fn into_values(self) -> Vec<Value> {
249        self.values
250    }
251
252    pub fn value(&self, column: &str) -> Option<&Value> {
253        self.table.position(column).map(|i| &self.values[i])
254    }
255
256    pub fn get<T: ColumnValue>(&self, column: &str) -> Result<T, DecodeError> {
257        let value = self.value(column).ok_or_else(|| {
258            DecodeError::new(column, format!("no such column on `{}`", self.table.name))
259        })?;
260        T::from_value(value.clone()).map_err(|m| DecodeError::new(column, m))
261    }
262
263    pub(crate) fn set(&mut self, column: &str, value: Value) {
264        if let Some(i) = self.table.position(column) {
265            self.values[i] = value;
266        }
267    }
268
269    /// The columns marked `returned`, as a camelCase JSON object: what clients see.
270    pub fn to_client_json(&self) -> serde_json::Map<String, serde_json::Value> {
271        self.table
272            .columns
273            .iter()
274            .zip(&self.values)
275            .filter(|(c, _)| c.returned)
276            .map(|(c, v)| (camel_case(c.name), v.to_json()))
277            .collect()
278    }
279}
280
281pub(crate) fn camel_case(snake: &str) -> String {
282    let mut out = String::with_capacity(snake.len());
283    let mut upper = false;
284    for ch in snake.chars() {
285        if ch == '_' {
286            upper = true;
287        } else if upper {
288            out.extend(ch.to_uppercase());
289            upper = false;
290        } else {
291            out.push(ch);
292        }
293    }
294    out
295}