@mikro-orm/core 7.0.0-dev.4 → 7.0.0-dev.40

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/EntityManager.d.ts +84 -18
  2. package/EntityManager.js +265 -172
  3. package/MikroORM.d.ts +7 -5
  4. package/MikroORM.js +0 -1
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +2 -1
  7. package/cache/FileCacheAdapter.js +6 -4
  8. package/connections/Connection.d.ts +4 -2
  9. package/connections/Connection.js +2 -2
  10. package/decorators/Check.d.ts +2 -2
  11. package/decorators/Embeddable.d.ts +5 -5
  12. package/decorators/Embeddable.js +1 -1
  13. package/decorators/Embedded.d.ts +6 -12
  14. package/decorators/Entity.d.ts +18 -3
  15. package/decorators/Enum.d.ts +1 -1
  16. package/decorators/Formula.d.ts +1 -2
  17. package/decorators/Indexed.d.ts +2 -2
  18. package/decorators/ManyToMany.d.ts +4 -2
  19. package/decorators/ManyToOne.d.ts +6 -2
  20. package/decorators/OneToMany.d.ts +4 -4
  21. package/decorators/OneToOne.d.ts +5 -1
  22. package/decorators/PrimaryKey.d.ts +2 -3
  23. package/decorators/Property.d.ts +54 -4
  24. package/decorators/Transactional.d.ts +1 -0
  25. package/decorators/Transactional.js +3 -3
  26. package/decorators/index.d.ts +1 -1
  27. package/drivers/DatabaseDriver.d.ts +4 -3
  28. package/drivers/IDatabaseDriver.d.ts +22 -2
  29. package/entity/ArrayCollection.d.ts +4 -2
  30. package/entity/ArrayCollection.js +18 -6
  31. package/entity/Collection.d.ts +1 -2
  32. package/entity/Collection.js +19 -10
  33. package/entity/EntityAssigner.d.ts +1 -1
  34. package/entity/EntityAssigner.js +9 -1
  35. package/entity/EntityFactory.d.ts +7 -0
  36. package/entity/EntityFactory.js +29 -9
  37. package/entity/EntityHelper.js +25 -3
  38. package/entity/EntityLoader.d.ts +5 -4
  39. package/entity/EntityLoader.js +74 -37
  40. package/entity/EntityRepository.d.ts +1 -1
  41. package/entity/EntityValidator.js +1 -1
  42. package/entity/Reference.d.ts +9 -7
  43. package/entity/Reference.js +30 -3
  44. package/entity/WrappedEntity.js +1 -1
  45. package/entity/defineEntity.d.ts +561 -0
  46. package/entity/defineEntity.js +537 -0
  47. package/entity/index.d.ts +2 -0
  48. package/entity/index.js +2 -0
  49. package/entity/utils.d.ts +7 -0
  50. package/entity/utils.js +15 -3
  51. package/enums.d.ts +16 -3
  52. package/enums.js +13 -0
  53. package/errors.d.ts +6 -0
  54. package/errors.js +14 -0
  55. package/events/EventSubscriber.d.ts +3 -1
  56. package/hydration/ObjectHydrator.d.ts +4 -4
  57. package/hydration/ObjectHydrator.js +35 -24
  58. package/index.d.ts +2 -1
  59. package/index.js +1 -1
  60. package/logging/DefaultLogger.d.ts +1 -1
  61. package/logging/SimpleLogger.d.ts +1 -1
  62. package/metadata/EntitySchema.d.ts +8 -4
  63. package/metadata/EntitySchema.js +39 -19
  64. package/metadata/MetadataDiscovery.d.ts +1 -1
  65. package/metadata/MetadataDiscovery.js +88 -32
  66. package/metadata/MetadataStorage.js +1 -1
  67. package/metadata/MetadataValidator.js +4 -3
  68. package/naming-strategy/AbstractNamingStrategy.d.ts +5 -1
  69. package/naming-strategy/AbstractNamingStrategy.js +7 -1
  70. package/naming-strategy/NamingStrategy.d.ts +11 -1
  71. package/package.json +5 -5
  72. package/platforms/Platform.d.ts +5 -3
  73. package/platforms/Platform.js +4 -8
  74. package/serialization/EntitySerializer.d.ts +2 -0
  75. package/serialization/EntitySerializer.js +2 -2
  76. package/serialization/EntityTransformer.js +1 -1
  77. package/serialization/SerializationContext.js +14 -11
  78. package/types/BigIntType.d.ts +9 -6
  79. package/types/BigIntType.js +3 -0
  80. package/types/BooleanType.d.ts +1 -1
  81. package/types/DecimalType.d.ts +6 -4
  82. package/types/DecimalType.js +1 -1
  83. package/types/DoubleType.js +1 -1
  84. package/types/JsonType.d.ts +1 -1
  85. package/types/JsonType.js +7 -2
  86. package/types/Type.d.ts +2 -1
  87. package/types/Type.js +1 -1
  88. package/types/index.d.ts +1 -1
  89. package/typings.d.ts +88 -39
  90. package/typings.js +24 -4
  91. package/unit-of-work/ChangeSetComputer.js +3 -1
  92. package/unit-of-work/ChangeSetPersister.d.ts +4 -2
  93. package/unit-of-work/ChangeSetPersister.js +37 -16
  94. package/unit-of-work/UnitOfWork.d.ts +8 -1
  95. package/unit-of-work/UnitOfWork.js +109 -41
  96. package/utils/Configuration.d.ts +23 -5
  97. package/utils/Configuration.js +17 -3
  98. package/utils/ConfigurationLoader.d.ts +0 -2
  99. package/utils/ConfigurationLoader.js +2 -24
  100. package/utils/Cursor.d.ts +3 -3
  101. package/utils/Cursor.js +3 -0
  102. package/utils/DataloaderUtils.d.ts +7 -2
  103. package/utils/DataloaderUtils.js +38 -7
  104. package/utils/EntityComparator.d.ts +6 -2
  105. package/utils/EntityComparator.js +104 -58
  106. package/utils/QueryHelper.d.ts +9 -1
  107. package/utils/QueryHelper.js +66 -5
  108. package/utils/RawQueryFragment.d.ts +36 -2
  109. package/utils/RawQueryFragment.js +35 -1
  110. package/utils/TransactionManager.d.ts +65 -0
  111. package/utils/TransactionManager.js +218 -0
  112. package/utils/Utils.d.ts +11 -5
  113. package/utils/Utils.js +76 -33
  114. package/utils/index.d.ts +1 -0
  115. package/utils/index.js +1 -0
  116. package/utils/upsert-utils.d.ts +7 -2
  117. package/utils/upsert-utils.js +52 -1
