about summary refs log tree commit diff
path: root/src/db.rs
diff options
context:
space:
mode:
authorgennyble <gen@nyble.dev>2025-02-15 14:57:35 -0600
committergennyble <gen@nyble.dev>2025-02-15 14:57:35 -0600
commit9143dab218dee9e1095ba52ded7fdca96471e5be (patch)
tree74f91367b276023e2cfbd0236a6bf6228d135247 /src/db.rs
parent11abf8128d619282498c4b2572f73421e8adf300 (diff)
downloadawake-9143dab218dee9e1095ba52ded7fdca96471e5be.tar.gz
awake-9143dab218dee9e1095ba52ded7fdca96471e5be.zip
Low-budget stats
Diffstat (limited to 'src/db.rs')
-rw-r--r--src/db.rs64
1 files changed, 64 insertions, 0 deletions
diff --git a/src/db.rs b/src/db.rs
new file mode 100644
index 0000000..d4038cb
--- /dev/null
+++ b/src/db.rs
@@ -0,0 +1,64 @@
+use std::sync::Mutex;
+
+use camino::Utf8PathBuf;
+use rusqlite::{params, Connection, OptionalExtension};
+use time::OffsetDateTime;
+
+use crate::Meminfo;
+
+
+pub struct Database{ 
+    db_path: Utf8PathBuf,
+    conn: Mutex<Connection>
+}
+
+impl Database {
+    pub fn new(db_path: Utf8PathBuf) -> Self {
+        Self {
+            conn:Mutex::new(Connection::open(&db_path).unwrap()),
+            db_path,
+        }
+    }
+
+    pub fn create_tables(&self) {
+        let conn = self.conn.lock().unwrap();
+        conn.execute(CREATE_TABLE_HOSTMEM, params![]).unwrap();
+    }
+
+    pub fn insert_host_meminfo(&self, meminfo: Meminfo) {
+        let conn = self.conn.lock().unwrap();
+
+        conn.execute("INSERT INTO stats_hostmem(total_kb, available_kb) VALUES (?1, ?2)", params![meminfo.total, meminfo.avaialable]).unwrap();
+    }
+
+    pub fn get_last_host_meminfo(&self) -> DbMeminfo {
+        let conn = self.conn.lock().unwrap();
+
+        conn.query_row("SELECT * FROM stats_hostmem ORDER BY stamp DESC LIMIT 1", [], |row| {
+            let (stamp, total_kb, available_kb) = row.try_into().unwrap();
+
+            Ok(DbMeminfo {
+                stamp, total_kb, available_kb
+            })
+        }).optional().unwrap().unwrap()
+    }
+}
+
+pub const CREATE_TABLE_HOSTMEM: &'static str = "\
+    CREATE TABLE IF NOT EXISTS stats_hostmem (
+        stamp TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+        total_kb INTEGER NOT NULL,
+        available_kb INTEGER NOT NULL
+    );";
+
+pub struct DbMeminfo {
+    pub stamp: OffsetDateTime,
+    pub total_kb: usize,
+    pub available_kb: usize
+}
+
+impl DbMeminfo {
+    pub fn usage(&self) -> usize {
+        self.total_kb - self.available_kb
+    }
+}
\ No newline at end of file