@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,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
+ }
@@ -1,11 +1,14 @@
1
1
  import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
2
2
  import { Repository } from "../crud/repository.js";
3
- import { createEntity, diffEntity, mergeRecordIntoEntity, ENTITY_META } from "./entity.js";
3
+ import { createEntity, diffEntity, mergeRecordIntoEntity, ENTITY_META, originalValue } from "./entity.js";
4
4
  import { HookRegistry } from "./hooks.js";
5
5
  import { createRecords } from "../crud/create-many.js";
6
+ import { upsertRecords } from "../crud/upsert.js";
6
7
  import { assertPrimaryKeyUntouched } from "../crud/prepare-write.js";
7
8
  import { withPrimaryKey } from "../crud/select.js";
8
9
  import { primaryKeyOf } from "../models/primary-key.js";
10
+ import { saveEntityLifecycle, deleteEntityLifecycle } from "./lifecycle.js";
11
+ import { resolveDb } from "../transaction/context.js";
9
12
 
10
13
  /**
11
14
  * Ties together identity-mapped loading, dirty-tracked saving, and
@@ -32,6 +35,8 @@ export class UnitOfWork {
32
35
  * @param {import('../fields/registry.js').FieldTypeRegistry} [options.fieldTypeRegistry]
33
36
  * @param {HookRegistry} [options.hooks]
34
37
  * @param {import('knex').Knex.Transaction} [options.trx]
38
+ * @param {boolean} [options.identityMap] - keep one object per row across reads (default true).
39
+ * False: every read returns fresh objects and nothing is retained - for a long-lived unit.
35
40
  */
