@mikro-orm/sql 7.3.0-dev.25 → 7.3.0-dev.27
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 +0 -6
- package/AbstractSqlDriver.js +12 -27
- package/AbstractSqlPlatform.d.ts +5 -0
- package/AbstractSqlPlatform.js +9 -0
- package/README.md +4 -0
- package/SqlEntityManager.js +4 -1
- package/dialects/mysql/MySqlNativeQueryBuilder.d.ts +1 -0
- package/dialects/mysql/MySqlNativeQueryBuilder.js +1 -0
- package/dialects/mysql/MySqlSchemaHelper.js +1 -1
- package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +2 -0
- package/dialects/postgresql/PostgreSqlSchemaHelper.js +31 -20
- package/dialects/sqlite/SqliteNativeQueryBuilder.d.ts +1 -0
- package/dialects/sqlite/SqliteNativeQueryBuilder.js +1 -0
- package/package.json +3 -3
- package/query/NativeQueryBuilder.d.ts +2 -0
- package/query/NativeQueryBuilder.js +5 -0
- package/query/ObjectCriteriaNode.js +6 -3
- package/query/QueryBuilder.d.ts +9 -1
- package/query/QueryBuilder.js +22 -2
- package/query/QueryBuilderHelper.js +21 -5
- package/schema/DatabaseTable.js +5 -1
- package/schema/SchemaComparator.js +32 -7
- package/schema/SchemaHelper.d.ts +4 -0
- package/schema/SchemaHelper.js +15 -3
- package/schema/SqlSchemaGenerator.js +4 -2
- package/typings.d.ts +2 -0
package/AbstractSqlDriver.d.ts
CHANGED
|
@@ -77,12 +77,6 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
|
|
|
77
77
|
nativeUpdate<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T> & UpsertOptions<T>): Promise<QueryResult<T>>;
|
|
78
78
|
nativeUpdateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T> & UpsertManyOptions<T>, transform?: (sql: string, params: any[]) => string): Promise<QueryResult<T>>;
|
|
79
79
|
nativeDelete<T extends object>(entityName: EntityName<T>, where: FilterQuery<T> | string | any, options?: DeleteOptions<T>): Promise<QueryResult<T>>;
|
|
80
|
-
/**
|
|
81
|
-
* Fast comparison for collection snapshots that are represented by PK arrays.
|
|
82
|
-
* Compares scalars via `===` and fallbacks to Utils.equals()` for more complex types like Buffer.
|
|
83
|
-
* Always expects the same length of the arrays, since we only compare PKs of the same entity type.
|
|
84
|
-
*/
|
|
85
|
-
private comparePrimaryKeyArrays;
|
|
86
80
|
syncCollections<T extends object, O extends object>(collections: Iterable<Collection<T, O>>, options?: DriverMethodOptions): Promise<void>;
|
|
87
81
|
loadFromPivotTable<T extends object, O extends object>(prop: EntityProperty, owners: Primary<O>[][], where?: FilterQuery<any>, orderBy?: OrderDefinition<T>, ctx?: Transaction, options?: FindOptions<T, any, any, any>, pivotJoin?: boolean): Promise<Dictionary<T[]>>;
|
|
88
82
|
/**
|
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);
|
|
@@ -96,10 +99,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
96
99
|
}
|
|
97
100
|
}
|
|
98
101
|
if (options.collation != null && typeof options.collation !== 'string') {
|
|
99
|
-
throw new
|
|
102
|
+
throw new ValidationError('Collation option for SQL drivers must be a string (collation name). Use a CollationOptions object only with MongoDB.');
|
|
100
103
|
}
|
|
101
104
|
if (options.indexHint != null && typeof options.indexHint !== 'string') {
|
|
102
|
-
throw new
|
|
105
|
+
throw new ValidationError("indexHint for SQL drivers must be a string (e.g. 'force index(my_index)'). Use an object only with MongoDB.");
|
|
103
106
|
}
|
|
104
107
|
}
|
|
105
108
|
createEntityManager(useContext) {
|
|
@@ -1262,26 +1265,6 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1262
1265
|
qb.setAbortOptions(pickAbortOptions(options));
|
|
1263
1266
|
return this.rethrow(qb.execute('run', false));
|
|
1264
1267
|
}
|
|
1265
|
-
/**
|
|
1266
|
-
* Fast comparison for collection snapshots that are represented by PK arrays.
|
|
1267
|
-
* Compares scalars via `===` and fallbacks to Utils.equals()` for more complex types like Buffer.
|
|
1268
|
-
* Always expects the same length of the arrays, since we only compare PKs of the same entity type.
|
|
1269
|
-
*/
|
|
1270
|
-
comparePrimaryKeyArrays(a, b) {
|
|
1271
|
-
for (let i = a.length; i-- !== 0;) {
|
|
1272
|
-
if (['number', 'string', 'bigint', 'boolean'].includes(typeof a[i])) {
|
|
1273
|
-
if (a[i] !== b[i]) {
|
|
1274
|
-
return false;
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
else {
|
|
1278
|
-
if (!Utils.equals(a[i], b[i])) {
|
|
1279
|
-
return false;
|
|
1280
|
-
}
|
|
1281
|
-
}
|
|
1282
|
-
}
|
|
1283
|
-
return true;
|
|
1284
|
-
}
|
|
1285
1268
|
async syncCollections(collections, options) {
|
|
1286
1269
|
const groups = {};
|
|
1287
1270
|
for (const coll of collections) {
|
|
@@ -1289,7 +1272,6 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1289
1272
|
const meta = wrapped.__meta;
|
|
1290
1273
|
const pks = wrapped.getPrimaryKeys(true);
|
|
1291
1274
|
const snap = coll.getSnapshot();
|
|
1292
|
-
const includes = (arr, item) => !!arr.find(i => this.comparePrimaryKeyArrays(i, item));
|
|
1293
1275
|
// For union-target polymorphic M:N, prepend the per-row discriminator value so the pivot
|
|
1294
1276
|
// persister can write it alongside the FK id. Memoized per sync-run because a collection can
|
|
1295
1277
|
// hold hundreds of items of the same few types, and findDiscriminatorValue walks the prototype
|
|
@@ -1313,9 +1295,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
|
|
|
1313
1295
|
};
|
|
1314
1296
|
const snapshot = snap ? snap.map(toDiff) : [];
|
|
1315
1297
|
const current = coll.getItems(false).map(toDiff);
|
|
1316
|
-
const
|
|
1317
|
-
const
|
|
1318
|
-
const
|
|
1298
|
+
const hash = (item) => Utils.getPrimaryKeyHash(item);
|
|
1299
|
+
const currentKeys = new Set(current.map(hash));
|
|
1300
|
+
const snapshotKeys = new Set(snapshot.map(hash));
|
|
1301
|
+
const deleteDiff = snap ? snapshot.filter(item => !currentKeys.has(hash(item))) : true;
|
|
1302
|
+
const insertDiff = current.filter(item => !snapshotKeys.has(hash(item)));
|
|
1303
|
+
const target = snapshot.filter(item => currentKeys.has(hash(item))).concat(...insertDiff);
|
|
1319
1304
|
const equals = Utils.equals(current, target);
|
|
1320
1305
|
// wrong order if we just delete and insert to the end (only owning sides can have fixed order)
|
|
1321
1306
|
if (coll.property.owner && coll.property.fixedOrder && !equals && Array.isArray(deleteDiff)) {
|
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/README.md
CHANGED
|
@@ -201,6 +201,10 @@ You can find example integrations for some popular frameworks in the [`mikro-orm
|
|
|
201
201
|
|
|
202
202
|
- [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)
|
|
203
203
|
|
|
204
|
+
## Supported Versions
|
|
205
|
+
|
|
206
|
+
New features and bug fixes land in the latest major version. The previous major version keeps receiving fixes for high and critical severity vulnerabilities for 12 months after the next major is released, and reaches end of life after that. See the [security policy](SECURITY.md) for the current status of each version and for how to report a vulnerability.
|
|
207
|
+
|
|
204
208
|
## Contributing
|
|
205
209
|
|
|
206
210
|
Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.
|
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
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { NativeQueryBuilder } from '../../query/NativeQueryBuilder.js';
|
|
2
2
|
/** @internal */
|
|
3
3
|
export declare class MySqlNativeQueryBuilder extends NativeQueryBuilder {
|
|
4
|
+
protected readonly noLimit = "18446744073709551615";
|
|
4
5
|
protected compileInsert(): void;
|
|
5
6
|
protected addLockClause(): void;
|
|
6
7
|
protected addOnConflictClause(): void;
|
|
@@ -2,6 +2,7 @@ import { isRaw, LockMode, Utils } from '@mikro-orm/core';
|
|
|
2
2
|
import { NativeQueryBuilder } from '../../query/NativeQueryBuilder.js';
|
|
3
3
|
/** @internal */
|
|
4
4
|
export class MySqlNativeQueryBuilder extends NativeQueryBuilder {
|
|
5
|
+
noLimit = '18446744073709551615';
|
|
5
6
|
compileInsert() {
|
|
6
7
|
if (this.options.insertSubQuery) {
|
|
7
8
|
super.compileInsert();
|
|
@@ -84,7 +84,7 @@ export class MySqlSchemaHelper extends SchemaHelper {
|
|
|
84
84
|
// and may return NULL. Use SHOW CREATE VIEW as fallback.
|
|
85
85
|
let definition = view.view_definition?.trim();
|
|
86
86
|
if (!definition) {
|
|
87
|
-
const createView = await connection.execute(`show create view
|
|
87
|
+
const createView = await connection.execute(`show create view ${this.quoteTableName(view.view_name)}`, [], 'all', ctx);
|
|
88
88
|
if (createView[0]?.['Create View']) {
|
|
89
89
|
// Extract SELECT statement from CREATE VIEW ... AS SELECT ...
|
|
90
90
|
const match = /\bAS\s+(.+)$/is.exec(createView[0]['Create View']);
|
|
@@ -88,6 +88,8 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
88
88
|
private dropPolicy;
|
|
89
89
|
private formatPolicyRoles;
|
|
90
90
|
createRoutine(routine: SqlRoutineDef): string;
|
|
91
|
+
/** Wraps a function body in a dollar-quote tag that does not occur in it. */
|
|
92
|
+
private dollarQuote;
|
|
91
93
|
dropRoutine(routine: SqlRoutineDef): string;
|
|
92
94
|
getAllRoutines(connection: AbstractSqlConnection, schemas?: string[]): Promise<SqlRoutineDef[]>;
|
|
93
95
|
private formatRoutineParams;
|
|
@@ -168,7 +168,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
168
168
|
}
|
|
169
169
|
}
|
|
170
170
|
createMaterializedView(name, schema, definition, withData = true) {
|
|
171
|
-
const viewName = this.
|
|
171
|
+
const viewName = this.quoteTableName(name, schema);
|
|
172
172
|
const dataClause = withData ? ' with data' : ' with no data';
|
|
173
173
|
return `create materialized view ${viewName} as ${definition}${dataClause}`;
|
|
174
174
|
}
|
|
@@ -192,7 +192,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
192
192
|
return [createTable, ...sequences, ...rest];
|
|
193
193
|
}
|
|
194
194
|
const partitions = partitioning.partitions.map(partition => {
|
|
195
|
-
const partitionName = this.
|
|
195
|
+
const partitionName = this.quoteTableName(partition.name, partition.schema ?? table.schema);
|
|
196
196
|
return `create table ${partitionName} partition of ${table.getQuotedName()} ${partition.bound}`;
|
|
197
197
|
});
|
|
198
198
|
// SchemaHelper.append() always terminates the CREATE TABLE with `;`; we rely on that to splice
|
|
@@ -208,11 +208,11 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
208
208
|
return `select setval(pg_get_serial_sequence(${table}, ${this.platform.quoteValue(columnName)}), ${startWith}, false)`;
|
|
209
209
|
}
|
|
210
210
|
dropMaterializedViewIfExists(name, schema) {
|
|
211
|
-
return `drop materialized view if exists ${this.
|
|
211
|
+
return `drop materialized view if exists ${this.quoteTableName(name, schema)} cascade`;
|
|
212
212
|
}
|
|
213
213
|
refreshMaterializedView(name, schema, concurrently = false) {
|
|
214
214
|
const concurrent = concurrently ? ' concurrently' : '';
|
|
215
|
-
return `refresh materialized view${concurrent} ${this.
|
|
215
|
+
return `refresh materialized view${concurrent} ${this.quoteTableName(name, schema)}`;
|
|
216
216
|
}
|
|
217
217
|
async getNamespaces(connection, ctx) {
|
|
218
218
|
const sql = `select schema_name from information_schema.schemata ` +
|
|
@@ -620,7 +620,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
620
620
|
const when = trigger.when ? `\n when (${trigger.when})` : '';
|
|
621
621
|
const fnName = this.getSchemaQualifiedTriggerFnName(table, trigger);
|
|
622
622
|
const triggerName = this.quote(trigger.name);
|
|
623
|
-
const fnSql = `create or replace function ${fnName}() returns trigger as
|
|
623
|
+
const fnSql = `create or replace function ${fnName}() returns trigger as ${this.dollarQuote(`begin ${this.normalizeTriggerBody(trigger.body)} end;`)} language plpgsql`;
|
|
624
624
|
const triggerSql = `create trigger ${triggerName} ${timing} ${events} on ${table.getQuotedName()} for each ${forEach}${when} execute function ${fnName}()`;
|
|
625
625
|
return `${fnSql};\n${triggerSql}`;
|
|
626
626
|
}
|
|
@@ -735,16 +735,26 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
735
735
|
const flatten = (s) => stripStatementNewlines(s).trim();
|
|
736
736
|
if (routine.type === 'procedure') {
|
|
737
737
|
const body = language === 'sql' ? flatten(routine.body ?? '') : this.wrapRoutineBody(routine.body ?? '');
|
|
738
|
-
return `create or replace procedure ${qualifiedName}(${params})${security} language ${language} as
|
|
738
|
+
return `create or replace procedure ${qualifiedName}(${params})${security} language ${language} as ${this.dollarQuote(body)}`;
|
|
739
739
|
}
|
|
740
740
|
const returnType = routine.returns?.type ?? 'void';
|
|
741
741
|
const body = language === 'sql' ? flatten(routine.body ?? '') : this.wrapRoutineBody(routine.body ?? '');
|
|
742
|
-
return `create or replace function ${qualifiedName}(${params}) returns ${returnType}${security}${determinism} language ${language} as
|
|
742
|
+
return `create or replace function ${qualifiedName}(${params}) returns ${returnType}${security}${determinism} language ${language} as ${this.dollarQuote(body)}`;
|
|
743
|
+
}
|
|
744
|
+
/** Wraps a function body in a dollar-quote tag that does not occur in it. */
|
|
745
|
+
dollarQuote(body) {
|
|
746
|
+
let tag = '$$';
|
|
747
|
+
for (let i = 0; body.includes(tag); i++) {
|
|
748
|
+
tag = `$body${i || ''}$`;
|
|
749
|
+
}
|
|
750
|
+
return `${tag} ${body} ${tag}`;
|
|
743
751
|
}
|
|
744
752
|
dropRoutine(routine) {
|
|
745
753
|
const qualifiedName = this.qualifiedRoutineName(routine);
|
|
746
|
-
const argTypes = routine.params.map(p => p.type).join(', ');
|
|
747
754
|
const kind = routine.type === 'procedure' ? 'procedure' : 'function';
|
|
755
|
+
// OUT parameters are not part of a function's identity, only of a procedure's
|
|
756
|
+
const identityParams = routine.params.filter(p => kind === 'procedure' || p.direction !== 'out');
|
|
757
|
+
const argTypes = identityParams.map(p => p.type).join(', ');
|
|
748
758
|
return `drop ${kind} if exists ${qualifiedName}(${argTypes})`;
|
|
749
759
|
}
|
|
750
760
|
async getAllRoutines(connection, schemas = []) {
|
|
@@ -760,7 +770,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
760
770
|
case when p.provolatile = 'i' then true when p.provolatile = 'v' then false else null end as deterministic,
|
|
761
771
|
case when p.prosecdef then 'definer' else 'invoker' end as security,
|
|
762
772
|
pg_get_functiondef(p.oid) as full_def,
|
|
763
|
-
|
|
773
|
+
pg_get_function_identity_arguments(p.oid) as arg_signature,
|
|
764
774
|
pg_get_function_result(p.oid) as result_type,
|
|
765
775
|
d.description as comment
|
|
766
776
|
from pg_proc p
|
|
@@ -812,13 +822,14 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
812
822
|
if (!signature.trim()) {
|
|
813
823
|
return [];
|
|
814
824
|
}
|
|
815
|
-
return signature.split(/,(?![^()]*\))/).map(part => {
|
|
825
|
+
return signature.split(/,(?![^()]*\))(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(part => {
|
|
816
826
|
const trimmed = part.trim();
|
|
817
827
|
// INOUT before IN/OUT, with required trailing space so identifiers like `input` aren't
|
|
818
|
-
// mis-parsed as a direction keyword. The name is optional — `
|
|
828
|
+
// mis-parsed as a direction keyword. The name is optional — `pg_get_function_identity_arguments`
|
|
819
829
|
// omits it for unnamed parameters (e.g. `text`), leaving just the type.
|
|
820
|
-
|
|
821
|
-
|
|
830
|
+
// 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`.
|
|
831
|
+
const match = /^(?:(INOUT|VARIADIC|IN|OUT)\s+)?(?:(?:"((?:[^"]|"")+)"|(?!(?:double\s+precision|character|bit|timestamp|time)(?![\w$]))([\w$]+))\s+)?(.+)$/is.exec(trimmed);
|
|
832
|
+
/* v8 ignore next 3: defensive guard for unexpected `pg_get_function_identity_arguments` output shapes */
|
|
822
833
|
if (!match) {
|
|
823
834
|
throw new Error(`Could not parse PostgreSQL routine parameter signature: ${JSON.stringify(trimmed)}`);
|
|
824
835
|
}
|
|
@@ -1183,7 +1194,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1183
1194
|
// child partitions are separate tables that don't move with the parent — park them too so their
|
|
1184
1195
|
// names are free for the new partitions
|
|
1185
1196
|
for (const partition of diff.fromTable.getPartitioning()?.partitions ?? []) {
|
|
1186
|
-
const partitionName = this.
|
|
1197
|
+
const partitionName = this.quoteTableName(partition.name, partition.schema ?? table.schema);
|
|
1187
1198
|
ret.push(`alter table ${partitionName} set schema ${this.quote(tmpSchema)}`);
|
|
1188
1199
|
}
|
|
1189
1200
|
// create the new partitioned table (+ partitions, indexes, checks)
|
|
@@ -1248,16 +1259,16 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1248
1259
|
const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
|
|
1249
1260
|
for (const col of changedEnums) {
|
|
1250
1261
|
if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.fromColumn.default) {
|
|
1251
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1262
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} drop default`);
|
|
1252
1263
|
}
|
|
1253
1264
|
if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.fromColumn.default) {
|
|
1254
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1265
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} drop default`);
|
|
1255
1266
|
}
|
|
1256
1267
|
}
|
|
1257
1268
|
// changing uuid column type requires to cast it to text first
|
|
1258
1269
|
const uuids = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid');
|
|
1259
1270
|
for (const col of uuids) {
|
|
1260
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1271
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} type text using (${this.quote(col.column.name)}::text)`);
|
|
1261
1272
|
}
|
|
1262
1273
|
for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
|
|
1263
1274
|
if (!column.autoincrement && column.default == null) {
|
|
@@ -1287,10 +1298,10 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1287
1298
|
const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
|
|
1288
1299
|
for (const col of changedEnums) {
|
|
1289
1300
|
if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
|
|
1290
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1301
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} set default ${col.column.default}`);
|
|
1291
1302
|
}
|
|
1292
1303
|
if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.column.default) {
|
|
1293
|
-
ret.push(`alter table ${quotedName} alter column
|
|
1304
|
+
ret.push(`alter table ${quotedName} alter column ${this.quote(col.column.name)} set default ${col.column.default}`);
|
|
1294
1305
|
}
|
|
1295
1306
|
}
|
|
1296
1307
|
for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
|
|
@@ -1479,7 +1490,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
1479
1490
|
join pg_namespace as ns on i.relnamespace = ns.oid
|
|
1480
1491
|
join pg_am as am on am.oid = i.relam
|
|
1481
1492
|
left join pg_constraint as c on c.conname = i.relname
|
|
1482
|
-
where indrelid in (${tables.map(t => `${this.platform.quoteValue(
|
|
1493
|
+
where indrelid in (${tables.map(t => `${this.platform.quoteValue(this.platform.quoteQualifiedName(t.table_name, t.schema_name))}::regclass`).join(', ')})
|
|
1483
1494
|
and (c.contype is null or c.contype <> 'x')
|
|
1484
1495
|
order by relname`;
|
|
1485
1496
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { NativeQueryBuilder } from '../../query/NativeQueryBuilder.js';
|
|
2
2
|
/** @internal */
|
|
3
3
|
export declare class SqliteNativeQueryBuilder extends NativeQueryBuilder {
|
|
4
|
+
protected readonly noLimit = "-1";
|
|
4
5
|
protected compileTruncate(): void;
|
|
5
6
|
protected addLockClause(): void;
|
|
6
7
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { NativeQueryBuilder } from '../../query/NativeQueryBuilder.js';
|
|
2
2
|
/** @internal */
|
|
3
3
|
export class SqliteNativeQueryBuilder extends NativeQueryBuilder {
|
|
4
|
+
noLimit = '-1';
|
|
4
5
|
compileTruncate() {
|
|
5
6
|
const sql = `delete from ${this.getTableName()}`;
|
|
6
7
|
this.parts.push(sql);
|
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.27",
|
|
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.9"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@mikro-orm/core": "^7.2.
|
|
53
|
+
"@mikro-orm/core": "^7.2.13"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@mikro-orm/core": "7.3.0-dev.
|
|
56
|
+
"@mikro-orm/core": "7.3.0-dev.27"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">= 22.17.0"
|
|
@@ -80,6 +80,8 @@ export declare class NativeQueryBuilder implements Subquery {
|
|
|
80
80
|
protected parts: string[];
|
|
81
81
|
protected params: unknown[];
|
|
82
82
|
protected options: Options;
|
|
83
|
+
/** Literal emitted as `limit` for offset-only queries, for dialects that reject `offset` without `limit`. */
|
|
84
|
+
protected readonly noLimit?: string;
|
|
83
85
|
constructor(platform: AbstractSqlPlatform);
|
|
84
86
|
select(fields: string | RawQueryFragment | (string | RawQueryFragment)[]): this;
|
|
85
87
|
count(fields?: string | RawQueryFragment | (string | RawQueryFragment)[], distinct?: boolean): this;
|
|
@@ -7,6 +7,8 @@ export class NativeQueryBuilder {
|
|
|
7
7
|
parts = [];
|
|
8
8
|
params = [];
|
|
9
9
|
options = {};
|
|
10
|
+
/** Literal emitted as `limit` for offset-only queries, for dialects that reject `offset` without `limit`. */
|
|
11
|
+
noLimit;
|
|
10
12
|
/** the table name or alias usable as a column qualifier (without the alias definition or index hint) */
|
|
11
13
|
#tableQualifier;
|
|
12
14
|
constructor(platform) {
|
|
@@ -348,6 +350,9 @@ export class NativeQueryBuilder {
|
|
|
348
350
|
this.parts.push(`limit ?`);
|
|
349
351
|
this.params.push(this.options.limit);
|
|
350
352
|
}
|
|
353
|
+
else if (this.options.offset != null && this.noLimit) {
|
|
354
|
+
this.parts.push(`limit ${this.noLimit}`);
|
|
355
|
+
}
|
|
351
356
|
if (this.options.offset != null) {
|
|
352
357
|
this.parts.push(`offset ?`);
|
|
353
358
|
this.params.push(this.options.offset);
|
|
@@ -87,10 +87,13 @@ export class ObjectCriteriaNode extends CriteriaNode {
|
|
|
87
87
|
else {
|
|
88
88
|
sub.where({ [this.key]: payload });
|
|
89
89
|
}
|
|
90
|
+
// compiled lazily, so filters can still be applied to its joins, except inside a filter (those could cycle)
|
|
91
|
+
if (!options?.filter) {
|
|
92
|
+
sub.scheduleFilterCheck(`${parentMeta.className}.${this.key}`);
|
|
93
|
+
qb.scheduleSubQueryFilterCheck(sub, ownerAlias);
|
|
94
|
+
}
|
|
90
95
|
const op = ['$size', '$some'].includes(key) ? '$in' : '$nin';
|
|
91
|
-
$and.push({
|
|
92
|
-
[Utils.getPrimaryKeyHash(primaryKeys)]: { [op]: sub.getNativeQuery().toRaw() },
|
|
93
|
-
});
|
|
96
|
+
$and.push({ [Utils.getPrimaryKeyHash(primaryKeys)]: { [op]: sub } });
|
|
94
97
|
}
|
|
95
98
|
if (matchNothing) {
|
|
96
99
|
$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,17 +407,32 @@ 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) {
|
|
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
|
+
};
|
|
413
429
|
for (const path of this.#state.autoJoinedPaths) {
|
|
414
430
|
const join = this.getJoinForPath(path);
|
|
415
431
|
if (join.type === JoinType.pivotJoin) {
|
|
416
432
|
continue;
|
|
417
433
|
}
|
|
418
|
-
|
|
419
|
-
let cond = await em.applyFilters(join.prop.targetMeta.class, join.cond,
|
|
434
|
+
const joinFilters = getJoinFilters(join);
|
|
435
|
+
let cond = await em.applyFilters(join.prop.targetMeta.class, join.cond, joinFilters, 'read');
|
|
420
436
|
const criteriaNode = CriteriaNodeFactory.createNode(this.metadata, join.prop.targetMeta.class, cond);
|
|
421
437
|
cond = criteriaNode.process(this, {
|
|
422
438
|
matchPopulateJoins: true,
|
|
@@ -463,6 +479,10 @@ export class QueryBuilder {
|
|
|
463
479
|
}
|
|
464
480
|
}
|
|
465
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
|
+
}
|
|
466
486
|
}
|
|
467
487
|
/**
|
|
468
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,11 @@ export class DatabaseTable {
|
|
|
33
33
|
this.#platform = platform;
|
|
34
34
|
}
|
|
35
35
|
getQuotedName() {
|
|
36
|
-
|
|
36
|
+
// a dot in the name can be a `database.schema.table` qualifier, it is kept inside the identifier in the default schema only
|
|
37
|
+
if (this.schema && this.schema !== this.#platform.getDefaultSchemaName()) {
|
|
38
|
+
return this.#platform.quoteIdentifier(this.getShortestName()).replaceAll('\\?', '?');
|
|
39
|
+
}
|
|
40
|
+
return this.#platform.quoteQualifiedName(this.name);
|
|
37
41
|
}
|
|
38
42
|
getColumns() {
|
|
39
43
|
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) {
|
|
@@ -283,12 +301,15 @@ export class SchemaComparator {
|
|
|
283
301
|
}
|
|
284
302
|
/** Engines drop length/precision modifiers and use different aliases for the same logical type — canonicalise both sides. */
|
|
285
303
|
normaliseParamType(type) {
|
|
286
|
-
const
|
|
287
|
-
const
|
|
304
|
+
const lower = type.trim().toLowerCase();
|
|
305
|
+
const array = /\[\d*\]$/.test(lower);
|
|
306
|
+
const element = array ? lower.slice(0, lower.indexOf('[')) : lower;
|
|
307
|
+
const open = element.indexOf('(');
|
|
308
|
+
const close = element.indexOf(')', open);
|
|
309
|
+
const stripped = open < 0 || close < 0 ? element : element.slice(0, open) + element.slice(close + 1);
|
|
310
|
+
const base = stripped.replace(/\s+/g, ' ').trim();
|
|
288
311
|
const aliased = SchemaComparator.PARAM_TYPE_ALIASES[base] ?? base;
|
|
289
|
-
|
|
290
|
-
const options = Number.isFinite(length) ? { length } : {};
|
|
291
|
-
return this.#platform.normalizeColumnType(aliased, options).toLowerCase();
|
|
312
|
+
return this.#platform.normalizeColumnType(aliased, {}).toLowerCase() + (array ? '[]' : '');
|
|
292
313
|
}
|
|
293
314
|
static PARAM_TYPE_ALIASES = {
|
|
294
315
|
int: 'integer',
|
|
@@ -297,7 +318,11 @@ export class SchemaComparator {
|
|
|
297
318
|
int2: 'smallint',
|
|
298
319
|
bool: 'boolean',
|
|
299
320
|
'character varying': 'varchar',
|
|
321
|
+
character: 'char',
|
|
300
322
|
bpchar: 'char',
|
|
323
|
+
'bit varying': 'varbit',
|
|
324
|
+
'time without time zone': 'time',
|
|
325
|
+
'timestamp without time zone': 'timestamp',
|
|
301
326
|
float8: 'double precision',
|
|
302
327
|
float4: 'real',
|
|
303
328
|
// Oracle's USER_ARGUMENTS reports `REF CURSOR`; users declare `sys_refcursor`.
|
package/schema/SchemaHelper.d.ts
CHANGED
|
@@ -204,6 +204,8 @@ export declare abstract class SchemaHelper {
|
|
|
204
204
|
/** Returns SQL to create a foreign key constraint on a table. */
|
|
205
205
|
createForeignKey(table: DatabaseTable, foreignKey: ForeignKey, alterTable?: boolean, inline?: boolean): string;
|
|
206
206
|
splitTableName(name: string, skipDefaultSchema?: boolean): [string | undefined, string];
|
|
207
|
+
/** Splits a developer-supplied name on the last dot, the qualifier can have more parts (`database.schema`). */
|
|
208
|
+
splitQualifiedName(name: string): [string | undefined, string];
|
|
207
209
|
getReferencedTableName(referencedTableName: string, schema?: string): string;
|
|
208
210
|
createIndex(index: IndexDef, table: DatabaseTable, createPrimary?: boolean): string;
|
|
209
211
|
createCheck(table: DatabaseTable, check: CheckDef): string;
|
|
@@ -239,6 +241,8 @@ export declare abstract class SchemaHelper {
|
|
|
239
241
|
get options(): NonNullable<Options['schemaGenerator']>;
|
|
240
242
|
protected processComment(comment: string): string;
|
|
241
243
|
protected quote(...keys: (string | undefined)[]): string;
|
|
244
|
+
/** A dot in the name stays inside the identifier in the default schema only, elsewhere it can be a `database.schema.table` qualifier. */
|
|
245
|
+
protected quoteTableName(name: string, schema?: string): string;
|
|
242
246
|
dropForeignKey(tableName: string, constraintName: string): string;
|
|
243
247
|
dropIndex(table: string, index: IndexDef, oldIndexName?: string): string;
|
|
244
248
|
dropConstraint(table: string, name: string): string;
|
package/schema/SchemaHelper.js
CHANGED
|
@@ -925,6 +925,11 @@ export class SchemaHelper {
|
|
|
925
925
|
}
|
|
926
926
|
return [schemaName, tableName];
|
|
927
927
|
}
|
|
928
|
+
/** Splits a developer-supplied name on the last dot, the qualifier can have more parts (`database.schema`). */
|
|
929
|
+
splitQualifiedName(name) {
|
|
930
|
+
const index = name.lastIndexOf('.');
|
|
931
|
+
return index === -1 ? [undefined, name] : [name.substring(0, index), name.substring(index + 1)];
|
|
932
|
+
}
|
|
928
933
|
getReferencedTableName(referencedTableName, schema) {
|
|
929
934
|
const [schemaName, tableName] = this.splitTableName(referencedTableName);
|
|
930
935
|
schema = schemaName ?? schema ?? this.platform.getConfig().get('schema');
|
|
@@ -1065,6 +1070,13 @@ export class SchemaHelper {
|
|
|
1065
1070
|
// DDL is not a query template, so question marks need no escaping there
|
|
1066
1071
|
return this.platform.quoteIdentifier(keys.filter(Boolean).join('.')).replaceAll('\\?', '?');
|
|
1067
1072
|
}
|
|
1073
|
+
/** A dot in the name stays inside the identifier in the default schema only, elsewhere it can be a `database.schema.table` qualifier. */
|
|
1074
|
+
quoteTableName(name, schema) {
|
|
1075
|
+
if (schema && schema !== this.platform.getDefaultSchemaName()) {
|
|
1076
|
+
return this.quote(schema, name);
|
|
1077
|
+
}
|
|
1078
|
+
return this.platform.quoteQualifiedName(name);
|
|
1079
|
+
}
|
|
1068
1080
|
dropForeignKey(tableName, constraintName) {
|
|
1069
1081
|
return `alter table ${this.quote(tableName)} drop foreign key ${this.quote(constraintName)}`;
|
|
1070
1082
|
}
|
|
@@ -1079,18 +1091,18 @@ export class SchemaHelper {
|
|
|
1079
1091
|
}
|
|
1080
1092
|
/** Returns SQL to drop a table if it exists. */
|
|
1081
1093
|
dropTableIfExists(name, schema) {
|
|
1082
|
-
let sql = `drop table if exists ${this.
|
|
1094
|
+
let sql = `drop table if exists ${this.quoteTableName(name, schema)}`;
|
|
1083
1095
|
if (this.platform.usesCascadeStatement()) {
|
|
1084
1096
|
sql += ' cascade';
|
|
1085
1097
|
}
|
|
1086
1098
|
return sql;
|
|
1087
1099
|
}
|
|
1088
1100
|
createView(name, schema, definition) {
|
|
1089
|
-
const viewName = this.
|
|
1101
|
+
const viewName = this.quoteTableName(name, schema);
|
|
1090
1102
|
return `create view ${viewName} as ${definition}`;
|
|
1091
1103
|
}
|
|
1092
1104
|
dropViewIfExists(name, schema) {
|
|
1093
|
-
let sql = `drop view if exists ${this.
|
|
1105
|
+
let sql = `drop view if exists ${this.quoteTableName(name, schema)}`;
|
|
1094
1106
|
if (this.platform.usesCascadeStatement()) {
|
|
1095
1107
|
sql += ' cascade';
|
|
1096
1108
|
}
|
|
@@ -209,7 +209,8 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
|
|
|
209
209
|
}
|
|
210
210
|
}
|
|
211
211
|
if (options.dropMigrationsTable) {
|
|
212
|
-
|
|
212
|
+
const [schema, name] = this.helper.splitQualifiedName(this.config.get('migrations').tableName);
|
|
213
|
+
this.append(ret, this.helper.dropTableIfExists(name, schema ?? this.config.get('schema')));
|
|
213
214
|
}
|
|
214
215
|
return this.wrapSchema(ret, options);
|
|
215
216
|
}
|
|
@@ -528,7 +529,8 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
|
|
|
528
529
|
return false;
|
|
529
530
|
}
|
|
530
531
|
async dropTableIfExists(name, schema) {
|
|
531
|
-
const
|
|
532
|
+
const [schemaName, tableName] = schema ? [schema, name] : this.helper.splitQualifiedName(name);
|
|
533
|
+
const sql = this.helper.dropTableIfExists(tableName, schemaName);
|
|
532
534
|
return this.execute(sql);
|
|
533
535
|
}
|
|
534
536
|
wrapSchema(sql, options) {
|
package/typings.d.ts
CHANGED
|
@@ -298,6 +298,8 @@ export interface IQueryBuilder<T> {
|
|
|
298
298
|
withRecursive(name: string, query: AnyQueryBuilder | NativeQueryBuilder | RawQueryFragment, options?: CteOptions): this;
|
|
299
299
|
scheduleFilterCheck(path: string): void;
|
|
300
300
|
/** @internal */
|
|
301
|
+
scheduleSubQueryFilterCheck(qb: IQueryBuilder<any>, ownerAlias: string): void;
|
|
302
|
+
/** @internal */
|
|
301
303
|
ensureTPTJoins(): void;
|
|
302
304
|
/** @internal */
|
|
303
305
|
addPolymorphicJoin(prop: EntityProperty, targetMeta: EntityMetadata, ownerAlias: string, alias: string, type: JoinType, path: string, schema?: string): void;
|