@mikro-orm/core 6.4.17-dev.1 → 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 (67) 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/ManyToMany.d.ts +2 -0
  9. package/decorators/ManyToOne.d.ts +2 -0
  10. package/decorators/OneToOne.d.ts +2 -0
  11. package/decorators/Transactional.d.ts +1 -0
  12. package/decorators/Transactional.js +3 -3
  13. package/drivers/IDatabaseDriver.d.ts +4 -0
  14. package/entity/ArrayCollection.d.ts +3 -1
  15. package/entity/ArrayCollection.js +7 -2
  16. package/entity/EntityFactory.d.ts +6 -0
  17. package/entity/EntityFactory.js +17 -6
  18. package/entity/EntityHelper.js +4 -1
  19. package/entity/EntityLoader.js +26 -18
  20. package/entity/Reference.d.ts +5 -0
  21. package/entity/Reference.js +16 -0
  22. package/entity/WrappedEntity.js +1 -1
  23. package/entity/defineEntity.d.ts +537 -0
  24. package/entity/defineEntity.js +703 -0
  25. package/entity/index.d.ts +2 -0
  26. package/entity/index.js +2 -0
  27. package/entity/utils.d.ts +7 -0
  28. package/entity/utils.js +16 -3
  29. package/enums.d.ts +13 -1
  30. package/enums.js +13 -1
  31. package/errors.d.ts +5 -0
  32. package/errors.js +13 -1
  33. package/hydration/ObjectHydrator.js +1 -1
  34. package/index.d.ts +1 -1
  35. package/index.mjs +16 -0
  36. package/metadata/EntitySchema.js +10 -2
  37. package/metadata/MetadataDiscovery.d.ts +0 -1
  38. package/metadata/MetadataDiscovery.js +17 -13
  39. package/package.json +4 -4
  40. package/platforms/Platform.d.ts +3 -1
  41. package/types/BooleanType.d.ts +1 -1
  42. package/types/DecimalType.js +1 -1
  43. package/types/DoubleType.js +1 -1
  44. package/typings.d.ts +32 -11
  45. package/typings.js +21 -4
  46. package/unit-of-work/ChangeSetComputer.js +3 -1
  47. package/unit-of-work/ChangeSetPersister.d.ts +4 -2
  48. package/unit-of-work/ChangeSetPersister.js +14 -10
  49. package/unit-of-work/UnitOfWork.d.ts +2 -1
  50. package/unit-of-work/UnitOfWork.js +36 -13
  51. package/utils/Configuration.d.ts +7 -1
  52. package/utils/Configuration.js +1 -0
  53. package/utils/ConfigurationLoader.js +2 -2
  54. package/utils/Cursor.js +3 -0
  55. package/utils/EntityComparator.d.ts +6 -2
  56. package/utils/EntityComparator.js +29 -8
  57. package/utils/QueryHelper.d.ts +6 -0
  58. package/utils/QueryHelper.js +47 -4
  59. package/utils/RawQueryFragment.d.ts +34 -0
  60. package/utils/RawQueryFragment.js +35 -0
  61. package/utils/TransactionManager.d.ts +65 -0
  62. package/utils/TransactionManager.js +203 -0
  63. package/utils/Utils.d.ts +2 -2
  64. package/utils/Utils.js +32 -8
  65. package/utils/index.d.ts +1 -0
  66. package/utils/index.js +1 -0
  67. package/utils/upsert-utils.js +9 -1
@@ -112,7 +112,9 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
112
112
  /**
113
113
  * Gets logger context for this entity manager.
114
114
  */
115
- getLoggerContext<T extends Dictionary = Dictionary>(): T;
115
+ getLoggerContext<T extends Dictionary = Dictionary>(options?: {
116
+ disableContextResolution?: boolean;
117
+ }): T;
116
118
  setFlushMode(flushMode?: FlushMode): void;
117
119
  protected processWhere<Entity extends object, Hint extends string = never, Fields extends string = '*', Excludes extends string = never>(entityName: string, where: FilterQuery<Entity>, options: FindOptions<Entity, Hint, Fields, Excludes> | FindOneOptions<Entity, Hint, Fields, Excludes>, type: 'read' | 'update' | 'delete'): Promise<FilterQuery<Entity>>;
118
120
  protected applyDiscriminatorCondition<Entity extends object>(entityName: string, where: FilterQuery<Entity>): FilterQuery<Entity>;
@@ -482,7 +484,7 @@ export declare class EntityManager<Driver extends IDatabaseDriver = IDatabaseDri
482
484
  * some additional lazy properties, if so, we reload and merge the data from database
483
485
  */
484
486
  protected shouldRefresh<T extends object, P extends string = never, F extends string = '*', E extends string = never>(meta: EntityMetadata<T>, entity: T, options: FindOneOptions<T, P, F, E>): boolean;
