@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
package/typings.js CHANGED
@@ -47,12 +47,29 @@ class EntityMetadata {
47
47
  this.sync();
48
48
  }
49
49
  }
50
- getPrimaryProps() {
51
- return this.primaryKeys.map(pk => this.properties[pk]);
50
+ getPrimaryProps(flatten = false) {
51
+ const pks = this.primaryKeys.map(pk => this.properties[pk]);
52
+ if (flatten) {
53
+ return pks.flatMap(pk => {
54
+ if ([enums_1.ReferenceKind.MANY_TO_ONE, enums_1.ReferenceKind.ONE_TO_ONE].includes(pk.kind)) {
55
+ return pk.targetMeta.getPrimaryProps(true);
56
+ }
57
+ return [pk];
58
+ });
59
+ }
60
+ return pks;
52
61
  }
53
62
  getPrimaryProp() {
54
63
  return this.properties[this.primaryKeys[0]];
55
64
  }
65
+ createColumnMappingObject() {
66
+ return Object.values(this.properties).reduce((o, prop) => {
67
+ if (prop.fieldNames) {
68
+ o[prop.name] = prop.fieldNames[0];
69
+ }
70
+ return o;
71
+ }, {});
72
+ }
56
73
  get tableName() {
57
74
  return this.collection;
58
75
  }
@@ -72,7 +89,7 @@ class EntityMetadata {
72
89
  // `prop.userDefined` is either `undefined` or `false`
73
90
  const discriminator = this.root.discriminatorColumn === prop.name && prop.userDefined === false;
74
91
  // even if we don't have a setter, do not ignore value from database!
75
- const onlyGetter = prop.getter && !prop.setter;
92
+ const onlyGetter = prop.getter && !prop.setter && prop.persist === false;
76
93
  return !prop.inherited && prop.hydrate !== false && !discriminator && !prop.embedded && !onlyGetter;
77
94
  });
78
95
  this.trackingProps = this.hydrateProps
@@ -115,7 +132,7 @@ class EntityMetadata {
115
132
  wrapped.__data[prop.name] = entity_1.Reference.wrapReference(val, prop);
116
133
  // when propagation from inside hydration, we set the FK to the entity data immediately
117
134
  if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
118
- wrapped.__originalEntityData[prop.name] = Utils_1.Utils.getPrimaryKeyValues(val, prop.targetMeta.primaryKeys, true);
135
+ wrapped.__originalEntityData[prop.name] = Utils_1.Utils.getPrimaryKeyValues(val, prop.targetMeta, true);
119
136
  }
