@mikro-orm/core 7.0.0-dev.1 → 7.0.0-dev.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/EntityManager.d.ts +96 -58
  2. package/EntityManager.js +465 -395
  3. package/MikroORM.d.ts +45 -35
  4. package/MikroORM.js +109 -160
  5. package/README.md +3 -2
  6. package/cache/CacheAdapter.js +1 -2
  7. package/cache/FileCacheAdapter.d.ts +2 -2
  8. package/cache/FileCacheAdapter.js +20 -27
  9. package/cache/GeneratedCacheAdapter.d.ts +2 -3
  10. package/cache/GeneratedCacheAdapter.js +1 -7
  11. package/cache/MemoryCacheAdapter.d.ts +1 -1
  12. package/cache/MemoryCacheAdapter.js +1 -5
  13. package/cache/NullCacheAdapter.d.ts +1 -1
  14. package/cache/NullCacheAdapter.js +1 -5
  15. package/cache/index.d.ts +4 -5
  16. package/cache/index.js +4 -21
  17. package/connections/Connection.d.ts +22 -14
  18. package/connections/Connection.js +27 -23
  19. package/connections/index.d.ts +1 -1
  20. package/connections/index.js +1 -17
  21. package/drivers/DatabaseDriver.d.ts +25 -15
  22. package/drivers/DatabaseDriver.js +77 -64
  23. package/drivers/IDatabaseDriver.d.ts +40 -16
  24. package/drivers/IDatabaseDriver.js +1 -4
  25. package/drivers/index.d.ts +2 -2
  26. package/drivers/index.js +2 -18
  27. package/entity/BaseEntity.d.ts +6 -7
  28. package/entity/BaseEntity.js +16 -23
  29. package/entity/Collection.d.ts +98 -34
  30. package/entity/Collection.js +466 -131
  31. package/entity/EntityAssigner.d.ts +3 -3
  32. package/entity/EntityAssigner.js +67 -64
  33. package/entity/EntityFactory.d.ts +10 -3
  34. package/entity/EntityFactory.js +112 -91
  35. package/entity/EntityHelper.d.ts +2 -2
  36. package/entity/EntityHelper.js +66 -53
  37. package/entity/EntityIdentifier.d.ts +1 -1
  38. package/entity/EntityIdentifier.js +1 -5
  39. package/entity/EntityLoader.d.ts +8 -7
  40. package/entity/EntityLoader.js +161 -128
  41. package/entity/EntityRepository.d.ts +8 -8
  42. package/entity/EntityRepository.js +7 -11
  43. package/entity/Reference.d.ts +10 -13
  44. package/entity/Reference.js +64 -46
  45. package/entity/WrappedEntity.d.ts +12 -17
  46. package/entity/WrappedEntity.js +22 -31
  47. package/entity/defineEntity.d.ts +568 -0
  48. package/entity/defineEntity.js +529 -0
  49. package/entity/index.d.ts +14 -13
  50. package/entity/index.js +14 -29
  51. package/entity/utils.d.ts +8 -1
  52. package/entity/utils.js +22 -13
  53. package/entity/validators.d.ts +11 -0
  54. package/entity/validators.js +65 -0
  55. package/entity/wrap.d.ts +1 -1
  56. package/entity/wrap.js +2 -6
  57. package/enums.d.ts +24 -9
  58. package/enums.js +50 -41
  59. package/errors.d.ts +11 -3
  60. package/errors.js +42 -32
  61. package/events/EventManager.d.ts +5 -4
  62. package/events/EventManager.js +26 -22
  63. package/events/EventSubscriber.d.ts +8 -5
  64. package/events/EventSubscriber.js +1 -2
  65. package/events/TransactionEventBroadcaster.d.ts +3 -3
  66. package/events/TransactionEventBroadcaster.js +1 -5
  67. package/events/index.d.ts +3 -3
  68. package/events/index.js +3 -19
  69. package/exceptions.js +18 -39
  70. package/hydration/Hydrator.d.ts +5 -5
  71. package/hydration/Hydrator.js +2 -6
  72. package/hydration/ObjectHydrator.d.ts +7 -7
  73. package/hydration/ObjectHydrator.js +58 -50
  74. package/hydration/index.d.ts +2 -2
  75. package/hydration/index.js +2 -18
  76. package/index.d.ts +21 -21
  77. package/index.js +20 -46
  78. package/logging/DefaultLogger.d.ts +2 -2
  79. package/logging/DefaultLogger.js +10 -13
  80. package/logging/Logger.d.ts +1 -1
  81. package/logging/Logger.js +1 -2
  82. package/logging/SimpleLogger.d.ts +3 -3
  83. package/logging/SimpleLogger.js +2 -6
  84. package/logging/colors.js +1 -5
  85. package/logging/index.d.ts +5 -4
  86. package/logging/index.js +5 -20
  87. package/logging/inspect.d.ts +2 -0
  88. package/logging/inspect.js +16 -0
  89. package/metadata/EntitySchema.d.ts +14 -10
  90. package/metadata/EntitySchema.js +78 -64
  91. package/metadata/MetadataDiscovery.d.ts +11 -14
  92. package/metadata/MetadataDiscovery.js +278 -317
  93. package/metadata/MetadataProvider.d.ts +13 -4
  94. package/metadata/MetadataProvider.js +47 -8
  95. package/metadata/MetadataStorage.d.ts +2 -7
  96. package/metadata/MetadataStorage.js +19 -35
  97. package/metadata/MetadataValidator.d.ts +3 -10
  98. package/metadata/MetadataValidator.js +51 -64
  99. package/metadata/discover-entities.d.ts +5 -0
  100. package/metadata/discover-entities.js +40 -0
  101. package/metadata/index.d.ts +6 -6
  102. package/metadata/index.js +6 -22
  103. package/metadata/types.d.ts +480 -0
  104. package/metadata/types.js +1 -0
  105. package/naming-strategy/AbstractNamingStrategy.d.ts +7 -3
  106. package/naming-strategy/AbstractNamingStrategy.js +11 -9
  107. package/naming-strategy/EntityCaseNamingStrategy.d.ts +1 -1
  108. package/naming-strategy/EntityCaseNamingStrategy.js +2 -6
  109. package/naming-strategy/MongoNamingStrategy.d.ts +1 -1
  110. package/naming-strategy/MongoNamingStrategy.js +2 -6
  111. package/naming-strategy/NamingStrategy.d.ts +12 -2
  112. package/naming-strategy/NamingStrategy.js +1 -2
  113. package/naming-strategy/UnderscoreNamingStrategy.d.ts +1 -1
  114. package/naming-strategy/UnderscoreNamingStrategy.js +2 -6
  115. package/naming-strategy/index.d.ts +5 -5
  116. package/naming-strategy/index.js +5 -21
  117. package/not-supported.d.ts +2 -0
  118. package/not-supported.js +4 -0
  119. package/package.json +19 -20
  120. package/platforms/ExceptionConverter.d.ts +2 -2
  121. package/platforms/ExceptionConverter.js +4 -8
  122. package/platforms/Platform.d.ts +15 -22
  123. package/platforms/Platform.js +58 -88
  124. package/platforms/index.d.ts +2 -2
  125. package/platforms/index.js +2 -18
  126. package/serialization/EntitySerializer.d.ts +4 -2
  127. package/serialization/EntitySerializer.js +64 -51
  128. package/serialization/EntityTransformer.d.ts +1 -1
  129. package/serialization/EntityTransformer.js +48 -42
  130. package/serialization/SerializationContext.d.ts +2 -2
  131. package/serialization/SerializationContext.js +24 -25
  132. package/serialization/index.d.ts +3 -3
  133. package/serialization/index.js +3 -19
  134. package/types/ArrayType.d.ts +3 -3
  135. package/types/ArrayType.js +6 -11
  136. package/types/BigIntType.d.ts +12 -9
  137. package/types/BigIntType.js +6 -6
  138. package/types/BlobType.d.ts +3 -4
  139. package/types/BlobType.js +2 -11
  140. package/types/BooleanType.d.ts +5 -4
  141. package/types/BooleanType.js +5 -6
  142. package/types/CharacterType.d.ts +3 -3
  143. package/types/CharacterType.js +2 -6
  144. package/types/DateTimeType.d.ts +3 -3
  145. package/types/DateTimeType.js +2 -6
  146. package/types/DateType.d.ts +3 -3
  147. package/types/DateType.js +2 -6
  148. package/types/DecimalType.d.ts +9 -7
  149. package/types/DecimalType.js +5 -8
  150. package/types/DoubleType.d.ts +3 -3
  151. package/types/DoubleType.js +4 -7
  152. package/types/EnumArrayType.d.ts +4 -4
  153. package/types/EnumArrayType.js +4 -10
  154. package/types/EnumType.d.ts +3 -3
  155. package/types/EnumType.js +2 -6
  156. package/types/FloatType.d.ts +3 -3
  157. package/types/FloatType.js +2 -6
  158. package/types/IntegerType.d.ts +3 -3
  159. package/types/IntegerType.js +2 -6
  160. package/types/IntervalType.d.ts +3 -3
  161. package/types/IntervalType.js +2 -6
  162. package/types/JsonType.d.ts +4 -4
  163. package/types/JsonType.js +9 -8
  164. package/types/MediumIntType.d.ts +3 -3
  165. package/types/MediumIntType.js +2 -6
  166. package/types/SmallIntType.d.ts +3 -3
  167. package/types/SmallIntType.js +2 -6
  168. package/types/StringType.d.ts +3 -3
  169. package/types/StringType.js +2 -6
  170. package/types/TextType.d.ts +3 -3
  171. package/types/TextType.js +2 -6
  172. package/types/TimeType.d.ts +3 -3
  173. package/types/TimeType.js +4 -8
  174. package/types/TinyIntType.d.ts +3 -3
  175. package/types/TinyIntType.js +3 -6
  176. package/types/Type.d.ts +4 -6
  177. package/types/Type.js +6 -10
  178. package/types/Uint8ArrayType.d.ts +3 -4
  179. package/types/Uint8ArrayType.js +3 -12
  180. package/types/UnknownType.d.ts +3 -3
  181. package/types/UnknownType.js +2 -6
  182. package/types/UuidType.d.ts +3 -3
  183. package/types/UuidType.js +2 -6
  184. package/types/index.d.ts +25 -25
  185. package/types/index.js +52 -79
  186. package/typings.d.ts +134 -93
  187. package/typings.js +67 -65
  188. package/unit-of-work/ChangeSet.d.ts +1 -4
  189. package/unit-of-work/ChangeSet.js +13 -17
  190. package/unit-of-work/ChangeSetComputer.d.ts +8 -9
  191. package/unit-of-work/ChangeSetComputer.js +36 -38
  192. package/unit-of-work/ChangeSetPersister.d.ts +11 -9
  193. package/unit-of-work/ChangeSetPersister.js +100 -65
  194. package/unit-of-work/CommitOrderCalculator.d.ts +1 -1
  195. package/unit-of-work/CommitOrderCalculator.js +6 -10
  196. package/unit-of-work/IdentityMap.d.ts +1 -1
  197. package/unit-of-work/IdentityMap.js +1 -5
  198. package/unit-of-work/UnitOfWork.d.ts +16 -8
  199. package/unit-of-work/UnitOfWork.js +266 -209
  200. package/unit-of-work/index.d.ts +6 -6
  201. package/unit-of-work/index.js +6 -22
  202. package/utils/AbstractSchemaGenerator.d.ts +11 -11
  203. package/utils/AbstractSchemaGenerator.js +21 -20
  204. package/utils/Configuration.d.ts +774 -224
  205. package/utils/Configuration.js +166 -216
  206. package/utils/ConfigurationLoader.d.ts +1 -53
  207. package/utils/ConfigurationLoader.js +1 -367
  208. package/utils/Cursor.d.ts +6 -9
  209. package/utils/Cursor.js +25 -25
  210. package/utils/DataloaderUtils.d.ts +18 -8
  211. package/utils/DataloaderUtils.js +63 -21
  212. package/utils/EntityComparator.d.ts +9 -5
  213. package/utils/EntityComparator.js +155 -108
  214. package/utils/NullHighlighter.d.ts +1 -1
  215. package/utils/NullHighlighter.js +1 -5
  216. package/utils/QueryHelper.d.ts +12 -4
  217. package/utils/QueryHelper.js +110 -53
  218. package/utils/RawQueryFragment.d.ts +37 -14
  219. package/utils/RawQueryFragment.js +50 -33
  220. package/utils/RequestContext.d.ts +2 -2
  221. package/utils/RequestContext.js +3 -7
  222. package/utils/TransactionContext.d.ts +1 -1
  223. package/utils/TransactionContext.js +4 -8
  224. package/utils/TransactionManager.d.ts +65 -0
  225. package/utils/TransactionManager.js +223 -0
  226. package/utils/Utils.d.ts +16 -100
  227. package/utils/Utils.js +114 -332
  228. package/utils/clone.js +7 -11
  229. package/utils/env-vars.d.ts +3 -0
  230. package/utils/env-vars.js +87 -0
  231. package/utils/fs-utils.d.ts +12 -0
  232. package/utils/fs-utils.js +97 -0
  233. package/utils/index.d.ts +14 -13
  234. package/utils/index.js +14 -29
  235. package/utils/upsert-utils.d.ts +8 -3
  236. package/utils/upsert-utils.js +57 -10
  237. package/decorators/Check.d.ts +0 -3
  238. package/decorators/Check.js +0 -16
  239. package/decorators/CreateRequestContext.d.ts +0 -3
  240. package/decorators/CreateRequestContext.js +0 -33
  241. package/decorators/Embeddable.d.ts +0 -8
  242. package/decorators/Embeddable.js +0 -14
  243. package/decorators/Embedded.d.ts +0 -18
  244. package/decorators/Embedded.js +0 -20
  245. package/decorators/Entity.d.ts +0 -18
  246. package/decorators/Entity.js +0 -16
  247. package/decorators/Enum.d.ts +0 -9
  248. package/decorators/Enum.js +0 -19
  249. package/decorators/Filter.d.ts +0 -2
  250. package/decorators/Filter.js +0 -11
  251. package/decorators/Formula.d.ts +0 -5
  252. package/decorators/Formula.js +0 -18
  253. package/decorators/Indexed.d.ts +0 -17
  254. package/decorators/Indexed.js +0 -24
  255. package/decorators/ManyToMany.d.ts +0 -40
  256. package/decorators/ManyToMany.js +0 -16
  257. package/decorators/ManyToOne.d.ts +0 -30
  258. package/decorators/ManyToOne.js +0 -16
  259. package/decorators/OneToMany.d.ts +0 -28
  260. package/decorators/OneToMany.js +0 -20
  261. package/decorators/OneToOne.d.ts +0 -24
  262. package/decorators/OneToOne.js +0 -10
  263. package/decorators/PrimaryKey.d.ts +0 -9
  264. package/decorators/PrimaryKey.js +0 -23
  265. package/decorators/Property.d.ts +0 -250
  266. package/decorators/Property.js +0 -34
  267. package/decorators/Transactional.d.ts +0 -13
  268. package/decorators/Transactional.js +0 -31
  269. package/decorators/hooks.d.ts +0 -16
  270. package/decorators/hooks.js +0 -59
  271. package/decorators/index.d.ts +0 -17
  272. package/decorators/index.js +0 -36
  273. package/entity/ArrayCollection.d.ts +0 -116
  274. package/entity/ArrayCollection.js +0 -399
  275. package/entity/EntityValidator.d.ts +0 -19
  276. package/entity/EntityValidator.js +0 -154
  277. package/index.mjs +0 -199
  278. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  279. package/metadata/ReflectMetadataProvider.js +0 -48
  280. package/utils/resolveContextProvider.d.ts +0 -10
  281. package/utils/resolveContextProvider.js +0 -31
