Node.js Embedded

Run Traverse inside your Node.js process, with no server: open or create a .tvdb file, query it with openCypher or GQL, and load data with the bulk writer.

Install

npm install @truespar/traverse-node

Note: the package installs a prebuilt native addon for Windows x64 or Linux x64 (glibc) through a platform package, and ships its TypeScript types. To use an addon you built yourself, point NAPI_RS_NATIVE_LIBRARY_PATH at it.

Open a Database

const traverse = require('@truespar/traverse-node');

// open, or create, a database file
const db = traverse.open('mydb.tvdb');
// ...
db.close();

Closing rolls back transactions still open on the database, saves it, and leaves the .tvdb as a single file. Another process can't open the file while it's open.

Run Queries

execute on the database runs a query as a transaction of its own: a read runs on a snapshot and never waits, a write commits when it succeeds and rolls back when it fails. It blocks the event loop while it runs; executeAsync runs it on the libuv thread pool instead.

db.execute("CREATE (:Person {name: 'Alice', age: 30}), (:Person {name: 'Bob', age: 25})");

const result = db.execute('MATCH (n:Person) WHERE n.age > $minAge RETURN n.name AS name', { minAge: 26 });
for (const row of result.rows) {
    console.log(row.name); // Alice
}

// off the event loop
const later = await db.executeAsync('MATCH (n:Person) RETURN count(n) AS n');
console.log(later.rows[0].n); // 2

GQL

Pass 'gql' as the third argument to run ISO/IEC 39075 GQL instead of openCypher (on the database or a transaction):

const gql = db.execute('MATCH (n:Person) FILTER n.age > 26 RETURN n.name AS name', null, 'gql');

Transactions

// a write transaction
const tx = db.begin();
tx.execute("CREATE (:Person {name: 'Carol', age: 41})");
tx.execute("MATCH (a:Person {name: 'Alice'}), (c:Person {name: 'Carol'}) CREATE (a)-[:KNOWS]->(c)");
tx.commit();

// a read transaction: a snapshot of the database as of now, alongside the writer and other readers
const snapshot = db.beginRead();
console.log(snapshot.execute('MATCH (p:Person) RETURN count(p) AS n').rows); // [ { n: 3 } ]
snapshot.commit(); // ends the read transaction

A transaction that's never committed or aborted rolls back when it's garbage collected. One write transaction is active at a time: begin waits for the active one for up to db.busyTimeout milliseconds (5000), then throws. A statement that fails after changing data fails its transaction: later statements and commit throw with code ERR_TRAVERSE_TRANSACTION_FAILED, and only abort() ends it.

A commit is durable when it returns: it's written to the database's redo log first. The database also saves itself in the background (once the log has grown by 64 MiB, or when a commit has gone five minutes unsaved), so reopening after a crash replays little.

QueryResult

const people = db.execute('MATCH (n:Person) RETURN n.name, n.age');
console.log(people.columns);  // [ 'n.name', 'n.age' ]
console.log(people.rowCount); // 3
for (const row of people.rows) { // one object per row, keyed by column
    console.log(row['n.name']);
}

console.log(db.execute('CREATE (n:Test)').stats.nodesCreated); // 1

Nodes come back as { _id, _labels, ...properties }, relationships as { _id, _type, _source, _target, ...properties }, paths as { nodes, edges }, temporal values as ISO strings and byte arrays as base64 strings. Integers are numbers, exact up to 253.

Bulk Writer

A bulk load is a write transaction that skips the redo log: commit saves the database with the load in it, so the data is written once and is durable when commit returns. Readers don't see the load until then, and abort rolls it back.

const writer = db.bulkWriter();
const acme = writer.createNode(['Company'], { name: 'Acme', founded: 1998 });
const globex = writer.createNode(['Company'], { name: 'Globex', founded: 2004 });
writer.createEdge(acme, globex, 'OWNS', { share: 0.6 });
writer.createIndex('company_name', 'Company', 'name');
writer.createEdgeIndex('owns_share', 'OWNS', 'share');
writer.createEdgeIndex('owns', 'OWNS'); // type-only index
writer.commit();

Labels-only nodes (writer.createNode(['Company', 'Active'])) and relationships without properties (writer.createEdge(source, target, 'WORKS_AT')) work too, and dropEdgeIndex(name) removes a relationship index. Cypher creates indexes as well: db.execute('CREATE INDEX person_age FOR (n:Person) ON (n.age)'). A file built this way can be uploaded to a Traverse server and put behind an alias, so queries move to the new data in one step.

Timeouts, Cancelling and Errors

db.busyTimeout = 10000;      // ms to wait for another writer
db.statementTimeout = 30000; // ms a statement may run (Infinity: no limit)

// an AbortSignal stops an executeAsync that's still running: it rejects with an AbortError
const controller = new AbortController();
setTimeout(() => controller.abort(), 1000);
const counted = await db.executeAsync('MATCH (n) RETURN count(n) AS n', null, null, controller.signal);

try {
    db.execute('MATCH (p:Person) RETURN nosuchfunction(p.name)');
} catch (err) {
    console.log(err.gqlStatus); // 42N48 (unknown function)
}

A statement that runs past statementTimeout, or that tx.cancel() stops, throws with code ERR_TRAVERSE_INTERRUPTED. gqlStatus holds the error's GQLSTATUS code (the ISO/IEC 39075 code where the standard has one). Embedded transactions show in SHOW TRANSACTIONS, and TERMINATE TRANSACTIONS stops them.

Flush and Close

db.flush(); // save now (waits for an active writer like begin)
db.close(); // roll back open transactions, save, release the file