Embedded library

skaidb's engine runs inside your process as a library: the same storage, SQL and on-disk format as the server, with no listener, no socket and no second process. Use it for a local store that an application owns — a desktop tool, a test fixture, a device cache — and the server when several processes or machines need the data.

An embedded database is a single node. It has what a standalone server has (tables, secondary indexes, transactions, BACKUP / RESTORE, at-rest encryption) and none of what needs a cluster (replication, consistency levels, witnesses). The directory it writes is a server's data directory: skaidbsh --local <dir> opens an unencrypted one, and a server can be started on it.

There are two ways in:

  • skaidb-engine — the engine's own Rust API (Session, Database). Everything a server can do on one node, with a server's defaults.
  • skaidb-embedded — a small, stable surface over it, for applications and other languages: one handle that is safe to share between threads, typed error codes, bound parameters, one opener per directory, and a C ABI (libskaidb_embedded). The Android library is built on it. See The embedded library.

Contents

Opening a database

The library is the skaidb-engine crate. A Session is one database directory plus a current database (USE works as on a connection):

use skaidb_engine::{EngineOptions, QueryOutput, Session};

let mut db = Session::open_with_options(
    "/var/lib/myapp/store",
    EngineOptions::with_memory_budget(64 * 1024 * 1024),
)?;
db.execute("CREATE TABLE IF NOT EXISTS messages (PRIMARY KEY (channel, ts))")?;
db.execute("INSERT INTO messages (channel, ts, body) VALUES ('C1', '1700000000.000100', 'hi')")?;
if let QueryOutput::Rows(rs) =
    db.execute("SELECT ts, body FROM messages WHERE channel = 'C1' ORDER BY ts DESC LIMIT 200")?
{
    for row in rs.rows { /* rs.columns names each position */ }
}
db.close();

Session::open(dir) opens with the server's defaults. Every statement in the statement reference that is not cluster-only works, including BEGIN / COMMIT / ROLLBACK.

Open a directory from one process at a time.

Closing

close() writes out everything still in memory, so the next open replays no write-ahead log and starts in the time it takes to read the catalog and open the files. It returns what it flushed. A close flushes and does not compact: it costs what was unflushed, not the size of the tables.

A database opened through skaidb-engine does not flush or compact in the background: a flush or a compaction runs inside the statement that makes it due. One opened through skaidb-embedded does that work on threads of its own — see Background maintenance.

Dropping a database without closing it — or the process being killed — is safe: every acknowledged write is in a write-ahead log, and the next open replays what had not been flushed yet. How much that can be is what the memory budget bounds.

A memory budget

The default sizes are a server's: a 32 MB write buffer and a 64 MB read cache per table. EngineOptions::with_memory_budget(bytes) sizes an embedded database for a process that can spare bytes:

Part Share of the budget
Block cache, shared by every table 1/4
Unflushed writes, summed over every table and index 1/4
Point-read cache, per table or index 1/64
One statement's result set, before the statement errors 1/4

The first two stay resident while the database is open. The write share is a ceiling for the whole database (memtable_budget_bytes), not per table: it counts every write buffer not yet in a file, and the statement that takes the sum past it flushes the largest ones before it returns. That ceiling is also the most a crash can leave to replay — an open after one replays at most that much, and brings it back under the ceiling before the first statement runs. (With background maintenance the write that crosses the ceiling waits for the flush instead of doing it, and the open leaves what it replayed to the same threads.)

Outside these shares: what a statement needs while it runs, and an open transaction — its buffered writes are held in memory until the commit, and written once more to its journal as it commits. Keep transactions to the size of a batch, not of a table.

A statement whose result would pass its share fails with a resource-limit error instead of holding the rows; read large results in keyset pages (ORDER BY <pk> LIMIT n AFTER (…) — see Deep pagination).

Budgets under 8 MB are raised to 8 MB. Every field can still be set by hand afterwards:

let opts = EngineOptions {
    scan_byte_budget: 32 * 1024 * 1024,
    ..EngineOptions::with_memory_budget(64 * 1024 * 1024)
};

Choosing the engines

