@mikro-orm/core 7.0.0-dev.9 → 7.0.0-dev.90

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 (191) hide show
  1. package/EntityManager.d.ts +77 -48
  2. package/EntityManager.js +288 -225
  3. package/MikroORM.d.ts +40 -31
  4. package/MikroORM.js +98 -137
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +6 -5
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +0 -1
  11. package/cache/index.js +0 -1
  12. package/connections/Connection.d.ts +11 -7
  13. package/connections/Connection.js +16 -14
  14. package/drivers/DatabaseDriver.d.ts +11 -5
  15. package/drivers/DatabaseDriver.js +23 -11
  16. package/drivers/IDatabaseDriver.d.ts +25 -4
  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 +432 -93
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +17 -9
  23. package/entity/EntityFactory.d.ts +7 -0
  24. package/entity/EntityFactory.js +63 -41
  25. package/entity/EntityHelper.js +26 -12
  26. package/entity/EntityLoader.d.ts +5 -4
  27. package/entity/EntityLoader.js +63 -38
  28. package/entity/EntityRepository.d.ts +1 -1
  29. package/entity/Reference.d.ts +6 -5
  30. package/entity/Reference.js +34 -9
  31. package/entity/WrappedEntity.d.ts +2 -7
  32. package/entity/WrappedEntity.js +2 -7
  33. package/entity/defineEntity.d.ts +568 -0
  34. package/entity/defineEntity.js +529 -0
  35. package/entity/index.d.ts +3 -2
  36. package/entity/index.js +3 -2
  37. package/entity/utils.d.ts +7 -0
  38. package/entity/utils.js +16 -4
  39. package/entity/validators.d.ts +11 -0
  40. package/entity/validators.js +65 -0
  41. package/enums.d.ts +21 -6
  42. package/enums.js +14 -1
  43. package/errors.d.ts +10 -2
  44. package/errors.js +29 -10
  45. package/events/EventManager.d.ts +2 -1
  46. package/events/EventManager.js +19 -11
  47. package/events/EventSubscriber.d.ts +3 -1
  48. package/hydration/Hydrator.js +1 -2
  49. package/hydration/ObjectHydrator.d.ts +4 -4
  50. package/hydration/ObjectHydrator.js +35 -25
  51. package/index.d.ts +2 -2
  52. package/index.js +1 -2
  53. package/logging/DefaultLogger.d.ts +1 -1
  54. package/logging/DefaultLogger.js +1 -0
  55. package/logging/SimpleLogger.d.ts +1 -1
  56. package/logging/index.d.ts +1 -0
  57. package/logging/index.js +1 -0
  58. package/logging/inspect.d.ts +2 -0
  59. package/logging/inspect.js +16 -0
  60. package/metadata/EntitySchema.d.ts +9 -13
  61. package/metadata/EntitySchema.js +44 -26
  62. package/metadata/MetadataDiscovery.d.ts +6 -9
  63. package/metadata/MetadataDiscovery.js +165 -205
  64. package/metadata/MetadataProvider.d.ts +11 -2
  65. package/metadata/MetadataProvider.js +44 -2
  66. package/metadata/MetadataStorage.d.ts +1 -6
  67. package/metadata/MetadataStorage.js +6 -18
  68. package/metadata/MetadataValidator.d.ts +0 -7
  69. package/metadata/MetadataValidator.js +0 -10
  70. package/metadata/discover-entities.d.ts +5 -0
  71. package/metadata/discover-entities.js +40 -0
  72. package/metadata/index.d.ts +1 -1
  73. package/metadata/index.js +1 -1
  74. package/metadata/types.d.ts +480 -0
  75. package/metadata/types.js +1 -0
  76. package/naming-strategy/AbstractNamingStrategy.d.ts +5 -1
  77. package/naming-strategy/AbstractNamingStrategy.js +8 -2
  78. package/naming-strategy/NamingStrategy.d.ts +11 -1
  79. package/not-supported.d.ts +2 -0
  80. package/not-supported.js +4 -0
  81. package/package.json +18 -10
  82. package/platforms/ExceptionConverter.js +1 -1
  83. package/platforms/Platform.d.ts +6 -13
  84. package/platforms/Platform.js +15 -41
  85. package/serialization/EntitySerializer.d.ts +2 -0
  86. package/serialization/EntitySerializer.js +32 -14
  87. package/serialization/EntityTransformer.js +22 -12
  88. package/serialization/SerializationContext.js +16 -13
  89. package/types/ArrayType.d.ts +1 -1
  90. package/types/ArrayType.js +2 -3
  91. package/types/BigIntType.d.ts +8 -6
  92. package/types/BigIntType.js +1 -1
  93. package/types/BlobType.d.ts +0 -1
  94. package/types/BlobType.js +0 -3
  95. package/types/BooleanType.d.ts +2 -1
  96. package/types/BooleanType.js +3 -0
  97. package/types/DecimalType.d.ts +6 -4
  98. package/types/DecimalType.js +3 -3
  99. package/types/DoubleType.js +2 -2
  100. package/types/EnumArrayType.js +1 -2
  101. package/types/JsonType.d.ts +1 -1
  102. package/types/JsonType.js +7 -2
  103. package/types/TinyIntType.js +1 -1
  104. package/types/Type.d.ts +2 -4
  105. package/types/Type.js +3 -3
  106. package/types/Uint8ArrayType.d.ts +0 -1
  107. package/types/Uint8ArrayType.js +1 -4
  108. package/types/index.d.ts +1 -1
  109. package/typings.d.ts +109 -73
  110. package/typings.js +38 -35
  111. package/unit-of-work/ChangeSet.d.ts +0 -3
  112. package/unit-of-work/ChangeSet.js +2 -2
  113. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  114. package/unit-of-work/ChangeSetComputer.js +11 -9
  115. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  116. package/unit-of-work/ChangeSetPersister.js +51 -19
  117. package/unit-of-work/UnitOfWork.d.ts +8 -1
  118. package/unit-of-work/UnitOfWork.js +91 -49
  119. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  120. package/utils/AbstractSchemaGenerator.js +11 -9
  121. package/utils/Configuration.d.ts +757 -206
  122. package/utils/Configuration.js +140 -188
  123. package/utils/ConfigurationLoader.d.ts +1 -54
  124. package/utils/ConfigurationLoader.js +1 -352
  125. package/utils/Cursor.d.ts +0 -3
  126. package/utils/Cursor.js +6 -3
  127. package/utils/DataloaderUtils.d.ts +15 -5
  128. package/utils/DataloaderUtils.js +54 -8
  129. package/utils/EntityComparator.d.ts +8 -4
  130. package/utils/EntityComparator.js +52 -17
  131. package/utils/QueryHelper.d.ts +9 -1
  132. package/utils/QueryHelper.js +70 -9
  133. package/utils/RawQueryFragment.d.ts +36 -13
  134. package/utils/RawQueryFragment.js +36 -16
  135. package/utils/TransactionManager.d.ts +65 -0
  136. package/utils/TransactionManager.js +223 -0
  137. package/utils/Utils.d.ts +8 -97
  138. package/utils/Utils.js +82 -302
  139. package/utils/clone.js +2 -3
  140. package/utils/env-vars.d.ts +3 -0
  141. package/utils/env-vars.js +87 -0
  142. package/utils/fs-utils.d.ts +12 -0
  143. package/utils/fs-utils.js +97 -0
  144. package/utils/index.d.ts +2 -1
  145. package/utils/index.js +2 -1
  146. package/utils/upsert-utils.d.ts +7 -2
  147. package/utils/upsert-utils.js +55 -4
  148. package/decorators/Check.d.ts +0 -3
  149. package/decorators/Check.js +0 -13
  150. package/decorators/CreateRequestContext.d.ts +0 -3
  151. package/decorators/CreateRequestContext.js +0 -32
  152. package/decorators/Embeddable.d.ts +0 -8
  153. package/decorators/Embeddable.js +0 -11
  154. package/decorators/Embedded.d.ts +0 -18
  155. package/decorators/Embedded.js +0 -18
  156. package/decorators/Entity.d.ts +0 -18
  157. package/decorators/Entity.js +0 -12
  158. package/decorators/Enum.d.ts +0 -9
  159. package/decorators/Enum.js +0 -16
  160. package/decorators/Filter.d.ts +0 -2
  161. package/decorators/Filter.js +0 -8
  162. package/decorators/Formula.d.ts +0 -4
  163. package/decorators/Formula.js +0 -15
  164. package/decorators/Indexed.d.ts +0 -19
  165. package/decorators/Indexed.js +0 -20
  166. package/decorators/ManyToMany.d.ts +0 -40
  167. package/decorators/ManyToMany.js +0 -14
  168. package/decorators/ManyToOne.d.ts +0 -30
  169. package/decorators/ManyToOne.js +0 -14
  170. package/decorators/OneToMany.d.ts +0 -28
  171. package/decorators/OneToMany.js +0 -17
  172. package/decorators/OneToOne.d.ts +0 -24
  173. package/decorators/OneToOne.js +0 -7
  174. package/decorators/PrimaryKey.d.ts +0 -8
  175. package/decorators/PrimaryKey.js +0 -20
  176. package/decorators/Property.d.ts +0 -250
  177. package/decorators/Property.js +0 -32
  178. package/decorators/Transactional.d.ts +0 -13
  179. package/decorators/Transactional.js +0 -28
  180. package/decorators/hooks.d.ts +0 -16
  181. package/decorators/hooks.js +0 -47
  182. package/decorators/index.d.ts +0 -17
  183. package/decorators/index.js +0 -17
  184. package/entity/ArrayCollection.d.ts +0 -116
  185. package/entity/ArrayCollection.js +0 -402
  186. package/entity/EntityValidator.d.ts +0 -19
  187. package/entity/EntityValidator.js +0 -150
  188. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  189. package/metadata/ReflectMetadataProvider.js +0 -44
  190. package/utils/resolveContextProvider.d.ts +0 -10
  191. package/utils/resolveContextProvider.js +0 -28
