//! Persistence. The only module that talks to turso. mod directory; use std::collections::HashMap; use tokio::sync::mpsc; use std::sync::{Arc, RwLock}; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, anyhow}; use crate::matcher::{Matcher, Part}; use tokio::sync::Mutex; use crate::export::LinkTarget; use directory::{Change, Directory, Entry, Vocab}; #[derive(Clone)] pub struct NoteMeta { pub id: String, pub title: String, pub created_at: i64, pub updated_at: i64, /// `None` when the note is not in any notebook. pub notebook_id: Option, /// `None` when the note is not in the trash. Millis when it was trashed. pub trashed_at: Option, } /// Which notes a list shows. Every filter but `Trash` leaves the trash out. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ListFilter { /// Every note outside the trash. All, /// Notes outside the trash that are in no notebook. Unfiled, /// Notes outside the trash that are in the notebook with this id. Notebook(String), /// Trashed notes, most recently trashed first. Trash, } impl ListFilter { /// The WHERE clause for this filter, and the parameters it binds (`?1` when any). fn clause(&self) -> (&'static str, Vec) { match self { Self::All => ("trashed_at IS NULL", Vec::new()), Self::Unfiled => ("trashed_at IS NULL AND notebook_id IS NULL", Vec::new()), Self::Notebook(id) => ("trashed_at IS NULL AND notebook_id = ?1", vec![id.clone()]), Self::Trash => ("trashed_at IS NOT NULL", Vec::new()), } } /// The ORDER BY for this filter: most recently updated first, or most recently trashed /// first for the trash. Ties go to the newer id, so the order is an index read /// backwards rather than a sort of every row. fn order(&self) -> &'static str { match self { Self::Trash => "trashed_at DESC, id DESC", _ => "updated_at DESC, id DESC", } } } pub struct Notebook { pub id: String, pub name: String, pub created_at: i64, } /// Snapshot (if any) plus every update stored after it, in insertion order. pub struct DocBytes { pub snapshot: Option>, pub updates: Vec>, /// The markdown stored with the snapshot, when no update came after it. pub markdown: Option, /// [`crate::export::to_markdown_deferred`] of the doc, when cached for its snapshot /// and no update came after it. Only read by [`Store::load_docs`], which then skips /// the snapshot. pub export: Option, /// The snapshot's last update, 0 without a snapshot. pub upto_seq: i64, } impl DocBytes { /// Bytes held: what reading the note cost. pub fn stored_len(&self) -> usize { let text = |t: &Option| t.as_ref().map_or(0, String::len); self.snapshot.as_ref().map_or(0, Vec::len) + self.updates.iter().map(Vec::len).sum::() + text(&self.markdown) + text(&self.export) } } pub struct Store { /// Single connection shared by all tasks. Calls are serialized by the mutex, /// which also keeps transactions from interleaving on one connection. conn: Mutex, /// A second connection for single-statement reads: in WAL they do not wait for a /// write, and a huge note's write holds `conn` for seconds. read: Mutex, /// Loaded on first use. See [`directory`]. dir: Mutex>, /// Writes committed since the directory was last read, in order. changes: std::sync::Mutex>, /// Notes whose text changed but is too long to index while the directory waits: /// [`Store::keep_directory_fresh`] indexes them off its lock. heavy: std::sync::Mutex>, /// Keeps the database handle alive for as long as the connection is used. db: turso::Database, } pub(crate) fn now_millis() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_millis() as i64) .unwrap_or(0) } /// The form of a title that links match on: whitespace collapsed and lowercased. pub fn title_key(title: &str) -> String { title .split_whitespace() .collect::>() .join(" ") .to_lowercase() } fn text_col(row: &turso::Row, idx: usize) -> anyhow::Result { match row.get_value(idx)? { turso::Value::Text(s) => Ok(s), other => Err(anyhow!("column {idx}: expected TEXT, got {other:?}")), } } fn opt_text_col(row: &turso::Row, idx: usize) -> anyhow::Result> { match row.get_value(idx)? { turso::Value::Null => Ok(None), turso::Value::Text(s) => Ok(Some(s)), other => Err(anyhow!("column {idx}: expected TEXT or NULL, got {other:?}")), } } fn int_col(row: &turso::Row, idx: usize) -> anyhow::Result { match row.get_value(idx)? { turso::Value::Integer(i) => Ok(i), other => Err(anyhow!("column {idx}: expected INTEGER, got {other:?}")), } } fn opt_int_col(row: &turso::Row, idx: usize) -> anyhow::Result> { match row.get_value(idx)? { turso::Value::Null => Ok(None), turso::Value::Integer(i) => Ok(Some(i)), other => Err(anyhow!("column {idx}: expected INTEGER or NULL, got {other:?}")), } } fn blob_col(row: &turso::Row, idx: usize) -> anyhow::Result> { match row.get_value(idx)? { turso::Value::Blob(b) => Ok(b), other => Err(anyhow!("column {idx}: expected BLOB, got {other:?}")), } } fn opt_blob_col(row: &turso::Row, idx: usize) -> anyhow::Result>> { match row.get_value(idx)? { turso::Value::Null => Ok(None), turso::Value::Blob(b) => Ok(Some(b)), other => Err(anyhow!("column {idx}: expected BLOB or NULL, got {other:?}")), } } fn note_from_row(row: &turso::Row) -> anyhow::Result { Ok(NoteMeta { id: text_col(row, 0)?, title: text_col(row, 1)?, created_at: int_col(row, 2)?, updated_at: int_col(row, 3)?, notebook_id: opt_text_col(row, 4)?, trashed_at: opt_int_col(row, 5)?, }) } /// Id of the notebook named `name`, ignoring case. The exact name is looked up first, /// through the index; other casings need a scan. async fn find_notebook(tx: &turso::transaction::Transaction<'_>, name: &str) -> anyhow::Result> { let mut rows = tx.query("SELECT id FROM notebooks WHERE name = ?1 LIMIT 1", (name.to_string(),)).await?; if let Some(row) = rows.next().await? { return Ok(Some(text_col(&row, 0)?)); } drop(rows); let key = name.to_lowercase(); let mut rows = tx.query("SELECT id, name FROM notebooks", ()).await?; while let Some(row) = rows.next().await? { if text_col(&row, 1)?.to_lowercase() == key { return Ok(Some(text_col(&row, 0)?)); } } Ok(None) } /// Inserts the note links of `src` inside an open transaction. async fn insert_links( tx: &turso::transaction::Transaction<'_>, src: &str, targets: &[LinkTarget], ) -> anyhow::Result<()> { for target in targets { match target { LinkTarget::Id(id) => { tx.execute( "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, ?2, NULL)", (src.to_string(), id.clone()), ) .await?; } LinkTarget::Title(title) => { let key = title_key(title); if key.is_empty() { continue; } tx.execute( "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, NULL, ?2)", (src.to_string(), key), ) .await?; } } } Ok(()) } /// Deletes one note's rows inside an open transaction. async fn delete_note_rows( tx: &turso::transaction::Transaction<'_>, note_id: &str, ) -> anyhow::Result<()> { tx.execute("DELETE FROM updates WHERE note_id = ?1", (note_id.to_string(),)) .await?; tx.execute("DELETE FROM snapshots WHERE note_id = ?1", (note_id.to_string(),)) .await?; tx.execute("DELETE FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),)) .await?; tx.execute("DELETE FROM export_text WHERE note_id = ?1", (note_id.to_string(),)) .await?; tx.execute("DELETE FROM note_text WHERE note_id = ?1", (note_id.to_string(),)) .await?; tx.execute("DELETE FROM note_versions WHERE note_id = ?1", (note_id.to_string(),)) .await?; tx.execute("DELETE FROM note_links WHERE src = ?1", (note_id.to_string(),)) .await?; tx.execute("DELETE FROM notes WHERE id = ?1", (note_id.to_string(),)) .await?; Ok(()) } fn notebook_from_row(row: &turso::Row) -> anyhow::Result { Ok(Notebook { id: text_col(row, 0)?, name: text_col(row, 1)?, created_at: int_col(row, 2)?, }) } /// What [`Store::search`] found: the best hits, and whether the time budget ran out /// before every note was read. #[derive(Default)] pub struct Searched { pub hits: Vec, pub partial: bool, } /// A note matched by [`Store::search`], with a plain-text excerpt of its body. pub struct SearchHit { pub note: NoteMeta, pub snippet: String, } /// Characters of body text shown around the first match. const SNIPPET_CHARS: usize = 160; /// Characters of body text shown as a note's preview in a list. const PREVIEW_CHARS: usize = 140; /// Characters of a note's body read for its preview. Enough for `PREVIEW_CHARS` of plain /// text, so the rest of a long body is never loaded. const PREVIEW_SOURCE_CHARS: usize = 2000; /// The stored markdown of each of `ids`, by id, read on `conn`. async fn bodies_on(conn: &turso::Connection, ids: &[String]) -> anyhow::Result> { let placeholders = (1..=ids.len()).map(|i| format!("?{i}")).collect::>().join(", "); let mut rows = conn .query(format!("SELECT note_id, body FROM note_text WHERE note_id IN ({placeholders})"), ids.to_vec()) .await?; let mut bodies = HashMap::new(); while let Some(row) = rows.next().await? { bodies.insert(text_col(&row, 0)?, text_col(&row, 1)?); } Ok(bodies) } /// Bytes of note bodies indexed at a time when the directory is loaded. const DIRECTORY_BATCH_BYTES: usize = 256 << 20; /// Connections reading note texts at once for a search. const SEARCH_READERS: usize = 8; /// Connections reading the notes at once when the directory is loaded. const DIRECTORY_READERS: usize = 4; /// Note ids per `IN (...)` query, well under SQLite's parameter limit. const PREVIEW_BATCH: usize = 500; /// Bytes of a changed note's text above which it is indexed in the background: a /// 100 MB note takes seconds, and every page waits for the directory meanwhile. const HEAVY_INDEX_BYTES: i64 = 1 << 20; /// How long such a note goes unchanged before it is indexed: while someone types in /// it, each text flush would cost a core for a second. const HEAVY_QUIET: std::time::Duration = std::time::Duration::from_secs(2); /// Markdown as plain text. Code fences are dropped, block markers (headings, quotes, /// list and task markers, rules) and inline syntax (emphasis, code spans, escapes) are /// removed, link and image text is kept, and lines are joined with single spaces. fn plain_text(markdown: &str) -> String { PlainChunks::new(markdown, usize::MAX).next().unwrap_or_default() } /// [`plain_text`] in pieces of at least `chunk` bytes, which joined with single spaces /// give the whole: a long note is matched a piece at a time and the rest skipped once /// nothing better can turn up. struct PlainChunks<'a> { lines: std::str::Lines<'a>, in_fence: bool, chunk: usize, } impl<'a> PlainChunks<'a> { fn new(markdown: &'a str, chunk: usize) -> Self { Self { lines: markdown.lines(), in_fence: false, chunk } } } impl Iterator for PlainChunks<'_> { type Item = String; fn next(&mut self) -> Option { fn push(out: &mut String, text: &str) { // Most lines are ASCII with single spaces: already what the words joined give. let mut prev_space = false; let simple = text.bytes().all(|b| { let ok = b.is_ascii() && !matches!(b, b'\t' | b'\n' | b'\r' | b'\x0b' | b'\x0c') && !(b == b' ' && prev_space); prev_space = b == b' '; ok }); if simple && !text.starts_with(' ') && !text.ends_with(' ') { if !text.is_empty() { if !out.is_empty() { out.push(' '); } out.push_str(text); } return; } for word in text.split_whitespace() { if !out.is_empty() { out.push(' '); } out.push_str(word); } } let mut out = String::new(); let mut any = false; for line in self.lines.by_ref() { any = true; let trimmed = line.trim(); if trimmed.starts_with("```") || trimmed.starts_with("~~~") { self.in_fence = !self.in_fence; } else if self.in_fence { push(&mut out, trimmed); } else { push(&mut out, &strip_inline(strip_block(trimmed))); } if out.len() >= self.chunk { break; } } (any && (!out.is_empty() || self.chunk == usize::MAX)).then_some(out) } } /// `matcher` against a note's title and its whole `body`, read a piece at a time: the /// note's key and a snippet when it matches. Stops early once every term matched at /// `floor`, the least it can cost in this note, which nothing beats. fn match_long(title: &str, body: &str, matcher: &Matcher, floor: usize) -> Option<(SearchKey, String)> { match_pieces(title, PlainChunks::new(body, 64 << 10), matcher, floor).0 } /// [`match_long`] over plain text given in pieces joined by single spaces. Also says /// whether every term matched at `floor`: then the rest of the text cannot change it. fn match_pieces( title: &str, pieces: impl Iterator, matcher: &Matcher, floor: usize, ) -> (Option<(SearchKey, String)>, bool) { // Text carried into the next piece, for matches across the cut. const OVERLAP: usize = 1024; let in_title = matcher.term_costs(title); let mut in_text: Vec> = vec![None; in_title.len()]; let mut snip: Option = None; let mut tail = String::new(); let mut perfect = false; for (i, piece) in pieces.enumerate() { let window = if tail.is_empty() { piece } else { format!("{tail} {piece}") }; for (best, cost) in in_text.iter_mut().zip(matcher.term_costs(&window)) { if let Some(cost) = cost { *best = Some(best.map_or(cost, |b| b.min(cost))); } } if snip.is_none() && in_text.iter().any(Option::is_some) { let s = snippet(&window, matcher); snip = Some(if i > 0 && !s.starts_with('…') { format!("…{s}") } else { s }); } if in_text.iter().all(|c| c.is_some_and(|c| c <= floor)) { perfect = true; break; } let from = window.char_indices().rev().nth(OVERLAP).map_or(0, |(at, _)| at); // From a word start, so a match there is not taken for one at a word start. let from = if from == 0 { 0 } else { window[from..].find(' ').map_or(window.len(), |sp| from + sp + 1) }; tail = window[from..].to_owned(); } let key = search_key(in_title.into_iter(), in_text.into_iter()).map(|k| (k, snip.unwrap_or_default())); (key, perfect) } /// `plain` in pieces of about 64 KB cut at spaces, the cut spaces left out. fn plain_pieces(plain: &str) -> impl Iterator + '_ { let mut rest = plain; std::iter::from_fn(move || { if rest.is_empty() { return None; } let mut cut = (64 << 10).min(rest.len()); while !rest.is_char_boundary(cut) { cut += 1; } let cut = if cut == rest.len() { cut } else { rest[cut..].find(' ').map_or(rest.len(), |sp| cut + sp) }; let piece = rest[..cut].to_owned(); rest = rest.get(cut + 1..).unwrap_or(""); Some(piece) }) } /// Removes the block syntax at the start of one trimmed line: quote marks, heading /// hashes, list and task markers, and thematic breaks. fn strip_block(line: &str) -> &str { let mut s = line; if s.len() >= 3 && s.chars().all(|c| matches!(c, '-' | '*' | '_' | ' ')) { return ""; } while let Some(rest) = s.strip_prefix('>') { s = rest.trim_start(); } let hashes = s.len() - s.trim_start_matches('#').len(); if hashes > 0 && (hashes == s.len() || s[hashes..].starts_with(' ')) { s = s[hashes..].trim_start(); } if let Some(rest) = s.strip_prefix(['-', '*', '+']) { if rest.is_empty() || rest.starts_with(' ') { s = rest.trim_start(); } } let digits = s.len() - s.trim_start_matches(|c: char| c.is_ascii_digit()).len(); if digits > 0 { if let Some(rest) = s[digits..].strip_prefix(['.', ')']) { if rest.is_empty() || rest.starts_with(' ') { s = rest.trim_start(); } } } for checkbox in ["[ ]", "[x]", "[X]"] { if let Some(rest) = s.strip_prefix(checkbox) { s = rest.trim_start(); break; } } s } /// Removes inline syntax from one line: `[text](url)` and `![alt](url)` become their /// text, emphasis and code markers are dropped, `_` is kept inside words only, and a /// backslash escape yields the escaped character. fn strip_inline(text: &str) -> std::borrow::Cow<'_, str> { // Most lines have no inline syntax at all. if !text.contains(['!', '[', '\\', '*', '`', '~', '_']) { return text.into(); } let chars: Vec = text.chars().collect(); let mut out = String::with_capacity(text.len()); let mut i = 0; while i < chars.len() { let c = chars[i]; if c == '!' && chars.get(i + 1) == Some(&'[') { if let Some((label, end)) = link_at(&chars, i + 1) { out.push_str(&label); i = end; continue; } } if c == '[' { if let Some((label, end)) = link_at(&chars, i) { out.push_str(&label); i = end; continue; } } if c == '\\' && chars.get(i + 1).is_some_and(|next| next.is_ascii_punctuation()) { out.push(chars[i + 1]); i += 2; continue; } match c { '*' | '`' | '~' => {} '_' => { let inside_word = i > 0 && chars[i - 1].is_alphanumeric() && chars.get(i + 1).is_some_and(|next| next.is_alphanumeric()); if inside_word { out.push(c); } } _ => out.push(c), } i += 1; } out.into() } /// Parses `[label](target)` whose `[` is at `open`. Returns the label and the index just /// after the closing `)`. fn link_at(chars: &[char], open: usize) -> Option<(String, usize)> { let close = open + 1 + chars[open + 1..].iter().position(|&c| c == ']')?; if chars.get(close + 1) != Some(&'(') { return None; } let end = close + 2 + chars[close + 2..].iter().position(|&c| c == ')')?; Some((chars[open + 1..close].iter().collect(), end + 1)) } /// The first `PREVIEW_CHARS` characters of a note's text after its title. The first /// non-blank line of the markdown is the title, so it is skipped. fn preview(markdown: &str) -> String { let head = markdown.char_indices().nth(PREVIEW_SOURCE_CHARS).map_or(markdown, |(i, _)| &markdown[..i]); // The text after the first non-blank line, the title. let mut rest = head; loop { let (line, after) = rest.split_once('\n').unwrap_or((rest, "")); rest = after; if !line.trim().is_empty() || rest.is_empty() { break; } } plain_text(rest).chars().take(PREVIEW_CHARS).collect() } /// About `SNIPPET_CHARS` characters of `plain` around the first term match. /// Cut ends get an ellipsis. fn snippet(plain: &str, matcher: &Matcher) -> String { if plain.is_empty() { return String::new(); } // Most hits match near the start: look there before reading the whole text. let mut center = 0; for window in [4 << 10, 64 << 10, usize::MAX] { let mut end = window.min(plain.len()); while !plain.is_char_boundary(end) { end -= 1; } if let Some(range) = matcher.ranges(&plain[..end]).first() { center = range.0; break; } if end == plain.len() { break; } } let start = center.saturating_sub(SNIPPET_CHARS / 3); let mut chars = plain.char_indices().skip(start).map(|(i, _)| i); let Some(from) = chars.next() else { // The match is near the end: show the last `SNIPPET_CHARS`. let from = plain.char_indices().rev().nth(SNIPPET_CHARS - 1).map_or(0, |(i, _)| i); return format!("{}{}", if from > 0 { "…" } else { "" }, plain[from..].trim()); }; let to = chars.nth(SNIPPET_CHARS - 1).unwrap_or(plain.len()); if to == plain.len() && start > 0 { // Too close to the end for a full window: take it from further back. let from = plain.char_indices().rev().nth(SNIPPET_CHARS - 1).map_or(0, |(i, _)| i); return format!("{}{}", if from > 0 { "…" } else { "" }, plain[from..].trim()); } let mut out = String::new(); if from > 0 { out.push('…'); } out.push_str(plain[from..to].trim()); if to < plain.len() { out.push('…'); } out } /// Scores every row against `matcher`, in parallel, keeping their order. type SearchKey = (usize, std::cmp::Reverse); /// Each term matches the title or the text, whichever is closer. Cheaper matches /// first (exact before typos), then more terms in the title. fn search_key(in_title: impl Iterator>, in_text: impl Iterator>) -> Option { let mut cost = 0; let mut title_terms = 0; for (t, x) in in_title.zip(in_text) { match (t, x) { (Some(t), Some(x)) if t <= x => (cost += t, title_terms += 1), (Some(t), None) => (cost += t, title_terms += 1), (_, Some(x)) => (cost += x, ()), (None, None) => return None, }; } Some((cost, std::cmp::Reverse(title_terms))) } /// A search hit's rank: its [`SearchKey`], then the newest. type RankKey = (SearchKey, std::cmp::Reverse); /// The `limit` best notes outside the trash by `matcher`, best first: see [`par_top`]. /// Notes whose text is longer than kept in memory are left out of a case, phrase or /// regex search here: [`Store::search`] matches them against their stored text. fn match_top(matcher: &Matcher, slots: &[Option>], vocab: &RwLock, limit: usize) -> Vec<(RankKey, Arc)> { let newest = |k: SearchKey, e: &Entry| (k, std::cmp::Reverse(e.updated_at)); match matcher.word_terms() { Some(terms) => { let tables = word_costs(matcher, terms, &vocab.read().unwrap()); par_top_keyed(slots, limit, |e| { let k = search_key( tables.iter().map(|t| best_cost(t, e.title_words())), tables.iter().map(|t| best_cost(t, e.text_words())), )?; Some(newest(k, e)) }) } None => par_top_keyed(slots, limit, |e| { if e.plain_cut { return None; } let k = search_key(matcher.term_costs(e.title()).into_iter(), matcher.term_costs(e.plain()).into_iter())?; Some(newest(k, e)) }), } } /// The `limit` notes outside the trash with the lowest `key`, lowest first; ties go to /// the lower id. Each thread keeps only its own best `limit`, so a query that matches /// every note never collects them all. fn par_top( slots: &[Option>], limit: usize, key: impl Fn(&Entry) -> Option + Sync, ) -> Vec> { par_top_keyed(slots, limit, key).into_iter().map(|(_, e)| e).collect() } /// [`par_top`] with the keys kept. fn par_top_keyed( slots: &[Option>], limit: usize, key: impl Fn(&Entry) -> Option + Sync, ) -> Vec<(K, Arc)> { let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); let chunk_len = slots.len().div_ceil(threads).max(1); let key = &key; let best: Vec<(K, &Arc)> = std::thread::scope(|scope| { let handles: Vec<_> = slots .chunks(chunk_len) .map(|chunk| { scope.spawn(move || { // Trimmed to the best `limit` whenever it fills, and past that only // keys as good as the worst kept one enter: a word in every note // would otherwise collect them all, megabytes per search. let cap = 4 * limit.max(64); let mut hits: Vec<(K, &Arc)> = Vec::with_capacity(cap); let mut worst: Option = None; for e in chunk.iter().flatten().filter(|e| e.trashed_at.is_none()) { let Some(k) = key(e) else { continue }; if worst.is_some_and(|w| k > w) { continue; } hits.push((k, e)); if hits.len() == cap { hits = top_keyed(hits, limit, |e| e.id()); worst = hits.last().map(|h| h.0); } } top_keyed(hits, limit, |e| e.id()) }) }) .collect(); handles .into_iter() .flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))) .collect() }); top_keyed(best, limit, |e| e.id()).into_iter().map(|(k, e)| (k, e.clone())).collect() } /// Each term's cost in every word of the vocabulary, by word id; `u8::MAX` where the /// term does not occur in the word. fn word_costs(matcher: &Matcher, terms: &[Vec], vocab: &Vocab) -> Vec>> { /// Term tables kept for the next searches. const KEPT: usize = 8; let Some(opts) = matcher.options() else { return Vec::new() }; let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); // The costs of `term` in `words`, on every core. let compute = |term: &[char], from: usize| -> Vec { let n = vocab.len() - from; let chunk_len = n.div_ceil(threads).max(1); std::thread::scope(|scope| { let handles: Vec<_> = (from..vocab.len()) .step_by(chunk_len) .map(|start| { let ids = start..(start + chunk_len).min(vocab.len()); scope.spawn(move || { ids.map(|id| matcher.word_cost(term, vocab.word(id)).map_or(u8::MAX, |c| c.min(254) as u8)).collect::>() }) }) .collect(); handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect() }) }; terms .iter() .map(|term| { let found = { let mut kept = vocab.costs.lock().unwrap(); let at = kept.iter().position(|(t, o, _)| **t == **term && *o == opts); at.map(|i| kept.remove(i)) }; let table = match found { Some((_, _, table)) if table.len() == vocab.len() => table, Some((_, _, table)) => { let mut grown = (*table).clone(); grown.extend(compute(term, table.len())); Arc::new(grown) } None => Arc::new(compute(term, 0)), }; let mut kept = vocab.costs.lock().unwrap(); kept.push((term.clone().into(), opts, table.clone())); if kept.len() > KEPT { kept.remove(0); } table }) .collect() } /// The cheapest cost in `table` among `words`, None if the term is in none of them. fn best_cost(table: &[u8], words: &[u32]) -> Option { let best = words.iter().map(|&w| table[w as usize]).min()?; (best != u8::MAX).then_some(usize::from(best)) } /// The `limit` items with the smallest keys, in key order, ties by `id`. Selects before /// sorting: a common word matches every note, and sorting them all costs more than /// matching them. fn top(items: Vec<(K, T)>, limit: usize, id: impl Fn(&T) -> &str) -> Vec { top_keyed(items, limit, id).into_iter().map(|(_, t)| t).collect() } /// [`top`] with the keys kept. fn top_keyed(mut items: Vec<(K, T)>, limit: usize, id: impl Fn(&T) -> &str) -> Vec<(K, T)> { let cmp = |a: &(K, T), b: &(K, T)| a.0.cmp(&b.0).then_with(|| id(&a.1).cmp(id(&b.1))); if limit == 0 { return Vec::new(); } if items.len() > limit { items.select_nth_unstable_by(limit - 1, cmp); items.truncate(limit); } items.sort_unstable_by(cmp); items } impl Store { /// Opens (or creates) the database file and runs schema setup. pub async fn open(path: &str) -> anyhow::Result { // The FTS index method is gated behind this flag in turso 0.8. Search no longer // uses the index, but databases made before still have one to drop. let db = turso::Builder::new_local(path) .experimental_index_method(true) .build() .await .with_context(|| format!("opening database at {path}"))?; let conn = db.connect()?; // WAL with NORMAL sync: a commit no longer waits for an fsync, so a power loss can // drop the last commits but never corrupts the database. Each note save is a commit. conn.execute("PRAGMA synchronous = NORMAL", ()).await.context("setting synchronous")?; conn.execute_batch( "CREATE TABLE IF NOT EXISTS notes ( id TEXT PRIMARY KEY, title TEXT NOT NULL DEFAULT 'Untitled', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, notebook_id TEXT, trashed_at INTEGER ); CREATE TABLE IF NOT EXISTS notebooks ( id TEXT PRIMARY KEY, name TEXT NOT NULL, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS updates ( seq INTEGER PRIMARY KEY AUTOINCREMENT, note_id TEXT NOT NULL, hash BLOB NOT NULL, data BLOB NOT NULL, UNIQUE(note_id, hash) ); CREATE TABLE IF NOT EXISTS snapshots ( note_id TEXT PRIMARY KEY, data BLOB NOT NULL, upto_seq INTEGER NOT NULL, markdown TEXT NOT NULL ); -- Export markdown of a snapshot, its note links left for the export to name. CREATE TABLE IF NOT EXISTS export_text ( note_id TEXT PRIMARY KEY, upto_seq INTEGER NOT NULL, markdown TEXT NOT NULL ); -- Imported markdown whose doc is not built yet: see hub::ensure_doc. CREATE TABLE IF NOT EXISTS pending_docs ( note_id TEXT PRIMARY KEY, markdown TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS note_text ( note_id TEXT PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS note_versions ( note_id TEXT NOT NULL, at INTEGER NOT NULL, frontiers BLOB NOT NULL, PRIMARY KEY(note_id, at) ); DROP INDEX IF EXISTS note_text_fts; CREATE TABLE IF NOT EXISTS note_links ( src TEXT NOT NULL, dst_id TEXT, dst_title TEXT ); CREATE INDEX IF NOT EXISTS notebooks_name ON notebooks(name); CREATE INDEX IF NOT EXISTS note_links_src ON note_links(src); CREATE INDEX IF NOT EXISTS note_links_dst_id ON note_links(dst_id); CREATE INDEX IF NOT EXISTS note_links_dst_title ON note_links(dst_title);", ) .await .context("running schema setup")?; // Databases created before notebooks have a notes table without notebook_id. // CREATE TABLE IF NOT EXISTS does not add columns, so add it when missing. if !Self::notes_columns(&conn).await?.iter().any(|c| c == "notebook_id") { conn.execute("ALTER TABLE notes ADD COLUMN notebook_id TEXT", ()) .await .context("adding notes.notebook_id")?; } // Databases created before the trash existed lack notes.trashed_at. if !Self::notes_columns(&conn).await?.iter().any(|c| c == "trashed_at") { conn.execute("ALTER TABLE notes ADD COLUMN trashed_at INTEGER", ()) .await .context("adding notes.trashed_at")?; } // List queries filter on trashed_at and notebook_id and sort by updated_at. These // indexes are created after the column migrations above, which they depend on. conn.execute_batch( "DROP INDEX IF EXISTS notes_trashed_updated; DROP INDEX IF EXISTS notes_notebook_trashed_updated; CREATE INDEX IF NOT EXISTS notes_trashed_updated_id ON notes(trashed_at, updated_at, id); CREATE INDEX IF NOT EXISTS notes_notebook_trashed_updated_id ON notes(notebook_id, trashed_at, updated_at, id);", ) .await .context("creating notes indexes")?; // Notes saved before note_text existed: copy their snapshot markdown, once per // database (a scan of every snapshot, seconds at a million notes). let mut rows = conn.query("PRAGMA user_version", ()).await?; let version = match rows.next().await? { Some(row) => int_col(&row, 0)?, None => 0, }; drop(rows); if version < 1 { conn.execute( "INSERT INTO note_text (note_id, title, body) SELECT s.note_id, n.title, s.markdown FROM snapshots s JOIN notes n ON n.id = s.note_id WHERE NOT EXISTS (SELECT 1 FROM note_text t WHERE t.note_id = s.note_id)", (), ) .await .context("backfilling note_text")?; conn.execute("PRAGMA user_version = 1", ()).await.context("setting user_version")?; } // Cached export markdown used to be checked against its snapshot on read. Now a // new snapshot drops it, so what was cached before cannot be trusted. if version < 2 { conn.execute("DELETE FROM export_text", ()).await.context("clearing export_text")?; conn.execute("PRAGMA user_version = 2", ()).await.context("setting user_version")?; } Ok(Self { conn: Mutex::new(conn), read: Mutex::new(db.connect()?), dir: Mutex::new(None), changes: std::sync::Mutex::new(Vec::new()), heavy: std::sync::Mutex::new(HashMap::new()), db, }) } /// Column names of the notes table, read from `PRAGMA table_info`. async fn notes_columns(conn: &turso::Connection) -> anyhow::Result> { let mut rows = conn.query("PRAGMA table_info(notes)", ()).await?; let mut names = Vec::new(); while let Some(row) = rows.next().await? { names.push(text_col(&row, 1)?); } Ok(names) } /// Records a committed write for the directory. fn changed(&self, change: Change) { self.changes.lock().unwrap().push(change); } /// The directory, loaded if needed and with every recorded write applied. async fn directory(&self) -> anyhow::Result> { let mut dir = self.dir.lock().await; let result = self.refresh_directory(&mut dir).await; if result.is_err() { // Changes may have been taken without being applied: start over next time. *dir = None; } result?; Ok(tokio::sync::MutexGuard::map(dir, |d| d.as_mut().unwrap())) } async fn refresh_directory(&self, dir: &mut Option) -> anyhow::Result<()> { const SELECT: &str = "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, COALESCE(t.body, '') FROM notes n LEFT JOIN note_text t ON t.note_id = n.id"; let select_changed = format!( "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, CASE WHEN length(t.body) > {HEAVY_INDEX_BYTES} THEN NULL ELSE COALESCE(t.body, '') END FROM notes n LEFT JOIN note_text t ON t.note_id = n.id" ); if dir.is_none() { // Whatever was committed before this point is in the full read. self.changes.lock().unwrap().clear(); // Held while reading: no write lands between the read and the change log. let conn = self.conn.lock().await; let mut rows = conn.query("SELECT min(rowid), max(rowid) FROM notes", ()).await?; let (first, last) = match rows.next().await? { Some(row) => (row.get::>(0)?.unwrap_or(0), row.get::>(1)?.unwrap_or(0)), None => (0, 0), }; drop(rows); // Indexed in batches of a bounded size, as they are read: all the bodies may // not fit in memory. Ranges of rows are read on their own connections at once. let (tx, rx) = std::sync::mpsc::sync_channel::>(DIRECTORY_READERS); let indexer = std::thread::spawn(move || { let mut loaded = Directory::default(); for batch in rx { loaded.put_many(batch); } loaded }); let span = (last - first) / DIRECTORY_READERS as i64 + 1; let mut readers = tokio::task::JoinSet::new(); for k in 0..DIRECTORY_READERS as i64 { let (reader, tx) = (self.db.connect()?, tx.clone()); let (from, to) = (first + k * span, first + (k + 1) * span - 1); readers.spawn(async move { let mut rows = reader.query(format!("{SELECT} WHERE n.rowid BETWEEN ?1 AND ?2"), (from, to)).await?; let (mut batch, mut bytes) = (Vec::new(), 0); while let Some(row) = rows.next().await? { let body = text_col(&row, 6)?; bytes += body.len() + 200; batch.push((note_from_row(&row)?, body)); if bytes > DIRECTORY_BATCH_BYTES / DIRECTORY_READERS { let full = std::mem::take(&mut batch); tokio::task::block_in_place(|| tx.send(full))?; bytes = 0; } } tokio::task::block_in_place(|| tx.send(batch))?; anyhow::Ok(()) }); } drop(tx); while let Some(read) = readers.join_next().await { read??; } drop(conn); let mut loaded = tokio::task::block_in_place(|| indexer.join()).map_err(|_| anyhow::anyhow!("indexing notes panicked"))?; loaded.shrink(); *dir = Some(loaded); } let changes = std::mem::take(&mut *self.changes.lock().unwrap()); if changes.is_empty() { return Ok(()); } let dir = dir.as_mut().unwrap(); // A write landing meanwhile records its change again, for the next refresh. let conn = self.read.lock().await; // Changed notes are re-read in batches, each note once; a deleted notebook // first needs the notes changed before it. let mut ids: Vec = Vec::new(); let mut seen = std::collections::HashSet::new(); for change in changes.into_iter().map(Some).chain([None]) { match change { Some(Change::Note(id)) => { if seen.insert(id.clone()) { ids.push(id); } continue; } Some(Change::NotebookGone(_)) | None => {} } for chunk in ids.chunks(PREVIEW_BATCH) { let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::>().join(", "); let mut rows = conn.query(format!("{select_changed} WHERE n.id IN ({placeholders})"), chunk.to_vec()).await?; let mut found = std::collections::HashSet::new(); let (mut batch, mut heavy) = (Vec::new(), Vec::new()); while let Some(row) = rows.next().await? { let meta = note_from_row(&row)?; found.insert(meta.id.clone()); match opt_text_col(&row, 6)? { Some(body) => batch.push((meta, body)), None => heavy.push(meta), } } tokio::task::block_in_place(|| dir.put_many(batch)); for meta in heavy { self.heavy.lock().unwrap().insert(meta.id.clone(), std::time::Instant::now()); dir.set_meta(meta); } for id in chunk.iter().filter(|id| !found.contains(*id)) { dir.remove(id); } } ids.clear(); seen.clear(); if let Some(Change::NotebookGone(id)) = change { dir.unfile(&id); } } Ok(()) } /// Loads the directory, then keeps applying writes in the background, so a request /// after a burst of writes (a big import) does not have to. pub async fn keep_directory_fresh(&self) { loop { if let Err(err) = self.directory().await { eprintln!("note directory refresh failed: {err:#}"); } if let Err(err) = self.index_heavy().await { eprintln!("indexing a long note failed: {err:#}"); } tokio::time::sleep(std::time::Duration::from_millis(250)).await; } } /// Indexes the long notes the directory left for later: read on a connection of /// their own and indexed with no lock held, then put in unless edited again since. async fn index_heavy(&self) -> anyhow::Result<()> { let ids: Vec = { let mut heavy = self.heavy.lock().unwrap(); let quiet: Vec = heavy.iter().filter(|(_, at)| at.elapsed() >= HEAVY_QUIET).map(|(id, _)| id.clone()).collect(); for id in &quiet { heavy.remove(id); } quiet }; for id in ids { let conn = self.db.connect()?; let mut rows = conn .query( "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, COALESCE(t.body, '') FROM notes n LEFT JOIN note_text t ON t.note_id = n.id WHERE n.id = ?1", [id.as_str()], ) .await?; let Some(row) = rows.next().await? else { continue }; let (meta, body) = (note_from_row(&row)?, text_col(&row, 6)?); drop((rows, conn)); let updated_at = meta.updated_at; // At the lowest priority: requests and doc builds go first. let indexer = std::thread::spawn(move || { let _ = thread_priority::set_current_thread_priority(thread_priority::ThreadPriority::Min); directory::prepare_one(meta, body) }); let prepared = tokio::task::block_in_place(|| indexer.join()).map_err(|_| anyhow!("indexing a long note panicked"))?; let mut dir = self.dir.lock().await; if let Some(dir) = dir.as_mut() && dir.updated_at(&id).is_some_and(|at| at <= updated_at) { tokio::task::block_in_place(|| dir.put_prepared(prepared)); } } Ok(()) } pub async fn create_note(&self, notebook_id: Option<&str>) -> anyhow::Result { let now = now_millis(); let note = NoteMeta { id: uuid::Uuid::now_v7().to_string(), title: "Untitled".to_string(), created_at: now, updated_at: now, notebook_id: notebook_id.map(str::to_string), trashed_at: None, }; let conn = self.conn.lock().await; conn.execute( "INSERT INTO notes (id, title, created_at, updated_at, notebook_id) VALUES (?1, ?2, ?3, ?4, ?5)", ( note.id.clone(), note.title.clone(), note.created_at, note.updated_at, note.notebook_id.clone(), ), ) .await?; self.changed(Change::Note(note.id.clone())); Ok(note) } pub async fn create_notebook(&self, name: &str) -> anyhow::Result { let notebook = Notebook { id: uuid::Uuid::now_v7().to_string(), name: name.to_string(), created_at: now_millis(), }; let conn = self.conn.lock().await; conn.execute( "INSERT INTO notebooks (id, name, created_at) VALUES (?1, ?2, ?3)", ( notebook.id.clone(), notebook.name.clone(), notebook.created_at, ), ) .await?; Ok(notebook) } pub async fn list_notebooks(&self) -> anyhow::Result> { let conn = self.read.lock().await; let mut rows = conn .query( "SELECT id, name, created_at FROM notebooks ORDER BY name COLLATE NOCASE, id", (), ) .await?; let mut notebooks = Vec::new(); while let Some(row) = rows.next().await? { notebooks.push(notebook_from_row(&row)?); } Ok(notebooks) } pub async fn get_notebook(&self, id: &str) -> anyhow::Result> { let conn = self.read.lock().await; let mut rows = conn .query( "SELECT id, name, created_at FROM notebooks WHERE id = ?1", (id.to_string(),), ) .await?; match rows.next().await? { Some(row) => Ok(Some(notebook_from_row(&row)?)), None => Ok(None), } } pub async fn rename_notebook(&self, id: &str, name: &str) -> anyhow::Result<()> { let conn = self.conn.lock().await; conn.execute( "UPDATE notebooks SET name = ?2 WHERE id = ?1", (id.to_string(), name.to_string()), ) .await?; Ok(()) } /// Deletes the notebook. Its notes are kept and become unfiled. pub async fn delete_notebook(&self, id: &str) -> anyhow::Result<()> { let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; tx.execute( "UPDATE notes SET notebook_id = NULL WHERE notebook_id = ?1", (id.to_string(),), ) .await?; tx.execute("DELETE FROM notebooks WHERE id = ?1", (id.to_string(),)) .await?; tx.commit().await?; self.changed(Change::NotebookGone(id.to_owned())); Ok(()) } pub async fn move_note(&self, note_id: &str, notebook_id: Option<&str>) -> anyhow::Result<()> { let conn = self.conn.lock().await; conn.execute( "UPDATE notes SET notebook_id = ?2 WHERE id = ?1", (note_id.to_string(), notebook_id.map(str::to_string)), ) .await?; self.changed(Change::Note(note_id.to_owned())); Ok(()) } /// Deletes the note together with its updates, snapshot and searchable text. pub async fn delete_note(&self, note_id: &str) -> anyhow::Result<()> { let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; delete_note_rows(&tx, note_id).await?; tx.commit().await?; self.changed(Change::Note(note_id.to_owned())); Ok(()) } /// Moves the note to the trash. It stays readable by `get_note` and is hidden /// from lists and search until restored or purged. pub async fn trash_note(&self, note_id: &str) -> anyhow::Result<()> { let conn = self.conn.lock().await; conn.execute( "UPDATE notes SET trashed_at = ?2 WHERE id = ?1", (note_id.to_string(), now_millis()), ) .await?; self.changed(Change::Note(note_id.to_owned())); Ok(()) } /// Takes the note out of the trash. pub async fn restore_note(&self, note_id: &str) -> anyhow::Result<()> { let conn = self.conn.lock().await; conn.execute( "UPDATE notes SET trashed_at = NULL WHERE id = ?1", (note_id.to_string(),), ) .await?; self.changed(Change::Note(note_id.to_owned())); Ok(()) } /// Permanently deletes notes trashed more than `older_than_ms` milliseconds ago. /// Returns the ids of the deleted notes. pub async fn purge_trash(&self, older_than_ms: i64) -> anyhow::Result> { let cutoff = now_millis().saturating_sub(older_than_ms); self.delete_trashed(cutoff).await } /// Permanently deletes every trashed note. Returns the ids of the deleted notes. pub async fn empty_trash(&self) -> anyhow::Result> { self.delete_trashed(i64::MAX).await } /// Deletes trashed notes with `trashed_at < before` in one transaction. async fn delete_trashed(&self, before: i64) -> anyhow::Result> { let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; let mut rows = tx .query( "SELECT id FROM notes WHERE trashed_at IS NOT NULL AND trashed_at < ?1 ORDER BY trashed_at, id", (before,), ) .await?; let mut ids = Vec::new(); while let Some(row) = rows.next().await? { ids.push(text_col(&row, 0)?); } drop(rows); for id in &ids { delete_note_rows(&tx, id).await?; } tx.commit().await?; for id in &ids { self.changed(Change::Note(id.clone())); } Ok(ids) } /// Notes that are not in the trash, most recently updated first. pub async fn list_notes(&self) -> anyhow::Result> { let mut notes: Vec = self.directory().await?.live().iter().map(|e| e.meta()).collect(); notes.sort_by(|a, b| b.updated_at.cmp(&a.updated_at).then_with(|| a.id.cmp(&b.id))); Ok(notes) } /// The most recently updated note outside the trash whose `title_key` is `key`. pub async fn note_by_title_key(&self, key: &str) -> anyhow::Result> { let dir = self.directory().await?; Ok(dir .entries() .filter(|e| e.trashed_at.is_none() && title_key(e.title()) == key) .max_by(|a, b| a.updated_at.cmp(&b.updated_at).then_with(|| b.id().cmp(a.id()))) .map(|e| e.meta())) } /// One page of the notes `filter` selects, in the order of the list: `limit` rows /// after the first `offset`. pub async fn list_notes_page( &self, filter: ListFilter, limit: usize, offset: usize, ) -> anyhow::Result> { let (clause, params) = filter.clause(); // Both are plain numbers, so they are written into the SQL rather than bound. let sql = format!( "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes WHERE {clause} ORDER BY {} LIMIT {limit} OFFSET {offset}", filter.order() ); let conn = self.conn.lock().await; let mut rows = conn.query(sql, params).await?; let mut notes = Vec::new(); while let Some(row) = rows.next().await? { notes.push(note_from_row(&row)?); } Ok(notes) } /// How many notes `filter` selects. pub async fn count_filter(&self, filter: &ListFilter) -> anyhow::Result { let dir = self.directory().await?; let c = &dir.counts; Ok(match filter { ListFilter::All => c.live, ListFilter::Unfiled => c.unfiled, ListFilter::Notebook(id) => c.notebooks.get(id).copied().unwrap_or(0), ListFilter::Trash => c.trashed, }) } /// Counts for the sidebar: notes outside the trash, notes outside the trash in no /// notebook, and trashed notes. pub async fn count_notes(&self) -> anyhow::Result<(usize, usize, usize)> { let dir = self.directory().await?; Ok((dir.counts.live, dir.counts.unfiled, dir.counts.trashed)) } /// Number of notes outside the trash in each notebook, keyed by notebook id. Notebooks /// with no notes are absent. pub async fn notebook_counts(&self) -> anyhow::Result> { Ok(self.directory().await?.counts.notebooks.clone()) } pub async fn get_note(&self, id: &str) -> anyhow::Result> { let conn = self.read.lock().await; let mut rows = conn .query( "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes WHERE id = ?1", (id.to_string(),), ) .await?; match rows.next().await? { Some(row) => Ok(Some(note_from_row(&row)?)), None => Ok(None), } } /// Appends a Loro update. Idempotent: the same bytes stored twice are kept once. pub async fn append_update(&self, note_id: &str, update: &[u8]) -> anyhow::Result<()> { let hash = blake3::hash(update).as_bytes().to_vec(); let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; let inserted = tx .execute( "INSERT OR IGNORE INTO updates (note_id, hash, data) VALUES (?1, ?2, ?3)", (note_id.to_string(), hash, update.to_vec()), ) .await?; if inserted > 0 { tx.execute( "UPDATE notes SET updated_at = ?2 WHERE id = ?1", (note_id.to_string(), now_millis()), ) .await?; } tx.commit().await?; if inserted > 0 { self.changed(Change::Note(note_id.to_owned())); } Ok(()) } pub async fn load_doc(&self, note_id: &str) -> anyhow::Result { let conn = self.conn.lock().await; let mut rows = conn .query( "SELECT data, upto_seq, markdown FROM snapshots WHERE note_id = ?1", (note_id.to_string(),), ) .await?; let (snapshot, upto_seq, markdown) = match rows.next().await? { Some(row) => (Some(blob_col(&row, 0)?), int_col(&row, 1)?, opt_text_col(&row, 2)?), None => (None, 0, None), }; drop(rows); let mut rows = conn .query( "SELECT data FROM updates WHERE note_id = ?1 AND seq > ?2 ORDER BY seq", (note_id.to_string(), upto_seq), ) .await?; let mut updates = Vec::new(); while let Some(row) = rows.next().await? { updates.push(blob_col(&row, 0)?); } drop(rows); let markdown = match snapshot { Some(_) => markdown.filter(|_| updates.is_empty()), None => { let mut rows = conn .query("SELECT markdown FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),)) .await?; match rows.next().await? { Some(row) => Some(text_col(&row, 0)?), None => None, } } }; Ok(DocBytes { snapshot, updates, markdown, export: None, upto_seq }) } /// [`load_doc`](Self::load_doc) for many notes, in the order of `ids`, with a few /// queries per `PREVIEW_BATCH` notes rather than two per note. /// The stored state of each of `ids`, for the export: a note whose export markdown /// is cached for its snapshot comes without the snapshot, and so does one whose /// stored markdown is current, unless it is in `linking`. pub async fn load_docs(&self, ids: &[String], linking: &std::collections::HashSet) -> anyhow::Result> { let empty = || DocBytes { snapshot: None, updates: Vec::new(), markdown: None, export: None, upto_seq: 0 }; let mut docs: HashMap = HashMap::new(); let conn = self.conn.lock().await; for chunk in ids.chunks(PREVIEW_BATCH) { let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::>().join(", "); let mut rows = conn .query( format!( "SELECT s.note_id, s.upto_seq, CASE WHEN e.markdown IS NULL THEN s.markdown END, e.markdown, CASE WHEN e.markdown IS NULL AND s.markdown IS NULL THEN s.data END FROM snapshots s LEFT JOIN export_text e ON e.note_id = s.note_id AND e.upto_seq = s.upto_seq WHERE s.note_id IN ({placeholders})" ), chunk.to_vec(), ) .await?; while let Some(row) = rows.next().await? { let export = opt_text_col(&row, 3)?; let snapshot = opt_blob_col(&row, 4)?; let doc = DocBytes { snapshot, updates: Vec::new(), markdown: opt_text_col(&row, 2)?, export, upto_seq: int_col(&row, 1)? }; docs.insert(text_col(&row, 0)?, doc); } drop(rows); let mut rows = conn .query( format!("SELECT note_id, seq, data FROM updates WHERE note_id IN ({placeholders}) ORDER BY seq"), chunk.to_vec(), ) .await?; while let Some(row) = rows.next().await? { let id = text_col(&row, 0)?; let doc = docs.entry(id).or_insert_with(empty); if int_col(&row, 1)? > doc.upto_seq { doc.updates.push(blob_col(&row, 2)?); doc.markdown = None; doc.export = None; } } drop(rows); // Edited since its markdown was stored, or linking: the snapshot is needed after all. let stale: Vec = chunk .iter() .filter(|id| { docs.get(*id).is_some_and(|d| { d.snapshot.is_none() && d.export.is_none() && (d.markdown.is_none() || linking.contains(*id)) }) }) .cloned() .collect(); for id in stale { let mut rows = conn.query("SELECT data FROM snapshots WHERE note_id = ?1", (id.clone(),)).await?; if let Some(row) = rows.next().await? { docs.get_mut(&id).unwrap().snapshot = Some(blob_col(&row, 0)?); } } let mut rows = conn .query( format!("SELECT note_id, markdown FROM pending_docs WHERE note_id IN ({placeholders})"), chunk.to_vec(), ) .await?; while let Some(row) = rows.next().await? { docs.insert(text_col(&row, 0)?, DocBytes { markdown: Some(text_col(&row, 1)?), ..empty() }); } } Ok(ids.iter().map(|id| docs.remove(id).unwrap_or_else(empty)).collect()) } /// Streams every cached export markdown that is current for its snapshot, as /// `(note id, markdown)` batches of about `batch_bytes`, read on a connection of its /// own so other requests go on meanwhile. A note edited since its snapshot may /// still come: see [`Store::stale_snapshots`]. pub fn scan_export_texts(&self, batch_bytes: usize) -> anyhow::Result>>> { let conn = self.db.connect()?; let (tx, rx) = mpsc::channel(2); tokio::spawn(async move { let result = async { let mut rows = conn .query( // Joining snapshots would read their blobs: a new snapshot drops // the row instead (see put_snapshot). "SELECT note_id, markdown FROM export_text", (), ) .await?; let (mut batch, mut bytes) = (Vec::new(), 0); while let Some(row) = rows.next().await? { let md = text_col(&row, 1)?; bytes += md.len() + 64; batch.push((text_col(&row, 0)?, md)); if bytes > batch_bytes { bytes = 0; if tx.send(Ok(std::mem::take(&mut batch))).await.is_err() { return Ok(()); } } } let _ = tx.send(Ok(batch)).await; anyhow::Ok(()) } .await; if let Err(err) = result { let _ = tx.send(Err(err)).await; } }); Ok(rx) } /// Caches export markdown (see [`DocBytes::export`]) as `(note id, snapshot's last /// update, markdown)`. pub async fn put_export_texts(&self, texts: &[(String, i64, String)]) -> anyhow::Result<()> { let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; for (id, upto_seq, markdown) in texts { // A newer snapshot may have been written since this was rendered. let mut rows = tx.query("SELECT upto_seq FROM snapshots WHERE note_id = ?1", (id.clone(),)).await?; let current = match rows.next().await? { Some(row) => int_col(&row, 0)? == *upto_seq, None => false, }; drop(rows); if !current { continue; } tx.execute( "INSERT INTO export_text (note_id, upto_seq, markdown) VALUES (?1, ?2, ?3) ON CONFLICT(note_id) DO UPDATE SET upto_seq = excluded.upto_seq, markdown = excluded.markdown", (id.clone(), *upto_seq, markdown.clone()), ) .await?; } tx.commit().await?; Ok(()) } /// Notes with updates newer than their snapshot: a snapshot was due when the server /// stopped. Their docs load slower until a new snapshot covers them. pub async fn stale_snapshots(&self) -> anyhow::Result> { // Two plain reads: turso scans every update for each note when they are joined. let conn = self.conn.lock().await; let mut rows = conn.query("SELECT note_id, seq FROM updates", ()).await?; let mut newest: HashMap = HashMap::new(); while let Some(row) = rows.next().await? { let seq = int_col(&row, 1)?; let max = newest.entry(text_col(&row, 0)?).or_insert(seq); *max = (*max).max(seq); } drop(rows); let ids: Vec = newest.keys().cloned().collect(); for chunk in ids.chunks(PREVIEW_BATCH) { let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::>().join(", "); let mut rows = conn .query(format!("SELECT note_id, upto_seq FROM snapshots WHERE note_id IN ({placeholders})"), chunk.to_vec()) .await?; while let Some(row) = rows.next().await? { let id = text_col(&row, 0)?; if newest.get(&id).is_some_and(|max| *max <= int_col(&row, 1).unwrap_or(0)) { newest.remove(&id); } } } Ok(newest.into_keys().collect()) } /// The newest stored update's sequence number for the note, 0 when there is none. pub async fn max_seq(&self, note_id: &str) -> anyhow::Result { let conn = self.conn.lock().await; let mut rows = conn .query("SELECT COALESCE(MAX(seq), 0) FROM updates WHERE note_id = ?1", (note_id.to_string(),)) .await?; match rows.next().await? { Some(row) => int_col(&row, 0), None => Ok(0), } } /// Whether the note's stored text links to other notes. pub async fn has_links(&self, note_id: &str) -> anyhow::Result { let conn = self.read.lock().await; let mut rows = conn .query("SELECT 1 FROM note_links WHERE src = ?1 LIMIT 1", (note_id.to_string(),)) .await?; Ok(rows.next().await?.is_some()) } /// Every note whose stored text links to other notes. pub async fn linking_notes(&self) -> anyhow::Result> { let conn = self.conn.lock().await; // Deduplicated here: turso's DISTINCT spills and thrashes on millions of rows. let mut rows = conn.query("SELECT src FROM note_links", ()).await?; let mut out = std::collections::HashSet::new(); while let Some(row) = rows.next().await? { out.insert(text_col(&row, 0)?); } Ok(out) } /// Ids of the notes some note links to. pub async fn link_targets(&self) -> anyhow::Result> { let conn = self.conn.lock().await; let mut rows = conn.query("SELECT dst_id FROM note_links WHERE dst_id IS NOT NULL", ()).await?; let mut out = std::collections::HashSet::new(); while let Some(row) = rows.next().await? { out.insert(text_col(&row, 0)?); } Ok(out) } /// Titles of the given notes that are outside the trash, by id. pub async fn titles_of(&self, ids: impl IntoIterator) -> anyhow::Result> { let dir = self.directory().await?; Ok(ids .into_iter() .filter_map(|id| { let e = dir.get(&id).filter(|e| e.trashed_at.is_none())?; Some((id, e.title().to_owned())) }) .collect()) } /// Stores a full snapshot that holds every update up to `upto_seq`, plus the derived /// markdown and title. A snapshot older than the stored one is ignored, and so is /// the result `false`. Updates are never deleted; later loads only read updates /// newer than the snapshot. pub async fn put_snapshot( &self, note_id: &str, snapshot: Vec, upto_seq: i64, markdown: &str, title: &str, ) -> anyhow::Result { let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; // Only a snapshot at least as new replaces the stored one. Delete, then insert: // an upsert reads the old row whole, and a huge note's row is hundreds of MB. let mut rows = tx .query("SELECT upto_seq FROM snapshots WHERE note_id = ?1", (note_id.to_string(),)) .await?; let stored = match rows.next().await? { Some(row) => Some(int_col(&row, 0)?), None => None, }; drop(rows); if stored.is_some_and(|stored| stored > upto_seq) { return Ok(false); } if stored.is_some() { tx.execute("DELETE FROM snapshots WHERE note_id = ?1", (note_id.to_string(),)).await?; } tx.execute( "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, ?3, ?4)", ( note_id.to_string(), snapshot, upto_seq, markdown.to_string(), ), ) .await?; // The snapshot holds every op of the updates up to it. tx.execute("DELETE FROM updates WHERE note_id = ?1 AND seq <= ?2", (note_id.to_string(), upto_seq)).await?; tx.execute("DELETE FROM export_text WHERE note_id = ?1 AND upto_seq <> ?2", (note_id.to_string(), upto_seq)).await?; tx.execute( "UPDATE notes SET title = ?2 WHERE id = ?1", (note_id.to_string(), title.to_string()), ) .await?; tx.commit().await?; self.changed(Change::Note(note_id.to_owned())); Ok(true) } pub async fn set_title(&self, note_id: &str, title: &str) -> anyhow::Result<()> { let conn = self.conn.lock().await; conn.execute( "UPDATE notes SET title = ?2 WHERE id = ?1", (note_id.to_string(), title.to_string()), ) .await?; self.changed(Change::Note(note_id.to_owned())); Ok(()) } /// Writes the searchable text of a note. Does nothing when the note no longer /// exists, so a flush that races a delete cannot bring the text back. pub async fn put_text(&self, note_id: &str, title: &str, body: &str) -> anyhow::Result<()> { let mut conn = self.conn.lock().await; let mut rows = conn .query("SELECT 1 FROM notes WHERE id = ?1", (note_id.to_string(),)) .await?; let exists = rows.next().await?.is_some(); drop(rows); if !exists { return Ok(()); } // Delete, then insert: an upsert reads the old row whole. let tx = conn.transaction().await?; tx.execute("DELETE FROM note_text WHERE note_id = ?1", (note_id.to_string(),)).await?; tx.execute( "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3)", (note_id.to_string(), title.to_string(), body.to_string()), ) .await?; tx.commit().await?; self.changed(Change::Note(note_id.to_owned())); Ok(()) } /// Replaces the note links of `src`. Does nothing when the note no longer exists, like /// `put_text`. Title targets are stored by `title_key`. pub async fn set_links(&self, src: &str, targets: &[LinkTarget]) -> anyhow::Result<()> { let mut conn = self.conn.lock().await; let mut rows = conn .query("SELECT 1 FROM notes WHERE id = ?1", (src.to_string(),)) .await?; let exists = rows.next().await?.is_some(); drop(rows); if !exists { return Ok(()); } let tx = conn.transaction().await?; tx.execute("DELETE FROM note_links WHERE src = ?1", (src.to_string(),)) .await?; insert_links(&tx, src, targets).await?; tx.commit().await?; Ok(()) } /// Creates a note from imported content in one transaction: the note row in the /// notebook named `notebook` (matched case-insensitively, created when missing), /// its snapshot, searchable text, links and export markdown (see [`DocBytes::export`]). /// Returns the note id. pub async fn import_note( &self, notebook: Option<&str>, snapshot: Option<&[u8]>, title: &str, body: &str, links: &[LinkTarget], export: Option<&str>, ) -> anyhow::Result { let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; let notebook_id = match notebook { Some(name) => Some(match find_notebook(&tx, name).await? { Some(id) => id, None => { let id = uuid::Uuid::now_v7().to_string(); tx.execute( "INSERT INTO notebooks (id, name, created_at) VALUES (?1, ?2, ?3)", (id.clone(), name.to_string(), now_millis()), ) .await?; id } }), None => None, }; let id = uuid::Uuid::now_v7().to_string(); let now = now_millis(); tx.execute( "INSERT INTO notes (id, title, created_at, updated_at, notebook_id) VALUES (?1, ?2, ?3, ?4, ?5)", (id.clone(), title.to_string(), now, now, notebook_id), ) .await?; match snapshot { Some(snapshot) => { tx.execute( "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, 0, ?3)", (id.clone(), snapshot.to_vec(), body.to_string()), ) .await?; if let Some(export) = export { tx.execute( "INSERT INTO export_text (note_id, upto_seq, markdown) VALUES (?1, 0, ?2)", (id.clone(), export.to_string()), ) .await?; } } None => { tx.execute("INSERT INTO pending_docs (note_id, markdown) VALUES (?1, ?2)", (id.clone(), body.to_string())) .await?; } } tx.execute( "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3)", (id.clone(), title.to_string(), body.to_string()), ) .await?; insert_links(&tx, &id, links).await?; tx.commit().await?; self.changed(Change::Note(id.clone())); Ok(id) } /// Notes imported without a doc yet, oldest first. pub async fn pending_docs(&self) -> anyhow::Result> { let conn = self.conn.lock().await; let mut rows = conn.query("SELECT note_id FROM pending_docs ORDER BY note_id", ()).await?; let mut out = Vec::new(); while let Some(row) = rows.next().await? { out.push(text_col(&row, 0)?); } Ok(out) } /// The first `bytes` bytes or so of a pending note's markdown, cut at a line end. pub async fn pending_head(&self, note_id: &str, bytes: usize) -> anyhow::Result> { let conn = self.read.lock().await; let mut rows = conn .query( "SELECT substr(markdown, 1, ?2) FROM pending_docs WHERE note_id = ?1", (note_id.to_string(), bytes as i64), ) .await?; let Some(row) = rows.next().await? else { return Ok(None) }; let mut head = text_col(&row, 0)?; if head.len() >= bytes && let Some(end) = head.rfind('\n') { head.truncate(end + 1); } Ok(Some(head)) } /// The imported markdown of a note whose doc is not built yet. pub async fn pending_markdown(&self, note_id: &str) -> anyhow::Result> { let conn = self.conn.lock().await; let mut rows = conn .query("SELECT markdown FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),)) .await?; match rows.next().await? { Some(row) => Ok(Some(text_col(&row, 0)?)), None => Ok(None), } } /// Replaces a pending note's markdown with its built doc, and the text derived from /// it. Does nothing when the note is gone or no longer pending. pub async fn finish_pending( &self, note_id: &str, snapshot: &[u8], title: &str, body: &str, links: &[LinkTarget], ) -> anyhow::Result<()> { let mut conn = self.conn.lock().await; let tx = conn.transaction().await?; let id = note_id.to_string(); if tx.execute("DELETE FROM pending_docs WHERE note_id = ?1", (id.clone(),)).await? == 0 { return Ok(()); } tx.execute( "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, 0, ?3)", (id.clone(), snapshot.to_vec(), body.to_string()), ) .await?; tx.execute("UPDATE notes SET title = ?2 WHERE id = ?1", (id.clone(), title.to_string())).await?; tx.execute( "UPDATE note_text SET title = ?2, body = ?3 WHERE note_id = ?1", (id.clone(), title.to_string(), body.to_string()), ) .await?; tx.execute("DELETE FROM note_links WHERE src = ?1", (id.clone(),)).await?; insert_links(&tx, note_id, links).await?; tx.commit().await?; self.changed(Change::Note(id)); Ok(()) } /// Non-trashed notes, other than `note_id`, that link to the note by its id or by /// its title. Most recently updated first. pub async fn backlinks(&self, note_id: &str, title: &str) -> anyhow::Result> { let conn = self.read.lock().await; let mut rows = conn .query( "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes WHERE trashed_at IS NULL AND id <> ?1 AND id IN (SELECT src FROM note_links WHERE dst_id = ?1 OR dst_title = ?2) ORDER BY updated_at DESC, id", (note_id.to_string(), title_key(title)), ) .await?; let mut notes = Vec::new(); while let Some(row) = rows.next().await? { notes.push(note_from_row(&row)?); } Ok(notes) } /// Search over titles and bodies with `matcher` (see [`crate::matcher`]): every term /// must match the title or the text. Closest matches first, then more terms in the /// title, then most recently updated. /// /// Long notes are matched against their stored text, which for a pattern without a /// literal means reading all of it. With a `budget`, that stops once the budget is /// spent, and the result says it is partial: the best hits found so far. pub async fn search(&self, matcher: &Matcher, limit: usize, budget: Option) -> anyhow::Result { if limit == 0 { return Ok(Searched::default()); } let started = std::time::Instant::now(); // Words are matched rather than looked up: typing "asd" has to find "asdadasxd" // (and "isik" find "Işık"). The directory is read in place, on this worker. let dir = self.directory().await?; let (mut hits, cut) = tokio::task::block_in_place(|| { let hits = match_top(matcher, dir.slots(), &dir.vocab, limit); // With the least each can cost: no cost, unless the words say otherwise. let mut cut: Vec<(Arc, usize)> = match matcher.word_terms() { Some(_) => Vec::new(), None => dir.entries().filter(|e| e.plain_cut && e.trashed_at.is_none()).map(|e| (e.clone(), 0)).collect(), }; // Notes without the words a match needs are not read. An exact phrase costs // nothing only where its first word starts a word. if let Some(alts) = matcher.required_words().filter(|_| !cut.is_empty()) { let vocab = dir.vocab.read().unwrap(); let mask = |piece: &[char], part: Part| (0..vocab.len()).map(|id| part.holds(vocab.word(id), piece)).collect::>(); let holds: Vec>> = alts.iter().map(|words| words.iter().map(|(piece, part)| mask(piece, *part)).collect()).collect(); let starts = matches!(matcher, Matcher::Terms { .. }).then(|| match &alts[0][0] { (piece, Part::End) => mask(piece, Part::Whole), (piece, Part::Inside) => mask(piece, Part::Start), _ => holds[0][0].clone(), }); drop(vocab); let has = |e: &Entry, h: &[bool]| e.text_words().iter().any(|&id| h[id as usize]); cut.retain(|(e, _)| holds.iter().any(|alt| alt.iter().all(|h| has(e, h) || e.title_words().iter().any(|&id| h[id as usize])))); if let Some(starts) = starts { for (e, floor) in &mut cut { *floor = usize::from(!has(e, &starts)); } } } // A regex that only matches inside words needs a word it matches. if let Some(re) = matcher.word_regex().filter(|_| !cut.is_empty()) { let vocab = dir.vocab.read().unwrap(); let mut word = String::new(); let hits: Vec = (0..vocab.len()) .map(|id| { word.clear(); word.extend(vocab.word(id).iter()); re.is_match(&word) }) .collect(); drop(vocab); cut.retain(|(e, _)| e.text_words().iter().chain(e.title_words()).any(|&id| hits[id as usize])); } (hits, cut) }); drop(dir); // Long notes keep only their start in memory: match them against their stored // text, a few at a time, and keep the text of those that match for the snippet. // The best key each could get, from its title: the text matching at no cost. // Going from the best bound, the rest can stop once `limit` hits beat it. let bound = |e: &Entry, floor: usize| -> RankKey { let in_title = matcher.term_costs(e.title()); let zero = in_title.iter().filter(|c| **c == Some(0)).count(); let cost = in_title.iter().map(|c| if *c == Some(0) { 0 } else { floor }).sum(); ((cost, std::cmp::Reverse(zero)), std::cmp::Reverse(e.updated_at)) }; let mut cut: Vec<(RankKey, Arc, usize)> = cut.into_iter().map(|(e, floor)| (bound(&e, floor), e, floor)).collect(); cut.sort_unstable_by(|a, b| a.0.cmp(&b.0)); // The start of each is in memory: its full text is read, on a connection of its // own, only when the start does not settle the match. let per_batch = std::thread::available_parallelism().map_or(1, |n| n.get()); let (want, mut wanted) = (mpsc::channel::>(1), mpsc::channel::>>(1)); let (mut requests, answers) = (want.1, wanted.0); // One connection reads some 1.5 GB/s: a few share each batch. let readers: Vec> = (0..SEARCH_READERS).map(|_| self.db.connect().map(Arc::new)).collect::>()?; tokio::spawn(async move { while let Some(ids) = requests.recv().await { let parts = ids.chunks(ids.len().div_ceil(readers.len()).max(1)).zip(&readers).map(|(part, conn)| { let (part, conn) = (part.to_vec(), conn.clone()); tokio::spawn(async move { bodies_on(&conn, &part).await }) }); let mut bodies = HashMap::new(); let mut result = Ok(()); for part in parts.collect::>() { match part.await.map_err(anyhow::Error::from).and_then(|r| r) { Ok(b) => bodies.extend(b), Err(e) => result = Err(e), } } if answers.send(result.map(|_| bodies)).await.is_err() { return; } } }); let ask = want.0; let mut snippets: HashMap = HashMap::new(); type Found = Option<(SearchKey, String)>; let par = |f: &(dyn Fn(&(Arc, usize)) -> (Found, bool) + Sync), entries: &[(Arc, usize)]| { tokio::task::block_in_place(|| { std::thread::scope(|scope| { let handles: Vec<_> = entries.iter().map(|e| scope.spawn(move || f(e))).collect(); handles.into_iter().map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect::>() }) }) }; let from_bodies = |bodies: &HashMap, entries: &[(Arc, usize)]| -> Vec { par(&|(e, floor)| (bodies.get(e.id()).and_then(|body| match_long(e.title(), body, matcher, *floor)), true), entries) .into_iter() .map(|(found, _)| found) .collect() }; let mut found_in = |entries: Vec<(Arc, usize)>, found: Vec, hits: &mut Vec<(RankKey, Arc)>| { for ((e, _), found) in entries.into_iter().zip(found) { if let Some((k, snip)) = found { snippets.insert(e.id().to_owned(), snip); hits.push(((k, std::cmp::Reverse(e.updated_at)), e)); } } }; // The notes whose texts were asked for: the next batch is read while they are // matched. let mut asked: Vec<(Arc, usize)> = Vec::new(); let mut partial = false; for batch in cut.chunks(per_batch) { if budget.is_some_and(|b| started.elapsed() >= b) { partial = true; break; } if hits.len() >= limit { hits = top_keyed(hits, limit, |e| e.id()); if hits.last().is_some_and(|(k, _)| *k < batch[0].0) { break; } } let entries: Vec<(Arc, usize)> = batch.iter().map(|(_, e, floor)| (e.clone(), *floor)).collect(); let from_start = par(&|(e, floor)| match_pieces(e.title(), plain_pieces(e.plain()), matcher, *floor), &entries); let (mut settled, mut settled_found, mut unsettled) = (Vec::new(), Vec::new(), Vec::new()); for (e, (found, perfect)) in entries.into_iter().zip(from_start) { if perfect { settled.push(e); settled_found.push(found); } else { unsettled.push(e); } } found_in(settled, settled_found, &mut hits); if !unsettled.is_empty() { ask.send(unsettled.iter().map(|(e, _)| e.id().to_owned()).collect()).await?; } let previous = std::mem::replace(&mut asked, unsettled); if !previous.is_empty() { let bodies = wanted.1.recv().await.context("reading note texts")??; let found = from_bodies(&bodies, &previous); found_in(previous, found, &mut hits); } } // Out of time: the batch still being read is left unread. if !asked.is_empty() && !partial { let bodies = wanted.1.recv().await.context("reading note texts")??; let found = from_bodies(&bodies, &asked); found_in(asked, found, &mut hits); } let hits = top(hits, limit, |e| e.id()); // Snippets only for the hits shown: a common word matches nearly every note. let hits = hits .into_iter() .map(|e| SearchHit { snippet: snippets.remove(e.id()).unwrap_or_else(|| snippet(e.plain(), matcher)), note: e.meta(), }) .collect(); Ok(Searched { hits, partial }) } /// Notes, not in the trash, whose title holds every word of `query`, typos allowed /// (see [`crate::matcher`]). Closest matches first, then most recently updated. pub async fn search_titles(&self, query: &str, limit: usize) -> anyhow::Result> { let Some(matcher) = Matcher::simple(query) else { return Ok(Vec::new()); }; if limit == 0 { return Ok(Vec::new()); } // Matched in Rust, not with SQL LIKE, which folds only ASCII case and has no // typo tolerance: "izmir" and "izmr" have to find "İzmir". let dir = self.directory().await?; // Closest first, then most recently updated. let hits = tokio::task::block_in_place(|| { let terms = matcher.word_terms().unwrap_or_default(); let tables = word_costs(&matcher, terms, &dir.vocab.read().unwrap()); par_top(dir.slots(), limit, |e| { let cost = tables.iter().map(|t| best_cost(t, e.title_words())).sum::>()?; Some((cost, std::cmp::Reverse(e.updated_at))) }) }); Ok(hits.into_iter().map(|e| e.meta()).collect()) } /// Previews of the given notes' text, keyed by note id, for list rows. pub async fn previews_for(&self, ids: &[String]) -> anyhow::Result> { let dir = self.directory().await?; Ok(ids.iter().filter_map(|id| Some((id.clone(), dir.get(id)?.preview().to_string()))).collect()) } /// Stores a version of a note: the time in millis and the encoded frontiers of the doc. pub async fn add_version(&self, note_id: &str, at_ms: i64, frontiers: &[u8]) -> anyhow::Result<()> { let conn = self.conn.lock().await; conn.execute( "INSERT OR REPLACE INTO note_versions (note_id, at, frontiers) VALUES (?1, ?2, ?3)", (note_id.to_string(), at_ms, frontiers.to_vec()), ) .await?; Ok(()) } /// Recorded versions of a note as `(at, frontiers)`, newest first. pub async fn list_versions(&self, note_id: &str) -> anyhow::Result)>> { let conn = self.conn.lock().await; let mut rows = conn .query( "SELECT at, frontiers FROM note_versions WHERE note_id = ?1 ORDER BY at DESC", (note_id.to_string(),), ) .await?; let mut versions = Vec::new(); while let Some(row) = rows.next().await? { versions.push((int_col(&row, 0)?, blob_col(&row, 1)?)); } Ok(versions) } /// The encoded frontiers of the version of a note taken at `at`, if it exists. pub async fn get_version(&self, note_id: &str, at: i64) -> anyhow::Result>> { let conn = self.conn.lock().await; let mut rows = conn .query( "SELECT frontiers FROM note_versions WHERE note_id = ?1 AND at = ?2", (note_id.to_string(), at), ) .await?; match rows.next().await? { Some(row) => Ok(Some(blob_col(&row, 0)?)), None => Ok(None), } } } #[cfg(test)] mod tests { use super::Store; #[tokio::test] async fn older_snapshot_does_not_replace_newer() { let dir = std::env::temp_dir().join(format!("note-test-{}", uuid::Uuid::now_v7())); std::fs::create_dir_all(&dir).unwrap(); let store = Store::open(dir.join("t.db").to_str().unwrap()).await.unwrap(); let note = store.create_note(None).await.unwrap(); assert!(store.put_snapshot(¬e.id, b"new".to_vec(), 5, "new", "t").await.unwrap()); assert!(!store.put_snapshot(¬e.id, b"old".to_vec(), 3, "old", "t").await.unwrap()); let doc = store.load_doc(¬e.id).await.unwrap(); assert_eq!(doc.snapshot.as_deref(), Some(&b"new"[..])); assert_eq!(doc.markdown.as_deref(), Some("new")); let _ = std::fs::remove_dir_all(&dir); } }