feat : GistDatabase is Clone and add ping to GistDatabase

master
Aravinth Manivannan 2022-02-12 23:47:08 +05:30
parent 28bbdaebad
commit f67a0038cf
4 changed files with 56 additions and 2 deletions

View File

@ -93,7 +93,7 @@ pub struct UpdateUsernamePayload<'a> {
use dev::*;
/// foo
#[async_trait]
pub trait GistDatabase: std::marker::Send + std::marker::Sync {
pub trait GistDatabase: std::marker::Send + std::marker::Sync + CloneGistDatabase {
/// Update email of specified user in database
async fn update_email(&self, payload: &UpdateEmailPayload) -> DBResult<()>;
/// Update password of specified user in database
@ -118,10 +118,13 @@ pub trait GistDatabase: std::marker::Send + std::marker::Sync {
async fn email_register(&self, payload: &EmailRegisterPayload) -> DBResult<()>;
/// register with username
async fn username_register(&self, payload: &UsernameRegisterPayload) -> DBResult<()>;
/// ping DB
async fn ping(&self) -> bool;
}
#[async_trait]
impl<T: GistDatabase + ?Sized> GistDatabase for Box<T> {
impl GistDatabase for Box<dyn GistDatabase> {
async fn update_email(&self, payload: &UpdateEmailPayload) -> DBResult<()> {
(**self).update_email(payload).await
}
@ -169,4 +172,30 @@ impl<T: GistDatabase + ?Sized> GistDatabase for Box<T> {
async fn username_register(&self, payload: &UsernameRegisterPayload) -> DBResult<()> {
(**self).username_register(payload).await
}
/// ping DB
async fn ping(&self) -> bool {
(**self).ping().await
}
}
/// Trait to clone GistDatabase
pub trait CloneGistDatabase {
/// clone DB
fn clone_db<'a>(&self) -> Box<dyn GistDatabase>;
}
impl<T> CloneGistDatabase for T
where
T: GistDatabase + Clone + 'static,
{
fn clone_db(&self) -> Box<dyn GistDatabase> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn GistDatabase> {
fn clone(&self) -> Self {
(**self).clone_db()
}
}

View File

@ -14,6 +14,7 @@ pub mod tests;
/// Database pool. All database functionallity(`libadmin` traits) are implemented on this
/// data structure
#[derive(Clone)]
pub struct Database {
/// database pool
pub pool: PgPool,
@ -269,4 +270,15 @@ impl GistDatabase for Database {
Ok(secret.secret)
}
/// ping DB
async fn ping(&self) -> bool {
use sqlx::Connection;
if let Ok(mut con) = self.pool.acquire().await {
con.ping().await.is_ok()
} else {
false
}
}
}

View File

@ -7,6 +7,7 @@ pub fn map_register_err(e: Error) -> DBError {
if let Error::Database(err) = e {
if err.code() == Some(Cow::from("2067")) {
let msg = err.message();
println!("{}", msg);
if msg.contains("admin_users.username") {
DBError::DuplicateUsername
} else if msg.contains("admin_users.email") {

View File

@ -7,6 +7,7 @@ pub mod errors;
#[cfg(test)]
pub mod tests;
#[derive(Clone)]
pub struct Database {
pub pool: SqlitePool,
}
@ -238,4 +239,15 @@ impl GistDatabase for Database {
Ok(secret.secret)
}
/// ping DB
async fn ping(&self) -> bool {
use sqlx::Connection;
if let Ok(mut con) = self.pool.acquire().await {
con.ping().await.is_ok()
} else {
false
}
}
}