@mikro-orm/sql 7.3.0-dev.17 → 7.3.0-dev.19
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 +120 -59
- package/AbstractSqlPlatform.js +1 -1
- package/dialects/mysql/BaseMySqlPlatform.d.ts +2 -0
- package/dialects/mysql/BaseMySqlPlatform.js +4 -0
- package/dialects/mysql/MySqlSchemaHelper.d.ts +2 -0
- package/dialects/mysql/MySqlSchemaHelper.js +15 -2
- 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 +1 -0
- package/dialects/postgresql/PostgreSqlSchemaHelper.js +77 -7
- package/dialects/sqlite/SqlitePlatform.d.ts +2 -1
- package/dialects/sqlite/SqlitePlatform.js +9 -0
- package/dialects/sqlite/SqliteSchemaHelper.d.ts +1 -0
- package/dialects/sqlite/SqliteSchemaHelper.js +12 -5
- package/package.json +4 -4
- package/query/CriteriaNode.d.ts +1 -0
- package/query/CriteriaNode.js +11 -2
- package/query/NativeQueryBuilder.d.ts +2 -0
- package/query/NativeQueryBuilder.js +18 -3
- package/query/ObjectCriteriaNode.js +4 -14
- package/query/QueryBuilder.d.ts +8 -3
- package/query/QueryBuilder.js +74 -38
- package/query/QueryBuilderHelper.d.ts +2 -0
- package/query/QueryBuilderHelper.js +40 -12
- package/schema/DatabaseTable.js +25 -6
- package/schema/SchemaComparator.js +22 -18
- package/schema/SchemaHelper.d.ts +9 -0
- package/schema/SchemaHelper.js +18 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { MetadataError } from '@mikro-orm/core';
|
|
1
2
|
import { AbstractSqlPlatform } from '../../AbstractSqlPlatform.js';
|
|
2
3
|
import { SqliteNativeQueryBuilder } from './SqliteNativeQueryBuilder.js';
|
|
3
4
|
import { SqliteSchemaHelper } from './SqliteSchemaHelper.js';
|
|
@@ -113,6 +114,14 @@ export class SqlitePlatform extends AbstractSqlPlatform {
|
|
|
113
114
|
// Return 'main' only when schema support is active (i.e., databases are attached)
|
|
114
115
|
return this.supportsSchemas() ? 'main' : undefined;
|
|
115
116
|
}
|
|
117
|
+
validateMetadata(meta) {
|
|
118
|
+
super.validateMetadata(meta);
|
|
119
|
+
// `main` always exists and `*` resolves at runtime; anything else fails later as `unknown database` unless attached
|
|
120
|
+
const attached = this.config.get('attachDatabases')?.some(db => db.name === meta.schema);
|
|
121
|
+
if (meta.schema && !['main', '*'].includes(meta.schema) && !attached) {
|
|
122
|
+
throw new MetadataError(`Entity ${meta.className} declares schema '${meta.schema}', but SQLite cannot address it: attach it via \`attachDatabases\` or remove the schema in \`discovery.onMetadata\` when sharing entities between drivers`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
116
125
|
getFullTextWhereClause() {
|
|
117
126
|
return `:column: match :query`;
|
|
118
127
|
}
|
|
@@ -8,6 +8,7 @@ export declare class SqliteSchemaHelper extends SchemaHelper {
|
|
|
8
8
|
private static readonly PARTIAL_WHERE_RE;
|
|
9
9
|
disableForeignKeysSQL(): string;
|
|
10
10
|
enableForeignKeysSQL(): string;
|
|
11
|
+
getForeignKeyCheckSQL(): string;
|
|
11
12
|
supportsSchemaConstraints(): boolean;
|
|
12
13
|
getCreateNamespaceSQL(name: string): string;
|
|
13
14
|
getDropNamespaceSQL(name: string): string;
|
|
@@ -22,6 +22,9 @@ export class SqliteSchemaHelper extends SchemaHelper {
|
|
|
22
22
|
enableForeignKeysSQL() {
|
|
23
23
|
return 'pragma foreign_keys = on;';
|
|
24
24
|
}
|
|
25
|
+
getForeignKeyCheckSQL() {
|
|
26
|
+
return 'pragma foreign_key_check';
|
|
27
|
+
}
|
|
25
28
|
supportsSchemaConstraints() {
|
|
26
29
|
return false;
|
|
27
30
|
}
|
|
@@ -128,8 +131,10 @@ export class SqliteSchemaHelper extends SchemaHelper {
|
|
|
128
131
|
sql += `, primary key (${primaryKey.columnNames.map(c => this.quote(c)).join(', ')})`;
|
|
129
132
|
}
|
|
130
133
|
const parts = [];
|
|
131
|
-
|
|
132
|
-
|
|
134
|
+
if (this.options.createForeignKeyConstraints) {
|
|
135
|
+
for (const fk of Object.values(table.getForeignKeys())) {
|
|
136
|
+
parts.push(this.createForeignKey(table, fk, false));
|
|
137
|
+
}
|
|
133
138
|
}
|
|
134
139
|
for (const check of table.getChecks()) {
|
|
135
140
|
const sql = `constraint ${this.quote(check.name)} check (${check.expression})`;
|
|
@@ -253,7 +258,8 @@ export class SqliteSchemaHelper extends SchemaHelper {
|
|
|
253
258
|
}
|
|
254
259
|
for (let i = cols.length - 1; i >= 0; i--) {
|
|
255
260
|
const col = cols[i];
|
|
256
|
-
|
|
261
|
+
// the first column is not preceded by a comma
|
|
262
|
+
const re = ` *(?:^|,) *[\`"']?${col.name}[\`"']? (.*)`;
|
|
257
263
|
const columnDef = new RegExp(re, 'i').exec(columnsDef);
|
|
258
264
|
if (columnDef) {
|
|
259
265
|
columns[col.name] = { name: col.name, definition: columnDef[1] };
|
|
@@ -511,7 +517,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
|
|
|
511
517
|
const [schemaName, tableName] = this.splitTableName(diff.name);
|
|
512
518
|
if (Utils.hasObjectKeys(diff.removedChecks) ||
|
|
513
519
|
Utils.hasObjectKeys(diff.changedChecks) ||
|
|
514
|
-
Utils.hasObjectKeys(diff.changedForeignKeys) ||
|
|
520
|
+
(this.options.createForeignKeyConstraints && Utils.hasObjectKeys(diff.changedForeignKeys)) ||
|
|
515
521
|
Utils.hasObjectKeys(diff.changedColumns) ||
|
|
516
522
|
// sqlite can only add or change a primary key by rebuilding the table
|
|
517
523
|
[...Object.values(diff.addedIndexes), ...Object.values(diff.changedIndexes)].some(index => index.primary)) {
|
|
@@ -530,7 +536,8 @@ export class SqliteSchemaHelper extends SchemaHelper {
|
|
|
530
536
|
if (Object.values(diff.addedColumns).length > 0) {
|
|
531
537
|
this.append(ret, this.getAddColumnsSQL(diff.toTable, Object.values(diff.addedColumns), diff));
|
|
532
538
|
}
|
|
533
|
-
if (
|
|
539
|
+
if ((this.options.createForeignKeyConstraints && Utils.hasObjectKeys(diff.addedForeignKeys)) ||
|
|
540
|
+
Utils.hasObjectKeys(diff.addedChecks)) {
|
|
534
541
|
return this.getAlterTempTableSQL(diff);
|
|
535
542
|
}
|
|
536
543
|
for (const [oldColumnName, column] of Object.entries(diff.renamedColumns)) {
|
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.19",
|
|
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.6"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@mikro-orm/core": "7.3.0-dev.
|
|
56
|
+
"@mikro-orm/core": "7.3.0-dev.19"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">= 22.17.0"
|
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
|
@@ -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]`;
|
|
@@ -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(...
|
|
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(...
|
|
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
|
+
});
|
|
@@ -61,6 +61,8 @@ export class ObjectCriteriaNode extends CriteriaNode {
|
|
|
61
61
|
// schema-less entities the schema is resolved dynamically and needs to be carried over
|
|
62
62
|
const fixedSchema = parentMeta.schema && parentMeta.schema !== '*';
|
|
63
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);
|
|
64
66
|
const joinAlias = qb2.getNextAlias(this.prop.targetMeta.class);
|
|
65
67
|
const sub = qb2
|
|
66
68
|
.from(parentMeta.class)
|
|
@@ -314,18 +316,7 @@ export class ObjectCriteriaNode extends CriteriaNode {
|
|
|
314
316
|
const embeddable = this.prop.kind === ReferenceKind.EMBEDDED;
|
|
315
317
|
const knownKey = [ReferenceKind.SCALAR, ReferenceKind.MANY_TO_ONE, ReferenceKind.EMBEDDED].includes(this.prop.kind) ||
|
|
316
318
|
(this.prop.kind === ReferenceKind.ONE_TO_ONE && this.prop.owner);
|
|
317
|
-
const operatorKeys = knownKey &&
|
|
318
|
-
keys.every(key => {
|
|
319
|
-
if (key === '$not') {
|
|
320
|
-
// $not wraps conditions like $and/$or, check if it wraps entity property conditions (needs auto-join)
|
|
321
|
-
// vs simple operator conditions on the FK (doesn't need auto-join)
|
|
322
|
-
const childPayload = this.payload[key].payload;
|
|
323
|
-
if (Utils.isPlainObject(childPayload)) {
|
|
324
|
-
return Utils.getObjectQueryKeys(childPayload).every(k => Utils.isOperator(k, false));
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
return Utils.isOperator(key, false);
|
|
328
|
-
});
|
|
319
|
+
const operatorKeys = knownKey && this.isOperatorPayload(this.payload);
|
|
329
320
|
const primaryKeys = knownKey &&
|
|
330
321
|
keys.every(key => {
|
|
331
322
|
if (key === '$not') {
|
|
@@ -353,8 +344,7 @@ export class ObjectCriteriaNode extends CriteriaNode {
|
|
|
353
344
|
this.payload instanceof RegExp ||
|
|
354
345
|
this.payload instanceof Date ||
|
|
355
346
|
rawField;
|
|
356
|
-
const operator = Utils.isPlainObject(this.payload) &&
|
|
357
|
-
Utils.getObjectQueryKeys(this.payload).every(k => Utils.isOperator(k, false));
|
|
347
|
+
const operator = Utils.isPlainObject(this.payload) && this.isOperatorPayload(this.payload);
|
|
358
348
|
const field = `${alias}.${this.prop.name}`;
|
|
359
349
|
const method = qb.hasFlag(QueryFlag.INFER_POPULATE) ? 'joinAndSelect' : 'join';
|
|
360
350
|
const path = this.getPath();
|
package/query/QueryBuilder.d.ts
CHANGED
|
@@ -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
|
-
*
|
|
1016
|
-
*
|
|
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
|
/**
|
package/query/QueryBuilder.js
CHANGED
|
@@ -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';
|
|
@@ -1080,12 +1080,19 @@ export class QueryBuilder {
|
|
|
1080
1080
|
const conn = this.getConnection();
|
|
1081
1081
|
// outside a transaction, wrap in a short implicit one so RLS `set local` session context applies (no-op when unset)
|
|
1082
1082
|
const sessionContext = this.context ? undefined : this.em?.getTransactionSessionContext();
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
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
|
+
}
|
|
1089
1096
|
const meta = this.mainAlias.meta;
|
|
1090
1097
|
if (!options.mapResults || !meta) {
|
|
1091
1098
|
await this.em?.storeCache(this.#state.cache, cached, res);
|
|
@@ -1146,7 +1153,7 @@ export class QueryBuilder {
|
|
|
1146
1153
|
const chunkSize = options.chunkSize ?? 100;
|
|
1147
1154
|
const query = this.toQuery();
|
|
1148
1155
|
const loggerContext = { id: this.em?.id, ...this.loggerContext, ...this.#abortOptions };
|
|
1149
|
-
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));
|
|
1150
1157
|
const meta = this.mainAlias.meta;
|
|
1151
1158
|
if (options.rawResults || !meta) {
|
|
1152
1159
|
yield* res;
|
|
@@ -1157,8 +1164,9 @@ export class QueryBuilder {
|
|
|
1157
1164
|
const hash = (data) => {
|
|
1158
1165
|
return Utils.getPrimaryKeyHash(meta.primaryKeys.map(pk => data[pk]));
|
|
1159
1166
|
};
|
|
1167
|
+
const map = {};
|
|
1160
1168
|
for await (const row of res) {
|
|
1161
|
-
const mapped = this.driver.mapResult(row, meta, this.#state.populate, this);
|
|
1169
|
+
const mapped = this.driver.mapResult(row, meta, this.#state.populate, this, map);
|
|
1162
1170
|
if (!options.mergeResults || joinedProps.length === 0) {
|
|
1163
1171
|
yield this.mapResult(mapped, options.mapResults);
|
|
1164
1172
|
continue;
|
|
@@ -1179,6 +1187,14 @@ export class QueryBuilder {
|
|
|
1179
1187
|
}
|
|
1180
1188
|
}
|
|
1181
1189
|
}
|
|
1190
|
+
async *convertStreamExceptions(res) {
|
|
1191
|
+
try {
|
|
1192
|
+
yield* res;
|
|
1193
|
+
}
|
|
1194
|
+
catch (e) {
|
|
1195
|
+
throw this.driver.convertException(e);
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1182
1198
|
/**
|
|
1183
1199
|
* Alias for `qb.getResultList()`
|
|
1184
1200
|
*/
|
|
@@ -1557,7 +1573,10 @@ export class QueryBuilder {
|
|
|
1557
1573
|
field = asMatch[1].trim();
|
|
1558
1574
|
customAlias = asMatch[2];
|
|
1559
1575
|
}
|
|
1560
|
-
|
|
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('#')));
|
|
1561
1580
|
if (join && type === 'where') {
|
|
1562
1581
|
ret.push(...this.helper.mapJoinColumns(this.type, this.#state.joins[join]));
|
|
1563
1582
|
return;
|
|
@@ -1568,6 +1587,19 @@ export class QueryBuilder {
|
|
|
1568
1587
|
if (prop && [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
|
|
1569
1588
|
return;
|
|
1570
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
|
+
}
|
|
1571
1603
|
if (prop?.persist === false && !prop.embedded && !prop.formula && type === 'where') {
|
|
1572
1604
|
return;
|
|
1573
1605
|
}
|
|
@@ -1577,11 +1609,7 @@ export class QueryBuilder {
|
|
|
1577
1609
|
ret.push(getFieldName(aliased, customAlias));
|
|
1578
1610
|
return;
|
|
1579
1611
|
}
|
|
1580
|
-
|
|
1581
|
-
const shadowed = customAlias &&
|
|
1582
|
-
prop?.kind === ReferenceKind.EMBEDDED &&
|
|
1583
|
-
(this.#state.aliases[a]?.meta ?? this.mainAlias.meta).props.some(p => (p.kind !== ReferenceKind.EMBEDDED || p.object) && p.fieldNames?.includes(f));
|
|
1584
|
-
if (prop?.kind === ReferenceKind.EMBEDDED && !shadowed) {
|
|
1612
|
+
if (prop?.kind === ReferenceKind.EMBEDDED) {
|
|
1585
1613
|
if (customAlias) {
|
|
1586
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}').`);
|
|
1587
1615
|
}
|
|
@@ -1873,20 +1901,7 @@ export class QueryBuilder {
|
|
|
1873
1901
|
if (meta.root.inheritanceType !== 'sti' || !meta.discriminatorValue) {
|
|
1874
1902
|
return;
|
|
1875
1903
|
}
|
|
1876
|
-
|
|
1877
|
-
const children = [];
|
|
1878
|
-
const lookUpChildren = (ret, parent) => {
|
|
1879
|
-
const children = types.filter(meta2 => meta2.extends && this.metadata.find(meta2.extends) === parent);
|
|
1880
|
-
children.forEach(m => lookUpChildren(ret, m));
|
|
1881
|
-
ret.push(...children.filter(c => c.discriminatorValue));
|
|
1882
|
-
return children;
|
|
1883
|
-
};
|
|
1884
|
-
lookUpChildren(children, meta);
|
|
1885
|
-
this.andWhere({
|
|
1886
|
-
[meta.root.discriminatorColumn]: children.length > 0
|
|
1887
|
-
? { $in: [meta.discriminatorValue, ...children.map(c => c.discriminatorValue)] }
|
|
1888
|
-
: meta.discriminatorValue,
|
|
1889
|
-
});
|
|
1904
|
+
this.andWhere({ [meta.root.discriminatorColumn]: this.helper.getDiscriminatorCondition(meta) });
|
|
1890
1905
|
}
|
|
1891
1906
|
/**
|
|
1892
1907
|
* Ensures TPT joins are applied. Can be called early before finalize() to populate
|
|
@@ -1943,7 +1958,8 @@ export class QueryBuilder {
|
|
|
1943
1958
|
if (parentAlias) {
|
|
1944
1959
|
const schema = parentMeta.schema === '*' ? '*' : this.driver.getSchemaName(parentMeta);
|
|
1945
1960
|
parentMeta
|
|
1946
|
-
|
|
1961
|
+
// inherited formulas are selected on the main alias in `finalize()`
|
|
1962
|
+
.ownProps.filter(prop => !prop.formula && this.platform.shouldHaveColumn(prop, []))
|
|
1947
1963
|
.forEach(prop => this.#state.fields.push(...this.driver.mapPropToFieldNames(this, prop, parentAlias, parentMeta, schema)));
|
|
1948
1964
|
}
|
|
1949
1965
|
parentMeta = parentMeta.tptParent;
|
|
@@ -1962,12 +1978,16 @@ export class QueryBuilder {
|
|
|
1962
1978
|
if (!this.#state.fields?.includes('*') && !this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`)) {
|
|
1963
1979
|
return;
|
|
1964
1980
|
}
|
|
1965
|
-
// LEFT JOIN each descendant table
|
|
1981
|
+
// LEFT JOIN each descendant table
|
|
1966
1982
|
for (const childMeta of descendants) {
|
|
1967
1983
|
const childAlias = this.getNextAlias(childMeta.className);
|
|
1968
1984
|
this.createAlias(childMeta.class, childAlias);
|
|
1969
1985
|
this.#state.tptAlias[childMeta.className] = childAlias;
|
|
1970
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];
|
|
1971
1991
|
// Add child fields
|
|
1972
1992
|
const schema = childMeta.schema === '*' ? '*' : this.driver.getSchemaName(childMeta);
|
|
1973
1993
|
childMeta
|
|
@@ -1976,7 +1996,7 @@ export class QueryBuilder {
|
|
|
1976
1996
|
}
|
|
1977
1997
|
// Add computed discriminator (CASE WHEN to determine concrete type)
|
|
1978
1998
|
// descendants is pre-sorted by depth (deepest first) during discovery
|
|
1979
|
-
if (meta.tptDiscriminatorColumn) {
|
|
1999
|
+
if (meta.root.tptDiscriminatorColumn) {
|
|
1980
2000
|
this.#state.fields.push(this.driver.buildTPTDiscriminatorExpression(meta, descendants, this.#state.tptAlias, this.mainAlias.aliasName));
|
|
1981
2001
|
}
|
|
1982
2002
|
}
|
|
@@ -1996,7 +2016,7 @@ export class QueryBuilder {
|
|
|
1996
2016
|
this.processNestedJoins();
|
|
1997
2017
|
if (meta && (this.#state.fields?.includes('*') || this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`))) {
|
|
1998
2018
|
const schema = this.getSchema(this.mainAlias);
|
|
1999
|
-
//
|
|
2019
|
+
// Per-column entries are unquoted (meant for `quote`), while `toString()` yields the quoted alias for plain template literals
|
|
2000
2020
|
// For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
|
|
2001
2021
|
const quotedMainAlias = this.platform.quoteIdentifier(this.mainAlias.aliasName).toString();
|
|
2002
2022
|
const columns = meta.createColumnMappingObject(prop => this.helper.getTPTAliasForProperty(prop.name, this.mainAlias.aliasName), quotedMainAlias);
|
|
@@ -2100,7 +2120,13 @@ export class QueryBuilder {
|
|
|
2100
2120
|
}
|
|
2101
2121
|
mergeOnConditions(joins, cond, filter, op) {
|
|
2102
2122
|
for (const k of Object.keys(cond)) {
|
|
2103
|
-
|
|
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) {
|
|
2104
2130
|
if (Array.isArray(cond[k])) {
|
|
2105
2131
|
if (k === '$or' && !this.canDistributeOrBranches(cond[k], joins)) {
|
|
2106
2132
|
// entity filters have no other sink, so their `$or` is kept intact on the outermost targeted join instead
|
|
@@ -2114,7 +2140,7 @@ export class QueryBuilder {
|
|
|
2114
2140
|
/* v8 ignore next */
|
|
2115
2141
|
this.mergeOnConditions(joins, cond[k], filter, k);
|
|
2116
2142
|
}
|
|
2117
|
-
const
|
|
2143
|
+
const alias = notAlias ?? this.helper.splitField(k)[0];
|
|
2118
2144
|
const join = joins.find(j => j.alias === alias);
|
|
2119
2145
|
if (join) {
|
|
2120
2146
|
const parentJoin = joins.find(j => j.alias === join.ownerAlias);
|
|
@@ -2143,6 +2169,14 @@ export class QueryBuilder {
|
|
|
2143
2169
|
}
|
|
2144
2170
|
}
|
|
2145
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
|
+
}
|
|
2146
2180
|
/**
|
|
2147
2181
|
* `$or` branches can be moved to a join's `on` clause only when they all target that same join
|
|
2148
2182
|
* and stay flat — a partial `$or` in the `on` clause would drop rows matching a sibling branch,
|
|
@@ -2171,9 +2205,9 @@ export class QueryBuilder {
|
|
|
2171
2205
|
return aliases;
|
|
2172
2206
|
}
|
|
2173
2207
|
/**
|
|
2174
|
-
*
|
|
2175
|
-
*
|
|
2176
|
-
* 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.
|
|
2177
2211
|
*/
|
|
2178
2212
|
mergeFilterOrCondition(branches, joins) {
|
|
2179
2213
|
const aliases = this.getOrBranchAliases(branches);
|
|
@@ -2641,3 +2675,5 @@ export class QueryBuilder {
|
|
|
2641
2675
|
}
|
|
2642
2676
|
}
|
|
2643
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,4 +1,4 @@
|
|
|
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');
|
|
@@ -296,7 +296,7 @@ export class QueryBuilderHelper {
|
|
|
296
296
|
!join.path?.endsWith('[pivot]')) {
|
|
297
297
|
const typeProperty = join.prop.targetMeta.root.discriminatorColumn;
|
|
298
298
|
const alias = join.inverseAlias ?? join.alias;
|
|
299
|
-
join.cond[`${alias}.${typeProperty}`] = join.prop.targetMeta
|
|
299
|
+
join.cond[`${alias}.${typeProperty}`] = this.getDiscriminatorCondition(join.prop.targetMeta);
|
|
300
300
|
}
|
|
301
301
|
// For polymorphic relations, add discriminator condition to filter by target entity type
|
|
302
302
|
if (join.prop.polymorphic && join.prop.discriminatorColumn && join.prop.discriminatorMap) {
|
|
@@ -341,6 +341,22 @@ export class QueryBuilderHelper {
|
|
|
341
341
|
}
|
|
342
342
|
return { sql, params };
|
|
343
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
|
+
}
|
|
344
360
|
mapJoinColumns(type, join) {
|
|
345
361
|
if (join.prop && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(join.prop.kind)) {
|
|
346
362
|
return join.prop.fieldNames.map((_fieldName, idx) => {
|
|
@@ -597,7 +613,7 @@ export class QueryBuilderHelper {
|
|
|
597
613
|
else {
|
|
598
614
|
const opValue = value[op];
|
|
599
615
|
const opValueIsRaw = isRaw(opValue);
|
|
600
|
-
if (opValueIsRaw ||
|
|
616
|
+
if (opValueIsRaw || isSubquery(opValue)) {
|
|
601
617
|
const query = opValueIsRaw ? opValue : opValue.toRaw();
|
|
602
618
|
const mappedKey = this.mapper(key, type, query, null);
|
|
603
619
|
let sql = this.replaceAliases(query.sql);
|
|
@@ -607,6 +623,19 @@ export class QueryBuilderHelper {
|
|
|
607
623
|
parts.push(`${this.#platform.quoteIdentifier(mappedKey)} ${replacement} ${sql}`);
|
|
608
624
|
params.push(...query.params);
|
|
609
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
|
+
}
|
|
610
639
|
else {
|
|
611
640
|
const mappedKey = this.mapper(key, type, opValue, null);
|
|
612
641
|
const val = this.getValueReplacement(fields, opValue, params, op, prop, rowValues);
|
|
@@ -625,16 +654,15 @@ export class QueryBuilderHelper {
|
|
|
625
654
|
}
|
|
626
655
|
return `(${tmp.join(', ')})`;
|
|
627
656
|
}
|
|
628
|
-
// array custom types
|
|
629
|
-
// 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
|
|
630
658
|
if (prop?.customType instanceof ArrayType) {
|
|
631
|
-
const
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
mode: 'query'
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
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;
|
|
638
666
|
}
|
|
639
667
|
value.forEach(p => params.push(p));
|
|
640
668
|
return `(${value.map(() => '?').join(', ')})`;
|