use sqlite::{Connection, Error}; use std::sync::Arc; const DEBUG: bool = true; // @TODO pub struct Table { pub id: i64, pub time: i64, } pub struct Database { connection: Arc, } impl Database { pub fn init(connection: Arc) -> Database { // Init app table if let Err(error) = connection.execute( "CREATE TABLE IF NOT EXISTS `app` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `time` INTEGER NOT NULL DEFAULT CURRENT_TIMESTAMP )", [], ) { panic!("{error}"); // @TODO } // Return struct Self { connection } } pub fn add(&self) -> Result { return match self.connection.execute("INSERT INTO `app`", []) { Ok(total) => { if DEBUG { println!("Inserted {total} row to `app` table"); } Ok(total) } Err(error) => Err(error.to_string()), }; } pub fn records(&self) -> Result, Error> { let mut records: Vec = Vec::new(); let mut statement = self.connection.prepare("SELECT `id`, `time` FROM `app`")?; let _ = statement.query_map([], |row| { records.push(Table { id: row.get(0)?, time: row.get(1)?, }); Ok(()) }); Ok(records) } pub fn delete(&self, id: i64) -> Result { return match self .connection .execute("DELETE FROM `app` WHERE `id` = ?", [id]) { Ok(total) => { if DEBUG { println!("Deleted {total} row(s) from `app` table"); } Ok(total) } Err(error) => Err(error.to_string()), }; } pub fn last_insert_id(&self) -> i64 { self.connection.last_insert_rowid() } }