@mikro-orm/core 7.0.0-dev.99 → 7.0.0-rc.1

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 (107) hide show
  1. package/EntityManager.d.ts +34 -17
  2. package/EntityManager.js +95 -103
  3. package/MikroORM.d.ts +5 -5
  4. package/MikroORM.js +25 -20
  5. package/cache/FileCacheAdapter.js +11 -3
  6. package/connections/Connection.d.ts +3 -2
  7. package/connections/Connection.js +4 -3
  8. package/drivers/DatabaseDriver.d.ts +11 -11
  9. package/drivers/DatabaseDriver.js +91 -25
  10. package/drivers/IDatabaseDriver.d.ts +50 -20
  11. package/entity/BaseEntity.d.ts +61 -1
  12. package/entity/Collection.d.ts +8 -1
  13. package/entity/Collection.js +12 -13
  14. package/entity/EntityAssigner.js +9 -9
  15. package/entity/EntityFactory.d.ts +6 -1
  16. package/entity/EntityFactory.js +40 -22
  17. package/entity/EntityHelper.d.ts +2 -2
  18. package/entity/EntityHelper.js +27 -4
  19. package/entity/EntityLoader.d.ts +5 -4
  20. package/entity/EntityLoader.js +193 -80
  21. package/entity/EntityRepository.d.ts +27 -7
  22. package/entity/EntityRepository.js +8 -2
  23. package/entity/PolymorphicRef.d.ts +12 -0
  24. package/entity/PolymorphicRef.js +18 -0
  25. package/entity/WrappedEntity.d.ts +2 -2
  26. package/entity/WrappedEntity.js +1 -1
  27. package/entity/defineEntity.d.ts +89 -50
  28. package/entity/defineEntity.js +12 -0
  29. package/entity/index.d.ts +1 -0
  30. package/entity/index.js +1 -0
  31. package/entity/utils.d.ts +6 -1
  32. package/entity/utils.js +33 -0
  33. package/entity/validators.js +2 -2
  34. package/enums.d.ts +2 -2
  35. package/enums.js +1 -0
  36. package/errors.d.ts +16 -8
  37. package/errors.js +40 -13
  38. package/hydration/ObjectHydrator.js +63 -21
  39. package/index.d.ts +1 -1
  40. package/logging/colors.d.ts +1 -1
  41. package/logging/colors.js +7 -6
  42. package/logging/inspect.js +1 -6
  43. package/metadata/EntitySchema.d.ts +43 -13
  44. package/metadata/EntitySchema.js +82 -27
  45. package/metadata/MetadataDiscovery.d.ts +60 -3
  46. package/metadata/MetadataDiscovery.js +665 -154
  47. package/metadata/MetadataProvider.js +3 -1
  48. package/metadata/MetadataStorage.d.ts +13 -6
  49. package/metadata/MetadataStorage.js +64 -19
  50. package/metadata/MetadataValidator.d.ts +32 -2
  51. package/metadata/MetadataValidator.js +196 -31
  52. package/metadata/discover-entities.js +5 -5
  53. package/metadata/types.d.ts +111 -14
  54. package/naming-strategy/AbstractNamingStrategy.d.ts +11 -3
  55. package/naming-strategy/AbstractNamingStrategy.js +12 -0
  56. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  57. package/naming-strategy/EntityCaseNamingStrategy.js +6 -5
  58. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  59. package/naming-strategy/MongoNamingStrategy.js +6 -6
  60. package/naming-strategy/NamingStrategy.d.ts +17 -3
  61. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  62. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  63. package/package.json +2 -2
  64. package/platforms/Platform.d.ts +4 -2
  65. package/platforms/Platform.js +5 -2
  66. package/serialization/EntitySerializer.d.ts +3 -0
  67. package/serialization/EntitySerializer.js +15 -13
  68. package/serialization/EntityTransformer.js +6 -6
  69. package/serialization/SerializationContext.d.ts +6 -6
  70. package/typings.d.ts +325 -110
  71. package/typings.js +84 -17
  72. package/unit-of-work/ChangeSet.d.ts +4 -3
  73. package/unit-of-work/ChangeSet.js +2 -3
  74. package/unit-of-work/ChangeSetComputer.d.ts +3 -6
  75. package/unit-of-work/ChangeSetComputer.js +34 -13
  76. package/unit-of-work/ChangeSetPersister.d.ts +12 -10
  77. package/unit-of-work/ChangeSetPersister.js +55 -25
  78. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  79. package/unit-of-work/CommitOrderCalculator.js +13 -13
  80. package/unit-of-work/IdentityMap.d.ts +12 -0
  81. package/unit-of-work/IdentityMap.js +39 -1
  82. package/unit-of-work/UnitOfWork.d.ts +21 -3
  83. package/unit-of-work/UnitOfWork.js +203 -56
  84. package/utils/AbstractSchemaGenerator.js +17 -8
  85. package/utils/AsyncContext.d.ts +6 -0
  86. package/utils/AsyncContext.js +42 -0
  87. package/utils/Configuration.d.ts +52 -11
  88. package/utils/Configuration.js +12 -8
  89. package/utils/Cursor.js +21 -8
  90. package/utils/DataloaderUtils.js +13 -11
  91. package/utils/EntityComparator.d.ts +14 -7
  92. package/utils/EntityComparator.js +132 -46
  93. package/utils/QueryHelper.d.ts +16 -6
  94. package/utils/QueryHelper.js +53 -18
  95. package/utils/RawQueryFragment.d.ts +28 -23
  96. package/utils/RawQueryFragment.js +34 -56
  97. package/utils/RequestContext.js +2 -2
  98. package/utils/TransactionContext.js +2 -2
  99. package/utils/TransactionManager.js +1 -1
  100. package/utils/Utils.d.ts +7 -26
  101. package/utils/Utils.js +25 -79
  102. package/utils/clone.js +7 -21
  103. package/utils/env-vars.d.ts +4 -0
  104. package/utils/env-vars.js +13 -3
  105. package/utils/fs-utils.d.ts +21 -0
  106. package/utils/fs-utils.js +106 -11
  107. package/utils/upsert-utils.d.ts +4 -4
@@ -1,13 +1,14 @@
1
1
  import type { EntityManager } from '../EntityManager.js';
2
2
  import type { ColumnType, PropertyOptions, ReferenceOptions, EnumOptions, EmbeddedOptions, ManyToOneOptions, OneToManyOptions, OneToOneOptions, ManyToManyOptions } from '../metadata/types.js';
