Skip to main content

beyonder_store/
block_store.rs

1use beyonder_core::{Block, BlockId, BlockStatus, SessionId};
2use rusqlite::params;
3
4use crate::{Store, StoreError, StoreResult};
5
6pub struct BlockStore<'a> {
7    store: &'a Store,
8}
9
10impl<'a> BlockStore<'a> {
11    pub fn new(store: &'a Store) -> Self {
12        Self { store }
13    }
14
15    pub fn insert(&self, block: &Block) -> StoreResult<()> {
16        let data = serde_json::to_string(block)?;
17        self.store.conn.execute(
18            r#"INSERT INTO blocks (id, session_id, kind, status, agent_id, parent_id, created_at, updated_at, data)
19               VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)"#,
20            params![
21                block.id.0,
22                block.session_id.0,
23                format!("{:?}", block.kind),
24                format!("{:?}", block.status),
25                block.agent_id.as_ref().map(|a| &a.0),
26                block.parent_id.as_ref().map(|p| &p.0),
27                block.created_at.to_rfc3339(),
28                block.updated_at.to_rfc3339(),
29                data,
30            ],
31        )?;
32        Ok(())
33    }
34
35    pub fn update(&self, block: &Block) -> StoreResult<()> {
36        let data = serde_json::to_string(block)?;
37        self.store.conn.execute(
38            "UPDATE blocks SET status = ?1, updated_at = ?2, data = ?3 WHERE id = ?4",
39            params![
40                format!("{:?}", block.status),
41                block.updated_at.to_rfc3339(),
42                data,
43                block.id.0,
44            ],
45        )?;
46        Ok(())
47    }
48
49    pub fn get(&self, id: &BlockId) -> StoreResult<Block> {
50        let data: String = self
51            .store
52            .conn
53            .query_row(
54                "SELECT data FROM blocks WHERE id = ?1",
55                params![id.0],
56                |row| row.get(0),
57            )
58            .map_err(|_| StoreError::NotFound(id.0.clone()))?;
59        Ok(serde_json::from_str(&data)?)
60    }
61
62    pub fn list_for_session(&self, session_id: &SessionId) -> StoreResult<Vec<Block>> {
63        let mut stmt = self
64            .store
65            .conn
66            .prepare("SELECT data FROM blocks WHERE session_id = ?1 ORDER BY created_at ASC")?;
67        let blocks = stmt
68            .query_map(params![session_id.0], |row| row.get::<_, String>(0))?
69            .filter_map(|r| r.ok())
70            .filter_map(|data| serde_json::from_str(&data).ok())
71            .collect();
72        Ok(blocks)
73    }
74
75    pub fn update_status(&self, id: &BlockId, status: &BlockStatus) -> StoreResult<()> {
76        self.store.conn.execute(
77            "UPDATE blocks SET status = ?1 WHERE id = ?2",
78            params![format!("{:?}", status), id.0],
79        )?;
80        Ok(())
81    }
82}