implement macro for get and creating database objects
This commit is contained in:
parent
49d473f0cf
commit
bb479f170b
2 changed files with 27 additions and 7 deletions
25
src/db.rs
25
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue