forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

store.rs2221 lines, 91.1 KiBHistoryRawDownload
1//! Persistence. The only module that talks to turso.
2
3mod directory;
4
5use std::collections::HashMap;
6
7use tokio::sync::mpsc;
8use std::sync::{Arc, RwLock};
9use std::time::{SystemTime, UNIX_EPOCH};
10
11use anyhow::{Context, anyhow};
12
13use crate::matcher::{Matcher, Part};
14use tokio::sync::Mutex;
15
16use crate::export::LinkTarget;
17use directory::{Change, Directory, Entry, Vocab};
18
19#[derive(Clone)]
20pub struct NoteMeta {
21 pub id: String,
22 pub title: String,
23 pub created_at: i64,
24 pub updated_at: i64,
25 /// `None` when the note is not in any notebook.
26 pub notebook_id: Option<String>,
27 /// `None` when the note is not in the trash. Millis when it was trashed.
28 pub trashed_at: Option<i64>,
29}
30
31/// Which notes a list shows. Every filter but `Trash` leaves the trash out.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub enum ListFilter {
34 /// Every note outside the trash.
35 All,
36 /// Notes outside the trash that are in no notebook.
37 Unfiled,
38 /// Notes outside the trash that are in the notebook with this id.
39 Notebook(String),
40 /// Trashed notes, most recently trashed first.
41 Trash,
42}
43
44impl ListFilter {
45 /// The WHERE clause for this filter, and the parameters it binds (`?1` when any).
46 fn clause(&self) -> (&'static str, Vec<String>) {
47 match self {
48 Self::All => ("trashed_at IS NULL", Vec::new()),
49 Self::Unfiled => ("trashed_at IS NULL AND notebook_id IS NULL", Vec::new()),
50 Self::Notebook(id) => ("trashed_at IS NULL AND notebook_id = ?1", vec![id.clone()]),
51 Self::Trash => ("trashed_at IS NOT NULL", Vec::new()),
52 }
53 }
54
55 /// The ORDER BY for this filter: most recently updated first, or most recently trashed
56 /// first for the trash. Ties go to the newer id, so the order is an index read
57 /// backwards rather than a sort of every row.
58 fn order(&self) -> &'static str {
59 match self {
60 Self::Trash => "trashed_at DESC, id DESC",
61 _ => "updated_at DESC, id DESC",
62 }
63 }
64}
65
66pub struct Notebook {
67 pub id: String,
68 pub name: String,
69 pub created_at: i64,
70}
71
72/// Snapshot (if any) plus every update stored after it, in insertion order.
73pub struct DocBytes {
74 pub snapshot: Option<Vec<u8>>,
75 pub updates: Vec<Vec<u8>>,
76 /// The markdown stored with the snapshot, when no update came after it.
77 pub markdown: Option<String>,
78 /// [`crate::export::to_markdown_deferred`] of the doc, when cached for its snapshot
79 /// and no update came after it. Only read by [`Store::load_docs`], which then skips
80 /// the snapshot.
81 pub export: Option<String>,
82 /// The snapshot's last update, 0 without a snapshot.
83 pub upto_seq: i64,
84}
85
86impl DocBytes {
87 /// Bytes held: what reading the note cost.
88 pub fn stored_len(&self) -> usize {
89 let text = |t: &Option<String>| t.as_ref().map_or(0, String::len);
90 self.snapshot.as_ref().map_or(0, Vec::len) + self.updates.iter().map(Vec::len).sum::<usize>() + text(&self.markdown) + text(&self.export)
91 }
92}
93
94pub struct Store {
95 /// Single connection shared by all tasks. Calls are serialized by the mutex,
96 /// which also keeps transactions from interleaving on one connection.
97 conn: Mutex<turso::Connection>,
98 /// A second connection for single-statement reads: in WAL they do not wait for a
99 /// write, and a huge note's write holds `conn` for seconds.
100 read: Mutex<turso::Connection>,
101 /// Loaded on first use. See [`directory`].
102 dir: Mutex<Option<Directory>>,
103 /// Writes committed since the directory was last read, in order.
104 changes: std::sync::Mutex<Vec<Change>>,
105 /// Notes whose text changed but is too long to index while the directory waits:
106 /// [`Store::keep_directory_fresh`] indexes them off its lock.
107 heavy: std::sync::Mutex<HashMap<String, std::time::Instant>>,
108 /// Keeps the database handle alive for as long as the connection is used.
109 db: turso::Database,
110}
111
112pub(crate) fn now_millis() -> i64 {
113 SystemTime::now()
114 .duration_since(UNIX_EPOCH)
115 .map(|d| d.as_millis() as i64)
116 .unwrap_or(0)
117}
118
119/// The form of a title that links match on: whitespace collapsed and lowercased.
120pub fn title_key(title: &str) -> String {
121 title
122 .split_whitespace()
123 .collect::<Vec<_>>()
124 .join(" ")
125 .to_lowercase()
126}
127
128fn text_col(row: &turso::Row, idx: usize) -> anyhow::Result<String> {
129 match row.get_value(idx)? {
130 turso::Value::Text(s) => Ok(s),
131 other => Err(anyhow!("column {idx}: expected TEXT, got {other:?}")),
132 }
133}
134
135fn opt_text_col(row: &turso::Row, idx: usize) -> anyhow::Result<Option<String>> {
136 match row.get_value(idx)? {
137 turso::Value::Null => Ok(None),
138 turso::Value::Text(s) => Ok(Some(s)),
139 other => Err(anyhow!("column {idx}: expected TEXT or NULL, got {other:?}")),
140 }
141}
142
143fn int_col(row: &turso::Row, idx: usize) -> anyhow::Result<i64> {
144 match row.get_value(idx)? {
145 turso::Value::Integer(i) => Ok(i),
146 other => Err(anyhow!("column {idx}: expected INTEGER, got {other:?}")),
147 }
148}
149
150fn opt_int_col(row: &turso::Row, idx: usize) -> anyhow::Result<Option<i64>> {
151 match row.get_value(idx)? {
152 turso::Value::Null => Ok(None),
153 turso::Value::Integer(i) => Ok(Some(i)),
154 other => Err(anyhow!("column {idx}: expected INTEGER or NULL, got {other:?}")),
155 }
156}
157
158fn blob_col(row: &turso::Row, idx: usize) -> anyhow::Result<Vec<u8>> {
159 match row.get_value(idx)? {
160 turso::Value::Blob(b) => Ok(b),
161 other => Err(anyhow!("column {idx}: expected BLOB, got {other:?}")),
162 }
163}
164
165fn opt_blob_col(row: &turso::Row, idx: usize) -> anyhow::Result<Option<Vec<u8>>> {
166 match row.get_value(idx)? {
167 turso::Value::Null => Ok(None),
168 turso::Value::Blob(b) => Ok(Some(b)),
169 other => Err(anyhow!("column {idx}: expected BLOB or NULL, got {other:?}")),
170 }
171}
172
173fn note_from_row(row: &turso::Row) -> anyhow::Result<NoteMeta> {
174 Ok(NoteMeta {
175 id: text_col(row, 0)?,
176 title: text_col(row, 1)?,
177 created_at: int_col(row, 2)?,
178 updated_at: int_col(row, 3)?,
179 notebook_id: opt_text_col(row, 4)?,
180 trashed_at: opt_int_col(row, 5)?,
181 })
182}
183
184/// Id of the notebook named `name`, ignoring case. The exact name is looked up first,
185/// through the index; other casings need a scan.
186async fn find_notebook(tx: &turso::transaction::Transaction<'_>, name: &str) -> anyhow::Result<Option<String>> {
187 let mut rows = tx.query("SELECT id FROM notebooks WHERE name = ?1 LIMIT 1", (name.to_string(),)).await?;
188 if let Some(row) = rows.next().await? {
189 return Ok(Some(text_col(&row, 0)?));
190 }
191 drop(rows);
192 let key = name.to_lowercase();
193 let mut rows = tx.query("SELECT id, name FROM notebooks", ()).await?;
194 while let Some(row) = rows.next().await? {
195 if text_col(&row, 1)?.to_lowercase() == key {
196 return Ok(Some(text_col(&row, 0)?));
197 }
198 }
199 Ok(None)
200}
201
202/// Inserts the note links of `src` inside an open transaction.
203async fn insert_links(
204 tx: &turso::transaction::Transaction<'_>,
205 src: &str,
206 targets: &[LinkTarget],
207) -> anyhow::Result<()> {
208 for target in targets {
209 match target {
210 LinkTarget::Id(id) => {
211 tx.execute(
212 "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, ?2, NULL)",
213 (src.to_string(), id.clone()),
214 )
215 .await?;
216 }
217 LinkTarget::Title(title) => {
218 let key = title_key(title);
219 if key.is_empty() {
220 continue;
221 }
222 tx.execute(
223 "INSERT INTO note_links (src, dst_id, dst_title) VALUES (?1, NULL, ?2)",
224 (src.to_string(), key),
225 )
226 .await?;
227 }
228 }
229 }
230 Ok(())
231}
232
233/// Deletes one note's rows inside an open transaction.
234async fn delete_note_rows(
235 tx: &turso::transaction::Transaction<'_>,
236 note_id: &str,
237) -> anyhow::Result<()> {
238 tx.execute("DELETE FROM updates WHERE note_id = ?1", (note_id.to_string(),))
239 .await?;
240 tx.execute("DELETE FROM snapshots WHERE note_id = ?1", (note_id.to_string(),))
241 .await?;
242 tx.execute("DELETE FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),))
243 .await?;
244 tx.execute("DELETE FROM export_text WHERE note_id = ?1", (note_id.to_string(),))
245 .await?;
246 tx.execute("DELETE FROM note_text WHERE note_id = ?1", (note_id.to_string(),))
247 .await?;
248 tx.execute("DELETE FROM note_versions WHERE note_id = ?1", (note_id.to_string(),))
249 .await?;
250 tx.execute("DELETE FROM note_links WHERE src = ?1", (note_id.to_string(),))
251 .await?;
252 tx.execute("DELETE FROM notes WHERE id = ?1", (note_id.to_string(),))
253 .await?;
254 Ok(())
255}
256
257fn notebook_from_row(row: &turso::Row) -> anyhow::Result<Notebook> {
258 Ok(Notebook {
259 id: text_col(row, 0)?,
260 name: text_col(row, 1)?,
261 created_at: int_col(row, 2)?,
262 })
263}
264
265/// What [`Store::search`] found: the best hits, and whether the time budget ran out
266/// before every note was read.
267#[derive(Default)]
268pub struct Searched {
269 pub hits: Vec<SearchHit>,
270 pub partial: bool,
271}
272
273/// A note matched by [`Store::search`], with a plain-text excerpt of its body.
274pub struct SearchHit {
275 pub note: NoteMeta,
276 pub snippet: String,
277}
278
279/// Characters of body text shown around the first match.
280const SNIPPET_CHARS: usize = 160;
281/// Characters of body text shown as a note's preview in a list.
282const PREVIEW_CHARS: usize = 140;
283/// Characters of a note's body read for its preview. Enough for `PREVIEW_CHARS` of plain
284/// text, so the rest of a long body is never loaded.
285const PREVIEW_SOURCE_CHARS: usize = 2000;
286/// The stored markdown of each of `ids`, by id, read on `conn`.
287async fn bodies_on(conn: &turso::Connection, ids: &[String]) -> anyhow::Result<HashMap<String, String>> {
288 let placeholders = (1..=ids.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", ");
289 let mut rows = conn
290 .query(format!("SELECT note_id, body FROM note_text WHERE note_id IN ({placeholders})"), ids.to_vec())
291 .await?;
292 let mut bodies = HashMap::new();
293 while let Some(row) = rows.next().await? {
294 bodies.insert(text_col(&row, 0)?, text_col(&row, 1)?);
295 }
296 Ok(bodies)
297}
298
299/// Bytes of note bodies indexed at a time when the directory is loaded.
300const DIRECTORY_BATCH_BYTES: usize = 256 << 20;
301/// Connections reading note texts at once for a search.
302const SEARCH_READERS: usize = 8;
303/// Connections reading the notes at once when the directory is loaded.
304const DIRECTORY_READERS: usize = 4;
305/// Note ids per `IN (...)` query, well under SQLite's parameter limit.
306const PREVIEW_BATCH: usize = 500;
307/// Bytes of a changed note's text above which it is indexed in the background: a
308/// 100 MB note takes seconds, and every page waits for the directory meanwhile.
309const HEAVY_INDEX_BYTES: i64 = 1 << 20;
310/// How long such a note goes unchanged before it is indexed: while someone types in
311/// it, each text flush would cost a core for a second.
312const HEAVY_QUIET: std::time::Duration = std::time::Duration::from_secs(2);
313/// Markdown as plain text. Code fences are dropped, block markers (headings, quotes,
314/// list and task markers, rules) and inline syntax (emphasis, code spans, escapes) are
315/// removed, link and image text is kept, and lines are joined with single spaces.
316fn plain_text(markdown: &str) -> String {
317 PlainChunks::new(markdown, usize::MAX).next().unwrap_or_default()
318}
319
320/// [`plain_text`] in pieces of at least `chunk` bytes, which joined with single spaces
321/// give the whole: a long note is matched a piece at a time and the rest skipped once
322/// nothing better can turn up.
323struct PlainChunks<'a> {
324 lines: std::str::Lines<'a>,
325 in_fence: bool,
326 chunk: usize,
327}
328
329impl<'a> PlainChunks<'a> {
330 fn new(markdown: &'a str, chunk: usize) -> Self {
331 Self { lines: markdown.lines(), in_fence: false, chunk }
332 }
333}
334
335impl Iterator for PlainChunks<'_> {
336 type Item = String;
337
338 fn next(&mut self) -> Option<String> {
339 fn push(out: &mut String, text: &str) {
340 // Most lines are ASCII with single spaces: already what the words joined give.
341 let mut prev_space = false;
342 let simple = text.bytes().all(|b| {
343 let ok = b.is_ascii() && !matches!(b, b'\t' | b'\n' | b'\r' | b'\x0b' | b'\x0c') && !(b == b' ' && prev_space);
344 prev_space = b == b' ';
345 ok
346 });
347 if simple && !text.starts_with(' ') && !text.ends_with(' ') {
348 if !text.is_empty() {
349 if !out.is_empty() {
350 out.push(' ');
351 }
352 out.push_str(text);
353 }
354 return;
355 }
356 for word in text.split_whitespace() {
357 if !out.is_empty() {
358 out.push(' ');
359 }
360 out.push_str(word);
361 }
362 }
363 let mut out = String::new();
364 let mut any = false;
365 for line in self.lines.by_ref() {
366 any = true;
367 let trimmed = line.trim();
368 if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
369 self.in_fence = !self.in_fence;
370 } else if self.in_fence {
371 push(&mut out, trimmed);
372 } else {
373 push(&mut out, &strip_inline(strip_block(trimmed)));
374 }
375 if out.len() >= self.chunk {
376 break;
377 }
378 }
379 (any && (!out.is_empty() || self.chunk == usize::MAX)).then_some(out)
380 }
381}
382
383/// `matcher` against a note's title and its whole `body`, read a piece at a time: the
384/// note's key and a snippet when it matches. Stops early once every term matched at
385/// `floor`, the least it can cost in this note, which nothing beats.
386fn match_long(title: &str, body: &str, matcher: &Matcher, floor: usize) -> Option<(SearchKey, String)> {
387 match_pieces(title, PlainChunks::new(body, 64 << 10), matcher, floor).0
388}
389
390/// [`match_long`] over plain text given in pieces joined by single spaces. Also says
391/// whether every term matched at `floor`: then the rest of the text cannot change it.
392fn match_pieces(
393 title: &str,
394 pieces: impl Iterator<Item = String>,
395 matcher: &Matcher,
396 floor: usize,
397) -> (Option<(SearchKey, String)>, bool) {
398 // Text carried into the next piece, for matches across the cut.
399 const OVERLAP: usize = 1024;
400 let in_title = matcher.term_costs(title);
401 let mut in_text: Vec<Option<usize>> = vec![None; in_title.len()];
402 let mut snip: Option<String> = None;
403 let mut tail = String::new();
404 let mut perfect = false;
405 for (i, piece) in pieces.enumerate() {
406 let window = if tail.is_empty() { piece } else { format!("{tail} {piece}") };
407 for (best, cost) in in_text.iter_mut().zip(matcher.term_costs(&window)) {
408 if let Some(cost) = cost {
409 *best = Some(best.map_or(cost, |b| b.min(cost)));
410 }
411 }
412 if snip.is_none() && in_text.iter().any(Option::is_some) {
413 let s = snippet(&window, matcher);
414 snip = Some(if i > 0 && !s.starts_with('…') { format!("…{s}") } else { s });
415 }
416 if in_text.iter().all(|c| c.is_some_and(|c| c <= floor)) {
417 perfect = true;
418 break;
419 }
420 let from = window.char_indices().rev().nth(OVERLAP).map_or(0, |(at, _)| at);
421 // From a word start, so a match there is not taken for one at a word start.
422 let from = if from == 0 { 0 } else { window[from..].find(' ').map_or(window.len(), |sp| from + sp + 1) };
423 tail = window[from..].to_owned();
424 }
425 let key = search_key(in_title.into_iter(), in_text.into_iter()).map(|k| (k, snip.unwrap_or_default()));
426 (key, perfect)
427}
428
429/// `plain` in pieces of about 64 KB cut at spaces, the cut spaces left out.
430fn plain_pieces(plain: &str) -> impl Iterator<Item = String> + '_ {
431 let mut rest = plain;
432 std::iter::from_fn(move || {
433 if rest.is_empty() {
434 return None;
435 }
436 let mut cut = (64 << 10).min(rest.len());
437 while !rest.is_char_boundary(cut) {
438 cut += 1;
439 }
440 let cut = if cut == rest.len() { cut } else { rest[cut..].find(' ').map_or(rest.len(), |sp| cut + sp) };
441 let piece = rest[..cut].to_owned();
442 rest = rest.get(cut + 1..).unwrap_or("");
443 Some(piece)
444 })
445}
446
447/// Removes the block syntax at the start of one trimmed line: quote marks, heading
448/// hashes, list and task markers, and thematic breaks.
449fn strip_block(line: &str) -> &str {
450 let mut s = line;
451 if s.len() >= 3 && s.chars().all(|c| matches!(c, '-' | '*' | '_' | ' ')) {
452 return "";
453 }
454 while let Some(rest) = s.strip_prefix('>') {
455 s = rest.trim_start();
456 }
457 let hashes = s.len() - s.trim_start_matches('#').len();
458 if hashes > 0 && (hashes == s.len() || s[hashes..].starts_with(' ')) {
459 s = s[hashes..].trim_start();
460 }
461 if let Some(rest) = s.strip_prefix(['-', '*', '+']) {
462 if rest.is_empty() || rest.starts_with(' ') {
463 s = rest.trim_start();
464 }
465 }
466 let digits = s.len() - s.trim_start_matches(|c: char| c.is_ascii_digit()).len();
467 if digits > 0 {
468 if let Some(rest) = s[digits..].strip_prefix(['.', ')']) {
469 if rest.is_empty() || rest.starts_with(' ') {
470 s = rest.trim_start();
471 }
472 }
473 }
474 for checkbox in ["[ ]", "[x]", "[X]"] {
475 if let Some(rest) = s.strip_prefix(checkbox) {
476 s = rest.trim_start();
477 break;
478 }
479 }
480 s
481}
482
483/// Removes inline syntax from one line: `[text](url)` and `![alt](url)` become their
484/// text, emphasis and code markers are dropped, `_` is kept inside words only, and a
485/// backslash escape yields the escaped character.
486fn strip_inline(text: &str) -> std::borrow::Cow<'_, str> {
487 // Most lines have no inline syntax at all.
488 if !text.contains(['!', '[', '\\', '*', '`', '~', '_']) {
489 return text.into();
490 }
491 let chars: Vec<char> = text.chars().collect();
492 let mut out = String::with_capacity(text.len());
493 let mut i = 0;
494 while i < chars.len() {
495 let c = chars[i];
496 if c == '!' && chars.get(i + 1) == Some(&'[') {
497 if let Some((label, end)) = link_at(&chars, i + 1) {
498 out.push_str(&label);
499 i = end;
500 continue;
501 }
502 }
503 if c == '[' {
504 if let Some((label, end)) = link_at(&chars, i) {
505 out.push_str(&label);
506 i = end;
507 continue;
508 }
509 }
510 if c == '\\' && chars.get(i + 1).is_some_and(|next| next.is_ascii_punctuation()) {
511 out.push(chars[i + 1]);
512 i += 2;
513 continue;
514 }
515 match c {
516 '*' | '`' | '~' => {}
517 '_' => {
518 let inside_word = i > 0
519 && chars[i - 1].is_alphanumeric()
520 && chars.get(i + 1).is_some_and(|next| next.is_alphanumeric());
521 if inside_word {
522 out.push(c);
523 }
524 }
525 _ => out.push(c),
526 }
527 i += 1;
528 }
529 out.into()
530}
531
532/// Parses `[label](target)` whose `[` is at `open`. Returns the label and the index just
533/// after the closing `)`.
534fn link_at(chars: &[char], open: usize) -> Option<(String, usize)> {
535 let close = open + 1 + chars[open + 1..].iter().position(|&c| c == ']')?;
536 if chars.get(close + 1) != Some(&'(') {
537 return None;
538 }
539 let end = close + 2 + chars[close + 2..].iter().position(|&c| c == ')')?;
540 Some((chars[open + 1..close].iter().collect(), end + 1))
541}
542
543/// The first `PREVIEW_CHARS` characters of a note's text after its title. The first
544/// non-blank line of the markdown is the title, so it is skipped.
545fn preview(markdown: &str) -> String {
546 let head = markdown.char_indices().nth(PREVIEW_SOURCE_CHARS).map_or(markdown, |(i, _)| &markdown[..i]);
547 // The text after the first non-blank line, the title.
548 let mut rest = head;
549 loop {
550 let (line, after) = rest.split_once('\n').unwrap_or((rest, ""));
551 rest = after;
552 if !line.trim().is_empty() || rest.is_empty() {
553 break;
554 }
555 }
556 plain_text(rest).chars().take(PREVIEW_CHARS).collect()
557}
558
559/// About `SNIPPET_CHARS` characters of `plain` around the first term match.
560/// Cut ends get an ellipsis.
561fn snippet(plain: &str, matcher: &Matcher) -> String {
562 if plain.is_empty() {
563 return String::new();
564 }
565 // Most hits match near the start: look there before reading the whole text.
566 let mut center = 0;
567 for window in [4 << 10, 64 << 10, usize::MAX] {
568 let mut end = window.min(plain.len());
569 while !plain.is_char_boundary(end) {
570 end -= 1;
571 }
572 if let Some(range) = matcher.ranges(&plain[..end]).first() {
573 center = range.0;
574 break;
575 }
576 if end == plain.len() {
577 break;
578 }
579 }
580 let start = center.saturating_sub(SNIPPET_CHARS / 3);
581 let mut chars = plain.char_indices().skip(start).map(|(i, _)| i);
582 let Some(from) = chars.next() else {
583 // The match is near the end: show the last `SNIPPET_CHARS`.
584 let from = plain.char_indices().rev().nth(SNIPPET_CHARS - 1).map_or(0, |(i, _)| i);
585 return format!("{}{}", if from > 0 { "…" } else { "" }, plain[from..].trim());
586 };
587 let to = chars.nth(SNIPPET_CHARS - 1).unwrap_or(plain.len());
588 if to == plain.len() && start > 0 {
589 // Too close to the end for a full window: take it from further back.
590 let from = plain.char_indices().rev().nth(SNIPPET_CHARS - 1).map_or(0, |(i, _)| i);
591 return format!("{}{}", if from > 0 { "…" } else { "" }, plain[from..].trim());
592 }
593 let mut out = String::new();
594 if from > 0 {
595 out.push('…');
596 }
597 out.push_str(plain[from..to].trim());
598 if to < plain.len() {
599 out.push('…');
600 }
601 out
602}
603
604/// Scores every row against `matcher`, in parallel, keeping their order.
605type SearchKey = (usize, std::cmp::Reverse<usize>);
606
607/// Each term matches the title or the text, whichever is closer. Cheaper matches
608/// first (exact before typos), then more terms in the title.
609fn search_key(in_title: impl Iterator<Item = Option<usize>>, in_text: impl Iterator<Item = Option<usize>>) -> Option<SearchKey> {
610 let mut cost = 0;
611 let mut title_terms = 0;
612 for (t, x) in in_title.zip(in_text) {
613 match (t, x) {
614 (Some(t), Some(x)) if t <= x => (cost += t, title_terms += 1),
615 (Some(t), None) => (cost += t, title_terms += 1),
616 (_, Some(x)) => (cost += x, ()),
617 (None, None) => return None,
618 };
619 }
620 Some((cost, std::cmp::Reverse(title_terms)))
621}
622
623/// A search hit's rank: its [`SearchKey`], then the newest.
624type RankKey = (SearchKey, std::cmp::Reverse<i64>);
625
626/// The `limit` best notes outside the trash by `matcher`, best first: see [`par_top`].
627/// Notes whose text is longer than kept in memory are left out of a case, phrase or
628/// regex search here: [`Store::search`] matches them against their stored text.
629fn match_top(matcher: &Matcher, slots: &[Option<Arc<Entry>>], vocab: &RwLock<Vocab>, limit: usize) -> Vec<(RankKey, Arc<Entry>)> {
630 let newest = |k: SearchKey, e: &Entry| (k, std::cmp::Reverse(e.updated_at));
631
632 match matcher.word_terms() {
633 Some(terms) => {
634 let tables = word_costs(matcher, terms, &vocab.read().unwrap());
635 par_top_keyed(slots, limit, |e| {
636 let k = search_key(
637 tables.iter().map(|t| best_cost(t, e.title_words())),
638 tables.iter().map(|t| best_cost(t, e.text_words())),
639 )?;
640 Some(newest(k, e))
641 })
642 }
643 None => par_top_keyed(slots, limit, |e| {
644 if e.plain_cut {
645 return None;
646 }
647 let k = search_key(matcher.term_costs(e.title()).into_iter(), matcher.term_costs(e.plain()).into_iter())?;
648 Some(newest(k, e))
649 }),
650 }
651}
652
653/// The `limit` notes outside the trash with the lowest `key`, lowest first; ties go to
654/// the lower id. Each thread keeps only its own best `limit`, so a query that matches
655/// every note never collects them all.
656fn par_top<K: Ord + Copy + Send>(
657 slots: &[Option<Arc<Entry>>],
658 limit: usize,
659 key: impl Fn(&Entry) -> Option<K> + Sync,
660) -> Vec<Arc<Entry>> {
661 par_top_keyed(slots, limit, key).into_iter().map(|(_, e)| e).collect()
662}
663
664/// [`par_top`] with the keys kept.
665fn par_top_keyed<K: Ord + Copy + Send>(
666 slots: &[Option<Arc<Entry>>],
667 limit: usize,
668 key: impl Fn(&Entry) -> Option<K> + Sync,
669) -> Vec<(K, Arc<Entry>)> {
670 let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
671 let chunk_len = slots.len().div_ceil(threads).max(1);
672 let key = &key;
673 let best: Vec<(K, &Arc<Entry>)> = std::thread::scope(|scope| {
674 let handles: Vec<_> = slots
675 .chunks(chunk_len)
676 .map(|chunk| {
677 scope.spawn(move || {
678 // Trimmed to the best `limit` whenever it fills, and past that only
679 // keys as good as the worst kept one enter: a word in every note
680 // would otherwise collect them all, megabytes per search.
681 let cap = 4 * limit.max(64);
682 let mut hits: Vec<(K, &Arc<Entry>)> = Vec::with_capacity(cap);
683 let mut worst: Option<K> = None;
684 for e in chunk.iter().flatten().filter(|e| e.trashed_at.is_none()) {
685 let Some(k) = key(e) else { continue };
686 if worst.is_some_and(|w| k > w) {
687 continue;
688 }
689 hits.push((k, e));
690 if hits.len() == cap {
691 hits = top_keyed(hits, limit, |e| e.id());
692 worst = hits.last().map(|h| h.0);
693 }
694 }
695 top_keyed(hits, limit, |e| e.id())
696 })
697 })
698 .collect();
699 handles
700 .into_iter()
701 .flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p)))
702 .collect()
703 });
704 top_keyed(best, limit, |e| e.id()).into_iter().map(|(k, e)| (k, e.clone())).collect()
705}
706
707/// Each term's cost in every word of the vocabulary, by word id; `u8::MAX` where the
708/// term does not occur in the word.
709fn word_costs(matcher: &Matcher, terms: &[Vec<char>], vocab: &Vocab) -> Vec<Arc<Vec<u8>>> {
710 /// Term tables kept for the next searches.
711 const KEPT: usize = 8;
712 let Some(opts) = matcher.options() else { return Vec::new() };
713 let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
714 // The costs of `term` in `words`, on every core.
715 let compute = |term: &[char], from: usize| -> Vec<u8> {
716 let n = vocab.len() - from;
717 let chunk_len = n.div_ceil(threads).max(1);
718 std::thread::scope(|scope| {
719 let handles: Vec<_> = (from..vocab.len())
720 .step_by(chunk_len)
721 .map(|start| {
722 let ids = start..(start + chunk_len).min(vocab.len());
723 scope.spawn(move || {
724 ids.map(|id| matcher.word_cost(term, vocab.word(id)).map_or(u8::MAX, |c| c.min(254) as u8)).collect::<Vec<u8>>()
725 })
726 })
727 .collect();
728 handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect()
729 })
730 };
731 terms
732 .iter()
733 .map(|term| {
734 let found = {
735 let mut kept = vocab.costs.lock().unwrap();
736 let at = kept.iter().position(|(t, o, _)| **t == **term && *o == opts);
737 at.map(|i| kept.remove(i))
738 };
739 let table = match found {
740 Some((_, _, table)) if table.len() == vocab.len() => table,
741 Some((_, _, table)) => {
742 let mut grown = (*table).clone();
743 grown.extend(compute(term, table.len()));
744 Arc::new(grown)
745 }
746 None => Arc::new(compute(term, 0)),
747 };
748 let mut kept = vocab.costs.lock().unwrap();
749 kept.push((term.clone().into(), opts, table.clone()));
750 if kept.len() > KEPT {
751 kept.remove(0);
752 }
753 table
754 })
755 .collect()
756}
757
758/// The cheapest cost in `table` among `words`, None if the term is in none of them.
759fn best_cost(table: &[u8], words: &[u32]) -> Option<usize> {
760 let best = words.iter().map(|&w| table[w as usize]).min()?;
761 (best != u8::MAX).then_some(usize::from(best))
762}
763
764/// The `limit` items with the smallest keys, in key order, ties by `id`. Selects before
765/// sorting: a common word matches every note, and sorting them all costs more than
766/// matching them.
767fn top<K: Ord + Copy, T>(items: Vec<(K, T)>, limit: usize, id: impl Fn(&T) -> &str) -> Vec<T> {
768 top_keyed(items, limit, id).into_iter().map(|(_, t)| t).collect()
769}
770
771/// [`top`] with the keys kept.
772fn top_keyed<K: Ord + Copy, T>(mut items: Vec<(K, T)>, limit: usize, id: impl Fn(&T) -> &str) -> Vec<(K, T)> {
773 let cmp = |a: &(K, T), b: &(K, T)| a.0.cmp(&b.0).then_with(|| id(&a.1).cmp(id(&b.1)));
774 if limit == 0 {
775 return Vec::new();
776 }
777 if items.len() > limit {
778 items.select_nth_unstable_by(limit - 1, cmp);
779 items.truncate(limit);
780 }
781 items.sort_unstable_by(cmp);
782 items
783}
784
785impl Store {
786 /// Opens (or creates) the database file and runs schema setup.
787 pub async fn open(path: &str) -> anyhow::Result<Self> {
788 // The FTS index method is gated behind this flag in turso 0.8. Search no longer
789 // uses the index, but databases made before still have one to drop.
790 let db = turso::Builder::new_local(path)
791 .experimental_index_method(true)
792 .build()
793 .await
794 .with_context(|| format!("opening database at {path}"))?;
795 let conn = db.connect()?;
796 // WAL with NORMAL sync: a commit no longer waits for an fsync, so a power loss can
797 // drop the last commits but never corrupts the database. Each note save is a commit.
798 conn.execute("PRAGMA synchronous = NORMAL", ()).await.context("setting synchronous")?;
799
800 conn.execute_batch(
801 "CREATE TABLE IF NOT EXISTS notes (
802 id TEXT PRIMARY KEY,
803 title TEXT NOT NULL DEFAULT 'Untitled',
804 created_at INTEGER NOT NULL,
805 updated_at INTEGER NOT NULL,
806 notebook_id TEXT,
807 trashed_at INTEGER
808 );
809 CREATE TABLE IF NOT EXISTS notebooks (
810 id TEXT PRIMARY KEY,
811 name TEXT NOT NULL,
812 created_at INTEGER NOT NULL
813 );
814 CREATE TABLE IF NOT EXISTS updates (
815 seq INTEGER PRIMARY KEY AUTOINCREMENT,
816 note_id TEXT NOT NULL,
817 hash BLOB NOT NULL,
818 data BLOB NOT NULL,
819 UNIQUE(note_id, hash)
820 );
821 CREATE TABLE IF NOT EXISTS snapshots (
822 note_id TEXT PRIMARY KEY,
823 data BLOB NOT NULL,
824 upto_seq INTEGER NOT NULL,
825 markdown TEXT NOT NULL
826 );
827 -- Export markdown of a snapshot, its note links left for the export to name.
828 CREATE TABLE IF NOT EXISTS export_text (
829 note_id TEXT PRIMARY KEY,
830 upto_seq INTEGER NOT NULL,
831 markdown TEXT NOT NULL
832 );
833 -- Imported markdown whose doc is not built yet: see hub::ensure_doc.
834 CREATE TABLE IF NOT EXISTS pending_docs (
835 note_id TEXT PRIMARY KEY,
836 markdown TEXT NOT NULL
837 );
838 CREATE TABLE IF NOT EXISTS note_text (
839 note_id TEXT PRIMARY KEY,
840 title TEXT NOT NULL,
841 body TEXT NOT NULL
842 );
843 CREATE TABLE IF NOT EXISTS note_versions (
844 note_id TEXT NOT NULL,
845 at INTEGER NOT NULL,
846 frontiers BLOB NOT NULL,
847 PRIMARY KEY(note_id, at)
848 );
849 DROP INDEX IF EXISTS note_text_fts;
850 CREATE TABLE IF NOT EXISTS note_links (
851 src TEXT NOT NULL,
852 dst_id TEXT,
853 dst_title TEXT
854 );
855 CREATE INDEX IF NOT EXISTS notebooks_name ON notebooks(name);
856 CREATE INDEX IF NOT EXISTS note_links_src ON note_links(src);
857 CREATE INDEX IF NOT EXISTS note_links_dst_id ON note_links(dst_id);
858 CREATE INDEX IF NOT EXISTS note_links_dst_title ON note_links(dst_title);",
859 )
860 .await
861 .context("running schema setup")?;
862
863 // Databases created before notebooks have a notes table without notebook_id.
864 // CREATE TABLE IF NOT EXISTS does not add columns, so add it when missing.
865 if !Self::notes_columns(&conn).await?.iter().any(|c| c == "notebook_id") {
866 conn.execute("ALTER TABLE notes ADD COLUMN notebook_id TEXT", ())
867 .await
868 .context("adding notes.notebook_id")?;
869 }
870
871 // Databases created before the trash existed lack notes.trashed_at.
872 if !Self::notes_columns(&conn).await?.iter().any(|c| c == "trashed_at") {
873 conn.execute("ALTER TABLE notes ADD COLUMN trashed_at INTEGER", ())
874 .await
875 .context("adding notes.trashed_at")?;
876 }
877
878 // List queries filter on trashed_at and notebook_id and sort by updated_at. These
879 // indexes are created after the column migrations above, which they depend on.
880 conn.execute_batch(
881 "DROP INDEX IF EXISTS notes_trashed_updated;
882 DROP INDEX IF EXISTS notes_notebook_trashed_updated;
883 CREATE INDEX IF NOT EXISTS notes_trashed_updated_id ON notes(trashed_at, updated_at, id);
884 CREATE INDEX IF NOT EXISTS notes_notebook_trashed_updated_id ON notes(notebook_id, trashed_at, updated_at, id);",
885 )
886 .await
887 .context("creating notes indexes")?;
888
889 // Notes saved before note_text existed: copy their snapshot markdown, once per
890 // database (a scan of every snapshot, seconds at a million notes).
891 let mut rows = conn.query("PRAGMA user_version", ()).await?;
892 let version = match rows.next().await? {
893 Some(row) => int_col(&row, 0)?,
894 None => 0,
895 };
896 drop(rows);
897 if version < 1 {
898 conn.execute(
899 "INSERT INTO note_text (note_id, title, body)
900 SELECT s.note_id, n.title, s.markdown FROM snapshots s
901 JOIN notes n ON n.id = s.note_id
902 WHERE NOT EXISTS (SELECT 1 FROM note_text t WHERE t.note_id = s.note_id)",
903 (),
904 )
905 .await
906 .context("backfilling note_text")?;
907 conn.execute("PRAGMA user_version = 1", ()).await.context("setting user_version")?;
908 }
909 // Cached export markdown used to be checked against its snapshot on read. Now a
910 // new snapshot drops it, so what was cached before cannot be trusted.
911 if version < 2 {
912 conn.execute("DELETE FROM export_text", ()).await.context("clearing export_text")?;
913 conn.execute("PRAGMA user_version = 2", ()).await.context("setting user_version")?;
914 }
915
916 Ok(Self {
917 conn: Mutex::new(conn),
918 read: Mutex::new(db.connect()?),
919 dir: Mutex::new(None),
920 changes: std::sync::Mutex::new(Vec::new()),
921 heavy: std::sync::Mutex::new(HashMap::new()),
922 db,
923 })
924 }
925
926 /// Column names of the notes table, read from `PRAGMA table_info`.
927 async fn notes_columns(conn: &turso::Connection) -> anyhow::Result<Vec<String>> {
928 let mut rows = conn.query("PRAGMA table_info(notes)", ()).await?;
929 let mut names = Vec::new();
930 while let Some(row) = rows.next().await? {
931 names.push(text_col(&row, 1)?);
932 }
933 Ok(names)
934 }
935
936 /// Records a committed write for the directory.
937 fn changed(&self, change: Change) {
938 self.changes.lock().unwrap().push(change);
939 }
940
941 /// The directory, loaded if needed and with every recorded write applied.
942 async fn directory(&self) -> anyhow::Result<tokio::sync::MappedMutexGuard<'_, Directory>> {
943 let mut dir = self.dir.lock().await;
944 let result = self.refresh_directory(&mut dir).await;
945 if result.is_err() {
946 // Changes may have been taken without being applied: start over next time.
947 *dir = None;
948 }
949 result?;
950 Ok(tokio::sync::MutexGuard::map(dir, |d| d.as_mut().unwrap()))
951 }
952
953 async fn refresh_directory(&self, dir: &mut Option<Directory>) -> anyhow::Result<()> {
954 const SELECT: &str = "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at,
955 COALESCE(t.body, '')
956 FROM notes n LEFT JOIN note_text t ON t.note_id = n.id";
957 let select_changed = format!(
958 "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at,
959 CASE WHEN length(t.body) > {HEAVY_INDEX_BYTES} THEN NULL ELSE COALESCE(t.body, '') END
960 FROM notes n LEFT JOIN note_text t ON t.note_id = n.id"
961 );
962 if dir.is_none() {
963 // Whatever was committed before this point is in the full read.
964 self.changes.lock().unwrap().clear();
965 // Held while reading: no write lands between the read and the change log.
966 let conn = self.conn.lock().await;
967 let mut rows = conn.query("SELECT min(rowid), max(rowid) FROM notes", ()).await?;
968 let (first, last) = match rows.next().await? {
969 Some(row) => (row.get::<Option<i64>>(0)?.unwrap_or(0), row.get::<Option<i64>>(1)?.unwrap_or(0)),
970 None => (0, 0),
971 };
972 drop(rows);
973 // Indexed in batches of a bounded size, as they are read: all the bodies may
974 // not fit in memory. Ranges of rows are read on their own connections at once.
975 let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<(NoteMeta, String)>>(DIRECTORY_READERS);
976 let indexer = std::thread::spawn(move || {
977 let mut loaded = Directory::default();
978 for batch in rx {
979 loaded.put_many(batch);
980 }
981 loaded
982 });
983 let span = (last - first) / DIRECTORY_READERS as i64 + 1;
984 let mut readers = tokio::task::JoinSet::new();
985 for k in 0..DIRECTORY_READERS as i64 {
986 let (reader, tx) = (self.db.connect()?, tx.clone());
987 let (from, to) = (first + k * span, first + (k + 1) * span - 1);
988 readers.spawn(async move {
989 let mut rows = reader.query(format!("{SELECT} WHERE n.rowid BETWEEN ?1 AND ?2"), (from, to)).await?;
990 let (mut batch, mut bytes) = (Vec::new(), 0);
991 while let Some(row) = rows.next().await? {
992 let body = text_col(&row, 6)?;
993 bytes += body.len() + 200;
994 batch.push((note_from_row(&row)?, body));
995 if bytes > DIRECTORY_BATCH_BYTES / DIRECTORY_READERS {
996 let full = std::mem::take(&mut batch);
997 tokio::task::block_in_place(|| tx.send(full))?;
998 bytes = 0;
999 }
1000 }
1001 tokio::task::block_in_place(|| tx.send(batch))?;
1002 anyhow::Ok(())
1003 });
1004 }
1005 drop(tx);
1006 while let Some(read) = readers.join_next().await {
1007 read??;
1008 }
1009 drop(conn);
1010 let mut loaded = tokio::task::block_in_place(|| indexer.join()).map_err(|_| anyhow::anyhow!("indexing notes panicked"))?;
1011 loaded.shrink();
1012 *dir = Some(loaded);
1013 }
1014 let changes = std::mem::take(&mut *self.changes.lock().unwrap());
1015 if changes.is_empty() {
1016 return Ok(());
1017 }
1018 let dir = dir.as_mut().unwrap();
1019 // A write landing meanwhile records its change again, for the next refresh.
1020 let conn = self.read.lock().await;
1021 // Changed notes are re-read in batches, each note once; a deleted notebook
1022 // first needs the notes changed before it.
1023 let mut ids: Vec<String> = Vec::new();
1024 let mut seen = std::collections::HashSet::new();
1025 for change in changes.into_iter().map(Some).chain([None]) {
1026 match change {
1027 Some(Change::Note(id)) => {
1028 if seen.insert(id.clone()) {
1029 ids.push(id);
1030 }
1031 continue;
1032 }
1033 Some(Change::NotebookGone(_)) | None => {}
1034 }
1035 for chunk in ids.chunks(PREVIEW_BATCH) {
1036 let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", ");
1037 let mut rows = conn.query(format!("{select_changed} WHERE n.id IN ({placeholders})"), chunk.to_vec()).await?;
1038 let mut found = std::collections::HashSet::new();
1039 let (mut batch, mut heavy) = (Vec::new(), Vec::new());
1040 while let Some(row) = rows.next().await? {
1041 let meta = note_from_row(&row)?;
1042 found.insert(meta.id.clone());
1043 match opt_text_col(&row, 6)? {
1044 Some(body) => batch.push((meta, body)),
1045 None => heavy.push(meta),
1046 }
1047 }
1048 tokio::task::block_in_place(|| dir.put_many(batch));
1049 for meta in heavy {
1050 self.heavy.lock().unwrap().insert(meta.id.clone(), std::time::Instant::now());
1051 dir.set_meta(meta);
1052 }
1053 for id in chunk.iter().filter(|id| !found.contains(*id)) {
1054 dir.remove(id);
1055 }
1056 }
1057 ids.clear();
1058 seen.clear();
1059 if let Some(Change::NotebookGone(id)) = change {
1060 dir.unfile(&id);
1061 }
1062 }
1063 Ok(())
1064 }
1065
1066 /// Loads the directory, then keeps applying writes in the background, so a request
1067 /// after a burst of writes (a big import) does not have to.
1068 pub async fn keep_directory_fresh(&self) {
1069 loop {
1070 if let Err(err) = self.directory().await {
1071 eprintln!("note directory refresh failed: {err:#}");
1072 }
1073 if let Err(err) = self.index_heavy().await {
1074 eprintln!("indexing a long note failed: {err:#}");
1075 }
1076 tokio::time::sleep(std::time::Duration::from_millis(250)).await;
1077 }
1078 }
1079
1080 /// Indexes the long notes the directory left for later: read on a connection of
1081 /// their own and indexed with no lock held, then put in unless edited again since.
1082 async fn index_heavy(&self) -> anyhow::Result<()> {
1083 let ids: Vec<String> = {
1084 let mut heavy = self.heavy.lock().unwrap();
1085 let quiet: Vec<String> = heavy.iter().filter(|(_, at)| at.elapsed() >= HEAVY_QUIET).map(|(id, _)| id.clone()).collect();
1086 for id in &quiet {
1087 heavy.remove(id);
1088 }
1089 quiet
1090 };
1091 for id in ids {
1092 let conn = self.db.connect()?;
1093 let mut rows = conn
1094 .query(
1095 "SELECT n.id, n.title, n.created_at, n.updated_at, n.notebook_id, n.trashed_at, COALESCE(t.body, '')
1096 FROM notes n LEFT JOIN note_text t ON t.note_id = n.id WHERE n.id = ?1",
1097 [id.as_str()],
1098 )
1099 .await?;
1100 let Some(row) = rows.next().await? else { continue };
1101 let (meta, body) = (note_from_row(&row)?, text_col(&row, 6)?);
1102 drop((rows, conn));
1103 let updated_at = meta.updated_at;
1104 // At the lowest priority: requests and doc builds go first.
1105 let indexer = std::thread::spawn(move || {
1106 let _ = thread_priority::set_current_thread_priority(thread_priority::ThreadPriority::Min);
1107 directory::prepare_one(meta, body)
1108 });
1109 let prepared = tokio::task::block_in_place(|| indexer.join()).map_err(|_| anyhow!("indexing a long note panicked"))?;
1110 let mut dir = self.dir.lock().await;
1111 if let Some(dir) = dir.as_mut()
1112 && dir.updated_at(&id).is_some_and(|at| at <= updated_at)
1113 {
1114 tokio::task::block_in_place(|| dir.put_prepared(prepared));
1115 }
1116 }
1117 Ok(())
1118 }
1119
1120 pub async fn create_note(&self, notebook_id: Option<&str>) -> anyhow::Result<NoteMeta> {
1121 let now = now_millis();
1122 let note = NoteMeta {
1123 id: uuid::Uuid::now_v7().to_string(),
1124 title: "Untitled".to_string(),
1125 created_at: now,
1126 updated_at: now,
1127 notebook_id: notebook_id.map(str::to_string),
1128 trashed_at: None,
1129 };
1130
1131 let conn = self.conn.lock().await;
1132 conn.execute(
1133 "INSERT INTO notes (id, title, created_at, updated_at, notebook_id) VALUES (?1, ?2, ?3, ?4, ?5)",
1134 (
1135 note.id.clone(),
1136 note.title.clone(),
1137 note.created_at,
1138 note.updated_at,
1139 note.notebook_id.clone(),
1140 ),
1141 )
1142 .await?;
1143 self.changed(Change::Note(note.id.clone()));
1144 Ok(note)
1145 }
1146
1147 pub async fn create_notebook(&self, name: &str) -> anyhow::Result<Notebook> {
1148 let notebook = Notebook {
1149 id: uuid::Uuid::now_v7().to_string(),
1150 name: name.to_string(),
1151 created_at: now_millis(),
1152 };
1153
1154 let conn = self.conn.lock().await;
1155 conn.execute(
1156 "INSERT INTO notebooks (id, name, created_at) VALUES (?1, ?2, ?3)",
1157 (
1158 notebook.id.clone(),
1159 notebook.name.clone(),
1160 notebook.created_at,
1161 ),
1162 )
1163 .await?;
1164 Ok(notebook)
1165 }
1166
1167 pub async fn list_notebooks(&self) -> anyhow::Result<Vec<Notebook>> {
1168 let conn = self.read.lock().await;
1169 let mut rows = conn
1170 .query(
1171 "SELECT id, name, created_at FROM notebooks ORDER BY name COLLATE NOCASE, id",
1172 (),
1173 )
1174 .await?;
1175 let mut notebooks = Vec::new();
1176 while let Some(row) = rows.next().await? {
1177 notebooks.push(notebook_from_row(&row)?);
1178 }
1179 Ok(notebooks)
1180 }
1181
1182 pub async fn get_notebook(&self, id: &str) -> anyhow::Result<Option<Notebook>> {
1183 let conn = self.read.lock().await;
1184 let mut rows = conn
1185 .query(
1186 "SELECT id, name, created_at FROM notebooks WHERE id = ?1",
1187 (id.to_string(),),
1188 )
1189 .await?;
1190 match rows.next().await? {
1191 Some(row) => Ok(Some(notebook_from_row(&row)?)),
1192 None => Ok(None),
1193 }
1194 }
1195
1196 pub async fn rename_notebook(&self, id: &str, name: &str) -> anyhow::Result<()> {
1197 let conn = self.conn.lock().await;
1198 conn.execute(
1199 "UPDATE notebooks SET name = ?2 WHERE id = ?1",
1200 (id.to_string(), name.to_string()),
1201 )
1202 .await?;
1203 Ok(())
1204 }
1205
1206 /// Deletes the notebook. Its notes are kept and become unfiled.
1207 pub async fn delete_notebook(&self, id: &str) -> anyhow::Result<()> {
1208 let mut conn = self.conn.lock().await;
1209 let tx = conn.transaction().await?;
1210 tx.execute(
1211 "UPDATE notes SET notebook_id = NULL WHERE notebook_id = ?1",
1212 (id.to_string(),),
1213 )
1214 .await?;
1215 tx.execute("DELETE FROM notebooks WHERE id = ?1", (id.to_string(),))
1216 .await?;
1217 tx.commit().await?;
1218 self.changed(Change::NotebookGone(id.to_owned()));
1219 Ok(())
1220 }
1221
1222 pub async fn move_note(&self, note_id: &str, notebook_id: Option<&str>) -> anyhow::Result<()> {
1223 let conn = self.conn.lock().await;
1224 conn.execute(
1225 "UPDATE notes SET notebook_id = ?2 WHERE id = ?1",
1226 (note_id.to_string(), notebook_id.map(str::to_string)),
1227 )
1228 .await?;
1229 self.changed(Change::Note(note_id.to_owned()));
1230 Ok(())
1231 }
1232
1233 /// Deletes the note together with its updates, snapshot and searchable text.
1234 pub async fn delete_note(&self, note_id: &str) -> anyhow::Result<()> {
1235 let mut conn = self.conn.lock().await;
1236 let tx = conn.transaction().await?;
1237 delete_note_rows(&tx, note_id).await?;
1238 tx.commit().await?;
1239 self.changed(Change::Note(note_id.to_owned()));
1240 Ok(())
1241 }
1242
1243 /// Moves the note to the trash. It stays readable by `get_note` and is hidden
1244 /// from lists and search until restored or purged.
1245 pub async fn trash_note(&self, note_id: &str) -> anyhow::Result<()> {
1246 let conn = self.conn.lock().await;
1247 conn.execute(
1248 "UPDATE notes SET trashed_at = ?2 WHERE id = ?1",
1249 (note_id.to_string(), now_millis()),
1250 )
1251 .await?;
1252 self.changed(Change::Note(note_id.to_owned()));
1253 Ok(())
1254 }
1255
1256 /// Takes the note out of the trash.
1257 pub async fn restore_note(&self, note_id: &str) -> anyhow::Result<()> {
1258 let conn = self.conn.lock().await;
1259 conn.execute(
1260 "UPDATE notes SET trashed_at = NULL WHERE id = ?1",
1261 (note_id.to_string(),),
1262 )
1263 .await?;
1264 self.changed(Change::Note(note_id.to_owned()));
1265 Ok(())
1266 }
1267
1268 /// Permanently deletes notes trashed more than `older_than_ms` milliseconds ago.
1269 /// Returns the ids of the deleted notes.
1270 pub async fn purge_trash(&self, older_than_ms: i64) -> anyhow::Result<Vec<String>> {
1271 let cutoff = now_millis().saturating_sub(older_than_ms);
1272 self.delete_trashed(cutoff).await
1273 }
1274
1275 /// Permanently deletes every trashed note. Returns the ids of the deleted notes.
1276 pub async fn empty_trash(&self) -> anyhow::Result<Vec<String>> {
1277 self.delete_trashed(i64::MAX).await
1278 }
1279
1280 /// Deletes trashed notes with `trashed_at < before` in one transaction.
1281 async fn delete_trashed(&self, before: i64) -> anyhow::Result<Vec<String>> {
1282 let mut conn = self.conn.lock().await;
1283 let tx = conn.transaction().await?;
1284 let mut rows = tx
1285 .query(
1286 "SELECT id FROM notes WHERE trashed_at IS NOT NULL AND trashed_at < ?1 ORDER BY trashed_at, id",
1287 (before,),
1288 )
1289 .await?;
1290 let mut ids = Vec::new();
1291 while let Some(row) = rows.next().await? {
1292 ids.push(text_col(&row, 0)?);
1293 }
1294 drop(rows);
1295 for id in &ids {
1296 delete_note_rows(&tx, id).await?;
1297 }
1298 tx.commit().await?;
1299 for id in &ids {
1300 self.changed(Change::Note(id.clone()));
1301 }
1302 Ok(ids)
1303 }
1304
1305 /// Notes that are not in the trash, most recently updated first.
1306 pub async fn list_notes(&self) -> anyhow::Result<Vec<NoteMeta>> {
1307 let mut notes: Vec<NoteMeta> = self.directory().await?.live().iter().map(|e| e.meta()).collect();
1308 notes.sort_by(|a, b| b.updated_at.cmp(&a.updated_at).then_with(|| a.id.cmp(&b.id)));
1309 Ok(notes)
1310 }
1311
1312 /// The most recently updated note outside the trash whose `title_key` is `key`.
1313 pub async fn note_by_title_key(&self, key: &str) -> anyhow::Result<Option<NoteMeta>> {
1314 let dir = self.directory().await?;
1315 Ok(dir
1316 .entries()
1317 .filter(|e| e.trashed_at.is_none() && title_key(e.title()) == key)
1318 .max_by(|a, b| a.updated_at.cmp(&b.updated_at).then_with(|| b.id().cmp(a.id())))
1319 .map(|e| e.meta()))
1320 }
1321
1322 /// One page of the notes `filter` selects, in the order of the list: `limit` rows
1323 /// after the first `offset`.
1324 pub async fn list_notes_page(
1325 &self,
1326 filter: ListFilter,
1327 limit: usize,
1328 offset: usize,
1329 ) -> anyhow::Result<Vec<NoteMeta>> {
1330 let (clause, params) = filter.clause();
1331 // Both are plain numbers, so they are written into the SQL rather than bound.
1332 let sql = format!(
1333 "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes
1334 WHERE {clause} ORDER BY {} LIMIT {limit} OFFSET {offset}",
1335 filter.order()
1336 );
1337 let conn = self.conn.lock().await;
1338 let mut rows = conn.query(sql, params).await?;
1339 let mut notes = Vec::new();
1340 while let Some(row) = rows.next().await? {
1341 notes.push(note_from_row(&row)?);
1342 }
1343 Ok(notes)
1344 }
1345
1346 /// How many notes `filter` selects.
1347 pub async fn count_filter(&self, filter: &ListFilter) -> anyhow::Result<usize> {
1348 let dir = self.directory().await?;
1349 let c = &dir.counts;
1350 Ok(match filter {
1351 ListFilter::All => c.live,
1352 ListFilter::Unfiled => c.unfiled,
1353 ListFilter::Notebook(id) => c.notebooks.get(id).copied().unwrap_or(0),
1354 ListFilter::Trash => c.trashed,
1355 })
1356 }
1357
1358 /// Counts for the sidebar: notes outside the trash, notes outside the trash in no
1359 /// notebook, and trashed notes.
1360 pub async fn count_notes(&self) -> anyhow::Result<(usize, usize, usize)> {
1361 let dir = self.directory().await?;
1362 Ok((dir.counts.live, dir.counts.unfiled, dir.counts.trashed))
1363 }
1364
1365 /// Number of notes outside the trash in each notebook, keyed by notebook id. Notebooks
1366 /// with no notes are absent.
1367 pub async fn notebook_counts(&self) -> anyhow::Result<HashMap<String, usize>> {
1368 Ok(self.directory().await?.counts.notebooks.clone())
1369 }
1370
1371 pub async fn get_note(&self, id: &str) -> anyhow::Result<Option<NoteMeta>> {
1372 let conn = self.read.lock().await;
1373 let mut rows = conn
1374 .query(
1375 "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes WHERE id = ?1",
1376 (id.to_string(),),
1377 )
1378 .await?;
1379 match rows.next().await? {
1380 Some(row) => Ok(Some(note_from_row(&row)?)),
1381 None => Ok(None),
1382 }
1383 }
1384
1385 /// Appends a Loro update. Idempotent: the same bytes stored twice are kept once.
1386 pub async fn append_update(&self, note_id: &str, update: &[u8]) -> anyhow::Result<()> {
1387 let hash = blake3::hash(update).as_bytes().to_vec();
1388 let mut conn = self.conn.lock().await;
1389 let tx = conn.transaction().await?;
1390 let inserted = tx
1391 .execute(
1392 "INSERT OR IGNORE INTO updates (note_id, hash, data) VALUES (?1, ?2, ?3)",
1393 (note_id.to_string(), hash, update.to_vec()),
1394 )
1395 .await?;
1396 if inserted > 0 {
1397 tx.execute(
1398 "UPDATE notes SET updated_at = ?2 WHERE id = ?1",
1399 (note_id.to_string(), now_millis()),
1400 )
1401 .await?;
1402 }
1403 tx.commit().await?;
1404 if inserted > 0 {
1405 self.changed(Change::Note(note_id.to_owned()));
1406 }
1407 Ok(())
1408 }
1409
1410 pub async fn load_doc(&self, note_id: &str) -> anyhow::Result<DocBytes> {
1411 let conn = self.conn.lock().await;
1412
1413 let mut rows = conn
1414 .query(
1415 "SELECT data, upto_seq, markdown FROM snapshots WHERE note_id = ?1",
1416 (note_id.to_string(),),
1417 )
1418 .await?;
1419 let (snapshot, upto_seq, markdown) = match rows.next().await? {
1420 Some(row) => (Some(blob_col(&row, 0)?), int_col(&row, 1)?, opt_text_col(&row, 2)?),
1421 None => (None, 0, None),
1422 };
1423 drop(rows);
1424
1425 let mut rows = conn
1426 .query(
1427 "SELECT data FROM updates WHERE note_id = ?1 AND seq > ?2 ORDER BY seq",
1428 (note_id.to_string(), upto_seq),
1429 )
1430 .await?;
1431 let mut updates = Vec::new();
1432 while let Some(row) = rows.next().await? {
1433 updates.push(blob_col(&row, 0)?);
1434 }
1435
1436 drop(rows);
1437 let markdown = match snapshot {
1438 Some(_) => markdown.filter(|_| updates.is_empty()),
1439 None => {
1440 let mut rows = conn
1441 .query("SELECT markdown FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),))
1442 .await?;
1443 match rows.next().await? {
1444 Some(row) => Some(text_col(&row, 0)?),
1445 None => None,
1446 }
1447 }
1448 };
1449 Ok(DocBytes { snapshot, updates, markdown, export: None, upto_seq })
1450 }
1451
1452 /// [`load_doc`](Self::load_doc) for many notes, in the order of `ids`, with a few
1453 /// queries per `PREVIEW_BATCH` notes rather than two per note.
1454 /// The stored state of each of `ids`, for the export: a note whose export markdown
1455 /// is cached for its snapshot comes without the snapshot, and so does one whose
1456 /// stored markdown is current, unless it is in `linking`.
1457 pub async fn load_docs(&self, ids: &[String], linking: &std::collections::HashSet<String>) -> anyhow::Result<Vec<DocBytes>> {
1458 let empty = || DocBytes { snapshot: None, updates: Vec::new(), markdown: None, export: None, upto_seq: 0 };
1459 let mut docs: HashMap<String, DocBytes> = HashMap::new();
1460 let conn = self.conn.lock().await;
1461 for chunk in ids.chunks(PREVIEW_BATCH) {
1462 let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", ");
1463 let mut rows = conn
1464 .query(
1465 format!(
1466 "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
1467 FROM snapshots s LEFT JOIN export_text e ON e.note_id = s.note_id AND e.upto_seq = s.upto_seq
1468 WHERE s.note_id IN ({placeholders})"
1469 ),
1470 chunk.to_vec(),
1471 )
1472 .await?;
1473 while let Some(row) = rows.next().await? {
1474 let export = opt_text_col(&row, 3)?;
1475 let snapshot = opt_blob_col(&row, 4)?;
1476 let doc = DocBytes { snapshot, updates: Vec::new(), markdown: opt_text_col(&row, 2)?, export, upto_seq: int_col(&row, 1)? };
1477 docs.insert(text_col(&row, 0)?, doc);
1478 }
1479 drop(rows);
1480 let mut rows = conn
1481 .query(
1482 format!("SELECT note_id, seq, data FROM updates WHERE note_id IN ({placeholders}) ORDER BY seq"),
1483 chunk.to_vec(),
1484 )
1485 .await?;
1486 while let Some(row) = rows.next().await? {
1487 let id = text_col(&row, 0)?;
1488 let doc = docs.entry(id).or_insert_with(empty);
1489 if int_col(&row, 1)? > doc.upto_seq {
1490 doc.updates.push(blob_col(&row, 2)?);
1491 doc.markdown = None;
1492 doc.export = None;
1493 }
1494 }
1495 drop(rows);
1496 // Edited since its markdown was stored, or linking: the snapshot is needed after all.
1497 let stale: Vec<String> = chunk
1498 .iter()
1499 .filter(|id| {
1500 docs.get(*id).is_some_and(|d| {
1501 d.snapshot.is_none() && d.export.is_none() && (d.markdown.is_none() || linking.contains(*id))
1502 })
1503 })
1504 .cloned()
1505 .collect();
1506 for id in stale {
1507 let mut rows = conn.query("SELECT data FROM snapshots WHERE note_id = ?1", (id.clone(),)).await?;
1508 if let Some(row) = rows.next().await? {
1509 docs.get_mut(&id).unwrap().snapshot = Some(blob_col(&row, 0)?);
1510 }
1511 }
1512 let mut rows = conn
1513 .query(
1514 format!("SELECT note_id, markdown FROM pending_docs WHERE note_id IN ({placeholders})"),
1515 chunk.to_vec(),
1516 )
1517 .await?;
1518 while let Some(row) = rows.next().await? {
1519 docs.insert(text_col(&row, 0)?, DocBytes { markdown: Some(text_col(&row, 1)?), ..empty() });
1520 }
1521 }
1522 Ok(ids.iter().map(|id| docs.remove(id).unwrap_or_else(empty)).collect())
1523 }
1524
1525 /// Streams every cached export markdown that is current for its snapshot, as
1526 /// `(note id, markdown)` batches of about `batch_bytes`, read on a connection of its
1527 /// own so other requests go on meanwhile. A note edited since its snapshot may
1528 /// still come: see [`Store::stale_snapshots`].
1529 pub fn scan_export_texts(&self, batch_bytes: usize) -> anyhow::Result<mpsc::Receiver<anyhow::Result<Vec<(String, String)>>>> {
1530 let conn = self.db.connect()?;
1531 let (tx, rx) = mpsc::channel(2);
1532 tokio::spawn(async move {
1533 let result = async {
1534 let mut rows = conn
1535 .query(
1536 // Joining snapshots would read their blobs: a new snapshot drops
1537 // the row instead (see put_snapshot).
1538 "SELECT note_id, markdown FROM export_text",
1539 (),
1540 )
1541 .await?;
1542 let (mut batch, mut bytes) = (Vec::new(), 0);
1543 while let Some(row) = rows.next().await? {
1544 let md = text_col(&row, 1)?;
1545 bytes += md.len() + 64;
1546 batch.push((text_col(&row, 0)?, md));
1547 if bytes > batch_bytes {
1548 bytes = 0;
1549 if tx.send(Ok(std::mem::take(&mut batch))).await.is_err() {
1550 return Ok(());
1551 }
1552 }
1553 }
1554 let _ = tx.send(Ok(batch)).await;
1555 anyhow::Ok(())
1556 }
1557 .await;
1558 if let Err(err) = result {
1559 let _ = tx.send(Err(err)).await;
1560 }
1561 });
1562 Ok(rx)
1563 }
1564
1565 /// Caches export markdown (see [`DocBytes::export`]) as `(note id, snapshot's last
1566 /// update, markdown)`.
1567 pub async fn put_export_texts(&self, texts: &[(String, i64, String)]) -> anyhow::Result<()> {
1568 let mut conn = self.conn.lock().await;
1569 let tx = conn.transaction().await?;
1570 for (id, upto_seq, markdown) in texts {
1571 // A newer snapshot may have been written since this was rendered.
1572 let mut rows = tx.query("SELECT upto_seq FROM snapshots WHERE note_id = ?1", (id.clone(),)).await?;
1573 let current = match rows.next().await? {
1574 Some(row) => int_col(&row, 0)? == *upto_seq,
1575 None => false,
1576 };
1577 drop(rows);
1578 if !current {
1579 continue;
1580 }
1581 tx.execute(
1582 "INSERT INTO export_text (note_id, upto_seq, markdown) VALUES (?1, ?2, ?3)
1583 ON CONFLICT(note_id) DO UPDATE SET upto_seq = excluded.upto_seq, markdown = excluded.markdown",
1584 (id.clone(), *upto_seq, markdown.clone()),
1585 )
1586 .await?;
1587 }
1588 tx.commit().await?;
1589 Ok(())
1590 }
1591
1592 /// Notes with updates newer than their snapshot: a snapshot was due when the server
1593 /// stopped. Their docs load slower until a new snapshot covers them.
1594 pub async fn stale_snapshots(&self) -> anyhow::Result<Vec<String>> {
1595 // Two plain reads: turso scans every update for each note when they are joined.
1596 let conn = self.conn.lock().await;
1597 let mut rows = conn.query("SELECT note_id, seq FROM updates", ()).await?;
1598 let mut newest: HashMap<String, i64> = HashMap::new();
1599 while let Some(row) = rows.next().await? {
1600 let seq = int_col(&row, 1)?;
1601 let max = newest.entry(text_col(&row, 0)?).or_insert(seq);
1602 *max = (*max).max(seq);
1603 }
1604 drop(rows);
1605 let ids: Vec<String> = newest.keys().cloned().collect();
1606 for chunk in ids.chunks(PREVIEW_BATCH) {
1607 let placeholders = (1..=chunk.len()).map(|i| format!("?{i}")).collect::<Vec<_>>().join(", ");
1608 let mut rows = conn
1609 .query(format!("SELECT note_id, upto_seq FROM snapshots WHERE note_id IN ({placeholders})"), chunk.to_vec())
1610 .await?;
1611 while let Some(row) = rows.next().await? {
1612 let id = text_col(&row, 0)?;
1613 if newest.get(&id).is_some_and(|max| *max <= int_col(&row, 1).unwrap_or(0)) {
1614 newest.remove(&id);
1615 }
1616 }
1617 }
1618 Ok(newest.into_keys().collect())
1619 }
1620
1621 /// The newest stored update's sequence number for the note, 0 when there is none.
1622 pub async fn max_seq(&self, note_id: &str) -> anyhow::Result<i64> {
1623 let conn = self.conn.lock().await;
1624 let mut rows = conn
1625 .query("SELECT COALESCE(MAX(seq), 0) FROM updates WHERE note_id = ?1", (note_id.to_string(),))
1626 .await?;
1627 match rows.next().await? {
1628 Some(row) => int_col(&row, 0),
1629 None => Ok(0),
1630 }
1631 }
1632
1633 /// Whether the note's stored text links to other notes.
1634 pub async fn has_links(&self, note_id: &str) -> anyhow::Result<bool> {
1635 let conn = self.read.lock().await;
1636 let mut rows = conn
1637 .query("SELECT 1 FROM note_links WHERE src = ?1 LIMIT 1", (note_id.to_string(),))
1638 .await?;
1639 Ok(rows.next().await?.is_some())
1640 }
1641
1642 /// Every note whose stored text links to other notes.
1643 pub async fn linking_notes(&self) -> anyhow::Result<std::collections::HashSet<String>> {
1644 let conn = self.conn.lock().await;
1645 // Deduplicated here: turso's DISTINCT spills and thrashes on millions of rows.
1646 let mut rows = conn.query("SELECT src FROM note_links", ()).await?;
1647 let mut out = std::collections::HashSet::new();
1648 while let Some(row) = rows.next().await? {
1649 out.insert(text_col(&row, 0)?);
1650 }
1651 Ok(out)
1652 }
1653
1654 /// Ids of the notes some note links to.
1655 pub async fn link_targets(&self) -> anyhow::Result<std::collections::HashSet<String>> {
1656 let conn = self.conn.lock().await;
1657 let mut rows = conn.query("SELECT dst_id FROM note_links WHERE dst_id IS NOT NULL", ()).await?;
1658 let mut out = std::collections::HashSet::new();
1659 while let Some(row) = rows.next().await? {
1660 out.insert(text_col(&row, 0)?);
1661 }
1662 Ok(out)
1663 }
1664
1665 /// Titles of the given notes that are outside the trash, by id.
1666 pub async fn titles_of(&self, ids: impl IntoIterator<Item = String>) -> anyhow::Result<HashMap<String, String>> {
1667 let dir = self.directory().await?;
1668 Ok(ids
1669 .into_iter()
1670 .filter_map(|id| {
1671 let e = dir.get(&id).filter(|e| e.trashed_at.is_none())?;
1672 Some((id, e.title().to_owned()))
1673 })
1674 .collect())
1675 }
1676
1677 /// Stores a full snapshot that holds every update up to `upto_seq`, plus the derived
1678 /// markdown and title. A snapshot older than the stored one is ignored, and so is
1679 /// the result `false`. Updates are never deleted; later loads only read updates
1680 /// newer than the snapshot.
1681 pub async fn put_snapshot(
1682 &self,
1683 note_id: &str,
1684 snapshot: Vec<u8>,
1685 upto_seq: i64,
1686 markdown: &str,
1687 title: &str,
1688 ) -> anyhow::Result<bool> {
1689 let mut conn = self.conn.lock().await;
1690 let tx = conn.transaction().await?;
1691
1692 // Only a snapshot at least as new replaces the stored one. Delete, then insert:
1693 // an upsert reads the old row whole, and a huge note's row is hundreds of MB.
1694 let mut rows = tx
1695 .query("SELECT upto_seq FROM snapshots WHERE note_id = ?1", (note_id.to_string(),))
1696 .await?;
1697 let stored = match rows.next().await? {
1698 Some(row) => Some(int_col(&row, 0)?),
1699 None => None,
1700 };
1701 drop(rows);
1702 if stored.is_some_and(|stored| stored > upto_seq) {
1703 return Ok(false);
1704 }
1705 if stored.is_some() {
1706 tx.execute("DELETE FROM snapshots WHERE note_id = ?1", (note_id.to_string(),)).await?;
1707 }
1708 tx.execute(
1709 "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, ?3, ?4)",
1710 (
1711 note_id.to_string(),
1712 snapshot,
1713 upto_seq,
1714 markdown.to_string(),
1715 ),
1716 )
1717 .await?;
1718 // The snapshot holds every op of the updates up to it.
1719 tx.execute("DELETE FROM updates WHERE note_id = ?1 AND seq <= ?2", (note_id.to_string(), upto_seq)).await?;
1720 tx.execute("DELETE FROM export_text WHERE note_id = ?1 AND upto_seq <> ?2", (note_id.to_string(), upto_seq)).await?;
1721 tx.execute(
1722 "UPDATE notes SET title = ?2 WHERE id = ?1",
1723 (note_id.to_string(), title.to_string()),
1724 )
1725 .await?;
1726
1727 tx.commit().await?;
1728 self.changed(Change::Note(note_id.to_owned()));
1729 Ok(true)
1730 }
1731
1732 pub async fn set_title(&self, note_id: &str, title: &str) -> anyhow::Result<()> {
1733 let conn = self.conn.lock().await;
1734 conn.execute(
1735 "UPDATE notes SET title = ?2 WHERE id = ?1",
1736 (note_id.to_string(), title.to_string()),
1737 )
1738 .await?;
1739 self.changed(Change::Note(note_id.to_owned()));
1740 Ok(())
1741 }
1742
1743 /// Writes the searchable text of a note. Does nothing when the note no longer
1744 /// exists, so a flush that races a delete cannot bring the text back.
1745 pub async fn put_text(&self, note_id: &str, title: &str, body: &str) -> anyhow::Result<()> {
1746 let mut conn = self.conn.lock().await;
1747 let mut rows = conn
1748 .query("SELECT 1 FROM notes WHERE id = ?1", (note_id.to_string(),))
1749 .await?;
1750 let exists = rows.next().await?.is_some();
1751 drop(rows);
1752 if !exists {
1753 return Ok(());
1754 }
1755 // Delete, then insert: an upsert reads the old row whole.
1756 let tx = conn.transaction().await?;
1757 tx.execute("DELETE FROM note_text WHERE note_id = ?1", (note_id.to_string(),)).await?;
1758 tx.execute(
1759 "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3)",
1760 (note_id.to_string(), title.to_string(), body.to_string()),
1761 )
1762 .await?;
1763 tx.commit().await?;
1764 self.changed(Change::Note(note_id.to_owned()));
1765 Ok(())
1766 }
1767
1768 /// Replaces the note links of `src`. Does nothing when the note no longer exists, like
1769 /// `put_text`. Title targets are stored by `title_key`.
1770 pub async fn set_links(&self, src: &str, targets: &[LinkTarget]) -> anyhow::Result<()> {
1771 let mut conn = self.conn.lock().await;
1772 let mut rows = conn
1773 .query("SELECT 1 FROM notes WHERE id = ?1", (src.to_string(),))
1774 .await?;
1775 let exists = rows.next().await?.is_some();
1776 drop(rows);
1777 if !exists {
1778 return Ok(());
1779 }
1780 let tx = conn.transaction().await?;
1781 tx.execute("DELETE FROM note_links WHERE src = ?1", (src.to_string(),))
1782 .await?;
1783 insert_links(&tx, src, targets).await?;
1784 tx.commit().await?;
1785 Ok(())
1786 }
1787
1788 /// Creates a note from imported content in one transaction: the note row in the
1789 /// notebook named `notebook` (matched case-insensitively, created when missing),
1790 /// its snapshot, searchable text, links and export markdown (see [`DocBytes::export`]).
1791 /// Returns the note id.
1792 pub async fn import_note(
1793 &self,
1794 notebook: Option<&str>,
1795 snapshot: Option<&[u8]>,
1796 title: &str,
1797 body: &str,
1798 links: &[LinkTarget],
1799 export: Option<&str>,
1800 ) -> anyhow::Result<String> {
1801 let mut conn = self.conn.lock().await;
1802 let tx = conn.transaction().await?;
1803 let notebook_id = match notebook {
1804 Some(name) => Some(match find_notebook(&tx, name).await? {
1805 Some(id) => id,
1806 None => {
1807 let id = uuid::Uuid::now_v7().to_string();
1808 tx.execute(
1809 "INSERT INTO notebooks (id, name, created_at) VALUES (?1, ?2, ?3)",
1810 (id.clone(), name.to_string(), now_millis()),
1811 )
1812 .await?;
1813 id
1814 }
1815 }),
1816 None => None,
1817 };
1818 let id = uuid::Uuid::now_v7().to_string();
1819 let now = now_millis();
1820 tx.execute(
1821 "INSERT INTO notes (id, title, created_at, updated_at, notebook_id) VALUES (?1, ?2, ?3, ?4, ?5)",
1822 (id.clone(), title.to_string(), now, now, notebook_id),
1823 )
1824 .await?;
1825 match snapshot {
1826 Some(snapshot) => {
1827 tx.execute(
1828 "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, 0, ?3)",
1829 (id.clone(), snapshot.to_vec(), body.to_string()),
1830 )
1831 .await?;
1832 if let Some(export) = export {
1833 tx.execute(
1834 "INSERT INTO export_text (note_id, upto_seq, markdown) VALUES (?1, 0, ?2)",
1835 (id.clone(), export.to_string()),
1836 )
1837 .await?;
1838 }
1839 }
1840 None => {
1841 tx.execute("INSERT INTO pending_docs (note_id, markdown) VALUES (?1, ?2)", (id.clone(), body.to_string()))
1842 .await?;
1843 }
1844 }
1845 tx.execute(
1846 "INSERT INTO note_text (note_id, title, body) VALUES (?1, ?2, ?3)",
1847 (id.clone(), title.to_string(), body.to_string()),
1848 )
1849 .await?;
1850 insert_links(&tx, &id, links).await?;
1851 tx.commit().await?;
1852 self.changed(Change::Note(id.clone()));
1853 Ok(id)
1854 }
1855
1856 /// Notes imported without a doc yet, oldest first.
1857 pub async fn pending_docs(&self) -> anyhow::Result<Vec<String>> {
1858 let conn = self.conn.lock().await;
1859 let mut rows = conn.query("SELECT note_id FROM pending_docs ORDER BY note_id", ()).await?;
1860 let mut out = Vec::new();
1861 while let Some(row) = rows.next().await? {
1862 out.push(text_col(&row, 0)?);
1863 }
1864 Ok(out)
1865 }
1866
1867 /// The first `bytes` bytes or so of a pending note's markdown, cut at a line end.
1868 pub async fn pending_head(&self, note_id: &str, bytes: usize) -> anyhow::Result<Option<String>> {
1869 let conn = self.read.lock().await;
1870 let mut rows = conn
1871 .query(
1872 "SELECT substr(markdown, 1, ?2) FROM pending_docs WHERE note_id = ?1",
1873 (note_id.to_string(), bytes as i64),
1874 )
1875 .await?;
1876 let Some(row) = rows.next().await? else { return Ok(None) };
1877 let mut head = text_col(&row, 0)?;
1878 if head.len() >= bytes
1879 && let Some(end) = head.rfind('\n')
1880 {
1881 head.truncate(end + 1);
1882 }
1883 Ok(Some(head))
1884 }
1885
1886 /// The imported markdown of a note whose doc is not built yet.
1887 pub async fn pending_markdown(&self, note_id: &str) -> anyhow::Result<Option<String>> {
1888 let conn = self.conn.lock().await;
1889 let mut rows = conn
1890 .query("SELECT markdown FROM pending_docs WHERE note_id = ?1", (note_id.to_string(),))
1891 .await?;
1892 match rows.next().await? {
1893 Some(row) => Ok(Some(text_col(&row, 0)?)),
1894 None => Ok(None),
1895 }
1896 }
1897
1898 /// Replaces a pending note's markdown with its built doc, and the text derived from
1899 /// it. Does nothing when the note is gone or no longer pending.
1900 pub async fn finish_pending(
1901 &self,
1902 note_id: &str,
1903 snapshot: &[u8],
1904 title: &str,
1905 body: &str,
1906 links: &[LinkTarget],
1907 ) -> anyhow::Result<()> {
1908 let mut conn = self.conn.lock().await;
1909 let tx = conn.transaction().await?;
1910 let id = note_id.to_string();
1911 if tx.execute("DELETE FROM pending_docs WHERE note_id = ?1", (id.clone(),)).await? == 0 {
1912 return Ok(());
1913 }
1914 tx.execute(
1915 "INSERT INTO snapshots (note_id, data, upto_seq, markdown) VALUES (?1, ?2, 0, ?3)",
1916 (id.clone(), snapshot.to_vec(), body.to_string()),
1917 )
1918 .await?;
1919 tx.execute("UPDATE notes SET title = ?2 WHERE id = ?1", (id.clone(), title.to_string())).await?;
1920 tx.execute(
1921 "UPDATE note_text SET title = ?2, body = ?3 WHERE note_id = ?1",
1922 (id.clone(), title.to_string(), body.to_string()),
1923 )
1924 .await?;
1925 tx.execute("DELETE FROM note_links WHERE src = ?1", (id.clone(),)).await?;
1926 insert_links(&tx, note_id, links).await?;
1927 tx.commit().await?;
1928 self.changed(Change::Note(id));
1929 Ok(())
1930 }
1931
1932 /// Non-trashed notes, other than `note_id`, that link to the note by its id or by
1933 /// its title. Most recently updated first.
1934 pub async fn backlinks(&self, note_id: &str, title: &str) -> anyhow::Result<Vec<NoteMeta>> {
1935 let conn = self.read.lock().await;
1936 let mut rows = conn
1937 .query(
1938 "SELECT id, title, created_at, updated_at, notebook_id, trashed_at FROM notes
1939 WHERE trashed_at IS NULL AND id <> ?1 AND id IN
1940 (SELECT src FROM note_links WHERE dst_id = ?1 OR dst_title = ?2)
1941 ORDER BY updated_at DESC, id",
1942 (note_id.to_string(), title_key(title)),
1943 )
1944 .await?;
1945 let mut notes = Vec::new();
1946 while let Some(row) = rows.next().await? {
1947 notes.push(note_from_row(&row)?);
1948 }
1949 Ok(notes)
1950 }
1951
1952 /// Search over titles and bodies with `matcher` (see [`crate::matcher`]): every term
1953 /// must match the title or the text. Closest matches first, then more terms in the
1954 /// title, then most recently updated.
1955 ///
1956 /// Long notes are matched against their stored text, which for a pattern without a
1957 /// literal means reading all of it. With a `budget`, that stops once the budget is
1958 /// spent, and the result says it is partial: the best hits found so far.
1959 pub async fn search(&self, matcher: &Matcher, limit: usize, budget: Option<std::time::Duration>) -> anyhow::Result<Searched> {
1960 if limit == 0 {
1961 return Ok(Searched::default());
1962 }
1963 let started = std::time::Instant::now();
1964 // Words are matched rather than looked up: typing "asd" has to find "asdadasxd"
1965 // (and "isik" find "Işık"). The directory is read in place, on this worker.
1966 let dir = self.directory().await?;
1967 let (mut hits, cut) = tokio::task::block_in_place(|| {
1968 let hits = match_top(matcher, dir.slots(), &dir.vocab, limit);
1969 // With the least each can cost: no cost, unless the words say otherwise.
1970 let mut cut: Vec<(Arc<Entry>, usize)> = match matcher.word_terms() {
1971 Some(_) => Vec::new(),
1972 None => dir.entries().filter(|e| e.plain_cut && e.trashed_at.is_none()).map(|e| (e.clone(), 0)).collect(),
1973 };
1974 // Notes without the words a match needs are not read. An exact phrase costs
1975 // nothing only where its first word starts a word.
1976 if let Some(alts) = matcher.required_words().filter(|_| !cut.is_empty()) {
1977 let vocab = dir.vocab.read().unwrap();
1978 let mask = |piece: &[char], part: Part| (0..vocab.len()).map(|id| part.holds(vocab.word(id), piece)).collect::<Vec<bool>>();
1979 let holds: Vec<Vec<Vec<bool>>> = alts.iter().map(|words| words.iter().map(|(piece, part)| mask(piece, *part)).collect()).collect();
1980 let starts = matches!(matcher, Matcher::Terms { .. }).then(|| match &alts[0][0] {
1981 (piece, Part::End) => mask(piece, Part::Whole),
1982 (piece, Part::Inside) => mask(piece, Part::Start),
1983 _ => holds[0][0].clone(),
1984 });
1985 drop(vocab);
1986 let has = |e: &Entry, h: &[bool]| e.text_words().iter().any(|&id| h[id as usize]);
1987 cut.retain(|(e, _)| holds.iter().any(|alt| alt.iter().all(|h| has(e, h) || e.title_words().iter().any(|&id| h[id as usize]))));
1988 if let Some(starts) = starts {
1989 for (e, floor) in &mut cut {
1990 *floor = usize::from(!has(e, &starts));
1991 }
1992 }
1993 }
1994 // A regex that only matches inside words needs a word it matches.
1995 if let Some(re) = matcher.word_regex().filter(|_| !cut.is_empty()) {
1996 let vocab = dir.vocab.read().unwrap();
1997 let mut word = String::new();
1998 let hits: Vec<bool> = (0..vocab.len())
1999 .map(|id| {
2000 word.clear();
2001 word.extend(vocab.word(id).iter());
2002 re.is_match(&word)
2003 })
2004 .collect();
2005 drop(vocab);
2006 cut.retain(|(e, _)| e.text_words().iter().chain(e.title_words()).any(|&id| hits[id as usize]));
2007 }
2008 (hits, cut)
2009 });
2010 drop(dir);
2011 // Long notes keep only their start in memory: match them against their stored
2012 // text, a few at a time, and keep the text of those that match for the snippet.
2013 // The best key each could get, from its title: the text matching at no cost.
2014 // Going from the best bound, the rest can stop once `limit` hits beat it.
2015 let bound = |e: &Entry, floor: usize| -> RankKey {
2016 let in_title = matcher.term_costs(e.title());
2017 let zero = in_title.iter().filter(|c| **c == Some(0)).count();
2018 let cost = in_title.iter().map(|c| if *c == Some(0) { 0 } else { floor }).sum();
2019 ((cost, std::cmp::Reverse(zero)), std::cmp::Reverse(e.updated_at))
2020 };
2021 let mut cut: Vec<(RankKey, Arc<Entry>, usize)> = cut.into_iter().map(|(e, floor)| (bound(&e, floor), e, floor)).collect();
2022 cut.sort_unstable_by(|a, b| a.0.cmp(&b.0));
2023 // The start of each is in memory: its full text is read, on a connection of its
2024 // own, only when the start does not settle the match.
2025 let per_batch = std::thread::available_parallelism().map_or(1, |n| n.get());
2026 let (want, mut wanted) = (mpsc::channel::<Vec<String>>(1), mpsc::channel::<anyhow::Result<HashMap<String, String>>>(1));
2027 let (mut requests, answers) = (want.1, wanted.0);
2028 // One connection reads some 1.5 GB/s: a few share each batch.
2029 let readers: Vec<Arc<turso::Connection>> = (0..SEARCH_READERS).map(|_| self.db.connect().map(Arc::new)).collect::<Result<_, _>>()?;
2030 tokio::spawn(async move {
2031 while let Some(ids) = requests.recv().await {
2032 let parts = ids.chunks(ids.len().div_ceil(readers.len()).max(1)).zip(&readers).map(|(part, conn)| {
2033 let (part, conn) = (part.to_vec(), conn.clone());
2034 tokio::spawn(async move { bodies_on(&conn, &part).await })
2035 });
2036 let mut bodies = HashMap::new();
2037 let mut result = Ok(());
2038 for part in parts.collect::<Vec<_>>() {
2039 match part.await.map_err(anyhow::Error::from).and_then(|r| r) {
2040 Ok(b) => bodies.extend(b),
2041 Err(e) => result = Err(e),
2042 }
2043 }
2044 if answers.send(result.map(|_| bodies)).await.is_err() {
2045 return;
2046 }
2047 }
2048 });
2049 let ask = want.0;
2050 let mut snippets: HashMap<String, String> = HashMap::new();
2051 type Found = Option<(SearchKey, String)>;
2052 let par = |f: &(dyn Fn(&(Arc<Entry>, usize)) -> (Found, bool) + Sync), entries: &[(Arc<Entry>, usize)]| {
2053 tokio::task::block_in_place(|| {
2054 std::thread::scope(|scope| {
2055 let handles: Vec<_> = entries.iter().map(|e| scope.spawn(move || f(e))).collect();
2056 handles.into_iter().map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect::<Vec<_>>()
2057 })
2058 })
2059 };
2060 let from_bodies = |bodies: &HashMap<String, String>, entries: &[(Arc<Entry>, usize)]| -> Vec<Found> {
2061 par(&|(e, floor)| (bodies.get(e.id()).and_then(|body| match_long(e.title(), body, matcher, *floor)), true), entries)
2062 .into_iter()
2063 .map(|(found, _)| found)
2064 .collect()
2065 };
2066 let mut found_in = |entries: Vec<(Arc<Entry>, usize)>, found: Vec<Found>, hits: &mut Vec<(RankKey, Arc<Entry>)>| {
2067 for ((e, _), found) in entries.into_iter().zip(found) {
2068 if let Some((k, snip)) = found {
2069 snippets.insert(e.id().to_owned(), snip);
2070 hits.push(((k, std::cmp::Reverse(e.updated_at)), e));
2071 }
2072 }
2073 };
2074 // The notes whose texts were asked for: the next batch is read while they are
2075 // matched.
2076 let mut asked: Vec<(Arc<Entry>, usize)> = Vec::new();
2077 let mut partial = false;
2078 for batch in cut.chunks(per_batch) {
2079 if budget.is_some_and(|b| started.elapsed() >= b) {
2080 partial = true;
2081 break;
2082 }
2083 if hits.len() >= limit {
2084 hits = top_keyed(hits, limit, |e| e.id());
2085 if hits.last().is_some_and(|(k, _)| *k < batch[0].0) {
2086 break;
2087 }
2088 }
2089 let entries: Vec<(Arc<Entry>, usize)> = batch.iter().map(|(_, e, floor)| (e.clone(), *floor)).collect();
2090 let from_start = par(&|(e, floor)| match_pieces(e.title(), plain_pieces(e.plain()), matcher, *floor), &entries);
2091 let (mut settled, mut settled_found, mut unsettled) = (Vec::new(), Vec::new(), Vec::new());
2092 for (e, (found, perfect)) in entries.into_iter().zip(from_start) {
2093 if perfect {
2094 settled.push(e);
2095 settled_found.push(found);
2096 } else {
2097 unsettled.push(e);
2098 }
2099 }
2100 found_in(settled, settled_found, &mut hits);
2101 if !unsettled.is_empty() {
2102 ask.send(unsettled.iter().map(|(e, _)| e.id().to_owned()).collect()).await?;
2103 }
2104 let previous = std::mem::replace(&mut asked, unsettled);
2105 if !previous.is_empty() {
2106 let bodies = wanted.1.recv().await.context("reading note texts")??;
2107 let found = from_bodies(&bodies, &previous);
2108 found_in(previous, found, &mut hits);
2109 }
2110 }
2111 // Out of time: the batch still being read is left unread.
2112 if !asked.is_empty() && !partial {
2113 let bodies = wanted.1.recv().await.context("reading note texts")??;
2114 let found = from_bodies(&bodies, &asked);
2115 found_in(asked, found, &mut hits);
2116 }
2117 let hits = top(hits, limit, |e| e.id());
2118 // Snippets only for the hits shown: a common word matches nearly every note.
2119 let hits = hits
2120 .into_iter()
2121 .map(|e| SearchHit {
2122 snippet: snippets.remove(e.id()).unwrap_or_else(|| snippet(e.plain(), matcher)),
2123 note: e.meta(),
2124 })
2125 .collect();
2126 Ok(Searched { hits, partial })
2127 }
2128
2129 /// Notes, not in the trash, whose title holds every word of `query`, typos allowed
2130 /// (see [`crate::matcher`]). Closest matches first, then most recently updated.
2131 pub async fn search_titles(&self, query: &str, limit: usize) -> anyhow::Result<Vec<NoteMeta>> {
2132 let Some(matcher) = Matcher::simple(query) else {
2133 return Ok(Vec::new());
2134 };
2135 if limit == 0 {
2136 return Ok(Vec::new());
2137 }
2138 // Matched in Rust, not with SQL LIKE, which folds only ASCII case and has no
2139 // typo tolerance: "izmir" and "izmr" have to find "İzmir".
2140 let dir = self.directory().await?;
2141 // Closest first, then most recently updated.
2142 let hits = tokio::task::block_in_place(|| {
2143 let terms = matcher.word_terms().unwrap_or_default();
2144 let tables = word_costs(&matcher, terms, &dir.vocab.read().unwrap());
2145 par_top(dir.slots(), limit, |e| {
2146 let cost = tables.iter().map(|t| best_cost(t, e.title_words())).sum::<Option<usize>>()?;
2147 Some((cost, std::cmp::Reverse(e.updated_at)))
2148 })
2149 });
2150 Ok(hits.into_iter().map(|e| e.meta()).collect())
2151 }
2152
2153 /// Previews of the given notes' text, keyed by note id, for list rows.
2154 pub async fn previews_for(&self, ids: &[String]) -> anyhow::Result<HashMap<String, String>> {
2155 let dir = self.directory().await?;
2156 Ok(ids.iter().filter_map(|id| Some((id.clone(), dir.get(id)?.preview().to_string()))).collect())
2157 }
2158
2159 /// Stores a version of a note: the time in millis and the encoded frontiers of the doc.
2160 pub async fn add_version(&self, note_id: &str, at_ms: i64, frontiers: &[u8]) -> anyhow::Result<()> {
2161 let conn = self.conn.lock().await;
2162 conn.execute(
2163 "INSERT OR REPLACE INTO note_versions (note_id, at, frontiers) VALUES (?1, ?2, ?3)",
2164 (note_id.to_string(), at_ms, frontiers.to_vec()),
2165 )
2166 .await?;
2167 Ok(())
2168 }
2169
2170 /// Recorded versions of a note as `(at, frontiers)`, newest first.
2171 pub async fn list_versions(&self, note_id: &str) -> anyhow::Result<Vec<(i64, Vec<u8>)>> {
2172 let conn = self.conn.lock().await;
2173 let mut rows = conn
2174 .query(
2175 "SELECT at, frontiers FROM note_versions WHERE note_id = ?1 ORDER BY at DESC",
2176 (note_id.to_string(),),
2177 )
2178 .await?;
2179 let mut versions = Vec::new();
2180 while let Some(row) = rows.next().await? {
2181 versions.push((int_col(&row, 0)?, blob_col(&row, 1)?));
2182 }
2183 Ok(versions)
2184 }
2185
2186 /// The encoded frontiers of the version of a note taken at `at`, if it exists.
2187 pub async fn get_version(&self, note_id: &str, at: i64) -> anyhow::Result<Option<Vec<u8>>> {
2188 let conn = self.conn.lock().await;
2189 let mut rows = conn
2190 .query(
2191 "SELECT frontiers FROM note_versions WHERE note_id = ?1 AND at = ?2",
2192 (note_id.to_string(), at),
2193 )
2194 .await?;
2195 match rows.next().await? {
2196 Some(row) => Ok(Some(blob_col(&row, 0)?)),
2197 None => Ok(None),
2198 }
2199 }
2200}
2201
2202
2203#[cfg(test)]
2204mod tests {
2205 use super::Store;
2206
2207 #[tokio::test]
2208 async fn older_snapshot_does_not_replace_newer() {
2209 let dir = std::env::temp_dir().join(format!("note-test-{}", uuid::Uuid::now_v7()));
2210 std::fs::create_dir_all(&dir).unwrap();
2211 let store = Store::open(dir.join("t.db").to_str().unwrap()).await.unwrap();
2212 let note = store.create_note(None).await.unwrap();
2213 assert!(store.put_snapshot(&note.id, b"new".to_vec(), 5, "new", "t").await.unwrap());
2214 assert!(!store.put_snapshot(&note.id, b"old".to_vec(), 3, "old", "t").await.unwrap());
2215 let doc = store.load_doc(&note.id).await.unwrap();
2216 assert_eq!(doc.snapshot.as_deref(), Some(&b"new"[..]));
2217 assert_eq!(doc.markdown.as_deref(), Some("new"));
2218 let _ = std::fs::remove_dir_all(&dir);
2219 }
2220}
2221