Skip to main content

Crate cute_sqlite_kv

Crate cute_sqlite_kv 

Source
Expand description

This crate provides a very small and simple multi-process persistent key-value store, using SQLite for storage.

The code is intended to be as simple a wrapper around SQLite (via rusqlite) as possible.

Two stores are provided:

  • KVStore maps string keys to string values.
  • BlobStore maps string keys to binary (Vec<u8>) values.

Both are thin aliases for the generic Store, which holds all the logic; only the value type differs. Keys are always &str.

The store can be used from multiple processes, and also opened multiple times from the same process. File-backed stores use WAL mode so reads can proceed during a write (see Store::new_from_file for the caveats, notably that WAL does not work over network filesystems).

While SQLite can be very quick, this key-value store is not intended for high-performance situations, but when you need something as simple as possible, but still correct. Please feel free to take, extend, and modify this code for your own requirements!

§One value type per database file

A given database file should be used with a single store type. The value column happily holds whatever you write (text or binary), but reading a binary value back as a String (or a text value as bytes) fails – and, per the panic policy below, that failure is a panic. So pick KVStore or BlobStore for a file and stick to it.

§Errors and panics

Opening a store (new_from_file / new_in_memory) returns a Result, because a bad path or permissions is a normal thing a caller might want to handle.

Every other operation panics if the underlying SQLite call fails. The reasoning: once the store is open, the only remaining failures are catastrophic (disk full, corruption, the file vanished) and there is no sensible recovery. A loud panic is better than a silently dropped error. Lock contention between processes does not cause a panic: a busy_timeout is set so writers wait for the lock rather than failing.

§Examples

use cute_sqlite_kv::KVStore;

let kvstore = KVStore::new_in_memory().unwrap();

kvstore.insert("key", "value");

assert_eq!(kvstore.get("key"), Some("value".to_string()));

kvstore.remove("key");

assert_eq!(kvstore.get("key"), None);

Storing binary values with BlobStore:

use cute_sqlite_kv::BlobStore;

let store = BlobStore::new_in_memory().unwrap();

let bytes: &[u8] = &[0, 1, 2, 255];
store.insert("key", bytes);

assert_eq!(store.get("key"), Some(bytes.to_vec()));

Creating a file-backed store:

use cute_sqlite_kv::KVStore;

let kvstore = KVStore::new_from_file("mydata.db").unwrap();

Structs§

Store
A simple key-value store backed by SQLite, generic over its value type.

Traits§

StoreValue
A type that can be used as the value of a Store.

Type Aliases§

BlobStore
A key-value store mapping string keys to binary (Vec<u8>) values.
KVStore
A key-value store mapping string keys to string values.