persistence.rs

 1use std::path::{Path, PathBuf};
 2
 3use anyhow::{Context, Result};
 4use db::{connection, exec_method};
 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 INTEGER 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    exec_method!(save_path(item_id: ItemId, workspace_id: WorkspaceId, path: &Path):
43        "INSERT OR REPLACE INTO editors(item_id, workspace_id, path)
44         VALUES (?, ?, ?)"
45    );
46}