Skip to content

Commit c091f29

Browse files
bheylinBrian
andauthored
Impl FromSql and ToSql for serde_json::RawValue (#35)
Co-authored-by: Brian <brianheylin@dreamsolution.nl>
1 parent 0e6896c commit c091f29

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

postgres-types/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ eui48-1 = { version = "1.0", package = "eui48", optional = true, default-feature
4646
geo-types-06 = { version = "0.6", package = "geo-types", optional = true }
4747
geo-types-0_7 = { version = "0.7", package = "geo-types", optional = true }
4848
serde-1 = { version = "1.0", package = "serde", optional = true }
49-
serde_json-1 = { version = "1.0", package = "serde_json", optional = true }
49+
serde_json-1 = { version = "1.0", package = "serde_json", optional = true, features = ["raw_value"]}
5050
uuid-08 = { version = "0.8", package = "uuid", optional = true }
5151
uuid-1 = { version = "1.0", package = "uuid", optional = true }
5252
time-02 = { version = "0.2", package = "time", optional = true }

postgres-types/src/serde_json_1.rs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::{FromSql, IsNull, ToSql, Type};
22
use bytes::{BufMut, BytesMut};
33
use serde_1::{Deserialize, Serialize};
4-
use serde_json_1::Value;
4+
use serde_json_1::{value::RawValue, Value};
55
use std::error::Error;
66
use std::fmt::Debug;
77
use std::io::Read;
@@ -71,3 +71,45 @@ impl ToSql for Value {
7171
accepts!(JSON, JSONB);
7272
to_sql_checked!();
7373
}
74+
75+
impl<'a> FromSql<'a> for &'a RawValue {
76+
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<&'a RawValue, Box<dyn Error + Sync + Send>> {
77+
Json::<&'a RawValue>::from_sql(ty, raw).map(|json| json.0)
78+
}
79+
80+
accepts!(JSON, JSONB);
81+
}
82+
83+
impl<'a> ToSql for &'a RawValue {
84+
fn to_sql(
85+
&self,
86+
ty: &Type,
87+
out: &mut BytesMut,
88+
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
89+
Json(self).to_sql(ty, out)
90+
}
91+
92+
accepts!(JSON, JSONB);
93+
to_sql_checked!();
94+
}
95+
96+
impl<'a> FromSql<'a> for Box<RawValue> {
97+
fn from_sql(ty: &Type, raw: &[u8]) -> Result<Box<RawValue>, Box<dyn Error + Sync + Send>> {
98+
Json::<Box<RawValue>>::from_sql(ty, raw).map(|json| json.0)
99+
}
100+
101+
accepts!(JSON, JSONB);
102+
}
103+
104+
impl ToSql for Box<RawValue> {
105+
fn to_sql(
106+
&self,
107+
ty: &Type,
108+
out: &mut BytesMut,
109+
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
110+
Json(self).to_sql(ty, out)
111+
}
112+
113+
accepts!(JSON, JSONB);
114+
to_sql_checked!();
115+
}

0 commit comments

Comments
 (0)