package/MikroORM.d.ts CHANGED
@@ -1,14 +1,44 @@
1
- import type { EntityManagerType, IDatabaseDriver } from './drivers';
2
- import { type EntitySchema, MetadataStorage } from './metadata';
3
- import { Configuration, type Options } from './utils';
4
- import type { EntityManager } from './EntityManager';
5
- import type { Constructor, EntityMetadata, EntityName, IEntityGenerator, IMigrator, ISeedManager } from './typings';
1
+ import type { EntityManagerType, IDatabaseDriver } from './drivers/IDatabaseDriver.js';
2
+ import { type EntitySchema } from './metadata/EntitySchema.js';
3
+ import { MetadataStorage } from './metadata/MetadataStorage.js';
4
+ import { Configuration, type Options } from './utils/Configuration.js';
5
+ import type { EntityManager } from './EntityManager.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>;
6
9
  /**
7
- * 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
+ * ```
8
36
  */
9
- 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)[]> {
10
38
  /** The global EntityManager instance. If you are using `RequestContext` helper, it will automatically pick the request specific context under the hood */
11
- em: EM;
39
+ em: EM & {
40
+ '~entities'?: Entities;
41
+ };
12
42
  readonly driver: Driver;
13
43
  readonly config: Configuration<Driver>;
14
44
  private metadata;
@@ -18,16 +48,14 @@ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver,
18
48
  * Initialize the ORM, load entity metadata, create EntityManager and connect to the database.
19
49
  * If you omit the `options` parameter, your CLI config will be used.
20
50
  */
21
- 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>>;
22
52
  /**
23
53
  * Synchronous variant of the `init` method with some limitations:
24
54
  * - database connection will be established when you first interact with the database (or you can use `orm.connect()` explicitly)
25
55
  * - no loading of the `config` file, `options` parameter is mandatory
26
56
  * - no support for folder based discovery
27
- * - no check for mismatched package versions
28
57
  */
29
- static initSync<D extends IDatabaseDriver = IDatabaseDriver, EM extends EntityManager = D[typeof EntityManagerType] & EntityManager>(options: Options<D, EM>): MikroORM<D, EM>;
30
- constructor(options: Options<Driver, EM> | Configuration<Driver, EM>);
58
+ constructor(options: Options<Driver, EM, Entities>);
31
59
  /**
32
60
  * Connects to the database.
33
61
  */
@@ -35,13 +63,13 @@ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver,
35
63
  /**
36
64
  * Reconnects, possibly to a different database.
37
65
  */
38
- reconnect(options?: Options): Promise<void>;
66
+ reconnect(options?: Partial<Options<Driver, EM, Entities>>): Promise<void>;
39
67
  /**
40
68
  * Checks whether the database connection is active.
41
69
  */
42
70
  isConnected(): Promise<boolean>;
43
71
  /**
44
- * Checks whether the database connection is active, returns .
72
+ * Checks whether the database connection is active, returns the reason if not.
45
73
  */
46
74
  checkConnection(): Promise<{
47
75
  ok: true;
@@ -62,8 +90,6 @@ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver,
62
90
  * Gets the `EntityMetadata` instance when provided with the `entityName` parameter.
63
91
  */
64
92
  getMetadata<Entity extends object>(entityName: EntityName<Entity>): EntityMetadata<Entity>;
65
- discoverEntities(): Promise<void>;
66
- discoverEntitiesSync(): void;
67
93
  private createEntityManager;
68
94
  /**
69
95
  * Allows dynamically discovering new entity by reference, handy for testing schema diffing.
@@ -72,33 +98,17 @@ export declare class MikroORM<Driver extends IDatabaseDriver = IDatabaseDriver,
72
98
  /**
73
99
  * Gets the SchemaGenerator.
74
100
  */
75
- getSchemaGenerator(): ReturnType<ReturnType<Driver['getPlatform']>['getSchemaGenerator']>;
76
- /**
77
- * Gets the EntityGenerator.
78
- */
79
- getEntityGenerator<T extends IEntityGenerator = IEntityGenerator>(): T;
80
- /**
81
- * Gets the Migrator.
82
- */
83
- getMigrator<T extends IMigrator = IMigrator>(): T;
101
+ get schema(): ReturnType<ReturnType<Driver['getPlatform']>['getSchemaGenerator']>;
84
102
  /**
85
103
  * Gets the SeedManager
86
104
  */
87
- getSeeder<T extends ISeedManager = ISeedManager>(): T;
88
- /**
89
- * Shortcut for `orm.getSchemaGenerator()`
90
- */
91
- get schema(): ReturnType<ReturnType<Driver["getPlatform"]>["getSchemaGenerator"]>;
92
- /**
93
- * Shortcut for `orm.getSeeder()`
94
- */
95
105
  get seeder(): ISeedManager;
96
106
  /**
97
- * Shortcut for `orm.getMigrator()`
107
+ * Gets the Migrator.
98
108
  */
99
109
  get migrator(): IMigrator;
100
110
  /**
101
- * Shortcut for `orm.getEntityGenerator()`
111
+ * Gets the EntityGenerator.
102
112
  */
103
113
  get entityGenerator(): IEntityGenerator;
104
114
  }
package/MikroORM.js CHANGED
@@ -1,14 +1,71 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MikroORM = void 0;
4
- const metadata_1 = require("./metadata");
5
- const utils_1 = require("./utils");
6
- const logging_1 = require("./logging");
7
- const cache_1 = require("./cache");
1
+ import { MetadataDiscovery } from './metadata/MetadataDiscovery.js';
2
+ import { MetadataStorage } from './metadata/MetadataStorage.js';
3
+ import { Configuration } from './utils/Configuration.js';
4
+ import { loadEnvironmentVars } from './utils/env-vars.js';
5
+ import { Utils } from './utils/Utils.js';
6
+ import { colors } from './logging/colors.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
+ }
8
40
  /**
9
- * 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
+ * ```
10
67
  */