@@ -0,0 +1,87 @@
1
+ import { Utils } from './Utils.js';
2
+ /** @internal */
3
+ export function loadEnvironmentVars() {
4
+ const ret = {};
5
+ const getEnvKey = (key, envPrefix = 'MIKRO_ORM_') => {
6
+ return envPrefix + key
7
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
8
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')
9
+ .toUpperCase();
10
+ };
11
+ const array = (v) => v.split(',').map(vv => vv.trim());
12
+ const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
13
+ const num = (v) => +v;
14
+ const read = (o, envPrefix, key, mapper = v => v) => {
15
+ const envKey = getEnvKey(key, envPrefix);
16
+ if (envKey in process.env) {
17
+ o[key] = mapper(process.env[envKey]);
18
+ }
19
+ };
20
+ const cleanup = (o, k) => Utils.hasObjectKeys(o[k]) ? {} : delete o[k];
21
+ const read0 = read.bind(null, ret, 'MIKRO_ORM_');
22
+ read0('baseDir');
23
+ read0('entities', array);
24
+ read0('entitiesTs', array);
25
+ read0('clientUrl');
26
+ read0('host');
27
+ read0('port', num);
28
+ read0('user');
29
+ read0('password');
30
+ read0('dbName');
31
+ read0('schema');
32
+ read0('loadStrategy');
33
+ read0('batchSize', num);
34
+ read0('useBatchInserts', bool);
35
+ read0('useBatchUpdates', bool);
36
+ read0('allowGlobalContext', bool);
37
+ read0('autoJoinOneToOneOwner', bool);
38
+ read0('populateAfterFlush', bool);
39
+ read0('forceEntityConstructor', bool);
40
+ read0('forceUndefined', bool);
41
+ read0('forceUtcTimezone', bool);
42
+ read0('timezone');
43
+ read0('ensureIndexes', bool);
44
+ read0('implicitTransactions', bool);
45
+ read0('debug', bool);
46
+ read0('colors', bool);
47
+ ret.discovery = {};
48
+ const read1 = read.bind(null, ret.discovery, 'MIKRO_ORM_DISCOVERY_');
49
+ read1('warnWhenNoEntities', bool);
50
+ read1('checkDuplicateTableNames', bool);
51
+ read1('checkDuplicateFieldNames', bool);
52
+ read1('checkDuplicateEntities', bool);
53
+ read1('checkNonPersistentCompositeProps', bool);
54
+ read1('inferDefaultValues', bool);
55
+ read1('tsConfigPath');
56
+ cleanup(ret, 'discovery');
57
+ ret.migrations = {};
58
+ const read2 = read.bind(null, ret.migrations, 'MIKRO_ORM_MIGRATIONS_');
59
+ read2('tableName');
60
+ read2('path');
61
+ read2('pathTs');
62
+ read2('glob');
63
+ read2('transactional', bool);
64
+ read2('disableForeignKeys', bool);
65
+ read2('allOrNothing', bool);
66
+ read2('dropTables', bool);
67
+ read2('safe', bool);
68
+ read2('silent', bool);
69
+ read2('emit');
70
+ read2('snapshot', bool);
71
+ read2('snapshotName');
72
+ cleanup(ret, 'migrations');
73
+ ret.schemaGenerator = {};
74
+ const read3 = read.bind(null, ret.schemaGenerator, 'MIKRO_ORM_SCHEMA_GENERATOR_');
75
+ read3('disableForeignKeys', bool);
76
+ read3('createForeignKeyConstraints', bool);
77
+ cleanup(ret, 'schemaGenerator');
78
+ ret.seeder = {};
79
+ const read4 = read.bind(null, ret.seeder, 'MIKRO_ORM_SEEDER_');
80
+ read4('path');
81
+ read4('pathTs');
82
+ read4('glob');
83
+ read4('emit');
84
+ read4('defaultSeeder');
85
+ cleanup(ret, 'seeder');
86
+ return ret;
87
+ }
@@ -0,0 +1,12 @@
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
+ getPackageConfig<T extends Dictionary>(basePath?: string): T;
8
+ getORMPackages(): Set<string>;
9
+ getORMPackageVersion(name: string): string | undefined;
10
+ checkPackageVersion(): void;
11
+ };
12
+ export * from '../cache/FileCacheAdapter.js';
@@ -0,0 +1,97 @@
1
+ import { existsSync, globSync, mkdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { fileURLToPath } 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
+ if (Array.isArray(input)) {
24
+ return input.flatMap(paths => this.glob(paths, cwd));
25
+ }
26
+ const hasGlobChars = /[*?[\]]/.test(input);
27
+ if (!hasGlobChars) {
28
+ try {
29
+ const s = statSync(cwd ? Utils.normalizePath(cwd, input) : input);
30
+ if (s.isDirectory()) {
31
+ const files = globSync(join(input, '**'), { cwd, withFileTypes: true });
32
+ return files.filter(f => f.isFile()).map(f => join(f.parentPath, f.name));
33
+ }
34
+ }
35
+ catch {
36
+ // ignore
37
+ }
38
+ }
39
+ const files = globSync(input, { cwd, withFileTypes: true });
40
+ return files.filter(f => f.isFile()).map(f => join(f.parentPath, f.name));
41
+ },
42
+ getPackageConfig(basePath = process.cwd()) {
43
+ if (this.pathExists(`${basePath}/package.json`)) {
44
+ try {
45
+ const path = import.meta.resolve(`${basePath}/package.json`);
46
+ return this.readJSONSync(fileURLToPath(path));
47
+ }
48
+ catch (e) {
49
+ /* v8 ignore next */
50
+ return {};
51
+ }
52
+ }
53
+ const parentFolder = realpathSync(`${basePath}/..`);
54
+ // we reached the root folder
55
+ if (basePath === parentFolder) {
56
+ return {};
57
+ }
58
+ return this.getPackageConfig(parentFolder);
59
+ },
60
+ getORMPackages() {
61
+ const pkg = this.getPackageConfig();
62
+ return new Set([
63
+ ...Object.keys(pkg.dependencies ?? {}),
64
+ ...Object.keys(pkg.devDependencies ?? {}),
65
+ ]);
66
+ },
67
+ getORMPackageVersion(name) {
68
+ try {
69
+ const path = import.meta.resolve(`${name}/package.json`);
70
+ const pkg = this.readJSONSync(fileURLToPath(path));
71
+ return pkg?.version;
72
+ }
73
+ catch (e) {
74
+ return undefined;
75
+ }
76
+ },
77
+ // inspired by https://github.com/facebook/docusaurus/pull/3386
78
+ checkPackageVersion() {
79
+ const coreVersion = Utils.getORMVersion();
80
+ if (process.env.MIKRO_ORM_ALLOW_VERSION_MISMATCH || coreVersion === '[[MIKRO_ORM_VERSION]]') {
81
+ return;
82
+ }
83
+ const deps = this.getORMPackages();
84
+ const exceptions = new Set(['nestjs', 'sql-highlighter', 'mongo-highlighter']);
85
+ const ormPackages = [...deps].filter(d => d.startsWith('@mikro-orm/') && d !== '@mikro-orm/core' && !exceptions.has(d.substring('@mikro-orm/'.length)));
86
+ for (const ormPackage of ormPackages) {
87
+ const version = this.getORMPackageVersion(ormPackage);
88
+ if (version != null && version !== coreVersion) {
89
+ throw new Error(`Bad ${colors.cyan(ormPackage)} version ${colors.yellow('' + version)}.\n` +
90
+ `All official @mikro-orm/* packages need to have the exact same version as @mikro-orm/core (${colors.green(coreVersion)}).\n` +
91
+ `Only exceptions are packages that don't live in the 'mikro-orm' repository: ${[...exceptions].join(', ')}.\n` +
92
+ `Maybe you want to check, or regenerate your yarn.lock or package-lock.json file?`);
93
+ }
94
+ }
95
+ },
96
+ };
97
+ 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 RawQueryFragment } from '../utils/RawQueryFragment.js';
4
4
  /** @internal */
