@mikro-orm/core 7.0.0-dev.12 → 7.0.0-dev.121

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 +85 -56
  2. package/EntityManager.js +332 -293
  3. package/MikroORM.d.ts +41 -32
  4. package/MikroORM.js +100 -140
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +8 -7
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +0 -1
  11. package/cache/index.js +0 -1
  12. package/connections/Connection.d.ts +16 -7
  13. package/connections/Connection.js +23 -14
  14. package/drivers/DatabaseDriver.d.ts +25 -16
  15. package/drivers/DatabaseDriver.js +40 -24
  16. package/drivers/IDatabaseDriver.d.ts +38 -17
  17. package/entity/BaseEntity.d.ts +0 -1
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +95 -30
  20. package/entity/Collection.js +439 -99
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +26 -18
  23. package/entity/EntityFactory.d.ts +7 -0
  24. package/entity/EntityFactory.js +72 -53
  25. package/entity/EntityHelper.d.ts +2 -2
  26. package/entity/EntityHelper.js +30 -15
  27. package/entity/EntityLoader.d.ts +7 -6
  28. package/entity/EntityLoader.js +84 -72
  29. package/entity/EntityRepository.d.ts +1 -1
  30. package/entity/EntityRepository.js +2 -2
  31. package/entity/Reference.d.ts +6 -5
  32. package/entity/Reference.js +34 -9
  33. package/entity/WrappedEntity.d.ts +2 -7
  34. package/entity/WrappedEntity.js +3 -8
  35. package/entity/defineEntity.d.ts +568 -0
  36. package/entity/defineEntity.js +529 -0
  37. package/entity/index.d.ts +3 -2
  38. package/entity/index.js +3 -2
  39. package/entity/utils.d.ts +7 -0
  40. package/entity/utils.js +16 -4
  41. package/entity/validators.d.ts +11 -0
  42. package/entity/validators.js +65 -0
  43. package/enums.d.ts +21 -6
  44. package/enums.js +14 -1
  45. package/errors.d.ts +17 -9
  46. package/errors.js +41 -21
  47. package/events/EventManager.d.ts +2 -1
  48. package/events/EventManager.js +19 -11
  49. package/hydration/Hydrator.js +1 -2
  50. package/hydration/ObjectHydrator.d.ts +4 -4
  51. package/hydration/ObjectHydrator.js +50 -33
  52. package/index.d.ts +2 -2
  53. package/index.js +1 -2
  54. package/logging/DefaultLogger.d.ts +1 -1
  55. package/logging/DefaultLogger.js +1 -0
  56. package/logging/SimpleLogger.d.ts +1 -1
  57. package/logging/colors.d.ts +1 -1
  58. package/logging/colors.js +7 -6
  59. package/logging/index.d.ts +1 -0
  60. package/logging/index.js +1 -0
  61. package/logging/inspect.d.ts +2 -0
  62. package/logging/inspect.js +11 -0
  63. package/metadata/EntitySchema.d.ts +22 -24
  64. package/metadata/EntitySchema.js +73 -51
  65. package/metadata/MetadataDiscovery.d.ts +6 -10
  66. package/metadata/MetadataDiscovery.js +289 -298
  67. package/metadata/MetadataProvider.d.ts +11 -2
  68. package/metadata/MetadataProvider.js +46 -2
  69. package/metadata/MetadataStorage.d.ts +13 -11
  70. package/metadata/MetadataStorage.js +70 -37
  71. package/metadata/MetadataValidator.d.ts +2 -9
  72. package/metadata/MetadataValidator.js +22 -38
  73. package/metadata/discover-entities.d.ts +5 -0
  74. package/metadata/discover-entities.js +40 -0
  75. package/metadata/index.d.ts +1 -1
  76. package/metadata/index.js +1 -1
  77. package/metadata/types.d.ts +480 -0
  78. package/metadata/types.js +1 -0
  79. package/naming-strategy/AbstractNamingStrategy.d.ts +8 -4
  80. package/naming-strategy/AbstractNamingStrategy.js +8 -2
  81. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  82. package/naming-strategy/EntityCaseNamingStrategy.js +6 -5
  83. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  84. package/naming-strategy/MongoNamingStrategy.js +6 -6
  85. package/naming-strategy/NamingStrategy.d.ts +14 -4
  86. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  87. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  88. package/not-supported.d.ts +2 -0
  89. package/not-supported.js +4 -0
  90. package/package.json +19 -11
  91. package/platforms/ExceptionConverter.js +1 -1
  92. package/platforms/Platform.d.ts +6 -13
  93. package/platforms/Platform.js +17 -43
  94. package/serialization/EntitySerializer.d.ts +5 -0
  95. package/serialization/EntitySerializer.js +47 -27
  96. package/serialization/EntityTransformer.js +28 -18
  97. package/serialization/SerializationContext.d.ts +6 -6
  98. package/serialization/SerializationContext.js +16 -13
  99. package/types/ArrayType.d.ts +1 -1
  100. package/types/ArrayType.js +2 -3
  101. package/types/BigIntType.d.ts +8 -6
  102. package/types/BigIntType.js +1 -1
  103. package/types/BlobType.d.ts +0 -1
  104. package/types/BlobType.js +0 -3
  105. package/types/BooleanType.d.ts +2 -1
  106. package/types/BooleanType.js +3 -0
  107. package/types/DecimalType.d.ts +6 -4
  108. package/types/DecimalType.js +3 -3
  109. package/types/DoubleType.js +2 -2
  110. package/types/EnumArrayType.js +1 -2
  111. package/types/JsonType.d.ts +1 -1
  112. package/types/JsonType.js +7 -2
  113. package/types/TinyIntType.js +1 -1
  114. package/types/Type.d.ts +2 -4
  115. package/types/Type.js +3 -3
  116. package/types/Uint8ArrayType.d.ts +0 -1
  117. package/types/Uint8ArrayType.js +1 -4
  118. package/types/index.d.ts +1 -1
  119. package/typings.d.ts +148 -109
  120. package/typings.js +50 -42
  121. package/unit-of-work/ChangeSet.d.ts +2 -6
  122. package/unit-of-work/ChangeSet.js +4 -5
  123. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  124. package/unit-of-work/ChangeSetComputer.js +14 -12
  125. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  126. package/unit-of-work/ChangeSetPersister.js +65 -33
  127. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  128. package/unit-of-work/CommitOrderCalculator.js +13 -13
  129. package/unit-of-work/UnitOfWork.d.ts +10 -3
  130. package/unit-of-work/UnitOfWork.js +139 -96
  131. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  132. package/utils/AbstractSchemaGenerator.js +18 -16
  133. package/utils/AsyncContext.d.ts +6 -0
  134. package/utils/AsyncContext.js +42 -0
  135. package/utils/Configuration.d.ts +753 -207
  136. package/utils/Configuration.js +145 -190
  137. package/utils/ConfigurationLoader.d.ts +1 -54
  138. package/utils/ConfigurationLoader.js +1 -352
  139. package/utils/Cursor.d.ts +0 -3
  140. package/utils/Cursor.js +9 -6
  141. package/utils/DataloaderUtils.d.ts +15 -5
  142. package/utils/DataloaderUtils.js +65 -17
  143. package/utils/EntityComparator.d.ts +13 -9
  144. package/utils/EntityComparator.js +85 -43
  145. package/utils/QueryHelper.d.ts +14 -6
  146. package/utils/QueryHelper.js +87 -25
  147. package/utils/RawQueryFragment.d.ts +48 -25
  148. package/utils/RawQueryFragment.js +66 -70
  149. package/utils/RequestContext.js +2 -2
  150. package/utils/TransactionContext.js +2 -2
  151. package/utils/TransactionManager.d.ts +65 -0
  152. package/utils/TransactionManager.js +223 -0
  153. package/utils/Utils.d.ts +12 -119
  154. package/utils/Utils.js +97 -373
  155. package/utils/clone.js +8 -23
  156. package/utils/env-vars.d.ts +7 -0
  157. package/utils/env-vars.js +97 -0
  158. package/utils/fs-utils.d.ts +32 -0
  159. package/utils/fs-utils.js +178 -0
  160. package/utils/index.d.ts +2 -1
  161. package/utils/index.js +2 -1
  162. package/utils/upsert-utils.d.ts +9 -4
  163. package/utils/upsert-utils.js +55 -4
  164. package/decorators/Check.d.ts +0 -3
  165. package/decorators/Check.js +0 -13
  166. package/decorators/CreateRequestContext.d.ts +0 -3
  167. package/decorators/CreateRequestContext.js +0 -32
  168. package/decorators/Embeddable.d.ts +0 -8
  169. package/decorators/Embeddable.js +0 -11
  170. package/decorators/Embedded.d.ts +0 -18
  171. package/decorators/Embedded.js +0 -18
  172. package/decorators/Entity.d.ts +0 -18
  173. package/decorators/Entity.js +0 -12
  174. package/decorators/Enum.d.ts +0 -9
  175. package/decorators/Enum.js +0 -16
  176. package/decorators/Filter.d.ts +0 -2
  177. package/decorators/Filter.js +0 -8
  178. package/decorators/Formula.d.ts +0 -4
  179. package/decorators/Formula.js +0 -15
  180. package/decorators/Indexed.d.ts +0 -19
  181. package/decorators/Indexed.js +0 -20
  182. package/decorators/ManyToMany.d.ts +0 -40
  183. package/decorators/ManyToMany.js +0 -14
  184. package/decorators/ManyToOne.d.ts +0 -30
  185. package/decorators/ManyToOne.js +0 -14
  186. package/decorators/OneToMany.d.ts +0 -28
  187. package/decorators/OneToMany.js +0 -17
  188. package/decorators/OneToOne.d.ts +0 -24
  189. package/decorators/OneToOne.js +0 -7
  190. package/decorators/PrimaryKey.d.ts +0 -8
  191. package/decorators/PrimaryKey.js +0 -20
  192. package/decorators/Property.d.ts +0 -250
  193. package/decorators/Property.js +0 -32
  194. package/decorators/Transactional.d.ts +0 -13
  195. package/decorators/Transactional.js +0 -28
  196. package/decorators/hooks.d.ts +0 -16
  197. package/decorators/hooks.js +0 -47
  198. package/decorators/index.d.ts +0 -17
  199. package/decorators/index.js +0 -17
  200. package/entity/ArrayCollection.d.ts +0 -116
  201. package/entity/ArrayCollection.js +0 -402
  202. package/entity/EntityValidator.d.ts +0 -19
  203. package/entity/EntityValidator.js +0 -150
  204. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  205. package/metadata/ReflectMetadataProvider.js +0 -44
  206. package/utils/resolveContextProvider.d.ts +0 -10
  207. package/utils/resolveContextProvider.js +0 -28
