@mikro-orm/core 7.0.2-dev.8 → 7.0.2

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 (207) hide show
  1. package/EntityManager.d.ts +883 -579
  2. package/EntityManager.js +1897 -1865
  3. package/MikroORM.d.ts +103 -72
  4. package/MikroORM.js +178 -177
  5. package/README.md +128 -294
  6. package/cache/CacheAdapter.d.ts +38 -36
  7. package/cache/FileCacheAdapter.d.ts +30 -24
  8. package/cache/FileCacheAdapter.js +80 -78
  9. package/cache/GeneratedCacheAdapter.d.ts +19 -20
  10. package/cache/GeneratedCacheAdapter.js +31 -30
  11. package/cache/MemoryCacheAdapter.d.ts +19 -20
  12. package/cache/MemoryCacheAdapter.js +36 -36
  13. package/cache/NullCacheAdapter.d.ts +17 -16
  14. package/cache/NullCacheAdapter.js +25 -24
  15. package/connections/Connection.d.ts +99 -75
  16. package/connections/Connection.js +166 -160
  17. package/drivers/DatabaseDriver.d.ts +187 -69
  18. package/drivers/DatabaseDriver.js +451 -432
  19. package/drivers/IDatabaseDriver.d.ts +464 -281
  20. package/drivers/IDatabaseDriver.js +1 -0
  21. package/entity/BaseEntity.d.ts +121 -73
  22. package/entity/BaseEntity.js +44 -33
  23. package/entity/Collection.d.ts +216 -157
  24. package/entity/Collection.js +728 -707
  25. package/entity/EntityAssigner.d.ts +90 -76
  26. package/entity/EntityAssigner.js +232 -229
  27. package/entity/EntityFactory.d.ts +68 -40
  28. package/entity/EntityFactory.js +427 -366
  29. package/entity/EntityHelper.d.ts +34 -22
  30. package/entity/EntityHelper.js +280 -267
  31. package/entity/EntityIdentifier.d.ts +4 -4
  32. package/entity/EntityIdentifier.js +10 -10
  33. package/entity/EntityLoader.d.ts +105 -56
  34. package/entity/EntityLoader.js +754 -722
  35. package/entity/EntityRepository.d.ts +317 -200
  36. package/entity/EntityRepository.js +214 -212
  37. package/entity/PolymorphicRef.d.ts +5 -5
  38. package/entity/PolymorphicRef.js +10 -10
  39. package/entity/Reference.d.ts +130 -66
  40. package/entity/Reference.js +280 -260
  41. package/entity/WrappedEntity.d.ts +116 -53
  42. package/entity/WrappedEntity.js +169 -147
  43. package/entity/defineEntity.d.ts +1290 -614
  44. package/entity/defineEntity.js +521 -511
  45. package/entity/utils.d.ts +13 -3
  46. package/entity/utils.js +71 -73
  47. package/entity/validators.js +43 -43
  48. package/entity/wrap.js +8 -8
  49. package/enums.d.ts +275 -138
  50. package/enums.js +268 -137
  51. package/errors.d.ts +120 -72
  52. package/errors.js +356 -253
  53. package/events/EventManager.d.ts +27 -10
  54. package/events/EventManager.js +80 -73
  55. package/events/EventSubscriber.d.ts +33 -29
  56. package/events/TransactionEventBroadcaster.d.ts +16 -7
  57. package/events/TransactionEventBroadcaster.js +15 -13
  58. package/exceptions.d.ts +23 -40
  59. package/exceptions.js +35 -52
  60. package/hydration/Hydrator.d.ts +43 -16
  61. package/hydration/Hydrator.js +44 -42
  62. package/hydration/ObjectHydrator.d.ts +51 -17
  63. package/hydration/ObjectHydrator.js +480 -416
  64. package/index.d.ts +116 -2
  65. package/index.js +10 -1
  66. package/logging/DefaultLogger.d.ts +35 -30
  67. package/logging/DefaultLogger.js +87 -84
  68. package/logging/Logger.d.ts +45 -40
  69. package/logging/SimpleLogger.d.ts +13 -11
  70. package/logging/SimpleLogger.js +22 -22
  71. package/logging/colors.d.ts +6 -6
  72. package/logging/colors.js +11 -10
  73. package/logging/inspect.js +7 -7
  74. package/metadata/EntitySchema.d.ts +214 -108
  75. package/metadata/EntitySchema.js +398 -379
  76. package/metadata/MetadataDiscovery.d.ts +115 -111
  77. package/metadata/MetadataDiscovery.js +1948 -1857
  78. package/metadata/MetadataProvider.d.ts +25 -14
  79. package/metadata/MetadataProvider.js +83 -77
  80. package/metadata/MetadataStorage.d.ts +39 -19
  81. package/metadata/MetadataStorage.js +119 -106
  82. package/metadata/MetadataValidator.d.ts +39 -39
  83. package/metadata/MetadataValidator.js +381 -338
  84. package/metadata/discover-entities.d.ts +5 -2
  85. package/metadata/discover-entities.js +27 -27
  86. package/metadata/types.d.ts +615 -531
  87. package/naming-strategy/AbstractNamingStrategy.d.ts +55 -39
  88. package/naming-strategy/AbstractNamingStrategy.js +91 -85
  89. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  90. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  91. package/naming-strategy/MongoNamingStrategy.d.ts +7 -6
  92. package/naming-strategy/MongoNamingStrategy.js +19 -18
  93. package/naming-strategy/NamingStrategy.d.ts +109 -99
  94. package/naming-strategy/UnderscoreNamingStrategy.d.ts +8 -7
  95. package/naming-strategy/UnderscoreNamingStrategy.js +22 -21
  96. package/not-supported.js +7 -4
  97. package/package.json +1 -1
  98. package/platforms/ExceptionConverter.d.ts +2 -1
  99. package/platforms/ExceptionConverter.js +5 -4
  100. package/platforms/Platform.d.ts +310 -236
  101. package/platforms/Platform.js +661 -573
  102. package/serialization/EntitySerializer.d.ts +49 -25
  103. package/serialization/EntitySerializer.js +224 -216
  104. package/serialization/EntityTransformer.d.ts +11 -5
  105. package/serialization/EntityTransformer.js +220 -216
  106. package/serialization/SerializationContext.d.ts +27 -18
  107. package/serialization/SerializationContext.js +105 -100
  108. package/types/ArrayType.d.ts +9 -8
  109. package/types/ArrayType.js +34 -33
  110. package/types/BigIntType.d.ts +17 -10
  111. package/types/BigIntType.js +37 -37
  112. package/types/BlobType.d.ts +4 -3
  113. package/types/BlobType.js +14 -13
  114. package/types/BooleanType.d.ts +5 -4
  115. package/types/BooleanType.js +13 -12
  116. package/types/CharacterType.d.ts +3 -2
  117. package/types/CharacterType.js +7 -6
  118. package/types/DateTimeType.d.ts +6 -5
  119. package/types/DateTimeType.js +16 -15
  120. package/types/DateType.d.ts +6 -5
  121. package/types/DateType.js +16 -15
  122. package/types/DecimalType.d.ts +7 -7
  123. package/types/DecimalType.js +26 -26
  124. package/types/DoubleType.d.ts +3 -3
  125. package/types/DoubleType.js +12 -12
  126. package/types/EnumArrayType.d.ts +6 -5
  127. package/types/EnumArrayType.js +25 -24
  128. package/types/EnumType.d.ts +4 -3
  129. package/types/EnumType.js +12 -11
  130. package/types/FloatType.d.ts +4 -3
  131. package/types/FloatType.js +10 -9
  132. package/types/IntegerType.d.ts +4 -3
  133. package/types/IntegerType.js +10 -9
  134. package/types/IntervalType.d.ts +5 -4
  135. package/types/IntervalType.js +13 -12
  136. package/types/JsonType.d.ts +9 -8
  137. package/types/JsonType.js +33 -32
  138. package/types/MediumIntType.d.ts +2 -1
  139. package/types/MediumIntType.js +4 -3
  140. package/types/SmallIntType.d.ts +4 -3
  141. package/types/SmallIntType.js +10 -9
  142. package/types/StringType.d.ts +5 -4
  143. package/types/StringType.js +13 -12
  144. package/types/TextType.d.ts +4 -3
  145. package/types/TextType.js +10 -9
  146. package/types/TimeType.d.ts +6 -5
  147. package/types/TimeType.js +18 -17
  148. package/types/TinyIntType.d.ts +4 -3
  149. package/types/TinyIntType.js +11 -10
  150. package/types/Type.d.ts +88 -73
  151. package/types/Type.js +85 -74
  152. package/types/Uint8ArrayType.d.ts +5 -4
  153. package/types/Uint8ArrayType.js +22 -21
  154. package/types/UnknownType.d.ts +5 -4
  155. package/types/UnknownType.js +13 -12
  156. package/types/UuidType.d.ts +6 -5
  157. package/types/UuidType.js +20 -19
  158. package/types/index.d.ts +77 -49
  159. package/types/index.js +64 -26
  160. package/typings.d.ts +1388 -729
  161. package/typings.js +255 -231
  162. package/unit-of-work/ChangeSet.d.ts +28 -24
  163. package/unit-of-work/ChangeSet.js +58 -54
  164. package/unit-of-work/ChangeSetComputer.d.ts +13 -11
  165. package/unit-of-work/ChangeSetComputer.js +180 -159
  166. package/unit-of-work/ChangeSetPersister.d.ts +64 -41
  167. package/unit-of-work/ChangeSetPersister.js +443 -418
  168. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  169. package/unit-of-work/CommitOrderCalculator.js +89 -88
  170. package/unit-of-work/IdentityMap.d.ts +32 -25
  171. package/unit-of-work/IdentityMap.js +106 -99
  172. package/unit-of-work/UnitOfWork.d.ts +182 -127
  173. package/unit-of-work/UnitOfWork.js +1201 -1169
  174. package/utils/AbstractMigrator.d.ts +111 -91
  175. package/utils/AbstractMigrator.js +275 -275
  176. package/utils/AbstractSchemaGenerator.d.ts +43 -34
  177. package/utils/AbstractSchemaGenerator.js +121 -122
  178. package/utils/AsyncContext.d.ts +3 -3
  179. package/utils/AsyncContext.js +34 -35
  180. package/utils/Configuration.d.ts +853 -801
  181. package/utils/Configuration.js +360 -337
  182. package/utils/Cursor.d.ts +40 -22
  183. package/utils/Cursor.js +135 -127
  184. package/utils/DataloaderUtils.d.ts +58 -43
  185. package/utils/DataloaderUtils.js +203 -198
  186. package/utils/EntityComparator.d.ts +99 -80
  187. package/utils/EntityComparator.js +825 -727
  188. package/utils/NullHighlighter.d.ts +2 -1
  189. package/utils/NullHighlighter.js +4 -3
  190. package/utils/QueryHelper.d.ts +79 -51
  191. package/utils/QueryHelper.js +372 -361
  192. package/utils/RawQueryFragment.d.ts +54 -28
  193. package/utils/RawQueryFragment.js +110 -99
  194. package/utils/RequestContext.d.ts +33 -32
  195. package/utils/RequestContext.js +52 -53
  196. package/utils/TransactionContext.d.ts +17 -16
  197. package/utils/TransactionContext.js +28 -27
  198. package/utils/TransactionManager.d.ts +58 -58
  199. package/utils/TransactionManager.js +199 -197
  200. package/utils/Utils.d.ts +210 -145
  201. package/utils/Utils.js +820 -813
  202. package/utils/clone.js +104 -113
  203. package/utils/env-vars.js +90 -88
  204. package/utils/fs-utils.d.ts +15 -15
  205. package/utils/fs-utils.js +180 -181
  206. package/utils/upsert-utils.d.ts +20 -5
  207. package/utils/upsert-utils.js +114 -116
