sqlx_mysql/types/
str.rs

1use std::borrow::Cow;
2use std::rc::Rc;
3use std::sync::Arc;
4
5use crate::collation::Collation;
6use crate::decode::Decode;
7use crate::encode::{Encode, IsNull};
8use crate::error::BoxDynError;
9use crate::io::MySqlBufMutExt;
10use crate::protocol::text::{ColumnFlags, ColumnType};
11use crate::types::Type;
12use crate::{MySql, MySqlTypeInfo, MySqlValueRef};
13
14impl Type<MySql> for str {
15    fn type_info() -> MySqlTypeInfo {
16        MySqlTypeInfo {
17            r#type: ColumnType::VarString, // VARCHAR
18            flags: ColumnFlags::empty(),
19            // Doesn't matter because we never send this.
20            collation: Collation::UTF8MB4_GENERAL_CI,
21            max_size: None,
22        }
23    }
24
25    fn compatible(ty: &MySqlTypeInfo) -> bool {
26        // TODO: Support more collations being returned from SQL?
27        matches!(
28            ty.r#type,
29            ColumnType::VarChar
30                | ColumnType::Blob
31                | ColumnType::TinyBlob
32                | ColumnType::MediumBlob
33                | ColumnType::LongBlob
34                | ColumnType::String
35                | ColumnType::VarString
36                | ColumnType::Enum
37        )
38            // Any collation that *isn't* `binary` generally indicates string data.
39            // The actual collation used for storage doesn't matter, 
40            // because the server will transcode to the charset we specify.
41            //
42            // See comment in `src/collation.rs` for details.
43            && ty.collation != Collation::BINARY
44    }
45}
46
47impl Encode<'_, MySql> for &'_ str {
48    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
49        buf.put_str_lenenc(self);
50
51        Ok(IsNull::No)
52    }
53}
54
55impl<'r> Decode<'r, MySql> for &'r str {
56    fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
57        value.as_str()
58    }
59}
60
61impl Type<MySql> for String {
62    fn type_info() -> MySqlTypeInfo {
63        <str as Type<MySql>>::type_info()
64    }
65
66    fn compatible(ty: &MySqlTypeInfo) -> bool {
67        <str as Type<MySql>>::compatible(ty)
68    }
69}
70
71impl Decode<'_, MySql> for String {
72    fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
73        <&str as Decode<MySql>>::decode(value).map(ToOwned::to_owned)
74    }
75}
76
77forward_encode_impl!(Arc<str>, &str, MySql);
78forward_encode_impl!(Rc<str>, &str, MySql);
79forward_encode_impl!(Cow<'_, str>, &str, MySql);
80forward_encode_impl!(Box<str>, &str, MySql);
81forward_encode_impl!(String, &str, MySql);