NOTE: Issues tracker is disabled. You are welcome to contribute, pull requests accepted.
EJDB2 is an embeddable JSON database engine published under MIT license.
The Story of the IT-depression, birds and EJDB 2.0
- C11 API
- Single file database
- Online backups support
- Simple but powerful query language
- Support of collection joins
- Powered by IOWOW - The persistent key/value storage engine
- HTTP REST/Websockets endpoints powered by IWNET
- Native language bindings
- Supported platforms
- JQL query language
- Indexes and performance
- Network API
- C API
- License
- EJDB 2.0 core engine is well tested and used in various heavily loaded deployments
- Tested on
Linux,macOSandFreeBSD.
Prerequisites
- Linux, macOS or FreeBSD
- gcc or clang compiler
- pkgconf or pkg-config
Build by Autark
./build.shTesting and sanitizers
# Build and run the test cases
./build.sh -DEJDB_RUN_TESTS=1
# Address sanitizer / undefined behavior sanitizer builds
./build.sh -DENABLE_ASAN=1 -DEJDB_RUN_TESTS=1
./build.sh -DENABLE_UBSAN=1 -DEJDB_RUN_TESTS=1ENABLE_ASAN and ENABLE_UBSAN can be enabled together.
Installation
./build.sh --prefix=$HOME/.localEJDB query language (JQL) is designed for querying and updating sets of JSON documents.
Its syntax is inspired by ideas behind XPath and Unix shell pipes: a query is a chain of
|-separated sections that filter documents, modify them, project a subset of fields, and
finally tune the result set.
The JQL parser is generated by
peg/leg — recursive-descent parser generators for C.
The formal parser grammar is jqp.leg.
The overview below is a readable equivalent of that grammar; jqp.leg is the source of
truth whenever they disagree.
Notation used below is based on SQL syntax description:
| Rule | Description |
|---|---|
' ' |
String in single quotes denotes a keyword or a punctuation character of the query. |
{ a | b } |
Curly brackets enclose two or more required alternative choices, separated by vertical bars. |
[ ] |
Square brackets indicate an optional element or clause. |
| |
Vertical bars separate two or more alternative syntax elements. |
... |
Ellipses indicate that the preceding element can be repeated. |
( ) |
Parentheses are grouping symbols. |
| Unquoted word in lower case | Denotes a semantic part of the query. For example: placeholder_name — name of a placeholder. |
QUERY = ( FILTEREXPR | FILTER_PK )
[ '|' ( APPLY | UPSERT | 'del' ) ]
[ '|' PROJECTIONS ]
[ '|' OPTS ];
FILTEREXPR = FILTERFACTOR { FILTERJOIN FILTERFACTOR };
FILTERFACTOR = FILTER | '(' FILTEREXPR ')';
FILTERJOIN = ( 'and' | 'or' ) [ 'not' ];
FILTER = [ '@' collection_name ] NODE { NODE };
FILTER_PK = [ '@' collection_name ] '/' '=' ( PLACEHOLDER | NUMBER | NUMBER_ARRAY );
NODE = '/' ( STR | STRP | NEXPR );
NEXPR = '[' NEXPAIR { NEXJOIN NEXPAIR } ']';
NEXPAIR = NEXLEFT NEXOP NEXRIGHT;
NEXLEFT = '**' | '*' | STR | STRP | NEXPRLEFT;
NEXPRLEFT = '[' '*' NEXOP NEXRIGHT ']';
NEXRIGHT = PLACEHOLDER | JSON_VALUE | STRP;
NEXJOIN = ( 'and' | 'or' ) [ 'not' ];
NEXOP = [ 'not' ] ( 'in' | 'ni' | 're' )
| '>=' | 'gte' | '<=' | 'lte' | '>' | 'gt' | '<' | 'lt'
| [ '!' ] ( '=' | 'eq' | '~' );
APPLY = 'apply' ( PLACEHOLDER | JSON_OBJECT | JSON_ARRAY );
UPSERT = 'upsert' ( PLACEHOLDER | JSON_OBJECT | JSON_ARRAY );
PROJECTIONS = PROJNODES { ( '+' | '-' ) PROJNODES };
PROJNODES = 'all' | PROJNODE { PROJNODE };
PROJNODE = '/' ( '{' PROJPROP { ',' PROJPROP } '}' | PROJPROP );
PROJPROP = STR | STRP | PLACEHOLDER | join_prop;
OPTS = OPT { OPT };
OPT = 'skip' ( NUMBER | PLACEHOLDER )
| 'limit' ( NUMBER | PLACEHOLDER )
| 'count'
| 'noidx'
| 'inverse'
| ( 'asc' | 'desc' ) ( ORDERNODES | PLACEHOLDER );
ORDERNODES = ORDERNODE { ORDERNODE };
ORDERNODE = '/' PROJPROP;
STR = quoted string;
STRP = unquoted string;
PLACEHOLDER = ':' ( placeholder_name | '?' );
join_prop = field_name '<' collection_name;
JSON_VALUEis any valid JSON value: object, array, string, number, boolean, ornull.STRis a double-quoted string with JSON escapes, e.g."John Doe","a.b".STRPis an unquoted string. It cannot contain spaces, tabs, newlines, or any of/ " [ ] = > < ! ( ). Use a quoted string for anything else.join_propis recognized at runtime: a projection property containing<is treated as a join (see JQL collection joins).json_pathused below is a simplified JSON pointer, e.g./foo/baror/"bar with spaces".
A query consists of up to four |-separated sections, always in this order:
- Filters (required) — select documents.
- Modification (
apply,upsert, ordel) — change matched documents. - Projections — return only a subset of each document.
- Options (
skip,limit,count,noidx,inverse,asc/desc) — affect the result set. All options belong to the same section:| asc /age limit 2, not| asc /age | limit 2.
Any of the last three sections can be omitted.
Let's play with some basic data and queries.
For simplicity we use the EJDB HTTP/WebSocket server (jbs), which also provides an
interactive wscat client. The same queries work through the C API
(ejdb2.h, jql.h) and the language bindings.
NOTE: See the JQL tests for more examples.
{
"firstName": "John",
"lastName": "Doe",
"age": 28,
"pets": [
{"name": "Rexy rex", "kind": "dog", "likes": ["bones", "jumping", "toys"]},
{"name": "Grenny", "kind": "parrot", "likes": ["green color", "night", "toys"]}
]
}Start the server:
./jbs -a 'myaccess01'
8 Mar 16:15:58.601 INFO: HTTP/WS endpoint at localhost:9191Documents can be added over HTTP:
# Document 1
curl -d '{"firstName":"John","lastName":"Doe","age":28,"pets":[{"name":"Rexy rex","kind":"dog","likes":["bones","jumping","toys"]},{"name":"Grenny","kind":"parrot","likes":["green color","night","toys"]}]}' \
-H'X-Access-Token:myaccess01' -X POST http://localhost:9191/family
# Document 2
curl -d '{"firstName":"Jack","lastName":"Parker","age":35,"pets":[{"name":"Sonic","kind":"mouse","likes":[]}]}' \
-H'X-Access-Token:myaccess01' -X POST http://localhost:9191/family
# Document 3
curl -d '{"firstName":"John","lastName":"Ryan","age":39,"tags":["a","bestseller"],"meta":{"x":{"y":7}},"active":true,"score":1.5,"nil":null}' \
-H'X-Access-Token:myaccess01' -X POST http://localhost:9191/familyThe interactive wscat client is handy for experimenting:
wscat -H 'X-Access-Token:myaccess01' -c http://localhost:9191
connected (press CTRL+C to quit)
> k @family/*
< k 3 {"firstName":"John","lastName":"Ryan","age":39,"tags":["a","bestseller"],"meta":{"x":{"y":7}},"active":true,"score":1.5,"nil":null}
< k 2 {"firstName":"Jack","lastName":"Parker","age":35,"pets":[{"name":"Sonic","kind":"mouse","likes":[]}]}
< k 1 {"firstName":"John","lastName":"Doe","age":28,"pets":[{"name":"Rexy rex","kind":"dog","likes":["bones","jumping","toys"]},{"name":"Grenny","kind":"parrot","likes":["green color","night","toys"]}]}The k prefix is an arbitrary key chosen by the client. It is returned with the response
and lets the client match a response to its request.
More info
A query can also be executed over HTTP:
curl --data-raw '@family/[firstName = John]' -H'X-Access-Token:myaccess01' -X POST http://localhost:9191
1 {"firstName":"John","lastName":"Doe","age":28,"pets":[...]}The collection can be supplied by the command (k query <collection> <query>) or
in the query itself (@collection/...). Most examples below are shown as typed in
wscat and include the k prefix; blocks without a > prompt show the plain JQL
text. The @family anchor is required when a query is executed over HTTP or through
the ejdb2 API without an explicit collection name.
@collection/... selects the collection. A query is always executed against one
collection — the first anchor in the query is used.
> k @family/*/* and /** as the only path node also match every document.
A path without an expression matches documents where the path exists:
> k @family/tags
< k 3 {"firstName":"John","lastName":"Ryan","age":39,"tags":["a","bestseller"],...}
> k @family/pets
< k 2 {"firstName":"Jack","lastName":"Parker","age":35,"pets":[...]}
< k 1 {"firstName":"John","lastName":"Doe","age":28,"pets":[...]}
> k @family/nil
< k 3 {"firstName":"John","lastName":"Ryan","age":39,...,"nil":null}| Node | Matches |
|---|---|
/field |
Object key field (exact name). Array element position when the parent is an array. |
/"quoted name" |
Object key with spaces or special characters. |
/* |
Any key name at exactly one nesting level (and any array element). |
/** |
Any key name at any nesting level, including zero levels. |
/0, /1, ... |
Array element at the given zero-based position. |
# Element at index 1 of every `likes` array
> k @family/pets/*/likes/1
< k 1 {"firstName":"John","lastName":"Doe",...}
# Name of the first pet
> k @family/pets/0/name
< k 2 {"firstName":"Jack","lastName":"Parker",...}
< k 1 {"firstName":"John","lastName":"Doe",...}A node is treated as a field name. If a field name contains spaces or characters that are special in JQL, use a double-quoted string:
> k @family/"a.b"Keys that look like numbers are matched literally (/10 addresses a key named 10,
not array position 10).
Expressions are written in square brackets: [ <left> <operator> <right> ].
An expression is applied to the children of the level reached by the path in front of
it. So /[age > 20] checks the root-level age field, while /pets/*/[kind = dog]
checks the fields of every object of the pets array.
/pets/*/[name = "Rexy rex"]
/pets/*/[name eq "Rexy rex"]
/pets/*/[name = "Rexy rex" or name = Grenny]NOTE: strings with spaces must be quoted.
Get documents where the owner age is greater than 20 and that have a pet
who likes bones or toys:
/[age > 20] and /pets/*/likes/[** in ["bones", "toys"]]Here ** as the left operand denotes any value of the current level — an element of
the likes array.
ni tests array membership with the operands reversed: array ni value is true when
the document field is an array containing value.
# Documents where `bones` is somewhere in one of the `likes` arrays
/pets/*/[likes ni "bones"]Conditions can be grouped with parentheses:
(/[age <= 20] or /[lastName re "Do.*"]) and /pets/*/likes/[** in ["bones", "toys"]]~ is a prefix matching operator (since ejdb v2.0.53).
Prefix matching can benefit from an index.
# Documents where `/lastName` starts with "Do"
/[lastName ~ Do]| Operator | Aliases | Description |
|---|---|---|
= |
eq |
Equal |
!= |
!eq |
Not equal |
> |
gt |
Greater than |
>= |
gte |
Greater than or equal |
< |
lt |
Less than |
<= |
lte |
Less than or equal |
~ |
String prefix match | |
!~ |
String prefix mismatch | |
re |
Regular expression match | |
not re |
Regular expression mismatch | |
in |
The document value is equal to an element of the given JSON array | |
not in |
The document value is not equal to any element of the given JSON array | |
ni |
The document array value contains the given value | |
not ni |
The document array value does not contain the given value |
! negation is accepted only for =, eq, and ~.
in, ni, and re are negated with the not keyword.
Examples:
/[firstName = John]
/[firstName eq John]
/[firstName != John]
/[firstName !~ Jo]
/[lastName re "Do.*"]
/[lastName not re "Do.*"]
/[age in [28, 35]]
/[age not in [28, 35]]
/[tags ni bestseller]
/[tags not ni bestseller]Filter documents with a likes array exactly matching ["bones","jumping","toys"]:
/**/[likes = ["bones","jumping","toys"]]Matching algorithms for arrays and maps are different:
- Array elements are matched from start to end. In equal arrays all values at the same index must be equal.
- Object maps matching consists of the following steps:
- Lexicographically sort object keys in both maps.
- Match the keys and their values starting from the lowest key.
- If all corresponding keys and values in one map fully match the ones in the other map
and vice versa, the maps are considered equal.
For example
{"f":"d","e":"j"}and{"e":"j","f":"d"}are equal maps.
A document array value is not equal to a scalar, so /[tags = bestseller] never matches
an array tags. Use /[tags ni bestseller] or /tags/[** = bestseller] instead.
A document object value is not equal to a scalar either.
Find JSON documents having a firstName key at the root level. In this context *
denotes a key name:
/[* = "firstName"]** on the left side compares values instead of key names. To reach keys at any depth,
put a ** path node in front of the expression:
# Documents that have a key named `firstName` anywhere
/**/[* = "firstName"]You can test a key name and a key value at the same time:
# Document has the `firstName` key with the `John` value
/[[* = "firstName"] = John]The key name can be either firstName or lastName, but the value must be John:
/[[* in ["firstName", "lastName"]] = John]This is especially useful with dynamic placeholders (C API):
/[[* = :keyName] = :keyValue]Filters are combined with and / or / not:
/[firstName = John] and /[age = 28]
/[firstName = John] and not /[age = 28]NOTE: a filter (including a negated one) matches only existing JSON fields.
/[age != 28] will not match a document without age. To select documents that
lack a field, combine an existing condition with a negated one:
/[firstName = John] and not /[age = 28]The conditions of a filter are evaluated left to right. A satisfied or operand
completes the filter immediately, so the remaining conditions of that filter are not
evaluated. Parenthesize expressions when combining or with and:
# (a or b) and c
(/[age < 30] or /[age > 40]) and @family/[lastName = Doe]Parentheses must be written without spaces next to the filters:
(/[a] or /[b]) and ....
Filters inside a single expression are also joined:
/[firstName = John and age = 39]Such an expression matches when all conditions hold for the same object, even if they refer to different fields.
Placeholders :name (or :? for the next free index) can be used instead of any
JSON value in an expression, ordering clause, or skip/limit option.
Placeholders are bound by the client API only; they cannot be bound over HTTP/WebSocket.
const q = db.createQuery('@users/[name = :name] and /[age > :age]');
q.setString('name', 'John');
q.setNumber('age', 20);A primary key query is a special query form that cannot be combined with other filters:
FILTER_PK = [ '@' collection_name ] '/' '=' ( PLACEHOLDER | NUMBER | NUMBER_ARRAY );
In order to get documents by primary key the following options are available:
-
Use the API call
ejdb_get():const doc = await db.get('users', 112);
-
Use the special query construction
/=:?,/=112, or@collection/=112:> k @users/=112Update the
tagsarray of a document in thejobscollection (TypeScript):await db.createQuery('@jobs/=:? | apply :? | count') .setNumber(0, id) .setJSON(1, { tags }) .completionPromise();
An array of primary keys also matches:
> k @users/=[112,113,114]await db.createQuery('@jobs/=[1,2,3] | apply :? | count') .setJSON(0, { tags }) .completionPromise();
JQL is a dynamically typed query language. The document value is always the left operand.
- Integers and floating point numbers are compared numerically.
- A string is compared lexicographically with another string.
- Booleans are compared as
0/1against numbers, sotrue = 1andfalse = 0. nullequalsnulland an empty string.- If the document value is a number and the query value is a quoted string, the string
is converted to a number:
/[age = "28"]matches"age": 28. - If the document value is a string and the query value is a number, the number's text representation is compared with the string.
Values of incompatible types (an object or array against a scalar) do not match.
A negated comparison (!=, !~, not re) matches in that case.
NOTE: mixing types is a common source of surprises. Always compare numbers with numbers.
The modification section is responsible for changing the content of matched documents.
APPLY = 'apply' ( PLACEHOLDER | JSON_OBJECT | JSON_ARRAY );
If a JSON object follows apply, it is treated as an
RFC 7386 merge patch. If a JSON array follows,
it is treated as an RFC 6902 JSON patch.
Placeholders are also supported.
For the modification examples we use a separate jobs collection, so the family
documents from the previous sections are not changed:
> k add jobs {"title":"Coding","tags":["dev"],"counter":1}
< k 1
> k add jobs {"title":"Cleaning","tags":[]}
< k 2Add a priority field to all matched documents (RFC 7386 merge patch):
> k @jobs/[title = Coding] | apply {"priority": 10}
< k 1 {"title":"Coding","tags":["dev"],"counter":1,"priority":10}Append a value to the tags array (RFC 6902 patch, - means the end of an array):
> k @jobs/[title = Coding] | apply [{"op":"add", "path":"/tags/-", "value":"home"}]
< k 1 {"title":"Coding","tags":["dev","home"],"counter":1,"priority":10}Increments the numeric value identified by the JSON path by the specified value.
Document: {"foo": 1}
Patch: [{"op": "increment", "path": "/foo", "value": 2}]
Result: {"foo": 3}
> k @jobs/[title = Coding] | apply [{"op":"increment", "path":"/counter", "value":41}]
< k 1 {"title":"Coding","tags":["dev","home"],"counter":42,"priority":10}Same as the JSON patch add, but creates intermediate object nodes for missing JSON
path segments.
Document: {"foo": {"bar": 1}}
Patch: [{"op": "add_create", "path": "/foo/zaz/gaz", "value": 22}]
Result: {"foo":{"bar":1,"zaz":{"gaz":22}}}
Document: {"foo": {"bar": 1}}
Patch: [{"op": "add_create", "path": "/foo/bar/gaz", "value": 22}]
Result: Error, since the element pointed to by /foo/bar is not an object
> k @jobs/[title = Coding] | apply [{"op":"add_create", "path":"/meta/info/level", "value":3}]
< k 1 {"title":"Coding",...,"meta":{"info":{"level":3}}}Swaps two values of a JSON document starting from the from path.
Swapping rules:
- If the value pointed to by
fromdoes not exist, an error is raised. - If the value pointed to by
pathdoes not exist, it is set to the value fromfrom, and then the value pointed to byfromis removed. - If both values exist, they are swapped.
Document: {"foo": ["bar"], "baz": {"gaz": 11}}
Patch: [{"op": "swap", "from": "/foo/0", "path": "/baz/gaz"}]
Result: {"foo": [11], "baz": {"gaz": "bar"}}
Document: {"foo": ["bar"], "baz": {"gaz": 11}}
Patch: [{"op": "swap", "from": "/foo/0", "path": "/baz/zaz"}]
Result: {"foo":[],"baz":{"gaz":11,"zaz":"bar"}}
> k @jobs/[title = Coding] | apply [{"op":"swap", "from":"/tags/0", "path":"/priority"}]
< k 1 {"title":"Coding","tags":[10,"home"],"counter":42,"priority":"dev",...}upsert updates an existing document using the given JSON argument as a merge patch,
or inserts the argument as a new document when nothing is matched:
> k @jobs/[title = Gardening] | upsert {"title":"Gardening","tags":["outdoor"]}
< k 3 {"title":"Gardening","tags":["outdoor"]}The returned document has the identifier of the inserted or updated document.
Use the del keyword to remove matched elements from the collection:
> k @jobs/[title = Cleaning] | del
< k 2 {"title":"Cleaning","tags":[]}
> k @jobs/* | /title
< k 3 {"title":"Gardening"}
< k 1 {"title":"Coding"}The modified documents are returned as the query result. Add count to the options
section to avoid transferring and converting them:
> k @jobs/* | apply {"seen": true} | count
< k 2Projections allow you to get only a subset of a JSON document, excluding unneeded data.
Query placeholders are supported in projections. Add count to the options if
you only need the number of matched documents.
Projection forms:
# Whole document
/* | all
# Field set: selected root fields
/* | /{firstName,lastName}
# Nested path
/* | /meta/x/y
# Array element or wildcard
/* | /pets/0
/* | /pets/*/name
# Combine and exclude
/* | /{firstName,lastName} + /pets
/* | all - /petsLet's query only the pet owners' firstName and lastName:
> k @family/* | /{firstName,lastName}
< k 3 {"firstName":"John","lastName":"Ryan"}
< k 2 {"firstName":"Jack","lastName":"Parker"}
< k 1 {"firstName":"John","lastName":"Doe"}Add the pets array to every document:
> k @family/* | /{firstName,lastName} + /pets
< k 3 {"firstName":"John","lastName":"Ryan"}
< k 2 {"firstName":"Jack","lastName":"Parker","pets":[...]}
< k 1 {"firstName":"John","lastName":"Doe","pets":[...]}Exclude only the pets field from documents:
> k @family/* | all - /pets
< k 3 {"firstName":"John","lastName":"Ryan","age":39,...}
< k 2 {"firstName":"Jack","lastName":"Parker","age":35}
< k 1 {"firstName":"John","lastName":"Doe","age":28}Fields are returned in the order they appear in the document, not in the order they are listed in the projection. A document that has none of the requested paths produces an empty object:
> k @family/* | /meta
< k 3 {"meta":{"x":{"y":7}}}
< k 2 {}
< k 1 {}A join materializes a reference to a document into the real document object, replacing the reference in place. Documents are joined by their primary keys only. Reference keys are stored in the referring document as a number or a string field.
Joins can be specified as part of a projection expression in the following form:
/.../field<collection
Where:
field— JSON field containing the primary key of the joined document.<— the special mark symbol that instructs the EJDB engine to replace thefieldkey with the body of the joined document.collection— name of the DB collection where the joined documents are located.
Here is a simple demonstration of collection joins in the interactive websocket shell:
> k add artists {"name":"Leonardo Da Vinci", "years":[1452,1519]}
< k 1
> k add paintings {"name":"Mona Lisa", "year":1490, "artist": 1}
< k 1
> k add paintings {"name":"Last Supper", "year":1498, "artist": 1}
< k 2
# List paintings documents
> k @paintings/*
# Do a simple join with the artists collection
> k @paintings/* | /artist<artists
< k 2 {"name":"Last Supper","year":1498,"artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}
< k 1 {"name":"Mona Lisa","year":1490,"artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}
# Strip all document fields except `name` and the `artist` join
> k @paintings/* | /artist<artists + /name + /artist/*
< k 2 {"name":"Last Supper","artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}
< k 1 {"name":"Mona Lisa","artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}
# Same result as above:
> k @paintings/* | /{name, artist<artists} + /artist/*An unresolved reference behaves differently depending on the projection form:
- A plain join projection (
/artist<artists) leaves the unresolved reference untouched. - A join inside a field set (
/{name, artist<artists}) drops the field.
> k add paintings {"name":"Lost Work", "year":1500, "artist": 999}
< k 3
> k @paintings/* | /artist<artists
< k 3 {"name":"Lost Work","year":1500,"artist":999}
< k 2 {"name":"Last Supper","year":1498,"artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}
< k 1 {"name":"Mona Lisa","year":1490,"artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}
> k @paintings/* | /{name, artist<artists}
< k 3 {"name":"Lost Work"}
< k 2 {"name":"Last Supper","artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}
< k 1 {"name":"Mona Lisa","artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}A string primary key reference is also accepted:
> k add paintings {"name":"String Ref", "year":1501, "artist": "1"}
< k 4
> k @paintings/[name = "String Ref"] | /artist<artists
< k 4 {"name":"String Ref","year":1501,"artist":{"name":"Leonardo Da Vinci","years":[1452,1519]}}OPT = ( 'asc' | 'desc' ) ( ORDERNODES | PLACEHOLDER )
Add one more document and sort documents by firstName ascending and age
descending:
> k add family {"firstName":"John", "lastName":"Ryan2", "age":39}
< k 4
> k @family/* | /{firstName,lastName,age} | asc /firstName desc /age
< k 2 {"firstName":"Jack","lastName":"Parker","age":35}
< k 4 {"firstName":"John","lastName":"Ryan2","age":39}
< k 3 {"firstName":"John","lastName":"Ryan","age":39}
< k 1 {"firstName":"John","lastName":"Doe","age":28}Sorting clauses are applied in the order they are written. Documents with equal values of all ordering paths keep an implementation-defined order.
asc/desc may use an index defined for a collection to avoid a separate document
sorting stage. At most 64 ordering clauses are allowed.
All options are specified in a single | section:
> k @family/* | skip 1 limit 2skip n— skip the firstnrecords of the result set.limit n— set the maximum number of documents in the result set.limit 0means no limit.count— return only the number of matched documents:> k @family/* | count < k 4
countis applied afterskip/limit:Duplicate> k @family/* | skip 1 count < k 3
skiporlimitclauses are rejected with an error.noidx— do not use any index for query execution.inverse— by default a query scans documents from the most recently added to the older ones. This option inverts the scan direction and implicitly enablesnoidx. It has no effect if the query hasasc/descordering clauses.
> k @family/* | /{firstName,lastName} | inverse
< k 1 {"firstName":"John","lastName":"Doe"}
< k 2 {"firstName":"Jack","lastName":"Parker"}
< k 3 {"firstName":"John","lastName":"Ryan"}
< k 4 {"firstName":"John","lastName":"Ryan2"}Options may be listed in any order inside the section. Placeholders can be used
for skip and limit values.
A database index can be built for any JSON field path containing values of number or
string type. An index can be unique — disallowing value duplication — or non unique.
The following index mode bit mask flags are used (defined in ejdb2.h):
| Index mode | Description |
|---|---|
0x01 EJDB_IDX_UNIQUE |
Index is unique |
0x04 EJDB_IDX_STR |
Index for JSON string field values |
0x08 EJDB_IDX_I64 |
Index for 8 byte signed integer field values |
0x10 EJDB_IDX_F64 |
Index for 8 byte floating point field values |
For example, a unique index of string type is specified by
EJDB_IDX_UNIQUE | EJDB_IDX_STR = 0x05.
An index can be defined for only one value type located under a specific path in a
JSON document.
Let's define a non-unique string index for the /lastName path:
> k idx family 4 /lastName
< kIndex selection for queries is based on a set of heuristic rules.
You can always check index usage by issuing the explain command in the WS API:
> k explain family /[lastName=Doe]
< k explain [INDEX] MATCHED STR|3 /lastName EXPR1: 'lastName = Doe' INIT: IWKV_CURSOR_EQ
[INDEX] SELECTED STR|3 /lastName EXPR1: 'lastName = Doe' INIT: IWKV_CURSOR_EQ
[COLLECTOR] PLAINThe following statements are taken into account when using EJDB2 indexes:
-
Only one index can be used for a particular query execution.
explainreports all matched indexes and the one that was selected. -
If a query contains an
or-joined part at the top level of the query expression, or a negated expression at the top level, indexes are not used at all:# No index /[lastName != Doe] /[lastName = "John"] or /[lastName = Ryan] # Index is used /[lastName = Doe] /[lastName = Doe] and /[age = 28] /[lastName = Doe] and not /[age = 28] /[lastName = Doe] and /[age != 28] -
A filter path containing
*or**nodes is not indexable. Use a concrete path:# No index /**/[lastName = Doe] # Index is used /[lastName = Doe] -
The following operators are supported by indexes (ejdb 2.0.x and later):
eq,=gt,>gte,>=lt,<lte,<=in(unless the value list is large relative to the collection)~(prefix matching, string indexes only)
-
ORDERBYclauses may use an index to avoid result set sorting. Only the first ordering clause is eligible, and the index must match its path:> k explain family /* | asc /lastName [INDEX] SELECTED STR|3 /lastName INIT: IWKV_CURSOR_AFTER_LAST STEP: IWKV_CURSOR_PREV ORDERBY [COLLECTOR] PLAIN > k explain family /* | asc /firstName [INDEX] NO [COLLECTOR] SORTER -
Array fields can also be indexed. A typical use case is indexing entity tags:
> k add books {"name":"Mastering Ultra", "tags":["ultra", "language", "bestseller"]} > k add books {"name":"Learn something in 24 hours", "tags":["bestseller"]} > k idx books 4 /tags > k explain books /tags/[** in ["bestseller"]] [INDEX] MATCHED STR|4 /tags EXPR1: '** in ["bestseller"]' INIT: IWKV_CURSOR_EQ [INDEX] SELECTED STR|4 /tags EXPR1: '** in ["bestseller"]' INIT: IWKV_CURSOR_EQ [COLLECTOR] PLAIN
All documents in a collection are sorted by their primary key in descending order.
So if you use auto-generated keys (ejdb_put_new), documents returned by a full scan
query are ordered by insertion time in descending order, unless query sorting, indexes,
or the inverse keyword is used.
In many cases using an index may decrease overall query performance, because the index
collection contains only document references (id) and the engine has to fetch each
document by its primary key to finish query matching. For not so large collections a
brute force scan may perform better than an indexed scan. However, exact matching
operations eq and in, sorting by natural index order, and prefix matching usually
benefit from an index.
If you would like to update a set of documents with apply or del operations but do
not want to fetch all of them as the query result, add the count option: it avoids
unnecessary data transferring and JSON conversion.
The queries below demonstrate less obvious corners of JQL. They all run against the
family collection from the introduction plus one intentionally quirky document:
> k add family {"firstName":"Quirky","age":42,"emptyArr":[],"emptyObj":{},"matrix":[[1,2],[3,4]],"deep":{"deeper":{"needle":"found"}},"10":"ten","a.b":"dot","tmp_counter":1}
< k 51. Find documents by a key name at any depth. Indexes are not used here, but the query is convenient for unknown document schemas:
> k @family/**/[* re "^tmp_"]
< k 5 {"firstName":"Quirky",...,"tmp_counter":1}2. Find documents by a value several levels deep. ** can match zero or more
path levels:
> k @family/**/needle
< k 5 {"firstName":"Quirky",...,"deep":{"deeper":{"needle":"found"}},...}3. Find documents containing an empty array or an empty object. [** = []]
compares every value of the current level with an empty array:
> k @family/[** = []]
< k 5 {"firstName":"Quirky",...,"emptyArr":[],...}
> k @family/[** = {}]
< k 5 {"firstName":"Quirky",...,"emptyObj":{},...}4. Match nested arrays by position. matrix/1/0 is the first element of the second
row:
> k @family/matrix/1/0
< k 5 {"firstName":"Quirky",...,"matrix":[[1,2],[3,4]],...}5. Find a document where some array contains a value. ni works on any array value
reached by **:
> k @family/**/[** ni 1]
< k 5 {"firstName":"Quirky",...,"matrix":[[1,2],[3,4]],...}6. Match keys that look like numbers or contain dots. Such keys are ordinary keys:
> k @family/10
< k 5 {"firstName":"Quirky",...,"10":"ten",...}
> k @family/"a.b"
< k 5 {"firstName":"Quirky",...,"a.b":"dot",...}7. The first pet is a dog. Combine an array position with an expression:
> k @family/pets/0/[kind = dog]
< k 1 {"firstName":"John","lastName":"Doe",...}8. Prefix matching works on non-string values by comparing their text
representation. /[age ~ 2] matches 28, but not 35 or 39:
> k @family/[age ~ 2]
< k 1 {"firstName":"John","lastName":"Doe","age":28,...}9. Regex on numbers. Numeric values are converted to strings before the match,
so ^[23] matches every age whose text representation starts with 2 or 3:
> k @family/[age re "^[23]"]
< k 4 {"firstName":"John","lastName":"Ryan2","age":39}
< k 3 {"firstName":"John","lastName":"Ryan","age":39,...}
< k 2 {"firstName":"Jack","lastName":"Parker","age":35,...}
< k 1 {"firstName":"John","lastName":"Doe","age":28,...}Use ^[23][0-9]*$ to require a full match.
10. Value membership vs array membership. Note the difference:
# Documents whose `tags` array contains `bestseller`
> k @family/[tags ni bestseller]
< k 3 {"firstName":"John","lastName":"Ryan","tags":["a","bestseller"],...}
# Documents having a root-level value equal to `bestseller` (array elements are not visited)
> k @family/[** = bestseller]The second query returns nothing: ** compares values only at the level reached by the
path, and tags is a single array value. To descend into the array use /**/[** = ...]
with a ** path node.
11. Test two fields of the same object in one expression:
> k @family/[firstName = John and age = 39]
< k 4 {"firstName":"John","lastName":"Ryan2","age":39}
< k 3 {"firstName":"John","lastName":"Ryan","age":39,...}12. Key name and value together. Find documents where either firstName or
lastName equals John:
> k @family/[[* in ["firstName","lastName"]] = John]
< k 4 {"firstName":"John","lastName":"Ryan2",...}
< k 3 {"firstName":"John","lastName":"Ryan",...}
< k 1 {"firstName":"John","lastName":"Doe",...}13. Document lacks a field. Negate a filter; a nonexistent field never matches, so its negation matches:
> k @family/[age = 42] and not /[lastName = Doe]
< k 5 {"firstName":"Quirky","age":42,...}14. Grouped or plus a collection anchor. A leading group has no anchor, so put
@collection on one of the filters inside or after the group:
> k (/[age < 30] or /[age > 40]) and @family/pets/*/likes/[** = toys] and /[firstName = John]
< k 1 {"firstName":"John","lastName":"Doe","age":28,...}15. Bulk update with a count. Update documents and return only their count:
> k @family/[age > 30] | apply {"adult": true} | count
< k 4- Parentheses are whitespace sensitive.
( /[a] or /[b] )is a parse error. Write(/[a] or /[b]). orshort-circuits the rest of the filter. See Combining filters.- Array literals contain JSON values.
in [John]is invalid; usein ["John"]. - A missing field is not unequal to anything.
/[age != 28]needs an existingage; useand not /[age = 28]to select documents without the field. inandniare not interchangeable./[age in [28, 35]]tests a scalar against a list;/[tags ni bestseller]tests that an array contains a value.*is one level,**is any level. In a filter path*consumes one nesting level;**consumes any number of levels. In an expression, a*left operand compares key names, while**compares values.- All options go into one
|section.| asc /age | limit 2is invalid; write| asc /age limit 2. - Sections have a fixed order: filters, modification, projections, options.
- Unquoted strings are limited. Use
"..."for strings with spaces or with any of/ " [ ] = > < ! ( ). - Placeholders cannot be used over HTTP/WebSocket. They must be bound with the client API.
- Projection of a missing path yields
{}rather than an empty result document. orat the top level disables indexes. Split such queries or accept the scan.inverseor a filter with*/**disables indexes (inverseimpliesnoidx).- Numeric types are coerced.
true = 1andnull = ""are true; compare values of the same type.
The parser and matching behavior are covered by the tests in src/jql/tests and src/tests.
EJDB2 can expose its data over the network:
- REST API over HTTP.
- WebSocket API for interactive/persistent sessions.
- TLS (HTTP and WebSocket) with a PEM key and certificate.
The endpoint can be started either by the standalone jbs server or embedded into
an application through struct ejdb_http / jbr.h (see
Embedded HTTP server).
All document payloads are JSON; queries are written in JQL.
Usage: jbs [options]
-f, --file=<> Database file path. Default: ejdb2.db
-p, --port=NUM HTTP server port number. Default: 9191
-l, --listen=<> Network address to listen on. Default: localhost
-k, --key=<> PEM private key file for TLS 1.2
-c, --certs=<> PEM certificates file for TLS 1.2
-a, --access=TOKEN Access token expected in the X-Access-Token header
-r, --access-read Allow anonymous read-only access
-C, --cors Enable CORS response headers
-t, --trunc Cleanup/reset the database file on open
-w, --wal Enable the write-ahead log (WAL)
Advanced options:
-S, --sbz=NUM Max sorting buffer size, default: 16777216, min: 1048576
-D, --dsz=NUM Initial buffer size for documents processed during queries,
default: 65536, min: 16384
-T, --trylock Exit with an error if the database is locked by another
process instead of waiting for the lock
Notes:
-b, --bindis accepted as an alias of-l, --listenfor backward compatibility.jbsdisables the write-ahead log by default;-wturns it on. The embedded C API keeps WAL enabled unlessstruct ejdb_opts.no_walis set.- The access token is used as is; it is not read from a file.
Examples:
# Local server protected by an access token
./jbs -a 'myaccess01'
# Listen on all interfaces, allow anonymous reads, enable CORS
./jbs -l 0.0.0.0 -a 'myaccess01' -r -C
# TLS endpoint
./jbs -a 'myaccess01' -k server.key -c server.crtWhen an access token is configured (-a or struct ejdb_http.access_token), every
HTTP request and every WebSocket handshake must provide it in the X-Access-Token
header.
| Request | Result |
|---|---|
| Token missing, token required | 401 Unauthorized |
| Token provided but does not match | 403 Forbidden |
| Token valid | Request is processed |
With -r (--access-read, read_anon = true) an anonymous client (no token) may
perform read requests only:
GET/HEAD /{collection}/{id}andPOST /(query) are allowed.- A query that contains an
apply/upsert/delsection is rejected with403. - Any mutating request (
POST /{collection},PUT,PATCH,DELETE) is rejected with401. - Over WebSocket,
infoand all mutating commands are rejected withAccess denied (JBR_ERROR_WS_ACCESS_DENIED). OPTIONS /is not available anonymously (401).
A caller that provides a valid token is not limited by -r; the flag affects only
anonymous requests.
The same endpoint can be started by the ejdb2 library. Fill
struct ejdb_opts.http and set enabled = true:
struct ejdb_opts opts = {
.kv = { .path = "example.db" },
.http = {
.enabled = true,
.port = 9191,
.bind = "localhost", // Default: "localhost"
.access_token = "myaccess01", // Default: zero (no token required)
.access_token_len = 10,
.read_anon = true, // Allow anonymous read-only access
.cors = true, // Send CORS headers
.blocking = false, // false: serve in a background thread
.ssl_private_key = "server.key",
.ssl_certs = "server.crt",
.max_body_size = 0 // Default: 64Mb, minimum: 512K
}
};
struct ejdb *db;
iwrc rc = ejdb_open(&opts, &db);Behaviour:
- With
blocking = falsethe server runs in a background thread andejdb_open()returns immediately. - With
blocking = trueejdb_open()enters the server loop and returns only after the server is stopped (this is whatjbsdoes). ejdb_close()stops the embedded server and waits for it to finish.jbr.hexposes the server lifecycle directly for applications that need it:jbr_start(),jbr_shutdown_request(),jbr_shutdown_wait(),jbr_init().
- A collection name is a non-empty string of at most
EJDB_COLLECTION_NAME_MAX_LEN(255) bytes. - A document identifier is a positive
int64(>= 1). - Request paths are
/{collection}or/{collection}/{id}.{id}must be a decimal integer;0, a negative value, or a non-numeric value is rejected with400. - Missing or unparsable JSON bodies, invalid queries, and malformed paths produce
400 Bad Request. - Unknown documents produce
404 Not Found. - Internal failures produce
500. - Error responses have a
text/plainbody with a human readable description (for exampleNot FoundorFailed to parse JSON string (JBL_ERROR_PARSE_JSON)).
Responses to authorized requests include Access-Control-Allow-Origin: * when CORS
is enabled. Authentication failures (401/403) are produced before the request is
routed and do not carry CORS headers.
Add a new document to {collection}. The collection is created if it does not exist.
- Request body: JSON document.
200 OK,text/plainbody: the new document identifier as anint64number.
curl -s -X POST --data-raw '{"firstName":"John","age":28}' \
-H 'X-Access-Token: myaccess01' http://localhost:9191/family
1Retrieve a document.
200 OK,application/jsonbody: the document, pretty printed.404 Not Foundif the document (or the collection) does not exist.HEADreturns the same status and headers, includingContent-Length, without a body.400when the identifier is missing (GET /{collection}).
curl -s -H 'X-Access-Token: myaccess01' http://localhost:9191/family/1
{
"firstName": "John",
"age": 28
}Store a document under the given numeric identifier, replacing an existing document. The collection is created if it does not exist.
- Request body: JSON document.
200 OK,text/plainbody:OK.400for an invalid body or identifier.
Patch a document with an RFC 7396 merge patch (a JSON object) or an RFC 6902 JSON patch (a JSON array).
200 OK,text/plainbody:OK.400for an invalid patch.404if the document is not found.
Remove a document.
200 OK,text/plainbody:OK.404if the document is not found.- Requires a writable (token-authenticated) client when
-ris used.
Execute a JQL
query. The request body is the query text; the collection must be encoded in the
query with an @collection anchor.
-
Request header
X-Hints— comma separated hints:explain— print the query execution plan before the results, separated by a--------------------line.
-
Response is streamed with HTTP chunked transfer encoding.
-
200 OK; each matched document is sent as:\r\n<document id>\t<document JSON>There is no trailing newline after the last document. A query that matches nothing returns an empty body.
-
A query with the
countoption returns the number of matched documents astext/plaininstead of documents. -
400for an empty body, a query without a collection anchor (No collection specified in query (JQL_ERROR_NO_COLLECTION)), or a query parse error (the parse error text is returned). -
403for anapply/upsert/delquery sent by an anonymous client in read-only mode.
curl -s -X POST --data-raw '@family/[age > 18]' \
-H 'X-Access-Token: myaccess01' http://localhost:9191/
2 {"firstName":"Jack","age":35}
1 {"firstName":"John","age":28}With the explain hint:
curl -s -X POST --data-raw '@family/[age > 18]' \
-H 'X-Access-Token: myaccess01' -H 'X-Hints: explain' http://localhost:9191/
[INDEX] NO [COLLECTOR] PLAIN
--------------------
2 {"firstName":"Jack","age":35}
1 {"firstName":"John","age":28}Counting without transferring documents:
curl -s -X POST --data-raw '@family/* | count' \
-H 'X-Access-Token: myaccess01' http://localhost:9191/
2Fetch database metadata as a JSON document. The response also contains the Allow
header with the methods accepted by the endpoint, and CORS headers when CORS is enabled.
curl -s -X OPTIONS -H 'X-Access-Token: myaccess01' http://localhost:9191/
{
"version": "2.100",
"file": "/var/lib/ejdb2/example.db",
"size": 32768,
"collections": [
{
"name": "family",
"dbid": 3,
"rnum": 2,
"indexes": []
}
]
}The Allow header lists GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS for a writable
endpoint, and GET, HEAD, POST, OPTIONS when the server runs in read-only mode
(-r).
OPTIONS /{collection} is not supported (400).
The WebSocket endpoint is the server root (GET / with Upgrade: websocket on the
same port). If an access token is configured it must be sent in the
X-Access-Token header of the handshake.
The protocol is text based: every WebSocket text message contains one command, and a command may produce one or more response messages. Messages are tab separated.
<key> <command> [arguments]
<key> is an arbitrary client-chosen token of at most 36 bytes (not containing
whitespace). It is echoed back as the first field of every response message, so a
client can match responses to requests.
<key> info
<key> get <collection> <id>
<key> set <collection> <id> <document json>
<key> add <collection> <document json>
<key> del <collection> <id>
<key> patch <collection> <id> <patch json>
<key> idx <collection> <mode> <path>
<key> rmi <collection> <mode> <path>
<key> rmc <collection>
<key> query <collection> <query>
<key> explain <collection> <query>
<key> <query>
Send ? (a message consisting of a single question mark) to receive this help text.
| Response | Meaning |
|---|---|
<key>\t<metadata json> |
info result |
<key>\t<id> |
add, set, del, patch result |
<key>\t<id>\t<document json> |
get result, or one query result document |
<key>\t<explain>\t<plan> |
query execution plan (explain) |
<key>\t<count> |
count query result |
<key> |
End of a query result set. Also the successful reply of idx, rmi, rmc |
<key> ERROR: <description> |
Error |
Examples below are shown as rendered by wscat; response fields are separated by horizontal tabs.
Request the list of supported commands:
wscat -H 'X-Access-Token: myaccess01' -c http://localhost:9191
> ?
< <key> info
< <key> get <collection> <id>
...Return database metadata as a pretty printed JSON document.
> k info
< k {
"version": "2.100",
"file": "/tmp/ejdb2.db",
"size": 32768,
"collections": [ ... ]
}Anonymous clients are not allowed to call info in read-only mode.
Add a new document and return its generated identifier. The collection is created if it does not exist.
> k add mycollection {"foo":"bar"}
< k 1
> k add mycollection {"foo":"bar"}
< k 2Store a document under the given numeric identifier, replacing an existing document.
> k set mycollection 3 {"foo":"baz"}
< k 3Return a document. The document is pretty printed.
> k get mycollection 1
< k 1 {
"foo": "bar"
}If the document is not found:
> k get mycollection 55
< k ERROR: Key not found. (IWKV_ERROR_NOTFOUND)Remove a document. Returns its identifier, or an error if the document is not found.
Apply an RFC 7396 merge patch (JSON object) or an RFC 6902 JSON patch (JSON array) to the document. Returns the document identifier.
Execute a JQL query. Each matched document is sent as a separate message, and the result set is terminated by a message containing only the key:
> k query family /* | /firstName
< k 3 {"firstName":"John"}
< k 2 {"firstName":"Jack"}
< k 1 {"firstName":"John"}
< kA query with the count option returns a single message with the number of matched
documents and no termination message:
> k query family /* | count
< k 3Same as query, but sends the execution plan first:
> k explain family /* | /firstName
< k explain [INDEX] NO [COLLECTOR] PLAIN
< k 3 {"firstName":"John"}
< k 2 {"firstName":"Jack"}
< k 1 {"firstName":"John"}
< kExecute the query text given in the message. The collection must be encoded in the
query with an @collection anchor:
> k @family/[age > 30]
< k 2 {"firstName":"Jack","age":35}
< kCreate an index for the given JSON path. Returns an empty message on success. The collection is created if it does not exist.
| Index mode | Description |
|---|---|
0x01 EJDB_IDX_UNIQUE |
Index is unique |
0x04 EJDB_IDX_STR |
Index for JSON string values |
0x08 EJDB_IDX_I64 |
Index for 64 bit signed integer values |
0x10 EJDB_IDX_F64 |
Index for floating point values |
For example a unique string index over /name uses mode 0x01 | 0x04 = 5:
> k idx mycollection 5 /name
< kRemove an index. Returns an empty message on success, including the case when the
index does not exist. A missing collection is reported as
Resource is not exists. (IW_ERROR_NOT_EXISTS).
Remove a collection with all its documents and indexes. Removing a missing collection is not an error.
Errors are returned as:
<key> ERROR: <description>
For example:
> k get mycollection 55
< k ERROR: Key not found. (IWKV_ERROR_NOTFOUND)A message that cannot be parsed far enough to read the key (for example a lone <key>
without a command) terminates the WebSocket session.
EJDB2 is an embeddable JSON database: an application links libejdb2, opens one or
more database files and works with JSON documents, collections, indexes and queries
through a plain C11 API. No server process is required (an embedded HTTP/WebSocket
endpoint is optional).
The public API is documented in the installed headers:
- ejdb2.h — storage, documents, collections, indexes, queries and query execution.
- jql.h — JQL query objects and placeholder binding.
- jbr.h — embedded
HTTP/WebSocket server (requires a build with
EJDB_ENABLE_HTTP). iowow/iwjbl.h,iowow/iwjbn.h,iowow/iwjson.h— JSON documents (struct jbl,struct jbl_node), provided by the iowow dependency.iowow/iwkv.h,iowow/iwpool.h,iowow/iwxstr.h,iowow/iwlog.h— storage, memory pools, string buffers and logging primitives used by the public API.
The library is also available through language bindings (src/bindings: Node.js, JNI
and Android wrappers).
| Task | Start with |
|---|---|
| Open/close a database | ejdb_init(), ejdb_open(), ejdb_close() |
| Store and fetch documents | jbl_from_json(), ejdb_put_new(), ejdb_get() |
| Run a query | jql_create(), ejdb_exec(), jql_destroy() |
| Run a query and get a list | ejdb_list2() / ejdb_list3(), ejdb_list_destroy() |
| Count or update matched documents | ejdb_count(), ejdb_update() |
| Index a field | ejdb_ensure_index() |
| Inspect the query plan | struct ejdb_exec.log |
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <ejdb2/ejdb2.h>
#define CHECK(rc_) \
if (rc_) { \
iwlog_ecode_error3(rc_);\
return 1; \
}
static iwrc documents_visitor(struct ejdb_exec *ctx, struct ejdb_doc *doc, int64_t *step) {
(void) ctx;
(void) step;
printf("%" PRId64 " ", doc->id);
iwrc rc = jbl_as_json(doc->raw, jbl_fstream_json_printer, stdout, 0);
fputc('\n', stdout);
return rc;
}
int main(void) {
struct ejdb_opts opts = {
.kv = {
.path = "example.db",
.oflags = IWKV_TRUNC
}
};
struct ejdb *db = 0; // EJDB2 storage handle
struct jql *q = 0; // Query instance
struct jbl *jbl = 0; // JSON document
int64_t id = 0; // Document id placeholder
iwrc rc = ejdb_init();
CHECK(rc);
rc = ejdb_open(&opts, &db);
CHECK(rc);
// First record
rc = jbl_from_json(&jbl, "{\"name\":\"Bianca\", \"age\":4}");
RCGO(rc, finish);
rc = ejdb_put_new(db, "parrots", jbl, &id);
RCGO(rc, finish);
jbl_destroy(&jbl);
// Second record
rc = jbl_from_json(&jbl, "{\"name\":\"Darko\", \"age\":8}");
RCGO(rc, finish);
rc = ejdb_put_new(db, "parrots", jbl, &id);
RCGO(rc, finish);
jbl_destroy(&jbl);
// Query over the collection with an unbound `:age` placeholder
rc = jql_create(&q, "parrots", "/[age > :age]");
RCGO(rc, finish);
rc = jql_set_i64(q, "age", 0, 3); // Actual query: /[age > 3]
RCGO(rc, finish);
struct ejdb_exec ux = {
.db = db,
.q = q,
.visitor = documents_visitor
};
rc = ejdb_exec(&ux);
finish:
jql_destroy(&q);
jbl_destroy(&jbl);
ejdb_close(&db);
CHECK(rc);
return 0;
}Build and run:
# The installed header defines IW_BLOCKS when the library was built with blocks
# support; a blocks-capable compiler (clang) is required in that case:
clang -std=gnu11 -fblocks -o example1 example1.c $(pkg-config --cflags --libs libejdb2)
# Otherwise:
cc -std=gnu11 -o example1 example1.c $(pkg-config --cflags --libs libejdb2)
./example1
2 {"name":"Darko","age":8}
1 {"name":"Bianca","age":4}The 1/2 prefixes are document identifiers (doc->id). Without an asc/desc
option a full scan visits documents in descending primary key order (see
JQL performance tips),
which is why Darko comes first.
The examples below assume that <stdio.h>, <stdlib.h>, <string.h>,
<inttypes.h> and <iowow/iwxstr.h> are included where used.
-
#include <ejdb2/ejdb2.h>— the header is installed into${prefix}/include/ejdb2by./build.sh --prefix=.... -
pkg-config --cflags --libs libejdb2gives the compile and link flags. -
Static linking: add
--statictopkg-config --libs. That pulls inlibiwnet/libiowow/libbinncand, with blocks support,BlocksRuntime:clang -std=gnu11 -fblocks example1.c \ $(pkg-config --cflags --libs --static libejdb2) -lBlocksRuntime -
Without
pkg-configlink with-lejdb2. -
Header-only aliases such as
EJDB,EJDB_DOC,JBL,JQLstill exist, but new code may use the plainstructnames. This document uses the plain names.
iwrc rc = ejdb_init(); // Once per process, before any other call
rc = ejdb_open(&opts, &db); // Open (and optionally start the HTTP server)
...
rc = ejdb_close(&db); // Close and release everythingejdb_init()registers the error code namespaces. It is idempotent and is also called implicitly byejdb_open(), but call it explicitly before using any other API function.- A storage file can be opened by one process at a time. A second
ejdb_open()of the same file blocks until the first handle is closed (seekv.file_lock_fail_fast). - A database handle can be used from multiple threads. Conflicting operations are serialized internally with a read/write lock per collection.
- All application threads must stop using the handle (and the
iowowAPI) beforeejdb_close()is called.ejdb_close()sets the handle to zero.
struct ejdb_opts:
| Field | Description |
|---|---|
kv |
struct iwkv_opts storage options: path (database file, required), oflags (IWKV_TRUNC resets the file, IWKV_RDONLY opens read-only), file_lock_fail_fast (fail with an errno-class error instead of waiting for another process), random_seed, fmt_version, wal |
http |
HTTP/WebSocket server options (struct ejdb_http), disabled by default |
no_wal |
Do not use the write-ahead log. Default: false |
sort_buffer_sz |
Max sorting buffer size; overflow is spilled to a temporary file. Default: 16 MiB, min: 1 MiB |
document_buffer_sz |
Initial buffer size for documents processed during queries. Default: 64 KiB, min: 16 KiB |
struct ejdb_opts may be stack allocated and released after ejdb_open(); the
library keeps its own copy of the structure.
// Read-only access to an existing database
struct ejdb_opts opts = {
.kv = {
.path = "example.db",
.oflags = IWKV_RDONLY,
.file_lock_fail_fast = true
}
};A read-only database cannot be modified: write calls fail, and writes to a collection
that does not exist report IW_ERROR_NOT_EXISTS.
Enabling opts.http starts the same REST/WebSocket service that the jbs tool
provides. See the embedded HTTP server
section for the full option list; ejdb_close() stops the server and waits for it to
finish.
struct ejdb_opts opts = {
.kv = { .path = "example.db" },
.http = {
.enabled = true,
.port = 9191,
.access_token = "myaccess01",
.read_anon = true,
.blocking = false // Serve in a background thread
}
};All functions return iwrc (0 on success, a non-zero error code otherwise) or a
void/value result. Errors are structured codes from several namespaces:
IW_ERROR_*, IWKV_ERROR_*, JBL_ERROR_*, EJDB_ERROR_*, JQL_ERROR_*, JBR_ERROR_*.
iwrc rc = ejdb_get(db, "parrots", 1, &jbl);
if (rc) {
// "Key not found. (IWKV_ERROR_NOTFOUND)"
fprintf(stderr, "%s\n", iwlog_ecode_explained(rc));
iwlog_ecode_error3(rc); // Log with file/line and the symbolic code name
}iwlog_ecode_explained() returns a human readable description of a code. Some codes
carry an embedded errno part; strip it with iwrc_strip_code(&rc) before comparing a
code with a specific constant:
iwrc_strip_code(&rc);
if (rc == IWKV_ERROR_NOTFOUND) {
// No such document
}Helpers from iowow keep error handling out of the way:
| Macro | Effect |
|---|---|
RCRET(rc) |
Return rc from the current function when it is non-zero |
RCGO(rc, label) |
Jump to label when rc is non-zero |
RCC(rc, label, expr) |
Assign expr to rc and jump when it is non-zero |
RCB(label, ptr) |
Jump when an allocation returned zero, setting IW_ERROR_ALLOC |
RCA(ptr, label) |
Same as RCB for an assignment expression |
RCBREAK(rc) |
Break out of a loop when rc is non-zero |
IWRC(expr, rc) |
Run expr, keep the first error in rc and log the rest |
WUR |
Function attribute marking the result as "must be used" |
A typical helper ends with a single cleanup label:
static iwrc store_parrot(struct ejdb *db, const char *json, int64_t *id) {
struct jbl *jbl = 0;
iwrc rc = jbl_from_json(&jbl, json);
RCRET(rc);
rc = ejdb_put_new(db, "parrots", jbl, id);
jbl_destroy(&jbl);
return rc;
}Always check the result of jbl_*/jbn_* creators before using the handle: on error
the output handle is zero.
| Constant | Meaning |
|---|---|
IWKV_ERROR_NOTFOUND |
Document or key not found |
IW_ERROR_NOT_EXISTS |
Collection does not exist |
IW_ERROR_INVALID_ARGS |
Required argument is zero or out of range |
EJDB_ERROR_INVALID_COLLECTION_NAME |
Empty name or longer than EJDB_COLLECTION_NAME_MAX_LEN (255) |
EJDB_ERROR_UNIQUE_INDEX_CONSTRAINT_VIOLATED |
Unique index would be violated |
EJDB_ERROR_MISMATCHED_INDEX_UNIQUENESS_MODE |
Index exists with a different uniqueness mode |
EJDB_ERROR_INVALID_INDEX_MODE |
Invalid index mode bits |
EJDB_ERROR_COLLECTION_NOT_FOUND |
Collection not found (ejdb_rename_collection) |
EJDB_ERROR_TARGET_COLLECTION_EXISTS |
Target collection already exists |
EJDB_ERROR_PATCH_JSON_NOT_OBJECT |
Merge patch for an absent document is not a JSON object |
JQL_ERROR_QUERY_PARSE |
JQL query syntax error |
JQL_ERROR_NO_COLLECTION |
Query has no @collection anchor and no collection was given |
JQL_ERROR_UNSET_PLACEHOLDER |
A query placeholder was not bound |
JQL_ERROR_INVALID_PLACEHOLDER_VALUE_TYPE |
Bound value type is not allowed here |
JQL_ERROR_REGEXP_INVALID |
Invalid regular expression in jql_set_regexp() |
A document is either a struct jbl (compact binary JSON, the storage format) or a
struct jbl_node (an in-memory tree of JSON values used to build and modify
documents). Both are converted from and to JSON text.
| Type | Purpose | Lifetime |
|---|---|---|
struct jbl |
Storage format; returned by ejdb_get(), ejdb_list*() |
Released by jbl_destroy() |
struct jbl_node |
Mutable tree used by apply/projections and JSON builders |
Released with its struct iwpool (or manually when pool is zero) |
| Function | Description |
|---|---|
jbl_from_json(&jbl, json) |
Parse a JSON text into struct jbl |
jbl_from_json_printf(&jbl, fmt, ...) |
Same with a printf() style format string |
jbn_from_json(json, &node, pool) |
Parse into a struct jbl_node allocated in pool |
jbl_to_node(jbl, &node, clone_strings, pool) |
Convert jbl into a node tree |
jbl_from_node(&jbl, node) |
Build a struct jbl from an object/array node |
jbl_fill_from_node(jbl, node) |
Refill an existing struct jbl from a node |
jbl_as_json(jbl, printer, op, flags) |
Serialize with a printer callback |
jbn_as_json(node, printer, op, flags) |
Serialize a node tree |
jbl_as_json_alloc(jbl, flags, &str) |
Serialize into a malloc()ed C string |
jbn_as_json_alloc(node, flags, &str) |
Same for a node tree |
jbl_destroy(&jbl) |
Release a document (no-op on a zero handle) |
Printers: jbl_fstream_json_printer (FILE *), jbl_xstr_json_printer
(struct iwxstr *), jbl_count_json_printer (byte counter). Flags:
JBL_PRINT_PRETTY, JBL_PRINT_PRETTY_INDENT2, JBL_PRINT_PRETTY_INDENT4,
JBL_PRINT_CODEPOINTS.
Values are read either with typed accessors (jbl_type(), jbl_get_i64(),
jbl_get_f64(), jbl_get_str(), jbl_get_str2()) or with an RFC 6901 JSON pointer:
struct jbl *age = 0;
iwrc rc = jbl_at(doc->raw, "/age", &age);
if (!rc && age) { // `age` is zero when the path does not exist
printf("age=%" PRId64 "\n", jbl_get_i64(age));
}
jbl_destroy(&age); // Zero handles are ignoredSerializing a document into a C string (convenient for logging or IPC) — the result
must be released with free():
char *json = 0;
iwrc rc = jbl_as_json_alloc(jbl, JBL_PRINT_PRETTY, &json);
if (!rc) {
puts(json);
free(json);
}| Function | Description |
|---|---|
ejdb_put(db, coll, jbl, id) |
Store a document under the given identifier (replaces an existing one) |
ejdb_put_jbn(db, coll, jbn, id) |
Same for struct jbl_node |
ejdb_put_new(db, coll, jbl, &id) |
Store a document under a new auto-generated identifier |
ejdb_put_new_jbn(db, coll, jbn, &id) |
Same for struct jbl_node |
ejdb_get(db, coll, id, &jbl) |
Fetch a document; the result must be released with jbl_destroy() |
ejdb_del(db, coll, id) |
Remove a document |
ejdb_patch(db, coll, patchjson, id) |
Apply an RFC 7396/6902 patch to a stored document |
ejdb_patch_jbl, ejdb_patch_jbn |
Same with a struct jbl/struct jbl_node patch |
ejdb_merge_or_put(db, coll, patchjson, id) |
Atomically merge-patch an existing document or insert a new one |
ejdb_merge_or_put_jbl, ejdb_merge_or_put_jbn |
Same with a struct jbl/struct jbl_node patch |
struct jbl *jbl = 0;
int64_t id = 0;
iwrc rc = jbl_from_json(&jbl, "{\"name\":\"Bianca\",\"age\":4}");
RCC(rc, finish, ejdb_put_new(db, "parrots", jbl, &id));
jbl_destroy(&jbl);
// ... later, read it back
RCC(rc, finish, ejdb_get(db, "parrots", id, &jbl));
// ... and remove it
RCC(rc, finish, ejdb_del(db, "parrots", id));
finish:
jbl_destroy(&jbl);Tips:
- Documents are not retained by
ejdb_put*(): the call serializes the document into the storage, so thestruct jblmay be released immediately afterwards. - Collections are created implicitly by the first write operation.
ejdb_get()returns a document over a buffer owned by the returnedstruct jbl; release it withjbl_destroy().- Document identifiers are positive 64-bit integers.
ejdb_put_new()allocates the next identifier of the collection; identifiers of deleted documents are not reused. 0is not a valid document identifier.ejdb_get(db, coll, 0, &jbl)fails withIW_ERROR_INVALID_ARGS.
ejdb_patch() accepts both patch flavours: a JSON array is an RFC 6902 JSON patch, a
JSON object is an RFC 7396 merge patch. ejdb_merge_or_put() additionally inserts the
patch as a new document when the identifier does not exist yet (atomically).
// RFC 7396 merge patch: set `age`, delete `nick` (null removes the key), add `tags`
rc = ejdb_patch(db, "parrots",
"{\"age\":5,\"nick\":null,\"tags\":[\"dev\"]}", id);
// RFC 6902 JSON patch: append to the `tags` array (`-` means the end of an array)
rc = ejdb_patch(db, "parrots",
"[{\"op\":\"add\",\"path\":\"/tags/-\",\"value\":\"home\"}]", id);
// Merge patch, or insert {"name":"Ghost","age":1} under id 42
rc = ejdb_merge_or_put(db, "parrots", "{\"name\":\"Ghost\",\"age\":1}", 42);Tips:
- An RFC 6902
addrequires the parent container to exist (/tagsabove). The non-standardadd_createop creates missing intermediate objects — see JSON patch extensions. - Patching a missing document returns
IWKV_ERROR_NOTFOUND; RFC 6902testfailures are reported asJBL_ERROR_PATCH_TEST_FAILED. ejdb_merge_or_put()fails withEJDB_ERROR_PATCH_JSON_NOT_OBJECTif the inserted patch is not a JSON object.
| Function | Description |
|---|---|
ejdb_ensure_collection(db, coll) |
Create a collection if it does not exist |
ejdb_remove_collection(db, coll) |
Remove a collection; no error if it is missing |
ejdb_rename_collection(db, coll, new_coll) |
Rename a collection |
ejdb_ensure_index(db, coll, path, mode) |
Create an index if it does not exist |
ejdb_remove_index(db, coll, path, mode) |
Remove an index; 0 if the index does not exist, IW_ERROR_NOT_EXISTS if the collection does not exist |
ejdb_get_meta(db, &jbl) |
Database metadata as a JSON document |
Collection names are non-empty strings of at most EJDB_COLLECTION_NAME_MAX_LEN (255)
bytes.
Index mode bits (ejdb_idx_mode_t); exactly one of the type bits is required:
| Mode | Description |
|---|---|
EJDB_IDX_UNIQUE (0x01) |
Values must be unique |
EJDB_IDX_STR (0x04) |
Index for string values |
EJDB_IDX_I64 (0x08) |
Index for 64 bit signed integer values |
EJDB_IDX_F64 (0x10) |
Index for floating point values |
An index path is an RFC 6901 JSON pointer to a concrete field, for example
/address/street. Wildcards in the middle of a path are not allowed. A path can point
to an array field to index each of its elements.
// Unique string index over a nested field
rc = ejdb_ensure_index(db, "users", "/address/street", EJDB_IDX_UNIQUE | EJDB_IDX_STR);
// Numeric index used by range queries and `asc`/`desc`
rc = ejdb_ensure_index(db, "users", "/age", EJDB_IDX_I64);
// Index every element of the `tags` array
rc = ejdb_ensure_index(db, "books", "/tags", EJDB_IDX_STR);Tips:
ejdb_ensure_index()is idempotent. An existing index with the same path but a different type/uniqueness fails withEJDB_ERROR_MISMATCHED_INDEX_UNIQUENESS_MODE.- Creating an index over an existing collection builds the index for all documents. When importing a large batch, insert the documents first and create the indexes afterwards.
- A unique index is enforced by every write; a conflicting
ejdb_put*()fails withEJDB_ERROR_UNIQUE_INDEX_CONSTRAINT_VIOLATED. - Whether an index is actually used is reported by the query execution log, see Query plan log.
Queries are created with the JQL API (jql.h), optionally bound to placeholder values,
and executed with ejdb_exec(). The query language itself — filters, apply,
projections, joins, sorting and options — is described in the
JQL documentation.
| Function | Description |
|---|---|
jql_create(&q, coll, query) |
Parse a query; coll may be zero if the query has an @collection anchor |
jql_create2(&q, coll, query, mode) |
Same with JQL_KEEP_QUERY_ON_PARSE_ERROR/JQL_SILENT_ON_PARSE_ERROR |
jql_collection(q) |
Collection name the query is bound to |
jql_first_anchor(q) |
First @collection anchor of the query, if any |
jql_error(q) |
Parse error text (with a <--- marker) for a kept query |
jql_has_apply(q), jql_has_apply_upsert(q), jql_has_apply_delete(q) |
Query contains a modification section |
jql_has_projection(q), jql_has_orderby(q), jql_has_aggregate_count(q) |
Query shape inspection |
jql_get_skip(q, &skip), jql_get_limit(q, &limit) |
Options encoded in the query |
jql_reset(q, reset_match_cache, reset_placeholders) |
Reuse a query object for the next invocation |
jql_destroy(&q) |
Release the query object |
struct jql *q = 0;
// Collection from the argument
iwrc rc = jql_create(&q, "parrots", "/[age > :age]");
// Collection from the query anchor, the `coll` argument is zero
rc = jql_create(&q, 0, "@parrots/[age > :age]");Reporting a query syntax error with a caret marker:
struct jql *q = 0;
iwrc rc = jql_create2(&q, "parrots", "/[age > ]",
JQL_KEEP_QUERY_ON_PARSE_ERROR | JQL_SILENT_ON_PARSE_ERROR);
if (rc) {
fprintf(stderr, "%s\n", jql_error(q)); // jql_error() returns "" for a zero query
}
jql_destroy(&q); // The kept query object must be destroyed in any caseA query object returned together with an error is kept only for error reporting; it cannot be executed.
Placeholders are written :name (named) or :? (positional). Positional
placeholders are bound by index (jql_set_*(q, 0, index, value)), named ones by name
(jql_set_*(q, "name", 0, value)). A query with an unbound placeholder fails with
JQL_ERROR_UNSET_PLACEHOLDER.
| Function | Description |
|---|---|
jql_set_i64(q, ph, idx, v) |
64-bit signed integer |
jql_set_f64(q, ph, idx, v) |
Floating point value |
jql_set_bool(q, ph, idx, v) |
Boolean |
jql_set_null(q, ph, idx) |
null |
jql_set_str(q, ph, idx, s) |
String, not copied — s must stay alive until the query releases it |
jql_set_str3(q, ph, idx, s, len) |
String of a given length, copied into the query |
jql_set_str2(q, ph, idx, s, freefn, op) |
String with an ownership callback |
jql_set_json(q, ph, idx, node) |
struct jbl_node value, not copied (typically allocated in a pool) |
jql_set_json_jbl(q, ph, idx, jbl) |
struct jbl value, converted and copied by the query |
jql_set_json2(q, ph, idx, node, freefn, op) |
Node value with an ownership callback |
jql_set_regexp(q, ph, idx, expr) |
Regular expression compiled from expr |
jql_set_regexp2(q, ph, idx, expr, freefn, op) |
Same with an ownership callback |
Ownership rules for the *2 variants: on success the query takes ownership of the
value and op, and freefn(value, op) is invoked when the placeholder is released
(jql_reset() with reset_placeholders = true, or jql_destroy()). On failure the
caller keeps ownership and freefn is not invoked.
struct iwpool *pool = iwpool_create_empty();
struct jbl_node *tags = 0, *patch = 0;
struct jql *q = 0;
iwrc rc = jql_create(&q, "books", "/tags/[** in :tags] | apply :patch");
RCC(rc, finish, jbn_from_json("[\"bestseller\",\"dev\"]", &tags, pool));
RCC(rc, finish, jql_set_json(q, "tags", 0, tags));
RCC(rc, finish, jbn_from_json("{\"checked\":true}", &patch, pool));
RCC(rc, finish, jql_set_json(q, "patch", 0, patch));
finish:
jql_destroy(&q);
iwpool_destroy(pool);Tips:
jql_set_str()does not copy the string. For a temporary buffer usejql_set_str3()(copies) or keep the buffer alive until the query is destroyed.jql_set_json()does not copy the node. Allocate nodes in aniwpoolthat outlives all executions of the query; usejql_set_json_jbl()to get a private copy.- An
apply/upsertplaceholder value must be bound as a JSON node (jql_set_json()/jql_set_json_jbl()); a plain string binding fails withJQL_ERROR_INVALID_PLACEHOLDER_VALUE_TYPE. - Placeholders can be used in filters, projections, ordering clauses,
apply, andskip/limit.
A query object can be executed many times with different placeholder values.
ejdb_exec() resets the internal match cache after each run but keeps the bound
placeholders, so only the changed values have to be re-bound:
struct jql *q = 0;
iwrc rc = jql_create(&q, "parrots", "/[age > :age] | asc /age");
if (!rc) {
for (int i = 0; i < 3; ++i) {
struct ejdb_exec ux = {
.db = db,
.q = q
};
rc = jql_set_i64(q, "age", 0, i * 5);
if (!rc) {
rc = ejdb_exec(&ux);
}
if (rc) {
break;
}
printf("age > %d: %" PRId64 " documents\n", i * 5, ux.cnt);
}
}
jql_destroy(&q);Use jql_reset(q, reset_match_cache, reset_placeholders) to release bound values
explicitly — pass reset_placeholders = true to drop all bindings, or false to only
clear the match cache.
jql_matched(q, jbl, &matched) checks a single document against the query filter
without touching the storage. This is handy when documents arrive from another source
and the same JQL syntax should be used for filtering:
struct jql *q = 0;
struct jbl *doc = 0;
bool matched = false;
iwrc rc = jql_create(&q, "parrots", "/[age > :age]");
if (!rc) {
rc = jql_set_i64(q, "age", 0, 3);
}
if (!rc) {
rc = jbl_from_json(&doc, "{\"name\":\"Darko\",\"age\":8}");
}
if (!rc) {
rc = jql_matched(q, doc, &matched);
}
if (!rc) {
printf("matched=%d\n", matched);
}
jbl_destroy(&doc);
jql_destroy(&q);ejdb_exec() streams matched documents to a visitor:
typedef iwrc (*ejdb_exec_visitor)(struct ejdb_exec *ctx, struct ejdb_doc *doc, int64_t *step);
struct ejdb_exec ux = {
.db = db, // Database handle, required
.q = q, // Query object, required
.visitor = visitor, // Optional; without it documents are only matched
.opaque = my_ctx, // Optional user data passed to the visitor
.skip = 0, // Overrides `skip` encoded in the query
.limit = 0, // Overrides `limit` encoded in the query; 0 means "use the query value"
.log = 0, // Optional `struct iwxstr` receiving the execution plan
.pool = 0, // Optional pool for projected/patched node trees
.cnt = 0 // Out: number of documents passed to the visitor
};
iwrc rc = ejdb_exec(&ux);Behaviour:
ux.limit < 1orux.skip < 1mean "take the value from the query". A query withoutlimitmatches everything.ux.cntcounts the documents passed to the visitor. Without a visitor (as inejdb_count()) it counts matched documents.- Executing a query on a collection that does not exist is not an error:
ejdb_exec()returns0and no documents. Useejdb_ensure_collection()or a preceding write if a missing collection has to be detected. - A query with an
apply/upsert/delsection takes a write lock on the collection and modifies the storage while documents are visited. - Without a visitor the projection section is ignored (the query only matches and counts documents).
doc->idis the document identifier,doc->rawis the stored document.doc->nodeis set only when the query has anapplyor projection section. After anapplyit holds the modified document, whiledoc->rawstill holds the stored (pre-modification) one. Print/serializedoc->nodewhen it is not zero.doc->nodeis valid only during the callback unlessux.poolis set (then node trees are allocated from that pool and stay valid until the pool is destroyed).docand its data are valid only during the callback; copy everything that must outlive it.- Return
0to continue. Any non-zero return value aborts the execution and is returned byejdb_exec(). *stepcontrols the cursor:1(default) advances to the next document,0stops the iteration, positive values advance by that number of documents, negative values move backwards. Multi-step and backward movement is intended for custom navigation of sorted result sets (asc/desc); most visitors use1and0.*step == -1re-enters the visitor with the same document (useful when one document produces several output records).
// Print either the projected/modified tree or the stored document
static iwrc print_doc_visitor(struct ejdb_exec *ctx, struct ejdb_doc *doc, int64_t *step) {
(void) ctx;
(void) step;
if (doc->node) {
return jbn_as_json(doc->node, jbl_fstream_json_printer, stdout, 0);
}
return jbl_as_json(doc->raw, jbl_fstream_json_printer, stdout, 0);
}
// Stop iterating once ten documents have been visited
static iwrc head_visitor(struct ejdb_exec *ctx, struct ejdb_doc *doc, int64_t *step) {
(void) doc;
int64_t *visited = ctx->opaque;
if (++(*visited) >= 10) {
*step = 0;
}
return 0;
}int64_t visited = 0;
struct ejdb_exec ux = {
.db = db,
.q = q,
.visitor = head_visitor,
.opaque = &visited
};
iwrc rc = ejdb_exec(&ux);
printf("visited=%" PRId64 "\n", ux.cnt);Setting ux.log to a struct iwxstr collects index selection and collector
decisions. It is the C API equivalent of the explain command of the WebSocket API:
#include <iowow/iwxstr.h>
struct iwxstr *log = iwxstr_new();
struct jql *q = 0;
struct ejdb_list *list = 0;
iwrc rc = jql_create(&q, "parrots", "/[age > :age] | asc /age");
RCC(rc, finish, jql_set_i64(q, "age", 0, 3));
RCC(rc, finish, ejdb_list4(db, q, 0, log, &list));
printf("%s", iwxstr_ptr(log));
finish:
ejdb_list_destroy(&list);
jql_destroy(&q);
iwxstr_destroy(log);Example output for a query served by the /age index:
[INDEX] MATCHED I64|4 /age EXPR1: 'age > :age' INIT: IWKV_CURSOR_GE STEP: IWKV_CURSOR_PREV ORDERBY
[INDEX] SELECTED I64|4 /age EXPR1: 'age > :age' INIT: IWKV_CURSOR_GE STEP: IWKV_CURSOR_PREV ORDERBY
[COLLECTOR] PLAIN
[INDEX] NO followed by [COLLECTOR] SORTER means a full collection scan and (if the
query sorts) an in-memory or temporary-file sort. See
JQL indexes and performance
for the filters that can use an index.
| Function | Description |
|---|---|
ejdb_list(db, q, &first, limit, pool) |
Fill a linked list of documents using a caller-provided iwpool (not zero); the caller owns and destroys the pool |
ejdb_list2(db, coll, query, limit, &list) |
Same from a query text |
ejdb_list3(db, coll, query, limit, log, &list) |
Same with an execution plan buffer |
ejdb_list4(db, q, limit, log, &list) |
Same from a query object |
ejdb_list_destroy(&list) |
Release a result list |
struct ejdb_list *list = 0;
iwrc rc = ejdb_list3(db, "parrots", "/[age > 3]", 0 /* no limit */, 0 /* no log */, &list);
if (!rc) {
for (struct ejdb_doc *doc = list->first; doc; doc = doc->next) {
printf("%" PRId64 " ", doc->id);
jbl_as_json(doc->raw, jbl_fstream_json_printer, stdout, 0);
putchar('\n');
}
ejdb_list_destroy(&list);
}Notes:
- The
ejdb_list*()helpers copy every matched document into a memory pool; preferejdb_exec()with a visitor (or a smalllimit) for large result sets. ejdb_list2/3/4create the pool themselves and release it inejdb_list_destroy().ejdb_list()does not allocate astruct ejdb_list: it returns the first document, and the caller supplied pool must stay alive while the list is walked.list->qis set only byejdb_list2()/ejdb_list3(), which parse the query themselves. A query object passed toejdb_list()/ejdb_list4()remains owned by the caller.
| Function | Description |
|---|---|
ejdb_count(db, q, &count, limit) |
Execute a query and return the number of matched documents |
ejdb_count2(db, coll, query, &count, limit) |
Same from a query text |
ejdb_update(db, q) |
Execute an update query (with an apply section) |
ejdb_update2(db, coll, query) |
Same from a query text |
int64_t count = 0;
iwrc rc = ejdb_count2(db, "parrots", "/[age > 3]", &count, 0);The *2 text variants create and execute the query in one step, so they cannot bind
placeholder values. Use the struct jql variants for queries with placeholders:
struct jql *q = 0;
int64_t count = 0;
iwrc rc = jql_create(&q, "parrots", "/[age > :age]");
if (!rc) {
rc = jql_set_i64(q, "age", 0, 3);
}
if (!rc) {
rc = ejdb_count(db, q, &count, 0);
}
jql_destroy(&q);Adding count to the options section ("/[age > :age] | count") makes the engine
return only the count without converting documents for the visitor; this is the fastest
way to count or to perform a bulk apply/del.
With IW_BLOCKS defined (the default for clang builds) the library exposes a
block-based iteration shortcut. The block receives a document and returns true to
continue or false to stop:
#ifdef IW_BLOCKS
iwrc rc = ejdb_visit_block(db, q, ^bool(struct ejdb_doc *doc) {
printf("%" PRId64 "\n", doc->id);
return true;
});
#endifejdb_visit_block2() accepts a struct ejdb_visit_block with db, q, an optional
pool and user_data, and reports the number of visited documents in num_visits.
Note that variables captured by the block and modified inside it must be declared with
__block.
| Function | Description |
|---|---|
ejdb_online_backup(db, &ts, target_file) |
Consistent online backup; all records written before ts are included |
ejdb_get_iwkv(db, &kv) |
Access the underlying IWKV storage (advanced use) |
ejdb_get_meta(db, &jbl) |
Database structure as JSON (version, file, size, collections, indexes) |
ejdb_version_full(), ejdb_version_major(), ejdb_version_minor(), ejdb_version_patch() |
Library version |
ejdb_git_revision() |
Source revision the library was built from |
uint64_t ts = 0;
iwrc rc = ejdb_online_backup(db, &ts, "backup.db");
if (!rc) {
printf("backup finished at %" PRIu64 "\n", ts);
}The backup file is a regular database image that can be opened with ejdb_open().
Reads and writes are allowed while the backup is running. Because the backup uses
database cursors internally, close your own cursors or run the backup from a dedicated
thread to avoid deadlocks.
Inspecting the database structure:
struct jbl *meta = 0;
iwrc rc = ejdb_get_meta(db, &meta);
if (!rc) {
char *json = 0;
if (!jbl_as_json_alloc(meta, JBL_PRINT_PRETTY, &json)) {
puts(json);
free(json);
}
}
jbl_destroy(&meta);The metadata contains the engine version, the storage file/size and the list of
collections with their document counts (rnum) and indexes (ptr, mode).
Bulk insert. Reuse one write call per document and create indexes after the import (see Collections and indexes):
int64_t id = 0;
for (int i = 0; i < 1000; ++i) {
struct jbl *jbl = 0;
iwrc rc = jbl_from_json_printf(&jbl, "{\"n\":%d}", i);
if (!rc) {
rc = ejdb_put_new(db, "numbers", jbl, &id);
}
jbl_destroy(&jbl);
if (rc) {
break;
}
}Pagination. skip/limit can be encoded in the query or overridden per
execution. skip is applied after filtering, so a deep page still scans the skipped
documents:
struct jql *q = 0;
iwrc rc = jql_create(&q, "parrots", "/* | asc /age");
if (!rc) {
for (int page = 0; page < 3; ++page) {
struct ejdb_exec ux = {
.db = db,
.q = q,
.skip = page * 50,
.limit = 50,
.visitor = print_doc_visitor
};
RCC(rc, finish, ejdb_exec(&ux));
}
}
finish:
jql_destroy(&q);Upsert by query. Insert the document when nothing matches:
struct iwpool *pool = iwpool_create_empty();
struct jbl_node *doc = 0;
struct jql *q = 0;
iwrc rc = jql_create(&q, "jobs", "@jobs/[title = :title] | upsert :doc");
RCC(rc, finish, jql_set_str(q, "title", 0, "Gardening"));
RCC(rc, finish, jbn_from_json("{\"title\":\"Gardening\",\"tags\":[\"outdoor\"]}", &doc, pool));
RCC(rc, finish, jql_set_json(q, "doc", 0, doc));
rc = ejdb_update(db, q);
finish:
jql_destroy(&q);
iwpool_destroy(pool);Bulk update with a count. Store the changed documents without transferring them to a visitor:
struct iwpool *pool = iwpool_create_empty();
struct jbl_node *patch = 0;
struct jql *q = 0;
int64_t count = 0;
iwrc rc = jql_create(&q, "parrots", "/[age > :age] | apply :patch | count");
RCC(rc, finish, jql_set_i64(q, "age", 0, 3));
RCC(rc, finish, jbn_from_json("{\"adult\":true}", &patch, pool));
RCC(rc, finish, jql_set_json(q, "patch", 0, patch));
RCC(rc, finish, ejdb_count(db, q, &count, 0));
printf("updated=%" PRId64 "\n", count);
finish:
jql_destroy(&q);
iwpool_destroy(pool);| Object | Ownership |
|---|---|
struct ejdb * |
Owned by the caller; released by ejdb_close(); shareable between threads |
struct jbl * |
Owned by the caller; released by jbl_destroy(); returned by ejdb_get()/ejdb_get_meta() |
struct jbl_node * |
Released with its struct iwpool; a node bound with jql_set_json() must outlive the query executions |
struct jql * |
Owned by the caller; released by jql_destroy() |
struct ejdb_list * |
Owned by the caller; released by ejdb_list_destroy() |
struct ejdb_doc (visitor) |
Valid only during the visitor callback |
struct ejdb_exec.pool |
Optional memory pool for projected/patched nodes owned by the caller |
- The database handle is thread-safe. Every collection has its own read/write lock:
queries take a read lock, while
apply/upsert/delqueries and all write calls take a write lock. ejdb_exec()holds the collection lock for the whole execution. Do not call write API functions for the same collection from a visitor — collect the data and modify the storage afterejdb_exec()returns.- A slow visitor slows down the query and blocks writers of that collection. Offload expensive work (network calls, large serialization) to another thread.
- Query objects, documents and result lists are not internally synchronized; use each of them from one thread at a time.
- Stop all threads before
ejdb_close().
- Initialize once.
ejdb_open()callsejdb_init()implicitly, but call it explicitly before any other API function. - Zero-initialize output handles.
jql_destroy(),jbl_destroy()andejdb_list_destroy()accept zero handles, which makes a single cleanup block possible. - Prefer
ejdb_exec()overejdb_list*(). Lists copy every document; large collections will exhaust memory. - Add
countwhen only a number is needed. It avoids JSON conversion forapply/delqueries and is the fastest way to count. - Bind placeholders instead of composing query text. This avoids escaping bugs and lets the engine reuse the parsed query.
- Use
jql_set_str3()for temporary strings andjql_set_json_jbl()for document values that must be copied. apply/upsertvalues must be JSON nodes, not strings.ejdb_patch()does not insert. Useejdb_merge_or_put()when a missing document should be created.- A missing collection is not an error for queries.
ejdb_exec()returns0with an empty result; only write calls create collections. - Create indexes after a bulk import. Building an index once over the final data set is faster than maintaining it during inserts.
- Verify the plan with
ux.log. If the log says[INDEX] NO, the query does a full scan; add an index or rewrite the filter. - Print
doc->nodewhen it is set.doc->rawstill holds the pre-applydocument. - Keep lifetimes explicit. A document fetched with
ejdb_get()is released byjbl_destroy(); node trees are released with theiriwpool. - Log errors with
iwlog_ecode_error3()/iwlog_ecode_explained()to get the symbolic code name and description instead of a bare number. - Run memory-sensitive code under sanitizers.
./build.sh -DENABLE_ASAN=1builds the library and tests with AddressSanitizer.
- JQL query language
- HTTP REST/WebSocket API
- Test suite and tools
- iowow — JSON, storage and utility library
MIT License
Copyright (c) 2012-2026 Softmotions Ltd <info@softmotions.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.