Skip to main content

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