Full-text search, time-series tables, vector indexes and geo indexes are each an engine of their own. All are available by default; an application that ships a narrower product turns the others off for its opens:

use skaidb_engine::{Capabilities, EngineOptions};

let opts = EngineOptions {
    capabilities: Capabilities::CORE,           // rows, indexes and SQL only
    ..EngineOptions::with_memory_budget(64 * 1024 * 1024)
};
// or one at a time:
let caps = Capabilities { timeseries: false, ..Capabilities::ALL };
Capability Refuses
search CREATE SEARCH INDEX
timeseries CREATE TIMESERIES TABLE, CREATE ROLLUP on a time-series table
vector CREATE VECTOR INDEX
geo CREATE GEO INDEX

With a capability off:

  • its CREATE statements fail with EngineError::UnsupportedCapability, naming the capability — a typed error, so an application can tell "this product has no such feature" from a statement that is wrong;
  • a directory that already holds such an object is refused at open with the same error, naming the objects. Nothing is dropped or rewritten: open with the capability on and they are as they were;
  • RESTORE of a backup that holds one is refused before the live data moves.

A capability is a property of the open, not of the directory.

The search engine is the one part with a large dependency tree of its own. It sits behind the search feature of skaidb-engine, on by default:

[dependencies]
skaidb-engine = { version = "…", default-features = false }

A build without it carries no search code or dependencies. It behaves as an open with the search capability off, whatever the options ask for: the refusals say the engine is not compiled into the build.

Encryption at rest

Pass a key in the options and every table and index file is sealed:

use skaidb_engine::{EngineOptions, Kek, Keyring};

let kek = Kek::from_material(&key_bytes)?;      // 32 bytes, from your key store
let opts = EngineOptions {
    keyring: Some(Keyring::new(kek, vec![])),
    at_rest_enabled: true,
    ..EngineOptions::with_memory_budget(64 * 1024 * 1024)
};

The key never touches the disk; the library holds it for as long as the database is open. A transaction's redo journal (txn.journal) is sealed like the tables it writes. What is and is not sealed is listed under What at-rest encryption covers — for an embedded database the unsealed parts that matter are catalog.json (object names and definitions, no rows) and full-text indexes (fts/, absent when search is off).

The embedded library (skaidb-embedded)

use skaidb_embedded::{Database, ErrorCode, Key, OpenOptions, QueryOutput, Value};

let db = Database::open("/var/lib/myapp/store", OpenOptions {
    key: Some(Key::from_bytes(&key_bytes)?),       // or None for a plain store
    schema_version: Some(1),
    ..OpenOptions::default()                       // 64 MiB budget; rows, indexes and SQL
})?;
db.execute("CREATE TABLE IF NOT EXISTS t (PRIMARY KEY (id))", &[])?;
db.execute("INSERT INTO t (id, name) VALUES (?, ?)", &[Value::Int(1), Value::String("ada".into())])?;

let mut txn = db.begin()?;
txn.execute("DELETE FROM t WHERE id = ?", &[Value::Int(1)])?;
txn.commit()?;

