| 1 | use rusqlite::params; |
| 2 | |
| 3 | use crate::error::Result; |
| 4 | use crate::models::ReadHorizonRecord; |
| 5 | use crate::store::Store; |
| 6 | use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis}; |
| 7 | |
| 8 | impl Store { |
| 9 | pub fn read_horizons(&self, conversation_id: &str) -> Result<Vec<ReadHorizonRecord>> { |
| 10 | let connection = self.read()?; |
| 11 | let mut statement = connection.prepare_cached( |
| 12 | "SELECT member_id, read_until, read_at FROM read_horizons |
| 13 | WHERE conversation_id = ?1 ORDER BY member_id", |
| 14 | )?; |
| 15 | let rows = statement.query_map([conversation_id], |row| { |
| 16 | Ok(ReadHorizonRecord { |
| 17 | member_id: row.get(0)?, |
| 18 | read_until: from_millis(row.get(1)?), |
| 19 | read_at: optional_from_millis(row.get(2)?), |
| 20 | }) |
| 21 | })?; |
| 22 | Ok(rows.collect::<rusqlite::Result<_>>()?) |
| 23 | } |
| 24 | |
| 25 | /// Replaces every stored horizon of the conversation. |
| 26 | pub fn set_read_horizons( |
| 27 | &self, |
| 28 | conversation_id: &str, |
| 29 | horizons: &[ReadHorizonRecord], |
| 30 | ) -> Result<()> { |
| 31 | let mut connection = self.lock()?; |
| 32 | let transaction = connection.transaction()?; |
| 33 | transaction.execute( |
| 34 | "DELETE FROM read_horizons WHERE conversation_id = ?1", |
| 35 | [conversation_id], |
| 36 | )?; |
| 37 | { |
| 38 | let mut statement = transaction.prepare_cached( |
| 39 | "INSERT INTO read_horizons (conversation_id, member_id, read_until, read_at) |
| 40 | VALUES (?1, ?2, ?3, ?4) |
| 41 | ON CONFLICT (conversation_id, member_id) DO UPDATE SET |
| 42 | read_until = excluded.read_until, read_at = excluded.read_at", |
| 43 | )?; |
| 44 | for horizon in horizons { |
| 45 | statement.execute(params![ |
| 46 | conversation_id, |
| 47 | horizon.member_id, |
| 48 | to_millis(horizon.read_until), |
| 49 | optional_to_millis(horizon.read_at), |
| 50 | ])?; |
| 51 | } |
| 52 | } |
| 53 | transaction.commit()?; |
| 54 | Ok(()) |
| 55 | } |
| 56 | } |