@mikro-orm/core 6.2.10-dev.8 → 6.2.10-dev.81

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 (82) hide show
  1. package/EntityManager.d.ts +1 -2
  2. package/EntityManager.js +26 -24
  3. package/decorators/Check.js +1 -2
  4. package/decorators/CreateRequestContext.js +2 -3
  5. package/decorators/Embeddable.js +1 -2
  6. package/decorators/Embedded.js +1 -2
  7. package/decorators/Entity.js +1 -2
  8. package/decorators/Enum.js +1 -2
  9. package/decorators/Filter.js +1 -2
  10. package/decorators/Formula.js +1 -2
  11. package/decorators/Indexed.d.ts +3 -3
  12. package/decorators/Indexed.js +2 -3
  13. package/decorators/ManyToMany.js +1 -2
  14. package/decorators/ManyToOne.js +1 -2
  15. package/decorators/OneToMany.js +2 -3
  16. package/decorators/OneToOne.d.ts +1 -1
  17. package/decorators/OneToOne.js +1 -2
  18. package/decorators/PrimaryKey.d.ts +3 -2
  19. package/decorators/PrimaryKey.js +2 -3
  20. package/decorators/Property.d.ts +1 -1
  21. package/decorators/Property.js +1 -2
  22. package/decorators/hooks.js +10 -11
  23. package/drivers/DatabaseDriver.js +1 -1
  24. package/drivers/IDatabaseDriver.d.ts +2 -1
  25. package/entity/ArrayCollection.d.ts +0 -1
  26. package/entity/EntityIdentifier.d.ts +1 -1
  27. package/entity/EntityLoader.js +3 -0
  28. package/entity/Reference.d.ts +0 -1
  29. package/entity/Reference.js +10 -7
  30. package/entity/WrappedEntity.d.ts +0 -1
  31. package/entity/wrap.js +2 -3
  32. package/events/TransactionEventBroadcaster.d.ts +2 -2
  33. package/index.mjs +1 -0
  34. package/metadata/MetadataDiscovery.js +6 -4
  35. package/naming-strategy/AbstractNamingStrategy.d.ts +8 -0
  36. package/naming-strategy/AbstractNamingStrategy.js +12 -0
  37. package/naming-strategy/NamingStrategy.d.ts +21 -0
  38. package/package.json +2 -2
  39. package/platforms/Platform.d.ts +5 -1
  40. package/platforms/Platform.js +12 -4
  41. package/serialization/EntitySerializer.js +2 -2
  42. package/serialization/SerializationContext.d.ts +2 -2
  43. package/types/BigIntType.d.ts +2 -2
  44. package/types/BigIntType.js +1 -1
  45. package/types/BlobType.d.ts +0 -1
  46. package/types/CharacterType.d.ts +7 -0
  47. package/types/CharacterType.js +13 -0
  48. package/types/DateTimeType.d.ts +1 -0
  49. package/types/DateTimeType.js +3 -0
  50. package/types/DateType.d.ts +1 -0
  51. package/types/DateType.js +3 -0
  52. package/types/DecimalType.d.ts +2 -2
  53. package/types/IntervalType.d.ts +1 -0
  54. package/types/IntervalType.js +3 -0
  55. package/types/StringType.d.ts +1 -0
  56. package/types/StringType.js +3 -0
  57. package/types/TimeType.d.ts +1 -0
  58. package/types/TimeType.js +3 -0
  59. package/types/Type.d.ts +16 -2
  60. package/types/Uint8ArrayType.d.ts +0 -1
  61. package/types/index.d.ts +19 -16
  62. package/types/index.js +34 -31
  63. package/typings.d.ts +19 -19
  64. package/unit-of-work/ChangeSet.d.ts +0 -1
  65. package/unit-of-work/ChangeSetPersister.d.ts +1 -1
  66. package/unit-of-work/ChangeSetPersister.js +5 -3
  67. package/unit-of-work/UnitOfWork.d.ts +1 -1
  68. package/unit-of-work/UnitOfWork.js +32 -18
  69. package/utils/Configuration.js +2 -2
  70. package/utils/ConfigurationLoader.js +1 -0
  71. package/utils/Cursor.d.ts +0 -1
  72. package/utils/DataloaderUtils.d.ts +3 -3
  73. package/utils/DataloaderUtils.js +4 -4
  74. package/utils/EntityComparator.d.ts +13 -0
  75. package/utils/EntityComparator.js +62 -34
  76. package/utils/RawQueryFragment.d.ts +1 -2
  77. package/utils/RawQueryFragment.js +4 -4
  78. package/utils/Utils.d.ts +4 -6
  79. package/utils/Utils.js +13 -10
  80. package/utils/clone.js +1 -2
  81. package/utils/upsert-utils.d.ts +3 -2
  82. package/utils/upsert-utils.js +4 -5
package/typings.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Transaction } from './connections';
2
- import { type PopulatePath, type DeferMode, type Cascade, type EventType, type LoadStrategy, type QueryOrderMap, ReferenceKind } from './enums';
2
+ import { type Cascade, type DeferMode, type EventType, type LoadStrategy, type PopulatePath, type QueryOrderMap, ReferenceKind } from './enums';
3
3
  import { type AssignOptions, type Collection, type EntityFactory, type EntityIdentifier, type EntityLoaderOptions, type EntityRepository, Reference, type ScalarReference } from './entity';
4
4
  import type { SerializationContext, SerializeOptions } from './serialization';
5
5
  import type { EntitySchema, MetadataStorage } from './metadata';
@@ -13,9 +13,9 @@ export type Constructor<T = unknown> = new (...args: any[]) => T;
13
13
  export type Dictionary<T = any> = {
14
14
  [k: string]: T;
15
15
  };
