From d5bb5089da496ad0a961ffc794f70375a5f92f64 Mon Sep 17 00:00:00 2001 From: Daniel Svitan Date: Sun, 11 May 2025 08:48:43 +0200 Subject: [PATCH] :hammer: Refactors db connection --- backend/src/db.rs | 70 ++++++++++++++++++++++++++++++++++++--------- backend/src/main.rs | 2 +- 2 files changed, 58 insertions(+), 14 deletions(-) diff --git a/backend/src/db.rs b/backend/src/db.rs index 506ad4a..73b4e30 100644 --- a/backend/src/db.rs +++ b/backend/src/db.rs @@ -6,6 +6,23 @@ pub enum ActionKind { Script, } +impl ActionKind { + fn parse(kind: String) -> Result { + match kind.to_lowercase().as_str() { + "text" => Ok(ActionKind::Text), + "script" => Ok(ActionKind::Script), + _ => Err(Error::QueryReturnedNoRows), + } + } + + fn stringify(&self) -> String { + match self { + ActionKind::Text => "text".to_string(), + ActionKind::Script => "script".to_string(), + } + } +} + #[derive(Debug)] pub struct Action { id: i32, @@ -20,20 +37,47 @@ pub struct Conn { conn: Connection, } -pub fn new_conn(db_path: &str) -> Result { - let conn = Connection::open(db_path).expect("failed to open database"); +impl Conn { + pub fn new(db_path: &str) -> Result { + let conn = Connection::open(db_path).expect("failed to open database"); - conn.execute( - "CREATE TABLE action ( - id INTEGER PRIMARY KEY, - name TEXT NOT NULL, - kind TEXT NOT NULL, - source TEXT NOT NULL, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL + conn.execute( + "CREATE TABLE action ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + kind TEXT NOT NULL, + source TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL )", - (), // empty list of parameters. - )?; + (), // empty list of parameters. + )?; - Ok(Conn { conn }) + Ok(Conn { conn }) + } + + fn action_by_id(self, id: i32) -> Result { + let mut query = self.conn.prepare("SELECT * FROM action WHERE id = ?")?; + let mut actions = query.query_map(&[&id], |row| { + Ok(Action { + id: row.get(0)?, + name: row.get(1)?, + kind: ActionKind::parse(row.get(2)?)?, + source: row.get(3)?, + created_at: row.get(4)?, + updated_at: row.get(5)?, + }) + })?; + + let action = actions.next(); + let len = actions.next().unwrap().iter().count(); + if len != 0 { + return Err(Error::InvalidQuery); + } + + if let None = action { + return Err(Error::QueryReturnedNoRows); + } + action.unwrap() + } } diff --git a/backend/src/main.rs b/backend/src/main.rs index 220e87c..f219dd6 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -14,7 +14,7 @@ async fn index() -> &'static str { fn rocket() -> _ { dotenv::dotenv().ok(); let db_path = dotenv::var("DB_PATH").expect("DB_PATH is not set"); - let db = db::new_conn(&db_path); + let db = db::Conn::new(&db_path); rocket::build().mount("/", routes![index]) }