@mikro-orm/core 7.0.0-dev.8 → 7.0.0-dev.80

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 (181) hide show
  1. package/EntityManager.d.ts +85 -48
  2. package/EntityManager.js +300 -225
  3. package/MikroORM.d.ts +40 -31
  4. package/MikroORM.js +98 -137
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +6 -5
  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 +11 -7
  13. package/connections/Connection.js +16 -14
  14. package/drivers/DatabaseDriver.d.ts +11 -5
  15. package/drivers/DatabaseDriver.js +17 -8
  16. package/drivers/IDatabaseDriver.d.ts +27 -5
  17. package/entity/BaseEntity.d.ts +0 -1
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +98 -30
  20. package/entity/Collection.js +432 -93
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +15 -7
  23. package/entity/EntityFactory.d.ts +7 -0
  24. package/entity/EntityFactory.js +64 -41
  25. package/entity/EntityHelper.js +26 -9
  26. package/entity/EntityLoader.d.ts +5 -4
  27. package/entity/EntityLoader.js +73 -40
  28. package/entity/EntityRepository.d.ts +1 -1
  29. package/entity/Reference.d.ts +9 -7
  30. package/entity/Reference.js +33 -6
  31. package/entity/WrappedEntity.d.ts +2 -4
  32. package/entity/WrappedEntity.js +1 -5
  33. package/entity/defineEntity.d.ts +549 -0
  34. package/entity/defineEntity.js +529 -0
  35. package/entity/index.d.ts +3 -2
  36. package/entity/index.js +3 -2
  37. package/entity/utils.d.ts +7 -0
  38. package/entity/utils.js +16 -4
  39. package/entity/validators.d.ts +11 -0
  40. package/entity/validators.js +65 -0
  41. package/enums.d.ts +21 -6
  42. package/enums.js +14 -1
  43. package/errors.d.ts +6 -2
  44. package/errors.js +14 -9
  45. package/events/EventSubscriber.d.ts +3 -1
  46. package/hydration/Hydrator.js +1 -2
  47. package/hydration/ObjectHydrator.d.ts +4 -4
  48. package/hydration/ObjectHydrator.js +36 -25
  49. package/index.d.ts +2 -2
  50. package/index.js +1 -2
  51. package/logging/DefaultLogger.d.ts +1 -1
  52. package/logging/SimpleLogger.d.ts +1 -1
  53. package/metadata/EntitySchema.d.ts +9 -13
  54. package/metadata/EntitySchema.js +44 -26
  55. package/metadata/MetadataDiscovery.d.ts +6 -9
  56. package/metadata/MetadataDiscovery.js +167 -206
  57. package/metadata/MetadataProvider.d.ts +11 -2
  58. package/metadata/MetadataProvider.js +44 -2
  59. package/metadata/MetadataStorage.d.ts +1 -6
  60. package/metadata/MetadataStorage.js +6 -18
  61. package/metadata/MetadataValidator.d.ts +0 -7
  62. package/metadata/MetadataValidator.js +4 -13
  63. package/metadata/discover-entities.d.ts +5 -0
  64. package/metadata/discover-entities.js +40 -0
  65. package/metadata/index.d.ts +1 -1
  66. package/metadata/index.js +1 -1
  67. package/metadata/types.d.ts +480 -0
  68. package/metadata/types.js +1 -0
  69. package/naming-strategy/AbstractNamingStrategy.d.ts +5 -1
  70. package/naming-strategy/AbstractNamingStrategy.js +8 -2
  71. package/naming-strategy/NamingStrategy.d.ts +11 -1
  72. package/not-supported.d.ts +2 -0
  73. package/not-supported.js +4 -0
  74. package/package.json +18 -10
  75. package/platforms/ExceptionConverter.js +1 -1
  76. package/platforms/Platform.d.ts +6 -10
  77. package/platforms/Platform.js +14 -39
  78. package/serialization/EntitySerializer.d.ts +2 -0
  79. package/serialization/EntitySerializer.js +32 -14
  80. package/serialization/EntityTransformer.js +22 -12
  81. package/serialization/SerializationContext.js +16 -13
  82. package/types/ArrayType.d.ts +1 -1
  83. package/types/ArrayType.js +2 -3
  84. package/types/BigIntType.d.ts +8 -6
  85. package/types/BigIntType.js +1 -1
  86. package/types/BlobType.d.ts +0 -1
  87. package/types/BlobType.js +0 -3
  88. package/types/BooleanType.d.ts +2 -1
  89. package/types/BooleanType.js +3 -0
  90. package/types/DecimalType.d.ts +6 -4
  91. package/types/DecimalType.js +3 -3
  92. package/types/DoubleType.js +2 -2
  93. package/types/JsonType.d.ts +1 -1
  94. package/types/JsonType.js +7 -2
  95. package/types/TinyIntType.js +1 -1
  96. package/types/Type.d.ts +2 -1
  97. package/types/Type.js +1 -1
  98. package/types/Uint8ArrayType.d.ts +0 -1
  99. package/types/Uint8ArrayType.js +1 -4
  100. package/types/index.d.ts +1 -1
  101. package/typings.d.ts +113 -77
  102. package/typings.js +41 -35
  103. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  104. package/unit-of-work/ChangeSetComputer.js +11 -9
  105. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  106. package/unit-of-work/ChangeSetPersister.js +58 -20
  107. package/unit-of-work/UnitOfWork.d.ts +8 -1
  108. package/unit-of-work/UnitOfWork.js +115 -57
  109. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  110. package/utils/AbstractSchemaGenerator.js +11 -9
  111. package/utils/Configuration.d.ts +757 -206
  112. package/utils/Configuration.js +139 -187
  113. package/utils/ConfigurationLoader.d.ts +1 -54
  114. package/utils/ConfigurationLoader.js +1 -352
  115. package/utils/Cursor.d.ts +3 -3
  116. package/utils/Cursor.js +4 -1
  117. package/utils/DataloaderUtils.d.ts +15 -5
  118. package/utils/DataloaderUtils.js +54 -8
  119. package/utils/EntityComparator.d.ts +8 -4
  120. package/utils/EntityComparator.js +111 -64
  121. package/utils/QueryHelper.d.ts +9 -1
  122. package/utils/QueryHelper.js +70 -9
  123. package/utils/RawQueryFragment.d.ts +36 -4
  124. package/utils/RawQueryFragment.js +35 -14
  125. package/utils/TransactionManager.d.ts +65 -0
  126. package/utils/TransactionManager.js +223 -0
  127. package/utils/Utils.d.ts +8 -97
  128. package/utils/Utils.js +88 -303
  129. package/utils/clone.js +2 -3
  130. package/utils/env-vars.d.ts +3 -0
  131. package/utils/env-vars.js +87 -0
  132. package/utils/fs-utils.d.ts +12 -0
  133. package/utils/fs-utils.js +96 -0
  134. package/utils/index.d.ts +2 -1
  135. package/utils/index.js +2 -1
  136. package/utils/upsert-utils.d.ts +7 -2
  137. package/utils/upsert-utils.js +55 -4
  138. package/decorators/Check.d.ts +0 -3
  139. package/decorators/Check.js +0 -13
  140. package/decorators/CreateRequestContext.d.ts +0 -3
  141. package/decorators/CreateRequestContext.js +0 -32
  142. package/decorators/Embeddable.d.ts +0 -8
  143. package/decorators/Embeddable.js +0 -11
  144. package/decorators/Embedded.d.ts +0 -18
  145. package/decorators/Embedded.js +0 -18
  146. package/decorators/Entity.d.ts +0 -18
  147. package/decorators/Entity.js +0 -12
  148. package/decorators/Enum.d.ts +0 -9
  149. package/decorators/Enum.js +0 -16
  150. package/decorators/Filter.d.ts +0 -2
  151. package/decorators/Filter.js +0 -8
  152. package/decorators/Formula.d.ts +0 -4
  153. package/decorators/Formula.js +0 -15
  154. package/decorators/Indexed.d.ts +0 -19
  155. package/decorators/Indexed.js +0 -20
  156. package/decorators/ManyToMany.d.ts +0 -40
  157. package/decorators/ManyToMany.js +0 -14
  158. package/decorators/ManyToOne.d.ts +0 -30
  159. package/decorators/ManyToOne.js +0 -14
  160. package/decorators/OneToMany.d.ts +0 -28
  161. package/decorators/OneToMany.js +0 -17
  162. package/decorators/OneToOne.d.ts +0 -24
  163. package/decorators/OneToOne.js +0 -7
  164. package/decorators/PrimaryKey.d.ts +0 -8
  165. package/decorators/PrimaryKey.js +0 -20
  166. package/decorators/Property.d.ts +0 -250
  167. package/decorators/Property.js +0 -32
  168. package/decorators/Transactional.d.ts +0 -13
  169. package/decorators/Transactional.js +0 -28
  170. package/decorators/hooks.d.ts +0 -16
  171. package/decorators/hooks.js +0 -47
  172. package/decorators/index.d.ts +0 -17
  173. package/decorators/index.js +0 -17
  174. package/entity/ArrayCollection.d.ts +0 -116
  175. package/entity/ArrayCollection.js +0 -402
  176. package/entity/EntityValidator.d.ts +0 -19
  177. package/entity/EntityValidator.js +0 -150
  178. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  179. package/metadata/ReflectMetadataProvider.js +0 -44
  180. package/utils/resolveContextProvider.d.ts +0 -10
  181. package/utils/resolveContextProvider.js +0 -28
