@mikro-orm/sql 7.2.9-dev.9 → 7.2.10-dev.0
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/mysql/MySqlSchemaHelper.d.ts +1 -0
- package/dialects/mysql/MySqlSchemaHelper.js +8 -2
- package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +1 -0
- package/dialects/postgresql/BasePostgreSqlPlatform.js +11 -17
- package/dialects/postgresql/PostgreSqlSchemaHelper.js +11 -4
- package/package.json +3 -3
- package/query/ObjectCriteriaNode.js +4 -1
- package/query/QueryBuilder.d.ts +0 -2
- package/query/QueryBuilder.js +7 -26
- package/query/QueryBuilderHelper.js +28 -28
- package/schema/DatabaseTable.js +3 -1
- package/schema/SchemaComparator.js +9 -2
- 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
|
}
|
|
@@ -62,6 +62,7 @@ export declare class MySqlSchemaHelper extends SchemaHelper {
|
|
|
62
62
|
protected getChecksSQL(tables: Table[]): string;
|
|
63
63
|
normalizeDefaultValue(defaultValue: string, length: number): string | number;
|
|
64
64
|
protected wrap(val: string | null | undefined, type: Type<unknown>): string | null | undefined;
|
|
65
|
+
normalizeExpression(expr: string): string;
|
|
65
66
|
/** Decodes the backslash escapes of an introspected string literal. */
|
|
66
67
|
unescapeDefault(val: string): string;
|
|
67
68
|
}
|
|
@@ -295,12 +295,14 @@ export class MySqlSchemaHelper extends SchemaHelper {
|
|
|
295
295
|
const ret = {};
|
|
296
296
|
for (const check of allChecks) {
|
|
297
297
|
const key = this.getTableKey(check);
|
|
298
|
+
// string literals come back escaped twice, decoded one level the same as the defaults in `wrap()`
|
|
299
|
+
const expression = check.expression.replace(/\\(.)/gs, '$1');
|
|
298
300
|
ret[key] ??= [];
|
|
299
301
|
ret[key].push({
|
|
300
302
|
name: check.name,
|
|
301
303
|
columnName: check.column_name,
|
|
302
|
-
definition: `check ${
|
|
303
|
-
expression:
|
|
304
|
+
definition: `check ${expression}`,
|
|
305
|
+
expression: expression.replace(/^\((.*)\)$/, '$1'),
|
|
304
306
|
});
|
|
305
307
|
}
|
|
306
308
|
return ret;
|
|
@@ -610,6 +612,10 @@ export class MySqlSchemaHelper extends SchemaHelper {
|
|
|
610
612
|
const stringType = type instanceof StringType || type instanceof TextType || type instanceof EnumType;
|
|
611
613
|
return stringType ? this.platform.quoteDefaultValue(val) : val;
|
|
612
614
|
}
|
|
615
|
+
normalizeExpression(expr) {
|
|
616
|
+
// `\'` and `''` are the same quote inside a literal
|
|
617
|
+
return expr.replace(/\\(.)/gs, (escape, char) => (char === "'" ? "''" : escape));
|
|
618
|
+
}
|
|
613
619
|
/** Decodes the backslash escapes of an introspected string literal. */
|
|
614
620
|
unescapeDefault(val) {
|
|
615
621
|
const sqlEscapes = { 0: '\0', b: '\b', n: '\n', r: '\r', t: '\t', Z: '\x1a' };
|
|
@@ -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 */
|
|
@@ -230,7 +230,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
230
230
|
const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
|
|
231
231
|
table.collation = dbCollation;
|
|
232
232
|
const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
|
|
233
|
-
const enums = this.getEnumDefinitions(checks[key] ?? []);
|
|
233
|
+
const enums = this.getEnumDefinitions(checks[key] ?? [], columns[key] ?? []);
|
|
234
234
|
if (columns[key]) {
|
|
235
235
|
table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
|
|
236
236
|
}
|
|
@@ -1051,7 +1051,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1051
1051
|
}
|
|
1052
1052
|
return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
|
|
1053
1053
|
}
|
|
1054
|
-
getEnumDefinitions(checks) {
|
|
1054
|
+
getEnumDefinitions(checks, columns) {
|
|
1055
1055
|
return checks.reduce((o, item) => {
|
|
1056
1056
|
// check constraints are defined as one of:
|
|
1057
1057
|
// `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
|
|
@@ -1063,13 +1063,20 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1063
1063
|
// the single-value form must compare against a quoted literal (`= 'a'::text`); anything else
|
|
1064
1064
|
// (e.g. a JSON `->>` extraction like `name = data->>'name'`) is not an enum constraint
|
|
1065
1065
|
const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = ('(?:[^']|'')*'::[\w ]+)\)/i);
|
|
1066
|
-
|
|
1066
|
+
// enums with string items are emulated with a check, a check like `delta in (1, -1)` on a number is a plain one
|
|
1067
|
+
const column = columns.find(c => c.name === item.columnName);
|
|
1068
|
+
const numeric = column != null &&
|
|
1069
|
+
(this.platform.isNumericColumn(column.mappedType) ||
|
|
1070
|
+
[DecimalType, FloatType, DoubleType].some(t => column.mappedType instanceof t));
|
|
1071
|
+
if (item.columnName && m1 && m2 && !numeric) {
|
|
1067
1072
|
/* v8 ignore next */
|
|
1068
1073
|
const parts = m2[1].match(/('(?:[^']|'')*'::\w[\w ]*)/g) ?? m2[1].split(',');
|
|
1069
1074
|
let items = parts.map((item) => /^\(?'((?:[^']|'')*)'/.exec(item.trim())?.[1]?.replace(/''/g, "'"));
|
|
1070
1075
|
items = items.filter(item => item !== undefined);
|
|
1071
1076
|
if (items.length > 0) {
|
|
1072
1077
|
o[item.columnName] = items;
|
|
1078
|
+
// kept to compare with a plain check of the same values, e.g. `kind = 'manual'` is stored like a single item enum
|
|
1079
|
+
item.introspectedExpression = item.expression;
|
|
1073
1080
|
item.expression = this.platform.getEnumCheckConstraintExpression(item.columnName, items);
|
|
1074
1081
|
item.definition = `check (${item.expression})`;
|
|
1075
1082
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mikro-orm/sql",
|
|
3
|
-
"version": "7.2.
|
|
3
|
+
"version": "7.2.10-dev.0",
|
|
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.2.
|
|
56
|
+
"@mikro-orm/core": "7.2.10-dev.0"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">= 22.17.0"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, 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 matchPopulateJoins = options?.matchPopulateJoins ||
|
|
11
14
|
(this.prop && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(this.prop.kind));
|
|
12
15
|
const nestedAlias = qb.getAliasForJoinPath(this.getPath(options), { ...options, matchPopulateJoins });
|
package/query/QueryBuilder.d.ts
CHANGED
|
@@ -980,8 +980,6 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
|
|
|
980
980
|
* Tier 3: Derive from target entity metadata (all cloneable columns), auto-populate source select
|
|
981
981
|
*/
|
|
982
982
|
private resolveInsertFromColumns;
|
|
983
|
-
/** Returns properties that are safe to clone (persistable, non-PK, non-generated). */
|
|
984
|
-
private getCloneableProps;
|
|
985
983
|
private applyDiscriminatorCondition;
|
|
986
984
|
/**
|
|
987
985
|
* Ensures TPT joins are applied. Can be called early before finalize() to populate
|
package/query/QueryBuilder.js
CHANGED
|
@@ -1262,7 +1262,6 @@ export class QueryBuilder {
|
|
|
1262
1262
|
const entities = [];
|
|
1263
1263
|
for (const row of res) {
|
|
1264
1264
|
const entity = this.mapResult(row);
|
|
1265
|
-
this.propagatePopulateHint(entity, this.#state.populate);
|
|
1266
1265
|
entities.push(entity);
|
|
1267
1266
|
if (limit != null && --limit === 0) {
|
|
1268
1267
|
break;
|
|
@@ -1300,7 +1299,9 @@ export class QueryBuilder {
|
|
|
1300
1299
|
* Executes the query, returning both array of results and total count query (without offset and limit).
|
|
1301
1300
|
*/
|
|
1302
1301
|
async getResultAndCount() {
|
|
1303
|
-
|
|
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()];
|
|
1304
1305
|
}
|
|
1305
1306
|
as(aliasOrTargetEntity, alias) {
|
|
1306
1307
|
const qb = this.getNativeQuery();
|
|
@@ -1884,7 +1885,7 @@ export class QueryBuilder {
|
|
|
1884
1885
|
});
|
|
1885
1886
|
}
|
|
1886
1887
|
// Tier 3: derive from metadata — all cloneable columns
|
|
1887
|
-
const cloneableProps = this.getCloneableProps(meta);
|
|
1888
|
+
const cloneableProps = this.driver.getCloneableProps(meta);
|
|
1888
1889
|
const selectFields = [];
|
|
1889
1890
|
const columns = [];
|
|
1890
1891
|
for (const prop of cloneableProps) {
|
|
@@ -1899,27 +1900,6 @@ export class QueryBuilder {
|
|
|
1899
1900
|
}
|
|
1900
1901
|
return columns;
|
|
1901
1902
|
}
|
|
1902
|
-
/** Returns properties that are safe to clone (persistable, non-PK, non-generated). */
|
|
1903
|
-
getCloneableProps(meta) {
|
|
1904
|
-
return meta.props.filter(prop => {
|
|
1905
|
-
if (prop.persist === false) {
|
|
1906
|
-
return false;
|
|
1907
|
-
}
|
|
1908
|
-
if (prop.primary) {
|
|
1909
|
-
return false;
|
|
1910
|
-
}
|
|
1911
|
-
if (!prop.fieldNames?.length) {
|
|
1912
|
-
return false;
|
|
1913
|
-
}
|
|
1914
|
-
if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
|
|
1915
|
-
return false;
|
|
1916
|
-
}
|
|
1917
|
-
if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) {
|
|
1918
|
-
return false;
|
|
1919
|
-
}
|
|
1920
|
-
return true;
|
|
1921
|
-
});
|
|
1922
|
-
}
|
|
1923
1903
|
applyDiscriminatorCondition() {
|
|
1924
1904
|
const meta = this.mainAlias.meta;
|
|
1925
1905
|
if (meta.root.inheritanceType !== 'sti' || !meta.discriminatorValue) {
|
|
@@ -2041,12 +2021,13 @@ export class QueryBuilder {
|
|
|
2041
2021
|
if (meta && (this.#state.fields?.includes('*') || this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`))) {
|
|
2042
2022
|
const schema = this.getSchema(this.mainAlias);
|
|
2043
2023
|
// Per-column entries are unquoted (meant for `quote`), while `toString()` yields the quoted alias for plain template literals
|
|
2044
|
-
// For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
|
|
2045
2024
|
const quotedMainAlias = this.platform.quoteIdentifier(this.mainAlias.aliasName).toString();
|
|
2046
|
-
|
|
2025
|
+
let columns;
|
|
2047
2026
|
meta.props
|
|
2048
2027
|
.filter(prop => prop.formula && (!prop.lazy || this.#state.flags.has(QueryFlag.INCLUDE_LAZY_FORMULAS)))
|
|
2049
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);
|
|
2050
2031
|
const aliased = this.platform.quoteIdentifier(prop.fieldNames[0]);
|
|
2051
2032
|
const table = this.helper.createFormulaTable(quotedMainAlias, meta, schema);
|
|
2052
2033
|
return `${this.driver.evaluateFormula(prop.formula, columns, table)} as ${aliased}`;
|
|
@@ -415,14 +415,18 @@ export class QueryBuilderHelper {
|
|
|
415
415
|
Utils.runIfNotEmpty(() => {
|
|
416
416
|
let mergeParam = item.merge;
|
|
417
417
|
if (Utils.isObject(item.merge)) {
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
const k = this.mapper(key, type);
|
|
421
|
-
mergeParam[k] = item.merge[key];
|
|
422
|
-
});
|
|
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);
|
|
423
420
|
}
|
|
424
421
|
if (Array.isArray(item.merge)) {
|
|
425
|
-
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
|
+
});
|
|
426
430
|
}
|
|
427
431
|
sub.merge = mergeParam ?? [];
|
|
428
432
|
// a merged row is updated, so its version is bumped as `updateVersionProperty()` does
|
|
@@ -763,33 +767,29 @@ export class QueryBuilderHelper {
|
|
|
763
767
|
if (isRaw(colPart)) {
|
|
764
768
|
colPart = this.#platform.formatQuery(colPart.sql, colPart.params);
|
|
765
769
|
}
|
|
766
|
-
|
|
767
|
-
order.forEach(part => ret.push(...this.getQueryOrderFromObject(type, part, populate, collation)));
|
|
768
|
-
}
|
|
769
|
-
else {
|
|
770
|
-
ret.push(...this.#platform.getOrderByExpression(colPart, order, collation));
|
|
771
|
-
}
|
|
770
|
+
ret.push(...this.#platform.getOrderByExpression(colPart, order, collation));
|
|
772
771
|
}
|
|
773
772
|
}
|
|
774
773
|
return ret;
|
|
775
774
|
}
|
|
776
775
|
splitField(field, greedyAlias = false) {
|
|
777
|
-
const
|
|
778
|
-
const
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
if (
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
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];
|
|
793
793
|
}
|
|
794
794
|
getLockSQL(qb, lockMode, lockTables = [], joinsMap) {
|
|
795
795
|
const meta = this.#metadata.find(this.#entityName);
|
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,
|
|
@@ -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 &&
|
|
@@ -925,12 +931,13 @@ export class SchemaComparator {
|
|
|
925
931
|
// Protect dots inside string literals before the quote strip below, or the alias-prefix normalization
|
|
926
932
|
// would mangle literal contents — `current_setting('app.tenant')` and `current_setting('req.tenant')`
|
|
927
933
|
// must not both collapse to `current_settingtenant`
|
|
928
|
-
|
|
934
|
+
// numbers are left alone, postgres quotes the negative ones (`'-1.5'::numeric`)
|
|
935
|
+
.replace(/'([^']*)'/g, (m, inner) => /^-?\d+(\.\d+)?$/.test(inner) ? m : `'${inner.replaceAll('.', '\u0000')}'`)
|
|
929
936
|
// Remove quotes first so we can process identifiers
|
|
930
937
|
.replace(/['"`]/g, '')
|
|
931
938
|
// MySQL adds table/alias prefixes to columns (e.g., a.name or table_name.column vs just column)
|
|
932
939
|
// Strip these prefixes - match word.word patterns and keep only the last part
|
|
933
|
-
.replace(/\b\w+\.(\w+)/g, '$1')
|
|
940
|
+
.replace(/\b(?!\d)\w+\.(\w+)/g, '$1')
|
|
934
941
|
// PostgreSQL rewrites `x [not] between a and b` to `x >= a and x <= b` (`x < a or x > b`), cast targets are skipped
|
|
935
942
|
.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}`)
|
|
936
943
|
// Normalize JOIN syntax: inner join -> join (equivalent in SQL)
|
package/typings.d.ts
CHANGED
|
@@ -113,6 +113,8 @@ export interface CheckDef<T = unknown> {
|
|
|
113
113
|
expression: string | CheckCallback<T>;
|
|
114
114
|
definition?: string;
|
|
115
115
|
columnName?: string;
|
|
116
|
+
/** @internal the expression as introspected, before it was normalized as the check of an enum */
|
|
117
|
+
introspectedExpression?: string;
|
|
116
118
|
}
|
|
117
119
|
/** Resolved row level security policy for schema operations (all callbacks resolved to strings). */
|
|
118
120
|
export interface SqlPolicyDef {
|