persistence.rs

 1use anyhow::Result;
 2use db::{define_connection, query, sqlez::statement::Statement, sqlez_macros::sql};
 3use workspace::{ItemId, WorkspaceDb, WorkspaceId};
 4
 5define_connection! {
 6    pub static ref COMPONENT_PREVIEW_DB: ComponentPreviewDb<WorkspaceDb> =
 7        &[sql!(
 8            CREATE TABLE component_previews (
 9                workspace_id INTEGER,
10                item_id INTEGER UNIQUE,
11                active_page_id TEXT,
12                PRIMARY KEY(workspace_id, item_id),
13                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
14                ON DELETE CASCADE
15            ) STRICT;
16        )];
17}
18
19impl ComponentPreviewDb {
20    pub async fn save_active_page(
21        &self,
22        item_id: ItemId,
23        workspace_id: WorkspaceId,
24        active_page_id: String,
25    ) -> Result<()> {
26        let query = "INSERT INTO component_previews(item_id, workspace_id, active_page_id)
27            VALUES (?1, ?2, ?3)
28            ON CONFLICT DO UPDATE SET
29                active_page_id = ?3";
30        self.write(move |conn| {
31            let mut statement = Statement::prepare(conn, query)?;
32            let mut next_index = statement.bind(&item_id, 1)?;
33            next_index = statement.bind(&workspace_id, next_index)?;
34            statement.bind(&active_page_id, next_index)?;
35            statement.exec()
36        })
37        .await
38    }
39
40    query! {
41        pub fn get_active_page(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<String>> {
42            SELECT active_page_id
43            FROM component_previews
44            WHERE item_id = ? AND workspace_id = ?
45        }
46    }
47
48    pub async fn delete_unloaded_items(
49        &self,
50        workspace: WorkspaceId,
51        alive_items: Vec<ItemId>,
52    ) -> Result<()> {
53        let placeholders = alive_items
54            .iter()
55            .map(|_| "?")
56            .collect::<Vec<&str>>()
57            .join(", ");
58
59        let query = format!(
60            "DELETE FROM component_previews WHERE workspace_id = ? AND item_id NOT IN ({placeholders})"
61        );
62
63        self.write(move |conn| {
64            let mut statement = Statement::prepare(conn, query)?;
65            let mut next_index = statement.bind(&workspace, 1)?;
66            for id in alive_items {
67                next_index = statement.bind(&id, next_index)?;
68            }
69            statement.exec()
70        })
71        .await
72    }
73}