@mikro-orm/sql 7.2.13-dev.1 → 7.2.13-dev.10
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.js +4 -1
- package/AbstractSqlPlatform.d.ts +5 -0
- package/AbstractSqlPlatform.js +9 -0
- package/SqlEntityManager.js +4 -1
- package/dialects/mysql/MySqlSchemaHelper.js +1 -1
- package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +2 -0
- package/dialects/postgresql/PostgreSqlSchemaHelper.js +31 -20
- package/package.json +2 -2
- package/query/ObjectCriteriaNode.js +6 -3
- package/query/QueryBuilder.d.ts +9 -1
- package/query/QueryBuilder.js +20 -6
- package/query/QueryBuilderHelper.js +21 -5
- package/schema/DatabaseTable.js +2 -1
- package/schema/SchemaComparator.js +20 -2
- package/schema/SchemaHelper.d.ts +2 -0
- package/schema/SchemaHelper.js +7 -3
- package/schema/SqlSchemaGenerator.js +4 -2
- package/typings.d.ts +2 -0
package/AbstractSqlDriver.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ALIAS_REPLACEMENT_RE, DatabaseDriver, DateType, EntityManagerType, getLoadingStrategy, getOnConflictFields, getOnConflictReturningFields, helper, isRaw, LoadStrategy, parseJsonSafe, PolymorphicRef, QueryFlag, QueryHelper, QueryOrder, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { ALIAS_REPLACEMENT_RE, DatabaseDriver, DateType, EntityManagerType, getLoadingStrategy, getOnConflictFields, getOnConflictReturningFields, helper, isRaw, LoadStrategy, parseJsonSafe, PolymorphicRef, QueryFlag, QueryHelper, QueryOrder, raw, RawQueryFragment, ReferenceKind, Utils, ValidationError, } from '@mikro-orm/core';
|
|
2
2
|
import { QueryBuilder } from './query/QueryBuilder.js';
|
|
3
3
|
import { JoinType, QueryType } from './query/enums.js';
|
|
4
4
|
import { SqlEntityManager } from './SqlEntityManager.js';
|
|
@@ -88,6 +88,9 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
88
88
|
return { alias, name: meta.tableName, schema: effectiveSchema, qualifiedName, toString: () => alias };
|
|
89
89
|
}
|
|
90
90
|
validateSqlOptions(options) {
|
|
91
|
+
if (options.having != null && typeof options.having !== 'object') {
|
|
92
|
+
throw ValidationError.invalidQueryCondition(options.having);
|
|
93
|
+
}
|
|
91
94
|
if (options.using && !options.indexHint) {
|
|
92
95
|
const names = Utils.asArray(options.using);
|
|
93
96
|
const hint = this.platform.formatIndexHint(names);
|
package/AbstractSqlPlatform.d.ts
CHANGED
|
@@ -28,6 +28,11 @@ export declare abstract class AbstractSqlPlatform extends Platform {
|
|
|
28
28
|
getSavepointSQL(savepointName: string): string;
|
|
29
29
|
getRollbackToSavepointSQL(savepointName: string): string;
|
|
30
30
|
getReleaseSavepointSQL(savepointName: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* Quotes a name and its optional schema as separate identifiers, so a dot inside either is not read as a qualifier.
|
|
33
|
+
* @internal
|
|
34
|
+
*/
|
|
35
|
+
quoteQualifiedName(name: string, schema?: string): string;
|
|
31
36
|
quoteValue(value: any): string;
|
|
32
37
|
getSearchJsonPropertySQL(path: string, type: string, aliased: boolean): string | RawQueryFragment;
|
|
33
38
|
getSearchJsonPropertyKey(path: string[], type: string, aliased: boolean | string, value?: unknown): string | RawQueryFragment;
|
package/AbstractSqlPlatform.js
CHANGED
|
@@ -91,6 +91,15 @@ export class AbstractSqlPlatform extends Platform {
|
|
|
91
91
|
getReleaseSavepointSQL(savepointName) {
|
|
92
92
|
return `release savepoint ${this.quoteIdentifier(savepointName)}`;
|
|
93
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Quotes a name and its optional schema as separate identifiers, so a dot inside either is not read as a qualifier.
|
|
96
|
+
* @internal
|
|
97
|
+
*/
|
|
98
|
+
quoteQualifiedName(name, schema) {
|
|
99
|
+
const [open, close] = this.quoteIdentifier('');
|
|
100
|
+
const quote = (part) => open + part.replaceAll(close, close + close) + close;
|
|
101
|
+
return schema ? `${quote(schema)}.${quote(name)}` : quote(name);
|
|
102
|
+
}
|
|
94
103
|
quoteValue(value) {
|
|
95
104
|
if (isRaw(value)) {
|
|
96
105
|
return this.formatQuery(value.sql, value.params);
|
package/SqlEntityManager.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EntityManager, QueryFlag, raw, Utils, } from '@mikro-orm/core';
|
|
1
|
+
import { EntityManager, QueryFlag, raw, Utils, ValidationError, } from '@mikro-orm/core';
|
|
2
2
|
import { MikroKyselyPlugin } from './plugin/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* @inheritDoc
|
|
@@ -82,6 +82,9 @@ export class SqlEntityManager extends EntityManager {
|
|
|
82
82
|
const meta = em.getMetadata().find(entityName);
|
|
83
83
|
const fields = Utils.asArray(groupBy);
|
|
84
84
|
const { where: rawWhere, ...countOptions } = options;
|
|
85
|
+
if (countOptions.having != null && typeof countOptions.having !== 'object') {
|
|
86
|
+
throw ValidationError.invalidQueryCondition(countOptions.having);
|
|
87
|
+
}
|
|
85
88
|
await em.tryFlush(entityName, options);
|
|
86
89
|
const where = await em.processWhere(entityName, rawWhere ?? {}, options, 'read');
|
|
87
90
|
// match `em.count()` semantics: an active transaction always wins over the requested connection type
|
|
@@ -66,7 +66,7 @@ export class MySqlSchemaHelper extends SchemaHelper {
|
|
|
66
66
|
// and may return NULL. Use SHOW CREATE VIEW as fallback.
|
|
67
67
|
let definition = view.view_definition?.trim();
|
|
68
68
|
if (!definition) {
|
|
69
|
-
const createView = await connection.execute(`show create view
|
|
69
|
+
const createView = await connection.execute(`show create view ${this.quoteTableName(view.view_name)}`, [], 'all', ctx);
|
|
70
70
|
if (createView[0]?.['Create View']) {
|
|
71
71
|
// Extract SELECT statement from CREATE VIEW ... AS SELECT ...
|
|
72
72
|
const match = /\bAS\s+(.+)$/is.exec(createView[0]['Create View']);
|
|
@@ -83,6 +83,8 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
83
83
|
private dropPolicy;
|
|
84
84
|
private formatPolicyRoles;
|
|
85
85
|
createRoutine(routine: SqlRoutineDef): string;
|
|
86
|
+
/** Wraps a function body in a dollar-quote tag that does not occur in it. */
|
|
87
|
+
private dollarQuote;
|
|
86
88
|
dropRoutine(routine: SqlRoutineDef): string;
|
|
87
89
|
getAllRoutines(connection: AbstractSqlConnection, schemas?: string[]): Promise<SqlRoutineDef[]>;
|
|
88
90
|
private formatRoutineParams;
|
|
@@ -161,7 +161,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
163
|
createMaterializedView(name, schema, definition, withData = true) {
|
|
164
|
-
const viewName = this.
|
|
164
|
+
const viewName = this.quoteTableName(name, schema);
|
|
165
165
|
const dataClause = withData ? ' with data' : ' with no data';
|
|
166
166
|
return `create materialized view ${viewName} as ${definition}${dataClause}`;
|
|
167
167
|
}
|
|
@@ -172,7 +172,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
172
172
|
}
|
|
173
173
|
const [createTable, ...rest] = super.createTable(table, alter);
|
|
174
174
|
const partitions = partitioning.partitions.map(partition => {
|
|
175
|
-
const partitionName = this.
|
|
175
|
+
const partitionName = this.quoteTableName(partition.name, partition.schema ?? table.schema);
|
|
176
176
|
return `create table ${partitionName} partition of ${table.getQuotedName()} ${partition.bound}`;
|
|
177
177
|
});
|
|
178
178
|
// SchemaHelper.append() always terminates the CREATE TABLE with `;`; we rely on that to splice
|
|
@@ -183,11 +183,11 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
183
183
|
return [spliced, ...rest, ...partitions];
|
|
184
184
|
}
|
|
185
185
|
dropMaterializedViewIfExists(name, schema) {
|
|
186
|
-
return `drop materialized view if exists ${this.
|
|
186
|
+
return `drop materialized view if exists ${this.quoteTableName(name, schema)} cascade`;
|
|
187
187
|
}
|
|
188
188
|
refreshMaterializedView(name, schema, concurrently = false) {
|
|
189
189
|
const concurrent = concurrently ? ' concurrently' : '';
|
|
190
|
-
return `refresh materialized view${concurrent} ${this.
|
|
190
|
+
return `refresh materialized view${concurrent} ${this.quoteTableName(name, schema)}`;
|
|
191
191
|
}
|
|
192
192
|
async getNamespaces(connection, ctx) {
|
|
193
193
|
const sql = `select schema_name from information_schema.schemata ` +
|
|
@@ -599,7 +599,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
599
599
|
const when = trigger.when ? `\n when (${trigger.when})` : '';
|
|
600
600
|
const fnName = this.getSchemaQualifiedTriggerFnName(table, trigger);
|
|
601
601
|
const triggerName = this.quote(trigger.name);
|
|
602
|
-
const fnSql = `create or replace function ${fnName}() returns trigger as
|
|
602
|
+
const fnSql = `create or replace function ${fnName}() returns trigger as ${this.dollarQuote(`begin ${this.normalizeTriggerBody(trigger.body)} end;`)} language plpgsql`;
|
|
603
603
|
const triggerSql = `create trigger ${triggerName} ${timing} ${events} on ${table.getQuotedName()} for each ${forEach}${when} execute function ${fnName}()`;
|
|
604
604
|
return `${fnSql};\n${triggerSql}`;
|
|
605
605
|
}
|
|
@@ -714,16 +714,26 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
714
714
|
const flatten = (s) => stripStatementNewlines(s).trim();
|
|
715
715
|
if (routine.type === 'procedure') {
|
|
716
716
|
const body = language === 'sql' ? flatten(routine.body ?? '') : this.wrapRoutineBody(routine.body ?? '');
|
|
717
|
-
return `create or replace procedure ${qualifiedName}(${params})${security} language ${language} as
|
|
717
|
+
return `create or replace procedure ${qualifiedName}(${params})${security} language ${language} as ${this.dollarQuote(body)}`;
|
|
718
718
|
}
|
|
719
719
|
const returnType = routine.returns?.type ?? 'void';
|
|
720
720
|
const body = language === 'sql' ? flatten(routine.body ?? '') : this.wrapRoutineBody(routine.body ?? '');
|
|
721
|
-
return `create or replace function ${qualifiedName}(${params}) returns ${returnType}${security}${determinism} language ${language} as
|
|
721
|
+
return `create or replace function ${qualifiedName}(${params}) returns ${returnType}${security}${determinism} language ${language} as ${this.dollarQuote(body)}`;
|
|
722
|
+
}
|
|
723
|
+
/** Wraps a function body in a dollar-quote tag that does not occur in it. */
|
|
724
|
+
dollarQuote(body) {
|
|
725
|
+
let tag = '$$';
|
|
726
|
+
for (let i = 0; body.includes(tag); i++) {
|
|
727
|
+
tag = `$body${i || ''}$`;
|
|
728
|
+
}
|
|
729
|
+
return `${tag} ${body} ${tag}`;
|
|
722
730
|
}
|
|
723
731
|
dropRoutine(routine) {
|
|
724
732
|
const qualifiedName = this.qualifiedRoutineName(routine);
|
|
725
|
-
const argTypes = routine.params.map(p => p.type).join(', ');
|
|
726
733
|
const kind = routine.type === 'procedure' ? 'procedure' : 'function';
|
|
734
|
+
// OUT parameters are not part of a function's identity, only of a procedure's
|
|
735
|
+
const identityParams = routine.params.filter(p => kind === 'procedure' || p.direction !== 'out');
|
|
736
|
+
const argTypes = identityParams.map(p => p.type).join(', ');
|
|
727
737
|
return `drop ${kind} if exists ${qualifiedName}(${argTypes})`;
|
|
728
738
|
}
|
|
729
739
|
async getAllRoutines(connection, schemas = []) {
|
|
@@ -739,7 +749,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
739
749
|
case when p.provolatile = 'i' then true when p.provolatile = 'v' then false else null end as deterministic,
|
|
740
750
|
case when p.prosecdef then 'definer' else 'invoker' end as security,
|
|
741
751
|
pg_get_functiondef(p.oid) as full_def,
|
|
742
|
-
|
|
752
|
+
pg_get_function_identity_arguments(p.oid) as arg_signature,
|
|
743
753
|
pg_get_function_result(p.oid) as result_type,
|
|
744
754
|
d.description as comment
|
|
745
755
|
from pg_proc p
|
|
@@ -791,13 +801,14 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
791
801
|
if (!signature.trim()) {
|
|
792
802
|
return [];
|
|
793
803
|
}
|
|
794
|
-
return signature.split(/,(?![^()]*\))/).map(part => {
|
|
804
|
+
return signature.split(/,(?![^()]*\))(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(part => {
|
|
795
805
|
const trimmed = part.trim();
|
|
796
806
|
// INOUT before IN/OUT, with required trailing space so identifiers like `input` aren't
|
|
797
|
-
// mis-parsed as a direction keyword. The name is optional — `
|
|
807
|
+
// mis-parsed as a direction keyword. The name is optional — `pg_get_function_identity_arguments`
|
|
798
808
|
// omits it for unnamed parameters (e.g. `text`), leaving just the type.
|
|
799
|
-
|
|
800
|
-
|
|
809
|
+
// An unquoted name is never the first word of a multi-word type: postgres quotes those keywords in names, and `double` is only one before `precision`.
|
|
810
|
+
const match = /^(?:(INOUT|VARIADIC|IN|OUT)\s+)?(?:(?:"((?:[^"]|"")+)"|(?!(?:double\s+precision|character|bit|timestamp|time)(?![\w$]))([\w$]+))\s+)?(.+)$/is.exec(trimmed);
|
|
811
|
+
/* v8 ignore next 3: defensive guard for unexpected `pg_get_function_identity_arguments` output shapes */
|
|
801
812
|
if (!match) {
|
|
802
813
|
throw new Error(`Could not parse PostgreSQL routine parameter signature: ${JSON.stringify(trimmed)}`);
|
|
803
814
|
}
|
|
@@ -1158,7 +1169,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1158
1169
|
// child partitions are separate tables that don't move with the parent — park them too so their
|
|
1159
1170
|
// names are free for the new partitions
|
|
1160
1171
|
for (const partition of diff.fromTable.getPartitioning()?.partitions ?? []) {
|
|
1161
|
-
const partitionName = this.
|
|
1172
|
+
const partitionName = this.quoteTableName(partition.name, partition.schema ?? table.schema);
|
|
1162
1173
|
ret.push(`alter table ${partitionName} set schema ${this.quote(tmpSchema)}`);
|
|
1163
1174
|
}
|
|
1164
1175
|
// create the new partitioned table (+ partitions, indexes, checks)
|
|
@@ -1223,16 +1234,16 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1223
1234
|
const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
|
|
1224
1235
|
for (const col of changedEnums) {
|
|
1225
1236
|
if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.fromColumn.default) {
|
|
1226
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1237
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} drop default`);
|
|
1227
1238
|
}
|
|
1228
1239
|
if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.fromColumn.default) {
|
|
1229
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1240
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} drop default`);
|
|
1230
1241
|
}
|
|
1231
1242
|
}
|
|
1232
1243
|
// changing uuid column type requires to cast it to text first
|
|
1233
1244
|
const uuids = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid');
|
|
1234
1245
|
for (const col of uuids) {
|
|
1235
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1246
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} type text using (${this.quote(col.column.name)}::text)`);
|
|
1236
1247
|
}
|
|
1237
1248
|
for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
|
|
1238
1249
|
if (!column.autoincrement && column.default == null) {
|
|
@@ -1262,10 +1273,10 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1262
1273
|
const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
|
|
1263
1274
|
for (const col of changedEnums) {
|
|
1264
1275
|
if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
|
|
1265
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1276
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} set default ${col.column.default}`);
|
|
1266
1277
|
}
|
|
1267
1278
|
if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.column.default) {
|
|
1268
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1279
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} set default ${col.column.default}`);
|
|
1269
1280
|
}
|
|
1270
1281
|
}
|
|
1271
1282
|
for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
|
|
@@ -1418,7 +1429,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1418
1429
|
join pg_namespace as ns on i.relnamespace = ns.oid
|
|
1419
1430
|
join pg_am as am on am.oid = i.relam
|
|
1420
1431
|
left join pg_constraint as c on c.conname = i.relname
|
|
1421
|
-
where indrelid in (${tables.map(t => `${this.platform.quoteValue(
|
|
1432
|
+
where indrelid in (${tables.map(t => `${this.platform.quoteValue(this.platform.quoteQualifiedName(t.table_name, t.schema_name))}::regclass`).join(', ')})
|
|
1422
1433
|
and (c.contype is null or c.contype <> 'x')
|
|
1423
1434
|
order by relname`;
|
|
1424
1435
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mikro-orm/sql",
|
|
3
|
-
"version": "7.2.13-dev.
|
|
3
|
+
"version": "7.2.13-dev.10",
|
|
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",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"@mikro-orm/core": "^7.2.12"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@mikro-orm/core": "7.2.13-dev.
|
|
56
|
+
"@mikro-orm/core": "7.2.13-dev.10"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">= 22.17.0"
|
|
@@ -83,10 +83,13 @@ export class ObjectCriteriaNode extends CriteriaNode {
|
|
|
83
83
|
else {
|
|
84
84
|
sub.where({ [this.key]: payload });
|
|
85
85
|
}
|
|
86
|
+
// compiled lazily, so filters can still be applied to its joins, except inside a filter (those could cycle)
|
|
87
|
+
if (!options?.filter) {
|
|
88
|
+
sub.scheduleFilterCheck(`${parentMeta.className}.${this.key}`);
|
|
89
|
+
qb.scheduleSubQueryFilterCheck(sub, ownerAlias);
|
|
90
|
+
}
|
|
86
91
|
const op = ['$size', '$some'].includes(key) ? '$in' : '$nin';
|
|
87
|
-
$and.push({
|
|
88
|
-
[Utils.getPrimaryKeyHash(primaryKeys)]: { [op]: sub.getNativeQuery().toRaw() },
|
|
89
|
-
});
|
|
92
|
+
$and.push({ [Utils.getPrimaryKeyHash(primaryKeys)]: { [op]: sub } });
|
|
90
93
|
}
|
|
91
94
|
if (matchNothing) {
|
|
92
95
|
$and.push({ [Utils.getPrimaryKeyHash(primaryKeys)]: { $in: [] } });
|
package/query/QueryBuilder.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { JoinType, QueryType } from './enums.js';
|
|
|
3
3
|
import type { AbstractSqlDriver } from '../AbstractSqlDriver.js';
|
|
4
4
|
import { type Alias, type OnConflictClause, QueryBuilderHelper } from './QueryBuilderHelper.js';
|
|
5
5
|
import type { SqlEntityManager } from '../SqlEntityManager.js';
|
|
6
|
-
import type { ICriteriaNodeProcessOptions, InternalField, JoinOptions } from '../typings.js';
|
|
6
|
+
import type { ICriteriaNodeProcessOptions, InternalField, IQueryBuilder, JoinOptions } from '../typings.js';
|
|
7
7
|
import type { AbstractSqlPlatform } from '../AbstractSqlPlatform.js';
|
|
8
8
|
import { type CteOptions, NativeQueryBuilder } from './NativeQueryBuilder.js';
|
|
9
9
|
export interface ExecuteOptions {
|
|
@@ -212,6 +212,10 @@ export interface QBState<Entity extends object> {
|
|
|
212
212
|
})[];
|
|
213
213
|
tptJoinsApplied: boolean;
|
|
214
214
|
autoJoinedPaths: string[];
|
|
215
|
+
filteredSubQueries: {
|
|
216
|
+
qb: QueryBuilder<any>;
|
|
217
|
+
ownerAlias: string;
|
|
218
|
+
}[];
|
|
215
219
|
partitionLimit?: {
|
|
216
220
|
partitionBy: string;
|
|
217
221
|
limit: number;
|
|
@@ -501,6 +505,10 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
|
|
|
501
505
|
* @internal
|
|
502
506
|
*/
|
|
503
507
|
scheduleFilterCheck(path: string): void;
|
|
508
|
+
/**
|
|
509
|
+
* @internal
|
|
510
|
+
*/
|
|
511
|
+
scheduleSubQueryFilterCheck(qb: IQueryBuilder<any>, ownerAlias: string): void;
|
|
504
512
|
/**
|
|
505
513
|
* @internal
|
|
506
514
|
*/
|
package/query/QueryBuilder.js
CHANGED
|
@@ -61,6 +61,7 @@ export class QueryBuilder {
|
|
|
61
61
|
ctes: [],
|
|
62
62
|
tptJoinsApplied: false,
|
|
63
63
|
autoJoinedPaths: [],
|
|
64
|
+
filteredSubQueries: [],
|
|
64
65
|
populate: [],
|
|
65
66
|
populateMap: {},
|
|
66
67
|
flags: new Set([QueryFlag.CONVERT_CUSTOM_TYPES]),
|
|
@@ -406,22 +407,31 @@ export class QueryBuilder {
|
|
|
406
407
|
this.#state.autoJoinedPaths.push(path);
|
|
407
408
|
}
|
|
408
409
|
}
|
|
410
|
+
/**
|
|
411
|
+
* @internal
|
|
412
|
+
*/
|
|
413
|
+
scheduleSubQueryFilterCheck(qb, ownerAlias) {
|
|
414
|
+
this.#state.filteredSubQueries.push({ qb: qb, ownerAlias });
|
|
415
|
+
}
|
|
409
416
|
/**
|
|
410
417
|
* @internal
|
|
411
418
|
*/
|
|
412
419
|
async applyJoinedFilters(em, filterOptions) {
|
|
413
420
|
const joins = Object.values(this.#state.joins);
|
|
421
|
+
// nested joins inherit the overrides of their ancestor relations
|
|
422
|
+
const getJoinFilters = (join) => {
|
|
423
|
+
const chain = join ? [join] : [];
|
|
424
|
+
for (let parent; (parent = joins.find(j => j.alias === chain[0]?.ownerAlias));) {
|
|
425
|
+
chain.unshift(parent);
|
|
426
|
+
}
|
|
427
|
+
return chain.reduce((acc, j) => QueryHelper.mergePropertyFilters(j.prop.filters, acc), filterOptions);
|
|
428
|
+
};
|
|
414
429
|
for (const path of this.#state.autoJoinedPaths) {
|
|
415
430
|
const join = this.getJoinForPath(path);
|
|
416
431
|
if (join.type === JoinType.pivotJoin) {
|
|
417
432
|
continue;
|
|
418
433
|
}
|
|
419
|
-
|
|
420
|
-
const chain = [join];
|
|
421
|
-
for (let parent; (parent = joins.find(j => j.alias === chain[0].ownerAlias));) {
|
|
422
|
-
chain.unshift(parent);
|
|
423
|
-
}
|
|
424
|
-
const joinFilters = chain.reduce((acc, j) => QueryHelper.mergePropertyFilters(j.prop.filters, acc), filterOptions);
|
|
434
|
+
const joinFilters = getJoinFilters(join);
|
|
425
435
|
let cond = await em.applyFilters(join.prop.targetMeta.class, join.cond, joinFilters, 'read');
|
|
426
436
|
const criteriaNode = CriteriaNodeFactory.createNode(this.metadata, join.prop.targetMeta.class, cond);
|
|
427
437
|
cond = criteriaNode.process(this, {
|
|
@@ -469,6 +479,10 @@ export class QueryBuilder {
|
|
|
469
479
|
}
|
|
470
480
|
}
|
|
471
481
|
}
|
|
482
|
+
for (const sub of this.#state.filteredSubQueries) {
|
|
483
|
+
const filters = getJoinFilters(joins.find(j => j.alias === sub.ownerAlias));
|
|
484
|
+
await sub.qb.applyJoinedFilters(em, filters);
|
|
485
|
+
}
|
|
472
486
|
}
|
|
473
487
|
/**
|
|
474
488
|
* The `on` clause of `condJoin` — its explicit join condition or a filter condition merged into
|
|
@@ -568,6 +568,15 @@ export class QueryBuilderHelper {
|
|
|
568
568
|
['$in', '$nin'].includes(op) &&
|
|
569
569
|
Array.isArray(value[op]) &&
|
|
570
570
|
value[op].every((v) => Array.isArray(v));
|
|
571
|
+
// `in` and `not in` never match null, so a null in the list becomes an explicit null check
|
|
572
|
+
if (fields.length === 1 && ['$in', '$nin'].includes(op) && Array.isArray(value[op]) && value[op].includes(null)) {
|
|
573
|
+
const list = value[op].filter((v) => v !== null);
|
|
574
|
+
const conds = [{ [key]: { [op === '$in' ? '$eq' : '$ne']: null } }];
|
|
575
|
+
if (list.length > 0) {
|
|
576
|
+
conds.unshift({ [key]: { [op]: list } });
|
|
577
|
+
}
|
|
578
|
+
return this.appendGroupCondition(type, op === '$in' ? '$or' : '$and', conds);
|
|
579
|
+
}
|
|
571
580
|
// an empty list falls through to the generic `1 = 0` / `1 = 1` handling below
|
|
572
581
|
if (fields.length > 1 && Array.isArray(value[op]) && value[op].length > 0) {
|
|
573
582
|
const singleTuple = !value[op].every((v) => Array.isArray(v));
|
|
@@ -997,8 +1006,14 @@ export class QueryBuilderHelper {
|
|
|
997
1006
|
parts.push(`1 = ${op === '$in' ? 0 : 1}`);
|
|
998
1007
|
}
|
|
999
1008
|
else {
|
|
1000
|
-
val.
|
|
1001
|
-
|
|
1009
|
+
const list = val.filter((v) => v !== null);
|
|
1010
|
+
const conds = list.length > 0 ? [`${lhs} ${replacement} (${list.map(() => '?').join(', ')})`] : [];
|
|
1011
|
+
list.forEach((v) => params.push(v));
|
|
1012
|
+
// `in` and `not in` never match null, so a null in the list becomes an explicit null check
|
|
1013
|
+
if (list.length < val.length) {
|
|
1014
|
+
conds.push(`${lhs} is ${op === '$in' ? '' : 'not '}null`);
|
|
1015
|
+
}
|
|
1016
|
+
parts.push(conds.length > 1 ? `(${conds.join(op === '$in' ? ' or ' : ' and ')})` : conds[0]);
|
|
1002
1017
|
}
|
|
1003
1018
|
}
|
|
1004
1019
|
else if (op === '$exists') {
|
|
@@ -1102,11 +1117,12 @@ export class QueryBuilderHelper {
|
|
|
1102
1117
|
if (typeof v === 'bigint') {
|
|
1103
1118
|
return 'bigint';
|
|
1104
1119
|
}
|
|
1105
|
-
if (Array.isArray(v)
|
|
1106
|
-
|
|
1120
|
+
if (Array.isArray(v)) {
|
|
1121
|
+
const first = v.find(i => i !== null);
|
|
1122
|
+
if (typeof first === 'number') {
|
|
1107
1123
|
return 'number';
|
|
1108
1124
|
}
|
|
1109
|
-
if (typeof
|
|
1125
|
+
if (typeof first === 'boolean') {
|
|
1110
1126
|
return 'boolean';
|
|
1111
1127
|
}
|
|
1112
1128
|
}
|
package/schema/DatabaseTable.js
CHANGED
|
@@ -33,7 +33,8 @@ export class DatabaseTable {
|
|
|
33
33
|
this.#platform = platform;
|
|
34
34
|
}
|
|
35
35
|
getQuotedName() {
|
|
36
|
-
|
|
36
|
+
const schema = this.getShortestName() === this.name ? undefined : this.schema;
|
|
37
|
+
return this.#platform.quoteQualifiedName(this.name, schema);
|
|
37
38
|
}
|
|
38
39
|
getColumns() {
|
|
39
40
|
return Object.values(this.#columns);
|
|
@@ -175,8 +175,26 @@ export class SchemaComparator {
|
|
|
175
175
|
const ignoreRoutines = this.#platform.getConfig().get('schemaGenerator').ignoreRoutines;
|
|
176
176
|
// Case-fold so user-written `'sql_hash'` matches Oracle's introspected `'SQL_HASH'`.
|
|
177
177
|
const routineKey = (r) => ((r.schema ? `${r.schema}.` : '') + r.name).toLowerCase();
|
|
178
|
-
|
|
179
|
-
const
|
|
178
|
+
// Overloads share a name: the one matching the other side keeps the plain key, the rest get a signature-qualified one.
|
|
179
|
+
const indexRoutines = (routines, others) => {
|
|
180
|
+
const map = new Map();
|
|
181
|
+
for (const routine of routines) {
|
|
182
|
+
const key = routineKey(routine);
|
|
183
|
+
const prev = map.get(key);
|
|
184
|
+
if (!prev) {
|
|
185
|
+
map.set(key, routine);
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const other = others.find(o => routineKey(o) === key);
|
|
189
|
+
const keep = other && !this.diffRoutineParams(routine.params, other.params) ? routine : prev;
|
|
190
|
+
const extra = keep === routine ? prev : routine;
|
|
191
|
+
map.set(key, keep);
|
|
192
|
+
map.set(`${key}(${extra.params.map(p => `${p.direction} ${p.type}`).join(', ')})`, extra);
|
|
193
|
+
}
|
|
194
|
+
return map;
|
|
195
|
+
};
|
|
196
|
+
const fromByKey = indexRoutines(fromSchema.getRoutines(), toSchema.getRoutines());
|
|
197
|
+
const toByKey = indexRoutines(toSchema.getRoutines(), fromSchema.getRoutines());
|
|
180
198
|
for (const [key, toRoutine] of toByKey) {
|
|
181
199
|
const fromRoutine = fromByKey.get(key);
|
|
182
200
|
if (!fromRoutine) {
|
package/schema/SchemaHelper.d.ts
CHANGED
|
@@ -224,6 +224,8 @@ export declare abstract class SchemaHelper {
|
|
|
224
224
|
get options(): NonNullable<Options['schemaGenerator']>;
|
|
225
225
|
protected processComment(comment: string): string;
|
|
226
226
|
protected quote(...keys: (string | undefined)[]): string;
|
|
227
|
+
/** Quotes a table or view name held separately from its schema, a dot in either stays inside the identifier. */
|
|
228
|
+
protected quoteTableName(name: string, schema?: string): string;
|
|
227
229
|
dropForeignKey(tableName: string, constraintName: string): string;
|
|
228
230
|
dropIndex(table: string, index: IndexDef, oldIndexName?: string): string;
|
|
229
231
|
dropConstraint(table: string, name: string): string;
|
package/schema/SchemaHelper.js
CHANGED
|
@@ -1025,6 +1025,10 @@ export class SchemaHelper {
|
|
|
1025
1025
|
// DDL is not a query template, so question marks need no escaping there
|
|
1026
1026
|
return this.platform.quoteIdentifier(keys.filter(Boolean).join('.')).replaceAll('\\?', '?');
|
|
1027
1027
|
}
|
|
1028
|
+
/** Quotes a table or view name held separately from its schema, a dot in either stays inside the identifier. */
|
|
1029
|
+
quoteTableName(name, schema) {
|
|
1030
|
+
return this.platform.quoteQualifiedName(name, schema === this.platform.getDefaultSchemaName() ? undefined : schema);
|
|
1031
|
+
}
|
|
1028
1032
|
dropForeignKey(tableName, constraintName) {
|
|
1029
1033
|
return `alter table ${this.quote(tableName)} drop foreign key ${this.quote(constraintName)}`;
|
|
1030
1034
|
}
|
|
@@ -1039,18 +1043,18 @@ export class SchemaHelper {
|
|
|
1039
1043
|
}
|
|
1040
1044
|
/** Returns SQL to drop a table if it exists. */
|
|
1041
1045
|
dropTableIfExists(name, schema) {
|
|
1042
|
-
let sql = `drop table if exists ${this.
|
|
1046
|
+
let sql = `drop table if exists ${this.quoteTableName(name, schema)}`;
|
|
1043
1047
|
if (this.platform.usesCascadeStatement()) {
|
|
1044
1048
|
sql += ' cascade';
|
|
1045
1049
|
}
|
|
1046
1050
|
return sql;
|
|
1047
1051
|
}
|
|
1048
1052
|
createView(name, schema, definition) {
|
|
1049
|
-
const viewName = this.
|
|
1053
|
+
const viewName = this.quoteTableName(name, schema);
|
|
1050
1054
|
return `create view ${viewName} as ${definition}`;
|
|
1051
1055
|
}
|
|
1052
1056
|
dropViewIfExists(name, schema) {
|
|
1053
|
-
let sql = `drop view if exists ${this.
|
|
1057
|
+
let sql = `drop view if exists ${this.quoteTableName(name, schema)}`;
|
|
1054
1058
|
if (this.platform.usesCascadeStatement()) {
|
|
1055
1059
|
sql += ' cascade';
|
|
1056
1060
|
}
|
|
@@ -201,7 +201,8 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
|
|
|
201
201
|
}
|
|
202
202
|
}
|
|
203
203
|
if (options.dropMigrationsTable) {
|
|
204
|
-
|
|
204
|
+
const [schema, name] = this.helper.splitTableName(this.config.get('migrations').tableName);
|
|
205
|
+
this.append(ret, this.helper.dropTableIfExists(name, schema ?? this.config.get('schema')));
|
|
205
206
|
}
|
|
206
207
|
return this.wrapSchema(ret, options);
|
|
207
208
|
}
|
|
@@ -520,7 +521,8 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
|
|
|
520
521
|
return false;
|
|
521
522
|
}
|
|
522
523
|
async dropTableIfExists(name, schema) {
|
|
523
|
-
const
|
|
524
|
+
const [schemaName, tableName] = schema ? [schema, name] : this.helper.splitTableName(name);
|
|
525
|
+
const sql = this.helper.dropTableIfExists(tableName, schemaName);
|
|
524
526
|
return this.execute(sql);
|
|
525
527
|
}
|
|
526
528
|
wrapSchema(sql, options) {
|
package/typings.d.ts
CHANGED
|
@@ -296,6 +296,8 @@ export interface IQueryBuilder<T> {
|
|
|
296
296
|
withRecursive(name: string, query: AnyQueryBuilder | NativeQueryBuilder | RawQueryFragment, options?: CteOptions): this;
|
|
297
297
|
scheduleFilterCheck(path: string): void;
|
|
298
298
|
/** @internal */
|
|
299
|
+
scheduleSubQueryFilterCheck(qb: IQueryBuilder<any>, ownerAlias: string): void;
|
|
300
|
+
/** @internal */
|
|
299
301
|
ensureTPTJoins(): void;
|
|
300
302
|
withSchema(schema: string): this;
|
|
301
303
|
}
|