package/errors.d.ts CHANGED
@@ -24,6 +24,7 @@ export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Er
24
24
  static cannotCommit(): ValidationError;
25
25
  static cannotUseGlobalContext(): ValidationError;
26
26
  static cannotUseOperatorsInsideEmbeddables(className: string, propName: string, payload: unknown): ValidationError;
27
+ static cannotUseGroupOperatorsInsideScalars(className: string, propName: string, payload: unknown): ValidationError;
27
28
  static invalidEmbeddableQuery(className: string, propName: string, embeddableType: string): ValidationError;
28
29
  }
29
30
  export declare class CursorError<T extends AnyEntity = AnyEntity> extends ValidationError<T> {
@@ -66,3 +67,8 @@ export declare class NotFoundError<T extends AnyEntity = AnyEntity> extends Vali
66
67
  static findOneFailed(name: string, where: Dictionary | IPrimaryKey): NotFoundError;
67
68
  static findExactlyOneFailed(name: string, where: Dictionary | IPrimaryKey): NotFoundError;
68
69
  }
70
+ export declare class TransactionStateError extends ValidationError {
71
+ static requiredTransactionNotFound(propagation: string): TransactionStateError;
72
+ static transactionNotAllowed(propagation: string): TransactionStateError;
73
+ static invalidPropagation(propagation: string): TransactionStateError;
74
+ }
package/errors.js CHANGED
@@ -94,6 +94,9 @@ export class ValidationError extends Error {
94
94
  static cannotUseOperatorsInsideEmbeddables(className, propName, payload) {
95
95
  return new ValidationError(`Using operators inside embeddables is not allowed, move the operator above. (property: ${className}.${propName}, payload: ${inspect(payload)})`);
96
96
  }
97
+ static cannotUseGroupOperatorsInsideScalars(className, propName, payload) {
98
+ return new ValidationError(`Using group operators ($and/$or) inside scalar properties is not allowed, move the operator above. (property: ${className}.${propName}, payload: ${inspect(payload)})`);
99
+ }
97
100
  static invalidEmbeddableQuery(className, propName, embeddableType) {
98
101
  return new ValidationError(`Invalid query for entity '${className}', property '${propName}' does not exist in embeddable '${embeddableType}'`);
99
102
  }
@@ -220,3 +223,14 @@ export class NotFoundError extends ValidationError {
220
223
  return new NotFoundError(`Wrong number of ${name} entities found for query ${inspect(where)}, expected exactly one`);
221
224
  }
222
225
  }
