@decohere/data-memory 0.0.1-dev.20261122.343 → 0.0.1-dev.5

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.
@@ -0,0 +1,508 @@
1
+ import {
2
+ comparison,
3
+ type Comparison,
4
+ DataConfigurationError,
5
+ DataError,
6
+ type EntityClass,
7
+ type Row,
8
+ type RowQuery,
9
+ } from "@decohere/data";
10
+ import { type MemoryEntity, memoryEntities } from "./memory-entity.js";
11
+
12
+ /**
13
+ * Row locks, as Postgres takes them: a reference check takes `key-share` on the row it points at,
14
+ * an update that keeps the key takes `no-key-update`, and a delete, a key change or
15
+ * `lock: "update"` takes `update`. Each blocks only the modes Postgres says it conflicts with.
16
+ */
17
+ type LockMode = "key-share" | "no-key-update" | "update";
18
+
19
+ const CONFLICTS: Record<LockMode, readonly LockMode[]> = {
20
+ "key-share": ["update"],
21
+ "no-key-update": ["no-key-update", "update"],
22
+ update: ["key-share", "no-key-update", "update"],
23
+ };
24
+ const STRENGTH: Record<LockMode, number> = { "key-share": 0, "no-key-update": 1, update: 2 };
25
+
26
+ /** One transaction: its writes, kept apart until commit, and the row locks it holds. */
27
+ export class MemoryTransaction {
28
+ /** Per class, by key: the row as this transaction wrote it, or null where it deleted one. */
29
+ public readonly writes = new Map<EntityClass, Map<string, Row | null>>();
30
+ public readonly held: { type: EntityClass; key: string }[] = [];
31
+ /** The transactions holding locks this one waits for. */
32
+ public waitingFor = new Set<MemoryTransaction>();
33
+ /** The error that aborted it: after a failed statement, as in Postgres, it only rolls back. */
34
+ public aborted: unknown;
35
+ public finished = false;
36
+ public readonly done: Promise<void>;
37
+ private settle!: () => void;
38
+
39
+ public constructor() {
40
+ this.done = new Promise((resolve) => {
41
+ this.settle = resolve;
42
+ });
43
+ }
44
+
45
+ public finish() {
46
+ this.finished = true;
47
+ this.settle();
48
+ }
49
+ }
50
+
51
+ /**
52
+ * The rows of one data source, held in the process. Reads see what is committed plus their own
53
+ * transaction's writes (read committed); a commit applies a transaction's writes in one step.
54
+ * Rows are copied in and out, so an object held outside can't change what is stored.
55
+ */
56
+ export class MemoryStore {
57
+ private readonly models: Map<EntityClass, MemoryEntity>;
58
+ private readonly tables = new Map<EntityClass, Map<string, Row>>();
59
+ private readonly sequences = new Map<EntityClass, number>();
60
+ private readonly locks = new Map<
61
+ EntityClass,
62
+ Map<string, Map<MemoryTransaction, LockMode>>
63
+ >();
64
+
65
+ public constructor(entities: readonly MemoryEntity[]) {
66
+ this.models = memoryEntities.check(entities);
67
+ }
68
+
69
+ public model(type: EntityClass): MemoryEntity {
70
+ const model = this.models.get(type);
71
+ if (model == null) {
72
+ throw new DataConfigurationError(
73
+ `${type.name} isn't mapped: add mapEntity(${type.name}, …) to memory()'s entities`,
74
+ );
75
+ }
76
+ return model;
77
+ }
78
+
79
+ public begin(): MemoryTransaction {
80
+ return new MemoryTransaction();
81
+ }
82
+
83
+ public commit(tx: MemoryTransaction) {
84
+ this.assertOpen(tx);
85
+ if (tx.aborted !== undefined) {
86
+ this.rollback(tx);
87
+ throw new DataError(
88
+ "The transaction was aborted by an earlier error, so it was rolled back",
89
+ {
90
+ cause: tx.aborted,
91
+ },
92
+ );
93
+ }
94
+ for (const [type, writes] of tx.writes) {
95
+ const table = this.table(type);
96
+ for (const [key, row] of writes) {
97
+ if (row === null) table.delete(key);
98
+ else table.set(key, row);
99
+ }
100
+ }
101
+ this.end(tx);
102
+ }
103
+
104
+ public rollback(tx: MemoryTransaction) {
105
+ this.assertOpen(tx);
106
+ this.end(tx);
107
+ }
108
+
109
+ public select(tx: MemoryTransaction, type: EntityClass, query: RowQuery): Promise<Row[]> {
110
+ return this.statement(tx, async () => {
111
+ const model = this.model(type);
112
+ for (const prop of Object.keys(query.where ?? {})) this.assertProp(model, prop);
113
+ for (const prop of Object.keys(query.orderBy ?? {})) this.assertProp(model, prop);
114
+ let found = this.query(tx, type, query);
115
+ if (query.lock === "update") {
116
+ // Lock what matched, then read again: a row another transaction changed while this one
117
+ // waited is read as it now is, and dropped if it no longer matches.
118
+ for (;;) {
119
+ const unlocked = found.filter(([key]) => !this.holds(tx, type, key, "update"));
120
+ if (unlocked.length === 0) break;
121
+ for (const [key] of unlocked) await this.acquire(tx, type, key, "update");
122
+ found = this.query(tx, type, query);
123
+ }
124
+ }
125
+ const props = [...model.fields, ...model.references.map((r) => r.prop)];
126
+ return found.map(([, row]) =>
127
+ Object.fromEntries(props.map((prop) => [prop, copy(row[prop] ?? null)])),
128
+ );
129
+ });
130
+ }
131
+
132
+ public insert(tx: MemoryTransaction, type: EntityClass, rows: Row[]): Promise<Row[]> {
133
+ return this.statement(tx, async () => {
134
+ const model = this.model(type);
135
+ const generated: Row[] = [];
136
+ for (const input of rows) {
137
+ const row = copy(input) as Row;
138
+ const out: Row = {};
139
+ if (model.generated && row[model.generated] == null) {
140
+ const next = (this.sequences.get(type) ?? 0) + 1;
141
+ this.sequences.set(type, next);
142
+ row[model.generated] = next;
143
+ out[model.generated] = next;
144
+ }
145
+ for (const prop of model.key) {
146
+ if (row[prop] == null) throw new DataError(`${model.name}: key ${prop} is empty`);
147
+ }
148
+ await this.checkReferences(
149
+ tx,
150
+ model,
151
+ row,
152
+ model.references.map((r) => r.prop),
153
+ );
154
+ const key = this.keyOf(model, row);
155
+ await this.acquire(tx, type, key, "update");
156
+ if (this.row(tx, type, key)) {
157
+ throw new DataError(`${model.name} ${this.describe(model, row)} already exists`);
158
+ }
159
+ this.write(tx, type, key, row);
160
+ generated.push(out);
161
+ }
162
+ return generated;
163
+ });
164
+ }
165
+
166
+ public update(
167
+ tx: MemoryTransaction,
168
+ type: EntityClass,
169
+ keyRow: Row,
170
+ changes: Row,
171
+ version?: { prop: string; expected: unknown },
172
+ ): Promise<number> {
173
+ return this.statement(tx, async () => {
174
+ const model = this.model(type);
175
+ for (const prop of Object.keys(changes)) this.assertProp(model, prop);
176
+ const key = this.keyOf(model, keyRow);
177
+ const changesKey = model.key.some(
178
+ (prop) => prop in changes && !equal(changes[prop], keyRow[prop]),
179
+ );
180
+ await this.acquire(tx, type, key, changesKey ? "update" : "no-key-update");
181
+ const current = this.row(tx, type, key);
182
+ if (current == null) return 0;
183
+ if (version && !equal(current[version.prop], version.expected)) return 0;
184
+ const next = { ...current, ...(copy(changes) as Row) };
185
+ await this.checkReferences(tx, model, next, Object.keys(changes));
186
+ if (!changesKey) {
187
+ this.write(tx, type, key, next);
188
+ return 1;
189
+ }
190
+ const nextKey = this.keyOf(model, next);
191
+ await this.acquire(tx, type, nextKey, "update");
192
+ if (this.row(tx, type, nextKey)) {
193
+ throw new DataError(`${model.name} ${this.describe(model, next)} already exists`);
194
+ }
195
+ this.assertUnreferenced(tx, model, current);
196
+ this.write(tx, type, key, null);
197
+ this.write(tx, type, nextKey, next);
198
+ return 1;
199
+ });
200
+ }
201
+
202
+ public delete(tx: MemoryTransaction, type: EntityClass, keys: Row[]): Promise<void> {
203
+ return this.statement(tx, async () => {
204
+ const model = this.model(type);
205
+ const deleted: { model: MemoryEntity; row: Row }[] = [];
206
+ for (const keyRow of keys) {
207
+ const key = this.keyOf(model, keyRow);
208
+ await this.acquire(tx, type, key, "update");
209
+ const row = this.row(tx, type, key);
210
+ if (row == null) continue;
211
+ this.write(tx, type, key, null);
212
+ deleted.push({ model, row });
213
+ }
214
+ // Then what referenced them: cascaded where the reference says so, refused otherwise.
215
+ for (let i = 0; i < deleted.length; i++) {
216
+ const { model: parent, row } = deleted[i];
217
+ for (const { child, ref, key, row: referencing } of this.referencing(
218
+ tx,
219
+ parent,
220
+ row,
221
+ )) {
222
+ if (ref.onDelete !== "cascade") {
223
+ throw new DataError(
224
+ `Can't delete ${parent.name} ${this.describe(parent, row)}: ${child.name}.${ref.prop} still references it`,
225
+ );
226
+ }
227
+ await this.acquire(tx, child.type, key, "update");
228
+ if (this.row(tx, child.type, key) == null) continue;
229
+ this.write(tx, child.type, key, null);
230
+ deleted.push({ model: child, row: referencing });
231
+ }
232
+ }
233
+ });
234
+ }
235
+
236
+ // ── Rows ───────────────────────────────────────────────────────────────
237
+
238
+ private query(tx: MemoryTransaction, type: EntityClass, query: RowQuery): [string, Row][] {
239
+ const where = Object.entries(query.where ?? {});
240
+ const found = [...this.rows(tx, type)].filter(([, row]) =>
241
+ where.every(([prop, condition]) => matches(row[prop] ?? null, condition)),
242
+ );
243
+ const orderBy = Object.entries(query.orderBy ?? {});
244
+ if (orderBy.length > 0) {
245
+ found.sort(([, a], [, b]) => {
246
+ for (const [prop, direction] of orderBy) {
247
+ const order = sortOrder(a[prop] ?? null, b[prop] ?? null, direction);
248
+ if (order !== 0) return order;
249
+ }
250
+ return 0;
251
+ });
252
+ }
253
+ return query.limit === undefined ? found : found.slice(0, query.limit);
254
+ }
255
+
256
+ /** Every row as this transaction sees it: committed, then overlaid with its own writes. */
257
+ private *rows(tx: MemoryTransaction, type: EntityClass): Iterable<[string, Row]> {
258
+ const table = this.table(type);
259
+ const writes = tx.writes.get(type);
260
+ for (const [key, row] of table) {
261
+ const written = writes?.get(key);
262
+ if (written === undefined) yield [key, row];
263
+ else if (written !== null) yield [key, written];
264
+ }
265
+ for (const [key, row] of writes ?? []) {
266
+ if (row !== null && !table.has(key)) yield [key, row];
267
+ }
268
+ }
269
+
270
+ private row(tx: MemoryTransaction, type: EntityClass, key: string): Row | undefined {
271
+ const written = tx.writes.get(type)?.get(key);
272
+ if (written !== undefined) return written ?? undefined;
273
+ return this.table(type).get(key);
274
+ }
275
+
276
+ private write(tx: MemoryTransaction, type: EntityClass, key: string, row: Row | null) {
277
+ let writes = tx.writes.get(type);
278
+ if (writes == null) {
279
+ writes = new Map();
280
+ tx.writes.set(type, writes);
281
+ }
282
+ writes.set(key, row);
283
+ }
284
+
285
+ private table(type: EntityClass): Map<string, Row> {
286
+ let table = this.tables.get(type);
287
+ if (table == null) {
288
+ table = new Map();
289
+ this.tables.set(type, table);
290
+ }
291
+ return table;
292
+ }
293
+
294
+ /** A row's references, as a foreign key checks them: each set one points at a row that exists. */
295
+ private async checkReferences(
296
+ tx: MemoryTransaction,
297
+ model: MemoryEntity,
298
+ row: Row,
299
+ props: string[],
300
+ ) {
301
+ for (const ref of model.references) {
302
+ if (!props.includes(ref.prop)) continue;
303
+ const value = row[ref.prop];
304
+ if (value == null) {
305
+ if (ref.nullable) continue;
306
+ throw new DataError(`${model.name}.${ref.prop} can't be empty`);
307
+ }
308
+ const target = this.model(ref.target);
309
+ const key = this.keyOf(target, { [target.key[0]]: value });
310
+ await this.acquire(tx, ref.target, key, "key-share");
311
+ if (this.row(tx, ref.target, key) == null) {
312
+ throw new DataError(
313
+ `${model.name}.${ref.prop} references ${target.name} ${String(value)}, which doesn't exist`,
314
+ );
315
+ }
316
+ }
317
+ }
318
+
319
+ private referencing(tx: MemoryTransaction, parent: MemoryEntity, row: Row) {
320
+ const found: {
321
+ child: MemoryEntity;
322
+ ref: MemoryEntity["references"][number];
323
+ key: string;
324
+ row: Row;
325
+ }[] = [];
326
+ if (parent.key.length !== 1) return found;
327
+ const value = row[parent.key[0]];
328
+ for (const child of this.models.values()) {
329
+ for (const ref of child.references) {
330
+ if (ref.target !== parent.type) continue;
331
+ for (const [key, candidate] of this.rows(tx, child.type)) {
332
+ if (equal(candidate[ref.prop], value))
333
+ found.push({ child, ref, key, row: candidate });
334
+ }
335
+ }
336
+ }
337
+ return found;
338
+ }
339
+
340
+ private assertUnreferenced(tx: MemoryTransaction, model: MemoryEntity, row: Row) {
341
+ const [first] = this.referencing(tx, model, row);
342
+ if (first) {
343
+ throw new DataError(
344
+ `Can't change the key of ${model.name} ${this.describe(model, row)}: ${first.child.name}.${first.ref.prop} references it`,
345
+ );
346
+ }
347
+ }
348
+
349
+ // ── Locks ──────────────────────────────────────────────────────────────
350
+
351
+ /** Take a row lock, waiting while another transaction holds one that conflicts. */
352
+ private async acquire(
353
+ tx: MemoryTransaction,
354
+ type: EntityClass,
355
+ key: string,
356
+ mode: LockMode,
357
+ ) {
358
+ let byKey = this.locks.get(type);
359
+ if (byKey == null) {
360
+ byKey = new Map();
361
+ this.locks.set(type, byKey);
362
+ }
363
+ for (;;) {
364
+ let holders = byKey.get(key);
365
+ if (holders == null) {
366
+ holders = new Map();
367
+ byKey.set(key, holders);
368
+ }
369
+ const blocking = [...holders]
370
+ .filter(([other, held]) => other !== tx && CONFLICTS[mode].includes(held))
371
+ .map(([other]) => other);
372
+ if (blocking.length === 0) {
373
+ const mine = holders.get(tx);
374
+ if (mine == null) tx.held.push({ type, key });
375
+ if (mine == null || STRENGTH[mode] > STRENGTH[mine]) holders.set(tx, mode);
376
+ return;
377
+ }
378
+ tx.waitingFor = new Set(blocking);
379
+ if (this.waitsOnItself(tx)) {
380
+ tx.waitingFor = new Set();
381
+ throw new DataError(
382
+ `Deadlock: two transactions each wait for a row the other has locked (${this.model(type).name})`,
383
+ );
384
+ }
385
+ await Promise.race(blocking.map((other) => other.done));
386
+ tx.waitingFor = new Set();
387
+ }
388
+ }
389
+
390
+ private holds(tx: MemoryTransaction, type: EntityClass, key: string, mode: LockMode) {
391
+ const held = this.locks.get(type)?.get(key)?.get(tx);
392
+ return held != null && STRENGTH[held] >= STRENGTH[mode];
393
+ }
394
+
395
+ private waitsOnItself(tx: MemoryTransaction): boolean {
396
+ const seen = new Set<MemoryTransaction>();
397
+ const visit = (other: MemoryTransaction): boolean => {
398
+ if (other === tx) return true;
399
+ if (seen.has(other)) return false;
400
+ seen.add(other);
401
+ return [...other.waitingFor].some(visit);
402
+ };
403
+ return [...tx.waitingFor].some(visit);
404
+ }
405
+
406
+ private end(tx: MemoryTransaction) {
407
+ for (const { type, key } of tx.held) {
408
+ const byKey = this.locks.get(type);
409
+ const holders = byKey?.get(key);
410
+ holders?.delete(tx);
411
+ if (holders?.size === 0) byKey?.delete(key);
412
+ }
413
+ tx.finish();
414
+ }
415
+
416
+ // ── Helpers ────────────────────────────────────────────────────────────
417
+
418
+ /** Run one statement. A failure aborts the transaction, as in Postgres: it can only roll back. */
419
+ private async statement<R>(tx: MemoryTransaction, run: () => Promise<R>): Promise<R> {
420
+ this.assertOpen(tx);
421
+ if (tx.aborted !== undefined) {
422
+ throw new DataError("The transaction was aborted by an earlier error: roll it back", {
423
+ cause: tx.aborted,
424
+ });
425
+ }
426
+ try {
427
+ return await run();
428
+ } catch (err) {
429
+ tx.aborted = err;
430
+ throw err;
431
+ }
432
+ }
433
+
434
+ private assertOpen(tx: MemoryTransaction) {
435
+ if (tx.finished) throw new DataError("The transaction has ended");
436
+ }
437
+
438
+ private assertProp(model: MemoryEntity, prop: string) {
439
+ if (!model.fields.includes(prop) && !model.references.some((r) => r.prop === prop)) {
440
+ throw new DataConfigurationError(`${model.name} has no field "${prop}"`);
441
+ }
442
+ }
443
+
444
+ /** A row's key as one string. Dates count by their instant. */
445
+ private keyOf(model: MemoryEntity, row: Row): string {
446
+ return JSON.stringify(
447
+ model.key.map((prop) => {
448
+ const value = row[prop];
449
+ return value instanceof Date ? { date: value.getTime() } : value;
450
+ }),
451
+ );
452
+ }
453
+
454
+ private describe(model: MemoryEntity, row: Row): string {
455
+ return model.key.map((prop) => String(row[prop])).join(", ");
456
+ }
457
+ }
458
+
459
+ /** Whether a stored value meets a condition, with SQL's nulls: only `null` and `ne` match an empty value. */
460
+ function matches(value: unknown, condition: Comparison<unknown>): boolean {
461
+ if (condition === null) return value === null;
462
+ const operator = comparison.operatorOf(condition);
463
+ if (!operator) return value !== null && equal(value, condition);
464
+ const [op, operand] = operator;
465
+ if (op === "ne" && operand === null) return value !== null;
466
+ if (value === null) return false;
467
+ if (op === "in") return (operand as unknown[]).some((v) => equal(value, v));
468
+ if (op === "ne") return !equal(value, operand);
469
+ if (operand === null) return false;
470
+ const order = compare(value, operand);
471
+ if (op === "gt") return order > 0;
472
+ if (op === "gte") return order >= 0;
473
+ if (op === "lt") return order < 0;
474
+ return order <= 0;
475
+ }
476
+
477
+ /** Postgres's order: empty values last ascending, first descending. */
478
+ function sortOrder(a: unknown, b: unknown, direction: "asc" | "desc"): number {
479
+ const sign = direction === "desc" ? -1 : 1;
480
+ if (a === null || b === null) {
481
+ if (a === b) return 0;
482
+ return (a === null ? 1 : -1) * sign;
483
+ }
484
+ return compare(a, b) * sign;
485
+ }
486
+
487
+ function compare(a: unknown, b: unknown): number {
488
+ const x = a instanceof Date ? a.getTime() : a;
489
+ const y = b instanceof Date ? b.getTime() : b;
490
+ const kind = typeof x;
491
+ if (kind !== typeof y || !["number", "string", "bigint", "boolean"].includes(kind)) {
492
+ throw new DataError(`Can't compare ${String(a)} with ${String(b)}`);
493
+ }
494
+ if ((x as number) < (y as number)) return -1;
495
+ return (x as number) > (y as number) ? 1 : 0;
496
+ }
497
+
498
+ function equal(a: unknown, b: unknown): boolean {
499
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
500
+ if (a !== null && b !== null && typeof a === "object" && typeof b === "object") {
501
+ return JSON.stringify(a) === JSON.stringify(b);
502
+ }
503
+ return a === b;
504
+ }
505
+
506
+ function copy(value: unknown): unknown {
507
+ return value !== null && typeof value === "object" ? structuredClone(value) : value;
508
+ }
@@ -0,0 +1,100 @@
1
+ // An app on the memory provider, as a developer composes it: repositories over the unit of work,
2
+ // with no database and no database config.
3
+ import "reflect-metadata";
4
+ import { Builder } from "@decohere/core/hosting";
5
+ import { ServiceContainerBuilder } from "@decohere/crucible";
6
+ import { injectable } from "@decohere/crucible/decorators";
7
+ import {
8
+ DataConfigurationError,
9
+ DEFAULT_DATA_SOURCE,
10
+ type IUnitOfWork,
11
+ injectUnitOfWork,
12
+ Repository,
13
+ } from "@decohere/data";
14
+ import { describe, expect, it } from "vitest";
15
+ import { mapEntity, memory, type MemoryModuleConfig } from "../src/index.js";
16
+ import { Book, book, entities, Shelf, shelf } from "./model.js";
17
+
18
+ @injectable()
19
+ class ShelfRepository extends Repository<Shelf> {
20
+ public constructor(@injectUnitOfWork() unitOfWork: IUnitOfWork) {
21
+ super(unitOfWork, Shelf);
22
+ }
23
+ }
24
+
25
+ function build(config: Partial<MemoryModuleConfig> = {}) {
26
+ return Builder.create(new ServiceContainerBuilder())
27
+ .use(memory({ entities, repositories: [ShelfRepository], ...config }))
28
+ .build();
29
+ }
30
+
31
+ async function start(config: Partial<MemoryModuleConfig> = {}) {
32
+ const app = await build(config);
33
+ await app.start({ port: 0, shutdownSignals: false, startRetry: false });
34
+ return app;
35
+ }
36
+
37
+ describe("memory()", () => {
38
+ it("gives each request a unit of work, and what one request commits the next one reads", async () => {
39
+ await using app = await start();
40
+ {
41
+ await using scope = app.services.beginScope("a request");
42
+ const shelves = scope.resolve(ShelfRepository);
43
+ const s = shelf("s1", "fiction");
44
+ s.books.add(book("b1", "Dune", s));
45
+ shelves.add(s);
46
+ await scope.resolve<IUnitOfWork>(DEFAULT_DATA_SOURCE).commit();
47
+ }
48
+ await using scope = app.services.beginScope("a later request");
49
+ const found = await scope.resolve(ShelfRepository).findById("s1", ["books"]);
50
+ expect([...found.books].map((b) => b.title)).toEqual(["Dune"]);
51
+ });
52
+
53
+ it("gives each app its own rows", async () => {
54
+ await using first = await start();
55
+ await using second = await start();
56
+ {
57
+ await using scope = first.services.beginScope("a request");
58
+ const uow = scope.resolve<IUnitOfWork>(DEFAULT_DATA_SOURCE);
59
+ uow.add(shelf("s1", "fiction"));
60
+ await uow.commit();
61
+ }
62
+ await using scope = second.services.beginScope("a request");
63
+ expect(await scope.resolve(ShelfRepository).find()).toEqual([]);
64
+ });
65
+
66
+ it("seeds when the app starts, not when it is built", async () => {
67
+ const seed = async (uow: IUnitOfWork) => uow.add(shelf("s1", "seeded"));
68
+ await using app = await build({ seed });
69
+ const read = async () => {
70
+ await using scope = app.services.beginScope("a request");
71
+ return scope.resolve(ShelfRepository).find();
72
+ };
73
+ expect(await read()).toEqual([]);
74
+ await app.start({ port: 0, shutdownSignals: false, startRetry: false });
75
+ expect((await read()).map((s) => s.label)).toEqual(["seeded"]);
76
+ });
77
+
78
+ it("fails the build when a mapping points at a class that isn't mapped", async () => {
79
+ await expect(build({ entities: [entities[0]] })).rejects.toThrow(
80
+ "Shelf.books points at Book, which isn't mapped: add it to entities",
81
+ );
82
+ await expect(
83
+ build({
84
+ entities: [
85
+ entities[0],
86
+ mapEntity(Book, {
87
+ fields: ["title"],
88
+ references: [{ prop: "shelf", target: Book }],
89
+ }),
90
+ ],
91
+ }),
92
+ ).rejects.toThrow("Shelf.books: Book.shelf must be a reference to Shelf");
93
+ });
94
+
95
+ it("needs a name for each data source when there are several", () => {
96
+ expect(() => memory([{ entities }, { name: "audit", entities }])).toThrow(
97
+ DataConfigurationError,
98
+ );
99
+ });
100
+ });