Skip to content

Commit

Permalink
[db] Add TryFrom DbElement to agdb_derive #839 (#840)
Browse files Browse the repository at this point in the history
add ability to convert from DbElement to struct
  • Loading branch information
michaelvlach authored Dec 9, 2023
1 parent a689bce commit 5ed0567
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
18 changes: 18 additions & 0 deletions agdb/tests/db_user_value_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
20 changes: 14 additions & 6 deletions agdb_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self, Self::Error> {
use agdb::DbUserValue;
#name::from_db_element(value)
}
}

impl TryFrom<agdb::QueryResult> for #name {
type Error = agdb::DbError;

fn try_from(value: agdb::QueryResult) -> Result<Self, Self::Error> {
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()
}
}
};
Expand Down

0 comments on commit 5ed0567

Please sign in to comment.