226
+ export class TransactionStateError extends ValidationError {
227
+ static requiredTransactionNotFound(propagation) {
228
+ return new TransactionStateError(`No existing transaction found for transaction marked with propagation "${propagation}"`);
229
+ }
230
+ static transactionNotAllowed(propagation) {
231
+ return new TransactionStateError(`Existing transaction found for transaction marked with propagation "${propagation}"`);
232
+ }
233
+ static invalidPropagation(propagation) {
234
+ return new TransactionStateError(`Unsupported transaction propagation type: ${propagation}`);
235
+ }
236
+ }
@@ -13,7 +13,9 @@ export interface FlushEventArgs extends Omit<EventArgs<any>, 'entity' | 'changeS
13
13
  uow: UnitOfWork;
14
14
  }
15
15
  export interface TransactionEventArgs extends Omit<EventArgs<any>, 'entity' | 'meta' | 'changeSet'> {
16
- transaction?: Transaction;
16
+ transaction?: Transaction & {
17
+ savepointName?: string;
18
+ };
17
19
  uow?: UnitOfWork;
18
20
  }
19
21
  export interface EventSubscriber<T = any> {
@@ -1,22 +1,22 @@
1
1
  import type { EntityData, EntityMetadata } from '../typings.js';
2
2
  import { Hydrator } from './Hydrator.js';
3
3
  import type { EntityFactory } from '../entity/EntityFactory.js';
4
- type EntityHydrator<T extends object> = (entity: T, data: EntityData<T>, factory: EntityFactory, newEntity: boolean, convertCustomTypes: boolean, schema?: string, parentSchema?: string) => void;
4
+ type EntityHydrator<T extends object> = (entity: T, data: EntityData<T>, factory: EntityFactory, newEntity: boolean, convertCustomTypes: boolean, schema?: string, parentSchema?: string, normalizeAccessors?: boolean) => void;
5
5
  export declare class ObjectHydrator extends Hydrator {
6
6
  private readonly hydrators;
7
7
  private tmpIndex;
8
8
  /**
9
9
  * @inheritDoc
10
10
  */
11
- hydrate<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, type: 'full' | 'reference', newEntity?: boolean, convertCustomTypes?: boolean, schema?: string, parentSchema?: string): void;
11
+ hydrate<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, type: 'full' | 'reference', newEntity?: boolean, convertCustomTypes?: boolean, schema?: string, parentSchema?: string, normalizeAccessors?: boolean): void;
12
12
  /**
13
13
  * @inheritDoc
14
14
  */
15
- hydrateReference<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, convertCustomTypes?: boolean, schema?: string, parentSchema?: string): void;
15
+ hydrateReference<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, convertCustomTypes?: boolean, schema?: string, parentSchema?: string, normalizeAccessors?: boolean): void;
16
16
  /**
17
17
  * @internal Highly performance-sensitive method.
18
18
  */
19
- getEntityHydrator<T extends object>(meta: EntityMetadata<T>, type: 'full' | 'reference'): EntityHydrator<T>;
19
+ getEntityHydrator<T extends object>(meta: EntityMetadata<T>, type: 'full' | 'reference', normalizeAccessors?: boolean): EntityHydrator<T>;
20
20
  private createCollectionItemMapper;
21
21
  private wrap;
22
22
  private safeKey;
@@ -6,37 +6,40 @@ import { ReferenceKind } from '../enums.js';
6
6
  import { RawQueryFragment } from '../utils/RawQueryFragment.js';
