use std::cell::Cell;
use std::path::Path;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use rusqlite::config::DbConfig;
use rusqlite::limits::Limit;
use rusqlite::{Connection, ErrorCode, OpenFlags};
use super::given::{self, OWN};
use super::{Config, Durability};
use crate::{Error, ErrorKind, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Role {
Writer,
Reader,
}
pub(crate) fn open(path: &Path, config: &Config, role: Role) -> Result<Connection> {
let what = || format!("{}: {} connection", path.display(), role.name());
super::give_mutexes();
warn_of_a_slow_build();
let connection = Connection::open_with_flags(path, flags(role)).map_err(|error| sql_error(what(), error))?;
connection.busy_timeout(config.busy_timeout).map_err(|error| sql_error(what(), error))?;
connection.set_prepared_statement_cache_capacity(config.statements);
match role {
Role::Writer => {
let mode = configure_writer(&connection, config).map_err(|error| sql_error(what(), error))?;
if !mode.eq_ignore_ascii_case("wal") {
return Err(Error::invalid(format!("{}: the journal mode is {mode}, not wal", what())));
}
}
Role::Reader => configure_reader(&connection, config).map_err(|error| sql_error(what(), error))?,
}
keep_to_its_file(&connection).map_err(|error| sql_error(what(), error))?;
if role == Role::Writer {
commit_only_through_commit(&connection).map_err(|error| sql_error(what(), error))?;
}
Ok(connection)
}
thread_local! {
static COMMITTING: Cell<bool> = const { Cell::new(false) };
}
fn commit_only_through_commit(writer: &Connection) -> rusqlite::Result<()> {
writer.commit_hook(Some(|| !COMMITTING.get()))
}
pub(crate) fn commit(writer: &Connection) -> rusqlite::Result<()> {
let before = COMMITTING.replace(true);
let committed = execute(writer, super::group::COMMIT);
COMMITTING.set(before);
committed
}
fn keep_to_its_file(connection: &Connection) -> rusqlite::Result<()> {
connection.set_limit(Limit::SQLITE_LIMIT_ATTACHED, 0)?;
given::guard(connection)
}
const SHARED_PAGE_CACHE: &str = "SQLite was built with SQLITE_ENABLE_MEMORY_MANAGEMENT, so every connection \
shares one page cache behind one mutex and readers stop one another: point reads from 16 threads ran 7-9x \
slower (research rust-slice-2026-10-10); build with LIBSQLITE3_FLAGS=\"SQLITE_DQS=0 \
-USQLITE_ENABLE_MEMORY_MANAGEMENT SQLITE_ENABLE_DBPAGE_VTAB -DHAVE_FDATASYNC=1\"";
const OWN_MUTEXES: &str = "SQLite had started before the store opened and keeps its own mutexes, which park a \
thread at once: a few threads reading one file wait on each other; open the store before the program's own SQLite";
static SLOW_BUILD: OnceLock<(Vec<&'static str>, AtomicBool)> = OnceLock::new();
fn warn_of_a_slow_build() {
SLOW_BUILD.get_or_init(|| {
let mut warnings = Vec::new();
if super::memory::shares_page_cache() {
warnings.push(SHARED_PAGE_CACHE);
}
if !super::mutexes_given() {
warnings.push(OWN_MUTEXES);
}
for warning in &warnings {
tracing::warn!(target: "tinystore", "{warning}");
}
(warnings, AtomicBool::new(!tracing::dispatcher::has_been_set()))
});
}
pub(crate) fn unheard_warnings() -> &'static [&'static str] {
match SLOW_BUILD.get() {
Some((warnings, unheard)) if unheard.swap(false, Ordering::Relaxed) => warnings,
_ => &[],
}
}
fn flags(role: Role) -> OpenFlags {
let shared = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX | OpenFlags::SQLITE_OPEN_EXRESCODE;
match role {
Role::Writer => shared | OpenFlags::SQLITE_OPEN_CREATE,
Role::Reader => shared,
}
}
const PAGES: &str = "pragma page_count";
const INCREMENTAL_AT_FIRST_WRITE: &str = "pragma auto_vacuum = incremental";
fn configure_writer(connection: &Connection, config: &Config) -> rusqlite::Result<String> {
connection.pragma_update(None, "page_size", config.page_size)?;
if config.incremental_vacuum && connection.query_row(PAGES, [], |row| row.get::<_, i64>(0))? == 0 {
drop(connection.prepare(INCREMENTAL_AT_FIRST_WRITE)?);
}
let mode: String = connection.pragma_update_and_check(None, "journal_mode", "wal", |row| row.get(0))?;
let synchronous = match config.durability {
Durability::Full => "full",
Durability::Os => "normal",
};
connection.pragma_update(None, "synchronous", synchronous)?;
if cfg!(target_os = "macos") {
connection.pragma_update(None, "fullfsync", true)?;
connection.pragma_update(None, "checkpoint_fullfsync", true)?;
}
configure_shared(connection, config)?;
Ok(mode)
}
fn configure_reader(connection: &Connection, config: &Config) -> rusqlite::Result<()> {
connection.pragma_update(None, "query_only", true)?;
connection.progress_handler(crate::cancel::STEPS, Some(crate::cancel::stopped))?;
configure_shared(connection, config)
}
fn configure_shared(connection: &Connection, config: &Config) -> rusqlite::Result<()> {
connection.pragma_update(None, "foreign_keys", true)?;
connection.pragma_update(None, "trusted_schema", false)?;
if config.keep_wal {
connection.set_db_config(DbConfig::SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, true)?;
}
connection.pragma_update(None, "cache_size", -i64::from(config.cache_kib))
}
pub(crate) fn read_copy<T>(path: &Path, read: impl FnOnce(&Connection) -> rusqlite::Result<T>) -> Result<T> {
let what = || format!("read the copy {}", path.display());
let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX | OpenFlags::SQLITE_OPEN_EXRESCODE;
let connection = Connection::open_with_flags(path, flags).map_err(|error| sql_error(what(), error))?;
read(&connection).map_err(|error| sql_error(what(), error))
}
#[cfg(feature = "kv")]
pub(crate) fn read_file<T>(path: &Path, read: impl FnOnce(&Connection) -> rusqlite::Result<T>) -> Result<T> {
let what = || format!("read {}", path.display());
super::give_mutexes();
let open = || -> rusqlite::Result<Connection> {
let connection = Connection::open_with_flags(path, flags(Role::Reader))?;
connection.set_db_config(DbConfig::SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, true)?;
connection.busy_timeout(Config::default().busy_timeout)?;
connection.pragma_update(None, "query_only", true)?;
Ok(connection)
};
let connection = open().map_err(|error| sql_error(what(), error))?;
read(&connection).map_err(|error| sql_error(what(), error))
}
pub(crate) fn execute(connection: &Connection, sql: &str) -> rusqlite::Result<()> {
debug_assert!(sql.starts_with(OWN), "{sql}: the adapter's own statement is written with own!");
connection.prepare_cached(sql)?.execute([]).map(|_| ())
}
pub(crate) fn quote_ident(name: &str) -> String {
format!("\"{}\"", name.replace('"', "\"\""))
}
pub(crate) fn execute_cached(
connection: &Connection,
sql: &str,
params: impl rusqlite::Params,
what: &str,
) -> crate::Result<usize> {
let ran = connection.prepare_cached(sql).and_then(|mut statement| statement.execute(params));
ran.map_err(|error| sql_error(what, error))
}
pub(crate) fn query_cached<T, C: FromIterator<T>>(
connection: &Connection,
(sql, what): (&str, &str),
params: impl rusqlite::Params,
row: impl FnMut(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
) -> crate::Result<C> {
let read = || -> rusqlite::Result<C> { connection.prepare_cached(sql)?.query_map(params, row)?.collect() };
read().map_err(|error| sql_error(what, error))
}
impl Role {
fn name(self) -> &'static str {
match self {
Self::Writer => "writer",
Self::Reader => "reader",
}
}
}
pub(crate) fn sql_error(what: impl Into<String>, error: rusqlite::Error) -> Error {
error_of(what, error, ErrorKind::Internal)
}
pub(crate) fn given_sql_error(what: impl Into<String>, error: rusqlite::Error) -> Error {
error_of(what, error, ErrorKind::Invalid)
}
fn error_of(what: impl Into<String>, error: rusqlite::Error, plain: ErrorKind) -> Error {
let kind = match &error {
rusqlite::Error::SqliteFailure(failure, _) | rusqlite::Error::SqlInputError { error: failure, .. } => {
kind_of(failure, plain)
}
rusqlite::Error::QueryReturnedNoRows => ErrorKind::NotFound,
rusqlite::Error::FromSqlConversionFailure(..)
| rusqlite::Error::InvalidColumnType(..)
| rusqlite::Error::IntegralValueOutOfRange(..) => ErrorKind::Corrupt,
_ => ErrorKind::Internal,
};
super::name_constraint(Error::new(kind, what), &error).with_source(error)
}
fn kind_of(failure: &rusqlite::ffi::Error, plain: ErrorKind) -> ErrorKind {
use rusqlite::ffi;
let held = [ffi::SQLITE_CONSTRAINT_UNIQUE, ffi::SQLITE_CONSTRAINT_PRIMARYKEY, ffi::SQLITE_CONSTRAINT_ROWID];
match failure.code {
ErrorCode::ConstraintViolation if held.contains(&failure.extended_code) => ErrorKind::Conflict,
ErrorCode::ConstraintViolation => ErrorKind::Invalid,
ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked => ErrorKind::Unavailable,
ErrorCode::DatabaseCorrupt | ErrorCode::NotADatabase => ErrorKind::Corrupt,
ErrorCode::DiskFull | ErrorCode::TooBig => ErrorKind::Limit,
ErrorCode::SystemIoFailure | ErrorCode::CannotOpen | ErrorCode::PermissionDenied => ErrorKind::Io,
ErrorCode::ReadOnly => ErrorKind::Invalid,
ErrorCode::OperationInterrupted => ErrorKind::Cancelled,
ErrorCode::Unknown => plain,
_ => ErrorKind::Internal,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn broken(sql: &str) -> Error {
super::super::give_mutexes();
let connection = Connection::open_in_memory().unwrap();
connection
.execute_batch(
"CREATE TABLE parent (id INTEGER PRIMARY KEY);
CREATE TABLE t (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE,
total INTEGER CHECK (total > 0), parent INTEGER REFERENCES parent (id));
INSERT INTO t VALUES (1, 'a', 1, NULL);
PRAGMA foreign_keys = ON;",
)
.unwrap();
sql_error("t", connection.execute_batch(sql).unwrap_err())
}
#[test]
fn only_a_key_already_held_is_a_conflict() {
assert_eq!(broken("INSERT INTO t VALUES (2, 'a', 1, NULL)").kind(), ErrorKind::Conflict, "unique");
assert_eq!(broken("INSERT INTO t VALUES (1, 'b', 1, NULL)").kind(), ErrorKind::Conflict, "primary key");
assert_eq!(broken("INSERT INTO t VALUES (2, NULL, 1, NULL)").kind(), ErrorKind::Invalid, "not null");
assert_eq!(broken("INSERT INTO t VALUES (2, 'b', 0, NULL)").kind(), ErrorKind::Invalid, "check");
assert_eq!(broken("INSERT INTO t VALUES (2, 'b', 1, 9)").kind(), ErrorKind::Invalid, "foreign key");
}
}