16
- export type EntityKey<T = unknown, B extends boolean = false> = string & keyof {
17
- [K in keyof T as CleanKeys<T, K, B>]?: unknown;
18
- };
16
+ export type EntityKey<T = unknown, B extends boolean = false> = string & {
17
+ [K in keyof T]-?: CleanKeys<T, K, B> extends never ? never : K;
18
+ }[keyof T];
19
19
  export type EntityValue<T> = T[EntityKey<T>];
20
20
  export type FilterKey<T> = keyof FilterQuery<T>;
21
21
  export type AsyncFunction<R = any, T = Dictionary> = (args: T) => Promise<T>;
@@ -126,7 +126,7 @@ export type ExpandQuery<T> = T extends object ? T extends Scalar ? never : Filte
126
126
  export type EntityProps<T> = {
127
127
  -readonly [K in EntityKey<T>]?: T[K];
128
128
  };
129
- export type ObjectQuery<T> = OperatorMap<T> & ExpandObject<T>;
129
+ export type ObjectQuery<T> = OperatorMap<T> & FilterObject<T>;
130
130
  export type FilterQuery<T> = ObjectQuery<T> | NonNullable<ExpandScalar<Primary<T>>> | NonNullable<EntityProps<T> & OperatorMap<T>> | FilterQuery<T>[];
131
131
  export type QBFilterQuery<T = any> = ObjectQuery<T> | Dictionary;
