@mikro-orm/core 7.2.0-dev.14 → 7.2.0-dev.16

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/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;
@@ -66,6 +73,9 @@ export declare class MetadataError<T extends AnyEntity = AnyEntity> extends Vali
66
73
  static targetIsAbstract(meta: EntityMetadata, prop: EntityProperty): MetadataError;
67
74
  static nonPersistentCompositeProp(meta: EntityMetadata, prop: EntityProperty): MetadataError;
68
75
  static propertyTargetsEntityType(meta: EntityMetadata, prop: EntityProperty, target: EntityMetadata): MetadataError;
76
+ static throughRelationMissingProperty(meta: EntityMetadata, prop: EntityProperty, through: EntityMetadata, side: 'owner' | 'target'): MetadataError;
77
+ static throughRelationCompositeTarget(meta: EntityMetadata, prop: EntityProperty): MetadataError;
78
+ static throughRelationInvalidKind(meta: EntityMetadata, prop: EntityProperty): MetadataError;
69
79
  static fromMissingOption(meta: EntityMetadata, prop: EntityProperty, option: string): MetadataError;
70
80
  static targetKeyOnManyToMany(meta: EntityMetadata, prop: EntityProperty): MetadataError;
71
81
  static targetKeyNotUnique(meta: EntityMetadata, prop: EntityProperty, target?: EntityMetadata): MetadataError;
@@ -77,6 +87,30 @@ export declare class MetadataError<T extends AnyEntity = AnyEntity> extends Vali
77
87
  static tptNotSupportedByDriver(meta: EntityMetadata): MetadataError;
78
88
  /** Thrown when database triggers are defined on an entity using a driver that does not support them. */
79
89
  static triggersNotSupportedByDriver(meta: EntityMetadata): MetadataError;
90
+ /** Thrown when row level security is declared on an entity using a driver that does not support it. */
91
+ static rowLevelSecurityNotSupportedByDriver(meta: EntityMetadata): MetadataError;
92
+ /** Thrown when row level security is declared on a non-root entity of an STI hierarchy. */
93
+ static rowLevelSecurityOnNonRootStiEntity(meta: EntityMetadata): MetadataError;
94
+ /** Thrown when two policies on the same entity are given the same explicit name. */
95
+ static duplicatePolicyName(meta: EntityMetadata, name: string): MetadataError;
96
+ /** Thrown when a filter flagged with `rls` is declared on a driver that does not support row level security. */
97
+ static rlsFilterNotSupportedByDriver(meta: EntityMetadata, filterName: string): MetadataError;
98
+ /** Thrown when a filter flagged with `rls` is declared on a non-root entity of an STI hierarchy. */
99
+ static rlsFilterOnNonRootStiEntity(meta: EntityMetadata, filterName: string): MetadataError;
100
+ /** Thrown when a global (config or EM registered) filter is flagged with `rls`; RLS filters must be entity scoped. */
101
+ static rlsFilterMustBeEntityScoped(filterName: string): MetadataError;
102
+ /** Thrown when an entity-scoped `rls` filter is registered at runtime via `em.addFilter()` instead of in metadata. */
103
+ static rlsFilterCannotBeRegisteredAtRuntime(filterName: string): MetadataError;
104
+ /** Thrown when a filter's custom `setting` is used with more than one argument. */
105
+ static rlsFilterMultiArgSetting(filterName: string, args: string[]): MetadataError;
106
+ /** Thrown when an `rls` filter's condition depends on runtime state and cannot be compiled to a static policy. */
107
+ static rlsFilterDependsOnRuntimeState(filterName: string): MetadataError;
108
+ /** Thrown when an `rls` filter compares against a column whose type has no automatic session-variable cast. */
109
+ static rlsFilterUncastableType(filterName: string, columnType: string): MetadataError;
110
+ /** Thrown when an `rls` filter references an argument outside of a direct comparison, which cannot be compiled. */
111
+ static rlsFilterUnsupportedCond(filterName: string): MetadataError;
112
+ /** Thrown when an `rls` filter compares against a column the schema generator does not manage. */
113
+ static rlsFilterUnmanagedColumn(filterName: string, column: string): MetadataError;
80
114
  private static fromMessage;
81
115
  }
