use std::collections::BTreeSet;
use rusqlite::params;
use super::{Cache, conn::Conn, sync::SyncState};
use crate::{
Document, RepoPath,
grammar::KeyScope,
model::{KeyEntry, KeyIndex},
source::Fnv,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocRow {
pub knowledge: usize,
pub id: Option<String>,
pub type_name: Option<String>,
pub title: Option<String>,
pub description: Option<String>,
pub broken: bool,
pub visible: u64,
pub scalars: String,
}
impl DocRow {
pub fn of(knowledge: usize, doc: &Document) -> DocRow {
DocRow {
knowledge,
id: doc.core.id.clone(),
type_name: doc.core.type_.clone(),
title: doc.core.title.clone(),
description: doc.core.description.clone(),
broken: !doc.core.present,
visible: doc.visible_hash(),
scalars: crate::model::archive::encode_scalars(&crate::model::archive::scalars(doc)),
}
}
pub fn hash(&self) -> u64 {
let mut h = Fnv::new();
h.update(&(self.knowledge as u64).to_le_bytes());
for field in [&self.id, &self.type_name, &self.title, &self.description] {
match field {
Some(s) => {
h.update(&[1]);
h.update(s.as_bytes());
}
None => h.update(&[0]),
}
h.update(&[0xFF]);
}
h.update(&[u8::from(self.broken)]);
h.update(&self.visible.to_le_bytes());
h.update(self.scalars.as_bytes());
h.finish()
}
}
impl Cache {
pub fn record_row(&self, path: &RepoPath, row: DocRow) {
self.state.borrow_mut().rows.insert(path.clone(), row);
}
pub fn old_row(&self, path: &RepoPath) -> Option<DocRow> {
self.conn()
.query_row(
"SELECT store, id, type, title, description, broken, visible_hash, scalars \
FROM documents WHERE path = ?1",
[path.as_str()],
|r| {
Ok(DocRow {
knowledge: r.get::<_, usize>(0)?,
id: r.get(1)?,
type_name: r.get(2)?,
title: r.get(3)?,
description: r.get(4)?,
broken: r.get::<_, i64>(5)? != 0,
visible: r.get::<_, i64>(6)?.cast_unsigned(),
scalars: r.get(7)?,
})
},
)
.ok()
}
pub fn stored_keys_for(
&self,
slugs: &BTreeSet<String>,
except: &BTreeSet<RepoPath>,
) -> KeyIndex {
let mut index = KeyIndex::default();
let removed = self.removed_set();
let Ok(mut stmt) = self.conn().prepare(
"SELECT path, key, line, heading_slug, scope, knowledge, rule_id FROM keys \
WHERE slug = ?1 ORDER BY path, line, key",
) else {
return index;
};
for slug in slugs {
let Ok(rows) = stmt.query_map([slug.as_str()], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, usize>(2)?,
r.get::<_, Option<String>>(3)?,
r.get::<_, String>(4)?,
r.get::<_, usize>(5)?,
r.get::<_, Option<String>>(6)?,
))
}) else {
continue;
};
for (path, key, line, heading_slug, scope, knowledge, rule_id) in rows.flatten() {
let Some(path) = RepoPath::parse(&path) else {
continue;
};
if removed.contains(&path) || except.contains(&path) {
continue;
}
index.add(KeyEntry {
key,
path,
line,
heading_slug,
scope: match scope.as_str() {
"document" => KeyScope::Document,
host => KeyScope::Host(host.to_string()),
},
knowledge,
rule_id,
});
}
}
index
}
pub(super) fn commit_rows(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
let mut delete_doc = conn.prepare("DELETE FROM documents WHERE path = ?1")?;
let mut delete_ids = conn.prepare("DELETE FROM ids WHERE path = ?1")?;
let mut insert_doc = conn.prepare(
"INSERT OR REPLACE INTO documents (path, store, id, type, title, description, \
broken, visible_hash, scalars) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
)?;
let mut insert_id =
conn.prepare("INSERT OR IGNORE INTO ids (store, id, path) VALUES (?1, ?2, ?3)")?;
for path in &state.removed {
delete_doc.execute([path.as_str()])?;
delete_ids.execute([path.as_str()])?;
}
for (path, row) in &state.rows {
let known = state
.known
.get(path)
.and_then(|k| k.as_ref())
.and_then(|k| k.row_hash);
if known == Some(row.hash()) {
continue;
}
delete_ids.execute([path.as_str()])?;
insert_doc.execute(params![
path.as_str(),
row.knowledge,
row.id,
row.type_name,
row.title,
row.description,
i64::from(row.broken),
row.visible.cast_signed(),
row.scalars,
])?;
if let Some(id) = &row.id {
insert_id.execute(params![row.knowledge, id, path.as_str()])?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Source, model::ParseMode};
fn doc(text: &str) -> Document {
let source = Source::from_text(RepoPath::parse("/k/a.md").unwrap(), text);
let parsed = crate::model::parse_source(&source, ParseMode::Document);
Document::new(source, parsed)
}
#[test]
fn a_row_carries_the_fields_and_the_hash_and_no_text() {
let full = doc("---\ntype: A\nid: a\ntitle: T\ndescription: D\n---\n\n# T\n\nBody.\n");
let row = DocRow::of(2, &full);
assert_eq!(row.knowledge, 2);
assert_eq!(row.id.as_deref(), Some("a"));
assert_eq!(row.type_name.as_deref(), Some("A"));
assert_eq!(row.title.as_deref(), Some("T"));
assert_eq!(row.description.as_deref(), Some("D"));
assert!(!row.broken);
assert_eq!(row.visible, full.visible_hash());
let edited = doc("---\ntype: A\nid: a\ntitle: T\ndescription: D\n---\n\n# T\n\nMore.\n");
assert_eq!(DocRow::of(2, &edited), row);
assert_eq!(DocRow::of(2, &edited).hash(), row.hash());
let retitled = doc("---\ntype: A\nid: a\ntitle: U\ndescription: D\n---\n\n# T\n");
assert_ne!(DocRow::of(2, &retitled).hash(), row.hash());
assert!(DocRow::of(2, &doc("---\n: [\n---\n\n# T\n")).broken);
assert!(DocRow::of(2, &doc("# No frontmatter\n")).broken);
}
}