@kiri-orm/core 0.1.7 → 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.
Files changed (99) hide show
  1. package/README.md +27 -15
  2. package/dist/types/client/model-handle.d.ts +4 -1
  3. package/dist/types/connection.d.ts +39 -0
  4. package/dist/types/crud/database-errors.d.ts +61 -0
  5. package/dist/types/crud/errors.d.ts +10 -0
  6. package/dist/types/crud/fast-path.d.ts +73 -0
  7. package/dist/types/crud/index.d.ts +4 -1
  8. package/dist/types/crud/insert-many.d.ts +1 -1
  9. package/dist/types/crud/order.d.ts +28 -0
  10. package/dist/types/crud/repository.d.ts +5 -3
  11. package/dist/types/crud/upsert.d.ts +39 -0
  12. package/dist/types/crud/value.d.ts +39 -0
  13. package/dist/types/dialect/index.d.ts +1 -1
  14. package/dist/types/dialect/transaction-guard.d.ts +19 -18
  15. package/dist/types/domain/compile.d.ts +17 -0
  16. package/dist/types/fields/filter-value.d.ts +21 -0
  17. package/dist/types/fields/registry.d.ts +1 -0
  18. package/dist/types/fields/storage.d.ts +28 -0
  19. package/dist/types/fields/types/date.d.ts +5 -0
  20. package/dist/types/fields/types/decimal.d.ts +40 -0
  21. package/dist/types/global/index.d.ts +1 -0
  22. package/dist/types/global/transaction.d.ts +10 -13
  23. package/dist/types/index.d.ts +2 -0
  24. package/dist/types/meta/snapshot.d.ts +10 -0
  25. package/dist/types/meta/upsert.d.ts +16 -0
  26. package/dist/types/migrations/diff.d.ts +25 -2
  27. package/dist/types/models/constraints.d.ts +27 -0
  28. package/dist/types/schema/alter-column.d.ts +46 -0
  29. package/dist/types/schema/build-column.d.ts +11 -0
  30. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  31. package/dist/types/transaction/after-commit.d.ts +42 -0
  32. package/dist/types/transaction/context.d.ts +39 -0
  33. package/dist/types/uow/entity.d.ts +39 -29
  34. package/dist/types/uow/hooks.d.ts +6 -1
  35. package/dist/types/uow/lifecycle.d.ts +82 -0
  36. package/dist/types/uow/unit-of-work.d.ts +11 -7
  37. package/package.json +5 -4
  38. package/src/client/model-handle.js +14 -4
  39. package/src/client/orm-client.js +10 -5
  40. package/src/connection.js +34 -4
  41. package/src/crud/aggregate-filter.js +8 -2
  42. package/src/crud/aggregate-spec.js +2 -2
  43. package/src/crud/aggregate.js +16 -5
  44. package/src/crud/create-many.js +52 -29
  45. package/src/crud/database-errors.js +107 -0
  46. package/src/crud/errors.js +14 -0
  47. package/src/crud/fast-path.js +449 -0
  48. package/src/crud/index.js +4 -1
  49. package/src/crud/insert-many.js +25 -7
  50. package/src/crud/map-filter.js +2 -1
  51. package/src/crud/order.js +59 -9
  52. package/src/crud/repository.js +106 -38
  53. package/src/crud/row-mapping.js +32 -7
  54. package/src/crud/upsert.js +203 -0
  55. package/src/crud/value.js +71 -0
  56. package/src/dialect/index.js +1 -1
  57. package/src/dialect/transaction-guard.js +216 -45
  58. package/src/domain/compile.js +85 -12
  59. package/src/dto/field-schema.js +5 -0
  60. package/src/fields/default-registry.js +3 -1
  61. package/src/fields/filter-value.js +87 -0
  62. package/src/fields/registry.js +1 -0
  63. package/src/fields/storage.js +50 -0
  64. package/src/fields/types/date.js +16 -3
  65. package/src/fields/types/decimal.js +147 -0
  66. package/src/fields/types/integer.js +7 -0
  67. package/src/global/connect.js +2 -2
  68. package/src/global/create-model.js +59 -57
  69. package/src/global/errors.js +1 -1
  70. package/src/global/index.js +1 -0
  71. package/src/global/transaction.js +12 -14
  72. package/src/index.js +2 -0
  73. package/src/meta/schema.js +10 -0
  74. package/src/meta/snapshot.js +5 -0
  75. package/src/meta/upsert.js +28 -0
  76. package/src/migrations/describe.js +49 -0
  77. package/src/migrations/diff.js +50 -7
  78. package/src/migrations/generate.js +38 -2
  79. package/src/migrations/render.js +30 -12
  80. package/src/migrations/runner.js +2 -1
  81. package/src/models/constraints.js +96 -0
  82. package/src/models/define-model.js +4 -0
  83. package/src/models/inheritance.js +4 -1
  84. package/src/models/registry.js +2 -1
  85. package/src/relations/cascade-delete.js +2 -1
  86. package/src/relations/eager-load.js +45 -40
  87. package/src/reports/report-handle.js +2 -1
  88. package/src/schema/alter-column.js +219 -0
  89. package/src/schema/build-column.js +28 -2
  90. package/src/schema/default-column-builders.js +16 -2
  91. package/src/schema/introspect-indexes.js +22 -0
  92. package/src/schema/sync.js +15 -1
  93. package/src/transaction/after-commit.js +142 -0
  94. package/src/transaction/context.js +84 -0
  95. package/src/uow/entity.js +133 -133
  96. package/src/uow/hooks.js +9 -0
  97. package/src/uow/lifecycle.js +162 -0
  98. package/src/uow/unit-of-work.js +44 -56
  99. package/src/uow/with-unit-of-work.js +2 -1
