@mikro-orm/core 7.1.16-dev.1 → 7.1.16-dev.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/EntityManager.d.ts +41 -7
  2. package/EntityManager.js +203 -42
  3. package/MikroORM.d.ts +4 -0
  4. package/MikroORM.js +9 -0
  5. package/README.md +1 -0
  6. package/cache/FileCacheAdapter.js +1 -1
  7. package/connections/Connection.d.ts +10 -1
  8. package/connections/Connection.js +9 -0
  9. package/drivers/DatabaseDriver.d.ts +14 -5
  10. package/drivers/DatabaseDriver.js +151 -52
  11. package/entity/Collection.js +4 -2
  12. package/entity/EntityLoader.d.ts +7 -1
  13. package/entity/EntityLoader.js +35 -5
  14. package/entity/EntityRepository.d.ts +4 -5
  15. package/entity/EntityRepository.js +2 -1
  16. package/entity/defineEntity.d.ts +23 -5
  17. package/entity/defineEntity.js +31 -0
  18. package/enums.d.ts +5 -1
  19. package/enums.js +2 -0
  20. package/errors.d.ts +35 -0
  21. package/errors.js +87 -0
  22. package/exceptions.d.ts +5 -0
  23. package/exceptions.js +5 -0
  24. package/index.d.ts +1 -1
  25. package/metadata/MetadataDiscovery.d.ts +3 -0
  26. package/metadata/MetadataDiscovery.js +94 -7
  27. package/metadata/types.d.ts +19 -3
  28. package/package.json +1 -1
  29. package/platforms/Platform.d.ts +19 -1
  30. package/platforms/Platform.js +56 -0
  31. package/types/BigIntType.d.ts +1 -0
  32. package/types/BigIntType.js +23 -0
  33. package/types/DateTimeType.d.ts +1 -0
  34. package/types/DateTimeType.js +8 -0
  35. package/types/StringType.d.ts +14 -3
  36. package/types/StringType.js +34 -4
  37. package/types/TextType.d.ts +2 -4
  38. package/types/TextType.js +2 -8
  39. package/types/Type.d.ts +11 -0
  40. package/types/index.d.ts +2 -2
  41. package/typings.d.ts +48 -0
  42. package/typings.js +1 -0
  43. package/unit-of-work/UnitOfWork.js +1 -0
  44. package/utils/Configuration.d.ts +21 -1
  45. package/utils/Configuration.js +12 -1
  46. package/utils/Cursor.d.ts +2 -0
  47. package/utils/Cursor.js +43 -33
  48. package/utils/QueryHelper.d.ts +12 -0
  49. package/utils/QueryHelper.js +63 -0
  50. package/utils/RawQueryFragment.d.ts +6 -0
  51. package/utils/RawQueryFragment.js +15 -6
  52. package/utils/RequestContext.d.ts +2 -2
  53. package/utils/RequestContext.js +11 -2
  54. package/utils/TransactionManager.js +1 -1
  55. package/utils/Utils.d.ts +2 -0
  56. package/utils/Utils.js +12 -3
  57. package/utils/env-vars.js +2 -0
  58. package/utils/index.d.ts +1 -0
  59. package/utils/index.js +1 -0
  60. package/utils/rls-utils.d.ts +35 -0
  61. package/utils/rls-utils.js +97 -0
@@ -4,6 +4,7 @@ import { ARRAY_OPERATORS, GroupOperator, JSON_KEY_OPERATORS, ReferenceKind } fro
4
4
  import { JsonType } from '../types/JsonType.js';
5
5
  import { helper } from '../entity/wrap.js';
6
6
  import { isRaw, Raw } from './RawQueryFragment.js';
7
+ import { MetadataError } from '../errors.js';
7
8
  /** @internal */
8
9
  export class QueryHelper {
9
10
  static SUPPORTED_OPERATORS = ['>', '<', '<=', '>=', '!', '!='];
@@ -286,6 +287,68 @@ export class QueryHelper {
286
287
  return filters[f];
287
288
  });
288
289
  }