82
116
  /** 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
  }
@@ -217,6 +241,16 @@ export class MetadataError extends ValidationError {
217
241
  const suggestion = target.embeddable ? 'Embedded' : 'ManyToOne';
218
242
  return this.fromMessage(meta, prop, `is defined as scalar @Property(), but its type is a discovered entity ${target.className}. Maybe you want to use @${suggestion}() decorator instead?`);
219
243
  }
244
+ static throughRelationMissingProperty(meta, prop, through, side) {
245
+ const target = side === 'owner' ? meta.className : prop.targetMeta.className;
246
+ return this.fromMessage(meta, prop, `uses 'through' entity ${through.className} which has no ManyToOne property pointing to ${target}`);
247
+ }
248
+ static throughRelationCompositeTarget(meta, prop) {
249
+ return this.fromMessage(meta, prop, `uses 'through' option which is not supported for targets with composite primary key`);
250
+ }
251
+ static throughRelationInvalidKind(meta, prop) {
252
+ return this.fromMessage(meta, prop, `uses 'through' option which is only supported for ManyToOne and OneToOne relations`);
253
+ }
220
254
  static fromMissingOption(meta, prop, option) {
221
255
  return this.fromMessage(meta, prop, `is missing '${option}' option`);
222
256
  }
@@ -250,6 +284,54 @@ export class MetadataError extends ValidationError {
250
284
  static triggersNotSupportedByDriver(meta) {
251
285
  return new MetadataError(`Entity ${meta.className} defines database triggers which are not supported by the current driver. Triggers are only available with SQL drivers.`);
252
286
  }
287
+ /** Thrown when row level security is declared on an entity using a driver that does not support it. */
288
+ static rowLevelSecurityNotSupportedByDriver(meta) {
289
+ 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.`);
290
+ }
291
+ /** Thrown when row level security is declared on a non-root entity of an STI hierarchy. */
292
+ static rowLevelSecurityOnNonRootStiEntity(meta) {
293
+ 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.`);
294
+ }
295
+ /** Thrown when two policies on the same entity are given the same explicit name. */
296
+ static duplicatePolicyName(meta, name) {
297
+ 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.`);
298
+ }
299
+ /** Thrown when a filter flagged with `rls` is declared on a driver that does not support row level security. */
300
+ static rlsFilterNotSupportedByDriver(meta, filterName) {
301
+ 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.`);
302
+ }
303
+ /** Thrown when a filter flagged with `rls` is declared on a non-root entity of an STI hierarchy. */
304
+ static rlsFilterOnNonRootStiEntity(meta, filterName) {
305
+ 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.`);
306
+ }
307
+ /** Thrown when a global (config or EM registered) filter is flagged with `rls`; RLS filters must be entity scoped. */
308
+ static rlsFilterMustBeEntityScoped(filterName) {
309
+ 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.`);
310
+ }
311
+ /** Thrown when an entity-scoped `rls` filter is registered at runtime via `em.addFilter()` instead of in metadata. */
312
+ static rlsFilterCannotBeRegisteredAtRuntime(filterName) {
313
+ 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.`);
314
+ }
315
+ /** Thrown when a filter's custom `setting` is used with more than one argument. */
316
+ static rlsFilterMultiArgSetting(filterName, args) {
317
+ 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.`);
318
+ }
319
+ /** Thrown when an `rls` filter's condition depends on runtime state and cannot be compiled to a static policy. */
320
+ static rlsFilterDependsOnRuntimeState(filterName) {
321
+ 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.`);
322
+ }
323
+ /** Thrown when an `rls` filter compares against a column whose type has no automatic session-variable cast. */
324
+ static rlsFilterUncastableType(filterName, columnType) {
325
+ 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.`);
326
+ }
327
+ /** Thrown when an `rls` filter references an argument outside of a direct comparison, which cannot be compiled. */
328
+ static rlsFilterUnsupportedCond(filterName) {
329
+ 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.`);
330
+ }
331
+ /** Thrown when an `rls` filter compares against a column the schema generator does not manage. */
332
+ static rlsFilterUnmanagedColumn(filterName, column) {
333
+ 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.`);
334
+ }
253
335
  static fromMessage(meta, prop, message) {
254
336
  return new MetadataError(`${meta.className}.${prop.name} ${message}`);
255
337
  }
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
+ }
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;
@@ -125,6 +126,8 @@ export declare class MetadataDiscovery {
125
126
  private initVersionProperty;
126
127
  private initCustomType;
127
128
  private initRelation;
129
+ /** Resolves the `through` option of a virtual to-one relation into a read-only formula property. */
130
+ private initThroughRelation;
128
131
  private initColumnType;
129
132
  private getMappedType;
130
133
  private getPrefix;
@@ -165,10 +165,14 @@ export class MetadataDiscovery {
165
165
  filtered.forEach(meta => this.initAutoincrement(meta)); // once again after we init custom types
166
166
  filtered.forEach(meta => this.initCheckConstraints(meta));
167
167
  filtered.forEach(meta => this.initTriggers(meta));
168
- forEachProp((_m, p) => {
168
+ // filter names are load-bearing for RLS (policy and session variable names), backfill from the dictionary key
169
+ filtered.forEach(meta => Object.entries(meta.filters).forEach(([key, filter]) => (filter.name ??= key)));
170
+ filtered.forEach(meta => this.initPolicies(meta));
171
+ forEachProp((m, p) => {
169
172
  this.initDefaultValue(p);
170
173
  this.inferTypeFromDefault(p);
171
174
  this.initRelation(p);
175
+ this.initThroughRelation(m, p);
172
176
  this.initColumnType(p);
173
177
  });
174
178
  forEachProp((m, p) => this.initIndexes(m, p));
@@ -220,11 +224,9 @@ export class MetadataDiscovery {
220
224
  };
221
225
  const missing = [];
222
226
  this.#discovered.forEach(meta => Object.values(meta.properties).forEach(prop => {
223
- if (prop.kind === ReferenceKind.MANY_TO_MANY && prop.pivotEntity) {
224
- const pivotEntity = prop.pivotEntity;
225
- const target = typeof pivotEntity === 'function' && !pivotEntity.prototype
226
- ? pivotEntity()
227
- : pivotEntity;
227
+ const indirect = (prop.kind === ReferenceKind.MANY_TO_MANY ? prop.pivotEntity : prop.through);
228
+ if (indirect) {
229
+ const target = typeof indirect === 'function' && !indirect.prototype ? indirect() : indirect;
228
230
  if (!this.#discovered.find(m => m.className === Utils.className(target)) || !discoveredByIdentity(target)) {
229
231
  missing.push(target);
230
232
  }
@@ -1076,6 +1078,12 @@ export class MetadataDiscovery {
1076
1078
  meta.checks = Utils.unique([...base.checks, ...meta.checks], Utils.equals);
1077
1079
  meta.triggers = Utils.unique([...base.triggers, ...meta.triggers], Utils.equals);
1078
1080
  }
1081
+ // Policies pass down only from inlined abstract bases; STI children share the root table
1082
+ // and TPT children own their tables, so both declare policies directly on the root/child.
1083
+ if (base.abstract && base.inheritanceType !== 'sti' && (meta.inheritanceType !== 'tpt' || !meta.tptParent)) {
1084
+ meta.policies = Utils.unique([...base.policies, ...meta.policies]);
1085
+ meta.rowLevelSecurity ??= base.rowLevelSecurity;
1086
+ }
1079
1087
  const pks = Object.values(meta.properties)
1080
1088
  .filter(p => p.primary)
1081
1089
  .map(p => p.name);
@@ -1743,6 +1751,28 @@ export class MetadataDiscovery {
1743
1751
  }
1744
1752
  meta.hasTriggers = true;
1745
1753
  }
1754
+ initPolicies(meta) {
1755
+ if (meta.policies.length === 0) {
1756
+ return;
1757
+ }
1758
+ const columns = meta.createSchemaColumnMappingObject();
1759
+ const table = this.createSchemaTable(meta);
1760
+ // resolve callbacks into a copy — the defs can be shared with siblings via an inlined abstract base,
1761
+ // and resolving in place would bake the first child's table into every other child's policy
1762
+ meta.policies = meta.policies.map(policy => {
1763
+ if (!(policy.using instanceof Function) && !(policy.check instanceof Function)) {
1764
+ return policy;
1765
+ }
1766
+ const resolved = { ...policy };
1767
+ if (resolved.using instanceof Function) {
1768
+ resolved.using = resolved.using(columns, table);
1769
+ }
1770
+ if (resolved.check instanceof Function) {
1771
+ resolved.check = resolved.check(columns, table);
1772
+ }
1773
+ return resolved;
1774
+ });
1775
+ }
1746
1776
  initGeneratedColumn(meta, prop) {
1747
1777
  if (!prop.generated && prop.columnTypes) {
1748
1778
  const match = /(.*) generated always as (.*)/i.exec(prop.columnTypes[0]);
@@ -2047,6 +2077,58 @@ export class MetadataDiscovery {
2047
2077
  }
2048
2078
  }
2049
2079
  }
2080
+ /** Resolves the `through` option of a virtual to-one relation into a read-only formula property. */
2081
+ initThroughRelation(meta, prop) {
2082
+ // already resolved, or not a through relation at all
2083
+ if (prop.through?.ownerProperty || !prop.through) {
2084
+ return;
2085
+ }
2086
+ if (![ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
2087
+ throw MetadataError.throughRelationInvalidKind(meta, prop);
2088
+ }
2089
+ const targetMeta = prop.targetMeta;
2090
+ // the subquery selects a single column
2091
+ if (targetMeta.compositePK) {
2092
+ throw MetadataError.throughRelationCompositeTarget(meta, prop);
2093
+ }
2094
+ const through = prop.through;
2095
+ const throughMeta = this.#metadata.get(!through.prototype ? through() : through);
2096
+ // a property is considered to point at an entity when it targets it or one of its parents
2097
+ const pointsTo = (p, m) => {
2098
+ const candidate = this.#metadata.find(p.target);
2099
+ /* v8 ignore next 3 */
2100
+ if (!candidate) {
2101
+ return false;
2102
+ }
2103
+ return candidate.class === m.class || m.class.prototype instanceof candidate.class;
2104
+ };
2105
+ const fks = Object.values(throughMeta.properties).filter(p => p.kind === ReferenceKind.MANY_TO_ONE);
2106
+ const ownerProp = fks.find(p => pointsTo(p, meta));
2107
+ if (!ownerProp) {
2108
+ throw MetadataError.throughRelationMissingProperty(meta, prop, throughMeta, 'owner');
2109
+ }
2110
+ let targetProperty;
2111
+ const selectsTarget = throughMeta.class === targetMeta.class || throughMeta.class.prototype instanceof targetMeta.class;
2112
+ if (!selectsTarget) {
2113
+ const targetProp = fks.find(p => p !== ownerProp && pointsTo(p, targetMeta));
2114
+ if (!targetProp) {
2115
+ throw MetadataError.throughRelationMissingProperty(meta, prop, throughMeta, 'target');
2116
+ }
2117
+ targetProperty = targetProp.name;
2118
+ }
2119
+ prop.through = {
2120
+ entity: throughMeta.class,
2121
+ where: prop.where,
2122
+ orderBy: prop.orderBy ? Utils.asArray(prop.orderBy) : undefined,
2123
+ ownerProperty: ownerProp.name,
2124
+ targetProperty,
2125
+ };
2126
+ // the condition and ordering apply to the `through` entity, not to the target, so they must not leak into the target joins
2127
+ delete prop.where;
2128
+ delete prop.orderBy;
2129
+ prop.persist = false;
2130
+ prop.formula = columns => this.#platform.getThroughRelationFormula(prop, columns);
2131
+ }
2050
2132
  initColumnType(prop) {
2051
2133
  this.initUnsigned(prop);
2052
2134
  // Get the target properties for FK relations - use targetKey property if specified, otherwise PKs
@@ -1,4 +1,4 @@
1
- import type { AnyEntity, Constructor, EntityName, AnyString, CheckCallback, GeneratedColumnCallback, FormulaCallback, FilterQuery, Dictionary, AutoPath, EntityClass, IndexCallback, ObjectQuery, Raw, SchemaColumns, TriggerDef } from '../typings.js';
1
+ import type { AnyEntity, Constructor, EntityName, AnyString, CheckCallback, GeneratedColumnCallback, FormulaCallback, FilterQuery, Dictionary, AutoPath, EntityClass, IndexCallback, ObjectQuery, Raw, SchemaColumns, TriggerDef, PolicyDef } from '../typings.js';
2
2
  import type { Cascade, LoadStrategy, DeferMode, QueryOrderMap, EmbeddedPrefixMode } from '../enums.js';
3
3
  import type { Type, types } from '../types/index.js';
4
4
  import type { EntityManager } from '../EntityManager.js';
@@ -104,6 +104,10 @@ export type EntityOptions<T, E = T extends EntityClass<infer P> ? P : T> = {
104
104
  hasTriggers?: boolean;
105
105
  /** Database triggers to create for this entity's table. (SQL drivers only) */
106
106
  triggers?: TriggerDef<E>[];
107
+ /** PostgreSQL row level security policies for this entity's table. Declaring policies implicitly enables RLS. */
108
+ policies?: PolicyDef<E>[];
109
+ /** Enables PostgreSQL row level security on this entity's table. `'force'` also enforces it for the table owner. Set to `false` to keep declared policies staged while leaving RLS disabled. */
110
+ rowLevelSecurity?: boolean | 'force';
107
111
  /**
108
112
  * PostgreSQL partitioning definition for this table.
109
113
  *
@@ -427,9 +431,15 @@ interface PolymorphicOptions {
427
431
  */
428
432
  discriminatorMap?: Dictionary<string>;
429
433
  }
430
- export interface ManyToOneOptions<Owner, Target> extends ReferenceOptions<Owner, Target>, PolymorphicOptions {
434
+ export interface ManyToOneOptions<Owner, Target, Through = Target> extends ReferenceOptions<Owner, Target>, PolymorphicOptions {
431
435
  /** Point to the inverse side property name. */
432
436
  inversedBy?: (string & keyof Target) | ((e: Target) => any);
437
+ /** Resolve this read-only relation via a subquery on another entity: a pivot entity with FKs to both sides, or the target itself to pick a single item out of a to-many relation (see {@doclink relationships#to-one-relations-through-another-entity | To-one relations through another entity}). */
438
+ through?: () => EntityName<Through>;
439
+ /** Condition applied on the `through` entity. */
440
+ where?: FilterQuery<Through>;
441
+ /** Ordering applied on the `through` entity, the first matching row is used. */
442
+ orderBy?: QueryOrderMap<Through> | QueryOrderMap<Through>[];
433
443
  /** Wrap the entity in {@apilink Reference} wrapper. */
434
444
  ref?: boolean;
435
445
  /** Use this relation as a primary key. */
@@ -481,9 +491,15 @@ export interface OneToManyOptions<Owner, Target> extends ReferenceOptions<Owner,
481
491
  /** Point to the owning side property name. */
482
492
  mappedBy: (string & keyof Target) | ((e: Target) => any);
483
493
  }
484
- export interface OneToOneOptions<Owner, Target> extends Partial<Omit<OneToManyOptions<Owner, Target>, 'orderBy'>>, PolymorphicOptions {
494
+ export interface OneToOneOptions<Owner, Target, Through = Target> extends Partial<Omit<OneToManyOptions<Owner, Target>, 'orderBy' | 'where'>>, PolymorphicOptions {
485
495
  /** Set this side as owning. Owning side is where the foreign key is defined. This option is not required if you use `inversedBy` or `mappedBy` to distinguish owning and inverse side. */
486
496
  owner?: boolean;
497
+ /** Resolve this read-only relation via a subquery on another entity: a pivot entity with FKs to both sides, or the target itself to pick a single item out of a to-many relation (see {@doclink relationships#to-one-relations-through-another-entity | To-one relations through another entity}). */
498
+ through?: () => EntityName<Through>;
499
+ /** Condition for {@doclink collections#declarative-partial-loading | Declarative partial loading}, or the condition applied on the `through` entity. */
500
+ where?: FilterQuery<Through>;
501
+ /** Ordering applied on the `through` entity, the first matching row is used. */
502
+ orderBy?: QueryOrderMap<Through> | QueryOrderMap<Through>[];
487
503
  /** Point to the inverse side property name. */
488
504
  inversedBy?: (string & keyof Target) | ((e: Target) => any);
489
505
  /** Wrap the entity in {@apilink Reference} wrapper. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "7.2.0-dev.14",
3
+ "version": "7.2.0-dev.16",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
5
  "keywords": [
6
6
  "data-mapper",
@@ -1,6 +1,6 @@
1
1
  import { EntityRepository } from '../entity/EntityRepository.js';
2
2
  import { type NamingStrategy } from '../naming-strategy/NamingStrategy.js';
3
- import type { Constructor, EntityMetadata, EntityProperty, IPrimaryKey, ISchemaGenerator, PopulateOptions, Primary, SimpleColumnMeta, FilterQuery, EntityValue, EntityKey } from '../typings.js';
3
+ import type { Constructor, EntityMetadata, EntityProperty, IPrimaryKey, ISchemaGenerator, PopulateOptions, Primary, SimpleColumnMeta, FilterQuery, EntityValue, EntityKey, FormulaColumns } from '../typings.js';
4
4
  import { ExceptionConverter } from './ExceptionConverter.js';
5
5
  import type { EntityManager } from '../EntityManager.js';
6
6
  import type { Configuration } from '../utils/Configuration.js';
@@ -275,6 +275,11 @@ export declare abstract class Platform {
275
275
  formatQuery(sql: string, params: readonly any[]): string;
276
276
  /** Deep-clones embeddable data and tags it for JSON serialization. */
277
277
  cloneEmbeddable<T>(data: T): T;
278
+ /**
279
+ * Builds the correlated subquery used as the formula of a virtual to-one relation defined via `through`.
280
+ * @internal
281
+ */
282
+ getThroughRelationFormula(prop: EntityProperty, columns: FormulaColumns<any>): string;
278
283
  /** Initializes the platform with the ORM configuration. */
279
284
  setConfig(config: Configuration): void;
280
285
  /** Returns the current ORM configuration. */
@@ -316,6 +321,15 @@ export declare abstract class Platform {
316
321
  supportsDownMigrations(): boolean;
317
322
  /** Whether the platform supports deferred unique constraints. */
318
323
  supportsDeferredUniqueConstraints(): boolean;
324
+ /** Whether the platform supports row level security (PostgreSQL). */
325
+ supportsRowLevelSecurity(): boolean;
326
+ /** Whether the driver can apply the session context on every pooled connection acquire (`sessionContext: 'connection'`). */
327
+ supportsConnectionSessionContext(): boolean;
328
+ /**
329
+ * SQL cast suffix (e.g. `'::uuid'`, or `''` when none is needed) applied when an RLS filter reads a session
330
+ * variable via `current_setting()` as the given column type, or `null` if the type has no automatic cast.
331
+ */
332
+ getCurrentSettingCast(mappedType: Type<unknown>): string | null;
319
333
  /** Platform-specific validation of entity metadata. */
320
334
  validateMetadata(meta: EntityMetadata): void;
321
335
  /**
@@ -616,6 +616,14 @@ export class Platform {
616
616
  Object.defineProperty(copy, JsonProperty, { enumerable: false, value: true });
617
617
  return copy;
618
618
  }
619
+ /**
620
+ * Builds the correlated subquery used as the formula of a virtual to-one relation defined via `through`.
621
+ * @internal
622
+ */
623
+ /* v8 ignore next 3 */
624
+ getThroughRelationFormula(prop, columns) {
625
+ throw new Error(`${this.constructor.name} does not support the 'through' option of ${prop.name}`);
626
+ }
619
627
  /** Initializes the platform with the ORM configuration. */
620
628
  setConfig(config) {
621
629
  this.config = config;
@@ -722,11 +730,51 @@ export class Platform {
722
730
  supportsDeferredUniqueConstraints() {
723
731
  return true;
724
732
  }
733
+ /** Whether the platform supports row level security (PostgreSQL). */
734
+ supportsRowLevelSecurity() {
735
+ return false;
736
+ }
737
+ /** Whether the driver can apply the session context on every pooled connection acquire (`sessionContext: 'connection'`). */
738
+ supportsConnectionSessionContext() {
739
+ return false;
740
+ }
741
+ /**
742
+ * SQL cast suffix (e.g. `'::uuid'`, or `''` when none is needed) applied when an RLS filter reads a session
743
+ * variable via `current_setting()` as the given column type, or `null` if the type has no automatic cast.
744
+ */
745
+ getCurrentSettingCast(mappedType) {
746
+ return null;
747
+ }
725
748
  /** Platform-specific validation of entity metadata. */
726
749
  validateMetadata(meta) {
727
750
  if (meta.partitionBy && !this.supportsPartitionedTables()) {
728
751
  throw new MetadataError(`Entity ${meta.className} uses partitionBy, but ${this.constructor.name} does not support partitioned tables`);
729
752
  }
753
+ const declaresRls = meta.policies.length > 0 || !!meta.rowLevelSecurity;
754
+ if (declaresRls && !this.supportsRowLevelSecurity()) {
755
+ throw MetadataError.rowLevelSecurityNotSupportedByDriver(meta);
756
+ }
757
+ // STI hierarchies share a single table, so only the root may declare policies; `root` is optional-chained
758
+ // as `validateMetadata` is public API and tolerates partially populated metadata
759
+ if (declaresRls && meta.root?.inheritanceType === 'sti' && meta.root !== meta) {
760
+ throw MetadataError.rowLevelSecurityOnNonRootStiEntity(meta);
761
+ }
762
+ if (meta.root?.inheritanceType === 'sti' && meta.root !== meta) {
763
+ for (const filter of Object.values(meta.filters)) {
764
+ // inherited root filters share the def object; only defs declared on the child itself are a problem,
765
+ // as non-root STI metas never reach the schema generator and the policy would silently not exist
766
+ if (filter.rls && meta.root.filters[filter.name] !== filter) {
767
+ throw MetadataError.rlsFilterOnNonRootStiEntity(meta, filter.name);
768
+ }
769
+ }
770
+ }
771
+ if (!this.supportsRowLevelSecurity()) {
772
+ for (const filter of Object.values(meta.filters)) {
773
+ if (filter.rls) {
774
+ throw MetadataError.rlsFilterNotSupportedByDriver(meta, filter.name);
775
+ }
776
+ }
777
+ }
730
778
  }
731
779
  /**
732
780
  * Generates a custom order by statement given a set of in order values, eg.
package/typings.d.ts CHANGED
@@ -653,6 +653,16 @@ export type SerializeDTO<T, H extends string = never, E extends string = never,
653
653
  };
654
654
  type TargetKeys<T> = T extends EntityClass<infer P> ? keyof P : keyof T;
655
655
  type PropertyName<T> = IsUnknown<T> extends false ? TargetKeys<T> : string;
656
+ /** Resolved `through` option of a virtual to-one relation, populated during discovery. */
657
+ export interface ThroughRelation {
658
+ entity: EntityClass;
659
+ where?: FilterQuery<any>;
660
+ orderBy?: QueryOrderMap<any>[];
661
+ /** M:1 property on the `through` entity pointing back to the owner. */
662
+ ownerProperty: string;
663
+ /** M:1 property on the `through` entity pointing to the target, undefined when the target is selected directly. */
664
+ targetProperty?: string;
665
+ }
656
666
  /** Table reference object passed to formula callbacks, including alias and schema information. */
657
667
  export type FormulaTable = {
658
668
  alias: string;
@@ -710,6 +720,8 @@ export type IndexCallback<T> = (columns: Record<PropertyName<T>, string>, table:
710
720
  export type FormulaCallback<T> = (columns: FormulaColumns<T>, table: FormulaTable) => string | Raw;
711
721
  /** Callback for CHECK constraint expressions. Receives column mappings and table info. */
712
722
  export type CheckCallback<T> = (columns: SchemaColumns<T>, table: SchemaTable) => string | Raw;
723
+ /** Callback for row level security policy expressions. Receives column mappings and table info. */
724
+ export type PolicyCallback<T> = (columns: SchemaColumns<T>, table: SchemaTable) => string | Raw;
713
725
  /** Callback for trigger body expressions. Receives column mappings and table info. */
714
726
  export type TriggerCallback<T> = (columns: Record<PropertyName<T>, string>, table: SchemaTable) => string | Raw;
715
727
  /**
@@ -724,6 +736,28 @@ export interface CheckConstraint<T = any> {
724
736
  property?: string;
725
737
  expression: string | Raw | CheckCallback<T>;
726
738
  }
739
+ /** Definition of a PostgreSQL row level security policy on a table. */
740
+ export interface PolicyDef<T = any> {
741
+ /** Policy name. Auto-generated if omitted. */
742
+ name?: string;
743
+ /** DML command the policy applies to. Defaults to `'all'`. */
744
+ command?: 'select' | 'insert' | 'update' | 'delete' | 'all';
745
+ /** Whether the policy is permissive (OR-combined) or restrictive (AND-combined). Defaults to `'permissive'`. */
746
+ type?: 'permissive' | 'restrictive';
747
+ /** Database roles the policy applies to. Defaults to `PUBLIC`. */
748
+ roles?: string[];
749
+ /** `USING` expression filtering visible rows. Can be a string, Raw query, or callback receiving column name mappings. */
750
+ using?: string | Raw | PolicyCallback<T>;
751
+ /** `WITH CHECK` expression validating written rows. Can be a string, Raw query, or callback receiving column name mappings. */
752
+ check?: string | Raw | PolicyCallback<T>;
753
+ }
754
+ /** Per-context database session state applied for row level security (session variables and role). */
755
+ export interface SessionContext {
756
+ /** Session variables set via `set_config`, typically referenced by RLS policies through `current_setting()`. `Date` values are serialized to ISO 8601. */
757
+ variables?: Dictionary<string | number | boolean | Date>;
758
+ /** Database role to switch to for the duration of the context (`set local role` / `set role`). */
759
+ role?: string;
760
+ }
727
761
  /** Definition of a database trigger on a table. */
728
762
  export interface TriggerDef<T = any> {
729
763
  /** Trigger name. Auto-generated if omitted. */
@@ -1019,6 +1053,7 @@ export interface EntityProperty<Owner = any, Target = any> {
1019
1053
  fixedOrderColumn?: string;
1020
1054
  pivotTable: string;
1021
1055
  pivotEntity: EntityClass<Target>;
1056
+ through?: ThroughRelation;
1022
1057
  joinColumns: string[];
1023
1058
  ownColumns: string[];
1024
1059
  inverseJoinColumns: string[];
@@ -1171,6 +1206,9 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
1171
1206
  }[];
1172
1207
  checks: CheckConstraint<Entity>[];
1173
1208
  triggers: TriggerDef<Entity>[];
1209
+ policies: PolicyDef<Entity>[];
1210
+ /** Enables row level security on the table. `'force'` also enables it for the table owner. Implied by non-empty `policies`, unless set to `false`, which keeps the policies staged but RLS disabled. */
1211
+ rowLevelSecurity?: boolean | 'force';
1174
1212
  repositoryClass?: string;
1175
1213
  repository: () => EntityClass<EntityRepository<any>>;
1176
1214
  hooks: {
@@ -1498,6 +1536,15 @@ type FilterDefResolved<T extends object = any> = {
1498
1536
  entity?: EntityName<T> | EntityName<T>[];
1499
1537
  args?: boolean;
1500
1538
  strict?: boolean;
1539
+ /**
1540
+ * Also materializes this filter as a PostgreSQL row level security policy on the entity's table, and stages the
1541
+ * matching session variables when its params are enabled via `em.setFilterParams()`. The `cond` must be compilable
1542
+ * to a static expression (no access to `em`/`type`/`options`, not async). Each referenced argument maps to a session
1543
+ * variable named `mikro.<filterName>.<argName>`; pass `{ setting }` to override that name for a single-argument filter.
1544
+ */
1545
+ rls?: boolean | {
1546
+ setting?: string;
1547
+ };
1501
1548
  };
1502
1549
  /** Definition of a query filter that can be registered globally or per-entity via `@Filter()`. */
1503
1550
  export type FilterDef<T extends EntityName | readonly EntityName[] = any> = FilterDefResolved<EntityFromInput<T>> & {
package/typings.js CHANGED
@@ -49,6 +49,7 @@ export class EntityMetadata {
49
49
  this.uniques = [];
50
50
  this.checks = [];
51
51
  this.triggers = [];
52
+ this.policies = [];
52
53
  this.referencingProperties = [];
53
54
  this.concurrencyCheckKeys = new Set();
54
55
  Object.assign(this, meta);
@@ -472,6 +472,7 @@ export class UnitOfWork {
472
472
  const loggerContext = Utils.merge({ id: this.#em._id }, this.#em.getLoggerContext({ disableContextResolution: true }));
473
473
  await this.#em.getConnection('write').transactional(trx => this.persistToDatabase(groups, trx), {
474
474
  ctx: oldTx,
475
+ sessionContext: this.#em.getTransactionSessionContext(),
475
476
  eventBroadcaster: new TransactionEventBroadcaster(this.#em),
476
477
  loggerContext,
477
478
  });