docterm 0.2.0

A TUI-first documentation browser for Dash/Zeal docsets, optimized for the terminal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
use std::{io::Cursor, path::Path};

use rusqlite::{Connection, params};
use zstd::{decode_all, encode_all};

use crate::{
    error::StorageError,
    model::{Docset, FavoriteEntry, PageContent, SearchEntry},
};

/// SQL schema — embedded at compile time so the binary is self-contained.
const SCHEMA: &str = include_str!("../tables.sql");

// ── Domain types ─────────────────────────────────────────────────────────────

// ── Compression helpers ───────────────────────────────────────────────────────

/// Compress `data` at `level`, optionally using a pre-trained Zstd dictionary.
fn compress_maybe_dict(
    data: &[u8],
    level: i32,
    dict: Option<&[u8]>,
) -> Result<Vec<u8>, StorageError> {
    if let Some(d) = dict {
        let mut enc =
            zstd::bulk::Compressor::with_dictionary(level, d).map_err(StorageError::Zstd)?;
        enc.compress(data).map_err(StorageError::Zstd)
    } else {
        encode_all(data, level).map_err(StorageError::Zstd)
    }
}

/// Decompress `data`, optionally using the same Zstd dictionary that was used
/// during compression.  The decompressed size is bounded at 64 MiB.
fn decompress_maybe_dict(data: &[u8], dict: Option<&[u8]>) -> Result<Vec<u8>, StorageError> {
    const MAX_DECOMPRESSED: usize = 64 * 1024 * 1024;
    if let Some(d) = dict {
        let mut dec = zstd::bulk::Decompressor::with_dictionary(d).map_err(StorageError::Zstd)?;
        dec.decompress(data, MAX_DECOMPRESSED)
            .map_err(StorageError::Zstd)
    } else {
        decode_all(Cursor::new(data)).map_err(StorageError::Zstd)
    }
}

// ── Storage ──────────────────────────────────────────────────────────────────

pub struct Storage {
    conn: Connection,
    compression_level: i32,
}

impl Storage {
    /// Open (or create) the database at `path` and apply the schema.
    ///
    /// Pass `Path::new(":memory:")` for an in-memory database (tests).
    pub fn open(path: &Path, compression_level: i32) -> Result<Self, StorageError> {
        let conn = Connection::open(path)?;
        conn.execute_batch("PRAGMA foreign_keys = ON;")?;
        // WAL is silently ignored for :memory: databases.
        conn.execute_batch("PRAGMA journal_mode = WAL;")?;
        conn.execute_batch(SCHEMA)?;
        Ok(Self {
            conn,
            compression_level,
        })
    }

    // ── Docsets ───────────────────────────────────────────────────────────────

    /// Insert a docset; if the name already exists the existing row is left
    /// untouched.  Returns the `id` of the inserted or existing row.
    pub fn insert_docset(
        &self,
        name: &str,
        version: Option<&str>,
        path: Option<&str>,
    ) -> Result<i64, StorageError> {
        self.conn.execute(
            "INSERT OR IGNORE INTO docsets (name, version, path) VALUES (?1, ?2, ?3)",
            params![name, version, path],
        )?;
        let id: i64 = self.conn.query_row(
            "SELECT id FROM docsets WHERE name = ?1",
            params![name],
            |row| row.get(0),
        )?;
        Ok(id)
    }

    /// List all docsets ordered by favourites first, then name.
    pub fn list_docsets(&self) -> Result<Vec<Docset>, StorageError> {
        let mut stmt = self.conn.prepare(
            "SELECT id, name, version, path, is_favorite \
             FROM docsets ORDER BY is_favorite DESC, name",
        )?;
        let rows = stmt.query_map([], row_to_docset)?;
        Ok(rows.collect::<Result<Vec<_>, _>>()?)
    }

    /// Delete a docset and all associated entries and pages (via CASCADE).
    pub fn delete_docset(&self, id: i64) -> Result<(), StorageError> {
        self.conn
            .execute("DELETE FROM docsets WHERE id = ?1", params![id])?;
        Ok(())
    }

    // ── Docset dictionary ─────────────────────────────────────────────────────