@@ -1,4 +1,3 @@
1
- import { URL } from 'node:url';
2
1
  import { Utils } from '../utils/Utils.js';
3
2
  export class Connection {
4
3
  config;
@@ -33,23 +32,42 @@ export class Connection {
33
32
  .forEach(k => delete this.options[k]);
34
33
  }
35
34
  /**
36
- * Ensure the connection exists, this is used to support lazy connect when using `MikroORM.initSync()`
35
+ * Ensure the connection exists, this is used to support lazy connect when using `new MikroORM()` instead of the async `init` method.
37
36
  */
38
37
  async ensureConnection() {
39
38
  if (!this.connected) {
40
39
  await this.connect();
41
40
  }
42
41
  }
42
+ /**
43
+ * Execute raw SQL queries, handy from running schema dump loaded from a file.
44
+ * This method doesn't support transactions, as opposed to `orm.schema.execute()`, which is used internally.
45
+ */
46
+ async executeDump(dump) {
47
+ throw new Error(`Executing SQL dumps is not supported by current driver`);
48
+ }
49
+ async onConnect() {
50
+ const schemaGenerator = this.config.getExtension('@mikro-orm/schema-generator');
51
+ if (this.type === 'write' && schemaGenerator) {
52
+ if (this.config.get('ensureDatabase')) {
53
+ const options = this.config.get('ensureDatabase');
54
+ await schemaGenerator.ensureDatabase(typeof options === 'boolean' ? {} : { ...options, forceCheck: true });
55
+ }
56
+ if (this.config.get('ensureIndexes')) {
57
+ await schemaGenerator.ensureIndexes();
58
+ }
59
+ }
60
+ }
43
61
  async transactional(cb, options) {
44
62
  throw new Error(`Transactions are not supported by current driver`);
45
63
  }
46
64
  async begin(options) {
47
65
  throw new Error(`Transactions are not supported by current driver`);
48
66
  }
49
- async commit(ctx, eventBroadcaster) {
67
+ async commit(ctx, eventBroadcaster, loggerContext) {
50
68
  throw new Error(`Transactions are not supported by current driver`);
51
69
  }
52
- async rollback(ctx, eventBroadcaster) {
70
+ async rollback(ctx, eventBroadcaster, loggerContext) {
53
71
  throw new Error(`Transactions are not supported by current driver`);
54
72
  }
55
73
  getConnectionOptions() {
@@ -67,7 +85,7 @@ export class Connection {
67
85
  }
68
86
  }
69
87
  else {
70
- const url = new URL(this.config.getClientUrl());
88
+ const url = new URL(this.config.get('clientUrl'));
71
89
  this.options.host = ret.host = this.options.host ?? this.config.get('host', decodeURIComponent(url.hostname));
72
90
  this.options.port = ret.port = this.options.port ?? this.config.get('port', +url.port);
73
91
  this.options.user = ret.user = this.options.user ?? this.config.get('user', decodeURIComponent(url.username));
@@ -76,15 +94,6 @@ export class Connection {
76
94
  }
77
95
  return ret;
78
96
  }
79
- getClientUrl() {
80
- const options = this.getConnectionOptions();
81
- const url = new URL(this.config.getClientUrl(true));
82
- const password = options.password ? ':*****' : '';
83
- const schema = options.schema && options.schema !== this.platform.getDefaultSchemaName()
84
- ? `?schema=${options.schema}`
85
- : '';
86
- return `${url.protocol}//${options.user}${password}@${options.host}:${options.port}${schema}`;
87
- }
88
97
  setMetadata(metadata) {
89
98
  this.metadata = metadata;
90
99
  }
@@ -1,5 +1,5 @@
1
- import { type CountOptions, type DeleteOptions, type DriverMethodOptions, EntityManagerType, type FindOneOptions, type FindOptions, type IDatabaseDriver, type LockOptions, type NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type OrderDefinition } from './IDatabaseDriver.js';
2
- import type { ConnectionType, Dictionary, EntityData, EntityDictionary, EntityMetadata, EntityProperty, FilterQuery, PopulateOptions, Primary } from '../typings.js';
1
+ import { type CountOptions, type DeleteOptions, type DriverMethodOptions, EntityManagerType, type FindOneOptions, type FindOptions, type IDatabaseDriver, type LockOptions, type NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type OrderDefinition, type StreamOptions } from './IDatabaseDriver.js';
2
+ import type { ConnectionType, Constructor, Dictionary, EntityData, EntityDictionary, EntityMetadata, EntityName, EntityProperty, FilterQuery, PopulateOptions, Primary } from '../typings.js';
3
3
  import type { MetadataStorage } from '../metadata/MetadataStorage.js';
4
4
  import type { Connection, QueryResult, Transaction } from '../connections/Connection.js';
5
5
  import { type Configuration, type ConnectionOptions } from '../utils/Configuration.js';
@@ -10,6 +10,7 @@ import type { Collection } from '../entity/Collection.js';
10
10
  import { EntityManager } from '../EntityManager.js';
11
11
  import { DriverException } from '../exceptions.js';
12
12
  import type { Logger } from '../logging/Logger.js';
13
+ import { MikroORM } from '../MikroORM.js';
13
14
  export declare abstract class DatabaseDriver<C extends Connection> implements IDatabaseDriver<C> {
14
15
  readonly config: Configuration;
15
16
  protected readonly dependencies: string[];
@@ -21,29 +22,34 @@ export declare abstract class DatabaseDriver<C extends Connection> implements ID
21
22
  protected comparator: EntityComparator;
22
23
  protected metadata: MetadataStorage;
23
24
  protected constructor(config: Configuration, dependencies: string[]);
24
- abstract find<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: string, where: FilterQuery<T>, options?: FindOptions<T, P, F, E>): Promise<EntityData<T>[]>;
25
- abstract findOne<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: string, where: FilterQuery<T>, options?: FindOneOptions<T, P, F, E>): Promise<EntityData<T> | null>;
26
- abstract nativeInsert<T extends object>(entityName: string, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
27
- abstract nativeInsertMany<T extends object>(entityName: string, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
28
- abstract nativeUpdate<T extends object>(entityName: string, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
29
- nativeUpdateMany<T extends object>(entityName: string, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>>;
30
- abstract nativeDelete<T extends object>(entityName: string, where: FilterQuery<T>, options?: DeleteOptions<T>): Promise<QueryResult<T>>;
31
- abstract count<T extends object, P extends string = never>(entityName: string, where: FilterQuery<T>, options?: CountOptions<T, P>): Promise<number>;
25
+ abstract find<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOptions<T, P, F, E>): Promise<EntityData<T>[]>;
26
+ abstract findOne<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOneOptions<T, P, F, E>): Promise<EntityData<T> | null>;
27
+ abstract nativeInsert<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
28
+ abstract nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
29
+ abstract nativeUpdate<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
30
+ nativeUpdateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>>;
31
+ abstract nativeDelete<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options?: DeleteOptions<T>): Promise<QueryResult<T>>;
32
+ abstract count<T extends object, P extends string = never>(entityName: EntityName<T>, where: FilterQuery<T>, options?: CountOptions<T, P>): Promise<number>;
32
33
  createEntityManager(useContext?: boolean): this[typeof EntityManagerType];
33
- findVirtual<T extends object>(entityName: string, where: FilterQuery<T>, options: FindOptions<T, any, any, any>): Promise<EntityData<T>[]>;
34
- countVirtual<T extends object>(entityName: string, where: FilterQuery<T>, options: CountOptions<T, any>): Promise<number>;
35
- aggregate(entityName: string, pipeline: any[]): Promise<any[]>;
34
+ findVirtual<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options: FindOptions<T, any, any, any>): Promise<EntityData<T>[]>;
35
+ countVirtual<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options: CountOptions<T, any>): Promise<number>;
36
+ aggregate(entityName: EntityName, pipeline: any[]): Promise<any[]>;
36
37
  loadFromPivotTable<T extends object, O extends object>(prop: EntityProperty, owners: Primary<O>[][], where?: FilterQuery<any>, orderBy?: OrderDefinition<T>, ctx?: Transaction, options?: FindOptions<T, any, any, any>, pivotJoin?: boolean): Promise<Dictionary<T[]>>;
37
38
  syncCollections<T extends object, O extends object>(collections: Iterable<Collection<T, O>>, options?: DriverMethodOptions): Promise<void>;
38
39
  mapResult<T extends object>(result: EntityDictionary<T>, meta?: EntityMetadata<T>, populate?: PopulateOptions<T>[]): EntityData<T> | null;
39
- connect(): Promise<C>;
40
- reconnect(): Promise<C>;
40
+ connect(options?: {
41
+ skipOnConnect?: boolean;
42
+ }): Promise<C>;
43
+ reconnect(options?: {
44
+ skipOnConnect?: boolean;
45
+ }): Promise<C>;
41
46
  getConnection(type?: ConnectionType): C;
42
47
  close(force?: boolean): Promise<void>;
43
48
  getPlatform(): Platform;
44
49
  setMetadata(metadata: MetadataStorage): void;
45
50
  getMetadata(): MetadataStorage;
46
51
  getDependencies(): string[];
52
+ protected isPopulated<T extends object>(meta: EntityMetadata<T>, prop: EntityProperty<T>, hint: PopulateOptions<T>, name?: string): boolean;
47
53
  protected processCursorOptions<T extends object, P extends string>(meta: EntityMetadata<T>, options: FindOptions<T, P, any, any>, orderBy: OrderDefinition<T>): {
48
54
  orderBy: OrderDefinition<T>[];
49
55
  where: FilterQuery<T>;
@@ -52,9 +58,10 @@ export declare abstract class DatabaseDriver<C extends Connection> implements ID
52
58
  /** @internal */
53
59
  mapDataToFieldNames(data: Dictionary, stringifyJsonArrays: boolean, properties?: Record<string, EntityProperty>, convertCustomTypes?: boolean, object?: boolean): Dictionary;
54
60
  protected inlineEmbeddables<T extends object>(meta: EntityMetadata<T>, data: T, where?: boolean): void;
55
- protected getPrimaryKeyFields(entityName: string): string[];
61
+ protected getPrimaryKeyFields<T>(meta: EntityMetadata<T>): string[];
56
62
  protected createReplicas(cb: (c: ConnectionOptions) => C): C[];
57
63
  lockPessimistic<T extends object>(entity: T, options: LockOptions): Promise<void>;
64
+ abstract stream<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options: StreamOptions<T>): AsyncIterableIterator<T>;
58
65
  /**
59
66
  * @inheritDoc
60
67
  */
@@ -71,4 +78,6 @@ export declare abstract class DatabaseDriver<C extends Connection> implements ID
71
78
  schema?: string;
72
79
  parentSchema?: string;
73
80
  }): string | undefined;
