@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/AbstractSqlConnection.js
CHANGED
|
@@ -130,6 +130,10 @@ export class AbstractSqlConnection extends Connection {
|
|
|
130
130
|
}
|
|
131
131
|
catch (rollbackError) {
|
|
132
132
|
this.logger.warn('query', `Failed to roll back transaction: ${rollbackError.message}`);
|
|
133
|
+
// the inner writes are still part of the outer transaction, so it must not commit them
|
|
134
|
+
if (options.ctx) {
|
|
135
|
+
options.ctx.failedSavepointRollback ??= new Error(`Cannot commit the transaction, rolling back to savepoint "${trx.savepointName}" failed: ${rollbackError.message}`, { cause: rollbackError });
|
|
136
|
+
}
|
|
133
137
|
}
|
|
134
138
|
throw error;
|
|
135
139
|
}
|
|
@@ -203,6 +207,9 @@ export class AbstractSqlConnection extends Connection {
|
|
|
203
207
|
if (ctx.isRolledBack) {
|
|
204
208
|
return;
|
|
205
209
|
}
|
|
210
|
+
if ('failedSavepointRollback' in ctx) {
|
|
211
|
+
throw ctx.failedSavepointRollback;
|
|
212
|
+
}
|
|
206
213
|
await eventBroadcaster?.dispatchEvent(EventType.beforeTransactionCommit, ctx);
|
|
207
214
|
if ('savepointName' in ctx) {
|
|
208
215
|
await ctx.releaseSavepoint(ctx.savepointName).execute();
|
|
@@ -216,6 +223,10 @@ export class AbstractSqlConnection extends Connection {
|
|
|
216
223
|
}
|
|
217
224
|
/** Rolls back the transaction or rolls back to the savepoint. */
|
|
218
225
|
async rollback(ctx, eventBroadcaster, loggerContext) {
|
|
226
|
+
// kysely rolls back on its own when the database answers a commit with a rollback
|
|
227
|
+
if (ctx.isRolledBack) {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
219
230
|
await eventBroadcaster?.dispatchEvent(EventType.beforeTransactionRollback, ctx);
|
|
220
231
|
await this.waitForIdleTransaction(ctx);
|
|
221
232
|
if ('savepointName' in ctx) {
|
package/AbstractSqlDriver.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
|
|
|
18
18
|
evaluateFormula(formula: (...args: any[]) => string | Raw, columns: any, table: FormulaTable): string;
|
|
19
19
|
/** For TPT entities, returns ownProps (columns in this table); otherwise returns all props. */
|
|
20
20
|
protected getTableProps<T extends object>(meta: EntityMetadata<T>): EntityProperty<T>[];
|
|
21
|
+
/** Columns reloaded by INSERT: generated/default columns any row leaves to the database, and explicit `returning` hints. */
|
|
22
|
+
protected getInsertReturningProperties<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[]): EntityProperty<T>[];
|
|
21
23
|
/** Columns reloaded by UPDATE: raw values, PKs, generated/version columns and explicit `returning` hints. */
|
|
22
24
|
protected getUpdateReturningProperties<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[]): EntityProperty<T>[];
|
|
23
25
|
/** Column expression for the `returning` clause of batch updates, applying `convertToJSValueSQL` of custom types. */
|
|
@@ -63,6 +65,8 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
|
|
|
63
65
|
private buildCloneFields;
|
|
64
66
|
private getCloneableProps;
|
|
65
67
|
nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
|
|
68
|
+
/** Resolves the primary key of every inserted row from the supplied data or the returned rows, and reports them via `insertedIds` when all are known. */
|
|
69
|
+
protected resolveInsertedPrimaryKeys<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[], res: QueryResult<T>): any[][];
|
|
66
70
|
nativeUpdate<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T> & UpsertOptions<T>): Promise<QueryResult<T>>;
|
|
67
71
|
nativeUpdateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T> & UpsertManyOptions<T>, transform?: (sql: string, params: any[]) => string): Promise<QueryResult<T>>;
|
|
68
72
|
nativeDelete<T extends object>(entityName: EntityName<T>, where: FilterQuery<T> | string | any, options?: DeleteOptions<T>): Promise<QueryResult<T>>;
|
|
@@ -127,6 +131,12 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
|
|
|
127
131
|
* @internal
|
|
128
132
|
*/
|
|
129
133
|
protected addTPTPolymorphicJoinsForRelation<T extends object>(qb: AnyQueryBuilder<T>, meta: EntityMetadata<T>, baseAlias: string, fields: InternalField<T>[]): void;
|
|
134
|
+
/**
|
|
135
|
+
* Registers the ancestor table aliases of each polymorphically joined TPT descendant,
|
|
136
|
+
* so formulas on descendants resolve inherited columns to the table that owns them.
|
|
137
|
+
* @internal
|
|
138
|
+
*/
|
|
139
|
+
registerTPTAncestorAliases(qb: AnyQueryBuilder<any>, meta: EntityMetadata, baseAlias: string, childAliases: Dictionary<string>): void;
|
|
130
140
|
/**
|
|
131
141
|
* Find the alias for a TPT child table in the query builder.
|
|
132
142
|
* @internal
|
package/AbstractSqlDriver.js
CHANGED
|
@@ -49,6 +49,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
49
49
|
getTableProps(meta) {
|
|
50
50
|
return meta.inheritanceType === 'tpt' && meta.ownProps ? meta.ownProps : meta.props;
|
|
51
51
|
}
|
|
52
|
+
/** Columns reloaded by INSERT: generated/default columns any row leaves to the database, and explicit `returning` hints. */
|
|
53
|
+
getInsertReturningProperties(meta, data) {
|
|
54
|
+
return this.getTableProps(meta).filter(prop => prop.returning ||
|
|
55
|
+
(((prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated) &&
|
|
56
|
+
data.some(d => !(prop.name in d) || isRaw(d[prop.name]))));
|
|
57
|
+
}
|
|
52
58
|
/** Columns reloaded by UPDATE: raw values, PKs, generated/version columns and explicit `returning` hints. */
|
|
53
59
|
getUpdateReturningProperties(meta, data) {
|
|
54
60
|
const returning = new Set();
|
|
@@ -467,9 +473,14 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
467
473
|
return;
|
|
468
474
|
}
|
|
469
475
|
const mapToPk = !hint.dataOnly && !!(ref || prop.mapToPk);
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
476
|
+
// all rows of a result share their columns, so resolve the mapped props once per join path
|
|
477
|
+
const joinedTargets = (map.joinedTargets ??= {});
|
|
478
|
+
const { targetProps, virtualProps } = (joinedTargets[path] ??= {
|
|
479
|
+
targetProps: (mapToPk
|
|
480
|
+
? meta2.getPrimaryProps()
|
|
481
|
+
: meta2.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []))).filter(prop => prop.fieldNames.some(name => typeof root[`${relationAlias}__${name}`] !== 'undefined')),
|
|
482
|
+
virtualProps: meta2.props.filter(prop => !ref && prop.persist === false && prop.fieldNames),
|
|
483
|
+
});
|
|
473
484
|
// If the primary key value for the relation is null, we know we haven't joined to anything
|
|
474
485
|
// and therefore we don't return any record (since all values would be null)
|
|
475
486
|
const hasPK = meta2.getPrimaryProps().every(pk => pk.fieldNames.every(name => {
|
|
@@ -490,9 +501,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
490
501
|
return;
|
|
491
502
|
}
|
|
492
503
|
let relationPojo = {};
|
|
493
|
-
|
|
494
|
-
.filter(prop => !ref && prop.persist === false && prop.fieldNames)
|
|
495
|
-
.forEach(prop => {
|
|
504
|
+
virtualProps.forEach(prop => {
|
|
496
505
|
/* v8 ignore next */
|
|
497
506
|
if (prop.fieldNames.length > 1) {
|
|
498
507
|
// composite keys
|
|
@@ -798,10 +807,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
798
807
|
? '(' + fields.map(k => this.platform.quoteIdentifier(k)).join(', ') + ')'
|
|
799
808
|
: `(${this.platform.quoteIdentifier(pks[0])})`;
|
|
800
809
|
if (this.platform.usesOutputStatement()) {
|
|
801
|
-
const
|
|
802
|
-
(((prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated) &&
|
|
803
|
-
(!(prop.name in data[0]) || isRaw(data[0][prop.name]))));
|
|
804
|
-
const returningFields = Utils.flatten(returningProps.map(prop => prop.fieldNames));
|
|
810
|
+
const returningFields = Utils.flatten(this.getInsertReturningProperties(meta, data).map(prop => prop.fieldNames));
|
|
805
811
|
sql +=
|
|
806
812
|
returningFields.length > 0
|
|
807
813
|
? ` output ${returningFields.map(field => 'inserted.' + this.platform.quoteIdentifier(field)).join(', ')}`
|
|
@@ -825,11 +831,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
825
831
|
value = this.platform.cloneEmbeddable(value);
|
|
826
832
|
for (let i = 0; i < value.length; i++) {
|
|
827
833
|
const item = value[i];
|
|
828
|
-
value[i] = this.mapDataToFieldNames(item, false, prop
|
|
834
|
+
value[i] = this.mapDataToFieldNames(item, false, this.variantProps(prop, item), options.convertCustomTypes);
|
|
829
835
|
}
|
|
830
836
|
}
|
|
831
837
|
else {
|
|
832
|
-
value = this.mapDataToFieldNames(value, false, prop
|
|
838
|
+
value = this.mapDataToFieldNames(value, false, this.variantProps(prop, value), options.convertCustomTypes);
|
|
833
839
|
}
|
|
834
840
|
}
|
|
835
841
|
if (typeof value === 'undefined' && this.platform.usesDefaultKeyword()) {
|
|
@@ -850,9 +856,19 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
850
856
|
props.forEach(prop => {
|
|
851
857
|
// For STI with conflicting fieldNames, use discriminator to determine which field gets value
|
|
852
858
|
if (prop.stiFieldNames && prop.stiFieldNameMap && meta.discriminatorColumn) {
|
|
853
|
-
|
|
859
|
+
// the map misses subtypes whose props were not initialized yet during discovery (root column owner, grandchildren)
|
|
860
|
+
const discriminator = row[meta.discriminatorColumn];
|
|
861
|
+
const childClass = meta.discriminatorMap?.[discriminator];
|
|
862
|
+
const childProp = childClass && this.metadata.find(childClass)?.properties[prop.name];
|
|
863
|
+
const activeField = prop.stiFieldNameMap[discriminator] ?? childProp?.fieldNames[0];
|
|
854
864
|
for (const field of prop.stiFieldNames) {
|
|
855
|
-
|
|
865
|
+
// the subtype's own property, as siblings can declare it with a different type or embeddable
|
|
866
|
+
if (field === activeField) {
|
|
867
|
+
addParams(childProp ?? prop, row);
|
|
868
|
+
}
|
|
869
|
+
else {
|
|
870
|
+
params.push(null);
|
|
871
|
+
}
|
|
856
872
|
keys.push('?');
|
|
857
873
|
}
|
|
858
874
|
return;
|
|
@@ -918,10 +934,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
918
934
|
.join(', ');
|
|
919
935
|
}
|
|
920
936
|
if (meta && this.platform.usesReturningStatement()) {
|
|
921
|
-
const
|
|
922
|
-
(((prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated) &&
|
|
923
|
-
(!(prop.name in data[0]) || isRaw(data[0][prop.name]))));
|
|
924
|
-
const returningFields = Utils.flatten(returningProps.map(prop => prop.fieldNames));
|
|
937
|
+
const returningFields = Utils.flatten(this.getInsertReturningProperties(meta, data).map(prop => prop.fieldNames));
|
|
925
938
|
/* v8 ignore next */
|
|
926
939
|
sql +=
|
|
927
940
|
returningFields.length > 0
|
|
@@ -932,22 +945,35 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
932
945
|
sql = transform(sql);
|
|
933
946
|
}
|
|
934
947
|
const res = await this.execute(sql, params, 'run', options.ctx, withAbortContext(options.loggerContext, options));
|
|
935
|
-
|
|
936
|
-
if (pks.length > 1) {
|
|
937
|
-
// owner has composite pk
|
|
938
|
-
pk = data.map(d => Utils.getOrderedPrimaryKeys(d, meta));
|
|
939
|
-
}
|
|
940
|
-
else {
|
|
941
|
-
res.row ??= {};
|
|
942
|
-
res.rows ??= [];
|
|
943
|
-
pk = data.map((d, i) => d[pks[0]] ?? res.rows[i]?.[pks[0]]).map(d => [d]);
|
|
944
|
-
res.insertId = res.insertId || res.row[pks[0]];
|
|
945
|
-
}
|
|
948
|
+
const pk = this.resolveInsertedPrimaryKeys(meta, data, res);
|
|
946
949
|
for (let i = 0; i < collections.length; i++) {
|
|
947
950
|
await this.processManyToMany(meta, pk[i], collections[i], false, options);
|
|
948
951
|
}
|
|
949
952
|
return res;
|
|
950
953
|
}
|
|
954
|
+
/** Resolves the primary key of every inserted row from the supplied data or the returned rows, and reports them via `insertedIds` when all are known. */
|
|
955
|
+
resolveInsertedPrimaryKeys(meta, data, res) {
|
|
956
|
+
const pks = this.getPrimaryKeyFields(meta);
|
|
957
|
+
if (pks.length > 1) {
|
|
958
|
+
// owner has composite pk
|
|
959
|
+
const pk = data.map(d => Utils.getOrderedPrimaryKeys(d, meta));
|
|
960
|
+
res.insertedIds = pk;
|
|
961
|
+
return pk;
|
|
962
|
+
}
|
|
963
|
+
res.row ??= {};
|
|
964
|
+
res.rows ??= [];
|
|
965
|
+
const ids = data.map((d, i) => {
|
|
966
|
+
// a raw pk expression is resolved by the database, its value only exists in the returned row
|
|
967
|
+
const supplied = d[meta.primaryKeys[0]] ?? d[pks[0]];
|
|
968
|
+
return supplied == null || isRaw(supplied) ? res.rows[i]?.[pks[0]] : supplied;
|
|
969
|
+
});
|
|
970
|
+
res.insertId = res.insertId || res.row[pks[0]];
|
|
971
|
+
// drivers without `returning` leave the ids unknown here, keep the `insertId` fallback for them
|
|
972
|
+
if (ids.every(id => id != null)) {
|
|
973
|
+
res.insertedIds = ids;
|
|
974
|
+
}
|
|
975
|
+
return ids.map(id => [id]);
|
|
976
|
+
}
|
|
951
977
|
async nativeUpdate(entityName, where, data, options = {}) {
|
|
952
978
|
options.convertCustomTypes ??= true;
|
|
953
979
|
const meta = this.metadata.get(entityName);
|
|
@@ -1007,16 +1033,23 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1007
1033
|
const meta = this.metadata.get(entityName);
|
|
1008
1034
|
if (options.upsert) {
|
|
1009
1035
|
if (meta.tptParent) {
|
|
1036
|
+
// the parent table reports a single insertId per batch, the EM sends such rows one by one
|
|
1037
|
+
if (where.filter(cond => Utils.isEmpty(cond)).length > 1) {
|
|
1038
|
+
throw new Error(`Cannot upsert more than one ${meta.className} row without a unique value in one batch`);
|
|
1039
|
+
}
|
|
1010
1040
|
// TPT parent tables go first, the PK they provide is the conflict target of this table
|
|
1011
|
-
await this.nativeUpdateMany(meta.tptParent.class, where, data, options);
|
|
1041
|
+
const res = await this.nativeUpdateMany(meta.tptParent.class, where, data, options);
|
|
1012
1042
|
for (const [i, row] of data.entries()) {
|
|
1013
1043
|
if (meta.primaryKeys.some(pk => row[pk] == null)) {
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1044
|
+
// a row without a condition cannot conflict, only the insert knows its PK
|
|
1045
|
+
const found = Utils.isEmpty(where[i])
|
|
1046
|
+
? { [meta.primaryKeys[0]]: res.insertId }
|
|
1047
|
+
: await this.findOne(meta.tptParent.class, where[i], {
|
|
1048
|
+
fields: meta.primaryKeys,
|
|
1049
|
+
ctx: options.ctx,
|
|
1050
|
+
connectionType: 'write',
|
|
1051
|
+
schema: options.schema,
|
|
1052
|
+
});
|
|
1020
1053
|
meta.primaryKeys.forEach(pk => (row[pk] = found?.[pk]));
|
|
1021
1054
|
}
|
|
1022
1055
|
}
|
|
@@ -1036,7 +1069,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1036
1069
|
data = data.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => own(key))));
|
|
1037
1070
|
options.onConflictMergeFields = options.onConflictMergeFields?.filter(f => own(f));
|
|
1038
1071
|
options.onConflictExcludeFields = options.onConflictExcludeFields?.filter(f => own(f));
|
|
1039
|
-
returning =
|
|
1072
|
+
returning = this.getPrimaryKeyFields(meta);
|
|
1040
1073
|
}
|
|
1041
1074
|
qb.insert(data)
|
|
1042
1075
|
.onConflict(uniqueFields)
|
|
@@ -1052,7 +1085,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1052
1085
|
qb.where(options.onConflictWhere);
|
|
1053
1086
|
}
|
|
1054
1087
|
const res = await this.rethrow(qb.execute('run', false));
|
|
1055
|
-
|
|
1088
|
+
if (meta.inheritanceType === 'tpt') {
|
|
1089
|
+
// child tables do not generate the PK, so every table of the hierarchy reports the one of its first row
|
|
1090
|
+
const insertId = data[0][meta.primaryKeys[0]] ?? res.insertId ?? res.row?.[returning[0]];
|
|
1091
|
+
return { ...res, insertId, row: undefined, rows: [] };
|
|
1092
|
+
}
|
|
1093
|
+
return res;
|
|
1056
1094
|
}
|
|
1057
1095
|
const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : [];
|
|
1058
1096
|
const keys = new Set();
|
|
@@ -1073,11 +1111,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1073
1111
|
if (prop.array && value) {
|
|
1074
1112
|
for (let i = 0; i < value.length; i++) {
|
|
1075
1113
|
const item = value[i];
|
|
1076
|
-
value[i] = this.mapDataToFieldNames(item, false, prop
|
|
1114
|
+
value[i] = this.mapDataToFieldNames(item, false, this.variantProps(prop, item), options.convertCustomTypes);
|
|
1077
1115
|
}
|
|
1078
1116
|
}
|
|
1079
1117
|
else {
|
|
1080
|
-
value = this.mapDataToFieldNames(value, false, prop
|
|
1118
|
+
value = this.mapDataToFieldNames(value, false, this.variantProps(prop, value), options.convertCustomTypes);
|
|
1081
1119
|
}
|
|
1082
1120
|
}
|
|
1083
1121
|
params.push(value ?? null);
|
|
@@ -1139,26 +1177,32 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1139
1177
|
}
|
|
1140
1178
|
sql += ' where ';
|
|
1141
1179
|
const pkProps = meta.primaryKeys.concat(...meta.getOwnConcurrencyCheckKeys());
|
|
1180
|
+
// an optimistically locked batch carries the version in every condition
|
|
1181
|
+
if (meta.versionProperty &&
|
|
1182
|
+
where.every(cond => Utils.isPlainObject(cond) && meta.versionProperty in cond)) {
|
|
1183
|
+
pkProps.push(meta.versionProperty);
|
|
1184
|
+
}
|
|
1142
1185
|
const pks = Utils.flatten(pkProps.map(pk => meta.properties[pk].fieldNames));
|
|
1143
1186
|
const useTupleIn = pks.length <= 1 || this.platform.allowsComparingTuples();
|
|
1144
1187
|
const condTemplate = useTupleIn
|
|
1145
1188
|
? `(${pks.map(() => '?').join(', ')})`
|
|
1146
1189
|
: `(${pks.map(pk => `${this.platform.quoteIdentifier(pk)} = ?`).join(' and ')})`;
|
|
1147
|
-
const conds = where.
|
|
1190
|
+
const conds = where.flatMap(cond => {
|
|
1148
1191
|
// with multiple PK columns the condition is looked up by property name, so it needs to stay an object
|
|
1149
1192
|
if (pks.length === 1 && Utils.isPlainObject(cond) && Utils.getObjectKeysSize(cond) === 1) {
|
|
1150
1193
|
cond = Object.values(cond)[0];
|
|
1151
1194
|
}
|
|
1152
1195
|
if (pks.length > 1) {
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1196
|
+
// a date version in sqlite matches either of its storage formats (see `convertVersionValue()`)
|
|
1197
|
+
const version = cond[meta.versionProperty];
|
|
1198
|
+
const versions = version?.$in ?? [version];
|
|
1199
|
+
return versions.map(v => {
|
|
1200
|
+
pkProps.forEach(pk => {
|
|
1201
|
+
const value = pk === meta.versionProperty ? v : cond[pk];
|
|
1202
|
+
params.push(...(Array.isArray(value) ? Utils.flatten(value) : [value]));
|
|
1203
|
+
});
|
|
1204
|
+
return condTemplate;
|
|
1160
1205
|
});
|
|
1161
|
-
return condTemplate;
|
|
1162
1206
|
}
|
|
1163
1207
|
params.push(cond);
|
|
1164
1208
|
return '?';
|
|
@@ -1809,7 +1853,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1809
1853
|
if (!this.platform.shouldHaveColumn(prop, populate, exclude)) {
|
|
1810
1854
|
return false;
|
|
1811
1855
|
}
|
|
1812
|
-
if (!fields ||
|
|
1856
|
+
if (!fields ||
|
|
1857
|
+
fields.includes('*') ||
|
|
1858
|
+
prop.primary ||
|
|
1859
|
+
meta.root.discriminatorColumn === prop.name ||
|
|
1860
|
+
meta.root.targetKeys?.includes(prop.name)) {
|
|
1813
1861
|
return true;
|
|
1814
1862
|
}
|
|
1815
1863
|
return fields.some(f => f === prop.name || f.toString().startsWith(prop.name + '.'));
|
|
@@ -1865,11 +1913,9 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1865
1913
|
const tptMeta = this.metadata.get(targetMeta.class);
|
|
1866
1914
|
this.addTPTPolymorphicJoinsForRelation(qb, tptMeta, tableAlias, fields);
|
|
1867
1915
|
}
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
}
|
|
1872
|
-
else {
|
|
1916
|
+
// target filters apply per target, both for filter :ref hints and populated relations
|
|
1917
|
+
qb.scheduleFilterCheck(targetPath);
|
|
1918
|
+
if (!ref) {
|
|
1873
1919
|
// Select fields from each target table
|
|
1874
1920
|
fields.push(...this.getFieldsForJoinedLoad(qb, targetMeta, {
|
|
1875
1921
|
...options,
|
|
@@ -1965,6 +2011,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1965
2011
|
qb.createAlias(childMeta.class, childAlias);
|
|
1966
2012
|
childAliases[childMeta.className] = childAlias;
|
|
1967
2013
|
qb.addPropertyJoin(childMeta.tptInverseProp, baseAlias, childAlias, JoinType.leftJoin, `[tpt]${meta.className}`);
|
|
2014
|
+
}
|
|
2015
|
+
this.registerTPTAncestorAliases(qb, meta, baseAlias, childAliases);
|
|
2016
|
+
for (const childMeta of descendants) {
|
|
2017
|
+
const childAlias = childAliases[childMeta.className];
|
|
1968
2018
|
// Add fields from this child (only ownProps, skip PKs)
|
|
1969
2019
|
const schema = childMeta.schema === '*' ? '*' : this.getSchemaName(childMeta);
|
|
1970
2020
|
childMeta
|
|
@@ -1976,6 +2026,21 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1976
2026
|
fields.push(this.buildTPTDiscriminatorExpression(meta, descendants, childAliases, baseAlias));
|
|
1977
2027
|
}
|
|
1978
2028
|
}
|
|
2029
|
+
/**
|
|
2030
|
+
* Registers the ancestor table aliases of each polymorphically joined TPT descendant,
|
|
2031
|
+
* so formulas on descendants resolve inherited columns to the table that owns them.
|
|
2032
|
+
* @internal
|
|
2033
|
+
*/
|
|
2034
|
+
registerTPTAncestorAliases(qb, meta, baseAlias, childAliases) {
|
|
2035
|
+
const tptAlias = qb.state.tptAlias;
|
|
2036
|
+
for (const childMeta of meta.allTPTDescendants) {
|
|
2037
|
+
for (let parent = childMeta.tptParent; parent; parent = parent.tptParent) {
|
|
2038
|
+
tptAlias[`${childAliases[childMeta.className]}:${parent.className}`] =
|
|
2039
|
+
childAliases[parent.className] ??
|
|
2040
|
+
(parent === meta ? baseAlias : tptAlias[`${baseAlias}:${parent.className}`]);
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
1979
2044
|
/**
|
|
1980
2045
|
* Find the alias for a TPT child table in the query builder.
|
|
1981
2046
|
* @internal
|
|
@@ -2063,6 +2128,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
2063
2128
|
}
|
|
2064
2129
|
const aliased = this.platform.quoteIdentifier(`${tableAlias}__${prop.fieldNames[0]}`);
|
|
2065
2130
|
const sourceAlias = qb.helper.getTPTAliasForProperty(prop.name, tableAlias);
|
|
2131
|
+
if (prop.formula) {
|
|
2132
|
+
const quotedAlias = this.platform.quoteIdentifier(tableAlias).toString();
|
|
2133
|
+
const table = this.createFormulaTable(quotedAlias, meta, schema);
|
|
2134
|
+
const columns = meta.createColumnMappingObject(p => qb.helper.getTPTAliasForProperty(p.name, tableAlias), quotedAlias);
|
|
2135
|
+
return [raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`)];
|
|
2136
|
+
}
|
|
2066
2137
|
if (prop.customTypes?.some(type => !!type?.convertToJSValueSQL)) {
|
|
2067
2138
|
return prop.fieldNames.map((col, idx) => {
|
|
2068
2139
|
if (!prop.customTypes[idx]?.convertToJSValueSQL) {
|
|
@@ -2077,12 +2148,6 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
2077
2148
|
const prefixed = this.platform.quoteIdentifier(`${sourceAlias}.${prop.fieldNames[0]}`);
|
|
2078
2149
|
return [raw(`${prop.customType.convertToJSValueSQL(prefixed, this.platform)} as ${aliased}`)];
|
|
2079
2150
|
}
|
|
2080
|
-
if (prop.formula) {
|
|
2081
|
-
const quotedAlias = this.platform.quoteIdentifier(tableAlias).toString();
|
|
2082
|
-
const table = this.createFormulaTable(quotedAlias, meta, schema);
|
|
2083
|
-
const columns = meta.createColumnMappingObject(tableAlias);
|
|
2084
|
-
return [raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`)];
|
|
2085
|
-
}
|
|
2086
2151
|
return prop.fieldNames.map(fieldName => {
|
|
2087
2152
|
return raw('?? as ??', [`${sourceAlias}.${fieldName}`, `${tableAlias}__${fieldName}`]);
|
|
2088
2153
|
});
|
|
@@ -2469,6 +2534,8 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
2469
2534
|
}
|
|
2470
2535
|
if (!options.fields.includes('*') && !options.fields.includes(`${qb.alias}.*`)) {
|
|
2471
2536
|
ret.unshift(...meta.primaryKeys.filter(pk => !options.fields.includes(pk)));
|
|
2537
|
+
// `targetKey` values identify the entity like its PK, references resolve it by them
|
|
2538
|
+
ret.push(...(meta.root.targetKeys ?? []).filter(key => meta.properties[key] && !options.fields.includes(key)));
|
|
2472
2539
|
}
|
|
2473
2540
|
if (meta.root.inheritanceType === 'sti' &&
|
|
2474
2541
|
!options.fields.includes(`${qb.alias}.${meta.root.discriminatorColumn}`)) {
|
|
@@ -2488,9 +2555,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
2488
2555
|
ret.push('*');
|
|
2489
2556
|
}
|
|
2490
2557
|
if (ret.length > 0 && !hasExplicitFields && addFormulas) {
|
|
2491
|
-
//
|
|
2558
|
+
// `toString()` must yield the quoted alias like `QueryBuilder.finalize()`, which dedupes formulas by rendered SQL
|
|
2492
2559
|
const quotedAlias = this.platform.quoteIdentifier(alias);
|
|
2493
|
-
|
|
2560
|
+
// TPT parent aliases are only known once the parent joins exist
|
|
2561
|
+
qb.ensureTPTJoins();
|
|
2562
|
+
const columns = meta.createColumnMappingObject(p => qb.helper.getTPTAliasForProperty(p.name, alias), quotedAlias.toString());
|
|
2494
2563
|
const effectiveSchema = schema ?? (meta.schema !== '*' ? meta.schema : undefined);
|
|
2495
2564
|
for (const prop of meta.props) {
|
|
2496
2565
|
if (lazyProps.includes(prop)) {
|
|
@@ -2501,7 +2570,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
2501
2570
|
const table = this.createFormulaTable(quotedAlias.toString(), meta, effectiveSchema);
|
|
2502
2571
|
ret.push(raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`));
|
|
2503
2572
|
}
|
|
2504
|
-
if (!prop.object && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)) {
|
|
2573
|
+
if (!prop.object && !prop.formula && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)) {
|
|
2505
2574
|
ret.push(prop.name);
|
|
2506
2575
|
}
|
|
2507
2576
|
}
|
package/AbstractSqlPlatform.js
CHANGED
|
@@ -96,7 +96,7 @@ export class AbstractSqlPlatform extends Platform {
|
|
|
96
96
|
return this.formatQuery(value.sql, value.params);
|
|
97
97
|
}
|
|
98
98
|
if (Utils.isPlainObject(value) || value?.[JsonProperty]) {
|
|
99
|
-
return this.escape(
|
|
99
|
+
return this.escape(this.convertJsonToDatabaseValue(value));
|
|
100
100
|
}
|
|
101
101
|
return this.escape(value);
|
|
102
102
|
}
|
package/SqlEntityManager.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EntityManager, raw, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { EntityManager, QueryFlag, raw, Utils, } from '@mikro-orm/core';
|
|
2
2
|
import { MikroKyselyPlugin } from './plugin/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* @inheritDoc
|
|
@@ -87,6 +87,7 @@ export class SqlEntityManager extends EntityManager {
|
|
|
87
87
|
// match `em.count()` semantics: an active transaction always wins over the requested connection type
|
|
88
88
|
const connectionType = em.getTransactionContext() ? 'write' : options.connectionType;
|
|
89
89
|
const qb = em.createQueryBuilder(meta.class, undefined, connectionType);
|
|
90
|
+
qb.unsetFlag(QueryFlag.CONVERT_CUSTOM_TYPES);
|
|
90
91
|
qb
|
|
91
92
|
.select([...fields, raw('count(*) as cnt')])
|
|
92
93
|
.where(where)
|
|
@@ -130,17 +130,18 @@ export class MsSqlNativeQueryBuilder extends NativeQueryBuilder {
|
|
|
130
130
|
}
|
|
131
131
|
this.parts.push('then update set');
|
|
132
132
|
if (!clause.merge || Array.isArray(clause.merge)) {
|
|
133
|
-
const
|
|
133
|
+
const merge = clause.merge?.length ? clause.merge : keys;
|
|
134
|
+
const parts = merge
|
|
134
135
|
.filter(field => !Array.isArray(clause.fields) || !clause.fields.includes(field))
|
|
135
136
|
.map((column) => `${this.quote(column)} = tsource.${this.quote(column)}`);
|
|
136
|
-
this.parts.push(
|
|
137
|
+
this.parts.push(this.joinVersionMerge(clause, parts, merge));
|
|
137
138
|
}
|
|
138
139
|
else if (typeof clause.merge === 'object') {
|
|
139
140
|
const parts = Object.entries(clause.merge).map(([key, value]) => {
|
|
140
141
|
this.params.push(value);
|
|
141
142
|
return `${this.getTableName()}.${this.quote(key)} = ?`;
|
|
142
143
|
});
|
|
143
|
-
this.parts.push(
|
|
144
|
+
this.parts.push(this.joinVersionMerge(clause, parts, Object.keys(clause.merge)));
|
|
144
145
|
}
|
|
145
146
|
}
|
|
146
147
|
this.addOutputClause('inserted');
|
|
@@ -16,6 +16,16 @@ export declare class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
16
16
|
};
|
|
17
17
|
/** mysql and mariadb treat null as the lowest value when no placement is requested. */
|
|
18
18
|
sortsNullsLowest(): boolean;
|
|
19
|
+
/** mysql reads backslashes in string literals as escapes, so defaults need the same escaping as values (minus the needless `\"`). */
|
|
20
|
+
quoteDefaultValue(value: string): string;
|
|
21
|
+
/** enum items are escaped the way mysql prints them back in `column_type`, so the next schema diff matches. */
|
|
22
|
+
getEnumTypeDeclarationSQL(column: {
|
|
23
|
+
items?: unknown[];
|
|
24
|
+
fieldNames: string[];
|
|
25
|
+
length?: number;
|
|
26
|
+
unsigned?: boolean;
|
|
27
|
+
autoincrement?: boolean;
|
|
28
|
+
}): string;
|
|
19
29
|
supportsMultiColumnCountDistinct(): boolean;
|
|
20
30
|
/** @internal */
|
|
21
31
|
createNativeQueryBuilder(): MySqlNativeQueryBuilder;
|
|
@@ -37,6 +47,7 @@ export declare class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
37
47
|
getDefaultMappedType(type: string): Type<unknown>;
|
|
38
48
|
isNumericColumn(mappedType: Type<unknown>): boolean;
|
|
39
49
|
supportsUnsigned(): boolean;
|
|
50
|
+
supportsAutoincrementIncrement(): boolean;
|
|
40
51
|
/** MySQL/MariaDB identifier limit. */
|
|
41
52
|
getMaxIdentifierLength(): number;
|
|
42
53
|
getIndexName(tableName: string, columns: string[], type: 'index' | 'unique' | 'foreign' | 'primary' | 'sequence' | 'check'): string;
|
|
@@ -12,6 +12,13 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
12
12
|
bigint: 'bigint',
|
|
13
13
|
boolean: 'unsigned',
|
|
14
14
|
};
|
|
15
|
+
#enumItemEscapes = {
|
|
16
|
+
'\0': '\\0',
|
|
17
|
+
'\n': '\\n',
|
|
18
|
+
'\r': '\\r',
|
|
19
|
+
"'": "''",
|
|
20
|
+
'\\': '\\\\',
|
|
21
|
+
};
|
|
15
22
|
ORDER_BY_NULLS_TRANSLATE = {
|
|
16
23
|
[QueryOrder.asc_nulls_first]: 'is not null',
|
|
17
24
|
[QueryOrder.asc_nulls_last]: 'is null',
|
|
@@ -22,6 +29,15 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
22
29
|
sortsNullsLowest() {
|
|
23
30
|
return true;
|
|
24
31
|
}
|
|
32
|
+
/** mysql reads backslashes in string literals as escapes, so defaults need the same escaping as values (minus the needless `\"`). */
|
|
33
|
+
quoteDefaultValue(value) {
|
|
34
|
+
return this.quoteValue(value).replaceAll('\\"', '"');
|
|
35
|
+
}
|
|
36
|
+
/** enum items are escaped the way mysql prints them back in `column_type`, so the next schema diff matches. */
|
|
37
|
+
getEnumTypeDeclarationSQL(column) {
|
|
38
|
+
const items = column.items?.map(item => typeof item === 'string' ? item.replace(/[\0\n\r'\\]/g, c => this.#enumItemEscapes[c]) : item);
|
|
39
|
+
return super.getEnumTypeDeclarationSQL({ ...column, items });
|
|
40
|
+
}
|
|
25
41
|
supportsMultiColumnCountDistinct() {
|
|
26
42
|
return true;
|
|
27
43
|
}
|
|
@@ -30,7 +46,7 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
30
46
|
return new MySqlNativeQueryBuilder(this);
|
|
31
47
|
}
|
|
32
48
|
formatIndexHint(indexNames) {
|
|
33
|
-
return `use index(${indexNames.join(', ')})`;
|
|
49
|
+
return `use index(${indexNames.map(name => this.quoteIdentifier(name)).join(', ')})`;
|
|
34
50
|
}
|
|
35
51
|
getDefaultCharset() {
|
|
36
52
|
return 'utf8mb4';
|
|
@@ -90,6 +106,9 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
90
106
|
supportsUnsigned() {
|
|
91
107
|
return true;
|
|
92
108
|
}
|
|
109
|
+
supportsAutoincrementIncrement() {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
93
112
|
/** MySQL/MariaDB identifier limit. */
|
|
94
113
|
getMaxIdentifierLength() {
|
|
95
114
|
return 64;
|
|
@@ -58,16 +58,17 @@ export class MySqlNativeQueryBuilder extends NativeQueryBuilder {
|
|
|
58
58
|
this.params.push(clause.merge[field]);
|
|
59
59
|
return `${this.quote(field)} = ?`;
|
|
60
60
|
});
|
|
61
|
-
this.parts.push(
|
|
61
|
+
this.parts.push(this.joinVersionMerge(clause, fields, Object.keys(clause.merge)));
|
|
62
62
|
}
|
|
63
63
|
else if (clause.merge.length === 0) {
|
|
64
64
|
const dataAsArray = Utils.asArray(this.options.data);
|
|
65
65
|
const keys = Object.keys(dataAsArray[0]);
|
|
66
|
-
|
|
66
|
+
const fields = keys.map(key => `${this.quote(key)} = values(${this.quote(key)})`);
|
|
67
|
+
this.parts.push(this.joinVersionMerge(clause, fields, keys));
|
|
67
68
|
}
|
|
68
69
|
else {
|
|
69
70
|
const fields = clause.merge.map(key => `${this.quote(key)} = values(${this.quote(key)})`);
|
|
70
|
-
this.parts.push(
|
|
71
|
+
this.parts.push(this.joinVersionMerge(clause, fields, clause.merge));
|
|
71
72
|
}
|
|
72
73
|
if (clause.where) {
|
|
73
74
|
this.parts.push(`where ${clause.where.sql}`);
|
|
@@ -16,10 +16,16 @@ export declare class MySqlSchemaHelper extends SchemaHelper {
|
|
|
16
16
|
getSchemaBeginning(charset: string, disableForeignKeys?: boolean): string;
|
|
17
17
|
getSetSchemaSQL(schema: string): string;
|
|
18
18
|
getResetSchemaSQL(defaultSchema: string): string;
|
|
19
|
+
getMigrationLockSQL(): {
|
|
20
|
+
acquire: string;
|
|
21
|
+
release: string;
|
|
22
|
+
};
|
|
19
23
|
supportsMigrationSchema(): boolean;
|
|
20
24
|
tableExists(connection: AbstractSqlConnection, tableName: string, schemaName: string | undefined, ctx?: Transaction): Promise<boolean>;
|
|
21
25
|
disableForeignKeysSQL(): string;
|
|
22
26
|
enableForeignKeysSQL(): string;
|
|
27
|
+
getResetSequenceSQL(tableName: string, schemaName: string | undefined, columnName: string, startWith: number): string;
|
|
28
|
+
getAddColumnsSQL(table: DatabaseTable, columns: Column[]): string[];
|
|
23
29
|
finalizeTable(table: DatabaseTable, charset: string, collate?: string): string;
|
|
24
30
|
getListTablesSQL(): string;
|
|
25
31
|
getListViewsSQL(): string;
|
|
@@ -62,4 +68,6 @@ export declare class MySqlSchemaHelper extends SchemaHelper {
|
|
|
62
68
|
protected getChecksSQL(tables: Table[]): string;
|
|
63
69
|
normalizeDefaultValue(defaultValue: string, length: number): string | number;
|
|
64
70
|
protected wrap(val: string | null | undefined, type: Type<unknown>): string | null | undefined;
|
|
71
|
+
/** Decodes the backslash escapes of an introspected string literal. */
|
|
72
|
+
unescapeDefault(val: string): string;
|
|
65
73
|
}
|