db/kv
lib/db/kv.vklib/db/kv.vk
Pure-Veko crash-safe embedded transactional key-value store over positioned OS file I/O
(os/open, os/pread, os/pwrite, os/fsync, os/truncate, os/rename, os/close).
Features CRC-32-verified WAL framing, automatic crash-tail truncation on open,
atomic multi-op batches, log compaction, sorted prefix scans, codec/vbin typed values,
and optional at-rest AES-256-GCM encryption via crypto/seal.
Requires .fs capability.
KvStore = struct { path str, fd i64, write_off i64, entries map[bytes], durable bool, wal_records i64 }
Open handle to an embedded crash-safe KV store.
BatchOp = struct { op enum, key str, val bytes = ... }
Single batch mutation (op = .put or .del).
open = fn [path str] KvStore
Opens or creates a durable (fsync-on-write) crash-safe KV store at path.
use [kv = db/kv]
p = str/join [(os/temp-dir) '/veko_kv_doctest_1.vkkv'] ''
_ = os/remove/or p [.ok]
mut db = kv/open p
_ = kv/put-val mut db 'user:1' { name = 'Ada', score = 99 }
_ = kv/close mut db
mut db2 = kv/open p
u = kv/get-val db2 'user:1'
_ = kv/close mut db2
_ = os/remove/or p [.ok]
if u.name != 'Ada' or u.score != 99 [ err 'kv reopen' ] else [ .ok ]
open-fast = fn [path str] KvStore
Opens or creates a KV store with deferred fsync (call kv/sync to flush durability).
put-bytes = fn [mut db KvStore, key str, val bytes] enum
Stores raw bytes under key with CRC-32 WAL framing.
get-bytes = fn [db KvStore, key str] bytes
Retrieves raw bytes for key, or returns err if absent (combine with /or).
put-val = fn [mut db KvStore, key str, val any] enum
Stores any Veko value (i64, str, bytes, block, map, etc.) encoded via codec/vbin.
get-val = fn [db KvStore, key str] any
Retrieves and decodes a codec/vbin value stored under key.
scan-prefix = fn [db KvStore, prefix str] block[str]
Returns all live keys starting with prefix in deterministic sorted order.
use [kv = db/kv]
p = str/join [(os/temp-dir) '/veko_kv_doctest_2.vkkv'] ''
_ = os/remove/or p [.ok]
mut db = kv/open-fast p
_ = kv/put-bytes mut db 'cfg/a' (bytes/from-str '1')
_ = kv/put-bytes mut db 'cfg/b' (bytes/from-str '2')
_ = kv/put-bytes mut db 'other/x' (bytes/from-str '3')
ks = kv/scan-prefix db 'cfg/'
_ = kv/close mut db
_ = os/remove/or p [.ok]
if (len ks) != 2 or ks[0] != 'cfg/a' or ks[1] != 'cfg/b' [ err 'scan-prefix' ] else [ .ok ]
batch = fn [mut db KvStore, ops block[BatchOp]] enum
Atomically commits a batch of BatchOp puts/deletes in a single WAL write + fsync.
put-sealed = fn [mut db KvStore, key str, enc_key32 bytes, plaintext bytes] enum
Encrypts plaintext with AES-256-GCM (crypto/seal, binding key as AAD) and stores the sealed envelope.
with-open-sealed = fn [db KvStore, key str, enc_key32 bytes, use_fn fn[bytes->any]] any
Unseals an encrypted entry under enc_key32, passes plaintext to use_fn, and zeroizes it on exit.
compact = fn [mut db KvStore] enum
Compacts the WAL by rewriting only live keys into a temporary file, syncing, atomically renaming, and reopening.