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

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 +35 -19
  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 +13 -17
  64. package/metadata/EntitySchema.js +67 -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 +124 -86
  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
package/utils/clone.js CHANGED
@@ -3,8 +3,6 @@
3
3
  * clone `EventEmitter`s to get around https://github.com/mikro-orm/mikro-orm/issues/2748
4
4
  * @internal
5
5
  */
6
- import { EventEmitter } from 'node:events';
7
- import { RawQueryFragment } from './RawQueryFragment.js';
8
6
  /**
9
7
  * Get the property descriptor of a property on an object or its prototype chain.
10
8
  *
@@ -30,11 +28,7 @@ export function clone(parent, respectCustomCloneMethod = true) {
30
28
  if (parent === null) {
31
29
  return null;
32
30
  }
33
- const raw = RawQueryFragment.getKnownFragment(parent, false);
34
- if (raw && respectCustomCloneMethod) {
35
- return raw.clone();
36
- }
37
- if (typeof parent !== 'object' || parent instanceof EventEmitter) {
31
+ if (typeof parent !== 'object') {
38
32
  return parent;
39
33
  }
40
34
  if (respectCustomCloneMethod && 'clone' in parent && typeof parent.clone === 'function') {
@@ -114,25 +108,16 @@ export function clone(parent, respectCustomCloneMethod = true) {
114
108
  if (attrs && typeof attrs.get === 'function' && attrs.set == null) {
115
109
  continue;
116
110
  }
117
- const raw = RawQueryFragment.getKnownFragment(i, false);
118
- if (raw && respectCustomCloneMethod) {
119
- const i2 = raw.clone().toString();
120
- child[i2] = _clone(parent[i]);
121
- continue;
122
- }
123
111
  child[i] = _clone(parent[i]);
124
112
  }
125
- if (Object.getOwnPropertySymbols) {
126
- const symbols = Object.getOwnPropertySymbols(parent);
127
- for (let i = 0; i < symbols.length; i++) {
128
- const symbol = symbols[i];
129
- const descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
130
- /* v8 ignore next 3 */
131
- if (descriptor && !descriptor.enumerable) {
132
- continue;
133
- }
134
- child[symbol] = _clone(parent[symbol]);
113
+ const symbols = Object.getOwnPropertySymbols(parent);
114
+ for (let i = 0; i < symbols.length; i++) {
115
+ const symbol = symbols[i];
116
+ const descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
117
+ if (descriptor && !descriptor.enumerable) {
118
+ continue;
135
119
  }
120
+ child[symbol] = _clone(parent[symbol]);
136
121
  }
137
122
  return child;
138
123
  }