    /// Store (or replace) a Zstd shared dictionary for `docset_id`.
    ///
    /// Produce the dictionary with [`postprocess::train_dictionary`] after
    /// converting all pages to Markdown, then pass it here for persistence.
    pub fn set_docset_dictionary(&self, docset_id: i64, dict: &[u8]) -> Result<(), StorageError> {
        self.conn.execute(
            "UPDATE docsets SET dictionary = ?1 WHERE id = ?2",
            params![dict, docset_id],
        )?;
        Ok(())
    }

    /// Retrieve the stored Zstd shared dictionary for `docset_id`, if any.
    pub fn get_docset_dictionary(&self, docset_id: i64) -> Result<Option<Vec<u8>>, StorageError> {
        let mut stmt = self
            .conn
            .prepare("SELECT dictionary FROM docsets WHERE id = ?1")?;
        let dict: Option<Vec<u8>> = stmt.query_row(params![docset_id], |row| row.get(0))?;
        Ok(dict)
    }

    // ── Search index ──────────────────────────────────────────────────────────

    pub fn insert_entry(
        &self,
        docset_id: i64,
        name: &str,
        entry_type: &str,
        path: &str,
    ) -> Result<i64, StorageError> {
        self.conn.execute(
            "INSERT INTO search_index (docset_id, name, type, path) \
             VALUES (?1, ?2, ?3, ?4)",
            params![docset_id, name, entry_type, path],
        )?;
        Ok(self.conn.last_insert_rowid())
    }

    pub fn get_entry(&self, id: i64) -> Result<SearchEntry, StorageError> {
        let mut stmt = self.conn.prepare(
            "SELECT si.id, si.docset_id, si.name, si.type, si.path, si.usage_count, \
                    d.name, d.version \
             FROM search_index si \
             JOIN docsets d ON d.id = si.docset_id \
             WHERE si.id = ?1",
        )?;
        Ok(stmt.query_row(params![id], row_to_entry)?)
    }

    pub fn list_entries_for_docset(
        &self,
        docset_id: i64,
    ) -> Result<Vec<SearchEntry>, StorageError> {
        let mut stmt = self.conn.prepare(
            "SELECT si.id, si.docset_id, si.name, si.type, si.path, si.usage_count, \
                    d.name, d.version \
             FROM search_index si \
             JOIN docsets d ON d.id = si.docset_id \
             WHERE si.docset_id = ?1 ORDER BY si.name",
        )?;
        let rows = stmt.query_map(params![docset_id], row_to_entry)?;
        Ok(rows.collect::<Result<Vec<_>, _>>()?)
    }

    /// List all entries across every docset, ordered by name.
    pub fn list_all_entries(&self) -> Result<Vec<SearchEntry>, StorageError> {
        let mut stmt = self.conn.prepare(
            "SELECT si.id, si.docset_id, si.name, si.type, si.path, si.usage_count, \
                    d.name, d.version \
             FROM search_index si \
             JOIN docsets d ON d.id = si.docset_id \
             ORDER BY si.name",
        )?;
        let rows = stmt.query_map([], row_to_entry)?;
        Ok(rows.collect::<Result<Vec<_>, _>>()?)
    }

    /// Find the most-recent (or version-pinned) docset matching `name`
    /// (case-insensitive).  Returns `None` if nothing matches.
    pub fn find_docset_by_name(
        &self,
        name: &str,
        version: Option<&str>,
    ) -> Result<Option<Docset>, StorageError> {
        if let Some(v) = version {
            let mut stmt = self.conn.prepare(
                "SELECT id, name, version, path, is_favorite \
                     FROM docsets WHERE lower(name) = lower(?1) AND version = ?2 \
                     LIMIT 1",
            )?;
            let mut rows = stmt.query_map(params![name, v], row_to_docset)?;
            Ok(rows.next().transpose()?)
        } else {
            let mut stmt = self.conn.prepare(
                "SELECT id, name, version, path, is_favorite \
                     FROM docsets WHERE lower(name) = lower(?1) \
                     ORDER BY version DESC LIMIT 1",
            )?;
            let mut rows = stmt.query_map(params![name], row_to_docset)?;
            Ok(rows.next().transpose()?)
        }
    }

