1use 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
27pub struct CitationRow {
28 pub target: RepoPath,
30 pub slug: Option<String>,
33 pub source: RepoPath,
35 pub source_type: String,
37 pub rel: Option<String>,
40 pub line: usize,
42 pub include: bool,
44 pub supersedes: bool,
47 pub retired: bool,
49 pub declared: bool,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
60pub struct CitedFact {
61 pub target: RepoPath,
63 pub slug: Option<String>,
66 pub source_type: String,
68 pub rel: Option<String>,
70 pub line: Option<usize>,
72 pub include: bool,
74 pub supersedes: bool,
77 pub retired: bool,
79 pub declared: bool,
81}
82
83impl CitedFact {
84 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
104pub struct AssetRow {
105 pub knowledge: usize,
107 pub asset: RepoPath,
109 pub sidecar: Option<RepoPath>,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
117pub struct AdditionalRow {
118 pub path: RepoPath,
120 pub schema: Option<RepoPath>,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
128pub struct SchemaRow {
129 pub knowledge: usize,
131 pub path: RepoPath,
133 pub key: String,
135 pub hash: u64,
137 pub globs: String,
139 pub asset_globs: String,
141 pub uses: String,
143 pub line: usize,
145 pub archived: String,
148}
149
150impl Cache {
151 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 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 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 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 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 pub fn history_queries(&self) -> BTreeSet<String> {
306 let start = crate::model::HISTORY_PREFIX;
307 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 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 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 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 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 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 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 pub fn record_assets(&self, rows: Vec<AssetRow>) {
397 self.state.borrow_mut().assets = Some(rows);
398 }
399
400 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 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 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 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 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 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 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 fn delete_gone(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
571 let mut gone: Vec<&str> = state.removed.iter().map(RepoPath::as_str).collect();
572 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 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 fn commit_deps(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
612 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 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 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 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 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 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 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 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}