Want to contribute? Fork me on Codeberg.org!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.4 KiB

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<Self, DatabaseCreationError> {
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<Vec<Word>> {
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::<Result<Vec<Word>>>()
}
}