2024-10-02 18:46:08 +03:00
|
|
|
use sqlite::Connection;
|
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-02 23:28:57 +03:00
|
|
|
enum Table {
|
2024-10-02 20:02:48 +03:00
|
|
|
Id,
|
|
|
|
Time,
|
|
|
|
}
|
|
|
|
|
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 {
|
2024-10-02 18:46:08 +03:00
|
|
|
pub fn init(connection: Arc<Connection>) -> Database {
|
2024-10-02 17:25:20 +03:00
|
|
|
// Init app table
|
2024-10-02 18:46:08 +03:00
|
|
|
if let Err(error) = connection.execute(
|
2024-10-02 20:00:08 +03:00
|
|
|
"CREATE TABLE IF NOT EXISTS `app`
|
|
|
|
(
|
|
|
|
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
|
|
`time` INTEGER NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
|
|
)",
|
|
|
|
[],
|
2024-10-02 17:25:20 +03:00
|
|
|
) {
|
2024-10-03 00:31:41 +03:00
|
|
|
panic!("{error}"); // @TODO
|
2024-10-02 17:25:20 +03:00
|
|
|
}
|
2024-10-02 15:22:50 +03:00
|
|
|
|
|
|
|
// Return struct
|
2024-10-02 17:25:20 +03:00
|
|
|
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()),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn clean(&self) -> Result<usize, String> {
|
|
|
|
return match self.connection.execute("DELETE FROM `app`", []) {
|
|
|
|
Ok(total) => {
|
|
|
|
if DEBUG {
|
|
|
|
println!("Deleted {total} rows from `app` table");
|
|
|
|
}
|
|
|
|
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 {
|
2024-10-02 20:00:08 +03:00
|
|
|
self.connection.last_insert_rowid()
|
2024-10-02 15:22:50 +03:00
|
|
|
}
|
|
|
|
}
|