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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/EntityManager.d.ts +11 -2
  2. package/EntityManager.js +39 -53
  3. package/README.md +1 -2
  4. package/connections/Connection.d.ts +4 -2
  5. package/connections/Connection.js +2 -2
  6. package/decorators/Entity.d.ts +14 -0
  7. package/decorators/Indexed.d.ts +2 -2
  8. package/decorators/ManyToMany.d.ts +2 -0
  9. package/decorators/ManyToOne.d.ts +2 -0
  10. package/decorators/OneToOne.d.ts +2 -0
  11. package/decorators/Transactional.d.ts +1 -0
  12. package/decorators/Transactional.js +3 -3
  13. package/drivers/IDatabaseDriver.d.ts +4 -0
  14. package/entity/ArrayCollection.d.ts +3 -1
  15. package/entity/ArrayCollection.js +7 -2
  16. package/entity/EntityFactory.d.ts +6 -0
  17. package/entity/EntityFactory.js +17 -6
  18. package/entity/EntityHelper.js +4 -1
  19. package/entity/EntityLoader.js +26 -18
  20. package/entity/Reference.d.ts +5 -0
  21. package/entity/Reference.js +16 -0
  22. package/entity/WrappedEntity.js +1 -1
  23. package/entity/defineEntity.d.ts +537 -0
  24. package/entity/defineEntity.js +703 -0
  25. package/entity/index.d.ts +2 -0
  26. package/entity/index.js +2 -0
  27. package/entity/utils.d.ts +7 -0
  28. package/entity/utils.js +16 -3
  29. package/enums.d.ts +13 -1
  30. package/enums.js +13 -1
  31. package/errors.d.ts +5 -0
  32. package/errors.js +13 -1
  33. package/hydration/ObjectHydrator.js +1 -1
  34. package/index.d.ts +1 -1
  35. package/index.mjs +16 -0
  36. package/metadata/EntitySchema.js +10 -2
  37. package/metadata/MetadataDiscovery.d.ts +0 -1
  38. package/metadata/MetadataDiscovery.js +17 -13
  39. package/package.json +4 -4
  40. package/platforms/Platform.d.ts +3 -1
  41. package/types/BooleanType.d.ts +1 -1
  42. package/types/DecimalType.js +1 -1
  43. package/types/DoubleType.js +1 -1
  44. package/typings.d.ts +32 -11
  45. package/typings.js +21 -4
  46. package/unit-of-work/ChangeSetComputer.js +3 -1
  47. package/unit-of-work/ChangeSetPersister.d.ts +4 -2
  48. package/unit-of-work/ChangeSetPersister.js +14 -10
  49. package/unit-of-work/UnitOfWork.d.ts +2 -1
  50. package/unit-of-work/UnitOfWork.js +36 -13
  51. package/utils/Configuration.d.ts +7 -1
  52. package/utils/Configuration.js +1 -0
  53. package/utils/ConfigurationLoader.js +2 -2
  54. package/utils/Cursor.js +3 -0
  55. package/utils/EntityComparator.d.ts +6 -2
  56. package/utils/EntityComparator.js +29 -8
  57. package/utils/QueryHelper.d.ts +6 -0
  58. package/utils/QueryHelper.js +47 -4
  59. package/utils/RawQueryFragment.d.ts +34 -0
  60. package/utils/RawQueryFragment.js +35 -0
  61. package/utils/TransactionManager.d.ts +65 -0
  62. package/utils/TransactionManager.js +203 -0
  63. package/utils/Utils.d.ts +2 -2
  64. package/utils/Utils.js +32 -8
  65. package/utils/index.d.ts +1 -0
  66. package/utils/index.js +1 -0
  67. package/utils/upsert-utils.js +9 -1
package/entity/index.d.ts CHANGED
@@ -11,3 +11,5 @@ export * from './Reference';
11
11
  export * from './BaseEntity';
12
12
  export * from './WrappedEntity';
13
13
  export * from './wrap';
14
+ export * from './defineEntity';
15
+ export * from './utils';
package/entity/index.js CHANGED
@@ -27,3 +27,5 @@ __exportStar(require("./Reference"), exports);
27
27
  __exportStar(require("./BaseEntity"), exports);
28
28
  __exportStar(require("./WrappedEntity"), exports);
29
29
  __exportStar(require("./wrap"), exports);
30
+ __exportStar(require("./defineEntity"), exports);
31
+ __exportStar(require("./utils"), exports);
package/entity/utils.d.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  import type { EntityMetadata, PopulateOptions } from '../typings';
2
+ import { LoadStrategy, ReferenceKind } from '../enums';
2
3
  /**
3
4
  * @internal
4
5
  */
5
6
  export declare function expandDotPaths<Entity>(meta: EntityMetadata<Entity>, populate?: readonly (string | PopulateOptions<Entity>)[], normalized?: boolean): PopulateOptions<Entity>[];
7
+ /**
8
+ * Returns the loading strategy based on the provided hint.
9
+ * If `BALANCED` strategy is used, it will return JOINED if the property is a to-one relation.
10
+ * @internal
11
+ */
12
+ export declare function getLoadingStrategy(strategy: LoadStrategy | `${LoadStrategy}`, kind: ReferenceKind): LoadStrategy.SELECT_IN | LoadStrategy.JOINED;
package/entity/utils.js CHANGED
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.expandDotPaths = expandDotPaths;
4
+ exports.getLoadingStrategy = getLoadingStrategy;
4
5
  const enums_1 = require("../enums");
