Skip to main content

sokf_core/cache/
edges.rs

1//! The store keeps the edges of each document for `graph`. The cache writes
2//! them when the run commits, and reads them back either all at once or only
3//! those that touch a set of paths or point under a directory. For a document that the current run checked, the cache answers
4//! with the run's own edges, not with the stored rows.
5
6use std::collections::BTreeSet;
7
8use rusqlite::params;
9
10use super::{Cache, conn::Conn, sync::SyncState};
11use crate::{
12    RepoPath,
13    graph::{EdgeKind, EdgeStore, NodeKey, RawEdge},
14};
15
16/// `COLUMNS` selects the columns of an edge row, in the order that `row_edge`
17/// reads them.
18const COLUMNS: &str = "SELECT source, kind, written, target, missing, rel, region, note FROM edges";
19
20/// `edge_code` returns the code under which the store keeps an `EdgeKind`.
21fn edge_code(kind: EdgeKind) -> i64 {
22    match kind {
23        EdgeKind::Includes => 0,
24        EdgeKind::Links => 1,
25        EdgeKind::Resource => 2,
26        EdgeKind::Sources => 3,
27        // The graph builds a key's edges only when the query starts from that
28        // key, so the store never holds an edge of this kind.
29        EdgeKind::Keys => 4,
30        // The graph reads a marker's edge from the citations that the check
31        // of its file stores, so the edges table never holds one.
32        EdgeKind::Marker => 5,
33    }
34}
35
36/// `edge_kind` returns the `EdgeKind` of a stored code, and reads an unknown
37/// code as a link.
38fn edge_kind(code: i64) -> EdgeKind {
39    match code {
40        0 => EdgeKind::Includes,
41        2 => EdgeKind::Resource,
42        3 => EdgeKind::Sources,
43        _ => EdgeKind::Links,
44    }
45}
46
47impl Cache {
48    /// `record_edges` holds the edges that one document declares until the
49    /// commit writes them (CACHE-1_AC-11).
50    // sokf-implements: CACHE-1_AC-22
51    pub fn record_edges(&self, source: &RepoPath, edges: Vec<RawEdge>) {
52        self.state.borrow_mut().edges.insert(source.clone(), edges);
53    }
54
55    /// `read_edges` returns the edges that `sql` selects with each set of
56    /// `args`, and prepares the statement once for all of them. It skips the
57    /// stored rows of each source that the run checked. In their place, it
58    /// adds each edge from the current run that `keep` accepts. It also skips
59    /// the rows of each removed file. Because it skips those rows, the answer
60    /// stays correct even when a commit fails (CACHE-1_AC-9).
61    fn read_edges(
62        &self,
63        sql: &str,
64        args: &[Vec<&str>],
65        keep: impl Fn(&RawEdge) -> bool,
66    ) -> Vec<RawEdge> {
67        let mut out = self.read_stored(sql, args, row_edge, |s, from| s.edges.contains_key(from));
68        let state = self.state.borrow();
69        for edges in state.edges.values() {
70            out.extend(edges.iter().filter(|e| keep(e)).cloned());
71        }
72        out
73    }
74
75    /// `read_markers` returns the edges of the markers that `sql` selects from
76    /// the stored citations with each set of `args`, as `read_edges` does for
77    /// the edges of documents. It skips the stored rows of each file that the
78    /// run checked, and adds in their place each marker of the run that
79    /// `keep` accepts. It also skips the rows of each removed file.
80    fn read_markers(
81        &self,
82        sql: &str,
83        args: &[Vec<&str>],
84        keep: impl Fn(&RawEdge) -> bool,
85    ) -> Vec<RawEdge> {
86        let mut out = self.read_stored(sql, args, row_marker, |s, from| {
87            s.citations.contains_key(from)
88        });
89        let state = self.state.borrow();
90        for rows in state.citations.values() {
91            out.extend(
92                rows.iter()
93                    .filter_map(|c| {
94                        let rel = c.rel.clone()?;
95                        Some(marker_edge(
96                            c.source.clone(),
97                            &c.target,
98                            c.slug.clone(),
99                            rel,
100                            c.line,
101                        ))
102                    })
103                    .filter(|e| keep(e)),
104            );
105        }
106        out
107    }
108
109    /// `read_stored` returns the stored edges that `sql` selects with each
110    /// set of `args`, and prepares the statement once for all of them. It
111    /// reads each row with `row`, and skips the rows of each source that
112    /// `checked` says the run checked, and of each removed file.
113    fn read_stored(
114        &self,
115        sql: &str,
116        args: &[Vec<&str>],
117        row: fn(&rusqlite::Row<'_>) -> rusqlite::Result<Option<RawEdge>>,
118        checked: impl Fn(&SyncState, &RepoPath) -> bool,
119    ) -> Vec<RawEdge> {
120        let state = self.state.borrow();
121        let removed: BTreeSet<&RepoPath> = state.removed.iter().collect();
122        let mut out: Vec<RawEdge> = Vec::new();
123        if let Ok(mut stmt) = self.conn().prepare(sql) {
124            for one in args {
125                if let Ok(rows) = stmt.query_map(rusqlite::params_from_iter(one), row) {
126                    out.extend(
127                        rows.flatten()
128                            .flatten()
129                            .filter(|e| !checked(&state, &e.from) && !removed.contains(&e.from)),
130                    );
131                }
132            }
133        }
134        out
135    }
136
137    /// `commit_edges` writes the edges of each document that the run checked,
138    /// in place of the document's stored rows.
139    pub(super) fn commit_edges(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
140        let mut del_edges = conn.prepare("DELETE FROM edges WHERE source = ?1")?;
141        let mut put_edge = conn.prepare(
142            "INSERT INTO edges (source, kind, written, target, missing, rel, region, note) \
143             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
144        )?;
145        for (source, edges) in &state.edges {
146            del_edges.execute([source.as_str()])?;
147            for e in edges {
148                put_edge.execute(params![
149                    source.as_str(),
150                    edge_code(e.kind),
151                    e.written,
152                    e.to.as_str(),
153                    i64::from(matches!(e.to, NodeKey::Missing(_))),
154                    e.rel,
155                    e.region,
156                    e.note
157                ])?;
158            }
159        }
160        Ok(())
161    }
162}
163
164/// `row_edge` reads one stored edge, and returns `None` when the edge's
165/// source isn't a valid path.
166fn row_edge(r: &rusqlite::Row<'_>) -> rusqlite::Result<Option<RawEdge>> {
167    let source: String = r.get(0)?;
168    let target: String = r.get(3)?;
169    let missing: i64 = r.get(4)?;
170    let Some(from) = RepoPath::parse(&source) else {
171        return Ok(None);
172    };
173    let to = match (missing != 0, RepoPath::parse(&target)) {
174        (false, Some(p)) => NodeKey::Path(p),
175        _ => NodeKey::Missing(target),
176    };
177    Ok(Some(RawEdge {
178        from,
179        kind: edge_kind(r.get(1)?),
180        written: r.get(2)?,
181        to,
182        rel: r.get(5)?,
183        region: r.get(6)?,
184        line: None,
185        note: r.get(7)?,
186    }))
187}
188
189/// `MARKERS` selects the columns of a marker's citation, in the order that
190/// `row_marker` reads them. A citation with a `rel` comes from a marker.
191const MARKERS: &str = "SELECT source, target, slug, rel, line FROM citations WHERE rel IS NOT NULL";
192
193/// `marker_edge` returns the edge of a marker in `source` that cites `target`.
194fn marker_edge(
195    source: RepoPath,
196    target: &RepoPath,
197    slug: Option<String>,
198    rel: String,
199    line: usize,
200) -> RawEdge {
201    RawEdge {
202        from: source,
203        kind: EdgeKind::Marker,
204        written: target.as_str().to_string(),
205        to: NodeKey::Path(target.clone()),
206        rel,
207        region: slug,
208        line: Some(line),
209        note: None,
210    }
211}
212
213/// `row_marker` reads the citation of one marker as its edge, and returns
214/// `None` when a path isn't valid.
215fn row_marker(r: &rusqlite::Row<'_>) -> rusqlite::Result<Option<RawEdge>> {
216    let (source, target): (String, String) = (r.get(0)?, r.get(1)?);
217    let (Some(source), Some(target)) = (RepoPath::parse(&source), RepoPath::parse(&target)) else {
218        return Ok(None);
219    };
220    let line: usize = r.get(4)?;
221    Ok(Some(marker_edge(
222        source,
223        &target,
224        r.get(2)?,
225        r.get(3)?,
226        line,
227    )))
228}
229
230/// The cache gives `graph` the edges that the store keeps (CACHE-1_AC-22).
231// sokf-implements: CACHE-1_AC-22
232// sokf-implements: CACHE-1_AC-38
233// sokf-implements: CACHE-1_AC-44
234// sokf-implements: CACHE-1_AC-45
235impl EdgeStore for Cache {
236    fn every(&self) -> Vec<RawEdge> {
237        let mut out = self.read_edges(COLUMNS, &[Vec::new()], |_| true);
238        out.extend(self.read_markers(MARKERS, &[Vec::new()], |_| true));
239        out
240    }
241
242    fn touching(&self, paths: &BTreeSet<RepoPath>) -> Vec<RawEdge> {
243        // The query returns an edge between two of `paths` once for each
244        // end, and the graph keeps only one copy.
245        let args: Vec<Vec<&str>> = paths.iter().map(|p| vec![p.as_str()]).collect();
246        let touches =
247            |e: &RawEdge| paths.contains(&e.from) || e.to.path().is_some_and(|p| paths.contains(p));
248        let mut out = self.read_edges(
249            &format!("{COLUMNS} WHERE source = ?1 OR (target = ?1 AND missing = 0)"),
250            &args,
251            touches,
252        );
253        out.extend(self.read_markers(
254            &format!("{MARKERS} AND (source = ?1 OR target = ?1)"),
255            &args,
256            touches,
257        ));
258        out
259    }
260
261    fn under(&self, dir: &RepoPath) -> Vec<RawEdge> {
262        let (low, high) = super::hint::under(dir);
263        let mut out = self.read_edges(
264            &format!("{COLUMNS} WHERE target >= ?1 AND target < ?2 AND missing = 0"),
265            &[vec![&low, &high]],
266            |e| e.to.path().is_some_and(|p| p != dir && p.starts_with(dir)),
267        );
268        // A file under `dir` that holds a marker is the source of the
269        // marker's edge, not its target.
270        out.extend(self.read_markers(
271            &format!("{MARKERS} AND source >= ?1 AND source < ?2"),
272            &[vec![&low, &high]],
273            |e| e.from != *dir && e.from.starts_with(dir),
274        ));
275        out
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use crate::{CacheMode, RepoRoot};
283
284    fn p(s: &str) -> RepoPath {
285        RepoPath::parse(s).unwrap()
286    }
287
288    fn edge(from: &str, to: &str) -> RawEdge {
289        RawEdge {
290            from: p(from),
291            kind: EdgeKind::Links,
292            written: to.into(),
293            to: NodeKey::Path(p(to)),
294            rel: "relates-to".into(),
295            region: None,
296            line: None,
297            note: None,
298        }
299    }
300
301    fn shown(mut edges: Vec<RawEdge>) -> Vec<String> {
302        edges.sort_by(|a, b| (&a.from, &a.to).cmp(&(&b.from, &b.to)));
303        edges
304            .iter()
305            .map(|e| format!("{} {}", e.from, e.to.as_str()))
306            .collect()
307    }
308
309    // sokf-tests: CACHE-1_AC-38
310    #[test]
311    fn the_store_gives_the_edges_near_paths_and_the_run_answers_for_its_checks() {
312        let root = RepoRoot::new(std::env::temp_dir());
313        let cache = Cache::open(&root, CacheMode::Off);
314        // The last run stored four edges: one from `/a.md`, one from `/c.md`
315        // to `/a.md`, one from `/d.md` to a file under `/src`, and one from
316        // `/e.md`. Since that run, `/a.md` has changed and the file `/e.md`
317        // has been removed.
318        cache.record_edges(&p("/a.md"), vec![edge("/a.md", "/old.md")]);
319        cache.record_edges(&p("/c.md"), vec![edge("/c.md", "/a.md")]);
320        cache.record_edges(&p("/d.md"), vec![edge("/d.md", "/src/x.rs")]);
321        cache.record_edges(&p("/e.md"), vec![edge("/e.md", "/a.md")]);
322        cache.commit();
323        // The current run has checked `/a.md`, but hasn't committed yet.
324        {
325            let mut state = cache.state.borrow_mut();
326            state.edges.clear();
327            state.removed.push(p("/e.md"));
328        }
329        cache.record_edges(&p("/a.md"), vec![edge("/a.md", "/b.md")]);
330        let at: BTreeSet<RepoPath> = [p("/a.md")].into();
331        assert_eq!(shown(cache.touching(&at)), ["/a.md /b.md", "/c.md /a.md"]);
332        assert_eq!(shown(cache.touching(&[p("/b.md")].into())), ["/a.md /b.md"]);
333        assert_eq!(shown(cache.under(&p("/src"))), ["/d.md /src/x.rs"]);
334        assert_eq!(cache.under(&p("/sr")), [] as [RawEdge; 0]);
335        // Each query finds its rows through an index, and never scans a table.
336        for (sql, args) in [
337            (
338                format!("{COLUMNS} WHERE source = ?1 OR (target = ?1 AND missing = 0)"),
339                vec!["/a.md"],
340            ),
341            (
342                format!("{COLUMNS} WHERE target >= ?1 AND target < ?2 AND missing = 0"),
343                vec!["/src/", "/src0"],
344            ),
345        ] {
346            let plan: Vec<String> = cache
347                .conn()
348                .prepare(&format!("EXPLAIN QUERY PLAN {sql}"))
349                .unwrap()
350                .query_map(rusqlite::params_from_iter(args), |r| r.get::<_, String>(3))
351                .unwrap()
352                .flatten()
353                .collect();
354            assert!(
355                plan.iter().all(|l| !l.starts_with("SCAN")),
356                "{sql}: {plan:?}"
357            );
358        }
359        assert_eq!(
360            shown(cache.every()),
361            ["/a.md /b.md", "/c.md /a.md", "/d.md /src/x.rs"]
362        );
363    }
364}