@@ -12,371 +12,394 @@ import { MemoryCacheAdapter } from '../cache/MemoryCacheAdapter.js';
12
12
  import { EntityComparator } from './EntityComparator.js';
13
13
  import { setEnv } from './env-vars.js';
14
14
  const DEFAULTS = {
15
- pool: {},
16
- entities: [],
17
- entitiesTs: [],
18
- extensions: [],
19
- subscribers: [],
20
- filters: {},
21
- discovery: {
22
- warnWhenNoEntities: true,
23
- checkDuplicateTableNames: true,
24
- checkDuplicateFieldNames: true,
25
- checkDuplicateEntities: true,
26
- checkNonPersistentCompositeProps: true,
27
- inferDefaultValues: true,
28
- },
29
- validateRequired: true,
30
- context: (name) => RequestContext.getEntityManager(name),
31
- contextName: 'default',
32
- allowGlobalContext: false,
33
- // eslint-disable-next-line no-console
34
- logger: console.log.bind(console),
35
- colors: true,
36
- findOneOrFailHandler: (entityName, where) => NotFoundError.findOneFailed(entityName, where),
37
- findExactlyOneOrFailHandler: (entityName, where) => NotFoundError.findExactlyOneFailed(entityName, where),
38
- baseDir: globalThis.process?.cwd?.(),
39
- hydrator: ObjectHydrator,
40
- flushMode: FlushMode.AUTO,
41
- loadStrategy: LoadStrategy.BALANCED,
42
- dataloader: DataloaderType.NONE,
43
- populateWhere: PopulateHint.ALL,
44
- ignoreUndefinedInQuery: false,
45
- onQuery: (sql) => sql,
46
- autoJoinOneToOneOwner: true,
47
- autoJoinRefsForFilters: true,
48
- filtersOnRelations: true,
49
- propagationOnPrototype: true,
50
- populateAfterFlush: true,
51
- serialization: {
52
- includePrimaryKeys: true,
53
- },
54
- assign: {
55
- updateNestedEntities: true,
56
- updateByPrimaryKey: true,
57
- mergeObjectProperties: false,
58
- mergeEmbeddedProperties: true,
59
- ignoreUndefined: false,
60
- },
61
- persistOnCreate: true,
62
- upsertManaged: true,
63
- forceEntityConstructor: false,
64
- forceUndefined: false,
65
- forceUtcTimezone: true,
66
- processOnCreateHooksEarly: true,
67
- ensureDatabase: true,
68
- ensureIndexes: false,
69
- batchSize: 300,
70
- debug: false,
71
- ignoreDeprecations: false,
72
- verbose: false,
73
- driverOptions: {},
74
- migrations: {
75
- tableName: 'mikro_orm_migrations',
76
- glob: '!(*.d).{js,ts,cjs}',
77
- silent: false,
78
- transactional: true,
79
- allOrNothing: true,
80
- dropTables: true,
81
- safe: false,
82
- snapshot: true,
83
- emit: 'ts',
84
- fileName: (timestamp, name) => `Migration${timestamp}${name ? '_' + name : ''}`,
85
- },
86
- schemaGenerator: {
87
- createForeignKeyConstraints: true,
88
- ignoreSchema: [],
89
- skipTables: [],
90
- skipViews: [],
91
- skipColumns: {},
92
- },
93
- embeddables: {
94
- prefixMode: 'relative',
95
- },
96
- entityGenerator: {
97
- forceUndefined: true,
98
- undefinedDefaults: false,
99
- scalarTypeInDecorator: false,
100
- bidirectionalRelations: true,
101
- identifiedReferences: true,
102
- scalarPropertiesForRelations: 'never',
103
- entityDefinition: 'defineEntity',
104
- decorators: 'legacy',
105
- enumMode: 'dictionary',
106
- /* v8 ignore next */
107
- fileName: (className) => className,
108
- onlyPurePivotTables: false,
109
- outputPurePivotTables: false,
110
- readOnlyPivotTables: false,
111
- useCoreBaseEntity: false,
112
- },
113
- metadataCache: {},
114
- resultCache: {
115
- adapter: MemoryCacheAdapter,
116
- expiration: 1000, // 1s
117
- options: {},
118
- },
119
- metadataProvider: MetadataProvider,
120
- highlighter: new NullHighlighter(),
121
- seeder: {
122
- defaultSeeder: 'DatabaseSeeder',
123
- glob: '!(*.d).{js,ts}',
124
- emit: 'ts',
125
- fileName: (className) => className,
126
- },
127
- preferReadReplicas: true,
128
- dynamicImportProvider: /* v8 ignore next */ (id) => import(id),
15
+ pool: {},
16
+ entities: [],
17
+ entitiesTs: [],
18
+ extensions: [],
19
+ subscribers: [],
20
+ filters: {},
21
+ discovery: {
22
+ warnWhenNoEntities: true,
23
+ checkDuplicateTableNames: true,
24
+ checkDuplicateFieldNames: true,
25
+ checkDuplicateEntities: true,
26
+ checkNonPersistentCompositeProps: true,
27
+ inferDefaultValues: true,
28
+ },
29
+ validateRequired: true,
30
+ context: name => RequestContext.getEntityManager(name),
31
+ contextName: 'default',
32
+ allowGlobalContext: false,
33
+ // eslint-disable-next-line no-console
34
+ logger: console.log.bind(console),
35
+ colors: true,
36
+ findOneOrFailHandler: (entityName, where) => NotFoundError.findOneFailed(entityName, where),
37
+ findExactlyOneOrFailHandler: (entityName, where) => NotFoundError.findExactlyOneFailed(entityName, where),
38
+ baseDir: globalThis.process?.cwd?.(),
39
+ hydrator: ObjectHydrator,
40
+ flushMode: FlushMode.AUTO,
41
+ loadStrategy: LoadStrategy.BALANCED,
42
+ dataloader: DataloaderType.NONE,
43
+ populateWhere: PopulateHint.ALL,
44
+ ignoreUndefinedInQuery: false,
45
+ onQuery: sql => sql,
46
+ autoJoinOneToOneOwner: true,
47
+ autoJoinRefsForFilters: true,
48
+ filtersOnRelations: true,
49
+ propagationOnPrototype: true,
50
+ populateAfterFlush: true,
51
+ serialization: {
52
+ includePrimaryKeys: true,
53
+ },
54
+ assign: {
55
+ updateNestedEntities: true,
56
+ updateByPrimaryKey: true,
57
+ mergeObjectProperties: false,
58
+ mergeEmbeddedProperties: true,
59
+ ignoreUndefined: false,
60
+ },
61
+ persistOnCreate: true,
62
+ upsertManaged: true,
63
+ forceEntityConstructor: false,
64
+ forceUndefined: false,
65
+ forceUtcTimezone: true,
66
+ processOnCreateHooksEarly: true,
67
+ ensureDatabase: true,
68
+ ensureIndexes: false,
69
+ batchSize: 300,
70
+ debug: false,
71
+ ignoreDeprecations: false,
72
+ verbose: false,
73
+ driverOptions: {},
74
+ migrations: {
75
+ tableName: 'mikro_orm_migrations',
76
+ glob: '!(*.d).{js,ts,cjs}',
77
+ silent: false,
78
+ transactional: true,
79
+ allOrNothing: true,
80
+ dropTables: true,
81
+ safe: false,
82
+ snapshot: true,
83
+ emit: 'ts',
84
+ fileName: (timestamp, name) => `Migration${timestamp}${name ? '_' + name : ''}`,
85
+ },
86
+ schemaGenerator: {
87
+ createForeignKeyConstraints: true,
88
+ ignoreSchema: [],
89
+ skipTables: [],
90
+ skipViews: [],
91
+ skipColumns: {},
92
+ },
93
+ embeddables: {
94
+ prefixMode: 'relative',
95
+ },
96
+ entityGenerator: {
97
+ forceUndefined: true,
98
+ undefinedDefaults: false,
99
+ scalarTypeInDecorator: false,
100
+ bidirectionalRelations: true,
101
+ identifiedReferences: true,
102
+ scalarPropertiesForRelations: 'never',
103
+ entityDefinition: 'defineEntity',
104
+ decorators: 'legacy',
105
+ enumMode: 'dictionary',
106
+ /* v8 ignore next */
107
+ fileName: className => className,
108
+ onlyPurePivotTables: false,
109
+ outputPurePivotTables: false,
110
+ readOnlyPivotTables: false,
111
+ useCoreBaseEntity: false,
112
+ },
113
+ metadataCache: {},
114
+ resultCache: {
115
+ adapter: MemoryCacheAdapter,
116
+ expiration: 1000, // 1s
117
+ options: {},
118
+ },
119
+ metadataProvider: MetadataProvider,
120
+ highlighter: new NullHighlighter(),
121
+ seeder: {
122
+ defaultSeeder: 'DatabaseSeeder',
123
+ glob: '!(*.d).{js,ts}',
124
+ emit: 'ts',
125
+ fileName: className => className,
126
+ },
127
+ preferReadReplicas: true,
128
+ dynamicImportProvider: /* v8 ignore next */ id => import(id),
129
129
  };