120
137
  else {
121
138
  wrapped.__touched = !hydrator.isRunning();
@@ -144,7 +144,9 @@ class ChangeSetComputer {
144
144
  if (!target.isDirty() && changeSet.type !== ChangeSet_1.ChangeSetType.CREATE) {
145
145
  return;
146
146
  }
147
- this.collectionUpdates.add(target);
147
+ if (target.isDirty()) {
148
+ this.collectionUpdates.add(target);
149
+ }
148
150
  if (prop.owner && !this.platform.usesPivotTable()) {
149
151
  changeSet.payload[prop.name] = target.getItems(false).map((item) => item.__helper.__identifier ?? item.__helper.getPrimaryKey());
150
152
  }
@@ -4,6 +4,7 @@ import { type EntityFactory, type EntityValidator } from '../entity';
4
4
  import { type ChangeSet } from './ChangeSet';
5
5
  import { type Configuration } from '../utils';
6
6
  import type { DriverMethodOptions, IDatabaseDriver } from '../drivers';
7
+ import type { EntityManager } from '../EntityManager';
7
8
  export declare class ChangeSetPersister {
8
9
  private readonly driver;
9
10
  private readonly metadata;
@@ -11,10 +12,11 @@ export declare class ChangeSetPersister {
11
12
  private readonly factory;
12
13
  private readonly validator;
13
14
  private readonly config;
15
+ private readonly em;
14
16
  private readonly platform;
15
17
  private readonly comparator;
16
18
  private readonly usesReturningStatement;
17
- constructor(driver: IDatabaseDriver, metadata: MetadataStorage, hydrator: IHydrator, factory: EntityFactory, validator: EntityValidator, config: Configuration);
19
+ constructor(driver: IDatabaseDriver, metadata: MetadataStorage, hydrator: IHydrator, factory: EntityFactory, validator: EntityValidator, config: Configuration, em: EntityManager);
18
20
  executeInserts<T extends object>(changeSets: ChangeSet<T>[], options?: DriverMethodOptions, withSchema?: boolean): Promise<void>;
19
21
  executeUpdates<T extends object>(changeSets: ChangeSet<T>[], batched: boolean, options?: DriverMethodOptions, withSchema?: boolean): Promise<void>;
20
22
  executeDeletes<T extends object>(changeSets: ChangeSet<T>[], options?: DriverMethodOptions, withSchema?: boolean): Promise<void>;
@@ -22,7 +24,7 @@ export declare class ChangeSetPersister {
22
24
  private processProperties;
23
25
  private persistNewEntity;
24
26
  private persistNewEntities;
25
- private propagateSchemaFromMetadata;
27
+ private prepareOptions;
26
28
  private persistNewEntitiesBatch;
27
29
  private persistManagedEntity;
28
30
  private persistManagedEntities;
@@ -13,16 +13,18 @@ class ChangeSetPersister {
13
13
  factory;
14
14
  validator;
15
15
  config;
16
+ em;
16
17
  platform;
17
18
  comparator;
18
19
  usesReturningStatement;
19
- constructor(driver, metadata, hydrator, factory, validator, config) {
20
+ constructor(driver, metadata, hydrator, factory, validator, config, em) {
20
21
  this.driver = driver;
21
22
  this.metadata = metadata;
22
23
  this.hydrator = hydrator;
23
24
  this.factory = factory;
24
25
  this.validator = validator;
25
26
  this.config = config;
27
+ this.em = em;
26
28
  this.platform = this.driver.getPlatform();
27
29
  this.comparator = this.config.getComparator(this.metadata);
28
30
  this.usesReturningStatement = this.platform.usesReturningStatement() || this.platform.usesOutputStatement();
@@ -63,7 +65,7 @@ class ChangeSetPersister {
63
65
  for (let i = 0; i < changeSets.length; i += size) {
64
66
  const chunk = changeSets.slice(i, i + size);
65
67
  const pks = chunk.map(cs => cs.getPrimaryKey());
66
- options = this.propagateSchemaFromMetadata(meta, options);
68
+ options = this.prepareOptions(meta, options);
67
69
  await this.driver.nativeDelete(meta.root.className, { [pk]: { $in: pks } }, options);
68
70
  }
69
71
  }
@@ -91,7 +93,7 @@ class ChangeSetPersister {
91
93
  }
92
94
  async persistNewEntity(meta, changeSet, options) {
93
95
  const wrapped = (0, entity_1.helper)(changeSet.entity);
94
- options = this.propagateSchemaFromMetadata(meta, options, {
96
+ options = this.prepareOptions(meta, options, {
95
97
  convertCustomTypes: false,
96
98
  });
97
99
  const res = await this.driver.nativeInsertMany(meta.className, [changeSet.payload], options);
@@ -117,15 +119,17 @@ class ChangeSetPersister {
117
119
  }
118
120
  }
119
121
  }
120
- propagateSchemaFromMetadata(meta, options, additionalOptions) {
122
+ prepareOptions(meta, options, additionalOptions) {
123
+ const loggerContext = utils_1.Utils.merge({ id: this.em._id }, this.em.getLoggerContext({ disableContextResolution: true }));
121
124
  return {
122
125
  ...options,
123
126
  ...additionalOptions,
124
127
  schema: options?.schema ?? meta.schema,
128
+ loggerContext,
125
129
  };
126
130
  }
127
131
  async persistNewEntitiesBatch(meta, changeSets, options) {
128
- options = this.propagateSchemaFromMetadata(meta, options, {
132
+ options = this.prepareOptions(meta, options, {
129
133
  convertCustomTypes: false,
130
134
  processCollections: false,
131
135
  });
@@ -176,7 +180,7 @@ class ChangeSetPersister {
176
180
  }
177
181
  async persistManagedEntitiesBatch(meta, changeSets, options) {
178
182
  await this.checkOptimisticLocks(meta, changeSets, options);
179
- options = this.propagateSchemaFromMetadata(meta, options, {
183
+ options = this.prepareOptions(meta, options, {
180
184
  convertCustomTypes: false,
181
185
  processCollections: false,
182
186
  });
@@ -236,7 +240,7 @@ class ChangeSetPersister {
236
240
  }
237
241
  async updateEntity(meta, changeSet, options) {
238
242
  const cond = changeSet.getPrimaryKey(true);
239
- options = this.propagateSchemaFromMetadata(meta, options, {
243
+ options = this.prepareOptions(meta, options, {
240
244
  convertCustomTypes: false,
241
245
  });
242
246
  if (meta.concurrencyCheckKeys.size === 0 && (!meta.versionProperty || changeSet.entity[meta.versionProperty] == null)) {
@@ -263,7 +267,7 @@ class ChangeSetPersister {
263
267
  return cond;
264
268
  });
265
269
  const primaryKeys = meta.primaryKeys.concat(...meta.concurrencyCheckKeys);
266
- options = this.propagateSchemaFromMetadata(meta, options, {
270
+ options = this.prepareOptions(meta, options, {
267
271
  fields: primaryKeys,
268
272
  });
269
273
  const res = await this.driver.find(meta.root.className, { $or }, options);
@@ -322,12 +326,12 @@ class ChangeSetPersister {
322
326
  }
323
327
  return val;
324
328
  });
325
- options = this.propagateSchemaFromMetadata(meta, options, {
329
+ options = this.prepareOptions(meta, options, {
326
330
  fields: utils_1.Utils.unique(reloadProps.map(prop => prop.name)),
327
331
  });
328
332
  const data = await this.driver.find(meta.className, { [pk]: { $in: pks } }, options);
329
333
  const map = new Map();
330
- data.forEach(item => map.set(utils_1.Utils.getCompositeKeyHash(item, meta, true, this.platform, true), item));
334
+ data.forEach(item => map.set(utils_1.Utils.getCompositeKeyHash(item, meta, false, this.platform, true), item));
331
335
  for (const changeSet of changeSets) {
332
336
  const data = map.get((0, entity_1.helper)(changeSet.entity).getSerializedPrimaryKey());
333
337
  this.hydrator.hydrate(changeSet.entity, meta, data, this.factory, 'full', false, true);
@@ -38,7 +38,7 @@ export declare class UnitOfWork {
38
38
  /**
39
39
  * Returns entity from the identity map. For composite keys, you need to pass an array of PKs in the same order as they are defined in `meta.primaryKeys`.
40
40
  */
41
- getById<T extends object>(entityName: string, id: Primary<T> | Primary<T>[], schema?: string): T | undefined;
41
+ getById<T extends object>(entityName: string, id: Primary<T> | Primary<T>[], schema?: string, convertCustomTypes?: boolean): T | undefined;
42
42
  tryGetById<T extends object>(entityName: string, where: FilterQuery<T>, schema?: string, strict?: boolean): T | null;
43
43
  /**
44
44
  * Returns map of all managed entities.
@@ -102,6 +102,7 @@ export declare class UnitOfWork {
102
102
  private commitDeleteChangeSets;
103
103
  private commitExtraUpdates;
104
104
  private commitCollectionUpdates;
105
+ private filterCollectionUpdates;
105
106
  /**
106
107
  * Orders change sets so FK constrains are maintained, ensures stable order (needed for node < 11)
107
108
  */
@@ -42,7 +42,7 @@ class UnitOfWork {
42
42
  this.eventManager = this.em.getEventManager();
43
43
  this.comparator = this.em.getComparator();
44
44
  this.changeSetComputer = new ChangeSetComputer_1.ChangeSetComputer(this.em.getValidator(), this.collectionUpdates, this.metadata, this.platform, this.em.config, this.em);
45
- this.changeSetPersister = new ChangeSetPersister_1.ChangeSetPersister(this.em.getDriver(), this.metadata, this.em.config.getHydrator(this.metadata), this.em.getEntityFactory(), this.em.getValidator(), this.em.config);
45
+ this.changeSetPersister = new ChangeSetPersister_1.ChangeSetPersister(this.em.getDriver(), this.metadata, this.em.config.getHydrator(this.metadata), this.em.getEntityFactory(), this.em.getValidator(), this.em.config, this.em);
46
46
  }
47
47
  merge(entity, visited) {
48
48
  const wrapped = (0, entity_1.helper)(entity);
@@ -88,7 +88,7 @@ class UnitOfWork {
88
88
  }
89
89
  wrapped.__loadedProperties.add(key);
90
90
  if ([enums_1.ReferenceKind.MANY_TO_ONE, enums_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind) && Utils_1.Utils.isPlainObject(data[prop.name])) {
91
- data[prop.name] = Utils_1.Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta.primaryKeys, true);
91
+ data[prop.name] = Utils_1.Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
92
92
  }
93
93
  else if (prop.kind === enums_1.ReferenceKind.EMBEDDED && !prop.object && Utils_1.Utils.isPlainObject(data[prop.name])) {
94
94
  for (const p of prop.targetMeta.props) {
@@ -96,7 +96,7 @@ class UnitOfWork {
96
96
  const prefix = prop.prefix === false ? '' : prop.prefix === true ? prop.name + '_' : prop.prefix;
97
97
  data[prefix + p.name] = data[prop.name][p.name];
98
98
  }
99
- data[prop.name] = Utils_1.Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta.primaryKeys, true);
99
+ data[prop.name] = Utils_1.Utils.getPrimaryKeyValues(data[prop.name], prop.targetMeta, true);
100
100
  }
101
101
  if (forceUndefined) {
102
102
  if (data[key] === null) {
@@ -124,7 +124,7 @@ class UnitOfWork {
124
124
  /**
125
125
  * Returns entity from the identity map. For composite keys, you need to pass an array of PKs in the same order as they are defined in `meta.primaryKeys`.
126
126
  */
127
- getById(entityName, id, schema) {
127
+ getById(entityName, id, schema, convertCustomTypes) {
128
128
  if (id == null || (Array.isArray(id) && id.length === 0)) {
129
129
  return undefined;
130
130
  }
@@ -134,7 +134,16 @@ class UnitOfWork {
134
134
  hash = '' + id;
135
135
  }
136
136
  else {
137
- const keys = Array.isArray(id) ? Utils_1.Utils.flatten(id) : [id];
137
+ let keys = Array.isArray(id) ? Utils_1.Utils.flatten(id) : [id];
138
+ keys = meta.getPrimaryProps(true).map((p, i) => {
139
+ if (!convertCustomTypes && p.customType) {
140
+ return p.customType.convertToDatabaseValue(keys[i], this.platform, {
141
+ key: p.name,
142
+ mode: 'hydration',
143
+ });
144
+ }
145
+ return keys[i];
146
+ });
138
147
  hash = Utils_1.Utils.getPrimaryKeyHash(keys);
139
148
  }
140
149
  schema ??= meta.schema ?? this.em.config.getSchema();
@@ -303,6 +312,7 @@ class UnitOfWork {
303
312
  cs.entity.__helper.__processing = true;
304
313
  }
305
314
  await this.eventManager.dispatchEvent(enums_1.EventType.onFlush, { em: this.em, uow: this });
315
+ this.filterCollectionUpdates();
306
316
  // nothing to do, do not start transaction
307
317
  if (this.changeSets.size === 0 && this.collectionUpdates.size === 0 && this.extraUpdates.size === 0) {
308
318
  return void await this.eventManager.dispatchEvent(enums_1.EventType.afterFlush, { em: this.em, uow: this });
@@ -311,9 +321,11 @@ class UnitOfWork {
311
321
  const platform = this.em.getPlatform();
312
322
  const runInTransaction = !this.em.isInTransaction() && platform.supportsTransactions() && this.em.config.get('implicitTransactions');
313
323
  if (runInTransaction) {
324
+ const loggerContext = Utils_1.Utils.merge({ id: this.em._id }, this.em.getLoggerContext({ disableContextResolution: true }));
314
325
  await this.em.getConnection('write').transactional(trx => this.persistToDatabase(groups, trx), {
315
326
  ctx: oldTx,
316
327
  eventBroadcaster: new events_1.TransactionEventBroadcaster(this.em, this),
328
+ loggerContext,
317
329
  });
318
330
  }
319
331
  else {
@@ -886,23 +898,34 @@ class UnitOfWork {
886
898
  }
887
899
  }
888
900
  async commitCollectionUpdates(ctx) {
889
- const collectionUpdates = [];
901
+ this.filterCollectionUpdates();
902
+ const loggerContext = Utils_1.Utils.merge({ id: this.em._id }, this.em.getLoggerContext({ disableContextResolution: true }));
903
+ await this.em.getDriver().syncCollections(this.collectionUpdates, {
904
+ ctx,
905
+ schema: this.em.schema,
906
+ loggerContext,
907
+ });
908
+ for (const coll of this.collectionUpdates) {
909
+ coll.takeSnapshot();
910
+ }
911
+ }
912
+ filterCollectionUpdates() {
890
913
  for (const coll of this.collectionUpdates) {
914
+ let skip = true;
891
915
  if (coll.property.owner || coll.getItems(false).filter(item => !item.__helper.__initialized).length > 0) {
892
916
  if (this.platform.usesPivotTable()) {
893
- collectionUpdates.push(coll);
917
+ skip = false;
894
918
  }
895
919
  }
896
920
  else if (coll.property.kind === enums_1.ReferenceKind.ONE_TO_MANY && coll.getSnapshot() === undefined) {
897
- collectionUpdates.push(coll);
921
+ skip = false;
898
922
  }
899
923
  else if (coll.property.kind === enums_1.ReferenceKind.MANY_TO_MANY && !coll.property.owner) {
900
- collectionUpdates.push(coll);
924
+ skip = false;
925
+ }
926
+ if (skip) {
927
+ this.collectionUpdates.delete(coll);
901
928
  }
902
- }
903
- await this.em.getDriver().syncCollections(collectionUpdates, { ctx, schema: this.em.schema });
904
- for (const coll of this.collectionUpdates) {
905
- coll.takeSnapshot();
906
929
  }
907
930
  }
908
931
  /**
@@ -77,6 +77,7 @@ export declare class Configuration<D extends IDatabaseDriver = IDatabaseDriver,
77
77
  upsertManaged: true;
78
78
  forceEntityConstructor: false;
79
79
  forceUndefined: false;
80
+ processOnCreateHooksEarly: false;
80
81
  ensureDatabase: true;
81
82
  ensureIndexes: false;
82
83
  batchSize: number;
@@ -345,6 +346,11 @@ export interface MikroORMOptions<D extends IDatabaseDriver = IDatabaseDriver, EM
345
346
  upsertManaged: boolean;
346
347
  forceEntityConstructor: boolean | (Constructor<AnyEntity> | string)[];
347
348
  forceUndefined: boolean;
349
+ /**
350
+ * Property `onCreate` hooks are normally executed during `flush` operation.
351
+ * With this option, they will be processed early inside `em.create()` method.
352
+ */
353
+ processOnCreateHooksEarly: boolean;
348
354
  forceUtcTimezone?: boolean;
349
355
  timezone?: string;
350
356
  ensureDatabase: boolean | EnsureDatabaseOptions;
@@ -353,7 +359,7 @@ export interface MikroORMOptions<D extends IDatabaseDriver = IDatabaseDriver, EM
353
359
  useBatchUpdates?: boolean;
354
360
  batchSize: number;
355
361
  hydrator: HydratorConstructor;
356
- loadStrategy: LoadStrategy | 'select-in' | 'joined';
362
+ loadStrategy: LoadStrategy | `${LoadStrategy}`;
357
363
  dataloader: DataloaderType | boolean;
358
364
  populateWhere?: PopulateHint | `${PopulateHint}`;
359
365
  flushMode: FlushMode | 'commit' | 'auto' | 'always';
@@ -71,6 +71,7 @@ class Configuration {
71
71
  upsertManaged: true,
72
72
  forceEntityConstructor: false,
73
73
  forceUndefined: false,
74
+ processOnCreateHooksEarly: false,
74
75
  ensureDatabase: true,
75
76
  ensureIndexes: false,
76
77
  batchSize: 300,
@@ -213,7 +213,7 @@ class ConfigurationLoader {
213
213
  const baseDir = options instanceof Configuration_1.Configuration ? options.get('baseDir') : options?.baseDir;
214
214
  const path = process.env.MIKRO_ORM_ENV ?? ((baseDir ?? process.cwd()) + '/.env');
215
215
  const env = {};
216
- dotenv_1.default.config({ path, processEnv: env });
216
+ dotenv_1.default.config({ path, processEnv: env, quiet: true });
217
217
  // only propagate known env vars
218
218
  for (const key of Object.keys(env)) {
219
219
  if (key.startsWith('MIKRO_ORM_')) {
@@ -347,7 +347,7 @@ class ConfigurationLoader {
347
347
  // inspired by https://github.com/facebook/docusaurus/pull/3386
348
348
  static checkPackageVersion() {
349
349
  const coreVersion = Utils_1.Utils.getORMVersion();
350
- if (process.env.MIKRO_ORM_ALLOW_VERSION_MISMATCH) {
350
+ if (process.env.MIKRO_ORM_ALLOW_VERSION_MISMATCH || coreVersion === 'N/A') {
351
351
  return coreVersion;
352
352
  }
353
353
  const deps = this.getORMPackages();
package/utils/Cursor.js CHANGED
@@ -110,6 +110,9 @@ class Cursor {
110
110
  if (Utils_1.Utils.isEntity(value, true)) {
111
111
  value = (0, wrap_1.helper)(value).getPrimaryKey();
112
112
  }
113
+ if (Utils_1.Utils.isScalarReference(value)) {
114
+ value = value.unwrap();
115
+ }
113
116
  if (object) {
114
117
  return ({ [prop]: value });
115
118
  }
@@ -1,6 +1,8 @@
1
1
  import type { EntityData, EntityDictionary, EntityMetadata, EntityProperty, IMetadataStorage } from '../typings';
2
2
  import type { Platform } from '../platforms';
3
- type Comparator<T> = (a: T, b: T) => EntityData<T>;
3
+ type Comparator<T> = (a: T, b: T, options?: {
4
+ includeInverseSides?: boolean;
5
+ }) => EntityData<T>;
4
6
  type ResultMapper<T> = (result: EntityData<T>) => EntityData<T> | null;
5
7
  type SnapshotGenerator<T> = (entity: T) => EntityData<T>;
6
8
  type CompositeKeyPart = string | CompositeKeyPart[];
@@ -18,7 +20,9 @@ export declare class EntityComparator {
18
20
  /**
19
21
  * Computes difference between two entities.
20
22
  */
21
- diffEntities<T>(entityName: string, a: EntityData<T>, b: EntityData<T>): EntityData<T>;
23
+ diffEntities<T>(entityName: string, a: EntityData<T>, b: EntityData<T>, options?: {
24
+ includeInverseSides?: boolean;
25
+ }): EntityData<T>;
22
26
  matching<T>(entityName: string, a: EntityData<T>, b: EntityData<T>): boolean;
23
27
  /**
24
28
  * Removes ORM specific code from entities and prepares it for serializing. Used before change set computation.
@@ -23,9 +23,9 @@ class EntityComparator {
23
23
  /**
24
24
  * Computes difference between two entities.
25
25
  */
26
- diffEntities(entityName, a, b) {
26
+ diffEntities(entityName, a, b, options) {
27
27
  const comparator = this.getEntityComparator(entityName);
28
- return Utils_1.Utils.callCompiledFunction(comparator, a, b);
28
+ return Utils_1.Utils.callCompiledFunction(comparator, a, b, options);
29
29
  }
30
30
  matching(entityName, a, b) {
31
31
  const diff = this.diffEntities(entityName, a, b);
@@ -158,6 +158,7 @@ class EntityComparator {
158
158
  const lines = [];
159
159
  const context = new Map();
160
160
  context.set('getCompositeKeyValue', (val) => Utils_1.Utils.flatten(Utils_1.Utils.getCompositeKeyValue(val, meta, 'convertToDatabaseValue', this.platform)));
161
+ context.set('getPrimaryKeyHash', (val) => Utils_1.Utils.getPrimaryKeyHash(Utils_1.Utils.asArray(val)));
161
162
  if (meta.primaryKeys.length > 1) {
162
163
  lines.push(` const pks = entity.__helper.__pk ? getCompositeKeyValue(entity.__helper.__pk) : [`);
163
164
  meta.primaryKeys.forEach(pk => {
@@ -173,14 +174,23 @@ class EntityComparator {
173
174
  }
174
175
  else {
175
176
  const pk = meta.primaryKeys[0];
176
- if (meta.properties[pk].kind !== enums_1.ReferenceKind.SCALAR) {
177
+ const prop = meta.properties[pk];
178
+ if (prop.kind !== enums_1.ReferenceKind.SCALAR) {
177
179
  lines.push(` if (entity${this.wrap(pk)} != null && (entity${this.wrap(pk)}.__entity || entity${this.wrap(pk)}.__reference)) return entity${this.wrap(pk)}.__helper.getSerializedPrimaryKey();`);
178
180
  }
179
181
  const serializedPrimaryKey = meta.props.find(p => p.serializedPrimaryKey);
180
182
  if (serializedPrimaryKey) {
181
183
  lines.push(` return '' + entity.${serializedPrimaryKey.name};`);
182
184
  }
183
- lines.push(` return '' + entity.${meta.primaryKeys[0]};`);
185
+ else if (prop.customType) {
186
+ const convertorKey = this.registerCustomType(meta.properties[pk], context);
187
+ const idx = this.tmpIndex++;
188
+ lines.push(` const val_${idx} = convertToDatabaseValue_${convertorKey}(entity${this.wrap(pk)});`);
189
+ lines.push(` return getPrimaryKeyHash(val_${idx});`);
190
+ }
191
+ else {
192
+ lines.push(` return '' + entity${this.wrap(pk)};`);
193
+ }
184
194
  }
185
195
  const code = `// compiled pk serializer for entity ${meta.className}\n`
186
196
  + `return function(entity) {\n${lines.join('\n')}\n}`;
@@ -534,11 +544,22 @@ class EntityComparator {
534
544
  context.set('compareBuffers', Utils_1.compareBuffers);
535
545
  context.set('compareObjects', Utils_1.compareObjects);
536
546
  context.set('equals', Utils_1.equals);
537
- meta.comparableProps.forEach(prop => {
538
- lines.push(this.getPropertyComparator(prop, context));
539
- });
547
+ for (const prop of meta.comparableProps) {
548
+ // skip properties that are not hydrated
549
+ if (prop.hydrate !== false) {
550
+ lines.push(this.getPropertyComparator(prop, context));
551
+ }
552
+ }
553
+ // also compare 1:1 inverse sides, important for `factory.mergeData`
554
+ lines.push(`if (options?.includeInverseSides) {`);
555
+ for (const prop of meta.bidirectionalRelations) {
556
+ if (prop.kind === enums_1.ReferenceKind.ONE_TO_ONE && !prop.owner && prop.hydrate !== false) {
557
+ lines.push(this.getPropertyComparator(prop, context));
558
+ }
559
+ }
560
+ lines.push(`}`);
540
561
  const code = `// compiled comparator for entity ${meta.className}\n`
541
- + `return function(last, current) {\n const diff = {};\n${lines.join('\n')}\n return diff;\n}`;
562
+ + `return function(last, current, options) {\n const diff = {};\n${lines.join('\n')}\n return diff;\n}`;
542
563
  const comparator = Utils_1.Utils.createFunction(context, code);
543
564
  this.comparators.set(entityName, comparator);
544
565
  return comparator;
@@ -1,10 +1,16 @@
1
1
  import type { Dictionary, EntityMetadata, EntityProperty, FilterDef, FilterQuery } from '../typings';
2
2
  import type { Platform } from '../platforms';
3
3
  import type { MetadataStorage } from '../metadata/MetadataStorage';
4
+ /** @internal */
4
5
  export declare class QueryHelper {
5
6
  static readonly SUPPORTED_OPERATORS: string[];
6
7
  static processParams(params: unknown): any;
7
8
  static processObjectParams<T extends object>(params?: T): T;
9
+ /**
10
+ * converts `{ account: { $or: [ [Object], [Object] ] } }`
11
+ * to `{ $or: [ { account: [Object] }, { account: [Object] } ] }`
12
+ */
13
+ static liftGroupOperators<T extends object>(where: Dictionary, meta: EntityMetadata<T>, metadata: MetadataStorage, key?: string): string | undefined;
8
14
  static inlinePrimaryKeyObjects<T extends object>(where: Dictionary, meta: EntityMetadata<T>, metadata: MetadataStorage, key?: string): boolean;
9
15
  static processWhere<T extends object>(options: ProcessWhereOptions<T>): FilterQuery<T>;
10
16
  static getActiveFilters(entityName: string, options: Dictionary<boolean | Dictionary> | string[] | boolean, filters: Dictionary<FilterDef>): FilterDef[];
@@ -7,6 +7,7 @@ const enums_1 = require("../enums");
7
7
  const JsonType_1 = require("../types/JsonType");
8
8
  const wrap_1 = require("../entity/wrap");
9
9
  const RawQueryFragment_1 = require("./RawQueryFragment");
10
+ /** @internal */
10
11
  class QueryHelper {
11
12
  static SUPPORTED_OPERATORS = ['>', '<', '<=', '>=', '!', '!='];
12
13
  static processParams(params) {
@@ -36,11 +37,52 @@ class QueryHelper {
36
37
  });
37
38
  return params;
38
39
  }
40
+ /**
41
+ * converts `{ account: { $or: [ [Object], [Object] ] } }`
42
+ * to `{ $or: [ { account: [Object] }, { account: [Object] } ] }`
43
+ */
44
+ static liftGroupOperators(where, meta, metadata, key) {
45
+ if (!Utils_1.Utils.isPlainObject(where)) {
46
+ return undefined;
47
+ }
48
+ const keys = Object.keys(where);
49
+ const groupOperator = keys.find(k => {
50
+ return Utils_1.Utils.isGroupOperator(k) && Array.isArray(where[k]) && where[k].every(cond => {
51
+ return Utils_1.Utils.isPlainObject(cond) && Object.keys(cond).every(k2 => {
52
+ if (Utils_1.Utils.isOperator(k2, false)) {
53
+ if (k2 === '$not') {
54
+ return Object.keys(cond[k2]).every(k3 => meta.primaryKeys.includes(k3));
55
+ }
56
+ return true;
57
+ }
58
+ return meta.primaryKeys.includes(k2);
59
+ });
60
+ });
61
+ });
62
+ if (groupOperator) {
63
+ return groupOperator;
64
+ }
65
+ for (const k of keys) {
66
+ const value = where[k];
67
+ const prop = meta.properties[k];
68
+ if (!prop || ![enums_1.ReferenceKind.MANY_TO_ONE, enums_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
69
+ continue;
70
+ }
71
+ const op = this.liftGroupOperators(value, prop.targetMeta, metadata, k);
72
+ if (op) {
73
+ delete where[k];
74
+ where[op] = value[op].map((v) => {
75
+ return { [k]: v };
76
+ });
77
+ }
78
+ }
79
+ return undefined;
80
+ }
39
81
  static inlinePrimaryKeyObjects(where, meta, metadata, key) {
40
82
  if (Array.isArray(where)) {
41
83
  where.forEach((item, i) => {
42
84
  if (this.inlinePrimaryKeyObjects(item, meta, metadata, key)) {
43
- where[i] = Utils_1.Utils.getPrimaryKeyValues(item, meta.primaryKeys, false);
85
+ where[i] = Utils_1.Utils.getPrimaryKeyValues(item, meta, false);
44
86
  }
45
87
  });
46
88
  }
@@ -50,7 +92,7 @@ class QueryHelper {
50
92
  if (meta.primaryKeys.every(pk => pk in where) && Utils_1.Utils.getObjectKeysSize(where) === meta.primaryKeys.length) {
51
93
  return !!key && !enums_1.GroupOperator[key] && key !== '$not' && Object.keys(where).every(k => !Utils_1.Utils.isPlainObject(where[k]) || Object.keys(where[k]).every(v => {
52
94
  if (Utils_1.Utils.isOperator(v, false)) {
53
- return false;
95
+ return true;
54
96
  }
55
97
  if (meta.properties[k].primary && [enums_1.ReferenceKind.ONE_TO_ONE, enums_1.ReferenceKind.MANY_TO_ONE].includes(meta.properties[k].kind)) {
56
98
  return this.inlinePrimaryKeyObjects(where[k], meta.properties[k].targetMeta, metadata, v);
@@ -61,7 +103,7 @@ class QueryHelper {
61
103
  Object.keys(where).forEach(k => {
62
104
  const meta2 = metadata.find(meta.properties[k]?.type) || meta;
63
105
  if (this.inlinePrimaryKeyObjects(where[k], meta2, metadata, k)) {
64
- where[k] = Utils_1.Utils.getPrimaryKeyValues(where[k], meta2.primaryKeys, true);
106
+ where[k] = Utils_1.Utils.getPrimaryKeyValues(where[k], meta2, true);
65
107
  }
66
108
  });
67
109
  return false;
@@ -72,6 +114,7 @@ class QueryHelper {
72
114
  const meta = metadata.find(entityName);
73
115
  // inline PK-only objects in M:N queries, so we don't join the target entity when not needed
74
116
  if (meta && root) {
117
+ QueryHelper.liftGroupOperators(where, meta, metadata);
75
118
  QueryHelper.inlinePrimaryKeyObjects(where, meta, metadata);
76
119
  }
77
120
  if (options.platform.getConfig().get('ignoreUndefinedInQuery') && where && typeof where === 'object') {
@@ -121,7 +164,7 @@ class QueryHelper {
121
164
  value = QueryHelper.processCustomType(prop, value, platform, undefined, true);
122
165
  }
123
166
  const isJsonProperty = prop?.customType instanceof JsonType_1.JsonType && Utils_1.Utils.isPlainObject(value) && !platform.isRaw(value) && Object.keys(value)[0] !== '$eq';
124
- if (isJsonProperty) {
167
+ if (isJsonProperty && prop?.kind !== enums_1.ReferenceKind.EMBEDDED) {
125
168
  return this.processJsonCondition(o, value, [prop.fieldNames[0]], platform, aliased);
126
169
  }
127
170
  if (Array.isArray(value) && !Utils_1.Utils.isOperator(key) && !QueryHelper.isSupportedOperator(key) && !key.includes('?') && options.type !== 'orderBy') {
@@ -70,6 +70,24 @@ export declare const ALIAS_REPLACEMENT_RE = "\\[::alias::\\]";
70
70
  * ```ts
71
71
  * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
72
72
  * ```
73
+ *
74
+ * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use:
75
+ *
76
+ * ```ts
77
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country")
78
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`)
79
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) })
80
+ * @Entity({ schema: 'library' })
81
+ * export class Author { ... }
82
+ * ```
83
+ *
84
+ * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax:
85
+ *
86
+ * ```ts
87
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
88
+ * @Entity({ schema: 'library' })
89
+ * export class Author { ... }
90
+ * ```
73
91
  */
74
92
  export declare function raw<T extends object = any, R = any>(sql: EntityKey<T> | EntityKey<T>[] | AnyString | ((alias: string) => string) | RawQueryFragment, params?: readonly unknown[] | Dictionary<unknown>): R;
75
93
  /**
@@ -94,3 +112,19 @@ export declare namespace sql {
94
112
  var upper: <T extends object>(key: string | ((alias: string) => string)) => string;
95
113
  }
96
114
  export declare function createSqlFunction<T extends object, R = string>(func: string, key: string | ((alias: string) => string)): R;
115
+ /**
116
+ * Tag function providing quoting of db identifiers (table name, columns names, index names, ...).
117
+ *
118
+ * Within the template literal on which the tag function is applied, all placeholders are considered to be database identifiers, and will thus be quoted as so according to the database in use.
119
+ *
120
+ * ```ts
121
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("name")
122
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`name`)
123
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
124
+ * @Entity({ schema: 'library' })
125
+ * export class Author { ... }
126
+ * ```
127
+ */
128
+ export declare function quote(expParts: readonly string[], ...values: (string | {
129
+ toString(): string;
130
+ })[]): any;