    /// Find an entry within `docset_id` whose path matches `path`.
    ///
    /// The anchor fragment (`#section`) is stripped before matching so both
    /// `foo.html` and `foo.html#anchor` resolve to the same entry.
    pub fn find_entry_by_path(
        &self,
        docset_id: i64,
        path: &str,
    ) -> Result<Option<SearchEntry>, StorageError> {
        let base = path.split('#').next().unwrap_or(path);
        let mut stmt = self.conn.prepare(
            "SELECT si.id, si.docset_id, si.name, si.type, si.path, si.usage_count, \
                    d.name, d.version \
             FROM search_index si \
             JOIN docsets d ON d.id = si.docset_id \
             WHERE si.docset_id = ?1 \
               AND (si.path = ?2 OR si.path LIKE ?3 ESCAPE '\\') \
             LIMIT 1",
        )?;
        let like_pattern = format!("{}%", escape_like(base));
        let mut rows = stmt.query_map(params![docset_id, base, like_pattern], row_to_entry)?;
        Ok(rows.next().transpose()?)
    }

    /// Increment the heatmap counter for `index_id`.
    pub fn increment_usage(&self, index_id: i64) -> Result<(), StorageError> {
        self.conn.execute(
            "UPDATE search_index SET usage_count = usage_count + 1 WHERE id = ?1",
            params![index_id],
        )?;
        Ok(())
    }

    // ── Pages ─────────────────────────────────────────────────────────────────

    /// Compress `markdown` with Zstd and upsert it into `pages`.
    pub fn insert_page(&self, index_id: i64, markdown: &str) -> Result<(), StorageError> {
        let compressed =
            encode_all(markdown.as_bytes(), self.compression_level).map_err(StorageError::Zstd)?;
        self.conn.execute(
            "INSERT OR REPLACE INTO pages (index_id, content) VALUES (?1, ?2)",
            params![index_id, compressed],
        )?;
        Ok(())
    }

    /// Fetch and decompress the Markdown content for `index_id`.
    pub fn get_page_content(&self, index_id: i64) -> Result<PageContent, StorageError> {
        let mut stmt = self
            .conn
            .prepare("SELECT content FROM pages WHERE index_id = ?1")?;
        let compressed: Vec<u8> = stmt.query_row(params![index_id], |row| row.get(0))?;
        let decompressed = decode_all(Cursor::new(compressed)).map_err(StorageError::Zstd)?;
        Ok(PageContent {
            markdown: String::from_utf8(decompressed)?,
        })
    }

    /// Compress `markdown` with a Zstd shared `dictionary` and upsert into `pages`.
    ///
    /// Pass `None` for `dict` to fall back to plain Zstd (same as [`Self::insert_page`]).
    pub fn insert_page_dict(
        &self,
        index_id: i64,
        markdown: &str,
        dict: Option<&[u8]>,
    ) -> Result<(), StorageError> {
        let compressed = compress_maybe_dict(markdown.as_bytes(), self.compression_level, dict)?;
        self.conn.execute(
            "INSERT OR REPLACE INTO pages (index_id, content) VALUES (?1, ?2)",
            params![index_id, compressed],
        )?;
        Ok(())
    }

    /// Fetch and decompress the Markdown content for `index_id` using an optional
    /// shared `dictionary` that must match the one used during compression.
    pub fn get_page_content_dict(
        &self,
        index_id: i64,
        dict: Option<&[u8]>,
    ) -> Result<PageContent, StorageError> {
        let mut stmt = self
            .conn
            .prepare("SELECT content FROM pages WHERE index_id = ?1")?;
        let compressed: Vec<u8> = stmt.query_row(params![index_id], |row| row.get(0))?;
        let decompressed = decompress_maybe_dict(&compressed, dict)?;
        Ok(PageContent {
            markdown: String::from_utf8(decompressed)?,
        })
    }

    // ── Entry favorites ───────────────────────────────────────────────────────

