implement macro for get and creating database objects

This commit is contained in:
mykola2312 2024-03-03 00:44:38 +02:00
parent 03665f183d
commit d0ea664ad3
2 changed files with 27 additions and 7 deletions

View file

@ -41,6 +41,8 @@ pub struct Chat {
pub can_download: i64,
}
pub mod chat;
#[derive(sqlx::FromRow)]
pub struct Link {
pub id: i64,
@ -72,3 +74,26 @@ pub async fn db_init() -> SqlitePool {
db
}
#[macro_export]
macro_rules! unwrap_or_create {
($db:expr, $tg:expr, $res:expr, $create:expr) => {
match $res {
Ok(obj) => return Ok(obj),
Err(e) => match e {
sqlx::Error::RowNotFound => $create($db, $tg).await,
_ => Err(e)
}
}
};
($db:expr, $tg:expr, $res:expr, $create: expr $(, $args: expr)*) => {
match $res {
Ok(obj) => return Ok(obj),
Err(e) => match e {
sqlx::Error::RowNotFound => $create($db, $tg $(,$args)*).await,
_ => Err(e)
}
}
}
}

View file

@ -1,6 +1,7 @@
use teloxide::types;
use super::{DbPool, User};
use crate::unwrap_or_create;
pub async fn create_user(
db: &DbPool,
@ -37,11 +38,5 @@ pub async fn find_or_create_user(db: &DbPool, user: &types::User) -> Result<User
.fetch_one(db)
.await;
match res {
Ok(user) => return Ok(user),
Err(e) => match e {
sqlx::Error::RowNotFound => create_user(db, user, false, false).await,
_ => Err(e),
},
}
unwrap_or_create!(db, user, res, create_user, false, false)
}