koan_core/db/connection.rs
1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::path::Path;
4use std::rc::Rc;
5
6use rusqlite::functions::FunctionFlags;
7use rusqlite::{Connection, OpenFlags};
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 brings the schema up
36 /// to date. 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, but an empty table never has statistics, so it
65 // asks for the write lock on every open: skipped while a writer holds
66 // it, and `optimize` runs again after every scan and sync.
67 let _ = without_waiting(&conn, |conn| conn.execute_batch("PRAGMA optimize"));
68
69 Ok(Self { conn })
70 }
71
72 /// Apply this build's schema and migrations to a snapshot of the database
73 /// at `path`, to learn whether it would open. The original is only read,
74 /// so this is safe beside a server that has it open: it is how a deploy
75 /// finds a migration that fails on the real library before replacing the
76 /// running version.
77 pub fn check_upgrade(path: &Path) -> Result<(), DbError> {
78 let snapshot = std::env::temp_dir().join(format!("koan-check-{}.db", std::process::id()));
79 let _ = std::fs::remove_file(&snapshot);
80 let result = (|| {
81 let source = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
82 source.execute("VACUUM INTO ?1", [snapshot.to_string_lossy()])?;
83 drop(source);
84 Self::open(&snapshot).map(drop)
85 })();
86 for suffix in ["", "-wal", "-shm"] {
87 let mut file = snapshot.clone().into_os_string();
88 file.push(suffix);
89 let _ = std::fs::remove_file(file);
90 }
91 result
92 }
93
94 /// Open an additional connection to a database whose schema is already
95 /// applied — pragmas only, no DDL, no checkpoint, no permission syscall.
96 ///
97 /// Callers are responsible for having run [`Database::open`] at least once
98 /// against the same path first.
99 pub fn open_existing(path: &Path) -> Result<Self, DbError> {
100 let conn = Connection::open(path)?;
101 configure(&conn)?;
102 Ok(Self { conn })
103 }
104
105 /// Open the default database at the standard data directory.
106 pub fn open_default() -> Result<Self, DbError> {
107 Self::open(&config::db_path())
108 }
109
110 /// Refresh the planner's statistics.
111 ///
112 /// Worth calling wherever the library changes size in bulk — a scan, a
113 /// remote sync — because the statistics gathered when the process started
114 /// describe a library that no longer exists, and the planner will keep
115 /// choosing for it. A no-op when nothing has moved far enough to matter.
116 pub fn optimize(&self) {
117 if let Err(e) = self.conn.execute_batch("PRAGMA optimize") {
118 log::debug!("PRAGMA optimize failed: {e}");
119 }
120 }
121}
122
123/// Long enough to outlast a scan chunk: a writer that gives up mid-scan
124/// silently loses favourites, queue state and play counts.
125const BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
126
127/// Run `write` without waiting for the write lock, which fails it with
128/// `SQLITE_BUSY` while a scan or sync holds the lock.
129///
130/// For bookkeeping a request should not wait on: a key's last use, a share's
131/// visit count. Skipping one costs a stale number; waiting costs the request.
132pub fn without_waiting<T>(
133 conn: &Connection,
134 write: impl FnOnce(&Connection) -> rusqlite::Result<T>,
135) -> rusqlite::Result<T> {
136 conn.busy_timeout(std::time::Duration::ZERO)?;
137 let result = write(conn);
138 conn.busy_timeout(BUSY_TIMEOUT)?;
139 result
140}
141
142/// Connection-scoped pragmas. Every connection needs these; none of them touch
143/// the file on disk, so they are cheap enough to repeat per connection.
144fn configure(conn: &Connection) -> Result<(), DbError> {
145 // WAL mode for concurrent reads + single writer.
146 conn.pragma_update(None, "journal_mode", "wal")?;
147 conn.pragma_update(None, "foreign_keys", "on")?;
148 conn.busy_timeout(BUSY_TIMEOUT)?;
149 // Slightly faster at the cost of durability on power loss (acceptable for a media DB).
150 conn.pragma_update(None, "synchronous", "normal")?;
151 // Map the whole library. A library this size fits well inside this, so
152 // reads become dereferences into a mapped region rather than syscalls —
153 // which is the useful sense in which a database can be "in memory". The
154 // page cache was already holding it; this stops copying it out per read.
155 conn.pragma_update(None, "mmap_size", 268_435_456i64)?;
156 // 32 MiB of pages, per connection. Negative means KiB rather than pages,
157 // so the figure does not change meaning with the page size.
158 conn.pragma_update(None, "cache_size", -32_000i64)?;
159 // Sorts and intermediate tables in memory. FTS and the ORDER BYs behind
160 // every library listing make temporary tables constantly.
161 conn.pragma_update(None, "temp_store", "memory")?;
162 // How many rows `PRAGMA optimize` samples per index. Bounded, so gathering
163 // statistics stays a fraction of a second on a library of any size; the
164 // planner needs the shape of the distribution, not an exact count.
165 conn.pragma_update(None, "analysis_limit", 400i64)?;
166 // Past rusqlite's default of 16, which the per-request reads alone exceed.
167 conn.set_prepared_statement_cache_capacity(128);
168 // The WAL keeps its high-water mark on disk after a checkpoint. A full sync
169 // grows it; this lets it shrink back.
170 conn.pragma_update(None, "journal_size_limit", 67_108_864i64)?;
171 // Here rather than with the schema: `open_existing` skips the DDL, and a
172 // connection without this collation fails every ORDER BY that uses it.
173 register_library_collation(conn)?;
174 register_shuffle_function(conn)?;
175 Ok(())
176}
177
178/// `koan_shuffle(id, seed)` — a stable pseudo-random ordering key.
179///
180/// A shuffled listing that is read a page at a time cannot shuffle in the
181/// client: page two would be drawn from a different shuffle than page one, and
182/// records would repeat or vanish as you scrolled. Ordering by a hash of the
183/// row id and a seed gives one order that every page of the same seed agrees
184/// on, and a new seed gives a different one.
185///
186/// Registered next to the collation, and for the same reason: a connection
187/// without it fails the query outright rather than sorting some other way.
188pub(crate) fn register_shuffle_function(conn: &Connection) -> rusqlite::Result<()> {
189 conn.create_scalar_function(
190 "koan_shuffle",
191 2,
192 FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
193 |ctx| {
194 let id = ctx.get::<i64>(0)? as u64;
195 let seed = ctx.get::<i64>(1)? as u64;
196 Ok(splitmix64(id ^ splitmix64(seed)) as i64)
197 },
198 )
199}
200
201/// SplitMix64. Cheap, and it scatters consecutive ids — which matters, because
202/// a library's ids are consecutive in the order it was scanned.
203fn splitmix64(x: u64) -> u64 {
204 let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
205 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
206 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
207 z ^ (z >> 31)
208}
209
210/// A collation for names the way a person reads them.
211///
212/// SQLite's default is a byte comparison, which sorts every capital before
213/// every lowercase and every accented letter after the whole ASCII range — so
214/// an artist list ran `Zebra`, then `aphex twin`, and put `Âme` at the end
215/// where nobody would look for it.
216///
217/// Case is folded, accents are folded onto their base letter (`Âme` sorts with
218/// `Ame`), and runs of digits compare by value so `Track 2` precedes
219/// `Track 10`. Ties fall back to the raw bytes, so two names that differ only
220/// in case or accent still have a stable order rather than being treated as
221/// equal.
222///
223/// Registered by `configure`, so every connection has it — a query using
224/// `COLLATE LIBRARY` on a connection that skipped this fails outright rather
225/// than quietly sorting some other way.
226pub(crate) fn register_library_collation(conn: &Connection) -> rusqlite::Result<()> {
227 conn.create_collation("LIBRARY", |a, b| {
228 cached_sort_key(a).cmp(&cached_sort_key(b)).then(a.cmp(b))
229 })
230}
231
232thread_local! {
233 /// Sort keys, kept for the life of the thread.
234 ///
235 /// A collation sees the same name once per level of the sort — around two
236 /// dozen times in a five-thousand-row list — and building a key means an
237 /// NFD pass and a `Vec` of freshly allocated `String`s. Cached, each name is
238 /// folded once per thread instead of once per comparison.
239 static SORT_KEYS: RefCell<HashMap<Box<str>, Rc<[Chunk]>>> = RefCell::new(HashMap::new());
240}
241
242fn cached_sort_key(s: &str) -> Rc<[Chunk]> {
243 SORT_KEYS.with_borrow_mut(|cache| {
244 if let Some(key) = cache.get(s) {
245 return Rc::clone(key);
246 }
247 // A library's worth of names is tens of thousands of entries. Anything
248 // beyond that is a query sorting something other than names, and it
249 // should not grow this without bound.
250 if cache.len() >= 50_000 {
251 cache.clear();
252 }
253 let key: Rc<[Chunk]> = sort_key(s).into();
254 cache.insert(s.into(), Rc::clone(&key));
255 key
256 })
257}
258
259/// One comparable chunk of a name: either a run of digits, as a number, or a
260/// run of folded characters.
261#[derive(PartialEq, Eq, PartialOrd, Ord)]
262enum Chunk {
263 Number(u128),
264 Text(String),
265}
266
267fn sort_key(s: &str) -> Vec<Chunk> {
268 use unicode_normalization::UnicodeNormalization;
269
270 // NFD splits an accented letter into its base plus a combining mark; dropping
271 // the marks leaves the base letter to sort on.
272 let folded: String = s
273 .nfd()
274 .filter(|c| !matches!(*c as u32, 0x0300..=0x036F))
275 .flat_map(char::to_lowercase)
276 .collect();
277
278 let mut chunks = Vec::new();
279 let mut rest = folded.as_str();
280 while !rest.is_empty() {
281 let digits = rest
282 .find(|c: char| !c.is_ascii_digit())
283 .unwrap_or(rest.len());
284 if digits > 0 && rest.starts_with(|c: char| c.is_ascii_digit()) {
285 // Absurdly long digit runs are not numbers anyone sorts by.
286 match rest[..digits].parse::<u128>() {
287 Ok(n) => chunks.push(Chunk::Number(n)),
288 Err(_) => chunks.push(Chunk::Text(rest[..digits].to_string())),
289 }
290 rest = &rest[digits..];
291 continue;
292 }
293 let text = rest
294 .find(|c: char| c.is_ascii_digit())
295 .unwrap_or(rest.len())
296 .max(1);
297 chunks.push(Chunk::Text(rest[..text].to_string()));
298 rest = &rest[text..];
299 }
300 chunks
301}
302
303#[cfg(test)]
304mod collation_tests {
305 use super::*;
306
307 fn sorted(names: &[&str]) -> Vec<String> {
308 let conn = Connection::open_in_memory().unwrap();
309 crate::db::schema::create_tables(&conn).unwrap();
310 conn.execute_batch("CREATE TABLE t (name TEXT)").unwrap();
311 for n in names {
312 conn.execute("INSERT INTO t VALUES (?1)", [n]).unwrap();
313 }
314 let mut stmt = conn
315 .prepare("SELECT name FROM t ORDER BY name COLLATE LIBRARY")
316 .unwrap();
317 let rows = stmt.query_map([], |r| r.get::<_, String>(0)).unwrap();
318 rows.map(Result::unwrap).collect()
319 }
320
321 #[test]
322 fn lowercase_does_not_sort_after_everything() {
323 assert_eq!(
324 sorted(&["Zebra", "aphex twin", "Boards of Canada"]),
325 ["aphex twin", "Boards of Canada", "Zebra"]
326 );
327 }
328
329 #[test]
330 fn accents_sort_with_their_base_letter() {
331 // Byte order puts every non-ASCII name after `z`, which is where nobody
332 // looks for Âme.
333 assert_eq!(
334 sorted(&["Zomby", "Âme", "Alva Noto"]),
335 ["Alva Noto", "Âme", "Zomby"]
336 );
337 }
338
339 #[test]
340 fn digit_runs_compare_as_numbers() {
341 assert_eq!(
342 sorted(&["Track 10", "Track 2", "Track 1"]),
343 ["Track 1", "Track 2", "Track 10"]
344 );
345 }
346
347 #[test]
348 fn names_differing_only_in_case_keep_a_stable_order() {
349 // Folding must not make them equal, or the order flips between runs.
350 assert_eq!(
351 sorted(&["kraftwerk", "Kraftwerk"]),
352 ["Kraftwerk", "kraftwerk"]
353 );
354 }
355}
356
357#[cfg(test)]
358mod check_upgrade_tests {
359 use super::*;
360
361 #[test]
362 fn leaves_the_original_untouched() {
363 let dir = tempfile::tempdir().unwrap();
364 let path = dir.path().join("koan.db");
365 let conn = Connection::open(&path).unwrap();
366 conn.execute_batch("CREATE TABLE marker (x); INSERT INTO marker VALUES (1);")
367 .unwrap();
368 drop(conn);
369
370 Database::check_upgrade(&path).unwrap();
371
372 let conn = Connection::open(&path).unwrap();
373 let tables: i64 = conn
374 .query_row(
375 "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table'",
376 [],
377 |r| r.get(0),
378 )
379 .unwrap();
380 assert_eq!(
381 tables, 1,
382 "the schema went into the snapshot, not the original"
383 );
384 }
385
386 #[test]
387 fn a_missing_database_fails() {
388 let dir = tempfile::tempdir().unwrap();
389 assert!(Database::check_upgrade(&dir.path().join("absent.db")).is_err());
390 }
391}