CozoDB for Node.js
Cozo-node is a Node.js binding for CozoDB, an embedded Datalog and graph database. It provides direct native access to CozoDB's capabilities, allowing developers to embed a powerful, relational-like database engine directly within their Node.js applications. The current stable version is 0.7.6, with recent minor releases indicating active development. Cozo-node differentiates itself by offering various storage engines, including in-memory ('mem'), SQLite, and RocksDB (depending on compile-time flags), enabling flexible persistence options. It exposes a simple API for running Datalog queries, managing relations, and handling database backups and restores. While primarily accessed via JavaScript/TypeScript, its underlying implementation is in Rust, providing high performance and low-level control. This library is suitable for applications requiring an embedded, queryable knowledge base or a lightweight graph database solution.
Common errors
-
Error: No precompiled binaries for your platform.
cause The `cozo-node` package could not find a prebuilt native binary matching your system's operating system, architecture, or Node.js version.fixInstall a Rust toolchain (`rustup.rs`) and then try installing the package with `npm install --build-from-source cozo-node` or by following the manual build steps in the README. -
TypeError: (0, _cozoNode.CozoDb) is not a constructor
cause This error typically occurs when trying to use a default import for `CozoDb`, which is a named export, or incorrect CommonJS `require` syntax.fixFor ES Modules, use `import { CozoDb } from 'cozo-node';`. For CommonJS, use destructuring: `const { CozoDb } = require('cozo-node');`. -
Database operation failed: <error message>
cause A Datalog query or database operation encountered a runtime error specific to CozoDB's internal logic, often due to malformed queries or data constraints.fixExamine the `err.display` or `err.message` property for specific CozoDB error details. Review your Datalog script and parameters for syntax, relation existence, and data consistency.
Warnings
- gotcha Failure to call `db.close()` on a CozoDb instance will lead to native resource leaks and may prevent the Node.js process from exiting cleanly.
- gotcha Precompiled binaries for `cozo-node` may not be available for all operating systems, architectures, or Node.js versions.
- gotcha The `importRelations` and `importRelationsFromBackup` methods bypass triggers; any triggers defined on the imported relations will not be executed during these operations.
- gotcha The `restore` method is designed for initializing an empty database; it will fail if the current database instance already contains any data.
Install
-
npm install cozo-node -
yarn add cozo-node -
pnpm add cozo-node
Imports
- CozoDb
import CozoDb from 'cozo-node';
import { CozoDb } from 'cozo-node'; - CozoDb
const CozoDb = require('cozo-node');const { CozoDb } = require('cozo-node'); - * as CozoNode
import * as CozoNode from 'cozo-node';
Quickstart
import { CozoDb } from 'cozo-node';
async function main() {
const db = new CozoDb('mem'); // Use 'mem' for in-memory, 'sqlite' for persistent storage
try {
console.log('Inserting initial data...');
await db.run("?[] <- [['hello', 'world!'], ['cozo', 'database']]");
console.log('Querying all data...');
const result1 = await db.run("?[a, b] <- [[a, b]]");
console.log("Result of '?[a, b] <- [[a, b]]':", result1);
console.log('Querying with parameters...');
const result2 = await db.run("?[message] <- [['hello', $name]]", { "name": "JavaScript" });
console.log("Result of '?[message] <- [['hello', $name]]':", result2);
console.log('Creating and querying a relation...');
await db.run(`
:create parent {child, parent}
:insert parent <- [['Alice', 'Bob'], ['Bob', 'Charlie']]
`);
const ancestors = await db.run(`
?[ancestor] := parent{child, parent}, ancestor = parent
:union
?[ancestor] := parent{child, intermediate}, ancestor_rec{intermediate, ancestor}
`, { child: 'Alice' });
console.log("Ancestors of Alice:", ancestors);
} catch (err: any) {
console.error("Database operation failed:", err.display || err.message);
} finally {
console.log("Closing database connection.");
db.close();
console.log("Database connection closed.");
}
}
main();