@mikro-orm/sql 7.2.13-dev.8 → 7.2.13

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.
@@ -99,10 +99,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
99
99
  }
100
100
  }
101
101
  if (options.collation != null && typeof options.collation !== 'string') {
102
- throw new Error('Collation option for SQL drivers must be a string (collation name). Use a CollationOptions object only with MongoDB.');
102
+ throw new ValidationError('Collation option for SQL drivers must be a string (collation name). Use a CollationOptions object only with MongoDB.');
103
103
  }
104
104
  if (options.indexHint != null && typeof options.indexHint !== 'string') {
105
- throw new Error("indexHint for SQL drivers must be a string (e.g. 'force index(my_index)'). Use an object only with MongoDB.");
105
+ throw new ValidationError("indexHint for SQL drivers must be a string (e.g. 'force index(my_index)'). Use an object only with MongoDB.");
106
106
  }
107
107
  }
108
108
  createEntityManager(useContext) {
@@ -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;
@@ -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);
@@ -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 \`${view.view_name}\``, [], 'all', ctx);
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.quote(this.getTableName(name, schema));
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.quote(this.getTableName(partition.name, partition.schema ?? table.schema));
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.quote(this.getTableName(name, schema))} cascade`;
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.quote(this.getTableName(name, schema))}`;
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 $$ begin ${this.normalizeTriggerBody(trigger.body)} end; $$ language plpgsql`;
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 $$ ${body} $$`;
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 $$ ${body} $$`;
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
- pg_get_function_arguments(p.oid) as arg_signature,
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 — `pg_get_function_arguments`
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
- const match = /^(?:(INOUT|VARIADIC|IN|OUT)\s+)?(?:(?:"((?:[^"]|"")+)"|([\w$]+))\s+)?(.+?)(?:\s+default\s+.+)?$/is.exec(trimmed);
800
- /* v8 ignore next 3: defensive guard for unexpected `pg_get_function_arguments` output shapes */
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.quote(this.getTableName(partition.name, partition.schema ?? table.schema));
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 "${col.column.name}" drop default`);
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 "${col.column.name}" drop default`);
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 "${col.column.name}" type text using ("${col.column.name}"::text)`);
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 "${col.column.name}" set default ${col.column.default}`);
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 "${col.column.name}" set default ${col.column.default}`);
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(`${this.quote(t.schema_name)}.${this.quote(t.table_name)}`)}::regclass`).join(', ')})
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.8",
3
+ "version": "7.2.13",
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.12"
53
+ "@mikro-orm/core": "^7.2.13"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.2.13-dev.8"
56
+ "@mikro-orm/core": "7.2.13"
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: [] } });
@@ -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
  */
@@ -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
- // nested joins inherit the overrides of their ancestor relations
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
@@ -33,7 +33,11 @@ export class DatabaseTable {
33
33
  this.#platform = platform;
34
34
  }
35
35
  getQuotedName() {
36
- return this.#platform.quoteIdentifier(this.getShortestName()).replaceAll('\\?', '?');
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
- const fromByKey = new Map(fromSchema.getRoutines().map(r => [routineKey(r), r]));
179
- const toByKey = new Map(toSchema.getRoutines().map(r => [routineKey(r), r]));
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 lengthMatch = /^([^()]+)\(([^)]*)\)\s*$/.exec(type);
287
- const base = (lengthMatch ? lengthMatch[1] : type).trim().toLowerCase();
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
- const length = lengthMatch ? Number.parseInt(lengthMatch[2].split(',')[0].trim(), 10) : NaN;
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`.
@@ -189,6 +189,8 @@ export declare abstract class SchemaHelper {
189
189
  /** Returns SQL to create a foreign key constraint on a table. */
190
190
  createForeignKey(table: DatabaseTable, foreignKey: ForeignKey, alterTable?: boolean, inline?: boolean): string;
191
191
  splitTableName(name: string, skipDefaultSchema?: boolean): [string | undefined, string];
192
+ /** Splits a developer-supplied name on the last dot, the qualifier can have more parts (`database.schema`). */
193
+ splitQualifiedName(name: string): [string | undefined, string];
192
194
  getReferencedTableName(referencedTableName: string, schema?: string): string;
193
195
  createIndex(index: IndexDef, table: DatabaseTable, createPrimary?: boolean): string;
194
196
  createCheck(table: DatabaseTable, check: CheckDef): string;
@@ -224,6 +226,8 @@ export declare abstract class SchemaHelper {
224
226
  get options(): NonNullable<Options['schemaGenerator']>;
225
227
  protected processComment(comment: string): string;
226
228
  protected quote(...keys: (string | undefined)[]): string;
229
+ /** A dot in the name stays inside the identifier in the default schema only, elsewhere it can be a `database.schema.table` qualifier. */
230
+ protected quoteTableName(name: string, schema?: string): string;
227
231
  dropForeignKey(tableName: string, constraintName: string): string;
228
232
  dropIndex(table: string, index: IndexDef, oldIndexName?: string): string;
229
233
  dropConstraint(table: string, name: string): string;
@@ -885,6 +885,11 @@ export class SchemaHelper {
885
885
  }
886
886
  return [schemaName, tableName];
887
887
  }
888
+ /** Splits a developer-supplied name on the last dot, the qualifier can have more parts (`database.schema`). */
889
+ splitQualifiedName(name) {
890
+ const index = name.lastIndexOf('.');
891
+ return index === -1 ? [undefined, name] : [name.substring(0, index), name.substring(index + 1)];
892
+ }
888
893
  getReferencedTableName(referencedTableName, schema) {
889
894
  const [schemaName, tableName] = this.splitTableName(referencedTableName);
890
895
  schema = schemaName ?? schema ?? this.platform.getConfig().get('schema');
@@ -1025,6 +1030,13 @@ export class SchemaHelper {
1025
1030
  // DDL is not a query template, so question marks need no escaping there
1026
1031
  return this.platform.quoteIdentifier(keys.filter(Boolean).join('.')).replaceAll('\\?', '?');
1027
1032
  }
1033
+ /** A dot in the name stays inside the identifier in the default schema only, elsewhere it can be a `database.schema.table` qualifier. */
1034
+ quoteTableName(name, schema) {
1035
+ if (schema && schema !== this.platform.getDefaultSchemaName()) {
1036
+ return this.quote(schema, name);
1037
+ }
1038
+ return this.platform.quoteQualifiedName(name);
1039
+ }
1028
1040
  dropForeignKey(tableName, constraintName) {
1029
1041
  return `alter table ${this.quote(tableName)} drop foreign key ${this.quote(constraintName)}`;
1030
1042
  }
@@ -1039,18 +1051,18 @@ export class SchemaHelper {
1039
1051
  }
1040
1052
  /** Returns SQL to drop a table if it exists. */
1041
1053
  dropTableIfExists(name, schema) {
1042
- let sql = `drop table if exists ${this.quote(this.getTableName(name, schema))}`;
1054
+ let sql = `drop table if exists ${this.quoteTableName(name, schema)}`;
1043
1055
  if (this.platform.usesCascadeStatement()) {
1044
1056
  sql += ' cascade';
1045
1057
  }
1046
1058
  return sql;
1047
1059
  }
1048
1060
  createView(name, schema, definition) {
1049
- const viewName = this.quote(this.getTableName(name, schema));
1061
+ const viewName = this.quoteTableName(name, schema);
1050
1062
  return `create view ${viewName} as ${definition}`;
1051
1063
  }
1052
1064
  dropViewIfExists(name, schema) {
1053
- let sql = `drop view if exists ${this.quote(this.getTableName(name, schema))}`;
1065
+ let sql = `drop view if exists ${this.quoteTableName(name, schema)}`;
1054
1066
  if (this.platform.usesCascadeStatement()) {
1055
1067
  sql += ' cascade';
1056
1068
  }
@@ -201,7 +201,8 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
201
201
  }
202
202
  }
203
203
  if (options.dropMigrationsTable) {
204
- this.append(ret, this.helper.dropTableIfExists(this.config.get('migrations').tableName, this.config.get('schema')));
204
+ const [schema, name] = this.helper.splitQualifiedName(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 sql = this.helper.dropTableIfExists(name, schema);
524
+ const [schemaName, tableName] = schema ? [schema, name] : this.helper.splitQualifiedName(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
  }