    /// Bookmark a documentation entry.  Silently replaces an existing bookmark
    /// for the same `entry_id` (upsert by unique constraint).
    pub fn insert_entry_favorite(
        &self,
        entry_id: i64,
        entry_name: &str,
        entry_type: &str,
        entry_path: &str,
        docset_id: i64,
        docset_name: &str,
    ) -> Result<(), StorageError> {
        self.conn.execute(
            "INSERT OR REPLACE INTO entry_favorites \
             (entry_id, entry_name, entry_type, entry_path, docset_id, docset_name) \
             VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            params![
                entry_id,
                entry_name,
                entry_type,
                entry_path,
                docset_id,
                docset_name
            ],
        )?;
        Ok(())
    }

    /// Remove a bookmarked entry.  No-op if not present.
    pub fn delete_entry_favorite(&self, entry_id: i64) -> Result<(), StorageError> {
        self.conn.execute(
            "DELETE FROM entry_favorites WHERE entry_id = ?1",
            params![entry_id],
        )?;
        Ok(())
    }

    /// List all bookmarked entries ordered by docset name then entry name.
    pub fn list_entry_favorites(&self) -> Result<Vec<FavoriteEntry>, StorageError> {
        let mut stmt = self.conn.prepare(
            "SELECT entry_id, entry_name, entry_type, entry_path, docset_id, docset_name \
             FROM entry_favorites \
             ORDER BY docset_name, entry_name",
        )?;
        let rows = stmt.query_map([], |row| {
            Ok(FavoriteEntry {
                entry_id: row.get(0)?,
                entry_name: row.get(1)?,
                entry_type: row.get(2)?,
                entry_path: row.get(3)?,
                docset_id: row.get(4)?,
                docset_name: row.get(5)?,
            })
        })?;
        Ok(rows.collect::<Result<Vec<_>, _>>()?)
    }
}

// ── Row-mapping helpers ───────────────────────────────────────────────────────

