BlueGit

ict rusty-teams

Files

rusty-teams / crates / store / src / activity.rs

activity.rs

activity.rs 2.7 KiB Download Raw
1use chrono::{DateTime, Utc};
2use rusqlite::{Row, params};
3
4use crate::error::Result;
5use crate::models::ActivityRecord;
6use crate::store::Store;
7use crate::time::{from_millis, to_millis};
8
9const ACTIVITY_COLUMNS: &str =
10 "id, conversation_id, kind, message_id, actors_json, preview, glyphs, count, updated_at, read";
11
12impl Store {
13 pub fn upsert_activity(&self, records: &[ActivityRecord]) -> Result<()> {
14 let mut connection = self.lock()?;
15 let transaction = connection.transaction()?;
16 {
17 let mut upsert = transaction.prepare_cached(&format!(
18 "INSERT INTO activity ({ACTIVITY_COLUMNS})
19 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
20 ON CONFLICT (id) DO UPDATE SET
21 conversation_id = excluded.conversation_id, kind = excluded.kind,
22 message_id = excluded.message_id, actors_json = excluded.actors_json,
23 preview = excluded.preview, glyphs = excluded.glyphs, count = excluded.count,
24 updated_at = excluded.updated_at, read = excluded.read"
25 ))?;
26 for record in records {
27 upsert.execute(params![
28 record.id,
29 record.conversation_id,
30 record.kind,
31 record.message_id,
32 record.actors_json,
33 record.preview,
34 record.glyphs,
35 record.count,
36 to_millis(record.updated_at),
37 record.read,
38 ])?;
39 }
40 }
41 Ok(transaction.commit()?)
42 }
43
44 /// Newest first.
45 pub fn activity(&self) -> Result<Vec<ActivityRecord>> {
46 let connection = self.lock()?;
47 let mut statement = connection.prepare_cached(&format!(
48 "SELECT {ACTIVITY_COLUMNS} FROM activity ORDER BY updated_at DESC, id DESC"
49 ))?;
50 let records = statement
51 .query_map([], activity_from_row)?
52 .collect::<rusqlite::Result<Vec<_>>>()?;
53 Ok(records)
54 }
55
56 pub fn prune_activity(&self, before: DateTime<Utc>) -> Result<usize> {
57 let connection = self.lock()?;
58 Ok(connection.execute(
59 "DELETE FROM activity WHERE updated_at < ?1",
60 [to_millis(before)],
61 )?)
62 }
63}
64
65fn activity_from_row(row: &Row<'_>) -> rusqlite::Result<ActivityRecord> {
66 Ok(ActivityRecord {
67 id: row.get(0)?,
68 conversation_id: row.get(1)?,
69 kind: row.get(2)?,
70 message_id: row.get(3)?,
71 actors_json: row.get(4)?,
72 preview: row.get(5)?,
73 glyphs: row.get(6)?,
74 count: row.get(7)?,
75 updated_at: from_millis(row.get(8)?),
76 read: row.get(9)?,
77 })
78}