package/MikroORM.d.ts CHANGED
@@ -3,13 +3,42 @@ import { type EntitySchema } from './metadata/EntitySchema.js';
3
3
  import { MetadataStorage } from './metadata/MetadataStorage.js';
4
4
  import { Configuration, type Options } from './utils/Configuration.js';
5
5
  import type { EntityManager } from './EntityManager.js';
6
- import type { Constructor, EntityMetadata, EntityName, IEntityGenerator, IMigrator, ISeedManager } from './typings.js';
6
+ import type { AnyEntity, Constructor, EntityClass, EntityMetadata, EntityName, IEntityGenerator, IMigrator, ISeedManager } from './typings.js';
7
+ /** @internal */
8
+ export declare function lookupExtensions(options: Options): Promise<void>;
7
9
  /**
8
- * Helper class for bootstrapping the MikroORM.
10
+ * The main class used to configure and bootstrap the ORM.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * // import from driver package
15
+ * import { MikroORM, defineEntity, p } from '@mikro-orm/sqlite';
16
+ *
17
+ * const User = defineEntity({
18
+ * name: 'User',
19
+ * properties: {
20
+ * id: p.integer().primary(),
21
+ * name: p.string(),
22
+ * },
23
+ * });
24
+ *
25
+ * const orm = new MikroORM({
26
+ * entities: [User],
27
+ * dbName: 'my.db',
28
+ * });
29
+ * await orm.schema.update();
30
+ *
31
+ * const em = orm.em.fork();
32
+ * const u1 = em.create(User, { name: 'John' });
33
+ * const u2 = em.create(User, { name: 'Ben' });
34
+ * await em.flush();
35
+ * ```
9
36
  */
