@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.
Files changed (117) 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 +66 -0
  4. package/dist/types/crud/chunk.d.ts +10 -0
  5. package/dist/types/crud/database-errors.d.ts +61 -0
  6. package/dist/types/crud/errors.d.ts +10 -0
  7. package/dist/types/crud/fast-path.d.ts +73 -0
  8. package/dist/types/crud/index.d.ts +4 -1
  9. package/dist/types/crud/insert-many.d.ts +12 -13
  10. package/dist/types/crud/order.d.ts +28 -0
  11. package/dist/types/crud/repository.d.ts +5 -3
  12. package/dist/types/crud/row-mapping.d.ts +9 -1
  13. package/dist/types/crud/upsert.d.ts +39 -0
  14. package/dist/types/crud/value.d.ts +39 -0
  15. package/dist/types/dialect/date-bucket.d.ts +2 -2
  16. package/dist/types/dialect/index.d.ts +1 -0
  17. package/dist/types/dialect/transaction-guard.d.ts +31 -0
  18. package/dist/types/domain/compile.d.ts +17 -0
  19. package/dist/types/fields/filter-value.d.ts +21 -0
  20. package/dist/types/fields/registry.d.ts +1 -0
  21. package/dist/types/fields/storage.d.ts +28 -0
  22. package/dist/types/fields/types/date.d.ts +6 -6
  23. package/dist/types/fields/types/decimal.d.ts +40 -0
  24. package/dist/types/global/errors.d.ts +3 -0
  25. package/dist/types/global/index.d.ts +2 -0
  26. package/dist/types/global/normalize-dates.d.ts +11 -0
  27. package/dist/types/global/state.d.ts +2 -0
  28. package/dist/types/global/transaction.d.ts +10 -13
  29. package/dist/types/index.d.ts +2 -0
  30. package/dist/types/meta/create-table-once.d.ts +15 -0
  31. package/dist/types/meta/snapshot.d.ts +10 -0
  32. package/dist/types/meta/upsert.d.ts +16 -0
  33. package/dist/types/migrations/diff.d.ts +25 -2
  34. package/dist/types/models/constraints.d.ts +27 -0
  35. package/dist/types/relations/pivot-schema.d.ts +1 -1
  36. package/dist/types/schema/alter-column.d.ts +46 -0
  37. package/dist/types/schema/build-column.d.ts +11 -0
  38. package/dist/types/schema/index.d.ts +1 -0
  39. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  40. package/dist/types/schema/normalize-dates.d.ts +41 -0
  41. package/dist/types/transaction/after-commit.d.ts +42 -0
  42. package/dist/types/transaction/context.d.ts +39 -0
  43. package/dist/types/uow/entity.d.ts +39 -29
  44. package/dist/types/uow/hooks.d.ts +6 -1
  45. package/dist/types/uow/lifecycle.d.ts +82 -0
  46. package/dist/types/uow/unit-of-work.d.ts +11 -7
  47. package/package.json +8 -5
  48. package/src/client/model-handle.js +14 -4
  49. package/src/client/orm-client.js +10 -5
  50. package/src/connection.js +53 -7
  51. package/src/crud/aggregate-filter.js +8 -2
  52. package/src/crud/aggregate-spec.js +2 -2
  53. package/src/crud/aggregate.js +16 -5
  54. package/src/crud/chunk.js +10 -0
  55. package/src/crud/create-many.js +52 -29
  56. package/src/crud/database-errors.js +107 -0
  57. package/src/crud/errors.js +14 -0
  58. package/src/crud/fast-path.js +449 -0
  59. package/src/crud/index.js +4 -1
  60. package/src/crud/insert-many.js +42 -7
  61. package/src/crud/map-filter.js +2 -1
  62. package/src/crud/order.js +59 -9
  63. package/src/crud/repository.js +106 -38
  64. package/src/crud/row-mapping.js +32 -7
  65. package/src/crud/upsert.js +203 -0
  66. package/src/crud/value.js +71 -0
  67. package/src/dialect/index.js +1 -0
  68. package/src/dialect/transaction-guard.js +254 -0
  69. package/src/domain/compile.js +85 -12
  70. package/src/dto/field-schema.js +5 -0
  71. package/src/fields/default-registry.js +3 -1
  72. package/src/fields/filter-value.js +87 -0
  73. package/src/fields/registry.js +1 -0
  74. package/src/fields/storage.js +50 -0
  75. package/src/fields/types/date.js +16 -3
  76. package/src/fields/types/decimal.js +147 -0
  77. package/src/fields/types/integer.js +7 -0
  78. package/src/global/connect.js +25 -1
  79. package/src/global/create-model.js +59 -57
  80. package/src/global/errors.js +1 -1
  81. package/src/global/index.js +2 -0
  82. package/src/global/normalize-dates.js +15 -0
  83. package/src/global/state.js +3 -0
  84. package/src/global/transaction.js +12 -14
  85. package/src/index.js +2 -0
  86. package/src/meta/create-table-once.js +23 -0
  87. package/src/meta/schema.js +15 -6
  88. package/src/meta/snapshot.js +5 -0
  89. package/src/meta/upsert.js +28 -0
  90. package/src/migrations/describe.js +49 -0
  91. package/src/migrations/diff.js +50 -7
  92. package/src/migrations/generate.js +38 -2
  93. package/src/migrations/render.js +30 -12
  94. package/src/migrations/runner.js +40 -6
  95. package/src/models/constraints.js +96 -0
  96. package/src/models/define-model.js +4 -0
  97. package/src/models/inheritance.js +4 -1
  98. package/src/models/registry.js +2 -1
  99. package/src/relations/attach-detach.js +49 -18
  100. package/src/relations/cascade-delete.js +32 -7
  101. package/src/relations/eager-load.js +75 -51
  102. package/src/relations/pivot-schema.js +24 -3
  103. package/src/reports/report-handle.js +2 -1
  104. package/src/schema/alter-column.js +219 -0
  105. package/src/schema/build-column.js +28 -2
  106. package/src/schema/default-column-builders.js +16 -2
  107. package/src/schema/index.js +1 -0
  108. package/src/schema/introspect-indexes.js +22 -0
  109. package/src/schema/normalize-dates.js +58 -0
  110. package/src/schema/sync.js +16 -2
  111. package/src/transaction/after-commit.js +142 -0
  112. package/src/transaction/context.js +84 -0
  113. package/src/uow/entity.js +133 -133
  114. package/src/uow/hooks.js +9 -0
  115. package/src/uow/lifecycle.js +162 -0
  116. package/src/uow/unit-of-work.js +55 -60
  117. package/src/uow/with-unit-of-work.js +2 -1
