diff --git a/src/db.rs b/src/db.rs index 6dcb2e3..a916382 100644 --- a/src/db.rs +++ b/src/db.rs @@ -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) + } + } + } +} \ No newline at end of file diff --git a/src/db/user.rs b/src/db/user.rs index 478baad..4bd83fd 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -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 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) }