Skip to main content

spg_sqlx/types/
json.rs

1//! v7.16.0 — `Type` / `Encode` / `Decode` for serde_json::Value
2//! against SPG's JSON / JSONB columns. Both PG types share the
3//! same text-backed storage in SPG (text round-trip on the wire).
4
5#![cfg(feature = "json")]
6
7use sqlx_core::decode::Decode;
8use sqlx_core::encode::{Encode, IsNull};
9use sqlx_core::error::BoxDynError;
10use sqlx_core::types::Type;
11
12use spg_embedded::Value as EngineValue;
13
14use crate::arguments::SpgArgumentValue;
15use crate::database::Spg;
16use crate::type_info::{Kind, SpgTypeInfo};
17use crate::value::SpgValueRef;
18
19impl Type<Spg> for serde_json::Value {
20    fn type_info() -> SpgTypeInfo {
21        SpgTypeInfo::of(Kind::Json)
22    }
23    fn compatible(ty: &SpgTypeInfo) -> bool {
24        // Accept TEXT-shaped columns too — mailrs has a few
25        // pre-D-pre-3 cells where JSON lives in TEXT.
26        matches!(ty.kind(), Kind::Json | Kind::Text)
27    }
28}
29
30impl<'q> Encode<'q, Spg> for serde_json::Value {
31    fn encode_by_ref(&self, buf: &mut Vec<SpgArgumentValue<'q>>) -> Result<IsNull, BoxDynError> {
32        let s = serde_json::to_string(self)?;
33        buf.push(SpgArgumentValue {
34            value: EngineValue::Json(s),
35            type_info: Some(<serde_json::Value as Type<Spg>>::type_info()),
36            _phantom: core::marker::PhantomData,
37        });
38        Ok(IsNull::No)
39    }
40}
41
42impl<'r> Decode<'r, Spg> for serde_json::Value {
43    fn decode(value: SpgValueRef<'r>) -> Result<Self, BoxDynError> {
44        match value.engine() {
45            EngineValue::Json(s) | EngineValue::Text(s) => {
46                serde_json::from_str(s).map_err(|e| Box::new(e) as BoxDynError)
47            }
48            other => Err(format!("cannot decode {other:?} as serde_json::Value").into()),
49        }
50    }
51}