tinystore 0.10.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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,
}

/// Opens one connection with every setting its role needs. Each setting is
/// per connection in SQLite, so a reader opened again is the same 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! {
    /// This thread runs the adapter's own commit, [`commit`].
    static COMMITTING: Cell<bool> = const { Cell::new(false) };
}

/// Has `writer` refuse every commit but [`commit`]'s.
///
/// SQLite rolls a whole transaction back, its savepoints with it, for a
/// statement's `or rollback`, a trigger's `raise(rollback)`, or a disk that
/// failed mid-statement, and the connection is then in autocommit: each
/// statement run after it would commit by itself, beside the writes that
/// shared the transaction and were told it rolled back. With the hook such a
/// statement fails instead, and writes nothing.
fn commit_only_through_commit(writer: &Connection) -> rusqlite::Result<()> {
    writer.commit_hook(Some(|| !COMMITTING.get()))
}

/// Commits the transaction open on `writer`.
pub(crate) fn commit(writer: &Connection) -> rusqlite::Result<()> {
    let before = COMMITTING.replace(true);
    let committed = execute(writer, super::group::COMMIT);
    COMMITTING.set(before);
    committed
}

/// Leaves the connection its one file and its settings: no statement
/// attaches another, the store's own included, and a statement the store was
/// given changes nothing the connection's next user would meet.
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";

/// The warnings of a slow build, once they were found, and whether they were
/// logged before any subscriber listened.
static SLOW_BUILD: OnceLock<(Vec<&'static str>, AtomicBool)> = OnceLock::new();

/// Says once what the SQLite linked in costs readers, where it was built or
/// started without what the workspace gives it: a program that builds the
/// crate elsewhere finds out from its log, not from a profile.
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}");
        }
        // The guides set the subscriber up after the store opens, with the
        // store's logger in it: these went nowhere, and that logger says them.
        (warnings, AtomicBool::new(!tracing::dispatcher::has_been_set()))
    });
}

/// The warnings of a slow build that no subscriber heard, once: what a
/// store's logger prints first.
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 {
    // Each connection is used by one thread at a time, under the file's own
    // locks, so SQLite's per-connection mutex would only cost.
    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";

/// Sets the writer up and says the journal mode the file is in.
fn configure_writer(connection: &Connection, config: &Config) -> rusqlite::Result<String> {
    // page_size and auto_vacuum take effect only before the first table, so
    // they come first.
    connection.pragma_update(None, "page_size", config.page_size)?;
    if config.incremental_vacuum && connection.query_row(PAGES, [], |row| row.get::<_, i64>(0))? == 0 {
        // Compiling the pragma sets the mode the file's first write makes it
        // with; running it would write page 1 on its own as well. On a file
        // with pages it is never run: it would commit page 1 at every open,
        // a write beside the store that a node's log takes for a gap.
        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)?;
    // Without it macOS's fsync leaves the data in the drive's cache.
    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)?;
    // A statement stops once the call stepping it was cancelled or timed out:
    // the handler reads the tokens of the thread that steps it, its caller's.
    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 {
        // The last connection to close would checkpoint frames its log may
        // not hold durably yet.
        connection.set_db_config(DbConfig::SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, true)?;
    }
    // A negative cache_size is KiB rather than pages.
    connection.pragma_update(None, "cache_size", -i64::from(config.cache_kib))
}

/// Reads a copy a snapshot made, which nothing else has open.
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))
}

/// Reads the SQLite file at `path` once, through a connection of its own,
/// whether a connection of the store's has it open or not: for what the
/// store asks of a file no engine may have opened yet. The connection writes
/// nothing, not even the checkpoint SQLite runs as the last one closes, which
/// would move a node's frames into the file before its log holds them.
#[cfg(any(feature = "kv", all(feature = "blobs", feature = "client")))]
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))
}

/// Runs a statement of the adapter's own that returns no rows, compiled once
/// a connection.
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(|_| ())
}

/// A name as SQL quotes it whole, its quotes doubled: `"created_at"`.
pub(crate) fn quote_ident(name: &str) -> String {
    format!("\"{}\"", name.replace('"', "\"\""))
}

/// Runs an engine's statement, compiled once a connection, and says how many
/// rows it changed; a failure is named `what`.
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))
}

/// The rows an engine's statement gives, compiled once a connection, each
/// read by `row`; a failure is named `what`.
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",
        }
    }
}

/// An SQLite failure as the error kind a caller acts on.
pub(crate) fn sql_error(what: impl Into<String>, error: rusqlite::Error) -> Error {
    error_of(what, error, ErrorKind::Internal)
}

