@decohere/data-memory 0.0.0-stage → 0.0.1-dev.20261122.343
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/LICENSE +15 -0
- package/README.md +52 -2
- package/es6/src/index.js +4 -0
- package/es6/src/memory-entity.js +91 -0
- package/es6/src/memory.plugin.js +119 -0
- package/es6/src/memory.row-store.js +62 -0
- package/es6/src/memory.store.js +447 -0
- package/package.json +36 -4
- package/types/src/index.d.ts +4 -0
- package/types/src/memory-entity.d.ts +52 -0
- package/types/src/memory.plugin.d.ts +20 -0
- package/types/src/memory.row-store.d.ts +27 -0
- package/types/src/memory.store.d.ts +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Typesmiths
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
7
|
+
copyright notice and this permission notice appear in all copies.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
10
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
11
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
12
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
13
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
14
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
15
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @decohere/data-memory
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The in-memory provider for [`@decohere/data`](../data/README.md): the same repositories and unit of work as on a database, with the rows held in the process. For tests and local runs that shouldn't need Postgres. The unit of work is data's `TrackingUnitOfWork`, as on [TypeORM](../data-typeorm/README.md), over a `MemoryRowStore`. The contract suite's cases run on it in `pnpm test`, with no Docker.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
builder.use(
|
|
7
|
+
memory({
|
|
8
|
+
entities: [
|
|
9
|
+
mapEntity(Order, {
|
|
10
|
+
fields: ["customer", "note", "status", "placedAt"],
|
|
11
|
+
version: "version",
|
|
12
|
+
children: [{ prop: "lines", target: Line, parentRef: "order" }],
|
|
13
|
+
}),
|
|
14
|
+
mapEntity(Line, {
|
|
15
|
+
fields: ["sku", "quantity"],
|
|
16
|
+
references: [{ prop: "order", target: Order }],
|
|
17
|
+
}),
|
|
18
|
+
],
|
|
19
|
+
repositories: [OrderRepository],
|
|
20
|
+
outbox: toOutboxMessage,
|
|
21
|
+
seed: async (uow) => uow.add(new Order("demo")),
|
|
22
|
+
}),
|
|
23
|
+
);
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Swapping it for `typeOrm(…)` or `mikroOrm(…)` changes this line and the mappings, not the repositories. It needs no `database` config, connects to nothing and has nothing to migrate, so the `db` commands find no data source on it. Each build of the app starts with empty stores, so two apps, or two tests, never share rows. With `seed`, the app's start step adds the rows, in a unit of work committed when it returns.
|
|
27
|
+
|
|
28
|
+
## Mapping
|
|
29
|
+
|
|
30
|
+
There's no ORM to read a mapping from, so each class is mapped with `mapEntity(type, options)`:
|
|
31
|
+
|
|
32
|
+
| Option | Means |
|
|
33
|
+
| --- | --- |
|
|
34
|
+
| `key` | The properties making the key: fields or references. Defaults to `["id"]`. |
|
|
35
|
+
| `fields` | The properties stored as values. Key fields, the version and the generated key may be left out. |
|
|
36
|
+
| `references` | `{ prop, target, nullable?, onDelete? }`: a property holding another mapped entity, stored as its key. Required unless `nullable`. `onDelete: "cascade"` deletes this row with the one it references. Otherwise that delete fails while this row references it. |
|
|
37
|
+
| `children` | `{ prop, target, parentRef, orderBy? }`: a `Children<T>` collection, the rows of `target` whose `parentRef` references this one. |
|
|
38
|
+
| `version` | A number checked and incremented on every update. |
|
|
39
|
+
| `generated` | A key field numbered 1, 2, 3… when an insert leaves it empty, like a serial column. |
|
|
40
|
+
|
|
41
|
+
The mapping is checked when the app is built, so a reference to a class that isn't mapped fails then.
|
|
42
|
+
|
|
43
|
+
## What it keeps from a database
|
|
44
|
+
|
|
45
|
+
It behaves as Postgres does wherever a repository could tell the difference:
|
|
46
|
+
|
|
47
|
+
- **Keys and foreign keys.** A second row with the same key fails. So does a reference to a row that doesn't exist, an empty required reference, or deleting a row that something still references (unless the reference cascades).
|
|
48
|
+
- **Transactions.** A unit of work's writes stay its own until it commits, and are applied all together. Reads see what is committed plus their own writes. A statement that fails aborts the transaction, which can then only roll back.
|
|
49
|
+
- **Row locks.** These take Postgres's modes: `lock: "update"` and deletes lock the row, updates lock it against other updates, and a reference locks the row it points at against deletion. A second unit of work waits for the first to commit or roll back, then reads the row as it is. Two that would wait for each other fail one of them with a deadlock error.
|
|
50
|
+
- **Copies.** Rows are copied in and out, so an object held outside the unit of work can't change what is stored.
|
|
51
|
+
- **SQL's nulls.** An empty value matches only `null` and `{ ne: … }` with a value given. It sorts last ascending and first descending.
|
|
52
|
+
|
|
53
|
+
What differs: strings compare and sort by code unit, not by the database's collation. Columns have no types, lengths or `NOT NULL` checks beyond the key and required references. And the rows last only as long as the app.
|
package/es6/src/index.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { DataConfigurationError } from "@decohere/data";
|
|
2
|
+
/**
|
|
3
|
+
* Map a class for the memory provider. With no ORM to read metadata from, the mapping is written
|
|
4
|
+
* out: which properties are stored, which reference another class, and which hold children.
|
|
5
|
+
*/ export function mapEntity(type, options) {
|
|
6
|
+
const key = options.key ?? [
|
|
7
|
+
"id"
|
|
8
|
+
];
|
|
9
|
+
const references = (options.references ?? []).map((r)=>({
|
|
10
|
+
prop: r.prop,
|
|
11
|
+
target: r.target,
|
|
12
|
+
nullable: r.nullable ?? false,
|
|
13
|
+
onDelete: r.onDelete
|
|
14
|
+
}));
|
|
15
|
+
const isReference = (prop)=>references.some((r)=>r.prop === prop);
|
|
16
|
+
const fields = new Set(options.fields);
|
|
17
|
+
for (const prop of key)if (!isReference(prop)) fields.add(prop);
|
|
18
|
+
if (options.version) fields.add(options.version);
|
|
19
|
+
if (options.generated) fields.add(options.generated);
|
|
20
|
+
return {
|
|
21
|
+
type,
|
|
22
|
+
name: type.name,
|
|
23
|
+
key,
|
|
24
|
+
fields: [
|
|
25
|
+
...fields
|
|
26
|
+
],
|
|
27
|
+
references,
|
|
28
|
+
children: (options.children ?? []).map((c)=>({
|
|
29
|
+
prop: c.prop,
|
|
30
|
+
target: c.target,
|
|
31
|
+
parentRef: c.parentRef,
|
|
32
|
+
orderBy: c.orderBy
|
|
33
|
+
})),
|
|
34
|
+
version: options.version,
|
|
35
|
+
generated: options.generated
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Check the mappings fit together, so a mistake fails when the app is built rather than at the
|
|
40
|
+
* first query: every key, reference and child names something mapped.
|
|
41
|
+
*/ function check(entities) {
|
|
42
|
+
const byType = new Map();
|
|
43
|
+
for (const entity of entities){
|
|
44
|
+
if (byType.has(entity.type)) {
|
|
45
|
+
throw new DataConfigurationError(`${entity.name} is mapped twice`);
|
|
46
|
+
}
|
|
47
|
+
byType.set(entity.type, entity);
|
|
48
|
+
}
|
|
49
|
+
const mapped = (owner, prop, target)=>{
|
|
50
|
+
const found = byType.get(target);
|
|
51
|
+
if (found == null) {
|
|
52
|
+
throw new DataConfigurationError(`${owner.name}.${prop} points at ${target.name}, which isn't mapped: add it to entities`);
|
|
53
|
+
}
|
|
54
|
+
return found;
|
|
55
|
+
};
|
|
56
|
+
for (const entity of entities){
|
|
57
|
+
const { name } = entity;
|
|
58
|
+
const isReference = (prop)=>entity.references.some((r)=>r.prop === prop);
|
|
59
|
+
if (entity.key.length === 0) {
|
|
60
|
+
throw new DataConfigurationError(`${name} has no key`);
|
|
61
|
+
}
|
|
62
|
+
if (entity.generated && (entity.key.length !== 1 || entity.key[0] !== entity.generated)) {
|
|
63
|
+
throw new DataConfigurationError(`${name}.${entity.generated} is generated, so it must be the whole key`);
|
|
64
|
+
}
|
|
65
|
+
for (const ref of entity.references){
|
|
66
|
+
if (entity.fields.includes(ref.prop)) {
|
|
67
|
+
throw new DataConfigurationError(`${name}.${ref.prop} is both a field and a reference`);
|
|
68
|
+
}
|
|
69
|
+
const target = mapped(entity, ref.prop, ref.target);
|
|
70
|
+
if (target.key.length !== 1) {
|
|
71
|
+
throw new DataConfigurationError(`${name}.${ref.prop} references ${target.name}, whose key is composite: a reference must point at a single key`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
for (const spec of entity.children){
|
|
75
|
+
const child = mapped(entity, spec.prop, spec.target);
|
|
76
|
+
const parentRef = child.references.find((r)=>r.prop === spec.parentRef);
|
|
77
|
+
if (parentRef == null || parentRef.target !== entity.type) {
|
|
78
|
+
throw new DataConfigurationError(`${name}.${spec.prop}: ${child.name}.${spec.parentRef} must be a reference to ${name}`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for (const prop of entity.key){
|
|
82
|
+
if (!entity.fields.includes(prop) && !isReference(prop)) {
|
|
83
|
+
throw new DataConfigurationError(`${name}'s key ${prop} isn't mapped`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return byType;
|
|
88
|
+
}
|
|
89
|
+
export const memoryEntities = {
|
|
90
|
+
check
|
|
91
|
+
};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
function _ts_add_disposable_resource(env, value, async) {
|
|
2
|
+
if (value !== null && value !== void 0) {
|
|
3
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
4
|
+
var dispose, inner;
|
|
5
|
+
if (async) {
|
|
6
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
7
|
+
dispose = value[Symbol.asyncDispose];
|
|
8
|
+
}
|
|
9
|
+
if (dispose === void 0) {
|
|
10
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
11
|
+
dispose = value[Symbol.dispose];
|
|
12
|
+
if (async) inner = dispose;
|
|
13
|
+
}
|
|
14
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
15
|
+
if (inner) dispose = function() {
|
|
16
|
+
try {
|
|
17
|
+
inner.call(this);
|
|
18
|
+
} catch (e) {
|
|
19
|
+
return Promise.reject(e);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
env.stack.push({
|
|
23
|
+
value: value,
|
|
24
|
+
dispose: dispose,
|
|
25
|
+
async: async
|
|
26
|
+
});
|
|
27
|
+
} else if (async) {
|
|
28
|
+
env.stack.push({
|
|
29
|
+
async: true
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
function _ts_dispose_resources(env) {
|
|
35
|
+
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
36
|
+
var e = new Error(message);
|
|
37
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
38
|
+
};
|
|
39
|
+
return (_ts_dispose_resources = function _ts_dispose_resources(env) {
|
|
40
|
+
function fail(e) {
|
|
41
|
+
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
42
|
+
env.hasError = true;
|
|
43
|
+
}
|
|
44
|
+
var r, s = 0;
|
|
45
|
+
function next() {
|
|
46
|
+
while(r = env.stack.pop()){
|
|
47
|
+
try {
|
|
48
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
49
|
+
if (r.dispose) {
|
|
50
|
+
var result = r.dispose.call(r.value);
|
|
51
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
52
|
+
fail(e);
|
|
53
|
+
return next();
|
|
54
|
+
});
|
|
55
|
+
} else s |= 1;
|
|
56
|
+
} catch (e) {
|
|
57
|
+
fail(e);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
61
|
+
if (env.hasError) throw env.error;
|
|
62
|
+
}
|
|
63
|
+
return next();
|
|
64
|
+
})(env);
|
|
65
|
+
}
|
|
66
|
+
import { DataConfigurationError, DEFAULT_DATA_SOURCE, TrackingUnitOfWork } from "@decohere/data";
|
|
67
|
+
import { MemoryRowStore } from "./memory.row-store.js";
|
|
68
|
+
import { MemoryStore } from "./memory.store.js";
|
|
69
|
+
/**
|
|
70
|
+
* Keep the data in the process, with no database: for tests and local runs. Each build of the app
|
|
71
|
+
* gets empty stores of its own. Needs no `database` config.
|
|
72
|
+
*/ export function memory(config) {
|
|
73
|
+
const modules = Array.isArray(config) ? config : [
|
|
74
|
+
config
|
|
75
|
+
];
|
|
76
|
+
if (modules.length > 1 && modules.some((m)=>m.name == null)) {
|
|
77
|
+
throw new DataConfigurationError("Name is required if there is more than one datasource");
|
|
78
|
+
}
|
|
79
|
+
return (builder)=>{
|
|
80
|
+
const stores = new Map();
|
|
81
|
+
builder.withServices((containerBuilder)=>{
|
|
82
|
+
for (const module of modules){
|
|
83
|
+
const store = new MemoryStore(module.entities);
|
|
84
|
+
stores.set(module, store);
|
|
85
|
+
containerBuilder.registerRequestScoped(module.name ?? DEFAULT_DATA_SOURCE, ()=>new TrackingUnitOfWork(new MemoryRowStore(store), {
|
|
86
|
+
outbox: module.outbox
|
|
87
|
+
}));
|
|
88
|
+
for (const repository of module.repositories ?? []){
|
|
89
|
+
containerBuilder.registerRequestScoped(repository);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
if (modules.every((m)=>m.seed == null)) return;
|
|
94
|
+
builder.registerStartStep(async ()=>{
|
|
95
|
+
for (const module of modules){
|
|
96
|
+
const env = {
|
|
97
|
+
stack: [],
|
|
98
|
+
error: void 0,
|
|
99
|
+
hasError: false
|
|
100
|
+
};
|
|
101
|
+
try {
|
|
102
|
+
const store = stores.get(module);
|
|
103
|
+
if (module.seed == null || store == null) continue;
|
|
104
|
+
const unitOfWork = _ts_add_disposable_resource(env, new TrackingUnitOfWork(new MemoryRowStore(store), {
|
|
105
|
+
outbox: module.outbox
|
|
106
|
+
}), true);
|
|
107
|
+
await module.seed(unitOfWork);
|
|
108
|
+
await unitOfWork.commit();
|
|
109
|
+
} catch (e) {
|
|
110
|
+
env.error = e;
|
|
111
|
+
env.hasError = true;
|
|
112
|
+
} finally{
|
|
113
|
+
const result = _ts_dispose_resources(env);
|
|
114
|
+
if (result) await result;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}, "memory data sources");
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { DataError } from "@decohere/data";
|
|
2
|
+
/**
|
|
3
|
+
* The memory provider's share of the unit of work: one transaction at a time on a
|
|
4
|
+
* {@link MemoryStore}. Outside a transaction each operation runs in one of its own, as a database
|
|
5
|
+
* runs a statement on its own.
|
|
6
|
+
*/ export class MemoryRowStore {
|
|
7
|
+
store;
|
|
8
|
+
transaction;
|
|
9
|
+
constructor(store){
|
|
10
|
+
this.store = store;
|
|
11
|
+
}
|
|
12
|
+
model(type) {
|
|
13
|
+
return this.store.model(type);
|
|
14
|
+
}
|
|
15
|
+
async begin() {
|
|
16
|
+
if (this.transaction) throw new DataError("A transaction is already open");
|
|
17
|
+
this.transaction = this.store.begin();
|
|
18
|
+
}
|
|
19
|
+
async commit() {
|
|
20
|
+
this.store.commit(this.end());
|
|
21
|
+
}
|
|
22
|
+
async rollback() {
|
|
23
|
+
this.store.rollback(this.end());
|
|
24
|
+
}
|
|
25
|
+
async release() {
|
|
26
|
+
if (this.transaction) await this.rollback();
|
|
27
|
+
}
|
|
28
|
+
inTransaction() {
|
|
29
|
+
return this.transaction != null;
|
|
30
|
+
}
|
|
31
|
+
select(type, query) {
|
|
32
|
+
return this.run((tx)=>this.store.select(tx, type, query));
|
|
33
|
+
}
|
|
34
|
+
insert(type, rows) {
|
|
35
|
+
return this.run((tx)=>this.store.insert(tx, type, rows));
|
|
36
|
+
}
|
|
37
|
+
update(type, key, changes, version) {
|
|
38
|
+
return this.run((tx)=>this.store.update(tx, type, key, changes, version));
|
|
39
|
+
}
|
|
40
|
+
delete(type, keys) {
|
|
41
|
+
return this.run((tx)=>this.store.delete(tx, type, keys));
|
|
42
|
+
}
|
|
43
|
+
end() {
|
|
44
|
+
const tx = this.transaction;
|
|
45
|
+
if (tx == null) throw new DataError("No transaction is open");
|
|
46
|
+
this.transaction = undefined;
|
|
47
|
+
return tx;
|
|
48
|
+
}
|
|
49
|
+
async run(operation) {
|
|
50
|
+
if (this.transaction) return operation(this.transaction);
|
|
51
|
+
const tx = this.store.begin();
|
|
52
|
+
let result;
|
|
53
|
+
try {
|
|
54
|
+
result = await operation(tx);
|
|
55
|
+
} catch (err) {
|
|
56
|
+
this.store.rollback(tx);
|
|
57
|
+
throw err;
|
|
58
|
+
}
|
|
59
|
+
this.store.commit(tx);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import { comparison, DataConfigurationError, DataError } from "@decohere/data";
|
|
2
|
+
import { memoryEntities } from "./memory-entity.js";
|
|
3
|
+
const CONFLICTS = {
|
|
4
|
+
"key-share": [
|
|
5
|
+
"update"
|
|
6
|
+
],
|
|
7
|
+
"no-key-update": [
|
|
8
|
+
"no-key-update",
|
|
9
|
+
"update"
|
|
10
|
+
],
|
|
11
|
+
update: [
|
|
12
|
+
"key-share",
|
|
13
|
+
"no-key-update",
|
|
14
|
+
"update"
|
|
15
|
+
]
|
|
16
|
+
};
|
|
17
|
+
const STRENGTH = {
|
|
18
|
+
"key-share": 0,
|
|
19
|
+
"no-key-update": 1,
|
|
20
|
+
update: 2
|
|
21
|
+
};
|
|
22
|
+
/** One transaction: its writes, kept apart until commit, and the row locks it holds. */ export class MemoryTransaction {
|
|
23
|
+
/** Per class, by key: the row as this transaction wrote it, or null where it deleted one. */ writes = new Map();
|
|
24
|
+
held = [];
|
|
25
|
+
/** The transactions holding locks this one waits for. */ waitingFor = new Set();
|
|
26
|
+
/** The error that aborted it: after a failed statement, as in Postgres, it only rolls back. */ aborted;
|
|
27
|
+
finished = false;
|
|
28
|
+
done;
|
|
29
|
+
settle;
|
|
30
|
+
constructor(){
|
|
31
|
+
this.done = new Promise((resolve)=>{
|
|
32
|
+
this.settle = resolve;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
finish() {
|
|
36
|
+
this.finished = true;
|
|
37
|
+
this.settle();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The rows of one data source, held in the process. Reads see what is committed plus their own
|
|
42
|
+
* transaction's writes (read committed); a commit applies a transaction's writes in one step.
|
|
43
|
+
* Rows are copied in and out, so an object held outside can't change what is stored.
|
|
44
|
+
*/ export class MemoryStore {
|
|
45
|
+
models;
|
|
46
|
+
tables = new Map();
|
|
47
|
+
sequences = new Map();
|
|
48
|
+
locks = new Map();
|
|
49
|
+
constructor(entities){
|
|
50
|
+
this.models = memoryEntities.check(entities);
|
|
51
|
+
}
|
|
52
|
+
model(type) {
|
|
53
|
+
const model = this.models.get(type);
|
|
54
|
+
if (model == null) {
|
|
55
|
+
throw new DataConfigurationError(`${type.name} isn't mapped: add mapEntity(${type.name}, …) to memory()'s entities`);
|
|
56
|
+
}
|
|
57
|
+
return model;
|
|
58
|
+
}
|
|
59
|
+
begin() {
|
|
60
|
+
return new MemoryTransaction();
|
|
61
|
+
}
|
|
62
|
+
commit(tx) {
|
|
63
|
+
this.assertOpen(tx);
|
|
64
|
+
if (tx.aborted !== undefined) {
|
|
65
|
+
this.rollback(tx);
|
|
66
|
+
throw new DataError("The transaction was aborted by an earlier error, so it was rolled back", {
|
|
67
|
+
cause: tx.aborted
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
for (const [type, writes] of tx.writes){
|
|
71
|
+
const table = this.table(type);
|
|
72
|
+
for (const [key, row] of writes){
|
|
73
|
+
if (row === null) table.delete(key);
|
|
74
|
+
else table.set(key, row);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
this.end(tx);
|
|
78
|
+
}
|
|
79
|
+
rollback(tx) {
|
|
80
|
+
this.assertOpen(tx);
|
|
81
|
+
this.end(tx);
|
|
82
|
+
}
|
|
83
|
+
select(tx, type, query) {
|
|
84
|
+
return this.statement(tx, async ()=>{
|
|
85
|
+
const model = this.model(type);
|
|
86
|
+
for (const prop of Object.keys(query.where ?? {}))this.assertProp(model, prop);
|
|
87
|
+
for (const prop of Object.keys(query.orderBy ?? {}))this.assertProp(model, prop);
|
|
88
|
+
let found = this.query(tx, type, query);
|
|
89
|
+
if (query.lock === "update") {
|
|
90
|
+
// Lock what matched, then read again: a row another transaction changed while this one
|
|
91
|
+
// waited is read as it now is, and dropped if it no longer matches.
|
|
92
|
+
for(;;){
|
|
93
|
+
const unlocked = found.filter(([key])=>!this.holds(tx, type, key, "update"));
|
|
94
|
+
if (unlocked.length === 0) break;
|
|
95
|
+
for (const [key] of unlocked)await this.acquire(tx, type, key, "update");
|
|
96
|
+
found = this.query(tx, type, query);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const props = [
|
|
100
|
+
...model.fields,
|
|
101
|
+
...model.references.map((r)=>r.prop)
|
|
102
|
+
];
|
|
103
|
+
return found.map(([, row])=>Object.fromEntries(props.map((prop)=>[
|
|
104
|
+
prop,
|
|
105
|
+
copy(row[prop] ?? null)
|
|
106
|
+
])));
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
insert(tx, type, rows) {
|
|
110
|
+
return this.statement(tx, async ()=>{
|
|
111
|
+
const model = this.model(type);
|
|
112
|
+
const generated = [];
|
|
113
|
+
for (const input of rows){
|
|
114
|
+
const row = copy(input);
|
|
115
|
+
const out = {};
|
|
116
|
+
if (model.generated && row[model.generated] == null) {
|
|
117
|
+
const next = (this.sequences.get(type) ?? 0) + 1;
|
|
118
|
+
this.sequences.set(type, next);
|
|
119
|
+
row[model.generated] = next;
|
|
120
|
+
out[model.generated] = next;
|
|
121
|
+
}
|
|
122
|
+
for (const prop of model.key){
|
|
123
|
+
if (row[prop] == null) throw new DataError(`${model.name}: key ${prop} is empty`);
|
|
124
|
+
}
|
|
125
|
+
await this.checkReferences(tx, model, row, model.references.map((r)=>r.prop));
|
|
126
|
+
const key = this.keyOf(model, row);
|
|
127
|
+
await this.acquire(tx, type, key, "update");
|
|
128
|
+
if (this.row(tx, type, key)) {
|
|
129
|
+
throw new DataError(`${model.name} ${this.describe(model, row)} already exists`);
|
|
130
|
+
}
|
|
131
|
+
this.write(tx, type, key, row);
|
|
132
|
+
generated.push(out);
|
|
133
|
+
}
|
|
134
|
+
return generated;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
update(tx, type, keyRow, changes, version) {
|
|
138
|
+
return this.statement(tx, async ()=>{
|
|
139
|
+
const model = this.model(type);
|
|
140
|
+
for (const prop of Object.keys(changes))this.assertProp(model, prop);
|
|
141
|
+
const key = this.keyOf(model, keyRow);
|
|
142
|
+
const changesKey = model.key.some((prop)=>prop in changes && !equal(changes[prop], keyRow[prop]));
|
|
143
|
+
await this.acquire(tx, type, key, changesKey ? "update" : "no-key-update");
|
|
144
|
+
const current = this.row(tx, type, key);
|
|
145
|
+
if (current == null) return 0;
|
|
146
|
+
if (version && !equal(current[version.prop], version.expected)) return 0;
|
|
147
|
+
const next = {
|
|
148
|
+
...current,
|
|
149
|
+
...copy(changes)
|
|
150
|
+
};
|
|
151
|
+
await this.checkReferences(tx, model, next, Object.keys(changes));
|
|
152
|
+
if (!changesKey) {
|
|
153
|
+
this.write(tx, type, key, next);
|
|
154
|
+
return 1;
|
|
155
|
+
}
|
|
156
|
+
const nextKey = this.keyOf(model, next);
|
|
157
|
+
await this.acquire(tx, type, nextKey, "update");
|
|
158
|
+
if (this.row(tx, type, nextKey)) {
|
|
159
|
+
throw new DataError(`${model.name} ${this.describe(model, next)} already exists`);
|
|
160
|
+
}
|
|
161
|
+
this.assertUnreferenced(tx, model, current);
|
|
162
|
+
this.write(tx, type, key, null);
|
|
163
|
+
this.write(tx, type, nextKey, next);
|
|
164
|
+
return 1;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
delete(tx, type, keys) {
|
|
168
|
+
return this.statement(tx, async ()=>{
|
|
169
|
+
const model = this.model(type);
|
|
170
|
+
const deleted = [];
|
|
171
|
+
for (const keyRow of keys){
|
|
172
|
+
const key = this.keyOf(model, keyRow);
|
|
173
|
+
await this.acquire(tx, type, key, "update");
|
|
174
|
+
const row = this.row(tx, type, key);
|
|
175
|
+
if (row == null) continue;
|
|
176
|
+
this.write(tx, type, key, null);
|
|
177
|
+
deleted.push({
|
|
178
|
+
model,
|
|
179
|
+
row
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
// Then what referenced them: cascaded where the reference says so, refused otherwise.
|
|
183
|
+
for(let i = 0; i < deleted.length; i++){
|
|
184
|
+
const { model: parent, row } = deleted[i];
|
|
185
|
+
for (const { child, ref, key, row: referencing } of this.referencing(tx, parent, row)){
|
|
186
|
+
if (ref.onDelete !== "cascade") {
|
|
187
|
+
throw new DataError(`Can't delete ${parent.name} ${this.describe(parent, row)}: ${child.name}.${ref.prop} still references it`);
|
|
188
|
+
}
|
|
189
|
+
await this.acquire(tx, child.type, key, "update");
|
|
190
|
+
if (this.row(tx, child.type, key) == null) continue;
|
|
191
|
+
this.write(tx, child.type, key, null);
|
|
192
|
+
deleted.push({
|
|
193
|
+
model: child,
|
|
194
|
+
row: referencing
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
// ── Rows ───────────────────────────────────────────────────────────────
|
|
201
|
+
query(tx, type, query) {
|
|
202
|
+
const where = Object.entries(query.where ?? {});
|
|
203
|
+
const found = [
|
|
204
|
+
...this.rows(tx, type)
|
|
205
|
+
].filter(([, row])=>where.every(([prop, condition])=>matches(row[prop] ?? null, condition)));
|
|
206
|
+
const orderBy = Object.entries(query.orderBy ?? {});
|
|
207
|
+
if (orderBy.length > 0) {
|
|
208
|
+
found.sort(([, a], [, b])=>{
|
|
209
|
+
for (const [prop, direction] of orderBy){
|
|
210
|
+
const order = sortOrder(a[prop] ?? null, b[prop] ?? null, direction);
|
|
211
|
+
if (order !== 0) return order;
|
|
212
|
+
}
|
|
213
|
+
return 0;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
return query.limit === undefined ? found : found.slice(0, query.limit);
|
|
217
|
+
}
|
|
218
|
+
/** Every row as this transaction sees it: committed, then overlaid with its own writes. */ *rows(tx, type) {
|
|
219
|
+
const table = this.table(type);
|
|
220
|
+
const writes = tx.writes.get(type);
|
|
221
|
+
for (const [key, row] of table){
|
|
222
|
+
const written = writes?.get(key);
|
|
223
|
+
if (written === undefined) yield [
|
|
224
|
+
key,
|
|
225
|
+
row
|
|
226
|
+
];
|
|
227
|
+
else if (written !== null) yield [
|
|
228
|
+
key,
|
|
229
|
+
written
|
|
230
|
+
];
|
|
231
|
+
}
|
|
232
|
+
for (const [key, row] of writes ?? []){
|
|
233
|
+
if (row !== null && !table.has(key)) yield [
|
|
234
|
+
key,
|
|
235
|
+
row
|
|
236
|
+
];
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
row(tx, type, key) {
|
|
240
|
+
const written = tx.writes.get(type)?.get(key);
|
|
241
|
+
if (written !== undefined) return written ?? undefined;
|
|
242
|
+
return this.table(type).get(key);
|
|
243
|
+
}
|
|
244
|
+
write(tx, type, key, row) {
|
|
245
|
+
let writes = tx.writes.get(type);
|
|
246
|
+
if (writes == null) {
|
|
247
|
+
writes = new Map();
|
|
248
|
+
tx.writes.set(type, writes);
|
|
249
|
+
}
|
|
250
|
+
writes.set(key, row);
|
|
251
|
+
}
|
|
252
|
+
table(type) {
|
|
253
|
+
let table = this.tables.get(type);
|
|
254
|
+
if (table == null) {
|
|
255
|
+
table = new Map();
|
|
256
|
+
this.tables.set(type, table);
|
|
257
|
+
}
|
|
258
|
+
return table;
|
|
259
|
+
}
|
|
260
|
+
/** A row's references, as a foreign key checks them: each set one points at a row that exists. */ async checkReferences(tx, model, row, props) {
|
|
261
|
+
for (const ref of model.references){
|
|
262
|
+
if (!props.includes(ref.prop)) continue;
|
|
263
|
+
const value = row[ref.prop];
|
|
264
|
+
if (value == null) {
|
|
265
|
+
if (ref.nullable) continue;
|
|
266
|
+
throw new DataError(`${model.name}.${ref.prop} can't be empty`);
|
|
267
|
+
}
|
|
268
|
+
const target = this.model(ref.target);
|
|
269
|
+
const key = this.keyOf(target, {
|
|
270
|
+
[target.key[0]]: value
|
|
271
|
+
});
|
|
272
|
+
await this.acquire(tx, ref.target, key, "key-share");
|
|
273
|
+
if (this.row(tx, ref.target, key) == null) {
|
|
274
|
+
throw new DataError(`${model.name}.${ref.prop} references ${target.name} ${String(value)}, which doesn't exist`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
referencing(tx, parent, row) {
|
|
279
|
+
const found = [];
|
|
280
|
+
if (parent.key.length !== 1) return found;
|
|
281
|
+
const value = row[parent.key[0]];
|
|
282
|
+
for (const child of this.models.values()){
|
|
283
|
+
for (const ref of child.references){
|
|
284
|
+
if (ref.target !== parent.type) continue;
|
|
285
|
+
for (const [key, candidate] of this.rows(tx, child.type)){
|
|
286
|
+
if (equal(candidate[ref.prop], value)) found.push({
|
|
287
|
+
child,
|
|
288
|
+
ref,
|
|
289
|
+
key,
|
|
290
|
+
row: candidate
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return found;
|
|
296
|
+
}
|
|
297
|
+
assertUnreferenced(tx, model, row) {
|
|
298
|
+
const [first] = this.referencing(tx, model, row);
|
|
299
|
+
if (first) {
|
|
300
|
+
throw new DataError(`Can't change the key of ${model.name} ${this.describe(model, row)}: ${first.child.name}.${first.ref.prop} references it`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// ── Locks ──────────────────────────────────────────────────────────────
|
|
304
|
+
/** Take a row lock, waiting while another transaction holds one that conflicts. */ async acquire(tx, type, key, mode) {
|
|
305
|
+
let byKey = this.locks.get(type);
|
|
306
|
+
if (byKey == null) {
|
|
307
|
+
byKey = new Map();
|
|
308
|
+
this.locks.set(type, byKey);
|
|
309
|
+
}
|
|
310
|
+
for(;;){
|
|
311
|
+
let holders = byKey.get(key);
|
|
312
|
+
if (holders == null) {
|
|
313
|
+
holders = new Map();
|
|
314
|
+
byKey.set(key, holders);
|
|
315
|
+
}
|
|
316
|
+
const blocking = [
|
|
317
|
+
...holders
|
|
318
|
+
].filter(([other, held])=>other !== tx && CONFLICTS[mode].includes(held)).map(([other])=>other);
|
|
319
|
+
if (blocking.length === 0) {
|
|
320
|
+
const mine = holders.get(tx);
|
|
321
|
+
if (mine == null) tx.held.push({
|
|
322
|
+
type,
|
|
323
|
+
key
|
|
324
|
+
});
|
|
325
|
+
if (mine == null || STRENGTH[mode] > STRENGTH[mine]) holders.set(tx, mode);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
tx.waitingFor = new Set(blocking);
|
|
329
|
+
if (this.waitsOnItself(tx)) {
|
|
330
|
+
tx.waitingFor = new Set();
|
|
331
|
+
throw new DataError(`Deadlock: two transactions each wait for a row the other has locked (${this.model(type).name})`);
|
|
332
|
+
}
|
|
333
|
+
await Promise.race(blocking.map((other)=>other.done));
|
|
334
|
+
tx.waitingFor = new Set();
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
holds(tx, type, key, mode) {
|
|
338
|
+
const held = this.locks.get(type)?.get(key)?.get(tx);
|
|
339
|
+
return held != null && STRENGTH[held] >= STRENGTH[mode];
|
|
340
|
+
}
|
|
341
|
+
waitsOnItself(tx) {
|
|
342
|
+
const seen = new Set();
|
|
343
|
+
const visit = (other)=>{
|
|
344
|
+
if (other === tx) return true;
|
|
345
|
+
if (seen.has(other)) return false;
|
|
346
|
+
seen.add(other);
|
|
347
|
+
return [
|
|
348
|
+
...other.waitingFor
|
|
349
|
+
].some(visit);
|
|
350
|
+
};
|
|
351
|
+
return [
|
|
352
|
+
...tx.waitingFor
|
|
353
|
+
].some(visit);
|
|
354
|
+
}
|
|
355
|
+
end(tx) {
|
|
356
|
+
for (const { type, key } of tx.held){
|
|
357
|
+
const byKey = this.locks.get(type);
|
|
358
|
+
const holders = byKey?.get(key);
|
|
359
|
+
holders?.delete(tx);
|
|
360
|
+
if (holders?.size === 0) byKey?.delete(key);
|
|
361
|
+
}
|
|
362
|
+
tx.finish();
|
|
363
|
+
}
|
|
364
|
+
// ── Helpers ────────────────────────────────────────────────────────────
|
|
365
|
+
/** Run one statement. A failure aborts the transaction, as in Postgres: it can only roll back. */ async statement(tx, run) {
|
|
366
|
+
this.assertOpen(tx);
|
|
367
|
+
if (tx.aborted !== undefined) {
|
|
368
|
+
throw new DataError("The transaction was aborted by an earlier error: roll it back", {
|
|
369
|
+
cause: tx.aborted
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
return await run();
|
|
374
|
+
} catch (err) {
|
|
375
|
+
tx.aborted = err;
|
|
376
|
+
throw err;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
assertOpen(tx) {
|
|
380
|
+
if (tx.finished) throw new DataError("The transaction has ended");
|
|
381
|
+
}
|
|
382
|
+
assertProp(model, prop) {
|
|
383
|
+
if (!model.fields.includes(prop) && !model.references.some((r)=>r.prop === prop)) {
|
|
384
|
+
throw new DataConfigurationError(`${model.name} has no field "${prop}"`);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/** A row's key as one string. Dates count by their instant. */ keyOf(model, row) {
|
|
388
|
+
return JSON.stringify(model.key.map((prop)=>{
|
|
389
|
+
const value = row[prop];
|
|
390
|
+
return value instanceof Date ? {
|
|
391
|
+
date: value.getTime()
|
|
392
|
+
} : value;
|
|
393
|
+
}));
|
|
394
|
+
}
|
|
395
|
+
describe(model, row) {
|
|
396
|
+
return model.key.map((prop)=>String(row[prop])).join(", ");
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
/** Whether a stored value meets a condition, with SQL's nulls: only `null` and `ne` match an empty value. */ function matches(value, condition) {
|
|
400
|
+
if (condition === null) return value === null;
|
|
401
|
+
const operator = comparison.operatorOf(condition);
|
|
402
|
+
if (!operator) return value !== null && equal(value, condition);
|
|
403
|
+
const [op, operand] = operator;
|
|
404
|
+
if (op === "ne" && operand === null) return value !== null;
|
|
405
|
+
if (value === null) return false;
|
|
406
|
+
if (op === "in") return operand.some((v)=>equal(value, v));
|
|
407
|
+
if (op === "ne") return !equal(value, operand);
|
|
408
|
+
if (operand === null) return false;
|
|
409
|
+
const order = compare(value, operand);
|
|
410
|
+
if (op === "gt") return order > 0;
|
|
411
|
+
if (op === "gte") return order >= 0;
|
|
412
|
+
if (op === "lt") return order < 0;
|
|
413
|
+
return order <= 0;
|
|
414
|
+
}
|
|
415
|
+
/** Postgres's order: empty values last ascending, first descending. */ function sortOrder(a, b, direction) {
|
|
416
|
+
const sign = direction === "desc" ? -1 : 1;
|
|
417
|
+
if (a === null || b === null) {
|
|
418
|
+
if (a === b) return 0;
|
|
419
|
+
return (a === null ? 1 : -1) * sign;
|
|
420
|
+
}
|
|
421
|
+
return compare(a, b) * sign;
|
|
422
|
+
}
|
|
423
|
+
function compare(a, b) {
|
|
424
|
+
const x = a instanceof Date ? a.getTime() : a;
|
|
425
|
+
const y = b instanceof Date ? b.getTime() : b;
|
|
426
|
+
const kind = typeof x;
|
|
427
|
+
if (kind !== typeof y || ![
|
|
428
|
+
"number",
|
|
429
|
+
"string",
|
|
430
|
+
"bigint",
|
|
431
|
+
"boolean"
|
|
432
|
+
].includes(kind)) {
|
|
433
|
+
throw new DataError(`Can't compare ${String(a)} with ${String(b)}`);
|
|
434
|
+
}
|
|
435
|
+
if (x < y) return -1;
|
|
436
|
+
return x > y ? 1 : 0;
|
|
437
|
+
}
|
|
438
|
+
function equal(a, b) {
|
|
439
|
+
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
|
440
|
+
if (a !== null && b !== null && typeof a === "object" && typeof b === "object") {
|
|
441
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
442
|
+
}
|
|
443
|
+
return a === b;
|
|
444
|
+
}
|
|
445
|
+
function copy(value) {
|
|
446
|
+
return value !== null && typeof value === "object" ? structuredClone(value) : value;
|
|
447
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decohere/data-memory",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1-dev.20261122.343",
|
|
4
|
+
"description": "In-memory provider for @decohere/data: repositories and the unit of work with no database, for tests and local runs",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"typescript",
|
|
7
|
+
"in-memory",
|
|
8
|
+
"testing",
|
|
9
|
+
"data-access",
|
|
10
|
+
"decohere"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/typesmiths/decohere/tree/main/projects/data/data-memory#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/typesmiths/decohere/issues"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/typesmiths/decohere.git",
|
|
19
|
+
"directory": "projects/data/data-memory"
|
|
20
|
+
},
|
|
21
|
+
"license": "ISC",
|
|
22
|
+
"author": "Typesmiths",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./types/src/index.d.ts",
|
|
27
|
+
"import": "./es6/src/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@decohere/core": "0.0.1-dev.20261122.343",
|
|
35
|
+
"@decohere/data": "0.0.1-dev.20261122.343"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {}
|
|
38
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type ChildKeys, type EntityClass, type EntityModel, type FieldKeys, type ReferenceModel } from "@decohere/data";
|
|
2
|
+
/** A reference to another mapped class, stored as that class's key. */
|
|
3
|
+
export type MemoryReference<T> = {
|
|
4
|
+
prop: FieldKeys<T>;
|
|
5
|
+
target: EntityClass;
|
|
6
|
+
/** Whether it may be empty. Defaults to false: a row can't be written without it. */
|
|
7
|
+
nullable?: boolean;
|
|
8
|
+
/** `"cascade"`: deleting the referenced row deletes this one, like `ON DELETE CASCADE`. Otherwise the delete fails while this row references it. */
|
|
9
|
+
onDelete?: "cascade";
|
|
10
|
+
};
|
|
11
|
+
/** A child collection: the rows of `target` whose `parentRef` references this one. */
|
|
12
|
+
export type MemoryChildren<T> = {
|
|
13
|
+
prop: ChildKeys<T>;
|
|
14
|
+
target: EntityClass;
|
|
15
|
+
/** The child's reference to its parent. */
|
|
16
|
+
parentRef: string;
|
|
17
|
+
/** The order children load in. Defaults to the child's key, ascending. */
|
|
18
|
+
orderBy?: Record<string, "asc" | "desc">;
|
|
19
|
+
};
|
|
20
|
+
export type MemoryEntityOptions<T> = {
|
|
21
|
+
/** The properties making the key: fields or references. Defaults to `["id"]`. */
|
|
22
|
+
key?: FieldKeys<T>[];
|
|
23
|
+
/** The properties stored as values. Key fields, the version and the generated key may be left out. */
|
|
24
|
+
fields: FieldKeys<T>[];
|
|
25
|
+
references?: MemoryReference<T>[];
|
|
26
|
+
children?: MemoryChildren<T>[];
|
|
27
|
+
/** A number checked and incremented on every update. */
|
|
28
|
+
version?: FieldKeys<T>;
|
|
29
|
+
/** A key field the store numbers 1, 2, 3… when an insert leaves it empty, like a serial column. */
|
|
30
|
+
generated?: FieldKeys<T>;
|
|
31
|
+
};
|
|
32
|
+
/** One class's mapping, as {@link mapEntity} makes it. */
|
|
33
|
+
export type MemoryEntity = EntityModel & {
|
|
34
|
+
references: (ReferenceModel & {
|
|
35
|
+
onDelete?: "cascade";
|
|
36
|
+
})[];
|
|
37
|
+
generated?: string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Map a class for the memory provider. With no ORM to read metadata from, the mapping is written
|
|
41
|
+
* out: which properties are stored, which reference another class, and which hold children.
|
|
42
|
+
*/
|
|
43
|
+
export declare function mapEntity<T extends object>(type: EntityClass<T>, options: MemoryEntityOptions<T>): MemoryEntity;
|
|
44
|
+
/**
|
|
45
|
+
* Check the mappings fit together, so a mistake fails when the app is built rather than at the
|
|
46
|
+
* first query: every key, reference and child names something mapped.
|
|
47
|
+
*/
|
|
48
|
+
declare function check(entities: readonly MemoryEntity[]): Map<EntityClass, MemoryEntity>;
|
|
49
|
+
export declare const memoryEntities: {
|
|
50
|
+
check: typeof check;
|
|
51
|
+
};
|
|
52
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { BuilderPlugin } from "@decohere/core/hosting";
|
|
2
|
+
import type { Constructable } from "@decohere/core/reflection";
|
|
3
|
+
import { type IUnitOfWork, type OutboxMapper } from "@decohere/data";
|
|
4
|
+
import type { MemoryEntity } from "./memory-entity.js";
|
|
5
|
+
export type MemoryModuleConfig = {
|
|
6
|
+
/** The data source's name, as `@injectUnitOfWork(name)` asks for it. Required when there are several. */
|
|
7
|
+
name?: string;
|
|
8
|
+
/** Each mapped class: `mapEntity(Order, { … })`. */
|
|
9
|
+
entities: MemoryEntity[];
|
|
10
|
+
repositories?: Constructable[];
|
|
11
|
+
/** Writes the events aggregates raise to an outbox entity, in the same commit. */
|
|
12
|
+
outbox?: OutboxMapper;
|
|
13
|
+
/** Runs when the app starts, with a unit of work that is committed when it returns. */
|
|
14
|
+
seed?: (unitOfWork: IUnitOfWork) => Promise<void>;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Keep the data in the process, with no database: for tests and local runs. Each build of the app
|
|
18
|
+
* gets empty stores of its own. Needs no `database` config.
|
|
19
|
+
*/
|
|
20
|
+
export declare function memory(config: MemoryModuleConfig[] | MemoryModuleConfig): BuilderPlugin;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type EntityClass, type EntityModel, type Row, type RowQuery, type RowStore } from "@decohere/data";
|
|
2
|
+
import type { MemoryStore } from "./memory.store.js";
|
|
3
|
+
/**
|
|
4
|
+
* The memory provider's share of the unit of work: one transaction at a time on a
|
|
5
|
+
* {@link MemoryStore}. Outside a transaction each operation runs in one of its own, as a database
|
|
6
|
+
* runs a statement on its own.
|
|
7
|
+
*/
|
|
8
|
+
export declare class MemoryRowStore implements RowStore {
|
|
9
|
+
private readonly store;
|
|
10
|
+
private transaction;
|
|
11
|
+
constructor(store: MemoryStore);
|
|
12
|
+
model(type: EntityClass): EntityModel;
|
|
13
|
+
begin(): Promise<void>;
|
|
14
|
+
commit(): Promise<void>;
|
|
15
|
+
rollback(): Promise<void>;
|
|
16
|
+
release(): Promise<void>;
|
|
17
|
+
inTransaction(): boolean;
|
|
18
|
+
select(type: EntityClass, query: RowQuery): Promise<Row[]>;
|
|
19
|
+
insert(type: EntityClass, rows: Row[]): Promise<Row[]>;
|
|
20
|
+
update(type: EntityClass, key: Row, changes: Row, version?: {
|
|
21
|
+
prop: string;
|
|
22
|
+
expected: unknown;
|
|
23
|
+
}): Promise<number>;
|
|
24
|
+
delete(type: EntityClass, keys: Row[]): Promise<void>;
|
|
25
|
+
private end;
|
|
26
|
+
private run;
|
|
27
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type EntityClass, type Row, type RowQuery } from "@decohere/data";
|
|
2
|
+
import { type MemoryEntity } from "./memory-entity.js";
|
|
3
|
+
/** One transaction: its writes, kept apart until commit, and the row locks it holds. */
|
|
4
|
+
export declare class MemoryTransaction {
|
|
5
|
+
/** Per class, by key: the row as this transaction wrote it, or null where it deleted one. */
|
|
6
|
+
readonly writes: Map<EntityClass, Map<string, Row>>;
|
|
7
|
+
readonly held: {
|
|
8
|
+
type: EntityClass;
|
|
9
|
+
key: string;
|
|
10
|
+
}[];
|
|
11
|
+
/** The transactions holding locks this one waits for. */
|
|
12
|
+
waitingFor: Set<MemoryTransaction>;
|
|
13
|
+
/** The error that aborted it: after a failed statement, as in Postgres, it only rolls back. */
|
|
14
|
+
aborted: unknown;
|
|
15
|
+
finished: boolean;
|
|
16
|
+
readonly done: Promise<void>;
|
|
17
|
+
private settle;
|
|
18
|
+
constructor();
|
|
19
|
+
finish(): void;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The rows of one data source, held in the process. Reads see what is committed plus their own
|
|
23
|
+
* transaction's writes (read committed); a commit applies a transaction's writes in one step.
|
|
24
|
+
* Rows are copied in and out, so an object held outside can't change what is stored.
|
|
25
|
+
*/
|
|
26
|
+
export declare class MemoryStore {
|
|
27
|
+
private readonly models;
|
|
28
|
+
private readonly tables;
|
|
29
|
+
private readonly sequences;
|
|
30
|
+
private readonly locks;
|
|
31
|
+
constructor(entities: readonly MemoryEntity[]);
|
|
32
|
+
model(type: EntityClass): MemoryEntity;
|
|
33
|
+
begin(): MemoryTransaction;
|
|
34
|
+
commit(tx: MemoryTransaction): void;
|
|
35
|
+
rollback(tx: MemoryTransaction): void;
|
|
36
|
+
select(tx: MemoryTransaction, type: EntityClass, query: RowQuery): Promise<Row[]>;
|
|
37
|
+
insert(tx: MemoryTransaction, type: EntityClass, rows: Row[]): Promise<Row[]>;
|
|
38
|
+
update(tx: MemoryTransaction, type: EntityClass, keyRow: Row, changes: Row, version?: {
|
|
39
|
+
prop: string;
|
|
40
|
+
expected: unknown;
|
|
41
|
+
}): Promise<number>;
|
|
42
|
+
delete(tx: MemoryTransaction, type: EntityClass, keys: Row[]): Promise<void>;
|
|
43
|
+
private query;
|
|
44
|
+
/** Every row as this transaction sees it: committed, then overlaid with its own writes. */
|
|
45
|
+
private rows;
|
|
46
|
+
private row;
|
|
47
|
+
private write;
|
|
48
|
+
private table;
|
|
49
|
+
/** A row's references, as a foreign key checks them: each set one points at a row that exists. */
|
|
50
|
+
private checkReferences;
|
|
51
|
+
private referencing;
|
|
52
|
+
private assertUnreferenced;
|
|
53
|
+
/** Take a row lock, waiting while another transaction holds one that conflicts. */
|
|
54
|
+
private acquire;
|
|
55
|
+
private holds;
|
|
56
|
+
private waitsOnItself;
|
|
57
|
+
private end;
|
|
58
|
+
/** Run one statement. A failure aborts the transaction, as in Postgres: it can only roll back. */
|
|
59
|
+
private statement;
|
|
60
|
+
private assertOpen;
|
|
61
|
+
private assertProp;
|
|
62
|
+
/** A row's key as one string. Dates count by their instant. */
|
|
63
|
+
private keyOf;
|
|
64
|
+
private describe;
|
|
65
|
+
}
|