JavaScript / TypeScript
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
- Csomag
nucleus-db- Telepítés
- npm: az első kiadással (2027 március) kerül fel; addig forrásból telepíthető.
- Forrás
drivers/js
Node.js, no dependencies, Promise API, written in TypeScript (Node 22.6+
runs src/index.ts directly; npm run build emits dist/ with typings).
import { connect, Decimal } from "nucleus-db";
const db = await connect(); // 127.0.0.1:20035, user/password "nucleus"
await db.query("INSERT INTO t VALUES ($1, $2)", [1, Decimal.parse("9.99")]);
const { rows } = await db.query("SELECT * FROM t");
await db.transaction(async (tx) => { /* … */ });
await db.close();
Types: boolean, number (smallint, integer, real — by its shortest
digits —, double; bigint too, or bigint beyond 2^53), Decimal (exact),
string (text, char(n), enums), Buffer (bytea; any Uint8Array as a
parameter), Date (date, timestamp, timestamptz — UTC, millisecond
precision when read), Time (time of day, µs), Interval, Inet and
Cidr (.bytes, .bits, .address, parse, toString), uuid as its
canonical string, Float32Array (vector), SparseVector (sparsevec: dims, 0-based indices, values), json as what JSON.parse makes (a plain object parameter is json; new Json(x) sends an array or a string as json), arrays, null; another registered type is Ext (its
name and binary form). Protocol version 4: the password is proved by
SCRAM-SHA-256, never sent. TLS: connect({ tls: true }) (Node’s CAs),
tlsCa: "ca.pem", tlsVerify: false (encrypted, unverified); tlsCert,
tlsKey for a client certificate; token for an identity token instead
of the password. Errors are
NucleusError with
code (SQLSTATE) and hint (what to do about it, or null). Queries on one connection run one after another.
Large results stream (protocol version 6): for await (const row of await db.stream(sql, params, { fetch: 1000 })) reads them as they arrive, the
server sending a batch at a time and waiting until it is read; leaving
the loop (or close(), or the next query) stops the statement.
Columnar results (protocol version 7): for await (const b of await db.batches(sql, params, { rows: 65536 })) gives a Batch whose columns’
values are typed arrays read in place (Int32Array, Float64Array,
BigInt64Array for bigint and timestamps — µs since 2000-01-01 —, …;
text as offsets and bytes), with isNull(i) and get(i). Bulk load:
await db.load("t", { id: new Int32Array(…), name: [...] }) (or rows) as
columnar batches in one COPY — typed arrays of the column’s width sent
as they are — and await db.copy("COPY t FROM STDIN WITH (FORMAT csv)", createReadStream("t.csv")) for text or CSV. Many statements in one
round trip: await db.pipeline([[sql, params], …]) (each one’s Result,
or its NucleusError in its place); one statement for many rows, all or
none, one commit for all: await db.executeMany(sql, rows). A script
as a tool shows it: await db.queryText("…; …") → { results, error },
every statement’s Result with the values as the server writes them
(text) and the first error, not thrown. Memory for
a model, in a memory store (CREATE MEMORY STORE notes USING m): await db.remember("notes", "ann", "prefers short answers", { kind: "preference", expires: "30 days" }) → { id, action } ("inserted",
"merged", "replaced" — replaces: oldId keeps the old one as
history), await db.recall("notes", "ann", "how to answer", 5) → the
subject’s current memories, best first (each with as_of, the commit
read: cite a memory by its id and as_of; SET request_id = 'gen-1'
records the reads that serve a request in nc_catalog.reads), await db.forget("notes", id);
await db.forgetSubject("ann") → { erasure, rows, scrubbed, found }
erases her rows from every table with subject columns (FORGET SUBJECT),
scrubs the files and searches them (found === 0: none of their values is
left).
Tests: npm test; example: examples/js/quickstart.ts.
Types from your schema: nucleus codegen ts <db> --out schema.ts writes an
interface per table with its select and fromRow(row) (DOCS §8.37).
In this process (the embedded edition)
The same API on a database in a directory, or in memory, inside this process — no server. A connection string chooses, so a program moves between the two by changing only that:
const db = await connect("file:app.db"); // directory app.db, made if missing
const mem = await connect(":memory:", { options: "cache=64MB" });
const srv = await connect("nucleus://nucleus:[email protected]:20035/nucleus?tls=true");
const local = await connect({ host: "/tmp/nucleus.sock" }); // a server's Unix socket (nucleus server --socket)
const web = await connect("ws://nucleus:[email protected]:20039/ncp"); // over a WebSocket (nucleus server --web)
const edge = await connect("https://nucleus:[email protected]:20039/ncp"); // over HTTP, a request at a time
const shared = Database.open(":memory:"); // several sessions on one
const a = await shared.connect(), b = await shared.connect({ user: "app" });
shared.close();
There is no login in the process: the session is the user it names, and
the directory’s file permissions guard the data. It needs the engine as a
Node-API addon, which Node, Bun and Deno load: native/build.sh builds
native/<platform>-<arch>/nucleus.node from this checkout (cargo, a C
compiler and Node’s headers), the package nucleus-db-<platform>-<arch>
will carry it, or NUCLEUS_EMBEDDED_ADDON names one. Each session is read
on a thread of its own and its bytes reach the event loop as a socket’s
would: queries never block it.
In the browser (the edition in WebAssembly)
In a browser the package’s entry is dist/browser.js (the browser
export, or nucleus-db/browser): the database itself, the engine in
WebAssembly, with the same connect and Client.
import { connect } from "nucleus-db";
const db = await connect("file:app.db"); // kept in the origin's OPFS: survives reloads
const mem = await connect(":memory:"); // gone with the page
await db.query("CREATE TABLE IF NOT EXISTS notes (id INT PRIMARY KEY, body TEXT)");
In a page the engine runs in a module worker of its own (OPFS’s
synchronous files are only there); in a worker, Node, Bun and Deno, on
the calling thread (in Node the storage is a directory of files,
NUCLEUS_POOL or .nucleus). One tab holds an origin’s storage at a
time. The engine is wasm/nucleus.wasm (7.1 MB, 1.65 MB with brotli),
built by wasm/build.sh (rustup target add wasm32-wasip1); connect’s
options wasm, pool and worker say where they are if not beside
the package. What differs: a server only over a WebSocket (ws:// or
wss://…/ncp, the server’s --web) or HTTP (https://…/ncp;
nucleus:// is refused there), no
login in the page’s own database, no embedding models; a COPY’s data goes with the COPY (the
client does this: copy and load work as elsewhere, the data held in
memory first), and a statement runs through — a stream reads a result
the engine has produced whole, at most 256 MB of it.
examples/browser/index.html is a page that keeps its visits;
examples/browser/server.html reaches a server over a WebSocket and is
told of a commit by a live query (written over HTTP from the page’s
origin, given ?http=); test/browser.mjs runs both in headless
Chrome.
Over a WebSocket. ws://user:password@host:20039/ncp?database=…
(or wss://, TLS) reaches a server’s web front end (nucleus server --web) from a browser, Node 22+, Deno or Bun: the nucleus protocol’s
bytes in binary messages, the same login (SCRAM, or token=), queries,
transactions, streams and live queries as over TCP. Over wss:// there
is no channel binding (a page cannot see the certificate).
Over HTTP. https://user:password@host:20039/ncp?database=… (or
http://) reaches the same front end a request at a time, with fetch
— where not even a WebSocket can stay open (serverless and edge
functions). What the client sends in one turn of the event loop is one
POST; each is a session of its own, logged in by its Authorization
(Basic, which the server takes only over TLS or from its own machine,
or Bearer with token=). So a transaction is one request’s:
BEGIN; …; COMMIT in one query, a pipeline, executeMany. After a
request that left a transaction open (rolled back with it), the next is
refused (25000) rather than run outside it; subscribe is refused
(0A000). connect makes an empty request to check the login.
Encrypted columns
A column’s values encrypted here and decrypted here: the server stores
bytea ciphertext and never holds the key; a blind index beside it finds
equal values (nucleus PLAN.md §M14.30 K5, DOCS.md §11 — what it leaves
visible is said there). master is 32 bytes the application keeps.
import { ColumnKey } from "nucleus-db";
const key = await ColumnKey.create(master, "users.email");
await db.query("INSERT INTO users VALUES ($1, $2, $3)",
[1, key.encrypt("[email protected]"), await key.blindIndex("[email protected]")]);
const { rows } = await db.query("SELECT email FROM users WHERE email_index = $1",
[await key.blindIndex("[email protected]")]);
key.decrypt(rows[0][0] as Buffer); // "[email protected]"
A sealed table’s rows whose key their user holds: await db.presentSubjectKey(subject, secret).
Documents
A collection’s documents by MongoDB’s requests (CREATE COLLECTION;
nucleus DOCS.md §8.41, §10 Documents), in the connection’s transaction:
const people = db.collection("people");
await people.insertOne({ name: "ann", age: 34 }); // its _id
await people.find({ age: { $gte: 30 } }, { projection: { name: 1 }, sort: { age: -1 }, limit: 10 });
await people.updateOne({ name: "ann" }, { $inc: { age: 1 } }, { upsert: true });
await people.deleteMany({ age: { $lt: 18 } });
Streams
A stream’s entries (CREATE STREAM; nucleus DOCS.md §8.43): appended in a
transaction, numbered by its commit; a consumer group’s next batch
handled exactly once — the work’s writes and the group’s position
committed together, a conflict with another consumer run again; a wait
for the next entry that holds no transaction on the server:
const jobs = db.streamOf("jobs");
await jobs.append({ name: "resize", image: 42 });
await jobs.process("workers", async (entries) => { // objects, seq first
for (const e of entries) await db.query("INSERT INTO done VALUES ($1)", [e.seq]);
}, { limit: 100, timeoutMs: 30000 }); // entries processed
await jobs.wait(0, 1000); // the newest seq
Task queues
A task queue’s tasks (CREATE QUEUE; nucleus DOCS.md §8.45): added (a
row), taken under a lease, each done exactly once — the work’s writes and
the task’s FINISH committed together; a task whose work fails is failed
into a retry after the backoff or, past its attempts, a dead letter; one
whose lease ran out while it worked is left to the worker that took it
again:
const jobs = db.queueOf("jobs");
await jobs.add({ kind: "resize", priority: 0 }); // its id
await jobs.process(async (task) => { // id, attempt, the columns
await db.query("INSERT INTO thumbnails VALUES ($1)", [task.id]);
}, { limit: 10 }); // tasks finished
const [task] = await jobs.take(1, 60_000); // or by hand: take, then
await jobs.fail(task, "timeout"); // finish(task) / fail(...): "retry" | "dead"
Live queries
A query’s result kept as the commits change it (nucleus DOCS.md §8.47):
const s = await db.subscribe("SELECT id, title FROM tasks WHERE done = $1", [false]);
console.log(s.rows); // the result now
for (;;) {
for (const { diff, row } of await s.changes(30000)) console.log(diff, row); // +1 came, -1 went
render(s.rows); // kept on this side
}
Sync
A database in the process (or the browser’s) as a device that holds a server’s rows and writes them offline (nucleus DOCS.md §8.48):
const device = await connect("file:app.db");
const server = await connect("nucleus://user:pw@host/db");
await device.query("SYNC SHAPE mine AS SELECT * FROM todos WHERE list = 1");
await device.sync(server); // one round; sync(server, 30000) waits for a change
await device.query("UPDATE todos SET done = true WHERE id = 1"); // offline too
await device.syncSettle(server); // rounds until nothing is left to send
A cluster
Several servers named, the one wanted found among them by the role each says it has (protocol version 12), and found again after a failover:
const db = await connect("nucleus://user:pw@db1,db2,db3/app"); // the primary
const reader = await connect("nucleus://user:pw@db1,db2,db3/app?target=prefer-replica");
await db.query("INSERT INTO t VALUES (1)");
await reader.waitCommit(db.lastCommit, 5000); // true: the replica has it
target is primary (the default), any, replica or
prefer-replica; load_balance=random (loadBalance) shuffles the
servers first; { host, hosts: "b:20035,c:20035", target } the same as
options. role, serverHost, serverPort, reconnect(). Over TCP
only: the WebSocket and HTTP transports reach one server. Outside a transaction block, a statement a former primary refused
(25006) or one not sent because the connection had closed runs again on
the primary found anew (looked for up to the failover timeout, 30 s);
one whose connection died while it ran fails with 08006 (its outcome
unknown) and the next statement connects anew. Inside a transaction
block the transaction went with the connection: the next statement is
refused with 08007 — a ROLLBACK passes — and the one after runs on
the new primary. What the session set (SET, prepared statements) does
not come along; the commit token does (nucleus DOCS.md §9 “Clients of a
cluster”).
Licence
The driver: MIT — see LICENSE. The edition in WebAssembly (wasm/nucleus.wasm)
and the Node addon is the database,
AGPL-3.0-only (the repository’s COPYRIGHT): a program that
opens a database in its own process with it is a work based on the
database; one that only reaches a nucleus server is not.