@mikro-orm/core 6.4.17-dev.10 → 6.4.17-dev.100

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 (62) hide show
  1. package/EntityManager.d.ts +11 -2
  2. package/EntityManager.js +39 -53
  3. package/README.md +1 -2
  4. package/connections/Connection.d.ts +4 -2
  5. package/connections/Connection.js +2 -2
  6. package/decorators/Entity.d.ts +14 -0
  7. package/decorators/Indexed.d.ts +2 -2
  8. package/decorators/Transactional.d.ts +1 -0
  9. package/decorators/Transactional.js +3 -3
  10. package/drivers/IDatabaseDriver.d.ts +4 -0
  11. package/entity/ArrayCollection.d.ts +3 -1
  12. package/entity/ArrayCollection.js +7 -2
  13. package/entity/EntityFactory.d.ts +6 -0
  14. package/entity/EntityFactory.js +17 -6
  15. package/entity/EntityHelper.js +4 -1
  16. package/entity/EntityLoader.js +26 -18
  17. package/entity/Reference.d.ts +5 -0
  18. package/entity/Reference.js +16 -0
  19. package/entity/WrappedEntity.js +1 -1
  20. package/entity/defineEntity.d.ts +537 -0
  21. package/entity/defineEntity.js +703 -0
  22. package/entity/index.d.ts +2 -0
  23. package/entity/index.js +2 -0
  24. package/entity/utils.d.ts +7 -0
  25. package/entity/utils.js +16 -3
  26. package/enums.d.ts +13 -1
  27. package/enums.js +13 -1
  28. package/errors.d.ts +5 -0
  29. package/errors.js +13 -1
  30. package/hydration/ObjectHydrator.js +1 -1
  31. package/index.d.ts +1 -1
  32. package/index.mjs +16 -0
  33. package/metadata/MetadataDiscovery.d.ts +0 -1
  34. package/metadata/MetadataDiscovery.js +16 -13
  35. package/package.json +4 -4
  36. package/platforms/Platform.d.ts +3 -1
  37. package/types/BooleanType.d.ts +1 -1
  38. package/types/DecimalType.js +1 -1
  39. package/types/DoubleType.js +1 -1
  40. package/typings.d.ts +31 -11
  41. package/typings.js +21 -4
  42. package/unit-of-work/ChangeSetPersister.d.ts +4 -2
  43. package/unit-of-work/ChangeSetPersister.js +14 -10
  44. package/unit-of-work/UnitOfWork.d.ts +1 -1
  45. package/unit-of-work/UnitOfWork.js +22 -6
  46. package/utils/Configuration.d.ts +7 -1
  47. package/utils/Configuration.js +1 -0
  48. package/utils/ConfigurationLoader.js +2 -2
  49. package/utils/Cursor.js +3 -0
  50. package/utils/EntityComparator.d.ts +6 -2
  51. package/utils/EntityComparator.js +29 -8
  52. package/utils/QueryHelper.d.ts +6 -0
  53. package/utils/QueryHelper.js +47 -4
  54. package/utils/RawQueryFragment.d.ts +34 -0
  55. package/utils/RawQueryFragment.js +35 -0
  56. package/utils/TransactionManager.d.ts +65 -0
  57. package/utils/TransactionManager.js +203 -0
  58. package/utils/Utils.d.ts +2 -2
  59. package/utils/Utils.js +32 -8
  60. package/utils/index.d.ts +1 -0
  61. package/utils/index.js +1 -0
  62. package/utils/upsert-utils.js +9 -1
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TransactionManager = void 0;
4
+ const enums_1 = require("../enums");
5
+ const events_1 = require("../events");
6
+ const TransactionContext_1 = require("../utils/TransactionContext");
7
+ const unit_of_work_1 = require("../unit-of-work");
8
+ const errors_1 = require("../errors");
9
+ /**
10
+ * Manages transaction lifecycle and propagation for EntityManager.
11
+ */
12
+ class TransactionManager {
13
+ em;
14
+ constructor(em) {
15
+ this.em = em;
16
+ }
17
+ /**
18
+ * Main entry point for handling transactional operations with propagation support.
19
+ */
20
+ async handle(cb, options = {}) {
21
+ const em = this.em.getContext(false);
22
+ // Set NESTED as the default propagation type
23
+ options.propagation ??= enums_1.TransactionPropagation.NESTED;
24
+ // Set the context to the current transaction context if not already set
25
+ options.ctx ??= em.getTransactionContext();
26
+ const hasExistingTransaction = !!em.getTransactionContext();
27
+ return this.executeWithPropagation(options.propagation, em, cb, options, hasExistingTransaction);
28
+ }
29
+ /**
30
+ * Executes the callback with the specified propagation type.
31
+ */
32
+ async executeWithPropagation(propagation, em, cb, options, hasExistingTransaction) {
33
+ switch (propagation) {
34
+ case enums_1.TransactionPropagation.NOT_SUPPORTED:
35
+ return this.executeWithoutTransaction(em, cb, options);
36
+ case enums_1.TransactionPropagation.REQUIRES_NEW:
37
+ return this.executeWithNewTransaction(em, cb, options, hasExistingTransaction);
38
+ case enums_1.TransactionPropagation.REQUIRED:
39
+ if (hasExistingTransaction) {
40
+ return cb(em);
41
+ }
42
+ return this.createNewTransaction(em, cb, options);
43
+ case enums_1.TransactionPropagation.NESTED:
44
+ if (hasExistingTransaction) {
45
+ return this.executeNestedTransaction(em, cb, options);
46
+ }
47
+ return this.createNewTransaction(em, cb, options);
48
+ case enums_1.TransactionPropagation.SUPPORTS:
49
+ if (hasExistingTransaction) {
50
+ return cb(em);
51
+ }
52
+ return this.executeWithoutTransaction(em, cb, options);
53
+ case enums_1.TransactionPropagation.MANDATORY:
54
+ if (!hasExistingTransaction) {
55
+ throw errors_1.TransactionStateError.requiredTransactionNotFound(propagation);
56
+ }
57
+ return cb(em);
58
+ case enums_1.TransactionPropagation.NEVER:
59
+ if (hasExistingTransaction) {
60
+ throw errors_1.TransactionStateError.transactionNotAllowed(propagation);
61
+ }
62
+ return this.executeWithoutTransaction(em, cb, options);
63
+ default:
64
+ throw errors_1.TransactionStateError.invalidPropagation(propagation);
65
+ }
66
+ }
67
+ /**
68
+ * Suspends the current transaction and returns the suspended resources.
69
+ */
70
+ suspendTransaction(em) {
71
+ const suspended = em.getTransactionContext();
72
+ em.resetTransactionContext();
73
+ return suspended;
74
+ }
75
+ /**
76
+ * Resumes a previously suspended transaction.
77
+ */
78
+ resumeTransaction(em, suspended) {
79
+ if (suspended != null) {
80
+ em.setTransactionContext(suspended);
81
+ }
82
+ }
83
+ /**
84
+ * Executes operation without transaction context.
85
+ */
86
+ async executeWithoutTransaction(em, cb, options) {
87
+ const suspended = this.suspendTransaction(em);
88
+ const fork = this.createFork(em, { ...options, disableTransactions: true });
89
+ const propagateToUpperContext = this.shouldPropagateToUpperContext(em);
90
+ try {
91
+ return await this.executeTransactionFlow(fork, cb, propagateToUpperContext, em);
92
+ }
93
+ finally {
94
+ this.resumeTransaction(em, suspended);
95
+ }
96
+ }
97
+ /**
98
+ * Creates new independent transaction, suspending any existing one.
99
+ */
100
+ async executeWithNewTransaction(em, cb, options, hasExistingTransaction) {
101
+ const fork = this.createFork(em, options);
102
+ let suspended = null;
103
+ // Suspend existing transaction if present
104
+ if (hasExistingTransaction) {
105
+ suspended = this.suspendTransaction(em);
106
+ }
107
+ const newOptions = { ...options, ctx: undefined };
108
+ try {
109
+ return await this.processTransaction(em, fork, cb, newOptions);
110
+ }
111
+ finally {
112
+ if (suspended != null) {
113
+ this.resumeTransaction(em, suspended);
114
+ }
115
+ }
116
+ }
117
+ /**
118
+ * Creates new transaction context.
119
+ */
120
+ async createNewTransaction(em, cb, options) {
121
+ const fork = this.createFork(em, options);
122
+ return this.processTransaction(em, fork, cb, options);
123
+ }
124
+ /**
125
+ * Executes nested transaction with savepoint.
126
+ */
127
+ async executeNestedTransaction(em, cb, options) {
128
+ const fork = this.createFork(em, options);
129
+ // Pass existing context to create savepoint
130
+ const nestedOptions = { ...options, ctx: em.getTransactionContext() };
131
+ return this.processTransaction(em, fork, cb, nestedOptions);
132
+ }
133
+ /**
134
+ * Creates a fork of the EntityManager with the given options.
135
+ */
136
+ createFork(em, options) {
137
+ return em.fork({
138
+ clear: options.clear ?? false,
139
+ flushMode: options.flushMode,
140
+ cloneEventManager: true,
141
+ disableTransactions: options.ignoreNestedTransactions,
142
+ loggerContext: options.loggerContext,
143
+ });
144
+ }
145
+ /**
146
+ * Determines if changes should be propagated to the upper context.
147
+ */
148
+ shouldPropagateToUpperContext(em) {
149
+ return !em.global || this.em.config.get('allowGlobalContext');
150
+ }
151
+ /**
152
+ * Merges entities from fork to parent EntityManager.
153
+ */
154
+ mergeEntitiesToParent(fork, parent) {
155
+ for (const entity of fork.getUnitOfWork(false).getIdentityMap()) {
156
+ parent.merge(entity, { disableContextResolution: true, keepIdentity: true, refresh: true });
157
+ }
158
+ }
159
+ /**
160
+ * Registers a deletion handler to unset entity identities after flush.
161
+ */
162
+ registerDeletionHandler(fork, parent) {
163
+ fork.getEventManager().registerSubscriber({
164
+ afterFlush: (args) => {
165
+ const deletionChangeSets = args.uow.getChangeSets()
166
+ .filter(cs => cs.type === unit_of_work_1.ChangeSetType.DELETE || cs.type === unit_of_work_1.ChangeSetType.DELETE_EARLY);
167
+ for (const cs of deletionChangeSets) {
168
+ parent.getUnitOfWork(false).unsetIdentity(cs.entity);
169
+ }
170
+ },
171
+ });
172
+ }
173
+ /**
174
+ * Processes transaction execution.
175
+ */
176
+ async processTransaction(em, fork, cb, options) {
177
+ const propagateToUpperContext = this.shouldPropagateToUpperContext(em);
178
+ const eventBroadcaster = new events_1.TransactionEventBroadcaster(fork, undefined, { topLevelTransaction: !options.ctx });
179
+ return TransactionContext_1.TransactionContext.create(fork, () => fork.getConnection().transactional(async (trx) => {
180
+ fork.setTransactionContext(trx);
181
+ return this.executeTransactionFlow(fork, cb, propagateToUpperContext, em);
182
+ }, { ...options, eventBroadcaster }));
183
+ }
184
+ /**
185
+ * Executes transaction workflow with entity synchronization.
186
+ */
187
+ async executeTransactionFlow(fork, cb, propagateToUpperContext, parentEm) {
188
+ if (!propagateToUpperContext) {
189
+ const ret = await cb(fork);
190
+ await fork.flush();
191
+ return ret;
192
+ }
193
+ // Setup: Register deletion handler before execution
194
+ this.registerDeletionHandler(fork, parentEm);
195
+ // Execute callback and flush
196
+ const ret = await cb(fork);
197
+ await fork.flush();
198
+ // Synchronization: Merge entities back to the parent
199
+ this.mergeEntitiesToParent(fork, parentEm);
200
+ return ret;
201
+ }
202
+ }
203
+ exports.TransactionManager = TransactionManager;
package/utils/Utils.d.ts CHANGED
@@ -134,14 +134,14 @@ export declare class Utils {
134
134
  static getCompositeKeyHash<T>(data: EntityData<T>, meta: EntityMetadata<T>, convertCustomTypes?: boolean, platform?: Platform, flat?: boolean): string;
135
135
  static getPrimaryKeyHash(pks: (string | Buffer | Date)[]): string;
136
136
  static splitPrimaryKeys<T extends object>(key: string): EntityKey<T>[];
137
- static getPrimaryKeyValues<T>(entity: T, primaryKeys: string[], allowScalar?: boolean, convertCustomTypes?: boolean): any;
137
+ static getPrimaryKeyValues<T>(entity: T, primaryKeys: string[] | EntityMetadata<T>, allowScalar?: boolean, convertCustomTypes?: boolean): any;
138
138
  static getPrimaryKeyCond<T>(entity: T, primaryKeys: EntityKey<T>[]): Record<string, Primary<T>> | null;
139
139
  /**
140
140
  * Maps nested FKs from `[1, 2, 3]` to `[1, [2, 3]]`.
141
141
  */
142
142
  static mapFlatCompositePrimaryKey(fk: Primary<any>[], prop: EntityProperty, fieldNames?: string[], idx?: number): Primary<any> | Primary<any>[];
143
143
  static getPrimaryKeyCondFromArray<T extends object>(pks: Primary<T>[], meta: EntityMetadata<T>): Record<string, Primary<T>>;
144
- static getOrderedPrimaryKeys<T>(id: Primary<T> | Record<string, Primary<T>>, meta: EntityMetadata<T>, platform?: Platform, convertCustomTypes?: boolean): Primary<T>[];
144
+ static getOrderedPrimaryKeys<T>(id: Primary<T> | Record<string, Primary<T>>, meta: EntityMetadata<T>, platform?: Platform, convertCustomTypes?: boolean, allowScalar?: boolean): Primary<T>[];
145
145
  /**
146
146
  * Checks whether given object is an entity instance.
147
147
  */
package/utils/Utils.js CHANGED
@@ -498,6 +498,7 @@ class Utils {
498
498
  static splitPrimaryKeys(key) {
499
499
  return key.split(this.PK_SEPARATOR);
500
500
  }
501
+ // TODO v7: remove support for `primaryKeys: string[]`
501
502
  static getPrimaryKeyValues(entity, primaryKeys, allowScalar = false, convertCustomTypes = false) {
502
503
  /* istanbul ignore next */
503
504
  if (entity == null) {
@@ -509,9 +510,24 @@ class Utils {
509
510
  }
510
511
  return val;
511
512
  }
512
- const pk = Utils.isEntity(entity, true)
513
- ? (0, wrap_1.helper)(entity).getPrimaryKey(convertCustomTypes)
514
- : primaryKeys.reduce((o, pk) => { o[pk] = entity[pk]; return o; }, {});
513
+ const meta = Array.isArray(primaryKeys) ? undefined : primaryKeys;
514
+ primaryKeys = Array.isArray(primaryKeys) ? primaryKeys : meta.primaryKeys;
515
+ let pk;
516
+ if (Utils.isEntity(entity, true)) {
517
+ pk = (0, wrap_1.helper)(entity).getPrimaryKey(convertCustomTypes);
518
+ }
519
+ else {
520
+ pk = primaryKeys.reduce((o, pk) => {
521
+ const targetMeta = meta?.properties[pk].targetMeta;
522
+ if (targetMeta && Utils.isPlainObject(entity[pk])) {
523
+ o[pk] = Utils.getPrimaryKeyValues(entity[pk], targetMeta, allowScalar, convertCustomTypes);
524
+ }
525
+ else {
526
+ o[pk] = entity[pk];
527
+ }
528
+ return o;
529
+ }, {});
530
+ }
515
531
  if (primaryKeys.length > 1) {
516
532
  return toArray(pk);
517
533
  }
@@ -561,7 +577,7 @@ class Utils {
561
577
  return o;
562
578
  }, {});
563
579
  }
564
- static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false) {
580
+ static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false, allowScalar = false) {
565
581
  const data = (Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id);
566
582
  const pks = meta.primaryKeys.map((pk, idx) => {
567
583
  const prop = meta.properties[pk];
@@ -571,11 +587,14 @@ class Utils {
571
587
  value = prop.customType.convertToJSValue(value, platform);
572
588
  }
573
589
  if (prop.kind !== enums_1.ReferenceKind.SCALAR && prop.targetMeta) {
574
- const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes);
590
+ const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes, allowScalar);
575
591
  value = value2.length > 1 ? value2 : value2[0];
576
592
  }
577
593
  return value;
578
594
  });