132
132
  export interface IWrappedEntity<Entity extends object> {
@@ -223,7 +223,7 @@ type ExplicitlyOptionalProps<T> = (T extends {
223
223
  type NullableKeys<T, V = null> = {
224
224
  [K in keyof T]: V extends T[K] ? K : never;
225
225
  }[keyof T];
226
- type ProbablyOptionalProps<T> = PrimaryProperty<T> | ExplicitlyOptionalProps<T> | Defined<NullableKeys<T>>;
226
+ type ProbablyOptionalProps<T> = PrimaryProperty<T> | ExplicitlyOptionalProps<T> | NonNullable<NullableKeys<T>>;
227
227
  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;
228
228
  type RequiredKeys<T, K extends keyof T, I> = IsOptional<T, K, I> extends false ? CleanKeys<T, K> : never;
229
229
  type OptionalKeys<T, K extends keyof T, I> = IsOptional<T, K, I> extends false ? never : CleanKeys<T, K>;
@@ -271,7 +271,7 @@ type PrimaryOrObject<T, U, C extends TypeConfig> = PreferExplicitConfig<C, Extra
271
271
  export type EntityDTOProp<E, T, C extends TypeConfig = never> = T extends Scalar ? T : T extends {
272
272
  __serialized?: infer U;
273
273
  } ? U : T extends LoadedReference<infer U> ? EntityDTO<U, C> : T extends Reference<infer U> ? PrimaryOrObject<E, U, C> : T extends ScalarReference<infer U> ? U : T extends LoadedCollection<infer U> ? EntityDTO<U, C>[] : T extends Collection<infer U> ? PrimaryOrObject<E, U, C>[] : T extends readonly (infer U)[] ? (T extends readonly any[] ? T : U[]) : T extends Relation<T> ? EntityDTO<T, C> : T;
274
- type DTOProbablyOptionalProps<T> = Defined<NullableKeys<T, undefined>>;
274
+ type DTOProbablyOptionalProps<T> = NonNullable<NullableKeys<T, undefined>>;
275
275
  type DTOIsOptional<T, K extends keyof T> = T[K] extends LoadedCollection<any> ? false : K extends PrimaryProperty<T> ? false : K extends DTOProbablyOptionalProps<T> ? true : false;
276
276
  type DTORequiredKeys<T, K extends keyof T> = DTOIsOptional<T, K> extends false ? ExcludeHidden<T, K> & CleanKeys<T, K> : never;
277
277
  type DTOOptionalKeys<T, K extends keyof T> = DTOIsOptional<T, K> extends false ? never : ExcludeHidden<T, K> & CleanKeys<T, K>;
@@ -372,7 +372,7 @@ export interface EntityProperty<Owner = any, Target = any> {
372
372
  extra?: string;
373
373
  userDefined?: boolean;
374
374
  optional?: boolean;
375
- ignoreSchemaChanges?: ('type' | 'extra')[];
375
+ ignoreSchemaChanges?: ('type' | 'extra' | 'default')[];
376
376
  deferMode?: DeferMode;
377
377
  }
378
378
  export declare class EntityMetadata<T = any> {
@@ -537,6 +537,7 @@ export interface GenerateOptions {
537
537
  readOnlyPivotTables?: boolean;
538
538
  customBaseEntityName?: string;
539
539
  useCoreBaseEntity?: boolean;
540
+ coreImportsPrefix?: string;
540
541
  onInitialMetadata?: MetadataProcessor;
541
542
  onProcessedMetadata?: MetadataProcessor;
542
543
  }
@@ -668,7 +669,7 @@ type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
668
669
  type CollectionKeys<T> = T extends object ? {
669
670
  [K in keyof T]: T[K] extends Collection<any> ? IsAny<T[K]> extends true ? never : K & string : never;
670
671
  }[keyof T] & {} : never;
671
- export type AutoPath<O, P extends string | boolean, E extends string = never, D extends Prev[number] = 9> = P extends boolean ? P : [D] extends [never] ? never : P extends any ? P extends string ? (P & `${string}.` extends never ? P : P & `${string}.`) extends infer Q ? Q extends `${infer A}.${infer B}` ? A extends StringKeys<O, E> ? `${A}.${AutoPath<Defined<GetStringKey<O, A, E>>, B, E, Prev[D]>}` : never : Q extends StringKeys<O, E> ? (Defined<GetStringKey<O, Q, E>> extends unknown ? Exclude<P, `${string}.`> : never) | (StringKeys<Defined<GetStringKey<O, Q, E>>, E> extends never ? never : `${Q & string}.`) : StringKeys<O, E> | `${CollectionKeys<O>}:ref` : never : never : never;
672
+ export type AutoPath<O, P extends string | boolean, E extends string = never, D extends Prev[number] = 9> = P extends boolean ? P : [D] extends [never] ? never : P extends any ? P extends string ? (P & `${string}.` extends never ? P : P & `${string}.`) extends infer Q ? Q extends `${infer A}.${infer B}` ? A extends StringKeys<O, E> ? `${A}.${AutoPath<NonNullable<GetStringKey<O, A, E>>, B, E, Prev[D]>}` : never : Q extends StringKeys<O, E> ? (NonNullable<GetStringKey<O, Q, E>> extends unknown ? Exclude<P, `${string}.`> : never) | (StringKeys<NonNullable<GetStringKey<O, Q, E>>, E> extends never ? never : `${Q & string}.`) : StringKeys<O, E> | `${CollectionKeys<O>}:ref` : never : never : never;
672
673
  export type UnboxArray<T> = T extends any[] ? ArrayElement<T> : T;
673
674
  export type ArrayElement<ArrayType extends unknown[]> = ArrayType extends (infer ElementType)[] ? ElementType : never;
674
675
  export type ExpandProperty<T> = T extends Reference<infer U> ? NonNullable<U> : T extends Collection<infer U, any> ? NonNullable<U> : T extends (infer U)[] ? NonNullable<U> : NonNullable<T>;
@@ -679,7 +680,6 @@ type Prefix<T, K> = K extends `${infer S}.${string}` ? S : (K extends '*' ? keyo
679
680
  type IsPrefixedExclude<T, K extends keyof T, E extends string> = K extends E ? never : K;
680
681
  export type IsPrefixed<T, K extends keyof T, L extends string, E extends string = never> = IsNever<E> extends false ? IsPrefixedExclude<T, K, E> : K extends symbol ? never : IsTrue<L> extends true ? (T[K] & {} extends Loadable<any> ? K : never) : IsNever<StringLiteral<L>> extends true ? never : K extends Prefix<T, L> ? K : K extends PrimaryProperty<T> ? K : never;
681
682
  type Suffix<Key, Hint extends string, All = true | '*'> = Hint extends `${infer Pref}.${infer Suf}` ? (Pref extends Key ? Suf : never) : Hint extends All ? Hint : never;
682
- type Defined<T> = T & {};
683
683
  export type IsSubset<T, U> = keyof U extends keyof T ? {} : Dictionary extends U ? {} : {
684
684
  [K in keyof U as K extends keyof T ? never : CleanKeys<U, K>]: never;
685
685
  };
@@ -695,7 +695,7 @@ type LoadedProp<T, L extends string = never, F extends string = '*', E extends s
695
695
  export type AddEager<T> = ExtractEagerProps<T> & string;
696
696
  export type ExpandHint<T, L extends string> = L | AddEager<T>;
697
697
  export type Selected<T, L extends string = never, F extends string = '*'> = {
698
- [K in keyof T as IsPrefixed<T, K, L | F | AddEager<T>>]: LoadedProp<Defined<T[K]>, Suffix<K, L, true>, Suffix<K, F, true>> | AddOptional<T[K]>;
698
+ [K in keyof T as IsPrefixed<T, K, L | F | AddEager<T>>]: LoadedProp<NonNullable<T[K]>, Suffix<K, L, true>, Suffix<K, F, true>> | AddOptional<T[K]>;
699
699
  } & {
700
700
  [K in keyof T as FunctionKeys<T, K>]: T[K];
701
701
  } & {
@@ -711,9 +711,9 @@ export type FromEntityType<T> = T extends LoadedEntityType<infer U> ? U : T;
711
711
  type LoadedInternal<T, L extends string = never, F extends string = '*', E extends string = never> = [
712
712
  F
713
713
  ] extends ['*'] ? IsNever<E> extends true ? T & {
714
- [K in keyof T as IsPrefixed<T, K, ExpandHint<T, L>>]: LoadedProp<Defined<T[K]>, Suffix<K, L>, Suffix<K, F>, Suffix<K, E>> | AddOptional<T[K]>;
714
+ [K in keyof T as IsPrefixed<T, K, ExpandHint<T, L>>]: LoadedProp<NonNullable<T[K]>, Suffix<K, L>, Suffix<K, F>, Suffix<K, E>> | AddOptional<T[K]>;
715
715
  } : {
716
- [K in keyof T as IsPrefixed<T, K, ExpandHint<T, L>, E>]: LoadedProp<Defined<T[K]>, Suffix<K, L>, Suffix<K, F>, Suffix<K, E>> | AddOptional<T[K]>;
716
+ [K in keyof T as IsPrefixed<T, K, ExpandHint<T, L>, E>]: LoadedProp<NonNullable<T[K]>, Suffix<K, L>, Suffix<K, F>, Suffix<K, E>> | AddOptional<T[K]>;
717
717
  } : Selected<T, L, F>;
718
718
  /**
719
719
  * Represents entity with its loaded relations (`populate` hint) and selected properties (`fields` hint).
@@ -721,13 +721,13 @@ type LoadedInternal<T, L extends string = never, F extends string = '*', E exten
721
721
  export type Loaded<T, L extends string = never, F extends string = '*', E extends string = never> = LoadedInternal<T, L, F, E> & {
722
722
  [__loadedType]?: T;
723
723
  };
724
- export interface LoadedReference<T> extends Reference<Defined<T>> {
725
- $: Defined<T>;
726
- get(): Defined<T>;
724
+ export interface LoadedReference<T> extends Reference<NonNullable<T>> {
725
+ $: NonNullable<T>;
726
+ get(): NonNullable<T>;
727
727
  }
728
- export interface LoadedScalarReference<T> extends ScalarReference<Defined<T>> {
729
- $: Defined<T>;
730
- get(): Defined<T>;
728
+ export interface LoadedScalarReference<T> extends ScalarReference<T> {
729
+ $: T;
730
+ get(): T;
731
731
  }
732
732
  export interface LoadedCollection<T extends object> extends Collection<T> {
733
733
  $: Collection<T>;
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { inspect } from 'util';
3
2
  import type { EntityData, EntityMetadata, EntityDictionary, Primary } from '../typings';
4
3
  export declare class ChangeSet<T extends object> {
@@ -47,5 +47,5 @@ export declare class ChangeSetPersister {
47
47
  * No need to handle composite keys here as they need to be set upfront.
48
48
  * We do need to map to the change set payload too, as it will be used in the originalEntityData for new entities.
49
49
  */
50
- mapReturnedValues<T extends object>(entity: T, payload: EntityDictionary<T>, row: Dictionary | undefined, meta: EntityMetadata<T>): void;
50
+ mapReturnedValues<T extends object>(entity: T | null | undefined, payload: EntityDictionary<T>, row: Dictionary | undefined, meta: EntityMetadata<T>, upsert?: boolean): void;
51
51
  }
@@ -351,10 +351,12 @@ class ChangeSetPersister {
351
351
  * No need to handle composite keys here as they need to be set upfront.
352
352
  * We do need to map to the change set payload too, as it will be used in the originalEntityData for new entities.
353
353
  */
354
- mapReturnedValues(entity, payload, row, meta) {
355
- if (this.usesReturningStatement && row && utils_1.Utils.hasObjectKeys(row)) {
354
+ mapReturnedValues(entity, payload, row, meta, upsert = false) {
355
+ if ((this.usesReturningStatement || upsert) && row && utils_1.Utils.hasObjectKeys(row)) {
356
356
  const mapped = this.comparator.mapResult(meta.className, row);
357
- this.hydrator.hydrate(entity, meta, mapped, this.factory, 'full', false, true);
357
+ if (entity) {
358
+ this.hydrator.hydrate(entity, meta, mapped, this.factory, 'full', false, true);
359
+ }
358
360
  Object.assign(payload, mapped); // merge to the changeset payload, so it gets saved to the entity snapshot
359
361
  }
360
362
  }
@@ -52,7 +52,7 @@ export declare class UnitOfWork {
52
52
  getRemoveStack(): Set<AnyEntity>;
53
53
  getChangeSets(): ChangeSet<AnyEntity>[];
54
54
  getCollectionUpdates(): Collection<AnyEntity>[];
55
- getExtraUpdates(): Set<[AnyEntity, string | string[], (AnyEntity | AnyEntity[] | Reference<any> | Collection<any>), ChangeSet<any> | undefined]>;
55
+ getExtraUpdates(): Set<[AnyEntity, string | string[], (AnyEntity | AnyEntity[] | Reference<any> | Collection<any>), ChangeSet<any> | undefined, ChangeSetType]>;
56
56
  shouldAutoFlush<T extends object>(meta: EntityMetadata<T>): boolean;
57
57
  clearActionsQueue(): void;
58
58
  computeChangeSet<T extends object>(entity: T, type?: ChangeSetType): void;
@@ -423,15 +423,24 @@ class UnitOfWork {
423
423
  return;
424
424
  }
425
425
  let conflicts = false;
426
+ let type = ChangeSet_1.ChangeSetType.UPDATE;
427
+ if (!props.some(prop => prop.name in changeSet.payload)) {
428
+ return;
429
+ }
426
430
  for (const cs of this.changeSets.values()) {
427
- if (cs.rootName === changeSet.rootName && cs.type === changeSet.type) {
428
- conflicts = true;
431
+ for (const prop of props) {
432
+ if (prop.name in cs.payload && cs.rootName === changeSet.rootName && cs.type === changeSet.type) {
433
+ conflicts = true;
434
+ if (changeSet.payload[prop.name] == null) {
435
+ type = ChangeSet_1.ChangeSetType.UPDATE_EARLY;
436
+ }
437
+ }
429
438
  }
430
439
  }
431
440
  if (!conflicts) {
432
441
  return;
433
442
  }
434
- this.extraUpdates.add([changeSet.entity, props.map(p => p.name), props.map(p => changeSet.entity[p.name]), changeSet]);
443
+ this.extraUpdates.add([changeSet.entity, props.map(p => p.name), props.map(p => changeSet.entity[p.name]), changeSet, type]);
435
444
  for (const p of props) {
436
445
  delete changeSet.entity[p.name];
437
446
  delete changeSet.payload[p.name];
@@ -483,13 +492,13 @@ class UnitOfWork {
483
492
  * Returns `true` when the change set should be skipped as it will be empty after the extra update.
484
493
  */
485
494
  checkUniqueProps(changeSet) {
486
- if (this.platform.allowsUniqueBatchUpdates() || changeSet.type !== ChangeSet_1.ChangeSetType.UPDATE) {
495
+ if (changeSet.type !== ChangeSet_1.ChangeSetType.UPDATE) {
487
496
  return false;
488
497
  }
489
- // when changing a unique nullable property (or a 1:1 relation), we can't do it in a single query as it would cause unique constraint violations
498
+ // when changing a unique nullable property (or a 1:1 relation), we can't do it in a single
499
+ // query as it would cause unique constraint violations
490
500
  const uniqueProps = changeSet.meta.uniqueProps.filter(prop => {
491
- return (prop.nullable || changeSet.type !== ChangeSet_1.ChangeSetType.CREATE)
492
- && changeSet.payload[prop.name] != null;
501
+ return (prop.nullable || changeSet.type !== ChangeSet_1.ChangeSetType.CREATE);
493
502
  });
494
503
  this.scheduleExtraUpdate(changeSet, uniqueProps);
495
504
  return changeSet.type === ChangeSet_1.ChangeSetType.UPDATE && !Utils_1.Utils.hasObjectKeys(changeSet.payload);
@@ -558,7 +567,7 @@ class UnitOfWork {
558
567
  }
559
568
  processToManyReference(collection, visited, processed, parent, prop) {
560
569
  if (this.isCollectionSelfReferenced(collection, processed)) {
561
- this.extraUpdates.add([parent, prop.name, collection, undefined]);
570
+ this.extraUpdates.add([parent, prop.name, collection, undefined, ChangeSet_1.ChangeSetType.UPDATE]);
562
571
  const coll = new entity_1.Collection(parent);
563
572
  coll.property = prop;
564
573
  parent[prop.name] = coll;
@@ -710,31 +719,33 @@ class UnitOfWork {
710
719
  }
711
720
  const commitOrder = this.getCommitOrder();
712
721
  const commitOrderReversed = [...commitOrder].reverse();
713
- // 1. early delete - when we recreate entity in the same UoW, we need to issue those delete queries before inserts
722
+ // early delete - when we recreate entity in the same UoW, we need to issue those delete queries before inserts
714
723
  for (const name of commitOrderReversed) {
715
724
  await this.commitDeleteChangeSets(groups[ChangeSet_1.ChangeSetType.DELETE_EARLY].get(name) ?? [], ctx);
716
725
  }
717
- // 2. early update - when we recreate entity in the same UoW, we need to issue those delete queries before inserts
726
+ // early update - when we recreate entity in the same UoW, we need to issue those delete queries before inserts
718
727
  for (const name of commitOrder) {
719
728
  await this.commitUpdateChangeSets(groups[ChangeSet_1.ChangeSetType.UPDATE_EARLY].get(name) ?? [], ctx);
720
729
  }
721
- // 3. create
730
+ // extra updates
731
+ await this.commitExtraUpdates(ChangeSet_1.ChangeSetType.UPDATE_EARLY, ctx);
732
+ // create
722
733
  for (const name of commitOrder) {
723
734
  await this.commitCreateChangeSets(groups[ChangeSet_1.ChangeSetType.CREATE].get(name) ?? [], ctx);
724
735
  }
725
- // 4. update
736
+ // update
726
737
  for (const name of commitOrder) {
727
738
  await this.commitUpdateChangeSets(groups[ChangeSet_1.ChangeSetType.UPDATE].get(name) ?? [], ctx);
728
739
  }
729
- // 5. extra updates
730
- await this.commitExtraUpdates(ctx);
731
- // 6. collection updates
740
+ // extra updates
741
+ await this.commitExtraUpdates(ChangeSet_1.ChangeSetType.UPDATE, ctx);
742
+ // collection updates
732
743
  await this.commitCollectionUpdates(ctx);
733
- // 7. delete - entity deletions need to be in reverse commit order
744
+ // delete - entity deletions need to be in reverse commit order
734
745
  for (const name of commitOrderReversed) {
735
746
  await this.commitDeleteChangeSets(groups[ChangeSet_1.ChangeSetType.DELETE].get(name) ?? [], ctx);
736
747
  }
737
- // 8. take snapshots of all persisted collections
748
+ // take snapshots of all persisted collections
738
749
  const visited = new Set();
739
750
  for (const changeSet of this.changeSets.values()) {
740
751
  this.takeCollectionSnapshots(changeSet.entity, visited);
@@ -825,9 +836,12 @@ class UnitOfWork {
825
836
  await this.runHooks(enums_1.EventType.afterDelete, changeSet);
826
837
  }
827
838
  }
828
- async commitExtraUpdates(ctx) {
839
+ async commitExtraUpdates(type, ctx) {
829
840
  const extraUpdates = [];
830
841
  for (const extraUpdate of this.extraUpdates) {
842
+ if (extraUpdate[4] !== type) {
843
+ continue;
844
+ }
831
845
  if (Array.isArray(extraUpdate[1])) {
832
846
  extraUpdate[1].forEach((p, i) => extraUpdate[0][p] = extraUpdate[2][i]);
833
847
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defineConfig = exports.Configuration = void 0;
3
+ exports.Configuration = void 0;
4
+ exports.defineConfig = defineConfig;
4
5
  const fs_extra_1 = require("fs-extra");
5
6
  const cache_1 = require("../cache");
6
7
  const hydration_1 = require("../hydration");
@@ -373,4 +374,3 @@ exports.Configuration = Configuration;
373
374
  function defineConfig(options) {
374
375
  return options;
375
376
  }
376
- exports.defineConfig = defineConfig;
@@ -119,6 +119,7 @@ class ConfigurationLoader {
119
119
  transpileOnly: true,
120
120
  compilerOptions: {
121
121
  module: 'nodenext',
122
+ moduleResolution: 'nodenext',
122
123
  },
123
124
  }).config;
124
125
  if (Object.entries(options?.paths ?? {}).length > 0) {
package/utils/Cursor.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { inspect } from 'util';
3
2
  import type { EntityMetadata, FilterObject, Loaded } from '../typings';
4
3
  import type { FindByCursorOptions, OrderDefinition } from '../drivers/IDatabaseDriver';
@@ -7,12 +7,12 @@ import { type LoadReferenceOptions } from '../entity/Reference';
7
7
  export declare class DataloaderUtils {
8
8
  /**
9
9
  * Groups identified references by entity and returns a Map with the
10
- * class name as the index and the corresponging primary keys as the value.
10
+ * class name as the index and the corresponding primary keys as the value.
11
11
  */
12
12
  static groupPrimaryKeysByEntityAndOpts(refsWithOpts: readonly [Ref<any>, Omit<LoadReferenceOptions<any, any>, 'dataloader'>?][]): Map<string, Set<Primary<any>>>;
13
13
  /**
14
14
  * Returns the reference dataloader batchLoadFn, which aggregates references by entity,
15
- * makes one query per entity and maps each input reference to the corresponging result.
15
+ * makes one query per entity and maps each input reference to the corresponding result.
16
16
  */
17
17
  static getRefBatchLoadFn(em: EntityManager): DataLoader.BatchLoadFn<[Ref<any>, Omit<LoadReferenceOptions<any, any>, 'dataloader'>?], any>;
18
18
  /**
@@ -36,7 +36,7 @@ export declare class DataloaderUtils {
36
36
  static getColFilter<T, S extends T>(collection: Collection<any, object>): (result: T) => result is S;
37
37
  /**
38
38
  * Returns the collection dataloader batchLoadFn, which aggregates collections by entity,
39
- * makes one query per entity and maps each input collection to the corresponging result.
39
+ * makes one query per entity and maps each input collection to the corresponding result.
40
40
  */
41
41
  static getColBatchLoadFn(em: EntityManager): DataLoader.BatchLoadFn<[Collection<any>, Omit<InitCollectionOptions<any, any>, 'dataloader'>?], any>;
42
42
  static getDataloaderType(dataloaderCfg: DataloaderType | boolean): DataloaderType;
@@ -7,7 +7,7 @@ const enums_1 = require("../enums");
7
7
  class DataloaderUtils {
8
8
  /**
9
9
  * Groups identified references by entity and returns a Map with the
10
- * class name as the index and the corresponging primary keys as the value.
10
+ * class name as the index and the corresponding primary keys as the value.
11
11
  */
12
12
  static groupPrimaryKeysByEntityAndOpts(refsWithOpts) {
13
13
  const map = new Map();
@@ -20,7 +20,7 @@ class DataloaderUtils {
20
20
  In real-world scenarios (GraphQL) most of the time you will end up batching the same sets of options anyway,
21
21
  so we end up getting most of the benefits with the much simpler implementation.
22
22
  Also there are scenarios where the single query per entity implementation may end up being slower, for example
23
- if the vast majority of the refereces batched for a certain entity don't have populate options while a few ones have
23
+ if the vast majority of the references batched for a certain entity don't have populate options while a few ones have
24
24
  a wildcard populate so you end up doing the additional joins for all the entities.
25
25
  Thus such approach should probably be configurable, if not opt-in.
26
26
  NOTE: meta + opts multi maps (https://github.com/martian17/ds-js) might be a more elegant way
@@ -37,7 +37,7 @@ class DataloaderUtils {
37
37
  }
38
38
  /**
39
39
  * Returns the reference dataloader batchLoadFn, which aggregates references by entity,
40
- * makes one query per entity and maps each input reference to the corresponging result.
40
+ * makes one query per entity and maps each input reference to the corresponding result.
41
41
  */
42
42
  static getRefBatchLoadFn(em) {
43
43
  return async (refsWithOpts) => {
@@ -159,7 +159,7 @@ class DataloaderUtils {
159
159
  }
160
160
  /**
161
161
  * Returns the collection dataloader batchLoadFn, which aggregates collections by entity,
162
- * makes one query per entity and maps each input collection to the corresponging result.
162
+ * makes one query per entity and maps each input collection to the corresponding result.
163
163
  */
164
164
  static getColBatchLoadFn(em) {
165
165
  return async (collsWithOpts) => {
@@ -3,6 +3,7 @@ import type { Platform } from '../platforms';
3
3
  type Comparator<T> = (a: T, b: T) => EntityData<T>;
4
4
  type ResultMapper<T> = (result: EntityData<T>) => EntityData<T> | null;
5
5
  type SnapshotGenerator<T> = (entity: T) => EntityData<T>;
6
+ type CompositeKeyPart = string | CompositeKeyPart[];
6
7
  export declare class EntityComparator {
7
8
  private readonly metadata;
8
9
  private readonly platform;
@@ -44,6 +45,18 @@ export declare class EntityComparator {
44
45
  * @internal Highly performance-sensitive method.
45
46
  */
46
47
  getSnapshotGenerator<T>(entityName: string): SnapshotGenerator<T>;
48
+ /**
49
+ * @internal
50
+ */
51
+ propName(name: string, parent?: string): string;
52
+ /**
53
+ * @internal respects nested composite keys, e.g. `[1, [2, 3]]`
54
+ */
55
+ createCompositeKeyArray(prop: EntityProperty, parents?: EntityProperty[]): string;
56
+ /**
57
+ * @internal
58
+ */
59
+ formatCompositeKeyPart(part: CompositeKeyPart): string;
47
60
  /**
48
61
  * @internal Highly performance-sensitive method.
49
62
  */
@@ -206,6 +206,50 @@ class EntityComparator {
206
206
  this.snapshotGenerators.set(entityName, snapshotGenerator);
207
207
  return snapshotGenerator;
208
208
  }
209
+ /**
210
+ * @internal
211
+ */
212
+ propName(name, parent = 'result') {
213
+ return parent + this.wrap(name);
214
+ }
215
+ /**
216
+ * @internal respects nested composite keys, e.g. `[1, [2, 3]]`
217
+ */
218
+ createCompositeKeyArray(prop, parents = []) {
219
+ if (!prop.targetMeta) {
220
+ let fieldName = prop.fieldNames[0];
221
+ // traverse all parents, mapping my field name to each parent's field name until we reach the root
222
+ for (let i = parents.length - 1; i >= 0; i--) {
223
+ const parent = parents[i];
224
+ // look for the field name in the parent's referencedColumnNames, except for M:N without a custom pivot entity
225
+ // (in that case, the field names are the referenced PK's )
226
+ const target = parent.kind === enums_1.ReferenceKind.MANY_TO_MANY && parent.pivotEntity === parent.pivotTable ?
227
+ parent.referencedPKs : parent.referencedColumnNames;
228
+ const idx = target.indexOf(fieldName);
229
+ fieldName = parent.fieldNames[idx];
230
+ }
231
+ return this.propName(fieldName);
232
+ }
233
+ const parts = [];
234
+ prop.targetMeta.getPrimaryProps().forEach(pk => {
235
+ const part = this.createCompositeKeyArray(pk, [...parents, prop]);
236
+ parts.push(part);
237
+ });
238
+ return this.formatCompositeKeyPart(parts);
239
+ }
240
+ /**
241
+ * @internal
242
+ */
243
+ formatCompositeKeyPart(part) {
244
+ if (!Array.isArray(part)) {
245
+ return part;
246
+ }
247
+ if (part.length === 1) {
248
+ return this.formatCompositeKeyPart(part[0]);
249
+ }
250
+ const formatted = part.map(this.formatCompositeKeyPart).join(', ');
251
+ return `[${formatted}]`;
252
+ }
209
253
  /**
210
254
  * @internal Highly performance-sensitive method.
211
255
  */
@@ -217,22 +261,6 @@ class EntityComparator {
217
261
  const meta = this.metadata.get(entityName);
218
262
  const lines = [];
219
263
  const context = new Map();
220
- const propName = (name, parent = 'result') => parent + this.wrap(name);
221
- // respects nested composite keys, e.g. `[1, [2, 3]]`
222
- const createCompositeKeyArray = (prop, fieldNames = prop.fieldNames, idx = 0) => {
223
- if (!prop.targetMeta) {
224
- return propName(fieldNames[idx++]);
225
- }
226
- const parts = [];
227
- for (const pk of prop.targetMeta.getPrimaryProps()) {
228
- parts.push(createCompositeKeyArray(pk, fieldNames, idx));
229
- idx += pk.fieldNames.length;
230
- }
231
- if (parts.length < 2) {
232
- return parts[0];
233
- }
234
- return '[' + parts.join(', ') + ']';
235
- };
236
264
  const tz = this.platform.getTimezone();
237
265
  const parseDate = (key, value, padding = '') => {
238
266
  lines.push(`${padding} if (${value} == null || ${value} instanceof Date) {`);
@@ -255,28 +283,28 @@ class EntityComparator {
255
283
  return;
256
284
  }
257
285
  if (prop.targetMeta && prop.fieldNames.length > 1) {
258
- lines.push(` if (${prop.fieldNames.map(field => `typeof ${propName(field)} === 'undefined'`).join(' && ')}) {`);
259
- lines.push(` } else if (${prop.fieldNames.map(field => `${propName(field)} != null`).join(' && ')}) {`);
260
- lines.push(` ret${this.wrap(prop.name)} = ${createCompositeKeyArray(prop)};`);
261
- lines.push(...prop.fieldNames.map(field => ` ${propName(field, 'mapped')} = true;`));
262
- lines.push(` } else if (${prop.fieldNames.map(field => `${propName(field)} == null`).join(' && ')}) {\n ret${this.wrap(prop.name)} = null;`);
263
- lines.push(...prop.fieldNames.map(field => ` ${propName(field, 'mapped')} = true;`), ' }');
286
+ lines.push(` if (${prop.fieldNames.map(field => `typeof ${this.propName(field)} === 'undefined'`).join(' && ')}) {`);
287
+ lines.push(` } else if (${prop.fieldNames.map(field => `${this.propName(field)} != null`).join(' && ')}) {`);
288
+ lines.push(` ret${this.wrap(prop.name)} = ${this.createCompositeKeyArray(prop)};`);
289
+ lines.push(...prop.fieldNames.map(field => ` ${this.propName(field, 'mapped')} = true;`));
290
+ lines.push(` } else if (${prop.fieldNames.map(field => `${this.propName(field)} == null`).join(' && ')}) {\n ret${this.wrap(prop.name)} = null;`);
291
+ lines.push(...prop.fieldNames.map(field => ` ${this.propName(field, 'mapped')} = true;`), ' }');
264
292
  return;
265
293
  }
266
294
  if (prop.embedded && (meta.embeddable || meta.properties[prop.embedded[0]].object)) {
267
295
  return;
268
296
  }
269
297
  if (prop.runtimeType === 'boolean') {
270
- lines.push(` if (typeof ${propName(prop.fieldNames[0])} !== 'undefined') {`);
271
- lines.push(` ret${this.wrap(prop.name)} = ${propName(prop.fieldNames[0])} == null ? ${propName(prop.fieldNames[0])} : !!${propName(prop.fieldNames[0])};`);
272
- lines.push(` ${propName(prop.fieldNames[0], 'mapped')} = true;`);
298
+ lines.push(` if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
299
+ lines.push(` ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} == null ? ${this.propName(prop.fieldNames[0])} : !!${this.propName(prop.fieldNames[0])};`);
300
+ lines.push(` ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
273
301
  lines.push(` }`);
274
302
  }
275
303
  else if (prop.runtimeType === 'Date') {
276
- lines.push(` if (typeof ${propName(prop.fieldNames[0])} !== 'undefined') {`);
304
+ lines.push(` if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
277
305
  context.set('parseDate', (value) => this.platform.parseDate(value));
278
- parseDate('ret' + this.wrap(prop.name), propName(prop.fieldNames[0]));
279
- lines.push(` ${propName(prop.fieldNames[0], 'mapped')} = true;`);
306
+ parseDate('ret' + this.wrap(prop.name), this.propName(prop.fieldNames[0]));
307
+ lines.push(` ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
280
308
  lines.push(` }`);
281
309
  }
282
310
  else if (prop.kind === enums_1.ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
@@ -288,15 +316,15 @@ class EntityComparator {
288
316
  }
289
317
  return item == null ? item : this.getResultMapper(prop.type)(item);
290
318
  });
291
- lines.push(` if (typeof ${propName(prop.fieldNames[0])} !== 'undefined') {`);
292
- lines.push(` ret${this.wrap(prop.name)} = ${propName(prop.fieldNames[0])} == null ? ${propName(prop.fieldNames[0])} : mapEmbeddedResult_${idx}(${propName(prop.fieldNames[0])});`);
293
- lines.push(` ${propName(prop.fieldNames[0], 'mapped')} = true;`);
319
+ lines.push(` if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
320
+ lines.push(` ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])} == null ? ${this.propName(prop.fieldNames[0])} : mapEmbeddedResult_${idx}(${this.propName(prop.fieldNames[0])});`);
321
+ lines.push(` ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
294
322
  lines.push(` }`);
295
323
  }
296
324
  else if (prop.kind !== enums_1.ReferenceKind.EMBEDDED) {
297
- lines.push(` if (typeof ${propName(prop.fieldNames[0])} !== 'undefined') {`);
298
- lines.push(` ret${this.wrap(prop.name)} = ${propName(prop.fieldNames[0])};`);
299
- lines.push(` ${propName(prop.fieldNames[0], 'mapped')} = true;`);
325
+ lines.push(` if (typeof ${this.propName(prop.fieldNames[0])} !== 'undefined') {`);
326
+ lines.push(` ret${this.wrap(prop.name)} = ${this.propName(prop.fieldNames[0])};`);
327
+ lines.push(` ${this.propName(prop.fieldNames[0], 'mapped')} = true;`);
300
328
  lines.push(` }`);
301
329
  }
302
330
  });
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { inspect } from 'util';
3
2
  import type { AnyString, Dictionary, EntityKey } from '../typings';
4
3
  export declare class RawQueryFragment {
@@ -89,7 +88,7 @@ export declare function raw<T extends object = any, R = any>(sql: EntityKey<T> |
89
88
  export declare function sql(sql: readonly string[], ...values: unknown[]): any;
90
89
  export declare namespace sql {
91
90
  var ref: <T extends object>(...keys: string[]) => RawQueryFragment;
92
- var now: (length?: number | undefined) => string;
91
+ var now: (length?: number) => string;
93
92
  var lower: <T extends object>(key: string | ((alias: string) => string)) => string;
94
93
  var upper: <T extends object>(key: string | ((alias: string) => string)) => string;
95
94
  }
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createSqlFunction = exports.sql = exports.raw = exports.ALIAS_REPLACEMENT_RE = exports.ALIAS_REPLACEMENT = exports.RawQueryFragment = void 0;
3
+ exports.ALIAS_REPLACEMENT_RE = exports.ALIAS_REPLACEMENT = exports.RawQueryFragment = void 0;
4
+ exports.raw = raw;
5
+ exports.sql = sql;
6
+ exports.createSqlFunction = createSqlFunction;
4
7
  const util_1 = require("util");
5
8
  const Utils_1 = require("./Utils");
6
9
  class RawQueryFragment {
@@ -152,7 +155,6 @@ function raw(sql, params) {
152
155
  }
153
156
  return new RawQueryFragment(sql, params);
154
157
  }
155
- exports.raw = raw;
156
158
  /**
157
159
  * Alternative to the `raw()` helper allowing to use it as a tagged template function for the simple cases.
158
160
  *
@@ -174,14 +176,12 @@ function sql(sql, ...values) {
174
176
  return valueExists ? text + '?' : text;
175
177
  }, ''), values);
176
178
  }
177
- exports.sql = sql;
178
179
  function createSqlFunction(func, key) {
179
180
  if (typeof key === 'string') {
180
181
  return raw(`${func}(${key})`);
181
182
  }
182
183
  return raw(a => `${func}(${(key(a))})`);
183
184
  }
184
- exports.createSqlFunction = createSqlFunction;
185
185
  sql.ref = (...keys) => raw('??', [keys.join('.')]);
186
186
  sql.now = (length) => raw('current_timestamp' + (length == null ? '' : `(${length})`));
187
187
  sql.lower = (key) => createSqlFunction('lower', key);
package/utils/Utils.d.ts CHANGED
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  import { type GlobbyOptions } from 'globby';
4
2
  import { type URL } from 'url';
5
3
  import type { Dictionary, EntityData, EntityDictionary, EntityKey, EntityMetadata, EntityName, EntityProperty, IMetadataStorage, Primary } from '../typings';
@@ -190,9 +188,9 @@ export declare class Utils {
190
188
  static isCollection<T extends object, O extends object = object>(item: any): item is Collection<T, O>;
191
189
  static fileURLToPath(url: string | URL): string;
192
190
  /**
193
- * Resolves and normalizes a series of path parts relative to each preceeding part.
191
+ * Resolves and normalizes a series of path parts relative to each preceding part.
194
192
  * If any part is a `file:` URL, it is converted to a local path. If any part is an
195
- * absolute path, it replaces preceeding paths (similar to `path.resolve` in NodeJS).
193
+ * absolute path, it replaces preceding paths (similar to `path.resolve` in NodeJS).
196
194
  * Trailing directory separators are removed, and all directory separators are converted
197
195
  * to POSIX-style separators (`/`).
198
196
  */
@@ -257,10 +255,10 @@ export declare class Utils {
257
255
  static keys<T extends object>(obj: T): (keyof T)[];
258
256
  static values<T extends object>(obj: T): T[keyof T][];
259
257
  static entries<T extends object>(obj: T): [keyof T, T[keyof T]][];
260
- static isRawSql(value: unknown): value is {
258
+ static isRawSql<T = {
261
259
  sql: string;
262
260
  params: unknown[];
263
261
  use: () => void;
264
- };
262
+ }>(value: unknown): value is T;
265
263
  static primaryKeyToObject<T>(meta: EntityMetadata<T>, primaryKey: Primary<T> | T, visible?: (keyof T)[]): T;
266
264
  }