@mikro-orm/sql 7.3.0-dev.2 → 7.3.0-dev.21
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/AbstractSqlConnection.js +11 -0
- package/AbstractSqlDriver.d.ts +10 -0
- package/AbstractSqlDriver.js +133 -64
- package/AbstractSqlPlatform.js +1 -1
- package/SqlEntityManager.js +2 -1
- package/dialects/mssql/MsSqlNativeQueryBuilder.js +4 -3
- package/dialects/mysql/BaseMySqlPlatform.d.ts +11 -0
- package/dialects/mysql/BaseMySqlPlatform.js +20 -1
- package/dialects/mysql/MySqlNativeQueryBuilder.js +4 -3
- package/dialects/mysql/MySqlSchemaHelper.d.ts +8 -0
- package/dialects/mysql/MySqlSchemaHelper.js +35 -6
- package/dialects/oracledb/OracleNativeQueryBuilder.js +4 -3
- package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +1 -0
- package/dialects/postgresql/BasePostgreSqlPlatform.js +3 -0
- package/dialects/postgresql/PostgreSqlExceptionConverter.js +1 -0
- package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +7 -0
- package/dialects/postgresql/PostgreSqlSchemaHelper.js +159 -18
- package/dialects/sqlite/SqlitePlatform.d.ts +3 -1
- package/dialects/sqlite/SqlitePlatform.js +12 -0
- package/dialects/sqlite/SqliteSchemaHelper.d.ts +2 -0
- package/dialects/sqlite/SqliteSchemaHelper.js +32 -9
- package/index.d.ts +2 -0
- package/index.js +2 -0
- package/package.json +4 -4
- package/plugin/transformer.d.ts +2 -1
- package/plugin/transformer.js +39 -13
- package/query/CriteriaNode.d.ts +1 -0
- package/query/CriteriaNode.js +12 -3
- package/query/CriteriaNodeFactory.js +1 -1
- package/query/NativeQueryBuilder.d.ts +8 -0
- package/query/NativeQueryBuilder.js +40 -6
- package/query/ObjectCriteriaNode.d.ts +2 -0
- package/query/ObjectCriteriaNode.js +46 -20
- package/query/QueryBuilder.d.ts +13 -3
- package/query/QueryBuilder.js +110 -44
- package/query/QueryBuilderHelper.d.ts +2 -0
- package/query/QueryBuilderHelper.js +75 -24
- package/schema/DatabaseTable.js +36 -8
- package/schema/SchemaComparator.d.ts +2 -1
- package/schema/SchemaComparator.js +48 -23
- package/schema/SchemaHelper.d.ts +25 -1
- package/schema/SchemaHelper.js +68 -5
- package/schema/SqlSchemaGenerator.d.ts +7 -4
- package/schema/SqlSchemaGenerator.js +29 -10
- package/schema/partitioning.js +6 -6
- package/typings.d.ts +3 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mikro-orm/sql",
|
|
3
|
-
"version": "7.3.0-dev.
|
|
3
|
+
"version": "7.3.0-dev.21",
|
|
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",
|
|
@@ -47,13 +47,13 @@
|
|
|
47
47
|
"copy": "node ../../scripts/copy.mjs"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"kysely": "0.29.
|
|
50
|
+
"kysely": "0.29.8"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@mikro-orm/core": "^7.2.
|
|
53
|
+
"@mikro-orm/core": "^7.2.8"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@mikro-orm/core": "7.3.0-dev.
|
|
56
|
+
"@mikro-orm/core": "7.3.0-dev.21"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">= 22.17.0"
|
package/plugin/transformer.d.ts
CHANGED
|
@@ -92,6 +92,7 @@ export declare class MikroTransformer extends OperationNodeTransformer {
|
|
|
92
92
|
* This is called for SELECT queries when columnNamingStrategy is 'property'
|
|
93
93
|
*/
|
|
94
94
|
transformResult(rows: Record<string, any>[] | undefined, entityMap: Map<string, EntityMetadata>): Record<string, any>[] | undefined;
|
|
95
|
+
private getResultMaps;
|
|
95
96
|
buildGlobalFieldMap(entityMap: Map<string, EntityMetadata>): Record<string, EntityProperty>;
|
|
96
97
|
buildGlobalRelationFieldMap(entityMap: Map<string, EntityMetadata>): Record<string, string>;
|
|
97
98
|
/**
|
|
@@ -108,6 +109,6 @@ export declare class MikroTransformer extends OperationNodeTransformer {
|
|
|
108
109
|
/**
|
|
109
110
|
* Transform a single row by mapping column names to property names
|
|
110
111
|
*/
|
|
111
|
-
transformRow(row: Record<string, any>,
|
|
112
|
+
transformRow(row: Record<string, any>, fieldEntries: [string, EntityProperty][], relationEntries: [string, string][]): Record<string, any>;
|
|
112
113
|
prepareOutputValue(prop: EntityProperty | undefined, value: unknown): unknown;
|
|
113
114
|
}
|
package/plugin/transformer.js
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { ReferenceKind, isRaw, } from '@mikro-orm/core';
|
|
2
2
|
import { AliasNode, ColumnNode, ColumnUpdateNode, IdentifierNode, OperationNodeTransformer, PrimitiveValueListNode, RawNode, ReferenceNode, SchemableIdentifierNode, SelectAllNode, SelectionNode, TableNode, ValueListNode, ValueNode, ValuesNode, } from 'kysely';
|
|
3
|
+
/** Past this many query shapes the cache of one metadata storage starts over, so generated aliases cannot grow it. */
|
|
4
|
+
const RESULT_MAPS_LIMIT = 1000;
|
|
5
|
+
/**
|
|
6
|
+
* Result maps per query shape (the aliases and entities of its entity map). They are derived from metadata alone, so
|
|
7
|
+
* they are built once and shared by every transformer, as `getKysely()` creates a new one per call.
|
|
8
|
+
*/
|
|
9
|
+
const resultMapsCache = new WeakMap();
|
|
3
10
|
const EXPANDABLE_KINDS = new Set([
|
|
4
11
|
ReferenceKind.SCALAR,
|
|
5
12
|
ReferenceKind.EMBEDDED,
|
|
@@ -884,12 +891,7 @@ export class MikroTransformer extends OperationNodeTransformer {
|
|
|
884
891
|
if (byEntity) {
|
|
885
892
|
return byEntity;
|
|
886
893
|
}
|
|
887
|
-
|
|
888
|
-
const byTable = allMetadata.find(m => m.tableName === name);
|
|
889
|
-
if (byTable) {
|
|
890
|
-
return byTable;
|
|
891
|
-
}
|
|
892
|
-
return undefined;
|
|
894
|
+
return this.#metadata.getByTableName(name);
|
|
893
895
|
}
|
|
894
896
|
/**
|
|
895
897
|
* Transform result rows by mapping database column names to property names
|
|
@@ -906,11 +908,35 @@ export class MikroTransformer extends OperationNodeTransformer {
|
|
|
906
908
|
if (entityMap.size === 0) {
|
|
907
909
|
return rows;
|
|
908
910
|
}
|
|
909
|
-
//
|
|
910
|
-
const
|
|
911
|
-
const relationFieldMap = this.buildGlobalRelationFieldMap(entityMap);
|
|
911
|
+
// The global mapping from database field names to property objects, built once per query shape
|
|
912
|
+
const { fields, relations } = this.getResultMaps(entityMap);
|
|
912
913
|
// Transform each row
|
|
913
|
-
return rows.map(row => this.transformRow(row,
|
|
914
|
+
return rows.map(row => this.transformRow(row, fields, relations));
|
|
915
|
+
}
|
|
916
|
+
getResultMaps(entityMap) {
|
|
917
|
+
let byShape = resultMapsCache.get(this.#metadata);
|
|
918
|
+
if (!byShape) {
|
|
919
|
+
byShape = new Map();
|
|
920
|
+
resultMapsCache.set(this.#metadata, byShape);
|
|
921
|
+
}
|
|
922
|
+
let shape = '';
|
|
923
|
+
for (const [alias, meta] of entityMap) {
|
|
924
|
+
shape += `${alias}\0${meta._id}\0`;
|
|
925
|
+
}
|
|
926
|
+
const cached = byShape.get(shape);
|
|
927
|
+
if (cached && Array.from(entityMap.values()).every((meta, i) => meta.props === cached.props[i])) {
|
|
928
|
+
return cached;
|
|
929
|
+
}
|
|
930
|
+
if (byShape.size >= RESULT_MAPS_LIMIT) {
|
|
931
|
+
byShape.clear();
|
|
932
|
+
}
|
|
933
|
+
const maps = {
|
|
934
|
+
props: Array.from(entityMap.values(), meta => meta.props),
|
|
935
|
+
fields: Object.entries(this.buildGlobalFieldMap(entityMap)),
|
|
936
|
+
relations: Object.entries(this.buildGlobalRelationFieldMap(entityMap)),
|
|
937
|
+
};
|
|
938
|
+
byShape.set(shape, maps);
|
|
939
|
+
return maps;
|
|
914
940
|
}
|
|
915
941
|
buildGlobalFieldMap(entityMap) {
|
|
916
942
|
const map = {};
|
|
@@ -986,10 +1012,10 @@ export class MikroTransformer extends OperationNodeTransformer {
|
|
|
986
1012
|
/**
|
|
987
1013
|
* Transform a single row by mapping column names to property names
|
|
988
1014
|
*/
|
|
989
|
-
transformRow(row,
|
|
1015
|
+
transformRow(row, fieldEntries, relationEntries) {
|
|
990
1016
|
const transformed = { ...row };
|
|
991
1017
|
// First pass: map regular fields from fieldName to propertyName and convert values
|
|
992
|
-
for (const [fieldName, prop] of
|
|
1018
|
+
for (const [fieldName, prop] of fieldEntries) {
|
|
993
1019
|
if (!(fieldName in transformed)) {
|
|
994
1020
|
continue;
|
|
995
1021
|
}
|
|
@@ -1011,7 +1037,7 @@ export class MikroTransformer extends OperationNodeTransformer {
|
|
|
1011
1037
|
// Second pass: handle relation fields
|
|
1012
1038
|
// Only run if columnNamingStrategy is 'property', as we don't want to rename FKs otherwise
|
|
1013
1039
|
if (this.#options.columnNamingStrategy === 'property') {
|
|
1014
|
-
for (const [fieldName, relationPropertyName] of
|
|
1040
|
+
for (const [fieldName, relationPropertyName] of relationEntries) {
|
|
1015
1041
|
if (fieldName in transformed && !(relationPropertyName in transformed)) {
|
|
1016
1042
|
// Move the foreign key value to the relation property name
|
|
1017
1043
|
transformed[relationPropertyName] = transformed[fieldName];
|
package/query/CriteriaNode.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ export declare class CriteriaNode<T extends object> implements ICriteriaNode<T>
|
|
|
29
29
|
parentPath?: string;
|
|
30
30
|
}): string;
|
|
31
31
|
private isPivotJoin;
|
|
32
|
+
protected isOperatorPayload(payload: any): boolean;
|
|
32
33
|
getPivotPath(path: string): string;
|
|
33
34
|
aliased(field: string, alias?: string): string;
|
|
34
35
|
isStrict(): boolean;
|
package/query/CriteriaNode.js
CHANGED
|
@@ -29,7 +29,7 @@ export class CriteriaNode {
|
|
|
29
29
|
}
|
|
30
30
|
for (const k of pks) {
|
|
31
31
|
const [name, target] = QueryHelper.splitPolymorphicKey(k);
|
|
32
|
-
this.prop = meta.props.find(prop => (prop.name === name && (!target ||
|
|
32
|
+
this.prop = meta.props.find(prop => (prop.name === name && (!target || QueryHelper.findTargetMetas(prop, k).length > 0)) ||
|
|
33
33
|
(prop.fieldNames?.length === 1 && prop.fieldNames[0] === k && prop.persist !== false));
|
|
34
34
|
const isProp = this.prop || meta.props.find(prop => (prop.fieldNames || []).includes(k));
|
|
35
35
|
// do not validate if the key is prefixed or type casted (e.g. `k::text`)
|
|
@@ -131,8 +131,17 @@ export class CriteriaNode {
|
|
|
131
131
|
this.payload instanceof RegExp ||
|
|
132
132
|
this.payload instanceof Date ||
|
|
133
133
|
rawField;
|
|
134
|
-
|
|
135
|
-
|
|
134
|
+
return this.prop.kind === ReferenceKind.MANY_TO_MANY && (scalar || this.isOperatorPayload(this.payload));
|
|
135
|
+
}
|
|
136
|
+
isOperatorPayload(payload) {
|
|
137
|
+
return (Utils.isObject(payload) &&
|
|
138
|
+
Utils.getObjectQueryKeys(payload).every(k => {
|
|
139
|
+
if (k === '$not' && payload[k] instanceof CriteriaNode && Utils.isPlainObject(payload[k].payload)) {
|
|
140
|
+
// `$not` wrapping entity conditions is a condition on the target entity, not on the relation itself
|
|
141
|
+
return Utils.getObjectQueryKeys(payload[k].payload).every(ik => Utils.isOperator(ik, false));
|
|
142
|
+
}
|
|
143
|
+
return Utils.isOperator(k, false);
|
|
144
|
+
}));
|
|
136
145
|
}
|
|
137
146
|
getPivotPath(path) {
|
|
138
147
|
return `${path}[pivot]`;
|
|
@@ -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
|
|
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) {
|
|
@@ -66,9 +66,14 @@ interface OnConflictClause {
|
|
|
66
66
|
sql: string;
|
|
67
67
|
params: unknown[];
|
|
68
68
|
};
|
|
69
|
+
version?: {
|
|
70
|
+
field: string;
|
|
71
|
+
timestamp?: string;
|
|
72
|
+
};
|
|
69
73
|
}
|
|
70
74
|
/** @internal */
|
|
71
75
|
export declare class NativeQueryBuilder implements Subquery {
|
|
76
|
+
#private;
|
|
72
77
|
protected readonly platform: AbstractSqlPlatform;
|
|
73
78
|
readonly __subquery: true;
|
|
74
79
|
protected type?: QueryType;
|
|
@@ -103,6 +108,7 @@ export declare class NativeQueryBuilder implements Subquery {
|
|
|
103
108
|
};
|
|
104
109
|
protected addLockClause(): void;
|
|
105
110
|
protected addOnConflictClause(): void;
|
|
111
|
+
protected joinVersionMerge(clause: OnConflictClause, parts: string[], merged: unknown[]): string;
|
|
106
112
|
protected combineParts(): {
|
|
107
113
|
sql: string;
|
|
108
114
|
params: unknown[];
|
|
@@ -121,6 +127,8 @@ export declare class NativeQueryBuilder implements Subquery {
|
|
|
121
127
|
lockMode(lockMode: LockMode, lockTables?: string[]): this;
|
|
122
128
|
comment(comment: string | string[]): this;
|
|
123
129
|
hintComment(comment: string | string[]): this;
|
|
130
|
+
/** Comments are interpolated verbatim, so a terminator or a `?` placeholder inside one would corrupt the query. */
|
|
131
|
+
private validateComments;
|
|
124
132
|
setFlags(flags: Set<QueryFlag>): this;
|
|
125
133
|
clear(clause: keyof Options): this;
|
|
126
134
|
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 {
|
|
@@ -7,6 +7,8 @@ export class NativeQueryBuilder {
|
|
|
7
7
|
parts = [];
|
|
8
8
|
params = [];
|
|
9
9
|
options = {};
|
|
10
|
+
/** the table name or alias usable as a column qualifier (without the alias definition or index hint) */
|
|
11
|
+
#tableQualifier;
|
|
10
12
|
constructor(platform) {
|
|
11
13
|
this.platform = platform;
|
|
12
14
|
}
|
|
@@ -33,8 +35,14 @@ export class NativeQueryBuilder {
|
|
|
33
35
|
const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
|
|
34
36
|
const alias = options?.alias ? `${asKeyword}${this.platform.quoteIdentifier(options.alias)}` : '';
|
|
35
37
|
const schema = options?.schema && options.schema !== this.platform.getDefaultSchemaName() ? `${options.schema}.` : '';
|
|
38
|
+
this.#tableQualifier = options?.alias
|
|
39
|
+
? this.platform.quoteIdentifier(options.alias)
|
|
40
|
+
: this.quote(schema + tableName);
|
|
36
41
|
tableName = this.quote(schema + tableName) + alias;
|
|
37
42
|
}
|
|
43
|
+
else {
|
|
44
|
+
this.#tableQualifier = undefined;
|
|
45
|
+
}
|
|
38
46
|
this.options.tableName = tableName;
|
|
39
47
|
this.options.indexHint = options?.indexHint;
|
|
40
48
|
return this;
|
|
@@ -174,19 +182,19 @@ export class NativeQueryBuilder {
|
|
|
174
182
|
this.params.push(clause.merge[field]);
|
|
175
183
|
return `${this.quote(field)} = ?`;
|
|
176
184
|
});
|
|
177
|
-
this.parts.push(
|
|
185
|
+
this.parts.push(this.joinVersionMerge(clause, fields, Object.keys(clause.merge)));
|
|
178
186
|
}
|
|
179
187
|
else if (clause.merge) {
|
|
180
188
|
this.parts.push('do update set');
|
|
181
189
|
if (clause.merge.length) {
|
|
182
190
|
const fields = clause.merge.map(field => `${this.quote(field)} = excluded.${this.quote(field)}`);
|
|
183
|
-
this.parts.push(
|
|
191
|
+
this.parts.push(this.joinVersionMerge(clause, fields, clause.merge));
|
|
184
192
|
}
|
|
185
193
|
else {
|
|
186
194
|
const dataAsArray = Utils.asArray(this.options.data);
|
|
187
195
|
const keys = Object.keys(dataAsArray[0]);
|
|
188
196
|
const fields = keys.map(field => `${this.quote(field)} = excluded.${this.quote(field)}`);
|
|
189
|
-
this.parts.push(
|
|
197
|
+
this.parts.push(this.joinVersionMerge(clause, fields, keys));
|
|
190
198
|
}
|
|
191
199
|
}
|
|
192
200
|
if (clause.where) {
|
|
@@ -194,6 +202,17 @@ export class NativeQueryBuilder {
|
|
|
194
202
|
this.params.push(...clause.where.params);
|
|
195
203
|
}
|
|
196
204
|
}
|
|
205
|
+
joinVersionMerge(clause, parts, merged) {
|
|
206
|
+
if (clause.version && !merged.includes(clause.version.field)) {
|
|
207
|
+
const field = this.quote(clause.version.field);
|
|
208
|
+
// the existing row's version, as the `version + 1` of an update (a bare column is ambiguous with `excluded`)
|
|
209
|
+
parts = [
|
|
210
|
+
...parts,
|
|
211
|
+
`${field} = ${clause.version.timestamp ?? `${this.#tableQualifier ?? this.getTableName()}.${field} + 1`}`,
|
|
212
|
+
];
|
|
213
|
+
}
|
|
214
|
+
return parts.join(', ');
|
|
215
|
+
}
|
|
197
216
|
combineParts() {
|
|
198
217
|
let sql = this.parts.join(' ');
|
|
199
218
|
if (this.options.wrap) {
|
|
@@ -258,14 +277,23 @@ export class NativeQueryBuilder {
|
|
|
258
277
|
}
|
|
259
278
|
comment(comment) {
|
|
260
279
|
this.options.comment ??= [];
|
|
261
|
-
this.options.comment.push(...
|
|
280
|
+
this.options.comment.push(...this.validateComments(comment));
|
|
262
281
|
return this;
|
|
263
282
|
}
|
|
264
283
|
hintComment(comment) {
|
|
265
284
|
this.options.hintComment ??= [];
|
|
266
|
-
this.options.hintComment.push(...
|
|
285
|
+
this.options.hintComment.push(...this.validateComments(comment));
|
|
267
286
|
return this;
|
|
268
287
|
}
|
|
288
|
+
/** Comments are interpolated verbatim, so a terminator or a `?` placeholder inside one would corrupt the query. */
|
|
289
|
+
validateComments(comment) {
|
|
290
|
+
const comments = Utils.asArray(comment);
|
|
291
|
+
const invalid = comments.find(c => c.includes('/*') || c.includes('*/') || c.includes('?'));
|
|
292
|
+
if (invalid != null) {
|
|
293
|
+
throw new Error(`Query comments cannot contain '/*', '*/' or '?', got: '${invalid}'`);
|
|
294
|
+
}
|
|
295
|
+
return comments;
|
|
296
|
+
}
|
|
269
297
|
setFlags(flags) {
|
|
270
298
|
this.options.flags = flags;
|
|
271
299
|
return this;
|
|
@@ -520,3 +548,9 @@ export class NativeQueryBuilder {
|
|
|
520
548
|
return this.platform.quoteIdentifier(id);
|
|
521
549
|
}
|
|
522
550
|
}
|
|
551
|
+
// prototype-level brand recognized by `isSubquery()`, JSON payloads cannot forge it
|
|
552
|
+
Object.defineProperty(NativeQueryBuilder.prototype, SUBQUERY_BRAND, {
|
|
553
|
+
value: true,
|
|
554
|
+
writable: false,
|
|
555
|
+
configurable: false,
|
|
556
|
+
});
|
|
@@ -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
|
-
|
|
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.
|
|
228
|
-
|
|
229
|
-
|
|
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
|
|
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
|
-
|
|
297
|
-
|
|
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
|
-
|
|
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;
|
package/query/QueryBuilder.d.ts
CHANGED
|
@@ -803,6 +803,11 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
|
|
|
803
803
|
* Use `method` to specify what kind of result you want to get (array/single/meta).
|
|
804
804
|
*/
|
|
805
805
|
execute<U = any>(method?: 'all' | 'get' | 'run', options?: ExecuteOptions | boolean): Promise<U>;
|
|
806
|
+
/**
|
|
807
|
+
* An update or delete with auto-joined conditions stays a select until `finalize()` wraps it,
|
|
808
|
+
* so read the same flags `wrapModifySubQuery()` uses.
|
|
809
|
+
*/
|
|
810
|
+
private getExecuteType;
|
|
806
811
|
private getConnection;
|
|
807
812
|
/**
|
|
808
813
|
* Executes the query and returns an async iterable (async generator) that yields results one by one.
|
|
@@ -821,6 +826,7 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
|
|
|
821
826
|
* ```
|
|
822
827
|
*/
|
|
823
828
|
stream(options?: QBStreamOptions): AsyncIterableIterator<Loaded<Entity, Hint, Fields>>;
|
|
829
|
+
private convertStreamExceptions;
|
|
824
830
|
/**
|
|
825
831
|
* Alias for `qb.getResultList()`
|
|
826
832
|
*/
|
|
@@ -1003,6 +1009,10 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
|
|
|
1003
1009
|
processPopulateHint(): void;
|
|
1004
1010
|
private processPopulateWhere;
|
|
1005
1011
|
private mergeOnConditions;
|
|
1012
|
+
/**
|
|
1013
|
+
* `$not` can be moved to a join's `on` clause as a whole only when all of its conditions target that join.
|
|
1014
|
+
*/
|
|
1015
|
+
private getNotConditionAlias;
|
|
1006
1016
|
/**
|
|
1007
1017
|
* `$or` branches can be moved to a join's `on` clause only when they all target that same join
|
|
1008
1018
|
* and stay flat — a partial `$or` in the `on` clause would drop rows matching a sibling branch,
|
|
@@ -1012,9 +1022,9 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
|
|
|
1012
1022
|
private canDistributeOrBranches;
|
|
1013
1023
|
private getOrBranchAliases;
|
|
1014
1024
|
/**
|
|
1015
|
-
*
|
|
1016
|
-
*
|
|
1017
|
-
* can reference their aliases.
|
|
1025
|
+
* A condition that cannot be distributed (an entity filter's `$or`, or a `$not` spanning several joins)
|
|
1026
|
+
* is applied intact to the `on` clause of the outermost join common to all targeted joins, nesting
|
|
1027
|
+
* the targeted joins under it so the clause can reference their aliases.
|
|
1018
1028
|
*/
|
|
1019
1029
|
private mergeFilterOrCondition;
|
|
1020
1030
|
/**
|