@kiri-orm/core 0.1.6 → 0.2.0
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 +27 -15
- package/dist/types/client/model-handle.d.ts +4 -1
- package/dist/types/connection.d.ts +66 -0
- package/dist/types/crud/chunk.d.ts +10 -0
- package/dist/types/crud/database-errors.d.ts +61 -0
- package/dist/types/crud/errors.d.ts +10 -0
- package/dist/types/crud/fast-path.d.ts +73 -0
- package/dist/types/crud/index.d.ts +4 -1
- package/dist/types/crud/insert-many.d.ts +12 -13
- package/dist/types/crud/order.d.ts +28 -0
- package/dist/types/crud/repository.d.ts +5 -3
- package/dist/types/crud/row-mapping.d.ts +9 -1
- package/dist/types/crud/upsert.d.ts +39 -0
- package/dist/types/crud/value.d.ts +39 -0
- package/dist/types/dialect/date-bucket.d.ts +2 -2
- package/dist/types/dialect/index.d.ts +1 -0
- package/dist/types/dialect/transaction-guard.d.ts +31 -0
- package/dist/types/domain/compile.d.ts +17 -0
- package/dist/types/fields/filter-value.d.ts +21 -0
- package/dist/types/fields/registry.d.ts +1 -0
- package/dist/types/fields/storage.d.ts +28 -0
- package/dist/types/fields/types/date.d.ts +6 -6
- package/dist/types/fields/types/decimal.d.ts +40 -0
- package/dist/types/global/errors.d.ts +3 -0
- package/dist/types/global/index.d.ts +2 -0
- package/dist/types/global/normalize-dates.d.ts +11 -0
- package/dist/types/global/state.d.ts +2 -0
- package/dist/types/global/transaction.d.ts +10 -13
- package/dist/types/index.d.ts +2 -0
- package/dist/types/meta/create-table-once.d.ts +15 -0
- package/dist/types/meta/snapshot.d.ts +10 -0
- package/dist/types/meta/upsert.d.ts +16 -0
- package/dist/types/migrations/diff.d.ts +25 -2
- package/dist/types/models/constraints.d.ts +27 -0
- package/dist/types/relations/pivot-schema.d.ts +1 -1
- package/dist/types/schema/alter-column.d.ts +46 -0
- package/dist/types/schema/build-column.d.ts +11 -0
- package/dist/types/schema/index.d.ts +1 -0
- package/dist/types/schema/introspect-indexes.d.ts +9 -0
- package/dist/types/schema/normalize-dates.d.ts +41 -0
- package/dist/types/transaction/after-commit.d.ts +42 -0
- package/dist/types/transaction/context.d.ts +39 -0
- package/dist/types/uow/entity.d.ts +39 -29
- package/dist/types/uow/hooks.d.ts +6 -1
- package/dist/types/uow/lifecycle.d.ts +82 -0
- package/dist/types/uow/unit-of-work.d.ts +11 -7
- package/package.json +8 -5
- package/src/client/model-handle.js +14 -4
- package/src/client/orm-client.js +10 -5
- package/src/connection.js +53 -7
- package/src/crud/aggregate-filter.js +8 -2
- package/src/crud/aggregate-spec.js +2 -2
- package/src/crud/aggregate.js +16 -5
- package/src/crud/chunk.js +10 -0
- package/src/crud/create-many.js +52 -29
- package/src/crud/database-errors.js +107 -0
- package/src/crud/errors.js +14 -0
- package/src/crud/fast-path.js +449 -0
- package/src/crud/index.js +4 -1
- package/src/crud/insert-many.js +42 -7
- package/src/crud/map-filter.js +2 -1
- package/src/crud/order.js +59 -9
- package/src/crud/repository.js +106 -38
- package/src/crud/row-mapping.js +32 -7
- package/src/crud/upsert.js +203 -0
- package/src/crud/value.js +71 -0
- package/src/dialect/index.js +1 -0
- package/src/dialect/transaction-guard.js +254 -0
- package/src/domain/compile.js +85 -12
- package/src/dto/field-schema.js +5 -0
- package/src/fields/default-registry.js +3 -1
- package/src/fields/filter-value.js +87 -0
- package/src/fields/registry.js +1 -0
- package/src/fields/storage.js +50 -0
- package/src/fields/types/date.js +16 -3
- package/src/fields/types/decimal.js +147 -0
- package/src/fields/types/integer.js +7 -0
- package/src/global/connect.js +25 -1
- package/src/global/create-model.js +59 -57
- package/src/global/errors.js +1 -1
- package/src/global/index.js +2 -0
- package/src/global/normalize-dates.js +15 -0
- package/src/global/state.js +3 -0
- package/src/global/transaction.js +12 -14
- package/src/index.js +2 -0
- package/src/meta/create-table-once.js +23 -0
- package/src/meta/schema.js +15 -6
- package/src/meta/snapshot.js +5 -0
- package/src/meta/upsert.js +28 -0
- package/src/migrations/describe.js +49 -0
- package/src/migrations/diff.js +50 -7
- package/src/migrations/generate.js +38 -2
- package/src/migrations/render.js +30 -12
- package/src/migrations/runner.js +40 -6
- package/src/models/constraints.js +96 -0
- package/src/models/define-model.js +4 -0
- package/src/models/inheritance.js +4 -1
- package/src/models/registry.js +2 -1
- package/src/relations/attach-detach.js +49 -18
- package/src/relations/cascade-delete.js +32 -7
- package/src/relations/eager-load.js +75 -51
- package/src/relations/pivot-schema.js +24 -3
- package/src/reports/report-handle.js +2 -1
- package/src/schema/alter-column.js +219 -0
- package/src/schema/build-column.js +28 -2
- package/src/schema/default-column-builders.js +16 -2
- package/src/schema/index.js +1 -0
- package/src/schema/introspect-indexes.js +22 -0
- package/src/schema/normalize-dates.js +58 -0
- package/src/schema/sync.js +16 -2
- package/src/transaction/after-commit.js +142 -0
- package/src/transaction/context.js +84 -0
- package/src/uow/entity.js +133 -133
- package/src/uow/hooks.js +9 -0
- package/src/uow/lifecycle.js +162 -0
- package/src/uow/unit-of-work.js +55 -60
- package/src/uow/with-unit-of-work.js +2 -1
package/src/uow/entity.js
CHANGED
|
@@ -12,158 +12,157 @@ import { expandSelect } from "../crud/select.js";
|
|
|
12
12
|
export const ENTITY_META = Symbol("entityMeta");
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* primitive and is safe to share as-is (primitives can't be mutated
|
|
22
|
-
* in place at all).
|
|
23
|
-
*
|
|
24
|
-
* @param {unknown} value
|
|
25
|
-
* @param {import('../fields/define-field.js').FieldDescriptor} field
|
|
15
|
+
* The as-loaded snapshot dirty tracking compares against, kept compact (since 0.2.0): a json
|
|
16
|
+
* value is stored as its JSON text and a Date as its epoch milliseconds, so a read costs one
|
|
17
|
+
* `JSON.stringify` per json value instead of two deep clones, and comparing needs no second
|
|
18
|
+
* serialization. Every other field type is a primitive and is stored as-is (primitives can't be
|
|
19
|
+
* mutated in place). A json value JSON can't serialize (a cycle, a BigInt) is kept by reference
|
|
20
|
+
* and compared with ===.
|
|
26
21
|
*/
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
return new Date(value.getTime());
|
|
22
|
+
class ByReference {
|
|
23
|
+
constructor(value) {
|
|
24
|
+
this.value = value;
|
|
31
25
|
}
|
|
26
|
+
}
|
|
27
|
+
const isDateField = (field) => field.type === "date" || field.type === "datetime";
|
|
28
|
+
|
|
29
|
+
/** @returns {unknown} the snapshot form of `value` */
|
|
30
|
+
export function toSnapshot(value, field) {
|
|
31
|
+
if (value === null || value === undefined) return value;
|
|
32
|
+
if (value instanceof Date && isDateField(field)) return value.getTime();
|
|
32
33
|
if (field.type === "json") {
|
|
33
34
|
try {
|
|
34
|
-
return JSON.
|
|
35
|
+
return JSON.stringify(value);
|
|
35
36
|
} catch {
|
|
36
|
-
return value;
|
|
37
|
+
return new ByReference(value);
|
|
37
38
|
}
|
|
38
39
|
}
|
|
39
40
|
return value;
|
|
40
41
|
}
|
|
41
42
|
|
|
42
|
-
/**
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
* `unitOfWork.saveEntity(entity, ...)`) - `handlers` just needs
|
|
52
|
-
* `save(entity, options)` and `delete(entity, options)` functions,
|
|
53
|
-
* which lets a document be fully self-contained: it can carry
|
|
54
|
-
* everything it needs to save/delete itself without requiring an
|
|
55
|
-
* external identity-map-holding object to mediate. `UnitOfWork` still
|
|
56
|
-
* supplies handlers bound to itself (for identity-mapped, per-
|
|
57
|
-
* transaction use), but the global Mongoose-style `createModel()` API
|
|
58
|
-
* supplies handlers with no external coordinator at all - just a
|
|
59
|
-
* shared connection and hook registry captured in a closure.
|
|
60
|
-
*
|
|
61
|
-
* The entity's live values and its `original` snapshot are built as
|
|
62
|
-
* two SEPARATE clones for mutable field types (see cloneFieldValue) -
|
|
63
|
-
* critical for correctness: without this, `entity.dueDate` and
|
|
64
|
-
* `original.dueDate` would be the same Date object, and mutating one
|
|
65
|
-
* in place would silently mutate the other too, making every
|
|
66
|
-
* in-place edit invisible to diffEntity(). A dedicated test
|
|
67
|
-
* (`flags a date field as dirty when mutated in place`) caught this
|
|
68
|
-
* exact bug during development.
|
|
69
|
-
*
|
|
70
|
-
* @param {Record<string, unknown>} record
|
|
71
|
-
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
72
|
-
* @param {string} modelName
|
|
73
|
-
* @param {{ save: (entity: object, options?: object) => Promise<unknown>, delete: (entity: object, options?: object) => Promise<unknown> }} handlers
|
|
74
|
-
*/
|
|
75
|
-
export function createEntity(record, model, modelName, handlers) {
|
|
76
|
-
const entity = {};
|
|
77
|
-
const original = {};
|
|
43
|
+
/** The snapshot value as a field value again: a fresh Date / parsed json. */
|
|
44
|
+
function fromSnapshot(stored, field) {
|
|
45
|
+
if (stored === null || stored === undefined) return stored;
|
|
46
|
+
if (stored instanceof ByReference) return stored.value;
|
|
47
|
+
if (field.type === "datetime" && typeof stored === "number") return new Date(stored);
|
|
48
|
+
if (field.type === "date" && typeof stored === "number") return new Date(stored);
|
|
49
|
+
if (field.type === "json" && typeof stored === "string") return JSON.parse(stored);
|
|
50
|
+
return stored;
|
|
51
|
+
}
|
|
78
52
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
53
|
+
function equalsSnapshot(value, stored, field) {
|
|
54
|
+
if (stored instanceof ByReference) return value === stored.value;
|
|
55
|
+
if (value === null || value === undefined || stored === null || stored === undefined) return value === stored;
|
|
56
|
+
if (isDateField(field) && (value instanceof Date || typeof stored === "number")) {
|
|
57
|
+
return (value instanceof Date ? value.getTime() : value) === stored;
|
|
83
58
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
// only model.fields keys). A real regression during development:
|
|
90
|
-
// the loop above alone (added to fix the Date/JSON in-place-
|
|
91
|
-
// mutation bug) silently dropped eager-loaded relations entirely,
|
|
92
|
-
// since it only ever considered model.fields - caught while
|
|
93
|
-
// building an example combining UnitOfWork with `with` for the
|
|
94
|
-
// first time, which no earlier test happened to do.
|
|
95
|
-
for (const relationName of Object.keys(model.relations ?? {})) {
|
|
96
|
-
if (relationName in record) {
|
|
97
|
-
entity[relationName] = record[relationName];
|
|
59
|
+
if (field.type === "json") {
|
|
60
|
+
try {
|
|
61
|
+
return JSON.stringify(value) === stored;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
98
64
|
}
|
|
99
65
|
}
|
|
66
|
+
return value === stored;
|
|
67
|
+
}
|
|
100
68
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
configurable: false,
|
|
113
|
-
});
|
|
69
|
+
/**
|
|
70
|
+
* The entity's as-loaded values as a plain object (fresh Dates and json values), e.g. a hook's
|
|
71
|
+
* `ctx.original`. `entity[ENTITY_META].original` returns the same: a copy, so writing to it
|
|
72
|
+
* changes nothing (use markClean()).
|
|
73
|
+
*/
|
|
74
|
+
export function originalValues(entity) {
|
|
75
|
+
const { snapshot, model } = entity[ENTITY_META];
|
|
76
|
+
const out = {};
|
|
77
|
+
for (const name of Object.keys(snapshot)) out[name] = fromSnapshot(snapshot[name], model.fields[name]);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
114
80
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
});
|
|
81
|
+
/** One as-loaded value (e.g. the primary key a save/delete targets). */
|
|
82
|
+
export function originalValue(entity, fieldName) {
|
|
83
|
+
const { snapshot, model } = entity[ENTITY_META];
|
|
84
|
+
return fromSnapshot(snapshot[fieldName], model.fields[fieldName]);
|
|
85
|
+
}
|
|
121
86
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
});
|
|
87
|
+
/** Whether `fieldName` still holds its as-loaded (last saved) value. */
|
|
88
|
+
export function isFieldClean(entity, fieldName) {
|
|
89
|
+
const { snapshot, model } = entity[ENTITY_META];
|
|
90
|
+
return equalsSnapshot(entity[fieldName], snapshot[fieldName], model.fields[fieldName]);
|
|
91
|
+
}
|
|
128
92
|
|
|
129
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Undoes, in memory, a save() whose transaction rolled back (since 0.2.0): each saved field goes
|
|
95
|
+
* back to `before` - its value in the database again - both as the document's value and as its
|
|
96
|
+
* snapshot. A field the caller changed again after that save keeps the newer value, and stays
|
|
97
|
+
* dirty against `before`, so the next save() writes it.
|
|
98
|
+
*
|
|
99
|
+
* @param {Record<string, unknown>} entity
|
|
100
|
+
* @param {Record<string, unknown>} before - field name -> value before the save
|
|
101
|
+
*/
|
|
102
|
+
export function revertSave(entity, before) {
|
|
103
|
+
for (const [fieldName, value] of Object.entries(before)) {
|
|
104
|
+
if (isFieldClean(entity, fieldName)) entity[fieldName] = value;
|
|
105
|
+
markClean(entity, fieldName, value);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Marks a document whose INSERT was rolled back: it has no row, and save() says why. */
|
|
110
|
+
export function markCreateRolledBack(entity) {
|
|
111
|
+
if (entity?.[ENTITY_META]) entity[ENTITY_META].createRolledBack = true;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Records `value` as the stored value of `fieldName`: the field is clean again. */
|
|
115
|
+
export function markClean(entity, fieldName, value) {
|
|
116
|
+
const { snapshot, model } = entity[ENTITY_META];
|
|
117
|
+
snapshot[fieldName] = toSnapshot(value, model.fields[fieldName]);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
class EntityMeta {
|
|
121
|
+
constructor(snapshot, model, modelName) {
|
|
122
|
+
this.snapshot = snapshot;
|
|
123
|
+
this.model = model;
|
|
124
|
+
this.modelName = modelName;
|
|
125
|
+
}
|
|
126
|
+
/** A copy of the as-loaded values (see originalValues()). */
|
|
127
|
+
get original() {
|
|
128
|
+
const out = {};
|
|
129
|
+
for (const name of Object.keys(this.snapshot)) out[name] = fromSnapshot(this.snapshot[name], this.model.fields[name]);
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
130
132
|
}
|
|
131
133
|
|
|
132
134
|
/**
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
+
* Turns a plain record into a tracked entity: same enumerable field properties, plus a hidden
|
|
136
|
+
* snapshot of the values as loaded and non-enumerable save()/delete() methods that call whatever
|
|
137
|
+
* `handlers.save`/`handlers.delete` functions the caller supplies.
|
|
135
138
|
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
139
|
+
* The record itself becomes the entity (since 0.2.0; before, its values were copied onto a new
|
|
140
|
+
* object): every record handed in here is a fresh fromRow() result nothing else holds, and its
|
|
141
|
+
* computed getters already read the record itself. What makes in-place edits visible
|
|
142
|
+
* (`entity.dueDate.setDate(...)`, `entity.meta.tags.push(...)`) is the snapshot: it's taken by
|
|
143
|
+
* value (see toSnapshot), never shares an object with the live record.
|
|
138
144
|
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
* in-place mutation (`entity.dueDate.setDate(...)`,
|
|
143
|
-
* `entity.metadata.tags.push(...)`) leaves the object reference
|
|
144
|
-
* unchanged - `entity[field] === original[field]` stays `true` even
|
|
145
|
-
* though the value's actual content changed. Comparing by moment
|
|
146
|
-
* (`getTime()`) or serialized content (`JSON.stringify`) instead
|
|
147
|
-
* catches that case correctly.
|
|
145
|
+
* Decoupled from any particular coordinator: `handlers` just needs `save(entity, options)` and
|
|
146
|
+
* `delete(entity, options)`. UnitOfWork supplies handlers bound to itself, the global API ones
|
|
147
|
+
* closing over the connection and hook registry.
|
|
148
148
|
*
|
|
149
|
-
* @param {unknown} a
|
|
150
|
-
* @param {
|
|
151
|
-
* @param {
|
|
149
|
+
* @param {Record<string, unknown>} record - a fresh fromRow() result; becomes the entity
|
|
150
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
151
|
+
* @param {string} modelName
|
|
152
|
+
* @param {{ save: (entity: object, options?: object) => Promise<unknown>, delete: (entity: object, options?: object) => Promise<unknown> }} handlers
|
|
152
153
|
*/
|
|
153
|
-
function
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
}
|
|
159
|
-
if (field.type === "json") {
|
|
160
|
-
try {
|
|
161
|
-
return JSON.stringify(a) === JSON.stringify(b);
|
|
162
|
-
} catch {
|
|
163
|
-
return a === b;
|
|
164
|
-
}
|
|
154
|
+
export function createEntity(record, model, modelName, handlers) {
|
|
155
|
+
const entity = record;
|
|
156
|
+
const snapshot = {};
|
|
157
|
+
for (const fieldName in model.fields) {
|
|
158
|
+
if (fieldName in record) snapshot[fieldName] = toSnapshot(record[fieldName], model.fields[fieldName]);
|
|
165
159
|
}
|
|
166
|
-
|
|
160
|
+
Object.defineProperties(entity, {
|
|
161
|
+
[ENTITY_META]: { value: new EntityMeta(snapshot, model, modelName), enumerable: false, writable: true, configurable: false },
|
|
162
|
+
save: { value: (options) => handlers.save(entity, options), enumerable: false },
|
|
163
|
+
delete: { value: (options) => handlers.delete(entity, options), enumerable: false },
|
|
164
|
+
});
|
|
165
|
+
return entity;
|
|
167
166
|
}
|
|
168
167
|
|
|
169
168
|
/**
|
|
@@ -177,10 +176,10 @@ function valuesEqual(a, b, field) {
|
|
|
177
176
|
* @returns {Record<string, unknown>}
|
|
178
177
|
*/
|
|
179
178
|
export function diffEntity(entity, model) {
|
|
180
|
-
const {
|
|
179
|
+
const { snapshot } = entity[ENTITY_META];
|
|
181
180
|
const dirty = {};
|
|
182
|
-
for (const
|
|
183
|
-
if (!
|
|
181
|
+
for (const fieldName in model.fields) {
|
|
182
|
+
if (!equalsSnapshot(entity[fieldName], snapshot[fieldName], model.fields[fieldName])) {
|
|
184
183
|
dirty[fieldName] = entity[fieldName];
|
|
185
184
|
}
|
|
186
185
|
}
|
|
@@ -208,12 +207,13 @@ export function diffEntity(entity, model) {
|
|
|
208
207
|
* @returns {Record<string, unknown>} the same entity
|
|
209
208
|
*/
|
|
210
209
|
export function mergeRecordIntoEntity(entity, record, model) {
|
|
211
|
-
const {
|
|
210
|
+
const { snapshot } = entity[ENTITY_META];
|
|
211
|
+
const original = snapshot;
|
|
212
212
|
|
|
213
213
|
for (const [fieldName, field] of Object.entries(model.fields)) {
|
|
214
|
-
if (fieldName in record && !(fieldName in
|
|
215
|
-
entity[fieldName] =
|
|
216
|
-
|
|
214
|
+
if (fieldName in record && !(fieldName in snapshot)) {
|
|
215
|
+
entity[fieldName] = record[fieldName];
|
|
216
|
+
snapshot[fieldName] = toSnapshot(record[fieldName], field);
|
|
217
217
|
}
|
|
218
218
|
}
|
|
219
219
|
|
package/src/uow/hooks.js
CHANGED
|
@@ -16,6 +16,7 @@ export const HOOK_NAMES = [
|
|
|
16
16
|
"afterSave",
|
|
17
17
|
"beforeDelete",
|
|
18
18
|
"afterDelete",
|
|
19
|
+
"afterCommit",
|
|
19
20
|
];
|
|
20
21
|
|
|
21
22
|
/**
|
|
@@ -58,6 +59,14 @@ export class HookRegistry {
|
|
|
58
59
|
* @param {typeof HOOK_NAMES[number]} hookName
|
|
59
60
|
* @param {unknown[]} args
|
|
60
61
|
*/
|
|
62
|
+
/**
|
|
63
|
+
* Whether any hook is registered for `modelName` (any of `hookNames`, or any at all). A write with
|
|
64
|
+
* no hooks needs no transaction around it; one with hooks runs them and the write atomically.
|
|
65
|
+
*/
|
|
66
|
+
has(modelName, hookNames = HOOK_NAMES) {
|
|
67
|
+
return hookNames.some((hookName) => (this.#hooks.get(`${modelName}:${hookName}`)?.length ?? 0) > 0);
|
|
68
|
+
}
|
|
69
|
+
|
|
61
70
|
async run(modelName, hookName, ...args) {
|
|
62
71
|
const fns = this.#hooks.get(`${modelName}:${hookName}`) ?? [];
|
|
63
72
|
for (const fn of fns) {
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { diffEntity, ENTITY_META, originalValues, originalValue, markClean, revertSave } from "./entity.js";
|
|
2
|
+
import { assertPrimaryKeyUntouched } from "../crud/prepare-write.js";
|
|
3
|
+
import { SaveDeletedError } from "../global/errors.js";
|
|
4
|
+
import { inTransactionIf } from "../transaction/context.js";
|
|
5
|
+
import { queueAfterCommit, onRollback } from "../transaction/after-commit.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The context every hook receives as its second argument (since 0.2.0):
|
|
9
|
+
* `hook(record, { event, isNew, trx, changes, original, model })`.
|
|
10
|
+
*
|
|
11
|
+
* - `event`: "create" | "update" | "delete" (and "upsert" before an upsert knows which it is)
|
|
12
|
+
* - `isNew`: true for a create, false for an update or delete, undefined before an upsert decides
|
|
13
|
+
* - `trx`: the transaction the write runs in, or null when it runs without one. Model calls in the
|
|
14
|
+
* hook join it on their own; `trx` is there for raw Knex queries and for passing on explicitly.
|
|
15
|
+
* - `changes`: the fields being written (a create's values, an update's changed fields). A
|
|
16
|
+
* before-hook may add to it - the additions are written too.
|
|
17
|
+
* - `original`: the values as read from the database, before this change (null for a create).
|
|
18
|
+
* - `model`: the model's name.
|
|
19
|
+
*
|
|
20
|
+
* @typedef {Object} HookContext
|
|
21
|
+
* @property {"create"|"update"|"delete"|"upsert"} event
|
|
22
|
+
* @property {boolean|undefined} isNew
|
|
23
|
+
* @property {import('knex').Knex.Transaction|null} trx
|
|
24
|
+
* @property {Record<string, unknown>|null} changes
|
|
25
|
+
* @property {Record<string, unknown>|null} original
|
|
26
|
+
* @property {string} model
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** @returns {HookContext} */
|
|
30
|
+
export function hookContext(db, event, { isNew, changes = null, original = null, model }) {
|
|
31
|
+
return { event, isNew, trx: db?.isTransaction ? db : null, changes, original, model };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Runs the after-hooks of a write that just happened on `db`: `after<Event>` and `afterSave` (not for
|
|
36
|
+
* deletes) now, inside the transaction, and `afterCommit` once it commits.
|
|
37
|
+
*/
|
|
38
|
+
export async function runAfterHooks(hooks, modelName, db, event, record, ctx) {
|
|
39
|
+
if (!hooks) return;
|
|
40
|
+
const name = event === "create" ? "afterCreate" : event === "update" ? "afterUpdate" : "afterDelete";
|
|
41
|
+
await hooks.run(modelName, name, record, ctx);
|
|
42
|
+
if (event !== "delete") await hooks.run(modelName, "afterSave", record, ctx);
|
|
43
|
+
if (hooks.has(modelName, ["afterCommit"])) {
|
|
44
|
+
await queueAfterCommit(db, () => hooks.run(modelName, "afterCommit", record, ctx));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Saves a tracked document's changes - shared by the global API's `doc.save()` and UnitOfWork.
|
|
50
|
+
*
|
|
51
|
+
* When the model has hooks, the before-hooks, the UPDATE and the after-hooks run as one atomic
|
|
52
|
+
* unit: in the open transaction if there is one, else in a transaction of their own. A hook that
|
|
53
|
+
* throws undoes the write and whatever the hooks wrote (since 0.2.0; before, after-hooks ran
|
|
54
|
+
* outside it and a before-hook's own writes survived a failed save).
|
|
55
|
+
*
|
|
56
|
+
* Before-hooks may change the document itself (`record.updatedAt = new Date()`) or add to
|
|
57
|
+
* `ctx.changes`; both are written. On any failure the document's values are put back as they
|
|
58
|
+
* were before save() - nothing was persisted.
|
|
59
|
+
*
|
|
60
|
+
* @param {Object} params
|
|
61
|
+
* @param {Record<string, unknown>} params.entity
|
|
62
|
+
* @param {import('../models/define-model.js').ModelDescriptor} params.model
|
|
63
|
+
* @param {string} params.modelName
|
|
64
|
+
* @param {import('./hooks.js').HookRegistry} [params.hooks]
|
|
65
|
+
* @param {import('knex').Knex} params.db - already resolved (explicit trx / ambient / connection)
|
|
66
|
+
* @param {(db: import('knex').Knex, changes: Record<string, unknown>) => Promise<number>} params.write - the UPDATE; returns rows affected
|
|
67
|
+
*/
|
|
68
|
+
export async function saveEntityLifecycle({ entity, model, modelName, hooks, db, write }) {
|
|
69
|
+
const dirty = diffEntity(entity, model);
|
|
70
|
+
if (Object.keys(dirty).length === 0) return entity;
|
|
71
|
+
|
|
72
|
+
// No hooks on this model: the UPDATE alone, no hook context or snapshot copy (since 0.2.0).
|
|
73
|
+
if (!(hooks?.has(modelName) ?? false)) return saveWithoutHooks(entity, model, modelName, db, write, dirty);
|
|
74
|
+
|
|
75
|
+
const originalSnapshot = originalValues(entity);
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
assertPrimaryKeyUntouched(model, dirty); // before any hook sees an id change
|
|
79
|
+
await inTransactionIf(hooks?.has(modelName) ?? false, db, async (conn) => {
|
|
80
|
+
const ctx = hookContext(conn, "update", { isNew: false, changes: dirty, original: originalSnapshot, model: modelName });
|
|
81
|
+
if (hooks) {
|
|
82
|
+
const beforeHooks = { ...dirty };
|
|
83
|
+
await hooks.run(modelName, "beforeUpdate", entity, ctx);
|
|
84
|
+
await hooks.run(modelName, "beforeSave", entity, ctx);
|
|
85
|
+
// A before-hook may have set fields on the document itself - new ones, or ones already being
|
|
86
|
+
// saved (`record.email = record.email.toLowerCase()`): the document's value wins for those.
|
|
87
|
+
// A field the hook changed only through ctx.changes keeps that value.
|
|
88
|
+
for (const [key, value] of Object.entries(diffEntity(entity, model))) {
|
|
89
|
+
if (!(key in dirty) || !Object.is(value, beforeHooks[key])) dirty[key] = value;
|
|
90
|
+
}
|
|
91
|
+
assertPrimaryKeyUntouched(model, dirty);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const affected = await write(conn, dirty);
|
|
95
|
+
if (!affected) throw saveDeletedError(entity, modelName);
|
|
96
|
+
// Dirty's final values onto both the document and its snapshot (a hook may have added some).
|
|
97
|
+
const before = {};
|
|
98
|
+
for (const [key, value] of Object.entries(dirty)) {
|
|
99
|
+
before[key] = originalSnapshot[key];
|
|
100
|
+
entity[key] = value;
|
|
101
|
+
markClean(entity, key, value);
|
|
102
|
+
}
|
|
103
|
+
onRollback(conn, () => revertSave(entity, before));
|
|
104
|
+
await runAfterHooks(hooks, modelName, conn, "update", entity, ctx);
|
|
105
|
+
});
|
|
106
|
+
} catch (error) {
|
|
107
|
+
// Nothing persisted: the document goes back to what the database holds.
|
|
108
|
+
for (const key of Object.keys(dirty)) {
|
|
109
|
+
entity[key] = originalSnapshot[key];
|
|
110
|
+
markClean(entity, key, originalSnapshot[key]);
|
|
111
|
+
}
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
return entity;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The error for a save() that matched no row: deleted since it was read, or never committed. */
|
|
118
|
+
function saveDeletedError(entity, modelName) {
|
|
119
|
+
return new SaveDeletedError(
|
|
120
|
+
entity[ENTITY_META]?.createRolledBack
|
|
121
|
+
? `save() on "${modelName}" did not affect any rows: the transaction that created this document rolled back, so its row was never committed.`
|
|
122
|
+
: `save() on "${modelName}" did not affect any rows: the row was deleted since it was read.`
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** saveEntityLifecycle() for a model without hooks: same result, less work. */
|
|
127
|
+
async function saveWithoutHooks(entity, model, modelName, db, write, dirty) {
|
|
128
|
+
const before = {};
|
|
129
|
+
for (const key of Object.keys(dirty)) before[key] = originalValue(entity, key);
|
|
130
|
+
try {
|
|
131
|
+
assertPrimaryKeyUntouched(model, dirty); // refused like any failure: the document goes back
|
|
132
|
+
const affected = await write(db, dirty);
|
|
133
|
+
if (!affected) throw saveDeletedError(entity, modelName);
|
|
134
|
+
for (const [key, value] of Object.entries(dirty)) markClean(entity, key, value);
|
|
135
|
+
// A rollback of the transaction this ran in undoes the UPDATE: the document goes back with it.
|
|
136
|
+
onRollback(db, () => revertSave(entity, before));
|
|
137
|
+
} catch (error) {
|
|
138
|
+
for (const [key, value] of Object.entries(before)) {
|
|
139
|
+
entity[key] = value;
|
|
140
|
+
markClean(entity, key, value);
|
|
141
|
+
}
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
return entity;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Deletes a tracked document - shared by the global API's `doc.delete()` and UnitOfWork. Hooks and
|
|
149
|
+
* the DELETE are one atomic unit when the model has hooks, as for saves.
|
|
150
|
+
*
|
|
151
|
+
* @returns {Promise<number>} rows deleted
|
|
152
|
+
*/
|
|
153
|
+
export async function deleteEntityLifecycle({ entity, modelName, hooks, db, write }) {
|
|
154
|
+
if (!(hooks?.has(modelName) ?? false)) return write(db);
|
|
155
|
+
return inTransactionIf(hooks?.has(modelName) ?? false, db, async (conn) => {
|
|
156
|
+
const ctx = hookContext(conn, "delete", { isNew: false, original: originalValues(entity), model: modelName });
|
|
157
|
+
if (hooks) await hooks.run(modelName, "beforeDelete", entity, ctx);
|
|
158
|
+
const affected = await write(conn);
|
|
159
|
+
await runAfterHooks(hooks, modelName, conn, "delete", entity, ctx);
|
|
160
|
+
return affected;
|
|
161
|
+
});
|
|
162
|
+
}
|