🔨 Refactors db connection

This commit is contained in:
Daniel Svitan 2025-05-11 08:48:43 +02:00
parent 05982880d3
commit d5bb5089da
2 changed files with 58 additions and 14 deletions

View File

@ -6,6 +6,23 @@ pub enum ActionKind {
Script,
}
impl ActionKind {
fn parse(kind: String) -> Result<ActionKind, Error> {
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<Conn, Error> {
let conn = Connection::open(db_path).expect("failed to open database");
impl Conn {
pub fn new(db_path: &str) -> Result<Conn, Error> {
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<Action, Error> {
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()
}
}

View File

@ -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])
}