diff --git a/agdb/tests/db_user_value_test.rs b/agdb/tests/db_user_value_test.rs index ebc6e492..28eb66df 100644 --- a/agdb/tests/db_user_value_test.rs +++ b/agdb/tests/db_user_value_test.rs @@ -418,3 +418,21 @@ fn derived_macro_should_not_panic() { assert!(user.is_err()); assert_eq!(user.unwrap_err().description, "Not enough keys"); } + +#[test] +fn try_from_db_element() { + let element = DbElement { + id: DbId(1), + values: vec![ + ("user_id", 100_u64).into(), + ("password", "pswd").into(), + ("status", Status::Active).into(), + ], + }; + + let user: User = (&element).try_into().unwrap(); + + assert_eq!(user.user_id, 100); + assert_eq!(user.status, Status::Active); + assert_eq!(user.password, "pswd"); +} diff --git a/agdb_derive/src/lib.rs b/agdb_derive/src/lib.rs index 1fe29752..67291b7f 100644 --- a/agdb_derive/src/lib.rs +++ b/agdb_derive/src/lib.rs @@ -106,17 +106,25 @@ pub fn db_user_value_derive(item: TokenStream) -> TokenStream { } } + impl TryFrom<&agdb::DbElement> for #name { + type Error = agdb::DbError; + + fn try_from(value: &agdb::DbElement) -> Result { + use agdb::DbUserValue; + #name::from_db_element(value) + } + } + impl TryFrom for #name { type Error = agdb::DbError; fn try_from(value: agdb::QueryResult) -> Result { use agdb::DbUserValue; - #name::from_db_element( - value - .elements - .get(0) - .ok_or(Self::Error::from("No element found"))? - ) + value + .elements + .get(0) + .ok_or(Self::Error::from("No element found"))? + .try_into() } } };