5
5
  export declare function getOnConflictFields<T>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | RawQueryFragment, options: UpsertOptions<T>): (keyof T)[];
6
6
  /** @internal */
7
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)[] | '*';
8
+ /** @internal */
9
+ export declare function getWhereCondition<T extends object>(meta: EntityMetadata<T>, onConflictFields: (keyof T)[] | RawQueryFragment | 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
- }
@@ -1,9 +0,0 @@
1
- import type { PropertyOptions } from './Property.js';
2
- import type { AnyEntity, Dictionary } from '../typings.js';
3
- export declare function Enum<T extends object>(options?: EnumOptions<AnyEntity> | (() => Dictionary)): (target: T, propertyName: string) => any;
4
- export interface EnumOptions<T> extends PropertyOptions<T> {
5
- items?: (number | string)[] | (() => Dictionary);
6
- array?: boolean;
7
- /** for postgres, by default it uses text column with check constraint */
8
- nativeEnumName?: string;
9
- }
@@ -1,16 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- import { ReferenceKind } from '../enums.js';
3
- import { Utils } from '../utils/Utils.js';
4
- export function Enum(options = {}) {
5
- return function (target, propertyName) {
6
- const meta = MetadataStorage.getMetadataFromDecorator(target.constructor);
7
- options = options instanceof Function ? { items: options } : options;
8
- meta.properties[propertyName] = {
9
- name: propertyName,
10
- kind: ReferenceKind.SCALAR,
11
- enum: true,
12
- ...options,
13
- };
14
- return Utils.propertyDecoratorReturnValue();
15
- };
16
- }
@@ -1,2 +0,0 @@
1
- import type { Dictionary, FilterDef } from '../typings.js';
2
- export declare function Filter<T>(options: FilterDef): <U>(target: U & Dictionary) => U & Dictionary;
@@ -1,8 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- export function Filter(options) {
3
- return function (target) {
4
- const meta = MetadataStorage.getMetadataFromDecorator(target);
5
- meta.filters[options.name] = options;
6
- return target;
7
- };
8
- }
@@ -1,4 +0,0 @@
1
- import type { PropertyOptions } from './Property.js';
2
- export declare function Formula<T extends object>(formula: string | ((alias: string) => string), options?: FormulaOptions<T>): (target: T, propertyName: string) => any;
3
- export interface FormulaOptions<T> extends PropertyOptions<T> {
4
- }
@@ -1,15 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- import { ReferenceKind } from '../enums.js';
3
- import { Utils } from '../utils/Utils.js';
4
- export function Formula(formula, options = {}) {
5
- return function (target, propertyName) {
6
- const meta = MetadataStorage.getMetadataFromDecorator(target.constructor);
7
- meta.properties[propertyName] = {
8
- name: propertyName,
9
- kind: ReferenceKind.SCALAR,
10
- formula,
11
- ...options,
12
- };
13
- return Utils.propertyDecoratorReturnValue();
14
- };
15
- }
@@ -1,19 +0,0 @@
1
- import type { EntityClass, Dictionary, AutoPath } from '../typings.js';
2
- import type { DeferMode } from '../enums.js';
3
- export declare function Index<T extends object, H extends string>(options?: IndexOptions<T, H>): (target: T, propertyName?: (T extends EntityClass<unknown> ? undefined : keyof T) | undefined) => any;
4
- export declare function Unique<T extends object, H extends string>(options?: UniqueOptions<T, H>): (target: T, propertyName?: (T extends EntityClass<unknown> ? undefined : keyof T) | undefined) => any;
5
- type MaybeArray<T> = T | T[];
6
- type Properties<T, H extends string> = MaybeArray<AutoPath<T, H>>;
7
- interface BaseOptions<T, H extends string> {
8
- name?: string;
9
- properties?: (T extends EntityClass<infer P> ? Properties<P, H> : Properties<T, H>);
10
- options?: Dictionary;
11
- expression?: string;
12
- }
13
- export interface UniqueOptions<T, H extends string = string> extends BaseOptions<T, H> {
14
- deferMode?: DeferMode | `${DeferMode}`;
15
- }
16
- export interface IndexOptions<T, H extends string = string> extends BaseOptions<T, H> {
17
- type?: string;
18
- }
19
- export {};
@@ -1,20 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- import { Utils } from '../utils/Utils.js';
3
- function createDecorator(options, unique) {
4
- return function (target, propertyName) {
5
- const meta = MetadataStorage.getMetadataFromDecorator(propertyName ? target.constructor : target);
6
- options.properties ??= propertyName;
7
- const key = unique ? 'uniques' : 'indexes';
8
- meta[key].push(options);
9
- if (!propertyName) {
10
- return target;
11
- }
12
- return Utils.propertyDecoratorReturnValue();
13
- };
14
- }
15
- export function Index(options = {}) {
16
- return createDecorator(options, false);
17
- }
18
- export function Unique(options = {}) {
19
- return createDecorator(options, true);
20
- }
@@ -1,40 +0,0 @@
1
- import type { ReferenceOptions } from './Property.js';
2
- import type { EntityName, FilterQuery, AnyString } from '../typings.js';
3
- import { type QueryOrderMap } from '../enums.js';
4
- export declare function ManyToMany<Target extends object, Owner extends object>(entity?: ManyToManyOptions<Owner, Target> | string | (() => EntityName<Target>), mappedBy?: (string & keyof Target) | ((e: Target) => any), options?: Partial<ManyToManyOptions<Owner, Target>>): (target: Owner, propertyName: keyof Owner) => any;
5
- export interface ManyToManyOptions<Owner, Target> extends ReferenceOptions<Owner, Target> {
6
- /** Set this side as owning. Owning side is where the foreign key is defined. This option is not required if you use `inversedBy` or `mappedBy` to distinguish owning and inverse side. */
7
- owner?: boolean;
8
- /** Point to the inverse side property name. */
9
- inversedBy?: (string & keyof Target) | ((e: Target) => any);
10
- /** Point to the owning side property name. */
11
- mappedBy?: (string & keyof Target) | ((e: Target) => any);
12
- /** Condition for {@doclink collections#declarative-partial-loading | Declarative partial loading}. */
13
- where?: FilterQuery<Target>;
14
- /** Set default ordering. */
15
- orderBy?: QueryOrderMap<Target> | QueryOrderMap<Target>[];
16
- /** Force stable insertion order of items in the collection (see {@doclink collections | Collections}). */
17
- fixedOrder?: boolean;
18
- /** Override default order column name (`id`) for fixed ordering. */
19
- fixedOrderColumn?: string;
20
- /** Override default name for pivot table (see {@doclink naming-strategy | Naming Strategy}). */
21
- pivotTable?: string;
22
- /** Set pivot entity for this relation (see {@doclink collections#custom-pivot-table-entity | Custom pivot table entity}). */
23
- pivotEntity?: string | (() => EntityName<any>);
24
- /** Override the default database column name on the owning side (see {@doclink naming-strategy | Naming Strategy}). This option is only for simple properties represented by a single column. */
25
- joinColumn?: string;
26
- /** Override the default database column name on the owning side (see {@doclink naming-strategy | Naming Strategy}). This option is suitable for composite keys, where one property is represented by multiple columns. */
27
- joinColumns?: string[];
28
- /** Override the default database column name on the inverse side (see {@doclink naming-strategy | Naming Strategy}). This option is only for simple properties represented by a single column. */
29
- inverseJoinColumn?: string;
30
- /** Override the default database column name on the inverse side (see {@doclink naming-strategy | Naming Strategy}). This option is suitable for composite keys, where one property is represented by multiple columns. */
31
- inverseJoinColumns?: string[];
32
- /** Override the default database column name on the target entity (see {@doclink naming-strategy | Naming Strategy}). This option is only for simple properties represented by a single column. */
33
- referenceColumnName?: string;
34
- /** Override the default database column name on the target entity (see {@doclink naming-strategy | Naming Strategy}). This option is suitable for composite keys, where one property is represented by multiple columns. */
35
- referencedColumnNames?: string[];
36
- /** What to do when the target entity gets deleted. */
37
- deleteRule?: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString;
38
- /** What to do when the reference to the target entity gets updated. */
39
- updateRule?: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString;
40
- }