@@ -0,0 +1,7 @@
1
+ import { type Options } from './Configuration.js';
2
+ /** @internal */
3
+ export declare function setEnv(key: string, value: unknown): void;
4
+ /** @internal */
5
+ export declare function getEnv(key: string): string | undefined;
6
+ /** @internal */
7
+ export declare function loadEnvironmentVars(): Partial<Options>;
@@ -0,0 +1,97 @@
1
+ import { Utils } from './Utils.js';
2
+ /** @internal */
3
+ export function setEnv(key, value) {
4
+ if (globalThis.process?.env) {
5
+ globalThis.process.env[key] = String(value);
6
+ }
7
+ }
8
+ /** @internal */
9
+ export function getEnv(key) {
10
+ return globalThis.process?.env?.[key];
11
+ }
12
+ /** @internal */
13
+ export function loadEnvironmentVars() {
14
+ const ret = {};
15
+ const getEnvKey = (key, envPrefix = 'MIKRO_ORM_') => {
16
+ return envPrefix + key
17
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
18
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')
19
+ .toUpperCase();
20
+ };
21
+ const array = (v) => v.split(',').map(vv => vv.trim());
22
+ const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
23
+ const num = (v) => +v;
24
+ const read = (o, envPrefix, key, mapper = v => v) => {
25
+ const envKey = getEnvKey(key, envPrefix);
26
+ /* v8 ignore next */
27
+ if (envKey in (globalThis.process?.env ?? {})) {
28
+ o[key] = mapper(getEnv(envKey));
29
+ }
30
+ };
31
+ const cleanup = (o, k) => Utils.hasObjectKeys(o[k]) ? {} : delete o[k];
32
+ const read0 = read.bind(null, ret, 'MIKRO_ORM_');
33
+ read0('baseDir');
34
+ read0('entities', array);
35
+ read0('entitiesTs', array);
36
+ read0('clientUrl');
37
+ read0('host');
38
+ read0('port', num);
39
+ read0('user');
40
+ read0('password');
41
+ read0('dbName');
42
+ read0('schema');
43
+ read0('loadStrategy');
44
+ read0('batchSize', num);
45
+ read0('useBatchInserts', bool);
46
+ read0('useBatchUpdates', bool);
47
+ read0('allowGlobalContext', bool);
48
+ read0('autoJoinOneToOneOwner', bool);
49
+ read0('populateAfterFlush', bool);
50
+ read0('forceEntityConstructor', bool);
51
+ read0('forceUndefined', bool);
52
+ read0('forceUtcTimezone', bool);
53
+ read0('timezone');
54
+ read0('ensureIndexes', bool);
55
+ read0('implicitTransactions', bool);
56
+ read0('debug', bool);
57
+ read0('colors', bool);
58
+ ret.discovery = {};
59
+ const read1 = read.bind(null, ret.discovery, 'MIKRO_ORM_DISCOVERY_');
60
+ read1('warnWhenNoEntities', bool);
61
+ read1('checkDuplicateTableNames', bool);
62
+ read1('checkDuplicateFieldNames', bool);
63
+ read1('checkNonPersistentCompositeProps', bool);
64
+ read1('inferDefaultValues', bool);
65
+ read1('tsConfigPath');
66
+ cleanup(ret, 'discovery');
67
+ ret.migrations = {};
68
+ const read2 = read.bind(null, ret.migrations, 'MIKRO_ORM_MIGRATIONS_');
69
+ read2('tableName');
70
+ read2('path');
71
+ read2('pathTs');
72
+ read2('glob');
73
+ read2('transactional', bool);
74
+ read2('disableForeignKeys', bool);
75
+ read2('allOrNothing', bool);
76
+ read2('dropTables', bool);
77
+ read2('safe', bool);
78
+ read2('silent', bool);
79
+ read2('emit');
80
+ read2('snapshot', bool);
81
+ read2('snapshotName');
82
+ cleanup(ret, 'migrations');
83
+ ret.schemaGenerator = {};
84
+ const read3 = read.bind(null, ret.schemaGenerator, 'MIKRO_ORM_SCHEMA_GENERATOR_');
85
+ read3('disableForeignKeys', bool);
86
+ read3('createForeignKeyConstraints', bool);
87
+ cleanup(ret, 'schemaGenerator');
88
+ ret.seeder = {};
89
+ const read4 = read.bind(null, ret.seeder, 'MIKRO_ORM_SEEDER_');
90
+ read4('path');
91
+ read4('pathTs');
92
+ read4('glob');
93
+ read4('emit');
94
+ read4('defaultSeeder');
95
+ cleanup(ret, 'seeder');
96
+ return ret;
97
+ }
@@ -0,0 +1,32 @@
1
+ import { type Dictionary } from '../typings.js';
2
+ export declare const fs: {
3
+ pathExists(path: string): boolean;
4
+ ensureDir(path: string): void;
5
+ readJSONSync<T = Dictionary>(path: string): T;
6
+ glob(input: string | string[], cwd?: string): string[];
7
+ resolveGlob(input: string | string[], cwd?: string): string[];
8
+ getPackageConfig<T extends Dictionary>(basePath?: string): T;
9
+ getORMPackages(): Set<string>;
10
+ getORMPackageVersion(name: string): string | undefined;
11
+ checkPackageVersion(): void;
12
+ /**
13
+ * Resolves and normalizes a series of path parts relative to each preceding part.
14
+ * If any part is a `file:` URL, it is converted to a local path. If any part is an
15
+ * absolute path, it replaces preceding paths (similar to `path.resolve` in NodeJS).
16
+ * Trailing directory separators are removed, and all directory separators are converted
17
+ * to POSIX-style separators (`/`).
18
+ */
19
+ normalizePath(...parts: string[]): string;
20
+ /**
21
+ * Determines the relative path between two paths. If either path is a `file:` URL,
22
+ * it is converted to a local path.
23
+ */
24
+ relativePath(path: string, relativeTo: string): string;
25
+ /**
26
+ * Computes the absolute path to for the given path relative to the provided base directory.
27
+ * If either `path` or `baseDir` are `file:` URLs, they are converted to local paths.
28
+ */
29
+ absolutePath(path: string, baseDir?: string): string;
30
+ dynamicImport<T = any>(id: string): Promise<T>;
31
+ };
32
+ export * from '../cache/FileCacheAdapter.js';
@@ -0,0 +1,178 @@
1
+ import { existsSync, globSync, mkdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { isAbsolute, join, normalize, relative } from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { Utils } from './Utils.js';
5
+ import { colors } from '../logging/colors.js';
6
+ export const fs = {
7
+ pathExists(path) {
8
+ if (/[*?[\]]/.test(path)) {
9
+ return globSync(path).length > 0;
10
+ }
11
+ return existsSync(path);
12
+ },
13
+ ensureDir(path) {
14
+ if (!existsSync(path)) {
15
+ mkdirSync(path, { recursive: true });
16
+ }
17
+ },
18
+ readJSONSync(path) {
19
+ const file = readFileSync(path);
20
+ return JSON.parse(file.toString());
21
+ },
22
+ glob(input, cwd) {
23
+ const patterns = Array.isArray(input) ? input : [input];
24
+ const positive = [];
25
+ const negative = [];
26
+ for (const p of patterns) {
27
+ if (p.startsWith('!')) {
28
+ negative.push(p.slice(1));
29
+ }
30
+ else {
31
+ positive.push(p);
32
+ }
33
+ }
34
+ const included = new Set(this.resolveGlob(positive, cwd));
35
+ if (included.size > 0 && negative.length > 0) {
36
+ const excluded = this.resolveGlob(negative, cwd);
37
+ for (const file of excluded) {
38
+ included.delete(file);
39
+ }
40
+ }
41
+ return [...included];
42
+ },
43
+ resolveGlob(input, cwd) {
44
+ if (Array.isArray(input)) {
45
+ return input.flatMap(paths => this.resolveGlob(paths, cwd));
46
+ }
47
+ const hasGlobChars = /[*?[\]]/.test(input);
48
+ if (!hasGlobChars) {
49
+ try {
50
+ const s = statSync(cwd ? this.normalizePath(cwd, input) : input);
51
+ if (s.isDirectory()) {
52
+ const files = globSync(join(input, '**'), { cwd, withFileTypes: true });
53
+ return files.filter(f => f.isFile()).map(f => join(f.parentPath, f.name));
54
+ }
55
+ }
56
+ catch {
57
+ // ignore
58
+ }
59
+ }
60
+ const files = globSync(input, { cwd, withFileTypes: true });
61
+ return files.filter(f => f.isFile()).map(f => join(f.parentPath, f.name));
62
+ },
63
+ getPackageConfig(basePath = process.cwd()) {
64
+ if (this.pathExists(`${basePath}/package.json`)) {
65
+ try {
66
+ const path = import.meta.resolve(`${basePath}/package.json`);
67
+ return this.readJSONSync(fileURLToPath(path));
68
+ }
69
+ catch (e) {
70
+ /* v8 ignore next */
71
+ return {};
72
+ }
73
+ }
74
+ const parentFolder = realpathSync(`${basePath}/..`);
75
+ // we reached the root folder
76
+ if (basePath === parentFolder) {
77
+ return {};
78
+ }
79
+ return this.getPackageConfig(parentFolder);
80
+ },
81
+ getORMPackages() {
82
+ const pkg = this.getPackageConfig();
83
+ return new Set([
84
+ ...Object.keys(pkg.dependencies ?? {}),
85
+ ...Object.keys(pkg.devDependencies ?? {}),
86
+ ]);
87
+ },
88
+ getORMPackageVersion(name) {
89
+ try {
90
+ const path = import.meta.resolve(`${name}/package.json`);
91
+ const pkg = this.readJSONSync(fileURLToPath(path));
92
+ return pkg?.version;
93
+ }
94
+ catch (e) {
95
+ return undefined;
96
+ }
97
+ },
98
+ // inspired by https://github.com/facebook/docusaurus/pull/3386
99
+ checkPackageVersion() {
100
+ const coreVersion = Utils.getORMVersion();
101
+ if (process.env.MIKRO_ORM_ALLOW_VERSION_MISMATCH || coreVersion === '[[MIKRO_ORM_VERSION]]') {
102
+ return;
103
+ }
104
+ const deps = this.getORMPackages();
105
+ const exceptions = new Set(['nestjs', 'sql-highlighter', 'mongo-highlighter']);
106
+ const ormPackages = [...deps].filter(d => d.startsWith('@mikro-orm/') && d !== '@mikro-orm/core' && !exceptions.has(d.substring('@mikro-orm/'.length)));
107
+ for (const ormPackage of ormPackages) {
108
+ const version = this.getORMPackageVersion(ormPackage);
109
+ if (version != null && version !== coreVersion) {
110
+ throw new Error(`Bad ${colors.cyan(ormPackage)} version ${colors.yellow('' + version)}.\n` +
111
+ `All official @mikro-orm/* packages need to have the exact same version as @mikro-orm/core (${colors.green(coreVersion)}).\n` +
112
+ `Only exceptions are packages that don't live in the 'mikro-orm' repository: ${[...exceptions].join(', ')}.\n` +
113
+ `Maybe you want to check, or regenerate your yarn.lock or package-lock.json file?`);
114
+ }
115
+ }
116
+ },
117
+ /**
118
+ * Resolves and normalizes a series of path parts relative to each preceding part.
119
+ * If any part is a `file:` URL, it is converted to a local path. If any part is an
120
+ * absolute path, it replaces preceding paths (similar to `path.resolve` in NodeJS).
121
+ * Trailing directory separators are removed, and all directory separators are converted
122
+ * to POSIX-style separators (`/`).
123
+ */
124
+ normalizePath(...parts) {
125
+ let start = 0;
126
+ for (let i = 0; i < parts.length; i++) {
127
+ const part = parts[i];
128
+ if (isAbsolute(part)) {
129
+ start = i;
130
+ }
131
+ else if (part.startsWith('file:')) {
132
+ start = i;
133
+ parts[i] = fileURLToPath(part);
134
+ }
135
+ }
136
+ if (start > 0) {
137
+ parts = parts.slice(start);
138
+ }
139
+ let path = parts.join('/').replace(/\\/g, '/').replace(/\/$/, '');
140
+ path = normalize(path).replace(/\\/g, '/');
141
+ return (path.match(/^[/.]|[a-zA-Z]:/) || path.startsWith('!')) ? path : './' + path;
142
+ },
143
+ /**
144
+ * Determines the relative path between two paths. If either path is a `file:` URL,
145
+ * it is converted to a local path.
146
+ */
147
+ relativePath(path, relativeTo) {
148
+ if (!path) {
149
+ return path;
150
+ }
151
+ path = this.normalizePath(path);
152
+ if (path.startsWith('.')) {
153
+ return path;
154
+ }
155
+ path = relative(this.normalizePath(relativeTo), path);
156
+ return this.normalizePath(path);
157
+ },
158
+ /**
159
+ * Computes the absolute path to for the given path relative to the provided base directory.
160
+ * If either `path` or `baseDir` are `file:` URLs, they are converted to local paths.
161
+ */
162
+ absolutePath(path, baseDir = process.cwd()) {
163
+ if (!path) {
164
+ return this.normalizePath(baseDir);
165
+ }
166
+ if (!isAbsolute(path) && !path.startsWith('file://')) {
167
+ path = baseDir + '/' + path;
168
+ }
169
+ return this.normalizePath(path);
170
+ },
171
+ async dynamicImport(id) {
172
+ /* v8 ignore next */
173
+ const specifier = id.startsWith('file://') ? id : pathToFileURL(id).href;
174
+ const dynamicImportProvider = globalThis.dynamicImportProvider ?? ((id) => import(id));
175
+ return dynamicImportProvider(specifier);
176
+ },
177
+ };
178
+ export * from '../cache/FileCacheAdapter.js';
package/utils/index.d.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  export * from './Configuration.js';
2
- export * from './ConfigurationLoader.js';
3
2
  export * from './Cursor.js';
4
3
  export * from './DataloaderUtils.js';
5
4
  export * from './Utils.js';
6
5
  export * from './RequestContext.js';
7
6
  export * from './TransactionContext.js';
7
+ export * from './TransactionManager.js';
8
8
  export * from './QueryHelper.js';
9
9
  export * from './NullHighlighter.js';
10
10
  export * from './EntityComparator.js';
11
11
  export * from './AbstractSchemaGenerator.js';
12
12
  export * from './RawQueryFragment.js';
13
+ export * from './env-vars.js';
13
14
  export * from './upsert-utils.js';
package/utils/index.js CHANGED
@@ -1,13 +1,14 @@
1
1
  export * from './Configuration.js';
2
- export * from './ConfigurationLoader.js';
3
2
  export * from './Cursor.js';
4
3
  export * from './DataloaderUtils.js';
5
4
  export * from './Utils.js';
6
5
  export * from './RequestContext.js';
7
6
  export * from './TransactionContext.js';
7
+ export * from './TransactionManager.js';
8
8
  export * from './QueryHelper.js';
9
9
  export * from './NullHighlighter.js';
10
10
  export * from './EntityComparator.js';
11
11
  export * from './AbstractSchemaGenerator.js';
12
12
  export * from './RawQueryFragment.js';
13
+ export * from './env-vars.js';
13
14
  export * from './upsert-utils.js';
@@ -1,7 +1,12 @@
1
- import type { EntityData, EntityMetadata } from '../typings.js';
1
+ import type { EntityData, EntityMetadata, FilterQuery } from '../typings.js';
2
2
  import type { UpsertOptions } from '../drivers/IDatabaseDriver.js';
3
- import type { RawQueryFragment } from '../utils/RawQueryFragment.js';
3
+ import { type Raw } from '../utils/RawQueryFragment.js';
4
4
  /** @internal */
5
- export declare function getOnConflictFields<T>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | RawQueryFragment, options: UpsertOptions<T>): (keyof T)[];
5
+ export declare function getOnConflictFields<T>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | Raw, options: UpsertOptions<T>): (keyof T)[];
6
6
  /** @internal */
