diff --git a/src/core/deck.rs b/src/core/deck.rs index 3bb2cd3..b09e41c 100644 --- a/src/core/deck.rs +++ b/src/core/deck.rs @@ -15,7 +15,7 @@ use std::sync::Arc; #[derive(Clone)] pub struct DeckData { pub(crate) words: Vec, - pub(crate) set: Vec, + pub(crate) set: Vec, current_word_index: Option, state: Arc>, order_module: OrderModule, @@ -54,7 +54,7 @@ impl DeckData { }) } - pub fn next(&mut self) -> (WordData, CardStatistics) { + pub fn next(&mut self) -> (WordData, CardState) { let index = match self.order_module { SemiRandomSRS(ref mut module) => { if !module.initialized { @@ -88,7 +88,7 @@ impl DeckData { } pub fn open(&mut self, status: WordOpenMode) -> MaybeError { if let Some(index) = self.current_word_index { - let word: &mut CardStatistics = &mut self.set[index]; + let word: &mut CardState = &mut self.set[index]; let old_score = word.score; word.update(status); let new_score = word.score; diff --git a/src/core/srs.rs b/src/core/srs.rs index 7bfd811..bd85444 100644 --- a/src/core/srs.rs +++ b/src/core/srs.rs @@ -1,4 +1,4 @@ -use crate::data::entities::CardStatistics; +use crate::data::entities::CardState; use chrono::{Local, TimeDelta}; use fsrs::FSRS; use rand::distr::weighted::WeightedIndex; @@ -31,9 +31,9 @@ pub enum OrderModule { Fsrs(FsrsModule), } pub trait SRSModule { - fn next(&mut self, set: &[CardStatistics]) -> usize; - fn open(&mut self, status: WordOpenMode, index: usize, updated_word: &mut CardStatistics); - fn init(&mut self, set: &[CardStatistics]); + fn next(&mut self, set: &[CardState]) -> usize; + fn open(&mut self, status: WordOpenMode, index: usize, updated_word: &mut CardState); + fn init(&mut self, set: &[CardState]); } #[derive(Clone)] pub struct RandomSRSModule { @@ -49,7 +49,7 @@ impl RandomSRSModule { } } impl SRSModule for RandomSRSModule { - fn next(&mut self, set: &[CardStatistics]) -> usize { + fn next(&mut self, set: &[CardState]) -> usize { match self.basket.pop() { Some(index) => index, None => { @@ -60,9 +60,9 @@ impl SRSModule for RandomSRSModule { } } - fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardStatistics) {} + fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardState) {} - fn init(&mut self, set: &[CardStatistics]) { + fn init(&mut self, set: &[CardState]) { self.initialized = true; self.basket = (0..set.len()).collect::>(); self.basket.shuffle(&mut rand::rng()) @@ -86,7 +86,7 @@ impl SemiRandomSRSModule { } } impl SRSModule for SemiRandomSRSModule { - fn next(&mut self, set: &[CardStatistics]) -> usize { + fn next(&mut self, set: &[CardState]) -> usize { let index = self.last_weights.sample(&mut self.generator); if self.history.contains(&index) && self.history.len() != 1 { @@ -100,13 +100,13 @@ impl SRSModule for SemiRandomSRSModule { index } - fn open(&mut self, _: WordOpenMode, index: usize, word: &mut CardStatistics) { + fn open(&mut self, _: WordOpenMode, index: usize, word: &mut CardState) { let new_weight = (100.0 / word.calculated_score()).powf(2.0); self.last_weights .update_weights(&[(index, &new_weight)]) .expect("update weights error"); } - fn init(&mut self, set: &[CardStatistics]) { + fn init(&mut self, set: &[CardState]) { self.initialized = true; let weights = set .iter() @@ -116,7 +116,7 @@ impl SRSModule for SemiRandomSRSModule { } } impl SemiRandomSRSModule { - fn history_len(&self, set: &[CardStatistics]) -> usize { + fn history_len(&self, set: &[CardState]) -> usize { ((set.len() as f32 * MAX_HISTORY_LEN_PART) as usize).clamp(1, MAX_HISTORY_LEN) } } @@ -130,7 +130,7 @@ pub struct WorstWordsSRSModule { rounds_count: u8, } impl SRSModule for WorstWordsSRSModule { - fn next(&mut self, set: &[CardStatistics]) -> usize { + fn next(&mut self, set: &[CardState]) -> usize { if self.rounds_remaining == 0 { self.fill_pool(set); self.rounds_remaining = self.rounds_count; @@ -146,9 +146,9 @@ impl SRSModule for WorstWordsSRSModule { } } - fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardStatistics) {} + fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardState) {} - fn init(&mut self, _: &[CardStatistics]) { + fn init(&mut self, _: &[CardState]) { self.initialized = true; } } @@ -163,7 +163,7 @@ impl WorstWordsSRSModule { queue: vec![], } } - fn fill_pool(&mut self, set: &[CardStatistics]) { + fn fill_pool(&mut self, set: &[CardState]) { let mut sorted = set.iter().enumerate().collect::>(); sorted.sort_by_key(|c| c.1.score); let mut worst = sorted[0..self.pool_size] @@ -187,7 +187,7 @@ pub struct FsrsModule { } impl SRSModule for FsrsModule { - fn next(&mut self, _: &[CardStatistics]) -> usize { + fn next(&mut self, _: &[CardState]) -> usize { if self.current_group.is_empty() { self.fill_partial_pool(); } @@ -200,7 +200,7 @@ impl SRSModule for FsrsModule { self.queue.pop().unwrap_or(0) } - fn open(&mut self, status: WordOpenMode, index: usize, updated_word: &mut CardStatistics) { + fn open(&mut self, status: WordOpenMode, index: usize, updated_word: &mut CardState) { let today = Local::now().date_naive(); let delta = today - updated_word.fsrs_opened; let delta_days = delta.num_days(); @@ -233,7 +233,7 @@ impl SRSModule for FsrsModule { } } - fn init(&mut self, set: &[CardStatistics]) { + fn init(&mut self, set: &[CardState]) { self.rng = rng(); let today = Local::now().date_naive(); self.today_set = set diff --git a/src/data/entities.rs b/src/data/entities.rs index 557866b..3c025db 100644 --- a/src/data/entities.rs +++ b/src/data/entities.rs @@ -145,7 +145,7 @@ impl DeckSettings { } #[derive(Clone, PartialEq)] -pub struct CardStatistics { +pub struct CardState { pub id: Id, pub word_id: Id, pub set_id: Id, @@ -155,7 +155,7 @@ pub struct CardStatistics { pub fsrs_memory: Option, pub fsrs_open_day: NaiveDate, } -impl CardStatistics { +impl CardState { pub fn update(&mut self, status: WordOpenMode) { match status { WordOpenMode::Easy => { diff --git a/src/data_provider/card_states.rs b/src/data_provider/card_states.rs index 0af64da..7db49eb 100644 --- a/src/data_provider/card_states.rs +++ b/src/data_provider/card_states.rs @@ -1,22 +1,72 @@ -use crate::data::entities::{CardStatistics, DeckSettings}; +use crate::data::entities::{CardState, DeckSettings}; +use crate::data_provider::TableAccessQuerySet; use crate::notification::NotificationData::{DbLoadError, DbSaveError}; use crate::notification::{MaybeError, NotificationData}; use chrono::NaiveDate; use fsrs::MemoryState; use log::info; -use rusqlite::{Connection, params}; +use rusqlite::{Connection, Error, Params, Row, params}; use std::time::Instant; +pub struct CardStatesQuerySet; +impl TableAccessQuerySet for CardStatesQuerySet { + fn load() -> &'static str { + "INSERT INTO states (word_id, set_id, score, last_opened, fsrs_opened, fsrs_memory, fsrs_open_day) VALUES (?1, ?2, ?3, ?4)" + } + + fn save() -> &'static str { + "UPDATE states SET score = ?1, last_opened = ?2 WHERE id = ?3" + } + + fn add() -> &'static str { + todo!() + } + + fn name() -> &'static str { + "states" + } + + fn from_sql(row: &Row) -> Result { + Ok(CardState { + id: row.get(0)?, + word_id: row.get(1)?, + set_id: set.id, + score: row.get(2)?, + fsrs_opened: NaiveDate::from_epoch_days(row.get::(4)?) + .expect("Incorrect date encoding"), + fsrs_memory: get_memory(row.get(5)?), + last_open: row.get(3)?, + fsrs_open_day: NaiveDate::from_epoch_days(row.get::(6)?) + .expect("Incorrect date encoding"), + }) + } + + fn insert_params(entity: &CardState) -> impl Params { + ( + entity.word_id, + entity.set_id, + entity.score, + entity.last_open.timestamp(), + entity.fsrs_opened.to_epoch_days(), + memory_to_i64(&entity.fsrs_memory), + entity.fsrs_open_day.to_epoch_days(), + ) + } + + fn update_params(entity: &CardState) -> impl Params { + (entity.score, entity.last_open.timestamp(), entity.id) + } +} pub fn load_stats_of_deck( set: &DeckSettings, connection: &Connection, -) -> Result, NotificationData> { +) -> Result, NotificationData> { let mut stmt = connection .prepare("SELECT id, word_id, score, last_opened, fsrs_opened, fsrs_memory, fsrs_open_day FROM states WHERE set_id = ?1") .expect("Failed to prepare state query"); let iter = stmt .query_map((set.id,), |row| { - Ok(CardStatistics { + Ok(CardState { id: row.get(0)?, word_id: row.get(1)?, set_id: set.id, @@ -55,7 +105,7 @@ fn memory_to_i64(value: &Option) -> i64 { value.stability.to_bits() as i64 | ((value.difficulty.to_bits() as i64) << 32) } -pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) -> MaybeError { +pub fn add_stat_list(stats: &mut [CardState], connection: &mut Connection) -> MaybeError { let time = Instant::now(); let tx = connection .transaction() @@ -96,7 +146,7 @@ pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) Ok(()) } -pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) -> MaybeError { +pub fn update_stat_score(stat: &CardState, connection: &Connection) -> MaybeError { let time = Instant::now(); connection @@ -109,7 +159,7 @@ pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) -> Mayb Ok(()) } -pub fn delete_stats(stat: &[CardStatistics], connection: &Connection) -> MaybeError { +pub fn delete_stats(stat: &[CardState], connection: &Connection) -> MaybeError { if stat.is_empty() { return Ok(()); } diff --git a/src/data_provider/mod.rs b/src/data_provider/mod.rs index 998b1f0..1c54a7a 100644 --- a/src/data_provider/mod.rs +++ b/src/data_provider/mod.rs @@ -1,11 +1,10 @@ -use crate::core::srs::OrderMode; use crate::data::Id; -use crate::data::entities::{DeckSettings, EntityData}; +use crate::data::entities::{CardState, EntityData}; use crate::data::repositories::{BatchedDbLayer, DbLayer}; use crate::notification::MaybeError; use crate::notification::NotificationData::{DbLoadError, DbSaveError}; use log::info; -use rusqlite::{Connection, Params, Row, params}; +use rusqlite::{Connection, Error, Params, Row}; use std::marker::PhantomData; use std::time::Instant; @@ -24,7 +23,7 @@ pub trait TableAccessQuerySet { fn save() -> &'static str; fn add() -> &'static str; fn name() -> &'static str; - fn from_sql(row: &Row) -> T; + fn from_sql(row: &Row) -> Result; fn insert_params(entity: &T) -> impl Params; fn update_params(entity: &T) -> impl Params; } @@ -33,8 +32,7 @@ pub struct SqliteDbLayer where Q: TableAccessQuerySet, { - query_set: Q, - _phantom: PhantomData, + _phantom: PhantomData<(T, Q)>, } impl> DbLayer for SqliteDbLayer { diff --git a/src/pages/repetition.rs b/src/pages/repetition.rs index 15f0a70..cbf5d91 100644 --- a/src/pages/repetition.rs +++ b/src/pages/repetition.rs @@ -2,7 +2,7 @@ use crate::app::AppState; use crate::core::deck::DeckData; use crate::core::srs::WordOpenMode; use crate::data::Id; -use crate::data::entities::{CardStatistics, DeckSettings, WordData}; +use crate::data::entities::{CardState, DeckSettings, WordData}; use crate::data_provider::voice::get_voice; use crate::navigation::Page::PreviousPage; use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage}; @@ -26,7 +26,7 @@ pub struct RepetitionState { pub settings: DeckSettings, pub set: DeckData, current_word: WordData, - current_statistic: CardStatistics, + current_statistic: CardState, open: bool, can_play: bool, sink: Arc>, diff --git a/src/pages/repetitions.rs b/src/pages/repetitions.rs index 84c4bc5..38f44d2 100644 --- a/src/pages/repetitions.rs +++ b/src/pages/repetitions.rs @@ -1,7 +1,7 @@ use crate::app::AppState; use crate::core::srs::{AppendMode, OrderMode}; use crate::data::Id; -use crate::data::entities::{CardStatistics, DeckSettings}; +use crate::data::entities::{CardState, DeckSettings}; use crate::data_provider::card_states::{add_stat_list, load_stats_of_deck}; use crate::data_provider::decks::update_deck; use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings}; @@ -585,7 +585,7 @@ impl RepetitionsState { let stats = &mut indices .map(|i| { let word = &words[i]; - CardStatistics { + CardState { id: 0.into(), word_id: word.id, last_open: Utc::now(),