persistence.rs

 1use std::path::PathBuf;
 2
 3use db::sqlez_macros::sql;
 4use db::{define_connection, query};
 5
 6use gpui::EntityId;
 7use workspace::{ItemId, WorkspaceDb, WorkspaceId};
 8
 9define_connection!(
10    // Current schema shape using pseudo-rust syntax:
11    // editors(
12    //   item_id: usize,
13    //   workspace_id: usize,
14    //   path: PathBuf,
15    //   scroll_top_row: usize,
16    //   scroll_vertical_offset: f32,
17    //   scroll_horizontal_offset: f32,
18    // )
19    pub static ref DB: EditorDb<WorkspaceDb> =
20        &[sql! (
21            CREATE TABLE editors(
22                item_id INTEGER NOT NULL,
23                workspace_id INTEGER NOT NULL,
24                path BLOB NOT NULL,
25                PRIMARY KEY(item_id, workspace_id),
26                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
27                ON DELETE CASCADE
28                ON UPDATE CASCADE
29            ) STRICT;
30        ),
31        sql! (
32            ALTER TABLE editors ADD COLUMN scroll_top_row INTEGER NOT NULL DEFAULT 0;
33            ALTER TABLE editors ADD COLUMN scroll_horizontal_offset REAL NOT NULL DEFAULT 0;
34            ALTER TABLE editors ADD COLUMN scroll_vertical_offset REAL NOT NULL DEFAULT 0;
35        )];
36);
37
38impl EditorDb {
39    query! {
40        pub fn get_path(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
41            SELECT path FROM editors
42            WHERE item_id = ? AND workspace_id = ?
43        }
44    }
45
46    query! {
47        pub async fn save_path(item_id: ItemId, workspace_id: WorkspaceId, path: PathBuf) -> Result<()> {
48            INSERT INTO editors
49                (item_id, workspace_id, path)
50            VALUES
51                (?1, ?2, ?3)
52            ON CONFLICT DO UPDATE SET
53                item_id = ?1,
54                workspace_id = ?2,
55                path = ?3
56        }
57    }
58
59    // Returns the scroll top row, and offset
60    query! {
61        pub fn get_scroll_position(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<(u32, f32, f32)>> {
62            SELECT scroll_top_row, scroll_horizontal_offset, scroll_vertical_offset
63            FROM editors
64            WHERE item_id = ? AND workspace_id = ?
65        }
66    }
67
68    query! {
69        pub async fn save_scroll_position(
70            item_id: EntityId,
71            workspace_id: WorkspaceId,
72            top_row: u32,
73            vertical_offset: f32,
74            horizontal_offset: f32
75        ) -> Result<()> {
76            UPDATE OR IGNORE editors
77            SET
78                scroll_top_row = ?3,
79                scroll_horizontal_offset = ?4,
80                scroll_vertical_offset = ?5
81            WHERE item_id = ?1 AND workspace_id = ?2
82        }
83    }
84}