36
41
  constructor(db, modelRegistry, options = {}) {
37
42
  this.db = db;
@@ -40,6 +45,7 @@ export class UnitOfWork {
40
45
  this.hooks = options.hooks ?? new HookRegistry();
41
46
  this.trx = options.trx;
42
47
  this.identityMap = new Map(); // `${modelName}:${pkValue}` -> entity
48
+ this.tracksIdentity = options.identityMap !== false;
43
49
  }
44
50
 
45
51
  #repositoryFor(modelName) {
@@ -68,7 +74,7 @@ export class UnitOfWork {
68
74
  // Same rule as the global API's withIdentityMap(): only a row with a primary key value has an
69
75
  // identity. Before 0.1.7 a model without a primary key keyed every row as "<model>:undefined",
70
76
  // so find() returned the first row's object once per row.
71
- if (pk === null || record[pk] === undefined || record[pk] === null) {
77
+ if (!this.tracksIdentity || pk === null || record[pk] === undefined || record[pk] === null) {
72
78
  return createEntity(record, model, modelName, hooks);
73
79
  }
74
80
  const key = this.#identityKey(modelName, record[pk]);
@@ -131,6 +137,16 @@ export class UnitOfWork {
131
137
  * @param {{ trx?: import('knex').Knex.Transaction }} [options]
132
138
  * @returns {Promise<Record<string, unknown>>}
133
139
  */
140
+ /** Insert or update by `conflict` key, as tracked entities (see crud/upsert.js). Since 0.2.0. */
141
+ async upsert(modelName, data, options = {}) {
142
+ const [entity] = await upsertRecords(this.#createRuntime(), this.modelRegistry.getModel(modelName), [data], { ...options, labels: [""] });
143
+ return entity;
144
+ }
145
+
146
+ async upsertMany(modelName, dataList, options = {}) {
147
+ return upsertRecords(this.#createRuntime(), this.modelRegistry.getModel(modelName), dataList, options);
148
+ }
149
+
134
150
  async create(modelName, data, options = {}) {
135
151
  const model = this.modelRegistry.getModel(modelName);
136
152
  const [entity] = await createRecords(this.#createRuntime(), model, [data], { ...options, labels: [""] });
@@ -194,70 +210,42 @@ export class UnitOfWork {
194
210
  * @param {{}} [options]
195
211
  */
196
212
  async saveEntity(entity, options = {}) {
197
- const { model, modelName, original } = entity[ENTITY_META];
198
- const dirty = diffEntity(entity, model);
199
-
200
- if (Object.keys(dirty).length === 0) {
201
- return entity;
202
- }
203
-
204
- const originalSnapshot = { ...original };
205
-
206
- try {
207
- assertPrimaryKeyUntouched(model, dirty); // before any hook sees an id change
208
- await this.hooks.run(modelName, "beforeUpdate", entity, dirty, originalSnapshot);
209
- await this.hooks.run(modelName, "beforeSave", entity, dirty, originalSnapshot);
210
-
211
- const { repo } = this.#repositoryFor(modelName);
212
- const pk = primaryKeyOf(model);
213
- await repo.update({ [pk]: original[pk] }, dirty, options);
214
- } catch (err) {
215
- // Nothing was persisted - revert entity's live values to match
216
- // what's actually in the database rather than leaving them at
217
- // whatever the caller had just (unsuccessfully) tried to save.
218
- for (const key of Object.keys(dirty)) {
219
- entity[key] = original[key];
220
- }
221
- throw err;
222
- }
223
-
224
- // Write dirty's final values onto both entity and original - not
225
- // entity's (possibly stale) value into original. A before* hook
226
- // may have added a field to `dirty` that the caller never touched
227
- // directly (e.g. auto-stamping `publishedAt`), and the entity
228
- // itself needs to reflect that too, not just the database.
229
- for (const [key, value] of Object.entries(dirty)) {
230
- entity[key] = value;
231
- original[key] = value;
232
- }
233
-
234
- await this.hooks.run(modelName, "afterUpdate", entity, dirty, originalSnapshot);
235
- await this.hooks.run(modelName, "afterSave", entity, dirty, originalSnapshot);
236
-
237
- return entity;
213
+ const { model, modelName } = entity[ENTITY_META];
214
+ const { repo } = this.#repositoryFor(modelName);
215
+ const pk = primaryKeyOf(model);
216
+ const id = originalValue(entity, pk);
217
+ // Shared with the global API (uow/lifecycle.js). Since 0.2.0 a save that matches no row throws
218
+ // SaveDeletedError here too (UnitOfWork used to report success).
219
+ return saveEntityLifecycle({
220
+ entity,
221
+ model,
222
+ modelName,
223
+ hooks: this.hooks,
224
+ db: resolveDb(this.db, options.trx ?? this.trx),
225
+ write: (conn, changes) => repo.update({ [pk]: id }, changes, { ...options, trx: conn.isTransaction ? conn : options.trx }),
226
+ });
238
227
  }
239
228
 
240
229
  /**
241
- * Called by a tracked entity's `.delete()`. Runs `beforeDelete`,
242
- * issues the DELETE, removes the entity from the identity map, then
243
- * runs `afterDelete`.
230
+ * Called by a tracked entity's `.delete()`: hooks and the DELETE as one unit, then the entity
231
+ * leaves the identity map.
244
232
  *
245
233
  * @param {Record<string, unknown>} entity
246
234
  * @param {{}} [options]
247
235
  */
248
236
  async deleteEntity(entity, options = {}) {
249
- const { model, modelName, original } = entity[ENTITY_META];
250
-
251
- await this.hooks.run(modelName, "beforeDelete", entity);
252
-
237
+ const { model, modelName } = entity[ENTITY_META];
253
238
  const { repo } = this.#repositoryFor(modelName);
254
239
  const pk = primaryKeyOf(model);
255
- await repo.delete({ [pk]: original[pk] }, options);
256
-
257
- this.identityMap.delete(this.#identityKey(modelName, original[pk]));
258
-
259
- await this.hooks.run(modelName, "afterDelete", entity);
260
-
240
+ const id = originalValue(entity, pk);
241
+ await deleteEntityLifecycle({
242
+ entity,
243
+ modelName,
244
+ hooks: this.hooks,
245
+ db: resolveDb(this.db, options.trx ?? this.trx),
246
+ write: (conn) => repo.delete({ [pk]: id }, { ...options, trx: conn.isTransaction ? conn : options.trx }),
247
+ });
248
+ this.identityMap.delete(this.#identityKey(modelName, id));
261
249
  return true;
262
250
  }
263
251
  }
@@ -1,4 +1,5 @@
1
1
  import { UnitOfWork } from "./unit-of-work.js";
2
+ import { resolveDb } from "../transaction/context.js";
2
3
 
3
4
  /**
4
5
  * Runs `fn` with a `UnitOfWork` bound to a fresh Knex transaction -
@@ -19,7 +20,7 @@ import { UnitOfWork } from "./unit-of-work.js";
19
20
  * @returns {Promise<T>}
20
21
  */
21
22
  export async function withUnitOfWork(db, modelRegistry, fn, options = {}) {
22
- return db.transaction(async (trx) => {
23
+ return resolveDb(db).transaction(async (trx) => {
23
24
  const uow = new UnitOfWork(db, modelRegistry, { ...options, trx });
24
25
  return fn(uow);
25
26
  });