use anyhow::Result; use redb::{Database, ReadableTable, TableDefinition}; use serde::Deserialize; use std::path::PathBuf; #[derive(Deserialize)] pub struct Config { path: PathBuf, } pub fn open_db(config: Config) -> Result { let db = Database::create(config.path)?; Ok(db) } static T_CREDS: TableDefinition<&str, &str> = TableDefinition::new("creds"); pub trait DatabaseExt { fn check_or_insert_creds(&self, username: &str, password: &str) -> anyhow::Result; } impl DatabaseExt for Database { fn check_or_insert_creds(&self, username: &str, password: &str) -> anyhow::Result { let txn = self.begin_write()?; let mut table = txn.open_table(T_CREDS)?; if let Some(pw) = table.get(username)? { return Ok(pw.value() == password); } table.insert(username, password)?; drop(table); txn.commit()?; Ok(true) } }