From 8a29f30fb2a949c03b318c4f7699136a8001be37 Mon Sep 17 00:00:00 2001 From: Joris Date: Sun, 13 Feb 2022 12:17:00 +0100 Subject: Synchronize deck only if necessary Look at the modification time of the deck, and synchronize if it has been modified after the last deck read. --- src/db/db.rs | 44 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) (limited to 'src/db') diff --git a/src/db/db.rs b/src/db/db.rs index 30ea1da..b42da3f 100644 --- a/src/db/db.rs +++ b/src/db/db.rs @@ -19,13 +19,23 @@ pub fn init(database: String) -> Result { Ok(conn) } +pub fn last_deck_read(conn: &Connection) -> Option { + let mut stmt = conn + .prepare("SELECT deck_read FROM cards ORDER BY deck_read DESC LIMIT 1") + .ok()?; + + let mut rows = stmt.query([]).ok()?; + let row = rows.next().ok()??; + row.get(0).ok()? +} + /// Synchronize the DB with the deck: /// /// - insert new cards, /// - keep existing cards, /// - hide unused cards (keep state in case the card is added back afterward). pub fn synchronize(conn: &Connection, entries: Vec) -> Result<()> { - let now = time::now()?; + let now = time::seconds_since_unix_epoch()?; let state = serde_json::to_string(&space_repetition::init())?; @@ -76,19 +86,21 @@ fn delete_read_before(conn: &Connection, t: u64) -> Result<()> { } pub fn pick_random_ready(conn: &Connection) -> Option { + let now = time::seconds_since_unix_epoch().ok()?; + let mut stmt = conn .prepare( " SELECT question, responses, state, ready FROM cards - WHERE deleted IS NULL + WHERE deleted IS NULL AND ready <= ? ORDER BY RANDOM() LIMIT 1 ", ) .ok()?; - let mut rows = stmt.query([]).ok()?; + let mut rows = stmt.query([now]).ok()?; let row = rows.next().ok()??; let state_str: String = row.get(2).ok()?; let responses_str: String = row.get(1).ok()?; @@ -101,9 +113,29 @@ pub fn pick_random_ready(conn: &Connection) -> Option { }) } +pub fn next_ready(conn: &Connection) -> Option { + let mut stmt = conn + .prepare( + " + SELECT ready + FROM cards + WHERE deleted IS NULL + ORDER BY ready + LIMIT 1 + ", + ) + .ok()?; + + let mut rows = stmt.query([]).ok()?; + let row = rows.next().ok()??; + row.get(0).ok()? +} + pub fn count_available(conn: &Connection) -> Option { - let now = time::now().ok()?; - let mut stmt = conn.prepare("SELECT COUNT(*) FROM cards WHERE ready <= ? AND deleted IS NULL").ok()?; + let now = time::seconds_since_unix_epoch().ok()?; + let mut stmt = conn + .prepare("SELECT COUNT(*) FROM cards WHERE ready <= ? AND deleted IS NULL") + .ok()?; let mut rows = stmt.query([now]).ok()?; let row = rows.next().ok()??; @@ -111,7 +143,7 @@ pub fn count_available(conn: &Connection) -> Option { } pub fn update(conn: &Connection, question: &String, state: &space_repetition::State) -> Result<()> { - let now = time::now()?; + let now = time::seconds_since_unix_epoch()?; let ready = now + state.get_interval_seconds(); let state_str = serde_json::to_string(state)?; -- cgit v1.2.3