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