7
7
  export class ObjectHydrator extends Hydrator {
8
8
  hydrators = {
9
- full: new Map(),
10
- reference: new Map(),
9
+ 'full~true': new Map(),
10
+ 'full~false': new Map(),
11
+ 'reference~true': new Map(),
12
+ 'reference~false': new Map(),
11
13
  };
12
14
  tmpIndex = 0;
13
15
  /**
14
16
  * @inheritDoc
15
17
  */
16
- hydrate(entity, meta, data, factory, type, newEntity = false, convertCustomTypes = false, schema, parentSchema) {
17
- const hydrate = this.getEntityHydrator(meta, type);
18
+ hydrate(entity, meta, data, factory, type, newEntity = false, convertCustomTypes = false, schema, parentSchema, normalizeAccessors) {
19
+ const hydrate = this.getEntityHydrator(meta, type, normalizeAccessors);
18
20
  const running = this.running;
19
21
  // the running state is used to consider propagation as hydration, saving the values directly to the entity data,
20
22
  // but we don't want that for new entities, their propagation should result in entity updates when flushing
21
23
  this.running = !newEntity;
22
- Utils.callCompiledFunction(hydrate, entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema);
24
+ Utils.callCompiledFunction(hydrate, entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors);
23
25
  this.running = running;
24
26
  }
25
27
  /**
26
28
  * @inheritDoc
27
29
  */
28
- hydrateReference(entity, meta, data, factory, convertCustomTypes = false, schema, parentSchema) {
29
- const hydrate = this.getEntityHydrator(meta, 'reference');
30
+ hydrateReference(entity, meta, data, factory, convertCustomTypes = false, schema, parentSchema, normalizeAccessors) {
31
+ const hydrate = this.getEntityHydrator(meta, 'reference', normalizeAccessors);
30
32
  const running = this.running;
31
33
  this.running = true;
32
- Utils.callCompiledFunction(hydrate, entity, data, factory, false, convertCustomTypes, schema, parentSchema);
34
+ Utils.callCompiledFunction(hydrate, entity, data, factory, false, convertCustomTypes, schema, parentSchema, normalizeAccessors);
33
35
  this.running = running;
34
36
  }
35
37
  /**
36
38
  * @internal Highly performance-sensitive method.
37
39
  */
38
- getEntityHydrator(meta, type) {
39
- const exists = this.hydrators[type].get(meta.className);
40
+ getEntityHydrator(meta, type, normalizeAccessors = false) {
41
+ const key = `${type}~${normalizeAccessors}`;
42
+ const exists = this.hydrators[key].get(meta.className);
40
43
  if (exists) {
41
44
  return exists;
42
45
  }
@@ -63,7 +66,7 @@ export class ObjectHydrator extends Hydrator {
63
66
  const ret = [];
64
67
  const idx = this.tmpIndex++;
65
68
  const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
66
- if (prop.getter && !prop.setter) {
69
+ if (prop.getter && !prop.setter && prop.persist === false) {
67
70
  return [];
68
71
  }
69
72
  if (prop.ref) {
@@ -71,7 +74,14 @@ export class ObjectHydrator extends Hydrator {
71
74
  ret.push(` const oldValue_${idx} = entity${entityKey};`);
72
75
  }
73
76
  ret.push(` if (data${dataKey} === null) {`);
74
- ret.push(` entity${entityKey} = ${nullVal};`);
77
+ if (prop.ref) {
78
+ ret.push(` entity${entityKey} = new ScalarReference();`);
79
+ ret.push(` entity${entityKey}.bind(entity, '${prop.name}');`);
80
+ ret.push(` entity${entityKey}.set(${nullVal});`);
81
+ }
82
+ else {
83
+ ret.push(` entity${entityKey} = ${nullVal};`);
84
+ }
75
85
  ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
76
86
  if (prop.customType) {
77
87
  registerCustomType(prop, convertorKey, 'convertToJSValue', context);
@@ -126,17 +136,17 @@ export class ObjectHydrator extends Hydrator {
126
136
  ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
127
137
  ret.push(` if (isPrimaryKey(data${dataKey}, true)) {`);
128
138
  if (prop.ref) {
129
- ret.push(` entity${entityKey} = Reference.create(factory.createReference('${prop.type}', data${dataKey}, { merge: true, convertCustomTypes, schema }));`);
139
+ ret.push(` entity${entityKey} = Reference.create(factory.createReference('${prop.type}', data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema }));`);
130
140
  }
131
141
  else {
132
- ret.push(` entity${entityKey} = factory.createReference('${prop.type}', data${dataKey}, { merge: true, convertCustomTypes, schema });`);
142
+ ret.push(` entity${entityKey} = factory.createReference('${prop.type}', data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema });`);
133
143
  }
134
144
  ret.push(` } else if (data${dataKey} && typeof data${dataKey} === 'object') {`);
135
145
  if (prop.ref) {
136
- ret.push(` entity${entityKey} = Reference.create(factory.${method}('${prop.type}', data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, schema }));`);
146
+ ret.push(` entity${entityKey} = Reference.create(factory.${method}('${prop.type}', data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema }));`);
137
147
  }
138
148
  else {
139
- ret.push(` entity${entityKey} = factory.${method}('${prop.type}', data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, schema });`);
149
+ ret.push(` entity${entityKey} = factory.${method}('${prop.type}', data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema });`);
140
150
  }
141
151
  ret.push(` }`);
142
152
  ret.push(` }`);
@@ -245,7 +255,7 @@ export class ObjectHydrator extends Hydrator {
245
255
  // weak comparison as we can have numbers that might have been converted to strings due to being object keys
246
256
  ret.push(` if (data${childDataKey} == '${childMeta.discriminatorValue}') {`);
247
257
  ret.push(` if (entity${entityKey} == null) {`);
248
- ret.push(` entity${entityKey} = factory.createEmbeddable('${childMeta.className}', embeddedData, { newEntity, convertCustomTypes });`);
258
+ ret.push(` entity${entityKey} = factory.createEmbeddable('${childMeta.className}', embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`);
249
259
  ret.push(` }`);
250
260
  meta.props
251
261
  .filter(p => p.embedded?.[0] === prop.name)
@@ -256,6 +266,7 @@ export class ObjectHydrator extends Hydrator {
256
266
  ...prop2,
257
267
  name: childProp.name,
258
268
  embedded: childProp.embedded,
269
+ embeddedProps: childProp.embeddedProps,
259
270
  };
260
271
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
261
272
  ret.push(...hydrateProperty(prop3, childProp.object, [...path, childProp.embedded[1]], childDataKey).map(l => ' ' + l));
@@ -265,7 +276,7 @@ export class ObjectHydrator extends Hydrator {
265
276
  }
266
277
  else {
267
278
  ret.push(` if (entity${entityKey} == null) {`);
268
- ret.push(` entity${entityKey} = factory.createEmbeddable('${prop.targetMeta.className}', embeddedData, { newEntity, convertCustomTypes });`);
279
+ ret.push(` entity${entityKey} = factory.createEmbeddable('${prop.targetMeta.className}', embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`);
269
280
  ret.push(` }`);
270
281
  meta.props
271
282
  .filter(p => p.embedded?.[0] === prop.name)
@@ -303,7 +314,7 @@ export class ObjectHydrator extends Hydrator {
303
314
  };
304
315
  const hydrateProperty = (prop, object = prop.object, path = [prop.name], dataKey) => {
305
316
  const entityKey = path.map(k => this.wrap(k)).join('');
306
- dataKey = dataKey ?? (object ? entityKey : this.wrap(prop.name));
317
+ dataKey = dataKey ?? (object ? entityKey : this.wrap(normalizeAccessors ? (prop.accessor ?? prop.name) : prop.name));
307
318
  const ret = [];
308
319
  if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.mapToPk) {
309
320
  ret.push(...hydrateToOne(prop, dataKey, entityKey));
@@ -333,11 +344,11 @@ export class ObjectHydrator extends Hydrator {
333
344
  for (const prop of props) {
334
345
  lines.push(...hydrateProperty(prop));
335
346
  }
336
- const code = `// compiled hydrator for entity ${meta.className} (${type})\n`
337
- + `return function(entity, data, factory, newEntity, convertCustomTypes, schema) {\n`
347
+ const code = `// compiled hydrator for entity ${meta.className} (${type + normalizeAccessors ? ' normalized' : ''})\n`
348
+ + `return function(entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors) {\n`
338
349
  + `${lines.join('\n')}\n}`;
339
350
  const hydrator = Utils.createFunction(context, code);
340
- this.hydrators[type].set(meta.className, hydrator);
351
+ this.hydrators[key].set(meta.className, hydrator);
341
352
  return hydrator;
342
353
  }
343
354
  createCollectionItemMapper(prop) {
@@ -350,9 +361,9 @@ export class ObjectHydrator extends Hydrator {
350
361
  lines.push(` value = { ...value, ['${prop2.name}']: Reference.wrapReference(entity, { ref: ${prop2.ref} }) };`);
351
362
  lines.push(` }`);
352
363
  }
353
- lines.push(` if (isPrimaryKey(value, ${meta.compositePK})) return factory.createReference('${prop.type}', value, { convertCustomTypes, schema, merge: true });`);
364
+ lines.push(` if (isPrimaryKey(value, ${meta.compositePK})) return factory.createReference('${prop.type}', value, { convertCustomTypes, schema, normalizeAccessors, merge: true });`);
354
365
  lines.push(` if (value && value.__entity) return value;`);
355
- lines.push(` return factory.create('${prop.type}', value, { newEntity, convertCustomTypes, schema, merge: true });`);
366
+ lines.push(` return factory.create('${prop.type}', value, { newEntity, convertCustomTypes, schema, normalizeAccessors, merge: true });`);
356
367
  lines.push(` }`);
357
368
  return lines;
358
369
  }
package/index.d.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  * @packageDocumentation
3
3
  * @module core
4
4
  */
5
- export { Constructor, ConnectionType, Dictionary, PrimaryKeyProp, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, EntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, EntityMetadata, QBFilterQuery, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, EntityRepositoryType, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, MigrationDiff, GenerateOptions, FilterObject, IEntityGenerator, ISeedManager, EntityClassGroup, OptionalProps, EagerProps, HiddenProps, RequiredEntityData, CheckCallback, SimpleColumnMeta, Rel, Ref, ScalarRef, EntityRef, ISchemaGenerator, UmzugMigration, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, Opt, EntityType, FromEntityType, Selected, IsSubset, NoInfer, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, Hidden, FilterValue, MergeLoaded, MergeSelected, Config, DefineConfig, TypeConfig, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, } from './typings.js';
5
+ export { EntityMetadata, PrimaryKeyProp, EntityRepositoryType, OptionalProps, EagerProps, HiddenProps, Config } from './typings.js';
6
+ export type { Constructor, ConnectionType, Dictionary, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, EntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, QBFilterQuery, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, MigrationDiff, GenerateOptions, FilterObject, IEntityGenerator, ISeedManager, EntityClassGroup, RequiredEntityData, CheckCallback, IndexCallback, SimpleColumnMeta, Rel, Ref, ScalarRef, EntityRef, ISchemaGenerator, UmzugMigration, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, EntityType, FromEntityType, Selected, IsSubset, NoInfer, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, FilterValue, MergeLoaded, MergeSelected, TypeConfig, AnyString, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, RequiredNullable, DefineConfig, Opt, Hidden, EntitySchemaWithMeta, InferEntity, } from './typings.js';
6
7
  export * from './enums.js';
7
8
  export * from './errors.js';
8
9
  export * from './exceptions.js';
package/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * @packageDocumentation
3
3
  * @module core
4
4
  */
5
- export { PrimaryKeyProp, EntityMetadata, EntityRepositoryType, OptionalProps, EagerProps, HiddenProps, Config, } from './typings.js';
5
+ export { EntityMetadata, PrimaryKeyProp, EntityRepositoryType, OptionalProps, EagerProps, HiddenProps, Config } from './typings.js';
6
6
  export * from './enums.js';
7
7
  export * from './errors.js';
8
8
  export * from './exceptions.js';
@@ -29,5 +29,5 @@ export declare class DefaultLogger implements Logger {
29
29
  logQuery(context: {
30
30
  query: string;
31
31
  } & LogContext): void;
32
- static create(options: LoggerOptions): DefaultLogger;
32
+ static create(this: void, options: LoggerOptions): DefaultLogger;
33
33
  }
@@ -14,5 +14,5 @@ export declare class SimpleLogger extends DefaultLogger {
14
14
  logQuery(context: {
15
15
  query: string;
16
16
  } & LogContext): void;
17
- static create(options: LoggerOptions): SimpleLogger;
17
+ static create(this: void, options: LoggerOptions): SimpleLogger;
18
18
  }
@@ -31,7 +31,7 @@ export type EntitySchemaProperty<Target, Owner> = ({
31
31
  kind: ReferenceKind.MANY_TO_MANY | 'm:n';
32
32
  } & TypeDef<Target> & ManyToManyOptions<Owner, Target>) | ({
33
33
  kind: ReferenceKind.EMBEDDED | 'embedded';
34
- } & EmbeddedTypeDef<Target> & EmbeddedOptions & PropertyOptions<Owner>) | ({
34
+ } & EmbeddedTypeDef<Target> & EmbeddedOptions<Owner, Target> & PropertyOptions<Owner>) | ({
35
35
  enum: true;
36
36
  } & EnumOptions<Owner>) | (TypeDef<Target> & PropertyOptions<Owner>);
37
37
  type OmitBaseProps<Entity, Base> = IsNever<Base> extends true ? Entity : Omit<Entity, keyof Base>;
@@ -41,7 +41,7 @@ export type EntitySchemaMetadata<Entity, Base = never> = Omit<Partial<EntityMeta
41
41
  class: EntityClass<Entity>;
42
42
  name?: string;
43
43
  }) & {
44
- extends?: string | EntitySchema<Base>;
44
+ extends?: EntityName<Base>;
45
45
  } & {
46
46
  properties?: {
47
47
  [Key in keyof OmitBaseProps<Entity, Base> as CleanKeys<OmitBaseProps<Entity, Base>, Key>]-?: EntitySchemaProperty<ExpandProperty<NonNullable<Entity[Key]>>, Entity>;
@@ -63,7 +63,7 @@ export declare class EntitySchema<Entity = any, Base = never> {
63
63
  addVersion(name: EntityKey<Entity>, type: TypeType, options?: PropertyOptions<Entity>): void;
64
64
  addPrimaryKey(name: EntityKey<Entity>, type: TypeType, options?: PrimaryKeyOptions<Entity>): void;
65
65
  addSerializedPrimaryKey(name: EntityKey<Entity>, type: TypeType, options?: SerializedPrimaryKeyOptions<Entity>): void;
66
- addEmbedded<Target = AnyEntity>(name: EntityKey<Entity>, options: EmbeddedOptions): void;
66
+ addEmbedded<Target = AnyEntity>(name: EntityKey<Entity>, options: EmbeddedOptions<Entity, Target>): void;
67
67
  addManyToOne<Target = AnyEntity>(name: EntityKey<Entity>, type: TypeType, options: ManyToOneOptions<Entity, Target>): void;
68
68
  addManyToMany<Target = AnyEntity>(name: EntityKey<Entity>, type: TypeType, options: ManyToManyOptions<Entity, Target>): void;
69
69
  addOneToMany<Target = AnyEntity>(name: EntityKey<Entity>, type: TypeType, options: OneToManyOptions<Entity, Target>): void;
@@ -71,10 +71,12 @@ export declare class EntitySchema<Entity = any, Base = never> {
71
71
  addIndex<Key extends string>(options: IndexOptions<Entity, Key>): void;
72
72
  addUnique<Key extends string>(options: UniqueOptions<Entity, Key>): void;
73
73
  setCustomRepository(repository: () => Constructor): void;
74
- setExtends(base: string | EntitySchema): void;
74
+ setExtends(base: EntityName<any>): void;
75
75
  setClass(proto: EntityClass<Entity>): void;
76
76
  get meta(): EntityMetadata<Entity>;
77
77
  get name(): EntityName<Entity>;
78
+ get tableName(): string;
79
+ get properties(): Record<string, any>;
78
80
  /**
79
81
  * @internal
80
82
  */
@@ -83,5 +85,7 @@ export declare class EntitySchema<Entity = any, Base = never> {
83
85
  private initPrimaryKeys;
84
86
  private normalizeType;
85
87
  private createProperty;
88
+ private rename;
89
+ private renameCompositeOptions;
86
90
  }
87
91
  export {};
@@ -34,23 +34,7 @@ export class EntitySchema {
34
34
  return schema;
35
35
  }
36
36
  addProperty(name, type, options = {}) {
37
- const rename = (data, from, to) => {
38
- if (from in options && !(to in options)) {
39
- // @ts-ignore
40
- options[to] = [options[from]];
41
- // @ts-ignore
42
- delete options[from];
43
- }
44
- };
45
- if (name !== options.name) {
46
- Utils.renameKey(options, 'name', 'fieldName');
47
- }
48
- rename(options, 'fieldName', 'fieldNames');
49
- rename(options, 'ref', 'ref');
50
- rename(options, 'joinColumn', 'joinColumns');
51
- rename(options, 'inverseJoinColumn', 'inverseJoinColumns');
52
- rename(options, 'referenceColumnName', 'referencedColumnNames');
53
- rename(options, 'columnType', 'columnTypes');
37
+ this.renameCompositeOptions(name, options);
54
38
  const prop = { name, kind: ReferenceKind.SCALAR, ...options, type: this.normalizeType(options, type) };
55
39
  if (type && Type.isMappedType(type.prototype)) {
56
40
  prop.type = type;
@@ -94,6 +78,7 @@ export class EntitySchema {
94
78
  this.addProperty(name, type, options);
95
79
  }
96
80
  addEmbedded(name, options) {
81
+ this.renameCompositeOptions(name, options);
97
82
  Utils.defaultValue(options, 'prefix', true);
98
83
  if (options.array) {
99
84
  options.object = true; // force object mode for arrays
@@ -114,6 +99,8 @@ export class EntitySchema {
114
99
  if (prop.fieldNames && !prop.joinColumns) {
115
100
  prop.joinColumns = prop.fieldNames;
116
101
  }
102
+ // By default, the foreign key constraint is created on the relation
103
+ Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
117
104
  this.addProperty(name, type, prop);
118
105
  }
119
106
  addManyToMany(name, type, options) {
@@ -123,6 +110,8 @@ export class EntitySchema {
123
110
  }
124
111
  if (options.owner) {
125
112
  Utils.renameKey(options, 'mappedBy', 'inversedBy');
113
+ // By default, the foreign key constraint is created on the relation
114
+ Utils.defaultValue(options, 'createForeignKeyConstraint', true);
126
115
  }
127
116
  const prop = this.createProperty(ReferenceKind.MANY_TO_MANY, options);
128
117
  this.addProperty(name, type, prop);
@@ -135,8 +124,12 @@ export class EntitySchema {
135
124
  const prop = this.createProperty(ReferenceKind.ONE_TO_ONE, options);
136
125
  Utils.defaultValue(prop, 'owner', !!prop.inversedBy || !prop.mappedBy);
137
126
  Utils.defaultValue(prop, 'unique', prop.owner);
138
- if (prop.owner && options.mappedBy) {
139
- Utils.renameKey(prop, 'mappedBy', 'inversedBy');
127
+ if (prop.owner) {
128
+ if (options.mappedBy) {
129
+ Utils.renameKey(prop, 'mappedBy', 'inversedBy');
130
+ }
131
+ // By default, the foreign key constraint is created on the relation
132
+ Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
140
133
  }
141
134
  if (prop.joinColumns && !prop.fieldNames) {
142
135
  prop.fieldNames = prop.joinColumns;
@@ -181,6 +174,12 @@ export class EntitySchema {
181
174
  get name() {
182
175
  return this._meta.className;
183
176
  }
177
+ get tableName() {
178
+ return this._meta.tableName;
179
+ }
180
+ get properties() {
181
+ return this._meta.properties;
182
+ }
184
183
  /**
185
184
  * @internal
186
185
  */
@@ -289,4 +288,25 @@ export class EntitySchema {
289
288
  ...options,
290
289
  };
291
290
  }
291
+ rename(data, from, to) {
292
+ if (from in data && !(to in data)) {
293
+ // @ts-ignore
294
+ data[to] = [data[from]];
295
+ // @ts-ignore
296
+ delete data[from];
297
+ }
298
+ }
299
+ renameCompositeOptions(name, options = {}) {
300
+ if (name !== options.name && !options.fieldNames) {
301
+ Utils.renameKey(options, 'name', 'fieldName');
302
+ }
303
+ else if (options.name && (options.fieldNames?.length ?? 0) > 1) {
304
+ delete options.name;
305
+ }
306
+ this.rename(options, 'fieldName', 'fieldNames');
307
+ this.rename(options, 'joinColumn', 'joinColumns');
308
+ this.rename(options, 'inverseJoinColumn', 'inverseJoinColumns');
309
+ this.rename(options, 'referenceColumnName', 'referencedColumnNames');
310
+ this.rename(options, 'columnType', 'columnTypes');
311
+ }
292
312
  }
@@ -18,6 +18,7 @@ export declare class MetadataDiscovery {
18
18
  discover(preferTs?: boolean): Promise<MetadataStorage>;
19
19
  discoverSync(preferTs?: boolean): MetadataStorage;
20
20
  private mapDiscoveredEntities;
21
+ private initAccessors;
21
22
  processDiscoveredEntities(discovered: EntityMetadata[]): EntityMetadata[];
22
23
  private findEntities;
23
24
  private discoverMissingTargets;
@@ -54,7 +55,6 @@ export declare class MetadataDiscovery {
54
55
  private initAutoincrement;
55
56
  private initCheckConstraints;
56
57
  private initGeneratedColumn;
57
- private createColumnMappingObject;
58
58
  private getDefaultVersionValue;
59
59
  private inferDefaultValue;
60
60
  private initDefaultValue;