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