130
+ /** Holds and validates all ORM configuration options, providing access to drivers, loggers, cache adapters, and other services. */
130
131
  export class Configuration {
131
- #options;
132
- #logger;
133
- #slowQueryLogger;
134
- #driver;
135
- #platform;
136
- #cache = new Map();
137
- #extensions = new Map();
138
- constructor(options, validate = true) {
139
- if (options.dynamicImportProvider) {
140
- globalThis.dynamicImportProvider = options.dynamicImportProvider;
141
- }
142
- this.#options = Utils.mergeConfig({}, DEFAULTS, options);
143
- if (validate) {
144
- this.validateOptions();
145
- }
146
- this.#options.loggerFactory ??= DefaultLogger.create;
147
- this.#logger = this.#options.loggerFactory({
148
- debugMode: this.#options.debug,
149
- ignoreDeprecations: this.#options.ignoreDeprecations,
150
- usesReplicas: (this.#options.replicas?.length ?? 0) > 0,
151
- highlighter: this.#options.highlighter,
152
- writer: this.#options.logger,
153
- });
154
- const cf = this.#options.compiledFunctions;
155
- if (cf && cf.__version !== Utils.getORMVersion()) {
156
- this.#logger.warn('discovery', `Compiled functions were generated with MikroORM v${cf.__version ?? 'unknown'}, but the current version is v${Utils.getORMVersion()}. Please regenerate with \`npx mikro-orm compile\`.`);
157
- }
158
- if (this.#options.driver) {
159
- this.#driver = new this.#options.driver(this);
160
- this.#platform = this.#driver.getPlatform();
161
- this.#platform.setConfig(this);
162
- this.init(validate);
163
- }
132
+ #options;
133
+ #logger;
134
+ #slowQueryLogger;
135
+ #driver;
136
+ #platform;
137
+ #cache = new Map();
138
+ #extensions = new Map();
139
+ constructor(options, validate = true) {
140
+ if (options.dynamicImportProvider) {
141
+ globalThis.dynamicImportProvider = options.dynamicImportProvider;
164
142
  }
165
- getPlatform() {
166
- return this.#platform;
143
+ this.#options = Utils.mergeConfig({}, DEFAULTS, options);
144
+ if (validate) {
145
+ this.validateOptions();
167
146
  }
168
- /**
169
- * Gets specific configuration option. Falls back to specified `defaultValue` if provided.
170
- */
171
- get(key, defaultValue) {
172
- if (typeof this.#options[key] !== 'undefined') {
173
- return this.#options[key];
174
- }
175
- return defaultValue;
147
+ this.#options.loggerFactory ??= DefaultLogger.create;
148
+ this.#logger = this.#options.loggerFactory({
149
+ debugMode: this.#options.debug,
150
+ ignoreDeprecations: this.#options.ignoreDeprecations,
151
+ usesReplicas: (this.#options.replicas?.length ?? 0) > 0,
152
+ highlighter: this.#options.highlighter,
153
+ writer: this.#options.logger,
154
+ });
155
+ const cf = this.#options.compiledFunctions;
156
+ if (cf && cf.__version !== Utils.getORMVersion()) {
157
+ this.#logger.warn(
158
+ 'discovery',
159
+ `Compiled functions were generated with MikroORM v${cf.__version ?? 'unknown'}, but the current version is v${Utils.getORMVersion()}. Please regenerate with \`npx mikro-orm compile\`.`,
160
+ );
176
161
  }
177
- getAll() {
178
- return this.#options;
162
+ if (this.#options.driver) {
163
+ this.#driver = new this.#options.driver(this);
164
+ this.#platform = this.#driver.getPlatform();
165
+ this.#platform.setConfig(this);
166
+ this.init(validate);
179
167
  }
180
- /**
181
- * Overrides specified configuration value.
182
- */
183
- set(key, value) {
184
- this.#options[key] = value;
185
- this.sync();
168
+ }
169
+ /** Returns the database platform instance. */
170
+ getPlatform() {
171
+ return this.#platform;
172
+ }
173
+ /**
174
+ * Gets specific configuration option. Falls back to specified `defaultValue` if provided.
175
+ */
176
+ get(key, defaultValue) {
177
+ if (typeof this.#options[key] !== 'undefined') {
178
+ return this.#options[key];
186
179
  }
187
- /**
188
- * Resets the configuration to its default value
189
- */
190
- reset(key) {
191
- this.#options[key] = DEFAULTS[key];
180
+ return defaultValue;
181
+ }
182
+ /** Returns all configuration options. */
183
+ getAll() {
184
+ return this.#options;
185
+ }
186
+ /**
187
+ * Overrides specified configuration value.
188
+ */
189
+ set(key, value) {
190
+ this.#options[key] = value;
191
+ this.sync();
192
+ }
193
+ /**
194
+ * Resets the configuration to its default value
195
+ */
196
+ reset(key) {
197
+ this.#options[key] = DEFAULTS[key];
198
+ }
199
+ /**
200
+ * Gets Logger instance.
201
+ */
202
+ getLogger() {
203
+ return this.#logger;
204
+ }
205
+ /**
206
+ * Gets the logger instance for slow queries.
207
+ * Falls back to the main logger if no custom slow query logger factory is configured.
208
+ */
209
+ getSlowQueryLogger() {
210
+ this.#slowQueryLogger ??=
211
+ this.#options.slowQueryLoggerFactory?.({
212
+ debugMode: this.#options.debug,
213
+ writer: this.#options.logger,
214
+ highlighter: this.#options.highlighter,
215
+ usesReplicas: (this.#options.replicas?.length ?? 0) > 0,
216
+ }) ?? this.#logger;
217
+ return this.#slowQueryLogger;
218
+ }
219
+ /** Returns the configured dataloader type, normalizing boolean values. */
220
+ getDataloaderType() {
221
+ if (typeof this.#options.dataloader === 'boolean') {
222
+ return this.#options.dataloader ? DataloaderType.ALL : DataloaderType.NONE;
192
223
  }
193
- /**
194
- * Gets Logger instance.
195
- */
196
- getLogger() {
197
- return this.#logger;
224
+ return this.#options.dataloader;
225
+ }
226
+ /** Returns the configured schema name, optionally skipping the platform's default schema. */
227
+ getSchema(skipDefaultSchema = false) {
228
+ if (skipDefaultSchema && this.#options.schema === this.#platform.getDefaultSchemaName()) {
229
+ return undefined;
198
230
  }
199
- /**
200
- * Gets the logger instance for slow queries.
201
- * Falls back to the main logger if no custom slow query logger factory is configured.
202
- */
203
- getSlowQueryLogger() {
204
- this.#slowQueryLogger ??=
205
- this.#options.slowQueryLoggerFactory?.({
206
- debugMode: this.#options.debug,
207
- writer: this.#options.logger,
208
- highlighter: this.#options.highlighter,
209
- usesReplicas: (this.#options.replicas?.length ?? 0) > 0,
210
- }) ?? this.#logger;
211
- return this.#slowQueryLogger;
231
+ return this.#options.schema;
232
+ }
233
+ /**
234
+ * Gets current database driver instance.
235
+ */
236
+ getDriver() {
237
+ return this.#driver;
238
+ }
239
+ /** Registers a lazily-initialized extension by name. */
240
+ registerExtension(name, cb) {
241
+ this.#extensions.set(name, cb);
242
+ }
243
+ /** Returns a previously registered extension by name, initializing it on first access. */
244
+ getExtension(name) {
245
+ if (this.#cache.has(name)) {
246
+ return this.#cache.get(name);
212
247
  }
213
- getDataloaderType() {
214
- if (typeof this.#options.dataloader === 'boolean') {
215
- return this.#options.dataloader ? DataloaderType.ALL : DataloaderType.NONE;
216
- }
217
- return this.#options.dataloader;
248
+ const ext = this.#extensions.get(name);
249
+ /* v8 ignore next */
250
+ if (!ext) {
251
+ return undefined;
218
252
  }
219
- getSchema(skipDefaultSchema = false) {
220
- if (skipDefaultSchema && this.#options.schema === this.#platform.getDefaultSchemaName()) {
221
- return undefined;
222
- }
223
- return this.#options.schema;
253
+ this.#cache.set(name, ext());
254
+ return this.#cache.get(name);
255
+ }
256
+ /**
257
+ * Gets instance of NamingStrategy. (cached)
258
+ */
259
+ getNamingStrategy() {
260
+ return this.getCachedService(this.#options.namingStrategy || this.#platform.getNamingStrategy());
261
+ }
262
+ /**
263
+ * Gets instance of Hydrator. (cached)
264
+ */
265
+ getHydrator(metadata) {
266
+ return this.getCachedService(this.#options.hydrator, metadata, this.#platform, this);
267
+ }
268
+ /**
269
+ * Gets instance of Comparator. (cached)
270
+ */
271
+ getComparator(metadata) {
272
+ return this.getCachedService(EntityComparator, metadata, this.#platform, this);
273
+ }
274
+ /**
275
+ * Gets instance of MetadataProvider. (cached)
276
+ */
277
+ getMetadataProvider() {
278
+ return this.getCachedService(this.#options.metadataProvider, this);
279
+ }
280
+ /**
281
+ * Gets instance of metadata CacheAdapter. (cached)
282
+ */
283
+ getMetadataCacheAdapter() {
284
+ return this.getCachedService(
285
+ this.#options.metadataCache.adapter,
286
+ this.#options.metadataCache.options,
287
+ this.#options.baseDir,
288
+ this.#options.metadataCache.pretty,
289
+ );
290
+ }
291
+ /**
292
+ * Gets instance of CacheAdapter for result cache. (cached)
293
+ */
294
+ getResultCacheAdapter() {
295
+ return this.getCachedService(this.#options.resultCache.adapter, {
296
+ expiration: this.#options.resultCache.expiration,
297
+ ...this.#options.resultCache.options,
298
+ });
299
+ }
300
+ /**
301
+ * Gets EntityRepository class to be instantiated.
302
+ */
303
+ getRepositoryClass(repository) {
304
+ if (repository) {
305
+ return repository();
224
306
  }
225
- /**
226
- * Gets current database driver instance.
227
- */
228
- getDriver() {
229
- return this.#driver;
307
+ if (this.#options.entityRepository) {
308
+ return this.#options.entityRepository;
230
309
  }
231
- registerExtension(name, cb) {
232
- this.#extensions.set(name, cb);
310
+ return this.#platform.getRepositoryClass();
311
+ }
312
+ /**
313
+ * Creates instance of given service and caches it.
314
+ */
315
+ getCachedService(cls, ...args) {
316
+ if (!this.#cache.has(cls.name)) {
317
+ this.#cache.set(cls.name, new cls(...args));
233
318
  }
234
- getExtension(name) {
235
- if (this.#cache.has(name)) {
236
- return this.#cache.get(name);
237
- }
238
- const ext = this.#extensions.get(name);
239
- /* v8 ignore next */
240
- if (!ext) {
241
- return undefined;
242
- }
243
- this.#cache.set(name, ext());
244
- return this.#cache.get(name);
319
+ return this.#cache.get(cls.name);
320
+ }
321
+ /** Clears the cached service instances, forcing re-creation on next access. */
322
+ resetServiceCache() {
323
+ this.#cache.clear();
324
+ }
325
+ init(validate) {
326
+ const useCache = this.getMetadataProvider().useCache();
327
+ const metadataCache = this.#options.metadataCache;
328
+ if (!useCache) {
329
+ metadataCache.adapter = NullCacheAdapter;
245
330
  }
246
- /**
247
- * Gets instance of NamingStrategy. (cached)
248
- */
249
- getNamingStrategy() {
250
- return this.getCachedService(this.#options.namingStrategy || this.#platform.getNamingStrategy());
331
+ metadataCache.enabled ??= useCache;
332
+ this.#options.clientUrl ??= this.#platform.getDefaultClientUrl();
333
+ this.#options.implicitTransactions ??= this.#platform.usesImplicitTransactions();
334
+ if (validate && metadataCache.enabled && !metadataCache.adapter) {
335
+ throw new Error(
336
+ 'No metadata cache adapter specified, please fill in `metadataCache.adapter` option or use the async MikroORM.init() method which can autoload it.',
337
+ );
251
338
  }
252
- /**
253
- * Gets instance of Hydrator. (cached)
254
- */
255
- getHydrator(metadata) {
256
- return this.getCachedService(this.#options.hydrator, metadata, this.#platform, this);
339
+ try {
340
+ const url = new URL(this.#options.clientUrl);
341
+ if (url.pathname) {
342
+ this.#options.dbName = this.get('dbName', decodeURIComponent(url.pathname).substring(1));
343
+ }
344
+ } catch {
345
+ const url = /:\/\/.*\/([^?]+)/.exec(this.#options.clientUrl);
346
+ if (url) {
347
+ this.#options.dbName = this.get('dbName', decodeURIComponent(url[1]));
348
+ }
257
349
  }
258
- /**
259
- * Gets instance of Comparator. (cached)
260
- */
261
- getComparator(metadata) {
262
- return this.getCachedService(EntityComparator, metadata, this.#platform, this);
350
+ if (validate && !this.#options.dbName && this.#options.clientUrl) {
351
+ throw new Error("No database specified, `clientUrl` option provided but it's missing the pathname.");
263
352
  }
264
- /**
265
- * Gets instance of MetadataProvider. (cached)
266
- */
267
- getMetadataProvider() {
268
- return this.getCachedService(this.#options.metadataProvider, this);
353
+ this.#options.schema ??= this.#platform.getDefaultSchemaName();
354
+ this.#options.charset ??= this.#platform.getDefaultCharset();
355
+ Object.keys(this.#options.filters).forEach(key => {
356
+ this.#options.filters[key].default ??= true;
357
+ });
358
+ if (!this.#options.filtersOnRelations) {
359
+ this.#options.autoJoinRefsForFilters ??= false;
269
360
  }
270
- /**
271
- * Gets instance of metadata CacheAdapter. (cached)
272
- */
273
- getMetadataCacheAdapter() {
274
- return this.getCachedService(this.#options.metadataCache.adapter, this.#options.metadataCache.options, this.#options.baseDir, this.#options.metadataCache.pretty);
361
+ this.#options.subscribers = [...this.#options.subscribers].map(subscriber => {
362
+ return subscriber.constructor.name === 'Function' ? new subscriber() : subscriber;
363
+ });
364
+ this.sync();
365
+ if (!colors.enabled()) {
366
+ this.#options.highlighter = new NullHighlighter();
275
367
  }
276
- /**
277
- * Gets instance of CacheAdapter for result cache. (cached)
278
- */
279
- getResultCacheAdapter() {
280
- return this.getCachedService(this.#options.resultCache.adapter, {
281
- expiration: this.#options.resultCache.expiration,
282
- ...this.#options.resultCache.options,
283
- });
368
+ }
369
+ sync() {
370
+ setEnv('MIKRO_ORM_COLORS', this.#options.colors);
371
+ this.#logger.setDebugMode(this.#options.debug);
372
+ this.#slowQueryLogger = undefined;
373
+ }
374
+ validateOptions() {
375
+ /* v8 ignore next */
376
+ if ('type' in this.#options) {
377
+ throw new Error(
378
+ "The `type` option has been removed in v6, please fill in the `driver` option instead or use `defineConfig` helper (to define your ORM config) or `MikroORM` class (to call the `init` method) exported from the driver package (e.g. `import { defineConfig } from '@mikro-orm/mysql'; export default defineConfig({ ... })`).",
379
+ );
284
380
  }
285
- /**
286
- * Gets EntityRepository class to be instantiated.
287
- */
288
- getRepositoryClass(repository) {
289
- if (repository) {
290
- return repository();
291
- }
292
- if (this.#options.entityRepository) {
293
- return this.#options.entityRepository;
294
- }
295
- return this.#platform.getRepositoryClass();
381
+ if (!this.#options.driver) {
382
+ throw new Error(
383
+ "No driver specified, please fill in the `driver` option or use `defineConfig` helper (to define your ORM config) or `MikroORM` class (to call the `init` method) exported from the driver package (e.g. `import { defineConfig } from '@mikro-orm/mysql'; export defineConfig({ ... })`).",
384
+ );
296
385
  }
297
- /**
298
- * Creates instance of given service and caches it.
299
- */
300
- getCachedService(cls, ...args) {
301
- if (!this.#cache.has(cls.name)) {
302
- this.#cache.set(cls.name, new cls(...args));
303
- }
304
- return this.#cache.get(cls.name);
386
+ if (!this.#options.dbName && !this.#options.clientUrl) {
387
+ throw new Error('No database specified, please fill in `dbName` or `clientUrl` option');
305
388
  }
306
- resetServiceCache() {
307
- this.#cache.clear();
389
+ if (this.#options.entities.length === 0 && this.#options.discovery.warnWhenNoEntities) {
390
+ throw new Error('No entities found, please use `entities` option');
308
391
  }
309
- init(validate) {
310
- const useCache = this.getMetadataProvider().useCache();
311
- const metadataCache = this.#options.metadataCache;
312
- if (!useCache) {
313
- metadataCache.adapter = NullCacheAdapter;
314
- }
315
- metadataCache.enabled ??= useCache;
316
- this.#options.clientUrl ??= this.#platform.getDefaultClientUrl();
317
- this.#options.implicitTransactions ??= this.#platform.usesImplicitTransactions();
318
- if (validate && metadataCache.enabled && !metadataCache.adapter) {
319
- throw new Error('No metadata cache adapter specified, please fill in `metadataCache.adapter` option or use the async MikroORM.init() method which can autoload it.');
320
- }
321
- try {
322
- const url = new URL(this.#options.clientUrl);
323
- if (url.pathname) {
324
- this.#options.dbName = this.get('dbName', decodeURIComponent(url.pathname).substring(1));
325
- }
326
- }
327
- catch {
328
- const url = /:\/\/.*\/([^?]+)/.exec(this.#options.clientUrl);
329
- if (url) {
330
- this.#options.dbName = this.get('dbName', decodeURIComponent(url[1]));
331
- }
332
- }
333
- if (validate && !this.#options.dbName && this.#options.clientUrl) {
334
- throw new Error("No database specified, `clientUrl` option provided but it's missing the pathname.");
335
- }
336
- this.#options.schema ??= this.#platform.getDefaultSchemaName();
337
- this.#options.charset ??= this.#platform.getDefaultCharset();
338
- Object.keys(this.#options.filters).forEach(key => {
339
- this.#options.filters[key].default ??= true;
340
- });
341
- if (!this.#options.filtersOnRelations) {
342
- this.#options.autoJoinRefsForFilters ??= false;
343
- }
344
- this.#options.subscribers = [...this.#options.subscribers].map(subscriber => {
345
- return subscriber.constructor.name === 'Function' ? new subscriber() : subscriber;
346
- });
347
- this.sync();
348
- if (!colors.enabled()) {
349
- this.#options.highlighter = new NullHighlighter();
350
- }
351
- }
352
- sync() {
353
- setEnv('MIKRO_ORM_COLORS', this.#options.colors);
354
- this.#logger.setDebugMode(this.#options.debug);
355
- this.#slowQueryLogger = undefined;
356
- }
357
- validateOptions() {
358
- /* v8 ignore next */
359
- if ('type' in this.#options) {
360
- throw new Error("The `type` option has been removed in v6, please fill in the `driver` option instead or use `defineConfig` helper (to define your ORM config) or `MikroORM` class (to call the `init` method) exported from the driver package (e.g. `import { defineConfig } from '@mikro-orm/mysql'; export default defineConfig({ ... })`).");
361
- }
362
- if (!this.#options.driver) {
363
- throw new Error("No driver specified, please fill in the `driver` option or use `defineConfig` helper (to define your ORM config) or `MikroORM` class (to call the `init` method) exported from the driver package (e.g. `import { defineConfig } from '@mikro-orm/mysql'; export defineConfig({ ... })`).");
364
- }
365
- if (!this.#options.dbName && !this.#options.clientUrl) {
366
- throw new Error('No database specified, please fill in `dbName` or `clientUrl` option');
367
- }
368
- if (this.#options.entities.length === 0 && this.#options.discovery.warnWhenNoEntities) {
369
- throw new Error('No entities found, please use `entities` option');
370
- }
371
- if (typeof this.#options.driverOptions === 'function' &&
372
- this.#options.driverOptions.constructor.name === 'AsyncFunction') {
373
- throw new Error('`driverOptions` callback cannot be async');
374
- }
392
+ if (
393
+ typeof this.#options.driverOptions === 'function' &&
394
+ this.#options.driverOptions.constructor.name === 'AsyncFunction'
395
+ ) {
396
+ throw new Error('`driverOptions` callback cannot be async');
375
397
  }
398
+ }
376
399
  }
377
400
  /**
378
401
  * Type helper to make it easier to use `mikro-orm.config.js`.
379
402
  */
380
403
  export function defineConfig(options) {
381
- return options;
404
+ return options;
382
405
  }