diff --git a/diesel/Cargo.toml b/diesel/Cargo.toml index 61389bec0810..1010abea9b40 100644 --- a/diesel/Cargo.toml +++ b/diesel/Cargo.toml @@ -34,6 +34,7 @@ bitflags = { version = "2.0.0", optional = true } r2d2 = { version = ">= 0.8.2, < 0.9.0", optional = true } itoa = { version = "1.0.0", optional = true } time = { version = "0.3.9", optional = true, features = ["macros"] } +macaddr = { version = "1.0.1", optional = true } [dependencies.diesel_derives] version = "~2.0.0" @@ -47,7 +48,7 @@ quickcheck = "1.0.3" [features] default = ["with-deprecated", "32-column-tables"] -extras = ["chrono", "time", "serde_json", "uuid", "network-address", "numeric", "r2d2"] +extras = ["chrono", "time", "serde_json", "uuid", "network-address", "numeric", "r2d2", "macaddr"] unstable = ["diesel_derives/nightly"] large-tables = ["32-column-tables"] huge-tables = ["64-column-tables"] diff --git a/diesel/src/pg/types/mac_addr.rs b/diesel/src/pg/types/mac_addr.rs index f28a84853492..4c17eb5d0672 100644 --- a/diesel/src/pg/types/mac_addr.rs +++ b/diesel/src/pg/types/mac_addr.rs @@ -37,6 +37,21 @@ impl ToSql for [u8; 6] { } } +#[cfg(all(feature = "macaddr", feature = "postgres_backend"))] +impl FromSql for macaddr::MacAddr6 { + fn from_sql(value: PgValue<'_>) -> deserialize::Result { + <[u8; 6] as FromSql>::from_sql(value).map(Into::into) + } +} + +#[cfg(all(feature = "macaddr", feature = "postgres_backend"))] +impl ToSql for macaddr::MacAddr6 { + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result { + let array_value = self.into_array(); + <[u8; 6] as ToSql>::to_sql(&array_value, &mut out.reborrow()) + } +} + #[test] fn macaddr_roundtrip() { use crate::query_builder::bind_collector::ByteWrapper; @@ -45,6 +60,16 @@ fn macaddr_roundtrip() { let mut bytes = Output::test(ByteWrapper(&mut buffer)); let input_address = [0x52, 0x54, 0x00, 0xfb, 0xc6, 0x16]; ToSql::::to_sql(&input_address, &mut bytes).unwrap(); + let output_address: [u8; 6] = FromSql::from_sql(PgValue::for_test(&buffer)).unwrap(); assert_eq!(input_address, output_address); + + #[cfg(feature = "macaddr")] + { + use macaddr::MacAddr6; + + let input_address: MacAddr6 = input_address.into(); + let output_address: MacAddr6 = FromSql::from_sql(PgValue::for_test(&buffer)).unwrap(); + assert_eq!(input_address, output_address); + } } diff --git a/diesel_tests/tests/types.rs b/diesel_tests/tests/types.rs index a661b0d36d1b..26ce762de657 100644 --- a/diesel_tests/tests/types.rs +++ b/diesel_tests/tests/types.rs @@ -1048,6 +1048,12 @@ fn pg_macaddress_from_sql() { expected_value, query_single_value::(query) ); + + #[cfg(feature = "macaddr")] + assert_eq!( + expected_value, + query_single_value::(query) + ); } #[test] @@ -1059,6 +1065,14 @@ fn pg_macaddress_to_sql_macaddress() { expected_value, value )); + + #[cfg(feature = "macaddr")] + { + assert!(query_to_sql_equality::( + expected_value, + macaddr::MacAddr6::new(0x08, 0x00, 0x2b, 0x01, 0x02, 0x03) + )); + } } #[test]