@loradb/lora-node 0.36.0 → 0.36.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/docs/README.md +86 -0
- package/docs/concepts/graph-model.md +270 -0
- package/docs/concepts/nodes.md +285 -0
- package/docs/concepts/properties.md +348 -0
- package/docs/concepts/relationships.md +325 -0
- package/docs/concepts/result-formats.md +183 -0
- package/docs/concepts/schema-free.md +183 -0
- package/docs/cookbook.md +1081 -0
- package/docs/data-types/lists-and-maps.md +406 -0
- package/docs/data-types/overview.md +210 -0
- package/docs/data-types/scalars.md +376 -0
- package/docs/data-types/spatial.md +291 -0
- package/docs/data-types/temporal.md +349 -0
- package/docs/data-types/vectors.md +563 -0
- package/docs/errors.md +183 -0
- package/docs/functions/aggregation.md +372 -0
- package/docs/functions/list.md +522 -0
- package/docs/functions/map.md +207 -0
- package/docs/functions/math.md +421 -0
- package/docs/functions/number.md +197 -0
- package/docs/functions/overview.md +545 -0
- package/docs/functions/spatial.md +384 -0
- package/docs/functions/string.md +502 -0
- package/docs/functions/temporal.md +590 -0
- package/docs/functions/utility.md +137 -0
- package/docs/functions/vectors.md +772 -0
- package/docs/getting-started/installation.md +204 -0
- package/docs/getting-started/node.md +582 -0
- package/docs/getting-started/tutorial.md +334 -0
- package/docs/index.md +203 -0
- package/docs/limitations.md +291 -0
- package/docs/performance.md +219 -0
- package/docs/queries/aggregation.md +520 -0
- package/docs/queries/cheat-sheet.md +302 -0
- package/docs/queries/constraints.md +239 -0
- package/docs/queries/create.md +331 -0
- package/docs/queries/examples.md +453 -0
- package/docs/queries/index.md +169 -0
- package/docs/queries/indexes.md +538 -0
- package/docs/queries/match.md +429 -0
- package/docs/queries/ordering.md +359 -0
- package/docs/queries/parameters.md +328 -0
- package/docs/queries/paths.md +462 -0
- package/docs/queries/return-with.md +500 -0
- package/docs/queries/set-delete.md +369 -0
- package/docs/queries/unwind-merge.md +358 -0
- package/docs/queries/where.md +416 -0
- package/docs/snapshot.md +545 -0
- package/docs/troubleshooting.md +1158 -0
- package/docs/wal.md +570 -0
- package/docs/why.md +273 -0
- package/package.json +13 -14
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Using LoraDB in Node.js and TypeScript"
|
|
3
|
+
description: "Install and use LoraDB in Node.js or TypeScript via the lora-node N-API binding — async queries on libuv, explain/profile diagnostics, helpers, snapshots, WAL persistence, and shared result shapes."
|
|
4
|
+
online: "https://loradb.com/docs/getting-started/node"
|
|
5
|
+
package: "@loradb/lora-node@0.36.1"
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Using LoraDB in Node.js and TypeScript
|
|
9
|
+
|
|
10
|
+
## Overview
|
|
11
|
+
|
|
12
|
+
`lora-node` is a native N-API binding. Queries run on the libuv
|
|
13
|
+
threadpool so they don't block the event loop. Auto-commit reads can
|
|
14
|
+
overlap on engine snapshots; write commits still serialize. The
|
|
15
|
+
surface, helpers, and type guards match the
|
|
16
|
+
[WASM binding](https://loradb.com/docs/getting-started/wasm) for query execution and result handling — the
|
|
17
|
+
same query code largely ports with an import swap. Node also adds
|
|
18
|
+
filesystem-backed persistence the WASM build cannot: container-backed
|
|
19
|
+
`.loradb` files, explicit WAL directories, and path-based snapshot
|
|
20
|
+
save/load.
|
|
21
|
+
|
|
22
|
+
**Use LoraDB in a Node.js or TypeScript project**
|
|
23
|
+
|
|
24
|
+
Install the @loradb/lora-node N-API binding, open an async in-memory handle, run a Cypher query, and persist the graph with a .loradb container or a WAL directory.
|
|
25
|
+
|
|
26
|
+
1. **Install the package**: Run npm install @loradb/lora-node (or yarn add @loradb/lora-node). The published package ships prebuilt N-API binaries for Linux, macOS, and Windows.
|
|
27
|
+
2. **Open a database handle**: Call createDatabase() for an in-memory graph, or createDatabase('app', { databaseDir: './data' }) for a .loradb container. The handle is async-only — every call returns a Promise.
|
|
28
|
+
3. **Run a Cypher query**: Await db.execute("CREATE (:Person {name: 'Ada'})") and then db.execute("MATCH (p:Person) RETURN p.name") to confirm the binding works end-to-end.
|
|
29
|
+
4. **Persist the graph**: Call db.saveSnapshot('graph.bin') for a point-in-time dump, or switch to openWalDatabase({ walDir, snapshotDir, snapshotEveryCommits }) for continuous WAL-backed durability.
|
|
30
|
+
|
|
31
|
+
## Installation / Setup
|
|
32
|
+
|
|
33
|
+
[](https://www.npmjs.com/package/@loradb/lora-node)
|
|
34
|
+
|
|
35
|
+
### Requirements
|
|
36
|
+
|
|
37
|
+
- Node.js **18+** for the published package
|
|
38
|
+
- Node.js **20+** for repository-wide tooling and docs / playground work
|
|
39
|
+
- For building from source: Rust toolchain (`rustup`) + `@napi-rs/cli`
|
|
40
|
+
|
|
41
|
+
### Install
|
|
42
|
+
|
|
43
|
+
Install from npm:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm install @loradb/lora-node
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
When working inside this repository, build from source:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
corepack enable
|
|
53
|
+
yarn install --immutable
|
|
54
|
+
yarn workspace @loradb/lora-node build # native .node artifact + TypeScript
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Creating a Client / Connection
|
|
58
|
+
|
|
59
|
+
`lora-node` is **async-only**. The common initialization path is
|
|
60
|
+
`createDatabase(...)`, which returns a `Promise<Database>`:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import { createDatabase } from '@loradb/lora-node';
|
|
64
|
+
|
|
65
|
+
const db = await createDatabase(); // in-memory by default
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
There is no synchronous constructor and no `Database.create()` static.
|
|
69
|
+
Use `createDatabase(...)` for in-memory or container-backed `.loradb`
|
|
70
|
+
databases, and `openWalDatabase(...)` when you want an explicit WAL
|
|
71
|
+
directory.
|
|
72
|
+
|
|
73
|
+
Rule of thumb:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { createDatabase, openWalDatabase } from '@loradb/lora-node';
|
|
77
|
+
|
|
78
|
+
const inMemory = await createDatabase(); // in-memory database
|
|
79
|
+
const persistent = await createDatabase('app', { databaseDir: './data' }); // ./data/app.loradb
|
|
80
|
+
const wal = await openWalDatabase({
|
|
81
|
+
walDir: './data/app.wal',
|
|
82
|
+
snapshotDir: './data/app.snapshots',
|
|
83
|
+
snapshotEveryCommits: 1000,
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
If you want persistence, pass a database name and `databaseDir` to
|
|
88
|
+
`createDatabase(...)`, or pass `walDir` to `openWalDatabase(...)`.
|
|
89
|
+
|
|
90
|
+
To open a container-backed embedded database instead of a fresh in-memory
|
|
91
|
+
one, pass a database name and `databaseDir`:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { createDatabase } from '@loradb/lora-node';
|
|
95
|
+
|
|
96
|
+
const db = await createDatabase('app', { databaseDir: './data' }); // ./data/app.loradb
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
The name is validated and resolved to `<databaseDir>/<name>.loradb`.
|
|
100
|
+
Relative paths resolve from the current working directory. On boot,
|
|
101
|
+
committed WAL records inside that archive are replayed automatically before
|
|
102
|
+
the handle is returned.
|
|
103
|
+
|
|
104
|
+
> **Caution: Do not skip the `await`**
|
|
105
|
+
>
|
|
106
|
+
> `createDatabase()` returns a `Promise`. Calling `execute()` on the
|
|
107
|
+
> unresolved promise will throw. Always `await` the factory before
|
|
108
|
+
> running queries, and never instantiate the `Database` type
|
|
109
|
+
> directly — it is exported as a **type only**.
|
|
110
|
+
|
|
111
|
+
## Running Your First Query
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { createDatabase } from '@loradb/lora-node';
|
|
115
|
+
|
|
116
|
+
const db = await createDatabase();
|
|
117
|
+
|
|
118
|
+
await db.execute("CREATE (:Person {name: 'Ada', born: 1815})");
|
|
119
|
+
|
|
120
|
+
const result = await db.execute(
|
|
121
|
+
"MATCH (p:Person) RETURN p.name AS name, p.born AS born"
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
console.log(result.rows);
|
|
125
|
+
// [ { name: 'Ada', born: 1815 } ]
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Examples
|
|
129
|
+
|
|
130
|
+
### Minimal working example
|
|
131
|
+
|
|
132
|
+
Already shown above — `await createDatabase()` → `execute` →
|
|
133
|
+
inspect `result.rows`.
|
|
134
|
+
|
|
135
|
+
### Parameterised query
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
const result = await db.execute(
|
|
139
|
+
"MATCH (p:Person) WHERE p.name = $name RETURN p.name AS name",
|
|
140
|
+
{ name: 'Ada' }
|
|
141
|
+
);
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Values map automatically: JS numbers → `Int` or `Float`, strings →
|
|
145
|
+
`String`, booleans → `Bool`, `null` → `Null`, arrays → `List`, plain
|
|
146
|
+
objects → `Map`. Dates and spatial points use helper factories — see
|
|
147
|
+
[Typed helpers](#typed-helpers).
|
|
148
|
+
|
|
149
|
+
### Explain and profile
|
|
150
|
+
|
|
151
|
+
`explain` and `profile` are first-class binding methods, not Cypher
|
|
152
|
+
keywords that you prepend to the query string. Use `db.explain(...)`
|
|
153
|
+
when you want the compiled plan without running the executor:
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
const plan = await db.explain(
|
|
157
|
+
"MATCH (p:Person) WHERE p.name = $name RETURN p",
|
|
158
|
+
{ name: 'Ada' }
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
console.log(plan.shape); // "readOnly" or "mutating"
|
|
162
|
+
console.log(plan.resultColumns); // ["p"]
|
|
163
|
+
console.log(plan.tree.operator); // top-level physical operator
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The plan tree contains stable operator `id`s, an `operator` label,
|
|
167
|
+
opaque human-readable `details`, `estimatedRows` (currently `null`),
|
|
168
|
+
and child operators. `explain` never invokes the executor, so even
|
|
169
|
+
`CREATE`, `MERGE`, `SET`, `DELETE`, and `REMOVE` plans leave the graph
|
|
170
|
+
untouched.
|
|
171
|
+
|
|
172
|
+
Use `db.profile(...)` when you want the same plan plus runtime metrics:
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
const profile = await db.profile(
|
|
176
|
+
"MATCH (p:Person) WHERE p.name = $name RETURN p",
|
|
177
|
+
{ name: 'Ada' }
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
console.log(profile.metrics.totalElapsedNs);
|
|
181
|
+
console.log(profile.metrics.totalRows);
|
|
182
|
+
console.log(profile.metrics.mutated);
|
|
183
|
+
console.log(profile.metrics.perOperator);
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
> **Caution: `profile` executes the query**
|
|
187
|
+
>
|
|
188
|
+
> Mutating queries passed to `profile` produce the same side effects as
|
|
189
|
+
> `execute`: WAL-backed databases write the commit, snapshots observe the
|
|
190
|
+
> new state, and the live graph advances. Use `explain` to inspect a
|
|
191
|
+
> mutating plan without running it.
|
|
192
|
+
|
|
193
|
+
Both methods accept the same parameter values as `execute`, including
|
|
194
|
+
tagged helper structs for temporal, spatial, vector, and binary values.
|
|
195
|
+
Graph structs such as `LoraNode` are returned by queries; for input,
|
|
196
|
+
pass property values or typed helper values:
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
import { date, wgs84 } from '@loradb/lora-node';
|
|
200
|
+
|
|
201
|
+
const params = {
|
|
202
|
+
since: date('1800-01-01'),
|
|
203
|
+
near: wgs84(4.89, 52.37),
|
|
204
|
+
radius: 5000,
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const plan = await db.explain(
|
|
208
|
+
`MATCH (c:City)
|
|
209
|
+
WHERE c.founded >= $since
|
|
210
|
+
AND geo.distance(c.location, $near) < $radius
|
|
211
|
+
RETURN c.name AS name`,
|
|
212
|
+
params
|
|
213
|
+
);
|
|
214
|
+
|
|
215
|
+
const profile = await db.profile(
|
|
216
|
+
`MATCH (c:City)
|
|
217
|
+
WHERE c.founded >= $since
|
|
218
|
+
AND geo.distance(c.location, $near) < $radius
|
|
219
|
+
RETURN c.name AS name`,
|
|
220
|
+
params
|
|
221
|
+
);
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### Structured result handling
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
import type { LoraNode } from '@loradb/lora-node';
|
|
228
|
+
import { isNode } from '@loradb/lora-node';
|
|
229
|
+
|
|
230
|
+
const res = await db.execute<{ n: LoraNode }>(
|
|
231
|
+
"MATCH (n:Person) RETURN n"
|
|
232
|
+
);
|
|
233
|
+
|
|
234
|
+
for (const row of res.rows) {
|
|
235
|
+
if (isNode(row.n)) {
|
|
236
|
+
console.log(row.n.id, row.n.labels, row.n.properties);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
### Express route handler
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
import express from 'express';
|
|
245
|
+
import { createDatabase, LoraError } from '@loradb/lora-node';
|
|
246
|
+
|
|
247
|
+
const db = await createDatabase();
|
|
248
|
+
const app = express();
|
|
249
|
+
app.use(express.json());
|
|
250
|
+
|
|
251
|
+
app.get('/users/:id', async (req, res) => {
|
|
252
|
+
try {
|
|
253
|
+
const { rows } = await db.execute(
|
|
254
|
+
"MATCH (u:User {id: $id}) RETURN u {.id, .handle, .tier} AS user",
|
|
255
|
+
{ id: Number(req.params.id) }
|
|
256
|
+
);
|
|
257
|
+
if (rows.length === 0) return res.status(404).end();
|
|
258
|
+
res.json(rows[0].user);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
if (err instanceof LoraError) {
|
|
261
|
+
return res.status(400).json({ error: err.message, code: err.code });
|
|
262
|
+
}
|
|
263
|
+
console.error(err);
|
|
264
|
+
res.status(500).end();
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
app.listen(3000);
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
The same shape generalises to Fastify, Hono, and the edge/serverless
|
|
272
|
+
handlers — the `Database` instance lives at module scope.
|
|
273
|
+
|
|
274
|
+
### Handle errors
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
import { LoraError } from '@loradb/lora-node';
|
|
278
|
+
|
|
279
|
+
try {
|
|
280
|
+
await db.execute("BAD QUERY");
|
|
281
|
+
} catch (err) {
|
|
282
|
+
if (err instanceof LoraError) {
|
|
283
|
+
console.error(err.code); // "LORA_PARSE", "LORA_INVALID_PARAMS", ...
|
|
284
|
+
console.error(err.message);
|
|
285
|
+
} else {
|
|
286
|
+
throw err; // unexpected — rethrow
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
### Concurrency
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
// Five lookups in parallel — read-only queries can overlap on snapshots
|
|
295
|
+
const handles = ['alice', 'bob', 'carol', 'dan', 'eve'];
|
|
296
|
+
const results = await Promise.all(
|
|
297
|
+
handles.map(h =>
|
|
298
|
+
db.execute("MATCH (u:User {handle: $h}) RETURN u.id", { h })
|
|
299
|
+
)
|
|
300
|
+
);
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
The event loop stays responsive. Read-only calls can overlap on engine
|
|
304
|
+
snapshots; write commits still serialize.
|
|
305
|
+
|
|
306
|
+
### Limit on open transactions
|
|
307
|
+
|
|
308
|
+
Each open `db.begin()` transaction and each write `stream()` that has to
|
|
309
|
+
wait for the writer lock runs on a thread of its own. A database keeps at
|
|
310
|
+
most `maxOpenTransactions` of them open at once: 1024 unless you set it.
|
|
311
|
+
Past the limit the call fails at once with `LORA_TOO_MANY_OPEN` instead
|
|
312
|
+
of starting another thread or waiting in a queue.
|
|
313
|
+
|
|
314
|
+
Plain `db.execute()` writes that arrive while a transaction holds the
|
|
315
|
+
writer lock do not take a thread each. They wait in one queue per
|
|
316
|
+
database and run in order, on a single thread, once the lock is free. A
|
|
317
|
+
queued write still fails with `LORA_TIMEOUT` when its `timeoutMs` (or the
|
|
318
|
+
database's `queryTimeoutMs`) runs out or its `signal` aborts, and the time
|
|
319
|
+
spent queued counts. `dispose()` rejects the writes still queued.
|
|
320
|
+
|
|
321
|
+
```ts
|
|
322
|
+
const db = await createDatabase('app', {
|
|
323
|
+
databaseDir: './data',
|
|
324
|
+
maxOpenTransactions: 256,
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
try {
|
|
328
|
+
const tx = await db.begin();
|
|
329
|
+
try {
|
|
330
|
+
await tx.execute("CREATE (:Order {id: $id})", { id: 1 });
|
|
331
|
+
await tx.commit();
|
|
332
|
+
} finally {
|
|
333
|
+
if (tx.isOpen) await tx.rollback();
|
|
334
|
+
}
|
|
335
|
+
} catch (err) {
|
|
336
|
+
if (err instanceof LoraError && err.code === 'LORA_TOO_MANY_OPEN') {
|
|
337
|
+
// Too much in flight: shed load, or retry once others have finished.
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
A slot frees up as soon as its transaction commits or rolls back, or its
|
|
343
|
+
stream ends or is closed. A transaction or stream you drop without
|
|
344
|
+
finishing frees its slot once it is garbage-collected, so finish them
|
|
345
|
+
explicitly.
|
|
346
|
+
|
|
347
|
+
Read-write `db.transaction()` batches never fail this way. At most
|
|
348
|
+
`maxOpenTransactions` of them run at once, and the rest wait their turn
|
|
349
|
+
in order. The wait counts against the batch's `timeoutMs`, and its
|
|
350
|
+
`signal` can cancel it:
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
// 2000 batches: up to 256 run at a time, the others queue.
|
|
354
|
+
await Promise.all(
|
|
355
|
+
orders.map((o) =>
|
|
356
|
+
db.transaction(
|
|
357
|
+
[{ query: "CREATE (:Order {id: $id})", params: { id: o.id } }],
|
|
358
|
+
'read_write',
|
|
359
|
+
{ timeoutMs: 5000 },
|
|
360
|
+
),
|
|
361
|
+
),
|
|
362
|
+
);
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
`openWalDatabase()` takes the same option, and the limits apply per
|
|
366
|
+
database handle.
|
|
367
|
+
|
|
368
|
+
### Persisting your graph
|
|
369
|
+
|
|
370
|
+
LoraDB has three Node persistence shapes:
|
|
371
|
+
|
|
372
|
+
- `createDatabase()` for a purely in-memory graph.
|
|
373
|
+
- `createDatabase('app', { databaseDir: './data' })` for container-backed
|
|
374
|
+
recovery between process restarts.
|
|
375
|
+
- `openWalDatabase({ walDir: './data/wal', snapshotDir: './data/snapshots' })`
|
|
376
|
+
for an explicit WAL directory with optional managed snapshots.
|
|
377
|
+
- `saveSnapshot` / `loadSnapshot` for point-in-time files that you can
|
|
378
|
+
move, back up, or load into a fresh handle.
|
|
379
|
+
|
|
380
|
+
```ts
|
|
381
|
+
import {
|
|
382
|
+
createDatabase,
|
|
383
|
+
openWalDatabase,
|
|
384
|
+
type SnapshotMeta,
|
|
385
|
+
} from '@loradb/lora-node';
|
|
386
|
+
|
|
387
|
+
const db = await createDatabase();
|
|
388
|
+
await db.execute("CREATE (:Person {name: 'Ada'})");
|
|
389
|
+
|
|
390
|
+
// Save everything to disk.
|
|
391
|
+
const meta: SnapshotMeta = await db.saveSnapshot('graph.bin');
|
|
392
|
+
console.log(meta.nodeCount, meta.relationshipCount);
|
|
393
|
+
|
|
394
|
+
// Restore into a fresh handle (in a new process, for example).
|
|
395
|
+
const db2 = await createDatabase();
|
|
396
|
+
await db2.loadSnapshot('graph.bin');
|
|
397
|
+
|
|
398
|
+
const durable = await openWalDatabase({
|
|
399
|
+
walDir: './data/wal',
|
|
400
|
+
snapshotDir: './data/snapshots',
|
|
401
|
+
snapshotEveryCommits: 1000,
|
|
402
|
+
snapshotOptions: { compression: { format: 'gzip', level: 1 } },
|
|
403
|
+
syncMode: 'groupSync',
|
|
404
|
+
});
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
`saveSnapshot` / `loadSnapshot` are `async` like every other
|
|
408
|
+
`@loradb/lora-node` call, but the underlying engine still encodes or decodes the
|
|
409
|
+
whole graph. When you are using
|
|
410
|
+
plain `createDatabase()` with no archive or WAL path, a crash loses
|
|
411
|
+
all in-memory state. Manual snapshots protect only the mutations saved
|
|
412
|
+
before the crash; WAL-backed opens replay committed writes on restart.
|
|
413
|
+
|
|
414
|
+
`saveSnapshot()` with no path returns a `Buffer`. `saveSnapshot(path)`
|
|
415
|
+
writes atomically to disk and returns `SnapshotMeta`. `loadSnapshot`
|
|
416
|
+
accepts a path string / `URL`, `Buffer`, `Uint8Array`, `ArrayBuffer`,
|
|
417
|
+
Node `Readable`, Web `ReadableStream`, or async iterable.
|
|
418
|
+
|
|
419
|
+
To back up a database opened with a name and `databaseDir` while it
|
|
420
|
+
serves traffic, call `db.snapshot(targetDir)` from the process that owns
|
|
421
|
+
it: it writes `<targetDir>/<name>.loradb` as of one committed
|
|
422
|
+
transaction while reads and writes continue, and resolves with
|
|
423
|
+
`{ path, bytes, lsn, nodeCount, relationshipCount }`. For a directory no
|
|
424
|
+
process has open, `npx lora snapshot <databaseDir> <targetDir>` does the
|
|
425
|
+
same. `db.checkpoint()` checkpoints on demand. See
|
|
426
|
+
[online backups](../wal.md#online-backups-of-a-named-database).
|
|
427
|
+
|
|
428
|
+
See the canonical [Snapshots guide](../snapshot.md) for the full
|
|
429
|
+
metadata shape, atomic-rename guarantees, and boundaries.
|
|
430
|
+
|
|
431
|
+
## Common Patterns
|
|
432
|
+
|
|
433
|
+
### Bulk insert from a JS array
|
|
434
|
+
|
|
435
|
+
```ts
|
|
436
|
+
const rows = [
|
|
437
|
+
{ id: 1, name: 'Ada' },
|
|
438
|
+
{ id: 2, name: 'Grace' },
|
|
439
|
+
{ id: 3, name: 'Alan' },
|
|
440
|
+
];
|
|
441
|
+
|
|
442
|
+
await db.execute(
|
|
443
|
+
`UNWIND $rows AS row
|
|
444
|
+
CREATE (:User {id: row.id, name: row.name})`,
|
|
445
|
+
{ rows }
|
|
446
|
+
);
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
See [`UNWIND`](../queries/unwind-merge.md#bulk-load-from-parameter).
|
|
450
|
+
|
|
451
|
+
### Typed helpers
|
|
452
|
+
|
|
453
|
+
Build typed temporal / spatial values in JS and pass them as
|
|
454
|
+
parameters:
|
|
455
|
+
|
|
456
|
+
```ts
|
|
457
|
+
import { createDatabase, date, duration, wgs84 } from '@loradb/lora-node';
|
|
458
|
+
|
|
459
|
+
const db = await createDatabase();
|
|
460
|
+
|
|
461
|
+
await db.execute(
|
|
462
|
+
"CREATE (:Trip {when: $when, span: $span, origin: $origin})",
|
|
463
|
+
{
|
|
464
|
+
when: date('2026-05-01'),
|
|
465
|
+
span: duration('PT90M'),
|
|
466
|
+
origin: wgs84(4.89, 52.37),
|
|
467
|
+
}
|
|
468
|
+
);
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
Available factories: `date`, `time`, `localtime`, `datetime`,
|
|
472
|
+
`localdatetime`, `duration`, `cartesian`, `cartesian3d`, `wgs84`,
|
|
473
|
+
`wgs84_3d`.
|
|
474
|
+
|
|
475
|
+
### Type guards
|
|
476
|
+
|
|
477
|
+
| Function | Narrows to |
|
|
478
|
+
|---|---|
|
|
479
|
+
| `isNode(v)` | `LoraNode` |
|
|
480
|
+
| `isRelationship(v)` | `LoraRelationship` |
|
|
481
|
+
| `isPath(v)` | `LoraPath` |
|
|
482
|
+
| `isPoint(v)` | `LoraPoint` |
|
|
483
|
+
| `isTemporal(v)` | any temporal variant |
|
|
484
|
+
|
|
485
|
+
### Other methods
|
|
486
|
+
|
|
487
|
+
```ts
|
|
488
|
+
await db.clear(); // drop all nodes + relationships
|
|
489
|
+
await db.nodeCount(); // number of nodes
|
|
490
|
+
await db.relationshipCount(); // number of relationships
|
|
491
|
+
db.dispose(); // release the native handle
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
`clear` / `nodeCount` / `relationshipCount` return Promises for API
|
|
495
|
+
symmetry but run synchronously inside the native layer. `dispose()` is
|
|
496
|
+
synchronous and idempotent; call it when you need to reopen the same
|
|
497
|
+
archive or WAL directory inside the same process.
|
|
498
|
+
|
|
499
|
+
### Repository pattern
|
|
500
|
+
|
|
501
|
+
`Database` is exported as a type-only symbol — use it to annotate
|
|
502
|
+
the instance that `createDatabase()` returned:
|
|
503
|
+
|
|
504
|
+
```ts
|
|
505
|
+
import { createDatabase, type Database } from '@loradb/lora-node';
|
|
506
|
+
|
|
507
|
+
export class UserRepo {
|
|
508
|
+
constructor(private readonly db: Database) {}
|
|
509
|
+
|
|
510
|
+
async upsert(id: number, handle: string) {
|
|
511
|
+
await this.db.execute(
|
|
512
|
+
`MERGE (u:User {id: $id})
|
|
513
|
+
ON CREATE SET u.created = temporal.timestamp()
|
|
514
|
+
SET u.handle = $handle, u.updated = temporal.timestamp()`,
|
|
515
|
+
{ id, handle }
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async findByHandle(handle: string) {
|
|
520
|
+
const { rows } = await this.db.execute(
|
|
521
|
+
"MATCH (u:User {handle: $handle}) RETURN u {.*} AS user",
|
|
522
|
+
{ handle }
|
|
523
|
+
);
|
|
524
|
+
return rows[0]?.user ?? null;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// Wire it up — initialization stays async-first at module scope.
|
|
529
|
+
const db = await createDatabase();
|
|
530
|
+
const users = new UserRepo(db);
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
## Common initialization mistakes
|
|
534
|
+
|
|
535
|
+
| ❌ Wrong | ✅ Right |
|
|
536
|
+
|---|---|
|
|
537
|
+
| `const db = new Database()` | `const db = await createDatabase()` |
|
|
538
|
+
| `const db = Database.create()` (missing `await`) | `const db = await createDatabase()` |
|
|
539
|
+
| `Database.create()` (legacy name) | `createDatabase()` |
|
|
540
|
+
| `import { Database } from '@loradb/lora-node'; new Database()` | `import { createDatabase } from '@loradb/lora-node'`; then `await createDatabase()` |
|
|
541
|
+
| `createDatabase(undefined, { walDir: './wal' })` | `openWalDatabase({ walDir: './wal' })` |
|
|
542
|
+
|
|
543
|
+
`Database` is a **type-only** export. Importing it as a value and
|
|
544
|
+
calling `new Database()` is a compile error — synchronous
|
|
545
|
+
initialization has been removed on purpose.
|
|
546
|
+
|
|
547
|
+
## Error Handling
|
|
548
|
+
|
|
549
|
+
Two classes to know:
|
|
550
|
+
|
|
551
|
+
| Class | When |
|
|
552
|
+
|---|---|
|
|
553
|
+
| `LoraError` | Any engine-level failure — parse, semantic, runtime |
|
|
554
|
+
| `InvalidParamsError` | Host supplied a parameter that couldn't be mapped to a `LoraValue` |
|
|
555
|
+
|
|
556
|
+
For the engine-level cases see the
|
|
557
|
+
[Troubleshooting guide](../troubleshooting.md).
|
|
558
|
+
|
|
559
|
+
## Performance / Best Practices
|
|
560
|
+
|
|
561
|
+
- **Integer precision.** Engine integers are `i64`. JS `number`
|
|
562
|
+
loses precision above `Number.MAX_SAFE_INTEGER` (2^53). For very
|
|
563
|
+
large IDs prefer `bigint` parameters or string encoding. See
|
|
564
|
+
[Troubleshooting → integer precision](../troubleshooting.md#integer-precision-lost-in-js).
|
|
565
|
+
- **Concurrency.** Each `Database` has its own in-memory graph. Auto-commit
|
|
566
|
+
reads can overlap on Arc snapshots; write commits and explicit read-write
|
|
567
|
+
transactions serialize. The event loop stays free while native work runs.
|
|
568
|
+
- **No cancellation.** Once dispatched, a query runs to completion.
|
|
569
|
+
Bound variable-length patterns and `UNWIND` list sizes.
|
|
570
|
+
- **Dispose explicitly** only when you need to release the native
|
|
571
|
+
handle eagerly, especially before reopening the same archive in
|
|
572
|
+
one process; otherwise GC eventually cleans up.
|
|
573
|
+
|
|
574
|
+
## See also
|
|
575
|
+
|
|
576
|
+
- [**Ten-Minute Tour**](./tutorial.md) — same queries in Node.
|
|
577
|
+
- [**Queries → Parameters**](../queries/parameters.md) — binding typed values.
|
|
578
|
+
- [**Cookbook**](../cookbook.md) — scenario-based recipes.
|
|
579
|
+
- [**Data Types**](../data-types/overview.md) — host-value mapping.
|
|
580
|
+
- [**WASM guide**](https://loradb.com/docs/getting-started/wasm) — same API, browser target.
|
|
581
|
+
- [**GraphQL for LoraDB**](https://loradb.com/docs/graphql): a schema-first GraphQL API on top of this binding.
|
|
582
|
+
- [**Troubleshooting**](../troubleshooting.md).
|