Skip to main content

renox_core/db/
json.rs

1use std::ops::{Deref, DerefMut};
2
3use serde::de::DeserializeOwned;
4use serde::{Deserialize, Serialize};
5use sqlx::error::BoxDynError;
6use sqlx::sqlite::{Sqlite, SqliteTypeInfo, SqliteValueRef};
7
8use super::column::{Condition, JsonOp};
9use super::{Col, DbValue, ToDbValue};
10
11/// A model field stored as JSON: `TEXT` on SQLite, `JSONB` (or `JSON`,
12/// `TEXT`) on PostgreSQL. Serializes as the value itself, so templates and
13/// APIs see the list or object.
14///
15/// ```
16/// # use renox::prelude::*;
17/// use renox::db::Json;
18///
19/// #[derive(Model, serde::Serialize, Default)]
20/// #[model(table = "products")]
21/// struct Product {
22///     id: i64,
23///     tags: Json<Vec<String>>, // tags TEXT (SQLite) / tags JSONB (PostgreSQL)
24/// }
25///
26/// let product = Product { tags: Json(vec!["coffee".into()]), ..Default::default() };
27/// assert_eq!(product.tags.len(), 1); // derefs to the Vec
28/// ```
29#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(transparent)]
31pub struct Json<T>(pub T);
32
33impl<T> Deref for Json<T> {
34    type Target = T;
35
36    fn deref(&self) -> &T {
37        &self.0
38    }
39}
40
41impl<T> DerefMut for Json<T> {
42    fn deref_mut(&mut self) -> &mut T {
43        &mut self.0
44    }
45}
46
47impl<T> From<T> for Json<T> {
48    fn from(value: T) -> Self {
49        Json(value)
50    }
51}
52
53impl<T: Serialize> ToDbValue for Json<T> {
54    fn to_db_value(&self) -> DbValue {
55        DbValue::Json(serde_json::to_value(&self.0).unwrap_or(serde_json::Value::Null))
56    }
57}
58
59impl<T> sqlx::Type<Sqlite> for Json<T> {
60    fn type_info() -> SqliteTypeInfo {
61        <String as sqlx::Type<Sqlite>>::type_info()
62    }
63
64    fn compatible(ty: &SqliteTypeInfo) -> bool {
65        <String as sqlx::Type<Sqlite>>::compatible(ty)
66    }
67}
68
69impl<'r, T: DeserializeOwned> sqlx::Decode<'r, Sqlite> for Json<T> {
70    fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
71        let text = <String as sqlx::Decode<Sqlite>>::decode(value)?;
72        Ok(Json(serde_json::from_str(&text)?))
73    }
74}
75
76#[cfg(feature = "postgres")]
77mod postgres {
78    use serde::de::DeserializeOwned;
79    use sqlx::error::BoxDynError;
80    use sqlx::postgres::{PgTypeInfo, PgValueRef, Postgres};
81    use sqlx::{TypeInfo, ValueRef};
82
83    use super::Json;
84
85    impl<T> sqlx::Type<Postgres> for Json<T> {
86        fn type_info() -> PgTypeInfo {
87            PgTypeInfo::with_name("jsonb")
88        }
89
90        fn compatible(ty: &PgTypeInfo) -> bool {
91            matches!(ty.name(), "JSON" | "JSONB")
92                || <String as sqlx::Type<Postgres>>::compatible(ty)
93        }
94    }
95
96    impl<'r, T: DeserializeOwned> sqlx::Decode<'r, Postgres> for Json<T> {
97        fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
98            let is_json = matches!(value.type_info().name(), "JSON" | "JSONB");
99            if is_json {
100                let sqlx::types::Json(inner) =
101                    <sqlx::types::Json<T> as sqlx::Decode<Postgres>>::decode(value)?;
102                Ok(Json(inner))
103            } else {
104                let text = <String as sqlx::Decode<Postgres>>::decode(value)?;
105                Ok(Json(serde_json::from_str(&text)?))
106            }
107        }
108    }
109}
110
111/// The `CREATE INDEX` statement that speeds up filters and sorting on one key of
112/// a JSON column ([`Col::json`]), in the SQL of `dialect`: an expression
113/// index on `json_extract(column, '$.key')` (SQLite) or
114/// `(column::jsonb ->> 'key')` (PostgreSQL), the expressions the query builder
115/// writes. Run it from a migration; nothing creates it for you.
116///
117/// `table` and `column` must be plain identifiers and `key` must match
118/// `[a-z][a-z0-9_]*`, else an error is returned.
119///
120/// ```
121/// use renox::db::{Dialect, json_index};
122///
123/// let sql = json_index(Dialect::Sqlite, "parties", "extra", "segment").unwrap();
124/// assert!(sql.contains("json_extract(\"extra\", '$.segment')"));
125/// assert!(json_index(Dialect::Postgres, "parties", "extra", "a'b").is_err());
126/// ```
127pub fn json_index(
128    dialect: super::Dialect,
129    table: &str,
130    column: &str,
131    key: &str,
132) -> crate::Result<String> {
133    let plain = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
134    if !plain(table) || !plain(column) || !crate::custom_fields::is_valid_key(key) {
135        return Err(crate::Error::BadRequest(format!(
136            "cannot index `{table}.{column}` key `{}`",
137            key.escape_debug()
138        )));
139    }
140    let expr = match dialect {
141        super::Dialect::Sqlite => format!("json_extract(\"{column}\", '$.{key}')"),
142        super::Dialect::Postgres => format!("((\"{column}\"::jsonb ->> '{key}'))"),
143    };
144    Ok(format!(
145        "CREATE INDEX IF NOT EXISTS \"idx_{table}_{column}_{key}\" ON \"{table}\" ({expr})"
146    ))
147}
148
149impl<M, T> Col<M, Json<T>> {
150    /// One key of the JSON object stored in this column, to filter or sort by.
151    ///
152    /// The SQL is `json_extract(column, '$.key')` on SQLite and
153    /// `column ->> 'key'` on PostgreSQL; values are always bound. A key that
154    /// does not match `[a-z][a-z0-9_]*` makes the query return an error and
155    /// is never put into SQL. Call
156    /// [`Query::with_custom_fields`](super::Query::with_custom_fields) to check
157    /// the key against the model's custom field definitions and to compare
158    /// numbers and booleans with the right type on PostgreSQL.
159    ///
160    /// ```
161    /// use renox::db::{Col, Json};
162    /// use renox::custom_fields::CustomValues;
163    ///
164    /// struct Party;
165    /// const EXTRA: Col<Party, Json<CustomValues>> = Col::new("extra");
166    ///
167    /// let retail = EXTRA.json("segment").eq("retail");
168    /// # let _ = retail;
169    /// ```
170    pub fn json(self, key: &str) -> JsonPath<M> {
171        JsonPath {
172            column: self.name(),
173            key: key.to_owned(),
174            _p: std::marker::PhantomData,
175        }
176    }
177}
178
179/// One key of a JSON column of the model `M`, made by [`Col::json`].
180pub struct JsonPath<M> {
181    pub(super) column: &'static str,
182    pub(super) key: String,
183    _p: std::marker::PhantomData<fn() -> M>,
184}
185
186impl<M> std::fmt::Debug for JsonPath<M> {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        f.debug_tuple("JsonPath")
189            .field(&self.column)
190            .field(&self.key)
191            .finish()
192    }
193}
194
195macro_rules! json_comparison {
196    ($($(#[$doc:meta])* $method:ident => $op:literal),* $(,)?) => {
197        $(
198            $(#[$doc])*
199            pub fn $method(self, value: impl ToDbValue) -> Condition<M> {
200                Condition::json(
201                    self.column,
202                    self.key,
203                    JsonOp::Cmp($op),
204                    vec![value.to_db_value()],
205                )
206            }
207        )*
208    };
209}
210
211impl<M> JsonPath<M> {
212    json_comparison! {
213        /// `key = value`.
214        eq => "=",
215        /// `key != value`.
216        ne => "!=",
217        /// `key < value`.
218        lt => "<",
219        /// `key <= value`.
220        lte => "<=",
221        /// `key > value`.
222        gt => ">",
223        /// `key >= value`.
224        gte => ">=",
225    }
226
227    /// `key LIKE pattern`, ignoring ASCII case on both databases.
228    pub fn like(self, pattern: &str) -> Condition<M> {
229        Condition::json(
230            self.column,
231            self.key,
232            JsonOp::Cmp("like"),
233            vec![pattern.to_db_value()],
234        )
235    }
236
237    /// The key is missing or `null`.
238    pub fn is_null(self) -> Condition<M> {
239        Condition::json(self.column, self.key, JsonOp::Null(true), Vec::new())
240    }
241
242    /// The key holds a value.
243    pub fn is_not_null(self) -> Condition<M> {
244        Condition::json(self.column, self.key, JsonOp::Null(false), Vec::new())
245    }
246
247    /// `key IN (...)`; an empty list matches no rows.
248    pub fn is_in<V: ToDbValue>(self, values: impl IntoIterator<Item = V>) -> Condition<M> {
249        let values = values.into_iter().map(|v| v.to_db_value()).collect();
250        Condition::json(self.column, self.key, JsonOp::In, values)
251    }
252}