11
- class MikroORM {
68
+ export class MikroORM {
12
69
  /** The global EntityManager instance. If you are using `RequestContext` helper, it will automatically pick the request specific context under the hood */
13
70
  em;
14
71
  driver;
@@ -21,43 +78,18 @@ class MikroORM {
21
78
  * If you omit the `options` parameter, your CLI config will be used.
22
79
  */
23
80
  static async init(options) {
24
- // for back-compatibility only, used by @mikro-orm/nestjs v5
25
- if (options instanceof utils_1.Configuration) {
26
- options = options.getAll();
27
- }
28
- utils_1.ConfigurationLoader.registerDotenv(options);
29
- const coreVersion = await utils_1.ConfigurationLoader.checkPackageVersion();
30
- const env = utils_1.ConfigurationLoader.loadEnvironmentVars();
81
+ /* v8 ignore next */
31
82
  if (!options) {
32
- const configPathFromArg = utils_1.ConfigurationLoader.configPathsFromArg();
33
- const config = (await utils_1.ConfigurationLoader.getConfiguration(process.env.MIKRO_ORM_CONTEXT_NAME ?? 'default', configPathFromArg ?? utils_1.ConfigurationLoader.getConfigPaths()));
34
- options = config.getAll();
35
- if (configPathFromArg) {
36
- 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' });
37
- }
38
- }
39
- options = utils_1.Utils.mergeConfig(options, env);
40
- await utils_1.ConfigurationLoader.commonJSCompat(options);
41
- if ('DRIVER' in this && !options.driver) {
42
- options.driver = this.DRIVER;
43
- }
44
- const orm = new MikroORM(options);
45
- orm.logger.log('info', `MikroORM version: ${logging_1.colors.green(coreVersion)}`);
46
- // we need to allow global context here as we are not in a scope of requests yet
47
- const allowGlobalContext = orm.config.get('allowGlobalContext');
48
- orm.config.set('allowGlobalContext', true);
49
- await orm.discoverEntities();
50
- orm.config.set('allowGlobalContext', allowGlobalContext);
51
- orm.driver.getPlatform().init(orm);
52
- if (orm.config.get('connect')) {
53
- await orm.connect();
54
- }
55
- for (const extension of orm.config.get('extensions')) {
56
- extension.register(orm);
57
- }
58
- if (orm.config.get('connect') && orm.config.get('ensureIndexes')) {
59
- await orm.getSchemaGenerator().ensureIndexes();
60
- }
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();
61
93
  return orm;
62
94
  }
63
95
  /**
@@ -65,74 +97,38 @@ class MikroORM {
65
97
  * - database connection will be established when you first interact with the database (or you can use `orm.connect()` explicitly)
66
98
  * - no loading of the `config` file, `options` parameter is mandatory
67
99
  * - no support for folder based discovery
68
- * - no check for mismatched package versions
69
100
  */
70
- static initSync(options) {
71
- // for back-compatibility only, used by @mikro-orm/nestjs v5
72
- if (options instanceof utils_1.Configuration) {
73
- options = options.getAll();
74
- }
75
- utils_1.ConfigurationLoader.registerDotenv(options);
76
- const env = utils_1.ConfigurationLoader.loadEnvironmentVars();
77
- options = utils_1.Utils.merge(options, env);
78
- if ('DRIVER' in this && !options.driver) {
79
- options.driver = this.DRIVER;
80
- }
81
- const orm = new MikroORM(options);
82
- // we need to allow global context here as we are not in a scope of requests yet
83
- const allowGlobalContext = orm.config.get('allowGlobalContext');
84
- orm.config.set('allowGlobalContext', true);
85
- orm.discoverEntitiesSync();
86
- orm.config.set('allowGlobalContext', allowGlobalContext);
87
- orm.driver.getPlatform().init(orm);
88
- for (const extension of orm.config.get('extensions')) {
89
- extension.register(orm);
90
- }
91
- return orm;
92
- }
93
101
  constructor(options) {
94
- if (options instanceof utils_1.Configuration) {
95
- this.config = options;
96
- }
97
- else {
98
- this.config = new utils_1.Configuration(options);
99
- }
102
+ const env = loadEnvironmentVars();
103
+ options = Utils.merge(options, env);
104
+ this.config = new Configuration(options);
100
105
  const discovery = this.config.get('discovery');
101
- if (discovery.disableDynamicFileAccess) {
102
- this.config.set('metadataProvider', metadata_1.ReflectMetadataProvider);
103
- this.config.set('metadataCache', { adapter: cache_1.NullCacheAdapter });
104
- discovery.requireEntitiesArray = true;
105
- }
106
106
  this.driver = this.config.getDriver();
107
107
  this.logger = this.config.getLogger();
108
- this.discovery = new metadata_1.MetadataDiscovery(new metadata_1.MetadataStorage(), this.driver.getPlatform(), this.config);
108
+ this.logger.log('info', `MikroORM version: ${colors.green(Utils.getORMVersion())}`);
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
+ }
109
118
  }
110
119
  /**
111
120
  * Connects to the database.
112
121
  */
113
122
  async connect() {
114
- const connection = await this.driver.connect();
115
- const clientUrl = connection.getClientUrl();
116
- const dbName = this.config.get('dbName');
117
- const db = dbName + (clientUrl ? ' on ' + clientUrl : '');
118
- if (this.config.get('ensureDatabase')) {
119
- const options = this.config.get('ensureDatabase');
120
- await this.schema.ensureDatabase(typeof options === 'boolean' ? {} : { ...options, forceCheck: true });
121
- }
122
- if (await this.isConnected()) {
123
- this.logger.log('info', `MikroORM successfully connected to database ${logging_1.colors.green(db)}`);
124
- }
125
- else {
126
- this.logger.error('info', `MikroORM failed to connect to database ${db}`);
127
- }
123
+ await this.driver.connect();
128
124
  return this.driver;
129
125
  }
130
126
  /**
131
127
  * Reconnects, possibly to a different database.
132
128
  */
133
129
  async reconnect(options = {}) {
134
- /* istanbul ignore next */
135
- for (const key of utils_1.Utils.keys(options)) {
130
+ /* v8 ignore next */
131
+ for (const key of Utils.keys(options)) {
136
132
  this.config.set(key, options[key]);
137
133
  }
138
134
  await this.driver.reconnect();
@@ -144,7 +140,7 @@ class MikroORM {
144
140
  return this.driver.getConnection().isConnected();
145
141
  }
146
142
  /**
147
- * Checks whether the database connection is active, returns .
143
+ * Checks whether the database connection is active, returns the reason if not.
148
144
  */
149
145
  async checkConnection() {
150
146
  return this.driver.getConnection().checkConnection();
@@ -153,34 +149,20 @@ class MikroORM {
153
149
  * Closes the database connection.
154
150
  */
155
151
  async close(force = false) {
156
- if (await this.isConnected()) {
157
- await this.driver.close(force);
158
- }
159
- if (this.config.getMetadataCacheAdapter()?.close) {
160
- await this.config.getMetadataCacheAdapter().close();
161
- }
162
- if (this.config.getResultCacheAdapter()?.close) {
163
- await this.config.getResultCacheAdapter().close();
164
- }
152
+ await this.driver.close(force);
153
+ await this.config.getMetadataCacheAdapter()?.close?.();
154
+ await this.config.getResultCacheAdapter()?.close?.();
165
155
  }
166
156
  /**
167
157
  * Gets the `MetadataStorage` (without parameters) or `EntityMetadata` instance when provided with the `entityName` parameter.
168
158
  */
169
159
  getMetadata(entityName) {
170
160
  if (entityName) {
171
- entityName = utils_1.Utils.className(entityName);
161
+ entityName = Utils.className(entityName);
172
162
  return this.metadata.get(entityName);
173
163
  }
174
164
  return this.metadata;
175
165
  }
176
- async discoverEntities() {
177
- this.metadata = await this.discovery.discover(this.config.get('preferTs'));
178
- this.createEntityManager();
179
- }
180
- discoverEntitiesSync() {
181
- this.metadata = this.discovery.discoverSync(this.config.get('preferTs'));
182
- this.createEntityManager();
183
- }
184
166
  createEntityManager() {
185
167
  this.driver.setMetadata(this.metadata);
186
168
  this.em = this.driver.createEntityManager();
@@ -192,73 +174,40 @@ class MikroORM {
192
174
  * Allows dynamically discovering new entity by reference, handy for testing schema diffing.
193
175
  */
194
176
  discoverEntity(entities, reset) {
195
- entities = utils_1.Utils.asArray(entities);
196
- for (const className of utils_1.Utils.asArray(reset)) {
177
+ for (const className of Utils.asArray(reset)) {
197
178
  this.metadata.reset(className);
198
179
  this.discovery.reset(className);
199
180
  }
200
- const tmp = this.discovery.discoverReferences(entities);
201
- const options = this.config.get('discovery');
202
- new metadata_1.MetadataValidator().validateDiscovered([...Object.values(this.metadata.getAll()), ...tmp], options);
181
+ const tmp = this.discovery.discoverReferences(Utils.asArray(entities));
203
182
  const metadata = this.discovery.processDiscoveredEntities(tmp);
204
- metadata.forEach(meta => {
183
+ for (const meta of metadata) {
205
184
  this.metadata.set(meta.className, meta);
206
185
  meta.root = this.metadata.get(meta.root.className);
207
- });
186
+ }
208
187
  this.metadata.decorate(this.em);
209
188
  }
210
189
  /**
211
190
  * Gets the SchemaGenerator.
212
191
  */
213
- getSchemaGenerator() {
214
- const extension = this.config.getExtension('@mikro-orm/schema-generator');
215
- if (extension) {
216
- return extension;
217
- }
218
- /* istanbul ignore next */
219
- throw new Error(`SchemaGenerator extension not registered.`);
220
- }
221
- /**
222
- * Gets the EntityGenerator.
223
- */
224
- getEntityGenerator() {
225
- return this.driver.getPlatform().getExtension('EntityGenerator', '@mikro-orm/entity-generator', '@mikro-orm/entity-generator', this.em);
226
- }
227
- /**
228
- * Gets the Migrator.
229
- */
230
- getMigrator() {
231
- return this.driver.getPlatform().getExtension('Migrator', '@mikro-orm/migrator', '@mikro-orm/migrations', this.em);
232
- }
233
- /**
234
- * Gets the SeedManager
235
- */
236
- getSeeder() {
237
- return this.driver.getPlatform().getExtension('SeedManager', '@mikro-orm/seeder', '@mikro-orm/seeder', this.em);
238
- }
239
- /**
240
- * Shortcut for `orm.getSchemaGenerator()`
241
- */
242
192
  get schema() {
243
- return this.getSchemaGenerator();
193
+ return this.config.getExtension('@mikro-orm/schema-generator');
244
194
  }
245
195
  /**
246
- * Shortcut for `orm.getSeeder()`
196
+ * Gets the SeedManager
247
197
  */
248
198
  get seeder() {
249
- return this.getSeeder();
199
+ return this.driver.getPlatform().getExtension('SeedManager', '@mikro-orm/seeder', '@mikro-orm/seeder', this.em);
250
200
  }
251
201
  /**
252
- * Shortcut for `orm.getMigrator()`
202
+ * Gets the Migrator.
253
203
  */
254
204
  get migrator() {
255
- return this.getMigrator();
205
+ return this.driver.getPlatform().getExtension('Migrator', '@mikro-orm/migrator', '@mikro-orm/migrations', this.em);
256
206
  }
257
207
  /**
258
- * Shortcut for `orm.getEntityGenerator()`
208
+ * Gets the EntityGenerator.
259
209
  */
260
210
  get entityGenerator() {
261
- return this.getEntityGenerator();
211
+ return this.driver.getPlatform().getExtension('EntityGenerator', '@mikro-orm/entity-generator', '@mikro-orm/entity-generator', this.em);
262
212
  }
263
213
  }
264
- exports.MikroORM = MikroORM;
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).
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,4 +1,4 @@
1
- import type { SyncCacheAdapter } from './CacheAdapter';
1
+ import type { SyncCacheAdapter } from './CacheAdapter.js';
2
2
  export declare class FileCacheAdapter implements SyncCacheAdapter {
3
3
  private readonly options;
4
4
  private readonly baseDir;
@@ -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,32 +1,27 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.FileCacheAdapter = void 0;
7
- const globby_1 = __importDefault(require("globby"));
8
- const fs_extra_1 = require("fs-extra");
9
- const Utils_1 = require("../utils/Utils");
10
- class FileCacheAdapter {
1
+ import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
2
+ import { fs } from '../utils/fs-utils.js';
3
+ import { Utils } from '../utils/Utils.js';
4
+ export class FileCacheAdapter {
11
5
  options;
12
6
  baseDir;
13
7
  pretty;
14
- VERSION = Utils_1.Utils.getORMVersion();
8
+ VERSION = Utils.getORMVersion();
15
9
  cache = {};
16
- constructor(options, baseDir, pretty = false) {
10
+ constructor(options = {}, baseDir, pretty = false) {
17
11
  this.options = options;
18
12
  this.baseDir = baseDir;
19
13
  this.pretty = pretty;
14
+ this.options.cacheDir ??= process.cwd() + '/temp';
20
15
  }
21
16
  /**
22
17
  * @inheritDoc
23
18
  */
24
19
  get(name) {
25
20
  const path = this.path(name);
26
- if (!(0, fs_extra_1.pathExistsSync)(path)) {
21
+ if (!existsSync(path)) {
27
22
  return null;
28
23
  }
29
- const payload = (0, fs_extra_1.readJSONSync)(path);
24
+ const payload = fs.readJSONSync(path);
30
25
  const hash = this.getHash(payload.origin);
31
26
  if (!hash || payload.hash !== hash) {
32
27
  return null;
@@ -43,23 +38,22 @@ class FileCacheAdapter {
43
38
  }
44
39
  const path = this.path(name);
45
40
  const hash = this.getHash(origin);
46
- const opts = this.pretty ? { spaces: 2 } : {};
47
- (0, fs_extra_1.writeJSONSync)(path, { data, origin, hash, version: this.VERSION }, opts);
41
+ writeFileSync(path, JSON.stringify({ data, origin, hash, version: this.VERSION }, null, this.pretty ? 2 : undefined));
48
42
  }
49
43
  /**
50
44
  * @inheritDoc
51
45
  */
52
46
  remove(name) {
53
47
  const path = this.path(name);
54
- (0, fs_extra_1.unlinkSync)(path);
48
+ unlinkSync(path);
55
49
  }
56
50
  /**
57
51
  * @inheritDoc
58
52
  */
59
53
  clear() {
60
54
  const path = this.path('*');
61
- const files = globby_1.default.sync(path);
62
- files.forEach(file => (0, fs_extra_1.unlinkSync)(file));
55
+ const files = fs.glob(path);
56
+ files.forEach(file => unlinkSync(file));
63
57
  this.cache = {};
64
58
  }
65
59
  combine() {
@@ -69,22 +63,21 @@ class FileCacheAdapter {
69
63
  let path = typeof this.options.combined === 'string'
70
64
  ? this.options.combined
71
65
  : './metadata.json';
72
- path = Utils_1.Utils.normalizePath(this.options.cacheDir, path);
66
+ path = Utils.normalizePath(this.options.cacheDir, path);
73
67
  this.options.combined = path; // override in the options, so we can log it from the CLI in `cache:generate` command
74
- (0, fs_extra_1.writeJSONSync)(path, this.cache, { spaces: this.pretty ? 2 : undefined });
68
+ writeFileSync(path, JSON.stringify(this.cache, null, this.pretty ? 2 : undefined));
75
69
  return path;
76
70
  }
77
71
  path(name) {
78
- (0, fs_extra_1.ensureDirSync)(this.options.cacheDir);
72
+ fs.ensureDir(this.options.cacheDir);
79
73
  return `${this.options.cacheDir}/${name}.json`;
80
74
  }
81
75
  getHash(origin) {
82
- origin = Utils_1.Utils.absolutePath(origin, this.baseDir);
83
- if (!(0, fs_extra_1.pathExistsSync)(origin)) {
76
+ origin = Utils.absolutePath(origin, this.baseDir);
77
+ if (!existsSync(origin)) {
84
78
  return null;
85
79
  }
86
- const contents = (0, fs_extra_1.readFileSync)(origin);
87
- return Utils_1.Utils.hash(contents.toString() + this.VERSION);
80
+ const contents = readFileSync(origin);
81
+ return Utils.hash(contents.toString() + this.VERSION);
88
82
  }
89
83
  }
90
- exports.FileCacheAdapter = FileCacheAdapter;
@@ -1,7 +1,6 @@
1
- import type { CacheAdapter } from './CacheAdapter';
2
- import type { Dictionary } from '../typings';
1
+ import type { CacheAdapter } from './CacheAdapter.js';
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;