From 5b3e091f2b5285dbc832191494738e2b73a69952 Mon Sep 17 00:00:00 2001 From: yggverse Date: Tue, 12 Nov 2024 17:07:00 +0200 Subject: [PATCH] add history model --- src/profile/database.rs | 3 ++ src/profile/database/history.rs | 67 +++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/profile/database/history.rs diff --git a/src/profile/database.rs b/src/profile/database.rs index d369d0ee..a125ac2d 100644 --- a/src/profile/database.rs +++ b/src/profile/database.rs @@ -1,7 +1,9 @@ mod bookmark; +mod history; mod identity; use bookmark::Bookmark; +use history::History; use identity::Identity; use sqlite::{Connection, Error}; @@ -55,6 +57,7 @@ fn init(mut connection: RwLockWriteGuard<'_, Connection>) -> Result<(), Error> { // Init profile components Bookmark::init(&transaction)?; + History::init(&transaction)?; Identity::init(&transaction)?; // Apply changes diff --git a/src/profile/database/history.rs b/src/profile/database/history.rs new file mode 100644 index 00000000..e9f563b5 --- /dev/null +++ b/src/profile/database/history.rs @@ -0,0 +1,67 @@ +use gtk::glib::DateTime; +use sqlite::{Error, Transaction}; + +pub struct Table { + pub id: i64, + pub time: DateTime, + pub request: String, +} + +pub struct History { + // nothing yet.. +} + +impl History { + pub fn init(tx: &Transaction) -> Result { + tx.execute( + "CREATE TABLE IF NOT EXISTS `history` + ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + `time` INTEGER NOT NULL, + `request` TEXT NOT NULL + )", + [], + ) + } + + pub fn add(tx: &Transaction, time: &DateTime, request: &str) -> Result { + tx.execute( + "INSERT INTO `history` ( + `time`, + `request` + ) VALUES (?, ?)", + (time.to_unix(), request), + ) + } + + pub fn records(tx: &Transaction, request: Option<&str>) -> Result, Error> { + let mut stmt = + tx.prepare("SELECT `id`, `time`, `request` FROM `history` WHERE `request` LIKE ?")?; + + let filter = match request { + Some(value) => value, + None => "%", + }; + + let result = stmt.query_map([filter], |row| { + Ok(Table { + id: row.get(0)?, + time: DateTime::from_unix_local(row.get(1)?).unwrap(), + request: row.get(2)?, + }) + })?; + + let mut records = Vec::new(); + + for record in result { + let table = record?; + records.push(table); + } + + Ok(records) + } + + pub fn delete(tx: &Transaction, id: &i64) -> Result { + tx.execute("DELETE FROM `history` WHERE `id` = ?", [id]) + } +}