5
- const core_1 = require("@mikro-orm/core");
6
+ const Utils_1 = require("../utils/Utils");
6
7
  /**
7
8
  * Expands `books.perex` like populate to use `children` array instead of the dot syntax
8
9
  */
@@ -20,7 +21,7 @@ function expandNestedPopulate(parentProp, parts, strategy, all) {
20
21
  * @internal
21
22
  */
22
23
  function expandDotPaths(meta, populate, normalized = false) {
23
- const ret = normalized ? populate : core_1.Utils.asArray(populate).map(field => {
24
+ const ret = normalized ? populate : Utils_1.Utils.asArray(populate).map(field => {
24
25
  if (typeof field === 'string') {
25
26
  return { field };
26
27
  }
@@ -37,7 +38,6 @@ function expandDotPaths(meta, populate, normalized = false) {
37
38
  p.field = f;
38
39
  p.children ??= [];
39
40
  const prop = meta.properties[p.field];
40
- p.strategy ??= prop.strategy;
41
41
  if (parts[0] === enums_1.PopulatePath.ALL) {
42
42
  prop.targetMeta.props
43
43
  .filter(prop => prop.lazy || prop.kind !== enums_1.ReferenceKind.SCALAR)
@@ -58,3 +58,16 @@ function expandDotPaths(meta, populate, normalized = false) {
58
58
  }
59
59
  return ret;
60
60
  }
61
+ /**
62
+ * Returns the loading strategy based on the provided hint.
63
+ * If `BALANCED` strategy is used, it will return JOINED if the property is a to-one relation.
64
+ * @internal
65
+ */
66
+ function getLoadingStrategy(strategy, kind) {
67
+ if (strategy === enums_1.LoadStrategy.BALANCED) {
68
+ return [enums_1.ReferenceKind.MANY_TO_ONE, enums_1.ReferenceKind.ONE_TO_ONE].includes(kind)
69
+ ? enums_1.LoadStrategy.JOINED
70
+ : enums_1.LoadStrategy.SELECT_IN;
71
+ }
72
+ return strategy;
73
+ }
package/enums.d.ts CHANGED
@@ -85,6 +85,7 @@ export declare enum QueryFlag {
85
85
  INCLUDE_LAZY_FORMULAS = "INCLUDE_LAZY_FORMULAS",
86
86
  AUTO_JOIN_ONE_TO_ONE_OWNER = "AUTO_JOIN_ONE_TO_ONE_OWNER",
87
87
  INFER_POPULATE = "INFER_POPULATE",
88
+ DISABLE_NESTED_INNER_JOIN = "DISABLE_NESTED_INNER_JOIN",
88
89
  IDENTITY_INSERT = "IDENTITY_INSERT"
89
90
  }
90
91
  export declare const SCALAR_TYPES: string[];
@@ -108,7 +109,8 @@ export declare enum Cascade {
108
109
  }
109
110
  export declare enum LoadStrategy {
110
111
  SELECT_IN = "select-in",
111
- JOINED = "joined"
112
+ JOINED = "joined",
113
+ BALANCED = "balanced"
112
114
  }
113
115
  export declare enum DataloaderType {
114
116
  NONE = 0,
@@ -156,8 +158,18 @@ export declare enum EventType {
156
158
  }
157
159
  export declare const EventTypeMap: Record<EventType, number>;
158
160
  export type TransactionEventType = EventType.beforeTransactionStart | EventType.afterTransactionStart | EventType.beforeTransactionCommit | EventType.afterTransactionCommit | EventType.beforeTransactionRollback | EventType.afterTransactionRollback;
161
+ export declare enum TransactionPropagation {
162
+ REQUIRED = "required",
163
+ REQUIRES_NEW = "requires_new",
164
+ NESTED = "nested",
165
+ NOT_SUPPORTED = "not_supported",
166
+ SUPPORTS = "supports",
167
+ MANDATORY = "mandatory",
168
+ NEVER = "never"
169
+ }
159
170
  export interface TransactionOptions {
160
171
  ctx?: Transaction;
172
+ propagation?: TransactionPropagation;
161
173
  isolationLevel?: IsolationLevel;
162
174
  readOnly?: boolean;
163
175
  clear?: boolean;
package/enums.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DeferMode = exports.PlainObject = exports.EventTypeMap = exports.EventType = exports.IsolationLevel = exports.LockMode = exports.DataloaderType = exports.LoadStrategy = exports.Cascade = exports.ReferenceKind = exports.SCALAR_TYPES = exports.QueryFlag = exports.QueryOrderNumeric = exports.QueryOrder = exports.JSON_KEY_OPERATORS = exports.ARRAY_OPERATORS = exports.QueryOperator = exports.GroupOperator = exports.PopulatePath = exports.PopulateHint = exports.FlushMode = void 0;
3
+ exports.DeferMode = exports.PlainObject = exports.TransactionPropagation = exports.EventTypeMap = exports.EventType = exports.IsolationLevel = exports.LockMode = exports.DataloaderType = exports.LoadStrategy = exports.Cascade = exports.ReferenceKind = exports.SCALAR_TYPES = exports.QueryFlag = exports.QueryOrderNumeric = exports.QueryOrder = exports.JSON_KEY_OPERATORS = exports.ARRAY_OPERATORS = exports.QueryOperator = exports.GroupOperator = exports.PopulatePath = exports.PopulateHint = exports.FlushMode = void 0;
4
4
  var FlushMode;
5
5
  (function (FlushMode) {
6
6
  /** The `EntityManager` delays the flush until the current Transaction is committed. */
@@ -98,6 +98,7 @@ var QueryFlag;
98
98
  QueryFlag["INCLUDE_LAZY_FORMULAS"] = "INCLUDE_LAZY_FORMULAS";
99
99
  QueryFlag["AUTO_JOIN_ONE_TO_ONE_OWNER"] = "AUTO_JOIN_ONE_TO_ONE_OWNER";
100
100
  QueryFlag["INFER_POPULATE"] = "INFER_POPULATE";
101
+ QueryFlag["DISABLE_NESTED_INNER_JOIN"] = "DISABLE_NESTED_INNER_JOIN";
101
102
  QueryFlag["IDENTITY_INSERT"] = "IDENTITY_INSERT";
102
103
  })(QueryFlag || (exports.QueryFlag = QueryFlag = {}));
103
104
  exports.SCALAR_TYPES = ['string', 'number', 'boolean', 'bigint', 'Date', 'Buffer', 'RegExp'];
@@ -125,6 +126,7 @@ var LoadStrategy;
125
126
  (function (LoadStrategy) {
126
127
  LoadStrategy["SELECT_IN"] = "select-in";
127
128
  LoadStrategy["JOINED"] = "joined";
129
+ LoadStrategy["BALANCED"] = "balanced";
128
130
  })(LoadStrategy || (exports.LoadStrategy = LoadStrategy = {}));
129
131
  var DataloaderType;
130
132
  (function (DataloaderType) {
@@ -178,6 +180,16 @@ exports.EventTypeMap = Object.keys(EventType).reduce((a, b, i) => {
178
180
  a[b] = i;
179
181
  return a;
180
182
  }, {});
183
+ var TransactionPropagation;
184
+ (function (TransactionPropagation) {
185
+ TransactionPropagation["REQUIRED"] = "required";
186
+ TransactionPropagation["REQUIRES_NEW"] = "requires_new";
187
+ TransactionPropagation["NESTED"] = "nested";
188
+ TransactionPropagation["NOT_SUPPORTED"] = "not_supported";
189
+ TransactionPropagation["SUPPORTS"] = "supports";
190
+ TransactionPropagation["MANDATORY"] = "mandatory";
191
+ TransactionPropagation["NEVER"] = "never";
192
+ })(TransactionPropagation || (exports.TransactionPropagation = TransactionPropagation = {}));
181
193
  class PlainObject {
182
194
  }
183
195
  exports.PlainObject = PlainObject;
package/errors.d.ts CHANGED
@@ -67,3 +67,8 @@ export declare class NotFoundError<T extends AnyEntity = AnyEntity> extends Vali
67
67
  static findOneFailed(name: string, where: Dictionary | IPrimaryKey): NotFoundError;
68
68
  static findExactlyOneFailed(name: string, where: Dictionary | IPrimaryKey): NotFoundError;
69
69
  }
70
+ export declare class TransactionStateError extends ValidationError {
71
+ static requiredTransactionNotFound(propagation: string): TransactionStateError;
72
+ static transactionNotAllowed(propagation: string): TransactionStateError;
73
+ static invalidPropagation(propagation: string): TransactionStateError;
74
+ }
package/errors.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NotFoundError = exports.MetadataError = exports.OptimisticLockError = exports.CursorError = exports.ValidationError = void 0;
3
+ exports.TransactionStateError = exports.NotFoundError = exports.MetadataError = exports.OptimisticLockError = exports.CursorError = exports.ValidationError = void 0;
4
4
  const node_util_1 = require("node:util");
5
5
  class ValidationError extends Error {
6
6
  entity;
@@ -232,3 +232,15 @@ class NotFoundError extends ValidationError {
232
232
  }
233
233
  }
234
234
  exports.NotFoundError = NotFoundError;
235
+ class TransactionStateError extends ValidationError {
236
+ static requiredTransactionNotFound(propagation) {
237
+ return new TransactionStateError(`No existing transaction found for transaction marked with propagation "${propagation}"`);
238
+ }
239
+ static transactionNotAllowed(propagation) {
240
+ return new TransactionStateError(`Existing transaction found for transaction marked with propagation "${propagation}"`);
241
+ }
242
+ static invalidPropagation(propagation) {
243
+ return new TransactionStateError(`Unsupported transaction propagation type: ${propagation}`);
244
+ }
245
+ }
246
+ exports.TransactionStateError = TransactionStateError;
@@ -65,7 +65,7 @@ class ObjectHydrator extends Hydrator_1.Hydrator {
65
65
  const ret = [];
66
66
  const idx = this.tmpIndex++;
67
67
  const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
68
- if (prop.getter && !prop.setter) {
68
+ if (prop.getter && !prop.setter && prop.persist === false) {
69
69
  return [];
70
70
  }
71
71
  if (prop.ref) {
package/index.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * @packageDocumentation
3
3
  * @module core
4
4
  */
5
- export { Constructor, ConnectionType, Dictionary, PrimaryKeyProp, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, EntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, EntityMetadata, QBFilterQuery, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, EntityRepositoryType, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, MigrationDiff, GenerateOptions, FilterObject, IEntityGenerator, ISeedManager, EntityClassGroup, OptionalProps, EagerProps, HiddenProps, RequiredEntityData, CheckCallback, SimpleColumnMeta, Rel, Ref, ScalarRef, EntityRef, ISchemaGenerator, UmzugMigration, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, Opt, EntityType, FromEntityType, Selected, IsSubset, NoInfer, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, Hidden, FilterValue, MergeLoaded, MergeSelected, Config, DefineConfig, TypeConfig, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, } from './typings';
5
+ export { Constructor, ConnectionType, Dictionary, PrimaryKeyProp, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, EntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, EntityMetadata, QBFilterQuery, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, EntityRepositoryType, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, MigrationDiff, GenerateOptions, FilterObject, IEntityGenerator, ISeedManager, EntityClassGroup, OptionalProps, EagerProps, HiddenProps, RequiredEntityData, CheckCallback, IndexCallback, SimpleColumnMeta, Rel, Ref, ScalarRef, EntityRef, ISchemaGenerator, UmzugMigration, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, Opt, EntityType, FromEntityType, Selected, IsSubset, NoInfer, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, Hidden, FilterValue, MergeLoaded, MergeSelected, Config, DefineConfig, TypeConfig, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, } from './typings';
6
6
  export * from './enums';
7
7
  export * from './errors';
8
8
  export * from './exceptions';
package/index.mjs CHANGED
@@ -55,6 +55,7 @@ export const DriverException = mod.DriverException;
55
55
  export const EagerProps = mod.EagerProps;
56
56
  export const Embeddable = mod.Embeddable;
57
57
  export const Embedded = mod.Embedded;
58
+ export const EmbeddedOptionsBuilder = mod.EmbeddedOptionsBuilder;
58
59
  export const EnsureRequestContext = mod.EnsureRequestContext;
59
60
  export const Entity = mod.Entity;
60
61
  export const EntityAssigner = mod.EntityAssigner;
@@ -75,6 +76,7 @@ export const EntityTransformer = mod.EntityTransformer;
75
76
  export const EntityValidator = mod.EntityValidator;
76
77
  export const Enum = mod.Enum;
77
78
  export const EnumArrayType = mod.EnumArrayType;
79
+ export const EnumOptionsBuilder = mod.EnumOptionsBuilder;
78
80
  export const EnumType = mod.EnumType;
79
81
  export const EventManager = mod.EventManager;
80
82
  export const EventType = mod.EventType;
@@ -103,7 +105,9 @@ export const LoadStrategy = mod.LoadStrategy;
103
105
  export const LockMode = mod.LockMode;
104
106
  export const LockWaitTimeoutException = mod.LockWaitTimeoutException;
105
107
  export const ManyToMany = mod.ManyToMany;
108
+ export const ManyToManyOptionsBuilder = mod.ManyToManyOptionsBuilder;
106
109
  export const ManyToOne = mod.ManyToOne;
110
+ export const ManyToOneOptionsBuilder = mod.ManyToOneOptionsBuilder;
107
111
  export const MediumIntType = mod.MediumIntType;
108
112
  export const MemoryCacheAdapter = mod.MemoryCacheAdapter;
109
113
  export const MetadataDiscovery = mod.MetadataDiscovery;
@@ -124,7 +128,10 @@ export const ObjectHydrator = mod.ObjectHydrator;
124
128
  export const OnInit = mod.OnInit;
125
129
  export const OnLoad = mod.OnLoad;
126
130
  export const OneToMany = mod.OneToMany;
131
+ export const OneToManyOptionsBuilder = mod.OneToManyOptionsBuilder;
132
+ export const OneToManyOptionsBuilderOnlyMappedBy = mod.OneToManyOptionsBuilderOnlyMappedBy;
127
133
  export const OneToOne = mod.OneToOne;
134
+ export const OneToOneOptionsBuilder = mod.OneToOneOptionsBuilder;
128
135
  export const OptimisticLockError = mod.OptimisticLockError;
129
136
  export const OptionalProps = mod.OptionalProps;
130
137
  export const PlainObject = mod.PlainObject;
@@ -134,6 +141,7 @@ export const PopulatePath = mod.PopulatePath;
134
141
  export const PrimaryKey = mod.PrimaryKey;
135
142
  export const PrimaryKeyProp = mod.PrimaryKeyProp;
136
143
  export const Property = mod.Property;
144
+ export const PropertyOptionsBuilder = mod.PropertyOptionsBuilder;
137
145
  export const QueryFlag = mod.QueryFlag;
138
146
  export const QueryHelper = mod.QueryHelper;
139
147
  export const QueryOperator = mod.QueryOperator;
@@ -144,6 +152,7 @@ export const ReadOnlyException = mod.ReadOnlyException;
144
152
  export const Ref = mod.Ref;
145
153
  export const Reference = mod.Reference;
146
154
  export const ReferenceKind = mod.ReferenceKind;
155
+ export const ReferenceOptionsBuilder = mod.ReferenceOptionsBuilder;
147
156
  export const ReflectMetadataProvider = mod.ReflectMetadataProvider;
148
157
  export const RequestContext = mod.RequestContext;
149
158
  export const SCALAR_TYPES = mod.SCALAR_TYPES;
@@ -162,6 +171,9 @@ export const TimeType = mod.TimeType;
162
171
  export const TinyIntType = mod.TinyIntType;
163
172
  export const TransactionContext = mod.TransactionContext;
164
173
  export const TransactionEventBroadcaster = mod.TransactionEventBroadcaster;
174
+ export const TransactionManager = mod.TransactionManager;
175
+ export const TransactionPropagation = mod.TransactionPropagation;
176
+ export const TransactionStateError = mod.TransactionStateError;
165
177
  export const Transactional = mod.Transactional;
166
178
  export const Type = mod.Type;
167
179
  export const Uint8ArrayType = mod.Uint8ArrayType;
@@ -182,11 +194,15 @@ export const compareBuffers = mod.compareBuffers;
182
194
  export const compareObjects = mod.compareObjects;
183
195
  export const createSqlFunction = mod.createSqlFunction;
184
196
  export const defineConfig = mod.defineConfig;
197
+ export const defineEntity = mod.defineEntity;
185
198
  export const equals = mod.equals;
199
+ export const expandDotPaths = mod.expandDotPaths;
200
+ export const getLoadingStrategy = mod.getLoadingStrategy;
186
201
  export const getOnConflictFields = mod.getOnConflictFields;
187
202
  export const getOnConflictReturningFields = mod.getOnConflictReturningFields;
188
203
  export const helper = mod.helper;
189
204
  export const parseJsonSafe = mod.parseJsonSafe;
205
+ export const quote = mod.quote;
190
206
  export const raw = mod.raw;
191
207
  export const ref = mod.ref;
192
208
  export const rel = mod.rel;
@@ -102,6 +102,8 @@ class EntitySchema {
102
102
  if (prop.fieldNames && !prop.joinColumns) {
103
103
  prop.joinColumns = prop.fieldNames;
104
104
  }
105
+ // By default, the foreign key constraint is created on the relation
106
+ utils_1.Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
105
107
  this.addProperty(name, type, prop);
106
108
  }
107
109
  addManyToMany(name, type, options) {
@@ -111,6 +113,8 @@ class EntitySchema {
111
113
  }
112
114
  if (options.owner) {
113
115
  utils_1.Utils.renameKey(options, 'mappedBy', 'inversedBy');
116
+ // By default, the foreign key constraint is created on the relation
117
+ utils_1.Utils.defaultValue(options, 'createForeignKeyConstraint', true);
114
118
  }
115
119
  const prop = this.createProperty(enums_1.ReferenceKind.MANY_TO_MANY, options);
116
120
  this.addProperty(name, type, prop);
@@ -123,8 +127,12 @@ class EntitySchema {
123
127
  const prop = this.createProperty(enums_1.ReferenceKind.ONE_TO_ONE, options);
124
128
  utils_1.Utils.defaultValue(prop, 'owner', !!prop.inversedBy || !prop.mappedBy);
125
129
  utils_1.Utils.defaultValue(prop, 'unique', prop.owner);
126
- if (prop.owner && options.mappedBy) {
127
- utils_1.Utils.renameKey(prop, 'mappedBy', 'inversedBy');
130
+ if (prop.owner) {
131
+ if (options.mappedBy) {
132
+ utils_1.Utils.renameKey(prop, 'mappedBy', 'inversedBy');
133
+ }
134
+ // By default, the foreign key constraint is created on the relation
135
+ utils_1.Utils.defaultValue(prop, 'createForeignKeyConstraint', true);
128
136
  }
129
137
  if (prop.joinColumns && !prop.fieldNames) {
130
138
  prop.fieldNames = prop.joinColumns;
@@ -54,7 +54,6 @@ export declare class MetadataDiscovery {
54
54
  private initAutoincrement;
55
55
  private initCheckConstraints;
56
56
  private initGeneratedColumn;
57
- private createColumnMappingObject;
58
57
  private getDefaultVersionValue;
59
58
  private inferDefaultValue;
60
59
  private initDefaultValue;
@@ -622,7 +622,7 @@ class MetadataDiscovery {
622
622
  }
623
623
  data.properties[meta.name + '_owner'] = this.definePivotProperty(prop, meta.name + '_owner', meta.className, targetType + '_inverse', true, meta.className === targetType);
624
624
  data.properties[targetType + '_inverse'] = this.definePivotProperty(prop, targetType + '_inverse', targetType, meta.name + '_owner', false, meta.className === targetType);
625
- return this.metadata.set(data.className, data);
625
+ return this.metadata.set(data.className, EntitySchema_1.EntitySchema.fromMetadata(data).init().meta);
626
626
  }
627
627
  defineFixedOrderProperty(prop, targetType) {
628
628
  const pk = prop.fixedOrderColumn || this.namingStrategy.referenceColumnName();
@@ -657,6 +657,7 @@ class MetadataDiscovery {
657
657
  autoincrement: false,
658
658
  updateRule: prop.updateRule,
659
659
  deleteRule: prop.deleteRule,
660
+ createForeignKeyConstraint: prop.createForeignKeyConstraint,
660
661
  };
661
662
  if (selfReferencing && !this.platform.supportsMultipleCascadePaths()) {
662
663
  ret.updateRule ??= 'no action';
@@ -824,9 +825,16 @@ class MetadataDiscovery {
824
825
  }
825
826
  return prop.embedded ? isParentObject(meta.properties[prop.embedded[0]]) : false;
826
827
  };
828
+ const isParentArray = (prop) => {
829
+ if (prop.array) {
830
+ return true;
831
+ }
832
+ return prop.embedded ? isParentArray(meta.properties[prop.embedded[0]]) : false;
833
+ };
827
834
  const rootProperty = getRootProperty(embeddedProp);
828
835
  const parentProperty = meta.properties[embeddedProp.embedded?.[0] ?? ''];
829
836
  const object = isParentObject(embeddedProp);
837
+ const array = isParentArray(embeddedProp);
830
838
  this.initFieldName(embeddedProp, rootProperty !== embeddedProp && object);
831
839
  // the prefix of the parent cannot be a boolean; it already passed here
832
840
  const prefix = this.getPrefix(embeddedProp, parentProperty);
@@ -839,7 +847,8 @@ class MetadataDiscovery {
839
847
  meta.propertyOrder.set(name, (order += 0.01));
840
848
  embeddedProp.embeddedProps[prop.name] = meta.properties[name];
841
849
  meta.properties[name].persist ??= embeddedProp.persist;
842
- if (embeddedProp.nullable) {
850
+ const refInArray = array && [enums_1.ReferenceKind.MANY_TO_ONE, enums_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind) && prop.owner;
851
+ if (embeddedProp.nullable || refInArray) {
843
852
  meta.properties[name].nullable = true;
844
853
  }
845
854
  if (meta.properties[name].fieldNames) {
@@ -968,7 +977,7 @@ class MetadataDiscovery {
968
977
  }
969
978
  }
970
979
  initCheckConstraints(meta) {
971
- const map = this.createColumnMappingObject(meta);
980
+ const map = meta.createColumnMappingObject();
972
981
  for (const check of meta.checks) {
973
982
  const columns = check.property ? meta.properties[check.property].fieldNames : [];
974
983
  check.name ??= this.namingStrategy.indexName(meta.tableName, columns, 'check');
@@ -991,19 +1000,11 @@ class MetadataDiscovery {
991
1000
  }
992
1001
  return;
993
1002
  }
994
- const map = this.createColumnMappingObject(meta);
1003
+ const map = meta.createColumnMappingObject();
995
1004
  if (prop.generated instanceof Function) {
996
1005
  prop.generated = prop.generated(map);
997
1006
  }
998
1007
  }
999
- createColumnMappingObject(meta) {
1000
- return Object.values(meta.properties).reduce((o, prop) => {
1001
- if (prop.fieldNames) {
1002
- o[prop.name] = prop.fieldNames[0];
1003
- }
1004
- return o;
1005
- }, {});
1006
- }
1007
1008
  getDefaultVersionValue(meta, prop) {
1008
1009
  if (typeof prop.defaultRaw !== 'undefined') {
1009
1010
  return prop.defaultRaw;
@@ -1057,7 +1058,7 @@ class MetadataDiscovery {
1057
1058
  prop.defaultRaw = this.platform.formatQuery(raw.sql, raw.params);
1058
1059
  return;
1059
1060
  }
1060
- if (prop.customType instanceof types_1.ArrayType && Array.isArray(prop.default)) {
1061
+ if (Array.isArray(prop.default) && prop.customType) {
1061
1062
  val = prop.customType.convertToDatabaseValue(prop.default, this.platform);
1062
1063
  }
1063
1064
  prop.defaultRaw = typeof val === 'string' ? `'${val}'` : '' + val;
@@ -1111,6 +1112,9 @@ class MetadataDiscovery {
1111
1112
  if (prop.kind === enums_1.ReferenceKind.SCALAR && !prop.customType && prop.columnTypes && ['json', 'jsonb'].includes(prop.columnTypes[0])) {
1112
1113
  prop.customType = new types_1.JsonType();
1113
1114
  }
1115
+ if (prop.kind === enums_1.ReferenceKind.EMBEDDED && !prop.customType && (prop.object || prop.array)) {
1116
+ prop.customType = new types_1.JsonType();
1117
+ }
1114
1118
  if (!prop.customType && prop.array && prop.items) {
1115
1119
  prop.customType = new types_1.EnumArrayType(`${meta.className}.${prop.name}`, prop.items);
1116
1120
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "6.4.17-dev.1",
3
+ "version": "6.4.17-dev.100",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",
@@ -60,11 +60,11 @@
60
60
  },
61
61
  "dependencies": {
62
62
  "dataloader": "2.2.3",
63
- "dotenv": "16.5.0",
63
+ "dotenv": "17.2.1",
64
64
  "esprima": "4.0.1",
65
- "fs-extra": "11.3.0",
65
+ "fs-extra": "11.3.1",
66
66
  "globby": "11.1.0",
67
- "mikro-orm": "6.4.17-dev.1",
67
+ "mikro-orm": "6.4.17-dev.100",
68
68
  "reflect-metadata": "0.2.2"
69
69
  }
70
70
  }
@@ -173,7 +173,9 @@ export declare abstract class Platform {
173
173
  getExtension<T>(extensionName: string, extensionKey: string, moduleName: string, em: EntityManager): T;
174
174
  getSchemaGenerator(driver: IDatabaseDriver, em?: EntityManager): ISchemaGenerator;
175
175
  processDateProperty(value: unknown): string | number | Date;
176
- quoteIdentifier(id: string, quote?: string): string;
176
+ quoteIdentifier(id: string | {
177
+ toString: () => string;
178
+ }, quote?: string): string;
177
179
  quoteValue(value: any): string;
178
180
  escape(value: any): string;
179
181
  formatQuery(sql: string, params: readonly any[]): string;
@@ -1,7 +1,7 @@
1
1
  import { Type } from './Type';
2
2
  import type { Platform } from '../platforms';
3
3
  import type { EntityProperty } from '../typings';
4
- export declare class BooleanType extends Type<number | null | undefined, number | null | undefined> {
4
+ export declare class BooleanType extends Type<boolean | null | undefined, boolean | null | undefined> {
5
5
  getColumnType(prop: EntityProperty, platform: Platform): string;
6
6
  compareAsType(): string;
7
7
  ensureComparable(): boolean;
@@ -15,7 +15,7 @@ class DecimalType extends Type_1.Type {
15
15
  if ((this.mode ?? this.prop?.runtimeType) === 'number') {
16
16
  return +value;
17
17
  }
18
- return value;
18
+ return String(value);
19
19
  }
20
20
  compareValues(a, b) {
21
21
  return this.format(a) === this.format(b);
@@ -10,7 +10,7 @@ class DoubleType extends Type_1.Type {
10
10
  if (this.prop?.runtimeType === 'number') {
11
11
  return +value;
12
12
  }
13
- return value;
13
+ return String(value);
14
14
  }
15
15
  getColumnType(prop, platform) {
16
16
  return platform.getDoubleDeclarationSQL();
package/typings.d.ts CHANGED
@@ -6,7 +6,7 @@ import type { SerializationContext, SerializeOptions } from './serialization';
6
6
  import type { EntitySchema, MetadataStorage } from './metadata';
7
7
  import type { Type, types } from './types';
8
8
  import type { Platform } from './platforms';
9
- import type { Configuration } from './utils';
9
+ import type { Configuration, RawQueryFragment } from './utils';
10
10
  import type { EntityManager } from './EntityManager';
11
11
  import type { EmbeddedPrefixMode } from './decorators/Embedded';
12
12
  import type { EventSubscriber } from './events';
@@ -44,11 +44,15 @@ export declare const EagerProps: unique symbol;
44
44
  export declare const HiddenProps: unique symbol;
45
45
  export declare const Config: unique symbol;
46
46
  declare const __optional: unique symbol;
47
+ declare const __requiredNullable: unique symbol;
47
48
  declare const __hidden: unique symbol;
48
49
  declare const __config: unique symbol;
49
50
  export type Opt<T = unknown> = T & {
50
51
  [__optional]?: 1;
51
52
  };
53
+ export type RequiredNullable<T = never> = (T & {
54
+ [__requiredNullable]?: 1;
55
+ }) | null;
52
56
  export type Hidden<T = unknown> = T & {
53
57
  [__hidden]?: 1;
54
58
  };
@@ -73,6 +77,7 @@ export type Primary<T> = IsAny<T> extends true ? any : T extends {
73
77
  } ? ReadonlyPrimary<PK> : T extends {
74
78
  id?: infer PK;
75
79
  } ? ReadonlyPrimary<PK> : T;
80
+ /** @internal */
76
81
  export type PrimaryProperty<T> = T extends {
77
82
  [PrimaryKeyProp]?: infer PK;
78
83
  } ? (PK extends keyof T ? PK : (PK extends any[] ? PK[number] : never)) : T extends {
@@ -215,7 +220,9 @@ export type EntityDataProp<T, C extends boolean> = T extends Date ? string | Dat
215
220
  __runtime?: infer Runtime;
216
221
  __raw?: infer Raw;
217
222
  } ? (C extends true ? Raw : Runtime) : T extends Reference<infer U> ? EntityDataNested<U, C> : T extends ScalarReference<infer U> ? EntityDataProp<U, C> : T extends Collection<infer U, any> ? U | U[] | EntityDataNested<U, C> | EntityDataNested<U, C>[] : T extends readonly (infer U)[] ? U extends NonArrayObject ? U | U[] | EntityDataNested<U, C> | EntityDataNested<U, C>[] : U[] | EntityDataNested<U, C>[] : EntityDataNested<T, C>;
218
- export type RequiredEntityDataProp<T, O, C extends boolean> = T extends Date ? string | Date : T extends Scalar ? T : T extends {
223
+ export type RequiredEntityDataProp<T, O, C extends boolean> = T extends Date ? string | Date : Exclude<T, null> extends {
224
+ [__requiredNullable]?: 1;
225
+ } ? T | null : T extends Scalar ? T : T extends {
219
226
  __runtime?: infer Runtime;
220
227
  __raw?: infer Raw;
221
228
  } ? (C extends true ? Raw : Runtime) : T extends Reference<infer U> ? RequiredEntityDataNested<U, O, C> : T extends ScalarReference<infer U> ? RequiredEntityDataProp<U, O, C> : T extends Collection<infer U, any> ? U | U[] | RequiredEntityDataNested<U, O, C> | RequiredEntityDataNested<U, O, C>[] : T extends readonly (infer U)[] ? U extends NonArrayObject ? U | U[] | RequiredEntityDataNested<U, O, C> | RequiredEntityDataNested<U, O, C>[] : U[] | RequiredEntityDataNested<U, O, C>[] : RequiredEntityDataNested<T, O, C>;
@@ -230,7 +237,12 @@ type ExplicitlyOptionalProps<T> = (T extends {
230
237
  type NullableKeys<T, V = null> = {
231
238
  [K in keyof T]: V extends T[K] ? K : never;
232
239
  }[keyof T];
233
- type ProbablyOptionalProps<T> = PrimaryProperty<T> | ExplicitlyOptionalProps<T> | NonNullable<NullableKeys<T, null | undefined>>;
240
+ type RequiredNullableKeys<T> = {
241
+ [K in keyof T]: Exclude<T[K], null> extends {
242
+ [__requiredNullable]?: 1;
243
+ } ? K : never;
244
+ }[keyof T];
245
+ type ProbablyOptionalProps<T> = PrimaryProperty<T> | ExplicitlyOptionalProps<T> | Exclude<NonNullable<NullableKeys<T, null | undefined>>, RequiredNullableKeys<T>>;
234
246
  type IsOptional<T, K extends keyof T, I> = T[K] extends Collection<any, any> ? true : ExtractType<T[K]> extends I ? true : K extends ProbablyOptionalProps<T> ? true : false;
235
247
  type RequiredKeys<T, K extends keyof T, I> = IsOptional<T, K, I> extends false ? CleanKeys<T, K> : never;
236
248
  type OptionalKeys<T, K extends keyof T, I> = IsOptional<T, K, I> extends false ? never : CleanKeys<T, K>;
@@ -287,8 +299,14 @@ export type EntityDTO<T, C extends TypeConfig = never> = {
287
299
  } & {
288
300
  [K in keyof T as DTOOptionalKeys<T, K>]?: EntityDTOProp<T, T[K], C> | AddOptional<T[K]>;
289
301
  };
290
- type CheckKey<T> = IsUnknown<T> extends false ? keyof T : string;
291
- export type CheckCallback<T> = (columns: Record<CheckKey<T>, string>) => string;
302
+ type PropertyName<T> = IsUnknown<T> extends false ? keyof T : string;
303
+ type TableName = {
304
+ name: string;
305
+ schema?: string;
306
+ toString: () => string;
307
+ };
308
+ export type IndexCallback<T> = (table: TableName, columns: Record<PropertyName<T>, string>) => string | RawQueryFragment;
309
+ export type CheckCallback<T> = (columns: Record<PropertyName<T>, string>) => string;
292
310
  export type GeneratedColumnCallback<T> = (columns: Record<keyof T, string>) => string;
293
311
  export interface CheckConstraint<T = any> {
294
312
  name?: string;
@@ -384,6 +402,7 @@ export interface EntityProperty<Owner = any, Target = any> {
384
402
  optional?: boolean;
385
403
  ignoreSchemaChanges?: ('type' | 'extra' | 'default')[];
386
404
  deferMode?: DeferMode;
405
+ createForeignKeyConstraint: boolean;
387
406
  foreignKeyName?: string;
388
407
  }
389
408
  export declare class EntityMetadata<T = any> {
@@ -393,8 +412,9 @@ export declare class EntityMetadata<T = any> {
393
412
  constructor(meta?: Partial<EntityMetadata>);
394
413
  addProperty(prop: Partial<EntityProperty<T>>, sync?: boolean): void;
395
414
  removeProperty(name: string, sync?: boolean): void;
396
- getPrimaryProps(): EntityProperty<T>[];
415
+ getPrimaryProps(flatten?: boolean): EntityProperty<T>[];
397
416
  getPrimaryProp(): EntityProperty<T>;
417
+ createColumnMappingObject(): Dictionary<any>;
398
418
  get tableName(): string;
399
419
  set tableName(name: string);
400
420
  sync(initIndexes?: boolean): void;
@@ -446,18 +466,18 @@ export interface EntityMetadata<T = any> {
446
466
  uniqueProps: EntityProperty<T>[];
447
467
  getterProps: EntityProperty<T>[];
448
468
  indexes: {
449
- properties: EntityKey<T> | EntityKey<T>[];
469
+ properties?: EntityKey<T> | EntityKey<T>[];
450
470
  name?: string;
451
471
  type?: string;
452
472
  options?: Dictionary;
453
- expression?: string;
473
+ expression?: string | IndexCallback<T>;
454
474
  }[];
455
475
  uniques: {
456
- properties: EntityKey<T> | EntityKey<T>[];
476
+ properties?: EntityKey<T> | EntityKey<T>[];
457
477
  name?: string;
458
478
  options?: Dictionary;
459
- expression?: string;
460
- deferMode?: DeferMode;
479
+ expression?: string | IndexCallback<T>;
480
+ deferMode?: DeferMode | `${DeferMode}`;
461
481
  }[];
462
482
  checks: CheckConstraint<T>[];
463
483
  repositoryClass?: string;
@@ -689,6 +709,7 @@ export type PopulateOptions<T> = {
689
709
  strategy?: LoadStrategy;
690
710
  all?: boolean;
691
711
  filter?: boolean;
712
+ joinType?: 'inner join' | 'left join';
692
713
  children?: PopulateOptions<T[keyof T]>[];
693
714
  };
694
715
  type Loadable<T extends object> = Collection<T, any> | Reference<T> | Ref<T> | readonly T[];