485
- protected prepareOptions(options: FindOptions<any, any, any, any> | FindOneOptions<any, any, any, any>): void;
487
+ protected prepareOptions(options: FindOptions<any, any, any, any> | FindOneOptions<any, any, any, any> | CountOptions<any, any>): void;
486
488
  /**
487
489
  * @internal
488
490
  */
@@ -542,11 +544,18 @@ export interface CreateOptions<Convert extends boolean> {
542
544
  partial?: boolean;
543
545
  /** convert raw database values based on mapped types (by default, already converted values are expected) */
544
546
  convertCustomTypes?: Convert;
547
+ /**
548
+ * Property `onCreate` hooks are normally executed during `flush` operation.
549
+ * With this option, they will be processed early inside `em.create()` method.
550
+ */
551
+ processOnCreateHooksEarly?: boolean;
545
552
  }
546
553
  export interface MergeOptions {
547
554
  refresh?: boolean;
548
555
  convertCustomTypes?: boolean;
549
556
  schema?: string;
557
+ disableContextResolution?: boolean;
558
+ keepIdentity?: boolean;
550
559
  }
551
560
  export interface ForkOptions {
552
561
  /** do we want a clear identity map? defaults to true */
package/EntityManager.js CHANGED
@@ -12,6 +12,8 @@ const unit_of_work_1 = require("./unit-of-work");
12
12
  const enums_1 = require("./enums");
13
13
  const events_1 = require("./events");
14
14
  const errors_1 = require("./errors");
15
+ const utils_2 = require("./entity/utils");
16
+ const TransactionManager_1 = require("./utils/TransactionManager");
15
17
  /**
16
18
  * The EntityManager is the central access point to ORM functionality. It is a facade to all different ORM subsystems
17
19
  * such as UnitOfWork, Query Language, and Repository API.
@@ -131,7 +133,6 @@ class EntityManager {
131
133
  await em.entityLoader.populate(entityName, cached.data, populate, {
132
134
  ...options,
133
135
  ...em.getPopulateWhere(where, options),
134
- convertCustomTypes: false,
135
136
  ignoreLazyScalarProperties: true,
136
137
  lookup: false,
137
138
  });
@@ -162,7 +163,6 @@ class EntityManager {
162
163
  await em.entityLoader.populate(entityName, unique, populate, {
163
164
  ...options,
164
165
  ...em.getPopulateWhere(where, options),
165
- convertCustomTypes: false,
166
166
  ignoreLazyScalarProperties: true,
167
167
  lookup: false,
168
168
  });
@@ -226,8 +226,8 @@ class EntityManager {
226
226
  /**
227
227
  * Gets logger context for this entity manager.
228
228
  */
229
- getLoggerContext() {
230
- const em = this.getContext();
229
+ getLoggerContext(options) {
230
+ const em = options?.disableContextResolution ? this : this.getContext();
231
231
  em.loggerContext ??= {};
232
232
  return em.loggerContext;
233
233
  }
@@ -283,7 +283,8 @@ class EntityManager {
283
283
  for (const hint of options.populate) {
284
284
  const field = hint.field.split(':')[0];
285
285
  const prop = meta.properties[field];
286
- const joined = (prop.strategy || options.strategy || hint.strategy || this.config.get('loadStrategy')) === enums_1.LoadStrategy.JOINED && prop.kind !== enums_1.ReferenceKind.SCALAR;
286
+ const strategy = (0, utils_2.getLoadingStrategy)(prop.strategy || hint.strategy || options.strategy || this.config.get('loadStrategy'), prop.kind);
287
+ const joined = strategy === enums_1.LoadStrategy.JOINED && prop.kind !== enums_1.ReferenceKind.SCALAR;
287
288
  if (!joined && !hint.filter) {
288
289
  continue;
289
290
  }
@@ -320,10 +321,19 @@ class EntityManager {
320
321
  const cond = await this.applyFilters(prop.type, {}, options.filters ?? {}, 'read', options);
321
322
  if (!utils_1.Utils.isEmpty(cond)) {
322
323
  const populated = options.populate.filter(({ field }) => field.split(':')[0] === prop.name);
324
+ let found = false;
323
325
  if (populated.length > 0) {
324
- populated.forEach(hint => hint.filter = true);
326
+ for (const hint of populated) {
327
+ if (!hint.all) {
328
+ hint.filter = true;
329
+ found = true;
330
+ }
331
+ else if (hint.field === `${prop.name}:ref`) {
332
+ found = true;
333
+ }
334
+ }
325
335
  }
326
- else {
336
+ if (!found) {
327
337
  ret.push({ field: `${prop.name}:ref`, strategy: enums_1.LoadStrategy.JOINED, filter: true });
328
338
  }
329
339
  }
@@ -488,11 +498,17 @@ class EntityManager {
488
498
  ...options,
489
499
  flushMode: enums_1.FlushMode.COMMIT,
490
500
  });
501
+ const em = this.getContext();
491
502
  if (reloaded) {
492
- this.config.getHydrator(this.metadata).hydrate(entity, (0, entity_1.helper)(entity).__meta, (0, entity_1.helper)(reloaded).toPOJO(), this.getEntityFactory(), 'full', false, true);
503
+ for (const e of fork.unitOfWork.getIdentityMap()) {
504
+ const ref = em.getReference(e.constructor.name, (0, entity_1.helper)(e).getPrimaryKey());
505
+ const data = this.comparator.prepareEntity(e);
506
+ em.config.getHydrator(this.metadata).hydrate(ref, (0, entity_1.helper)(ref).__meta, (0, entity_1.helper)(e).serialize({ ignoreSerializers: true }), em.entityFactory, 'full', false, true);
507
+ (0, entity_1.helper)(ref).__originalEntityData = data;
508
+ }
493
509
  }
494
510
  else {
495
- this.getUnitOfWork().unsetIdentity(entity);
511
+ em.unitOfWork.unsetIdentity(entity);
496
512
  }
497
513
  return reloaded ? entity : reloaded;
498
514
  }
@@ -535,7 +551,6 @@ class EntityManager {
535
551
  await em.entityLoader.populate(entityName, [cached.data], options.populate, {
536
552
  ...options,
537
553
  ...em.getPopulateWhere(where, options),
538
- convertCustomTypes: false,
539
554
  ignoreLazyScalarProperties: true,
540
555
  lookup: false,
541
556
  });
@@ -956,39 +971,8 @@ class EntityManager {
956
971
  if (this.disableTransactions || em.disableTransactions) {
957
972
  return cb(em);
958
973
  }
959
- const fork = em.fork({
960
- clear: options.clear ?? false, // state will be merged once resolves
961
- flushMode: options.flushMode,
962
- cloneEventManager: true,
963
- disableTransactions: options.ignoreNestedTransactions,
964
- loggerContext: options.loggerContext,
965
- });
966
- options.ctx ??= em.transactionContext;
967
- const propagateToUpperContext = !em.global || this.config.get('allowGlobalContext');
968
- return utils_1.TransactionContext.create(fork, async () => {
969
- return fork.getConnection().transactional(async (trx) => {
970
- fork.transactionContext = trx;
971
- if (propagateToUpperContext) {
972
- fork.eventManager.registerSubscriber({
973
- afterFlush(args) {
974
- args.uow.getChangeSets()
975
- .filter(cs => [unit_of_work_1.ChangeSetType.DELETE, unit_of_work_1.ChangeSetType.DELETE_EARLY].includes(cs.type))
976
- .forEach(cs => em.unitOfWork.unsetIdentity(cs.entity));
977
- },
978
- });
979
- }
980
- const ret = await cb(fork);
981
- await fork.flush();
982
- if (propagateToUpperContext) {
983
- // ensure all entities from inner context are merged to the upper one
984
- for (const entity of fork.unitOfWork.getIdentityMap()) {
985
- em.unitOfWork.register(entity);
986
- entity.__helper.__em = em;
987
- }
988
- }
989
- return ret;
990
- }, { ...options, eventBroadcaster: new events_1.TransactionEventBroadcaster(fork, undefined, { topLevelTransaction: !options.ctx }) });
991
- });
974
+ const manager = new TransactionManager_1.TransactionManager(this);
975
+ return manager.handle(cb, options);
992
976
  }
993
977
  /**
994
978
  * Starts new transaction bound to this EntityManager. Use `ctx` parameter to provide the parent when nesting transactions.
@@ -1168,10 +1152,10 @@ class EntityManager {
1168
1152
  * via second parameter. By default, it will return already loaded entities without modifying them.
1169
1153
  */
1170
1154
  merge(entityName, data, options = {}) {
1171
- const em = this.getContext();
1172
1155
  if (utils_1.Utils.isEntity(entityName)) {
1173
- return em.merge(entityName.constructor.name, entityName, data);
1156
+ return this.merge(entityName.constructor.name, entityName, data);
1174
1157
  }
1158
+ const em = options.disableContextResolution ? this : this.getContext();
1175
1159
  options.schema ??= em._schema;
1176
1160
  entityName = utils_1.Utils.className(entityName);
1177
1161
  em.validator.validatePrimaryKey(data, em.metadata.get(entityName));
@@ -1181,7 +1165,12 @@ class EntityManager {
1181
1165
  }
1182
1166
  const meta = em.metadata.find(entityName);
1183
1167
  const childMeta = em.metadata.getByDiscriminatorColumn(meta, data);
1184
- entity = utils_1.Utils.isEntity(data) ? data : em.entityFactory.create(entityName, data, { merge: true, ...options });
1168
+ const dataIsEntity = utils_1.Utils.isEntity(data);
1169
+ if (options.keepIdentity && entity && dataIsEntity && entity !== data) {
1170
+ em.entityFactory.mergeData(meta, entity, (0, entity_1.helper)(data).__originalEntityData, { initialized: true, merge: true, ...options });
1171
+ return entity;
1172
+ }
1173
+ entity = dataIsEntity ? data : em.entityFactory.create(entityName, data, { merge: true, ...options });
1185
1174
  em.validator.validate(entity, data, childMeta ?? meta);
1186
1175
  em.unitOfWork.merge(entity);
1187
1176
  return entity;
@@ -1246,10 +1235,8 @@ class EntityManager {
1246
1235
  async count(entityName, where = {}, options = {}) {
1247
1236
  const em = this.getContext(false);
1248
1237
  // Shallow copy options since the object will be modified when deleting orderBy
1249
- options = {
1250
- schema: em._schema,
1251
- ...options,
1252
- };
1238
+ options = { ...options };
1239
+ em.prepareOptions(options);
1253
1240
  entityName = utils_1.Utils.className(entityName);
1254
1241
  await em.tryFlush(entityName, options);
1255
1242
  where = await em.processWhere(entityName, where, options, 'read');
@@ -1267,7 +1254,7 @@ class EntityManager {
1267
1254
  if (cached?.data !== undefined) {
1268
1255
  return cached.data;
1269
1256
  }
1270
- const count = await em.driver.count(entityName, where, { ctx: em.transactionContext, ...options });
1257
+ const count = await em.driver.count(entityName, where, { ctx: em.transactionContext, em, ...options });
1271
1258
  await em.storeCache(options.cache, cached, () => +count);
1272
1259
  return +count;
1273
1260
  }
@@ -1547,7 +1534,6 @@ class EntityManager {
1547
1534
  ...options,
1548
1535
  ...this.getPopulateWhere(where, options),
1549
1536
  orderBy: options.populateOrderBy ?? options.orderBy,
1550
- convertCustomTypes: false,
1551
1537
  ignoreLazyScalarProperties: true,
1552
1538
  lookup: false,
1553
1539
  });
@@ -1670,7 +1656,7 @@ class EntityManager {
1670
1656
  throw new errors_1.ValidationError(`Cannot combine 'fields' and 'exclude' option.`);
1671
1657
  }
1672
1658
  options.schema ??= this._schema;
1673
- options.logging = utils_1.Utils.merge({ id: this.id }, this.loggerContext, options.loggerContext, options.logging);
1659
+ options.logging = options.loggerContext = utils_1.Utils.merge({ id: this.id }, this.loggerContext, options.loggerContext, options.logging);
1674
1660
  }
1675
1661
  /**
1676
1662
  * @internal
package/README.md CHANGED
@@ -11,7 +11,6 @@ TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-or
11
11
  [![Chat on discord](https://img.shields.io/discord/1214904142443839538?label=discord&color=blue)](https://discord.gg/w8bjxFHS7X)
12
12
  [![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)
13
13
  [![Coverage Status](https://img.shields.io/coveralls/mikro-orm/mikro-orm.svg)](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
14
- [![Maintainability](https://api.codeclimate.com/v1/badges/27999651d3adc47cfa40/maintainability)](https://codeclimate.com/github/mikro-orm/mikro-orm/maintainability)
15
14
  [![Build Status](https://github.com/mikro-orm/mikro-orm/workflows/tests/badge.svg?branch=master)](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
16
15
 
17
16
  ## 🤔 Unit of What?
@@ -141,7 +140,7 @@ There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit m
141
140
  - [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
142
141
  - [Filters](https://mikro-orm.io/docs/filters)
143
142
  - [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
144
- - [Preloading Deeply Nested Structures via populate](https://mikro-orm.io/docs/nested-populate)
143
+ - [Populating relations](https://mikro-orm.io/docs/populating-relations)
145
144
  - [Property Validation](https://mikro-orm.io/docs/property-validation)
146
145
  - [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
147
146
  - [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
@@ -49,15 +49,17 @@ export declare abstract class Connection {
49
49
  readOnly?: boolean;
50
50
  ctx?: Transaction;
51
51
  eventBroadcaster?: TransactionEventBroadcaster;
52
+ loggerContext?: LogContext;
52
53
  }): Promise<T>;
53
54
  begin(options?: {
54
55
  isolationLevel?: IsolationLevel;
55
56
  readOnly?: boolean;
56
57
  ctx?: Transaction;
57
58
  eventBroadcaster?: TransactionEventBroadcaster;
59
+ loggerContext?: LogContext;
58
60
  }): Promise<Transaction>;
59
- commit(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
60
- rollback(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
61
+ commit(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
62
+ rollback(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
61
63
  abstract execute<T>(query: string, params?: any[], method?: 'all' | 'get' | 'run', ctx?: Transaction): Promise<QueryResult<T> | any | any[]>;
62
64
  getConnectionOptions(): ConnectionConfig;
63
65
  getClientUrl(): string;
@@ -49,10 +49,10 @@ class Connection {
49
49
  async begin(options) {
50
50
  throw new Error(`Transactions are not supported by current driver`);
51
51
  }
52
- async commit(ctx, eventBroadcaster) {
52
+ async commit(ctx, eventBroadcaster, loggerContext) {
53
53
  throw new Error(`Transactions are not supported by current driver`);
54
54
  }
55
- async rollback(ctx, eventBroadcaster) {
55
+ async rollback(ctx, eventBroadcaster, loggerContext) {
56
56
  throw new Error(`Transactions are not supported by current driver`);
57
57
  }
58
58
  getConnectionOptions() {
@@ -2,18 +2,32 @@ import type { AnyString, Constructor, Dictionary, EntityClass, ObjectQuery } fro
2
2
  import type { FindOptions } from '../drivers/IDatabaseDriver';
3
3
  export declare function Entity<T extends EntityClass<unknown>>(options?: EntityOptions<T>): (target: T) => void;
4
4
  export type EntityOptions<T, E = T extends EntityClass<infer P> ? P : T> = {
5
+ /** Override default collection/table name. Alias for `collection`. */
5
6
  tableName?: string;
7
+ /** Sets the schema name. */
6
8
  schema?: string;
9
+ /** Override default collection/table name. Alias for `tableName`. */
7
10
  collection?: string;
11
+ /** For {@doclink inheritance-mapping#single-table-inheritance | Single Table Inheritance}. */
8
12
  discriminatorColumn?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString;
13
+ /** For {@doclink inheritance-mapping#single-table-inheritance | Single Table Inheritance}. */
9
14
  discriminatorMap?: Dictionary<string>;
15
+ /** For {@doclink inheritance-mapping#single-table-inheritance | Single Table Inheritance}. */
10
16
  discriminatorValue?: number | string;
17
+ /** Enforce use of constructor when creating managed entity instances. */
11
18
  forceConstructor?: boolean;
19
+ /** Specify comment to table. (SQL only) */
12
20
  comment?: string;
21
+ /** Marks entity as abstract, such entities are inlined during discovery. */
13
22
  abstract?: boolean;
23
+ /** Disables change tracking - such entities are ignored during flush. */
14
24
  readonly?: boolean;
25
+ /** Marks entity as {@doclink virtual-entities | virtual}. This is set automatically when you use `expression` option. */
15
26
  virtual?: boolean;
27
+ /** Used to make ORM aware of externally defined triggers. This is needed for MS SQL Server multi inserts, ignored in other dialects. */
16
28
  hasTriggers?: boolean;
29
+ /** SQL query that maps to a {@doclink virtual-entities | virtual entity}. */
17
30
  expression?: string | ((em: any, where: ObjectQuery<E>, options: FindOptions<E, any, any, any>) => object);
31
+ /** Set {@doclink repositories#custom-repository | custom repository class}. */
18
32
  repository?: () => Constructor;
19
33
  };
@@ -1,4 +1,4 @@
1
- import type { EntityClass, Dictionary, AutoPath } from '../typings';
1
+ import type { EntityClass, Dictionary, AutoPath, IndexCallback } from '../typings';
2
2
  import type { DeferMode } from '../enums';
3
3
  export declare function Index<T extends object, H extends string>(options?: IndexOptions<T, H>): (target: T, propertyName?: (T extends EntityClass<unknown> ? undefined : keyof T) | undefined) => any;
4
4
  export declare function Unique<T extends object, H extends string>(options?: UniqueOptions<T, H>): (target: T, propertyName?: (T extends EntityClass<unknown> ? undefined : keyof T) | undefined) => any;
@@ -8,7 +8,7 @@ interface BaseOptions<T, H extends string> {
8
8
  name?: string;
9
9
  properties?: (T extends EntityClass<infer P> ? Properties<P, H> : Properties<T, H>);
10
10
  options?: Dictionary;
11
- expression?: string;
11
+ expression?: string | (T extends EntityClass<infer P> ? IndexCallback<P> : IndexCallback<T>);
12
12
  }
13
13
  export interface UniqueOptions<T, H extends string = string> extends BaseOptions<T, H> {
14
14
  deferMode?: DeferMode | `${DeferMode}`;
@@ -37,4 +37,6 @@ export interface ManyToManyOptions<Owner, Target> extends ReferenceOptions<Owner
37
37
  deleteRule?: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString;
38
38
  /** What to do when the reference to the target entity gets updated. */
39
39
  updateRule?: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString;
40
+ /** Enable/disable foreign key constraint creation on this relation */
41
+ createForeignKeyConstraint?: boolean;
40
42
  }
@@ -27,6 +27,8 @@ export interface ManyToOneOptions<Owner, Target> extends ReferenceOptions<Owner,
27
27
  updateRule?: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString;
28
28
  /** Set the constraint type. Immediate constraints are checked for each statement, while deferred ones are only checked at the end of the transaction. Only for postgres unique constraints. */
29
29
  deferMode?: DeferMode | `${DeferMode}`;
30
+ /** Enable/disable foreign key constraint creation on this relation */
31
+ createForeignKeyConstraint?: boolean;
30
32
  /** Set a custom foreign key constraint name, overriding NamingStrategy.indexName(). */
31
33
  foreignKeyName?: string;
32
34
  }
@@ -23,4 +23,6 @@ export interface OneToOneOptions<Owner, Target> extends Partial<Omit<OneToManyOp
23
23
  deferMode?: DeferMode | `${DeferMode}`;
24
24
  /** Set a custom foreign key constraint name, overriding NamingStrategy.indexName(). */
25
25
  foreignKeyName?: string;
26
+ /** Enable/disable foreign key constraint creation on this relation */
27
+ createForeignKeyConstraint?: boolean;
26
28
  }
@@ -2,6 +2,7 @@ import type { TransactionOptions } from '../enums';
2
2
  import type { ContextProvider } from '../typings';
3
3
  type TransactionalOptions<T> = TransactionOptions & {
4
4
  context?: ContextProvider<T>;
5
+ contextName?: string;
5
6
  };
6
7
  /**
7
8
  * This decorator wraps the method with `em.transactional()`, so you can provide `TransactionOptions` just like with `em.transactional()`.
@@ -17,10 +17,10 @@ function Transactional(options = {}) {
17
17
  throw new Error('@Transactional() should be use with async functions');
18
18
  }
19
19
  descriptor.value = async function (...args) {
20
- const { context, ...txOptions } = options;
20
+ const { context, contextName, ...txOptions } = options;
21
21
  const em = await (0, resolveContextProvider_1.resolveContextProvider)(this, context)
22
- || TransactionContext_1.TransactionContext.getEntityManager()
23
- || RequestContext_1.RequestContext.getEntityManager();
22
+ || TransactionContext_1.TransactionContext.getEntityManager(contextName)
23
+ || RequestContext_1.RequestContext.getEntityManager(contextName);
24
24
  if (!em) {
25
25
  throw new Error(`@Transactional() decorator can only be applied to methods of classes with \`orm: MikroORM\` property, \`em: EntityManager\` property, or with a callback parameter like \`@Transactional(() => orm)\` that returns one of those types. The parameter will contain a reference to current \`this\`. Returning an EntityRepository from it is also supported.`);
26
26
  }
@@ -166,6 +166,7 @@ export interface NativeInsertUpdateOptions<T> {
166
166
  schema?: string;
167
167
  /** `nativeUpdate()` only option */
168
168
  upsert?: boolean;
169
+ loggerContext?: LogContext;
169
170
  }
170
171
  export interface NativeInsertUpdateManyOptions<T> extends NativeInsertUpdateOptions<T> {
171
172
  processCollections?: boolean;
@@ -200,6 +201,8 @@ export interface CountOptions<T extends object, P extends string = never> {
200
201
  hintComments?: string | string[];
201
202
  loggerContext?: LogContext;
202
203
  logging?: LoggingOptions;
204
+ /** @internal used to apply filters to the auto-joined relations */
205
+ em?: EntityManager;
203
206
  }
204
207
  export interface UpdateOptions<T> {
205
208
  filters?: FilterOptions;
@@ -221,6 +224,7 @@ export interface LockOptions extends DriverMethodOptions {
221
224
  export interface DriverMethodOptions {
222
225
  ctx?: Transaction;
223
226
  schema?: string;
227
+ loggerContext?: LogContext;
224
228
  }
225
229
  export interface GetReferenceOptions {
226
230
  wrapped?: boolean;
@@ -6,6 +6,7 @@ export declare class ArrayCollection<T extends object, O extends object> {
6
6
  protected readonly items: Set<T>;
7
7
  protected initialized: boolean;
8
8
  protected dirty: boolean;
9
+ protected partial: boolean;
9
10
  protected snapshot: T[] | undefined;
10
11
  protected _count?: number;
11
12
  private _property?;
@@ -25,7 +26,7 @@ export declare class ArrayCollection<T extends object, O extends object> {
25
26
  /**
26
27
  * @internal
27
28
  */
28
- hydrate(items: T[], forcePropagate?: boolean): void;
29
+ hydrate(items: T[], forcePropagate?: boolean, partial?: boolean): void;
29
30
  /**
30
31
  * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
31
32
  * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
@@ -83,6 +84,7 @@ export declare class ArrayCollection<T extends object, O extends object> {
83
84
  count(): number;
84
85
  isInitialized(fully?: boolean): boolean;
85
86
  isDirty(): boolean;
87
+ isPartial(): boolean;
86
88
  isEmpty(): boolean;
87
89
  setDirty(dirty?: boolean): void;
88
90
  get length(): number;
@@ -12,6 +12,7 @@ class ArrayCollection {
12
12
  items = new Set();
13
13
  initialized = true;
14
14
  dirty = false;
15
+ partial = false; // mark partially loaded collections, propagation is disabled for those
15
16
  snapshot = []; // used to create a diff of the collection at commit time, undefined marks overridden values so we need to wipe when flushing
16
17
  _count;
17
18
  _property;
@@ -110,11 +111,12 @@ class ArrayCollection {
110
111
  /**
111
112
  * @internal
112
113
  */
113
- hydrate(items, forcePropagate) {
114
+ hydrate(items, forcePropagate, partial) {
114
115
  for (let i = 0; i < this.items.size; i++) {
115
116
  delete this[i];
116
117
  }
117
118
  this.initialized = true;
119
+ this.partial = !!partial;
118
120
  this.items.clear();
119
121
  this._count = 0;
120
122
  this.add(items);
@@ -277,6 +279,9 @@ class ArrayCollection {
277
279
  isDirty() {
278
280
  return this.dirty;
279
281
  }
282
+ isPartial() {
283
+ return this.partial;
284
+ }
280
285
  isEmpty() {
281
286
  return this.count() === 0;
282
287
  }
@@ -393,7 +398,7 @@ class ArrayCollection {
393
398
  /** @ignore */
394
399
  [node_util_1.inspect.custom](depth = 2) {
395
400
  const object = { ...this };
396
- const hidden = ['items', 'owner', '_property', '_count', 'snapshot', '_populated', '_snapshot', '_lazyInitialized', '_em', 'readonly'];
401
+ const hidden = ['items', 'owner', '_property', '_count', 'snapshot', '_populated', '_snapshot', '_lazyInitialized', '_em', 'readonly', 'partial'];
397
402
  hidden.forEach(k => delete object[k]);
398
403
  const ret = (0, node_util_1.inspect)(object, { depth });
399
404
  const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
@@ -4,6 +4,11 @@ import type { EntityComparator } from '../utils/EntityComparator';
4
4
  export interface FactoryOptions {
5
5
  initialized?: boolean;
6
6
  newEntity?: boolean;
7
+ /**
8
+ * Property `onCreate` hooks are normally executed during `flush` operation.
9
+ * With this option, they will be processed early inside `em.create()` method.
10
+ */
11
+ processOnCreateHooksEarly?: boolean;
7
12
  merge?: boolean;
8
13
  refresh?: boolean;
9
14
  convertCustomTypes?: boolean;
@@ -27,6 +32,7 @@ export declare class EntityFactory {
27
32
  createEmbeddable<T extends object>(entityName: EntityName<T>, data: EntityData<T>, options?: Pick<FactoryOptions, 'newEntity' | 'convertCustomTypes'>): T;
28
33
  getComparator(): EntityComparator;
29
34
  private createEntity;
35
+ private assignDefaultValues;
30
36
  private hydrate;
31
37
  private findEntity;
32
38
  private processDiscriminatorColumn;
@@ -74,7 +74,7 @@ class EntityFactory {
74
74
  continue;
75
75
  }
76
76
  if ([enums_1.ReferenceKind.MANY_TO_ONE, enums_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind) && Utils_1.Utils.isPlainObject(data[prop.name])) {
77
- data[prop.name] = Utils_1.Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta.primaryKeys, true);
77
+ data[prop.name] = Utils_1.Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
78
78
  }
79
79
  data[prop.name] = prop.customType.convertToDatabaseValue(data[prop.name], this.platform, { key: prop.name, mode: 'hydration' });
80
80
  }
@@ -116,7 +116,7 @@ class EntityFactory {
116
116
  if (meta.versionProperty && data[meta.versionProperty] && data[meta.versionProperty] !== originalEntityData[meta.versionProperty]) {
117
117
  diff[meta.versionProperty] = data[meta.versionProperty];
118
118
  }
119
- const diff2 = this.comparator.diffEntities(meta.className, existsData, data);
119
+ const diff2 = this.comparator.diffEntities(meta.className, existsData, data, { includeInverseSides: true });
120
120
  // do not override values changed by user
121
121
  Utils_1.Utils.keys(diff).forEach(key => delete diff2[key]);
122
122
  Utils_1.Utils.keys(diff2).filter(key => {
@@ -174,8 +174,8 @@ class EntityFactory {
174
174
  if (Array.isArray(id)) {
175
175
  id = Utils_1.Utils.getPrimaryKeyCondFromArray(id, meta);
176
176
  }
177
- const pks = Utils_1.Utils.getOrderedPrimaryKeys(id, meta, this.platform, options.convertCustomTypes);
178
- const exists = this.unitOfWork.getById(entityName, pks, schema);
177
+ const pks = Utils_1.Utils.getOrderedPrimaryKeys(id, meta, this.platform);
178
+ const exists = this.unitOfWork.getById(entityName, pks, schema, options.convertCustomTypes);
179
179
  if (exists) {
180
180
  return exists;
181
181
  }
@@ -234,6 +234,13 @@ class EntityFactory {
234
234
  }
235
235
  return entity;
236
236
  }
237
+ assignDefaultValues(entity, meta) {
238
+ for (const prop of meta.props) {
239
+ if (prop.onCreate) {
240
+ entity[prop.name] ??= prop.onCreate(entity, this.em);
241
+ }
242
+ }
243
+ }
237
244
  hydrate(entity, meta, data, options) {
238
245
  if (options.initialized) {
239
246
  this.hydrator.hydrate(entity, meta, data, this, 'full', options.newEntity, options.convertCustomTypes, options.schema, this.driver.getSchemaName(meta, options));
@@ -245,6 +252,10 @@ class EntityFactory {
245
252
  (0, wrap_1.helper)(entity)?.__loadedProperties.add(key);
246
253
  (0, wrap_1.helper)(entity)?.__serializationContext.fields?.add(key);
247
254
  });
255
+ const processOnCreateHooksEarly = options.processOnCreateHooksEarly ?? this.config.get('processOnCreateHooksEarly');
256
+ if (options.newEntity && processOnCreateHooksEarly) {
257
+ this.assignDefaultValues(entity, meta);
258
+ }
248
259
  }
249
260
  findEntity(data, meta, options) {
250
261
  const schema = this.driver.getSchemaName(meta, options);
@@ -254,7 +265,7 @@ class EntityFactory {
254
265
  if (!Array.isArray(data) && meta.primaryKeys.some(pk => data[pk] == null)) {
255
266
  return undefined;
256
267
  }
257
- const pks = Utils_1.Utils.getOrderedPrimaryKeys(data, meta, this.platform);
268
+ const pks = Utils_1.Utils.getOrderedPrimaryKeys(data, meta, this.platform, options.convertCustomTypes);
258
269
  return this.unitOfWork.getById(meta.className, pks, schema);
259
270
  }
260
271
  processDiscriminatorColumn(meta, data) {
@@ -288,7 +299,7 @@ class EntityFactory {
288
299
  return meta.constructorParams.map(k => {
289
300
  if (meta.properties[k] && [enums_1.ReferenceKind.MANY_TO_ONE, enums_1.ReferenceKind.ONE_TO_ONE].includes(meta.properties[k].kind) && data[k]) {
290
301
  const pk = Reference_1.Reference.unwrapReference(data[k]);
291
- const entity = this.unitOfWork.getById(meta.properties[k].type, pk, options.schema);
302
+ const entity = this.unitOfWork.getById(meta.properties[k].type, pk, options.schema, true);
292
303
  if (entity) {
293
304
  return entity;
294
305
  }
@@ -155,7 +155,7 @@ class EntityHelper {
155
155
  wrapped.__data[prop.name] = Reference_1.Reference.wrapReference(val, prop);
156
156
  // when propagation from inside hydration, we set the FK to the entity data immediately
157
157
  if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
158
- wrapped.__originalEntityData[prop.name] = Utils_1.Utils.getPrimaryKeyValues(wrapped.__data[prop.name], prop.targetMeta.primaryKeys, true);
158
+ wrapped.__originalEntityData[prop.name] = Utils_1.Utils.getPrimaryKeyValues(wrapped.__data[prop.name], prop.targetMeta, true);
159
159
  }
160
160
  else {
161
161
  wrapped.__touched = !hydrator.isRunning();
@@ -175,6 +175,9 @@ class EntityHelper {
175
175
  continue;
176
176
  }
177
177
  const inverse = value?.[prop2.name];
178
+ if (Utils_1.Utils.isCollection(inverse) && inverse.isPartial()) {
179
+ continue;
180
+ }
178
181
  if (prop.kind === enums_1.ReferenceKind.MANY_TO_ONE && Utils_1.Utils.isCollection(inverse) && inverse.isInitialized()) {
179
182
  inverse.addWithoutPropagation(owner);
180
183
  (0, wrap_1.helper)(owner).__em?.getUnitOfWork().cancelOrphanRemoval(owner);