diff --git a/src/constants.rs b/src/constants.rs index 92e0d57..71e7f62 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -14,6 +14,9 @@ pub mod database_tables_names { /// User table pub const USERS_TABLE: &str = "utilisateurs"; + + /// Friends table + pub const FRIENDS_TABLE: &str = "amis"; } /// The account image to show for user who do not have any diff --git a/src/helpers/database.rs b/src/helpers/database.rs index 62318f3..8e823be 100644 --- a/src/helpers/database.rs +++ b/src/helpers/database.rs @@ -136,6 +136,17 @@ impl<'a> RowResult<'a> { } } + /// Find an integer included in the request + pub fn get_usize(&self, name: &str) -> Result> { + let value = self.row.get_opt(self.find_col(name)?); + + match value { + None => Err(ExecError::boxed_string( + format!("Could not extract integer field {} !", name))), + Some(s) => Ok(s?) + } + } + /// Find a string included in the request pub fn get_str(&self, name: &str) -> Result> { let value = self.row.get_opt(self.find_col(name)?); @@ -245,6 +256,15 @@ pub fn query ProcessRowResult>(info: QueryInfo, proce Ok(res) } +/// Count the number of results a query would have produced +pub fn count(mut q: QueryInfo) -> ResultBoxError { + &q.fields.clear(); + &q.fields.push("COUNT(*) as count".to_string()); + + query(q, |res| res.get_usize("count"))?.pop() + .ok_or(ExecError::boxed_new("database::count did not return a result!")) +} + /// Structure used to execute a insert query pub struct InsertQuery { pub table: String, diff --git a/src/helpers/friends_helper.rs b/src/helpers/friends_helper.rs new file mode 100644 index 0000000..706f875 --- /dev/null +++ b/src/helpers/friends_helper.rs @@ -0,0 +1,18 @@ +//! # Friends helper +//! +//! @author Pierre Hubert + + +use crate::data::user::UserID; +use crate::data::error::ResultBoxError; +use crate::helpers::database; +use crate::constants::database_tables_names::FRIENDS_TABLE; +use crate::helpers::database::QueryInfo; + +/// Check out whether two users are friend or not +pub fn are_friend(user_one: UserID, user_two: UserID) -> ResultBoxError { + Ok(database::count(QueryInfo::new(FRIENDS_TABLE) + .cond_i64("ID_personne", user_one) + .cond_i64("ID_amis", user_two) + .cond_i64("actif", 1))? > 0) +} \ No newline at end of file diff --git a/src/helpers/mod.rs b/src/helpers/mod.rs index c05dac7..f65b104 100644 --- a/src/helpers/mod.rs +++ b/src/helpers/mod.rs @@ -2,4 +2,5 @@ pub mod database; pub mod api_helper; pub mod account_helper; -pub mod user_helper; \ No newline at end of file +pub mod user_helper; +pub mod friends_helper; \ No newline at end of file