/// Escape SQLite `LIKE` wildcards (`%`, `_`) and the escape char itself (`\`)
/// so that `s` is matched literally.  Pair with `LIKE … ESCAPE '\'`.
fn escape_like(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(c, '\\' | '%' | '_') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

fn row_to_docset(row: &rusqlite::Row<'_>) -> rusqlite::Result<Docset> {
    Ok(Docset {
        id: row.get(0)?,
        name: row.get(1)?,
        version: row.get(2)?,
        path: row.get(3)?,
        is_favorite: row.get::<_, i32>(4)? != 0,
    })
}

fn row_to_entry(row: &rusqlite::Row<'_>) -> rusqlite::Result<SearchEntry> {
    Ok(SearchEntry {
        id: row.get(0)?,
        docset_id: row.get(1)?,
        name: row.get(2)?,
        entry_type: row.get(3)?,
        path: row.get(4)?,
        usage_count: row.get(5)?,
        docset_name: row.get(6)?,
        docset_version: row.get(7)?,
    })
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn open_memory() -> Storage {
        Storage::open(Path::new(":memory:"), 3).expect("in-memory storage must open")
    }

    // ── Schema ────────────────────────────────────────────────────────────────

    #[test]
    fn schema_initialises_without_error() {
        open_memory();
    }

    #[test]
    fn schema_is_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("docterm.sqlite");
        Storage::open(&path, 3).unwrap();
        Storage::open(&path, 3).unwrap();
    }

    // ── Docsets ───────────────────────────────────────────────────────────────

    #[test]
    fn insert_docset_is_idempotent() {
        let s = open_memory();
        let id1 = s.insert_docset("Rust", Some("1.80.0"), None).unwrap();
        let id2 = s.insert_docset("Rust", Some("1.80.0"), None).unwrap();
        assert_eq!(id1, id2);
    }

    #[test]
    fn list_docsets_alphabetical_non_favorites() {
        let s = open_memory();
        s.insert_docset("Tokio", None, None).unwrap();
        s.insert_docset("Rust", None, None).unwrap();
        let list = s.list_docsets().unwrap();
        assert_eq!(list.len(), 2);
        assert_eq!(list[0].name, "Rust");
        assert_eq!(list[1].name, "Tokio");
    }

    #[test]
    fn delete_docset_cascades_to_entries_and_pages() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "spawn", "Function", "tokio/fn.spawn.html")
            .unwrap();
        s.insert_page(eid, "# spawn").unwrap();

        s.delete_docset(did).unwrap();

        assert!(s.get_entry(eid).is_err());
        assert!(s.get_page_content(eid).is_err());
    }

    // ── Search entries ────────────────────────────────────────────────────────

    #[test]
    fn insert_and_get_entry() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();
        let e = s.get_entry(eid).unwrap();
        assert_eq!(e.name, "Vec");
        assert_eq!(e.entry_type, "Struct");
        assert_eq!(e.docset_id, did);
        assert_eq!(e.usage_count, 0);
    }

    #[test]
    fn list_entries_for_docset_sorted() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        s.insert_entry(did, "Vec", "Struct", "vec.html").unwrap();
        s.insert_entry(did, "Arc", "Struct", "arc.html").unwrap();
        let entries = s.list_entries_for_docset(did).unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].name, "Arc");
        assert_eq!(entries[1].name, "Vec");
    }

    #[test]
    fn list_all_entries_across_docsets() {
        let s = open_memory();
        let d1 = s.insert_docset("Rust", None, None).unwrap();
        let d2 = s.insert_docset("Tokio", None, None).unwrap();
        s.insert_entry(d1, "Vec", "Struct", "vec.html").unwrap();
        s.insert_entry(d2, "spawn", "Function", "spawn.html")
            .unwrap();
        let all = s.list_all_entries().unwrap();
        assert_eq!(all.len(), 2);
        // Ordered by name: "Vec" > "spawn" alphabetically, but lowercase
        // ordering depends on SQLite collation — just check both are present.
        let names: Vec<_> = all.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"Vec"));
        assert!(names.contains(&"spawn"));
    }

    #[test]
    fn find_docset_by_name_case_insensitive() {
        let s = open_memory();
        s.insert_docset("Rust", Some("1.80.0"), None).unwrap();
        let found = s.find_docset_by_name("rust", None).unwrap();
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "Rust");
    }

    #[test]
    fn find_docset_by_name_with_version() {
        let s = open_memory();
        s.insert_docset("Rust", Some("1.80.0"), None).unwrap();
        s.insert_docset("Rust", Some("1.94.0"), None).unwrap();

        let found = s.find_docset_by_name("Rust", Some("1.80.0")).unwrap();
        assert!(found.is_some());
        assert_eq!(found.unwrap().version.as_deref(), Some("1.80.0"));
    }

    #[test]
    fn find_docset_by_name_returns_none_when_missing() {
        let s = open_memory();
        let found = s.find_docset_by_name("Python", None).unwrap();
        assert!(found.is_none());
    }

    #[test]
    fn increment_usage_accumulates() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();
        s.increment_usage(eid).unwrap();
        s.increment_usage(eid).unwrap();
        s.increment_usage(eid).unwrap();
        assert_eq!(s.get_entry(eid).unwrap().usage_count, 3);
    }

    // ── Pages ─────────────────────────────────────────────────────────────────

    #[test]
    fn page_round_trip() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();
        let original = "# Vec\n\nA contiguous growable array type.\n\n## Examples\n\n```rust\nlet v = vec![1, 2, 3];\n```";
        s.insert_page(eid, original).unwrap();
        assert_eq!(s.get_page_content(eid).unwrap().markdown, original);
    }

    #[test]
    fn insert_page_upserts() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();
        s.insert_page(eid, "# Vec v1").unwrap();
        s.insert_page(eid, "# Vec v2").unwrap();
        assert_eq!(s.get_page_content(eid).unwrap().markdown, "# Vec v2");
    }

    // ── Dictionary ────────────────────────────────────────────────────────────

    fn make_dict() -> Vec<u8> {
        // Build a small but valid Zstd dictionary from representative samples.
        let samples: Vec<&str> = (0..50)
            .map(|i| {
                // Each sample is a realistic Markdown doc fragment.
                Box::leak(
                    format!(
                        "# Item {i}\n\nDescription of item {i}.\n\n```rust\nlet x = {i};\n```\n"
                    )
                    .into_boxed_str(),
                ) as &str
            })
            .collect();
        crate::postprocess::train_dictionary(&samples, 16 * 1024).unwrap()
    }

    #[test]
    fn set_and_get_docset_dictionary() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();

        assert!(s.get_docset_dictionary(did).unwrap().is_none());

        let dict = make_dict();
        s.set_docset_dictionary(did, &dict).unwrap();

        let retrieved = s.get_docset_dictionary(did).unwrap().unwrap();
        assert_eq!(retrieved, dict);
    }

    #[test]
    fn page_round_trip_with_dictionary() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();

        let dict = make_dict();
        let original = "# Vec\n\nA growable array.\n\n```rust\nlet v = vec![1, 2, 3];\n```";

        s.insert_page_dict(eid, original, Some(&dict)).unwrap();
        let page = s.get_page_content_dict(eid, Some(&dict)).unwrap();
        assert_eq!(page.markdown, original);
    }

    #[test]
    fn insert_page_dict_none_falls_back_to_plain_zstd() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "Arc", "Struct", "std/sync/struct.Arc.html")
            .unwrap();

        let original = "# Arc\n\nAtomically reference-counted pointer.";
        s.insert_page_dict(eid, original, None).unwrap();
        // Decompress without dictionary — must still round-trip.
        let page = s.get_page_content_dict(eid, None).unwrap();
        assert_eq!(page.markdown, original);
    }

    // ── Entry favorites ───────────────────────────────────────────────────────

    fn insert_test_entry(s: &Storage, docset_id: i64, name: &str) -> i64 {
        s.insert_entry(docset_id, name, "Function", &format!("{name}.html"))
            .unwrap()
    }

    #[test]
    fn insert_and_list_favorites() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = insert_test_entry(&s, did, "spawn");
        s.insert_entry_favorite(eid, "spawn", "Function", "spawn.html", did, "Rust")
            .unwrap();
        let favs = s.list_entry_favorites().unwrap();
        assert_eq!(favs.len(), 1);
        assert_eq!(favs[0].entry_id, eid);
        assert_eq!(favs[0].entry_name, "spawn");
        assert_eq!(favs[0].docset_name, "Rust");
    }

    #[test]
    fn delete_entry_favorite() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = insert_test_entry(&s, did, "Arc");
        s.insert_entry_favorite(eid, "Arc", "Struct", "arc.html", did, "Rust")
            .unwrap();
        s.delete_entry_favorite(eid).unwrap();
        assert!(s.list_entry_favorites().unwrap().is_empty());
    }

    #[test]
    fn insert_favorite_is_upsert() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = insert_test_entry(&s, did, "Vec");
        s.insert_entry_favorite(eid, "Vec", "Struct", "vec.html", did, "Rust")
            .unwrap();
        s.insert_entry_favorite(eid, "Vec", "Struct", "vec.html", did, "Rust")
            .unwrap();
        assert_eq!(s.list_entry_favorites().unwrap().len(), 1);
    }

    #[test]
    fn favorite_cascades_on_entry_delete() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = insert_test_entry(&s, did, "Vec");
        s.insert_entry_favorite(eid, "Vec", "Struct", "vec.html", did, "Rust")
            .unwrap();
        s.delete_docset(did).unwrap();
        assert!(s.list_entry_favorites().unwrap().is_empty());
    }

    #[test]
    fn favorites_ordered_by_docset_then_name() {
        let s = open_memory();
        let d1 = s.insert_docset("Tokio", None, None).unwrap();
        let d2 = s.insert_docset("Rust", None, None).unwrap();
        let e1 = insert_test_entry(&s, d1, "spawn");
        let e2 = insert_test_entry(&s, d2, "Vec");
        let e3 = insert_test_entry(&s, d2, "Arc");
        s.insert_entry_favorite(e1, "spawn", "Function", "spawn.html", d1, "Tokio")
            .unwrap();
        s.insert_entry_favorite(e2, "Vec", "Struct", "vec.html", d2, "Rust")
            .unwrap();
        s.insert_entry_favorite(e3, "Arc", "Struct", "arc.html", d2, "Rust")
            .unwrap();
        let favs = s.list_entry_favorites().unwrap();
        assert_eq!(favs[0].entry_name, "Arc"); // Rust/Arc
        assert_eq!(favs[1].entry_name, "Vec"); // Rust/Vec
        assert_eq!(favs[2].entry_name, "spawn"); // Tokio/spawn
    }

    // ── find_entry_by_path ────────────────────────────────────────────────────

    #[test]
    fn find_entry_by_path_exact_match() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();
        let found = s
            .find_entry_by_path(did, "std/vec/struct.Vec.html")
            .unwrap();
        assert_eq!(found.unwrap().id, eid);
    }

    #[test]
    fn find_entry_by_path_ignores_anchor_in_query() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(did, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();
        // Query includes a fragment; stored path does not.  Should still match.
        let found = s
            .find_entry_by_path(did, "std/vec/struct.Vec.html#method.new")
            .unwrap();
        assert_eq!(found.unwrap().id, eid);
    }

    #[test]
    fn find_entry_by_path_matches_stored_anchor_via_prefix() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        let eid = s
            .insert_entry(
                did,
                "Vec::new",
                "Method",
                "std/vec/struct.Vec.html#method.new",
            )
            .unwrap();
        // Query has no anchor; stored row has one.  Prefix LIKE should match.
        let found = s
            .find_entry_by_path(did, "std/vec/struct.Vec.html")
            .unwrap();
        assert_eq!(found.unwrap().id, eid);
    }

    #[test]
    fn find_entry_by_path_underscore_is_literal_not_wildcard() {
        let s = open_memory();
        let did = s.insert_docset("Python", None, None).unwrap();
        // Insert a path whose single-char neighbour would collide with '_'-as-wildcard.
        let target = s
            .insert_entry(did, "hash_map", "Function", "lib/hash_map.html")
            .unwrap();
        let decoy = s
            .insert_entry(did, "hashXmap", "Function", "lib/hashXmap.html")
            .unwrap();
        assert_ne!(target, decoy);

        // A literal `_` in the query must not match the decoy's `X`.
        let found = s.find_entry_by_path(did, "lib/hashXmap.html").unwrap();
        assert_eq!(found.unwrap().id, decoy);

        let found = s.find_entry_by_path(did, "lib/hash_map.html").unwrap();
        assert_eq!(found.unwrap().id, target);
    }

    #[test]
    fn find_entry_by_path_percent_is_literal_not_wildcard() {
        let s = open_memory();
        let did = s.insert_docset("Weird", None, None).unwrap();
        let literal = s.insert_entry(did, "pct", "Function", "a%b.html").unwrap();
        let decoy = s
            .insert_entry(did, "long", "Function", "aXXXb.html")
            .unwrap();

        // Query for the literal `%` path must not match the decoy.
        let found = s.find_entry_by_path(did, "a%b.html").unwrap();
        assert_eq!(found.unwrap().id, literal);

        // And the decoy is still findable on its own path.
        let found = s.find_entry_by_path(did, "aXXXb.html").unwrap();
        assert_eq!(found.unwrap().id, decoy);
    }

    #[test]
    fn find_entry_by_path_backslash_is_literal() {
        let s = open_memory();
        let did = s.insert_docset("Weird", None, None).unwrap();
        // Escape char in the query must not confuse the LIKE parser.
        let eid = s.insert_entry(did, "bs", "Function", "a\\b.html").unwrap();
        let found = s.find_entry_by_path(did, "a\\b.html").unwrap();
        assert_eq!(found.unwrap().id, eid);
    }

    #[test]
    fn find_entry_by_path_returns_none_when_missing() {
        let s = open_memory();
        let did = s.insert_docset("Rust", None, None).unwrap();
        assert!(s.find_entry_by_path(did, "nope.html").unwrap().is_none());
    }

    // ── escape_like ───────────────────────────────────────────────────────────

    #[test]
    fn escape_like_passes_plain_text_unchanged() {
        assert_eq!(escape_like("foo/bar.html"), "foo/bar.html");
    }

    #[test]
    fn escape_like_escapes_wildcards_and_backslash() {
        assert_eq!(escape_like("a%b_c\\d"), r"a\%b\_c\\d");
    }

    // ── Error display ─────────────────────────────────────────────────────────

    #[test]
    fn storage_error_display_utf8() {
        let e = StorageError::Utf8(String::from_utf8(vec![0xFF]).unwrap_err());
        assert!(!e.to_string().is_empty());
    }

    #[test]
    fn storage_error_display_zstd() {
        let io_err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated");
        let e = StorageError::Zstd(io_err);
        assert!(e.to_string().contains("compression"));
    }
}