@@ -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) {
@@ -61,16 +67,23 @@ export class UnitOfWork {
61
67
  */
62
68
  #trackOrReuse(modelName, model, record) {
63
69
  const pk = primaryKeyOf(model);
64
- const key = this.#identityKey(modelName, pk === null ? undefined : record[pk]);
70
+ const hooks = {
71
+ save: (e, options) => this.saveEntity(e, options),
72
+ delete: (e, options) => this.deleteEntity(e, options),
73
+ };
74
+ // Same rule as the global API's withIdentityMap(): only a row with a primary key value has an
75
+ // identity. Before 0.1.7 a model without a primary key keyed every row as "<model>:undefined",
76
+ // so find() returned the first row's object once per row.
77
+ if (!this.tracksIdentity || pk === null || record[pk] === undefined || record[pk] === null) {
78
+ return createEntity(record, model, modelName, hooks);
79
+ }
80
+ const key = this.#identityKey(modelName, record[pk]);
65
81
  if (this.identityMap.has(key)) {
66
82
  // Field values already on the cached instance win (it may hold unsaved edits); fields it
67
83
  // doesn't have yet are filled in, and relations are refreshed. See mergeRecordIntoEntity().
68
84
  return mergeRecordIntoEntity(this.identityMap.get(key), record, model);
69
85
  }
70
- const entity = createEntity(record, model, modelName, {
71
- save: (e, options) => this.saveEntity(e, options),
72
- delete: (e, options) => this.deleteEntity(e, options),
73
- });
86
+ const entity = createEntity(record, model, modelName, hooks);
74
87
  this.identityMap.set(key, entity);
75
88
  return entity;
76
89
  }
@@ -124,6 +137,16 @@ export class UnitOfWork {
124
137
  * @param {{ trx?: import('knex').Knex.Transaction }} [options]
125
138
  * @returns {Promise<Record<string, unknown>>}
126
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
+
127
150
  async create(modelName, data, options = {}) {
128
151
  const model = this.modelRegistry.getModel(modelName);
129
152
  const [entity] = await createRecords(this.#createRuntime(), model, [data], { ...options, labels: [""] });
@@ -187,70 +210,42 @@ export class UnitOfWork {
187
210
  * @param {{}} [options]
188
211
  */
189
212
  async saveEntity(entity, options = {}) {
190
- const { model, modelName, original } = entity[ENTITY_META];
191
- const dirty = diffEntity(entity, model);
192
-
193
- if (Object.keys(dirty).length === 0) {
194
- return entity;
195
- }
196
-
197
- const originalSnapshot = { ...original };
198
-
199
- try {
200
- assertPrimaryKeyUntouched(model, dirty); // before any hook sees an id change
201
- await this.hooks.run(modelName, "beforeUpdate", entity, dirty, originalSnapshot);
202
- await this.hooks.run(modelName, "beforeSave", entity, dirty, originalSnapshot);
203
-
204
- const { repo } = this.#repositoryFor(modelName);
205
- const pk = primaryKeyOf(model);
206
- await repo.update({ [pk]: original[pk] }, dirty, options);
207
- } catch (err) {
208
- // Nothing was persisted - revert entity's live values to match
209
- // what's actually in the database rather than leaving them at
210
- // whatever the caller had just (unsuccessfully) tried to save.
211
- for (const key of Object.keys(dirty)) {
212
- entity[key] = original[key];
213
- }
214
- throw err;
215
- }
216
-
217
- // Write dirty's final values onto both entity and original - not
218
- // entity's (possibly stale) value into original. A before* hook
219
- // may have added a field to `dirty` that the caller never touched
220
- // directly (e.g. auto-stamping `publishedAt`), and the entity
221
- // itself needs to reflect that too, not just the database.
222
- for (const [key, value] of Object.entries(dirty)) {
223
- entity[key] = value;
224
- original[key] = value;
225
- }
226
-
227
- await this.hooks.run(modelName, "afterUpdate", entity, dirty, originalSnapshot);
228
- await this.hooks.run(modelName, "afterSave", entity, dirty, originalSnapshot);
229
-
230
- 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
+ });
231
227
  }
232
228
 
233
229
  /**
234
- * Called by a tracked entity's `.delete()`. Runs `beforeDelete`,
235
- * issues the DELETE, removes the entity from the identity map, then
236
- * 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.
237
232
  *
238
233
  * @param {Record<string, unknown>} entity
239
234
  * @param {{}} [options]
240
235
  */
241
236
  async deleteEntity(entity, options = {}) {
242
- const { model, modelName, original } = entity[ENTITY_META];
243
-
244
- await this.hooks.run(modelName, "beforeDelete", entity);
245
-
237
+ const { model, modelName } = entity[ENTITY_META];
246
238
  const { repo } = this.#repositoryFor(modelName);
247
239
  const pk = primaryKeyOf(model);
248
- await repo.delete({ [pk]: original[pk] }, options);
249
-
250
- this.identityMap.delete(this.#identityKey(modelName, original[pk]));
251
-
252
- await this.hooks.run(modelName, "afterDelete", entity);
253
-
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));
254
249
  return true;
255
250
  }
256
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
  });