81
+ /** @internal */
82
+ getORMClass(): Constructor<MikroORM>;
74
83
  }
@@ -9,6 +9,7 @@ import { CursorError, ValidationError } from '../errors.js';
9
9
  import { DriverException } from '../exceptions.js';
10
10
  import { helper } from '../entity/wrap.js';
11
11
  import { JsonType } from '../types/JsonType.js';
12
+ import { MikroORM } from '../MikroORM.js';
12
13
  export class DatabaseDriver {
13
14
  config;
14
15
  dependencies;
@@ -31,11 +32,11 @@ export class DatabaseDriver {
31
32
  const EntityManagerClass = this.config.get('entityManager', EntityManager);
32
33
  return new EntityManagerClass(this.config, this, this.metadata, useContext);
33
34
  }
34
- /* v8 ignore next 3 */
35
+ /* v8 ignore next */
35
36
  async findVirtual(entityName, where, options) {
36
37
  throw new Error(`Virtual entities are not supported by ${this.constructor.name} driver.`);
37
38
  }
38
- /* v8 ignore next 3 */
39
+ /* v8 ignore next */
39
40
  async countVirtual(entityName, where, options) {
40
41
  throw new Error(`Counting virtual entities is not supported by ${this.constructor.name} driver.`);
41
42
  }
@@ -47,32 +48,35 @@ export class DatabaseDriver {
47
48
  }
48
49
  async syncCollections(collections, options) {
49
50
  for (const coll of collections) {
51
+ /* v8 ignore else */
50
52
  if (!coll.property.owner) {
51
53
  if (coll.getSnapshot() === undefined) {
52
54
  throw ValidationError.cannotModifyInverseCollection(coll.owner, coll.property);
53
55
  }
54
56
  continue;
55
57
  }
56
- /* v8 ignore next 3 */
57
- const pk = coll.property.targetMeta.primaryKeys[0];
58
- const data = { [coll.property.name]: coll.getIdentifiers(pk) };
59
- await this.nativeUpdate(coll.owner.constructor.name, helper(coll.owner).getPrimaryKey(), data, options);
58
+ /* v8 ignore next */
59
+ {
60
+ const pk = coll.property.targetMeta.primaryKeys[0];
61
+ const data = { [coll.property.name]: coll.getIdentifiers(pk) };
62
+ await this.nativeUpdate(coll.owner.constructor, helper(coll.owner).getPrimaryKey(), data, options);
63
+ }
60
64
  }
61
65
  }
62
66
  mapResult(result, meta, populate = []) {
63
67
  if (!result || !meta) {
64
68
  return result ?? null;
65
69
  }
66
- return this.comparator.mapResult(meta.className, result);
70
+ return this.comparator.mapResult(meta, result);
67
71
  }
68
- async connect() {
69
- await this.connection.connect();
72
+ async connect(options) {
73
+ await this.connection.connect(options);
70
74
  await Promise.all(this.replicas.map(replica => replica.connect()));
71
75
  return this.connection;
72
76
  }
73
- async reconnect() {
77
+ async reconnect(options) {
74
78
  await this.close(true);
75
- await this.connect();
79
+ await this.connect(options);
76
80
  return this.connection;
77
81
  }
78
82
  getConnection(type = 'write') {
@@ -105,6 +109,15 @@ export class DatabaseDriver {
105
109
  getDependencies() {
106
110
  return this.dependencies;
107
111
  }
112
+ isPopulated(meta, prop, hint, name) {
113
+ if (hint.field === prop.name || hint.field === name || hint.all) {
114
+ return true;
115
+ }
116
+ if (prop.embedded && hint.children && meta.properties[prop.embedded[0]].name === hint.field) {
117
+ return hint.children.some(c => this.isPopulated(meta, prop, c, prop.embedded[1]));
118
+ }
119
+ return false;
120
+ }
108
121
  processCursorOptions(meta, options, orderBy) {
109
122
  const { first, last, before, after, overfetch } = options;
110
123
  const limit = first ?? last;
@@ -139,7 +152,7 @@ export class DatabaseDriver {
139
152
  }
140
153
  const createOrderBy = (prop, direction) => {
141
154
  if (Utils.isPlainObject(direction)) {
142
- const value = Utils.keys(direction).reduce((o, key) => {
155
+ const value = Utils.getObjectQueryKeys(direction).reduce((o, key) => {
143
156
  Object.assign(o, createOrderBy(key, direction[key]));
144
157
  return o;
145
158
  }, {});
@@ -244,7 +257,7 @@ export class DatabaseDriver {
244
257
  return data;
245
258
  }
246
259
  inlineEmbeddables(meta, data, where) {
247
- /* v8 ignore next 3 */
260
+ /* v8 ignore next */
248
261
  if (data == null) {
249
262
  return;
250
263
  }
@@ -264,38 +277,38 @@ export class DatabaseDriver {
264
277
  // explicitly allow `$exists`, `$eq` and `$ne` operators here as they can't be misused this way
265
278
  const operator = Object.keys(data[prop.name]).some(f => Utils.isOperator(f) && !['$exists', '$ne', '$eq'].includes(f));
266
279
  if (operator) {
267
- throw ValidationError.cannotUseOperatorsInsideEmbeddables(meta.className, prop.name, data);
280
+ throw ValidationError.cannotUseOperatorsInsideEmbeddables(meta.class, prop.name, data);
268
281
  }
269
282
  if (prop.object && where) {
270
283
  const inline = (payload, sub, path) => {
271
284
  if (sub.kind === ReferenceKind.EMBEDDED && Utils.isObject(payload[sub.embedded[1]])) {
272
285
  return Object.keys(payload[sub.embedded[1]]).forEach(kkk => {
273
286
  if (!sub.embeddedProps[kkk]) {
274
- throw ValidationError.invalidEmbeddableQuery(meta.className, kkk, sub.type);
287
+ throw ValidationError.invalidEmbeddableQuery(meta.class, kkk, sub.type);
275
288
  }
276
- inline(payload[sub.embedded[1]], sub.embeddedProps[kkk], [...path, sub.embedded[1]]);
289
+ inline(payload[sub.embedded[1]], sub.embeddedProps[kkk], [...path, sub.fieldNames[0]]);
277
290
  });
278
291
  }
279
- data[`${path.join('.')}.${sub.embedded[1]}`] = payload[sub.embedded[1]];
292
+ data[`${path.join('.')}.${sub.fieldNames[0]}`] = payload[sub.embedded[1]];
280
293
  };
281
294
  const parentPropName = kk.substring(0, kk.indexOf('.'));
282
295
  // we might be using some native JSON operator, e.g. with mongodb's `$geoWithin` or `$exists`
283
296
  if (props[kk]) {
284
297
  /* v8 ignore next */
285
- inline(data[prop.name], props[kk] || props[parentPropName], [prop.name]);
298
+ inline(data[prop.name], props[kk] || props[parentPropName], [prop.fieldNames[0]]);
286
299
  }
287
300
  else if (props[parentPropName]) {
288
- data[`${prop.name}.${kk}`] = data[prop.name][kk];
301
+ data[`${prop.fieldNames[0]}.${kk}`] = data[prop.name][kk];
289
302
  }
290
303
  else {
291
304
  unknownProp = true;
292
305
  }
293
306
  }
294
307
  else if (props[kk]) {
295
- data[props[kk].name] = data[prop.name][props[kk].embedded[1]];
308
+ data[props[kk].fieldNames[0]] = data[prop.name][props[kk].embedded[1]];
296
309
  }
297
310
  else {
298
- throw ValidationError.invalidEmbeddableQuery(meta.className, kk, prop.type);
311
+ throw ValidationError.invalidEmbeddableQuery(meta.class, kk, prop.type);
299
312
  }
300
313
  });
301
314
  if (!unknownProp) {
@@ -304,9 +317,8 @@ export class DatabaseDriver {
304
317
  }
305
318
  });
306
319
  }
307
- getPrimaryKeyFields(entityName) {
308
- const meta = this.metadata.find(entityName);
309
- return meta ? Utils.flatten(meta.getPrimaryProps().map(pk => pk.fieldNames)) : [this.config.getNamingStrategy().referenceColumnName()];
320
+ getPrimaryKeyFields(meta) {
321
+ return meta.getPrimaryProps().flatMap(pk => pk.fieldNames);
310
322
  }
311
323
  createReplicas(cb) {
312
324
  const replicas = this.config.get('replicas', []);
@@ -372,4 +384,8 @@ export class DatabaseDriver {
372
384
  const schemaName = meta?.schema === '*' ? this.config.getSchema() : meta?.schema;
373
385
  return options?.schema ?? options?.parentSchema ?? schemaName ?? this.config.getSchema();
374
386
  }
387
+ /** @internal */
388
+ getORMClass() {
389
+ return MikroORM;
390
+ }
375
391
  }
@@ -1,4 +1,4 @@
1
- import type { ConnectionType, EntityData, EntityMetadata, EntityProperty, FilterQuery, Primary, Dictionary, QBFilterQuery, IPrimaryKey, PopulateOptions, EntityDictionary, AutoPath, ObjectQuery, FilterObject, Populate } from '../typings.js';
1
+ import type { ConnectionType, EntityData, EntityMetadata, EntityProperty, FilterQuery, Primary, Dictionary, QBFilterQuery, IPrimaryKey, PopulateOptions, EntityDictionary, AutoPath, ObjectQuery, FilterObject, Populate, EntityName } from '../typings.js';
2
2
  import type { Connection, QueryResult, Transaction } from '../connections/Connection.js';
3
3
  import type { FlushMode, LockMode, QueryOrderMap, QueryFlag, LoadStrategy, PopulateHint, PopulatePath } from '../enums.js';
4
4
  import type { Platform } from '../platforms/Platform.js';
@@ -8,33 +8,38 @@ import type { EntityManager } from '../EntityManager.js';
8
8
  import type { DriverException } from '../exceptions.js';
9
9
  import type { Configuration } from '../utils/Configuration.js';
10
10
  import type { LoggingOptions, LogContext } from '../logging/Logger.js';
11
- import type { RawQueryFragment } from '../utils/RawQueryFragment.js';
11
+ import type { Raw } from '../utils/RawQueryFragment.js';
12
12
  export declare const EntityManagerType: unique symbol;
13
13
  export interface IDatabaseDriver<C extends Connection = Connection> {
14
14
  [EntityManagerType]: EntityManager<this>;
15
15
  readonly config: Configuration;
16
16
  createEntityManager(useContext?: boolean): this[typeof EntityManagerType];
17
- connect(): Promise<C>;
17
+ connect(options?: {
18
+ skipOnConnect?: boolean;
19
+ }): Promise<C>;
18
20
  close(force?: boolean): Promise<void>;
19
- reconnect(): Promise<C>;
21
+ reconnect(options?: {
22
+ skipOnConnect?: boolean;
23
+ }): Promise<C>;
20
24
  getConnection(type?: ConnectionType): C;
21
25
  /**
22
26
  * Finds selection of entities
23
27
  */
24
- find<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: string, where: FilterQuery<T>, options?: FindOptions<T, P, F, E>): Promise<EntityData<T>[]>;
28
+ find<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOptions<T, P, F, E>): Promise<EntityData<T>[]>;
25
29
  /**
26
30
  * Finds single entity (table row, document)
27
31
  */
28
- findOne<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: string, where: FilterQuery<T>, options?: FindOneOptions<T, P, F, E>): Promise<EntityData<T> | null>;
29
- findVirtual<T extends object>(entityName: string, where: FilterQuery<T>, options: FindOptions<T, any, any, any>): Promise<EntityData<T>[]>;
30
- nativeInsert<T extends object>(entityName: string, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
31
- nativeInsertMany<T extends object>(entityName: string, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
32
- nativeUpdate<T extends object>(entityName: string, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
33
- nativeUpdateMany<T extends object>(entityName: string, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>>;
34
- nativeDelete<T extends object>(entityName: string, where: FilterQuery<T>, options?: NativeDeleteOptions<T>): Promise<QueryResult<T>>;
32
+ findOne<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOneOptions<T, P, F, E>): Promise<EntityData<T> | null>;
33
+ findVirtual<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options: FindOptions<T, any, any, any>): Promise<EntityData<T>[]>;
34
+ stream<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options: StreamOptions<T>): AsyncIterableIterator<T>;
35
+ nativeInsert<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
36
+ nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
37
+ nativeUpdate<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
38
+ nativeUpdateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>>;
39
+ nativeDelete<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options?: NativeDeleteOptions<T>): Promise<QueryResult<T>>;
35
40
  syncCollections<T extends object, O extends object>(collections: Iterable<Collection<T, O>>, options?: DriverMethodOptions): Promise<void>;
36
- count<T extends object, P extends string = never>(entityName: string, where: FilterQuery<T>, options?: CountOptions<T, P>): Promise<number>;
37
- aggregate(entityName: string, pipeline: any[]): Promise<any[]>;
41
+ count<T extends object, P extends string = never>(entityName: EntityName<T>, where: FilterQuery<T>, options?: CountOptions<T, P>): Promise<number>;
42
+ aggregate(entityName: EntityName, pipeline: any[]): Promise<any[]>;
38
43
  mapResult<T extends object>(result: EntityDictionary<T>, meta: EntityMetadata<T>, populate?: PopulateOptions<T>[]): EntityData<T> | null;
39
44
  /**
40
45
  * When driver uses pivot tables for M:N, this method will load identifiers for given collections from them
@@ -68,6 +73,18 @@ export type OrderDefinition<T> = (QueryOrderMap<T> & {
68
73
  export interface FindAllOptions<T, P extends string = never, F extends string = '*', E extends string = never> extends FindOptions<T, P, F, E> {
69
74
  where?: FilterQuery<T>;
70
75
  }
76
+ export interface StreamOptions<Entity, Populate extends string = never, Fields extends string = '*', Exclude extends string = never> extends Omit<FindAllOptions<Entity, Populate, Fields, Exclude>, 'cache' | 'before' | 'after' | 'first' | 'last' | 'overfetch' | 'strategy'> {
77
+ /**
78
+ * When populating to-many relations, the ORM streams fully merged entities instead of yielding every row.
79
+ * You can opt out of this behavior by specifying `mergeResults: false`. This will yield every row from
80
+ * the SQL result, but still mapped to entities, meaning that to-many collections will contain at most
81
+ * a single item, and you will get duplicate root entities when they have multiple items in the populated
82
+ * collection.
83
+ *
84
+ * @default true
85
+ */
86
+ mergeResults?: boolean;
87
+ }
71
88
  export type FilterOptions = Dictionary<boolean | Dictionary> | string[] | boolean;
72
89
  export interface LoadHint<Entity, Hint extends string = never, Fields extends string = PopulatePath.ALL, Excludes extends string = never> {
73
90
  populate?: Populate<Entity, Hint>;
@@ -149,10 +166,10 @@ export interface FindOptions<Entity, Hint extends string = never, Fields extends
149
166
  /** @internal used to apply filters to the auto-joined relations */
150
167
  em?: EntityManager;
151
168
  }
152
- export interface FindByCursorOptions<T extends object, P extends string = never, F extends string = '*', E extends string = never, I extends boolean = true> extends Omit<FindOptions<T, P, F, E>, 'limit' | 'offset'> {
169
+ export interface FindByCursorOptions<T extends object, P extends string = never, F extends string = '*', E extends string = never, I extends boolean = true> extends Omit<FindAllOptions<T, P, F, E>, 'limit' | 'offset'> {
153
170
  includeCount?: I;
154
171
  }
155
- export interface FindOneOptions<T extends object, P extends string = never, F extends string = '*', E extends string = never> extends Omit<FindOptions<T, P, F, E>, 'limit' | 'lockMode'> {
172
+ export interface FindOneOptions<T, P extends string = never, F extends string = '*', E extends string = never> extends Omit<FindOptions<T, P, F, E>, 'limit' | 'lockMode'> {
156
173
  lockMode?: LockMode;
157
174
  lockVersion?: number | Date;
158
175
  }
@@ -166,12 +183,13 @@ export interface NativeInsertUpdateOptions<T> {
166
183
  schema?: string;
167
184
  /** `nativeUpdate()` only option */
168
185
  upsert?: boolean;
186
+ loggerContext?: LogContext;
169
187
  }
170
188
  export interface NativeInsertUpdateManyOptions<T> extends NativeInsertUpdateOptions<T> {
171
189
  processCollections?: boolean;
172
190
  }
173
191
  export interface UpsertOptions<Entity, Fields extends string = never> extends Omit<NativeInsertUpdateOptions<Entity>, 'upsert'> {
174
- onConflictFields?: (keyof Entity)[] | RawQueryFragment;
192
+ onConflictFields?: (keyof Entity)[] | Raw;
175
193
  onConflictAction?: 'ignore' | 'merge';
176
194
  onConflictMergeFields?: AutoPath<Entity, Fields, `${PopulatePath.ALL}`>[];
177
195
  onConflictExcludeFields?: AutoPath<Entity, Fields, `${PopulatePath.ALL}`>[];
@@ -200,6 +218,8 @@ export interface CountOptions<T extends object, P extends string = never> {
200
218
  hintComments?: string | string[];
201
219
  loggerContext?: LogContext;
202
220
  logging?: LoggingOptions;
221
+ /** @internal used to apply filters to the auto-joined relations */
222
+ em?: EntityManager;
203
223
  }
204
224
  export interface UpdateOptions<T> {
205
225
  filters?: FilterOptions;
@@ -221,6 +241,7 @@ export interface LockOptions extends DriverMethodOptions {
221
241
  export interface DriverMethodOptions {
222
242
  ctx?: Transaction;
223
243
  schema?: string;
244
+ loggerContext?: LogContext;
224
245
  }
225
246
  export interface GetReferenceOptions {
226
247
  wrapped?: boolean;
@@ -6,7 +6,6 @@ import { type SerializeOptions } from '../serialization/EntitySerializer.js';
6
6
  import type { FindOneOptions } from '../drivers/IDatabaseDriver.js';
7
7
  export declare abstract class BaseEntity {
8
8
  isInitialized(): boolean;
9
- isTouched(): boolean;
10
9
  populated(populated?: boolean): void;
11
10
  populate<Entity extends this = this, Hint extends string = never>(populate: AutoPath<Entity, Hint>[] | false, options?: EntityLoaderOptions<Entity>): Promise<Loaded<Entity, Hint>>;
12
11
  toReference<Entity extends this = this>(): Ref<Entity> & LoadedReference<Loaded<Entity, AddEager<Entity>>>;
@@ -6,9 +6,6 @@ export class BaseEntity {
6
6
  isInitialized() {
7
7
  return helper(this).__initialized;
8
8
  }
9
- isTouched() {
10
- return helper(this).__touched;
11
- }
12
9
  populated(populated = true) {
13
10
  helper(this).populated(populated);
14
11
  }