libk  kdb.md at [f37ee769c9]

File mod/kdb/kdb.md artifact 1c2867c8a9 part of check-in f37ee769c9


# kdb

kdb is a module for storing and loading data from files.

## model

the first argument to all kdb functions is of type `struct kdb`, which describes the database to be accessed. the first field of that struct is a pointer to a struct of type `struct kdb_fmt` which describes the format of the database.

kdb encodes records as a tuple of three fields: (kind, key, value). `kind` is a 16-bit integer, `key` is an integer of platform width, and `value` is a blob decoded according to the type of the record, which is not saved in the database itself. records are indexed by the tuple (kind, key); `key` may be null. `kind` denotes the structure of the record, and is user-defined.

to use strings as the keys for database entries, either atoms should be stored in the database or a hash function may be used. kdb contains procedures to automate the use of atoms as keys.

## types

### struct kdb

 * `struct kdb_fmt* fmt`
 * `enum kdb_conn conn`
 * `union { kfile* file; const kdb_store* mem; kmptr ptr; } store;`

### struct kdb_rec

 * `u16 kind`
 * `word key`
 * `ksraw value`

### enum kdb_conn

 * `kdb_conn_none`: no database is connected; calls will fail
 * `kdb_conn_file`: the database is stored in a file; calls to modify it will modify the file on-disk
 * `kdb_conn_file_static`: the database is stored in a file; calls to modify it will fail. if the file is writable to the process, can be seamlessly changed to `kdb_conn_file` and vice-versa
 * `kdb_conn_mem`: the database is stored in-memory, allocated by kmem and referenced by `ptr`. calls to modify it will re-allocate memory via the appropriate interfaces.
 * `kdb_conn_mem_static`: the database is stored in-memory, referenced by `mem`; calls to modify it will fail