10
- export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver, EM extends EntityManager = Driver[typeof EntityManagerType] & EntityManager> {
37
+ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver, EM extends Driver[typeof EntityManagerType] & EntityManager<Driver> = Driver[typeof EntityManagerType] & EntityManager<Driver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> {
11
38
  /** The global EntityManager instance. If you are using `RequestContext` helper, it will automatically pick the request specific context under the hood */
12
- em: EM;
39
+ em: EM & {
40
+ '~entities'?: Entities;
41
+ };
13
42
  readonly driver: Driver;
14
43
  readonly config: Configuration<Driver>;
15
44
  private metadata;
@@ -19,16 +48,14 @@ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver,
19
48
  * Initialize the ORM, load entity metadata, create EntityManager and connect to the database.
20
49
  * If you omit the `options` parameter, your CLI config will be used.
21
50
  */
22
- static init<D extends IDatabaseDriver = IDatabaseDriver, EM extends EntityManager = D[typeof EntityManagerType] & EntityManager>(options?: Options<D, EM>): Promise<MikroORM<D, EM>>;
51
+ static init<D extends IDatabaseDriver = IDatabaseDriver, EM extends D[typeof EntityManagerType] & EntityManager<D> = D[typeof EntityManagerType] & EntityManager<D>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: Options<D, EM, Entities>): Promise<MikroORM<D, EM, Entities>>;
23
52
  /**
24
53
  * Synchronous variant of the `init` method with some limitations:
25
54
  * - database connection will be established when you first interact with the database (or you can use `orm.connect()` explicitly)
26
55
  * - no loading of the `config` file, `options` parameter is mandatory
27
56
  * - no support for folder based discovery
28
- * - no check for mismatched package versions
29
57
  */
30
- static initSync<D extends IDatabaseDriver = IDatabaseDriver, EM extends EntityManager = D[typeof EntityManagerType] & EntityManager>(options: Options<D, EM>): MikroORM<D, EM>;
31
- constructor(options: Options<Driver, EM>);
58
+ constructor(options: Options<Driver, EM, Entities>);
32
59
  /**
33
60
  * Connects to the database.
34
61
  */
@@ -36,13 +63,13 @@ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver,
36
63
  /**
37
64
  * Reconnects, possibly to a different database.
38
65
  */
39
- reconnect(options?: Options): Promise<void>;
66
+ reconnect(options?: Partial<Options<Driver, EM, Entities>>): Promise<void>;
40
67
  /**
41
68
  * Checks whether the database connection is active.
42
69
  */
43
70
  isConnected(): Promise<boolean>;
44
71
  /**
45
- * Checks whether the database connection is active, returns .
72
+ * Checks whether the database connection is active, returns the reason if not.
46
73
  */
47
74
  checkConnection(): Promise<{
48
75
  ok: true;
@@ -63,8 +90,6 @@ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver,
63
90
  * Gets the `EntityMetadata` instance when provided with the `entityName` parameter.
64
91
  */
65
92
  getMetadata<Entity extends object>(entityName: EntityName<Entity>): EntityMetadata<Entity>;
66
- discoverEntities(): Promise<void>;
67
- discoverEntitiesSync(): void;
68
93
  private createEntityManager;
69
94
  /**
70
95
  * Allows dynamically discovering new entity by reference, handy for testing schema diffing.
@@ -73,33 +98,17 @@ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver,
73
98
  /**
74
99
  * Gets the SchemaGenerator.
75
100
  */
76
- getSchemaGenerator(): ReturnType<ReturnType<Driver['getPlatform']>['getSchemaGenerator']>;
77
- /**
78
- * Gets the EntityGenerator.
79
- */
80
- getEntityGenerator<T extends IEntityGenerator = IEntityGenerator>(): T;
81
- /**
82
- * Gets the Migrator.
83
- */
84
- getMigrator<T extends IMigrator = IMigrator>(): T;
101
+ get schema(): ReturnType<ReturnType<Driver['getPlatform']>['getSchemaGenerator']>;
85
102
  /**
86
103
  * Gets the SeedManager
87
104
  */
88
- getSeeder<T extends ISeedManager = ISeedManager>(): T;
89
- /**
90
- * Shortcut for `orm.getSchemaGenerator()`
91
- */
92
- get schema(): ReturnType<ReturnType<Driver["getPlatform"]>["getSchemaGenerator"]>;
93
- /**
94
- * Shortcut for `orm.getSeeder()`
95
- */
96
105
  get seeder(): ISeedManager;
97
106
  /**
98
- * Shortcut for `orm.getMigrator()`
107
+ * Gets the Migrator.
99
108
  */
100
109
  get migrator(): IMigrator;
101
110
  /**
102
- * Shortcut for `orm.getEntityGenerator()`
111
+ * Gets the EntityGenerator.
103
112
  */
104
113
  get entityGenerator(): IEntityGenerator;
105
114
  }
package/MikroORM.js CHANGED
@@ -1,14 +1,69 @@
1
1
  import { MetadataDiscovery } from './metadata/MetadataDiscovery.js';
2
2
  import { MetadataStorage } from './metadata/MetadataStorage.js';
3
- import { MetadataValidator } from './metadata/MetadataValidator.js';
4
- import { ReflectMetadataProvider } from './metadata/ReflectMetadataProvider.js';
5
3
  import { Configuration } from './utils/Configuration.js';
6
- import { ConfigurationLoader } from './utils/ConfigurationLoader.js';
4
+ import { loadEnvironmentVars } from './utils/env-vars.js';
7
5
  import { Utils } from './utils/Utils.js';
8
6
  import { colors } from './logging/colors.js';
9
- import { NullCacheAdapter } from './cache/NullCacheAdapter.js';
7
+ async function registerExtension(name, mod, extensions) {
8
+ /* v8 ignore next */
9
+ const resolved = await mod.catch(() => null);
10
+ const module = resolved?.[name];
11
+ /* v8 ignore else */
12
+ if (module) {
13
+ extensions.push(module);
14
+ }
15
+ }
16
+ /** @internal */
17
+ export async function lookupExtensions(options) {
18
+ const extensions = options.extensions ?? [];
19
+ const exists = (name) => extensions.some(ext => ext.name === name);
20
+ if (!exists('SeedManager')) {
21
+ await registerExtension('SeedManager', import('@mikro-orm/seeder' + ''), extensions);
22
+ }
23
+ if (!exists('Migrator')) {
24
+ await registerExtension('Migrator', import('@mikro-orm/migrations' + ''), extensions);
25
+ }
26
+ /* v8 ignore if */
27
+ if (!exists('Migrator')) {
28
+ await registerExtension('Migrator', import('@mikro-orm/migrations-mongodb' + ''), extensions);
29
+ }
30
+ if (!exists('EntityGenerator')) {
31
+ await registerExtension('EntityGenerator', import('@mikro-orm/entity-generator' + ''), extensions);
32
+ }
33
+ options.extensions = extensions;
34
+ const metadataCacheEnabled = options.metadataCache?.enabled || options.metadataProvider?.useCache?.();
35
+ if (metadataCacheEnabled) {
36
+ options.metadataCache ??= {};
37
+ options.metadataCache.adapter ??= await import('@mikro-orm/core/fs-utils').then(m => m.FileCacheAdapter);
38
+ }
39
+ }
10
40
  /**
11
- * Helper class for bootstrapping the MikroORM.
41
+ * The main class used to configure and bootstrap the ORM.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * // import from driver package
46
+ * import { MikroORM, defineEntity, p } from '@mikro-orm/sqlite';
47
+ *
48
+ * const User = defineEntity({
49
+ * name: 'User',
50
+ * properties: {
51
+ * id: p.integer().primary(),
52
+ * name: p.string(),
53
+ * },
54
+ * });
55
+ *
56
+ * const orm = new MikroORM({
57
+ * entities: [User],
58
+ * dbName: 'my.db',
59
+ * });
60
+ * await orm.schema.update();
61
+ *
62
+ * const em = orm.em.fork();
63
+ * const u1 = em.create(User, { name: 'John' });
64
+ * const u2 = em.create(User, { name: 'Ben' });
65
+ * await em.flush();
66
+ * ```
12
67
  */
13
68
  export class MikroORM {
14
69
  /** The global EntityManager instance. If you are using `RequestContext` helper, it will automatically pick the request specific context under the hood */
@@ -23,39 +78,18 @@ export class MikroORM {
23
78
  * If you omit the `options` parameter, your CLI config will be used.
24
79
  */
25
80
  static async init(options) {
26
- ConfigurationLoader.registerDotenv(options);
27
- const coreVersion = ConfigurationLoader.checkPackageVersion();
28
- const env = await ConfigurationLoader.loadEnvironmentVars();
81
+ /* v8 ignore next */
29
82
  if (!options) {
30
- const configPathFromArg = ConfigurationLoader.configPathsFromArg();
31
- const config = (await ConfigurationLoader.getConfiguration(process.env.MIKRO_ORM_CONTEXT_NAME ?? 'default', configPathFromArg ?? ConfigurationLoader.getConfigPaths()));
32
- options = config.getAll();
33
- if (configPathFromArg) {
34
- config.getLogger().warn('deprecated', 'Path for config file was inferred from the command line arguments. Instead, you should set the MIKRO_ORM_CLI_CONFIG environment variable to specify the path, or if you really must use the command line arguments, import the config manually based on them, and pass it to init.', { label: 'D0001' });
35
- }
36
- }
37
- options = Utils.mergeConfig(options, env);
38
- ConfigurationLoader.commonJSCompat(options);
39
- if ('DRIVER' in this && !options.driver) {
40
- options.driver = this.DRIVER;
41
- }
42
- const orm = new MikroORM(options);
43
- orm.logger.log('info', `MikroORM version: ${colors.green(coreVersion)}`);
44
- // we need to allow global context here as we are not in a scope of requests yet
45
- const allowGlobalContext = orm.config.get('allowGlobalContext');
46
- orm.config.set('allowGlobalContext', true);
47
- await orm.discoverEntities();
48
- orm.config.set('allowGlobalContext', allowGlobalContext);
49
- orm.driver.getPlatform().init(orm);
50
- if (orm.config.get('connect')) {
51
- await orm.connect();
52
- }
53
- for (const extension of orm.config.get('extensions')) {
54
- extension.register(orm);
55
- }
56
- if (orm.config.get('connect') && orm.config.get('ensureIndexes')) {
57
- await orm.getSchemaGenerator().ensureIndexes();
58
- }
83
+ throw new Error(`options parameter is required`);
84
+ }
85
+ options = { ...options };
86
+ options.discovery ??= {};
87
+ options.discovery.skipSyncDiscovery ??= true;
88
+ await lookupExtensions(options);
89
+ const orm = new this(options);
90
+ const preferTs = orm.config.get('preferTs', Utils.detectTypeScriptSupport());
91
+ orm.metadata = await orm.discovery.discover(preferTs);
92
+ orm.createEntityManager();
59
93
  return orm;
60
94
  }
61
95
  /**
@@ -63,64 +97,37 @@ export class MikroORM {
63
97
  * - database connection will be established when you first interact with the database (or you can use `orm.connect()` explicitly)
64
98
  * - no loading of the `config` file, `options` parameter is mandatory
65
99
  * - no support for folder based discovery
66
- * - no check for mismatched package versions
67
100
  */
68
- static initSync(options) {
69
- ConfigurationLoader.registerDotenv(options);
70
- const env = ConfigurationLoader.loadEnvironmentVarsSync();
71
- options = Utils.merge(options, env);
72
- if ('DRIVER' in this && !options.driver) {
73
- options.driver = this.DRIVER;
74
- }
75
- const orm = new MikroORM(options);
76
- // we need to allow global context here as we are not in a scope of requests yet
77
- const allowGlobalContext = orm.config.get('allowGlobalContext');
78
- orm.config.set('allowGlobalContext', true);
79
- orm.discoverEntitiesSync();
80
- orm.config.set('allowGlobalContext', allowGlobalContext);
81
- orm.driver.getPlatform().init(orm);
82
- for (const extension of orm.config.get('extensions')) {
83
- extension.register(orm);
84
- }
85
- return orm;
86
- }
87
101
  constructor(options) {
102
+ const env = loadEnvironmentVars();
103
+ options = Utils.merge(options, env);
88
104
  this.config = new Configuration(options);
89
105
  const discovery = this.config.get('discovery');
90
- if (discovery.disableDynamicFileAccess) {
91
- this.config.set('metadataProvider', ReflectMetadataProvider);
92
- this.config.set('metadataCache', { adapter: NullCacheAdapter });
93
- discovery.requireEntitiesArray = true;
94
- }
95
106
  this.driver = this.config.getDriver();
96
107
  this.logger = this.config.getLogger();
108
+ this.logger.log('info', `MikroORM version: ${colors.green(Utils.getORMVersion())}`);
97
109
  this.discovery = new MetadataDiscovery(new MetadataStorage(), this.driver.getPlatform(), this.config);
110
+ this.driver.getPlatform().init(this);
111
+ for (const extension of this.config.get('extensions')) {
112
+ extension.register(this);
113
+ }
114
+ if (!discovery.skipSyncDiscovery) {
115
+ this.metadata = this.discovery.discoverSync();
116
+ this.createEntityManager();
117
+ }
98
118
  }
99
119
  /**
100
120
  * Connects to the database.
101
121
  */
102
122
  async connect() {
103
- const connection = await this.driver.connect();
104
- const clientUrl = connection.getClientUrl();
105
- const dbName = this.config.get('dbName');
106
- const db = dbName + (clientUrl ? ' on ' + clientUrl : '');
107
- if (this.config.get('ensureDatabase')) {
108
- const options = this.config.get('ensureDatabase');
109
- await this.schema.ensureDatabase(typeof options === 'boolean' ? {} : { ...options, forceCheck: true });
110
- }
111
- if (await this.isConnected()) {
112
- this.logger.log('info', `MikroORM successfully connected to database ${colors.green(db)}`);
113
- }
114
- else {
115
- this.logger.error('info', `MikroORM failed to connect to database ${db}`);
116
- }
123
+ await this.driver.connect();
117
124
  return this.driver;
118
125
  }
119
126
  /**
120
127
  * Reconnects, possibly to a different database.
121
128
  */
122
129
  async reconnect(options = {}) {
123
- /* v8 ignore next 3 */
130
+ /* v8 ignore next */
124
131
  for (const key of Utils.keys(options)) {
125
132
  this.config.set(key, options[key]);
126
133
  }
@@ -133,7 +140,7 @@ export class MikroORM {
133
140
  return this.driver.getConnection().isConnected();
134
141
  }
135
142
  /**
136
- * Checks whether the database connection is active, returns .
143
+ * Checks whether the database connection is active, returns the reason if not.
137
144
  */
138
145
  async checkConnection() {
139
146
  return this.driver.getConnection().checkConnection();
@@ -142,15 +149,9 @@ export class MikroORM {
142
149
  * Closes the database connection.
143
150
  */
144
151
  async close(force = false) {
145
- if (await this.isConnected()) {
146
- await this.driver.close(force);
147
- }
148
- if (this.config.getMetadataCacheAdapter()?.close) {
149
- await this.config.getMetadataCacheAdapter().close();
150
- }
151
- if (this.config.getResultCacheAdapter()?.close) {
152
- await this.config.getResultCacheAdapter().close();
153
- }
152
+ await this.driver.close(force);
153
+ await this.config.getMetadataCacheAdapter().close?.();
154
+ await this.config.getResultCacheAdapter().close?.();
154
155
  }
155
156
  /**
156
157
  * Gets the `MetadataStorage` (without parameters) or `EntityMetadata` instance when provided with the `entityName` parameter.
@@ -162,14 +163,6 @@ export class MikroORM {
162
163
  }
163
164
  return this.metadata;
164
165
  }
165
- async discoverEntities() {
166
- this.metadata = await this.discovery.discover(this.config.get('preferTs'));
167
- this.createEntityManager();
168
- }
169
- discoverEntitiesSync() {
170
- this.metadata = this.discovery.discoverSync(this.config.get('preferTs'));
171
- this.createEntityManager();
172
- }
173
166
  createEntityManager() {
174
167
  this.driver.setMetadata(this.metadata);
175
168
  this.em = this.driver.createEntityManager();
@@ -181,72 +174,40 @@ export class MikroORM {
181
174
  * Allows dynamically discovering new entity by reference, handy for testing schema diffing.
182
175
  */
183
176
  discoverEntity(entities, reset) {
184
- entities = Utils.asArray(entities);
185
177
  for (const className of Utils.asArray(reset)) {
186
178
  this.metadata.reset(className);
187
179
  this.discovery.reset(className);
188
180
  }
189
- const tmp = this.discovery.discoverReferences(entities);
190
- const options = this.config.get('discovery');
191
- new MetadataValidator().validateDiscovered([...Object.values(this.metadata.getAll()), ...tmp], options);
181
+ const tmp = this.discovery.discoverReferences(Utils.asArray(entities));
192
182
  const metadata = this.discovery.processDiscoveredEntities(tmp);
193
- metadata.forEach(meta => {
183
+ for (const meta of metadata) {
194
184
  this.metadata.set(meta.className, meta);
195
185
  meta.root = this.metadata.get(meta.root.className);
196
- });
186
+ }
197
187
  this.metadata.decorate(this.em);
198
188
  }
199
189
  /**
200
190
  * Gets the SchemaGenerator.
201
191
  */
202
- getSchemaGenerator() {
203
- const extension = this.config.getExtension('@mikro-orm/schema-generator');
204
- if (extension) {
205
- return extension;
206
- }
207
- /* v8 ignore next 2 */
208
- throw new Error(`SchemaGenerator extension not registered.`);
209
- }
210
- /**
211
- * Gets the EntityGenerator.
212
- */
213
- getEntityGenerator() {
214
- return this.driver.getPlatform().getExtension('EntityGenerator', '@mikro-orm/entity-generator', '@mikro-orm/entity-generator', this.em);
215
- }
216
- /**
217
- * Gets the Migrator.
218
- */
219
- getMigrator() {
220
- return this.driver.getPlatform().getExtension('Migrator', '@mikro-orm/migrator', '@mikro-orm/migrations', this.em);
221
- }
222
- /**
223
- * Gets the SeedManager
224
- */
225
- getSeeder() {
226
- return this.driver.getPlatform().getExtension('SeedManager', '@mikro-orm/seeder', '@mikro-orm/seeder', this.em);
227
- }
228
- /**
229
- * Shortcut for `orm.getSchemaGenerator()`
230
- */
231
192
  get schema() {
232
- return this.getSchemaGenerator();
193
+ return this.config.getExtension('@mikro-orm/schema-generator');
233
194
  }
234
195
  /**
235
- * Shortcut for `orm.getSeeder()`
196
+ * Gets the SeedManager
236
197
  */
237
198
  get seeder() {
238
- return this.getSeeder();
199
+ return this.driver.getPlatform().getExtension('SeedManager', '@mikro-orm/seeder', '@mikro-orm/seeder', this.em);
239
200
  }
240
201
  /**
241
- * Shortcut for `orm.getMigrator()`
202
+ * Gets the Migrator.
242
203
  */
243
204
  get migrator() {
244
- return this.getMigrator();
205
+ return this.driver.getPlatform().getExtension('Migrator', '@mikro-orm/migrator', '@mikro-orm/migrations', this.em);
245
206
  }
246
207
  /**
247
- * Shortcut for `orm.getEntityGenerator()`
208
+ * Gets the EntityGenerator.
248
209
  */
249
210
  get entityGenerator() {
250
- return this.getEntityGenerator();
211
+ return this.driver.getPlatform().getExtension('EntityGenerator', '@mikro-orm/entity-generator', '@mikro-orm/entity-generator', this.em);
251
212
  }
252
213
  }
package/README.md CHANGED
@@ -11,7 +11,6 @@ TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-or
11
11
  [![Chat on discord](https://img.shields.io/discord/1214904142443839538?label=discord&color=blue)](https://discord.gg/w8bjxFHS7X)
12
12
  [![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)
13
13
  [![Coverage Status](https://img.shields.io/coveralls/mikro-orm/mikro-orm.svg)](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
14
- [![Maintainability](https://api.codeclimate.com/v1/badges/27999651d3adc47cfa40/maintainability)](https://codeclimate.com/github/mikro-orm/mikro-orm/maintainability)
15
14
  [![Build Status](https://github.com/mikro-orm/mikro-orm/workflows/tests/badge.svg?branch=master)](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
16
15
 
17
16
  ## 🤔 Unit of What?
@@ -141,7 +140,7 @@ There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit m
141
140
  - [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
142
141
  - [Filters](https://mikro-orm.io/docs/filters)
143
142
  - [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
144
- - [Preloading Deeply Nested Structures via populate](https://mikro-orm.io/docs/nested-populate)
143
+ - [Populating relations](https://mikro-orm.io/docs/populating-relations)
145
144
  - [Property Validation](https://mikro-orm.io/docs/property-validation)
146
145
  - [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
147
146
  - [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
@@ -382,6 +381,8 @@ See also the list of contributors who [participated](https://github.com/mikro-or
382
381
 
383
382
  Please ⭐️ this repository if this project helped you!
384
383
 
384
+ > If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
385
+
385
386
  ## 📝 License
386
387
 
387
388
  Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
@@ -8,7 +8,7 @@ export declare class FileCacheAdapter implements SyncCacheAdapter {
8
8
  constructor(options: {
9
9
  cacheDir: string;
10
10
  combined?: boolean | string;
11
- }, baseDir: string, pretty?: boolean);
11
+ } | undefined, baseDir: string, pretty?: boolean);
12
12
  /**
13
13
  * @inheritDoc
14
14
  */
@@ -1,5 +1,5 @@
1
- import globby from 'globby';
2
1
  import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
2
+ import { fs } from '../utils/fs-utils.js';
3
3
  import { Utils } from '../utils/Utils.js';
4
4
  export class FileCacheAdapter {
5
5
  options;
@@ -7,10 +7,11 @@ export class FileCacheAdapter {
7
7
  pretty;
8
8
  VERSION = Utils.getORMVersion();
9
9
  cache = {};
10
- constructor(options, baseDir, pretty = false) {
10
+ constructor(options = {}, baseDir, pretty = false) {
11
11
  this.options = options;
12
12
  this.baseDir = baseDir;
13
13
  this.pretty = pretty;
14
+ this.options.cacheDir ??= process.cwd() + '/temp';
14
15
  }
15
16
  /**
16
17
  * @inheritDoc
@@ -20,7 +21,7 @@ export class FileCacheAdapter {
20
21
  if (!existsSync(path)) {
21
22
  return null;
22
23
  }
23
- const payload = Utils.readJSONSync(path);
24
+ const payload = fs.readJSONSync(path);
24
25
  const hash = this.getHash(payload.origin);
25
26
  if (!hash || payload.hash !== hash) {
26
27
  return null;
@@ -51,7 +52,7 @@ export class FileCacheAdapter {
51
52
  */
52
53
  clear() {
53
54
  const path = this.path('*');
54
- const files = globby.sync(path);
55
+ const files = fs.glob(path);
55
56
  files.forEach(file => unlinkSync(file));
56
57
  this.cache = {};
57
58
  }
@@ -68,7 +69,7 @@ export class FileCacheAdapter {
68
69
  return path;
69
70
  }
70
71
  path(name) {
71
- Utils.ensureDir(this.options.cacheDir);
72
+ fs.ensureDir(this.options.cacheDir);
72
73
  return `${this.options.cacheDir}/${name}.json`;
73
74
  }
74
75
  getHash(origin) {
@@ -1,7 +1,6 @@
1
1
  import type { CacheAdapter } from './CacheAdapter.js';
2
2
  import type { Dictionary } from '../typings.js';
3
3
  export declare class GeneratedCacheAdapter implements CacheAdapter {
4
- private readonly options;
5
4
  private readonly data;
6
5
  constructor(options: {
7
6
  data: Dictionary;
@@ -1,8 +1,6 @@
1
1
  export class GeneratedCacheAdapter {
2
- options;
3
2
  data = new Map();
4
3
  constructor(options) {
5
- this.options = options;
6
4
  this.data = new Map(Object.entries(options.data));
7
5
  }
8
6
  /**
package/cache/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  export * from './CacheAdapter.js';
2
2
  export * from './NullCacheAdapter.js';
3
- export * from './FileCacheAdapter.js';
4
3
  export * from './MemoryCacheAdapter.js';
5
4
  export * from './GeneratedCacheAdapter.js';
package/cache/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  export * from './CacheAdapter.js';
2
2
  export * from './NullCacheAdapter.js';
3
- export * from './FileCacheAdapter.js';
4
3
  export * from './MemoryCacheAdapter.js';
5
4
  export * from './GeneratedCacheAdapter.js';
@@ -17,7 +17,9 @@ export declare abstract class Connection {
17
17
  /**
18
18
  * Establishes connection to database
19
19
  */
20
- abstract connect(): void | Promise<void>;
20
+ abstract connect(options?: {
21
+ skipOnConnect?: boolean;
22
+ }): void | Promise<void>;
21
23
  /**
22
24
  * Are we connected to the database
23
25
  */
@@ -37,26 +39,28 @@ export declare abstract class Connection {
37
39
  */
38
40
  close(force?: boolean): Promise<void>;
39
41
  /**
40
- * Ensure the connection exists, this is used to support lazy connect when using `MikroORM.initSync()`
42
+ * Ensure the connection exists, this is used to support lazy connect when using `new MikroORM()` instead of the async `init` method.
41
43
  */
42
44
  ensureConnection(): Promise<void>;
45
+ protected onConnect(): Promise<void>;
43
46
  transactional<T>(cb: (trx: Transaction) => Promise<T>, options?: {
44
- isolationLevel?: IsolationLevel;
47
+ isolationLevel?: IsolationLevel | `${IsolationLevel}`;
45
48
  readOnly?: boolean;
46
49
  ctx?: Transaction;
47
50
  eventBroadcaster?: TransactionEventBroadcaster;
51
+ loggerContext?: LogContext;
48
52
  }): Promise<T>;
49
53
  begin(options?: {
50
- isolationLevel?: IsolationLevel;
54
+ isolationLevel?: IsolationLevel | `${IsolationLevel}`;
51
55
  readOnly?: boolean;
52
56
  ctx?: Transaction;
53
57
  eventBroadcaster?: TransactionEventBroadcaster;
58
+ loggerContext?: LogContext;
54
59
  }): Promise<Transaction>;
55
- commit(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
56
- rollback(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
60
+ commit(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
61
+ rollback(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
57
62
  abstract execute<T>(query: string, params?: any[], method?: 'all' | 'get' | 'run', ctx?: Transaction): Promise<QueryResult<T> | any | any[]>;
58
63
  getConnectionOptions(): ConnectionConfig;
59
- getClientUrl(): string;
60
64
  setMetadata(metadata: MetadataStorage): void;
61
65
  setPlatform(platform: Platform): void;
62
66
  getPlatform(): Platform;