postgres_types/
serde_json_1.rs

1use crate::{FromSql, IsNull, ToSql, Type};
2use bytes::{BufMut, BytesMut};
3use serde_1::{Deserialize, Serialize};
4use serde_json_1::Value;
5use std::error::Error;
6use std::fmt::Debug;
7use std::io::Read;
8
9/// A wrapper type to allow arbitrary `Serialize`/`Deserialize` types to convert to Postgres JSON values.
10#[derive(Clone, Default, Debug, PartialEq, Eq)]
11pub struct Json<T>(pub T);
12
13impl<'a, T> FromSql<'a> for Json<T>
14where
15    T: Deserialize<'a>,
16{
17    fn from_sql(ty: &Type, mut raw: &'a [u8]) -> Result<Json<T>, Box<dyn Error + Sync + Send>> {
18        if *ty == Type::JSONB {
19            let mut b = [0; 1];
20            raw.read_exact(&mut b)?;
21            // We only support version 1 of the jsonb binary format
22            if b[0] != 1 {
23                return Err("unsupported JSONB encoding version".into());
24            }
25        }
26        serde_json_1::de::from_slice(raw)
27            .map(Json)
28            .map_err(Into::into)
29    }
30
31    accepts!(JSON, JSONB);
32}
33
34impl<T> ToSql for Json<T>
35where
36    T: Serialize + Debug,
37{
38    fn to_sql(
39        &self,
40        ty: &Type,
41        out: &mut BytesMut,
42    ) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
43        if *ty == Type::JSONB {
44            out.put_u8(1);
45        }
46        serde_json_1::ser::to_writer(out.writer(), &self.0)?;
47        Ok(IsNull::No)
48    }
49
50    accepts!(JSON, JSONB);
51    to_sql_checked!();
52}
53
54impl<'a> FromSql<'a> for Value {
55    fn from_sql(ty: &Type, raw: &[u8]) -> Result<Value, Box<dyn Error + Sync + Send>> {
56        Json::<Value>::from_sql(ty, raw).map(|json| json.0)
57    }
58
59    accepts!(JSON, JSONB);
60}
61
62impl ToSql for Value {
63    fn to_sql(
64        &self,
65        ty: &Type,
66        out: &mut BytesMut,
67    ) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
68        Json(self).to_sql(ty, out)
69    }
70
71    accepts!(JSON, JSONB);
72    to_sql_checked!();
73}