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#[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
111pub 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 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
179pub 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 eq => "=",
215 ne => "!=",
217 lt => "<",
219 lte => "<=",
221 gt => ">",
223 gte => ">=",
225 }
226
227 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 pub fn is_null(self) -> Condition<M> {
239 Condition::json(self.column, self.key, JsonOp::Null(true), Vec::new())
240 }
241
242 pub fn is_not_null(self) -> Condition<M> {
244 Condition::json(self.column, self.key, JsonOp::Null(false), Vec::new())
245 }
246
247 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}