@mikro-orm/sql 7.2.7-dev.8 → 7.2.7
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/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +1 -0
- package/dialects/postgresql/PostgreSqlSchemaHelper.js +66 -0
- package/dialects/sqlite/SqliteSchemaHelper.d.ts +1 -0
- package/dialects/sqlite/SqliteSchemaHelper.js +3 -0
- package/package.json +3 -3
- package/query/NativeQueryBuilder.js +7 -1
- package/query/QueryBuilder.js +4 -2
- package/query/QueryBuilderHelper.js +2 -2
- package/schema/DatabaseTable.js +8 -4
- package/schema/SchemaComparator.js +6 -2
- package/schema/SchemaHelper.d.ts +7 -0
- package/schema/SchemaHelper.js +11 -0
|
@@ -137,6 +137,7 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
137
137
|
private getAlterColumnAutoincrement;
|
|
138
138
|
getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
|
|
139
139
|
alterTableComment(table: DatabaseTable, comment?: string): string;
|
|
140
|
+
normalizeExpression(expr: string): string;
|
|
140
141
|
normalizeDefaultValue(defaultValue: string, length: number): string | number;
|
|
141
142
|
appendComments(table: DatabaseTable): string[];
|
|
142
143
|
getDatabaseExistsSQL(name: string): string;
|
|
@@ -7,6 +7,65 @@ const POSTGIS_VIEWS = ['geography_columns', 'geometry_columns'];
|
|
|
7
7
|
const DOLLAR_QUOTE_TAG = /(\$(?:[A-Za-z_]\w*)?\$)/;
|
|
8
8
|
/** pg-added `(<operand>)::type` cast in a check body, including multi word types like `double precision`. */
|
|
9
9
|
const CHECK_CAST_RE = /\(([^()]*)\)::\w+(?: precision| varying| with(?:out)? time zone)?(?:\[\])?/g;
|
|
10
|
+
/**
|
|
11
|
+
* PostgreSQL prints `interval '1 minute'` back as `'00:01:00'`, so the literal is reformatted the same way.
|
|
12
|
+
* Only non-negative `<n> <unit>` lists are handled, anything else has to be written the way PostgreSQL prints it.
|
|
13
|
+
*/
|
|
14
|
+
function normalizeIntervalLiteral(literal) {
|
|
15
|
+
// `[field, factor]` into the months, days and microseconds triple PostgreSQL stores an interval as
|
|
16
|
+
const units = {
|
|
17
|
+
year: [0, 12],
|
|
18
|
+
yr: [0, 12],
|
|
19
|
+
y: [0, 12],
|
|
20
|
+
month: [0, 1],
|
|
21
|
+
mon: [0, 1],
|
|
22
|
+
week: [1, 7],
|
|
23
|
+
w: [1, 7],
|
|
24
|
+
day: [1, 1],
|
|
25
|
+
d: [1, 1],
|
|
26
|
+
hour: [2, 3_600_000_000],
|
|
27
|
+
hr: [2, 3_600_000_000],
|
|
28
|
+
h: [2, 3_600_000_000],
|
|
29
|
+
minute: [2, 60_000_000],
|
|
30
|
+
min: [2, 60_000_000],
|
|
31
|
+
m: [2, 60_000_000],
|
|
32
|
+
second: [2, 1_000_000],
|
|
33
|
+
sec: [2, 1_000_000],
|
|
34
|
+
s: [2, 1_000_000],
|
|
35
|
+
millisecond: [2, 1_000],
|
|
36
|
+
msec: [2, 1_000],
|
|
37
|
+
ms: [2, 1_000],
|
|
38
|
+
microsecond: [2, 1],
|
|
39
|
+
usec: [2, 1],
|
|
40
|
+
us: [2, 1],
|
|
41
|
+
};
|
|
42
|
+
const parts = [0, 0, 0];
|
|
43
|
+
// longer spellings first, so `ms`/`msec` are not read as `m` + plural `s`
|
|
44
|
+
const unitRe = /(\d+(?:\.\d+)?) *(milliseconds?|microseconds?|msecs?|usecs?|years?|months?|mons?|weeks?|days?|hours?|minutes?|seconds?|yrs?|hrs?|mins?|secs?|ms|us|[ywdhms])\b/g;
|
|
45
|
+
const rest = literal.toLowerCase().replace(unitRe, (_, qty, unit) => {
|
|
46
|
+
const [field, factor] = units[unit] ?? units[unit.slice(0, -1)];
|
|
47
|
+
parts[field] += +qty * factor;
|
|
48
|
+
return '';
|
|
49
|
+
});
|
|
50
|
+
if (rest.trim() || !Number.isInteger(parts[0]) || !Number.isInteger(parts[1])) {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
const [months, days] = parts;
|
|
54
|
+
const micros = Math.round(parts[2]);
|
|
55
|
+
const fields = [
|
|
56
|
+
[Math.trunc(months / 12), 'year'],
|
|
57
|
+
[months % 12, 'mon'],
|
|
58
|
+
[days, 'day'],
|
|
59
|
+
]
|
|
60
|
+
.filter(([v]) => v > 0)
|
|
61
|
+
.map(([v, u]) => `${v} ${u}${v === 1 ? '' : 's'}`);
|
|
62
|
+
if (micros || !fields.length) {
|
|
63
|
+
const s = Math.floor(micros / 1_000_000);
|
|
64
|
+
const time = [s / 3600, (s / 60) % 60, s % 60].map(v => String(Math.floor(v)).padStart(2, '0')).join(':');
|
|
65
|
+
fields.push(time + String((micros % 1_000_000) / 1_000_000).slice(1));
|
|
66
|
+
}
|
|
67
|
+
return fields.join(' ');
|
|
68
|
+
}
|
|
10
69
|
export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
11
70
|
static DEFAULT_VALUES = {
|
|
12
71
|
'now()': ['now()', 'current_timestamp'],
|
|
@@ -1227,6 +1286,13 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1227
1286
|
alterTableComment(table, comment) {
|
|
1228
1287
|
return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
|
|
1229
1288
|
}
|
|
1289
|
+
normalizeExpression(expr) {
|
|
1290
|
+
return expr.replace(/\binterval\s*'([^']*)'|'([^']*)'\s*::\s*interval\b/gi, (_, typed, cast) => {
|
|
1291
|
+
// `interval 'x'` and `'x'::interval` are the same literal and PostgreSQL always prints the cast form
|
|
1292
|
+
const literal = typed ?? cast;
|
|
1293
|
+
return `'${normalizeIntervalLiteral(literal) ?? literal}'::interval`;
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1230
1296
|
normalizeDefaultValue(defaultValue, length) {
|
|
1231
1297
|
if (!defaultValue || typeof defaultValue !== 'string') {
|
|
1232
1298
|
return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
|
|
@@ -8,6 +8,7 @@ export declare class SqliteSchemaHelper extends SchemaHelper {
|
|
|
8
8
|
private static readonly PARTIAL_WHERE_RE;
|
|
9
9
|
disableForeignKeysSQL(): string;
|
|
10
10
|
enableForeignKeysSQL(): string;
|
|
11
|
+
getForeignKeyCheckSQL(): string;
|
|
11
12
|
supportsSchemaConstraints(): boolean;
|
|
12
13
|
getCreateNamespaceSQL(name: string): string;
|
|
13
14
|
getDropNamespaceSQL(name: string): string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mikro-orm/sql",
|
|
3
|
-
"version": "7.2.7
|
|
3
|
+
"version": "7.2.7",
|
|
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.7"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@mikro-orm/core": "7.2.7
|
|
56
|
+
"@mikro-orm/core": "7.2.7"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">= 22.17.0"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isRaw, LockMode, raw, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { isRaw, LockMode, raw, SUBQUERY_BRAND, Utils, } from '@mikro-orm/core';
|
|
2
2
|
import { QueryType } from './enums.js';
|
|
3
3
|
/** @internal */
|
|
4
4
|
export class NativeQueryBuilder {
|
|
@@ -529,3 +529,9 @@ export class NativeQueryBuilder {
|
|
|
529
529
|
return this.platform.quoteIdentifier(id);
|
|
530
530
|
}
|
|
531
531
|
}
|
|
532
|
+
// prototype-level brand recognized by `isSubquery()`, JSON payloads cannot forge it
|
|
533
|
+
Object.defineProperty(NativeQueryBuilder.prototype, SUBQUERY_BRAND, {
|
|
534
|
+
value: true,
|
|
535
|
+
writable: false,
|
|
536
|
+
configurable: false,
|
|
537
|
+
});
|
package/query/QueryBuilder.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var _a;
|
|
2
|
-
import { EntityMetadata, helper, inspect, isRaw, LoadStrategy, LockMode, PopulateHint, QueryFlag, QueryHelper, raw, RawQueryFragment, Reference, ReferenceKind, serialize, Utils, ValidationError, } from '@mikro-orm/core';
|
|
2
|
+
import { EntityMetadata, helper, inspect, isRaw, LoadStrategy, LockMode, PopulateHint, QueryFlag, QueryHelper, raw, RawQueryFragment, Reference, ReferenceKind, serialize, SUBQUERY_BRAND, Utils, ValidationError, } from '@mikro-orm/core';
|
|
3
3
|
import { JoinType, QueryType } from './enums.js';
|
|
4
4
|
import { QueryBuilderHelper } from './QueryBuilderHelper.js';
|
|
5
5
|
import { CriteriaNodeFactory } from './CriteriaNodeFactory.js';
|
|
@@ -2016,7 +2016,7 @@ export class QueryBuilder {
|
|
|
2016
2016
|
this.processNestedJoins();
|
|
2017
2017
|
if (meta && (this.#state.fields?.includes('*') || this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`))) {
|
|
2018
2018
|
const schema = this.getSchema(this.mainAlias);
|
|
2019
|
-
//
|
|
2019
|
+
// Per-column entries are unquoted (meant for `quote`), while `toString()` yields the quoted alias for plain template literals
|
|
2020
2020
|
// For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
|
|
2021
2021
|
const quotedMainAlias = this.platform.quoteIdentifier(this.mainAlias.aliasName).toString();
|
|
2022
2022
|
const columns = meta.createColumnMappingObject(prop => this.helper.getTPTAliasForProperty(prop.name, this.mainAlias.aliasName), quotedMainAlias);
|
|
@@ -2675,3 +2675,5 @@ export class QueryBuilder {
|
|
|
2675
2675
|
}
|
|
2676
2676
|
}
|
|
2677
2677
|
_a = QueryBuilder;
|
|
2678
|
+
// prototype-level brand recognized by `isSubquery()`, JSON payloads cannot forge it
|
|
2679
|
+
Object.defineProperty(QueryBuilder.prototype, SUBQUERY_BRAND, { value: true, writable: false, configurable: false });
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ALIAS_REPLACEMENT, ALIAS_REPLACEMENT_RE, ArrayType, JsonType, inspect, isRaw, LockMode, OptimisticLockError, QueryOperator, QueryOrderNumeric, raw, Raw, QueryHelper, ReferenceKind, Utils, ValidationError, } from '@mikro-orm/core';
|
|
1
|
+
import { ALIAS_REPLACEMENT, ALIAS_REPLACEMENT_RE, ArrayType, JsonType, inspect, isRaw, isSubquery, LockMode, OptimisticLockError, QueryOperator, QueryOrderNumeric, raw, Raw, QueryHelper, ReferenceKind, Utils, ValidationError, } from '@mikro-orm/core';
|
|
2
2
|
import { EMBEDDABLE_ARRAY_OPS, JoinType, QueryType } from './enums.js';
|
|
3
3
|
/** Captures the column name that follows the alias placeholder. */
|
|
4
4
|
const QUALIFYING_ALIAS_RE = new RegExp(ALIAS_REPLACEMENT_RE + '(?=["\'`\\]]*\\.["\'`\\[]?([\\w$]+))', 'g');
|
|
@@ -613,7 +613,7 @@ export class QueryBuilderHelper {
|
|
|
613
613
|
else {
|
|
614
614
|
const opValue = value[op];
|
|
615
615
|
const opValueIsRaw = isRaw(opValue);
|
|
616
|
-
if (opValueIsRaw ||
|
|
616
|
+
if (opValueIsRaw || isSubquery(opValue)) {
|
|
617
617
|
const query = opValueIsRaw ? opValue : opValue.toRaw();
|
|
618
618
|
const mappedKey = this.mapper(key, type, query, null);
|
|
619
619
|
let sql = this.replaceAliases(query.sql);
|
package/schema/DatabaseTable.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DecimalType, EntitySchema, isRaw, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { DecimalType, EntitySchema, isRaw, MetadataError, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
|
|
2
2
|
import { toEntityPartitionBy } from './partitioning.js';
|
|
3
3
|
/**
|
|
4
4
|
* @internal
|
|
@@ -975,19 +975,23 @@ export class DatabaseTable {
|
|
|
975
975
|
if (columns?.length && properties.length > 0) {
|
|
976
976
|
for (const col of columns) {
|
|
977
977
|
if (!properties.includes(col.name)) {
|
|
978
|
-
throw new
|
|
978
|
+
throw new MetadataError(`Index '${name}' on entity '${meta.className}': column option references field '${col.name}' which is not in the index properties`);
|
|
979
979
|
}
|
|
980
980
|
}
|
|
981
981
|
}
|
|
982
982
|
// Validate fillFactor range
|
|
983
983
|
if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
|
|
984
|
-
throw new
|
|
984
|
+
throw new MetadataError(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${name}' on entity '${meta.className}'`);
|
|
985
985
|
}
|
|
986
986
|
// The `expression` escape hatch takes the full index definition as raw SQL; combining it
|
|
987
987
|
// with `where` is dialect-dependent (PG/Oracle/MySQL drop `where`, MSSQL appends it) so we
|
|
988
988
|
// reject the combination up-front and ask users to inline the predicate into `expression`.
|
|
989
989
|
if (index.expression && index.where != null) {
|
|
990
|
-
throw new
|
|
990
|
+
throw new MetadataError(`Index '${name}' on entity '${meta.className}': cannot combine \`expression\` with \`where\` — inline the WHERE clause into the \`expression\` escape hatch, or drop \`expression\` and use structured \`properties\` + \`where\`.`);
|
|
991
|
+
}
|
|
992
|
+
// `where` forces the `create unique index` form, and no dialect accepts `deferrable` on an index.
|
|
993
|
+
if (index.where != null && index.deferMode) {
|
|
994
|
+
throw new MetadataError(`Index '${name}' on entity '${meta.className}': cannot combine \`deferMode\` with \`where\` — partial unique indexes cannot be deferrable. On PostgreSQL, declare an exclusion constraint instead, e.g. \`exclude using btree (col with =) where (...) deferrable initially ${index.deferMode}\`.`);
|
|
991
995
|
}
|
|
992
996
|
const where = this.processIndexWhere(index.where, meta);
|
|
993
997
|
const expression = this.processIndexExpression(name, index.expression, meta);
|
|
@@ -906,9 +906,13 @@ export class SchemaComparator {
|
|
|
906
906
|
// expressions like check constraints might be normalized by the driver,
|
|
907
907
|
// e.g. quotes might be added (https://github.com/mikro-orm/mikro-orm/issues/3827)
|
|
908
908
|
const simplify = (str) => {
|
|
909
|
-
|
|
909
|
+
if (str == null) {
|
|
910
|
+
return str;
|
|
911
|
+
}
|
|
912
|
+
return (this.#helper
|
|
913
|
+
.normalizeExpression(str)
|
|
910
914
|
// lookbehind: only strip a real charset introducer, never an underscore inside a literal like 'a_b'
|
|
911
|
-
|
|
915
|
+
.replace(/(?<![\w'])_\w+'(.*?)'/g, '$1')
|
|
912
916
|
.replace(/!=/g, '<>')
|
|
913
917
|
// `\b` keeps this from firing inside identifiers like `min(...)`
|
|
914
918
|
.replace(/\bnot\s+in\s*\((.*?)\)/gi, '<> all (array[$1])')
|
package/schema/SchemaHelper.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export declare abstract class SchemaHelper {
|
|
|
33
33
|
disableForeignKeysSQL(): string;
|
|
34
34
|
/** Returns SQL to re-enable foreign key checks. */
|
|
35
35
|
enableForeignKeysSQL(): string;
|
|
36
|
+
/** Returns SQL listing rows that violate foreign keys; when non-empty, migrations run with FK checks off and verify afterwards (SQLite). */
|
|
37
|
+
getForeignKeyCheckSQL(): string;
|
|
36
38
|
/** Returns SQL to append to schema migration scripts (e.g., re-enabling FK checks). */
|
|
37
39
|
getSchemaEnd(disableForeignKeys?: boolean): string;
|
|
38
40
|
/** Sets the current schema for the session (e.g. `SET search_path`). */
|
|
@@ -163,6 +165,11 @@ export declare abstract class SchemaHelper {
|
|
|
163
165
|
getNamespaces(connection: AbstractSqlConnection, ctx?: Transaction): Promise<string[]>;
|
|
164
166
|
protected mapIndexes(indexes: IndexDef[]): Promise<IndexDef[]>;
|
|
165
167
|
mapForeignKeys(fks: any[], tableName: string, schemaName?: string): Dictionary;
|
|
168
|
+
/**
|
|
169
|
+
* Rewrites the parts of a user-provided expression the database stores in a different form, so that
|
|
170
|
+
* `SchemaComparator.diffExpression()` compares it to the introspected definition on equal footing.
|
|
171
|
+
*/
|
|
172
|
+
normalizeExpression(expr: string): string;
|
|
166
173
|
/** Decodes the content of an introspected string literal, the inverse of `Platform.quoteDefaultValue()`. */
|
|
167
174
|
unescapeDefault(val: string): string;
|
|
168
175
|
normalizeDefaultValue(defaultValue: string | RawQueryFragment, length?: number, defaultValues?: Dictionary<string[]>): string | number;
|
package/schema/SchemaHelper.js
CHANGED
|
@@ -52,6 +52,10 @@ export class SchemaHelper {
|
|
|
52
52
|
enableForeignKeysSQL() {
|
|
53
53
|
return '';
|
|
54
54
|
}
|
|
55
|
+
/** Returns SQL listing rows that violate foreign keys; when non-empty, migrations run with FK checks off and verify afterwards (SQLite). */
|
|
56
|
+
getForeignKeyCheckSQL() {
|
|
57
|
+
return '';
|
|
58
|
+
}
|
|
55
59
|
/** Returns SQL to append to schema migration scripts (e.g., re-enabling FK checks). */
|
|
56
60
|
getSchemaEnd(disableForeignKeys) {
|
|
57
61
|
if (disableForeignKeys) {
|
|
@@ -718,6 +722,13 @@ export class SchemaHelper {
|
|
|
718
722
|
return ret;
|
|
719
723
|
}, {});
|
|
720
724
|
}
|
|
725
|
+
/**
|
|
726
|
+
* Rewrites the parts of a user-provided expression the database stores in a different form, so that
|
|
727
|
+
* `SchemaComparator.diffExpression()` compares it to the introspected definition on equal footing.
|
|
728
|
+
*/
|
|
729
|
+
normalizeExpression(expr) {
|
|
730
|
+
return expr;
|
|
731
|
+
}
|
|
721
732
|
/** Decodes the content of an introspected string literal, the inverse of `Platform.quoteDefaultValue()`. */
|
|
722
733
|
unescapeDefault(val) {
|
|
723
734
|
return val.replaceAll("''", "'");
|