| 1 | use serde::{Deserialize, Serialize}; |
| 2 | |
| 3 | use crate::decode::Decode; |
| 4 | use crate::encode::{Encode, IsNull}; |
| 5 | use crate::error::BoxDynError; |
| 6 | use crate::protocol::text::ColumnType; |
| 7 | use crate::types::{Json, Type}; |
| 8 | use crate::{MySql, MySqlTypeInfo, MySqlValueRef}; |
| 9 | |
| 10 | impl<T> Type<MySql> for Json<T> { |
| 11 | fn type_info() -> MySqlTypeInfo { |
| 12 | // MySql uses the `CHAR` type to pass JSON data from and to the client |
| 13 | // NOTE: This is forwards-compatible with MySQL v8+ as CHAR is a common transmission format |
| 14 | // and has nothing to do with the native storage ability of MySQL v8+ |
| 15 | MySqlTypeInfo::binary(ColumnType::String) |
| 16 | } |
| 17 | |
| 18 | fn compatible(ty: &MySqlTypeInfo) -> bool { |
| 19 | ty.r#type == ColumnType::Json |
| 20 | || <&str as Type<MySql>>::compatible(ty) |
| 21 | || <&[u8] as Type<MySql>>::compatible(ty) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | impl<T> Encode<'_, MySql> for Json<T> |
| 26 | where |
| 27 | T: Serialize, |
| 28 | { |
| 29 | fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> { |
| 30 | // Encode JSON as a length-prefixed string. |
| 31 | // |
| 32 | // The previous implementation encoded into an intermediate buffer to get the final length. |
| 33 | // This is because the length prefix for the string is itself length-encoded, so we have |
| 34 | // to know the length first before we can start encoding in the buffer... or do we? |
| 35 | // |
| 36 | // The docs suggest that the integer length-encoding doesn't actually enforce a range on |
| 37 | // the value itself as long as it fits in the chosen encoding, so why not just choose |
| 38 | // the full length encoding to begin with? Then we can just reserve the space up-front |
| 39 | // and encode directly into the buffer. |
| 40 | // |
| 41 | // If someone is storing a JSON value it's likely large enough that the overhead of using |
| 42 | // the full-length integer encoding doesn't really matter. And if it's so large it overflows |
| 43 | // a `u64` then the process is likely to run OOM during the encoding process first anyway. |
| 44 | |
| 45 | let lenenc_start = buf.len(); |
| 46 | |
| 47 | buf.extend_from_slice(&[0u8; 9]); |
| 48 | |
| 49 | let encode_start = buf.len(); |
| 50 | self.encode_to(buf)?; |
| 51 | let encoded_len = (buf.len() - encode_start) as u64; |
| 52 | |
| 53 | // This prefix indicates that the following 8 bytes are a little-endian integer. |
| 54 | buf[lenenc_start] = 0xFE; |
| 55 | buf[lenenc_start + 1..][..8].copy_from_slice(&encoded_len.to_le_bytes()); |
| 56 | |
| 57 | Ok(IsNull::No) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | impl<'r, T> Decode<'r, MySql> for Json<T> |
| 62 | where |
| 63 | T: 'r + Deserialize<'r>, |
| 64 | { |
| 65 | fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> { |
| 66 | Json::decode_from_string(value.as_str()?) |
| 67 | } |
| 68 | } |