@mikro-orm/sql 7.3.0-dev.2 → 7.3.0-dev.20

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 (41) hide show
  1. package/AbstractSqlConnection.js +11 -0
  2. package/AbstractSqlDriver.d.ts +10 -0
  3. package/AbstractSqlDriver.js +133 -64
  4. package/AbstractSqlPlatform.js +1 -1
  5. package/SqlEntityManager.js +2 -1
  6. package/dialects/mysql/BaseMySqlPlatform.d.ts +3 -0
  7. package/dialects/mysql/BaseMySqlPlatform.js +7 -0
  8. package/dialects/mysql/MySqlSchemaHelper.d.ts +8 -0
  9. package/dialects/mysql/MySqlSchemaHelper.js +33 -2
  10. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +1 -0
  11. package/dialects/postgresql/BasePostgreSqlPlatform.js +3 -0
  12. package/dialects/postgresql/PostgreSqlExceptionConverter.js +1 -0
  13. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +7 -0
  14. package/dialects/postgresql/PostgreSqlSchemaHelper.js +159 -18
  15. package/dialects/sqlite/SqlitePlatform.d.ts +3 -1
  16. package/dialects/sqlite/SqlitePlatform.js +12 -0
  17. package/dialects/sqlite/SqliteSchemaHelper.d.ts +2 -0
  18. package/dialects/sqlite/SqliteSchemaHelper.js +32 -9
  19. package/package.json +4 -4
  20. package/plugin/transformer.d.ts +2 -1
  21. package/plugin/transformer.js +39 -13
  22. package/query/CriteriaNode.d.ts +1 -0
  23. package/query/CriteriaNode.js +12 -3
  24. package/query/CriteriaNodeFactory.js +1 -1
  25. package/query/NativeQueryBuilder.d.ts +2 -0
  26. package/query/NativeQueryBuilder.js +18 -3
  27. package/query/ObjectCriteriaNode.d.ts +2 -0
  28. package/query/ObjectCriteriaNode.js +46 -20
  29. package/query/QueryBuilder.d.ts +8 -3
  30. package/query/QueryBuilder.js +78 -40
  31. package/query/QueryBuilderHelper.d.ts +2 -0
  32. package/query/QueryBuilderHelper.js +58 -21
  33. package/schema/DatabaseTable.js +34 -8
  34. package/schema/SchemaComparator.d.ts +1 -1
  35. package/schema/SchemaComparator.js +35 -22
  36. package/schema/SchemaHelper.d.ts +25 -1
  37. package/schema/SchemaHelper.js +68 -5
  38. package/schema/SqlSchemaGenerator.d.ts +7 -4
  39. package/schema/SqlSchemaGenerator.js +29 -10
  40. package/schema/partitioning.js +6 -6
  41. package/typings.d.ts +3 -1
