|
| 1 | +use diesel::{ExpressionMethods, Identifiable, OptionalExtension as _, QueryDsl, RunQueryDsl}; |
| 2 | + |
| 3 | +use crate::DbHandle; |
| 4 | +use crate::schema::worktrees::dsl::worktrees; |
| 5 | + |
| 6 | +use diesel::prelude::{Insertable, Queryable, Selectable}; |
| 7 | +use serde::{Deserialize, Serialize}; |
| 8 | + |
| 9 | +#[derive( |
| 10 | + Debug, Clone, PartialEq, Serialize, Deserialize, Queryable, Selectable, Insertable, Identifiable, |
| 11 | +)] |
| 12 | +#[diesel(table_name = crate::schema::worktrees)] |
| 13 | +#[diesel(check_for_backend(diesel::sqlite::Sqlite))] |
| 14 | +#[diesel(primary_key(path))] |
| 15 | +pub struct Worktree { |
| 16 | + pub path: String, |
| 17 | + pub reference: String, |
| 18 | + pub base: String, |
| 19 | + pub source: String, |
| 20 | +} |
| 21 | + |
| 22 | +impl DbHandle { |
| 23 | + pub fn worktrees(&mut self) -> WorktreesHandle<'_> { |
| 24 | + WorktreesHandle { db: self } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +pub struct WorktreesHandle<'a> { |
| 29 | + db: &'a mut DbHandle, |
| 30 | +} |
| 31 | + |
| 32 | +impl WorktreesHandle<'_> { |
| 33 | + pub fn insert(&mut self, worktree: Worktree) -> Result<(), diesel::result::Error> { |
| 34 | + diesel::insert_into(worktrees) |
| 35 | + .values(worktree) |
| 36 | + .execute(&mut self.db.conn)?; |
| 37 | + Ok(()) |
| 38 | + } |
| 39 | + |
| 40 | + pub fn get(&mut self, path: &str) -> Result<Option<Worktree>, diesel::result::Error> { |
| 41 | + let worktree = worktrees |
| 42 | + .filter(crate::schema::worktrees::path.eq(path)) |
| 43 | + .first::<Worktree>(&mut self.db.conn) |
| 44 | + .optional()?; |
| 45 | + Ok(worktree) |
| 46 | + } |
| 47 | + |
| 48 | + pub fn delete(&mut self, path: &str) -> Result<(), diesel::result::Error> { |
| 49 | + diesel::delete(worktrees.filter(crate::schema::worktrees::path.eq(path))) |
| 50 | + .execute(&mut self.db.conn)?; |
| 51 | + Ok(()) |
| 52 | + } |
| 53 | + |
| 54 | + pub fn list(&mut self) -> Result<Vec<Worktree>, diesel::result::Error> { |
| 55 | + let worktree_list = worktrees.load::<Worktree>(&mut self.db.conn)?; |
| 56 | + Ok(worktree_list) |
| 57 | + } |
| 58 | +} |
0 commit comments