koan_core/db/connection.rs
1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::path::Path;
4use std::rc::Rc;
5
6use rusqlite::Connection;
7use rusqlite::functions::FunctionFlags;
8use thiserror::Error;
9
10use super::schema;
11use crate::config;
12
13#[derive(Debug, Error)]
14pub enum DbError {
15 #[error("sqlite error: {0}")]
16 Sqlite(#[from] rusqlite::Error),
17 #[error("io error: {0}")]
18 Io(#[from] std::io::Error),
19 /// A bulk delete looked like a mount failure rather than an intentional
20 /// deletion, so it was refused. The library is untouched.
21 #[error("refused unsafe bulk delete: {0}")]
22 UnsafeBulkDelete(String),
23}
24
25/// Wrapper around a SQLite connection with koan's schema applied.
26pub struct Database {
27 pub conn: Connection,
28}
29
30impl Database {
31 /// Open (or create) a database at the given path, applying the schema and
32 /// pending migrations.
33 ///
34 /// This is the once-per-process path: it creates the parent directory,
35 /// tightens file permissions, checkpoints the WAL and runs the ~30-statement
36 /// DDL batch. Anything opening a connection per request wants
37 /// [`Database::open_existing`] instead.
38 pub fn open(path: &Path) -> Result<Self, DbError> {
39 if let Some(parent) = path.parent() {
40 std::fs::create_dir_all(parent)?;
41 }
42
43 let conn = Connection::open(path)?;
44
45 #[cfg(unix)]
46 {
47 use std::os::unix::fs::PermissionsExt;
48 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
49 }
50
51 configure(&conn)?;
52
53 // Attempt a passive WAL checkpoint on open. This is non-blocking — it
54 // moves WAL pages back to the main DB file only if no readers/writers
55 // are active, preventing unbounded WAL growth across sessions.
56 let _ = conn.execute_batch("PRAGMA wal_checkpoint(PASSIVE)");
57
58 schema::create_tables(&conn)?;
59
60 // The planner picks between indexes by guessing how many rows each one
61 // will yield, and with no statistics it guesses the same number for all
62 // of them. That is how a partial index on the column a query filters by
63 // loses to an index that merely happens to supply the ORDER BY. Cheap
64 // after the first run, and a no-op when nothing has moved.
65 let _ = conn.execute_batch("PRAGMA optimize");
66
67 Ok(Self { conn })
68 }
69
70 /// Open an additional connection to a database whose schema is already
71 /// applied — pragmas only, no DDL, no checkpoint, no permission syscall.
72 ///
73 /// Callers are responsible for having run [`Database::open`] at least once
74 /// against the same path first.
75 pub fn open_existing(path: &Path) -> Result<Self, DbError> {
76 let conn = Connection::open(path)?;
77 configure(&conn)?;
78 Ok(Self { conn })
79 }
80
81 /// Open the default database at the standard data directory.
82 pub fn open_default() -> Result<Self, DbError> {
83 Self::open(&config::db_path())
84 }
85
86 /// Refresh the planner's statistics.
87 ///
88 /// Worth calling wherever the library changes size in bulk — a scan, a
89 /// remote sync — because the statistics gathered when the process started
90 /// describe a library that no longer exists, and the planner will keep
91 /// choosing for it. A no-op when nothing has moved far enough to matter.
92 pub fn optimize(&self) {
93 if let Err(e) = self.conn.execute_batch("PRAGMA optimize") {
94 log::debug!("PRAGMA optimize failed: {e}");
95 }
96 }
97}
98
99/// Connection-scoped pragmas. Every connection needs these; none of them touch
100/// the file on disk, so they are cheap enough to repeat per connection.
101fn configure(conn: &Connection) -> Result<(), DbError> {
102 // WAL mode for concurrent reads + single writer.
103 conn.pragma_update(None, "journal_mode", "wal")?;
104 conn.pragma_update(None, "foreign_keys", "on")?;
105 // Long enough to outlast a scan chunk: a writer that gives up mid-scan
106 // silently loses favourites, queue state and play counts.
107 conn.pragma_update(None, "busy_timeout", 30000)?;
108 // Slightly faster at the cost of durability on power loss (acceptable for a media DB).
109 conn.pragma_update(None, "synchronous", "normal")?;
110 // Map the whole library. A library this size fits well inside this, so
111 // reads become dereferences into a mapped region rather than syscalls —
112 // which is the useful sense in which a database can be "in memory". The
113 // page cache was already holding it; this stops copying it out per read.
114 conn.pragma_update(None, "mmap_size", 268_435_456i64)?;
115 // 32 MiB of pages, per connection. Negative means KiB rather than pages,
116 // so the figure does not change meaning with the page size.
117 conn.pragma_update(None, "cache_size", -32_000i64)?;
118 // Sorts and intermediate tables in memory. FTS and the ORDER BYs behind
119 // every library listing make temporary tables constantly.
120 conn.pragma_update(None, "temp_store", "memory")?;
121 // How many rows `PRAGMA optimize` samples per index. Bounded, so gathering
122 // statistics stays a fraction of a second on a library of any size; the
123 // planner needs the shape of the distribution, not an exact count.
124 conn.pragma_update(None, "analysis_limit", 400i64)?;
125 // Here rather than with the schema: `open_existing` skips the DDL, and a
126 // connection without this collation fails every ORDER BY that uses it.
127 register_library_collation(conn)?;
128 register_shuffle_function(conn)?;
129 Ok(())
130}
131
132/// `koan_shuffle(id, seed)` — a stable pseudo-random ordering key.
133///
134/// A shuffled listing that is read a page at a time cannot shuffle in the
135/// client: page two would be drawn from a different shuffle than page one, and
136/// records would repeat or vanish as you scrolled. Ordering by a hash of the
137/// row id and a seed gives one order that every page of the same seed agrees
138/// on, and a new seed gives a different one.
139///
140/// Registered next to the collation, and for the same reason: a connection
141/// without it fails the query outright rather than sorting some other way.
142pub(crate) fn register_shuffle_function(conn: &Connection) -> rusqlite::Result<()> {
143 conn.create_scalar_function(
144 "koan_shuffle",
145 2,
146 FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
147 |ctx| {
148 let id = ctx.get::<i64>(0)? as u64;
149 let seed = ctx.get::<i64>(1)? as u64;
150 Ok(splitmix64(id ^ splitmix64(seed)) as i64)
151 },
152 )
153}
154
155/// SplitMix64. Cheap, and it scatters consecutive ids — which matters, because
156/// a library's ids are consecutive in the order it was scanned.
157fn splitmix64(x: u64) -> u64 {
158 let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
159 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
160 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
161 z ^ (z >> 31)
162}
163
164/// A collation for names the way a person reads them.
165///
166/// SQLite's default is a byte comparison, which sorts every capital before
167/// every lowercase and every accented letter after the whole ASCII range — so
168/// an artist list ran `Zebra`, then `aphex twin`, and put `Âme` at the end
169/// where nobody would look for it.
170///
171/// Case is folded, accents are folded onto their base letter (`Âme` sorts with
172/// `Ame`), and runs of digits compare by value so `Track 2` precedes
173/// `Track 10`. Ties fall back to the raw bytes, so two names that differ only
174/// in case or accent still have a stable order rather than being treated as
175/// equal.
176/// Registered by `create_tables`, so every connection has it — a query using
177/// `COLLATE LIBRARY` on a connection that skipped this fails outright rather
178/// than quietly sorting some other way.
179pub(crate) fn register_library_collation(conn: &Connection) -> rusqlite::Result<()> {
180 conn.create_collation("LIBRARY", |a, b| {
181 cached_sort_key(a).cmp(&cached_sort_key(b)).then(a.cmp(b))
182 })
183}
184
185thread_local! {
186 /// Sort keys, kept for the life of the thread.
187 ///
188 /// A collation sees the same name once per level of the sort — around two
189 /// dozen times in a five-thousand-row list — and building a key means an
190 /// NFD pass and a `Vec` of freshly allocated `String`s. Cached, each name is
191 /// folded once per thread instead of once per comparison.
192 static SORT_KEYS: RefCell<HashMap<Box<str>, Rc<[Chunk]>>> = RefCell::new(HashMap::new());
193}
194
195fn cached_sort_key(s: &str) -> Rc<[Chunk]> {
196 SORT_KEYS.with_borrow_mut(|cache| {
197 if let Some(key) = cache.get(s) {
198 return Rc::clone(key);
199 }
200 // A library's worth of names is tens of thousands of entries. Anything
201 // beyond that is a query sorting something other than names, and it
202 // should not grow this without bound.
203 if cache.len() >= 50_000 {
204 cache.clear();
205 }
206 let key: Rc<[Chunk]> = sort_key(s).into();
207 cache.insert(s.into(), Rc::clone(&key));
208 key
209 })
210}
211
212/// One comparable chunk of a name: either a run of digits, as a number, or a
213/// run of folded characters.
214#[derive(PartialEq, Eq, PartialOrd, Ord)]
215enum Chunk {
216 Number(u128),
217 Text(String),
218}
219
220fn sort_key(s: &str) -> Vec<Chunk> {
221 use unicode_normalization::UnicodeNormalization;
222
223 // NFD splits an accented letter into its base plus a combining mark; dropping
224 // the marks leaves the base letter to sort on.
225 let folded: String = s
226 .nfd()
227 .filter(|c| !matches!(*c as u32, 0x0300..=0x036F))
228 .flat_map(char::to_lowercase)
229 .collect();
230
231 let mut chunks = Vec::new();
232 let mut rest = folded.as_str();
233 while !rest.is_empty() {
234 let digits = rest
235 .find(|c: char| !c.is_ascii_digit())
236 .unwrap_or(rest.len());
237 if digits > 0 && rest.starts_with(|c: char| c.is_ascii_digit()) {
238 // Absurdly long digit runs are not numbers anyone sorts by.
239 match rest[..digits].parse::<u128>() {
240 Ok(n) => chunks.push(Chunk::Number(n)),
241 Err(_) => chunks.push(Chunk::Text(rest[..digits].to_string())),
242 }
243 rest = &rest[digits..];
244 continue;
245 }
246 let text = rest
247 .find(|c: char| c.is_ascii_digit())
248 .unwrap_or(rest.len())
249 .max(1);
250 chunks.push(Chunk::Text(rest[..text].to_string()));
251 rest = &rest[text..];
252 }
253 chunks
254}
255
256#[cfg(test)]
257mod collation_tests {
258 use super::*;
259
260 fn sorted(names: &[&str]) -> Vec<String> {
261 let conn = Connection::open_in_memory().unwrap();
262 crate::db::schema::create_tables(&conn).unwrap();
263 conn.execute_batch("CREATE TABLE t (name TEXT)").unwrap();
264 for n in names {
265 conn.execute("INSERT INTO t VALUES (?1)", [n]).unwrap();
266 }
267 let mut stmt = conn
268 .prepare("SELECT name FROM t ORDER BY name COLLATE LIBRARY")
269 .unwrap();
270 let rows = stmt.query_map([], |r| r.get::<_, String>(0)).unwrap();
271 rows.map(Result::unwrap).collect()
272 }
273
274 #[test]
275 fn lowercase_does_not_sort_after_everything() {
276 assert_eq!(
277 sorted(&["Zebra", "aphex twin", "Boards of Canada"]),
278 ["aphex twin", "Boards of Canada", "Zebra"]
279 );
280 }
281
282 #[test]
283 fn accents_sort_with_their_base_letter() {
284 // Byte order puts every non-ASCII name after `z`, which is where nobody
285 // looks for Âme.
286 assert_eq!(
287 sorted(&["Zomby", "Âme", "Alva Noto"]),
288 ["Alva Noto", "Âme", "Zomby"]
289 );
290 }
291
292 #[test]
293 fn digit_runs_compare_as_numbers() {
294 assert_eq!(
295 sorted(&["Track 10", "Track 2", "Track 1"]),
296 ["Track 1", "Track 2", "Track 10"]
297 );
298 }
299
300 #[test]
301 fn names_differing_only_in_case_keep_a_stable_order() {
302 // Folding must not make them equal, or the order flips between runs.
303 assert_eq!(
304 sorted(&["kraftwerk", "Kraftwerk"]),
305 ["Kraftwerk", "kraftwerk"]
306 );
307 }
308}