Skip to main content

sokf_core/cache/
rows.rs

1//! The store keeps, between runs, one row of metadata for each document,
2//! with the ids that the document declares and the keys that it captures
3//! (CACHE-1_AC-13). The row holds what the store knows of a document
4//! without reading its file. A check reads every other fact of the
5//! document from the file when it needs it.
6
7use std::collections::BTreeSet;
8
9use rusqlite::params;
10
11use super::{Cache, conn::Conn, sync::SyncState};
12use crate::{
13    Document, RepoPath,
14    grammar::KeyScope,
15    model::{KeyEntry, KeyIndex},
16    source::Fnv,
17};
18
19// sokf:begin row
20/// `DocRow` is what the store keeps of one document besides its
21/// relationships (CACHE-1_AC-13). It holds the fields that an index lists,
22/// whether the document is broken, and the hash of the document's parts
23/// read by other documents. It holds no text of the document.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct DocRow {
26    /// The knowledge store that holds the document.
27    pub knowledge: usize,
28    /// The document's `id`.
29    pub id: Option<String>,
30    /// The document's `type`.
31    pub type_name: Option<String>,
32    /// The document's `title`.
33    pub title: Option<String>,
34    /// The document's `description`.
35    pub description: Option<String>,
36    /// Whether the document's frontmatter is missing or doesn't parse.
37    /// Such a document has no readable type, so `new` refuses to choose
38    /// the next sequence number while the store holds a broken document.
39    pub broken: bool,
40    /// The hash of the parts of the document that other documents read.
41    pub visible: u64,
42    /// The row keeps the scalar frontmatter values, as `encode_scalars`
43    /// writes them, so that the store knows a document's lifecycle state
44    /// without reading its file.
45    pub scalars: String,
46}
47// sokf:end row
48
49impl DocRow {
50    /// `of` returns the row of `doc` in the knowledge store `knowledge`.
51    // sokf-implements: CACHE-1_AC-13
52    pub fn of(knowledge: usize, doc: &Document) -> DocRow {
53        DocRow {
54            knowledge,
55            id: doc.core.id.clone(),
56            type_name: doc.core.type_.clone(),
57            title: doc.core.title.clone(),
58            description: doc.core.description.clone(),
59            broken: !doc.core.present,
60            visible: doc.visible_hash(),
61            scalars: crate::model::archive::encode_scalars(&crate::model::archive::scalars(doc)),
62        }
63    }
64
65    /// `hash` returns the hash of the row, so that the commit doesn't
66    /// rewrite a row that the store already holds.
67    pub fn hash(&self) -> u64 {
68        let mut h = Fnv::new();
69        h.update(&(self.knowledge as u64).to_le_bytes());
70        for field in [&self.id, &self.type_name, &self.title, &self.description] {
71            match field {
72                Some(s) => {
73                    h.update(&[1]);
74                    h.update(s.as_bytes());
75                }
76                None => h.update(&[0]),
77            }
78            h.update(&[0xFF]);
79        }
80        h.update(&[u8::from(self.broken)]);
81        h.update(&self.visible.to_le_bytes());
82        h.update(self.scalars.as_bytes());
83        h.finish()
84    }
85}
86
87impl Cache {
88    /// `record_row` keeps the row of a document that this run read. The
89    /// commit writes the row when it differs from the store's.
90    pub fn record_row(&self, path: &RepoPath, row: DocRow) {
91        self.state.borrow_mut().rows.insert(path.clone(), row);
92    }
93
94    /// `old_row` returns the row that the store held for `path` before this
95    /// run.
96    pub fn old_row(&self, path: &RepoPath) -> Option<DocRow> {
97        self.conn()
98            .query_row(
99                "SELECT store, id, type, title, description, broken, visible_hash, scalars \
100                 FROM documents WHERE path = ?1",
101                [path.as_str()],
102                |r| {
103                    Ok(DocRow {
104                        knowledge: r.get::<_, usize>(0)?,
105                        id: r.get(1)?,
106                        type_name: r.get(2)?,
107                        title: r.get(3)?,
108                        description: r.get(4)?,
109                        broken: r.get::<_, i64>(5)? != 0,
110                        visible: r.get::<_, i64>(6)?.cast_unsigned(),
111                        scalars: r.get(7)?,
112                    })
113                },
114            )
115            .ok()
116    }
117
118    /// `stored_keys_for` returns the keys that the store holds for the given
119    /// slugs, from the documents that cite or capture them, and the anchors
120    /// with those slugs that the engine keeps. It leaves out the rows of the
121    /// documents that this run removed, and the rows of the documents in
122    /// `except`, whose keys this run captured.
123    pub fn stored_keys_for(
124        &self,
125        slugs: &BTreeSet<String>,
126        except: &BTreeSet<RepoPath>,
127    ) -> KeyIndex {
128        let mut index = KeyIndex::default();
129        let removed = self.removed_set();
130        let Ok(mut stmt) = self.conn().prepare(
131            "SELECT path, key, line, heading_slug, holds_anchor, scope, knowledge, rule_id FROM keys \
132             WHERE slug = ?1 ORDER BY path, line, key",
133        ) else {
134            return index;
135        };
136        for slug in slugs {
137            let Ok(rows) = stmt.query_map([slug.as_str()], |r| {
138                Ok((
139                    r.get::<_, String>(0)?,
140                    r.get::<_, String>(1)?,
141                    r.get::<_, usize>(2)?,
142                    r.get::<_, Option<String>>(3)?,
143                    r.get::<_, bool>(4)?,
144                    r.get::<_, String>(5)?,
145                    r.get::<_, usize>(6)?,
146                    r.get::<_, Option<String>>(7)?,
147                ))
148            }) else {
149                continue;
150            };
151            for (path, key, line, heading_slug, holds_anchor, scope, knowledge, rule_id) in
152                rows.flatten()
153            {
154                let Some(path) = RepoPath::parse(&path) else {
155                    continue;
156                };
157                if removed.contains(&path) || except.contains(&path) {
158                    continue;
159                }
160                index.add(KeyEntry {
161                    id: slug.clone(),
162                    key,
163                    path,
164                    line,
165                    heading_slug,
166                    holds_anchor,
167                    scope: match scope.as_str() {
168                        "document" => KeyScope::Document,
169                        host => KeyScope::Host(host.to_string()),
170                    },
171                    knowledge,
172                    rule_id,
173                });
174            }
175        }
176        let Ok(mut stmt) = self
177            .conn()
178            .prepare("SELECT path FROM anchors WHERE slug = ?1")
179        else {
180            return index;
181        };
182        for slug in slugs {
183            let Ok(rows) = stmt.query_map([slug.as_str()], |r| r.get::<_, String>(0)) else {
184                continue;
185            };
186            for path in rows.flatten().filter_map(|p| RepoPath::parse(&p)) {
187                if !removed.contains(&path) && !except.contains(&path) {
188                    index.add_anchor(path, slug.clone());
189                }
190            }
191        }
192        index
193    }
194
195    /// `old_keys_of` returns the keys that the document at `path` declares,
196    /// as the cache recorded them, each as `(scope, slug, knowledge)`.
197    pub fn old_keys_of(&self, path: &RepoPath) -> BTreeSet<(String, String, usize)> {
198        self.conn()
199            .rows(
200                "SELECT scope, slug, knowledge FROM keys WHERE path = ?1",
201                [path.as_str()],
202                |r| {
203                    Ok((
204                        r.get::<_, String>(0)?,
205                        r.get::<_, String>(1)?,
206                        r.get::<_, usize>(2)?,
207                    ))
208                },
209            )
210            .into_iter()
211            .collect()
212    }
213
214    /// `old_anchors_of` returns the slugs of the anchors that the engine
215    /// keeps in the document at `path`, as the cache recorded them.
216    pub fn old_anchors_of(&self, path: &RepoPath) -> BTreeSet<String> {
217        self.conn()
218            .rows(
219                "SELECT slug FROM anchors WHERE path = ?1",
220                [path.as_str()],
221                |r| r.get::<_, String>(0),
222            )
223            .into_iter()
224            .collect()
225    }
226
227    /// `commit_keys` writes the keys and the kept anchors of each checked
228    /// document, in place of the document's stored ones.
229    pub(super) fn commit_keys(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
230        let mut del_keys = conn.prepare("DELETE FROM keys WHERE path = ?1")?;
231        let mut put_key = conn.prepare(
232            "INSERT INTO keys (path, key, slug, line, heading_slug, holds_anchor, scope, knowledge, \
233             rule_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
234        )?;
235        for (path, entries) in &state.keys_of {
236            del_keys.execute([path.as_str()])?;
237            for e in entries {
238                let scope = match &e.scope {
239                    crate::grammar::KeyScope::Document => "document".to_string(),
240                    crate::grammar::KeyScope::Host(h) => h.clone(),
241                };
242                put_key.execute(params![
243                    path.as_str(),
244                    e.key,
245                    e.id,
246                    e.line,
247                    e.heading_slug,
248                    e.holds_anchor,
249                    scope,
250                    e.knowledge,
251                    e.rule_id
252                ])?;
253            }
254        }
255        let mut del_anchors = conn.prepare("DELETE FROM anchors WHERE path = ?1")?;
256        let mut put_anchor = conn.prepare("INSERT INTO anchors (path, slug) VALUES (?1, ?2)")?;
257        for (path, slugs) in &state.anchors_of {
258            del_anchors.execute([path.as_str()])?;
259            for slug in slugs {
260                put_anchor.execute(params![path.as_str(), slug])?;
261            }
262        }
263        Ok(())
264    }
265
266    /// `commit_rows` writes the rows and ids of the run inside the commit's
267    /// transaction.
268    pub(super) fn commit_rows(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
269        let mut delete_doc = conn.prepare("DELETE FROM documents WHERE path = ?1")?;
270        let mut delete_ids = conn.prepare("DELETE FROM ids WHERE path = ?1")?;
271        let mut insert_doc = conn.prepare(
272            "INSERT OR REPLACE INTO documents (path, store, id, type, title, description, \
273             broken, visible_hash, scalars) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
274        )?;
275        let mut insert_id =
276            conn.prepare("INSERT OR IGNORE INTO ids (store, id, path) VALUES (?1, ?2, ?3)")?;
277        for path in &state.removed {
278            delete_doc.execute([path.as_str()])?;
279            delete_ids.execute([path.as_str()])?;
280        }
281        for (path, row) in &state.rows {
282            let known = state
283                .known
284                .get(path)
285                .and_then(|k| k.as_ref())
286                .and_then(|k| k.row_hash);
287            if known == Some(row.hash()) {
288                continue;
289            }
290            delete_ids.execute([path.as_str()])?;
291            insert_doc.execute(params![
292                path.as_str(),
293                row.knowledge,
294                row.id,
295                row.type_name,
296                row.title,
297                row.description,
298                i64::from(row.broken),
299                row.visible.cast_signed(),
300                row.scalars,
301            ])?;
302            if let Some(id) = &row.id {
303                insert_id.execute(params![row.knowledge, id, path.as_str()])?;
304            }
305        }
306        Ok(())
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use crate::{Source, model::ParseMode};
314
315    fn doc(text: &str) -> Document {
316        let source = Source::from_text(RepoPath::parse("/k/a.md").unwrap(), text);
317        let parsed = crate::model::parse_source(&source, ParseMode::Document);
318        Document::new(source, parsed)
319    }
320
321    // sokf-tests: CACHE-1_AC-13
322    #[test]
323    fn a_row_carries_the_fields_and_the_hash_and_no_text() {
324        let full = doc("---\ntype: A\nid: a\ntitle: T\ndescription: D\n---\n\n# T\n\nBody.\n");
325        let row = DocRow::of(2, &full);
326        assert_eq!(row.knowledge, 2);
327        assert_eq!(row.id.as_deref(), Some("a"));
328        assert_eq!(row.type_name.as_deref(), Some("A"));
329        assert_eq!(row.title.as_deref(), Some("T"));
330        assert_eq!(row.description.as_deref(), Some("D"));
331        assert!(!row.broken);
332        assert_eq!(row.visible, full.visible_hash());
333        // A body edit changes neither the row nor its hash.
334        let edited = doc("---\ntype: A\nid: a\ntitle: T\ndescription: D\n---\n\n# T\n\nMore.\n");
335        assert_eq!(DocRow::of(2, &edited), row);
336        assert_eq!(DocRow::of(2, &edited).hash(), row.hash());
337        // A title edit changes both. A document whose frontmatter is
338        // missing or doesn't parse is broken, as it is for `new`.
339        let retitled = doc("---\ntype: A\nid: a\ntitle: U\ndescription: D\n---\n\n# T\n");
340        assert_ne!(DocRow::of(2, &retitled).hash(), row.hash());
341        assert!(DocRow::of(2, &doc("---\n: [\n---\n\n# T\n")).broken);
342        assert!(DocRow::of(2, &doc("# No frontmatter\n")).broken);
343    }
344}