diesel/mysql_like/types/
json.rs1use crate::deserialize::{self, FromSql};
2use crate::mysql_like::{MysqlLikeBackend, MysqlValue};
3use crate::serialize::{self, IsNull, Output, ToSql};
4use crate::sql_types;
5
6#[cfg(feature = "serde_json")]
7impl<DB: MysqlLikeBackend> FromSql<sql_types::Json, DB> for serde_json::Value {
8 fn from_sql(value: MysqlValue<'_>) -> deserialize::Result<Self> {
9 serde_json::from_slice(value.as_bytes()).map_err(|_| "Invalid Json".into())
10 }
11}
12
13#[cfg(feature = "serde_json")]
14impl<DB: MysqlLikeBackend> ToSql<sql_types::Json, DB> for serde_json::Value {
15 fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
16 serde_json::to_writer(out, self)
17 .map(|_| IsNull::No)
18 .map_err(Into::into)
19 }
20}
21
22#[cfg(all(test, feature = "mysql"))]
23mod tests {
24 use super::*;
25 use crate::mysql::Mysql;
26 #[diesel_test_helper::test]
27 fn json_to_sql() {
28 use crate::query_builder::bind_collector::ByteWrapper;
29
30 let mut buffer = Vec::new();
31 let mut bytes = Output::test(ByteWrapper(&mut buffer));
32 let test_json = serde_json::Value::Bool(true);
33 ToSql::<sql_types::Json, Mysql>::to_sql(&test_json, &mut bytes).unwrap();
34 assert_eq!(buffer, b"true");
35 }
36
37 #[diesel_test_helper::test]
38 fn some_json_from_sql() {
39 use crate::mysql::MysqlType;
40 let input_json = b"true";
41 let output_json: serde_json::Value = FromSql::<sql_types::Json, Mysql>::from_sql(
42 MysqlValue::new_internal(input_json, MysqlType::String),
43 )
44 .unwrap();
45 assert_eq!(output_json, serde_json::Value::Bool(true));
46 }
47
48 #[diesel_test_helper::test]
49 fn bad_json_from_sql() {
50 use crate::mysql::MysqlType;
51 let uuid: Result<serde_json::Value, _> = FromSql::<sql_types::Json, Mysql>::from_sql(
52 MysqlValue::new_internal(b"boom", MysqlType::String),
53 );
54 assert_eq!(uuid.unwrap_err().to_string(), "Invalid Json");
55 }
56
57 #[diesel_test_helper::test]
58 fn no_json_from_sql() {
59 let uuid: Result<serde_json::Value, _> =
60 FromSql::<sql_types::Json, Mysql>::from_nullable_sql(None);
61 assert_eq!(
62 uuid.unwrap_err().to_string(),
63 "Unexpected null for non-null column"
64 );
65 }
66}