1use 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#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct DocRow {
26 pub knowledge: usize,
28 pub id: Option<String>,
30 pub type_name: Option<String>,
32 pub title: Option<String>,
34 pub description: Option<String>,
36 pub broken: bool,
40 pub visible: u64,
42 pub scalars: String,
46}
47impl DocRow {
50 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 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 pub fn record_row(&self, path: &RepoPath, row: DocRow) {
91 self.state.borrow_mut().rows.insert(path.clone(), row);
92 }
93
94 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 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 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 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 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 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 #[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 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 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}