@mikro-orm/core 7.2.0-dev.13 → 7.2.0-dev.15
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.
- package/EntityManager.d.ts +30 -2
- package/EntityManager.js +214 -43
- package/MikroORM.js +3 -0
- package/connections/Connection.d.ts +3 -1
- package/drivers/IDatabaseDriver.d.ts +1 -0
- package/entity/Collection.js +4 -2
- package/entity/EntityFactory.js +6 -0
- package/entity/EntityLoader.js +12 -7
- package/entity/EntityRepository.js +5 -1
- package/entity/defineEntity.d.ts +34 -13
- package/entity/defineEntity.js +1 -1
- package/enums.d.ts +3 -1
- package/errors.d.ts +32 -0
- package/errors.js +75 -0
- package/events/EventManager.js +6 -3
- package/exceptions.d.ts +5 -0
- package/exceptions.js +5 -0
- package/hydration/ObjectHydrator.d.ts +2 -0
- package/hydration/ObjectHydrator.js +12 -8
- package/index.d.ts +1 -1
- package/metadata/MetadataDiscovery.d.ts +1 -0
- package/metadata/MetadataDiscovery.js +70 -11
- package/metadata/MetadataStorage.js +17 -1
- package/metadata/types.d.ts +5 -1
- package/package.json +1 -1
- package/platforms/Platform.d.ts +12 -2
- package/platforms/Platform.js +43 -1
- package/types/Type.js +4 -4
- package/typings.d.ts +44 -2
- package/typings.js +24 -1
- package/unit-of-work/ChangeSetPersister.js +17 -13
- package/unit-of-work/UnitOfWork.js +11 -4
- package/utils/Configuration.d.ts +15 -1
- package/utils/Configuration.js +11 -1
- package/utils/DataloaderUtils.js +2 -1
- package/utils/EntityComparator.d.ts +2 -0
- package/utils/EntityComparator.js +7 -3
- package/utils/QueryHelper.d.ts +12 -0
- package/utils/QueryHelper.js +75 -4
- package/utils/TransactionManager.js +1 -1
- package/utils/Utils.d.ts +14 -2
- package/utils/Utils.js +24 -2
- package/utils/env-vars.js +1 -0
- package/utils/index.d.ts +1 -0
- package/utils/index.js +1 -0
- package/utils/rls-utils.d.ts +35 -0
- package/utils/rls-utils.js +97 -0
- package/utils/upsert-utils.d.ts +9 -1
- package/utils/upsert-utils.js +26 -3
package/entity/EntityLoader.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { QueryHelper } from '../utils/QueryHelper.js';
|
|
2
|
-
import { Utils } from '../utils/Utils.js';
|
|
2
|
+
import { DANGEROUS_PROPERTY_NAMES, Utils } from '../utils/Utils.js';
|
|
3
3
|
import { ValidationError } from '../errors.js';
|
|
4
4
|
import { LoadStrategy, PopulatePath, ReferenceKind, } from '../enums.js';
|
|
5
5
|
import { Reference } from './Reference.js';
|
|
@@ -124,10 +124,10 @@ export class EntityLoader {
|
|
|
124
124
|
mergeNestedPopulate(populate) {
|
|
125
125
|
const tmp = populate.reduce((ret, item) => {
|
|
126
126
|
/* v8 ignore next */
|
|
127
|
-
if (item.field === PopulatePath.ALL) {
|
|
127
|
+
if (item.field === PopulatePath.ALL || DANGEROUS_PROPERTY_NAMES.includes(item.field)) {
|
|
128
128
|
return ret;
|
|
129
129
|
}
|
|
130
|
-
if (!ret
|
|
130
|
+
if (!Object.hasOwn(ret, item.field)) {
|
|
131
131
|
ret[item.field] = item;
|
|
132
132
|
return ret;
|
|
133
133
|
}
|
|
@@ -229,9 +229,10 @@ export class EntityLoader {
|
|
|
229
229
|
}
|
|
230
230
|
toPopulate.push(entity);
|
|
231
231
|
}
|
|
232
|
-
else if (refValue == null && !helper(entity).__loadedProperties.has(prop.name)) {
|
|
232
|
+
else if (refValue == null && !prop.object && !helper(entity).__loadedProperties.has(prop.name)) {
|
|
233
233
|
// FK columns weren't loaded (partial loading) — need to re-fetch them.
|
|
234
234
|
// If the property IS in __loadedProperties, the FK was loaded and is genuinely null.
|
|
235
|
+
// Object-embedded virtual props are skipped — they are populated via the embeddable instance.
|
|
235
236
|
needsFkLoad.push(entity);
|
|
236
237
|
}
|
|
237
238
|
}
|
|
@@ -445,7 +446,10 @@ export class EntityLoader {
|
|
|
445
446
|
}
|
|
446
447
|
}
|
|
447
448
|
}
|
|
448
|
-
|
|
449
|
+
// a missing target row means an orphaned reference, unless the query was narrowed by a populate condition
|
|
450
|
+
if ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind) &&
|
|
451
|
+
items.length !== children.length &&
|
|
452
|
+
Utils.isEmpty(options.where)) {
|
|
449
453
|
const nullVal = this.#em.config.get('forceUndefined') ? undefined : null;
|
|
450
454
|
const itemsMap = new Set();
|
|
451
455
|
const childrenMap = new Set();
|
|
@@ -620,7 +624,7 @@ export class EntityLoader {
|
|
|
620
624
|
if (!Utils.isEmpty(prop.where)) {
|
|
621
625
|
where = { $and: [where, prop.where] };
|
|
622
626
|
}
|
|
623
|
-
const map = await this.#driver.loadFromPivotTable(prop, ids, where, orderBy,
|
|
627
|
+
const map = await this.#em.withSessionContext(this.#em.getTransactionContext(), ctx => this.#driver.loadFromPivotTable(prop, ids, where, orderBy, ctx, options2, pivotJoin));
|
|
624
628
|
const children = [];
|
|
625
629
|
const isUnionTargetMN = QueryHelper.isUnionTargetPolymorphic(prop);
|
|
626
630
|
for (let i = 0; i < filtered.length; i++) {
|
|
@@ -667,7 +671,8 @@ export class EntityLoader {
|
|
|
667
671
|
}
|
|
668
672
|
return cond;
|
|
669
673
|
});
|
|
670
|
-
|
|
674
|
+
// partial extraction from `$or` is unsound — the parent may have matched via a dropped branch
|
|
675
|
+
if (child.length > 0 && (op === '$and' || child.length === where[op].length)) {
|
|
671
676
|
subCond[op] = child;
|
|
672
677
|
}
|
|
673
678
|
}
|
|
@@ -224,7 +224,11 @@ export class EntityRepository {
|
|
|
224
224
|
}
|
|
225
225
|
const entityName = entities[0].constructor.name;
|
|
226
226
|
const repoType = Utils.className(this.entityName);
|
|
227
|
-
|
|
227
|
+
// compare class identity where possible, as minifiers can mangle two classes to the same name
|
|
228
|
+
const entityMeta = entities[0].__meta;
|
|
229
|
+
const repoMeta = this.getEntityManager().getMetadata?.().find(this.entityName);
|
|
230
|
+
const mismatch = entityMeta && repoMeta ? entityMeta.class !== repoMeta.class : entityName && repoType !== entityName;
|
|
231
|
+
if (mismatch) {
|
|
228
232
|
throw ValidationError.fromWrongRepositoryType(entityName, repoType, method);
|
|
229
233
|
}
|
|
230
234
|
}
|
package/entity/defineEntity.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { EntityManager } from '../EntityManager.js';
|
|
2
2
|
import type { ColumnType, PropertyOptions, ReferenceOptions, EnumOptions, EmbeddedOptions, ManyToOneOptions, OneToManyOptions, OneToOneOptions, ManyToManyOptions, IndexColumnOptions } from '../metadata/types.js';
|
|
3
|
-
import type { AnyString, GeneratedColumnCallback, Constructor, CheckCallback, FilterQuery, EntityName, Dictionary, EntityMetadata, PrimaryKeyProp, EntityRepositoryType, Hidden, Opt, Primary, EntityClass, EntitySchemaWithMeta, InferEntity, MaybeReturnType, Ref, LazyRef, IndexCallback, TriggerCallback, FormulaCallback, EntityCtor, IsNever, IWrappedEntity, DefineConfig, Config, MaybePromise, IndexHints, ExtractDefineEntityProperties } from '../typings.js';
|
|
3
|
+
import type { AnyString, GeneratedColumnCallback, Constructor, CheckCallback, FilterQuery, EntityName, Dictionary, EntityMetadata, PrimaryKeyProp, EntityRepositoryType, Hidden, Opt, Primary, EntityClass, EntitySchemaWithMeta, InferEntity, MaybeReturnType, Ref, LazyRef, IndexCallback, TriggerCallback, FormulaCallback, EntityCtor, IsNever, IWrappedEntity, DefineConfig, Config, MaybePromise, IndexHints, OptionalProps, ExtractDefineEntityProperties } from '../typings.js';
|
|
4
4
|
import type { Raw } from '../utils/RawQueryFragment.js';
|
|
5
5
|
import type { ScalarReference } from './Reference.js';
|
|
6
6
|
import type { SerializeOptions } from '../serialization/EntitySerializer.js';
|
|
@@ -22,7 +22,7 @@ type HasKind<Options, K extends string> = Options extends {
|
|
|
22
22
|
kind: infer X extends string;
|
|
23
23
|
} ? X extends K ? true : false : false;
|
|
24
24
|
/** Lightweight chain result type for property builders - reduces type instantiation cost by avoiding full class resolution. */
|
|
25
|
-
export interface PropertyChain<Value, Options> {
|
|
25
|
+
export interface PropertyChain<in out Value, in out Options> {
|
|
26
26
|
'~type'?: {
|
|
27
27
|
value: Value;
|
|
28
28
|
};
|
|
@@ -112,7 +112,7 @@ export interface PropertyChain<Value, Options> {
|
|
|
112
112
|
getter(getter?: boolean): PropertyChain<Value, Options>;
|
|
113
113
|
getterName(getterName: string): PropertyChain<Value, Options>;
|
|
114
114
|
serializedPrimaryKey(serializedPrimaryKey?: boolean): PropertyChain<Value, Options>;
|
|
115
|
-
serializer(serializer: (value: Value, options?: SerializeOptions<any>) => any): PropertyChain<Value, Options>;
|
|
115
|
+
serializer(serializer: (value: SerializerValue<Value, Options>, options?: SerializeOptions<any>) => any): PropertyChain<Value, Options>;
|
|
116
116
|
serializedName(serializedName: string): PropertyChain<Value, Options>;
|
|
117
117
|
groups(...groups: string[]): PropertyChain<Value, Options>;
|
|
118
118
|
customOrder(...customOrder: string[] | number[] | boolean[]): PropertyChain<Value, Options>;
|
|
@@ -180,7 +180,7 @@ export interface PropertyChain<Value, Options> {
|
|
|
180
180
|
foreignKeyName(foreignKeyName: string): HasKind<Options, 'm:1' | '1:m' | '1:1' | 'm:n'> extends true ? PropertyChain<Value, Options> : never;
|
|
181
181
|
}
|
|
182
182
|
/** @internal */
|
|
183
|
-
export declare class UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys extends BuilderKeys> implements Record<Exclude<UniversalPropertyKeys, ExcludeKeys>, any> {
|
|
183
|
+
export declare class UniversalPropertyOptionsBuilder<in out Value, in out Options, in out IncludeKeys extends BuilderKeys> implements Record<Exclude<UniversalPropertyKeys, ExcludeKeys>, any> {
|
|
184
184
|
'~options': Options;
|
|
185
185
|
'~type'?: {
|
|
186
186
|
value: Value;
|
|
@@ -627,7 +627,7 @@ type PartialWhere<TProperties, TBase> = string | FilterQuery<{
|
|
|
627
627
|
[K in AllKeys<TProperties, TBase> & string]?: unknown;
|
|
628
628
|
}>;
|
|
629
629
|
/** Metadata descriptor for `defineEntity()`, combining entity options with property definitions. */
|
|
630
|
-
export interface EntityMetadataWithProperties<TName extends string, TTableName extends string, TProperties extends Record<string, any>, TPK extends (keyof TProperties)[] | undefined = undefined, TBase = never, TRepository = never, TForceObject extends boolean = false, TDiscriminatorColumn extends string | undefined = undefined, TDiscriminatorValue extends string | number | undefined = undefined, TBaseDiscriminatorColumn extends string | undefined = undefined> extends Omit<Partial<EntityMetadata<InferEntityFromProperties<TProperties, TPK, TBase, TRepository>>>, 'properties' | 'extends' | 'primaryKeys' | 'hooks' | 'discriminator' | 'discriminatorColumn' | 'discriminatorValue' | 'versionProperty' | 'concurrencyCheckKeys' | 'serializedPrimaryKey' | 'indexes' | 'uniques' | 'triggers' | 'repository' | 'filters' | 'orderBy'> {
|
|
630
|
+
export interface EntityMetadataWithProperties<TName extends string, TTableName extends string, TProperties extends Record<string, any>, TPK extends (keyof TProperties)[] | undefined = undefined, TBase = never, TRepository = never, TForceObject extends boolean = false, TDiscriminatorColumn extends string | undefined = undefined, TDiscriminatorValue extends string | number | undefined = undefined, TBaseDiscriminatorColumn extends string | undefined = undefined, TEmbeddable extends boolean = false> extends Omit<Partial<EntityMetadata<InferEntityFromProperties<TProperties, TPK, TBase, TRepository>>>, 'properties' | 'extends' | 'primaryKeys' | 'hooks' | 'discriminator' | 'discriminatorColumn' | 'discriminatorValue' | 'versionProperty' | 'concurrencyCheckKeys' | 'serializedPrimaryKey' | 'indexes' | 'uniques' | 'triggers' | 'repository' | 'filters' | 'orderBy'> {
|
|
631
631
|
name: TName;
|
|
632
632
|
tableName?: TTableName;
|
|
633
633
|
extends?: {
|
|
@@ -647,8 +647,12 @@ export interface EntityMetadataWithProperties<TName extends string, TTableName e
|
|
|
647
647
|
entity?: EntityName<any> | EntityName<any>[];
|
|
648
648
|
args?: boolean;
|
|
649
649
|
strict?: boolean;
|
|
650
|
+
rls?: boolean | {
|
|
651
|
+
setting?: string;
|
|
652
|
+
};
|
|
650
653
|
}>;
|
|
651
654
|
forceObject?: TForceObject;
|
|
655
|
+
embeddable?: TEmbeddable;
|
|
652
656
|
inheritance?: 'tpt';
|
|
653
657
|
orderBy?: {
|
|
654
658
|
[K in Extract<AllKeys<TProperties, TBase>, string>]?: QueryOrderKeysFlat;
|
|
@@ -699,7 +703,7 @@ export interface EntityMetadataWithProperties<TName extends string, TTableName e
|
|
|
699
703
|
}[];
|
|
700
704
|
}
|
|
701
705
|
/** Defines an entity schema using property builders, with full type inference from the property definitions. */
|
|
702
|
-
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, const TForceObject extends boolean = false, const TDiscriminatorColumn extends string | undefined = undefined, const TDiscriminatorValue extends string | number | undefined = undefined, const TBaseDiscriminatorColumn extends string | undefined = undefined>(meta: EntityMetadataWithProperties<TName, TTableName, TProperties, TPK, TBase, TRepository, TForceObject, TDiscriminatorColumn, TDiscriminatorValue, TBaseDiscriminatorColumn>): EntitySchemaWithMeta<TName, TTableName, InferEntityFromProperties<TProperties, TPK, TBase, TRepository, TForceObject, TBaseDiscriminatorColumn, TDiscriminatorValue>, TBase, TProperties, EntityCtor<InferEntityFromProperties<TProperties, TPK, TBase, TRepository, TForceObject, TBaseDiscriminatorColumn, TDiscriminatorValue>>, TDiscriminatorColumn>;
|
|
706
|
+
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, const TForceObject extends boolean = false, const TDiscriminatorColumn extends string | undefined = undefined, const TDiscriminatorValue extends string | number | undefined = undefined, const TBaseDiscriminatorColumn extends string | undefined = undefined, const TEmbeddable extends boolean = false>(meta: EntityMetadataWithProperties<TName, TTableName, TProperties, TPK, TBase, TRepository, TForceObject, TDiscriminatorColumn, TDiscriminatorValue, TBaseDiscriminatorColumn, TEmbeddable>): EntitySchemaWithMeta<TName, TTableName, InferEntityFromProperties<TProperties, TPK, TBase, TRepository, TForceObject, TBaseDiscriminatorColumn, TDiscriminatorValue, TEmbeddable>, TBase, TProperties, EntityCtor<InferEntityFromProperties<TProperties, TPK, TBase, TRepository, TForceObject, TBaseDiscriminatorColumn, TDiscriminatorValue, TEmbeddable>>, TDiscriminatorColumn>;
|
|
703
707
|
export declare namespace defineEntity {
|
|
704
708
|
export { propertyBuilders as properties };
|
|
705
709
|
}
|
|
@@ -734,22 +738,24 @@ type InferTypeByString<T extends string> = T extends keyof typeof types ? InferJ
|
|
|
734
738
|
type InferJSType<T> = T extends typeof Type<infer TValue, any> ? NonNullable<TValue> : never;
|
|
735
739
|
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;
|
|
736
740
|
type BaseEntityMethodKeys = 'toObject' | 'toPOJO' | 'serialize' | 'assign' | 'populate' | 'init' | 'toReference';
|
|
741
|
+
interface BaseEntityMethods<in out Entity extends object> extends Pick<IWrappedEntity<Entity>, BaseEntityMethodKeys> {
|
|
742
|
+
}
|
|
737
743
|
/** Infers the entity type from a `defineEntity()` properties map, resolving builders, base classes, and primary keys. */
|
|
738
|
-
export type InferEntityFromProperties<Properties extends Record<string, any>, PK extends (keyof Properties)[] | undefined = undefined, Base = never, Repository = never, ForceObject extends boolean = false, BaseDiscriminatorColumn extends string | undefined = undefined, DiscriminatorValue extends string | number | undefined = undefined> = (IsNever<Base> extends true ? {} : Base extends {
|
|
744
|
+
export type InferEntityFromProperties<Properties extends Record<string, any>, PK extends (keyof Properties)[] | undefined = undefined, Base = never, Repository = never, ForceObject extends boolean = false, BaseDiscriminatorColumn extends string | undefined = undefined, DiscriminatorValue extends string | number | undefined = undefined, Embeddable extends boolean = false> = (IsNever<Base> extends true ? {} : Base extends {
|
|
739
745
|
toObject(...args: any[]): any;
|
|
740
|
-
} ?
|
|
746
|
+
} ? BaseEntityMethods<{
|
|
741
747
|
-readonly [K in keyof Properties]: InferBuilderValue<MaybeReturnType<Properties[K]>>;
|
|
742
748
|
} & {
|
|
743
749
|
[PrimaryKeyProp]?: InferCombinedPrimaryKey<Properties, PK, Base>;
|
|
744
750
|
} & (IsNever<Repository> extends true ? {} : {
|
|
745
751
|
[EntityRepositoryType]?: Repository extends Constructor<infer R> ? R : Repository;
|
|
746
|
-
}) & NarrowDiscriminator<Omit<Base, typeof PrimaryKeyProp>, BaseDiscriminatorColumn, DiscriminatorValue
|
|
752
|
+
}) & NarrowDiscriminator<Omit<Base, typeof PrimaryKeyProp>, BaseDiscriminatorColumn, DiscriminatorValue, Embeddable>> : {}) & {
|
|
747
753
|
-readonly [K in keyof Properties]: InferBuilderValue<MaybeReturnType<Properties[K]>>;
|
|
748
754
|
} & {
|
|
749
755
|
[PrimaryKeyProp]?: InferCombinedPrimaryKey<Properties, PK, Base>;
|
|
750
756
|
} & (IsNever<Repository> extends true ? {} : {
|
|
751
757
|
[EntityRepositoryType]?: Repository extends Constructor<infer R> ? R : Repository;
|
|
752
|
-
}) & (IsNever<Base> extends true ? {} : NarrowDiscriminator<Omit<Base, typeof PrimaryKeyProp>, BaseDiscriminatorColumn, DiscriminatorValue>) & (ForceObject extends true ? {
|
|
758
|
+
}) & (IsNever<Base> extends true ? {} : NarrowDiscriminator<Omit<Base, typeof PrimaryKeyProp>, BaseDiscriminatorColumn, DiscriminatorValue, Embeddable>) & (ForceObject extends true ? {
|
|
753
759
|
[Config]?: DefineConfig<{
|
|
754
760
|
forceObject: true;
|
|
755
761
|
}>;
|
|
@@ -757,13 +763,26 @@ export type InferEntityFromProperties<Properties extends Record<string, any>, PK
|
|
|
757
763
|
[IndexHints]?: [Omit<ExtractBaseProperties<Base>, keyof Properties> & Properties];
|
|
758
764
|
};
|
|
759
765
|
type ExtractBaseProperties<Base> = [ExtractDefineEntityProperties<Base>] extends [infer P extends Record<string, any>] ? [P] extends [never] ? {} : P : {};
|
|
760
|
-
type
|
|
766
|
+
type ExtractOptionalProps<Base> = Base extends {
|
|
767
|
+
[OptionalProps]?: infer K;
|
|
768
|
+
} ? (K extends string ? K : never) : never;
|
|
769
|
+
type NarrowDiscriminator<Base, DiscColumn extends string | undefined, DiscValue, Embeddable extends boolean = false> = DiscColumn extends string ? DiscColumn extends keyof Base ? DiscValue extends string | number ? Embeddable extends true ? Omit<Base, DiscColumn> & {
|
|
761
770
|
[K in DiscColumn]: DiscValue;
|
|
771
|
+
} : Omit<Base, DiscColumn | typeof OptionalProps> & {
|
|
772
|
+
[K in DiscColumn]: DiscValue;
|
|
773
|
+
} & {
|
|
774
|
+
[OptionalProps]?: DiscColumn | ExtractOptionalProps<Base>;
|
|
762
775
|
} : Base : Base : Base;
|
|
763
776
|
type InferCombinedPrimaryKey<Properties extends Record<string, any>, PK, Base> = PK extends undefined ? CombinePrimaryKeys<InferPrimaryKey<Properties>, ExtractBasePrimaryKey<Base>> : PK;
|
|
764
|
-
type ExtractBasePrimaryKey<Base> = Base extends {
|
|
777
|
+
type ExtractBasePrimaryKey<Base> = typeof PrimaryKeyProp extends keyof Base ? Base extends {
|
|
765
778
|
[PrimaryKeyProp]?: infer BasePK;
|
|
766
|
-
} ? BasePK : never
|
|
779
|
+
} ? BasePK : never : [keyof Base] extends [never] ? never : Base extends {
|
|
780
|
+
_id?: any;
|
|
781
|
+
} ? '_id' : Base extends {
|
|
782
|
+
id?: any;
|
|
783
|
+
} ? 'id' : Base extends {
|
|
784
|
+
uuid?: any;
|
|
785
|
+
} ? 'uuid' : never;
|
|
767
786
|
type CombinePrimaryKeys<ChildPK, BasePK> = [ChildPK] extends [never] ? BasePK : [BasePK] extends [never] ? IsUnion<ChildPK> extends true ? ChildPK[] : ChildPK : ChildPK | BasePK;
|
|
768
787
|
/** Extracts the primary key property names from a properties map by finding builders with `primary: true`. */
|
|
769
788
|
export type InferPrimaryKey<Properties extends Record<string, any>> = {
|
|
@@ -790,6 +809,8 @@ type InferBuilderValue<Builder> = Builder extends {
|
|
|
790
809
|
type MaybeArray<Value, Options> = Options extends {
|
|
791
810
|
array: true;
|
|
792
811
|
} ? Value[] : Value;
|
|
812
|
+
/** The runtime value passed to a custom serializer — the property value as stored on the entity (e.g. `Collection`/`Ref` for relations). Skips `MaybeMapToPk`, as its `Primary<Value>` branch is too costly for the type checker. */
|
|
813
|
+
type SerializerValue<Value, Options> = MaybeNullable<MaybeRelationRef<MaybeArray<Value, Options>, Options>, Options>;
|
|
793
814
|
type MaybeMapToPk<Value, Options> = Options extends {
|
|
794
815
|
mapToPk: true;
|
|
795
816
|
} ? Primary<Value> : Value;
|
package/entity/defineEntity.js
CHANGED
|
@@ -496,7 +496,7 @@ export class StringPropertyOptionsBuilder extends UniversalPropertyOptionsBuilde
|
|
|
496
496
|
export class OneToManyOptionsBuilderOnlyMappedBy extends UniversalPropertyOptionsBuilder {
|
|
497
497
|
/** Point to the owning side property name. */
|
|
498
498
|
mappedBy(mappedBy) {
|
|
499
|
-
return
|
|
499
|
+
return this.assignOptions({ mappedBy });
|
|
500
500
|
}
|
|
501
501
|
}
|
|
502
502
|
function createPropertyBuilders(options) {
|
package/enums.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityKey, ExpandProperty } from './typings.js';
|
|
1
|
+
import type { EntityKey, ExpandProperty, SessionContext } from './typings.js';
|
|
2
2
|
import type { InflightQueryAbortStrategy, Transaction } from './connections/Connection.js';
|
|
3
3
|
import type { LogContext } from './logging/Logger.js';
|
|
4
4
|
/** Controls when the `EntityManager` flushes pending changes to the database. */
|
|
@@ -307,6 +307,8 @@ export interface TransactionOptions {
|
|
|
307
307
|
flushMode?: FlushMode | `${FlushMode}`;
|
|
308
308
|
ignoreNestedTransactions?: boolean;
|
|
309
309
|
loggerContext?: LogContext;
|
|
310
|
+
/** @internal database session context applied on `begin()` (set via `em.setSessionContext()`). */
|
|
311
|
+
sessionContext?: SessionContext;
|
|
310
312
|
/**
|
|
311
313
|
* `AbortSignal` cancelling every query within the transaction (including the implicit flush).
|
|
312
314
|
* Cancelling mid-transaction triggers a rollback once the in-flight query settles.
|
package/errors.d.ts
CHANGED
|
@@ -25,6 +25,13 @@ export declare class ValidationError<T extends AnyEntity = AnyEntity> extends Er
|
|
|
25
25
|
static invalidCompositeIdentifier(meta: EntityMetadata): ValidationError;
|
|
26
26
|
static cannotCommit(): ValidationError;
|
|
27
27
|
static cannotUseGlobalContext(): ValidationError;
|
|
28
|
+
static sessionContextNotSupported(): ValidationError;
|
|
29
|
+
static sessionContextRequiresImplicitTransactions(): ValidationError;
|
|
30
|
+
static sessionContextWithDisabledTransactions(): ValidationError;
|
|
31
|
+
static sessionContextInsideTransaction(action?: 'set' | 'clear'): ValidationError;
|
|
32
|
+
static cannotStageNonScalarSessionVariable(filterName: string, argName: string): ValidationError;
|
|
33
|
+
static sessionContextStreamRequiresTransaction(): ValidationError;
|
|
34
|
+
static connectionSessionContextNotSupported(): ValidationError;
|
|
28
35
|
static cannotUseOperatorsInsideEmbeddables(entityName: EntityName, propName: string, payload: unknown): ValidationError;
|
|
29
36
|
static cannotUseGroupOperatorsInsideScalars(entityName: EntityName, propName: string, payload: unknown): ValidationError;
|
|
30
37
|
static invalidEmbeddableQuery(entityName: EntityName, propName: string, embeddableType: string): ValidationError;
|
|
@@ -60,6 +67,7 @@ export declare class MetadataError<T extends AnyEntity = AnyEntity> extends Vali
|
|
|
60
67
|
static duplicateFieldName(entityName: EntityName, names: [string, string][]): MetadataError;
|
|
61
68
|
static multipleDecorators(entityName: string, propertyName: string): MetadataError;
|
|
62
69
|
static missingMetadata(entity: string): MetadataError;
|
|
70
|
+
static ambiguousEntityName(className: string): MetadataError;
|
|
63
71
|
static invalidPrimaryKey(meta: EntityMetadata, prop: EntityProperty, requiredName: string): MetadataError;
|
|
64
72
|
static invalidManyToManyWithPivotEntity(meta1: EntityMetadata, prop1: EntityProperty, meta2: EntityMetadata, prop2: EntityProperty): MetadataError;
|
|
65
73
|
static targetIsAbstract(meta: EntityMetadata, prop: EntityProperty): MetadataError;
|
|
@@ -76,6 +84,30 @@ export declare class MetadataError<T extends AnyEntity = AnyEntity> extends Vali
|
|
|
76
84
|
static tptNotSupportedByDriver(meta: EntityMetadata): MetadataError;
|
|
77
85
|
/** Thrown when database triggers are defined on an entity using a driver that does not support them. */
|
|
78
86
|
static triggersNotSupportedByDriver(meta: EntityMetadata): MetadataError;
|
|
87
|
+
/** Thrown when row level security is declared on an entity using a driver that does not support it. */
|
|
88
|
+
static rowLevelSecurityNotSupportedByDriver(meta: EntityMetadata): MetadataError;
|
|
89
|
+
/** Thrown when row level security is declared on a non-root entity of an STI hierarchy. */
|
|
90
|
+
static rowLevelSecurityOnNonRootStiEntity(meta: EntityMetadata): MetadataError;
|
|
91
|
+
/** Thrown when two policies on the same entity are given the same explicit name. */
|
|
92
|
+
static duplicatePolicyName(meta: EntityMetadata, name: string): MetadataError;
|
|
93
|
+
/** Thrown when a filter flagged with `rls` is declared on a driver that does not support row level security. */
|
|
94
|
+
static rlsFilterNotSupportedByDriver(meta: EntityMetadata, filterName: string): MetadataError;
|
|
95
|
+
/** Thrown when a filter flagged with `rls` is declared on a non-root entity of an STI hierarchy. */
|
|
96
|
+
static rlsFilterOnNonRootStiEntity(meta: EntityMetadata, filterName: string): MetadataError;
|
|
97
|
+
/** Thrown when a global (config or EM registered) filter is flagged with `rls`; RLS filters must be entity scoped. */
|
|
98
|
+
static rlsFilterMustBeEntityScoped(filterName: string): MetadataError;
|
|
99
|
+
/** Thrown when an entity-scoped `rls` filter is registered at runtime via `em.addFilter()` instead of in metadata. */
|
|
100
|
+
static rlsFilterCannotBeRegisteredAtRuntime(filterName: string): MetadataError;
|
|
101
|
+
/** Thrown when a filter's custom `setting` is used with more than one argument. */
|
|
102
|
+
static rlsFilterMultiArgSetting(filterName: string, args: string[]): MetadataError;
|
|
103
|
+
/** Thrown when an `rls` filter's condition depends on runtime state and cannot be compiled to a static policy. */
|
|
104
|
+
static rlsFilterDependsOnRuntimeState(filterName: string): MetadataError;
|
|
105
|
+
/** Thrown when an `rls` filter compares against a column whose type has no automatic session-variable cast. */
|
|
106
|
+
static rlsFilterUncastableType(filterName: string, columnType: string): MetadataError;
|
|
107
|
+
/** Thrown when an `rls` filter references an argument outside of a direct comparison, which cannot be compiled. */
|
|
108
|
+
static rlsFilterUnsupportedCond(filterName: string): MetadataError;
|
|
109
|
+
/** Thrown when an `rls` filter compares against a column the schema generator does not manage. */
|
|
110
|
+
static rlsFilterUnmanagedColumn(filterName: string, column: string): MetadataError;
|
|
79
111
|
private static fromMessage;
|
|
80
112
|
}
|
|
81
113
|
/** Error thrown when an entity lookup fails to find the expected result. */
|
package/errors.js
CHANGED
|
@@ -94,6 +94,30 @@ export class ValidationError extends Error {
|
|
|
94
94
|
static cannotUseGlobalContext() {
|
|
95
95
|
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.");
|
|
96
96
|
}
|
|
97
|
+
static sessionContextNotSupported() {
|
|
98
|
+
return new ValidationError('Database session context (row level security) is only supported by the PostgreSQL driver. To test a PostgreSQL app without a server, use the `@mikro-orm/pglite` driver instead of sqlite.');
|
|
99
|
+
}
|
|
100
|
+
static sessionContextRequiresImplicitTransactions() {
|
|
101
|
+
return new ValidationError("Cannot set a database session context (row level security) with the 'transaction' strategy while 'implicitTransactions' is disabled. The context is applied on transaction begin, but writes would run without a transaction and silently bypass the policies. Enable 'implicitTransactions', wrap the work in 'em.transactional()', or use the 'connection' session context strategy.");
|
|
102
|
+
}
|
|
103
|
+
static sessionContextWithDisabledTransactions() {
|
|
104
|
+
return new ValidationError("Cannot set a database session context (row level security) with the 'transaction' strategy while transactions are disabled via 'disableTransactions'. The context is applied on transaction begin, so flushes would run without it and silently bypass the policies. Enable transactions, or use the 'connection' session context strategy.");
|
|
105
|
+
}
|
|
106
|
+
static sessionContextInsideTransaction(action = 'set') {
|
|
107
|
+
const advice = action === 'set'
|
|
108
|
+
? "Set the session context before starting the transaction (e.g. via 'em.fork({ session })')."
|
|
109
|
+
: 'Clear the session context outside the transaction.';
|
|
110
|
+
return new ValidationError(`Cannot ${action} a database session context (row level security) inside an active transaction. The context is applied when the transaction begins or the connection is reserved, so the change would never reach an already-open transaction (with the 'connection' strategy the pinned connection was reserved with the previous context). ${advice}`);
|
|
111
|
+
}
|
|
112
|
+
static cannotStageNonScalarSessionVariable(filterName, argName) {
|
|
113
|
+
return new ValidationError(`Cannot stage the '${argName}' argument of filter '${filterName}' as a session variable (row level security) — only scalar values (string, number, boolean, Date) can be mirrored to the database policy backing the filter.`);
|
|
114
|
+
}
|
|
115
|
+
static sessionContextStreamRequiresTransaction() {
|
|
116
|
+
return new ValidationError("Cannot stream under a database session context (row level security) with the 'transaction' strategy outside a transaction. Streaming never opens the implicit transaction that applies the context, so the streamed rows would not be scoped by it (other tenants' rows would leak). Wrap the stream in 'em.transactional()', or use the 'connection' session context strategy.");
|
|
117
|
+
}
|
|
118
|
+
static connectionSessionContextNotSupported() {
|
|
119
|
+
return new ValidationError("The 'connection' session context strategy requires a driver that supports per-acquire connection hooks (the `postgresql` driver). Use the default 'transaction' strategy instead.");
|
|
120
|
+
}
|
|
97
121
|
static cannotUseOperatorsInsideEmbeddables(entityName, propName, payload) {
|
|
98
122
|
return new ValidationError(`Using operators inside embeddables is not allowed, move the operator above. (property: ${Utils.className(entityName)}.${propName}, payload: ${inspect(payload)})`);
|
|
99
123
|
}
|
|
@@ -195,6 +219,9 @@ export class MetadataError extends ValidationError {
|
|
|
195
219
|
static missingMetadata(entity) {
|
|
196
220
|
return new MetadataError(`Metadata for entity ${entity} not found`);
|
|
197
221
|
}
|
|
222
|
+
static ambiguousEntityName(className) {
|
|
223
|
+
return new MetadataError(`Entity name '${className}' is ambiguous, multiple discovered entity classes share it (possibly due to a minifier mangling class names). Use a class reference instead of a string name.`);
|
|
224
|
+
}
|
|
198
225
|
static invalidPrimaryKey(meta, prop, requiredName) {
|
|
199
226
|
return this.fromMessage(meta, prop, `has wrong field name, '${requiredName}' is required in current driver`);
|
|
200
227
|
}
|
|
@@ -247,6 +274,54 @@ export class MetadataError extends ValidationError {
|
|
|
247
274
|
static triggersNotSupportedByDriver(meta) {
|
|
248
275
|
return new MetadataError(`Entity ${meta.className} defines database triggers which are not supported by the current driver. Triggers are only available with SQL drivers.`);
|
|
249
276
|
}
|
|
277
|
+
/** Thrown when row level security is declared on an entity using a driver that does not support it. */
|
|
278
|
+
static rowLevelSecurityNotSupportedByDriver(meta) {
|
|
279
|
+
return new MetadataError(`Entity ${meta.className} declares row level security which is not supported by the current driver. Row level security is only available with the PostgreSQL driver. To test a PostgreSQL app without a server, use the \`@mikro-orm/pglite\` driver instead of sqlite.`);
|
|
280
|
+
}
|
|
281
|
+
/** Thrown when row level security is declared on a non-root entity of an STI hierarchy. */
|
|
282
|
+
static rowLevelSecurityOnNonRootStiEntity(meta) {
|
|
283
|
+
return new MetadataError(`Entity ${meta.className} declares row level security, but it is part of a single table inheritance hierarchy. Declare policies on the root entity ${meta.root.className} instead, as the whole hierarchy shares a single table.`);
|
|
284
|
+
}
|
|
285
|
+
/** Thrown when two policies on the same entity are given the same explicit name. */
|
|
286
|
+
static duplicatePolicyName(meta, name) {
|
|
287
|
+
return new MetadataError(`Entity ${meta.className} declares multiple row level security policies named '${name}'. Policy names must be unique per table; rename one of them or omit the name to use an auto-generated one.`);
|
|
288
|
+
}
|
|
289
|
+
/** Thrown when a filter flagged with `rls` is declared on a driver that does not support row level security. */
|
|
290
|
+
static rlsFilterNotSupportedByDriver(meta, filterName) {
|
|
291
|
+
return new MetadataError(`Filter '${filterName}' on entity ${meta.className} is flagged with 'rls', which is only supported by the PostgreSQL driver. To test a PostgreSQL app without a server, use the \`@mikro-orm/pglite\` driver instead of sqlite.`);
|
|
292
|
+
}
|
|
293
|
+
/** Thrown when a filter flagged with `rls` is declared on a non-root entity of an STI hierarchy. */
|
|
294
|
+
static rlsFilterOnNonRootStiEntity(meta, filterName) {
|
|
295
|
+
return new MetadataError(`Filter '${filterName}' on entity ${meta.className} is flagged with 'rls', but the entity is part of a single table inheritance hierarchy. Declare the filter on the root entity ${meta.root.className} instead, as the whole hierarchy shares a single table and the policy would never be created otherwise.`);
|
|
296
|
+
}
|
|
297
|
+
/** Thrown when a global (config or EM registered) filter is flagged with `rls`; RLS filters must be entity scoped. */
|
|
298
|
+
static rlsFilterMustBeEntityScoped(filterName) {
|
|
299
|
+
return new MetadataError(`Filter '${filterName}' is a global filter and cannot be flagged with 'rls'. RLS filters must be declared on an entity via @Filter() so a policy can be attached to its table.`);
|
|
300
|
+
}
|
|
301
|
+
/** Thrown when an entity-scoped `rls` filter is registered at runtime via `em.addFilter()` instead of in metadata. */
|
|
302
|
+
static rlsFilterCannotBeRegisteredAtRuntime(filterName) {
|
|
303
|
+
return new MetadataError(`Filter '${filterName}' cannot be flagged with 'rls' when registered at runtime via 'em.addFilter()'. RLS filters must be declared in entity metadata via the @Filter() decorator (or the entity 'filters' option) so a policy can be attached to the table.`);
|
|
304
|
+
}
|
|
305
|
+
/** Thrown when a filter's custom `setting` is used with more than one argument. */
|
|
306
|
+
static rlsFilterMultiArgSetting(filterName, args) {
|
|
307
|
+
return new MetadataError(`Filter '${filterName}' sets a custom 'setting' but references multiple arguments (${args.join(', ')}). A custom 'setting' is only allowed for single-argument RLS filters; remove it to use the default 'mikro.${filterName}.<arg>' names.`);
|
|
308
|
+
}
|
|
309
|
+
/** Thrown when an `rls` filter's condition depends on runtime state and cannot be compiled to a static policy. */
|
|
310
|
+
static rlsFilterDependsOnRuntimeState(filterName) {
|
|
311
|
+
return new MetadataError(`Filter '${filterName}' cannot be compiled to an RLS policy because its condition depends on runtime state (it accesses 'em', 'type', 'options' or 'entityName', or resolves asynchronously). Declare an explicit policy instead.`);
|
|
312
|
+
}
|
|
313
|
+
/** Thrown when an `rls` filter compares against a column whose type has no automatic session-variable cast. */
|
|
314
|
+
static rlsFilterUncastableType(filterName, columnType) {
|
|
315
|
+
return new MetadataError(`Filter '${filterName}' cannot be compiled to an RLS policy because the column type '${columnType}' has no automatic session-variable cast. Declare an explicit policy instead.`);
|
|
316
|
+
}
|
|
317
|
+
/** Thrown when an `rls` filter references an argument outside of a direct comparison, which cannot be compiled. */
|
|
318
|
+
static rlsFilterUnsupportedCond(filterName) {
|
|
319
|
+
return new MetadataError(`Filter '${filterName}' cannot be compiled to an RLS policy because it references an argument outside of a direct comparison (only expressions like { prop: args.x } are supported). Declare an explicit policy instead.`);
|
|
320
|
+
}
|
|
321
|
+
/** Thrown when an `rls` filter compares against a column the schema generator does not manage. */
|
|
322
|
+
static rlsFilterUnmanagedColumn(filterName, column) {
|
|
323
|
+
return new MetadataError(`Filter '${filterName}' cannot be compiled to an RLS policy because column '${column}' is not part of the managed schema (e.g. the property is marked 'persist: false' or the column is excluded via 'skipColumns'). Declare an explicit policy instead.`);
|
|
324
|
+
}
|
|
250
325
|
static fromMessage(meta, prop, message) {
|
|
251
326
|
return new MetadataError(`${meta.className}.${prop.name} ${message}`);
|
|
252
327
|
}
|
package/events/EventManager.js
CHANGED
|
@@ -43,7 +43,10 @@ export class EventManager {
|
|
|
43
43
|
}));
|
|
44
44
|
for (const listener of this.#listeners[event] ?? new Set()) {
|
|
45
45
|
const entities = this.#entities.get(listener);
|
|
46
|
-
if (entities.size === 0 ||
|
|
46
|
+
if (entities.size === 0 ||
|
|
47
|
+
!entity ||
|
|
48
|
+
entities.has(entity.constructor) ||
|
|
49
|
+
entities.has(entity.constructor.name)) {
|
|
47
50
|
listeners.push(listener[event].bind(listener));
|
|
48
51
|
}
|
|
49
52
|
}
|
|
@@ -68,7 +71,7 @@ export class EventManager {
|
|
|
68
71
|
}
|
|
69
72
|
for (const listener of this.#listeners[event] ?? new Set()) {
|
|
70
73
|
const entities = this.#entities.get(listener);
|
|
71
|
-
if (entities.size === 0 || entities.has(meta.className)) {
|
|
74
|
+
if (entities.size === 0 || entities.has(meta.class) || entities.has(meta.className)) {
|
|
72
75
|
this.#cache.set(cacheKey, true);
|
|
73
76
|
return true;
|
|
74
77
|
}
|
|
@@ -84,6 +87,6 @@ export class EventManager {
|
|
|
84
87
|
if (!listener.getSubscribedEntities) {
|
|
85
88
|
return new Set();
|
|
86
89
|
}
|
|
87
|
-
return new Set(listener.getSubscribedEntities().map(name => Utils.
|
|
90
|
+
return new Set(listener.getSubscribedEntities().map(name => Utils.classOrName(name)));
|
|
88
91
|
}
|
|
89
92
|
}
|
package/exceptions.d.ts
CHANGED
|
@@ -102,3 +102,8 @@ export declare class TableNotFoundException extends DatabaseObjectNotFoundExcept
|
|
|
102
102
|
*/
|
|
103
103
|
export declare class UniqueConstraintViolationException extends ConstraintViolationException {
|
|
104
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* Exception for a row-level security policy violation (failed `WITH CHECK`) detected in the driver.
|
|
107
|
+
*/
|
|
108
|
+
export declare class RowLevelSecurityViolationException extends ConstraintViolationException {
|
|
109
|
+
}
|
package/exceptions.js
CHANGED
|
@@ -115,3 +115,8 @@ export class TableNotFoundException extends DatabaseObjectNotFoundException {
|
|
|
115
115
|
*/
|
|
116
116
|
export class UniqueConstraintViolationException extends ConstraintViolationException {
|
|
117
117
|
}
|
|
118
|
+
/**
|
|
119
|
+
* Exception for a row-level security policy violation (failed `WITH CHECK`) detected in the driver.
|
|
120
|
+
*/
|
|
121
|
+
export class RowLevelSecurityViolationException extends ConstraintViolationException {
|
|
122
|
+
}
|
|
@@ -19,6 +19,8 @@ export declare class ObjectHydrator extends Hydrator {
|
|
|
19
19
|
getEntityHydrator<T extends object>(meta: EntityMetadata<T>, type: 'full' | 'reference', normalizeAccessors?: boolean): EntityHydrator<T>;
|
|
20
20
|
private createCollectionItemMapper;
|
|
21
21
|
private wrap;
|
|
22
|
+
/** Renders a key as a single-quoted JS string literal, safe to embed in generated code. */
|
|
23
|
+
private quote;
|
|
22
24
|
private safeKey;
|
|
23
25
|
}
|
|
24
26
|
export {};
|
|
@@ -87,7 +87,7 @@ export class ObjectHydrator extends Hydrator {
|
|
|
87
87
|
ret.push(` if (data${dataKey} === null) {`);
|
|
88
88
|
if (prop.ref) {
|
|
89
89
|
ret.push(` entity${entityKey} = new ScalarReference();`);
|
|
90
|
-
ret.push(` entity${entityKey}.bind(entity,
|
|
90
|
+
ret.push(` entity${entityKey}.bind(entity, ${this.quote(prop.name)});`);
|
|
91
91
|
ret.push(` entity${entityKey}.set(${nullVal});`);
|
|
92
92
|
}
|
|
93
93
|
else {
|
|
@@ -127,14 +127,14 @@ export class ObjectHydrator extends Hydrator {
|
|
|
127
127
|
if (prop.ref) {
|
|
128
128
|
ret.push(` const value = isScalarReference(entity${entityKey}) ? entity${entityKey}.unwrap() : entity${entityKey};`);
|
|
129
129
|
ret.push(` entity${entityKey} = oldValue_${idx} ?? new ScalarReference(value);`);
|
|
130
|
-
ret.push(` entity${entityKey}.bind(entity,
|
|
130
|
+
ret.push(` entity${entityKey}.bind(entity, ${this.quote(prop.name)});`);
|
|
131
131
|
ret.push(` entity${entityKey}.set(value);`);
|
|
132
132
|
}
|
|
133
133
|
ret.push(` }`);
|
|
134
134
|
if (prop.ref) {
|
|
135
135
|
ret.push(` if (!entity${entityKey}) {`);
|
|
136
136
|
ret.push(` entity${entityKey} = new ScalarReference();`);
|
|
137
|
-
ret.push(` entity${entityKey}.bind(entity,
|
|
137
|
+
ret.push(` entity${entityKey}.bind(entity, ${this.quote(prop.name)});`);
|
|
138
138
|
ret.push(` }`);
|
|
139
139
|
}
|
|
140
140
|
return ret;
|
|
@@ -220,7 +220,7 @@ export class ObjectHydrator extends Hydrator {
|
|
|
220
220
|
ret.push(` }`);
|
|
221
221
|
ret.push(` if (Array.isArray(data${dataKey})) {`);
|
|
222
222
|
ret.push(` const items = data${dataKey}.map(value => createCollectionItem_${this.safeKey(prop.name)}(value, entity));`);
|
|
223
|
-
ret.push(` const coll = Collection.create(entity,
|
|
223
|
+
ret.push(` const coll = Collection.create(entity, ${this.quote(prop.name)}, items, newEntity);`);
|
|
224
224
|
ret.push(` if (newEntity) {`);
|
|
225
225
|
ret.push(` coll.setDirty();`);
|
|
226
226
|
ret.push(` } else {`);
|
|
@@ -231,11 +231,11 @@ export class ObjectHydrator extends Hydrator {
|
|
|
231
231
|
if (!this.platform.usesPivotTable() && prop.owner && prop.kind === ReferenceKind.MANY_TO_MANY) {
|
|
232
232
|
ret.push(` } else if (!entity${entityKey} && Array.isArray(data${dataKey})) {`);
|
|
233
233
|
const items = this.platform.usesPivotTable() || !prop.owner ? 'undefined' : '[]';
|
|
234
|
-
ret.push(` const coll = Collection.create(entity,
|
|
234
|
+
ret.push(` const coll = Collection.create(entity, ${this.quote(prop.name)}, ${items}, !!data${dataKey} || newEntity);`);
|
|
235
235
|
ret.push(` coll.setDirty(false);`);
|
|
236
236
|
}
|
|
237
237
|
ret.push(` } else if (!entity${entityKey}) {`);
|
|
238
|
-
ret.push(` const coll = Collection.create(entity,
|
|
238
|
+
ret.push(` const coll = Collection.create(entity, ${this.quote(prop.name)}, undefined, newEntity);`);
|
|
239
239
|
ret.push(` coll.setDirty(false);`);
|
|
240
240
|
ret.push(` }`);
|
|
241
241
|
return ret;
|
|
@@ -431,10 +431,14 @@ export class ObjectHydrator extends Hydrator {
|
|
|
431
431
|
return lines;
|
|
432
432
|
}
|
|
433
433
|
wrap(key) {
|
|
434
|
-
if (/^\[
|
|
434
|
+
if (/^\[idx_\d+]$/.exec(key)) {
|
|
435
435
|
return key;
|
|
436
436
|
}
|
|
437
|
-
return /^\w+$/.exec(key) ? `.${key}` : `[
|
|
437
|
+
return /^\w+$/.exec(key) ? `.${key}` : `[${this.quote(key)}]`;
|
|
438
|
+
}
|
|
439
|
+
/** Renders a key as a single-quoted JS string literal, safe to embed in generated code. */
|
|
440
|
+
quote(key) {
|
|
441
|
+
return `'${key.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
|
|
438
442
|
}
|
|
439
443
|
safeKey(key) {
|
|
440
444
|
return key.replace(/\W/g, '_');
|
package/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* @module core
|
|
4
4
|
*/
|
|
5
5
|
export { EntityMetadata, PrimaryKeyProp, EntityRepositoryType, OptionalProps, EagerProps, HiddenProps, Config, EntityName, IndexHints, } from './typings.js';
|
|
6
|
-
export type { CompiledFunctions, Constructor, ConnectionType, Dictionary, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, InferEntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, EntityDTOFlat, EntityDTOProp, SerializeDTO, MigrationDiff, GenerateOptions, FilterObject, IndexFilterQuery, ExtractIndexHints, ExtractDefineEntityProperties, IndexName, IndexColumns, WithUsingOptions, IMigrationRunner, IEntityGenerator, ISeedManager, SeederObject, IMigratorStorage, RequiredEntityData, CheckCallback, TriggerCallback, IndexCallback, FormulaCallback, FormulaColumns, FormulaTable, SchemaTable, SchemaColumns, SchemaColumnRef, EntityDataPropValue, SimpleColumnMeta, Rel, Ref, LazyRef, ScalarRef, EntityRef, ISchemaGenerator, MigrationInfo, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, EntityType, FromEntityType, Selected, IsSubset, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, FilterValue, MergeLoaded, MergeSelected, TypeConfig, AnyString, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, RequiredNullable, DefineConfig, Opt, Hidden, EntitySchemaWithMeta, InferEntity, CheckConstraint, TriggerDef, RoutineReturns, RoutineBodyCallback, RoutineJsBody, RoutineIgnoreField, RoutineParamConfig, RoutineConfig, RoutineRuntimeType, RoutineArgs, RoutineReturn, GeneratedColumnCallback, FilterDef, EntityCtor, Subquery, PopulateHintOptions, Prefixes, } from './typings.js';
|
|
6
|
+
export type { CompiledFunctions, Constructor, ConnectionType, Dictionary, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, InferEntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, EntityDTOFlat, EntityDTOProp, SerializeDTO, MigrationDiff, GenerateOptions, FilterObject, IndexFilterQuery, ExtractIndexHints, ExtractDefineEntityProperties, IndexName, IndexColumns, WithUsingOptions, IMigrationRunner, IEntityGenerator, ISeedManager, SeederObject, IMigratorStorage, RequiredEntityData, CheckCallback, TriggerCallback, IndexCallback, FormulaCallback, FormulaColumns, FormulaTable, SchemaTable, SchemaColumns, SchemaColumnRef, EntityDataPropValue, SimpleColumnMeta, Rel, Ref, LazyRef, ScalarRef, EntityRef, ISchemaGenerator, MigrationInfo, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, EntityType, FromEntityType, Selected, IsSubset, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, FilterValue, MergeLoaded, MergeSelected, TypeConfig, AnyString, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, RequiredNullable, DefineConfig, Opt, Hidden, EntitySchemaWithMeta, InferEntity, CheckConstraint, TriggerDef, PolicyDef, PolicyCallback, SessionContext, RoutineReturns, RoutineBodyCallback, RoutineJsBody, RoutineIgnoreField, RoutineParamConfig, RoutineConfig, RoutineRuntimeType, RoutineArgs, RoutineReturn, GeneratedColumnCallback, FilterDef, EntityCtor, Subquery, PopulateHintOptions, Prefixes, } from './typings.js';
|
|
7
7
|
export * from './enums.js';
|
|
8
8
|
export * from './errors.js';
|
|
9
9
|
export * from './exceptions.js';
|
|
@@ -117,6 +117,7 @@ export declare class MetadataDiscovery {
|
|
|
117
117
|
private createSchemaTable;
|
|
118
118
|
private initCheckConstraints;
|
|
119
119
|
private initTriggers;
|
|
120
|
+
private initPolicies;
|
|
120
121
|
private initGeneratedColumn;
|
|
121
122
|
private getDefaultVersionValue;
|
|
122
123
|
private inferDefaultValue;
|