@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/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';
|
|
@@ -593,6 +593,16 @@ export class QueryBuilder {
|
|
|
593
593
|
o[raw('??', [key])] = o[key];
|
|
594
594
|
delete o[key];
|
|
595
595
|
}
|
|
596
|
+
// an alias-prefixed composite FK needs all its columns, like the unprefixed form gets in `renameFieldToPK()`
|
|
597
|
+
const [alias, field] = key.includes('.') ? this.helper.splitField(key, true) : [];
|
|
598
|
+
const prop = field && !Utils.isPlainObject(o[key]) ? this.helper.getProperty(field, alias) : undefined;
|
|
599
|
+
if (prop &&
|
|
600
|
+
prop.joinColumns?.length > 1 &&
|
|
601
|
+
(prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner))) {
|
|
602
|
+
const columns = prop.polymorphic ? prop.fieldNames : prop.joinColumns;
|
|
603
|
+
o[Utils.getPrimaryKeyHash(columns.map(col => `${alias}.${col}`))] = o[key];
|
|
604
|
+
delete o[key];
|
|
605
|
+
}
|
|
596
606
|
}
|
|
597
607
|
this.helper.validateQueryOrder(o);
|
|
598
608
|
const processed = QueryHelper.processWhere({
|
|
@@ -1032,9 +1042,11 @@ export class QueryBuilder {
|
|
|
1032
1042
|
* @internal
|
|
1033
1043
|
*/
|
|
1034
1044
|
addPolymorphicJoin(prop, targetMeta, ownerAlias, alias, type, path, schema) {
|
|
1035
|
-
// Override referencedColumnNames to use the specific target's PK columns
|
|
1045
|
+
// Override referencedColumnNames to use the specific target's PK (or `targetKey`) columns
|
|
1036
1046
|
// (polymorphic targets may have different PK column names, e.g. org_id vs user_id)
|
|
1037
|
-
const referencedColumnNames =
|
|
1047
|
+
const referencedColumnNames = prop.targetKey
|
|
1048
|
+
? targetMeta.properties[prop.targetKey].fieldNames
|
|
1049
|
+
: targetMeta.getPrimaryProps().flatMap(pk => pk.fieldNames);
|
|
1038
1050
|
const targetProp = { ...prop, targetMeta, referencedColumnNames };
|
|
1039
1051
|
const aliasedName = `${ownerAlias}.${prop.name}[${targetMeta.className}]#${alias}`;
|
|
1040
1052
|
this.#state.joins[aliasedName] = this.helper.joinManyToOneReference(targetProp, ownerAlias, alias, type, {}, schema);
|
|
@@ -1055,12 +1067,13 @@ export class QueryBuilder {
|
|
|
1055
1067
|
options = typeof options === 'boolean' ? { mapResults: options } : (options ?? {});
|
|
1056
1068
|
options.mergeResults ??= true;
|
|
1057
1069
|
options.mapResults ??= true;
|
|
1058
|
-
const
|
|
1070
|
+
const type = this.getExecuteType();
|
|
1071
|
+
const isRunType = [QueryType.INSERT, QueryType.UPDATE, QueryType.DELETE, QueryType.TRUNCATE].includes(type);
|
|
1059
1072
|
method ??= isRunType ? 'run' : 'all';
|
|
1060
1073
|
if (!this.connectionType && (isRunType || this.context)) {
|
|
1061
1074
|
this.connectionType = 'write';
|
|
1062
1075
|
}
|
|
1063
|
-
if (!this.#state.finalized && method === 'get' &&
|
|
1076
|
+
if (!this.#state.finalized && method === 'get' && type === QueryType.SELECT) {
|
|
1064
1077
|
this.limit(1);
|
|
1065
1078
|
}
|
|
1066
1079
|
const query = this.toQuery();
|
|
@@ -1078,12 +1091,19 @@ export class QueryBuilder {
|
|
|
1078
1091
|
const conn = this.getConnection();
|
|
1079
1092
|
// outside a transaction, wrap in a short implicit one so RLS `set local` session context applies (no-op when unset)
|
|
1080
1093
|
const sessionContext = this.context ? undefined : this.em?.getTransactionSessionContext();
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1094
|
+
let res;
|
|
1095
|
+
// a QueryBuilder used directly must honour the same `convertException` contract as the driver methods
|
|
1096
|
+
try {
|
|
1097
|
+
res = await (sessionContext
|
|
1098
|
+
? conn.transactional(trx => conn.execute(query.sql, query.params, method, trx, loggerContext), {
|
|
1099
|
+
sessionContext,
|
|
1100
|
+
loggerContext,
|
|
1101
|
+
})
|
|
1102
|
+
: conn.execute(query.sql, query.params, method, this.context, loggerContext));
|
|
1103
|
+
}
|
|
1104
|
+
catch (e) {
|
|
1105
|
+
throw this.driver.convertException(e);
|
|
1106
|
+
}
|
|
1087
1107
|
const meta = this.mainAlias.meta;
|
|
1088
1108
|
if (!options.mapResults || !meta) {
|
|
1089
1109
|
await this.em?.storeCache(this.#state.cache, cached, res);
|
|
@@ -1111,6 +1131,19 @@ export class QueryBuilder {
|
|
|
1111
1131
|
await this.em?.storeCache(this.#state.cache, cached, mapped);
|
|
1112
1132
|
return mapped;
|
|
1113
1133
|
}
|
|
1134
|
+
/**
|
|
1135
|
+
* An update or delete with auto-joined conditions stays a select until `finalize()` wraps it,
|
|
1136
|
+
* so read the same flags `wrapModifySubQuery()` uses.
|
|
1137
|
+
*/
|
|
1138
|
+
getExecuteType() {
|
|
1139
|
+
if (this.#state.flags.has(QueryFlag.UPDATE_SUB_QUERY)) {
|
|
1140
|
+
return QueryType.UPDATE;
|
|
1141
|
+
}
|
|
1142
|
+
if (this.#state.flags.has(QueryFlag.DELETE_SUB_QUERY)) {
|
|
1143
|
+
return QueryType.DELETE;
|
|
1144
|
+
}
|
|
1145
|
+
return this.type;
|
|
1146
|
+
}
|
|
1114
1147
|
getConnection() {
|
|
1115
1148
|
const write = !this.platform.getConfig().get('preferReadReplicas');
|
|
1116
1149
|
const type = this.connectionType || (write ? 'write' : 'read');
|
|
@@ -1144,7 +1177,7 @@ export class QueryBuilder {
|
|
|
1144
1177
|
const chunkSize = options.chunkSize ?? 100;
|
|
1145
1178
|
const query = this.toQuery();
|
|
1146
1179
|
const loggerContext = { id: this.em?.id, ...this.loggerContext, ...this.#abortOptions };
|
|
1147
|
-
const res = this.getConnection().stream(query.sql, query.params, this.context, loggerContext, chunkSize);
|
|
1180
|
+
const res = this.convertStreamExceptions(this.getConnection().stream(query.sql, query.params, this.context, loggerContext, chunkSize));
|
|
1148
1181
|
const meta = this.mainAlias.meta;
|
|
1149
1182
|
if (options.rawResults || !meta) {
|
|
1150
1183
|
yield* res;
|
|
@@ -1155,8 +1188,9 @@ export class QueryBuilder {
|
|
|
1155
1188
|
const hash = (data) => {
|
|
1156
1189
|
return Utils.getPrimaryKeyHash(meta.primaryKeys.map(pk => data[pk]));
|
|
1157
1190
|
};
|
|
1191
|
+
const map = {};
|
|
1158
1192
|
for await (const row of res) {
|
|
1159
|
-
const mapped = this.driver.mapResult(row, meta, this.#state.populate, this);
|
|
1193
|
+
const mapped = this.driver.mapResult(row, meta, this.#state.populate, this, map);
|
|
1160
1194
|
if (!options.mergeResults || joinedProps.length === 0) {
|
|
1161
1195
|
yield this.mapResult(mapped, options.mapResults);
|
|
1162
1196
|
continue;
|
|
@@ -1177,6 +1211,14 @@ export class QueryBuilder {
|
|
|
1177
1211
|
}
|
|
1178
1212
|
}
|
|
1179
1213
|
}
|
|
1214
|
+
async *convertStreamExceptions(res) {
|
|
1215
|
+
try {
|
|
1216
|
+
yield* res;
|
|
1217
|
+
}
|
|
1218
|
+
catch (e) {
|
|
1219
|
+
throw this.driver.convertException(e);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1180
1222
|
/**
|
|
1181
1223
|
* Alias for `qb.getResultList()`
|
|
1182
1224
|
*/
|
|
@@ -1555,7 +1597,10 @@ export class QueryBuilder {
|
|
|
1555
1597
|
field = asMatch[1].trim();
|
|
1556
1598
|
customAlias = asMatch[2];
|
|
1557
1599
|
}
|
|
1558
|
-
|
|
1600
|
+
// an aliased field is always a column, never a relation to expand, even when an FK column is named like its relation
|
|
1601
|
+
const join = customAlias
|
|
1602
|
+
? undefined
|
|
1603
|
+
: Object.keys(this.#state.joins).find(k => field === k.substring(0, k.indexOf('#')));
|
|
1559
1604
|
if (join && type === 'where') {
|
|
1560
1605
|
ret.push(...this.helper.mapJoinColumns(this.type, this.#state.joins[join]));
|
|
1561
1606
|
return;
|
|
@@ -1566,6 +1611,19 @@ export class QueryBuilder {
|
|
|
1566
1611
|
if (prop && [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
|
|
1567
1612
|
return;
|
|
1568
1613
|
}
|
|
1614
|
+
// the joined strategy selects by column name, which can collide with the name of another property
|
|
1615
|
+
const shadowed = customAlias &&
|
|
1616
|
+
prop &&
|
|
1617
|
+
(prop.kind === ReferenceKind.EMBEDDED ||
|
|
1618
|
+
(customAlias.endsWith(`__${f}`) && (prop.persist === false || !prop.fieldNames.includes(f)))) &&
|
|
1619
|
+
(this.#state.aliases[a]?.meta ?? this.mainAlias.meta).props.some(p => p !== prop &&
|
|
1620
|
+
p.persist !== false &&
|
|
1621
|
+
(p.kind !== ReferenceKind.EMBEDDED || p.object) &&
|
|
1622
|
+
p.fieldNames?.includes(f));
|
|
1623
|
+
if (shadowed) {
|
|
1624
|
+
ret.push(raw('?? as ??', [`${a}.${f}`, customAlias]));
|
|
1625
|
+
return;
|
|
1626
|
+
}
|
|
1569
1627
|
if (prop?.persist === false && !prop.embedded && !prop.formula && type === 'where') {
|
|
1570
1628
|
return;
|
|
1571
1629
|
}
|
|
@@ -1575,11 +1633,7 @@ export class QueryBuilder {
|
|
|
1575
1633
|
ret.push(getFieldName(aliased, customAlias));
|
|
1576
1634
|
return;
|
|
1577
1635
|
}
|
|
1578
|
-
|
|
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) {
|
|
1636
|
+
if (prop?.kind === ReferenceKind.EMBEDDED) {
|
|
1583
1637
|
if (customAlias) {
|
|
1584
1638
|
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
1639
|
}
|
|
@@ -1871,20 +1925,7 @@ export class QueryBuilder {
|
|
|
1871
1925
|
if (meta.root.inheritanceType !== 'sti' || !meta.discriminatorValue) {
|
|
1872
1926
|
return;
|
|
1873
1927
|
}
|
|
1874
|
-
|
|
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
|
-
});
|
|
1928
|
+
this.andWhere({ [meta.root.discriminatorColumn]: this.helper.getDiscriminatorCondition(meta) });
|
|
1888
1929
|
}
|
|
1889
1930
|
/**
|
|
1890
1931
|
* Ensures TPT joins are applied. Can be called early before finalize() to populate
|
|
@@ -1941,7 +1982,8 @@ export class QueryBuilder {
|
|
|
1941
1982
|
if (parentAlias) {
|
|
1942
1983
|
const schema = parentMeta.schema === '*' ? '*' : this.driver.getSchemaName(parentMeta);
|
|
1943
1984
|
parentMeta
|
|
1944
|
-
|
|
1985
|
+
// inherited formulas are selected on the main alias in `finalize()`
|
|
1986
|
+
.ownProps.filter(prop => !prop.formula && this.platform.shouldHaveColumn(prop, []))
|
|
1945
1987
|
.forEach(prop => this.#state.fields.push(...this.driver.mapPropToFieldNames(this, prop, parentAlias, parentMeta, schema)));
|
|
1946
1988
|
}
|
|
1947
1989
|
parentMeta = parentMeta.tptParent;
|
|
@@ -1960,12 +2002,16 @@ export class QueryBuilder {
|
|
|
1960
2002
|
if (!this.#state.fields?.includes('*') && !this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`)) {
|
|
1961
2003
|
return;
|
|
1962
2004
|
}
|
|
1963
|
-
// LEFT JOIN each descendant table
|
|
2005
|
+
// LEFT JOIN each descendant table
|
|
1964
2006
|
for (const childMeta of descendants) {
|
|
1965
2007
|
const childAlias = this.getNextAlias(childMeta.className);
|
|
1966
2008
|
this.createAlias(childMeta.class, childAlias);
|
|
1967
2009
|
this.#state.tptAlias[childMeta.className] = childAlias;
|
|
1968
2010
|
this.addPropertyJoin(childMeta.tptInverseProp, this.mainAlias.aliasName, childAlias, JoinType.leftJoin, `[tpt]${meta.className}`);
|
|
2011
|
+
}
|
|
2012
|
+
this.driver.registerTPTAncestorAliases(this, meta, this.mainAlias.aliasName, this.#state.tptAlias);
|
|
2013
|
+
for (const childMeta of descendants) {
|
|
2014
|
+
const childAlias = this.#state.tptAlias[childMeta.className];
|
|
1969
2015
|
// Add child fields
|
|
1970
2016
|
const schema = childMeta.schema === '*' ? '*' : this.driver.getSchemaName(childMeta);
|
|
1971
2017
|
childMeta
|
|
@@ -1974,7 +2020,7 @@ export class QueryBuilder {
|
|
|
1974
2020
|
}
|
|
1975
2021
|
// Add computed discriminator (CASE WHEN to determine concrete type)
|
|
1976
2022
|
// descendants is pre-sorted by depth (deepest first) during discovery
|
|
1977
|
-
if (meta.tptDiscriminatorColumn) {
|
|
2023
|
+
if (meta.root.tptDiscriminatorColumn) {
|
|
1978
2024
|
this.#state.fields.push(this.driver.buildTPTDiscriminatorExpression(meta, descendants, this.#state.tptAlias, this.mainAlias.aliasName));
|
|
1979
2025
|
}
|
|
1980
2026
|
}
|
|
@@ -1994,7 +2040,7 @@ export class QueryBuilder {
|
|
|
1994
2040
|
this.processNestedJoins();
|
|
1995
2041
|
if (meta && (this.#state.fields?.includes('*') || this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`))) {
|
|
1996
2042
|
const schema = this.getSchema(this.mainAlias);
|
|
1997
|
-
//
|
|
2043
|
+
// Per-column entries are unquoted (meant for `quote`), while `toString()` yields the quoted alias for plain template literals
|
|
1998
2044
|
// For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
|
|
1999
2045
|
const quotedMainAlias = this.platform.quoteIdentifier(this.mainAlias.aliasName).toString();
|
|
2000
2046
|
const columns = meta.createColumnMappingObject(prop => this.helper.getTPTAliasForProperty(prop.name, this.mainAlias.aliasName), quotedMainAlias);
|
|
@@ -2098,7 +2144,13 @@ export class QueryBuilder {
|
|
|
2098
2144
|
}
|
|
2099
2145
|
mergeOnConditions(joins, cond, filter, op) {
|
|
2100
2146
|
for (const k of Object.keys(cond)) {
|
|
2101
|
-
|
|
2147
|
+
const notAlias = k === '$not' ? this.getNotConditionAlias(cond[k], joins) : undefined;
|
|
2148
|
+
if (k === '$not' && !notAlias) {
|
|
2149
|
+
// splitting a `$not` across joins would drop the negation, so it is kept intact on their common ancestor join
|
|
2150
|
+
this.mergeFilterOrCondition([{ $not: cond[k] }], joins);
|
|
2151
|
+
continue;
|
|
2152
|
+
}
|
|
2153
|
+
if (Utils.isOperator(k) && !notAlias) {
|
|
2102
2154
|
if (Array.isArray(cond[k])) {
|
|
2103
2155
|
if (k === '$or' && !this.canDistributeOrBranches(cond[k], joins)) {
|
|
2104
2156
|
// entity filters have no other sink, so their `$or` is kept intact on the outermost targeted join instead
|
|
@@ -2112,7 +2164,7 @@ export class QueryBuilder {
|
|
|
2112
2164
|
/* v8 ignore next */
|
|
2113
2165
|
this.mergeOnConditions(joins, cond[k], filter, k);
|
|
2114
2166
|
}
|
|
2115
|
-
const
|
|
2167
|
+
const alias = notAlias ?? this.helper.splitField(k)[0];
|
|
2116
2168
|
const join = joins.find(j => j.alias === alias);
|
|
2117
2169
|
if (join) {
|
|
2118
2170
|
const parentJoin = joins.find(j => j.alias === join.ownerAlias);
|
|
@@ -2141,6 +2193,14 @@ export class QueryBuilder {
|
|
|
2141
2193
|
}
|
|
2142
2194
|
}
|
|
2143
2195
|
}
|
|
2196
|
+
/**
|
|
2197
|
+
* `$not` can be moved to a join's `on` clause as a whole only when all of its conditions target that join.
|
|
2198
|
+
*/
|
|
2199
|
+
getNotConditionAlias(cond, joins) {
|
|
2200
|
+
const aliases = this.getOrBranchAliases([cond]);
|
|
2201
|
+
const [alias] = aliases;
|
|
2202
|
+
return aliases.size === 1 && joins.some(j => j.alias === alias) ? alias : undefined;
|
|
2203
|
+
}
|
|
2144
2204
|
/**
|
|
2145
2205
|
* `$or` branches can be moved to a join's `on` clause only when they all target that same join
|
|
2146
2206
|
* and stay flat — a partial `$or` in the `on` clause would drop rows matching a sibling branch,
|
|
@@ -2169,9 +2229,9 @@ export class QueryBuilder {
|
|
|
2169
2229
|
return aliases;
|
|
2170
2230
|
}
|
|
2171
2231
|
/**
|
|
2172
|
-
*
|
|
2173
|
-
*
|
|
2174
|
-
* can reference their aliases.
|
|
2232
|
+
* A condition that cannot be distributed (an entity filter's `$or`, or a `$not` spanning several joins)
|
|
2233
|
+
* is applied intact to the `on` clause of the outermost join common to all targeted joins, nesting
|
|
2234
|
+
* the targeted joins under it so the clause can reference their aliases.
|
|
2175
2235
|
*/
|
|
2176
2236
|
mergeFilterOrCondition(branches, joins) {
|
|
2177
2237
|
const aliases = this.getOrBranchAliases(branches);
|
|
@@ -2318,8 +2378,12 @@ export class QueryBuilder {
|
|
|
2318
2378
|
if (this.#state.orderBy.length > 0) {
|
|
2319
2379
|
const orderBy = [];
|
|
2320
2380
|
for (const orderMap of this.#state.orderBy) {
|
|
2321
|
-
|
|
2322
|
-
|
|
2381
|
+
// a composite FK key holds several columns, each needs its own `min()`
|
|
2382
|
+
const entries = Utils.getObjectQueryKeys(orderMap).flatMap(key => {
|
|
2383
|
+
const fields = RawQueryFragment.isKnownFragmentSymbol(key) ? [key] : Utils.splitPrimaryKeys(key);
|
|
2384
|
+
return fields.map(field => [field, orderMap[key]]);
|
|
2385
|
+
});
|
|
2386
|
+
for (const [field, direction] of entries) {
|
|
2323
2387
|
if (RawQueryFragment.isKnownFragmentSymbol(field)) {
|
|
2324
2388
|
orderBy.push({ [field]: direction });
|
|
2325
2389
|
continue;
|
|
@@ -2639,3 +2703,5 @@ export class QueryBuilder {
|
|
|
2639
2703
|
}
|
|
2640
2704
|
}
|
|
2641
2705
|
_a = QueryBuilder;
|
|
2706
|
+
// prototype-level brand recognized by `isSubquery()`, JSON payloads cannot forge it
|
|
2707
|
+
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
|
|
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
|
|
388
|
+
if (/[im]/.test(re.flags)) {
|
|
363
389
|
return false;
|
|
364
390
|
}
|
|
365
|
-
//
|
|
366
|
-
return
|
|
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(
|
|
371
|
-
.replace(
|
|
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
|
}
|
|
@@ -384,6 +408,7 @@ export class QueryBuilderHelper {
|
|
|
384
408
|
return `%${value}%`;
|
|
385
409
|
}
|
|
386
410
|
appendOnConflictClause(type, onConflict, qb) {
|
|
411
|
+
const meta = this.#metadata.find(this.#entityName);
|
|
387
412
|
onConflict.forEach(item => {
|
|
388
413
|
const { fields, ignore } = item;
|
|
389
414
|
const sub = qb.onConflict({ fields, ignore });
|
|
@@ -400,6 +425,12 @@ export class QueryBuilderHelper {
|
|
|
400
425
|
mergeParam = item.merge.map(key => this.mapper(key, type));
|
|
401
426
|
}
|
|
402
427
|
sub.merge = mergeParam ?? [];
|
|
428
|
+
// a merged row is updated, so its version is bumped as `updateVersionProperty()` does
|
|
429
|
+
if (meta?.ownsVersionProperty()) {
|
|
430
|
+
const prop = meta.properties[meta.versionProperty];
|
|
431
|
+
const timestamp = prop.runtimeType === 'Date' ? this.#platform.getCurrentTimestampSQL(prop.length) : undefined;
|
|
432
|
+
sub.version = { field: prop.fieldNames[0], timestamp };
|
|
433
|
+
}
|
|
403
434
|
if (item.where) {
|
|
404
435
|
sub.where = this._appendQueryCondition(type, item.where);
|
|
405
436
|
}
|
|
@@ -445,7 +476,8 @@ export class QueryBuilderHelper {
|
|
|
445
476
|
const parts = [];
|
|
446
477
|
const params = [];
|
|
447
478
|
if (this.isSimpleRegExp(cond[key])) {
|
|
448
|
-
|
|
479
|
+
const escape = /[!%_]/.test(cond[key].source) ? ` escape '!'` : '';
|
|
480
|
+
parts.push(`${this.#platform.quoteIdentifier(this.mapper(key, type))} like ?${escape}`);
|
|
449
481
|
params.push(this.getRegExpParam(cond[key]));
|
|
450
482
|
return { sql: parts.join(' and '), params };
|
|
451
483
|
}
|
|
@@ -532,15 +564,17 @@ export class QueryBuilderHelper {
|
|
|
532
564
|
['$in', '$nin'].includes(op) &&
|
|
533
565
|
Array.isArray(value[op]) &&
|
|
534
566
|
value[op].every((v) => Array.isArray(v));
|
|
535
|
-
|
|
567
|
+
// an empty list falls through to the generic `1 = 0` / `1 = 1` handling below
|
|
568
|
+
if (fields.length > 1 && Array.isArray(value[op]) && value[op].length > 0) {
|
|
536
569
|
const singleTuple = !value[op].every((v) => Array.isArray(v));
|
|
537
570
|
if (!this.#platform.allowsComparingTuples()) {
|
|
538
571
|
const mapped = fields.map(f => this.mapper(f, type));
|
|
539
|
-
if (op === '$in') {
|
|
572
|
+
if (op === '$in' || op === '$nin') {
|
|
540
573
|
const conds = value[op].map(() => {
|
|
541
574
|
return `(${mapped.map(field => `${this.#platform.quoteIdentifier(field)} = ?`).join(' and ')})`;
|
|
542
575
|
});
|
|
543
|
-
|
|
576
|
+
const sql = `(${conds.join(' or ')})`;
|
|
577
|
+
parts.push(op === '$in' ? sql : `not ${sql}`);
|
|
544
578
|
params.push(...Utils.flatten(value[op]));
|
|
545
579
|
return { sql: parts.join(' and '), params };
|
|
546
580
|
}
|
|
@@ -588,7 +622,7 @@ export class QueryBuilderHelper {
|
|
|
588
622
|
else {
|
|
589
623
|
const opValue = value[op];
|
|
590
624
|
const opValueIsRaw = isRaw(opValue);
|
|
591
|
-
if (opValueIsRaw ||
|
|
625
|
+
if (opValueIsRaw || isSubquery(opValue)) {
|
|
592
626
|
const query = opValueIsRaw ? opValue : opValue.toRaw();
|
|
593
627
|
const mappedKey = this.mapper(key, type, query, null);
|
|
594
628
|
let sql = this.replaceAliases(query.sql);
|
|
@@ -598,6 +632,19 @@ export class QueryBuilderHelper {
|
|
|
598
632
|
parts.push(`${this.#platform.quoteIdentifier(mappedKey)} ${replacement} ${sql}`);
|
|
599
633
|
params.push(...query.params);
|
|
600
634
|
}
|
|
635
|
+
else if (['$in', '$nin'].includes(op) &&
|
|
636
|
+
prop?.customType instanceof ArrayType &&
|
|
637
|
+
Array.isArray(opValue) &&
|
|
638
|
+
!opValue.every((v) => Array.isArray(v))) {
|
|
639
|
+
// a flat list on an array column matches any of its elements, like in mongo
|
|
640
|
+
if (!this.#platform.supportsArrayOverlap()) {
|
|
641
|
+
throw new ValidationError(`${op} on array property ${prop.name} expects a list of arrays, use $eq for an exact match`);
|
|
642
|
+
}
|
|
643
|
+
const mappedKey = this.mapper(key, type, opValue, null);
|
|
644
|
+
const sql = `${this.#platform.quoteIdentifier(mappedKey)} && ?`;
|
|
645
|
+
parts.push(op === '$in' ? sql : `not (${sql})`);
|
|
646
|
+
params.push(prop.customType.convertToDatabaseValue(opValue, this.#platform, { fromQuery: true, key: op, mode: 'query' }));
|
|
647
|
+
}
|
|
601
648
|
else {
|
|
602
649
|
const mappedKey = this.mapper(key, type, opValue, null);
|
|
603
650
|
const val = this.getValueReplacement(fields, opValue, params, op, prop, rowValues);
|
|
@@ -616,16 +663,15 @@ export class QueryBuilderHelper {
|
|
|
616
663
|
}
|
|
617
664
|
return `(${tmp.join(', ')})`;
|
|
618
665
|
}
|
|
619
|
-
// array custom types
|
|
620
|
-
// array literal, so we emit a single bound parameter — not one per element wrapped in a tuple
|
|
666
|
+
// array custom types convert a whole array into one literal, so each candidate array binds a single parameter
|
|
621
667
|
if (prop?.customType instanceof ArrayType) {
|
|
622
|
-
const
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
mode: 'query'
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
return
|
|
668
|
+
const list = key === '$in' || key === '$nin';
|
|
669
|
+
const items = list ? value : [value];
|
|
670
|
+
for (const item of items) {
|
|
671
|
+
params.push(prop.customType.convertToDatabaseValue(item, this.#platform, { fromQuery: true, key, mode: 'query' }));
|
|
672
|
+
}
|
|
673
|
+
const sql = items.map(() => '?').join(', ');
|
|
674
|
+
return list ? `(${sql})` : sql;
|
|
629
675
|
}
|
|
630
676
|
value.forEach(p => params.push(p));
|
|
631
677
|
return `(${value.map(() => '?').join(', ')})`;
|
|
@@ -1072,6 +1118,11 @@ export class QueryBuilderHelper {
|
|
|
1072
1118
|
const meta = this.#metadata.get(this.#entityName);
|
|
1073
1119
|
const tableName = meta.tableName;
|
|
1074
1120
|
for (const key of Object.keys(cond)) {
|
|
1121
|
+
// operators are kept, only the properties inside them are qualified
|
|
1122
|
+
if (key === '$and' || key === '$or' || key === '$not') {
|
|
1123
|
+
Utils.asArray(cond[key]).forEach((sub) => this.processOnConflictCondition(sub, schema));
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1075
1126
|
const mapped = this.mapper(key, QueryType.UPSERT);
|
|
1076
1127
|
Utils.renameKey(cond, key, tableName + '.' + mapped);
|
|
1077
1128
|
}
|
package/schema/DatabaseTable.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DecimalType, EntitySchema, isRaw, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { DecimalType, EntitySchema, isRaw, MetadataError, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
|
|
2
2
|
import { toEntityPartitionBy } from './partitioning.js';
|
|
3
3
|
/**
|
|
4
4
|
* @internal
|
|
@@ -155,6 +155,7 @@ export class DatabaseTable {
|
|
|
155
155
|
comment: prop.comment,
|
|
156
156
|
collation: prop.collation,
|
|
157
157
|
extra: prop.extra,
|
|
158
|
+
sequence: prop.sequence,
|
|
158
159
|
ignoreSchemaChanges: prop.ignoreSchemaChanges,
|
|
159
160
|
};
|
|
160
161
|
this.#columns[field].unsigned ??= this.#columns[field].autoincrement;
|
|
@@ -760,6 +761,10 @@ export class DatabaseTable {
|
|
|
760
761
|
!idx.primary &&
|
|
761
762
|
!idx.where &&
|
|
762
763
|
!this.hasAdvancedIndexOptions(idx));
|
|
764
|
+
// `getMappedType('timestamptz(3)[]')` resolves to the element type so diffing keeps the modifier, but the property is still an array
|
|
765
|
+
if (column.type?.endsWith('[]') && !column.enumItems?.length) {
|
|
766
|
+
column = { ...column, mappedType: Type.getType(t.array) };
|
|
767
|
+
}
|
|
763
768
|
const kind = this.getReferenceKind(fk, unique);
|
|
764
769
|
const runtimeType = this.getPropertyTypeForColumn(namingStrategy, column, fk);
|
|
765
770
|
const type = fk
|
|
@@ -796,6 +801,7 @@ export class DatabaseTable {
|
|
|
796
801
|
nullable: column.nullable,
|
|
797
802
|
primary: column.primary && persist,
|
|
798
803
|
autoincrement: column.autoincrement,
|
|
804
|
+
sequence: column.sequence,
|
|
799
805
|
fieldName: column.name,
|
|
800
806
|
unsigned: column.unsigned,
|
|
801
807
|
length: column.length,
|
|
@@ -876,9 +882,9 @@ export class DatabaseTable {
|
|
|
876
882
|
return +defaultValue;
|
|
877
883
|
}
|
|
878
884
|
// unquote string defaults if `raw = false`
|
|
879
|
-
const match = /^'(.*)'
|
|
885
|
+
const match = /^'(.*)'$/s.exec('' + val);
|
|
880
886
|
if (!raw && match) {
|
|
881
|
-
return match[1];
|
|
887
|
+
return schemaHelper.unescapeDefault(match[1]);
|
|
882
888
|
}
|
|
883
889
|
return '' + val;
|
|
884
890
|
}
|
|
@@ -924,6 +930,17 @@ export class DatabaseTable {
|
|
|
924
930
|
};
|
|
925
931
|
return [expand(rootProp, 1)];
|
|
926
932
|
}
|
|
933
|
+
// object embedded property index, the JSON keys are the field names of the embedded properties
|
|
934
|
+
if (rootProp?.embeddable && rootProp.object && rootProp.embeddedProps[parts[1]]) {
|
|
935
|
+
let p = rootProp.embeddedProps[parts[1]];
|
|
936
|
+
let i = 2;
|
|
937
|
+
while (i < parts.length && p.embeddedProps?.[parts[i]]) {
|
|
938
|
+
p = p.embeddedProps[parts[i]];
|
|
939
|
+
i++;
|
|
940
|
+
}
|
|
941
|
+
// a path below the last embedded property targets plain JSON keys, kept as they are
|
|
942
|
+
return [[...p.embeddedPath, ...parts.slice(i)].join('.')];
|
|
943
|
+
}
|
|
927
944
|
// json index, we need to rename the column only
|
|
928
945
|
if (rootProp) {
|
|
929
946
|
return [prop.replace(root, rootProp.fieldNames[0])];
|
|
@@ -960,32 +977,41 @@ export class DatabaseTable {
|
|
|
960
977
|
if (columns?.length && properties.length > 0) {
|
|
961
978
|
for (const col of columns) {
|
|
962
979
|
if (!properties.includes(col.name)) {
|
|
963
|
-
throw new
|
|
980
|
+
throw new MetadataError(`Index '${name}' on entity '${meta.className}': column option references field '${col.name}' which is not in the index properties`);
|
|
964
981
|
}
|
|
965
982
|
}
|
|
966
983
|
}
|
|
967
984
|
// Validate fillFactor range
|
|
968
985
|
if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
|
|
969
|
-
throw new
|
|
986
|
+
throw new MetadataError(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${name}' on entity '${meta.className}'`);
|
|
970
987
|
}
|
|
971
988
|
// The `expression` escape hatch takes the full index definition as raw SQL; combining it
|
|
972
989
|
// with `where` is dialect-dependent (PG/Oracle/MySQL drop `where`, MSSQL appends it) so we
|
|
973
990
|
// reject the combination up-front and ask users to inline the predicate into `expression`.
|
|
974
991
|
if (index.expression && index.where != null) {
|
|
975
|
-
throw new
|
|
992
|
+
throw new MetadataError(`Index '${name}' on entity '${meta.className}': cannot combine \`expression\` with \`where\` — inline the WHERE clause into the \`expression\` escape hatch, or drop \`expression\` and use structured \`properties\` + \`where\`.`);
|
|
993
|
+
}
|
|
994
|
+
// `where` forces the `create unique index` form, and no dialect accepts `deferrable` on an index.
|
|
995
|
+
if (index.where != null && index.deferMode) {
|
|
996
|
+
throw new MetadataError(`Index '${name}' on entity '${meta.className}': cannot combine \`deferMode\` with \`where\` — partial unique indexes cannot be deferrable. On PostgreSQL, declare an exclusion constraint instead, e.g. \`exclude using btree (col with =) where (...) deferrable initially ${index.deferMode}\`.`);
|
|
976
997
|
}
|
|
977
998
|
const where = this.processIndexWhere(index.where, meta);
|
|
999
|
+
const expression = this.processIndexExpression(name, index.expression, meta);
|
|
978
1000
|
this.#indexes.push({
|
|
979
1001
|
keyName: name,
|
|
980
1002
|
columnNames: properties,
|
|
981
1003
|
composite: properties.length > 1,
|
|
982
1004
|
// JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them.
|
|
983
1005
|
// Partial indexes (`where`) must use CREATE [UNIQUE] INDEX form — constraints can't carry predicates.
|
|
984
|
-
|
|
1006
|
+
// Raw `create [unique] index` expressions are plain indexes, not constraints.
|
|
1007
|
+
constraint: type !== 'index' &&
|
|
1008
|
+
!properties.some((d) => d.includes('.')) &&
|
|
1009
|
+
!where &&
|
|
1010
|
+
!/^\s*create\s/i.test(expression ?? ''),
|
|
985
1011
|
primary: type === 'primary',
|
|
986
1012
|
unique: type !== 'index',
|
|
987
1013
|
type: index.type,
|
|
988
|
-
expression
|
|
1014
|
+
expression,
|
|
989
1015
|
where,
|
|
990
1016
|
options: index.options,
|
|
991
1017
|
deferMode: index.deferMode,
|
|
@@ -1179,6 +1205,8 @@ export class DatabaseTable {
|
|
|
1179
1205
|
// collapse mysql's `""` for unset comments to `null` so both sources agree. drop entirely on
|
|
1180
1206
|
// platforms that can't read comments back (sqlite), where keeping it would flip the snapshot
|
|
1181
1207
|
comment: supportsComments ? this.comment || null : null,
|
|
1208
|
+
// JSON.stringify drops it when unset, so snapshots of unpartitioned tables stay unchanged
|
|
1209
|
+
partitioning: this.partitioning,
|
|
1182
1210
|
};
|
|
1183
1211
|
// emit RLS state only when set, so snapshots of non-RLS tables stay byte-for-byte unchanged
|
|
1184
1212
|
if (sortedPolicies.length > 0) {
|