@mikro-orm/core 7.0.0-dev.19 → 7.0.0-dev.190

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 (211) hide show
  1. package/EntityManager.d.ts +99 -57
  2. package/EntityManager.js +302 -276
  3. package/MikroORM.d.ts +44 -35
  4. package/MikroORM.js +103 -143
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +8 -7
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +0 -1
  11. package/cache/index.js +0 -1
  12. package/connections/Connection.d.ts +16 -7
  13. package/connections/Connection.js +23 -14
  14. package/drivers/DatabaseDriver.d.ts +25 -16
  15. package/drivers/DatabaseDriver.js +80 -35
  16. package/drivers/IDatabaseDriver.d.ts +44 -17
  17. package/entity/BaseEntity.d.ts +2 -2
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +94 -29
  20. package/entity/Collection.js +434 -97
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +26 -18
  23. package/entity/EntityFactory.d.ts +13 -1
  24. package/entity/EntityFactory.js +84 -53
  25. package/entity/EntityHelper.d.ts +2 -2
  26. package/entity/EntityHelper.js +35 -15
  27. package/entity/EntityLoader.d.ts +6 -6
  28. package/entity/EntityLoader.js +117 -77
  29. package/entity/EntityRepository.d.ts +24 -4
  30. package/entity/EntityRepository.js +8 -2
  31. package/entity/Reference.d.ts +6 -5
  32. package/entity/Reference.js +34 -9
  33. package/entity/WrappedEntity.d.ts +2 -7
  34. package/entity/WrappedEntity.js +3 -8
  35. package/entity/defineEntity.d.ts +585 -0
  36. package/entity/defineEntity.js +533 -0
  37. package/entity/index.d.ts +3 -2
  38. package/entity/index.js +3 -2
  39. package/entity/utils.d.ts +7 -0
  40. package/entity/utils.js +16 -4
  41. package/entity/validators.d.ts +11 -0
  42. package/entity/validators.js +65 -0
  43. package/enums.d.ts +21 -5
  44. package/enums.js +15 -1
  45. package/errors.d.ts +23 -9
  46. package/errors.js +59 -21
  47. package/events/EventManager.d.ts +2 -1
  48. package/events/EventManager.js +19 -11
  49. package/hydration/Hydrator.js +1 -2
  50. package/hydration/ObjectHydrator.d.ts +4 -4
  51. package/hydration/ObjectHydrator.js +52 -33
  52. package/index.d.ts +2 -2
  53. package/index.js +1 -2
  54. package/logging/DefaultLogger.d.ts +1 -1
  55. package/logging/DefaultLogger.js +1 -0
  56. package/logging/SimpleLogger.d.ts +1 -1
  57. package/logging/colors.d.ts +1 -1
  58. package/logging/colors.js +7 -6
  59. package/logging/index.d.ts +1 -0
  60. package/logging/index.js +1 -0
  61. package/logging/inspect.d.ts +2 -0
  62. package/logging/inspect.js +11 -0
  63. package/metadata/EntitySchema.d.ts +20 -22
  64. package/metadata/EntitySchema.js +59 -34
  65. package/metadata/MetadataDiscovery.d.ts +7 -10
  66. package/metadata/MetadataDiscovery.js +396 -331
  67. package/metadata/MetadataProvider.d.ts +11 -2
  68. package/metadata/MetadataProvider.js +46 -2
  69. package/metadata/MetadataStorage.d.ts +13 -11
  70. package/metadata/MetadataStorage.js +70 -37
  71. package/metadata/MetadataValidator.d.ts +17 -9
  72. package/metadata/MetadataValidator.js +97 -40
  73. package/metadata/discover-entities.d.ts +5 -0
  74. package/metadata/discover-entities.js +40 -0
  75. package/metadata/index.d.ts +1 -1
  76. package/metadata/index.js +1 -1
  77. package/metadata/types.d.ts +502 -0
  78. package/metadata/types.js +1 -0
  79. package/naming-strategy/AbstractNamingStrategy.d.ts +8 -4
  80. package/naming-strategy/AbstractNamingStrategy.js +8 -2
  81. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  82. package/naming-strategy/EntityCaseNamingStrategy.js +6 -5
  83. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  84. package/naming-strategy/MongoNamingStrategy.js +6 -6
  85. package/naming-strategy/NamingStrategy.d.ts +14 -4
  86. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  87. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  88. package/not-supported.d.ts +2 -0
  89. package/not-supported.js +4 -0
  90. package/package.json +18 -11
  91. package/platforms/ExceptionConverter.js +1 -1
  92. package/platforms/Platform.d.ts +7 -13
  93. package/platforms/Platform.js +20 -43
  94. package/serialization/EntitySerializer.d.ts +5 -0
  95. package/serialization/EntitySerializer.js +47 -27
  96. package/serialization/EntityTransformer.js +28 -18
  97. package/serialization/SerializationContext.d.ts +6 -6
  98. package/serialization/SerializationContext.js +16 -13
  99. package/types/ArrayType.d.ts +1 -1
  100. package/types/ArrayType.js +2 -3
  101. package/types/BigIntType.d.ts +8 -6
  102. package/types/BigIntType.js +1 -1
  103. package/types/BlobType.d.ts +0 -1
  104. package/types/BlobType.js +0 -3
  105. package/types/BooleanType.d.ts +2 -1
  106. package/types/BooleanType.js +3 -0
  107. package/types/DecimalType.d.ts +6 -4
  108. package/types/DecimalType.js +3 -3
  109. package/types/DoubleType.js +2 -2
  110. package/types/EnumArrayType.js +1 -2
  111. package/types/JsonType.d.ts +1 -1
  112. package/types/JsonType.js +7 -2
  113. package/types/TinyIntType.js +1 -1
  114. package/types/Type.d.ts +2 -4
  115. package/types/Type.js +3 -3
  116. package/types/Uint8ArrayType.d.ts +0 -1
  117. package/types/Uint8ArrayType.js +1 -4
  118. package/types/index.d.ts +1 -1
  119. package/typings.d.ts +221 -124
  120. package/typings.js +59 -44
  121. package/unit-of-work/ChangeSet.d.ts +2 -6
  122. package/unit-of-work/ChangeSet.js +4 -5
  123. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  124. package/unit-of-work/ChangeSetComputer.js +26 -13
  125. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  126. package/unit-of-work/ChangeSetPersister.js +70 -34
  127. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  128. package/unit-of-work/CommitOrderCalculator.js +13 -13
  129. package/unit-of-work/IdentityMap.d.ts +12 -0
  130. package/unit-of-work/IdentityMap.js +39 -1
  131. package/unit-of-work/UnitOfWork.d.ts +23 -3
  132. package/unit-of-work/UnitOfWork.js +175 -98
  133. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  134. package/utils/AbstractSchemaGenerator.js +18 -16
  135. package/utils/AsyncContext.d.ts +6 -0
  136. package/utils/AsyncContext.js +42 -0
  137. package/utils/Configuration.d.ts +764 -207
  138. package/utils/Configuration.js +146 -190
  139. package/utils/ConfigurationLoader.d.ts +1 -54
  140. package/utils/ConfigurationLoader.js +1 -352
  141. package/utils/Cursor.d.ts +0 -3
  142. package/utils/Cursor.js +27 -11
  143. package/utils/DataloaderUtils.d.ts +15 -5
  144. package/utils/DataloaderUtils.js +64 -30
  145. package/utils/EntityComparator.d.ts +13 -9
  146. package/utils/EntityComparator.js +101 -42
  147. package/utils/QueryHelper.d.ts +14 -6
  148. package/utils/QueryHelper.js +87 -25
  149. package/utils/RawQueryFragment.d.ts +48 -25
  150. package/utils/RawQueryFragment.js +66 -70
  151. package/utils/RequestContext.js +2 -2
  152. package/utils/TransactionContext.js +2 -2
  153. package/utils/TransactionManager.d.ts +65 -0
  154. package/utils/TransactionManager.js +223 -0
  155. package/utils/Utils.d.ts +13 -126
  156. package/utils/Utils.js +100 -391
  157. package/utils/clone.js +8 -23
  158. package/utils/env-vars.d.ts +7 -0
  159. package/utils/env-vars.js +97 -0
  160. package/utils/fs-utils.d.ts +32 -0
  161. package/utils/fs-utils.js +178 -0
  162. package/utils/index.d.ts +2 -1
  163. package/utils/index.js +2 -1
  164. package/utils/upsert-utils.d.ts +9 -4
  165. package/utils/upsert-utils.js +55 -4
  166. package/decorators/Check.d.ts +0 -3
  167. package/decorators/Check.js +0 -13
  168. package/decorators/CreateRequestContext.d.ts +0 -3
  169. package/decorators/CreateRequestContext.js +0 -32
  170. package/decorators/Embeddable.d.ts +0 -8
  171. package/decorators/Embeddable.js +0 -11
  172. package/decorators/Embedded.d.ts +0 -12
  173. package/decorators/Embedded.js +0 -18
  174. package/decorators/Entity.d.ts +0 -18
  175. package/decorators/Entity.js +0 -12
  176. package/decorators/Enum.d.ts +0 -9
  177. package/decorators/Enum.js +0 -16
  178. package/decorators/Filter.d.ts +0 -2
  179. package/decorators/Filter.js +0 -8
  180. package/decorators/Formula.d.ts +0 -4
  181. package/decorators/Formula.js +0 -15
  182. package/decorators/Indexed.d.ts +0 -19
  183. package/decorators/Indexed.js +0 -20
  184. package/decorators/ManyToMany.d.ts +0 -40
  185. package/decorators/ManyToMany.js +0 -14
  186. package/decorators/ManyToOne.d.ts +0 -32
  187. package/decorators/ManyToOne.js +0 -14
  188. package/decorators/OneToMany.d.ts +0 -28
  189. package/decorators/OneToMany.js +0 -17
  190. package/decorators/OneToOne.d.ts +0 -26
  191. package/decorators/OneToOne.js +0 -7
  192. package/decorators/PrimaryKey.d.ts +0 -8
  193. package/decorators/PrimaryKey.js +0 -20
  194. package/decorators/Property.d.ts +0 -250
  195. package/decorators/Property.js +0 -32
  196. package/decorators/Transactional.d.ts +0 -13
  197. package/decorators/Transactional.js +0 -28
  198. package/decorators/hooks.d.ts +0 -16
  199. package/decorators/hooks.js +0 -47
  200. package/decorators/index.d.ts +0 -17
  201. package/decorators/index.js +0 -17
  202. package/entity/ArrayCollection.d.ts +0 -116
  203. package/entity/ArrayCollection.js +0 -402
  204. package/entity/EntityValidator.d.ts +0 -19
  205. package/entity/EntityValidator.js +0 -150
  206. package/exports.d.ts +0 -24
  207. package/exports.js +0 -23
  208. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  209. package/metadata/ReflectMetadataProvider.js +0 -44
  210. package/utils/resolveContextProvider.d.ts +0 -10
  211. package/utils/resolveContextProvider.js +0 -28
