Organize code, begin database implementation
This commit is contained in:
parent
376fba6795
commit
4e9784baf4
7 changed files with 594 additions and 177 deletions
52
src/database.rs
Normal file
52
src/database.rs
Normal file
|
@ -0,0 +1,52 @@
|
|||
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>>>()
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue