From 756ddf80932719bfec18e703b1bcd9aa042d7844 Mon Sep 17 00:00:00 2001 From: Aravinth Manivannan Date: Fri, 4 Aug 2023 11:27:20 +0530 Subject: [PATCH] feat: abstract db ops --- src/db.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/db.rs diff --git a/src/db.rs b/src/db.rs new file mode 100644 index 0000000..e96c9aa --- /dev/null +++ b/src/db.rs @@ -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(); + } +}