diesel/pg/types/
uuid.rs
1use std::io::prelude::*;
2
3use crate::deserialize::{self, FromSql, FromSqlRow};
4use crate::expression::AsExpression;
5use crate::pg::{Pg, PgValue};
6use crate::serialize::{self, IsNull, Output, ToSql};
7use crate::sql_types::Uuid;
8
9#[derive(AsExpression, FromSqlRow)]
10#[diesel(foreign_derive)]
11#[diesel(sql_type = Uuid)]
12#[allow(dead_code)]
13struct UuidProxy(uuid::Uuid);
14
15#[cfg(all(feature = "postgres_backend", feature = "uuid"))]
16impl FromSql<Uuid, Pg> for uuid::Uuid {
17 fn from_sql(value: PgValue<'_>) -> deserialize::Result<Self> {
18 uuid::Uuid::from_slice(value.as_bytes()).map_err(Into::into)
19 }
20}
21
22#[cfg(all(feature = "postgres_backend", feature = "uuid"))]
23impl ToSql<Uuid, Pg> for uuid::Uuid {
24 fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
25 out.write_all(self.as_bytes())
26 .map(|_| IsNull::No)
27 .map_err(Into::into)
28 }
29}
30
31#[test]
32fn uuid_to_sql() {
33 use crate::query_builder::bind_collector::ByteWrapper;
34
35 let mut buffer = Vec::new();
36 let bytes = [
37 0xFF_u8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
38 0x31, 0x32,
39 ];
40
41 let test_uuid = uuid::Uuid::from_slice(&bytes).unwrap();
42 let mut bytes = Output::test(ByteWrapper(&mut buffer));
43 ToSql::<Uuid, Pg>::to_sql(&test_uuid, &mut bytes).unwrap();
44 assert_eq!(&buffer, test_uuid.as_bytes());
45}
46
47#[test]
48fn some_uuid_from_sql() {
49 let bytes = [
50 0xFF_u8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
51 0x31, 0x32,
52 ];
53 let input_uuid = uuid::Uuid::from_slice(&bytes).unwrap();
54 let output_uuid =
55 <uuid::Uuid as FromSql<Uuid, Pg>>::from_sql(PgValue::for_test(input_uuid.as_bytes()))
56 .unwrap();
57 assert_eq!(input_uuid, output_uuid);
58}
59
60#[test]
61fn bad_uuid_from_sql() {
62 let uuid = uuid::Uuid::from_sql(PgValue::for_test(b"boom"));
63 assert!(uuid.is_err());
64 let error_message = uuid.unwrap_err().to_string();
71 assert!(error_message.starts_with("invalid"));
72 assert!(error_message.contains("length"));
73 assert!(error_message.contains("expected 16"));
74 assert!(error_message.ends_with("found 4"));
75}
76
77#[test]
78fn no_uuid_from_sql() {
79 let uuid = uuid::Uuid::from_nullable_sql(None);
80 assert_eq!(
81 uuid.unwrap_err().to_string(),
82 "Unexpected null for non-null column"
83 );
84}