use crate::Word; use derive_more::From; use std::path::PathBuf; use rusqlite::{Connection, Result, params}; pub struct Database { conn: Connection, } #[derive(From, Debug)] pub enum DatabaseCreationError { RusqliteError(rusqlite::Error), IoError(std::io::Error), } impl Database { pub fn new( testing: bool, ) -> Result { let conn = if testing { Connection::open_in_memory() } else { let path = PathBuf::from("shiritori.db"); //fs::create_dir_all(path.parent().unwrap())?; Connection::open(path) }?; conn.execute( "CREATE TABLE IF NOT EXISTS word ( id INTEGER PRIMARY KEY, word TEXT, reading TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, )", params![], )?; Ok(Self { conn }) } pub fn load_words_before(&self, before_id: i64) -> Result> { self.conn .prepare("SELECT id, word, reading, timestamp FROM word WHERE id < ? DESC LIMIT 10")? .query_map(params![before_id], |row| { Ok(Word { id: row.get(0)?, word: row.get(1)?, reading: row.get(2)?, timestamp: row.get(3)?, }) })? .collect::>>() } }