use rusqlite::params;
use super::{Cache, conn::Conn, sync::SyncState};
use crate::{
FileKind, RepoPath,
markers::{IgnoreFault, MarkerRow, RowKind},
};
fn encode(kind: &RowKind) -> (i64, &str, &str) {
match kind {
RowKind::Marker { rel, target } => (0, rel, target),
RowKind::Malformed(tag) => (1, tag, ""),
RowKind::Rel(tag) => (6, tag, ""),
RowKind::Ignore(IgnoreFault::BeginInside) => (3, "", ""),
RowKind::Ignore(IgnoreFault::EndOutside) => (4, "", ""),
RowKind::Ignore(IgnoreFault::NeverEnds) => (5, "", ""),
}
}
fn decode(code: i64, rel: String, target: String) -> Option<RowKind> {
Some(match code {
0 => RowKind::Marker { rel, target },
1 => RowKind::Malformed(rel),
3 => RowKind::Ignore(IgnoreFault::BeginInside),
4 => RowKind::Ignore(IgnoreFault::EndOutside),
5 => RowKind::Ignore(IgnoreFault::NeverEnds),
6 => RowKind::Rel(rel),
_ => return None,
})
}
impl Cache {
pub fn outside_to_read(&self) -> Vec<RepoPath> {
let state = self.state.borrow();
let mut paths: Vec<RepoPath> = state
.known
.keys()
.filter(|p| {
Self::listed(&state, p).is_some_and(|(kind, root)| {
root.is_none() && super::sync::kind_of(kind) == FileKind::Candidate
})
})
.cloned()
.collect();
paths.sort();
paths
}
pub fn unread(&self, path: &RepoPath) {
self.state.borrow_mut().candidates.remove(path);
}
pub fn record_markers(&self, path: &RepoPath, rows: Vec<MarkerRow>) {
self.state.borrow_mut().markers.insert(path.clone(), rows);
}
pub fn stored_markers(&self, path: &RepoPath) -> Vec<MarkerRow> {
let mut out: Vec<MarkerRow> = self
.conn()
.rows(
"SELECT line, kind, rel, target FROM markers WHERE path = ?1",
[path.as_str()],
|r| {
let line = r.get::<_, usize>(0)?;
let kind = decode(r.get(1)?, r.get(2)?, r.get(3)?);
Ok(kind.map(|kind| MarkerRow { line, kind }))
},
)
.into_iter()
.flatten()
.collect();
out.sort();
out
}
pub fn has_markers(&self, path: &RepoPath) -> bool {
self.conn()
.query_row(
"SELECT 1 FROM markers WHERE path = ?1 LIMIT 1",
[path.as_str()],
|_| Ok(()),
)
.is_ok()
}
pub(super) fn commit_markers(conn: &Conn, state: &SyncState) -> rusqlite::Result<()> {
let mut delete = conn.prepare("DELETE FROM markers WHERE path = ?1")?;
for path in &state.removed {
delete.execute([path.as_str()])?;
}
let mut put = conn.prepare(
"INSERT INTO markers (path, line, kind, rel, target) VALUES (?1, ?2, ?3, ?4, ?5)",
)?;
for (path, rows) in &state.markers {
delete.execute([path.as_str()])?;
for row in rows {
let (code, rel, target) = encode(&row.kind);
put.execute(params![path.as_str(), row.line, code, rel, target])?;
}
}
Ok(())
}
}