implement macro for get and creating database objects
This commit is contained in:
parent
03665f183d
commit
d0ea664ad3
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 can_download: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub mod chat;
|
||||||
|
|
||||||
#[derive(sqlx::FromRow)]
|
#[derive(sqlx::FromRow)]
|
||||||
pub struct Link {
|
pub struct Link {
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
|
|
@ -72,3 +74,26 @@ pub async fn db_init() -> SqlitePool {
|
||||||
|
|
||||||
db
|
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 teloxide::types;
|
||||||
|
|
||||||
use super::{DbPool, User};
|
use super::{DbPool, User};
|
||||||
|
use crate::unwrap_or_create;
|
||||||
|
|
||||||
pub async fn create_user(
|
pub async fn create_user(
|
||||||
db: &DbPool,
|
db: &DbPool,
|
||||||
|
|
@ -37,11 +38,5 @@ pub async fn find_or_create_user(db: &DbPool, user: &types::User) -> Result<User
|
||||||
.fetch_one(db)
|
.fetch_one(db)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
match res {
|
unwrap_or_create!(db, user, res, create_user, false, false)
|
||||||
Ok(user) => return Ok(user),
|
|
||||||
Err(e) => match e {
|
|
||||||
sqlx::Error::RowNotFound => create_user(db, user, false, false).await,
|
|
||||||
_ => Err(e),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue