flatdb API reference
A file-backed JSON document store. Load a JSON file once into a value-semantic handle, query and edit it in memory through JSON Pointer, and write it back with a crash-atomic whole-file replace (temp file + rename). It is deliberately NOT a database engine: crash-atomic snapshotting of small data. Atomicity is whole-file (temp + rename); the data is fsynced before the rename and the directory after it, so a completed save survives a crash. For a real database, use a client over net (e.g. redis), not this. It is a thin file-lifecycle + ergonomics layer over the json write surface, not a re-implementation of it. Runs on both binaries (json, fs and path, no network).
CONCURRENT WRITERS: crash-atomic is not the same as write-safe. Two writers that each open, edit different parts, and save would otherwise silently lose one update (last rename wins). Two guards address that: save fails loudly (a catchable flatdb error) if the file changed since it was opened, so a lost update is never silent (the final check and the rename run under a short save lock); and update(path, transform) brackets the whole read-modify-write in a cross-process advisory lock, so concurrent writers serialize and no update is lost. Prefer update when more than one writer (separate processes, or spawned tasks) can touch one store.
Import with import "flatdb.j" as flatdb;. See the flatdb guide for prose and examples.
Contents
| Name | What it is |
|---|---|
append | Push value onto the list addressed by pointer, returning a new DB. |
get | Return the sub-document at pointer (the whole document for ""). |
getOr | Return the sub-document at pointer, or fallback when the pointer does not resolve - the has + get pai... |
has | Report whether pointer resolves to an existing node. |
keys | List the keys of the object at pointer, in document order. |
length | Return the element count of a list, or entry count of an object, at pointer. |
lock | Take the advisory write lock for the store backed by dbPath, blocking (with a short poll) until it is fre... |
lockWith | lock with the caller's own wait bound: block (with a short poll) for at most waitMs milliseconds for a ... |
open | Load the JSON document at path into a DB. |
openString | Load a DB from an in-memory JSON string instead of a file - for a database fetched over the network (... |
openWith | open with a size cap: refuse a file larger than maxBytes before decoding it, for a store whose size ano... |
remove | Drop the key or element at pointer, returning a new DB. |
save | Write the document back to its own backing file, crash-atomically (temp + rename), and return a fresh DB re... |
saveAs | Write the document to path (not necessarily its own) and return a fresh DB bound to that path - the p... |
saveDefaults | The options save uses: compact JSON, no backup. |
saveWith | save with options: indented JSON (pretty) and a backup of the previous content (backup, kept as... |
set | Write value at pointer (upsert an object key / replace a list index), returning a new DB. |
unlock | Release a lock taken by lock, but only if this holder still owns it: if a stale-break already handed the ... |
update | Run a locked read-modify-write against the store at path: take the write lock, open the current docum... |
updateWith | update with the caller's own lock wait bound, as lockWith takes it. |
DB | struct: The value the caller holds: the file path plus the decoded document. |
Lock | struct: A held advisory lock, returned by lock and passed to unlock. |
SaveOptions | struct: How saveWith writes. |
Functions
append
flatdb.append(db as DB, pointer as string, value as json.Value)Push value onto the list addressed by pointer, returning a new DB. The list must already exist (create it first with set($db, ptr, json.list())).
db- the store to edit
pointer- the JSON Pointer to a list
value- the value to append
- Returns
DB - a new store with the element appended
- Throws
Error - when pointer does not resolve to an existing list
get
flatdb.get(db as DB, pointer as string)Return the sub-document at pointer (the whole document for "").
db- the store to read
pointer- the JSON Pointer
- Returns
json.Value - the node at pointer
- Throws
Error - when pointer does not resolve
getOr
flatdb.getOr(db as DB, pointer as string, fallback as json.Value)Return the sub-document at pointer, or fallback when the pointer does not resolve - the has + get pair in one call. Only a missing node falls back: a malformed pointer (one not starting with /) still throws.
db- the store to read
pointer- the JSON Pointer
fallback- what to return when nothing is at pointer
- Returns
json.Value - the node at pointer, or fallback
- Throws
Error - when pointer is malformed
has
flatdb.has(db as DB, pointer as string)Report whether pointer resolves to an existing node.
db- the store to read
pointer- the JSON Pointer
- Returns
bool - true when the node exists
keys
flatdb.keys(db as DB, pointer as string)List the keys of the object at pointer, in document order.
db- the store to read
pointer- the JSON Pointer to an object
- Returns
list of string - the object's keys
- Throws
Error - when pointer does not resolve to an object
length
flatdb.length(db as DB, pointer as string)Return the element count of a list, or entry count of an object, at pointer.
db- the store to read
pointer- the JSON Pointer to a list or object
- Returns
int - the element or entry count
- Throws
Error - when pointer does not resolve to a list or object
lock
flatdb.lock(dbPath as string)Take the advisory write lock for the store backed by dbPath, blocking (with a short poll) until it is free or LOCK_WAIT_MS elapses. Built on fs.writeNew (an atomic exclusive create), so it coordinates across processes, not just spawned tasks. A lock leaked by a crashed writer is broken after LOCK_STALE_SECONDS. Pair with unlock - or, better, use update, which brackets the whole read-modify-write and releases on every path. LOCK_WAIT_MS is 5000 (5 s); lockWith takes a different bound.
dbPath- the store's backing file path
- Returns
Lock - the held lock (pass to unlock)
- Throws
Error - kind "flatdb" if the lock cannot be taken within LOCK_WAIT_MS, or at once if the lock file cannot be created at all (no holder exists: a missing directory, a read-only mount, no write permission)
lockWith
flatdb.lockWith(dbPath as string, waitMs as int)lock with the caller's own wait bound: block (with a short poll) for at most waitMs milliseconds for a contended lock. 0 tries once and fails at once if the lock is held; a long bound lets a writer queue behind a slow one.
dbPath- the store's backing file path
waitMs- how long to wait for a held lock, in milliseconds (>= 0)
- Returns
Lock - the held lock (pass to unlock)
- Throws
Error - kind "flatdb" if
waitMsis negative, if the lock cannot be taken withinwaitMs, or at once if the lock file cannot be created at all
open
flatdb.open(path as string)Load the JSON document at path into a DB. A missing file yields an empty document (an empty object), so open never fails on a first run.
path- the backing file path
- Returns
DB - the loaded store
openString
flatdb.openString(text as string)Load a DB from an in-memory JSON string instead of a file - for a database fetched over the network (http.get(url, {}).body), embedded in the program, or built elsewhere. The returned DB has no backing path, so it is read-only: every reader verb works and the mutating verbs still return a fresh in-memory DB, but save throws (there is nowhere to write). Whitespace-only text yields an empty document, matching open on a missing file. This keeps flatdb transport-agnostic: it never imports http / net, so it stays fs-only and builds on both binaries; the caller brings the bytes.
text- the JSON document
- Returns
DB - a read-only store
openWith
flatdb.openWith(path as string, maxBytes as int)open with a size cap: refuse a file larger than maxBytes before decoding it, for a store whose size another party controls (an upload directory, a shared volume). At most maxBytes + 1 bytes are ever read, however large the file is or grows while being read. A missing file is an empty store, as for open.
path- the backing file path
maxBytes- the largest file accepted, in bytes (> 0)
- Returns
DB - the loaded store
- Throws
Error - kind "limit" if the file is larger than
maxBytes; kind "flatdb" ifmaxBytesis not positive; thefs/jsonerrorsopenthrows
remove
flatdb.remove(db as DB, pointer as string)Drop the key or element at pointer, returning a new DB.
db- the store to edit
pointer- the JSON Pointer to remove
- Returns
DB - a new store with the node removed
- Throws
Error - when pointer does not resolve
save
flatdb.save(db as DB)Write the document back to its own backing file, crash-atomically (temp + rename), and return a fresh DB rebound to the just-written file. A read-only DB (from openString, no backing file) has nowhere to write - use saveAs.
Conflict check: if the file changed since this DB was opened (a concurrent writer got there first), save throws a flatdb error instead of silently clobbering their write. The check runs again after the new file is written and synced, under the save lock (<path>.savelock, held only for that check and the rename), so no other save can slip in between. Re-open and retry, or - to serialize writers so no update is lost - use update. Because save returns the rebound DB, a program that saves the same handle repeatedly should thread it through ($db = flatdb.save($db);) so the next save checks against the file it wrote.
db- the store to persist
- Returns
DB - a fresh DB bound to the written file (its version is the new file's)
- Throws
Error - kind "flatdb" if the DB is read-only, if the document changed since it was opened, if the save lock stays held past SAVE_LOCK_WAIT_MS, or on a filesystem write / rename failure
saveAs
flatdb.saveAs(db as DB, path as string)Write the document to path (not necessarily its own) and return a fresh DB bound to that path - the passed-in db is unchanged (value semantics, like set / append / remove). Two uses: the first dump to disk of a read-only openString DB, and copying / forking an on-disk store to a new file (a snapshot or a new version). Which store is "current" for the next save is whichever handle you keep - reassign ($db = flatdb.saveAs($db, path);) to make the new file current, or hold both to keep the original too. Same crash-atomic temp+rename as save.
db- the store whose data to write
path- the destination file path
- Returns
DB - a new DB bound to
path(its data equalsdb's) - Throws
Error - kind "flatdb" if
pathis empty, or on a filesystem failure
saveDefaults
flatdb.saveDefaults()The options save uses: compact JSON, no backup.
- Returns
SaveOptions - the defaults
saveWith
flatdb.saveWith(db as DB, opts as SaveOptions)save with options: indented JSON (pretty) and a backup of the previous content (backup, kept as <path>.bak). The conflict check is the same as save's, and the backup is exactly the content it checked, written before the store is replaced; a first save, with no previous file, writes none.
db- the store to persist
opts- how to write (from
saveDefaults()) - Returns
DB - a fresh DB bound to the written file
- Throws
Error - kind "flatdb" as
save
set
flatdb.set(db as DB, pointer as string, value as json.Value)Write value at pointer (upsert an object key / replace a list index), returning a new DB. Strict: intermediate containers must already exist.
db- the store to edit
pointer- the JSON Pointer to write
value- the value to write (build scalars with
json.decode, objects and lists withjson.map/json.list) - Returns
DB - a new store with the write applied
- Throws
Error - when an intermediate container does not exist
unlock
flatdb.unlock(lk as Lock)Release a lock taken by lock, but only if this holder still owns it: if a stale-break already handed the lock to another writer, unlock does nothing (it never removes a lock it no longer holds).
lk- the lock returned by lock
- Returns
null
update
flatdb.update(path as string, transform as func)Run a locked read-modify-write against the store at path: take the write lock, open the current document under it, apply transform, save, and release the lock - on every exit path (via defer). This is the safe way to update a store that concurrent writers (separate processes, or spawned tasks) may also write: because the read and the write are one locked span, no update is lost and save cannot conflict. transform is a func value func(db as DB) -> DB - edit the DB it receives with set / append / remove and return the result.
The lock is advisory and has no lease renewal: a lock older than LOCK_STALE_SECONDS (120 s) is taken for a crashed writer's and broken, so transform must finish well inside that, and should not do slow I/O.
path- the store's backing file path
transform- func(db as DB) -> DB, the edit to apply under the lock
- Returns
DB - the saved DB (its version is the freshly-written file's)
- Throws
Error - kind "flatdb" if the lock cannot be taken, if
transformreturns a DB bound to another file, or on a write failure
updateWith
flatdb.updateWith(path as string, waitMs as int, transform as func)update with the caller's own lock wait bound, as lockWith takes it.
path- the store's backing file path
waitMs- how long to wait for a held lock, in milliseconds (>= 0)
transform- func(db as DB) -> DB, the edit to apply under the lock
- Returns
DB - the saved DB (its version is the freshly-written file's)
- Throws
Error - kind "flatdb" as
update, and ifwaitMsis negative
Structs
DB
The value the caller holds: the file path plus the decoded document. A module holds no mutable state and spawn deep-copies scope, so a store cannot be a shared open connection - it is a value. Mutating verbs return a fresh DB; save is the only side effect.
def struct DB {
path as string,
data as json.Value,
version as string
};path- the backing file path (empty for a read-only DB from openString)
data- the decoded in-memory document
version- an opaque token of the file's content at open (a SHA-256 of the text), so
savecan detect a concurrent write (empty when there was no backing file)
Lock
A held advisory lock, returned by lock and passed to unlock. Carries the lock file path and this holder's unique id, so unlock removes only a lock this holder still owns (never one a stale-break has handed to another writer).
def struct Lock {
path as string,
holder as string
};path- the lock file path
holder- this holder's unique id ("<uuid> <unix-seconds>")
SaveOptions
How saveWith writes. Start from saveDefaults() and change the fields you need, so a field added later does not break your code.
def struct SaveOptions {
pretty as bool,
backup as bool
};pretty- indent the JSON (
json.encodePretty) for a file people read or edit by hand; false writes it compact backup- before replacing the file, keep its previous content as
<path>.bak, itself written crash-atomically with the store's permissions