feat: abstract db ops

This commit is contained in:
Aravinth Manivannan 2023-08-04 11:27:20 +05:30
parent b4c24182ee
commit 756ddf8093
Signed by: realaravinth
GPG key ID: AD9F0F08E855ED88

34
src/db.rs Normal file
View file

@ -0,0 +1,34 @@
use std::time::Duration;
use sqlx::postgres::{PgPool, PgPoolOptions};
use url::Url;
pub struct DB {
pool: PgPool,
}
impl DB {
pub async fn new(url: &Url, conn: u32) -> Self {
let pool = PgPoolOptions::new()
.max_connections(conn)
.acquire_timeout(Duration::new(1000, 0))
.idle_timeout(Duration::new(1000, 0))
.connect(&url.to_string())
.await
.unwrap();
sqlx::migrate!("./migrations/").run(&pool).await.unwrap();
Self { pool }
}
pub async fn write_log(&self, log: &crate::Log, difficulty: u32) {
let time = log.time as i32;
sqlx::query!(
"INSERT INTO logs (string, salt, time, difficulty) VALUES ($1, $2, $3, $4) ON CONFLICT(difficulty) DO NOTHING;",
log.string,
log.salt,
time,
difficulty as i32,
).execute(&self.pool).await.unwrap();
}
}