@@ -52,7 +52,7 @@ export class CriteriaNodeFactory {
52
52
  const rawField = RawQueryFragment.isKnownFragmentSymbol(key);
53
53
  const prop = rawField ? null : meta?.properties[QueryHelper.splitPolymorphicKey(key)[0]];
54
54
  const target = rawField ? undefined : QueryHelper.findTargetMeta(prop, key);
55
- const childEntity = prop && prop.kind !== ReferenceKind.SCALAR ? (target ?? prop.targetMeta).class : entityName;
55
+ const childEntity = prop && prop.kind !== ReferenceKind.SCALAR && target ? target.class : entityName;
56
56
  const isNotEmbedded = rawField || prop?.kind !== ReferenceKind.EMBEDDED;
57
57
  const val = payload[key];
58
58
  if (isNotEmbedded && prop?.customType instanceof JsonType) {
@@ -121,6 +121,8 @@ export declare class NativeQueryBuilder implements Subquery {
121
121
  lockMode(lockMode: LockMode, lockTables?: string[]): this;
122
122
  comment(comment: string | string[]): this;
123
123
  hintComment(comment: string | string[]): this;
124
+ /** Comments are interpolated verbatim, so a terminator or a `?` placeholder inside one would corrupt the query. */
125
+ private validateComments;
124
126
  setFlags(flags: Set<QueryFlag>): this;
125
127
  clear(clause: keyof Options): this;
126
128
  wrap(prefix: string, suffix: string): this;
@@ -1,4 +1,4 @@
1
- import { isRaw, LockMode, raw, Utils, } from '@mikro-orm/core';
1
+ import { isRaw, LockMode, raw, SUBQUERY_BRAND, Utils, } from '@mikro-orm/core';
2
2
  import { QueryType } from './enums.js';
3
3
  /** @internal */
4
4
  export class NativeQueryBuilder {
@@ -258,14 +258,23 @@ export class NativeQueryBuilder {
258
258
  }
259
259
  comment(comment) {
260
260
  this.options.comment ??= [];
261
- this.options.comment.push(...Utils.asArray(comment));
261
+ this.options.comment.push(...this.validateComments(comment));
262
262
  return this;
263
263
  }
264
264
  hintComment(comment) {
265
265
  this.options.hintComment ??= [];
266
- this.options.hintComment.push(...Utils.asArray(comment));
266
+ this.options.hintComment.push(...this.validateComments(comment));
267
267
  return this;
268
268
  }
269
+ /** Comments are interpolated verbatim, so a terminator or a `?` placeholder inside one would corrupt the query. */
270
+ validateComments(comment) {
271
+ const comments = Utils.asArray(comment);
272
+ const invalid = comments.find(c => c.includes('/*') || c.includes('*/') || c.includes('?'));
273
+ if (invalid != null) {
274
+ throw new Error(`Query comments cannot contain '/*', '*/' or '?', got: '${invalid}'`);
275
+ }
276
+ return comments;
277
+ }
269
278
  setFlags(flags) {
270
279
  this.options.flags = flags;
271
280
  return this;
@@ -520,3 +529,9 @@ export class NativeQueryBuilder {
520
529
  return this.platform.quoteIdentifier(id);
521
530
  }
522
531
  }
532
+ // prototype-level brand recognized by `isSubquery()`, JSON payloads cannot forge it
533
+ Object.defineProperty(NativeQueryBuilder.prototype, SUBQUERY_BRAND, {
534
+ value: true,
535
+ writable: false,
536
+ configurable: false,
537
+ });
@@ -5,6 +5,8 @@ import type { ICriteriaNodeProcessOptions, IQueryBuilder } from '../typings.js';
5
5
  */
6
6
  export declare class ObjectCriteriaNode<T extends object> extends CriteriaNode<T> {
7
7
  process(qb: IQueryBuilder<T>, options?: ICriteriaNodeProcessOptions): any;
8
+ /** Orders by the first non-null value of the property across the joined polymorphic targets. */
9
+ private processPolymorphicOrderBy;
8
10
  isStrict(): boolean;
9
11
  unwrap(): any;
10
12
  willAutoJoin(qb: IQueryBuilder<T>, alias?: string, options?: ICriteriaNodeProcessOptions): boolean;
@@ -1,4 +1,4 @@
1
- import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
1
+ import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, QueryHelper, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
2
2
  import { CriteriaNode } from './CriteriaNode.js';
3
3
  import { JoinType, QueryType } from './enums.js';
4
4
  const COLLECTION_OPERATORS = ['$some', '$none', '$every', '$size', '$all'];
@@ -7,6 +7,10 @@ const COLLECTION_OPERATORS = ['$some', '$none', '$every', '$size', '$all'];
7
7
  */
8
8
  export class ObjectCriteriaNode extends CriteriaNode {
9
9
  process(qb, options) {
10
+ const targets = this.isPolymorphicBranch() ? QueryHelper.findTargetMetas(this.prop, this.key) : [];
11
+ if (options?.type === 'orderBy' && targets.length > 1) {
12
+ return this.processPolymorphicOrderBy(qb, targets, options);
13
+ }
10
14
  const matchPopulateJoins = options?.matchPopulateJoins ||
11
15
  (this.prop && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(this.prop.kind));
12
16
  const nestedAlias = qb.getAliasForJoinPath(this.getPath(options), { ...options, matchPopulateJoins });
@@ -57,6 +61,8 @@ export class ObjectCriteriaNode extends CriteriaNode {
57
61
  // schema-less entities the schema is resolved dynamically and needs to be carried over
58
62
  const fixedSchema = parentMeta.schema && parentMeta.schema !== '*';
59
63
  const qb2 = qb.clone(true, fixedSchema ? undefined : ['schema']);
64
+ // the payload was already converted when processing the parent query
65
+ qb2.unsetFlag(QueryFlag.CONVERT_CUSTOM_TYPES);
60
66
  const joinAlias = qb2.getNextAlias(this.prop.targetMeta.class);
61
67
  const sub = qb2
62
68
  .from(parentMeta.class)
@@ -150,12 +156,31 @@ export class ObjectCriteriaNode extends CriteriaNode {
150
156
  return o;
151
157
  }, {});
152
158
  // the target is left joined, so its condition must only match rows that point to it
153
- if (this.isPolymorphicBranch() && alias) {
159
+ if (this.isPolymorphicBranch() && alias && options?.type !== 'orderBy') {
154
160
  const pk = this.metadata.find(this.entityName).primaryKeys[0];
155
161
  this.inlineCondition(`${alias}.${pk}`, ret, { $ne: null });
156
162
  }
157
163
  return ret;
158
164
  }
165
+ /** Orders by the first non-null value of the property across the joined polymorphic targets. */
166
+ processPolymorphicOrderBy(qb, targets, options) {
167
+ const ownerAlias = options.alias || qb.alias;
168
+ const aliases = targets.map(target => {
169
+ const path = `${this.parent.getPath()}.${this.prop.name}[${target.className}]`;
170
+ const alias = qb.getAliasForJoinPath(path, { ...options, matchPopulateJoins: true });
171
+ if (alias) {
172
+ return alias;
173
+ }
174
+ const newAlias = qb.getNextAlias(target.class);
175
+ qb.addPolymorphicJoin(this.prop, target, ownerAlias, newAlias, JoinType.leftJoin, path);
176
+ return newAlias;
177
+ });
178
+ return Utils.getObjectQueryKeys(this.payload).reduce((o, field) => {
179
+ const columns = targets.map((target, i) => `${aliases[i]}.${target.properties[field].fieldNames[0]}`);
180
+ o[raw(`coalesce(${columns.map(() => '??').join(', ')})`, columns)] = this.payload[field].payload;
181
+ return o;
182
+ }, {});
183
+ }
159
184
  isStrict() {
160
185
  return (this.strict ||
161
186
  Utils.getObjectQueryKeys(this.payload).some(key => {
@@ -192,8 +217,9 @@ export class ObjectCriteriaNode extends CriteriaNode {
192
217
  const operator = Utils.isObject(payload) &&
193
218
  Utils.getObjectQueryKeys(payload).every(k => {
194
219
  if (k === '$not' && Utils.isPlainObject(payload[k])) {
195
- // $not wrapping non-operator conditions (entity props) should be inlined
196
- return Utils.getObjectQueryKeys(payload[k]).every(ik => Utils.isOperator(ik, false));
220
+ // $not wrapping non-operator conditions (entity props) or an empty one should be inlined
221
+ const inner = Utils.getObjectQueryKeys(payload[k]);
222
+ return inner.length > 0 && inner.every(ik => Utils.isOperator(ik, false));
197
223
  }
198
224
  return Utils.isOperator(k, false);
199
225
  });
@@ -224,9 +250,12 @@ export class ObjectCriteriaNode extends CriteriaNode {
224
250
  }
225
251
  else if (k === '$not' &&
226
252
  Utils.isPlainObject(payload[k]) &&
227
- Utils.getObjectQueryKeys(payload[k]).some(ik => !Utils.isOperator(ik, false))) {
228
- // $not wraps entity conditions (from auto-join), inline at current level
229
- this.inlineCondition(k, o, payload[k]);
253
+ (!Utils.hasObjectKeys(payload[k]) ||
254
+ Utils.getObjectQueryKeys(payload[k]).some(ik => !Utils.isOperator(ik, false)))) {
255
+ // $not wraps entity conditions (from auto-join) or an empty one, inline at current level with the same key mapping
256
+ const inner = {};
257
+ this.inlineChildPayload(inner, payload[k], field, alias, childAlias);
258
+ this.inlineCondition(k, o, inner);
230
259
  }
231
260
  else if (Utils.isOperator(k, false)) {
232
261
  const tmp = payload[k];
@@ -287,20 +316,16 @@ export class ObjectCriteriaNode extends CriteriaNode {
287
316
  const embeddable = this.prop.kind === ReferenceKind.EMBEDDED;
288
317
  const knownKey = [ReferenceKind.SCALAR, ReferenceKind.MANY_TO_ONE, ReferenceKind.EMBEDDED].includes(this.prop.kind) ||
289
318
  (this.prop.kind === ReferenceKind.ONE_TO_ONE && this.prop.owner);
290
- const operatorKeys = knownKey &&
319
+ const operatorKeys = knownKey && this.isOperatorPayload(this.payload);
320
+ const primaryKeys = knownKey &&
291
321
  keys.every(key => {
292
322
  if (key === '$not') {
293
- // $not wraps conditions like $and/$or, check if it wraps entity property conditions (needs auto-join)
294
- // vs simple operator conditions on the FK (doesn't need auto-join)
323
+ // e.g. `{ author: { $not: { id: 1 } } }` compares the FK column, relation PKs still need the join
295
324
  const childPayload = this.payload[key].payload;
296
- if (Utils.isPlainObject(childPayload)) {
297
- return Utils.getObjectQueryKeys(childPayload).every(k => Utils.isOperator(k, false));
298
- }
325
+ return (Utils.isPlainObject(childPayload) &&
326
+ Utils.getObjectQueryKeys(childPayload).every(k => meta.primaryKeys.includes(k) &&
327
+ meta.properties[k].kind === ReferenceKind.SCALAR));
299
328
  }
300
- return Utils.isOperator(key, false);
301
- });
302
- const primaryKeys = knownKey &&
303
- keys.every(key => {
304
329
  if (typeof key !== 'string' || !meta.primaryKeys.includes(key)) {
305
330
  return false;
306
331
  }
@@ -319,8 +344,7 @@ export class ObjectCriteriaNode extends CriteriaNode {
319
344
  this.payload instanceof RegExp ||
320
345
  this.payload instanceof Date ||
321
346
  rawField;
322
- const operator = Utils.isPlainObject(this.payload) &&
323
- Utils.getObjectQueryKeys(this.payload).every(k => Utils.isOperator(k, false));
347
+ const operator = Utils.isPlainObject(this.payload) && this.isOperatorPayload(this.payload);
324
348
  const field = `${alias}.${this.prop.name}`;
325
349
  const method = qb.hasFlag(QueryFlag.INFER_POPULATE) ? 'joinAndSelect' : 'join';
326
350
  const path = this.getPath();
@@ -334,7 +358,9 @@ export class ObjectCriteriaNode extends CriteriaNode {
334
358
  else {
335
359
  const prev = qb.state.fields?.slice();
336
360
  const toOneProperty = [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(this.prop.kind);
337
- const joinType = toOneProperty && !this.prop.nullable ? JoinType.innerJoin : JoinType.leftJoin;
361
+ // ordering must not drop rows whose polymorphic relation points to another target
362
+ const orderByPolymorphic = this.prop.polymorphic && options?.type === 'orderBy';
363
+ const joinType = toOneProperty && !this.prop.nullable && !orderByPolymorphic ? JoinType.innerJoin : JoinType.leftJoin;
338
364
  qb[method](field, nestedAlias, undefined, joinType, path);
339
365
  if (!qb.hasFlag(QueryFlag.INFER_POPULATE)) {
340
366
  qb.state.fields = prev;
@@ -821,6 +821,7 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
821
821
  * ```
822
822
  */
823
823
  stream(options?: QBStreamOptions): AsyncIterableIterator<Loaded<Entity, Hint, Fields>>;
824
+ private convertStreamExceptions;
824
825
  /**
825
826
  * Alias for `qb.getResultList()`
826
827
  */
@@ -1003,6 +1004,10 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
1003
1004
  processPopulateHint(): void;
1004
1005
  private processPopulateWhere;
1005
1006
  private mergeOnConditions;
1007
+ /**
1008
+ * `$not` can be moved to a join's `on` clause as a whole only when all of its conditions target that join.
1009
+ */
1010
+ private getNotConditionAlias;
1006
1011
  /**
1007
1012
  * `$or` branches can be moved to a join's `on` clause only when they all target that same join
1008
1013
  * and stay flat — a partial `$or` in the `on` clause would drop rows matching a sibling branch,
@@ -1012,9 +1017,9 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
1012
1017
  private canDistributeOrBranches;
1013
1018
  private getOrBranchAliases;
1014
1019
  /**
1015
- * An entity filter's `$or` that cannot be distributed is applied intact to the `on` clause of the
1016
- * outermost join common to all targeted joins, nesting the targeted joins under it so the clause
1017
- * can reference their aliases.
1020
+ * A condition that cannot be distributed (an entity filter's `$or`, or a `$not` spanning several joins)
1021
+ * is applied intact to the `on` clause of the outermost join common to all targeted joins, nesting
1022
+ * the targeted joins under it so the clause can reference their aliases.
1018
1023
  */
1019
1024
  private mergeFilterOrCondition;
1020
1025
  /**
@@ -1,5 +1,5 @@
1
1
  var _a;
2
- import { EntityMetadata, helper, inspect, isRaw, LoadStrategy, LockMode, PopulateHint, QueryFlag, QueryHelper, raw, RawQueryFragment, Reference, ReferenceKind, serialize, Utils, ValidationError, } from '@mikro-orm/core';
2
+ import { EntityMetadata, helper, inspect, isRaw, LoadStrategy, LockMode, PopulateHint, QueryFlag, QueryHelper, raw, RawQueryFragment, Reference, ReferenceKind, serialize, SUBQUERY_BRAND, Utils, ValidationError, } from '@mikro-orm/core';
3
3
  import { JoinType, QueryType } from './enums.js';
4
4
  import { QueryBuilderHelper } from './QueryBuilderHelper.js';
5
5
  import { CriteriaNodeFactory } from './CriteriaNodeFactory.js';
@@ -1032,9 +1032,11 @@ export class QueryBuilder {
1032
1032
  * @internal
1033
1033
  */
1034
1034
  addPolymorphicJoin(prop, targetMeta, ownerAlias, alias, type, path, schema) {
1035
- // Override referencedColumnNames to use the specific target's PK columns
1035
+ // Override referencedColumnNames to use the specific target's PK (or `targetKey`) columns
1036
1036
  // (polymorphic targets may have different PK column names, e.g. org_id vs user_id)
1037
- const referencedColumnNames = targetMeta.getPrimaryProps().flatMap(pk => pk.fieldNames);
1037
+ const referencedColumnNames = prop.targetKey
1038
+ ? targetMeta.properties[prop.targetKey].fieldNames
1039
+ : targetMeta.getPrimaryProps().flatMap(pk => pk.fieldNames);
1038
1040
  const targetProp = { ...prop, targetMeta, referencedColumnNames };
1039
1041
  const aliasedName = `${ownerAlias}.${prop.name}[${targetMeta.className}]#${alias}`;
1040
1042
  this.#state.joins[aliasedName] = this.helper.joinManyToOneReference(targetProp, ownerAlias, alias, type, {}, schema);
@@ -1078,12 +1080,19 @@ export class QueryBuilder {
1078
1080
  const conn = this.getConnection();
1079
1081
  // outside a transaction, wrap in a short implicit one so RLS `set local` session context applies (no-op when unset)
1080
1082
  const sessionContext = this.context ? undefined : this.em?.getTransactionSessionContext();
1081
- const res = await (sessionContext
1082
- ? conn.transactional(trx => conn.execute(query.sql, query.params, method, trx, loggerContext), {
1083
- sessionContext,
1084
- loggerContext,
1085
- })
1086
- : conn.execute(query.sql, query.params, method, this.context, loggerContext));
1083
+ let res;
1084
+ // a QueryBuilder used directly must honour the same `convertException` contract as the driver methods
1085
+ try {
1086
+ res = await (sessionContext
1087
+ ? conn.transactional(trx => conn.execute(query.sql, query.params, method, trx, loggerContext), {
1088
+ sessionContext,
1089
+ loggerContext,
1090
+ })
1091
+ : conn.execute(query.sql, query.params, method, this.context, loggerContext));
1092
+ }
1093
+ catch (e) {
1094
+ throw this.driver.convertException(e);
1095
+ }
1087
1096
  const meta = this.mainAlias.meta;
1088
1097
  if (!options.mapResults || !meta) {
1089
1098
  await this.em?.storeCache(this.#state.cache, cached, res);
@@ -1144,7 +1153,7 @@ export class QueryBuilder {
1144
1153
  const chunkSize = options.chunkSize ?? 100;
1145
1154
  const query = this.toQuery();
1146
1155
  const loggerContext = { id: this.em?.id, ...this.loggerContext, ...this.#abortOptions };
1147
- const res = this.getConnection().stream(query.sql, query.params, this.context, loggerContext, chunkSize);
1156
+ const res = this.convertStreamExceptions(this.getConnection().stream(query.sql, query.params, this.context, loggerContext, chunkSize));
1148
1157
  const meta = this.mainAlias.meta;
1149
1158
  if (options.rawResults || !meta) {
1150
1159
  yield* res;
@@ -1155,8 +1164,9 @@ export class QueryBuilder {
1155
1164
  const hash = (data) => {
1156
1165
  return Utils.getPrimaryKeyHash(meta.primaryKeys.map(pk => data[pk]));
1157
1166
  };
1167
+ const map = {};
1158
1168
  for await (const row of res) {
1159
- const mapped = this.driver.mapResult(row, meta, this.#state.populate, this);
1169
+ const mapped = this.driver.mapResult(row, meta, this.#state.populate, this, map);
1160
1170
  if (!options.mergeResults || joinedProps.length === 0) {
1161
1171
  yield this.mapResult(mapped, options.mapResults);
1162
1172
  continue;
@@ -1177,6 +1187,14 @@ export class QueryBuilder {
1177
1187
  }
1178
1188
  }
1179
1189
  }
1190
+ async *convertStreamExceptions(res) {
1191
+ try {
1192
+ yield* res;
1193
+ }
1194
+ catch (e) {
1195
+ throw this.driver.convertException(e);
1196
+ }
1197
+ }
1180
1198
  /**
1181
1199
  * Alias for `qb.getResultList()`
1182
1200
  */
@@ -1555,7 +1573,10 @@ export class QueryBuilder {
1555
1573
  field = asMatch[1].trim();
1556
1574
  customAlias = asMatch[2];
1557
1575
  }
1558
- const join = Object.keys(this.#state.joins).find(k => field === k.substring(0, k.indexOf('#')));
1576
+ // an aliased field is always a column, never a relation to expand, even when an FK column is named like its relation
1577
+ const join = customAlias
1578
+ ? undefined
1579
+ : Object.keys(this.#state.joins).find(k => field === k.substring(0, k.indexOf('#')));
1559
1580
  if (join && type === 'where') {
1560
1581
  ret.push(...this.helper.mapJoinColumns(this.type, this.#state.joins[join]));
1561
1582
  return;
@@ -1566,6 +1587,19 @@ export class QueryBuilder {
1566
1587
  if (prop && [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
1567
1588
  return;
1568
1589
  }
1590
+ // the joined strategy selects by column name, which can collide with the name of another property
1591
+ const shadowed = customAlias &&
1592
+ prop &&
1593
+ (prop.kind === ReferenceKind.EMBEDDED ||
1594
+ (customAlias.endsWith(`__${f}`) && (prop.persist === false || !prop.fieldNames.includes(f)))) &&
1595
+ (this.#state.aliases[a]?.meta ?? this.mainAlias.meta).props.some(p => p !== prop &&
1596
+ p.persist !== false &&
1597
+ (p.kind !== ReferenceKind.EMBEDDED || p.object) &&
1598
+ p.fieldNames?.includes(f));
1599
+ if (shadowed) {
1600
+ ret.push(raw('?? as ??', [`${a}.${f}`, customAlias]));
1601
+ return;
1602
+ }
1569
1603
  if (prop?.persist === false && !prop.embedded && !prop.formula && type === 'where') {
1570
1604
  return;
1571
1605
  }
@@ -1575,11 +1609,7 @@ export class QueryBuilder {
1575
1609
  ret.push(getFieldName(aliased, customAlias));
1576
1610
  return;
1577
1611
  }
1578
- // the joined strategy selects by column name, which can collide with an inline embedded property name
1579
- const shadowed = customAlias &&
1580
- prop?.kind === ReferenceKind.EMBEDDED &&
1581
- (this.#state.aliases[a]?.meta ?? this.mainAlias.meta).props.some(p => (p.kind !== ReferenceKind.EMBEDDED || p.object) && p.fieldNames?.includes(f));
1582
- if (prop?.kind === ReferenceKind.EMBEDDED && !shadowed) {
1612
+ if (prop?.kind === ReferenceKind.EMBEDDED) {
1583
1613
  if (customAlias) {
1584
1614
  throw new Error(`Cannot use 'as ${customAlias}' alias on embedded property '${field}' because it expands to multiple columns. Alias individual fields instead (e.g. '${field}.propertyName as ${customAlias}').`);
1585
1615
  }
@@ -1871,20 +1901,7 @@ export class QueryBuilder {
1871
1901
  if (meta.root.inheritanceType !== 'sti' || !meta.discriminatorValue) {
1872
1902
  return;
1873
1903
  }
1874
- const types = Object.values(meta.root.discriminatorMap).map(cls => this.metadata.get(cls));
1875
- const children = [];
1876
- const lookUpChildren = (ret, parent) => {
1877
- const children = types.filter(meta2 => meta2.extends && this.metadata.find(meta2.extends) === parent);
1878
- children.forEach(m => lookUpChildren(ret, m));
1879
- ret.push(...children.filter(c => c.discriminatorValue));
1880
- return children;
1881
- };
1882
- lookUpChildren(children, meta);
1883
- this.andWhere({
1884
- [meta.root.discriminatorColumn]: children.length > 0
1885
- ? { $in: [meta.discriminatorValue, ...children.map(c => c.discriminatorValue)] }
1886
- : meta.discriminatorValue,
1887
- });
1904
+ this.andWhere({ [meta.root.discriminatorColumn]: this.helper.getDiscriminatorCondition(meta) });
1888
1905
  }
1889
1906
  /**
1890
1907
  * Ensures TPT joins are applied. Can be called early before finalize() to populate
@@ -1941,7 +1958,8 @@ export class QueryBuilder {
1941
1958
  if (parentAlias) {
1942
1959
  const schema = parentMeta.schema === '*' ? '*' : this.driver.getSchemaName(parentMeta);
1943
1960
  parentMeta
1944
- .ownProps.filter(prop => this.platform.shouldHaveColumn(prop, []))
1961
+ // inherited formulas are selected on the main alias in `finalize()`
1962
+ .ownProps.filter(prop => !prop.formula && this.platform.shouldHaveColumn(prop, []))
1945
1963
  .forEach(prop => this.#state.fields.push(...this.driver.mapPropToFieldNames(this, prop, parentAlias, parentMeta, schema)));
1946
1964
  }
1947
1965
  parentMeta = parentMeta.tptParent;
@@ -1960,12 +1978,16 @@ export class QueryBuilder {
1960
1978
  if (!this.#state.fields?.includes('*') && !this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`)) {
1961
1979
  return;
1962
1980
  }
1963
- // LEFT JOIN each descendant table and add their fields
1981
+ // LEFT JOIN each descendant table
1964
1982
  for (const childMeta of descendants) {
1965
1983
  const childAlias = this.getNextAlias(childMeta.className);
1966
1984
  this.createAlias(childMeta.class, childAlias);
1967
1985
  this.#state.tptAlias[childMeta.className] = childAlias;
1968
1986
  this.addPropertyJoin(childMeta.tptInverseProp, this.mainAlias.aliasName, childAlias, JoinType.leftJoin, `[tpt]${meta.className}`);
1987
+ }
1988
+ this.driver.registerTPTAncestorAliases(this, meta, this.mainAlias.aliasName, this.#state.tptAlias);
1989
+ for (const childMeta of descendants) {
1990
+ const childAlias = this.#state.tptAlias[childMeta.className];
1969
1991
  // Add child fields
1970
1992
  const schema = childMeta.schema === '*' ? '*' : this.driver.getSchemaName(childMeta);
1971
1993
  childMeta
@@ -1974,7 +1996,7 @@ export class QueryBuilder {
1974
1996
  }
1975
1997
  // Add computed discriminator (CASE WHEN to determine concrete type)
1976
1998
  // descendants is pre-sorted by depth (deepest first) during discovery
1977
- if (meta.tptDiscriminatorColumn) {
1999
+ if (meta.root.tptDiscriminatorColumn) {
1978
2000
  this.#state.fields.push(this.driver.buildTPTDiscriminatorExpression(meta, descendants, this.#state.tptAlias, this.mainAlias.aliasName));
1979
2001
  }
1980
2002
  }
@@ -1994,7 +2016,7 @@ export class QueryBuilder {
1994
2016
  this.processNestedJoins();
1995
2017
  if (meta && (this.#state.fields?.includes('*') || this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`))) {
1996
2018
  const schema = this.getSchema(this.mainAlias);
1997
- // Create a column mapping with unquoted aliases - quoting should be handled by the user via `quote` helper
2019
+ // Per-column entries are unquoted (meant for `quote`), while `toString()` yields the quoted alias for plain template literals
1998
2020
  // For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
1999
2021
  const quotedMainAlias = this.platform.quoteIdentifier(this.mainAlias.aliasName).toString();
2000
2022
  const columns = meta.createColumnMappingObject(prop => this.helper.getTPTAliasForProperty(prop.name, this.mainAlias.aliasName), quotedMainAlias);
@@ -2098,7 +2120,13 @@ export class QueryBuilder {
2098
2120
  }
2099
2121
  mergeOnConditions(joins, cond, filter, op) {
2100
2122
  for (const k of Object.keys(cond)) {
2101
- if (Utils.isOperator(k)) {
2123
+ const notAlias = k === '$not' ? this.getNotConditionAlias(cond[k], joins) : undefined;
2124
+ if (k === '$not' && !notAlias) {
2125
+ // splitting a `$not` across joins would drop the negation, so it is kept intact on their common ancestor join
2126
+ this.mergeFilterOrCondition([{ $not: cond[k] }], joins);
2127
+ continue;
2128
+ }
2129
+ if (Utils.isOperator(k) && !notAlias) {
2102
2130
  if (Array.isArray(cond[k])) {
2103
2131
  if (k === '$or' && !this.canDistributeOrBranches(cond[k], joins)) {
2104
2132
  // entity filters have no other sink, so their `$or` is kept intact on the outermost targeted join instead
@@ -2112,7 +2140,7 @@ export class QueryBuilder {
2112
2140
  /* v8 ignore next */
2113
2141
  this.mergeOnConditions(joins, cond[k], filter, k);
2114
2142
  }
2115
- const [alias] = this.helper.splitField(k);
2143
+ const alias = notAlias ?? this.helper.splitField(k)[0];
2116
2144
  const join = joins.find(j => j.alias === alias);
2117
2145
  if (join) {
2118
2146
  const parentJoin = joins.find(j => j.alias === join.ownerAlias);
@@ -2141,6 +2169,14 @@ export class QueryBuilder {
2141
2169
  }
2142
2170
  }
2143
2171
  }
2172
+ /**
2173
+ * `$not` can be moved to a join's `on` clause as a whole only when all of its conditions target that join.
2174
+ */
2175
+ getNotConditionAlias(cond, joins) {
2176
+ const aliases = this.getOrBranchAliases([cond]);
2177
+ const [alias] = aliases;
2178
+ return aliases.size === 1 && joins.some(j => j.alias === alias) ? alias : undefined;
2179
+ }
2144
2180
  /**
2145
2181
  * `$or` branches can be moved to a join's `on` clause only when they all target that same join
2146
2182
  * and stay flat — a partial `$or` in the `on` clause would drop rows matching a sibling branch,
@@ -2169,9 +2205,9 @@ export class QueryBuilder {
2169
2205
  return aliases;
2170
2206
  }
2171
2207
  /**
2172
- * An entity filter's `$or` that cannot be distributed is applied intact to the `on` clause of the
2173
- * outermost join common to all targeted joins, nesting the targeted joins under it so the clause
2174
- * can reference their aliases.
2208
+ * A condition that cannot be distributed (an entity filter's `$or`, or a `$not` spanning several joins)
2209
+ * is applied intact to the `on` clause of the outermost join common to all targeted joins, nesting
2210
+ * the targeted joins under it so the clause can reference their aliases.
2175
2211
  */
2176
2212
  mergeFilterOrCondition(branches, joins) {
2177
2213
  const aliases = this.getOrBranchAliases(branches);
@@ -2639,3 +2675,5 @@ export class QueryBuilder {
2639
2675
  }
2640
2676
  }
2641
2677
  _a = QueryBuilder;
2678
+ // prototype-level brand recognized by `isSubquery()`, JSON payloads cannot forge it
2679
+ Object.defineProperty(QueryBuilder.prototype, SUBQUERY_BRAND, { value: true, writable: false, configurable: false });
@@ -30,6 +30,8 @@ export declare class QueryBuilderHelper {
30
30
  sql: string;
31
31
  params: unknown[];
32
32
  };
33
+ /** STI discriminator condition matching the entity and all its subclasses. */
34
+ getDiscriminatorCondition(meta: EntityMetadata): unknown;
33
35
  mapJoinColumns(type: QueryType, join: JoinOptions): (string | Raw)[];
34
36
  isOneToOneInverse(field: string, meta?: EntityMetadata): boolean;
35
37
  getTableName(entityName: EntityName): string;
@@ -1,7 +1,17 @@
1
- import { ALIAS_REPLACEMENT, ALIAS_REPLACEMENT_RE, ArrayType, JsonType, inspect, isRaw, LockMode, OptimisticLockError, QueryOperator, QueryOrderNumeric, raw, Raw, QueryHelper, ReferenceKind, Utils, ValidationError, } from '@mikro-orm/core';
1
+ import { ALIAS_REPLACEMENT, ALIAS_REPLACEMENT_RE, ArrayType, JsonType, inspect, isRaw, isSubquery, LockMode, OptimisticLockError, QueryOperator, QueryOrderNumeric, raw, Raw, QueryHelper, ReferenceKind, Utils, ValidationError, } from '@mikro-orm/core';
2
2
  import { EMBEDDABLE_ARRAY_OPS, JoinType, QueryType } from './enums.js';
3
3
  /** Captures the column name that follows the alias placeholder. */
4
4
  const QUALIFYING_ALIAS_RE = new RegExp(ALIAS_REPLACEMENT_RE + '(?=["\'`\\]]*\\.["\'`\\[]?([\\w$]+))', 'g');
5
+ /** Maps regexp tokens to LIKE pattern tokens, escaping LIKE wildcards with `!`. */
6
+ const LIKE_REPLACEMENTS = {
7
+ '\\.': '.',
8
+ '\\/': '/',
9
+ '.*': '%',
10
+ '.': '_',
11
+ '!': '!!',
12
+ '%': '!%',
13
+ _: '!_',
14
+ };
5
15
  /**
6
16
  * @internal
7
17
  */
@@ -286,7 +296,7 @@ export class QueryBuilderHelper {
286
296
  !join.path?.endsWith('[pivot]')) {
287
297
  const typeProperty = join.prop.targetMeta.root.discriminatorColumn;
288
298
  const alias = join.inverseAlias ?? join.alias;
289
- join.cond[`${alias}.${typeProperty}`] = join.prop.targetMeta.discriminatorValue;
299
+ join.cond[`${alias}.${typeProperty}`] = this.getDiscriminatorCondition(join.prop.targetMeta);
290
300
  }
291
301
  // For polymorphic relations, add discriminator condition to filter by target entity type
292
302
  if (join.prop.polymorphic && join.prop.discriminatorColumn && join.prop.discriminatorMap) {
@@ -331,6 +341,22 @@ export class QueryBuilderHelper {
331
341
  }
332
342
  return { sql, params };
333
343
  }
344
+ /** STI discriminator condition matching the entity and all its subclasses. */
345
+ getDiscriminatorCondition(meta) {
346
+ const types = Object.values(meta.root.discriminatorMap).map(cls => this.#metadata.get(cls));
347
+ const children = [];
348
+ const lookUpChildren = (ret, parent) => {
349
+ const children = types.filter(meta2 => meta2.extends && this.#metadata.find(meta2.extends) === parent);
350
+ children.forEach(m => lookUpChildren(ret, m));
351
+ ret.push(...children.filter(c => c.discriminatorValue));
352
+ return children;
353
+ };
354
+ // resolve from storage, `prop.targetMeta` can be a copy that fails the identity check above
355
+ lookUpChildren(children, this.#metadata.get(meta.class));
356
+ return children.length > 0
357
+ ? { $in: [meta.discriminatorValue, ...children.map(c => c.discriminatorValue)] }
358
+ : meta.discriminatorValue;
359
+ }
334
360
  mapJoinColumns(type, join) {
335
361
  if (join.prop && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(join.prop.kind)) {
336
362
  return join.prop.fieldNames.map((_fieldName, idx) => {
@@ -359,19 +385,17 @@ export class QueryBuilderHelper {
359
385
  if (!(re instanceof RegExp)) {
360
386
  return false;
361
387
  }
362
- if (re.flags.includes('i')) {
388
+ if (/[im]/.test(re.flags)) {
363
389
  return false;
364
390
  }
365
- // when including the opening bracket/paren we consider it complex
366
- return !/[{[(]/.exec(re.source);
391
+ // LIKE can only express edge anchors, `.`, `.*` and escaped `.` or `/`, anything else needs the regexp operator
392
+ return /^\^?(?:[^\\^$.*+?|{}[\]()]|\\[./]|\.\*?)*\$?$/.test(re.source);
367
393
  }
368
394
  getRegExpParam(re) {
369
395
  const value = re.source
370
- .replace(/\.\*/g, '%') // .* -> %
371
- .replace(/\./g, '_') // . -> _
372
- .replace(/\\_/g, '.') // \. -> .
373
- .replace(/^\^/g, '') // remove ^ from start
374
- .replace(/\$$/g, ''); // remove $ from end
396
+ .replace(/^\^/, '') // remove ^ from start
397
+ .replace(/\$$/, '') // remove $ from end
398
+ .replace(/\\[./]|\.\*|[.!%_]/g, m => LIKE_REPLACEMENTS[m]);
375
399
  if (re.source.startsWith('^') && re.source.endsWith('$')) {
376
400
  return value;
377
401
  }
@@ -445,7 +469,8 @@ export class QueryBuilderHelper {
445
469
  const parts = [];
446
470
  const params = [];
447
471
  if (this.isSimpleRegExp(cond[key])) {
448
- parts.push(`${this.#platform.quoteIdentifier(this.mapper(key, type))} like ?`);
472
+ const escape = /[!%_]/.test(cond[key].source) ? ` escape '!'` : '';
473
+ parts.push(`${this.#platform.quoteIdentifier(this.mapper(key, type))} like ?${escape}`);
449
474
  params.push(this.getRegExpParam(cond[key]));
450
475
  return { sql: parts.join(' and '), params };
451
476
  }
@@ -588,7 +613,7 @@ export class QueryBuilderHelper {
588
613
  else {
589
614
  const opValue = value[op];
590
615
  const opValueIsRaw = isRaw(opValue);
591
- if (opValueIsRaw || typeof opValue?.toRaw === 'function') {
616
+ if (opValueIsRaw || isSubquery(opValue)) {
592
617
  const query = opValueIsRaw ? opValue : opValue.toRaw();
593
618
  const mappedKey = this.mapper(key, type, query, null);
594
619
  let sql = this.replaceAliases(query.sql);
@@ -598,6 +623,19 @@ export class QueryBuilderHelper {
598
623
  parts.push(`${this.#platform.quoteIdentifier(mappedKey)} ${replacement} ${sql}`);
599
624
  params.push(...query.params);
600
625
  }
626
+ else if (['$in', '$nin'].includes(op) &&
627
+ prop?.customType instanceof ArrayType &&
628
+ Array.isArray(opValue) &&
629
+ !opValue.every((v) => Array.isArray(v))) {
630
+ // a flat list on an array column matches any of its elements, like in mongo
631
+ if (!this.#platform.supportsArrayOverlap()) {
632
+ throw new ValidationError(`${op} on array property ${prop.name} expects a list of arrays, use $eq for an exact match`);
633
+ }
634
+ const mappedKey = this.mapper(key, type, opValue, null);
635
+ const sql = `${this.#platform.quoteIdentifier(mappedKey)} && ?`;
636
+ parts.push(op === '$in' ? sql : `not (${sql})`);
637
+ params.push(prop.customType.convertToDatabaseValue(opValue, this.#platform, { fromQuery: true, key: op, mode: 'query' }));
638
+ }
601
639
  else {
602
640
  const mappedKey = this.mapper(key, type, opValue, null);
603
641
  const val = this.getValueReplacement(fields, opValue, params, op, prop, rowValues);
@@ -616,16 +654,15 @@ export class QueryBuilderHelper {
616
654
  }
617
655
  return `(${tmp.join(', ')})`;
618
656
  }
619
- // array custom types (e.g. `$contains`/`$overlap` on `string[]` columns) are converted to a single
620
- // array literal, so we emit a single bound parameter — not one per element wrapped in a tuple
657
+ // array custom types convert a whole array into one literal, so each candidate array binds a single parameter
621
658
  if (prop?.customType instanceof ArrayType) {
622
- const item = prop.customType.convertToDatabaseValue(value, this.#platform, {
623
- fromQuery: true,
624
- key,
625
- mode: 'query',
626
- });
627
- params.push(item);
628
- return '?';
659
+ const list = key === '$in' || key === '$nin';
660
+ const items = list ? value : [value];
661
+ for (const item of items) {
662
+ params.push(prop.customType.convertToDatabaseValue(item, this.#platform, { fromQuery: true, key, mode: 'query' }));
663
+ }
664
+ const sql = items.map(() => '?').join(', ');
665
+ return list ? `(${sql})` : sql;
629
666
  }
630
667
  value.forEach(p => params.push(p));
631
668
  return `(${value.map(() => '?').join(', ')})`;