@@ -3,40 +3,43 @@ import { Collection } from '../entity/Collection.js';
3
3
  import { Reference, ScalarReference } from '../entity/Reference.js';
4
4
  import { parseJsonSafe, Utils } from '../utils/Utils.js';
5
5
  import { ReferenceKind } from '../enums.js';
6
- import { RawQueryFragment } from '../utils/RawQueryFragment.js';
6
+ import { Raw } 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.class);
40
43
  if (exists) {
41
44
  return exists;
42
45
  }
@@ -48,22 +51,22 @@ export class ObjectHydrator extends Hydrator {
48
51
  context.set('Reference', Reference);
49
52
  const registerCustomType = (prop, convertorKey, method, context) => {
50
53
  context.set(`${method}_${convertorKey}`, (val) => {
51
- /* v8 ignore next 3 */
52
- if (RawQueryFragment.isKnownFragment(val)) {
54
+ /* v8 ignore next */
55
+ if (Raw.isKnownFragment(val)) {
53
56
  return val;
54
57
  }
55
58
  return prop.customType[method](val, this.platform, { mode: 'serialization' });
56
59
  });
57
60
  return convertorKey;
58
61
  };
59
- const hydrateScalar = (prop, object, path, dataKey) => {
62
+ const hydrateScalar = (prop, path, dataKey) => {
60
63
  const entityKey = path.map(k => this.wrap(k)).join('');
61
64
  const tz = this.platform.getTimezone();
62
65
  const convertorKey = path.filter(k => !k.match(/\[idx_\d+]/)).map(k => this.safeKey(k)).join('_');
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);
@@ -125,23 +135,27 @@ export class ObjectHydrator extends Hydrator {
125
135
  ret.push(` if (data${dataKey} === null) {\n entity${entityKey} = ${nullVal};`);
126
136
  ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
127
137
  ret.push(` if (isPrimaryKey(data${dataKey}, true)) {`);
138
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.tmpIndex++}`);
139
+ context.set(targetKey, prop.targetMeta.class);
140
+ // When targetKey is set, pass the key option to createReference so it uses the alternate key
141
+ const keyOption = prop.targetKey ? `, key: '${prop.targetKey}'` : '';
128
142
  if (prop.ref) {
129
- ret.push(` entity${entityKey} = Reference.create(factory.createReference('${prop.type}', data${dataKey}, { merge: true, convertCustomTypes, schema }));`);
143
+ ret.push(` entity${entityKey} = Reference.create(factory.createReference(${targetKey}, data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} }));`);
130
144
  }
131
145
  else {
132
- ret.push(` entity${entityKey} = factory.createReference('${prop.type}', data${dataKey}, { merge: true, convertCustomTypes, schema });`);
146
+ ret.push(` entity${entityKey} = factory.createReference(${targetKey}, data${dataKey}, { merge: true, convertCustomTypes, normalizeAccessors, schema${keyOption} });`);
133
147
  }
134
148
  ret.push(` } else if (data${dataKey} && typeof data${dataKey} === 'object') {`);
135
149
  if (prop.ref) {
136
- ret.push(` entity${entityKey} = Reference.create(factory.${method}('${prop.type}', data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, schema }));`);
150
+ ret.push(` entity${entityKey} = Reference.create(factory.${method}(${targetKey}, data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema }));`);
137
151
  }
138
152
  else {
139
- ret.push(` entity${entityKey} = factory.${method}('${prop.type}', data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, schema });`);
153
+ ret.push(` entity${entityKey} = factory.${method}(${targetKey}, data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, normalizeAccessors, schema });`);
140
154
  }
141
155
  ret.push(` }`);
142
156
  ret.push(` }`);
143
157
  if (prop.kind === ReferenceKind.ONE_TO_ONE) {
144
- const meta2 = this.metadata.get(prop.type);
158
+ const meta2 = this.metadata.get(prop.targetMeta.class);
145
159
  const prop2 = meta2.properties[prop.inversedBy || prop.mappedBy];
146
160
  if (prop2 && !prop2.mapToPk) {
147
161
  ret.push(` if (data${dataKey} && entity${entityKey} && !entity${entityKey}.${this.safeKey(prop2.name)}) {`);
@@ -159,7 +173,7 @@ export class ObjectHydrator extends Hydrator {
159
173
  };
160
174
  const hydrateToMany = (prop, dataKey, entityKey) => {
161
175
  const ret = [];
162
- ret.push(...this.createCollectionItemMapper(prop));
176
+ ret.push(...this.createCollectionItemMapper(prop, context));
163
177
  ret.push(` if (data${dataKey} && !Array.isArray(data${dataKey}) && typeof data${dataKey} === 'object') {`);
164
178
  ret.push(` data${dataKey} = [data${dataKey}];`);
165
179
  ret.push(` }`);
@@ -242,10 +256,11 @@ export class ObjectHydrator extends Hydrator {
242
256
  prop.targetMeta.polymorphs.forEach(childMeta => {
243
257
  const childProp = prop.embeddedProps[prop.targetMeta.discriminatorColumn];
244
258
  const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded[1]) : this.wrap(childProp.name);
259
+ context.set(childMeta.className, childMeta.class);
245
260
  // weak comparison as we can have numbers that might have been converted to strings due to being object keys
246
261
  ret.push(` if (data${childDataKey} == '${childMeta.discriminatorValue}') {`);
247
262
  ret.push(` if (entity${entityKey} == null) {`);
248
- ret.push(` entity${entityKey} = factory.createEmbeddable('${childMeta.className}', embeddedData, { newEntity, convertCustomTypes });`);
263
+ ret.push(` entity${entityKey} = factory.createEmbeddable(${childMeta.className}, embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`);
249
264
  ret.push(` }`);
250
265
  meta.props
251
266
  .filter(p => p.embedded?.[0] === prop.name)
@@ -265,8 +280,10 @@ export class ObjectHydrator extends Hydrator {
265
280
  });
266
281
  }
267
282
  else {
283
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.tmpIndex++}`);
284
+ context.set(targetKey, prop.targetMeta.class);
268
285
  ret.push(` if (entity${entityKey} == null) {`);
269
- ret.push(` entity${entityKey} = factory.createEmbeddable('${prop.targetMeta.className}', embeddedData, { newEntity, convertCustomTypes });`);
286
+ ret.push(` entity${entityKey} = factory.createEmbeddable(${targetKey}, embeddedData, { newEntity, convertCustomTypes, normalizeAccessors });`);
270
287
  ret.push(` }`);
271
288
  meta.props
272
289
  .filter(p => p.embedded?.[0] === prop.name)
@@ -304,7 +321,7 @@ export class ObjectHydrator extends Hydrator {
304
321
  };
305
322
  const hydrateProperty = (prop, object = prop.object, path = [prop.name], dataKey) => {
306
323
  const entityKey = path.map(k => this.wrap(k)).join('');
307
- dataKey = dataKey ?? (object ? entityKey : this.wrap(prop.name));
324
+ dataKey = dataKey ?? (object ? entityKey : this.wrap(normalizeAccessors ? (prop.accessor ?? prop.name) : prop.name));
308
325
  const ret = [];
309
326
  if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.mapToPk) {
310
327
  ret.push(...hydrateToOne(prop, dataKey, entityKey));
@@ -324,7 +341,7 @@ export class ObjectHydrator extends Hydrator {
324
341
  }
325
342
  }
326
343
  else { // ReferenceKind.SCALAR
327
- ret.push(...hydrateScalar(prop, object, path, dataKey));
344
+ ret.push(...hydrateScalar(prop, path, dataKey));
328
345
  }
329
346
  if (this.config.get('forceUndefined')) {
330
347
  ret.push(` if (data${dataKey} === null) entity${entityKey} = undefined;`);
@@ -334,15 +351,15 @@ export class ObjectHydrator extends Hydrator {
334
351
  for (const prop of props) {
335
352
  lines.push(...hydrateProperty(prop));
336
353
  }
337
- const code = `// compiled hydrator for entity ${meta.className} (${type})\n`
338
- + `return function(entity, data, factory, newEntity, convertCustomTypes, schema) {\n`
354
+ const code = `// compiled hydrator for entity ${meta.className} (${type + normalizeAccessors ? ' normalized' : ''})\n`
355
+ + `return function(entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors) {\n`
339
356
  + `${lines.join('\n')}\n}`;
340
357
  const hydrator = Utils.createFunction(context, code);
341
- this.hydrators[type].set(meta.className, hydrator);
358
+ this.hydrators[key].set(meta.class, hydrator);
342
359
  return hydrator;
343
360
  }
344
- createCollectionItemMapper(prop) {
345
- const meta = this.metadata.get(prop.type);
361
+ createCollectionItemMapper(prop, context) {
362
+ const meta = this.metadata.get(prop.targetMeta.class);
346
363
  const lines = [];
347
364
  lines.push(` const createCollectionItem_${this.safeKey(prop.name)} = (value, entity) => {`);
348
365
  const prop2 = prop.targetMeta.properties[prop.mappedBy];
@@ -351,9 +368,11 @@ export class ObjectHydrator extends Hydrator {
351
368
  lines.push(` value = { ...value, ['${prop2.name}']: Reference.wrapReference(entity, { ref: ${prop2.ref} }) };`);
352
369
  lines.push(` }`);
353
370
  }
354
- lines.push(` if (isPrimaryKey(value, ${meta.compositePK})) return factory.createReference('${prop.type}', value, { convertCustomTypes, schema, merge: true });`);
371
+ const targetKey = this.safeKey(`${prop.targetMeta.tableName}_${this.tmpIndex++}`);
372
+ context.set(targetKey, prop.targetMeta.class);
373
+ lines.push(` if (isPrimaryKey(value, ${meta.compositePK})) return factory.createReference(${targetKey}, value, { convertCustomTypes, schema, normalizeAccessors, merge: true });`);
355
374
  lines.push(` if (value && value.__entity) return value;`);
356
- lines.push(` return factory.create('${prop.type}', value, { newEntity, convertCustomTypes, schema, merge: true });`);
375
+ lines.push(` return factory.create(${targetKey}, value, { newEntity, convertCustomTypes, schema, normalizeAccessors, merge: true });`);
357
376
  lines.push(` }`);
358
377
  return lines;
359
378
  }
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, RequiredEntityData, CheckCallback, IndexCallback, FormulaCallback, FormulaTable, 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, CheckConstraint, GeneratedColumnCallback, FilterDef, EntityCtor, } from './typings.js';
6
7
  export * from './enums.js';
7
8
  export * from './errors.js';
8
9
  export * from './exceptions.js';
@@ -22,4 +23,3 @@ export * from './types/index.js';
22
23
  export * from './naming-strategy/index.js';
23
24
  export * from './metadata/index.js';
24
25
  export * from './cache/index.js';
25
- export * from './decorators/index.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';
@@ -22,4 +22,3 @@ export * from './types/index.js';
22
22
  export * from './naming-strategy/index.js';
23
23
  export * from './metadata/index.js';
24
24
  export * from './cache/index.js';
25
- export * from './decorators/index.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
  }
@@ -60,6 +60,7 @@ export class DefaultLogger {
60
60
  if (namespace === 'deprecated') {
61
61
  const { ignoreDeprecations = false } = this.options;
62
62
  return Array.isArray(ignoreDeprecations)
63
+ /* v8 ignore next */
63
64
  ? !ignoreDeprecations.includes(context?.label ?? '')
64
65
  : !ignoreDeprecations;
65
66
  }
@@ -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
  }
@@ -5,5 +5,5 @@ export declare const colors: {
5
5
  yellow: (text: string) => string;
6
6
  grey: (text: string) => string;
7
7
  cyan: (text: string) => string;
8
- enabled: () => boolean | "" | undefined;
8
+ enabled: () => boolean;
9
9
  };
package/logging/colors.js CHANGED
@@ -1,9 +1,10 @@
1
- const bool = (v) => v && ['true', 't', '1'].includes(v.toLowerCase());
2
- const boolIfDefined = (v) => v != null ? bool(v) : true;
3
- const enabled = () => !bool(process.env.NO_COLOR)
4
- && !bool(process.env.MIKRO_ORM_NO_COLOR)
5
- && boolIfDefined(process.env.FORCE_COLOR)
6
- && boolIfDefined(process.env.MIKRO_ORM_COLORS);
1
+ import { getEnv } from '../utils/env-vars.js';
2
+ const bool = (k) => ['true', 't', '1'].includes(getEnv(k)?.toLowerCase() ?? '');
3
+ const boolIfDefined = (k) => getEnv(k) != null ? bool(k) : true;
4
+ const enabled = () => !bool('NO_COLOR')
5
+ && !bool('MIKRO_ORM_NO_COLOR')
6
+ && boolIfDefined('FORCE_COLOR')
7
+ && boolIfDefined('MIKRO_ORM_COLORS');
7
8
  const wrap = (fn) => (text) => enabled() ? fn(text) : text;
8
9
  /** @internal */
9
10
  export const colors = {
@@ -2,3 +2,4 @@ export * from './colors.js';
2
2
  export * from './Logger.js';
3
3
  export * from './DefaultLogger.js';
4
4
  export * from './SimpleLogger.js';
5
+ export * from './inspect.js';
package/logging/index.js CHANGED
@@ -2,3 +2,4 @@ export * from './colors.js';
2
2
  export * from './Logger.js';
3
3
  export * from './DefaultLogger.js';
4
4
  export * from './SimpleLogger.js';
5
+ export * from './inspect.js';
@@ -0,0 +1,2 @@
1
+ /** @internal */
2
+ export declare function inspect(value: unknown, options?: Record<string, any>): string;
@@ -0,0 +1,11 @@
1
+ let nodeInspect;
2
+ /** @internal */
3
+ export function inspect(value, options) {
4
+ nodeInspect ??= globalThis.process?.getBuiltinModule?.('node:util').inspect;
5
+ /* v8 ignore else */
6
+ if (nodeInspect) {
7
+ return nodeInspect(value, options);
8
+ }
9
+ /* v8 ignore next */
10
+ return JSON.stringify(value, null, 2);
11
+ }
@@ -1,25 +1,17 @@
1
- import { EntityMetadata, type AnyEntity, type EntityKey, type Constructor, type DeepPartial, type EntityName, type EntityProperty, type CleanKeys, type ExpandProperty, type IsNever, type EntityClass } from '../typings.js';
2
- import type { EmbeddedOptions } from '../decorators/Embedded.js';
3
- import type { EnumOptions } from '../decorators/Enum.js';
4
- import type { IndexOptions, UniqueOptions } from '../decorators/Indexed.js';
5
- import type { ManyToManyOptions } from '../decorators/ManyToMany.js';
6
- import type { ManyToOneOptions } from '../decorators/ManyToOne.js';
7
- import type { OneToManyOptions } from '../decorators/OneToMany.js';
8
- import type { OneToOneOptions } from '../decorators/OneToOne.js';
9
- import type { PrimaryKeyOptions, SerializedPrimaryKeyOptions } from '../decorators/PrimaryKey.js';
10
- import type { PropertyOptions } from '../decorators/Property.js';
1
+ import { EntityMetadata, type AnyEntity, type EntityKey, type Constructor, type DeepPartial, type EntityName, type EntityProperty, type CleanKeys, type ExpandProperty, type IsNever, type EntityCtor } from '../typings.js';
11
2
  import { ReferenceKind } from '../enums.js';
12
3
  import { Type } from '../types/Type.js';
4
+ import type { PropertyOptions, ManyToOneOptions, OneToOneOptions, OneToManyOptions, ManyToManyOptions, EmbeddedOptions, EnumOptions, PrimaryKeyOptions, SerializedPrimaryKeyOptions, IndexOptions, UniqueOptions } from './types.js';
13
5
  type TypeType = string | NumberConstructor | StringConstructor | BooleanConstructor | DateConstructor | ArrayConstructor | Constructor<Type<any>> | Type<any>;
14
6
  type TypeDef<Target> = {
15
7
  type: TypeType;
16
8
  } | {
17
- entity: string | (() => string | EntityName<Target>);
9
+ entity: () => EntityName<Target>;
18
10
  };
19
11
  type EmbeddedTypeDef<Target> = {
20
12
  type: TypeType;
21
13
  } | {
22
- entity: string | (() => string | EntityName<Target> | EntityName<Target>[]);
14
+ entity: () => EntityName<Target> | EntityName[];
23
15
  };
24
16
  export type EntitySchemaProperty<Target, Owner> = ({
25
17
  kind: ReferenceKind.MANY_TO_ONE | 'm:1';
@@ -35,28 +27,30 @@ export type EntitySchemaProperty<Target, Owner> = ({
35
27
  enum: true;
36
28
  } & EnumOptions<Owner>) | (TypeDef<Target> & PropertyOptions<Owner>);
37
29
  type OmitBaseProps<Entity, Base> = IsNever<Base> extends true ? Entity : Omit<Entity, keyof Base>;
38
- export type EntitySchemaMetadata<Entity, Base = never> = Omit<Partial<EntityMetadata<Entity>>, 'name' | 'properties' | 'extends'> & ({
30
+ export type EntitySchemaMetadata<Entity, Base = never, Class extends EntityCtor = EntityCtor<Entity>> = Omit<Partial<EntityMetadata<Entity>>, 'name' | 'properties' | 'extends'> & ({
39
31
  name: string;
40
32
  } | {
41
- class: EntityClass<Entity>;
33
+ class: Class;
42
34
  name?: string;
43
35
  }) & {
44
- extends?: string | EntitySchema<Base>;
36
+ extends?: EntityName<Base>;
45
37
  } & {
46
38
  properties?: {
47
39
  [Key in keyof OmitBaseProps<Entity, Base> as CleanKeys<OmitBaseProps<Entity, Base>, Key>]-?: EntitySchemaProperty<ExpandProperty<NonNullable<Entity[Key]>>, Entity>;
48
40
  };
49
41
  };
50
- export declare class EntitySchema<Entity = any, Base = never> {
42
+ export declare class EntitySchema<Entity = any, Base = never, Class extends EntityCtor = EntityCtor<Entity>> {
51
43
  /**
52
44
  * When schema links the entity class via `class` option, this registry allows the lookup from opposite side,
53
45
  * so we can use the class in `entities` option just like the EntitySchema instance.
54
46
  */
55
- static REGISTRY: Map<Partial<any>, EntitySchema<any, never>>;
47
+ static REGISTRY: Map<Partial<any>, EntitySchema<any, never, EntityCtor<any>>>;
48
+ /** @internal Type-level marker for fast entity type inference */
49
+ readonly '~entity': Entity;
56
50
  private readonly _meta;
57
51
  private internal;
58
52
  private initialized;
59
- constructor(meta: EntitySchemaMetadata<Entity, Base>);
53
+ constructor(meta: EntitySchemaMetadata<Entity, Base, Class>);
60
54
  static fromMetadata<T = AnyEntity, U = never>(meta: EntityMetadata<T> | DeepPartial<EntityMetadata<T>>): EntitySchema<T, U>;
61
55
  addProperty(name: EntityKey<Entity>, type?: TypeType, options?: PropertyOptions<Entity> | EntityProperty<Entity>): void;
62
56
  addEnum(name: EntityKey<Entity>, type?: TypeType, options?: EnumOptions<Entity>): void;
@@ -71,10 +65,14 @@ export declare class EntitySchema<Entity = any, Base = never> {
71
65
  addIndex<Key extends string>(options: IndexOptions<Entity, Key>): void;
72
66
  addUnique<Key extends string>(options: UniqueOptions<Entity, Key>): void;
73
67
  setCustomRepository(repository: () => Constructor): void;
74
- setExtends(base: string | EntitySchema): void;
75
- setClass(proto: EntityClass<Entity>): void;
76
- get meta(): EntityMetadata<Entity>;
77
- get name(): EntityName<Entity>;
68
+ setExtends(base: EntityName): void;
69
+ setClass(cls: Class): void;
70
+ get meta(): EntityMetadata<Entity, Class>;
71
+ get name(): string | EntityName<Entity>;
72
+ get tableName(): string;
73
+ get class(): Class;
74
+ get properties(): Record<string, any>;
75
+ new(...params: ConstructorParameters<Class>): Entity;
78
76
  /**
79
77
  * @internal
80
78
  */
@@ -10,7 +10,7 @@ export class EntitySchema {
10
10
  * so we can use the class in `entities` option just like the EntitySchema instance.
11
11
  */
12
12
  static REGISTRY = new Map();
13
- _meta = new EntityMetadata();
13
+ _meta;
14
14
  internal = false;
15
15
  initialized = false;
16
16
  constructor(meta) {
@@ -18,15 +18,14 @@ export class EntitySchema {
18
18
  if (meta.name) {
19
19
  meta.abstract ??= false;
20
20
  }
21
+ this._meta = new EntityMetadata({
22
+ className: meta.name,
23
+ ...meta,
24
+ });
25
+ this._meta.root ??= this._meta;
21
26
  if (meta.class && !meta.internal) {
22
27
  EntitySchema.REGISTRY.set(meta.class, this);
23
28
  }
24
- if (meta.tableName || meta.collection) {
25
- Utils.renameKey(meta, 'tableName', 'collection');
26
- meta.tableName = meta.collection;
27
- }
28
- Object.assign(this._meta, { className: meta.name }, meta);
29
- this._meta.root ??= this._meta;
30
29
  }
31
30
  static fromMetadata(meta) {
32
31
  const schema = new EntitySchema({ ...meta, internal: true });
@@ -35,12 +34,12 @@ export class EntitySchema {
35
34
  }
36
35
  addProperty(name, type, options = {}) {
37
36
  this.renameCompositeOptions(name, options);
38
- const prop = { name, kind: ReferenceKind.SCALAR, ...options, type: this.normalizeType(options, type) };
37
+ const prop = { name, kind: ReferenceKind.SCALAR, ...options, ...this.normalizeType(options, type) };
39
38
  if (type && Type.isMappedType(type.prototype)) {
40
39
  prop.type = type;
41
40
  }
42
- if (Utils.isString(prop.formula)) {
43
- const formula = prop.formula; // tmp var is needed here
41
+ if (typeof prop.formula === 'string') {
42
+ const formula = prop.formula;
44
43
  prop.formula = () => formula;
45
44
  }
46
45
  if (prop.formula) {
@@ -75,7 +74,7 @@ export class EntitySchema {
75
74
  }
76
75
  addSerializedPrimaryKey(name, type, options = {}) {
77
76
  this._meta.serializedPrimaryKey = name;
78
- this.addProperty(name, type, options);
77
+ this.addProperty(name, type, { serializedPrimaryKey: true, ...options });
79
78
  }
80
79
  addEmbedded(name, options) {
81
80
  this.renameCompositeOptions(name, options);
@@ -85,8 +84,8 @@ export class EntitySchema {
85
84
  }
86
85
  this._meta.properties[name] = {
87
86
  name,
88
- type: this.normalizeType(options),
89
87
  kind: ReferenceKind.EMBEDDED,
88
+ ...this.normalizeType(options),
90
89
  ...options,
91
90
  };
92
91
  }
@@ -99,6 +98,8 @@ export class EntitySchema {
99
98
  if (prop.fieldNames && !prop.joinColumns) {
100
99
  prop.joinColumns = prop.fieldNames;
101
100
  }
101
+ // By default, the foreign key constraint is created on the relation
102
+ Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
102
103
  this.addProperty(name, type, prop);
103
104
  }
104
105
  addManyToMany(name, type, options) {
@@ -108,6 +109,8 @@ export class EntitySchema {
108
109
  }
109
110
  if (options.owner) {
110
111
  Utils.renameKey(options, 'mappedBy', 'inversedBy');
112
+ // By default, the foreign key constraint is created on the relation
113
+ Utils.defaultValue(options, 'createForeignKeyConstraint', true);
111
114
  }
112
115
  const prop = this.createProperty(ReferenceKind.MANY_TO_MANY, options);
113
116
  this.addProperty(name, type, prop);
@@ -120,8 +123,12 @@ export class EntitySchema {
120
123
  const prop = this.createProperty(ReferenceKind.ONE_TO_ONE, options);
121
124
  Utils.defaultValue(prop, 'owner', !!prop.inversedBy || !prop.mappedBy);
122
125
  Utils.defaultValue(prop, 'unique', prop.owner);
123
- if (prop.owner && options.mappedBy) {
124
- Utils.renameKey(prop, 'mappedBy', 'inversedBy');
126
+ if (prop.owner) {
127
+ if (options.mappedBy) {
128
+ Utils.renameKey(prop, 'mappedBy', 'inversedBy');
129
+ }
130
+ // By default, the foreign key constraint is created on the relation
131
+ Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
125
132
  }
126
133
  if (prop.joinColumns && !prop.fieldNames) {
127
134
  prop.fieldNames = prop.joinColumns;
@@ -143,21 +150,29 @@ export class EntitySchema {
143
150
  setExtends(base) {
144
151
  this._meta.extends = base;
145
152
  }
146
- setClass(proto) {
147
- const sameClass = this._meta.className === proto.name;
148
- this._meta.class = proto;
149
- this._meta.prototype = proto.prototype;
150
- this._meta.className = proto.name;
153
+ setClass(cls) {
154
+ const oldClass = this._meta.class;
155
+ const sameClass = this._meta.class === cls;
156
+ this._meta.class = cls;
157
+ this._meta.prototype = cls.prototype;
158
+ this._meta.className = this._meta.name ?? cls.name;
151
159
  if (!sameClass || !this._meta.constructorParams) {
152
- const tokens = Utils.tokenize(proto);
153
- this._meta.constructorParams = Utils.getParamNames(tokens, 'constructor');
154
- this._meta.toJsonParams = Utils.getParamNames(tokens, 'toJSON').filter(p => p !== '...args');
160
+ this._meta.constructorParams = Utils.getConstructorParams(cls);
155
161
  }
156
162
  if (!this.internal) {
157
- EntitySchema.REGISTRY.set(proto, this);
163
+ // Remove old class from registry if it's being replaced with a different class
164
+ if (oldClass && oldClass !== cls && EntitySchema.REGISTRY.get(oldClass) === this) {
165
+ EntitySchema.REGISTRY.delete(oldClass);
166
+ }
167
+ EntitySchema.REGISTRY.set(cls, this);
158
168
  }
159
- if (Object.getPrototypeOf(proto) !== BaseEntity) {
160
- this._meta.extends = this._meta.extends || Object.getPrototypeOf(proto).name || undefined;
169
+ const base = Object.getPrototypeOf(cls);
170
+ // Only set extends if the parent is NOT the auto-generated class for this same entity.
171
+ // When the user extends the auto-generated class (from defineEntity without a class option)
172
+ // and registers their custom class via setClass, we don't want to discover the
173
+ // auto-generated class as a separate parent entity.
174
+ if (base !== BaseEntity && base.name !== this._meta.className) {
175
+ this._meta.extends ??= base.name ? base : undefined;
161
176
  }
162
177
  }
163
178
  get meta() {
@@ -166,6 +181,18 @@ export class EntitySchema {
166
181
  get name() {
167
182
  return this._meta.className;
168
183
  }
184
+ get tableName() {
185
+ return this._meta.tableName;
186
+ }
187
+ get class() {
188
+ return this._meta.class;
189
+ }
190
+ get properties() {
191
+ return this._meta.properties;
192
+ }
193
+ new(...params) {
194
+ return new this._meta.class(...params);
195
+ }
169
196
  /**
170
197
  * @internal
171
198
  */
@@ -173,11 +200,6 @@ export class EntitySchema {
173
200
  if (this.initialized) {
174
201
  return this;
175
202
  }
176
- if (!this._meta.class) {
177
- const name = this.name;
178
- this._meta.class = ({ [name]: class {
179
- } })[name];
180
- }
181
203
  this.setClass(this._meta.class);
182
204
  if (this._meta.abstract && !this._meta.discriminatorColumn) {
183
205
  delete this._meta.name;
@@ -185,7 +207,7 @@ export class EntitySchema {
185
207
  const tableName = this._meta.collection ?? this._meta.tableName;
186
208
  if (tableName?.includes('.') && !this._meta.schema) {
187
209
  this._meta.schema = tableName.substring(0, tableName.indexOf('.'));
188
- this._meta.collection = tableName.substring(tableName.indexOf('.') + 1);
210
+ this._meta.tableName = tableName.substring(tableName.indexOf('.') + 1);
189
211
  }
190
212
  this.initProperties();
191
213
  this.initPrimaryKeys();
@@ -251,12 +273,15 @@ export class EntitySchema {
251
273
  }
252
274
  normalizeType(options, type) {
253
275
  if ('entity' in options) {
254
- if (Utils.isString(options.entity)) {
255
- type = options.type = options.entity;
276
+ /* v8 ignore next */
277
+ if (typeof options.entity === 'string') {
278
+ throw new Error(`Relation target needs to be an entity class or EntitySchema instance, string '${options.entity}' given instead for ${this._meta.className}.${options.name}.`);
256
279
  }
257
280
  else if (options.entity) {
258
281
  const tmp = options.entity();
259
282
  type = options.type = Array.isArray(tmp) ? tmp.map(t => Utils.className(t)).sort().join(' | ') : Utils.className(tmp);
283
+ const target = tmp instanceof EntitySchema ? tmp.meta.class : tmp;
284
+ return { type, target };
260
285
  }
261
286
  }
262
287
  if (type instanceof Function) {
@@ -265,7 +290,7 @@ export class EntitySchema {
265
290
  if (['String', 'Number', 'Boolean', 'Array'].includes(type)) {
266
291
  type = type.toLowerCase();
267
292
  }
268
- return type;
293
+ return { type };
269
294
  }
270
295
  createProperty(kind, options) {
271
296
  return {