595
+ if (allowScalar && pks.length === 1) {
596
+ return pks[0];
597
+ }
579
598
  // we need to flatten the PKs as composite PKs can be build from another composite PKs
580
599
  // and this method is used to get the PK hash in identity map, that expects flat array
581
600
  return Utils.flatten(pks);
@@ -928,9 +947,14 @@ class Utils {
928
947
  return require('../../package.json').version;
929
948
  }
930
949
  catch {
931
- // this works with node in production build (where we do not have the `src` folder)
932
- // eslint-disable-next-line @typescript-eslint/no-var-requires
933
- return require('../package.json').version;
950
+ try {
951
+ // this works with node in production build (where we do not have the `src` folder)
952
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
953
+ return require('../package.json').version;
954
+ }
955
+ catch {
956
+ return 'N/A';
957
+ }
934
958
  }
935
959
  }
936
960
  /* istanbul ignore next */
package/utils/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export * from './DataloaderUtils';
5
5
  export * from './Utils';
6
6
  export * from './RequestContext';
7
7
  export * from './TransactionContext';
8
+ export * from './TransactionManager';
8
9
  export * from './QueryHelper';
9
10
  export * from './NullHighlighter';
10
11
  export * from './EntityComparator';
package/utils/index.js CHANGED
@@ -21,6 +21,7 @@ __exportStar(require("./DataloaderUtils"), exports);
21
21
  __exportStar(require("./Utils"), exports);
22
22
  __exportStar(require("./RequestContext"), exports);
23
23
  __exportStar(require("./TransactionContext"), exports);
24
+ __exportStar(require("./TransactionManager"), exports);
24
25
  __exportStar(require("./QueryHelper"), exports);
25
26
  __exportStar(require("./NullHighlighter"), exports);
26
27
  __exportStar(require("./EntityComparator"), exports);
@@ -75,7 +75,15 @@ function getOnConflictReturningFields(meta, data, uniqueFields, options) {
75
75
  if (!meta) {
76
76
  return '*';
77
77
  }
78
- const keys = meta.comparableProps.filter(p => !p.lazy && !p.embeddable && Array.isArray(uniqueFields) && !uniqueFields.includes(p.name)).map(p => p.name);
78
+ const keys = meta.comparableProps.filter(p => {
79
+ if (p.lazy || p.embeddable) {
80
+ return false;
81
+ }
82
+ if (p.autoincrement) {
83
+ return true;
84
+ }
85
+ return Array.isArray(uniqueFields) && !uniqueFields.includes(p.name);
86
+ }).map(p => p.name);
79
87
  if (meta.versionProperty) {
80
88
  keys.push(meta.versionProperty);
81
89
  }