rbox_db/connection.rs
1// Copyright (C) 2026 Dylan Jones
2// SPDX-License-Identifier: GPL-3.0-only
3
4//! Connection types and configuration shared by the Rekordbox database formats.
5//!
6//! [`ConnectionOptions`] defaults to opening an existing database read-write and
7//! preserving its journal mode. [`ConnectionOptions::for_export`] selects creation
8//! and DELETE journaling for a new device export. Database-specific callers supply
9//! the encryption key. These options describe configuration; constructing them
10//! does not open a connection or execute any PRAGMAs.
11
12use diesel::r2d2::{self, ConnectionManager, CustomizeConnection, Pool};
13use diesel::result::{DatabaseErrorKind, Error as DieselError};
14use diesel::{Connection, QueryResult, RunQueryDsl, SqliteConnection};
15use std::fmt;
16use std::path::Path;
17use std::time::Duration;
18
19use crate::error::{Error, Result};
20
21/// SQLite connection used by the database model APIs.
22pub type DbConn = SqliteConnection;
23
24/// Pool of SQLite connections sharing the same database and configuration.
25pub type DbPool = Pool<ConnectionManager<DbConn>>;
26
27/// Whether opening a database permits writes or creation.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
29pub enum OpenMode {
30 /// Open an existing database for reading only.
31 ReadOnly,
32 /// Open an existing database for reading and writing; do not create it.
33 #[default]
34 ReadWrite,
35 /// Open a database for reading and writing, creating it if missing.
36 ReadWriteCreate,
37}
38
39/// Journal policy applied when opening or creating a database.
40///
41/// Initialize persistent mode changes before building a pool to avoid competing
42/// changes. Connection-local rollback modes still need setting on each handle.
43/// Read-only connections must use [`JournalMode::Preserve`].
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum JournalMode {
46 /// Leave the existing journal mode unchanged.
47 #[default]
48 Preserve,
49 /// Delete the rollback journal after committing; suitable for new exports.
50 Delete,
51 /// Truncate the rollback journal after committing.
52 Truncate,
53 /// Retain the rollback journal and invalidate its header after committing.
54 Persist,
55 /// Use write-ahead logging, which can keep committed data in a sidecar file.
56 Wal,
57}
58
59/// Synchronization policy for writable connections.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
61pub enum Synchronous {
62 /// Reduce synchronization overhead. In WAL mode, power loss can undo commits.
63 Normal,
64 /// Synchronize each commit in WAL mode.
65 Full,
66 /// Add directory synchronization for DELETE journals; equivalent to FULL in WAL.
67 #[default]
68 Extra,
69}
70
71/// Configuration to apply consistently to direct and pooled connections.
72///
73/// Defaults preserve the journal mode, enable foreign keys, wait up to five seconds
74/// for locks, and disable dirty reads. Writable connections use EXTRA synchronization
75/// and, on macOS, full filesystem synchronization. Cache sizes, page sizes, temporary
76/// storage, and cipher compatibility settings are left to the backend or format.
77///
78/// The key must be applied before reading the database, and the busy timeout before
79/// operations that may need locks. A schema read is required to validate decryption.
80/// Connection-local settings must be applied to every new pooled connection.
81///
82/// ```
83/// use rbox_db::connection::{ConnectionOptions, OpenMode};
84///
85/// let options = ConnectionOptions {
86/// open_mode: OpenMode::ReadWrite,
87/// key: Some("database-specific passphrase".into()),
88/// ..ConnectionOptions::default()
89/// };
90/// ```
91#[derive(Clone)]
92pub struct ConnectionOptions {
93 /// Access mode. Defaults to read-write; creation requires an explicit opt-in.
94 ///
95 /// The opener must select the matching SQLite URI mode (`ro`, `rw`, or `rwc`).
96 /// [`setup_connection`] can restrict queries but cannot change file-open flags.
97 pub open_mode: OpenMode,
98 /// SQLCipher passphrase supplied by the database format; `None` means no key.
99 ///
100 /// Redacted from debug output. This value is a passphrase, not a raw-key SQL literal.
101 pub key: Option<String>,
102 /// Time to wait for database locks. Defaults to five seconds.
103 pub busy_timeout: Duration,
104 /// Enforce foreign-key constraints on this connection. Defaults to `true`.
105 pub foreign_keys: bool,
106 /// Journal policy. Defaults to preserving the current mode.
107 pub journal_mode: JournalMode,
108 /// Synchronization policy for writes. Defaults to [`Synchronous::Extra`].
109 pub synchronous: Synchronous,
110 /// Request full filesystem synchronization where supported (macOS).
111 ///
112 /// Defaults to `true` on macOS and `false` elsewhere. When enabled, it also
113 /// covers checkpoints, so no separate checkpoint synchronization option is needed.
114 pub fullfsync: bool,
115 /// Permit dirty reads where SQLite supports them. Defaults to `false`.
116 pub read_uncommitted: bool,
117}
118
119impl Default for ConnectionOptions {
120 fn default() -> Self {
121 Self {
122 open_mode: Default::default(),
123 key: None,
124 busy_timeout: Duration::from_secs(5),
125 foreign_keys: true,
126 journal_mode: Default::default(),
127 synchronous: Default::default(),
128 fullfsync: cfg!(target_os = "macos"),
129 read_uncommitted: false,
130 }
131 }
132}
133
134impl ConnectionOptions {
135 /// Create a new instance with default settings.
136 pub fn new() -> Self {
137 Self::default()
138 }
139
140 /// Options for creating a device export with DELETE journaling and durable writes.
141 ///
142 /// Supply the export format's key before connecting. To open an existing export
143 /// while preserving its journal mode, use [`Self::default`] and select the desired
144 /// [`OpenMode`] instead.
145 pub fn for_export() -> Self {
146 Self {
147 open_mode: OpenMode::ReadWriteCreate,
148 journal_mode: JournalMode::Delete,
149 ..Self::default()
150 }
151 }
152
153 /// Set the access mode. Defaults to read-write.
154 ///
155 /// Creation requires an explicit opt-in.
156 /// Read-only connections must preserve the journal mode.
157 pub fn open_mode(&mut self, open_mode: OpenMode) -> &mut Self {
158 self.open_mode = open_mode;
159 self
160 }
161
162 /// Set the SQLCipher passphrase. Defaults to `None`.
163 pub fn key(&mut self, key: String) -> &mut Self {
164 self.key = Some(key);
165 self
166 }
167
168 /// Set the busy timeout. Defaults to five seconds.
169 pub fn busy_timeout(&mut self, busy_timeout: Duration) -> &mut Self {
170 self.busy_timeout = busy_timeout;
171 self
172 }
173
174 /// Enable or disable foreign-key enforcement. Defaults to `true`.
175 pub fn foreign_keys(&mut self, foreign_keys: bool) -> &mut Self {
176 self.foreign_keys = foreign_keys;
177 self
178 }
179
180 /// Set the journal mode. Defaults to preserving the current mode.
181 pub fn journal_mode(&mut self, journal_mode: JournalMode) -> &mut Self {
182 self.journal_mode = journal_mode;
183 self
184 }
185
186 /// Set the synchronization policy for writes. Defaults to [`Synchronous::Extra`].
187 pub fn synchronous(&mut self, synchronous: Synchronous) -> &mut Self {
188 self.synchronous = synchronous;
189 self
190 }
191
192 /// Enable or disable full filesystem synchronization where supported (macOS). Defaults to `true` on macOS and `false` elsewhere.
193 pub fn fullfsync(&mut self, fullfsync: bool) -> &mut Self {
194 self.fullfsync = fullfsync;
195 self
196 }
197
198 /// Enable or disable dirty reads where SQLite supports them. Defaults to `false`.
199 pub fn read_uncommitted(&mut self, read_uncommitted: bool) -> &mut Self {
200 self.read_uncommitted = read_uncommitted;
201 self
202 }
203
204 /// Validate the options for correctness and compatibility.
205 fn validate(&self) -> Result<()> {
206 let message = if self.busy_timeout.as_millis() > i32::MAX as u128 {
207 Some("Busy timeout exceeds SQLite's maximum of i32::MAX milliseconds")
208 } else if self.open_mode == OpenMode::ReadOnly && self.journal_mode != JournalMode::Preserve
209 {
210 Some("Read-only connections must preserve journal mode")
211 } else if self
212 .key
213 .as_ref()
214 .is_some_and(|key| key.is_empty() || key.contains('\0'))
215 {
216 Some("The SQLCipher passphrase must be nonempty and contain no NUL bytes")
217 } else {
218 None
219 };
220 match message {
221 Some(message) => Err(Error::InvalidOptions(message.into())),
222 None => Ok(()),
223 }
224 }
225}
226
227impl fmt::Debug for ConnectionOptions {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.debug_struct("ConnectionOptions")
230 .field("open_mode", &self.open_mode)
231 .field("key", &self.key.as_ref().map(|_| "[REDACTED]"))
232 .field("busy_timeout", &self.busy_timeout)
233 .field("foreign_keys", &self.foreign_keys)
234 .field("journal_mode", &self.journal_mode)
235 .field("synchronous", &self.synchronous)
236 .field("fullfsync", &self.fullfsync)
237 .field("read_uncommitted", &self.read_uncommitted)
238 .finish()
239 }
240}
241
242/// Configure a freshly opened connection before querying or starting transactions.
243///
244/// Applies the key and busy timeout, validates decryption with a schema read, and
245/// applies the remaining options. Journal changes are checked against SQLite's
246/// returned mode. Writable connections reject OFF and MEMORY journaling when
247/// preserving the existing mode; read-only connections require Preserve.
248///
249/// The opener must select SQLite URI mode `ro`, `rw`, or `rwc` to match `open_mode`.
250/// This function cannot change OS-level access flags or undo file creation. It also
251/// sets `query_only` for read-only connections. On failure, discard the connection:
252/// setup is not transactional and some settings may already have been applied.
253///
254/// ```no_run
255/// use diesel::{Connection, SqliteConnection};
256/// use rbox_db::connection::{setup_connection, ConnectionOptions, OpenMode};
257///
258/// let mut conn = SqliteConnection::establish("file:library.db?mode=ro")?;
259/// let options = ConnectionOptions { open_mode: OpenMode::ReadOnly, ..Default::default() };
260/// setup_connection(&mut conn, &options)?;
261/// # Ok::<(), rbox_db::error::Error>(())
262/// ```
263pub fn setup_connection(conn: &mut DbConn, options: &ConnectionOptions) -> QueryResult<()> {
264 let invalid = |message: &str| {
265 DieselError::DatabaseError(
266 DatabaseErrorKind::UnableToSendCommand,
267 Box::new(message.to_owned()),
268 )
269 };
270 options
271 .validate()
272 .map_err(|error| invalid(&error.to_string()))?;
273 let timeout = options.busy_timeout.as_millis();
274 let read_only = options.open_mode == OpenMode::ReadOnly;
275 if let Some(key) = &options.key {
276 // PRAGMA does not support bound parameters. Escape the SQL string literal.
277 let key = key.replace('\'', "''");
278 diesel::sql_query(format!("PRAGMA key = '{key}'")).execute(conn)?;
279 }
280 diesel::sql_query(format!("PRAGMA busy_timeout = {timeout}")).execute(conn)?;
281
282 #[derive(diesel::QueryableByName)]
283 struct SchemaCount {
284 #[diesel(sql_type = diesel::sql_types::BigInt)]
285 #[diesel(column_name = count)]
286 _count: i64,
287 }
288 diesel::sql_query("SELECT count(*) AS count FROM sqlite_master")
289 .get_result::<SchemaCount>(conn)?;
290
291 // This fails inside transactions, before foreign_keys can silently ignore changes.
292 let synchronous = match options.synchronous {
293 Synchronous::Normal => "NORMAL",
294 Synchronous::Full => "FULL",
295 Synchronous::Extra => "EXTRA",
296 };
297 diesel::sql_query(format!("PRAGMA synchronous = {synchronous}")).execute(conn)?;
298 for (name, enabled) in [
299 ("query_only", read_only),
300 ("foreign_keys", options.foreign_keys),
301 ("fullfsync", options.fullfsync),
302 ("read_uncommitted", options.read_uncommitted),
303 ] {
304 diesel::sql_query(format!("PRAGMA {name} = {}", i32::from(enabled))).execute(conn)?;
305 }
306
307 #[derive(diesel::QueryableByName)]
308 struct Journal {
309 #[diesel(sql_type = diesel::sql_types::Text)]
310 journal_mode: String,
311 }
312 let current = diesel::sql_query("PRAGMA journal_mode").get_result::<Journal>(conn)?;
313 let requested = match options.journal_mode {
314 JournalMode::Preserve => None,
315 JournalMode::Delete => Some("delete"),
316 JournalMode::Truncate => Some("truncate"),
317 JournalMode::Persist => Some("persist"),
318 JournalMode::Wal => Some("wal"),
319 };
320 if let Some(mode) = requested {
321 if !current.journal_mode.eq_ignore_ascii_case(mode) {
322 let actual = diesel::sql_query(format!("PRAGMA journal_mode = {mode}"))
323 .get_result::<Journal>(conn)?;
324 if !actual.journal_mode.eq_ignore_ascii_case(mode) {
325 return Err(invalid("SQLite did not apply the requested journal mode"));
326 }
327 }
328 } else if !read_only
329 && !matches!(
330 current.journal_mode.to_ascii_lowercase().as_str(),
331 "delete" | "truncate" | "persist" | "wal"
332 )
333 {
334 return Err(invalid("Writable connections require durable journaling"));
335 }
336 Ok(())
337}
338
339/// Apply settings to each new physical pool connection, before it is handed out.
340///
341/// Match the manager URL's access mode to `open_mode`. The customizer runs once per
342/// connection, not on every checkout; callers must not leave changed PRAGMAs behind.
343///
344/// ```no_run
345/// use diesel::r2d2::ConnectionManager;
346/// use rbox_db::connection::{ConnectionOptions, DbConn, DbPool, OpenMode};
347///
348/// let manager = ConnectionManager::<DbConn>::new("file:library.db?mode=ro");
349/// let options = ConnectionOptions { open_mode: OpenMode::ReadOnly, ..Default::default() };
350/// let pool = DbPool::builder()
351/// .connection_customizer(Box::new(options))
352/// .build(manager)?;
353/// # Ok::<(), rbox_db::error::Error>(())
354/// ```
355impl CustomizeConnection<DbConn, r2d2::Error> for ConnectionOptions {
356 fn on_acquire(&self, conn: &mut DbConn) -> std::result::Result<(), r2d2::Error> {
357 setup_connection(conn, self).map_err(r2d2::Error::QueryError)
358 }
359}
360
361/// Open a filesystem database and apply its connection options.
362///
363/// Read-only and read-write modes require an existing file. Only
364/// [`OpenMode::ReadWriteCreate`] permits creation. The path is treated literally,
365/// not as a SQLite URI; reserved characters are escaped before adding the access
366/// mode. Relative paths are resolved against the current working directory.
367/// In-memory databases and caller-provided URI parameters are not supported here.
368///
369/// # Errors
370/// Returns an error for invalid options or paths, opening failures, incorrect keys,
371/// or settings SQLite cannot apply. Invalid options are rejected before opening.
372///
373/// ```no_run
374/// use rbox_db::connection::{establish_connection, ConnectionOptions};
375///
376/// let conn = establish_connection("library.db", &ConnectionOptions::default())?;
377/// # Ok::<(), rbox_db::error::Error>(())
378/// ```
379pub fn establish_connection(path: impl AsRef<Path>, options: &ConnectionOptions) -> Result<DbConn> {
380 options.validate()?;
381 let url = connection_url(path.as_ref(), options.open_mode)?;
382 let mut conn = DbConn::establish(&url)?;
383 setup_connection(&mut conn, options)?;
384 Ok(conn)
385}
386
387/// Open a pool of configured connections to a filesystem database.
388///
389/// Uses the same path and access rules as [`establish_connection`]. A temporary
390/// connection validates the database and initializes journal mode before pool workers
391/// start. It stays open until the pool is ready, retaining WAL state during startup.
392/// Each new pool connection then receives the same options through the customizer.
393/// Options are cloned so callers can reuse them for another connection or pool.
394///
395/// # Errors
396/// Returns opening/setup errors immediately instead of retrying them until the pool
397/// times out. Pool startup errors are returned separately. `max_size` must be nonzero.
398///
399/// ```no_run
400/// use rbox_db::connection::{create_connection_pool, ConnectionOptions};
401///
402/// let pool = create_connection_pool("library.db", &ConnectionOptions::default(), 4)?;
403/// let conn = pool.get()?;
404/// # Ok::<(), rbox_db::error::Error>(())
405/// ```
406pub fn create_connection_pool(
407 path: impl AsRef<Path>,
408 options: &ConnectionOptions,
409 max_size: u32,
410) -> Result<DbPool> {
411 options.validate()?;
412 if max_size == 0 {
413 return Err(Error::InvalidOptions(
414 "Pool size must be greater than zero".into(),
415 ));
416 }
417 let url = connection_url(path.as_ref(), options.open_mode)?;
418 let mut initial = DbConn::establish(&url)?;
419 setup_connection(&mut initial, options)?;
420 let pool = DbPool::builder()
421 .max_size(max_size)
422 .connection_customizer(Box::new(options.clone()))
423 .build(ConnectionManager::<DbConn>::new(url))?;
424 drop(initial);
425 Ok(pool)
426}
427
428fn connection_url(path: &Path, mode: OpenMode) -> Result<String> {
429 let bad_path =
430 |message: String| Error::Connection(diesel::ConnectionError::BadConnection(message));
431 if path.as_os_str().is_empty() || path == Path::new(":memory:") {
432 return Err(bad_path(
433 "Expected a nonempty filesystem database path".into(),
434 ));
435 }
436 let absolute = std::path::absolute(path).map_err(|error| bad_path(error.to_string()))?;
437 let path = absolute
438 .to_str()
439 .ok_or_else(|| bad_path("Database path is not UTF-8".into()))?;
440 if path.contains('\0') {
441 return Err(bad_path("Database path contains a NUL byte".into()));
442 }
443
444 #[cfg(windows)]
445 let normalized = path
446 .strip_prefix(r"\\?\UNC\")
447 .map(|rest| format!("//{rest}"))
448 .unwrap_or_else(|| path.strip_prefix(r"\\?\").unwrap_or(path).to_owned())
449 .replace('\\', "/");
450 #[cfg(windows)]
451 let path = normalized.as_str();
452
453 // Four slashes keep a Windows UNC server in the path, not the URI authority.
454 let mut url = if path.starts_with("//") {
455 "file://"
456 } else {
457 "file:"
458 }
459 .to_owned();
460 for byte in path.bytes() {
461 if byte.is_ascii_alphanumeric() || b"/-._~:".contains(&byte) {
462 url.push(char::from(byte));
463 } else {
464 use std::fmt::Write;
465 write!(&mut url, "%{byte:02X}").expect("writing to a String cannot fail");
466 }
467 }
468 url.push_str(match mode {
469 OpenMode::ReadOnly => "?mode=ro",
470 OpenMode::ReadWrite => "?mode=rw",
471 OpenMode::ReadWriteCreate => "?mode=rwc",
472 });
473 Ok(url)
474}