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(); + } +}