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-04 02:22:37 +03:00
|
|
|
pub struct Table {
|
|
|
|
pub id: i64,
|
2024-10-04 19:23:00 +03:00
|
|
|
// 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 {
|
2024-10-04 02:57:50 +03:00
|
|
|
pub fn init(connection: Arc<Connection>) -> Result<Database, Error> {
|
|
|
|
connection.execute(
|
2024-10-02 20:00:08 +03:00
|
|
|
"CREATE TABLE IF NOT EXISTS `app`
|
|
|
|
(
|
|
|
|
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
|
2024-10-04 19:19:06 +03:00
|
|
|
`time` INTEGER NOT NULL DEFAULT (UNIXEPOCH('NOW'))
|
2024-10-02 20:00:08 +03:00
|
|
|
)",
|
|
|
|
[],
|
2024-10-04 02:57:50 +03:00
|
|
|
)?;
|
2024-10-02 15:22:50 +03:00
|
|
|
|
2024-10-04 02:57:50 +03:00
|
|
|
Ok(Self { connection })
|
2024-10-02 15:22:50 +03:00
|
|
|
}
|
|
|
|
|
2024-10-04 02:57:50 +03:00
|
|
|
pub fn add(&self) -> Result<usize, Error> {
|
2024-10-04 15:39:56 +03:00
|
|
|
self.connection
|
|
|
|
.execute("INSERT INTO `app` DEFAULT VALUES", [])
|
2024-10-03 00:31:41 +03:00
|
|
|
}
|
|
|
|
|
2024-10-04 02:22:37 +03:00
|
|
|
pub fn records(&self) -> Result<Vec<Table>, Error> {
|
2024-10-04 19:23:00 +03:00
|
|
|
let mut statement = self.connection.prepare("SELECT `id` FROM `app`")?;
|
|
|
|
|
|
|
|
let result = statement.query_map([], |row| Ok(Table { id: row.get(0)? }))?;
|
2024-10-04 18:59:41 +03:00
|
|
|
|
2024-10-04 19:00:47 +03:00
|
|
|
let mut records = Vec::new();
|
2024-10-04 18:59:41 +03:00
|
|
|
|
|
|
|
for record in result {
|
|
|
|
let table = record?;
|
|
|
|
records.push(table);
|
|
|
|
}
|
2024-10-04 02:22:37 +03:00
|
|
|
|
|
|
|
Ok(records)
|
|
|
|
}
|
|
|
|
|
2024-10-04 02:57:50 +03:00
|
|
|
pub fn delete(&self, id: i64) -> Result<usize, Error> {
|
|
|
|
self.connection
|
2024-10-04 02:22:37 +03:00
|
|
|
.execute("DELETE FROM `app` WHERE `id` = ?", [id])
|
2024-10-03 00:31:41 +03:00
|
|
|
}
|
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
|
|
|
}
|
|
|
|
}
|