Skip to main content

sokf_core/cache/
outputs.rs

1//! This module saves in the cache the results of a run's checks, so that the
2//! next run can read them back. It saves these results:
3//!
4//! - the output of each document's check
5//! - the queries of each check
6//! - the citations that each check resolved
7//! - whether each path probed outside the walk exists
8//! - the asset pairings
9//! - the key that each schema claims
10//! - the hash and fingerprint of the formats file
11//! - the current and former identity of each knowledge store
12
13use std::collections::{BTreeMap, BTreeSet};
14
15use rusqlite::params;
16
17use super::{Cache, conn::Conn, sync::SyncState};
18use crate::{
19    Finding, RepoPath,
20    check::Citation,
21    model::{IdentityRow, KeyEntry, KeyIndex, Query},
22};
23
24/// `CitationRow` is one citation as the cache keeps it, from `source` to
25/// `target`.
26#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
27pub struct CitationRow {
28    /// The cited document.
29    pub target: RepoPath,
30    /// The cited key, heading, or kept anchor, or `None` for the whole
31    /// document.
32    pub slug: Option<String>,
33    /// The citing document.
34    pub source: RepoPath,
35    /// The type of the citing document, or empty for a marker.
36    pub source_type: String,
37    /// The relationship of a marker, or `None` for a body link or an
38    /// include block.
39    pub rel: Option<String>,
40    /// The line of the citation.
41    pub line: usize,
42    /// Whether the citation is an include block.
43    pub include: bool,
44    /// Whether the citing document declares a `supersedes` link to the
45    /// target.
46    pub supersedes: bool,
47    /// Whether the citing document is archived or deprecated.
48    pub retired: bool,
49    /// Whether the citation is a declared `supersedes` entry.
50    pub declared: bool,
51}
52
53/// `CitedFact` holds the parts of one citation that the checks of its
54/// target depend on: when a fact changes, the run checks the target again.
55/// The fact leaves out the line of a body link, because no coverage finding
56/// reads it, but keeps the line of a marker, because the run reports a
57/// refused marker at its line. The pass of a deprecated document reads the
58/// body of each citing file, so a moved line checks it again.
59#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
60pub struct CitedFact {
61    /// The cited document.
62    pub target: RepoPath,
63    /// The cited key, heading, or kept anchor, or `None` for the whole
64    /// document.
65    pub slug: Option<String>,
66    /// The type of the citing document, or empty for a marker.
67    pub source_type: String,
68    /// The relationship of a marker, or `None` for a body link.
69    pub rel: Option<String>,
70    /// The line of a marker, or `None` for a body link.
71    pub line: Option<usize>,
72    /// Whether the citation is an include block.
73    pub include: bool,
74    /// Whether the citing document declares a `supersedes` link to the
75    /// target.
76    pub supersedes: bool,
77    /// Whether the citing document is archived or deprecated.
78    pub retired: bool,
79    /// Whether the citation is a declared `supersedes` entry.
80    pub declared: bool,
81}
82
83impl CitedFact {
84    /// `of` returns the parts of citation `c` of `target` that coverage
85    /// depends on.
86    pub fn of(target: &RepoPath, c: &Citation) -> Self {
87        CitedFact {
88            target: target.clone(),
89            slug: c.slug.clone(),
90            source_type: c.source_type.clone(),
91            rel: c.rel.clone(),
92            line: c.rel.as_ref().map(|_| c.line),
93            include: c.include,
94            supersedes: c.supersedes,
95            retired: c.retired,
96            declared: c.declared,
97        }
98    }
99}
100
101/// `AssetRow` is one asset pairing as the cache keeps it, so that a run can
102/// find the pairings that changed.
103#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
104pub struct AssetRow {
105    /// The knowledge store that holds the asset.
106    pub knowledge: usize,
107    /// The asset.
108    pub asset: RepoPath,
109    /// The sidecar, when the pairing has one.
110    pub sidecar: Option<RepoPath>,
111}
112
113/// `AdditionalRow` is one additional file as the cache keeps it, with the
114/// path of the schema whose glob governs the file, or none when no single
115/// schema does.
116#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
117pub struct AdditionalRow {
118    /// The file.
119    pub path: RepoPath,
120    /// The governing schema's path.
121    pub schema: Option<RepoPath>,
122}
123
124/// `SchemaRow` is one schema file as the cache keeps it. The row holds the
125/// key that the schema claims and the hash of the schema file. The key is
126/// either a type const or the path of the schema file.
127#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
128pub struct SchemaRow {
129    /// The knowledge store that holds the schema.
130    pub knowledge: usize,
131    /// The schema file.
132    pub path: RepoPath,
133    /// The key it claims.
134    pub key: String,
135    /// The hash of the file.
136    pub hash: u64,
137    /// The `additional-files` globs, one per line.
138    pub globs: String,
139    /// The `asset-files` globs, one per line.
140    pub asset_globs: String,
141    /// The names from the registry that the schema uses, one per line.
142    pub uses: String,
143    /// The line where the schema's body starts.
144    pub line: usize,
145    /// Which documents of the schema's type are archived, encoded by
146    /// `Archived::encode`.
147    pub archived: String,
148}
149
150impl Cache {
151    /// `identities_changed` reports whether the current and former
152    /// identities of the knowledge stores differ from the ones that the
153    /// cache recorded. The commit writes the new rows (CACHE-1_AC-11).
154    // sokf-implements: CACHE-1_AC-16
155    pub fn identities_changed(&self, rows: Vec<IdentityRow>) -> bool {
156        let old = self.conn().rows(
157            "SELECT root, identity, former FROM stores ORDER BY root",
158            [],
159            |r| {
160                Ok(IdentityRow {
161                    knowledge: r.get::<_, usize>(0)?,
162                    identity: r.get(1)?,
163                    former: r.get(2)?,
164                })
165            },
166        );
167        let changed = old != rows;
168        self.state.borrow_mut().identities = Some(rows);
169        changed
170    }
171
172    /// `formats_changed` returns the registry entries that an edit of the
173    /// formats file changed, or `None` when the file has the same hash as in
174    /// the last run. When the hash differs, `fingerprint` computes one hash for
175    /// each format and type of the current registry, and
176    /// `formats_changed` compares them with the `formats` rows of the cache.
177    /// The names whose hashes differ, and the names that were added or
178    /// removed, make up the returned set. The commit writes the new hash and
179    /// fingerprint (CACHE-1_AC-11).
180    // sokf-implements: CACHE-1_AC-17
181    pub fn formats_changed(
182        &self,
183        hash: u64,
184        fingerprint: impl FnOnce() -> Vec<(String, u64)>,
185    ) -> Option<BTreeSet<String>> {
186        let stored = self.conn().meta("formats_hash");
187        self.state.borrow_mut().formats_hash = Some(hash);
188        if stored == Some(hash) {
189            return None;
190        }
191        let mut old: BTreeMap<String, u64> = self
192            .conn()
193            .rows("SELECT name, hash FROM formats", [], |r| {
194                Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.cast_unsigned()))
195            })
196            .into_iter()
197            .collect();
198        let new = fingerprint();
199        let mut changed: BTreeSet<String> = BTreeSet::new();
200        for (name, hash) in &new {
201            if old.remove(name) != Some(*hash) {
202                changed.insert(name.clone());
203            }
204        }
205        changed.extend(old.into_keys());
206        self.state.borrow_mut().formats = Some(new);
207        Some(changed)
208    }
209
210    /// `schemas_changed` returns, as `(knowledge store, key)` pairs, the
211    /// keys whose schema file differs from the cached one. A key's schema
212    /// file is the file that claims the key. It differs when the schema
213    /// changed, was added or removed, or moved to another key. The commit
214    /// writes the new rows (CACHE-1_AC-11).
215    // sokf-implements: CACHE-1_AC-15
216    pub fn schemas_changed(&self, rows: Vec<SchemaRow>) -> BTreeSet<(usize, String)> {
217        let old: BTreeSet<SchemaRow> = self
218            .conn()
219            .rows(
220                "SELECT store, path, key, hash, globs, asset_globs, uses, line, archived \
221                 FROM schemas",
222                [],
223                |r| {
224                    let Some(path) = RepoPath::parse(&r.get::<_, String>(1)?) else {
225                        return Ok(None);
226                    };
227                    Ok(Some(SchemaRow {
228                        knowledge: r.get::<_, usize>(0)?,
229                        path,
230                        key: r.get(2)?,
231                        hash: r.get::<_, i64>(3)?.cast_unsigned(),
232                        globs: r.get(4)?,
233                        asset_globs: r.get(5)?,
234                        uses: r.get(6)?,
235                        line: r.get::<_, usize>(7)?,
236                        archived: r.get(8)?,
237                    }))
238                },
239            )
240            .into_iter()
241            .flatten()
242            .collect();
243        let new: BTreeSet<SchemaRow> = rows.iter().cloned().collect();
244        let changed = old
245            .symmetric_difference(&new)
246            .map(|r| (r.knowledge, r.key.clone()))
247            .collect();
248        self.state.borrow_mut().schemas = Some(rows);
249        changed
250    }
251
252    /// `additional_changed` returns the additional files whose governing
253    /// schema differs from the cached one: a glob started
254    /// or stopped matching the file, or another schema now governs it.
255    /// The commit writes the new rows (CACHE-1_AC-11).
256    // sokf-implements: CACHE-1_AC-15
257    // sokf-implements: CACHE-1_AC-20
258    pub fn additional_changed(&self, rows: Vec<AdditionalRow>) -> BTreeSet<RepoPath> {
259        let old: BTreeSet<AdditionalRow> = self
260            .conn()
261            .rows("SELECT path, schema FROM additional", [], |r| {
262                let schema = RepoPath::parse(&r.get::<_, String>(1)?);
263                Ok(RepoPath::parse(&r.get::<_, String>(0)?)
264                    .map(|path| AdditionalRow { path, schema }))
265            })
266            .into_iter()
267            .flatten()
268            .collect();
269        let new: BTreeSet<AdditionalRow> = rows.iter().cloned().collect();
270        let changed = old
271            .symmetric_difference(&new)
272            .map(|r| r.path.clone())
273            .collect();
274        self.state.borrow_mut().additional = Some(rows);
275        changed
276    }
277
278    /// `readers_of` returns every reader of any of `queries`, as the cache
279    /// recorded them. The `queries` table interns each query key and each
280    /// reader's path, and the `deps` table pairs their ids.
281    pub fn readers_of(&self, queries: &BTreeSet<String>) -> BTreeSet<RepoPath> {
282        let mut readers = BTreeSet::new();
283        let Ok(mut stmt) = self.conn().prepare(
284            "SELECT r.key FROM deps d JOIN queries r ON r.id = d.reader \
285             WHERE d.query = (SELECT id FROM queries WHERE key = ?1)",
286        ) else {
287            return readers;
288        };
289        for q in queries {
290            let Ok(rows) = stmt.query_map([q.as_str()], |r| r.get::<_, String>(0)) else {
291                continue;
292            };
293            for reader in rows.flatten() {
294                if let Some(p) = RepoPath::parse(&reader) {
295                    readers.insert(p);
296                }
297            }
298        }
299        readers
300    }
301
302    /// `history_queries` returns the key of each query of the history
303    /// that a stored check read, one for each commit that `HEAD` named
304    /// (CACHE-1_AC-97).
305    pub fn history_queries(&self) -> BTreeSet<String> {
306        let start = crate::model::HISTORY_PREFIX;
307        // The keys of the prefix lie between it and the prefix with its
308        // last byte raised, so that the index of the keys finds them. The
309        // prefix is ASCII, so the raised byte is a character.
310        let (stem, last) = start.split_at(start.len() - 1);
311        let end = format!("{stem}{}", char::from(last.as_bytes()[0] + 1));
312        self.conn()
313            .rows(
314                "SELECT q.key FROM queries q WHERE q.key >= ?1 AND q.key < ?2 \
315                 AND EXISTS (SELECT 1 FROM deps d WHERE d.query = q.id)",
316                [start, end.as_str()],
317                |r| r.get::<_, String>(0),
318            )
319            .into_iter()
320            .collect()
321    }
322
323    /// `record_output` keeps the output of one check for the commit to
324    /// write.
325    pub fn record_output(&self, path: &RepoPath, findings: Vec<Finding>) {
326        self.state
327            .borrow_mut()
328            .outputs
329            .insert(path.clone(), findings);
330    }
331
332    /// `record_deps` keeps the queries that one check made for the commit
333    /// to write.
334    pub fn record_deps(&self, path: &RepoPath, queries: &BTreeSet<Query>) {
335        self.state
336            .borrow_mut()
337            .deps
338            .insert(path.clone(), queries.iter().map(Query::key).collect());
339    }
340
341    /// `record_unsettled` adds to the queries of each of `paths`, which the
342    /// run checked, the query that every run checks again, because each
343    /// holds a text that the formatter left unsettled (CACHE-2_AC-9).
344    pub fn record_unsettled<'a>(&self, paths: impl Iterator<Item = &'a RepoPath>) {
345        let mut state = self.state.borrow_mut();
346        for path in paths {
347            if let Some(deps) = state.deps.get_mut(path) {
348                deps.insert(Query::Unsettled.key());
349            }
350        }
351    }
352
353    /// `record_citations` keeps the citations that one document resolved
354    /// for the commit to write.
355    pub fn record_citations(&self, source: &RepoPath, rows: Vec<CitationRow>) {
356        self.state
357            .borrow_mut()
358            .citations
359            .insert(source.clone(), rows);
360    }
361
362    /// `record_keys_of` records the keys that each document in `checked`
363    /// declares in this run, and the anchors that the engine keeps in the
364    /// document. The commit writes them in place of the document's rows in the
365    /// cache.
366    pub fn record_keys_of(&self, keys: &KeyIndex, checked: &BTreeSet<RepoPath>) {
367        let mut rows: BTreeMap<RepoPath, Vec<KeyEntry>> =
368            checked.iter().map(|p| (p.clone(), Vec::new())).collect();
369        for entries in keys.document.values() {
370            for e in entries {
371                if let Some(list) = rows.get_mut(&e.path) {
372                    list.push(e.clone());
373                }
374            }
375        }
376        for list in rows.values_mut() {
377            list.sort_by(|a, b| (a.line, &a.key).cmp(&(b.line, &b.key)));
378        }
379        let anchors = checked
380            .iter()
381            .map(|p| (p.clone(), keys.anchors.get(p).cloned().unwrap_or_default()));
382        let mut state = self.state.borrow_mut();
383        state.keys_of.extend(rows);
384        state.anchors_of.extend(anchors);
385    }
386
387    /// `record_probe` records what a path outside the walk names on disk,
388    /// nothing, a file, or a directory, so that the commit can write it. The
389    /// next sync checks the path with stat again.
390    pub fn record_probe(&self, path: &RepoPath, on_disk: crate::walk::OnDisk) {
391        self.state.borrow_mut().probes.insert(path.clone(), on_disk);
392    }
393
394    /// `record_assets` keeps the asset pairings of this run for the commit
395    /// to write.
396    pub fn record_assets(&self, rows: Vec<AssetRow>) {
397        self.state.borrow_mut().assets = Some(rows);
398    }
399
400    /// `assets_changed` returns the paths whose pairing differs from the
401    /// cached one. Such a path is an asset or a sidecar that gained, lost,
402    /// or changed its partner.
403    pub fn assets_changed(&self, rows: &[AssetRow]) -> BTreeSet<RepoPath> {
404        let old: BTreeSet<AssetRow> = self
405            .conn()
406            .rows("SELECT store, asset, sidecar FROM assets", [], |r| {
407                let knowledge = r.get::<_, usize>(0)?;
408                let sidecar = r.get::<_, Option<String>>(2)?;
409                Ok(
410                    RepoPath::parse(&r.get::<_, String>(1)?).map(|asset| AssetRow {
411                        knowledge,
412                        asset,
413                        sidecar: sidecar.and_then(|s| RepoPath::parse(&s)),
414                    }),
415                )
416            })
417            .into_iter()
418            .flatten()
419            .collect();
420        let new: BTreeSet<AssetRow> = rows.iter().cloned().collect();
421        let mut changed = BTreeSet::new();
422        for row in old.symmetric_difference(&new) {
423            changed.insert(row.asset.clone());
424            if let Some(s) = &row.sidecar {
425                changed.insert(s.clone());
426            }
427        }
428        changed
429    }
430
431    /// `probes_changed` returns the probed paths whose existence, or whose
432    /// kind, a file or a directory, changed after the cache recorded it.
433    pub fn probes_changed(&self, root: &crate::RepoRoot) -> BTreeSet<RepoPath> {
434        self.conn()
435            .rows("SELECT path, exists_ FROM probes", [], |r| {
436                Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?))
437            })
438            .into_iter()
439            .filter_map(|(path, answered)| {
440                RepoPath::parse(&path)
441                    .filter(|p| crate::walk::OnDisk::at(&p.to_fs(root)).code() != answered)
442            })
443            .collect()
444    }
445
446    /// `stored_citations_of` returns the citations of `target` that the
447    /// cache holds, except those from removed files and from the sources in
448    /// `excluding`. This run resolves the citations of those sources again.
449    pub fn stored_citations_of(
450        &self,
451        target: &RepoPath,
452        excluding: &BTreeSet<RepoPath>,
453    ) -> Vec<Citation> {
454        let removed = self.removed_set();
455        self.conn()
456            .rows(
457                "SELECT slug, source, source_type, rel, line, include, supersedes, retired, \
458                 declared FROM citations WHERE target = ?1",
459                [target.as_str()],
460                |r| {
461                    let Some(source) = RepoPath::parse(&r.get::<_, String>(1)?) else {
462                        return Ok(None);
463                    };
464                    Ok(Some(Citation {
465                        slug: r.get(0)?,
466                        source,
467                        source_type: r.get(2)?,
468                        rel: r.get(3)?,
469                        line: r.get::<_, usize>(4)?,
470                        include: r.get::<_, i64>(5)? != 0,
471                        supersedes: r.get::<_, i64>(6)? != 0,
472                        retired: r.get::<_, i64>(7)? != 0,
473                        declared: r.get::<_, i64>(8)? != 0,
474                    }))
475                },
476            )
477            .into_iter()
478            .flatten()
479            .filter(|c| !excluding.contains(&c.source) && !removed.contains(&c.source))
480            .collect()
481    }
482
483    /// `old_citation_targets` returns the targets that `source` cited, as
484    /// the cache recorded them.
485    pub fn old_citation_targets(&self, source: &RepoPath) -> BTreeSet<RepoPath> {
486        self.old_citations(source)
487            .into_iter()
488            .map(|c| c.target)
489            .collect()
490    }
491
492    /// `old_citations` returns what `source` cited, as the cache recorded
493    /// it.
494    pub fn old_citations(&self, source: &RepoPath) -> BTreeSet<CitedFact> {
495        self.conn()
496            .rows(
497                "SELECT target, slug, source_type, rel, line, include, supersedes, retired, \
498                 declared FROM citations WHERE source = ?1",
499                [source.as_str()],
500                |r| {
501                    let Some(target) = RepoPath::parse(&r.get::<_, String>(0)?) else {
502                        return Ok(None);
503                    };
504                    let rel: Option<String> = r.get(3)?;
505                    let line = r.get::<_, usize>(4)?;
506                    Ok(Some(CitedFact {
507                        target,
508                        slug: r.get(1)?,
509                        source_type: r.get(2)?,
510                        line: rel.as_ref().map(|_| line),
511                        rel,
512                        include: r.get::<_, i64>(5)? != 0,
513                        supersedes: r.get::<_, i64>(6)? != 0,
514                        retired: r.get::<_, i64>(7)? != 0,
515                        declared: r.get::<_, i64>(8)? != 0,
516                    }))
517                },
518            )
519            .into_iter()
520            .flatten()
521            .collect()
522    }
523
524    /// `stored_outputs` returns the stored findings of every document
525    /// except those in `except`, whose checks this run ran (CLI-4_AC-20).
526    pub fn stored_outputs(&self, except: &BTreeSet<RepoPath>) -> Vec<Finding> {
527        self.conn()
528            .rows(
529                "SELECT path, findings FROM outputs WHERE has_findings = 1",
530                [],
531                |r| Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?)),
532            )
533            .into_iter()
534            .filter(|(path, _)| RepoPath::parse(path).is_some_and(|p| !except.contains(&p)))
535            .filter_map(|(_, json)| serde_json::from_slice::<Vec<Finding>>(&json).ok())
536            .flatten()
537            .collect()
538    }
539
540    /// `commit_outputs` writes what the run recorded, inside the commit's
541    /// transaction. It writes the outputs, queries, citations, edges, keys,
542    /// kept anchors, and probes, and it replaces all the rows of each checked
543    /// document.
544    /// It also writes the asset pairings, the schemas, the fingerprint of
545    /// the formats file, the additional files, the identities of the
546    /// knowledge stores, and the hash of the formats file.
547    // sokf-implements: CACHE-1_AC-14
548    pub(super) fn commit_outputs(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
549        Self::delete_gone(conn, state)?;
550        Self::commit_edges(conn, state)?;
551        Self::commit_findings(conn, state)?;
552        Self::commit_deps(conn, state)?;
553        Self::commit_citations(conn, state)?;
554        Self::commit_keys(conn, state)?;
555        Self::commit_probes(conn, state)?;
556        Self::commit_assets(conn, state)?;
557        Self::commit_schemas(conn, state)?;
558        Self::commit_formats(conn, state)?;
559        Self::commit_additional(conn, state)?;
560        Self::commit_identities(conn, state)?;
561        if let Some(v) = state.formats_hash {
562            conn.put_meta("formats_hash", &v)?;
563        }
564        Ok(())
565    }
566
567    /// `delete_gone` deletes the outputs, dependencies, citations, edges,
568    /// keys, kept anchors, and probes of each file that the walk no longer
569    /// lists.
570    fn delete_gone(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
571        let mut gone: Vec<&str> = state.removed.iter().map(RepoPath::as_str).collect();
572        // When a directory is removed, the commit also deletes the rows of
573        // its index. If the directory never had an index, the deletes match
574        // no rows.
575        let gone_indexes: Vec<String> = state
576            .dirs_removed
577            .iter()
578            .map(|d| format!("{d}/index.md"))
579            .collect();
580        gone.extend(gone_indexes.iter().map(String::as_str));
581        for path in gone {
582            for sql in [
583                "DELETE FROM outputs WHERE path = ?1",
584                "DELETE FROM deps WHERE reader = (SELECT id FROM queries WHERE key = ?1)",
585                "DELETE FROM citations WHERE source = ?1",
586                "DELETE FROM edges WHERE source = ?1",
587                "DELETE FROM keys WHERE path = ?1",
588                "DELETE FROM anchors WHERE path = ?1",
589                "DELETE FROM probes WHERE path = ?1",
590            ] {
591                conn.execute(sql, [path])?;
592            }
593        }
594        Ok(())
595    }
596
597    /// `commit_findings` writes the findings of each check that the run ran.
598    fn commit_findings(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
599        let mut put_output = conn.prepare(
600            "INSERT OR REPLACE INTO outputs (path, findings, has_findings) VALUES (?1, ?2, ?3)",
601        )?;
602        for (path, findings) in &state.outputs {
603            let json = serde_json::to_vec(findings).unwrap_or_default();
604            put_output.execute(params![path.as_str(), json, !findings.is_empty()])?;
605        }
606        Ok(())
607    }
608
609    /// `commit_deps` writes the queries that each checked document read, in
610    /// place of the document's stored dependencies.
611    fn commit_deps(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
612        // The `queries` table interns each reader's path and each query key
613        // once, so the `deps` table stores each dependency as a pair of
614        // integer ids.
615        let mut add_key = conn.prepare("INSERT OR IGNORE INTO queries (key) VALUES (?1)")?;
616        let mut id_of = conn.prepare("SELECT id FROM queries WHERE key = ?1")?;
617        let mut intern = |key: &str| -> rusqlite::Result<i64> {
618            add_key.execute([key])?;
619            id_of.query_row([key], |r| r.get::<_, i64>(0))
620        };
621        let mut del_deps = conn.prepare("DELETE FROM deps WHERE reader = ?1")?;
622        let mut put_dep =
623            conn.prepare("INSERT OR IGNORE INTO deps (reader, query) VALUES (?1, ?2)")?;
624        for (reader, queries) in &state.deps {
625            let rid = intern(reader.as_str())?;
626            del_deps.execute([rid])?;
627            for q in queries {
628                let qid = intern(q)?;
629                put_dep.execute([rid, qid])?;
630            }
631        }
632        Ok(())
633    }
634
635    /// `commit_citations` writes the citations of each checked document, in
636    /// place of the document's stored citations.
637    fn commit_citations(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
638        let mut del_cit = conn.prepare("DELETE FROM citations WHERE source = ?1")?;
639        let mut put_cit = conn.prepare(
640            "INSERT INTO citations (target, slug, source, source_type, rel, line, include, \
641             supersedes, retired, declared) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
642        )?;
643        for (source, rows) in &state.citations {
644            del_cit.execute([source.as_str()])?;
645            for c in rows {
646                put_cit.execute(params![
647                    c.target.as_str(),
648                    c.slug,
649                    c.source.as_str(),
650                    c.source_type,
651                    c.rel,
652                    c.line,
653                    i64::from(c.include),
654                    i64::from(c.supersedes),
655                    i64::from(c.retired),
656                    i64::from(c.declared)
657                ])?;
658            }
659        }
660        Ok(())
661    }
662
663    /// `commit_probes` writes whether each path that the run probed exists.
664    fn commit_probes(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
665        let mut put_probe =
666            conn.prepare("INSERT OR REPLACE INTO probes (path, exists_) VALUES (?1, ?2)")?;
667        for (path, on_disk) in &state.probes {
668            put_probe.execute(params![path.as_str(), on_disk.code()])?;
669        }
670        Ok(())
671    }
672
673    /// `commit_assets` replaces the stored asset pairings with those that the
674    /// run recorded, if it recorded them.
675    fn commit_assets(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
676        if let Some(assets) = &state.assets {
677            conn.execute_batch("DELETE FROM assets")?;
678            let mut put =
679                conn.prepare("INSERT INTO assets (store, asset, sidecar) VALUES (?1, ?2, ?3)")?;
680            for a in assets {
681                put.execute(params![
682                    a.knowledge,
683                    a.asset.as_str(),
684                    a.sidecar.as_ref().map(RepoPath::as_str)
685                ])?;
686            }
687        }
688        Ok(())
689    }
690
691    /// `commit_schemas` replaces the stored schemas with those that the run
692    /// recorded, if it recorded them.
693    fn commit_schemas(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
694        if let Some(schemas) = &state.schemas {
695            conn.execute_batch("DELETE FROM schemas")?;
696            let mut put = conn.prepare(
697                "INSERT OR REPLACE INTO schemas (path, store, key, hash, globs, asset_globs, \
698                 uses, line, archived) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
699            )?;
700            for s in schemas {
701                put.execute(params![
702                    s.path.as_str(),
703                    s.knowledge,
704                    s.key,
705                    s.hash.cast_signed(),
706                    s.globs,
707                    s.asset_globs,
708                    s.uses,
709                    s.line,
710                    s.archived
711                ])?;
712            }
713        }
714        Ok(())
715    }
716
717    /// `commit_formats` replaces the stored fingerprint of the formats file
718    /// with the one that the run recorded, if it recorded one.
719    fn commit_formats(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
720        if let Some(formats) = &state.formats {
721            conn.execute_batch("DELETE FROM formats")?;
722            let mut put = conn.prepare("INSERT INTO formats (name, hash) VALUES (?1, ?2)")?;
723            for (name, hash) in formats {
724                put.execute(params![name, hash.cast_signed()])?;
725            }
726        }
727        Ok(())
728    }
729
730    /// `commit_additional` replaces the stored additional files with those
731    /// that the run recorded, if it recorded them.
732    fn commit_additional(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
733        if let Some(additional) = &state.additional {
734            conn.execute_batch("DELETE FROM additional")?;
735            let mut put = conn.prepare("INSERT INTO additional (path, schema) VALUES (?1, ?2)")?;
736            for a in additional {
737                put.execute(params![
738                    a.path.as_str(),
739                    a.schema.as_ref().map_or("", RepoPath::as_str)
740                ])?;
741            }
742        }
743        Ok(())
744    }
745
746    /// `commit_identities` replaces the stored identities of the knowledge
747    /// stores with those that the run recorded, if it recorded them.
748    fn commit_identities(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
749        if let Some(identities) = &state.identities {
750            conn.execute_batch("DELETE FROM stores")?;
751            let mut put =
752                conn.prepare("INSERT INTO stores (root, identity, former) VALUES (?1, ?2, ?3)")?;
753            for row in identities {
754                put.execute(params![row.knowledge, row.identity, row.former])?;
755            }
756        }
757        Ok(())
758    }
759}