290
+ /** @internal Sentinel wrapping for arguments accessed while statically resolving an `rls` filter condition. */
291
+ static RLS_SENTINEL_PREFIX = '__mikro_rls_arg__';
292
+ /** @internal */
293
+ static RLS_SENTINEL_SUFFIX = '__';
294
+ /**
295
+ * Resolves an `rls` filter's condition to a static `FilterQuery`. Function conditions are called with a proxy `args`
296
+ * that yields a unique sentinel per accessed argument, real `type`/`entityName` strings (validated to not affect the
297
+ * result), and a poison proxy or `undefined` for the remaining runtime-only parameters.
298
+ *
299
+ * @internal
300
+ */
301
+ static resolveRlsFilterCond(filter, accessed, entityName) {
302
+ if (!(filter.cond instanceof Function)) {
303
+ return filter.cond;
304
+ }
305
+ const args = new Proxy({}, {
306
+ get: (_target, prop) => {
307
+ if (typeof prop === 'symbol') {
308
+ // e.g. coercing `args` itself in a template literal triggers a `Symbol.toPrimitive` lookup
309
+ throw MetadataError.rlsFilterUnsupportedCond(filter.name);
310
+ }
311
+ accessed.add(prop);
312
+ return `${this.RLS_SENTINEL_PREFIX}${prop}${this.RLS_SENTINEL_SUFFIX}`;
313
+ },
314
+ });
315
+ const poison = new Proxy({}, {
316
+ get: () => {
317
+ throw MetadataError.rlsFilterDependsOnRuntimeState(filter.name);
318
+ },
319
+ });
320
+ // property access on the poison proxies throws, but equality/truthiness checks (`type === 'read'`,
321
+ // `entityName === 'X'`, `options ? a : b`) cannot be trapped — vary all three across the evaluations and require
322
+ // identical results, so a command-, entity-, or options-dependent condition cannot silently compile one branch.
323
+ // `entityName` uses the real class name (plus two derived-distinct variants) so an `=== '<name>'` check diverges;
324
+ // `options` alternates the poison proxy and `undefined` so a truthiness check flips. `em` stays poison throughout.
325
+ const name = entityName ?? `${this.RLS_SENTINEL_PREFIX}entity${this.RLS_SENTINEL_SUFFIX}`;
326
+ const evaluate = (type, entity, options) => {
327
+ let result;
328
+ try {
329
+ result = filter.cond(args, type, poison, options, entity);
330
+ }
331
+ catch (e) {
332
+ // a raw TypeError from touching the `undefined` options/em must fail closed like the poison proxy does,
333
+ // but the descriptive MetadataErrors thrown above are already correct — let them surface unchanged
334
+ if (e instanceof MetadataError) {
335
+ throw e;
336
+ }
337
+ throw MetadataError.rlsFilterDependsOnRuntimeState(filter.name);
338
+ }
339
+ if (result instanceof Promise) {
340
+ throw MetadataError.rlsFilterDependsOnRuntimeState(filter.name);
341
+ }
342
+ return result;
343
+ };
344
+ const read = evaluate('read', name, poison);
345
+ const update = evaluate('update', `${name}\0a`, undefined);
346
+ const del = evaluate('delete', `${name}\0b`, poison);
347
+ if (JSON.stringify(read) !== JSON.stringify(update) || JSON.stringify(read) !== JSON.stringify(del)) {
348
+ throw MetadataError.rlsFilterDependsOnRuntimeState(filter.name);
349
+ }
350
+ return read;
351
+ }
289
352
  static mergePropertyFilters(propFilters, options) {
290
353
  if (!options || !propFilters || options === true || propFilters === true) {
291
354
  return options ?? propFilters;
@@ -61,6 +61,12 @@ export declare const ALIAS_REPLACEMENT_RE = "\\[::alias::\\]";
61
61
  * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
62
62
  * ```
63
63
  *
64
+ * Named parameters are supported via an object of parameters, use `:name` for values and `:name:` for identifiers:
65
+ *
66
+ * ```ts
67
+ * raw('select :col: from geo where city = :city or region = :city', { col: 'city', city: 'Brno' });
68
+ * ```
69
+ *
64
70
  * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
65
71
  *
66
72
  * ```ts
@@ -146,6 +146,12 @@ export const ALIAS_REPLACEMENT_RE = '\\[::alias::\\]';
146
146
  * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
147
147
  * ```
148
148
  *
149
+ * Named parameters are supported via an object of parameters, use `:name` for values and `:name:` for identifiers:
150
+ *
151
+ * ```ts
152
+ * raw('select :col: from geo where city = :city or region = :city', { col: 'city', city: 'Brno' });
153
+ * ```
154
+ *
149
155
  * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
150
156
  *
151
157
  * ```ts
@@ -191,13 +197,16 @@ export function raw(sql, params) {
191
197
  return Utils.getPrimaryKeyHash(sql);
192
198
  }
193
199
  if (typeof params === 'object' && !Array.isArray(params)) {
194
- const pairs = Object.entries(params);
200
+ const dict = params;
195
201
  const objectParams = [];
196
- for (const [key, value] of pairs) {
197
- sql = sql.replace(`:${key}:`, '??');
198
- sql = sql.replace(`:${key}`, '?');
199
- objectParams.push(value);
200
- }
202
+ // single left-to-right scan keeps values in SQL-placeholder order while `::` casts and unknown tokens stay untouched
203
+ sql = sql.replace(/(?<!:):([$\w]+)(:(?!:))?/g, (match, key, identifier) => {
204
+ if (!Object.hasOwn(dict, key)) {
205
+ return match;
206
+ }
207
+ objectParams.push(dict[key]);
208
+ return identifier ? '??' : '?';
209
+ });
201
210
  return new RawQueryFragment(sql, objectParams);
202
211
  }
203
212
  return new RawQueryFragment(sql, params);
@@ -17,13 +17,13 @@ export declare class RequestContext {
17
17
  * If the handler is async, the return value needs to be awaited.
18
18
  * Uses `AsyncLocalStorage.run()`, suitable for regular express style middlewares with a `next` callback.
19
19
  */
20
- static create<T>(em: EntityManager | EntityManager[], next: (...args: any[]) => T, options?: CreateContextOptions): T;
20
+ static create<T>(em: EntityManager | EntityManager[], next: (...args: any[]) => T, options?: ((name: string) => CreateContextOptions) | CreateContextOptions): T;
21
21
  /**
22
22
  * Creates new RequestContext instance and runs the code inside its domain.
23
23
  * If the handler is async, the return value needs to be awaited.
24
24
  * Uses `AsyncLocalStorage.enterWith()`, suitable for elysia style middlewares without a `next` callback.
25
25
  */
26
- static enter(em: EntityManager | EntityManager[], options?: CreateContextOptions): void;
26
+ static enter(em: EntityManager | EntityManager[], options?: ((name: string) => CreateContextOptions) | CreateContextOptions): void;
27
27
  /**
28
28
  * Returns current RequestContext (if available).
29
29
  */
@@ -50,10 +50,19 @@ export class RequestContext {
50
50
  static createContext(em, options = {}) {
51
51
  const forks = new Map();
52
52
  if (Array.isArray(em)) {
53
- em.forEach(em => forks.set(em.name, em.fork({ useContext: true, ...options })));
53
+ if (typeof options === 'function') {
54
+ for (const emInstance of em) {
55
+ forks.set(emInstance.name, emInstance.fork({ useContext: true, ...options(emInstance.name) }));
56
+ }
57
+ }
58
+ else {
59
+ for (const emInstance of em) {
60
+ forks.set(emInstance.name, emInstance.fork({ useContext: true, ...options }));
61
+ }
62
+ }
54
63
  }
55
64
  else {
56
- forks.set(em.name, em.fork({ useContext: true, ...options }));
65
+ forks.set(em.name, em.fork({ useContext: true, ...(typeof options === 'function' ? options(em.name) : options) }));
57
66
  }
58
67
  return new RequestContext(forks);
59
68
  }
@@ -239,7 +239,7 @@ export class TransactionManager {
239
239
  return TransactionContext.create(fork, () => fork.getConnection().transactional(async (trx) => {
240
240
  fork.setTransactionContext(trx);
241
241
  return this.executeTransactionFlow(fork, cb, propagateToUpperContext, em);
242
- }, { ...options, eventBroadcaster }));
242
+ }, { sessionContext: fork.getTransactionSessionContext(), ...options, eventBroadcaster }));
243
243
  }
244
244
  /**
245
245
  * Executes transaction workflow with entity synchronization.
package/utils/Utils.d.ts CHANGED
@@ -33,6 +33,8 @@ export declare function parseJsonSafe<T = unknown>(value: unknown): T;
33
33
  export declare class Utils {
34
34
  #private;
35
35
  static readonly PK_SEPARATOR = "~~~";
36
+ /** Default session variable name backing an RLS filter argument (`current_setting('mikro.<filter>.<arg>')`). */
37
+ static getRlsSettingName(filterName: string, argName: string): string;
36
38
  /**
37
39
  * Checks if the argument is instance of `Object`. Returns false for arrays.
38
40
  */
package/utils/Utils.js CHANGED
@@ -153,7 +153,11 @@ export function parseJsonSafe(value) {
153
153
  /** Collection of general-purpose utility methods used throughout the ORM. */
154
154
  export class Utils {
155
155
  static PK_SEPARATOR = '~~~';
156
- static #ORM_VERSION = '7.1.16-dev.1';
156
+ static #ORM_VERSION = '7.1.16-dev.11';
157
+ /** Default session variable name backing an RLS filter argument (`current_setting('mikro.<filter>.<arg>')`). */
158
+ static getRlsSettingName(filterName, argName) {
159
+ return `mikro.${filterName}.${argName}`;
160
+ }
157
161
  /**
158
162
  * Checks if the argument is instance of `Object`. Returns false for arrays.
159
163
  */
@@ -602,7 +606,8 @@ export class Utils {
602
606
  return (arg.includes('ts-node') || // check for ts-node loader
603
607
  arg.includes('@swc-node/register') || // check for swc-node/register loader
604
608
  arg.includes('node_modules/tsx/') || // check for tsx loader
605
- arg.includes('@oxc-node/core') // check for oxc-node loader
609
+ arg.includes('@oxc-node/core') || // check for oxc-node loader
610
+ arg.includes('@nubjs/loader') // check for Nub loader
606
611
  );
607
612
  }));
608
613
  }
