use diesel::r2d2::{self, ConnectionManager, CustomizeConnection, Pool};
use diesel::result::{DatabaseErrorKind, Error as DieselError};
use diesel::{Connection, QueryResult, RunQueryDsl, SqliteConnection};
use std::fmt;
use std::path::Path;
use std::time::Duration;
use crate::error::{Error, Result};
pub type DbConn = SqliteConnection;
pub type DbPool = Pool<ConnectionManager<DbConn>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OpenMode {
ReadOnly,
#[default]
ReadWrite,
ReadWriteCreate,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JournalMode {
#[default]
Preserve,
Delete,
Truncate,
Persist,
Wal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Synchronous {
Normal,
Full,
#[default]
Extra,
}
#[derive(Clone)]
pub struct ConnectionOptions {
pub open_mode: OpenMode,
pub key: Option<String>,
pub busy_timeout: Duration,
pub foreign_keys: bool,
pub journal_mode: JournalMode,
pub synchronous: Synchronous,
pub fullfsync: bool,
pub read_uncommitted: bool,
}
impl Default for ConnectionOptions {
fn default() -> Self {
Self {
open_mode: Default::default(),
key: None,
busy_timeout: Duration::from_secs(5),
foreign_keys: true,
journal_mode: Default::default(),
synchronous: Default::default(),
fullfsync: cfg!(target_os = "macos"),
read_uncommitted: false,
}
}
}
impl ConnectionOptions {
pub fn new() -> Self {
Self::default()
}
pub fn for_export() -> Self {
Self {
open_mode: OpenMode::ReadWriteCreate,
journal_mode: JournalMode::Delete,
..Self::default()
}
}
pub fn open_mode(&mut self, open_mode: OpenMode) -> &mut Self {
self.open_mode = open_mode;
self
}
pub fn key(&mut self, key: String) -> &mut Self {
self.key = Some(key);
self
}
pub fn busy_timeout(&mut self, busy_timeout: Duration) -> &mut Self {
self.busy_timeout = busy_timeout;
self
}
pub fn foreign_keys(&mut self, foreign_keys: bool) -> &mut Self {
self.foreign_keys = foreign_keys;
self
}
pub fn journal_mode(&mut self, journal_mode: JournalMode) -> &mut Self {
self.journal_mode = journal_mode;
self
}
pub fn synchronous(&mut self, synchronous: Synchronous) -> &mut Self {
self.synchronous = synchronous;
self
}
pub fn fullfsync(&mut self, fullfsync: bool) -> &mut Self {
self.fullfsync = fullfsync;
self
}
pub fn read_uncommitted(&mut self, read_uncommitted: bool) -> &mut Self {
self.read_uncommitted = read_uncommitted;
self
}
fn validate(&self) -> Result<()> {
let message = if self.busy_timeout.as_millis() > i32::MAX as u128 {
Some("Busy timeout exceeds SQLite's maximum of i32::MAX milliseconds")
} else if self.open_mode == OpenMode::ReadOnly && self.journal_mode != JournalMode::Preserve
{
Some("Read-only connections must preserve journal mode")
} else if self
.key
.as_ref()
.is_some_and(|key| key.is_empty() || key.contains('\0'))
{
Some("The SQLCipher passphrase must be nonempty and contain no NUL bytes")
} else {
None
};
match message {
Some(message) => Err(Error::InvalidOptions(message.into())),
None => Ok(()),
}
}
}
impl fmt::Debug for ConnectionOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConnectionOptions")
.field("open_mode", &self.open_mode)
.field("key", &self.key.as_ref().map(|_| "[REDACTED]"))
.field("busy_timeout", &self.busy_timeout)
.field("foreign_keys", &self.foreign_keys)
.field("journal_mode", &self.journal_mode)
.field("synchronous", &self.synchronous)
.field("fullfsync", &self.fullfsync)
.field("read_uncommitted", &self.read_uncommitted)
.finish()
}
}
pub fn setup_connection(conn: &mut DbConn, options: &ConnectionOptions) -> QueryResult<()> {
let invalid = |message: &str| {
DieselError::DatabaseError(
DatabaseErrorKind::UnableToSendCommand,
Box::new(message.to_owned()),
)
};
options
.validate()
.map_err(|error| invalid(&error.to_string()))?;
let timeout = options.busy_timeout.as_millis();
let read_only = options.open_mode == OpenMode::ReadOnly;
if let Some(key) = &options.key {
let key = key.replace('\'', "''");
diesel::sql_query(format!("PRAGMA key = '{key}'")).execute(conn)?;
}
diesel::sql_query(format!("PRAGMA busy_timeout = {timeout}")).execute(conn)?;
#[derive(diesel::QueryableByName)]
struct SchemaCount {
#[diesel(sql_type = diesel::sql_types::BigInt)]
#[diesel(column_name = count)]
_count: i64,
}
diesel::sql_query("SELECT count(*) AS count FROM sqlite_master")
.get_result::<SchemaCount>(conn)?;
let synchronous = match options.synchronous {
Synchronous::Normal => "NORMAL",
Synchronous::Full => "FULL",
Synchronous::Extra => "EXTRA",
};
diesel::sql_query(format!("PRAGMA synchronous = {synchronous}")).execute(conn)?;
for (name, enabled) in [
("query_only", read_only),
("foreign_keys", options.foreign_keys),
("fullfsync", options.fullfsync),
("read_uncommitted", options.read_uncommitted),
] {
diesel::sql_query(format!("PRAGMA {name} = {}", i32::from(enabled))).execute(conn)?;
}
#[derive(diesel::QueryableByName)]
struct Journal {
#[diesel(sql_type = diesel::sql_types::Text)]
journal_mode: String,
}
let current = diesel::sql_query("PRAGMA journal_mode").get_result::<Journal>(conn)?;
let requested = match options.journal_mode {
JournalMode::Preserve => None,
JournalMode::Delete => Some("delete"),
JournalMode::Truncate => Some("truncate"),
JournalMode::Persist => Some("persist"),
JournalMode::Wal => Some("wal"),
};
if let Some(mode) = requested {
if !current.journal_mode.eq_ignore_ascii_case(mode) {
let actual = diesel::sql_query(format!("PRAGMA journal_mode = {mode}"))
.get_result::<Journal>(conn)?;
if !actual.journal_mode.eq_ignore_ascii_case(mode) {
return Err(invalid("SQLite did not apply the requested journal mode"));
}
}
} else if !read_only
&& !matches!(
current.journal_mode.to_ascii_lowercase().as_str(),
"delete" | "truncate" | "persist" | "wal"
)
{
return Err(invalid("Writable connections require durable journaling"));
}
Ok(())
}
impl CustomizeConnection<DbConn, r2d2::Error> for ConnectionOptions {
fn on_acquire(&self, conn: &mut DbConn) -> std::result::Result<(), r2d2::Error> {
setup_connection(conn, self).map_err(r2d2::Error::QueryError)
}
}
pub fn establish_connection(path: impl AsRef<Path>, options: &ConnectionOptions) -> Result<DbConn> {
options.validate()?;
let url = connection_url(path.as_ref(), options.open_mode)?;
let mut conn = DbConn::establish(&url)?;
setup_connection(&mut conn, options)?;
Ok(conn)
}
pub fn create_connection_pool(
path: impl AsRef<Path>,
options: &ConnectionOptions,
max_size: u32,
) -> Result<DbPool> {
options.validate()?;
if max_size == 0 {
return Err(Error::InvalidOptions(
"Pool size must be greater than zero".into(),
));
}
let url = connection_url(path.as_ref(), options.open_mode)?;
let mut initial = DbConn::establish(&url)?;
setup_connection(&mut initial, options)?;
let pool = DbPool::builder()
.max_size(max_size)
.connection_customizer(Box::new(options.clone()))
.build(ConnectionManager::<DbConn>::new(url))?;
drop(initial);
Ok(pool)
}
fn connection_url(path: &Path, mode: OpenMode) -> Result<String> {
let bad_path =
|message: String| Error::Connection(diesel::ConnectionError::BadConnection(message));
if path.as_os_str().is_empty() || path == Path::new(":memory:") {
return Err(bad_path(
"Expected a nonempty filesystem database path".into(),
));
}
let absolute = std::path::absolute(path).map_err(|error| bad_path(error.to_string()))?;
let path = absolute
.to_str()
.ok_or_else(|| bad_path("Database path is not UTF-8".into()))?;
if path.contains('\0') {
return Err(bad_path("Database path contains a NUL byte".into()));
}
#[cfg(windows)]
let normalized = path
.strip_prefix(r"\\?\UNC\")
.map(|rest| format!("//{rest}"))
.unwrap_or_else(|| path.strip_prefix(r"\\?\").unwrap_or(path).to_owned())
.replace('\\', "/");
#[cfg(windows)]
let path = normalized.as_str();
let mut url = if path.starts_with("//") {
"file://"
} else {
"file:"
}
.to_owned();
for byte in path.bytes() {
if byte.is_ascii_alphanumeric() || b"/-._~:".contains(&byte) {
url.push(char::from(byte));
} else {
use std::fmt::Write;
write!(&mut url, "%{byte:02X}").expect("writing to a String cannot fail");
}
}
url.push_str(match mode {
OpenMode::ReadOnly => "?mode=ro",
OpenMode::ReadWrite => "?mode=rw",
OpenMode::ReadWriteCreate => "?mode=rwc",
});
Ok(url)
}