/// Whether SQLite found its disk full under whatever wraps the error: `limit`
/// as a bound reached is, but a later try may get past it where a bound's
/// would fail again.
pub(crate) fn disk_full(error: &Error) -> bool {
    let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(error);
    while let Some(now) = cause {
        if let Some(rusqlite::Error::SqliteFailure(failure, _)) = now.downcast_ref::<rusqlite::Error>()
            && failure.code == ErrorCode::DiskFull
        {
            return true;
        }
        cause = now.source();
    }
    false
}

/// A failure of a statement the program wrote, its SQLite plain error
/// `invalid`: a syntax error, a table or a column that is not there, a
/// full-text query FTS5 cannot read are the statement's own, not the store's.
pub(crate) fn given_sql_error(what: impl Into<String>, error: rusqlite::Error) -> Error {
    error_of(what, error, ErrorKind::Invalid)
}

/// `plain` is what SQLite's plain `SQLITE_ERROR` means to the caller, and
/// what rusqlite's own refusals of a statement mean: the fault of whoever
/// wrote the statement, the program or the engine.
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,
        // What the file holds is not what the schema says it holds.
        rusqlite::Error::FromSqlConversionFailure(..)
        | rusqlite::Error::InvalidColumnType(..)
        | rusqlite::Error::IntegralValueOutOfRange(..) => ErrorKind::Corrupt,
        // Two statements in one text; or a text value that is not UTF-8,
        // which SQLite keeps as a statement cast it and rusqlite will not read.
        rusqlite::Error::MultipleStatement | rusqlite::Error::Utf8Error(..) => plain,
        // A store's directory that is not UTF-8, which rusqlite cannot name to
        // SQLite on Windows.
        rusqlite::Error::InvalidPath(_) => ErrorKind::Invalid,
        _ => ErrorKind::Internal,
    };
    let what = what.into();
    let what = if matches!(error, rusqlite::Error::MultipleStatement) { format!("{what}: {SEVERAL}") } else { what };
    super::name_constraint(Error::new(kind, what), &error).with_source(error)
}

/// What a text of two statements or more is told: SQLite would run only its
/// first, and rusqlite refuses it rather than drop the rest.
const SEVERAL: &str = "several statements, and a call runs one: a batch runs several";

/// A unique or a primary key already held is `conflict`; any other
/// constraint, a check, a not null or a foreign key, is `invalid`.
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 {
        // as the adapter does before a connection of its own, so that this one
        // does not start SQLite with other mutexes than the adapter's
        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 a_full_disk_is_told_apart_from_a_bound_under_what_wraps_it() {
        super::super::give_mutexes();
        let connection = Connection::open_in_memory().unwrap();
        // a file that may hold two pages is a disk with no room past them
        connection.execute_batch("PRAGMA max_page_count = 2; CREATE TABLE t (v BLOB)").unwrap();
        let full = connection.execute("INSERT INTO t VALUES (zeroblob(1 << 16))", []).unwrap_err();
        let full = sql_error("t", full).within("index articles");
        assert_eq!(full.kind(), ErrorKind::Limit);
        assert!(disk_full(&full), "{full}");
        connection.set_limit(Limit::SQLITE_LIMIT_LENGTH, 16).unwrap();
        let too_big = connection.execute("SELECT zeroblob(64)", []).unwrap_err();
        let too_big = sql_error("t", too_big);
        assert_eq!(too_big.kind(), ErrorKind::Limit);
        assert!(!disk_full(&too_big), "{too_big}");
    }

    #[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");
    }

    // contract: ERR-03
    #[test]
    fn what_rusqlite_refuses_of_a_statement_is_the_fault_of_whoever_wrote_it() {
        super::super::give_mutexes();
        let connection = Connection::open_in_memory().unwrap();
        let several = || connection.prepare("SELECT 1; SELECT 2").map(drop).unwrap_err();
        let given = given_sql_error("its text", several());
        assert_eq!(given.kind(), ErrorKind::Invalid, "{given}");
        assert!(given.to_string().contains("a batch runs several"), "{given}");
        assert_eq!(sql_error("its text", several()).kind(), ErrorKind::Internal, "an engine's own text");

        let not_utf8 = connection
            .query_row("SELECT CAST(x'ff' AS TEXT)", [], |row| row.get::<_, rusqlite::types::Value>(0))
            .unwrap_err();
        assert_eq!(given_sql_error("read table docs", not_utf8).kind(), ErrorKind::Invalid);
    }

    // contract: ERR-03
    #[cfg(windows)]
    #[test]
    fn a_directory_sqlite_cannot_be_told_is_invalid() {
        use std::os::windows::ffi::OsStringExt;
        let dir = tempfile::tempdir().unwrap();
        let unpaired = std::ffi::OsString::from_wide(&[u16::from(b'a'), 0xd800]);
        let error = open(&dir.path().join(unpaired).join("kv.db"), &Config::default(), Role::Writer).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Invalid, "{error}");
    }
}