@@ -854,7 +859,11 @@ export class Utils {
854
859
  return await import(module);
855
860
  }
856
861
  catch (err) {
857
- if (warning && err.code === 'ERR_MODULE_NOT_FOUND') {
862
+ // only a missing module is expected here, anything else is a real failure inside the module
863
+ if (!['ERR_MODULE_NOT_FOUND', 'MODULE_NOT_FOUND'].includes(err.code)) {
864
+ throw err;
865
+ }
866
+ if (warning) {
858
867
  // eslint-disable-next-line no-console
859
868
  console.warn(warning);
860
869
  }
package/utils/env-vars.js CHANGED
@@ -79,6 +79,7 @@ export function loadEnvironmentVars() {
79
79
  read2('silent', bool);
80
80
  read2('emit');
81
81
  read2('snapshot', bool);
82
+ read2('snapshotOnMigrate', bool);
82
83
  read2('snapshotName');
83
84
  cleanup(ret, 'migrations');
84
85
  ret.schemaGenerator = {};
@@ -87,6 +88,7 @@ export function loadEnvironmentVars() {
87
88
  read3('createForeignKeyConstraints', bool);
88
89
  read3('ignoreTriggers', bool);
89
90
  read3('ignoreRoutines', bool);
91
+ read3('ignorePolicies', bool);
90
92
  cleanup(ret, 'schemaGenerator');
91
93
  ret.seeder = {};
92
94
  const read4 = read.bind(null, ret.seeder, 'MIKRO_ORM_SEEDER_');
package/utils/index.d.ts CHANGED
@@ -10,4 +10,5 @@ export * from './EntityComparator.js';
10
10
  export * from './RawQueryFragment.js';
11
11
  export * from './env-vars.js';
12
12
  export * from './upsert-utils.js';
13
+ export * from './rls-utils.js';
13
14
  export * from './partition-utils.js';
package/utils/index.js CHANGED
@@ -10,4 +10,5 @@ export * from './EntityComparator.js';
10
10
  export * from './RawQueryFragment.js';
11
11
  export * from './env-vars.js';
12
12
  export * from './upsert-utils.js';
13
+ export * from './rls-utils.js';
13
14
  export * from './partition-utils.js';
@@ -0,0 +1,35 @@
1
+ import type { MetadataStorage } from '../metadata/MetadataStorage.js';
2
+ import type { Dictionary, FilterDef } from '../typings.js';
3
+ /** An `rls`-flagged filter definition together with the entity it is declared on. @internal */
4
+ export interface RlsFilterEntry {
5
+ filter: FilterDef;
6
+ entityName: string;
7
+ }
8
+ /**
9
+ * Collects all `rls`-flagged filter definitions with the given name (only entity-scoped filters can be `rls`).
10
+ * The full name -> defs lookup is built once and cached on the shared (immutable) MetadataStorage, so repeated
11
+ * `setFilterParams` calls and forks reuse it instead of walking every entity each time.
12
+ * @internal
13
+ */
14
+ export declare function findRlsFilterDefs(metadata: MetadataStorage, name: string): RlsFilterEntry[];
15
+ /**
16
+ * Drops the cached `rls` filter lookup — `MikroORM.discoverEntity()` mutates the shared MetadataStorage,
17
+ * so a lookup built before the call would miss the newly discovered filters.
18
+ *
19
+ * @internal
20
+ */
21
+ export declare function clearRlsFilterDefsCache(metadata: MetadataStorage): void;
22
+ /**
23
+ * Computes the `rls` session variables a set of same-named filter defs stages for the given args, mirroring the
24
+ * policy compilation (`current_setting` names and custom `setting` binding). Shared by staging and `fork({ session })`.
25
+ * @internal
26
+ */
27
+ export declare function computeRlsFilterVariables(filters: RlsFilterEntry[], args: Dictionary): Dictionary<string | number | boolean | Date>;
28
+ /**
29
+ * Computes which staged session variables a `setFilterParams` call may prune: the variables the OLD args staged for
30
+ * this filter that the new args no longer set, minus any variable another filter's current params still stage
31
+ * (a custom `setting` name can be shared by differently named filters). Recomputing from the old args rather than
32
+ * matching by prefix keeps a filter named `tenant` from also pruning a `tenant.x` filter's `mikro.tenant.x.*` variables.
33
+ * @internal
34
+ */
35
+ export declare function computeRemovedRlsVariables(metadata: MetadataStorage, name: string, filters: RlsFilterEntry[], previousArgs: Dictionary, nextVariables: Dictionary, allFilterParams: Dictionary<Dictionary>): string[];
@@ -0,0 +1,97 @@
1
+ import { MetadataError, ValidationError } from '../errors.js';
2
+ import { QueryHelper } from './QueryHelper.js';
3
+ import { Utils } from './Utils.js';
4
+ /** Lazily-built `rls` filter lookup keyed by the shared (immutable) MetadataStorage, so all forks reuse it. */
5
+ const rlsFilterDefs = new WeakMap();
6
+ /**
7
+ * Collects all `rls`-flagged filter definitions with the given name (only entity-scoped filters can be `rls`).
8
+ * The full name -> defs lookup is built once and cached on the shared (immutable) MetadataStorage, so repeated
9
+ * `setFilterParams` calls and forks reuse it instead of walking every entity each time.
10
+ * @internal
11
+ */
12
+ export function findRlsFilterDefs(metadata, name) {
13
+ let cache = rlsFilterDefs.get(metadata);
14
+ if (!cache) {
15
+ cache = new Map();
16
+ for (const meta of metadata) {
17
+ for (const filterName of Object.keys(meta.filters)) {
18
+ const filter = meta.filters[filterName];
19
+ if (!filter.rls) {
20
+ continue;
21
+ }
22
+ const defs = cache.get(filterName) ?? [];
23
+ // inheritance shares the same filter object across base and child metadata — keep a single entry
24
+ if (!defs.some(d => d.filter === filter)) {
25
+ defs.push({ filter, entityName: meta.className });
26
+ }
27
+ cache.set(filterName, defs);
28
+ }
29
+ }
30
+ rlsFilterDefs.set(metadata, cache);
31
+ }
32
+ return cache.get(name) ?? [];
33
+ }
34
+ /**
35
+ * Drops the cached `rls` filter lookup — `MikroORM.discoverEntity()` mutates the shared MetadataStorage,
36
+ * so a lookup built before the call would miss the newly discovered filters.
37
+ *
38
+ * @internal
39
+ */
40
+ export function clearRlsFilterDefsCache(metadata) {
41
+ rlsFilterDefs.delete(metadata);
42
+ }
43
+ /**
44
+ * Computes the `rls` session variables a set of same-named filter defs stages for the given args, mirroring the
45
+ * policy compilation (`current_setting` names and custom `setting` binding). Shared by staging and `fork({ session })`.
46
+ * @internal
47
+ */
48
+ export function computeRlsFilterVariables(filters, args) {
49
+ const variables = {};
50
+ for (const { filter, entityName } of filters) {
51
+ const setting = typeof filter.rls === 'object' ? filter.rls.setting : undefined;
52
+ let settingArg;
53
+ if (setting) {
54
+ // mirror the policy compilation — a custom `setting` binds the single argument the condition accesses
55
+ const accessed = new Set();
56
+ QueryHelper.resolveRlsFilterCond(filter, accessed, entityName);
57
+ if (accessed.size > 1) {
58
+ throw MetadataError.rlsFilterMultiArgSetting(filter.name, [...accessed]);
59
+ }
60
+ settingArg = [...accessed][0];
61
+ }
62
+ for (const key of Object.keys(args)) {
63
+ const value = args[key];
64
+ // treat `undefined` like an omitted arg — staging it would serialize as the literal string 'undefined'
65
+ if (value === undefined) {
66
+ continue;
67
+ }
68
+ // a non-scalar arg has no equivalent in the compiled `= current_setting(...)` comparison — the app-level
69
+ // filter would apply `$in`/`is null` semantics while the policy compares against `String(value)`
70
+ if (value === null || (typeof value === 'object' && !(value instanceof Date))) {
71
+ throw ValidationError.cannotStageNonScalarSessionVariable(filter.name, key);
72
+ }
73
+ const settingName = key === settingArg ? setting : Utils.getRlsSettingName(filter.name, key);
74
+ variables[settingName] = value;
75
+ }
76
+ }
77
+ return variables;
78
+ }
79
+ /**
80
+ * Computes which staged session variables a `setFilterParams` call may prune: the variables the OLD args staged for
81
+ * this filter that the new args no longer set, minus any variable another filter's current params still stage
82
+ * (a custom `setting` name can be shared by differently named filters). Recomputing from the old args rather than
83
+ * matching by prefix keeps a filter named `tenant` from also pruning a `tenant.x` filter's `mikro.tenant.x.*` variables.
84
+ * @internal
85
+ */
86
+ export function computeRemovedRlsVariables(metadata, name, filters, previousArgs, nextVariables, allFilterParams) {
87
+ const removed = Object.keys(computeRlsFilterVariables(filters, previousArgs)).filter(key => !(key in nextVariables));
88
+ const keptByOthers = new Set();
89
+ for (const otherName of removed.length > 0 ? Object.keys(allFilterParams) : []) {
90
+ if (otherName !== name) {
91
+ for (const key of Object.keys(computeRlsFilterVariables(findRlsFilterDefs(metadata, otherName), allFilterParams[otherName]))) {
92
+ keptByOthers.add(key);
93
+ }
94
+ }
95
+ }
96
+ return removed.filter(key => !keptByOthers.has(key));
97
+ }