3
- import type { AnyString, GeneratedColumnCallback, Constructor, CheckCallback, FilterQuery, EntityName, Dictionary, EntityMetadata, PrimaryKeyProp, Hidden, Opt, Primary, EntityClass, EntitySchemaWithMeta, InferEntity, MaybeReturnType, Ref, IndexCallback } from '../typings.js';
3
+ import type { AnyString, GeneratedColumnCallback, Constructor, CheckCallback, FilterQuery, EntityName, Dictionary, EntityMetadata, PrimaryKeyProp, EntityRepositoryType, Hidden, Opt, Primary, EntityClass, EntitySchemaWithMeta, InferEntity, MaybeReturnType, Ref, IndexCallback, FormulaCallback, EntityCtor, IsNever } from '../typings.js';
4
+ import type { Raw } from '../utils/RawQueryFragment.js';
4
5
  import type { ScalarReference } from './Reference.js';
5
6
  import type { SerializeOptions } from '../serialization/EntitySerializer.js';
6
- import type { Cascade, DeferMode, EmbeddedPrefixMode, EventType, LoadStrategy, QueryOrderMap } from '../enums.js';
7
+ import type { Cascade, DeferMode, EmbeddedPrefixMode, LoadStrategy, QueryOrderKeysFlat, QueryOrderMap } from '../enums.js';
8
+ import type { EventSubscriber } from '../events/EventSubscriber.js';
7
9
  import type { IType, Type } from '../types/Type.js';
8
10
  import { types } from '../types/index.js';
9
11
  import type { Collection } from './Collection.js';
10
- import type { EventSubscriber } from '../events/EventSubscriber.js';
11
12
  import type { FilterOptions } from '../drivers/IDatabaseDriver.js';
12
13
  export type UniversalPropertyKeys = keyof PropertyOptions<any> | keyof EnumOptions<any> | keyof EmbeddedOptions<any, any> | keyof ReferenceOptions<any, any> | keyof ManyToOneOptions<any, any> | keyof OneToManyOptions<any, any> | keyof OneToOneOptions<any, any> | keyof ManyToManyOptions<any, any>;
13
14
  type BuilderExtraKeys = '~options' | '~type' | '$type';
