Node.js binding for Minigraf, an embedded graph database. Open an in-memory database or a local file without running a separate server. Use bi-temporal Datalog queries to ask when a fact applied and when the database recorded it.
This branch documents the 3.x API. An unversioned npm install uses npm's
latest tag. If that tag still points to 2.x, use the
2.x README.
For a 3.x prerelease, install an exact version listed on
the npm package page.
npm install minigraf| Platform | Architecture | Support |
|---|---|---|
| Linux | x64 | ✅ |
| Linux | arm64 | ✅ |
| macOS | universal (x64 + arm64) | ✅ |
| Windows | x64 | ✅ |
Requires Node.js 18+.
import { MiniGrafDb } from 'minigraf'
// In-memory database
const db = MiniGrafDb.inMemory()
db.execute('(transact [[:alice :name "Alice"] [:alice :age 30]])')
const result = JSON.parse(db.execute('(query [:find ?n :where [?e :name ?n]])'))
console.log(result.results[0][0]) // "Alice"
// File-backed (persisted to disk)
const db2 = new MiniGrafDb('path/to/mydb.graph')
db2.execute('(transact [[:bob :name "Bob"]])')
db2.checkpoint()
db2.close()Only one handle per .graph file may be open in a process at a time — two
would each cache their own page table and corrupt the file — so call close()
when you are done with one:
const db = new MiniGrafDb('mydb.graph')
db.execute('(transact [[:bob :name "Bob"]])')
db.checkpoint()
db.close()
const again = new MiniGrafDb('mydb.graph') // fine: the first handle is goneCall close() before reopening the same file. Dropping the last reference does
not release the handle: V8 may collect the object much later, or not at all
before the process exits. Reopening before collection throws
Database is already open in this process.
close() is idempotent; every other database method throws after it succeeds.
It also releases all cursors (including prepared-query cursors) and fact logs
from the handle, so they do not prevent reopening the path. Their later
nextBatch() calls return null, as after their own close().
In-memory databases hold no file lock, so closing them is optional.
const { MiniGrafDb, LogWriter } = require('minigraf')
// Read-only: shared lock, nothing written; writes throw "[API-014] ...".
const src = MiniGrafDb.openWithOptions('old.graph', { readOnly: true, pageCacheSize: 4096 })
// A cursor's answer is fixed when it opens. Iterate over rows (decoded like
// execute()'s results), or call nextBatch(n) for a JSON string of up to n rows.
for (const row of src.query('(query [:find ?n :where [?e :name ?n]])')) console.log(row)
// Copy every fact version, keeping tx and valid-time bounds, into a new file.
const out = LogWriter.create('new.graph')
try {
const log = src.factLog({ attributePrefixes: [':app/'] })
for (let batch; (batch = log.nextBatch(10000)) !== null; ) out.appendBatch(batch)
out.advanceTxCount(src.currentTxCount())
out.finish()
} finally {
out.close() // abandons the build (no file) unless finish() ran
}Options: readOnly, pageCacheSize, allowUnlocked, walCheckpointThreshold,
maxDerivedFacts, maxResults, synchronous ('full' or 'normal'),
queryMemoryLimit, allowOverrides, transactionChunkFacts, maxIterations. Fact filter:
attributes, attributePrefixes, entities (UUID strings), txFrom/txTo
(inclusive, bigint), order ('tx' or 'storage'), window.
A record's txCount, txId, validFrom and validTo are bigints (validTo is
VALID_TIME_FOREVER for forever), and its value is { type, value } with type one
of 'string', 'integer' (a bigint), 'float', 'boolean', 'ref' (a UUID string),
'keyword' or 'null', so a record is written back exactly. Error messages start with
their code, such as [API-015]; appendBatch ends the message with (batch index N).
queryMemoryLimit caps the bytes one query may hold, counted per entry by the operators
that keep state (join build sides, negation and or tables, distinct sets, aggregate
groups, window rows, rule-derived facts). A query that would hold more throws QRY-012 and
frees what it held. The default, and Number.MAX_SAFE_INTEGER or more, is no limit. Rows
a cursor returns are not counted, so read a large answer with query().
Query text may override some settings with keywords such as :max-derived-facts 1000.
allowOverrides lists the keywords it may use, by name: 'maxDerivedFacts',
'maxResults', 'queryMemoryLimit', 'maxIterations'. Left out, the defaults apply:
OVERRIDABLE_DEFAULTS, read from the core library (today 'maxDerivedFacts',
'maxResults' and 'maxIterations'). A list replaces the defaults, it does not add to
them, and [] refuses every keyword: a query that uses one throws [API-025] from
execute(), query() and prepare(). An unknown name throws [API-017] when the
database opens, as a bad synchronous value does.
const { MiniGrafDb, OVERRIDABLE_DEFAULTS } = require('minigraf')
const db = MiniGrafDb.openWithOptions('app.graph', {
allowOverrides: [...OVERRIDABLE_DEFAULTS, 'queryMemoryLimit'],
maxIterations: 10000, // rounds per stratum of a rule query, else INT-020
transactionChunkFacts: 16384, // facts staged before a large transaction is chunked
})maxIterations defaults to 1,000,000, and Number.MAX_SAFE_INTEGER or more is no
limit; transactionChunkFacts defaults to 65,536 and is clamped to 1..=1,000,000. A
negative count throws [API-017].
db.prepare(text) parses a query once; execute(bindings) and query(bindings) run it
with its $slots bound (names without the $). Each run reads the database as it is then.
const pq = db.prepare('(query [:find ?n :where [?e :age $age] [?e :name ?n]])')
JSON.parse(pq.execute({ age: 30 })).results
for (const row of pq.query({ age: 40n })) console.log(row)A boolean, a string, null, a bigint and a number bind as values; a number is an
integer when Number.isInteger accepts it, else a float. Use a typed form for the other
kinds: a FactValue such as { type: 'float', value: 2 }, { type: 'keyword', value: ':k' }
or { type: 'ref', value: uuid }; { type: 'entity', value: uuid }; { type: 'txCount', value: 5 } or { type: 'timestamp', value: Date.now() } for :as-of; and
{ type: 'anyValidTime' } for :valid-at. Anything else throws a TypeError. A missing
slot throws [API-022], a slot in an attribute position [API-023], and a value of the
wrong kind [API-024].
A set binds as a JS Set or { type: 'set', value: [...] }, for in? and the other set
predicates or a set-valued attribute: pq.execute({ ids: new Set([1, 2, 3]) }). Its
elements are plain values or typed value forms ({ type: 'keyword', value: ':role/admin' }).
An element in an entity, tx count, timestamp or any-valid-time form throws [API-017], a
set inside a set [API-021]; a plain array is not a set (TypeError). Set values come
back as JSON arrays from execute() and as { type: 'set', value: [FactValue, ...] } in
fact records.
withMaxDerivedFacts(n), withQueryMemoryLimit(bytes) and withMaxIterations(n) each
return a new PreparedQuery with that limit; the one they are called on is unchanged.
allowOverrides only restricts overrides written in the query. It does not restrict these
methods. A permitted override in the query still takes precedence. Number.MAX_SAFE_INTEGER or more means
no limit and a negative value throws [API-017].
const reach = db.prepare('(query [:find ?x ?y :where (reach ?x ?y)])')
const small = reach.withMaxDerivedFacts(10000).withQueryMemoryLimit(16 * 1024 * 1024)
small.execute() // [INT-020] or [QRY-012] past a limit; reach is unchangeddb.close() also releases every prepared query made from it, derived ones included, so the path can be opened
again; a prepared query used after that throws [API-018] database is closed.
db.registerPredicate(name, fn) adds a predicate, called in a query as [(name ?v)].
db.registerAggregate(name, { init, step, finish }) adds an aggregate, used in :find
as (name ?v) and as a window function with :over: init() returns a new
accumulator (one per group or window partition), step(acc, value) returns the
updated accumulator, and finish(acc, count) returns the result. count is the
number of values passed to step. All are called as plain functions, with no this.
db.registerPredicate('adult?', (v) => v.type === 'integer' && v.value >= 18n)
db.regis
8000
terAggregate('product', {
init: () => 1n,
step: (acc, v) => acc * v.value,
finish: (acc) => acc,
})
db.execute('(query [:find ?n :where [?e :age ?a] [(adult? ?a)] [?e :name ?n]])')
db.execute('(query [:find (product ?a) :where [?e :age ?a]])')- Values. A function receives each value as a
FactValue,{ type, value }, as in fact records:typeis'string','integer'(valueabigint),'float','boolean','ref'(an entity UUID string),'keyword','null'(novalue) or'set'(valuean array of these). A predicate returns a boolean. An accumulator may be any value.finishreturns a value in any form a prepared query's bindings accept: a plain value or a typed{ type, value }form. - Errors. A callback exception, a non-boolean predicate result, or an invalid
finishresult stops the query with[QRY-014]. An exception uses itsmessageif available, otherwiseString(e). The query does not treat these failures asfalseor a missing value. Registration throws aTypeErrorwhen a function is missing, and[INT-040]when the name is taken (predicates and aggregates have separate names). - Lifecycle. A query that is already open (a cursor) does not see a function registered after it; every query opened afterwards does. The database keeps each function until it, and every cursor and prepared query opened from it, are released. There is no unregister.
- Threading. A function runs on the JavaScript thread that calls
execute,nextBatchor a prepared query, which is the thread that registered it. A database opened in a worker thread keeps its functions in that worker. - Cost. Each value is one call into JavaScript, so a function over many rows costs one call per value.
- Calling the database from a function. A function may query the same database
(
execute,query,prepareand the prepared query'sexecute/query), write, checkpoint, register another function, orclose()it. The query that called it does not see a write it makes. Anexecute()already running finishes after a successfulclose(); a cursor reading a batch releases it when the batch returns and returnsnull. The file can be reopened once that running call returns. Inside a write transaction's statement,close()throwsINT-001and leaves all resources open. A callback'snextBatch()call fails if it calls the cursor that invoked it and that cursor is still open. Once closed, the cursor returnsnull.
Use transact and retract to stage changes. Queries in the same transaction see
those changes. Commit to apply them together, or roll back to discard them (minigraf#824). First in the release built on core v3.0.0 (core commit
38b10383d6c94c1ae39091ef34e75f68d3d8c76f).
const db = new MiniGrafDb('bank.graph')
db.execute('(transact [[:alice :balance 100] [:bob :balance 50]])')
const tx = db.beginWrite({ chunkFacts: 10000 })
try {
tx.execute('(transact [[:alice :balance 70] [:bob :balance 80]])')
tx.execute('(retract [[:alice :balance 100] [:bob :balance 50]])')
const [[balance]] = JSON.parse(tx.execute('(query [:find ?b :where [:alice :balance ?b]])')).results
if (balance >= 0) tx.commit()
} finally {
tx.rollback() // does nothing once committed
}db.beginWrite(options?):{ synchronous?: 'full' | 'normal', chunkFacts?: number }. Omitted options use the database settings.synchronoussets the WAL sync mode for this commit.chunkFactssets how many facts a file-backed transaction stages before writing in chunks (negative or an unknownsynchronousis API-017). Read-only databases throw API-014.tx.execute(datalog)returns whatdb.executereturns; a staged write returns{"ok":true}. A statement that throws stages nothing and leaves the transaction open. There are no cursors or prepared queries inside a transaction.tx.commit()applies everything as one transaction; a commit that throws rolls back.tx.rollback()discards it. Either way it is finished (tx.isOpenis false):execute,incomingRefsandcommitthen throw API-018, androllbackdoes nothing.- Commit or roll back every transaction explicitly. Use
finallyto roll back if it is still open. Garbage collection may never release the write lock held by an abandoned transaction. - While a transaction is open, other calls that read or write through its database
fail immediately with INT-001. That includes
execute,query,factLog,prepare,checkpoint, anotherbeginWrite, and prepared queries. A callback run by the transaction gets the same error if it makes one of those calls or calls its own transaction. db.close()rolls back an open transaction and finishes it (API-018 afterwards). Called from a user function inside that transaction's running statement, it throws INT-001 without closing the database, transaction, prepared queries, cursors or logs. If the function does not catch it, the statement fails with QRY-014; the transaction stays open. Close after the statement returns to roll it back and release resources.- Rules registered inside a transaction stay registered after a rollback.
tx.incomingRefs(target, maxLinks, maxRecords) is synchronous and returns an
IncomingRefs object. Pass a UUID string and both limits as finite integers
from zero through Number.MAX_SAFE_INTEGER. They must fit native usize
(at most 4294967295 on a 32-bit target). Zero is a cap, and -0 counts as
zero. No value disables either limit. The method does not coerce non-numbers.
{ status: 'complete', links: [{ source, attribute }, ...], recordsExamined }contains every distinct source/attribute pair. Sources are canonical lowercase UUID strings and link order is unspecified. An unknown target completes with empty links and zero records, even with both budgets zero.{ status: 'exhausted', budget: 'links' | 'records', recordsExamined }has nolinksproperty.maxLinkscaps distinct links;maxRecordscaps examined fact versions, including retractions, superseded versions and lookahead.recordsExaminednever exceedsmaxRecords.
The lookup sees committed data plus earlier writes and retractions staged in this transaction. Only stored scalar Ref values count: Keywords (even when resolving to the same UUID), UUID-looking strings, refs inside sets and derived facts are excluded. Valid time is ignored, including future and expired assertions. The lookup stages nothing, takes no transaction number and writes no WAL entry.
Look up references before staging deletions. Delete only if the result is
complete. If it is exhausted, retry with higher limits or abandon the
deletions. Exhaustion does not undo earlier staged writes. Complete, exhausted,
and invalid-argument calls leave the transaction usable.
const tx = db.beginWrite()
try {
const target = '82958a33-8334-5ef8-ae38-de39ce3fab69'
let incoming = tx.incomingRefs(target, 100, 1000)
if (incoming.status === 'exhausted') {
incoming = tx.incomingRefs(target, 1000, 10000) // retry before staging deletes
}
if (incoming.status === 'complete') {
for (const { source, attribute } of incoming.links) {
tx.execute(`(retract [[#uuid "${source}" ${attribute} #uuid "${target}"]])`)
}
tx.commit()
} // otherwise abandon; finally rolls back
} finally {
tx.rollback()
}Invalid UUIDs or budgets throw [API-017]. Finished transactions, including after
db.close(), throw [API-018] before checking arguments. A callback from one of
this transaction's own statements throws [INT-001] first, even with invalid
arguments. Core read and storage failures remain errors, never empty results.
Requires Rust stable toolchain and @napi-rs/cli.
npm install
npx napi build --platform --release --no-jsAfter the branch move, the default branch's release.yml handles both source
lines. A core-release dispatch carries only the full core tag: major 3 selects
main, and major 2 selects v2.x. The selected branch is also the write target;
a missing branch fails without a fallback. Manual production recovery must use
the default branch's workflow definition:
gh workflow run release.yml --ref main -f version=v3.0.0-alphaAccepted versions are v2.MINOR.PATCH and v3.MINOR.PATCH, optionally suffixed
with -alpha, -alpha2 through -alpha9, -beta, -beta2 through -beta9, or
-rc1 through -rc9. Git tags retain the v; Cargo and all five npm packages
use the unprefixed version. Prerelease preparation stamps the installation
command above with the exact version; stable preparation restores its usual form.
The workflow converts the core dependency to an exact crates.io requirement, preserves its feature settings, and checks the lockfile and resolved feature graph before building. The workflow commit provides the release scripts and the CI, packaging and verification definitions. The selected source provides its tests and consumer checks. The 3.x TypeScript check is required. Both lines build the root package and four platform packages. The workflow checks that the macOS binary contains both architectures, but tests only on the runner's architecture.
Tests and local consumers finish before the selected branch and an annotated,
immutable release tag are pushed atomically. The tag identifies the tested commit,
dependency resolution and original tarball digests. Original bytes, the source
bundle and test evidence are retained as Actions artifacts for 90 days,
subject to repository retention policy. Do not delete a tag to recover: repeat
the same dispatch. A retry authenticates the original run and evidence,
checks that the tagged commit still belongs to its source branch, and compares
npm integrity digests. It uploads only missing original tarballs. The workflow
stops on expired or missing evidence, legacy tags without evidence, or a
published tarball that differs. On success, the workflow installs and tests
the exact version from npm on all four platforms, even if it uploaded nothing. Production failures
after publication starts are reported with release-broken.
Only one release job can update npm at a time. While it holds that slot, it
checks npm's current tags and makes one channel decision for all five packages. Prereleases use next;
stable releases use latest unless any package's latest is on a higher major.
In that case all five packages use maintenance-v<major> (for example,
maintenance-v2). An already newer channel is preserved. A missing older package
is published with the explicit holding tag release-<version> (for example,
release-3.0.0-alpha) without moving its channel. Holding tags are retained.
Retries repair missing tags even when all tarballs are already on npm. The
summary lists packages whose tags disagree.
Publication uses npm 11.21.3 with OIDC. Each package's trusted publisher must
authorize release.yml for direct publishing and enable Allow npm dist-tag;
permission to publish alone does not authorize tag repair. A failed repair stops
the run with the package, tag and required permission in the error. These settings
and an authenticated repair require verification in a hosted production run;
public registry reads cannot establish write permission.
See npm's trusted publishing requirements.
The maintenance and holding tags avoid npm's rejection of SemVer ranges such as
v2; see npm's tag restrictions.
Runs for the same tag are serialized. Different versions can build at the same time, but their npm publishing and tag repair jobs run one at a time. GitHub keeps one pending job. A new arrival can cancel that pending job without stopping the one that is running. Retry a cancelled run with its original tag; cancellation does not confirm publication or verification.
To rehearse a release, manually run release.yml from main with
rehearsal=true. Omit source_alias:
- For 3.x, use
version=v3.0.0-alphaand setcandidateto the exact 40-character core commit SHA. The workflow testsmainand records the core crate version separately from the npm package version. - For 2.x, use
version=v2.0.12(or the 2.x version you want to test) and omitcandidate. The workflow testsv2.xagainst the published core crate.
A repository dispatch cannot start a rehearsal. Rehearsals build and test the selected branch head. A Git bundle carries the prepared commit without pushing a temporary branch. The summary records the workflow, source, and prepared commits, the selected branch and dependency, artifact hashes, and consumer test results. Rehearsals do not change branches, tags, npm packages or dist-tags, releases, or issues.
MIT OR Apache-2.0