@@ -0,0 +1,142 @@
1
+ import { currentTransaction } from "./context.js";
2
+
3
+ /**
4
+ * Work deferred until a transaction commits (since 0.2.0): the `afterCommit` hook, and anything
5
+ * else registered with afterCommit(fn). And, since 0.2.0, work that undoes in-memory state when a
6
+ * transaction rolls back (onRollback()).
7
+ *
8
+ * Callbacks are queued on the OUTERMOST transaction - a savepoint's release isn't a commit - and run
9
+ * in order once it commits. A rollback drops them: the outermost transaction's rollback drops all of
10
+ * them; a savepoint's rollback (inside a transaction that still commits) drops only those queued
11
+ * inside that savepoint. Outside any transaction there is nothing to wait for and the callback runs
12
+ * at once.
13
+ *
14
+ * instrumentConnection() calls flushAfterCommit() when a transaction it started commits, before the
15
+ * caller's `await db.transaction(...)` resumes; so an error thrown there reaches that caller (the
16
+ * data is already committed - it is the side effect that failed).
17
+ */
18
+ const queues = new WeakMap(); // outermost transactor -> [{ owner, fn }]
19
+ const rollbackQueues = new WeakMap(); // outermost transactor -> [{ owner, fn }]
20
+
21
+ export function outermostTransaction(trx) {
22
+ let current = trx;
23
+ while (current.parentTransaction) current = current.parentTransaction;
24
+ return current;
25
+ }
26
+
27
+ /**
28
+ * Runs `fn` after `db` commits, or now when `db` isn't a transaction. The ORM's own entry point
29
+ * (the `afterCommit` hook), with the connection it resolved.
30
+ *
31
+ * @param {import('knex').Knex} db
32
+ * @param {() => unknown} fn
33
+ */
34
+ export async function queueAfterCommit(db, fn) {
35
+ if (!db?.isTransaction) {
36
+ await fn();
37
+ return;
38
+ }
39
+ const root = outermostTransaction(db);
40
+ if (!queues.has(root)) queues.set(root, []);
41
+ queues.get(root).push({ owner: db, fn });
42
+ }
43
+
44
+ /**
45
+ * Runs `fn` once the transaction open in this async flow commits - the outermost one, so a
46
+ * savepoint's release doesn't count - or right away outside a transaction:
47
+ *
48
+ * await transaction(async () => {
49
+ * const order = await Order.create(data);
50
+ * afterCommit(() => queue.publish("order.created", { id: order.id }));
51
+ * });
52
+ *
53
+ * A rollback (of the transaction, or of the savepoint the call was made in) drops `fn`. An error it
54
+ * throws reaches whoever awaited the outermost `transaction()`. Outside a transaction it returns a
55
+ * promise of `fn`'s result. `afterCommit(trx, fn)` (0.2.0's form) queues on `trx`.
56
+ *
57
+ * @param {(() => unknown) | import('knex').Knex} fnOrTrx
58
+ * @param {() => unknown} [fn]
59
+ * @returns {Promise<unknown>}
60
+ */
61
+ export function afterCommit(fnOrTrx, fn) {
62
+ if (typeof fnOrTrx !== "function" || fn !== undefined) {
63
+ if (typeof fn !== "function") return Promise.reject(new TypeError("afterCommit(fn) expects a function"));
64
+ return queueAfterCommit(fnOrTrx, fn);
65
+ }
66
+ const trx = currentTransaction();
67
+ if (trx) return queueAfterCommit(trx, fnOrTrx);
68
+ try {
69
+ return Promise.resolve(fnOrTrx());
70
+ } catch (error) {
71
+ return Promise.reject(error);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Registers `fn` to run if `db` - or the transaction it is part of - rolls back (since 0.2.0). The
77
+ * ORM uses it to put tracked documents back to what the database holds after a rollback undid
78
+ * their save(). Callbacks are synchronous and run in reverse order of registration, so several
79
+ * saves of one document unwind to its value before the first. Nothing is registered outside a
80
+ * transaction (an autocommitted write can't roll back).
81
+ *
82
+ * @param {import('knex').Knex} db
83
+ * @param {() => void} fn
84
+ */
85
+ export function onRollback(db, fn) {
86
+ if (!db?.isTransaction) return;
87
+ const root = outermostTransaction(db);
88
+ if (!rollbackQueues.has(root)) rollbackQueues.set(root, []);
89
+ rollbackQueues.get(root).push({ owner: db, fn });
90
+ }
91
+
92
+ /** Runs everything queued on a committed outermost transaction, in order. */
93
+ export async function flushAfterCommit(root) {
94
+ rollbackQueues.delete(root); // committed: nothing left to undo
95
+ const queue = queues.get(root);
96
+ if (!queue) return;
97
+ queues.delete(root);
98
+ const errors = [];
99
+ for (const { fn } of queue) {
100
+ try {
101
+ await fn();
102
+ } catch (error) {
103
+ errors.push(error);
104
+ }
105
+ }
106
+ if (errors.length === 1) throw errors[0];
107
+ if (errors.length > 1) throw new AggregateError(errors, `${errors.length} afterCommit callbacks failed (the transaction had committed)`);
108
+ }
109
+
110
+ /** Drops what was queued inside `trx` (and the savepoints inside it), because it rolled back. */
111
+ export function discardAfterCommit(trx) {
112
+ const root = outermostTransaction(trx);
113
+ const inside = (owner) => {
114
+ for (let t = owner; t; t = t.parentTransaction) if (t === trx) return true;
115
+ return false;
116
+ };
117
+ runRollbackCallbacks(root, trx === root ? () => true : inside);
118
+ if (root === trx) {
119
+ queues.delete(root);
120
+ return;
121
+ }
122
+ const queue = queues.get(root);
123
+ if (!queue) return;
124
+ queues.set(root, queue.filter((entry) => !inside(entry.owner)));
125
+ }
126
+
127
+ /** Runs (newest first) and removes the rollback callbacks registered inside the rolled-back part. */
128
+ function runRollbackCallbacks(root, isInside) {
129
+ const queue = rollbackQueues.get(root);
130
+ if (!queue) return;
131
+ const undone = queue.filter((entry) => isInside(entry.owner));
132
+ const kept = queue.filter((entry) => !isInside(entry.owner));
133
+ if (kept.length) rollbackQueues.set(root, kept);
134
+ else rollbackQueues.delete(root);
135
+ for (let i = undone.length - 1; i >= 0; i--) {
136
+ try {
137
+ undone[i].fn();
138
+ } catch {
139
+ // Restoring in-memory state must never hide the rollback's own error.
140
+ }
141
+ }
142
+ }
@@ -0,0 +1,84 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ /**
4
+ * The transactions open in the current async flow (since 0.2.0).
5
+ *
6
+ * Every transaction started with a container - `db.transaction(async (trx) => ...)`, the global
7
+ * `transaction()`, `client.transaction()`, savepoints inside them, and the ORM's own internal
8
+ * transactions - runs its callback inside a scope recorded here (see instrumentConnection()).
9
+ * Any model call made in that callback, however deep (a hook, a helper in another file), finds
10
+ * the transaction through resolveDb() and joins it, without `{ trx }` being passed along.
11
+ *
12
+ * A scope: { baseClient, trx, parent } - `baseClient` is the Knex client of the connection the
13
+ * transaction belongs to, so a transaction on one connection is never joined by queries meant for
14
+ * another; `parent` is the enclosing scope (nested transactions and savepoints).
15
+ */
16
+ const scopes = new AsyncLocalStorage();
17
+
18
+ /** Runs `fn` inside a scope where `trx` is the open transaction for `baseClient`. */
19
+ export function runInTransactionScope(baseClient, trx, fn) {
20
+ return scopes.run({ baseClient, trx, parent: scopes.getStore() }, fn);
21
+ }
22
+
23
+ /**
24
+ * The transaction open in this async flow for `db`'s connection, or null. A `db` that is already a
25
+ * transaction is used as given (null here). A finished transaction is never returned: code still
26
+ * running after its commit (a timer started inside it, say) goes back to the connection itself.
27
+ *
28
+ * @param {import('knex').Knex} db
29
+ * @returns {import('knex').Knex.Transaction | null}
30
+ */
31
+ export function ambientTransaction(db) {
32
+ if (!db || db.isTransaction || !db.client) return null;
33
+ for (let scope = scopes.getStore(); scope; scope = scope.parent) {
34
+ if (scope.baseClient === db.client) return scope.trx.isCompleted() ? null : scope.trx;
35
+ }
36
+ return null;
37
+ }
38
+
39
+ /**
40
+ * Which connection an operation runs on: an explicit `{ trx }` first, then the transaction open in
41
+ * this async flow, then `db` itself. Every ORM entry point resolves its connection through this.
42
+ *
43
+ * @param {import('knex').Knex} db
44
+ * @param {import('knex').Knex.Transaction} [trx]
45
+ */
46
+ export function resolveDb(db, trx) {
47
+ return trx ?? ambientTransaction(db) ?? db;
48
+ }
49
+
50
+ /**
51
+ * The innermost unfinished transaction open in this async flow, on any connection, or null. For
52
+ * APIs that take no connection at all, like the public `afterCommit(fn)`.
53
+ *
54
+ * @returns {import('knex').Knex.Transaction | null}
55
+ */
56
+ export function currentTransaction() {
57
+ for (let scope = scopes.getStore(); scope; scope = scope.parent) {
58
+ if (!scope.trx.isCompleted()) return scope.trx;
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /** Whether a transaction for `client` is open (and unfinished) in this async flow. */
64
+ export function holdsTransactionFor(client) {
65
+ for (let scope = scopes.getStore(); scope; scope = scope.parent) {
66
+ if (scope.baseClient === client && !scope.trx.isCompleted()) return true;
67
+ }
68
+ return false;
69
+ }
70
+
71
+ /**
72
+ * Runs `fn(db)` in a transaction when `needed` and `db` isn't one already; otherwise on `db` as is.
73
+ * Used to make a write and its hooks one atomic unit only when there are hooks to protect.
74
+ *
75
+ * @template T
76
+ * @param {boolean} needed
77
+ * @param {import('knex').Knex} db
78
+ * @param {(db: import('knex').Knex) => Promise<T>} fn
79
+ * @returns {Promise<T>}
80
+ */
81
+ export function inTransactionIf(needed, db, fn) {
82
+ if (!needed || db.isTransaction) return fn(db);
83
+ return db.transaction((trx) => fn(trx));
84
+ }
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
- * Deep-clones a field's value where "deep" actually matters for
16
- * dirty-tracking correctness: Date objects and JSON values are
17
- * mutable, so entity's live value and its original snapshot need to
18
- * be genuinely independent objects from the moment the entity is
19
- * created - not two references to the same object, which a shallow
20
- * `{...record}` would produce. Every other field type is a JS
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
- function cloneFieldValue(value, field) {
28
- if (value === null || value === undefined) return value;
29
- if ((field.type === "date" || field.type === "datetime") && value instanceof Date) {
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.parse(JSON.stringify(value));
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
- * Wraps a plain record (as returned by Repository) into a tracked
44
- * entity: same enumerable field properties, plus a hidden snapshot of
45
- * the values as-loaded and non-enumerable save()/delete() methods
46
- * that call whatever `handlers.save`/`handlers.delete` functions the
47
- * caller supplies.
48
- *
49
- * Deliberately decoupled from any particular coordinator object
50
- * (originally this took a `UnitOfWork` instance directly and called
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
- for (const [fieldName, field] of Object.entries(model.fields)) {
80
- if (!(fieldName in record)) continue;
81
- entity[fieldName] = cloneFieldValue(record[fieldName], field);
82
- original[fieldName] = cloneFieldValue(record[fieldName], field);
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
- // Eager-loaded relation values (attached by Repository's `with`
86
- // option) aren't persisted columns and are never part of dirty
87
- // tracking, but still need to be visible on the entity - copied
88
- // as-is (no cloning needed since diffEntity() never inspects them,
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
- // Computed fields read the ENTITY (not the record it was built from), so
102
- // `entity.firstName = "x"` is reflected by `entity.fullName` immediately.
103
- // Not part of `original`, so they never appear in dirty tracking.
104
- // A record read with `select` only carries the computed fields that were asked for (and
105
- // could be computed from what was loaded) - define just those; see PARTIAL in row-mapping.js.
106
- defineComputedGetters(entity, model, record[PARTIAL]?.computed);
107
-
108
- Object.defineProperty(entity, ENTITY_META, {
109
- value: { original, model, modelName },
110
- enumerable: false,
111
- writable: true,
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
- Object.defineProperty(entity, "save", {
116
- value: function save(options) {
117
- return handlers.save(entity, options);
118
- },
119
- enumerable: false,
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
- Object.defineProperty(entity, "delete", {
123
- value: function del(options) {
124
- return handlers.delete(entity, options);
125
- },
126
- enumerable: false,
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
- return entity;
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
- * True if two field values should be considered equal for dirty-
134
- * tracking purposes.
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
- * Primitive field types (char, text, integer, float, boolean, enum)
137
- * use `===`, which already *is* value equality for them.
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
- * `date`/`datetime` and `json` are handled differently, and
140
- * deliberately do NOT take a `===` reference-equality shortcut first:
141
- * doing so would defeat the entire point of comparing by value, since
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 {unknown} b
151
- * @param {import('../fields/define-field.js').FieldDescriptor} field
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 valuesEqual(a, b, field) {
154
- if (field.type === "date" || field.type === "datetime") {
155
- const aTime = a instanceof Date ? a.getTime() : a;
156
- const bTime = b instanceof Date ? b.getTime() : b;
157
- return aTime === bTime;
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
- return a === b;
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 { original } = entity[ENTITY_META];
179
+ const { snapshot } = entity[ENTITY_META];
181
180
  const dirty = {};
182
- for (const [fieldName, field] of Object.entries(model.fields)) {
183
- if (!valuesEqual(entity[fieldName], original[fieldName], field)) {
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 { original } = entity[ENTITY_META];
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 original)) {
215
- entity[fieldName] = cloneFieldValue(record[fieldName], field);
216
- original[fieldName] = cloneFieldValue(record[fieldName], field);
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) {