@mikro-orm/sql 7.3.0-dev.26 → 7.3.0-dev.28

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.
@@ -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 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.');
100
103
  }
101
104
  if (options.indexHint != null && typeof options.indexHint !== 'string') {
102
- 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.");
103
106
  }
104
107
  }
105
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);
@@ -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();
@@ -56,6 +56,7 @@ export declare class MySqlSchemaHelper extends SchemaHelper {
56
56
  private parseDataAccess;
57
57
  getAllTriggers(connection: AbstractSqlConnection, tables: Table[]): Promise<Dictionary<SqlTriggerDef[]>>;
58
58
  getAllForeignKeys(connection: AbstractSqlConnection, tables: Table[], ctx?: Transaction): Promise<Dictionary<Dictionary<ForeignKey>>>;
59
+ alterTable(diff: TableDifference, safe?: boolean): string[];
59
60
  getPreAlterTable(tableDiff: TableDifference, safe: boolean): string[];
60
61
  getRenameColumnSQL(tableName: string, oldColumnName: string, to: Column): string;
61
62
  getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string[];
@@ -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 \`${view.view_name}\``, [], 'all', ctx);
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']);
@@ -536,6 +536,33 @@ export class MySqlSchemaHelper extends SchemaHelper {
536
536
  });
537
537
  return ret;
538
538
  }
539
+ alterTable(diff, safe) {
540
+ const ret = super.alterTable(diff, safe);
541
+ const prefix = `alter table ${this.quote(diff.toTable.getShortestName())} `;
542
+ const mergeable = (sql) => sql.startsWith(prefix) && ret.includes(sql);
543
+ const fks = Object.values(diff.fromTable.getForeignKeys())
544
+ .map(fk => fk.columnNames[0])
545
+ .filter(col => !diff.removedColumns[col]);
546
+ const changed = Object.values(diff.changedIndexes);
547
+ const drops = [...Object.values(diff.removedIndexes), ...changed.map(idx => diff.fromTable.getIndex(idx.keyName))]
548
+ .filter(idx => !idx.primary && fks.includes(idx.columnNames[0]))
549
+ .map(idx => this.dropIndex(diff.name, idx))
550
+ .filter(mergeable);
551
+ const creates = [...Object.values(diff.addedIndexes), ...changed]
552
+ .map(idx => this.createIndex(idx, diff.toTable, true))
553
+ .filter(mergeable);
554
+ if (drops.length === 0 || creates.length === 0) {
555
+ return ret;
556
+ }
557
+ // an index backing a foreign key can only be dropped in the same statement that adds its replacement
558
+ const merged = prefix + [...drops, ...creates].map(sql => sql.slice(prefix.length)).join(', ');
559
+ return ret.flatMap(sql => {
560
+ if (sql === creates[0]) {
561
+ return [merged];
562
+ }
563
+ return drops.includes(sql) || creates.includes(sql) ? [] : [sql];
564
+ });
565
+ }
539
566
  getPreAlterTable(tableDiff, safe) {
540
567
  // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
541
568
  const pk = Object.values(tableDiff.removedIndexes).find(idx => idx.primary);
@@ -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.quote(this.getTableName(name, schema));
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.quote(this.getTableName(partition.name, partition.schema ?? table.schema));
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.quote(this.getTableName(name, schema))} cascade`;
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.quote(this.getTableName(name, schema))}`;
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 $$ begin ${this.normalizeTriggerBody(trigger.body)} end; $$ language plpgsql`;
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 $$ ${body} $$`;
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 $$ ${body} $$`;
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
- pg_get_function_arguments(p.oid) as arg_signature,
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 — `pg_get_function_arguments`
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
- const match = /^(?:(INOUT|VARIADIC|IN|OUT)\s+)?(?:(?:"((?:[^"]|"")+)"|([\w$]+))\s+)?(.+?)(?:\s+default\s+.+)?$/is.exec(trimmed);
821
- /* v8 ignore next 3: defensive guard for unexpected `pg_get_function_arguments` output shapes */
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.quote(this.getTableName(partition.name, partition.schema ?? table.schema));
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 "${col.column.name}" drop default`);
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 "${col.column.name}" drop default`);
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 "${col.column.name}" type text using ("${col.column.name}"::text)`);
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 "${col.column.name}" set default ${col.column.default}`);
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 "${col.column.name}" set default ${col.column.default}`);
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(`${this.quote(t.schema_name)}.${this.quote(t.table_name)}`)}::regclass`).join(', ')})
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.26",
3
+ "version": "7.3.0-dev.28",
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.3.0-dev.26"
56
+ "@mikro-orm/core": "7.3.0-dev.28"
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: [] } });
@@ -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
@@ -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.forEach((v) => params.push(v));
1001
- parts.push(`${lhs} ${replacement} (${val.map(() => '?').join(', ')})`);
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) && v.length > 0) {
1106
- if (typeof v[0] === 'number') {
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 v[0] === 'boolean') {
1125
+ if (typeof first === 'boolean') {
1110
1126
  return 'boolean';
1111
1127
  }
1112
1128
  }
@@ -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`.
@@ -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;
@@ -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.quote(this.getTableName(name, schema))}`;
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.quote(this.getTableName(name, schema));
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.quote(this.getTableName(name, schema))}`;
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
- this.append(ret, this.helper.dropTableIfExists(this.config.get('migrations').tableName, this.config.get('schema')));
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 sql = this.helper.dropTableIfExists(name, schema);
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;