69 lines
2.2 KiB
Rust
69 lines
2.2 KiB
Rust
#![allow(non_snake_case)]
|
|
use sqlx::Acquire;
|
|
use uuid::Uuid;
|
|
|
|
use sqlx::Pool;
|
|
|
|
use sqlx::Sqlite;
|
|
|
|
pub async fn get_username_by_id(id: Uuid, pool: &Pool<Sqlite>) -> Result<String, String> {
|
|
let id_str = id.to_string();
|
|
let res = sqlx::query!("SELECT name FROM users WHERE id = $1;", id_str)
|
|
.fetch_one(pool)
|
|
.await
|
|
.map_err(|_| format!("Cannot find username from {}", id))?;
|
|
Ok(res.NAME)
|
|
}
|
|
pub async fn get_uid_by_name(name: String, pool: &Pool<Sqlite>) -> Result<Uuid, String> {
|
|
let res = sqlx::query!("SELECT id FROM users WHERE name = $1;", name)
|
|
.fetch_optional(pool)
|
|
.await
|
|
.map_err(|_| format!("Cannot find Uid from {}", name))?;
|
|
match res {
|
|
Some(id) => {
|
|
Ok(Uuid::parse_str(&id.ID)
|
|
.map_err(|_| "Cannot parse uid string to uuid".to_string())?)
|
|
}
|
|
None => Err("cannot get uid from name".to_string()),
|
|
}
|
|
}
|
|
|
|
pub async fn get_user_count_by_uid(id: Uuid, pool: &Pool<Sqlite>) -> Result<i32, String> {
|
|
let id = id.to_string();
|
|
let record = sqlx::query!("SELECT COUNT(id) AS count FROM users WHERE id = $1;", id)
|
|
.fetch_one(pool)
|
|
.await
|
|
.map_err(|_| "Error in db while checking usercount")?;
|
|
return Ok(record.count);
|
|
}
|
|
|
|
/// Return rows affected and error reason
|
|
pub async fn create_user_if_non_existent(
|
|
id: Uuid,
|
|
name: String,
|
|
pool: &Pool<Sqlite>,
|
|
) -> Result<u64, String> {
|
|
let uid = id.to_string();
|
|
let mut tx = pool
|
|
.begin()
|
|
.await
|
|
.map_err(|_| "cannot start DB transaction")?;
|
|
let record = sqlx::query!("SELECT COUNT(id) AS count FROM users WHERE id = $1;", uid)
|
|
.fetch_one(&mut *tx)
|
|
.await
|
|
.map_err(|_| "Error in db while checking usercount")?;
|
|
let err_msg = "Transaction Failed".to_string();
|
|
if record.count == 0 {
|
|
let res = sqlx::query!("INSERT INTO users(id, name) VALUES($1, $2);", uid, name)
|
|
.execute(&mut *tx)
|
|
.await
|
|
.map_err(|_| "error from db when adding user".to_string())?
|
|
.rows_affected();
|
|
let _ = tx.commit().await.map_err(|_| err_msg)?;
|
|
Ok(res)
|
|
} else {
|
|
let _ = tx.rollback().await.map_err(|_| err_msg.to_string())?;
|
|
Err(err_msg)
|
|
}
|
|
}
|