7
- export declare function getOnConflictReturningFields<T, P extends string>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | RawQueryFragment, options: UpsertOptions<T, P>): (keyof T)[] | '*';
7
+ export declare function getOnConflictReturningFields<T, P extends string>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | Raw, options: UpsertOptions<T, P>): (keyof T)[] | '*';
8
+ /** @internal */
9
+ export declare function getWhereCondition<T extends object>(meta: EntityMetadata<T>, onConflictFields: (keyof T)[] | Raw | undefined, data: EntityData<T>, where: FilterQuery<T>): {
10
+ where: FilterQuery<T>;
11
+ propIndex: number | false;
12
+ };
@@ -1,9 +1,11 @@
1
+ import { isRaw } from '../utils/RawQueryFragment.js';
2
+ import { Utils } from './Utils.js';
1
3
  function expandEmbeddedProperties(prop, key) {
2
4
  if (prop.object) {
3
5
  return [prop.name];
4
6
  }
5
7
  return Object.values(prop.embeddedProps).flatMap(p => {
6
- /* v8 ignore next 3 */
8
+ /* v8 ignore next */
7
9
  if (p.embeddable && !p.object) {
8
10
  return expandEmbeddedProperties(p);
9
11
  }
@@ -42,7 +44,7 @@ export function getOnConflictFields(meta, data, uniqueFields, options) {
42
44
  const onConflictMergeFields = expandFields(meta, options.onConflictMergeFields);
43
45
  return onConflictMergeFields.flatMap(f => {
44
46
  const prop = meta?.properties[f];
45
- /* v8 ignore next 3 */
47
+ /* v8 ignore next */
46
48
  if (prop?.embeddable && !prop.object) {
47
49
  return Object.values(prop.embeddedProps).map(p => p.name);
48
50
  }
@@ -67,11 +69,19 @@ export function getOnConflictFields(meta, data, uniqueFields, options) {
67
69
  }
68
70
  /** @internal */
69
71
  export function getOnConflictReturningFields(meta, data, uniqueFields, options) {
70
- /* v8 ignore next 3 */
72
+ /* v8 ignore next */
71
73
  if (!meta) {
72
74
  return '*';
73
75
  }
74
- const keys = meta.comparableProps.filter(p => !p.lazy && !p.embeddable && Array.isArray(uniqueFields) && !uniqueFields.includes(p.name)).map(p => p.name);
76
+ const keys = meta.comparableProps.filter(p => {
77
+ if (p.lazy || p.embeddable) {
78
+ return false;
79
+ }
80
+ if (p.autoincrement) {
81
+ return true;
82
+ }
83
+ return Array.isArray(uniqueFields) && !uniqueFields.includes(p.name);
84
+ }).map(p => p.name);
75
85
  if (meta.versionProperty) {
76
86
  keys.push(meta.versionProperty);
77
87
  }
@@ -88,3 +98,44 @@ export function getOnConflictReturningFields(meta, data, uniqueFields, options)
88
98
  }
89
99
  return keys.filter(key => !(key in data));
90
100
  }
101
+ function getPropertyValue(obj, key) {
102
+ if (key.indexOf('.') === -1) {
103
+ return obj[key];
104
+ }
105
+ const parts = key.split('.');
106
+ let curr = obj;
107
+ for (let i = 0; i < parts.length - 1; i++) {
108
+ curr[parts[i]] ??= {};
109
+ curr = curr[parts[i]];
110
+ }
111
+ return curr[parts[parts.length - 1]];
112
+ }
113
+ /** @internal */
114
+ export function getWhereCondition(meta, onConflictFields, data, where) {
115
+ const unique = onConflictFields ?? meta.props.filter(p => p.unique).map(p => p.name);
116
+ const propIndex = !isRaw(unique) && unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
117
+ if (onConflictFields || where == null) {
118
+ if (propIndex !== false && propIndex >= 0) {
119
+ let key = unique[propIndex];
120
+ if (key.includes('.')) {
121
+ const prop = meta.properties[key.substring(0, key.indexOf('.'))];
122
+ if (prop) {
123
+ key = `${prop.fieldNames[0]}${key.substring(key.indexOf('.'))}`;
124
+ }
125
+ }
126
+ where = { [key]: getPropertyValue(data, unique[propIndex]) };
127
+ }
128
+ else if (meta.uniques.length > 0) {
129
+ for (const u of meta.uniques) {
130
+ if (Utils.asArray(u.properties).every(p => data[p] != null)) {
131
+ where = Utils.asArray(u.properties).reduce((o, key) => {
132
+ o[key] = data[key];
133
+ return o;
134
+ }, {});
135
+ break;
136
+ }
137
+ }
138
+ }
139
+ }
140
+ return { where, propIndex };
141
+ }
@@ -1,3 +0,0 @@
1
- import type { CheckConstraint, EntityClass } from '../typings.js';
2
- export declare function Check<T>(options: CheckOptions<T>): (target: T, propertyName?: T extends EntityClass<unknown> ? undefined : keyof T) => any;
3
- export type CheckOptions<T = any> = CheckConstraint<T>;
@@ -1,13 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- import { Utils } from '../utils/Utils.js';
3
- export function Check(options) {
4
- return function (target, propertyName) {
5
- const meta = MetadataStorage.getMetadataFromDecorator((propertyName ? target.constructor : target));
6
- options.property ??= propertyName;
7
- meta.checks.push(options);
8
- if (!propertyName) {
9
- return target;
10
- }
11
- return Utils.propertyDecoratorReturnValue();
12
- };
13
- }
@@ -1,3 +0,0 @@
1
- import type { ContextProvider } from '../typings.js';
2
- export declare function CreateRequestContext<T extends object>(context?: ContextProvider<T>, respectExistingContext?: boolean): MethodDecorator;
3
- export declare function EnsureRequestContext<T extends object>(context?: ContextProvider<T>): MethodDecorator;
@@ -1,32 +0,0 @@
1
- import { RequestContext } from '../utils/RequestContext.js';
2
- import { resolveContextProvider } from '../utils/resolveContextProvider.js';
3
- import { TransactionContext } from '../utils/TransactionContext.js';
4
- export function CreateRequestContext(context, respectExistingContext = false) {
5
- return function (target, propertyKey, descriptor) {
6
- const originalMethod = descriptor.value;
7
- const name = respectExistingContext ? 'EnsureRequestContext' : 'CreateRequestContext';
8
- if (originalMethod.constructor.name !== 'AsyncFunction') {
9
- throw new Error(`@${name}() should be use with async functions`);
10
- }
11
- descriptor.value = async function (...args) {
12
- const em = await resolveContextProvider(this, context);
13
- if (!em) {
14
- throw new Error(`@${name}() decorator can only be applied to methods of classes with \`orm: MikroORM\` property, \`em: EntityManager\` property, or with a callback parameter like \`@${name}(() => orm)\` that returns one of those types. The parameter will contain a reference to current \`this\`. Returning an EntityRepository from it is also supported.`);
15
- }
16
- // reuse existing context if available for given respect `contextName`
17
- if (respectExistingContext && RequestContext.getEntityManager(em.name)) {
18
- return originalMethod.apply(this, args);
19
- }
20
- // Otherwise, the outer tx context would be preferred.
21
- const txContext = TransactionContext.currentTransactionContext();
22
- const provider = txContext ? TransactionContext : RequestContext;
23
- return txContext
24
- ? provider.create(em.fork({ useContext: true }), () => originalMethod.apply(this, args))
25
- : provider.create(em, () => originalMethod.apply(this, args));
26
- };
27
- return descriptor;
28
- };
29
- }
30
- export function EnsureRequestContext(context) {
31
- return CreateRequestContext(context, true);
32
- }
@@ -1,8 +0,0 @@
1
- import type { AnyString, Dictionary, EntityClass } from '../typings.js';
2
- export declare function Embeddable<T>(options?: EmbeddableOptions<T>): (target: T) => T;
3
- export interface EmbeddableOptions<T> {
4
- discriminatorColumn?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString;
5
- discriminatorMap?: Dictionary<string>;
6
- discriminatorValue?: number | string;
7
- abstract?: boolean;
8
- }
@@ -1,11 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- export function Embeddable(options = {}) {
3
- return function (target) {
4
- const meta = MetadataStorage.getMetadataFromDecorator(target);
5
- meta.class = target;
6
- meta.name = meta.class.name;
7
- meta.embeddable = true;
8
- Object.assign(meta, options);
9
- return target;
10
- };
11
- }
@@ -1,18 +0,0 @@
1
- import type { AnyEntity } from '../typings.js';
2
- export declare function Embedded<T extends object>(type?: EmbeddedOptions | (() => AnyEntity), options?: EmbeddedOptions): (target: AnyEntity, propertyName: string) => any;
3
- /** With `absolute` the prefix is set at the root of the entity (regardless of the nesting level) */
4
- export type EmbeddedPrefixMode = 'absolute' | 'relative';
5
- export interface EmbeddedOptions {
6
- entity?: string | (() => AnyEntity | AnyEntity[]);
7
- type?: string;
8
- prefix?: string | boolean;
9
- prefixMode?: EmbeddedPrefixMode;
10
- nullable?: boolean;
11
- object?: boolean;
12
- array?: boolean;
13
- hidden?: boolean;
14
- serializer?: (value: any) => any;
15
- serializedName?: string;
16
- groups?: string[];
17
- persist?: boolean;
18
- }
@@ -1,18 +0,0 @@
1
- import { MetadataValidator } from '../metadata/MetadataValidator.js';
2
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
3
- import { Utils } from '../utils/Utils.js';
4
- import { ReferenceKind } from '../enums.js';
5
- export function Embedded(type = {}, options = {}) {
6
- return function (target, propertyName) {
7
- const meta = MetadataStorage.getMetadataFromDecorator(target.constructor);
8
- MetadataValidator.validateSingleDecorator(meta, propertyName, ReferenceKind.EMBEDDED);
9
- options = type instanceof Function ? { entity: type, ...options } : { ...type, ...options };
10
- Utils.defaultValue(options, 'prefix', true);
11
- meta.properties[propertyName] = {
12
- name: propertyName,
13
- kind: ReferenceKind.EMBEDDED,
14
- ...options,
15
- };
16
- return Utils.propertyDecoratorReturnValue();
17
- };
18
- }
@@ -1,18 +0,0 @@
1
- import type { AnyString, Constructor, Dictionary, EntityClass, ObjectQuery } from '../typings.js';
2
- import type { FindOptions } from '../drivers/IDatabaseDriver.js';
3
- export declare function Entity<T extends EntityClass<unknown>>(options?: EntityOptions<T>): (target: T) => void;
4
- export type EntityOptions<T, E = T extends EntityClass<infer P> ? P : T> = {
5
- tableName?: string;
6
- schema?: string;
7
- collection?: string;
8
- discriminatorColumn?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString;
9
- discriminatorMap?: Dictionary<string>;
10
- discriminatorValue?: number | string;
11
- forceConstructor?: boolean;
12
- comment?: string;
13
- abstract?: boolean;
14
- readonly?: boolean;
15
- virtual?: boolean;
16
- expression?: string | ((em: any, where: ObjectQuery<E>, options: FindOptions<E, any, any, any>) => object);
17
- repository?: () => Constructor;
18
- };
@@ -1,12 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- import { Utils } from '../utils/Utils.js';
3
- export function Entity(options = {}) {
4
- return function (target) {
5
- const meta = MetadataStorage.getMetadataFromDecorator(target);
6
- Utils.mergeConfig(meta, options);
7
- meta.class = target;
8
- if (!options.abstract || meta.discriminatorColumn) {
9
- meta.name = target.name;
10
- }
11
- };
12
- }