Debian Codegraph @

src/types/uuid.rs

raw symbols SCIP
1 use uuid::{
2 fmt::{Hyphenated, Simple},
3 Uuid,
4 };
5
6 use crate::decode::Decode;
7 use crate::encode::{Encode, IsNull};
8 use crate::error::BoxDynError;
9 use crate::io::MySqlBufMutExt;
10 use crate::types::Type;
11 use crate::{MySql, MySqlTypeInfo, MySqlValueRef};
12
13 impl Type<MySql> for Uuid {
14 fn type_info() -> MySqlTypeInfo {
15 <&[u8] as Type<MySql>>::type_info()
16 }
17
18 fn compatible(ty: &MySqlTypeInfo) -> bool {
19 <&[u8] as Type<MySql>>::compatible(ty)
20 }
21 }
22
23 impl Encode<'_, MySql> for Uuid {
24 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
25 buf.put_bytes_lenenc(self.as_bytes());
26
27 Ok(IsNull::No)
28 }
29 }
30
31 impl Decode<'_, MySql> for Uuid {
32 fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
33 // delegate to the &[u8] type to decode from MySQL
34 let bytes = <&[u8] as Decode<MySql>>::decode(value)?;
35
36 if bytes.len() != 16 {
37 return Err(format!(
38 "Expected 16 bytes, got {}; `Uuid` uses binary format for MySQL/MariaDB. \
39 For text-formatted UUIDs, use `uuid::fmt::Hyphenated` instead of `Uuid`.",
40 bytes.len(),
41 )
42 .into());
43 }
44
45 // construct a Uuid from the returned bytes
46 Uuid::from_slice(bytes).map_err(Into::into)
47 }
48 }
49
50 impl Type<MySql> for Hyphenated {
51 fn type_info() -> MySqlTypeInfo {
52 <&str as Type<MySql>>::type_info()
53 }
54
55 fn compatible(ty: &MySqlTypeInfo) -> bool {
56 <&str as Type<MySql>>::compatible(ty)
57 }
58 }
59
60 impl Encode<'_, MySql> for Hyphenated {
61 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
62 buf.put_str_lenenc(&self.to_string());
63
64 Ok(IsNull::No)
65 }
66 }
67
68 impl Decode<'_, MySql> for Hyphenated {
69 fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
70 // delegate to the &str type to decode from MySQL
71 let text = <&str as Decode<MySql>>::decode(value)?;
72
73 // parse a UUID from the text
74 Uuid::parse_str(text)
75 .map_err(Into::into)
76 .map(|u| u.hyphenated())
77 }
78 }
79
80 impl Type<MySql> for Simple {
81 fn type_info() -> MySqlTypeInfo {
82 <&str as Type<MySql>>::type_info()
83 }
84
85 fn compatible(ty: &MySqlTypeInfo) -> bool {
86 <&str as Type<MySql>>::compatible(ty)
87 }
88 }
89
90 impl Encode<'_, MySql> for Simple {
91 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
92 buf.put_str_lenenc(&self.to_string());
93
94 Ok(IsNull::No)
95 }
96 }
97
98 impl Decode<'_, MySql> for Simple {
99 fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
100 // delegate to the &str type to decode from MySQL
101 let text = <&str as Decode<MySql>>::decode(value)?;
102
103 // parse a UUID from the text
104 Uuid::parse_str(text)
105 .map_err(Into::into)
106 .map(|u| u.simple())
107 }
108 }