persistence.rs

 1use std::path::{Path, PathBuf};
 2
 3use anyhow::{Context, Result};
 4use db::connection;
 5use indoc::indoc;
 6use sqlez::domain::Domain;
 7use workspace::{ItemId, Workspace, WorkspaceId};
 8
 9use crate::Editor;
10
11connection!(DB: EditorDb<(Workspace, Editor)>);
12
13impl Domain for Editor {
14    fn name() -> &'static str {
15        "editor"
16    }
17
18    fn migrations() -> &'static [&'static str] {
19        &[indoc! {"
20            CREATE TABLE editors(
21                item_id INTEGER NOT NULL,
22                workspace_id BLOB NOT NULL,
23                path BLOB NOT NULL,
24                PRIMARY KEY(item_id, workspace_id),
25                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
26                    ON DELETE CASCADE
27                    ON UPDATE CASCADE
28
29            ) STRICT;
30        "}]
31    }
32}
33
34impl EditorDb {
35    pub fn get_path(&self, item_id: ItemId, workspace_id: WorkspaceId) -> Result<PathBuf> {
36        self.select_row_bound(indoc! {"
37            SELECT path FROM editors 
38            WHERE item_id = ? AND workspace_id = ?"})?((item_id, &workspace_id))?
39        .context("Path not found for serialized editor")
40    }
41
42    pub fn save_path(
43        &self,
44        item_id: ItemId,
45        workspace_id: WorkspaceId,
46        path: PathBuf,
47    ) -> Result<()> {
48        self.exec_bound::<(ItemId, &WorkspaceId, &Path)>(indoc! {"
49            INSERT OR REPLACE INTO editors(item_id, workspace_id, path)
50            VALUES (?, ?, ?)"})?((item_id, &workspace_id, &path))
51    }
52}