@@ -120,7 +121,7 @@ export declare class UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys
120
121
  * Specify default column value for {@link https://mikro-orm.io/docs/schema-generator Schema Generator}.
121
122
  * This is a runtime value, assignable to the entity property. (SQL only)
122
123
  */
123
- default<T extends string | string[] | number | number[] | boolean | null>(defaultValue: T): Pick<UniversalPropertyOptionsBuilder<Value, Omit<Options, 'default'> & {
124
+ default<T extends string | string[] | number | number[] | boolean | null | Date | Raw>(defaultValue: T): Pick<UniversalPropertyOptionsBuilder<Value, Omit<Options, 'default'> & {
124
125
  default: T;
125
126
  }, IncludeKeys>, IncludeKeys>;
126
127
  /**
@@ -139,7 +140,7 @@ export declare class UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys
139
140
  *
140
141
  * @see https://mikro-orm.io/docs/defining-entities#formulas Formulas
141
142
  */
142
- formula<T extends string | ((alias: string) => string)>(formula: T): Pick<UniversalPropertyOptionsBuilder<Value, Omit<Options, 'formula'> & {
143
+ formula<T extends string | FormulaCallback<any>>(formula: T): Pick<UniversalPropertyOptionsBuilder<Value, Omit<Options, 'formula'> & {
143
144
  formula: T;
144
145
  }, IncludeKeys>, IncludeKeys>;
145
146
  /**
@@ -311,6 +312,10 @@ export declare class UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys
311
312
  owner<T extends boolean = true>(owner?: T): Pick<UniversalPropertyOptionsBuilder<Value, Omit<Options, 'owner'> & {
312
313
  owner: T;
313
314
  }, IncludeKeys>, IncludeKeys>;
315
+ /** For polymorphic relations. Specifies the property name that stores the entity type discriminator. Defaults to the property name. */
316
+ discriminator(discriminator: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
317
+ /** For polymorphic relations. Custom mapping of discriminator values to entity class names. */
318
+ discriminatorMap(discriminatorMap: Dictionary<string>): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
314
319
  /** Point to the inverse side property name. */
315
320
  inversedBy(inversedBy: keyof Value | ((e: Value) => any)): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
316
321
  /** Point to the owning side property name. */
@@ -326,7 +331,7 @@ export declare class UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys
326
331
  /** Override default name for pivot table (see {@doclink naming-strategy | Naming Strategy}). */
327
332
  pivotTable(pivotTable: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
328
333
  /** Set pivot entity for this relation (see {@doclink collections#custom-pivot-table-entity | Custom pivot table entity}). */
329
- pivotEntity(pivotEntity: string | (() => EntityName<any>)): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
334
+ pivotEntity(pivotEntity: () => EntityName): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
330
335
  /** 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. */
331
336
  joinColumn(joinColumn: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
332
337
  /** 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. */
@@ -339,6 +344,8 @@ export declare class UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys
339
344
  referenceColumnName(referenceColumnName: string): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
340
345
  /** 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. */
341
346
  referencedColumnNames(...referencedColumnNames: string[]): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
347
+ /** Specify the property name on the target entity that this FK references instead of the primary key. */
348
+ targetKey(targetKey: keyof Value): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
342
349
  /** What to do when the target entity gets deleted. */
343
350
  deleteRule(deleteRule: 'cascade' | 'no action' | 'set null' | 'set default' | AnyString): Pick<UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys>, IncludeKeys>;
344
351
  /** What to do when the reference to the target entity gets updated. */
@@ -366,33 +373,36 @@ export declare class OneToManyOptionsBuilderOnlyMappedBy<Value extends object> e
366
373
  kind: '1:m';
367
374
  }, IncludeKeysForOneToManyOptions> {
368
375
  /** Point to the owning side property name. */
369
- mappedBy(mappedBy: (AnyString & keyof Value) | ((e: Value) => any)): Pick<UniversalPropertyOptionsBuilder<Value, EmptyOptions & {
376
+ mappedBy(mappedBy: (keyof Value) | ((e: Value) => any)): Pick<UniversalPropertyOptionsBuilder<Value, EmptyOptions & {
370
377
  kind: '1:m';
371
378
  }, IncludeKeysForOneToManyOptions>, IncludeKeysForOneToManyOptions>;
372
379
  }
380
+ type EntityTarget = {
381
+ '~entity': any;
382
+ } | EntityClass;
373
383
  declare const propertyBuilders: {
374
384
  bigint: <Mode extends "bigint" | "number" | "string" = "bigint">(mode?: Mode) => UniversalPropertyOptionsBuilder<(Mode extends "bigint" ? bigint : Mode extends "number" ? number : string) & {}, EmptyOptions, IncludeKeysForProperty>;
375
385
  array: <T = string>(toJsValue?: (i: string) => T, toDbValue?: (i: T) => string) => UniversalPropertyOptionsBuilder<T[], EmptyOptions, IncludeKeysForProperty>;
376
386
  decimal: <Mode extends "number" | "string" = "string">(mode?: Mode) => UniversalPropertyOptionsBuilder<NonNullable<Mode extends "number" ? number : string>, EmptyOptions, IncludeKeysForProperty>;
377
387
  json: <T>() => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>;
378
- formula: <T>(formula: string | ((alias: string) => string)) => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>;
388
+ formula: <T>(formula: string | FormulaCallback<any>) => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>;
379
389
  datetime: (length?: number) => UniversalPropertyOptionsBuilder<Date, EmptyOptions, IncludeKeysForProperty>;
380
390
  time: (length?: number) => UniversalPropertyOptionsBuilder<any, EmptyOptions, IncludeKeysForProperty>;
381
391
  type: <T extends PropertyValueType>(type: T) => UniversalPropertyOptionsBuilder<InferPropertyValueType<T>, EmptyOptions, IncludeKeysForProperty>;
382
392
  enum: <const T extends (number | string)[] | (() => Dictionary)>(items?: T) => UniversalPropertyOptionsBuilder<T extends () => Dictionary ? ValueOf<ReturnType<T>> : T extends (infer Value)[] ? Value : T, EmptyOptions, IncludeKeysForEnumOptions>;
383
- embedded: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any> | EntitySchemaWithMeta<any, any, any, any, any>[] | EntityClass<any>[]>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target extends (infer T)[] ? T : Target>, EmptyOptions, IncludeKeysForEmbeddedOptions>;
384
- manyToMany: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any>>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target>, EmptyOptions & {
393
+ embedded: <Target extends EntityTarget | EntityTarget[]>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target extends (infer T)[] ? T : Target>, EmptyOptions, IncludeKeysForEmbeddedOptions>;
394
+ manyToMany: <Target extends EntityTarget>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target>, EmptyOptions & {
385
395
  kind: "m:n";
386
396
  }, IncludeKeysForManyToManyOptions>;
387
- manyToOne: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any>>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target>, EmptyOptions & {
397
+ manyToOne: <Target extends EntityTarget | EntityTarget[]>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target extends (infer T)[] ? T : Target>, EmptyOptions & {
388
398
  kind: "m:1";
389
399
  }, IncludeKeysForManyToOneOptions>;
390
- oneToMany: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any>>(target: Target) => OneToManyOptionsBuilderOnlyMappedBy<InferEntity<Target>>;
391
- oneToOne: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any>>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target>, EmptyOptions & {
400
+ oneToMany: <Target extends EntityTarget>(target: Target) => OneToManyOptionsBuilderOnlyMappedBy<InferEntity<Target>>;
401
+ oneToOne: <Target extends EntityTarget | EntityTarget[]>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target extends (infer T)[] ? T : Target>, EmptyOptions & {
392
402
  kind: "1:1";
393
403
  }, IncludeKeysForOneToOneOptions>;
394
404
  date: () => UniversalPropertyOptionsBuilder<string, EmptyOptions, IncludeKeysForProperty>;
395
- blob: () => UniversalPropertyOptionsBuilder<NonNullable<Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike> | null>, EmptyOptions, IncludeKeysForProperty>;
405
+ blob: () => UniversalPropertyOptionsBuilder<NonNullable<Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | null>, EmptyOptions, IncludeKeysForProperty>;
396
406
  uint8array: () => UniversalPropertyOptionsBuilder<Uint8Array<ArrayBufferLike>, EmptyOptions, IncludeKeysForProperty>;
397
407
  enumArray: () => UniversalPropertyOptionsBuilder<(string | number)[], EmptyOptions, IncludeKeysForProperty>;
398
408
  integer: () => UniversalPropertyOptionsBuilder<number, EmptyOptions, IncludeKeysForProperty>;
@@ -409,64 +419,76 @@ declare const propertyBuilders: {
409
419
  interval: () => UniversalPropertyOptionsBuilder<string, EmptyOptions, IncludeKeysForProperty>;
410
420
  unknown: () => UniversalPropertyOptionsBuilder<{}, EmptyOptions, IncludeKeysForProperty>;
411
421
  };
412
- export interface EntityMetadataWithProperties<TName extends string, TTableName extends string, TProperties extends Record<string, any>, TPK extends (keyof TProperties)[] | undefined = undefined, TBase = never> extends Omit<Partial<EntityMetadata<InferEntityFromProperties<TProperties, TPK>>>, 'properties' | 'extends' | 'primaryKeys' | 'hooks' | 'discriminatorColumn' | 'versionProperty' | 'concurrencyCheckKeys' | 'serializedPrimaryKey' | 'indexes' | 'uniques'> {
422
+ /** Own keys + base entity keys (when TBase is not `never`). Guards against `keyof never = string | number | symbol`. */
423
+ type AllKeys<TProperties, TBase> = keyof TProperties | (IsNever<TBase> extends true ? never : keyof TBase);
424
+ export interface EntityMetadataWithProperties<TName extends string, TTableName extends string, TProperties extends Record<string, any>, TPK extends (keyof TProperties)[] | undefined = undefined, TBase = never, TRepository = never> extends Omit<Partial<EntityMetadata<InferEntityFromProperties<TProperties, TPK, TBase, TRepository>>>, 'properties' | 'extends' | 'primaryKeys' | 'hooks' | 'discriminatorColumn' | 'versionProperty' | 'concurrencyCheckKeys' | 'serializedPrimaryKey' | 'indexes' | 'uniques' | 'repository' | 'orderBy'> {
413
425
  name: TName;
414
426
  tableName?: TTableName;
415
- extends?: EntityName<TBase>;
427
+ extends?: {
428
+ '~entity': TBase;
429
+ } | EntityCtor<TBase>;
416
430
  properties: TProperties | ((properties: typeof propertyBuilders) => TProperties);
417
431
  primaryKeys?: TPK & InferPrimaryKey<TProperties>[];
418
- hooks?: DefineEntityHooks<InferEntityFromProperties<TProperties, TPK>>;
419
- discriminatorColumn?: keyof TProperties;
420
- versionProperty?: keyof TProperties;
421
- concurrencyCheckKeys?: Set<keyof TProperties>;
422
- serializedPrimaryKey?: keyof TProperties;
432
+ hooks?: DefineEntityHooks;
433
+ repository?: () => TRepository;
434
+ inheritance?: 'tpt';
435
+ orderBy?: {
436
+ [K in Extract<AllKeys<TProperties, TBase>, string>]?: QueryOrderKeysFlat;
437
+ } | {
438
+ [K in Extract<AllKeys<TProperties, TBase>, string>]?: QueryOrderKeysFlat;
439
+ }[];
440
+ discriminatorColumn?: string;
441
+ versionProperty?: AllKeys<TProperties, TBase>;
442
+ concurrencyCheckKeys?: Set<AllKeys<TProperties, TBase>>;
443
+ serializedPrimaryKey?: AllKeys<TProperties, TBase>;
423
444
  indexes?: {
424
445
  properties?: keyof TProperties | (keyof TProperties)[];
425
446
  name?: string;
426
447
  type?: string;
427
448
  options?: Dictionary;
428
- expression?: string | IndexCallback<InferEntityFromProperties<TProperties, TPK>>;
449
+ expression?: string | IndexCallback<InferEntityFromProperties<TProperties, TPK, TBase>>;
429
450
  }[];
430
451
  uniques?: {
431
452
  properties?: keyof TProperties | (keyof TProperties)[];
432
453
  name?: string;
433
454
  options?: Dictionary;
434
- expression?: string | IndexCallback<InferEntityFromProperties<TProperties, TPK>>;
455
+ expression?: string | IndexCallback<InferEntityFromProperties<TProperties, TPK, TBase>>;
435
456
  deferMode?: DeferMode | `${DeferMode}`;
436
457
  }[];
437
458
  }
438
- export declare function defineEntity<const TName extends string, const TTableName extends string, const TProperties extends Record<string, any>, const TPK extends (keyof TProperties)[] | undefined = undefined, const TBase = never>(meta: EntityMetadataWithProperties<TName, TTableName, TProperties, TPK, TBase>): EntitySchemaWithMeta<TName, TTableName, InferEntityFromProperties<TProperties, TPK>, TBase, TProperties>;
439
- export declare function defineEntity<const TEntity = any, const TProperties extends Record<string, any> = Record<string, any>, const TClassName extends string = string, const TTableName extends string = string, const TBase = never>(meta: Omit<Partial<EntityMetadata<TEntity>>, 'properties' | 'extends' | 'className' | 'tableName'> & {
440
- class: EntityClass<TEntity>;
459
+ export declare function defineEntity<const TName extends string, const TTableName extends string, const TProperties extends Record<string, any>, const TPK extends (keyof TProperties)[] | undefined = undefined, const TBase = never, const TRepository = never>(meta: EntityMetadataWithProperties<TName, TTableName, TProperties, TPK, TBase, TRepository>): EntitySchemaWithMeta<TName, TTableName, InferEntityFromProperties<TProperties, TPK, TBase, TRepository>, TBase, TProperties>;
460
+ export declare function defineEntity<const TEntity = any, const TProperties extends Record<string, any> = Record<string, any>, const TClassName extends string = string, const TTableName extends string = string, const TBase = never, const TClass extends EntityCtor = EntityCtor<TEntity>>(meta: Omit<Partial<EntityMetadata<TEntity>>, 'properties' | 'extends' | 'className' | 'tableName' | 'hooks'> & {
461
+ class: TClass;
441
462
  className?: TClassName;
442
463
  tableName?: TTableName;
443
- extends?: EntityName<TBase>;
464
+ extends?: TBase;
444
465
  properties: TProperties | ((properties: typeof propertyBuilders) => TProperties);
445
- }): EntitySchemaWithMeta<TClassName, TTableName, TEntity, TBase, TProperties>;
466
+ hooks?: DefineEntityHooks<TEntity>;
467
+ }): EntitySchemaWithMeta<TClassName, TTableName, TEntity, TBase, TProperties, TClass>;
446
468
  export declare namespace defineEntity {
447
469
  var properties: {
448
470
  bigint: <Mode extends "bigint" | "number" | "string" = "bigint">(mode?: Mode) => UniversalPropertyOptionsBuilder<(Mode extends "bigint" ? bigint : Mode extends "number" ? number : string) & {}, EmptyOptions, IncludeKeysForProperty>;
449
471
  array: <T = string>(toJsValue?: (i: string) => T, toDbValue?: (i: T) => string) => UniversalPropertyOptionsBuilder<T[], EmptyOptions, IncludeKeysForProperty>;
450
472
  decimal: <Mode extends "number" | "string" = "string">(mode?: Mode) => UniversalPropertyOptionsBuilder<NonNullable<Mode extends "number" ? number : string>, EmptyOptions, IncludeKeysForProperty>;
451
473
  json: <T>() => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>;
452
- formula: <T>(formula: string | ((alias: string) => string)) => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>;
474
+ formula: <T>(formula: string | FormulaCallback<any>) => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>;
453
475
  datetime: (length?: number) => UniversalPropertyOptionsBuilder<Date, EmptyOptions, IncludeKeysForProperty>;
454
476
  time: (length?: number) => UniversalPropertyOptionsBuilder<any, EmptyOptions, IncludeKeysForProperty>;
455
477
  type: <T extends PropertyValueType>(type: T) => UniversalPropertyOptionsBuilder<InferPropertyValueType<T>, EmptyOptions, IncludeKeysForProperty>;
456
478
  enum: <const T extends (number | string)[] | (() => Dictionary)>(items?: T) => UniversalPropertyOptionsBuilder<T extends () => Dictionary ? ValueOf<ReturnType<T>> : T extends (infer Value)[] ? Value : T, EmptyOptions, IncludeKeysForEnumOptions>;
457
- embedded: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any> | EntitySchemaWithMeta<any, any, any, any, any>[] | EntityClass<any>[]>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target extends (infer T)[] ? T : Target>, EmptyOptions, IncludeKeysForEmbeddedOptions>;
458
- manyToMany: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any>>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target>, EmptyOptions & {
479
+ embedded: <Target extends EntityTarget | EntityTarget[]>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target extends (infer T)[] ? T : Target>, EmptyOptions, IncludeKeysForEmbeddedOptions>;
480
+ manyToMany: <Target extends EntityTarget>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target>, EmptyOptions & {
459
481
  kind: "m:n";
460
482
  }, IncludeKeysForManyToManyOptions>;
461
- manyToOne: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any>>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target>, EmptyOptions & {
483
+ manyToOne: <Target extends EntityTarget | EntityTarget[]>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target extends (infer T)[] ? T : Target>, EmptyOptions & {
462
484
  kind: "m:1";
463
485
  }, IncludeKeysForManyToOneOptions>;
464
- oneToMany: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any>>(target: Target) => OneToManyOptionsBuilderOnlyMappedBy<InferEntity<Target>>;
465
- oneToOne: <Target extends EntitySchemaWithMeta<any, any, any, any, any> | EntityClass<any>>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target>, EmptyOptions & {
486
+ oneToMany: <Target extends EntityTarget>(target: Target) => OneToManyOptionsBuilderOnlyMappedBy<InferEntity<Target>>;
487
+ oneToOne: <Target extends EntityTarget | EntityTarget[]>(target: Target) => UniversalPropertyOptionsBuilder<InferEntity<Target extends (infer T)[] ? T : Target>, EmptyOptions & {
466
488
  kind: "1:1";
467
489
  }, IncludeKeysForOneToOneOptions>;
468
490
  date: () => UniversalPropertyOptionsBuilder<string, EmptyOptions, IncludeKeysForProperty>;
469
- blob: () => UniversalPropertyOptionsBuilder<NonNullable<Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike> | null>, EmptyOptions, IncludeKeysForProperty>;
491
+ blob: () => UniversalPropertyOptionsBuilder<NonNullable<Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | null>, EmptyOptions, IncludeKeysForProperty>;
470
492
  uint8array: () => UniversalPropertyOptionsBuilder<Uint8Array<ArrayBufferLike>, EmptyOptions, IncludeKeysForProperty>;
471
493
  enumArray: () => UniversalPropertyOptionsBuilder<(string | number)[], EmptyOptions, IncludeKeysForProperty>;
472
494
  integer: () => UniversalPropertyOptionsBuilder<number, EmptyOptions, IncludeKeysForProperty>;
@@ -485,21 +507,38 @@ export declare namespace defineEntity {
485
507
  };
486
508
  }
487
509
  export { propertyBuilders as p };
488
- export interface DefineEntityHooks<T> extends Partial<MapToArray<Pick<EventSubscriber<T>, keyof typeof EventType>>> {
510
+ type EntityHookValue<T, K extends keyof EventSubscriber<T>> = (keyof T | NonNullable<EventSubscriber<T>[K]>)[];
511
+ export interface DefineEntityHooks<T = any> {
512
+ onInit?: EntityHookValue<T, 'onInit'>;
513
+ onLoad?: EntityHookValue<T, 'onLoad'>;
514
+ beforeCreate?: EntityHookValue<T, 'beforeCreate'>;
515
+ afterCreate?: EntityHookValue<T, 'afterCreate'>;
516
+ beforeUpdate?: EntityHookValue<T, 'beforeUpdate'>;
517
+ afterUpdate?: EntityHookValue<T, 'afterUpdate'>;
518
+ beforeUpsert?: EntityHookValue<T, 'beforeUpsert'>;
519
+ afterUpsert?: EntityHookValue<T, 'afterUpsert'>;
520
+ beforeDelete?: EntityHookValue<T, 'beforeDelete'>;
521
+ afterDelete?: EntityHookValue<T, 'afterDelete'>;
489
522
  }
490
- type MapToArray<T extends Record<string, any>> = {
491
- [K in keyof T]: NonNullable<T[K]>[];
492
- };
493
523
  type PropertyValueType = PropertyOptions<any>['type'];
494
524
  type InferPropertyValueType<T extends PropertyValueType> = T extends string ? InferTypeByString<T> : T extends NumberConstructor ? number : T extends StringConstructor ? string : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends ArrayConstructor ? string[] : T extends Constructor<infer TType> ? TType extends Type<infer TValue, any> ? NonNullable<TValue> : TType : T extends Type<infer TValue, any> ? NonNullable<TValue> : any;
495
525
  type InferTypeByString<T extends string> = T extends keyof typeof types ? InferJSType<typeof types[T]> : InferColumnType<T>;
496
526
  type InferJSType<T> = T extends typeof Type<infer TValue, any> ? NonNullable<TValue> : never;
497
527
  type InferColumnType<T extends string> = T extends 'int' | 'int4' | 'integer' | 'bigint' | 'int8' | 'int2' | 'tinyint' | 'smallint' | 'mediumint' ? number : T extends 'double' | 'double precision' | 'real' | 'float8' | 'decimal' | 'numeric' | 'float' | 'float4' ? number : T extends 'datetime' | 'time' | 'time with time zone' | 'timestamp' | 'timestamp with time zone' | 'timetz' | 'timestamptz' | 'date' | 'interval' ? Date : T extends 'ObjectId' | 'objectId' | 'character varying' | 'varchar' | 'char' | 'character' | 'uuid' | 'text' | 'tinytext' | 'mediumtext' | 'longtext' | 'enum' ? string : T extends 'boolean' | 'bool' | 'bit' ? boolean : T extends 'blob' | 'tinyblob' | 'mediumblob' | 'longblob' | 'bytea' ? Buffer : T extends 'point' | 'line' | 'lseg' | 'box' | 'circle' | 'path' | 'polygon' | 'geometry' ? number[] : T extends 'tsvector' | 'tsquery' ? string[] : T extends 'json' | 'jsonb' ? any : any;
498
- export type InferEntityFromProperties<Properties extends Record<string, any>, PK extends (keyof Properties)[] | undefined = undefined> = {
528
+ export type InferEntityFromProperties<Properties extends Record<string, any>, PK extends (keyof Properties)[] | undefined = undefined, Base = never, Repository = never> = {
499
529
  -readonly [K in keyof Properties]: InferBuilderValue<MaybeReturnType<Properties[K]>>;
500
530
  } & {
501
- [PrimaryKeyProp]?: PK extends undefined ? InferPrimaryKey<Properties> extends never ? never : IsUnion<InferPrimaryKey<Properties>> extends true ? InferPrimaryKey<Properties>[] : InferPrimaryKey<Properties> : PK;
502
- };
531
+ [PrimaryKeyProp]?: InferCombinedPrimaryKey<Properties, PK, Base>;
532
+ } & (IsNever<Repository> extends true ? {} : {
533
+ [EntityRepositoryType]?: Repository extends Constructor<infer R> ? R : Repository;
534
+ }) & (IsNever<Base> extends true ? {} : Omit<Base, typeof PrimaryKeyProp>);
535
+ type InferCombinedPrimaryKey<Properties extends Record<string, any>, PK, Base> = PK extends undefined ? CombinePrimaryKeys<InferPrimaryKey<Properties>, ExtractBasePrimaryKey<Base>> : PK;
536
+ type ExtractBasePrimaryKey<Base> = Base extends {
537
+ [PrimaryKeyProp]?: infer BasePK;
538
+ } ? BasePK : never;
539
+ type CombinePrimaryKeys<ChildPK, BasePK> = [
540
+ ChildPK
541
+ ] extends [never] ? BasePK : [BasePK] extends [never] ? IsUnion<ChildPK> extends true ? ChildPK[] : ChildPK : ChildPK | BasePK;
503
542
  export type InferPrimaryKey<Properties extends Record<string, any>> = {
504
543
  [K in keyof Properties]: MaybeReturnType<Properties[K]> extends {
505
544
  '~options': {
@@ -548,18 +587,18 @@ type MaybeOpt<Value, Options> = Options extends {
548
587
  mapToPk: true;
549
588
  } ? Value extends Opt<infer OriginalValue> ? OriginalValue : Value : Options extends {
550
589
  autoincrement: true;
551
- } ? Opt<Value> : Options extends {
590
+ } | {
552
591
  onCreate: Function;
553
- } ? Opt<Value> : Options extends {
554
- default: string | string[] | number | number[] | boolean | null;
555
- } ? Opt<Value> : Options extends {
592
+ } | {
593
+ default: string | string[] | number | number[] | boolean | null | Date | Raw;
594
+ } | {
556
595
  defaultRaw: string;
557
- } ? Opt<Value> : Options extends {
596
+ } | {
558
597
  persist: false;
559
- } ? Opt<Value> : Options extends {
598
+ } | {
560
599
  version: true;
561
- } ? Opt<Value> : Options extends {
562
- formula: string | (() => string);
600
+ } | {
601
+ formula: string | ((...args: any[]) => any);
563
602
  } ? Opt<Value> : Value;
564
603
  type MaybeHidden<Value, Options> = Options extends {
565
604
  hidden: true;
@@ -353,6 +353,14 @@ export class UniversalPropertyOptionsBuilder {
353
353
  owner(owner = true) {
354
354
  return this.assignOptions({ owner });
355
355
  }
356
+ /** For polymorphic relations. Specifies the property name that stores the entity type discriminator. Defaults to the property name. */
357
+ discriminator(discriminator) {
358
+ return this.assignOptions({ discriminator });
359
+ }
360
+ /** For polymorphic relations. Custom mapping of discriminator values to entity class names. */
361
+ discriminatorMap(discriminatorMap) {
362
+ return this.assignOptions({ discriminatorMap });
363
+ }
356
364
  /** Point to the inverse side property name. */
357
365
  inversedBy(inversedBy) {
358
366
  return this.assignOptions({ inversedBy });
@@ -409,6 +417,10 @@ export class UniversalPropertyOptionsBuilder {
409
417
  referencedColumnNames(...referencedColumnNames) {
410
418
  return this.assignOptions({ referencedColumnNames });
411
419
  }
420
+ /** Specify the property name on the target entity that this FK references instead of the primary key. */
421
+ targetKey(targetKey) {
422
+ return this.assignOptions({ targetKey });
423
+ }
412
424
  /** What to do when the target entity gets deleted. */
413
425
  deleteRule(deleteRule) {
414
426
  return this.assignOptions({ deleteRule });
package/entity/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './EntityRepository.js';
2
2
  export * from './EntityIdentifier.js';
3
+ export * from './PolymorphicRef.js';
3
4
  export * from './EntityAssigner.js';
4
5
  export * from './EntityHelper.js';
5
6
  export * from './EntityFactory.js';
package/entity/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './EntityRepository.js';
2
2
  export * from './EntityIdentifier.js';
3
+ export * from './PolymorphicRef.js';
3
4
  export * from './EntityAssigner.js';
4
5
  export * from './EntityHelper.js';
5
6
  export * from './EntityFactory.js';
package/entity/utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { EntityMetadata, PopulateOptions } from '../typings.js';
1
+ import type { EntityMetadata, PopulateHintOptions, PopulateOptions } from '../typings.js';
2
2
  import { LoadStrategy, ReferenceKind } from '../enums.js';
3
3
  /**
4
4
  * @internal
@@ -10,3 +10,8 @@ export declare function expandDotPaths<Entity>(meta: EntityMetadata<Entity>, pop
10
10
  * @internal
11
11
  */
12
12
  export declare function getLoadingStrategy(strategy: LoadStrategy | `${LoadStrategy}`, kind: ReferenceKind): LoadStrategy.SELECT_IN | LoadStrategy.JOINED;
13
+ /**
14
+ * Applies per-relation overrides from `populateHints` to the normalized populate tree.
15
+ * @internal
16
+ */
17
+ export declare function applyPopulateHints<Entity>(populate: PopulateOptions<Entity>[], hints: Record<string, PopulateHintOptions>): void;
package/entity/utils.js CHANGED
@@ -67,3 +67,36 @@ export function getLoadingStrategy(strategy, kind) {
67
67
  }
68
68
  return strategy;
69
69
  }
70
+ /**
71
+ * Applies per-relation overrides from `populateHints` to the normalized populate tree.
72
+ * @internal
73
+ */
74
+ export function applyPopulateHints(populate, hints) {
75
+ for (const [path, hint] of Object.entries(hints)) {
76
+ const entry = findPopulateEntry(populate, path.split('.'));
77
+ if (!entry) {
78
+ continue;
79
+ }
80
+ if (hint.strategy != null) {
81
+ entry.strategy = hint.strategy;
82
+ }
83
+ if (hint.joinType != null) {
84
+ entry.joinType = hint.joinType;
85
+ }
86
+ }
87
+ }
88
+ function findPopulateEntry(populate, parts) {
89
+ let current = populate;
90
+ for (let i = 0; i < parts.length; i++) {
91
+ const entry = current.find(p => p.field.split(':')[0] === parts[i]);
92
+ if (!entry) {
93
+ return undefined;
94
+ }
95
+ if (i === parts.length - 1) {
96
+ return entry;
97
+ }
98
+ current = (entry.children ?? []);
99
+ }
100
+ /* v8 ignore next */
101
+ return undefined;
102
+ }
@@ -1,6 +1,6 @@
1
1
  import { Utils } from '../utils/Utils.js';
2
2
  import { ValidationError } from '../errors.js';
3
- import { isRaw } from '../utils/RawQueryFragment.js';
3
+ import { isRaw, Raw } from '../utils/RawQueryFragment.js';
4
4
  import { SCALAR_TYPES } from '../enums.js';
5
5
  /** @internal */
6
6
  export function validateProperty(prop, givenValue, entity) {
@@ -59,7 +59,7 @@ export function validatePrimaryKey(entity, meta) {
59
59
  }
60
60
  /** @internal */
61
61
  export function validateEmptyWhere(where) {
62
- if (Utils.isEmpty(where)) {
62
+ if (Utils.isEmpty(where) && !Raw.hasObjectFragments(where)) {
63
63
  throw new Error(`You cannot call 'EntityManager.findOne()' with empty 'where' parameter`);
64
64
  }
65
65
  }
package/enums.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Dictionary, EntityKey, ExpandProperty } from './typings.js';
1
+ import type { EntityKey, ExpandProperty } from './typings.js';
2
2
  import type { Transaction } from './connections/Connection.js';
3
3
  import type { LogContext } from './logging/Logger.js';
4
4
  export declare enum FlushMode {
@@ -42,6 +42,7 @@ export declare enum QueryOperator {
42
42
  $none = "none",// collection operators, sql only
43
43
  $some = "some",// collection operators, sql only
44
44
  $every = "every",// collection operators, sql only
45
+ $size = "size",// collection operators, sql only
45
46
  $hasKey = "?",// postgres only, json
46
47
  $hasKeys = "?&",// postgres only, json
47
48
  $hasSomeKeys = "?|"
@@ -71,7 +72,6 @@ export type QueryOrderKeys<T> = QueryOrderKeysFlat | QueryOrderMap<T>;
71
72
  export type QueryOrderMap<T> = {
72
73
  [K in EntityKey<T>]?: QueryOrderKeys<ExpandProperty<T[K]>>;
73
74
  };
74
- export type QBQueryOrderMap<T> = QueryOrderMap<T> | Dictionary;
75
75
  export interface FlatQueryOrderMap {
76
76
  [x: string]: QueryOrderKeysFlat;
77
77
  }
package/enums.js CHANGED
@@ -44,6 +44,7 @@ export var QueryOperator;
44
44
  QueryOperator["$none"] = "none";
45
45
  QueryOperator["$some"] = "some";
46
46
  QueryOperator["$every"] = "every";
47
+ QueryOperator["$size"] = "size";
47
48
  QueryOperator["$hasKey"] = "?";
48
49
  QueryOperator["$hasKeys"] = "?&";
49
50
  QueryOperator["$hasSomeKeys"] = "?|";
package/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AnyEntity, Constructor, Dictionary, EntityMetadata, EntityProperty, IPrimaryKey } from './typings.js';
1
+ import type { AnyEntity, Constructor, Dictionary, EntityMetadata, EntityName, EntityProperty, IPrimaryKey } from './typings.js';
2
2
  export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Error {
3
3
  readonly entity?: T | undefined;
4
4
  constructor(message: string, entity?: T | undefined);
@@ -13,7 +13,7 @@ export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Er
13
13
  static entityNotManaged(entity: AnyEntity): ValidationError;
14
14
  static notEntity(owner: AnyEntity, prop: EntityProperty, data: any): ValidationError;
15
15
  static notDiscoveredEntity(data: any, meta?: EntityMetadata, action?: string): ValidationError;
16
- static invalidPropertyName(entityName: string, invalid: string): ValidationError;
16
+ static invalidPropertyName(entityName: EntityName, invalid: string): ValidationError;
17
17
  static invalidCollectionValues(entityName: string, propName: string, invalid: unknown): ValidationError;
18
18
  static invalidEnumArrayItems(entityName: string, invalid: unknown): ValidationError;
19
19
  static invalidType(type: Constructor<any>, value: any, mode: string): ValidationError;
@@ -24,9 +24,9 @@ export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Er
24
24
  static invalidCompositeIdentifier(meta: EntityMetadata): ValidationError;
25
25
  static cannotCommit(): ValidationError;
26
26
  static cannotUseGlobalContext(): ValidationError;
27
- static cannotUseOperatorsInsideEmbeddables(className: string, propName: string, payload: unknown): ValidationError;
28
- static cannotUseGroupOperatorsInsideScalars(className: string, propName: string, payload: unknown): ValidationError;
29
- static invalidEmbeddableQuery(className: string, propName: string, embeddableType: string): ValidationError;
27
+ static cannotUseOperatorsInsideEmbeddables(entityName: EntityName, propName: string, payload: unknown): ValidationError;
28
+ static cannotUseGroupOperatorsInsideScalars(entityName: EntityName, propName: string, payload: unknown): ValidationError;
29
+ static invalidEmbeddableQuery(entityName: EntityName, propName: string, embeddableType: string): ValidationError;
30
30
  static invalidQueryCondition(cond: unknown): ValidationError;
31
31
  }
32
32
  export declare class CursorError<T extends AnyEntity = AnyEntity> extends ValidationError<T> {
@@ -49,11 +49,11 @@ export declare class MetadataError<T extends AnyEntity = AnyEntity> extends Vali
49
49
  static unknownIndexProperty(meta: EntityMetadata, prop: string, type: string): MetadataError;
50
50
  static multipleVersionFields(meta: EntityMetadata, fields: string[]): MetadataError;
51
51
  static invalidVersionFieldType(meta: EntityMetadata): MetadataError;
52
- static fromUnknownEntity(className: string, source: string): MetadataError;
52
+ static fromUnknownEntity(entityName: string, source: string): MetadataError;
53
53
  static noEntityDiscovered(): MetadataError;
54
54
  static onlyAbstractEntitiesDiscovered(): MetadataError;
55
- static duplicateEntityDiscovered(paths: string[], subject?: string): MetadataError;
56
- static duplicateFieldName(className: string, names: [string, string][]): MetadataError;
55
+ static duplicateEntityDiscovered(paths: string[]): MetadataError;
56
+ static duplicateFieldName(entityName: EntityName, names: [string, string][]): MetadataError;
57
57
  static multipleDecorators(entityName: string, propertyName: string): MetadataError;
58
58
  static missingMetadata(entity: string): MetadataError;
59
59
  static invalidPrimaryKey(meta: EntityMetadata, prop: EntityProperty, requiredName: string): MetadataError<Partial<any>>;
@@ -62,6 +62,14 @@ export declare class MetadataError<T extends AnyEntity = AnyEntity> extends Vali
62
62
  static nonPersistentCompositeProp(meta: EntityMetadata, prop: EntityProperty): MetadataError<Partial<any>>;
63
63
  static propertyTargetsEntityType(meta: EntityMetadata, prop: EntityProperty, target: EntityMetadata): MetadataError<Partial<any>>;
64
64
  static fromMissingOption(meta: EntityMetadata, prop: EntityProperty, option: string): MetadataError<Partial<any>>;
65
+ static targetKeyOnManyToMany(meta: EntityMetadata, prop: EntityProperty): MetadataError<Partial<any>>;
66
+ static targetKeyNotUnique(meta: EntityMetadata, prop: EntityProperty, target?: EntityMetadata): MetadataError<Partial<any>>;
67
+ static targetKeyNotFound(meta: EntityMetadata, prop: EntityProperty, target?: EntityMetadata): MetadataError<Partial<any>>;
68
+ static incompatiblePolymorphicTargets(meta: EntityMetadata, prop: EntityProperty, target1: EntityMetadata, target2: EntityMetadata, reason: string): MetadataError<Partial<any>>;
69
+ static dangerousPropertyName(meta: EntityMetadata, prop: EntityProperty): MetadataError<Partial<any>>;
70
+ static viewEntityWithoutExpression(meta: EntityMetadata): MetadataError;
71
+ static mixedInheritanceStrategies(root: EntityMetadata, child: EntityMetadata): MetadataError;
72
+ static tptNotSupportedByDriver(meta: EntityMetadata): MetadataError;
65
73
  private static fromMessage;
66
74
  }
67
75
  export declare class NotFoundError<T extends AnyEntity = AnyEntity> extends ValidationError<T> {
package/errors.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { inspect } from './logging/inspect.js';
2
+ import { Utils } from './utils/Utils.js';
2
3
  export class ValidationError extends Error {
3
4
  entity;
4
5
  constructor(message, entity) {
@@ -46,7 +47,7 @@ export class ValidationError extends Error {
46
47
  return new ValidationError(err);
47
48
  }
48
49
  static invalidPropertyName(entityName, invalid) {
49
- return new ValidationError(`Entity '${entityName}' does not have property '${invalid}'`);
50
+ return new ValidationError(`Entity '${Utils.className(entityName)}' does not have property '${invalid}'`);
50
51
  }
51
52
  static invalidCollectionValues(entityName, propName, invalid) {
52
53
  return new ValidationError(`Invalid collection values provided for '${entityName}.${propName}' in ${entityName}.assign(): ${inspect(invalid)}`);
@@ -92,14 +93,14 @@ export class ValidationError extends Error {
92
93
  static cannotUseGlobalContext() {
93
94
  return new ValidationError('Using global EntityManager instance methods for context specific actions is disallowed. If you need to work with the global instance\'s identity map, use `allowGlobalContext` configuration option or `fork()` instead.');
94
95
  }
95
- static cannotUseOperatorsInsideEmbeddables(className, propName, payload) {
96
- return new ValidationError(`Using operators inside embeddables is not allowed, move the operator above. (property: ${className}.${propName}, payload: ${inspect(payload)})`);
96
+ static cannotUseOperatorsInsideEmbeddables(entityName, propName, payload) {
97
+ return new ValidationError(`Using operators inside embeddables is not allowed, move the operator above. (property: ${Utils.className(entityName)}.${propName}, payload: ${inspect(payload)})`);
97
98
  }
98
- static cannotUseGroupOperatorsInsideScalars(className, propName, payload) {
99
- return new ValidationError(`Using group operators ($and/$or) inside scalar properties is not allowed, move the operator above. (property: ${className}.${propName}, payload: ${inspect(payload)})`);
99
+ static cannotUseGroupOperatorsInsideScalars(entityName, propName, payload) {
100
+ return new ValidationError(`Using group operators ($and/$or) inside scalar properties is not allowed, move the operator above. (property: ${Utils.className(entityName)}.${propName}, payload: ${inspect(payload)})`);
100
101
  }
101
- static invalidEmbeddableQuery(className, propName, embeddableType) {
102
- return new ValidationError(`Invalid query for entity '${className}', property '${propName}' does not exist in embeddable '${embeddableType}'`);
102
+ static invalidEmbeddableQuery(entityName, propName, embeddableType) {
103
+ return new ValidationError(`Invalid query for entity '${Utils.className(entityName)}', property '${propName}' does not exist in embeddable '${embeddableType}'`);
103
104
  }
104
105
  /* v8 ignore next */
105
106
  static invalidQueryCondition(cond) {
@@ -169,8 +170,8 @@ export class MetadataError extends ValidationError {
169
170
  const prop = meta.properties[meta.versionProperty];
170
171
  return new MetadataError(`Version property ${meta.className}.${prop.name} has unsupported type '${prop.type}'. Only 'number' and 'Date' are allowed.`);
171
172
  }
172
- static fromUnknownEntity(className, source) {
173
- return new MetadataError(`Entity '${className}' was not discovered, please make sure to provide it in 'entities' array when initializing the ORM (used in ${source})`);
173
+ static fromUnknownEntity(entityName, source) {
174
+ return new MetadataError(`Entity '${entityName}' was not discovered, please make sure to provide it in 'entities' array when initializing the ORM (used in ${source})`);
174
175
  }
175
176
  static noEntityDiscovered() {
176
177
  return new MetadataError('No entities were discovered');
@@ -178,11 +179,11 @@ export class MetadataError extends ValidationError {
178
179
  static onlyAbstractEntitiesDiscovered() {
179
180
  return new MetadataError('Only abstract entities were discovered, maybe you forgot to use @Entity() decorator? This can also happen when you have multiple `@mikro-orm/core` packages installed side by side.');
180
181
  }
181
- static duplicateEntityDiscovered(paths, subject = 'entity names') {
182
- return new MetadataError(`Duplicate ${subject} are not allowed: ${paths.join(', ')}`);
182
+ static duplicateEntityDiscovered(paths) {
183
+ return new MetadataError(`Duplicate table names are not allowed: ${paths.join(', ')}`);
183
184
  }
184
- static duplicateFieldName(className, names) {
185
- return new MetadataError(`Duplicate fieldNames are not allowed: ${names.map(n => `${className}.${n[0]} (fieldName: '${n[1]}')`).join(', ')}`);
185
+ static duplicateFieldName(entityName, names) {
186
+ return new MetadataError(`Duplicate fieldNames are not allowed: ${names.map(n => `${Utils.className(entityName)}.${n[0]} (fieldName: '${n[1]}')`).join(', ')}`);
186
187
  }
187
188
  static multipleDecorators(entityName, propertyName) {
188
189
  return new MetadataError(`Multiple property decorators used on '${entityName}.${propertyName}' property`);
@@ -212,6 +213,32 @@ export class MetadataError extends ValidationError {
212
213
  static fromMissingOption(meta, prop, option) {
213
214
  return this.fromMessage(meta, prop, `is missing '${option}' option`);
214
215
  }
216
+ static targetKeyOnManyToMany(meta, prop) {
217
+ return this.fromMessage(meta, prop, `uses 'targetKey' option which is not supported for ManyToMany relations`);
218
+ }
219
+ static targetKeyNotUnique(meta, prop, target) {
220
+ const targetName = target?.className ?? prop.type;
221
+ return this.fromMessage(meta, prop, `has 'targetKey' set to '${prop.targetKey}', but ${targetName}.${prop.targetKey} is not marked as unique`);
222
+ }
223
+ static targetKeyNotFound(meta, prop, target) {
224
+ const targetName = target?.className ?? prop.type;
225
+ return this.fromMessage(meta, prop, `has 'targetKey' set to '${prop.targetKey}', but ${targetName}.${prop.targetKey} does not exist`);
226
+ }
227
+ static incompatiblePolymorphicTargets(meta, prop, target1, target2, reason) {
228
+ return this.fromMessage(meta, prop, `has incompatible polymorphic targets ${target1.className} and ${target2.className}: ${reason}`);
229
+ }
230
+ static dangerousPropertyName(meta, prop) {
231
+ return this.fromMessage(meta, prop, `uses a dangerous property name '${prop.name}' which could lead to prototype pollution. Please use a different property name.`);
232
+ }
233
+ static viewEntityWithoutExpression(meta) {
234
+ return new MetadataError(`View entity ${meta.className} is missing 'expression'. View entities must have an expression defining the SQL query.`);
235
+ }
236
+ static mixedInheritanceStrategies(root, child) {
237
+ return new MetadataError(`Entity ${child.className} cannot mix STI (Single Table Inheritance) and TPT (Table-Per-Type) inheritance. Root entity ${root.className} uses STI (discriminatorColumn) but also has inheritance: 'tpt'. Choose one inheritance strategy per hierarchy.`);
238
+ }
239
+ static tptNotSupportedByDriver(meta) {
240
+ return new MetadataError(`Entity ${meta.className} uses TPT (Table-Per-Type) inheritance which is not supported by the current driver. TPT requires SQL JOINs and is only available with SQL drivers.`);
241
+ }
215
242
  static fromMessage(meta, prop, message) {
216
243
  return new MetadataError(`${meta.className}.${prop.name} ${message}`);
217
244
  }