match db.execute("SELECT * FROM nope", &[]) {
    Err(e) if e.code == ErrorCode::NotFound => { /* … */ }
    other => { other?; }
}
db.close()?;
  • One handle, any thread. Database is Send + Sync and cheap to clone. Reads (SELECT, SHOW …, EXPLAIN) run concurrently; everything else runs one statement at a time.
  • One opener per directory. The open holds the directory's lock file — the one a server takes — until it is closed; a second open fails with Busy.
  • Parameters. ? placeholders are filled, in order, from the values passed with the statement.
  • Transactions are handles. BEGIN / COMMIT / ROLLBACK are refused as statements on the shared handle; begin() gives a Transaction whose writes are private until commit() applies them atomically. Dropping it rolls back. A transaction takes no locks; a commit is refused with Conflict — nothing applied — when a row it writes was changed by another caller after the transaction began, and db.transaction(attempts, |txn| …) runs the body again when that happens. DDL inside a transaction takes effect at once: see Transactions for the contract.
  • query() only reads. It takes SELECT, SHOW … and EXPLAIN, and refuses anything else before it runs; execute() runs any statement.
  • USE is refused. The handle is shared, so there is no "current database" to switch: name a table in another database as db.table.
  • Maintenance off the statement path. Flushes and merges run on the store's own threads: see Background maintenance.
  • Defaults for an application. A 64 MiB memory budget and no optional engines (Capabilities::CORE); full-text search is compiled in only with the crate's search feature.
  • A store identity. The directory records whether the store is encrypted, a check value for its key, and the application's schema version. A store is created encrypted or plain and stays that way: an encrypted store refuses a missing or wrong key before any data file is read, and a plain store refuses a key. An open that asks for schema version n refuses a store already above n. A directory an open was refused for is left as it was.
  • RESTORE keeps the identity true. A backup made from an encrypted store restores only into a store with the same key, a plain backup only into a plain store (Key otherwise, before anything moves); afterwards the store carries the backup's schema version. The data that was replaced is kept beside the store, in <dir>.pre-restore, until you remove it — a "delete the store" flow must delete that directory too.
  • The key in memory. The engine holds copies of the key while the store is open and wipes them when it is closed or dropped. The per-file keys derived from it, and data the process has read, are not wiped; a key in memory protects nothing from code running in the same process.
  • data_version() moves whenever stored data may have changed (a statement that is not a read; a commit) — remember the value a query was answered at and re-run the query when it has moved.

Every failure is an Error { code, message }:

Code Meaning
InvalidArgument (1) Parameters that do not match or decode, a key of the wrong length, transaction control as a statement
Sql (2) The statement does not parse or is not supported
Constraint (3) Unique / foreign key / NOT NULL / CHECK violation, or the object already exists
UnsupportedCapability (4) The statement needs an engine this open does not offer
Busy (5) The directory is open elsewhere
Key (6) The key is missing, wrong, or given for a plain store
Corrupt (7) A data file failed its integrity check
DiskFull (8) Out of space; nothing acknowledged was lost
Io (9) Any other I/O failure
ResourceLimit (10) A statement passed a resource ceiling: page the read
Closed (11) The handle or transaction is closed
NotFound (12) No such table, index or database
TooNew (13) The store's format or schema version is newer than this open accepts
Internal (14) A bug: the handle refuses further work until it is closed and reopened
Conflict (15) A commit refused: a row the transaction writes was changed by another caller after it began. Nothing was applied; run the transaction again

One limit worth knowing: values nest at most 128 levels of arrays and documents; a deeper one is refused when it is bound or written.

Background maintenance

Writes land in a write-ahead log and in memory. What is in memory is written out to table files later (a flush), and those files are merged as they pile up. An open store does both on two threads of its own, one for flushes and one for merges. They take the store's lock only to seal a write buffer and to install a finished file — the files are built with no lock held, so reads and writes go on meanwhile — and they sleep until a write wakes them: an idle store runs nothing.

  • The memory ceiling. A write that takes the unflushed writes past their share of the memory budget returns once the flush thread has brought them back under it. The writer waits; nobody else does. The write is applied either way: the wait ends after ten seconds, or as soon as a flush pass writes nothing (a device that refuses the files).
  • The merge backlog. A write that leaves a table with twice the files that make a merge due (eight, by default) returns once a merge has caught up — again the writer waits, nobody else. This is what bounds the files every read has to look at, however the store is used: a store that is only ever open for a moment (a periodic sync) completes its merges inside these waits. The wait ends after sixty seconds, or as soon as a merge round merges nothing. The wait is for the tables the statement wrote: a row added to one table does not wait while another table's merges catch up. (One merge runs at a time, so a table's own merge can queue behind another's.)
  • A statement that writes nothing waits for nothing — a CREATE TABLE IF NOT EXISTS that finds its table, a statement that fails before it writes. Neither of the two waits above applies to it, whatever state the last process left the store in.
  • An idle store is left as a close would leave it. Five seconds after the last write the flush thread settles what close() settles and — when the unflushed writes are at least a quarter of their ceiling (4 MiB with the default budget) — writes them out. A process that is killed after that, the ordinary end of an application on a phone, opens with nothing to replay; with less unflushed it replays that much, which costs less than a table file written — and merged into the files below it — for every few rows.
  • A vector index's graph is saved while idle once enough of it has changed: at least 64 vectors and a sixteenth of the index since the last save. A save writes the whole graph (about 22 MiB for 20,000 vectors of 256 dimensions), so it is not done for a handful of rows. close() saves whatever is unsaved, so the open after a close applies nothing. The open after a kill loads the saved graph and brings it up to date from the table — the rows written since are added (under a sixteenth of the index), the rows deleted since leave — without writing the graph on the thread that opens; the first idle pass then saves it, so the same rows are not applied at the next open as well.
  • close() does not wait for a merge. It waits for a write buffer whose file is being built — at most one buffer's worth of work — then flushes what is left. A merge in progress is given up (a merge is as long as its table is large) and started again at the next open. RESTORE holds the threads the same way while it swaps the store.
  • A kill in the middle of a burst of writes costs the next open what was unflushed, and no more: the write-ahead log of a write buffer is let go as soon as its file is installed. That is the ceiling on unflushed writes, a quarter of the memory budget.
  • A row and its index entries survive a power loss together. They are written to separate logs, each synced before the statement returns, and a device that loses power between the two can keep the row without its entries. The store tracks, per table, how far its index entries are known to be durable; the open after such a loss re-applies the entries of the rows above that mark.
  • info() reports background_flushes and background_merges since the open.

