@cossackframework/romedb 0.9.1 → 0.9.3
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 +29 -0
- package/agent-docs.json +1 -1
- package/package.json +12 -6
- package/src/database.ts +74 -21
- package/src/index.ts +2 -0
- package/src/orm.ts +40 -0
- package/src/rql.ts +20 -1
package/README.md
CHANGED
|
@@ -30,6 +30,7 @@ On Workers, pass `url` and `token` instead of `connect`.
|
|
|
30
30
|
| `@cossackframework/romedb/values` | `Float64`, `RecordId`, `Vector`, `toTransport`, `fromTransport` (client-safe) |
|
|
31
31
|
| `@cossackframework/romedb/node` | `connectNode` (files through `@romedb/node`, `romedb serve` and Cloud by URL), `FilePendingWriteStore` |
|
|
32
32
|
| `@cossackframework/romedb/cloudflare` | `RomeDBPendingWrites` Durable Object and `DurableObjectPendingWriteStore` |
|
|
33
|
+
| `@cossackframework/romedb/orm` | `romedb(db)`, the adapter that runs the Cossack ORM (`@cossackframework/database`) on a RomeDB instance, with relational and document entities, and `romedbClient()`, the instance behind an ORM (see the database package's `docs/romedb.md`) |
|
|
33
34
|
| `@cossackframework/romedb/dev` | `romedbDev()` Vite plugin: starts `romedb serve` for a loopback `ROMEDB_URL` and passes its token, and, unless `ROMEDB_SITES_URL` is set, `romedb serve --directory storage/romedb/sites` on the next port for a CMS network's added sites (`ROMEDB_SITES_URL`, `ROMEDB_SITES_TOKEN`); `romedbDevVars` hands them to the Cloudflare plugin |
|
|
34
35
|
| `@cossackframework/romedb/testing` | `startRomeDBService` and `startRomeDBDirectory` for live tests against `romedb serve` |
|
|
35
36
|
|
|
@@ -55,8 +56,36 @@ Rules:
|
|
|
55
56
|
- Every write is saved before dispatch. A lost response leaves an `UncertainWriteError`;
|
|
56
57
|
`recoverPending()` replays the exact request. It never sends a replacement write.
|
|
57
58
|
- Reads send explicit `workLimits` and retry 503/429 backpressure a bounded number of times.
|
|
59
|
+
- The client allows 32 calls in flight. A call it refuses for lack of places (`RDB_LIMIT`,
|
|
60
|
+
outcome `not-sent`, `limit` `client-requests` or `client-bytes`) waits and tries again like
|
|
61
|
+
a 503, so a burst of requests queues instead of failing. `isClientFull(error)` tells such a
|
|
62
|
+
refusal from one about the call's size.
|
|
58
63
|
- Request paths never warm a Cloud database. Call `warm()` from a schedule.
|
|
59
64
|
|
|
65
|
+
## Requests that end early
|
|
66
|
+
|
|
67
|
+
One binding serves every request of an isolate, and a call gives its place back when it
|
|
68
|
+
settles. On Workers a call whose request ends first never settles: the visitor left, or the
|
|
69
|
+
request failed while other calls of the same `Promise.all` were in flight, and the runtime
|
|
70
|
+
cancelled their I/O with the request. Two things keep a binding serving:
|
|
71
|
+
|
|
72
|
+
- `requestSignal`: a function that gives the signal of the current request. A call that passes
|
|
73
|
+
no `signal` of its own takes it, so its calls end, and give their places back, when it aborts.
|
|
74
|
+
The CMS passes one that aborts when the visitor leaves or the request fails. In your own
|
|
75
|
+
application, abort a controller from your first middleware the same way:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { getRequestContext } from '@cossackframework/core';
|
|
79
|
+
|
|
80
|
+
const db = createRomeDB({ url, token, pending, requestSignal: () => getRequestContext()?.get('requestCalls')?.signal });
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Work that runs after the answer under `waitUntil` should not take a signal that the end of the
|
|
84
|
+
answer aborts.
|
|
85
|
+
- The client gives back the place of a call past its deadline (`timeoutMs`, 20 seconds by
|
|
86
|
+
default) when it is full, since `@romedb/client` 0.2.26. A call that never settles holds its
|
|
87
|
+
place until then; `requestSignal` gives it back at once.
|
|
88
|
+
|
|
60
89
|
Live tests run when `COSSACK_TEST_ROMEDB_BIN` points at a `romedb` executable (or
|
|
61
90
|
`romedb` is on `PATH`); `COSSACK_TEST_ROMEDB_URL` and `COSSACK_TEST_ROMEDB_TOKEN`
|
|
62
91
|
select an existing database instead.
|
package/agent-docs.json
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"@cossackframework/romedb/node",
|
|
11
11
|
"@cossackframework/romedb/cloudflare"
|
|
12
12
|
],
|
|
13
|
-
"markdown": "On Node.js, `createRomeDB({ url, connect: () => connectNode({ url, token }), pending })` opens the database with RomeDB's own libraries: a file path (the CMS default is `storage/romedb/app.romedb`) opens the file in this process through `@romedb/node` and needs no token, and a URL reaches `romedb serve` or a RomeDB Cloud database. One process owns a file; share a live database through `romedb serve`. On Cloudflare Workers, `createRomeDB({ url, token, pending })` connects with `@romedb/client`, which uses Web APIs only, has no native addon and needs no `nodejs_compat`. Node applications that open files list `@romedb/node` at the same version as `@romedb/client`. Statements are `{ rql, params }`; the binding hands the text to RomeDB's client, whose results, values and `ClientError` pass through unchanged. The token is a server-only secret: a local service token or a Cloud database grant with `query` scope. In development, the `romedbDev()` Vite plugin from `@cossackframework/romedb/dev` starts `romedb serve` for a loopback `ROMEDB_URL` and passes its token, so it is never copied into `.env`.\n\nEvery write is saved in the pending store before dispatch. Use `FilePendingWriteStore` from `@cossackframework/romedb/node` on Node and `DurableObjectPendingWriteStore` with the exported `RomeDBPendingWrites` Durable Object on Workers; `MemoryPendingWriteStore` is for tests. When a response is lost after dispatch, `write()` throws `UncertainWriteError` and keeps the saved request. `recoverPending()` replays the exact request ID and body from a scheduled path; it never sends a replacement write. A write outside the 64-request receipt window needs a reconciler for its `kind`.\n\nReads use `/read` with `afterSequence` as a causal lower bound. Each call sends explicit `workLimits` (defaults from the binding). Responses with 503 or 429 and `retry-after` are retried a bounded number of times. `preflight()` reads the engine release and throws `EngineVersionError` for engines older than 0.2.9; local services are checked at connect. Request paths never warm a Cloud database: call `warm()` from a schedule. `retryConflicts` re-runs a batch the engine rolled back for a concurrent write to the same rows, only where re-evaluating the statements is correct.",
|
|
13
|
+
"markdown": "On Node.js, `createRomeDB({ url, connect: () => connectNode({ url, token }), pending })` opens the database with RomeDB's own libraries: a file path (the CMS default is `storage/romedb/app.romedb`) opens the file in this process through `@romedb/node` and needs no token, and a URL reaches `romedb serve` or a RomeDB Cloud database. One process owns a file; share a live database through `romedb serve`. On Cloudflare Workers, `createRomeDB({ url, token, pending })` connects with `@romedb/client`, which uses Web APIs only, has no native addon and needs no `nodejs_compat`. Node applications that open files list `@romedb/node` at the same version as `@romedb/client`. Statements are `{ rql, params }`; the binding hands the text to RomeDB's client, whose results, values and `ClientError` pass through unchanged. The token is a server-only secret: a local service token or a Cloud database grant with `query` scope. In development, the `romedbDev()` Vite plugin from `@cossackframework/romedb/dev` starts `romedb serve` for a loopback `ROMEDB_URL` and passes its token, so it is never copied into `.env`.\n\nEvery write is saved in the pending store before dispatch. Use `FilePendingWriteStore` from `@cossackframework/romedb/node` on Node and `DurableObjectPendingWriteStore` with the exported `RomeDBPendingWrites` Durable Object on Workers; `MemoryPendingWriteStore` is for tests. When a response is lost after dispatch, `write()` throws `UncertainWriteError` and keeps the saved request. `recoverPending()` replays the exact request ID and body from a scheduled path; it never sends a replacement write. A write outside the 64-request receipt window needs a reconciler for its `kind`.\n\nReads use `/read` with `afterSequence` as a causal lower bound. Each call sends explicit `workLimits` (defaults from the binding). Responses with 503 or 429 and `retry-after` are retried a bounded number of times. A call the client refuses for lack of places (`RDB_LIMIT`, outcome `not-sent`: 32 calls in flight) waits and tries again the same way. Pass `requestSignal: () => <the current request's signal>` so a request's calls end when the visitor leaves or the request fails: on Workers a call whose request ends first never settles. When the client is full and holds calls 5 seconds past their deadline, those calls were stranded and the binding opens a new client (never for a client from `connect`). `preflight()` reads the engine release and throws `EngineVersionError` for engines older than 0.2.9; local services are checked at connect. Request paths never warm a Cloud database: call `warm()` from a schedule. `retryConflicts` re-runs a batch the engine rolled back for a concurrent write to the same rows, only where re-evaluating the statements is correct.",
|
|
14
14
|
"examples": [
|
|
15
15
|
{
|
|
16
16
|
"id": "romedb-request-binding",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cossackframework/romedb",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "RomeDB request bindings for Cossack on Workers and Node.js, on RomeDB's own client",
|
|
6
6
|
"license": "MIT",
|
|
@@ -18,18 +18,20 @@
|
|
|
18
18
|
"access": "public"
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@romedb/client": "0.2.
|
|
21
|
+
"@romedb/client": "0.2.27"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@romedb/node": "0.2.
|
|
24
|
+
"@romedb/node": "0.2.27",
|
|
25
25
|
"@types/node": "^22.19.0",
|
|
26
|
-
"vitest": "^4.1.12"
|
|
26
|
+
"vitest": "^4.1.12",
|
|
27
|
+
"@cossackframework/database": "0.9.3"
|
|
27
28
|
},
|
|
28
29
|
"exports": {
|
|
29
30
|
".": "./src/index.ts",
|
|
30
31
|
"./values": "./src/values-entry.ts",
|
|
31
32
|
"./node": "./src/node.ts",
|
|
32
33
|
"./cloudflare": "./src/cloudflare.ts",
|
|
34
|
+
"./orm": "./src/orm.ts",
|
|
33
35
|
"./testing": "./src/testing.ts",
|
|
34
36
|
"./dev": {
|
|
35
37
|
"types": "./src/dev.d.ts",
|
|
@@ -38,10 +40,14 @@
|
|
|
38
40
|
"./package.json": "./package.json"
|
|
39
41
|
},
|
|
40
42
|
"peerDependencies": {
|
|
41
|
-
"@romedb/node": "0.2.
|
|
42
|
-
"vite": "*"
|
|
43
|
+
"@romedb/node": "0.2.27",
|
|
44
|
+
"vite": "*",
|
|
45
|
+
"@cossackframework/database": "0.9.3"
|
|
43
46
|
},
|
|
44
47
|
"peerDependenciesMeta": {
|
|
48
|
+
"@cossackframework/database": {
|
|
49
|
+
"optional": true
|
|
50
|
+
},
|
|
45
51
|
"@romedb/node": {
|
|
46
52
|
"optional": true
|
|
47
53
|
},
|
package/src/database.ts
CHANGED
|
@@ -75,6 +75,14 @@ export interface RomeDBOptions {
|
|
|
75
75
|
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
76
76
|
/** Reconcilers by pending write kind, used when a write left the 64-request receipt window. */
|
|
77
77
|
reconcilers?: { [kind: string]: Reconciler };
|
|
78
|
+
/**
|
|
79
|
+
* The signal of the request a call is made for, used when the call passes no `signal` of its
|
|
80
|
+
* own. When it aborts, the request's calls end and give their places back. On Workers a call
|
|
81
|
+
* whose request ends first never settles and keeps its place for good, so pass a signal that
|
|
82
|
+
* aborts when the visitor leaves or the request fails, such as the CMS's (see the package
|
|
83
|
+
* README, "Requests that end early").
|
|
84
|
+
*/
|
|
85
|
+
requestSignal?: () => AbortSignal | undefined;
|
|
78
86
|
}
|
|
79
87
|
|
|
80
88
|
/**
|
|
@@ -170,6 +178,15 @@ export class UncertainWriteError extends Error {
|
|
|
170
178
|
}
|
|
171
179
|
}
|
|
172
180
|
|
|
181
|
+
/**
|
|
182
|
+
* The client refused a call for lack of places: it allows 32 calls (and 2 MiB of request
|
|
183
|
+
* bodies) in flight. Nothing was sent, and it passes once earlier calls end, so it says
|
|
184
|
+
* nothing about the call's size. The binding waits and tries again before it gives up.
|
|
185
|
+
*/
|
|
186
|
+
export function isClientFull(error: unknown): boolean {
|
|
187
|
+
return error instanceof ClientError && error.code === 'RDB_LIMIT' && (error.limit === 'client-requests' || error.limit === 'client-bytes');
|
|
188
|
+
}
|
|
189
|
+
|
|
173
190
|
const DEFAULT_LIMITS: RomeDBWorkLimits = {
|
|
174
191
|
read: { rowsRead: 50_000, vmSteps: 2_000_000 },
|
|
175
192
|
write: { rowsRead: 50_000, rowMutations: 1_000, vmSteps: 2_000_000 },
|
|
@@ -177,7 +194,11 @@ const DEFAULT_LIMITS: RomeDBWorkLimits = {
|
|
|
177
194
|
|
|
178
195
|
/**
|
|
179
196
|
* One database binding per isolate or process. Calls are request-scoped through their
|
|
180
|
-
* options: pass the request's AbortSignal and explicit budgets.
|
|
197
|
+
* options: pass the request's AbortSignal (or `requestSignal`) and explicit budgets.
|
|
198
|
+
*
|
|
199
|
+
* A client that refuses a call for lack of places is backpressure: the call waits and tries
|
|
200
|
+
* again, like a 503. The client gives back the place of a call past its deadline itself, so a
|
|
201
|
+
* call that never settles (on Workers, one whose request ended first) holds its place no longer.
|
|
181
202
|
*/
|
|
182
203
|
export class RomeDB {
|
|
183
204
|
readonly url: string;
|
|
@@ -237,16 +258,17 @@ export class RomeDB {
|
|
|
237
258
|
|
|
238
259
|
/** Fresh snapshot read with bounded backpressure retries. Reads are always safe to retry. */
|
|
239
260
|
async read(statements: Statement[], options: ReadCallOptions = {}): Promise<BatchResult> {
|
|
240
|
-
const
|
|
241
|
-
const call = { ...
|
|
261
|
+
const scoped = this.#scoped(options);
|
|
262
|
+
const call = { ...scoped, workLimits: scoped.workLimits ?? this.#limits.read };
|
|
242
263
|
for (let attempt = 1; ; attempt++) {
|
|
264
|
+
const client = await this.#connection();
|
|
243
265
|
try {
|
|
244
266
|
return await client.read(clientStatements(statements), call);
|
|
245
267
|
} catch (error) {
|
|
246
268
|
if (tooLarge(error)) throw new RequestTooLargeError(error);
|
|
247
|
-
const delay = this.#retryDelay(error, attempt,
|
|
269
|
+
const delay = this.#retryDelay(error, attempt, call.signal);
|
|
248
270
|
if (delay === undefined) throw error;
|
|
249
|
-
await this.#
|
|
271
|
+
await this.#wait(delay, call.signal);
|
|
250
272
|
}
|
|
251
273
|
}
|
|
252
274
|
}
|
|
@@ -256,19 +278,30 @@ export class RomeDB {
|
|
|
256
278
|
* recovered with the same request ID and body, never with a replacement write.
|
|
257
279
|
*/
|
|
258
280
|
async write(statements: Statement[], options: WriteCallOptions = {}): Promise<BatchResult> {
|
|
259
|
-
const
|
|
260
|
-
|
|
281
|
+
const call = this.#scoped(options);
|
|
282
|
+
const retries = call.retryConflicts ?? 0;
|
|
283
|
+
let conflicts = 0;
|
|
284
|
+
let refusals = 0;
|
|
285
|
+
for (;;) {
|
|
286
|
+
const client = await this.#connection();
|
|
261
287
|
try {
|
|
262
|
-
|
|
288
|
+
// A batch refused for lack of places was never sent: it keeps its request ID.
|
|
289
|
+
return await this.#writeOnce(client, statements, conflicts === 0 ? call : { ...call, requestId: undefined });
|
|
263
290
|
} catch (error) {
|
|
264
|
-
if (
|
|
265
|
-
|
|
291
|
+
if (isClientFull(error)) {
|
|
292
|
+
const delay = this.#retryDelay(error, ++refusals, call.signal);
|
|
293
|
+
if (delay === undefined) throw error;
|
|
294
|
+
await this.#wait(delay, call.signal);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (conflicts >= retries || !(error instanceof ClientError) || error.outcome !== 'rolled-back' || error.code !== 'RDB_WRITE_CONFLICT') throw error;
|
|
298
|
+
conflicts++;
|
|
299
|
+
await this.#sleep(Math.floor(Math.random() * 10 * conflicts), call.signal).catch(() => {});
|
|
266
300
|
}
|
|
267
301
|
}
|
|
268
302
|
}
|
|
269
303
|
|
|
270
|
-
async #writeOnce(statements: Statement[], options: WriteCallOptions): Promise<BatchResult> {
|
|
271
|
-
const client = await this.#connection();
|
|
304
|
+
async #writeOnce(client: DatabaseClient, statements: Statement[], options: WriteCallOptions): Promise<BatchResult> {
|
|
272
305
|
if (options.afterSequence === undefined && !client.sequenceKnown) await this.preflight(options);
|
|
273
306
|
let request: PreparedWrite;
|
|
274
307
|
try {
|
|
@@ -416,6 +449,22 @@ export class RomeDB {
|
|
|
416
449
|
if (client) await (await client.catch(() => undefined))?.close();
|
|
417
450
|
}
|
|
418
451
|
|
|
452
|
+
/** Wait before a call tries again; a signal that aborts meanwhile ends the call, unsent. */
|
|
453
|
+
async #wait(ms: number, signal: AbortSignal | undefined): Promise<void> {
|
|
454
|
+
try { await this.#sleep(ms, signal); }
|
|
455
|
+
catch (cause) {
|
|
456
|
+
if (signal?.aborted) throw new ClientError('RDB_CANCELLED', 'Request cancelled before dispatch', 'not-sent', { cause });
|
|
457
|
+
throw cause;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** The call's own signal, or else the request's. */
|
|
462
|
+
#scoped<T extends RequestOptions>(options: T): T {
|
|
463
|
+
if (options.signal !== undefined) return options;
|
|
464
|
+
const signal = this.#options.requestSignal?.();
|
|
465
|
+
return signal ? { ...options, signal } : options;
|
|
466
|
+
}
|
|
467
|
+
|
|
419
468
|
#connection(): Promise<DatabaseClient> {
|
|
420
469
|
if (!this.#client) {
|
|
421
470
|
const { url, token, timeoutMs, fetch } = this.#options;
|
|
@@ -425,17 +474,19 @@ export class RomeDB {
|
|
|
425
474
|
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
|
426
475
|
...(fetch === undefined ? {} : { fetch }),
|
|
427
476
|
}));
|
|
428
|
-
|
|
429
|
-
if (cloud(client))
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
477
|
+
const opening: Promise<DatabaseClient> = open().then(async client => {
|
|
478
|
+
if (!cloud(client)) {
|
|
479
|
+
// Files and local services answer details at once; check the engine right away.
|
|
480
|
+
try {
|
|
481
|
+
const info = await client.info();
|
|
482
|
+
checkEngine(info.engineVersion, this.#required);
|
|
483
|
+
if (this.#client === opening) this.#preflight = Promise.resolve(info);
|
|
484
|
+
} catch (error) { await client.close(); throw error; }
|
|
485
|
+
}
|
|
436
486
|
return client;
|
|
437
487
|
});
|
|
438
|
-
this.#client
|
|
488
|
+
this.#client = opening;
|
|
489
|
+
opening.catch(() => { if (this.#client === opening) { this.#client = undefined; this.#preflight = undefined; } });
|
|
439
490
|
}
|
|
440
491
|
return this.#client;
|
|
441
492
|
}
|
|
@@ -443,6 +494,8 @@ export class RomeDB {
|
|
|
443
494
|
#retryDelay(error: unknown, attempt: number, signal: AbortSignal | undefined, writing = false): number | undefined {
|
|
444
495
|
if (attempt >= this.#attempts || signal?.aborted || !(error instanceof ClientError)) return undefined;
|
|
445
496
|
if (error.code === 'RDB_CANCELLED' || error.code === 'RDB_AUTH' || error.code === 'RDB_FORBIDDEN' || error.code === 'RDB_CLOSED') return undefined;
|
|
497
|
+
// The client's own places are full: wait for calls of other requests to settle.
|
|
498
|
+
if (isClientFull(error)) return Math.min(this.#maxDelay, 25 * 2 ** attempt) + Math.floor(Math.random() * 50);
|
|
446
499
|
const backpressure = error.status === 503 || error.status === 429;
|
|
447
500
|
if (!backpressure && !(writing && error.outcome === 'unknown') && !(error.outcome === 'read-failed' && (error.code === 'RDB_TRANSPORT' || error.status === undefined))) return undefined;
|
|
448
501
|
const base = error.retryAfterMs ?? 50 * 2 ** (attempt - 1);
|
package/src/index.ts
CHANGED
|
@@ -25,6 +25,7 @@ export {
|
|
|
25
25
|
type ConnectOptions,
|
|
26
26
|
type WarmResult,
|
|
27
27
|
type Outcome,
|
|
28
|
+
type ClientLimit,
|
|
28
29
|
type Value,
|
|
29
30
|
type PortableValue,
|
|
30
31
|
} from '@romedb/client';
|
|
@@ -42,6 +43,7 @@ export {
|
|
|
42
43
|
EngineVersionError,
|
|
43
44
|
UncertainWriteError,
|
|
44
45
|
RequestTooLargeError,
|
|
46
|
+
isClientFull,
|
|
45
47
|
MAX_STATEMENTS,
|
|
46
48
|
LOCAL_REQUEST_BYTES,
|
|
47
49
|
CLOUD_REQUEST_BYTES,
|
package/src/orm.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// RomeDB as the database of the Cossack ORM (`@cossackframework/database`).
|
|
2
|
+
import {
|
|
3
|
+
romedb as adapter,
|
|
4
|
+
romedbClient as client,
|
|
5
|
+
type RomeDBAdapterOptions,
|
|
6
|
+
} from '@cossackframework/database/romedb';
|
|
7
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
|
+
import type { Adapter, ORM } from '@cossackframework/database';
|
|
9
|
+
import { createAsyncLocalScope } from '@cossackframework/database/adapter';
|
|
10
|
+
import { Float64, Record as RecordId } from '@romedb/client';
|
|
11
|
+
import type { RomeDB } from './database';
|
|
12
|
+
|
|
13
|
+
export { RecordLink, isRecordLink, type RecordKey } from '@cossackframework/database/romedb';
|
|
14
|
+
|
|
15
|
+
export type RomeDBOrmOptions = Omit<RomeDBAdapterOptions, 'values'>;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* An ORM adapter on a RomeDB instance. Relational entities are SQLite-dialect tables and
|
|
19
|
+
* `@Entity({ model: 'document' })` entities are document tables. Each ORM statement is one
|
|
20
|
+
* request; an ORM batch is one atomic write. There are no interactive transactions.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* const orm = createORM({ adapter: await romedb(db), entities });
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export async function romedb(db: RomeDB, options: RomeDBOrmOptions = {}): Promise<Adapter> {
|
|
27
|
+
// For the ORM's commands: a file or a loopback service is the local database.
|
|
28
|
+
const local = !/^https?:\/\//i.test(db.url) || /^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i.test(db.url);
|
|
29
|
+
const created = await adapter(db, { tooling: { provider: 'romedb', target: local ? 'local' : 'remote' }, ...options, values: { RecordId, Float64 } });
|
|
30
|
+
// Each request keeps its own scope, also while several ORMs (one per database) are open.
|
|
31
|
+
return { ...created, scope: createAsyncLocalScope(new AsyncLocalStorage()) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The RomeDB instance an ORM runs on, for RomeQL the ORM does not write: record links,
|
|
36
|
+
* graph traversal, vectors and search. Without an argument it is the ORM of the current scope.
|
|
37
|
+
*/
|
|
38
|
+
export function romedbClient(orm?: ORM): RomeDB {
|
|
39
|
+
return client<RomeDB>(orm);
|
|
40
|
+
}
|
package/src/rql.ts
CHANGED
|
@@ -22,6 +22,12 @@ export interface RqlDatabaseOptions {
|
|
|
22
22
|
/** Pending-write label for reconciliation. Default `rql`. */
|
|
23
23
|
kind?: string;
|
|
24
24
|
signal?: AbortSignal;
|
|
25
|
+
/**
|
|
26
|
+
* Statements that create the tables, run once before the first statement: SQL text with
|
|
27
|
+
* statements separated by `;`, such as `jobStateSchema` from `@cossackframework/core/jobs`.
|
|
28
|
+
* Use `CREATE ... IF NOT EXISTS`. A failure is not kept: the next statement runs them again.
|
|
29
|
+
*/
|
|
30
|
+
schema?: string | readonly string[];
|
|
25
31
|
}
|
|
26
32
|
|
|
27
33
|
/**
|
|
@@ -30,6 +36,16 @@ export interface RqlDatabaseOptions {
|
|
|
30
36
|
* affected count is reported as `meta.changes`. Integer results that fit become numbers.
|
|
31
37
|
*/
|
|
32
38
|
export function rqlDatabase(db: RomeDB, options: RqlDatabaseOptions = {}): RqlDatabase {
|
|
39
|
+
const schema = (typeof options.schema === 'string' ? [options.schema] : options.schema ?? [])
|
|
40
|
+
.flatMap(text => text.split(/;\s*(?:\n|$)/)).map(text => text.trim()).filter(Boolean);
|
|
41
|
+
let created: Promise<unknown> | undefined;
|
|
42
|
+
// Each statement of the schema is its own write: a batch of DDL is not atomic anyway.
|
|
43
|
+
const ready = () => {
|
|
44
|
+
if (!schema.length) return undefined;
|
|
45
|
+
created ??= schema.reduce<Promise<unknown>>((before, rql) => before.then(() => db.write([{ rql }], { kind: options.kind ?? 'rql', ...(options.signal ? { signal: options.signal } : {}) })), Promise.resolve());
|
|
46
|
+
created.catch(() => { created = undefined; });
|
|
47
|
+
return created;
|
|
48
|
+
};
|
|
33
49
|
return {
|
|
34
50
|
prepare(sql: string): RqlStatement {
|
|
35
51
|
const text = numberPlaceholders(sql);
|
|
@@ -41,7 +57,10 @@ export function rqlDatabase(db: RomeDB, options: RqlDatabaseOptions = {}): RqlDa
|
|
|
41
57
|
const statement = values.length ? { rql: text, params } : { rql: text };
|
|
42
58
|
// A rolled-back write conflict re-runs as if the writes were serial.
|
|
43
59
|
const call: WriteCallOptions = { kind: options.kind ?? 'rql', retryConflicts: 5, ...(options.signal ? { signal: options.signal } : {}) };
|
|
44
|
-
const execute = () =>
|
|
60
|
+
const execute = async () => {
|
|
61
|
+
await ready();
|
|
62
|
+
return reading ? db.read([statement], call) : db.write([statement], call);
|
|
63
|
+
};
|
|
45
64
|
const rows = async () => {
|
|
46
65
|
const result = (await execute()).results[0]!;
|
|
47
66
|
return result.rows.map(row => Object.fromEntries(result.columns.map((name, index) => [name, plain(row[index]!)])));
|