Yoda/src/app/database.rs

79 lines
2.0 KiB
Rust
Raw Normal View History

2024-10-04 02:22:37 +03:00
use sqlite::{Connection, Error};
2024-10-02 15:22:50 +03:00
use std::sync::Arc;
2024-10-03 00:31:41 +03:00
const DEBUG: bool = true; // @TODO
2024-10-04 02:22:37 +03:00
pub struct Table {
pub id: i64,
pub time: i64,
2024-10-02 20:02:48 +03:00
}
2024-10-02 15:22:50 +03:00
pub struct Database {
2024-10-03 00:31:41 +03:00
connection: Arc<Connection>,
2024-10-02 15:22:50 +03:00
}
impl Database {
pub fn init(connection: Arc<Connection>) -> 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
)",
[],
) {
2024-10-03 00:31:41 +03:00
panic!("{error}"); // @TODO
}
2024-10-02 15:22:50 +03:00
// Return struct
Self { connection }
2024-10-02 15:22:50 +03:00
}
2024-10-03 00:31:41 +03:00
pub fn add(&self) -> Result<usize, String> {
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()),
};
}
2024-10-04 02:22:37 +03:00
pub fn records(&self) -> Result<Vec<Table>, Error> {
let mut records: Vec<Table> = 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<usize, String> {
return match self
.connection
.execute("DELETE FROM `app` WHERE `id` = ?", [id])
{
2024-10-03 00:31:41 +03:00
Ok(total) => {
if DEBUG {
2024-10-04 02:22:37 +03:00
println!("Deleted {total} row(s) from `app` table");
2024-10-03 00:31:41 +03:00
}
Ok(total)
}
Err(error) => Err(error.to_string()),
};
}
2024-10-02 15:22:50 +03:00
2024-10-03 00:31:41 +03:00
pub fn last_insert_id(&self) -> i64 {
self.connection.last_insert_rowid()
2024-10-02 15:22:50 +03:00
}
}