1use std::collections::{BTreeMap, BTreeSet};
7
8use rusqlite::params;
9
10use super::{Cache, conn::Conn, sync::SyncState};
11use crate::{
12 RepoPath,
13 model::{PlanIndex, Planned},
14};
15
16impl Cache {
17 pub fn record_plans_of(&self, plans: &PlanIndex, checked: &BTreeSet<RepoPath>) {
21 let rows: BTreeMap<RepoPath, BTreeSet<Planned>> =
22 checked.iter().map(|p| (p.clone(), plans.of(p))).collect();
23 self.state.borrow_mut().plans_of.extend(rows);
24 }
25
26 pub fn old_plans_of(&self, path: &RepoPath) -> BTreeSet<Planned> {
29 self.conn()
30 .rows(
31 "SELECT target FROM plans WHERE path = ?1",
32 [path.as_str()],
33 |r| r.get::<_, String>(0),
34 )
35 .iter()
36 .filter_map(|t| Planned::parse(t))
37 .collect()
38 }
39
40 pub fn stored_plans(&self, except: &BTreeSet<RepoPath>) -> PlanIndex {
43 let mut plans = PlanIndex::default();
44 let removed = self.removed_set();
45 let rows = self.conn().rows("SELECT path, target FROM plans", [], |r| {
46 Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
47 });
48 for (path, target) in rows {
49 let (Some(path), Some(target)) = (RepoPath::parse(&path), Planned::parse(&target))
50 else {
51 continue;
52 };
53 if !except.contains(&path) && !removed.contains(&path) {
54 plans.add(&path, &target);
55 }
56 }
57 plans
58 }
59
60 pub(super) fn commit_plans(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
63 let mut delete = conn.prepare("DELETE FROM plans WHERE path = ?1")?;
64 let mut put = conn.prepare("INSERT INTO plans (path, target) VALUES (?1, ?2)")?;
65 for path in &state.removed {
66 delete.execute([path.as_str()])?;
67 }
68 for (path, targets) in &state.plans_of {
69 delete.execute([path.as_str()])?;
70 for target in targets {
71 put.execute(params![path.as_str(), target.key()])?;
72 }
73 }
74 Ok(())
75 }
76}