OpenOptions { background_maintenance: false, .. } opens a store without the threads: each statement then does this work itself before it returns, every other caller waiting — for a tool that wants no thread it did not start. The C API and the Android library always run them.

If a maintenance thread panics, the handle refuses further work (Internal) the way it does after a statement's panic: close it and open the store again.

C API

The same surface as a C library: libskaidb_embedded (static and shared) with one header, skaidb_embedded.h. Each release publishes libskaidb_embedded-<version>-<target>.tar.gz (include/ + lib/) for Linux x86_64 and aarch64 at https://repo.dsys.org/dl/skaidb/<version>/; or build it with cargo build --release -p skaidb-embedded (target/release/ holds libskaidb_embedded.a and .so; the header is in crates/skaidb-embedded/include/). Link -lpthread -ldl -lm.

#include "skaidb_embedded.h"

skaidb_embedded_options_t opts;
skaidb_embedded_options_init(&opts);
opts.key = key;                       /* 32 bytes, or leave NULL */
opts.key_len = SKAIDB_EMBEDDED_KEY_LEN;

skaidb_embedded_t *db = NULL;
if (skaidb_embedded_open("/var/lib/myapp/store", &opts, &db) != SKAIDB_EMBEDDED_OK) {
    fprintf(stderr, "%s\n", skaidb_embedded_last_error());
    return 1;
}
char *json = NULL;
skaidb_embedded_execute_json(db, "SELECT id, name FROM t WHERE id = ?", "[1]", &json);
/* {"columns":["id","name"],"rows":[[1,"ada"]]} */
skaidb_embedded_string_free(json);
skaidb_embedded_close(db);
skaidb_embedded_free(db);
  • Every call returns SKAIDB_EMBEDDED_OK (0) or one of the codes above; skaidb_embedded_last_error() is the message of the last failure on the calling thread.
  • skaidb_embedded_execute takes parameters and returns results as bytes in the formats the network drivers use (wire protocol): parameters as one encoded ARRAY of the ? values, the result as one response message. A language binding reuses a driver's value codec. skaidb_embedded_execute_json is the same call with JSON on both sides, lossy where JSON is.
  • Transactions: skaidb_embedded_begin → _txn_execute → _txn_commit / _txn_rollback; _txn_free rolls back one still open.
  • A database handle may be used from any thread; a transaction handle from one thread at a time. A panic inside the library is caught at the boundary and reported as SKAIDB_EMBEDDED_ERR_INTERNAL.
  • Call skaidb_embedded_options_init on the options struct before setting fields: it records the struct's size, and options that were not initialised are refused.
  • A call that fails leaves its out-parameters untouched, and out-pointers are checked before a statement runs.
  • skaidb_embedded_free releases the directory even while transaction handles are alive; they answer SKAIDB_EMBEDDED_ERR_CLOSED afterwards.
Search the docs