@mikro-orm/sql 7.3.0-dev.20 → 7.3.0-dev.22
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/AbstractSqlDriver.d.ts +5 -1
- package/AbstractSqlDriver.js +26 -21
- package/AbstractSqlPlatform.js +6 -3
- package/dialects/mssql/MsSqlNativeQueryBuilder.js +4 -3
- package/dialects/mysql/BaseMySqlPlatform.d.ts +8 -0
- package/dialects/mysql/BaseMySqlPlatform.js +13 -1
- package/dialects/mysql/MySqlNativeQueryBuilder.js +4 -3
- package/dialects/mysql/MySqlSchemaHelper.d.ts +1 -0
- package/dialects/mysql/MySqlSchemaHelper.js +10 -6
- package/dialects/oracledb/OracleNativeQueryBuilder.js +4 -3
- package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +1 -0
- package/dialects/postgresql/BasePostgreSqlPlatform.js +11 -17
- package/dialects/postgresql/PostgreSqlSchemaHelper.js +11 -4
- package/index.d.ts +2 -0
- package/index.js +2 -0
- package/package.json +3 -3
- package/query/NativeQueryBuilder.d.ts +6 -0
- package/query/NativeQueryBuilder.js +22 -3
- package/query/ObjectCriteriaNode.js +4 -1
- package/query/QueryBuilder.d.ts +5 -2
- package/query/QueryBuilder.js +39 -30
- package/query/QueryBuilderHelper.js +45 -31
- package/schema/DatabaseTable.js +5 -1
- package/schema/SchemaComparator.d.ts +1 -0
- package/schema/SchemaComparator.js +22 -3
- package/typings.d.ts +2 -0
package/AbstractSqlDriver.d.ts
CHANGED
|
@@ -63,7 +63,11 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
|
|
|
63
63
|
private nativeCloneTPT;
|
|
64
64
|
private mapCloneOverrides;
|
|
65
65
|
private buildCloneFields;
|
|
66
|
-
|
|
66
|
+
/**
|
|
67
|
+
* Returns properties whose columns can be copied by an `INSERT … SELECT` (owning columns that are not PKs, generated or formulas).
|
|
68
|
+
* @internal
|
|
69
|
+
*/
|
|
70
|
+
getCloneableProps<T extends object>(meta: EntityMetadata<T>, ownProps?: boolean): EntityProperty<T>[];
|
|
67
71
|
nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
|
|
68
72
|
/** 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
73
|
protected resolveInsertedPrimaryKeys<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[], res: QueryResult<T>): any[][];
|
package/AbstractSqlDriver.js
CHANGED
|
@@ -342,6 +342,14 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
342
342
|
if (qb) {
|
|
343
343
|
// here we map the aliased results (cartesian product) to an object graph
|
|
344
344
|
this.mapJoinedProps(ret, meta, populate, qb, ret, map);
|
|
345
|
+
// the aliased columns were deleted, which left the row in slow dictionary mode
|
|
346
|
+
if (populate.length > 0) {
|
|
347
|
+
const clean = {};
|
|
348
|
+
for (const key in ret) {
|
|
349
|
+
clean[key] = ret[key];
|
|
350
|
+
}
|
|
351
|
+
return clean;
|
|
352
|
+
}
|
|
345
353
|
}
|
|
346
354
|
return ret;
|
|
347
355
|
}
|
|
@@ -763,25 +771,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
763
771
|
}
|
|
764
772
|
return { selectFields, insertColumns };
|
|
765
773
|
}
|
|
774
|
+
/**
|
|
775
|
+
* Returns properties whose columns can be copied by an `INSERT … SELECT` (owning columns that are not PKs, generated or formulas).
|
|
776
|
+
* @internal
|
|
777
|
+
*/
|
|
766
778
|
getCloneableProps(meta, ownProps) {
|
|
767
|
-
return (ownProps ? (meta.ownProps ?? meta.props) : meta.props).filter(prop =>
|
|
768
|
-
if (prop.persist === false) {
|
|
769
|
-
return false;
|
|
770
|
-
}
|
|
771
|
-
if (prop.primary) {
|
|
772
|
-
return false;
|
|
773
|
-
}
|
|
774
|
-
if (!prop.fieldNames?.length) {
|
|
775
|
-
return false;
|
|
776
|
-
}
|
|
777
|
-
if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
|
|
778
|
-
return false;
|
|
779
|
-
}
|
|
780
|
-
if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) {
|
|
781
|
-
return false;
|
|
782
|
-
}
|
|
783
|
-
return true;
|
|
784
|
-
});
|
|
779
|
+
return (ownProps ? (meta.ownProps ?? meta.props) : meta.props).filter(prop => !prop.primary && !prop.generated && this.platform.shouldHaveColumn(prop, true, undefined, false, false));
|
|
785
780
|
}
|
|
786
781
|
async nativeInsertMany(entityName, data, options = {}, transform) {
|
|
787
782
|
options.processCollections ??= true;
|
|
@@ -1130,6 +1125,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1130
1125
|
}
|
|
1131
1126
|
}
|
|
1132
1127
|
}
|
|
1128
|
+
const scalarColumn = prop.fieldNames.length > 1 && !prop.polymorphic ? this.getScalarFieldName(prop) : undefined;
|
|
1133
1129
|
prop.fieldNames.forEach((fieldName, fieldNameIdx) => {
|
|
1134
1130
|
if (fields.has(fieldName) || (prop.ownColumns && !prop.ownColumns.includes(fieldName))) {
|
|
1135
1131
|
return;
|
|
@@ -1151,7 +1147,15 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1151
1147
|
sql += '?';
|
|
1152
1148
|
}
|
|
1153
1149
|
params.push(...pks);
|
|
1154
|
-
|
|
1150
|
+
const value = data[idx][key];
|
|
1151
|
+
const scalar = Array.isArray(value) && value.length === 1 ? value[0] : value;
|
|
1152
|
+
// a composite FK given as a scalar holds only the target PK, written to the column that references it
|
|
1153
|
+
if (scalarColumn && !isRaw(scalar) && Utils.isPrimaryKey(scalar)) {
|
|
1154
|
+
addParams(prop, (fieldName === scalarColumn ? scalar : null));
|
|
1155
|
+
}
|
|
1156
|
+
else {
|
|
1157
|
+
addParams(prop, prop.fieldNames.length > 1 ? value?.[fieldNameIdx] : value);
|
|
1158
|
+
}
|
|
1155
1159
|
}
|
|
1156
1160
|
});
|
|
1157
1161
|
sql += ` else ${this.platform.quoteIdentifier(fieldName)} end, `;
|
|
@@ -1692,9 +1696,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1692
1696
|
if (!Utils.isEmpty(orderBy) || RawQueryFragment.hasObjectFragments(orderBy)) {
|
|
1693
1697
|
return Utils.asArray(orderBy).map(o => ({ [pivotProp.name]: o }));
|
|
1694
1698
|
}
|
|
1695
|
-
if (prop.kind === ReferenceKind.MANY_TO_MANY &&
|
|
1699
|
+
if (prop.kind === ReferenceKind.MANY_TO_MANY &&
|
|
1700
|
+
Utils.asArray(parentOrderBy).some(o => !Utils.isEmpty(o[prop.name]))) {
|
|
1696
1701
|
return Utils.asArray(parentOrderBy)
|
|
1697
|
-
.filter(o => o[prop.name])
|
|
1702
|
+
.filter(o => !Utils.isEmpty(o[prop.name]))
|
|
1698
1703
|
.map(o => ({ [pivotProp.name]: o[prop.name] }));
|
|
1699
1704
|
}
|
|
1700
1705
|
if (!Utils.isEmpty(prop.orderBy) || RawQueryFragment.hasObjectFragments(prop.orderBy)) {
|
package/AbstractSqlPlatform.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isRaw, JsonProperty, Platform, raw, Utils, ValidationError, } from '@mikro-orm/core';
|
|
1
|
+
import { inspect, isRaw, JsonProperty, Platform, raw, Utils, ValidationError, } from '@mikro-orm/core';
|
|
2
2
|
import { SqlEntityRepository } from './SqlEntityRepository.js';
|
|
3
3
|
import { SqlSchemaGenerator } from './schema/SqlSchemaGenerator.js';
|
|
4
4
|
import { NativeQueryBuilder } from './query/NativeQueryBuilder.js';
|
|
@@ -169,9 +169,12 @@ export class AbstractSqlPlatform extends Platform {
|
|
|
169
169
|
* @internal
|
|
170
170
|
*/
|
|
171
171
|
validateOrderByDirection(direction) {
|
|
172
|
-
|
|
172
|
+
if (typeof direction !== 'string') {
|
|
173
|
+
throw new ValidationError(`Invalid order direction: ${inspect(direction)}`);
|
|
174
|
+
}
|
|
175
|
+
const dir = direction.toLowerCase().trim();
|
|
173
176
|
if (!AbstractSqlPlatform.ORDER_BY_DIRECTIONS.has(dir)) {
|
|
174
|
-
throw new
|
|
177
|
+
throw new ValidationError(`Invalid order direction: '${direction}'`);
|
|
175
178
|
}
|
|
176
179
|
return dir;
|
|
177
180
|
}
|
|
@@ -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');
|
|
@@ -18,6 +18,14 @@ export declare class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
18
18
|
sortsNullsLowest(): boolean;
|
|
19
19
|
/** mysql reads backslashes in string literals as escapes, so defaults need the same escaping as values (minus the needless `\"`). */
|
|
20
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;
|
|
21
29
|
supportsMultiColumnCountDistinct(): boolean;
|
|
22
30
|
/** @internal */
|
|
23
31
|
createNativeQueryBuilder(): MySqlNativeQueryBuilder;
|
|
@@ -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',
|
|
@@ -26,6 +33,11 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
26
33
|
quoteDefaultValue(value) {
|
|
27
34
|
return this.quoteValue(value).replaceAll('\\"', '"');
|
|
28
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
|
+
}
|
|
29
41
|
supportsMultiColumnCountDistinct() {
|
|
30
42
|
return true;
|
|
31
43
|
}
|
|
@@ -34,7 +46,7 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
|
|
|
34
46
|
return new MySqlNativeQueryBuilder(this);
|
|
35
47
|
}
|
|
36
48
|
formatIndexHint(indexNames) {
|
|
37
|
-
return `use index(${indexNames.join(', ')})`;
|
|
49
|
+
return `use index(${indexNames.map(name => this.quoteIdentifier(name)).join(', ')})`;
|
|
38
50
|
}
|
|
39
51
|
getDefaultCharset() {
|
|
40
52
|
return 'utf8mb4';
|
|
@@ -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}`);
|
|
@@ -68,6 +68,7 @@ export declare class MySqlSchemaHelper extends SchemaHelper {
|
|
|
68
68
|
protected getChecksSQL(tables: Table[]): string;
|
|
69
69
|
normalizeDefaultValue(defaultValue: string, length: number): string | number;
|
|
70
70
|
protected wrap(val: string | null | undefined, type: Type<unknown>): string | null | undefined;
|
|
71
|
+
normalizeExpression(expr: string): string;
|
|
71
72
|
/** Decodes the backslash escapes of an introspected string literal. */
|
|
72
73
|
unescapeDefault(val: string): string;
|
|
73
74
|
}
|
|
@@ -313,12 +313,14 @@ export class MySqlSchemaHelper extends SchemaHelper {
|
|
|
313
313
|
const ret = {};
|
|
314
314
|
for (const check of allChecks) {
|
|
315
315
|
const key = this.getTableKey(check);
|
|
316
|
+
// string literals come back escaped twice, decoded one level the same as the defaults in `wrap()`
|
|
317
|
+
const expression = check.expression.replace(/\\(.)/gs, '$1');
|
|
316
318
|
ret[key] ??= [];
|
|
317
319
|
ret[key].push({
|
|
318
320
|
name: check.name,
|
|
319
321
|
columnName: check.column_name,
|
|
320
|
-
definition: `check ${
|
|
321
|
-
expression:
|
|
322
|
+
definition: `check ${expression}`,
|
|
323
|
+
expression: expression.replace(/^\((.*)\)$/, '$1'),
|
|
322
324
|
});
|
|
323
325
|
}
|
|
324
326
|
return ret;
|
|
@@ -590,10 +592,8 @@ export class MySqlSchemaHelper extends SchemaHelper {
|
|
|
590
592
|
const enums = await connection.execute(sql, [], 'all', ctx);
|
|
591
593
|
return enums.reduce((o, item) => {
|
|
592
594
|
o[item.table_name] ??= {};
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
.split(',')
|
|
596
|
-
.map((item) => /'(.*)'/.exec(item)[1]);
|
|
595
|
+
// items can hold commas, doubled quotes and backslash escapes
|
|
596
|
+
o[item.table_name][item.column_name] = [...item.column_type.matchAll(/'((?:''|\\.|[^'\\])*)'/g)].map(([, value]) => this.unescapeDefault(value.replaceAll("''", "'")));
|
|
597
597
|
return o;
|
|
598
598
|
}, {});
|
|
599
599
|
}
|
|
@@ -630,6 +630,10 @@ export class MySqlSchemaHelper extends SchemaHelper {
|
|
|
630
630
|
const stringType = type instanceof StringType || type instanceof TextType || type instanceof EnumType;
|
|
631
631
|
return stringType ? this.platform.quoteDefaultValue(val) : val;
|
|
632
632
|
}
|
|
633
|
+
normalizeExpression(expr) {
|
|
634
|
+
// `\'` and `''` are the same quote inside a literal
|
|
635
|
+
return expr.replace(/\\(.)/gs, (escape, char) => (char === "'" ? "''" : escape));
|
|
636
|
+
}
|
|
633
637
|
/** Decodes the backslash escapes of an introspected string literal. */
|
|
634
638
|
unescapeDefault(val) {
|
|
635
639
|
const sqlEscapes = { 0: '\0', b: '\b', n: '\n', r: '\r', t: '\t', Z: '\x1a' };
|
|
@@ -181,7 +181,8 @@ export class OracleNativeQueryBuilder extends NativeQueryBuilder {
|
|
|
181
181
|
if (!clause.ignore) {
|
|
182
182
|
/* v8 ignore next: merge type branch */
|
|
183
183
|
if (!clause.merge || Array.isArray(clause.merge)) {
|
|
184
|
-
const
|
|
184
|
+
const merge = clause.merge?.length ? clause.merge : keys;
|
|
185
|
+
const mergeParts = merge
|
|
185
186
|
.filter(field => !Array.isArray(clause.fields) || !clause.fields.includes(field))
|
|
186
187
|
.filter((field) => keys.includes(field)) // only reference columns present in the source data
|
|
187
188
|
.map((column) => `${this.quote(column)} = tsource.${this.quote(column)}`);
|
|
@@ -193,7 +194,7 @@ export class OracleNativeQueryBuilder extends NativeQueryBuilder {
|
|
|
193
194
|
this.params.push(...clause.where.params);
|
|
194
195
|
}
|
|
195
196
|
this.parts.push('then update set');
|
|
196
|
-
this.parts.push(
|
|
197
|
+
this.parts.push(this.joinVersionMerge(clause, mergeParts, merge));
|
|
197
198
|
}
|
|
198
199
|
} /* v8 ignore start: object-form merge branch */
|
|
199
200
|
else if (typeof clause.merge === 'object') {
|
|
@@ -207,7 +208,7 @@ export class OracleNativeQueryBuilder extends NativeQueryBuilder {
|
|
|
207
208
|
this.params.push(value);
|
|
208
209
|
return `${this.getTableName()}.${this.quote(key)} = ?`;
|
|
209
210
|
});
|
|
210
|
-
this.parts.push(
|
|
211
|
+
this.parts.push(this.joinVersionMerge(clause, parts, Object.keys(clause.merge)));
|
|
211
212
|
}
|
|
212
213
|
/* v8 ignore stop */
|
|
213
214
|
}
|
|
@@ -78,6 +78,7 @@ export declare class BasePostgreSqlPlatform extends AbstractSqlPlatform {
|
|
|
78
78
|
/**
|
|
79
79
|
* Ported from PostgreSQL 9.2.4 source code (`src/interfaces/libpq/fe-exec.c`),
|
|
80
80
|
* matching `pg.Client.prototype.escapeLiteral` so we don't need a `pg` dep here.
|
|
81
|
+
* Avoids per-character concatenation (builds a rope, slow on large values) and regexps (fixed cost on tiny values).
|
|
81
82
|
*/
|
|
82
83
|
private escapeLiteral;
|
|
83
84
|
getVarcharTypeDeclarationSQL(column: {
|
|
@@ -273,28 +273,22 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
|
|
|
273
273
|
/**
|
|
274
274
|
* Ported from PostgreSQL 9.2.4 source code (`src/interfaces/libpq/fe-exec.c`),
|
|
275
275
|
* matching `pg.Client.prototype.escapeLiteral` so we don't need a `pg` dep here.
|
|
276
|
+
* Avoids per-character concatenation (builds a rope, slow on large values) and regexps (fixed cost on tiny values).
|
|
276
277
|
*/
|
|
277
278
|
escapeLiteral(str) {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
if (c === `'`) {
|
|
283
|
-
escaped += c + c;
|
|
284
|
-
}
|
|
285
|
-
else if (c === '\\') {
|
|
286
|
-
escaped += c + c;
|
|
287
|
-
hasBackslash = true;
|
|
288
|
-
}
|
|
289
|
-
else {
|
|
290
|
-
escaped += c;
|
|
291
|
-
}
|
|
279
|
+
const hasBackslash = str.includes('\\');
|
|
280
|
+
const hasQuote = str.includes(`'`);
|
|
281
|
+
if (!hasBackslash && !hasQuote) {
|
|
282
|
+
return `'${str}'`;
|
|
292
283
|
}
|
|
293
|
-
escaped
|
|
284
|
+
let escaped = str;
|
|
294
285
|
if (hasBackslash) {
|
|
295
|
-
escaped =
|
|
286
|
+
escaped = escaped.replaceAll('\\', '\\\\');
|
|
287
|
+
}
|
|
288
|
+
if (hasQuote) {
|
|
289
|
+
escaped = escaped.replaceAll(`'`, `''`);
|
|
296
290
|
}
|
|
297
|
-
return escaped
|
|
291
|
+
return hasBackslash ? ` E'${escaped}'` : `'${escaped}'`;
|
|
298
292
|
}
|
|
299
293
|
getVarcharTypeDeclarationSQL(column) {
|
|
300
294
|
if (column.length === -1) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DeferMode, EnumType, Type, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { DecimalType, DeferMode, DoubleType, EnumType, FloatType, Type, Utils, } from '@mikro-orm/core';
|
|
2
2
|
import { SchemaHelper, stripStatementNewlines } from '../../schema/SchemaHelper.js';
|
|
3
3
|
import { normalizePartitionBound, normalizePartitionDefinition } from '../../schema/partitioning.js';
|
|
4
4
|
/** PostGIS system views that should be automatically ignored */
|
|
@@ -255,7 +255,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
255
255
|
const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
|
|
256
256
|
table.collation = dbCollation;
|
|
257
257
|
const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
|
|
258
|
-
const enums = this.getEnumDefinitions(checks[key] ?? []);
|
|
258
|
+
const enums = this.getEnumDefinitions(checks[key] ?? [], columns[key] ?? []);
|
|
259
259
|
if (columns[key]) {
|
|
260
260
|
table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
|
|
261
261
|
}
|
|
@@ -1072,7 +1072,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1072
1072
|
}
|
|
1073
1073
|
return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
|
|
1074
1074
|
}
|
|
1075
|
-
getEnumDefinitions(checks) {
|
|
1075
|
+
getEnumDefinitions(checks, columns) {
|
|
1076
1076
|
return checks.reduce((o, item) => {
|
|
1077
1077
|
// check constraints are defined as one of:
|
|
1078
1078
|
// `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
|
|
@@ -1084,13 +1084,20 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1084
1084
|
// the single-value form must compare against a quoted literal (`= 'a'::text`); anything else
|
|
1085
1085
|
// (e.g. a JSON `->>` extraction like `name = data->>'name'`) is not an enum constraint
|
|
1086
1086
|
const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = ('(?:[^']|'')*'::[\w ]+)\)/i);
|
|
1087
|
-
|
|
1087
|
+
// enums with string items are emulated with a check, a check like `delta in (1, -1)` on a number is a plain one
|
|
1088
|
+
const column = columns.find(c => c.name === item.columnName);
|
|
1089
|
+
const numeric = column != null &&
|
|
1090
|
+
(this.platform.isNumericColumn(column.mappedType) ||
|
|
1091
|
+
[DecimalType, FloatType, DoubleType].some(t => column.mappedType instanceof t));
|
|
1092
|
+
if (item.columnName && m1 && m2 && !numeric) {
|
|
1088
1093
|
/* v8 ignore next */
|
|
1089
1094
|
const parts = m2[1].match(/('(?:[^']|'')*'::\w[\w ]*)/g) ?? m2[1].split(',');
|
|
1090
1095
|
let items = parts.map((item) => /^\(?'((?:[^']|'')*)'/.exec(item.trim())?.[1]?.replace(/''/g, "'"));
|
|
1091
1096
|
items = items.filter(item => item !== undefined);
|
|
1092
1097
|
if (items.length > 0) {
|
|
1093
1098
|
o[item.columnName] = items;
|
|
1099
|
+
// kept to compare with a plain check of the same values, e.g. `kind = 'manual'` is stored like a single item enum
|
|
1100
|
+
item.introspectedExpression = item.expression;
|
|
1094
1101
|
item.expression = this.platform.getEnumCheckConstraintExpression(item.columnName, items);
|
|
1095
1102
|
item.definition = `check (${item.expression})`;
|
|
1096
1103
|
}
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
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.22",
|
|
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",
|
|
@@ -50,10 +50,10 @@
|
|
|
50
50
|
"kysely": "0.29.8"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@mikro-orm/core": "^7.2.
|
|
53
|
+
"@mikro-orm/core": "^7.2.9"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@mikro-orm/core": "7.3.0-dev.
|
|
56
|
+
"@mikro-orm/core": "7.3.0-dev.22"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">= 22.17.0"
|
|
@@ -66,9 +66,14 @@ interface OnConflictClause {
|
|
|
66
66
|
sql: string;
|
|
67
67
|
params: unknown[];
|
|
68
68
|
};
|
|
69
|
+
version?: {
|
|
70
|
+
field: string;
|
|
71
|
+
timestamp?: string;
|
|
72
|
+
};
|
|
69
73
|
}
|
|
70
74
|
/** @internal */
|
|
71
75
|
export declare class NativeQueryBuilder implements Subquery {
|
|
76
|
+
#private;
|
|
72
77
|
protected readonly platform: AbstractSqlPlatform;
|
|
73
78
|
readonly __subquery: true;
|
|
74
79
|
protected type?: QueryType;
|
|
@@ -103,6 +108,7 @@ export declare class NativeQueryBuilder implements Subquery {
|
|
|
103
108
|
};
|
|
104
109
|
protected addLockClause(): void;
|
|
105
110
|
protected addOnConflictClause(): void;
|
|
111
|
+
protected joinVersionMerge(clause: OnConflictClause, parts: string[], merged: unknown[]): string;
|
|
106
112
|
protected combineParts(): {
|
|
107
113
|
sql: string;
|
|
108
114
|
params: unknown[];
|
|
@@ -7,6 +7,8 @@ export class NativeQueryBuilder {
|
|
|
7
7
|
parts = [];
|
|
8
8
|
params = [];
|
|
9
9
|
options = {};
|
|
10
|
+
/** the table name or alias usable as a column qualifier (without the alias definition or index hint) */
|
|
11
|
+
#tableQualifier;
|
|
10
12
|
constructor(platform) {
|
|
11
13
|
this.platform = platform;
|
|
12
14
|
}
|
|
@@ -33,8 +35,14 @@ export class NativeQueryBuilder {
|
|
|
33
35
|
const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
|
|
34
36
|
const alias = options?.alias ? `${asKeyword}${this.platform.quoteIdentifier(options.alias)}` : '';
|
|
35
37
|
const schema = options?.schema && options.schema !== this.platform.getDefaultSchemaName() ? `${options.schema}.` : '';
|
|
38
|
+
this.#tableQualifier = options?.alias
|
|
39
|
+
? this.platform.quoteIdentifier(options.alias)
|
|
40
|
+
: this.quote(schema + tableName);
|
|
36
41
|
tableName = this.quote(schema + tableName) + alias;
|
|
37
42
|
}
|
|
43
|
+
else {
|
|
44
|
+
this.#tableQualifier = undefined;
|
|
45
|
+
}
|
|
38
46
|
this.options.tableName = tableName;
|
|
39
47
|
this.options.indexHint = options?.indexHint;
|
|
40
48
|
return this;
|
|
@@ -174,19 +182,19 @@ export class NativeQueryBuilder {
|
|
|
174
182
|
this.params.push(clause.merge[field]);
|
|
175
183
|
return `${this.quote(field)} = ?`;
|
|
176
184
|
});
|
|
177
|
-
this.parts.push(
|
|
185
|
+
this.parts.push(this.joinVersionMerge(clause, fields, Object.keys(clause.merge)));
|
|
178
186
|
}
|
|
179
187
|
else if (clause.merge) {
|
|
180
188
|
this.parts.push('do update set');
|
|
181
189
|
if (clause.merge.length) {
|
|
182
190
|
const fields = clause.merge.map(field => `${this.quote(field)} = excluded.${this.quote(field)}`);
|
|
183
|
-
this.parts.push(
|
|
191
|
+
this.parts.push(this.joinVersionMerge(clause, fields, clause.merge));
|
|
184
192
|
}
|
|
185
193
|
else {
|
|
186
194
|
const dataAsArray = Utils.asArray(this.options.data);
|
|
187
195
|
const keys = Object.keys(dataAsArray[0]);
|
|
188
196
|
const fields = keys.map(field => `${this.quote(field)} = excluded.${this.quote(field)}`);
|
|
189
|
-
this.parts.push(
|
|
197
|
+
this.parts.push(this.joinVersionMerge(clause, fields, keys));
|
|
190
198
|
}
|
|
191
199
|
}
|
|
192
200
|
if (clause.where) {
|
|
@@ -194,6 +202,17 @@ export class NativeQueryBuilder {
|
|
|
194
202
|
this.params.push(...clause.where.params);
|
|
195
203
|
}
|
|
196
204
|
}
|
|
205
|
+
joinVersionMerge(clause, parts, merged) {
|
|
206
|
+
if (clause.version && !merged.includes(clause.version.field)) {
|
|
207
|
+
const field = this.quote(clause.version.field);
|
|
208
|
+
// the existing row's version, as the `version + 1` of an update (a bare column is ambiguous with `excluded`)
|
|
209
|
+
parts = [
|
|
210
|
+
...parts,
|
|
211
|
+
`${field} = ${clause.version.timestamp ?? `${this.#tableQualifier ?? this.getTableName()}.${field} + 1`}`,
|
|
212
|
+
];
|
|
213
|
+
}
|
|
214
|
+
return parts.join(', ');
|
|
215
|
+
}
|
|
197
216
|
combineParts() {
|
|
198
217
|
let sql = this.parts.join(' ');
|
|
199
218
|
if (this.options.wrap) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, QueryHelper, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, QueryHelper, raw, RawQueryFragment, ReferenceKind, Utils, ValidationError, } from '@mikro-orm/core';
|
|
2
2
|
import { CriteriaNode } from './CriteriaNode.js';
|
|
3
3
|
import { JoinType, QueryType } from './enums.js';
|
|
4
4
|
const COLLECTION_OPERATORS = ['$some', '$none', '$every', '$size', '$all'];
|
|
@@ -7,6 +7,9 @@ const COLLECTION_OPERATORS = ['$some', '$none', '$every', '$size', '$all'];
|
|
|
7
7
|
*/
|
|
8
8
|
export class ObjectCriteriaNode extends CriteriaNode {
|
|
9
9
|
process(qb, options) {
|
|
10
|
+
if (options?.type === 'orderBy' && this.prop?.kind === ReferenceKind.SCALAR) {
|
|
11
|
+
throw new ValidationError(`Invalid order direction for ${Utils.className(this.entityName)}.${this.prop.name}`);
|
|
12
|
+
}
|
|
10
13
|
const targets = this.isPolymorphicBranch() ? QueryHelper.findTargetMetas(this.prop, this.key) : [];
|
|
11
14
|
if (options?.type === 'orderBy' && targets.length > 1) {
|
|
12
15
|
return this.processPolymorphicOrderBy(qb, targets, options);
|
package/query/QueryBuilder.d.ts
CHANGED
|
@@ -803,6 +803,11 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
|
|
|
803
803
|
* Use `method` to specify what kind of result you want to get (array/single/meta).
|
|
804
804
|
*/
|
|
805
805
|
execute<U = any>(method?: 'all' | 'get' | 'run', options?: ExecuteOptions | boolean): Promise<U>;
|
|
806
|
+
/**
|
|
807
|
+
* An update or delete with auto-joined conditions stays a select until `finalize()` wraps it,
|
|
808
|
+
* so read the same flags `wrapModifySubQuery()` uses.
|
|
809
|
+
*/
|
|
810
|
+
private getExecuteType;
|
|
806
811
|
private getConnection;
|
|
807
812
|
/**
|
|
808
813
|
* Executes the query and returns an async iterable (async generator) that yields results one by one.
|
|
@@ -975,8 +980,6 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
|
|
|
975
980
|
* Tier 3: Derive from target entity metadata (all cloneable columns), auto-populate source select
|
|
976
981
|
*/
|
|
977
982
|
private resolveInsertFromColumns;
|
|
978
|
-
/** Returns properties that are safe to clone (persistable, non-PK, non-generated). */
|
|
979
|
-
private getCloneableProps;
|
|
980
983
|
private applyDiscriminatorCondition;
|
|
981
984
|
/**
|
|
982
985
|
* Ensures TPT joins are applied. Can be called early before finalize() to populate
|
package/query/QueryBuilder.js
CHANGED
|
@@ -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({
|
|
@@ -1057,12 +1067,13 @@ export class QueryBuilder {
|
|
|
1057
1067
|
options = typeof options === 'boolean' ? { mapResults: options } : (options ?? {});
|
|
1058
1068
|
options.mergeResults ??= true;
|
|
1059
1069
|
options.mapResults ??= true;
|
|
1060
|
-
const
|
|
1070
|
+
const type = this.getExecuteType();
|
|
1071
|
+
const isRunType = [QueryType.INSERT, QueryType.UPDATE, QueryType.DELETE, QueryType.TRUNCATE].includes(type);
|
|
1061
1072
|
method ??= isRunType ? 'run' : 'all';
|
|
1062
1073
|
if (!this.connectionType && (isRunType || this.context)) {
|
|
1063
1074
|
this.connectionType = 'write';
|
|
1064
1075
|
}
|
|
1065
|
-
if (!this.#state.finalized && method === 'get' &&
|
|
1076
|
+
if (!this.#state.finalized && method === 'get' && type === QueryType.SELECT) {
|
|
1066
1077
|
this.limit(1);
|
|
1067
1078
|
}
|
|
1068
1079
|
const query = this.toQuery();
|
|
@@ -1120,6 +1131,19 @@ export class QueryBuilder {
|
|
|
1120
1131
|
await this.em?.storeCache(this.#state.cache, cached, mapped);
|
|
1121
1132
|
return mapped;
|
|
1122
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
|
+
}
|
|
1123
1147
|
getConnection() {
|
|
1124
1148
|
const write = !this.platform.getConfig().get('preferReadReplicas');
|
|
1125
1149
|
const type = this.connectionType || (write ? 'write' : 'read');
|
|
@@ -1238,7 +1262,6 @@ export class QueryBuilder {
|
|
|
1238
1262
|
const entities = [];
|
|
1239
1263
|
for (const row of res) {
|
|
1240
1264
|
const entity = this.mapResult(row);
|
|
1241
|
-
this.propagatePopulateHint(entity, this.#state.populate);
|
|
1242
1265
|
entities.push(entity);
|
|
1243
1266
|
if (limit != null && --limit === 0) {
|
|
1244
1267
|
break;
|
|
@@ -1276,7 +1299,9 @@ export class QueryBuilder {
|
|
|
1276
1299
|
* Executes the query, returning both array of results and total count query (without offset and limit).
|
|
1277
1300
|
*/
|
|
1278
1301
|
async getResultAndCount() {
|
|
1279
|
-
|
|
1302
|
+
// `getCount()` clones by itself, except when the type is not set yet
|
|
1303
|
+
const countQb = this.#state.type === undefined ? this.clone() : this;
|
|
1304
|
+
return [await this.clone().getResultList(), await countQb.getCount()];
|
|
1280
1305
|
}
|
|
1281
1306
|
as(aliasOrTargetEntity, alias) {
|
|
1282
1307
|
const qb = this.getNativeQuery();
|
|
@@ -1860,7 +1885,7 @@ export class QueryBuilder {
|
|
|
1860
1885
|
});
|
|
1861
1886
|
}
|
|
1862
1887
|
// Tier 3: derive from metadata — all cloneable columns
|
|
1863
|
-
const cloneableProps = this.getCloneableProps(meta);
|
|
1888
|
+
const cloneableProps = this.driver.getCloneableProps(meta);
|
|
1864
1889
|
const selectFields = [];
|
|
1865
1890
|
const columns = [];
|
|
1866
1891
|
for (const prop of cloneableProps) {
|
|
@@ -1875,27 +1900,6 @@ export class QueryBuilder {
|
|
|
1875
1900
|
}
|
|
1876
1901
|
return columns;
|
|
1877
1902
|
}
|
|
1878
|
-
/** Returns properties that are safe to clone (persistable, non-PK, non-generated). */
|
|
1879
|
-
getCloneableProps(meta) {
|
|
1880
|
-
return meta.props.filter(prop => {
|
|
1881
|
-
if (prop.persist === false) {
|
|
1882
|
-
return false;
|
|
1883
|
-
}
|
|
1884
|
-
if (prop.primary) {
|
|
1885
|
-
return false;
|
|
1886
|
-
}
|
|
1887
|
-
if (!prop.fieldNames?.length) {
|
|
1888
|
-
return false;
|
|
1889
|
-
}
|
|
1890
|
-
if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
|
|
1891
|
-
return false;
|
|
1892
|
-
}
|
|
1893
|
-
if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) {
|
|
1894
|
-
return false;
|
|
1895
|
-
}
|
|
1896
|
-
return true;
|
|
1897
|
-
});
|
|
1898
|
-
}
|
|
1899
1903
|
applyDiscriminatorCondition() {
|
|
1900
1904
|
const meta = this.mainAlias.meta;
|
|
1901
1905
|
if (meta.root.inheritanceType !== 'sti' || !meta.discriminatorValue) {
|
|
@@ -2017,12 +2021,13 @@ export class QueryBuilder {
|
|
|
2017
2021
|
if (meta && (this.#state.fields?.includes('*') || this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`))) {
|
|
2018
2022
|
const schema = this.getSchema(this.mainAlias);
|
|
2019
2023
|
// Per-column entries are unquoted (meant for `quote`), while `toString()` yields the quoted alias for plain template literals
|
|
2020
|
-
// For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
|
|
2021
2024
|
const quotedMainAlias = this.platform.quoteIdentifier(this.mainAlias.aliasName).toString();
|
|
2022
|
-
|
|
2025
|
+
let columns;
|
|
2023
2026
|
meta.props
|
|
2024
2027
|
.filter(prop => prop.formula && (!prop.lazy || this.#state.flags.has(QueryFlag.INCLUDE_LAZY_FORMULAS)))
|
|
2025
2028
|
.map(prop => {
|
|
2029
|
+
// For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
|
|
2030
|
+
columns ??= meta.createColumnMappingObject(p => this.helper.getTPTAliasForProperty(p.name, this.mainAlias.aliasName), quotedMainAlias);
|
|
2026
2031
|
const aliased = this.platform.quoteIdentifier(prop.fieldNames[0]);
|
|
2027
2032
|
const table = this.helper.createFormulaTable(quotedMainAlias, meta, schema);
|
|
2028
2033
|
return `${this.driver.evaluateFormula(prop.formula, columns, table)} as ${aliased}`;
|
|
@@ -2354,8 +2359,12 @@ export class QueryBuilder {
|
|
|
2354
2359
|
if (this.#state.orderBy.length > 0) {
|
|
2355
2360
|
const orderBy = [];
|
|
2356
2361
|
for (const orderMap of this.#state.orderBy) {
|
|
2357
|
-
|
|
2358
|
-
|
|
2362
|
+
// a composite FK key holds several columns, each needs its own `min()`
|
|
2363
|
+
const entries = Utils.getObjectQueryKeys(orderMap).flatMap(key => {
|
|
2364
|
+
const fields = RawQueryFragment.isKnownFragmentSymbol(key) ? [key] : Utils.splitPrimaryKeys(key);
|
|
2365
|
+
return fields.map(field => [field, orderMap[key]]);
|
|
2366
|
+
});
|
|
2367
|
+
for (const [field, direction] of entries) {
|
|
2359
2368
|
if (RawQueryFragment.isKnownFragmentSymbol(field)) {
|
|
2360
2369
|
orderBy.push({ [field]: direction });
|
|
2361
2370
|
continue;
|
|
@@ -408,22 +408,33 @@ export class QueryBuilderHelper {
|
|
|
408
408
|
return `%${value}%`;
|
|
409
409
|
}
|
|
410
410
|
appendOnConflictClause(type, onConflict, qb) {
|
|
411
|
+
const meta = this.#metadata.find(this.#entityName);
|
|
411
412
|
onConflict.forEach(item => {
|
|
412
413
|
const { fields, ignore } = item;
|
|
413
414
|
const sub = qb.onConflict({ fields, ignore });
|
|
414
415
|
Utils.runIfNotEmpty(() => {
|
|
415
416
|
let mergeParam = item.merge;
|
|
416
417
|
if (Utils.isObject(item.merge)) {
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
const k = this.mapper(key, type);
|
|
420
|
-
mergeParam[k] = item.merge[key];
|
|
421
|
-
});
|
|
418
|
+
// same mapping as the insert data, so composite FK and polymorphic values are split across their columns
|
|
419
|
+
mergeParam = this.processData(item.merge, false);
|
|
422
420
|
}
|
|
423
421
|
if (Array.isArray(item.merge)) {
|
|
424
|
-
mergeParam = item.merge.
|
|
422
|
+
mergeParam = item.merge.flatMap(key => {
|
|
423
|
+
const [a, f] = typeof key === 'string' ? this.splitField(key) : [];
|
|
424
|
+
const prop = f ? this.getProperty(f, a) : undefined;
|
|
425
|
+
// a property name merges all columns of a composite FK, a column name merges just that column
|
|
426
|
+
return prop?.targetMeta && prop.fieldNames.length > 1 && !prop.fieldNames.includes(f)
|
|
427
|
+
? (prop.ownColumns ?? prop.fieldNames)
|
|
428
|
+
: [this.mapper(key, type)];
|
|
429
|
+
});
|
|
425
430
|
}
|
|
426
431
|
sub.merge = mergeParam ?? [];
|
|
432
|
+
// a merged row is updated, so its version is bumped as `updateVersionProperty()` does
|
|
433
|
+
if (meta?.ownsVersionProperty()) {
|
|
434
|
+
const prop = meta.properties[meta.versionProperty];
|
|
435
|
+
const timestamp = prop.runtimeType === 'Date' ? this.#platform.getCurrentTimestampSQL(prop.length) : undefined;
|
|
436
|
+
sub.version = { field: prop.fieldNames[0], timestamp };
|
|
437
|
+
}
|
|
427
438
|
if (item.where) {
|
|
428
439
|
sub.where = this._appendQueryCondition(type, item.where);
|
|
429
440
|
}
|
|
@@ -557,15 +568,17 @@ export class QueryBuilderHelper {
|
|
|
557
568
|
['$in', '$nin'].includes(op) &&
|
|
558
569
|
Array.isArray(value[op]) &&
|
|
559
570
|
value[op].every((v) => Array.isArray(v));
|
|
560
|
-
|
|
571
|
+
// an empty list falls through to the generic `1 = 0` / `1 = 1` handling below
|
|
572
|
+
if (fields.length > 1 && Array.isArray(value[op]) && value[op].length > 0) {
|
|
561
573
|
const singleTuple = !value[op].every((v) => Array.isArray(v));
|
|
562
574
|
if (!this.#platform.allowsComparingTuples()) {
|
|
563
575
|
const mapped = fields.map(f => this.mapper(f, type));
|
|
564
|
-
if (op === '$in') {
|
|
576
|
+
if (op === '$in' || op === '$nin') {
|
|
565
577
|
const conds = value[op].map(() => {
|
|
566
578
|
return `(${mapped.map(field => `${this.#platform.quoteIdentifier(field)} = ?`).join(' and ')})`;
|
|
567
579
|
});
|
|
568
|
-
|
|
580
|
+
const sql = `(${conds.join(' or ')})`;
|
|
581
|
+
parts.push(op === '$in' ? sql : `not ${sql}`);
|
|
569
582
|
params.push(...Utils.flatten(value[op]));
|
|
570
583
|
return { sql: parts.join(' and '), params };
|
|
571
584
|
}
|
|
@@ -754,33 +767,29 @@ export class QueryBuilderHelper {
|
|
|
754
767
|
if (isRaw(colPart)) {
|
|
755
768
|
colPart = this.#platform.formatQuery(colPart.sql, colPart.params);
|
|
756
769
|
}
|
|
757
|
-
|
|
758
|
-
order.forEach(part => ret.push(...this.getQueryOrderFromObject(type, part, populate, collation)));
|
|
759
|
-
}
|
|
760
|
-
else {
|
|
761
|
-
ret.push(...this.#platform.getOrderByExpression(colPart, order, collation));
|
|
762
|
-
}
|
|
770
|
+
ret.push(...this.#platform.getOrderByExpression(colPart, order, collation));
|
|
763
771
|
}
|
|
764
772
|
}
|
|
765
773
|
return ret;
|
|
766
774
|
}
|
|
767
775
|
splitField(field, greedyAlias = false) {
|
|
768
|
-
const
|
|
769
|
-
const
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
if (
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
776
|
+
const lastDot = field.lastIndexOf('.');
|
|
777
|
+
const colon = field.indexOf(':', lastDot + 1);
|
|
778
|
+
let end = field.length;
|
|
779
|
+
let ref;
|
|
780
|
+
// only the segment between the first and second colon of the last path part is the ref
|
|
781
|
+
if (colon !== -1) {
|
|
782
|
+
const nextColon = field.indexOf(':', colon + 1);
|
|
783
|
+
ref = field.substring(colon + 1, nextColon === -1 ? end : nextColon);
|
|
784
|
+
if (ref) {
|
|
785
|
+
end = colon;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
if (lastDot === -1) {
|
|
789
|
+
return [this.#alias, field.substring(0, end), ref];
|
|
790
|
+
}
|
|
791
|
+
const aliasEnd = greedyAlias ? lastDot : field.indexOf('.');
|
|
792
|
+
return [field.substring(0, aliasEnd), field.substring(aliasEnd + 1, end), ref];
|
|
784
793
|
}
|
|
785
794
|
getLockSQL(qb, lockMode, lockTables = [], joinsMap) {
|
|
786
795
|
const meta = this.#metadata.find(this.#entityName);
|
|
@@ -1109,6 +1118,11 @@ export class QueryBuilderHelper {
|
|
|
1109
1118
|
const meta = this.#metadata.get(this.#entityName);
|
|
1110
1119
|
const tableName = meta.tableName;
|
|
1111
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
|
+
}
|
|
1112
1126
|
const mapped = this.mapper(key, QueryType.UPSERT);
|
|
1113
1127
|
Utils.renameKey(cond, key, tableName + '.' + mapped);
|
|
1114
1128
|
}
|
package/schema/DatabaseTable.js
CHANGED
|
@@ -151,7 +151,9 @@ export class DatabaseTable {
|
|
|
151
151
|
precision: prop.precision,
|
|
152
152
|
scale: prop.scale,
|
|
153
153
|
default: prop.defaultRaw,
|
|
154
|
-
enumItems: prop.nativeEnumName || prop.items?.every(i => typeof i === 'string')
|
|
154
|
+
enumItems: prop.nativeEnumName || ((prop.enum || prop.array) && prop.items?.every(i => typeof i === 'string'))
|
|
155
|
+
? prop.items
|
|
156
|
+
: undefined,
|
|
155
157
|
comment: prop.comment,
|
|
156
158
|
collation: prop.collation,
|
|
157
159
|
extra: prop.extra,
|
|
@@ -1205,6 +1207,8 @@ export class DatabaseTable {
|
|
|
1205
1207
|
// collapse mysql's `""` for unset comments to `null` so both sources agree. drop entirely on
|
|
1206
1208
|
// platforms that can't read comments back (sqlite), where keeping it would flip the snapshot
|
|
1207
1209
|
comment: supportsComments ? this.comment || null : null,
|
|
1210
|
+
// JSON.stringify drops it when unset, so snapshots of unpartitioned tables stay unchanged
|
|
1211
|
+
partitioning: this.partitioning,
|
|
1208
1212
|
};
|
|
1209
1213
|
// emit RLS state only when set, so snapshots of non-RLS tables stay byte-for-byte unchanged
|
|
1210
1214
|
if (sortedPolicies.length > 0) {
|
|
@@ -92,6 +92,7 @@ export declare class SchemaComparator {
|
|
|
92
92
|
private diffPolicy;
|
|
93
93
|
parseJsonDefault(defaultValue?: string | null): Dictionary | string | null;
|
|
94
94
|
private parseDecimalDefault;
|
|
95
|
+
private parseBigIntDefault;
|
|
95
96
|
hasSameDefaultValue(from: Column, to: Column): boolean;
|
|
96
97
|
private mapColumnToProperty;
|
|
97
98
|
private log;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ArrayType, BooleanType, DateTimeType, DecimalType, inspect, JsonType, parseJsonSafe, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { ArrayType, BigIntType, BooleanType, DateTimeType, DecimalType, inspect, JsonType, parseJsonSafe, Utils, } from '@mikro-orm/core';
|
|
2
2
|
import { DatabaseTable } from './DatabaseTable.js';
|
|
3
3
|
import { diffPartitioning } from './partitioning.js';
|
|
4
4
|
/**
|
|
@@ -483,6 +483,12 @@ export class SchemaComparator {
|
|
|
483
483
|
if (!this.diffExpression(check.expression, toTableCheck.expression)) {
|
|
484
484
|
continue;
|
|
485
485
|
}
|
|
486
|
+
// a check read as the one of an enum can be a plain check of the same values, e.g. `kind = 'manual'`
|
|
487
|
+
const introspected = check.introspectedExpression ?? toTableCheck.introspectedExpression;
|
|
488
|
+
const declared = check.introspectedExpression ? toTableCheck.expression : check.expression;
|
|
489
|
+
if (introspected && !this.diffExpression(introspected, declared)) {
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
486
492
|
// only auto-generated enum checks, a user check tagged with an enum column must be diffed by expression
|
|
487
493
|
if (fromColumn?.enumItems &&
|
|
488
494
|
toColumn?.enumItems &&
|
|
@@ -927,12 +933,13 @@ export class SchemaComparator {
|
|
|
927
933
|
// Protect dots inside string literals before the quote strip below, or the alias-prefix normalization
|
|
928
934
|
// would mangle literal contents — `current_setting('app.tenant')` and `current_setting('req.tenant')`
|
|
929
935
|
// must not both collapse to `current_settingtenant`
|
|
930
|
-
|
|
936
|
+
// numbers are left alone, postgres quotes the negative ones (`'-1.5'::numeric`)
|
|
937
|
+
.replace(/'([^']*)'/g, (m, inner) => /^-?\d+(\.\d+)?$/.test(inner) ? m : `'${inner.replaceAll('.', '\u0000')}'`)
|
|
931
938
|
// Remove quotes first so we can process identifiers
|
|
932
939
|
.replace(/['"`]/g, '')
|
|
933
940
|
// MySQL adds table/alias prefixes to columns (e.g., a.name or table_name.column vs just column)
|
|
934
941
|
// Strip these prefixes - match word.word patterns and keep only the last part
|
|
935
|
-
.replace(/\b\w+\.(\w+)/g, '$1')
|
|
942
|
+
.replace(/\b(?!\d)\w+\.(\w+)/g, '$1')
|
|
936
943
|
// PostgreSQL rewrites `x [not] between a and b` to `x >= a and x <= b` (`x < a or x > b`), cast targets are skipped
|
|
937
944
|
.replace(/(?<!::\s*)\b(?!not\b)(\w+)\s+(not\s+)?between\s+(\S+)\s+and\s+(\S+)/gi, (_, x, not, a, b) => not ? `${x} < ${a} or ${x} > ${b}` : `${x} >= ${a} and ${x} <= ${b}`)
|
|
938
945
|
// Normalize JOIN syntax: inner join -> join (equivalent in SQL)
|
|
@@ -1100,6 +1107,10 @@ export class SchemaComparator {
|
|
|
1100
1107
|
const value = +('' + defaultValue).replace(/^'(.+)'$/, '$1');
|
|
1101
1108
|
return Number.isFinite(value) ? value : null;
|
|
1102
1109
|
}
|
|
1110
|
+
parseBigIntDefault(defaultValue) {
|
|
1111
|
+
const value = ('' + defaultValue).replace(/^'(.+)'$/, '$1');
|
|
1112
|
+
return /^-?\d+$/.test(value) ? BigInt(value) : null;
|
|
1113
|
+
}
|
|
1103
1114
|
hasSameDefaultValue(from, to) {
|
|
1104
1115
|
if (from.default == null ||
|
|
1105
1116
|
from.default.toString().toLowerCase() === 'null' ||
|
|
@@ -1135,6 +1146,14 @@ export class SchemaComparator {
|
|
|
1135
1146
|
this.#platform.formatDecimal(defaultValueTo, to.scale));
|
|
1136
1147
|
}
|
|
1137
1148
|
}
|
|
1149
|
+
// metadata quotes bigint defaults (`'0'`) while mysql reports them bare
|
|
1150
|
+
if (to.mappedType instanceof BigIntType) {
|
|
1151
|
+
const defaultValueFrom = this.parseBigIntDefault(from.default);
|
|
1152
|
+
const defaultValueTo = this.parseBigIntDefault(to.default);
|
|
1153
|
+
if (defaultValueFrom != null && defaultValueTo != null) {
|
|
1154
|
+
return defaultValueFrom === defaultValueTo;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1138
1157
|
if (from.default && to.default) {
|
|
1139
1158
|
return from.default.toString().toLowerCase() === to.default.toString().toLowerCase();
|
|
1140
1159
|
}
|
package/typings.d.ts
CHANGED
|
@@ -115,6 +115,8 @@ export interface CheckDef<T = unknown> {
|
|
|
115
115
|
expression: string | CheckCallback<T>;
|
|
116
116
|
definition?: string;
|
|
117
117
|
columnName?: string;
|
|
118
|
+
/** @internal the expression as introspected, before it was normalized as the check of an enum */
|
|
119
|
+
introspectedExpression?: string;
|
|
118
120
|
}
|
|
119
121
|
/** Resolved row level security policy for schema operations (all callbacks resolved to strings). */
|
|
120
122
|
export interface SqlPolicyDef {
|