@mikro-orm/sql 7.3.0-dev.22 → 7.3.0-dev.24

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.
@@ -251,6 +251,8 @@ export class AbstractSqlConnection extends Connection {
251
251
  await ctx.getExecutor().provideConnection(async () => undefined);
252
252
  }
253
253
  prepareQuery(query, params = []) {
254
+ // a plain string without params is not a template, so it is sent as is
255
+ const verbatim = typeof query === 'string' && Array.isArray(params) && params.length === 0;
254
256
  if (query instanceof NativeQueryBuilder) {
255
257
  query = query.toRaw();
256
258
  }
@@ -263,7 +265,7 @@ export class AbstractSqlConnection extends Connection {
263
265
  query = query.sql;
264
266
  }
265
267
  query = this.config.get('onQuery')(query, params);
266
- const formatted = this.platform.formatQuery(query, params);
268
+ const formatted = verbatim ? query : this.platform.formatQuery(query, params);
267
269
  return { query, params: params, formatted };
268
270
  }
269
271
  /** Executes a SQL query and returns the result based on the method: `'all'` for rows, `'get'` for single row, `'run'` for affected count. */
@@ -51,6 +51,9 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
51
51
  */
52
52
  private mapTPTColumns;
53
53
  private mapJoinedProps;
54
+ /** Keys are marked consumed, not deleted per row: deletes are slow and shared FK columns must stay readable. */
55
+ private resolveJoinedTargets;
56
+ private aliasedKeys;
54
57
  /**
55
58
  * Maps a single property from a joined result row into the relation pojo.
56
59
  * Handles polymorphic FKs, composite keys, Date parsing, and embedded objects.
@@ -1,4 +1,4 @@
1
- import { ALIAS_REPLACEMENT_RE, DatabaseDriver, 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, } 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';
@@ -43,7 +43,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
43
43
  /** Evaluates a formula callback, handling both string and Raw return values. */
44
44
  evaluateFormula(formula, columns, table) {
45
45
  const result = formula(columns, table);
46
- return isRaw(result) ? this.platform.formatQuery(result.sql, result.params) : result;
46
+ return isRaw(result) ? this.platform.quoteIdentifier(result) : result;
47
47
  }
48
48
  /** For TPT entities, returns ownProps (columns in this table); otherwise returns all props. */
49
49
  getTableProps(meta) {
@@ -224,10 +224,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
224
224
  return this.wrapVirtualExpressionInSubquery(meta, res, where, options, type);
225
225
  }
226
226
  if (res instanceof QueryBuilder) {
227
- return this.wrapVirtualExpressionInSubquery(meta, res.getFormattedQuery(), where, options, type);
227
+ return this.wrapVirtualExpressionInSubquery(meta, this.platform.quoteIdentifier(res.toRaw()), where, options, type);
228
228
  }
229
229
  if (isRaw(res)) {
230
- const expr = this.platform.formatQuery(res.sql, res.params);
230
+ const expr = this.platform.quoteIdentifier(res);
231
231
  return this.wrapVirtualExpressionInSubquery(meta, expr, where, options, type);
232
232
  }
233
233
  /* v8 ignore next */
@@ -252,11 +252,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
252
252
  return;
253
253
  }
254
254
  if (res instanceof QueryBuilder) {
255
- yield* this.wrapVirtualExpressionInSubqueryStream(meta, res.getFormattedQuery(), where, options, QueryType.SELECT);
255
+ yield* this.wrapVirtualExpressionInSubqueryStream(meta, this.platform.quoteIdentifier(res.toRaw()), where, options, QueryType.SELECT);
256
256
  return;
257
257
  }
258
258
  if (isRaw(res)) {
259
- const expr = this.platform.formatQuery(res.sql, res.params);
259
+ const expr = this.platform.quoteIdentifier(res);
260
260
  yield* this.wrapVirtualExpressionInSubqueryStream(meta, expr, where, options, QueryType.SELECT);
261
261
  return;
262
262
  }
@@ -273,18 +273,17 @@ export class AbstractSqlDriver extends DatabaseDriver {
273
273
  }
274
274
  const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
275
275
  native.from(raw(`(${expression})${asKeyword}${this.platform.quoteIdentifier(qb.alias)}`));
276
- const query = native.compile();
277
276
  const loggerContext = withAbortContext(options.loggerContext, options);
278
277
  // virtual entities execute directly (not via QueryBuilder), so wrap in a short implicit transaction outside an
279
278
  // existing one when a session context (row level security) needs to apply — mirrors the QueryBuilder wrap
280
279
  const sessionContext = options.ctx ? undefined : options.em?.getTransactionSessionContext();
281
280
  const conn = this.getConnection(this.resolveConnectionType(options));
282
281
  const res = await (sessionContext
283
- ? conn.transactional(trx => this.execute(query.sql, query.params, 'all', trx, loggerContext), {
282
+ ? conn.transactional(trx => this.execute(native, [], 'all', trx, loggerContext), {
284
283
  sessionContext,
285
284
  loggerContext,
286
285
  })
287
- : this.execute(query.sql, query.params, 'all', options.ctx, loggerContext));
286
+ : this.execute(native, [], 'all', options.ctx, loggerContext));
288
287
  if (type === QueryType.COUNT) {
289
288
  return res[0].count;
290
289
  }
@@ -299,9 +298,8 @@ export class AbstractSqlDriver extends DatabaseDriver {
299
298
  const native = qb.getNativeQuery(false);
300
299
  const asKeyword = this.platform.usesAsKeyword() ? ' as ' : ' ';
301
300
  native.from(raw(`(${expression})${asKeyword}${this.platform.quoteIdentifier(qb.alias)}`));
302
- const query = native.compile();
303
301
  const connectionType = this.resolveConnectionType({ ctx: options.ctx, connectionType: options.connectionType });
304
- const res = this.getConnection(connectionType).stream(query.sql, query.params, options.ctx, withAbortContext(options.loggerContext, options), options.chunkSize);
302
+ const res = this.getConnection(connectionType).stream(native, [], options.ctx, withAbortContext(options.loggerContext, options), options.chunkSize);
305
303
  for await (const row of res) {
306
304
  yield this.mapResult(row, meta);
307
305
  }
@@ -342,11 +340,14 @@ export class AbstractSqlDriver extends DatabaseDriver {
342
340
  if (qb) {
343
341
  // here we map the aliased results (cartesian product) to an object graph
344
342
  this.mapJoinedProps(ret, meta, populate, qb, ret, map);
345
- // the aliased columns were deleted, which left the row in slow dictionary mode
343
+ // copy without the consumed aliased columns, deleting them would leave the row in slow dictionary mode
346
344
  if (populate.length > 0) {
347
345
  const clean = {};
346
+ const consumed = map.consumedKeys;
348
347
  for (const key in ret) {
349
- clean[key] = ret[key];
348
+ if (!consumed?.has(key)) {
349
+ clean[key] = ret[key];
350
+ }
350
351
  }
351
352
  return clean;
352
353
  }
@@ -421,7 +422,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
421
422
  const relationPojo = {};
422
423
  const tz = this.platform.getTimezone();
423
424
  for (const p of targetProps) {
424
- this.mapJoinedProp(relationPojo, p, relationAlias, root, tz, meta2);
425
+ this.mapJoinedProp(relationPojo, p, this.aliasedKeys(p, relationAlias), root, tz, meta2);
425
426
  }
426
427
  // For TPT base targets, map child-specific fields and resolve the
427
428
  // concrete class so the factory creates the correct subtype.
@@ -436,9 +437,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
436
437
  this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, targetPath);
437
438
  }
438
439
  // Clean up aliased columns for ALL targets (even non-matching ones)
440
+ const consumed = (map.consumedKeys ??= new Set());
439
441
  for (const p of targetProps) {
440
442
  for (const name of p.fieldNames) {
441
- delete root[`${relationAlias}__${name}`];
443
+ consumed.add(`${relationAlias}__${name}`);
442
444
  }
443
445
  }
444
446
  }
@@ -472,8 +474,9 @@ export class AbstractSqlDriver extends DatabaseDriver {
472
474
  const alias = `${relationAlias}__${prop.inverseJoinColumns[0]}`;
473
475
  item = root[alias];
474
476
  }
475
- prop.joinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
476
- prop.inverseJoinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
477
+ const consumed = (map.consumedKeys ??= new Set());
478
+ prop.joinColumns.forEach(name => consumed.add(`${relationAlias}__${name}`));
479
+ prop.inverseJoinColumns.forEach(name => consumed.add(`${relationAlias}__${name}`));
477
480
  result[prop.name] ??= [];
478
481
  if (item) {
479
482
  result[prop.name].push(item);
@@ -483,17 +486,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
483
486
  const mapToPk = !hint.dataOnly && !!(ref || prop.mapToPk);
484
487
  // all rows of a result share their columns, so resolve the mapped props once per join path
485
488
  const joinedTargets = (map.joinedTargets ??= {});
486
- const { targetProps, virtualProps } = (joinedTargets[path] ??= {
487
- targetProps: (mapToPk
488
- ? meta2.getPrimaryProps()
489
- : meta2.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []))).filter(prop => prop.fieldNames.some(name => typeof root[`${relationAlias}__${name}`] !== 'undefined')),
490
- virtualProps: meta2.props.filter(prop => !ref && prop.persist === false && prop.fieldNames),
491
- });
489
+ joinedTargets[path] ??= this.resolveJoinedTargets(meta2, hint, mapToPk, !!ref, relationAlias, root, map);
490
+ const targets = joinedTargets[path];
491
+ const { targetProps, targetKeys, pkKeys, virtualProps } = targets;
492
492
  // If the primary key value for the relation is null, we know we haven't joined to anything
493
493
  // and therefore we don't return any record (since all values would be null)
494
- const hasPK = meta2.getPrimaryProps().every(pk => pk.fieldNames.every(name => {
495
- return root[`${relationAlias}__${name}`] != null;
496
- }));
494
+ const hasPK = pkKeys.every(key => root[key] != null);
497
495
  if (!hasPK) {
498
496
  if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
499
497
  result[prop.name] = [];
@@ -501,10 +499,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
501
499
  if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
502
500
  result[prop.name] = null;
503
501
  }
504
- for (const prop of targetProps) {
505
- for (const name of prop.fieldNames) {
506
- delete root[`${relationAlias}__${name}`];
507
- }
502
+ // resolve nested join paths once, so their columns are dropped even when no row has this relation
503
+ if (hint.children?.length && !targets.childrenResolved) {
504
+ this.mapJoinedProps({}, meta2, hint.children, qb, root, map, path);
505
+ targets.childrenResolved = true;
508
506
  }
509
507
  return;
510
508
  }
@@ -521,18 +519,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
521
519
  }
522
520
  });
523
521
  const tz = this.platform.getTimezone();
524
- for (const prop of targetProps) {
525
- this.mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta2);
522
+ for (let i = 0; i < targetProps.length; i++) {
523
+ this.mapJoinedProp(relationPojo, targetProps[i], targetKeys[i], root, tz, meta2);
526
524
  }
527
525
  // Handle TPT polymorphic child fields - map fields from child table aliases
528
526
  this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root);
529
- // properties can be mapped to multiple places, e.g. when sharing a column in multiple FKs,
530
- // so we need to delete them after everything is mapped from given level
531
- for (const prop of targetProps) {
532
- for (const name of prop.fieldNames) {
533
- delete root[`${relationAlias}__${name}`];
534
- }
535
- }
536
527
  if (mapToPk) {
537
528
  const tmp = Object.values(relationPojo);
538
529
  /* v8 ignore next */
@@ -547,14 +538,34 @@ export class AbstractSqlDriver extends DatabaseDriver {
547
538
  }
548
539
  const populateChildren = hint.children || [];
549
540
  this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, path);
541
+ targets.childrenResolved = true;
550
542
  });
551
543
  }
544
+ /** Keys are marked consumed, not deleted per row: deletes are slow and shared FK columns must stay readable. */
545
+ resolveJoinedTargets(meta, hint, mapToPk, ref, relationAlias, root, map) {
546
+ const targetProps = (mapToPk
547
+ ? meta.getPrimaryProps()
548
+ : meta.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []))).filter(prop => prop.fieldNames.some(name => typeof root[`${relationAlias}__${name}`] !== 'undefined'));
549
+ const targetKeys = targetProps.map(prop => this.aliasedKeys(prop, relationAlias));
550
+ const consumed = (map.consumedKeys ??= new Set());
551
+ targetKeys.forEach(keys => keys.forEach(key => consumed.add(key)));
552
+ return {
553
+ targetProps,
554
+ targetKeys,
555
+ pkKeys: meta.getPrimaryProps().flatMap(pk => this.aliasedKeys(pk, relationAlias)),
556
+ virtualProps: meta.props.filter(prop => !ref && prop.persist === false && prop.fieldNames),
557
+ };
558
+ }
559
+ aliasedKeys(prop, relationAlias) {
560
+ return prop.fieldNames.map(name => `${relationAlias}__${name}`);
561
+ }
552
562
  /**
553
563
  * Maps a single property from a joined result row into the relation pojo.
554
564
  * Handles polymorphic FKs, composite keys, Date parsing, and embedded objects.
555
565
  */
556
- mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta, options) {
557
- if (prop.fieldNames.every(name => typeof root[`${relationAlias}__${name}`] === 'undefined')) {
566
+ mapJoinedProp(relationPojo, prop, keys, root, tz, meta, options) {
567
+ const row = root;
568
+ if (keys.every(key => typeof row[key] === 'undefined')) {
558
569
  return;
559
570
  }
560
571
  // inline embeddables are mapped via their flattened child props; mapping the embedded root prop
@@ -563,10 +574,8 @@ export class AbstractSqlDriver extends DatabaseDriver {
563
574
  return;
564
575
  }
565
576
  if (prop.polymorphic && prop.kind !== ReferenceKind.EMBEDDED) {
566
- const discriminatorAlias = `${relationAlias}__${prop.fieldNames[0]}`;
567
- const discriminatorValue = root[discriminatorAlias];
568
- const pkFieldNames = prop.fieldNames.slice(1);
569
- const pkValues = pkFieldNames.map(name => root[`${relationAlias}__${name}`]);
577
+ const discriminatorValue = row[keys[0]];
578
+ const pkValues = keys.slice(1).map(key => row[key]);
570
579
  const pkValue = pkValues.length === 1 ? pkValues[0] : pkValues;
571
580
  if (discriminatorValue != null && pkValue != null) {
572
581
  relationPojo[prop.name] = new PolymorphicRef(discriminatorValue, pkValue);
@@ -577,7 +586,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
577
586
  }
578
587
  else if (prop.fieldNames.length > 1) {
579
588
  // composite keys
580
- const fk = prop.fieldNames.map(name => root[`${relationAlias}__${name}`]);
589
+ const fk = keys.map(key => row[key]);
581
590
  // `mapFlatCompositePrimaryKey` collapses to a scalar when the target PK is a single prop
582
591
  // (e.g. a relation referencing a composite unique key on a single-PK target).
583
592
  const pk = Utils.mapFlatCompositePrimaryKey(fk, prop);
@@ -585,8 +594,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
585
594
  relationPojo[prop.name] = valid ? pk : null;
586
595
  }
587
596
  else if (prop.runtimeType === 'Date') {
588
- const alias = `${relationAlias}__${prop.fieldNames[0]}`;
589
- const value = root[alias];
597
+ const value = row[keys[0]];
590
598
  if (tz &&
591
599
  tz !== 'local' &&
592
600
  typeof value === 'string' &&
@@ -602,9 +610,13 @@ export class AbstractSqlDriver extends DatabaseDriver {
602
610
  relationPojo[prop.name] = value;
603
611
  }
604
612
  }
613
+ else if (prop.customType instanceof DateType) {
614
+ // tedious returns DATE columns as `Date`, map them to the string the entity holds, so the snapshot matches it
615
+ const value = row[keys[0]];
616
+ relationPojo[prop.name] = (value instanceof Date ? this.platform.convertDateToJSValue(value) : value);
617
+ }
605
618
  else {
606
- const alias = `${relationAlias}__${prop.fieldNames[0]}`;
607
- relationPojo[prop.name] = root[alias];
619
+ relationPojo[prop.name] = row[keys[0]];
608
620
  if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
609
621
  const item = parseJsonSafe(relationPojo[prop.name]);
610
622
  if (Array.isArray(item)) {
@@ -617,8 +629,8 @@ export class AbstractSqlDriver extends DatabaseDriver {
617
629
  }
618
630
  }
619
631
  if (options?.deleteFromRoot) {
620
- for (const name of prop.fieldNames) {
621
- delete root[`${relationAlias}__${name}`];
632
+ for (const key of keys) {
633
+ delete row[key];
622
634
  }
623
635
  }
624
636
  }
@@ -939,7 +951,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
939
951
  if (transform) {
940
952
  sql = transform(sql);
941
953
  }
942
- const res = await this.execute(sql, params, 'run', options.ctx, withAbortContext(options.loggerContext, options));
954
+ const res = await this.execute(raw(sql, params), [], 'run', options.ctx, withAbortContext(options.loggerContext, options));
943
955
  const pk = this.resolveInsertedPrimaryKeys(meta, data, res);
944
956
  for (let i = 0; i < collections.length; i++) {
945
957
  await this.processManyToMany(meta, pk[i], collections[i], false, options);
@@ -2109,7 +2121,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
2109
2121
  if (childAlias) {
2110
2122
  // Map fields using same filtering as joined loading, plus skip PKs
2111
2123
  for (const prop of currentMeta.ownProps.filter(p => !p.primary && this.platform.shouldHaveColumn(p, []))) {
2112
- this.mapJoinedProp(relationPojo, prop, childAlias, root, tz, currentMeta, {
2124
+ this.mapJoinedProp(relationPojo, prop, this.aliasedKeys(prop, childAlias), root, tz, currentMeta, {
2113
2125
  deleteFromRoot: true,
2114
2126
  });
2115
2127
  }
@@ -64,7 +64,7 @@ export class AbstractSqlPlatform extends Platform {
64
64
  qb.orderBy(through.orderBy);
65
65
  }
66
66
  qb.select(through.targetProperty ?? throughMeta.primaryKeys[0]).limit(1);
67
- const sql = qb.getFormattedQuery();
67
+ const sql = this.quoteIdentifier(qb.toRaw());
68
68
  if (Object.keys(qb.state.joins).length > 0) {
69
69
  throw new ValidationError(`The 'where' and 'orderBy' options of the through relation ${prop.name} can only reference own columns of ${throughMeta.className}`);
70
70
  }
@@ -105,7 +105,7 @@ export class AbstractSqlPlatform extends Platform {
105
105
  }
106
106
  getSearchJsonPropertyKey(path, type, aliased, value) {
107
107
  const [a, ...b] = path;
108
- const jsonPath = this.quoteValue(`$.${b.map(this.quoteJsonKey).join('.')}`);
108
+ const jsonPath = this.quoteValue(`$.${b.map(this.quoteJsonKey).join('.')}`).replaceAll('?', '\\?');
109
109
  if (typeof aliased === 'string') {
110
110
  return raw(`json_extract(${this.quoteIdentifier(`${aliased}.${a}`)}, ${jsonPath})`);
111
111
  }
@@ -81,7 +81,7 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
81
81
  return column;
82
82
  }
83
83
  const [root, ...path] = column.split('.');
84
- return `(json_value(${this.quoteIdentifier(root)}, '$.${path.join('.')}' returning ${index.options?.returning ?? 'char(255)'}))`;
84
+ return `(json_value(${this.quoteIdentifier(root).replaceAll('\\?', '?')}, '$.${path.join('.')}' returning ${index.options?.returning ?? 'char(255)'}))`;
85
85
  });
86
86
  }
87
87
  getBooleanTypeDeclarationSQL() {
@@ -133,7 +133,7 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
133
133
  const quotedTableName = this.quoteIdentifier(schemaName ? `${schemaName}.${tableName}` : tableName);
134
134
  const quotedColumnNames = columns.map(c => this.quoteIdentifier(c.name));
135
135
  const quotedIndexName = this.quoteIdentifier(indexName);
136
- return `alter table ${quotedTableName} add fulltext index ${quotedIndexName}(${quotedColumnNames.join(',')})`;
136
+ return `alter table ${quotedTableName} add fulltext index ${quotedIndexName}(${quotedColumnNames.join(',')})`.replaceAll('\\?', '?');
137
137
  }
138
138
  getOrderByExpression(column, direction, collation) {
139
139
  const ret = [];
@@ -350,12 +350,12 @@ export class MySqlSchemaHelper extends SchemaHelper {
350
350
  if (routine.expression) {
351
351
  return routine.expression;
352
352
  }
353
- const name = this.platform.quoteIdentifier(routine.name);
353
+ const name = this.quote(routine.name);
354
354
  // MySQL functions reject direction prefixes (function params are always IN); procedures use them.
355
355
  const params = routine.params
356
356
  .map(p => {
357
357
  const dir = routine.type === 'procedure' ? `${p.direction.toUpperCase()} ` : '';
358
- return `${dir}${this.platform.quoteIdentifier(p.name)} ${p.type}`;
358
+ return `${dir}${this.quote(p.name)} ${p.type}`;
359
359
  })
360
360
  .join(', ');
361
361
  const determinism = routine.deterministic === true ? ' deterministic' : routine.deterministic === false ? ' not deterministic' : '';
@@ -375,7 +375,7 @@ export class MySqlSchemaHelper extends SchemaHelper {
375
375
  }
376
376
  dropRoutine(routine) {
377
377
  const kind = routine.type === 'procedure' ? 'procedure' : 'function';
378
- return `drop ${kind} if exists ${this.platform.quoteIdentifier(routine.name)}`;
378
+ return `drop ${kind} if exists ${this.quote(routine.name)}`;
379
379
  }
380
380
  async getAllRoutines(connection) {
381
381
  const sql = `
@@ -588,12 +588,13 @@ export class MySqlSchemaHelper extends SchemaHelper {
588
588
  async getAllEnumDefinitions(connection, tables, ctx) {
589
589
  const sql = `select column_name as column_name, column_type as column_type, table_name as table_name
590
590
  from information_schema.columns
591
- where data_type = 'enum' and table_name in (${tables.map(t => `'${t.table_name}'`).join(', ')}) and table_schema = database()`;
591
+ where data_type = 'enum' and table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(', ')}) and table_schema = database()`;
592
592
  const enums = await connection.execute(sql, [], 'all', ctx);
593
593
  return enums.reduce((o, item) => {
594
- o[item.table_name] ??= {};
594
+ const key = this.getTableKey(item);
595
+ o[key] ??= {};
595
596
  // items can hold commas, doubled quotes and backslash escapes
596
- o[item.table_name][item.column_name] = [...item.column_type.matchAll(/'((?:''|\\.|[^'\\])*)'/g)].map(([, value]) => this.unescapeDefault(value.replaceAll("''", "'")));
597
+ o[key][item.column_name] = [...item.column_type.matchAll(/'((?:''|\\.|[^'\\])*)'/g)].map(([, value]) => this.unescapeDefault(value.replaceAll("''", "'")));
597
598
  return o;
598
599
  }, {});
599
600
  }
@@ -28,6 +28,7 @@ interface OracleResultSet<R> {
28
28
  declare class OracleQueryCompiler extends DefaultQueryCompiler {
29
29
  protected getLeftIdentifierWrapper(): string;
30
30
  protected getRightIdentifierWrapper(): string;
31
+ protected getCurrentParameterPlaceholder(): string;
31
32
  protected visitAlias(node: AliasNode): void;
32
33
  }
33
34
  declare class OracleAdapter extends DialectAdapterBase {
@@ -42,10 +43,6 @@ declare class OracleConnection implements DatabaseConnection {
42
43
  readonly id: number;
43
44
  constructor(connection: OraclePoolConnection, executeOptions?: Record<string, unknown>);
44
45
  executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>>;
45
- formatQuery(query: CompiledQuery): {
46
- sql: string;
47
- bindParams: unknown[];
48
- };
49
46
  streamQuery<R>(compiledQuery: CompiledQuery, chunkSize?: number): AsyncIterableIterator<QueryResult<R>>;
50
47
  get connection(): OraclePoolConnection;
51
48
  }
@@ -14,6 +14,9 @@ class OracleQueryCompiler extends DefaultQueryCompiler {
14
14
  getRightIdentifierWrapper() {
15
15
  return '';
16
16
  }
17
+ getCurrentParameterPlaceholder() {
18
+ return ':' + (this.numParameters - 1);
19
+ }
17
20
  visitAlias(node) {
18
21
  this.visitNode(node.node);
19
22
  this.append(' ');
@@ -47,8 +50,7 @@ class OracleConnection {
47
50
  this.#connection = connection;
48
51
  }
49
52
  async executeQuery(compiledQuery) {
50
- const { sql, bindParams } = this.formatQuery(compiledQuery);
51
- const result = await this.#connection.execute(sql, bindParams, {
53
+ const result = await this.#connection.execute(compiledQuery.sql, compiledQuery.parameters, {
52
54
  autoCommit: compiledQuery.autoCommit,
53
55
  outFormat: OUT_FORMAT_OBJECT,
54
56
  ...this.#executeOptions,
@@ -60,15 +62,8 @@ class OracleConnection {
60
62
  outBinds: result.outBinds,
61
63
  };
62
64
  }
63
- formatQuery(query) {
64
- return {
65
- sql: query.sql.replace(/\$(\d+)/g, (_match, p1) => `:${parseInt(p1, 10) - 1}`), // Format bind params in Oracle syntax :0, :1, etc.
66
- bindParams: query.parameters,
67
- };
68
- }
69
65
  async *streamQuery(compiledQuery, chunkSize) {
70
- const { sql, bindParams } = this.formatQuery(compiledQuery);
71
- const result = await this.#connection.execute(sql, bindParams, {
66
+ const result = await this.#connection.execute(compiledQuery.sql, compiledQuery.parameters, {
72
67
  resultSet: true,
73
68
  autoCommit: compiledQuery.autoCommit,
74
69
  outFormat: OUT_FORMAT_OBJECT,
@@ -98,7 +98,7 @@ export class OracleNativeQueryBuilder extends NativeQueryBuilder {
98
98
  }
99
99
  }
100
100
  // we need to interpolate to allow proper escaping
101
- const formatted = this.platform.formatQuery(sql, params).replaceAll(`'`, `''`);
101
+ const formatted = this.platform.formatQuery(sql, params).replaceAll(`'`, `''`).replaceAll('?', '\\?');
102
102
  /* v8 ignore next 3: returning field type branches */
103
103
  const using = this.options.returning.map(field => {
104
104
  const name = Array.isArray(field) ? field[0] : field;
@@ -119,9 +119,9 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
119
119
  const quotedColumnNames = columns.map(c => this.quoteIdentifier(c.name));
120
120
  const quotedIndexName = this.quoteIdentifier(indexName);
121
121
  if (columns.length === 1 && columns[0].type === 'tsvector') {
122
- return `create index ${quotedIndexName} on ${quotedTableName} using gin(${quotedColumnNames[0]})`;
122
+ return `create index ${quotedIndexName} on ${quotedTableName} using gin(${quotedColumnNames[0]})`.replaceAll('\\?', '?');
123
123
  }
124
- return `create index ${quotedIndexName} on ${quotedTableName} using gin(to_tsvector('simple', ${quotedColumnNames.join(` || ' ' || `)}))`;
124
+ return `create index ${quotedIndexName} on ${quotedTableName} using gin(to_tsvector('simple', ${quotedColumnNames.join(` || ' ' || `)}))`.replaceAll('\\?', '?');
125
125
  }
126
126
  normalizeColumnType(type, options) {
127
127
  const simpleType = this.extractSimpleType(type);
@@ -231,8 +231,9 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
231
231
  return ['begin'];
232
232
  }
233
233
  marshallArray(values) {
234
- const quote = (v) => (v === '' || /["{},\\]/.exec(v) ? JSON.stringify(v) : v);
235
- return `{${values.map(v => quote('' + v)).join(',')}}`;
234
+ // Quote what Postgres would read differently unquoted: empty, `NULL`, delimiters and surrounding whitespace.
235
+ const quote = (v) => v === '' || /^null$/i.test(v) || /["{},\\]|^\s|\s$/.test(v) ? `"${v.replace(/["\\]/g, '\\$&')}"` : v;
236
+ return `{${values.map(v => (v === null ? 'NULL' : quote('' + v))).join(',')}}`;
236
237
  }
237
238
  /* v8 ignore next */
238
239
  unmarshallArray(value) {
@@ -324,10 +325,11 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
324
325
  Object.keys(value).every(key => ARRAY_OPERATORS.includes(key) && Array.isArray(value[key]))) {
325
326
  lastOperator = '->';
326
327
  }
328
+ const quote = (key) => this.quoteValue(key).replaceAll('?', '\\?');
327
329
  if (path.length === 0) {
328
- return cast(`${root}${lastOperator}${this.quoteValue(last)}`);
330
+ return cast(`${root}${lastOperator}${quote(last)}`);
329
331
  }
330
- return cast(`${root}->${path.map(a => this.quoteValue(a)).join('->')}${lastOperator}${this.quoteValue(last)}`);
332
+ return cast(`${root}->${path.map(quote).join('->')}${lastOperator}${quote(last)}`);
331
333
  }
332
334
  getJsonIndexDefinition(index) {
333
335
  return index.columnNames.map(column => {
@@ -337,18 +339,22 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
337
339
  const path = column.split('.');
338
340
  const first = path.shift();
339
341
  const last = path.pop();
342
+ const root = this.quoteIdentifier(first).replaceAll('\\?', '?');
340
343
  if (path.length === 0) {
341
- return `(${this.quoteIdentifier(first)}->>${this.quoteValue(last)})`;
344
+ return `(${root}->>${this.quoteValue(last)})`;
342
345
  }
343
- return `(${this.quoteIdentifier(first)}->${path.map(c => this.quoteValue(c)).join('->')}->>${this.quoteValue(last)})`;
346
+ return `(${root}->${path.map(c => this.quoteValue(c)).join('->')}->>${this.quoteValue(last)})`;
344
347
  });
345
348
  }
346
349
  quoteIdentifier(id, quote = '"') {
347
350
  if (RawQueryFragment.isKnownFragment(id)) {
348
351
  return super.quoteIdentifier(id);
349
352
  }
350
- const escaped = id.toString().replaceAll(quote, quote + quote);
351
- return `${quote}${escaped.replace('.', `${quote}.${quote}`)}${quote}`;
353
+ const escaped = id
354
+ .toString()
355
+ .replaceAll(quote, quote + quote)
356
+ .replaceAll('?', '\\?');
357
+ return `${quote}${escaped.replaceAll('.', `${quote}.${quote}`)}${quote}`;
352
358
  }
353
359
  pad(number, digits) {
354
360
  return String(number).padStart(digits, '0');
@@ -112,7 +112,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
112
112
  // breaking a plain `table_name not in (...)` predicate).
113
113
  return (`select table_name, table_schema as schema_name, ` +
114
114
  `(select pg_catalog.obj_description(c.oid) from pg_catalog.pg_class c
115
- where c.oid = (select ('"' || table_schema || '"."' || table_name || '"')::regclass::oid) and c.relname = table_name) as table_comment ` +
115
+ where c.oid = (select format('%I.%I', table_schema, table_name)::regclass::oid) and c.relname = table_name) as table_comment ` +
116
116
  `from information_schema.tables t ` +
117
117
  `where ${this.getIgnoredNamespacesConditionSQL('table_schema')} ` +
118
118
  `and table_name != 'geometry_columns' and table_name != 'spatial_ref_sys' and table_type != 'VIEW' ` +
@@ -619,14 +619,14 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
619
619
  const forEach = trigger.forEach === 'statement' ? 'STATEMENT' : 'ROW';
620
620
  const when = trigger.when ? `\n when (${trigger.when})` : '';
621
621
  const fnName = this.getSchemaQualifiedTriggerFnName(table, trigger);
622
- const triggerName = this.platform.quoteIdentifier(trigger.name);
622
+ const triggerName = this.quote(trigger.name);
623
623
  const fnSql = `create or replace function ${fnName}() returns trigger as $$ 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
  }
627
627
  /** Generates SQL to drop a PostgreSQL trigger and its associated function. */
628
628
  dropTrigger(table, trigger) {
629
- const triggerName = this.platform.quoteIdentifier(trigger.name);
629
+ const triggerName = this.quote(trigger.name);
630
630
  const fnName = this.getSchemaQualifiedTriggerFnName(table, trigger);
631
631
  return `drop trigger if exists ${triggerName} on ${table.getQuotedName()};\ndrop function if exists ${fnName}()`;
632
632
  }
@@ -803,7 +803,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
803
803
  .map(p => {
804
804
  const dir = p.direction === 'in' ? '' : `${p.direction.toUpperCase()} `;
805
805
  const def = p.defaultRaw ? ` default ${p.defaultRaw}` : '';
806
- const name = p.name ? `${this.platform.quoteIdentifier(p.name)} ` : '';
806
+ const name = p.name ? `${this.quote(p.name)} ` : '';
807
807
  return `${dir}${name}${p.type}${def}`;
808
808
  })
809
809
  .join(', ');
@@ -817,7 +817,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
817
817
  // INOUT before IN/OUT, with required trailing space so identifiers like `input` aren't
818
818
  // mis-parsed as a direction keyword. The name is optional — `pg_get_function_arguments`
819
819
  // 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+.+)?$/i.exec(trimmed);
820
+ const match = /^(?:(INOUT|VARIADIC|IN|OUT)\s+)?(?:(?:"((?:[^"]|"")+)"|([\w$]+))\s+)?(.+?)(?:\s+default\s+.+)?$/is.exec(trimmed);
821
821
  /* v8 ignore next 3: defensive guard for unexpected `pg_get_function_arguments` output shapes */
822
822
  if (!match) {
823
823
  throw new Error(`Could not parse PostgreSQL routine parameter signature: ${JSON.stringify(trimmed)}`);
@@ -841,9 +841,9 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
841
841
  const rawName = `${table.name}_${trigger.name}_fn`;
842
842
  const defaultSchema = this.platform.getDefaultSchemaName();
843
843
  if (table.schema && table.schema !== defaultSchema) {
844
- return `${this.platform.quoteIdentifier(table.schema)}.${this.platform.quoteIdentifier(rawName)}`;
844
+ return `${this.quote(table.schema)}.${this.quote(rawName)}`;
845
845
  }
846
- return this.platform.quoteIdentifier(rawName);
846
+ return this.quote(rawName);
847
847
  }
848
848
  /**
849
849
  * Resolves the real name of the implicit 'default' collation (the DB's `datcollate`),
@@ -1331,18 +1331,20 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1331
1331
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
1332
1332
  if (column.autoincrement) {
1333
1333
  const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
1334
+ // the regclass text needs the quoted name too, otherwise postgres folds a mixed case name to lower case
1335
+ const seq = this.platform.quoteValue(this.quote(seqName));
1334
1336
  const sequenceOptions = this.getSequenceOptionsSQL(column);
1335
1337
  const { incrementBy = 1, startWith = incrementBy < 0 ? -1 : 1 } = column.sequence ?? {};
1336
1338
  const lastValue = `(select ${incrementBy < 0 ? 'min' : 'max'}(${this.quote(column.name)}) from ${this.quote(name)})`;
1337
1339
  ret.push(`create sequence if not exists ${this.quote(seqName)}${sequenceOptions ? ` ${sequenceOptions}` : ''}`);
1338
1340
  if (sequenceOptions) {
1339
1341
  // continue after the existing values, but never before the declared start
1340
- ret.push(`select setval('${seqName}', ${incrementBy < 0 ? 'least' : 'greatest'}(${lastValue} + ${incrementBy}, ${startWith}), false)`);
1342
+ ret.push(`select setval(${seq}, ${incrementBy < 0 ? 'least' : 'greatest'}(${lastValue} + ${incrementBy}, ${startWith}), false)`);
1341
1343
  }
1342
1344
  else {
1343
- ret.push(`select setval('${seqName}', ${lastValue})`);
1345
+ ret.push(`select setval(${seq}, ${lastValue})`);
1344
1346
  }
1345
- ret.push(`alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval('${seqName}')`);
1347
+ ret.push(`alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval(${seq})`);
1346
1348
  }
1347
1349
  return ret;
1348
1350
  }
@@ -29,7 +29,7 @@ export class BaseSqliteConnection extends AbstractSqlConnection {
29
29
  const baseDir = this.config.get('baseDir');
30
30
  return attachDatabases.map(db => {
31
31
  const path = fs.absolutePath(db.path, baseDir);
32
- return `attach database '${path}' as ${this.platform.quoteIdentifier(db.name)}`;
32
+ return `attach database '${path}' as ${this.platform.quoteIdentifier(db.name).replaceAll('\\?', '?')}`;
33
33
  });
34
34
  }
35
35
  }
@@ -258,8 +258,9 @@ export class SqliteSchemaHelper extends SchemaHelper {
258
258
  }
259
259
  for (let i = cols.length - 1; i >= 0; i--) {
260
260
  const col = cols[i];
261
+ const name = col.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
261
262
  // the first column is not preceded by a comma
262
- const re = ` *(?:^|,) *[\`"']?${col.name}[\`"']? (.*)`;
263
+ const re = ` *(?:^|,) *[\`"']?${name}[\`"']? (.*)`;
263
264
  const columnDef = new RegExp(re, 'i').exec(columnsDef);
264
265
  if (columnDef) {
265
266
  columns[col.name] = { name: col.name, definition: columnDef[1] };
@@ -277,7 +278,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
277
278
  if (!schemaName || schemaName === 'main') {
278
279
  return '';
279
280
  }
280
- return `${this.platform.quoteIdentifier(schemaName)}.`;
281
+ return `${this.quote(schemaName)}.`;
281
282
  }
282
283
  /**
283
284
  * Returns all database names excluding 'temp'.
@@ -296,7 +297,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
296
297
  }
297
298
  async getColumns(connection, tableName, schemaName, ctx) {
298
299
  const prefix = this.getSchemaPrefix(schemaName);
299
- const columns = await connection.execute(`pragma ${prefix}table_xinfo('${tableName}')`, [], 'all', ctx);
300
+ const columns = await connection.execute(`pragma ${prefix}table_xinfo(${this.platform.quoteValue(tableName)})`, [], 'all', ctx);
300
301
  const sql = `select sql from ${prefix}sqlite_master where type = ? and name = ?`;
301
302
  const tableDefinition = await connection.execute(sql, ['table', tableName], 'get', ctx);
302
303
  const composite = columns.reduce((count, col) => count + (col.pk ? 1 : 0), 0) > 1;
@@ -383,15 +384,15 @@ export class SqliteSchemaHelper extends SchemaHelper {
383
384
  }
384
385
  async getPrimaryKeys(connection, indexes, tableName, schemaName, ctx) {
385
386
  const prefix = this.getSchemaPrefix(schemaName);
386
- const sql = `pragma ${prefix}table_info(\`${tableName}\`)`;
387
+ const sql = `pragma ${prefix}table_info(${this.platform.quoteValue(tableName)})`;
387
388
  const cols = await connection.execute(sql, [], 'all', ctx);
388
389
  return cols.filter(col => !!col.pk).map(col => col.name);
389
390
  }
390
391
  async getIndexes(connection, tableName, schemaName, ctx) {
391
392
  const prefix = this.getSchemaPrefix(schemaName);
392
- const sql = `pragma ${prefix}table_info(\`${tableName}\`)`;
393
+ const sql = `pragma ${prefix}table_info(${this.platform.quoteValue(tableName)})`;
393
394
  const cols = await connection.execute(sql, [], 'all', ctx);
394
- const indexes = await connection.execute(`pragma ${prefix}index_list(\`${tableName}\`)`, [], 'all', ctx);
395
+ const indexes = await connection.execute(`pragma ${prefix}index_list(${this.platform.quoteValue(tableName)})`, [], 'all', ctx);
395
396
  // sqlite_master.sql holds the original CREATE INDEX statement — the only place a partial
396
397
  // index's WHERE predicate is preserved (PRAGMA index_* don't expose it).
397
398
  const indexSqls = await connection.execute(`select name, sql from ${prefix}sqlite_master where type = 'index' and tbl_name = ?`, [tableName], 'all', ctx);
@@ -413,7 +414,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
413
414
  });
414
415
  }
415
416
  for (const index of indexes.filter(index => !this.isImplicitIndex(index.name))) {
416
- const res = await connection.execute(`pragma ${prefix}index_info(\`${index.name}\`)`, [], 'all', ctx);
417
+ const res = await connection.execute(`pragma ${prefix}index_info(${this.platform.quoteValue(index.name)})`, [], 'all', ctx);
417
418
  const where = wherePredicates.get(index.name);
418
419
  ret.push(...res.map(row => ({
419
420
  columnNames: [row.name],
@@ -455,7 +456,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
455
456
  }
456
457
  async getColumnDefinitions(connection, tableName, schemaName, ctx) {
457
458
  const prefix = this.getSchemaPrefix(schemaName);
458
- const columns = await connection.execute(`pragma ${prefix}table_xinfo('${tableName}')`, [], 'all', ctx);
459
+ const columns = await connection.execute(`pragma ${prefix}table_xinfo(${this.platform.quoteValue(tableName)})`, [], 'all', ctx);
459
460
  const sql = `select sql from ${prefix}sqlite_master where type = ? and name = ?`;
460
461
  const tableDefinition = await connection.execute(sql, ['table', tableName], 'get', ctx);
461
462
  return this.parseTableDefinition(tableDefinition.sql, columns);
@@ -463,7 +464,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
463
464
  async getForeignKeys(connection, tableName, schemaName, ctx) {
464
465
  const { constraints } = await this.getColumnDefinitions(connection, tableName, schemaName, ctx);
465
466
  const prefix = this.getSchemaPrefix(schemaName);
466
- const fks = await connection.execute(`pragma ${prefix}foreign_key_list(\`${tableName}\`)`, [], 'all', ctx);
467
+ const fks = await connection.execute(`pragma ${prefix}foreign_key_list(${this.platform.quoteValue(tableName)})`, [], 'all', ctx);
467
468
  const qualifiedTableName = schemaName ? `${schemaName}.${tableName}` : tableName;
468
469
  return fks.reduce((ret, fk) => {
469
470
  const constraintName = this.platform.getIndexName(tableName, [fk.from], 'foreign');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/sql",
3
- "version": "7.3.0-dev.22",
3
+ "version": "7.3.0-dev.24",
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",
@@ -47,13 +47,13 @@
47
47
  "copy": "node ../../scripts/copy.mjs"
48
48
  },
49
49
  "dependencies": {
50
- "kysely": "0.29.8"
50
+ "kysely": "0.29.9"
51
51
  },
52
52
  "devDependencies": {
53
- "@mikro-orm/core": "^7.2.9"
53
+ "@mikro-orm/core": "^7.2.11"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.3.0-dev.22"
56
+ "@mikro-orm/core": "7.3.0-dev.24"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">= 22.17.0"
@@ -581,7 +581,9 @@ export class MikroTransformer extends OperationNodeTransformer {
581
581
  return out;
582
582
  }
583
583
  wrapRead(customType, fieldName, tableName) {
584
- const key = this.#platform.quoteIdentifier(tableName ? `${tableName}.${fieldName}` : fieldName);
584
+ const key = this.#platform
585
+ .quoteIdentifier(tableName ? `${tableName}.${fieldName}` : fieldName)
586
+ .replaceAll('\\?', '?');
585
587
  const sql = customType.convertToJSValueSQL(key, this.#platform);
586
588
  return SelectionNode.create(AliasNode.create(RawNode.createWithSql(sql), IdentifierNode.create(fieldName)));
587
589
  }
@@ -525,11 +525,10 @@ export class NativeQueryBuilder {
525
525
  }
526
526
  quote(id) {
527
527
  if (isRaw(id)) {
528
- return this.platform.formatQuery(id.sql, id.params);
528
+ return this.platform.quoteIdentifier(id);
529
529
  }
530
530
  if (id instanceof NativeQueryBuilder) {
531
- const { sql, params } = id.compile();
532
- return this.platform.formatQuery(sql, params);
531
+ return this.platform.quoteIdentifier(id.toRaw());
533
532
  }
534
533
  if (id.endsWith('.*')) {
535
534
  const schema = this.platform.quoteIdentifier(id.substring(0, id.indexOf('.')));
@@ -1031,6 +1031,11 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
1031
1031
  */
1032
1032
  private processNestedJoins;
1033
1033
  private hasToManyJoins;
1034
+ /**
1035
+ * Whether a join can match more than one row per root row. Only owning to-one joins target a unique key; inverse 1:1
1036
+ * relies on an unenforced unique FK, and sub-query or table reference joins match arbitrary rows.
1037
+ */
1038
+ private canRepeatRootRows;
1034
1039
  /**
1035
1040
  * Resolves a `persist: false` virtual field referenced in `orderBy` (e.g. `qb.as('reviewCount')` or a
1036
1041
  * `raw()` fragment aliased in the select) to the alias and SQL expression it was selected under. The
@@ -1,5 +1,5 @@
1
1
  var _a;
2
- import { EntityMetadata, helper, inspect, isRaw, LoadStrategy, LockMode, PopulateHint, QueryFlag, QueryHelper, raw, RawQueryFragment, Reference, ReferenceKind, serialize, SUBQUERY_BRAND, Utils, ValidationError, } from '@mikro-orm/core';
2
+ import { EntityMetadata, helper, inspect, isRaw, LoadStrategy, LockMode, PopulateHint, QueryFlag, QueryHelper, raw, RawQueryFragment, Reference, ReferenceKind, serialize, SUBQUERY_BRAND, Utils, validatePaginationValue, ValidationError, } from '@mikro-orm/core';
3
3
  import { JoinType, QueryType } from './enums.js';
4
4
  import { QueryBuilderHelper } from './QueryBuilderHelper.js';
5
5
  import { CriteriaNodeFactory } from './CriteriaNodeFactory.js';
@@ -308,7 +308,7 @@ export class QueryBuilder {
308
308
  let subquery;
309
309
  if (Array.isArray(field)) {
310
310
  const rawFragment = field[1] instanceof _a ? field[1].toRaw() : field[1];
311
- subquery = this.platform.formatQuery(rawFragment.sql, rawFragment.params);
311
+ subquery = this.platform.quoteIdentifier(rawFragment);
312
312
  field = field[0];
313
313
  }
314
314
  const { prop, key } = this.joinReference(field, alias, cond, type, path, schema, subquery);
@@ -508,19 +508,14 @@ export class QueryBuilder {
508
508
  }
509
509
  withSubQuery(subQuery, alias) {
510
510
  this.ensureNotFinalized();
511
- if (isRaw(subQuery)) {
512
- this.#state.subQueries[alias] = this.platform.formatQuery(subQuery.sql, subQuery.params);
513
- }
514
- else {
515
- this.#state.subQueries[alias] = subQuery.toString();
516
- }
511
+ this.#state.subQueries[alias] = this.platform.quoteIdentifier(isRaw(subQuery) ? subQuery : subQuery.toRaw());
517
512
  return this;
518
513
  }
519
514
  where(cond, params, operator) {
520
515
  this.ensureNotFinalized();
521
516
  let processedCond;
522
517
  if (isRaw(cond)) {
523
- const sql = this.platform.formatQuery(cond.sql, cond.params);
518
+ const sql = this.platform.quoteIdentifier(cond);
524
519
  processedCond = { [raw(`(${sql})`)]: Utils.asArray(params) };
525
520
  operator ??= '$and';
526
521
  }
@@ -737,7 +732,7 @@ export class QueryBuilder {
737
732
  */
738
733
  limit(limit, offset = 0) {
739
734
  this.ensureNotFinalized();
740
- this.#state.limit = limit;
735
+ this.#state.limit = validatePaginationValue(limit, 'limit');
741
736
  if (offset) {
742
737
  this.offset(offset);
743
738
  }
@@ -753,7 +748,7 @@ export class QueryBuilder {
753
748
  */
754
749
  offset(offset) {
755
750
  this.ensureNotFinalized();
756
- this.#state.offset = offset;
751
+ this.#state.offset = validatePaginationValue(offset, 'offset');
757
752
  return this;
758
753
  }
759
754
  withSchema(schema) {
@@ -944,7 +939,9 @@ export class QueryBuilder {
944
939
  * Returns the query with parameters as wildcards.
945
940
  */
946
941
  getQuery() {
947
- return this.toQuery().sql;
942
+ const { sql, params } = this.toQuery();
943
+ // nothing gets bound without params, so the escaped question marks are resolved here
944
+ return params.length === 0 ? this.platform.formatQuery(sql, []) : sql;
948
945
  }
949
946
  /**
950
947
  * Returns raw fragment representation of this QueryBuilder.
@@ -1091,15 +1088,16 @@ export class QueryBuilder {
1091
1088
  const conn = this.getConnection();
1092
1089
  // outside a transaction, wrap in a short implicit one so RLS `set local` session context applies (no-op when unset)
1093
1090
  const sessionContext = this.context ? undefined : this.em?.getTransactionSessionContext();
1091
+ const sql = this.getQuery();
1094
1092
  let res;
1095
1093
  // a QueryBuilder used directly must honour the same `convertException` contract as the driver methods
1096
1094
  try {
1097
1095
  res = await (sessionContext
1098
- ? conn.transactional(trx => conn.execute(query.sql, query.params, method, trx, loggerContext), {
1096
+ ? conn.transactional(trx => conn.execute(sql, query.params, method, trx, loggerContext), {
1099
1097
  sessionContext,
1100
1098
  loggerContext,
1101
1099
  })
1102
- : conn.execute(query.sql, query.params, method, this.context, loggerContext));
1100
+ : conn.execute(sql, query.params, method, this.context, loggerContext));
1103
1101
  }
1104
1102
  catch (e) {
1105
1103
  throw this.driver.convertException(e);
@@ -1117,7 +1115,7 @@ export class QueryBuilder {
1117
1115
  if (Array.isArray(res)) {
1118
1116
  const map = {};
1119
1117
  mapped = res.map(r => this.driver.mapResult(r, meta, this.#state.populate, this, map));
1120
- if (options.mergeResults && joinedProps.length > 0) {
1118
+ if (options.mergeResults && joinedProps.length > 0 && this.canRepeatRootRows()) {
1121
1119
  mapped = this.driver.mergeJoinedResult(mapped, this.mainAlias.meta, joinedProps);
1122
1120
  }
1123
1121
  }
@@ -1177,7 +1175,7 @@ export class QueryBuilder {
1177
1175
  const chunkSize = options.chunkSize ?? 100;
1178
1176
  const query = this.toQuery();
1179
1177
  const loggerContext = { id: this.em?.id, ...this.loggerContext, ...this.#abortOptions };
1180
- const res = this.convertStreamExceptions(this.getConnection().stream(query.sql, query.params, this.context, loggerContext, chunkSize));
1178
+ const res = this.convertStreamExceptions(this.getConnection().stream(this.getQuery(), query.params, this.context, loggerContext, chunkSize));
1181
1179
  const meta = this.mainAlias.meta;
1182
1180
  if (options.rawResults || !meta) {
1183
1181
  yield* res;
@@ -1444,10 +1442,10 @@ export class QueryBuilder {
1444
1442
  return `(${res}) as ${this.platform.quoteIdentifier(this.alias)}`;
1445
1443
  }
1446
1444
  if (res instanceof _a) {
1447
- return `(${res.getFormattedQuery()}) as ${this.platform.quoteIdentifier(this.alias)}`;
1445
+ return `(${this.platform.quoteIdentifier(res.toRaw())}) as ${this.platform.quoteIdentifier(this.alias)}`;
1448
1446
  }
1449
1447
  if (isRaw(res)) {
1450
- const query = this.platform.formatQuery(res.sql, res.params);
1448
+ const query = this.platform.quoteIdentifier(res);
1451
1449
  return `(${query}) as ${this.platform.quoteIdentifier(this.alias)}`;
1452
1450
  }
1453
1451
  /* v8 ignore next */
@@ -1488,10 +1486,7 @@ export class QueryBuilder {
1488
1486
  join.table = String(field.params[0]);
1489
1487
  }
1490
1488
  else {
1491
- if (isRaw(field)) {
1492
- field = this.platform.formatQuery(field.sql, field.params);
1493
- }
1494
- join.subquery = field.toString();
1489
+ join.subquery = this.platform.quoteIdentifier(isRaw(field) ? field : field.toRaw());
1495
1490
  }
1496
1491
  this.#state.joins[key] = join;
1497
1492
  return { prop, key };
@@ -2274,6 +2269,17 @@ export class QueryBuilder {
2274
2269
  return [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(join.prop.kind);
2275
2270
  });
2276
2271
  }
2272
+ /**
2273
+ * Whether a join can match more than one row per root row. Only owning to-one joins target a unique key; inverse 1:1
2274
+ * relies on an unenforced unique FK, and sub-query or table reference joins match arbitrary rows.
2275
+ */
2276
+ canRepeatRootRows() {
2277
+ return Object.values(this.#state.joins).some(join => {
2278
+ const { kind, owner, name } = join.prop;
2279
+ const uniqueTarget = kind === ReferenceKind.MANY_TO_ONE || (kind === ReferenceKind.ONE_TO_ONE && owner);
2280
+ return !uniqueTarget || join.subquery != null || name === '__subquery__';
2281
+ });
2282
+ }
2277
2283
  /**
2278
2284
  * Resolves a `persist: false` virtual field referenced in `orderBy` (e.g. `qb.as('reviewCount')` or a
2279
2285
  * `raw()` fragment aliased in the select) to the alias and SQL expression it was selected under. The
@@ -2291,19 +2297,19 @@ export class QueryBuilder {
2291
2297
  });
2292
2298
  if (field instanceof NativeQueryBuilder) {
2293
2299
  const alias = field[VirtualFieldAlias];
2294
- const rendered = field.toString();
2300
+ const rendered = this.platform.quoteIdentifier(field.toRaw());
2295
2301
  // strip the known trailing alias via the platform quoting, so it works on every dialect (mssql uses `[...]`)
2296
2302
  const suffix = ` as ${this.platform.quoteIdentifier(alias)}`;
2297
2303
  return { alias, expr: rendered.endsWith(suffix) ? rendered.slice(0, -suffix.length) : rendered };
2298
2304
  }
2299
2305
  if (isRaw(field)) {
2300
- const compiled = this.platform.formatQuery(field.sql, field.params);
2306
+ const compiled = this.platform.quoteIdentifier(field);
2301
2307
  const close = compiled[compiled.length - 1];
2302
2308
  const open = close === ']' ? '[' : close === '"' ? '"' : close === '`' ? '`' : undefined;
2303
2309
  // scan back for the trailing `as <quoted alias>` (linear, avoids regex backtracking on user SQL)
2304
2310
  const start = open ? compiled.lastIndexOf(open, compiled.length - 2) : -1;
2305
2311
  if (start >= 4 && compiled.slice(start - 4, start) === ' as ') {
2306
- return { alias: compiled.slice(start + 1, -1), expr: compiled.slice(0, start - 4) };
2312
+ return { alias: compiled.slice(start + 1, -1).replaceAll('\\?', '?'), expr: compiled.slice(0, start - 4) };
2307
2313
  }
2308
2314
  return { alias: fieldName, expr: compiled };
2309
2315
  }
@@ -745,7 +745,7 @@ export class QueryBuilderHelper {
745
745
  const order = typeof direction === 'number' ? QueryOrderNumeric[direction] : direction;
746
746
  if (Raw.isKnownFragmentSymbol(key)) {
747
747
  const raw = Raw.getKnownFragment(key);
748
- ret.push(...this.#platform.getOrderByExpression(this.#platform.formatQuery(raw.sql, raw.params), order, collation));
748
+ ret.push(...this.#platform.getOrderByExpression(this.#platform.quoteIdentifier(raw), order, collation));
749
749
  continue;
750
750
  }
751
751
  for (const f of Utils.splitPrimaryKeys(key)) {
@@ -765,7 +765,7 @@ export class QueryBuilderHelper {
765
765
  const customOrder = prop?.customOrder;
766
766
  let colPart = customOrder ? this.#platform.generateCustomOrder(rawColumn, customOrder) : rawColumn;
767
767
  if (isRaw(colPart)) {
768
- colPart = this.#platform.formatQuery(colPart.sql, colPart.params);
768
+ colPart = this.#platform.quoteIdentifier(colPart);
769
769
  }
770
770
  ret.push(...this.#platform.getOrderByExpression(colPart, order, collation));
771
771
  }
@@ -9,7 +9,10 @@ export class ScalarCriteriaNode extends CriteriaNode {
9
9
  process(qb, options) {
10
10
  const matchPopulateJoins = options?.matchPopulateJoins ||
11
11
  (this.prop && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(this.prop.kind));
12
- const nestedAlias = qb.getAliasForJoinPath(this.getPath(options), { ...options, matchPopulateJoins });
12
+ // nodes without a property (e.g. `$in` items) never join, so the alias lookup is not needed
13
+ const nestedAlias = this.prop
14
+ ? qb.getAliasForJoinPath(this.getPath(options), { ...options, matchPopulateJoins })
15
+ : undefined;
13
16
  if (this.shouldJoin(qb, nestedAlias)) {
14
17
  const path = this.getPath();
15
18
  const parentPath = this.parent.getPath(); // the parent is always there, otherwise `shouldJoin` would return `false`
@@ -191,7 +191,7 @@ export class DatabaseSchema {
191
191
  const table = schema.addTable(meta.collection, this.getSchemaName(meta, config, schemaName));
192
192
  table.comment = meta.comment;
193
193
  if (meta.partitionBy) {
194
- table.setPartitioning(getTablePartitioning(meta, this.getSchemaName(meta, config, schemaName), id => platform.quoteIdentifier(id)));
194
+ table.setPartitioning(getTablePartitioning(meta, this.getSchemaName(meta, config, schemaName), id => platform.quoteIdentifier(id).replaceAll('\\?', '?')));
195
195
  }
196
196
  // For TPT child entities, only use ownProps (properties defined in this entity only)
197
197
  // For all other entities (including TPT root), use all props
@@ -339,7 +339,7 @@ export class DatabaseSchema {
339
339
  }
340
340
  // native enum columns compare against the enum type itself, `current_setting()` text won't coerce implicitly
341
341
  const cast = col.nativeEnumName
342
- ? `::${platform.quoteIdentifier(col.nativeEnumName)}`
342
+ ? `::${platform.quoteIdentifier(col.nativeEnumName).replaceAll('\\?', '?')}`
343
343
  : platform.getCurrentSettingCast(col.mappedType);
344
344
  if (cast === null) {
345
345
  throw MetadataError.rlsFilterUncastableType(filter.name, col.type);
@@ -33,7 +33,7 @@ export class DatabaseTable {
33
33
  this.#platform = platform;
34
34
  }
35
35
  getQuotedName() {
36
- return this.#platform.quoteIdentifier(this.getShortestName());
36
+ return this.#platform.quoteIdentifier(this.getShortestName()).replaceAll('\\?', '?');
37
37
  }
38
38
  getColumns() {
39
39
  return Object.values(this.#columns);
@@ -838,9 +838,10 @@ export class DatabaseTable {
838
838
  let field = baseName;
839
839
  if (fk) {
840
840
  const idx = fk.columnNames.indexOf(baseName);
841
- let replacedFieldName = field.replace(new RegExp(`_${fk.referencedColumnNames[idx]}$`), '');
841
+ const stripSuffix = (suffix) => (field.endsWith(suffix) ? field.slice(0, -suffix.length) : field);
842
+ let replacedFieldName = stripSuffix(`_${fk.referencedColumnNames[idx]}`);
842
843
  if (replacedFieldName === field) {
843
- replacedFieldName = field.replace(new RegExp(`_${namingStrategy.referenceColumnName()}$`), '');
844
+ replacedFieldName = stripSuffix(`_${namingStrategy.referenceColumnName()}`);
844
845
  }
845
846
  field = replacedFieldName;
846
847
  }
@@ -1033,9 +1033,9 @@ export class SchemaHelper {
1033
1033
  qualifiedRoutineName(routine) {
1034
1034
  const defaultSchema = this.platform.getDefaultSchemaName();
1035
1035
  if (routine.schema && routine.schema !== defaultSchema) {
1036
- return `${this.platform.quoteIdentifier(routine.schema)}.${this.platform.quoteIdentifier(routine.name)}`;
1036
+ return `${this.quote(routine.schema)}.${this.quote(routine.name)}`;
1037
1037
  }
1038
- return this.platform.quoteIdentifier(routine.name);
1038
+ return this.quote(routine.name);
1039
1039
  }
1040
1040
  /** @internal */
1041
1041
  getTableName(table, schema) {
@@ -1062,7 +1062,8 @@ export class SchemaHelper {
1062
1062
  return comment;
1063
1063
  }
1064
1064
  quote(...keys) {
1065
- return this.platform.quoteIdentifier(keys.filter(Boolean).join('.'));
1065
+ // DDL is not a query template, so question marks need no escaping there
1066
+ return this.platform.quoteIdentifier(keys.filter(Boolean).join('.')).replaceAll('\\?', '?');
1066
1067
  }
1067
1068
  dropForeignKey(tableName, constraintName) {
1068
1069
  return `alter table ${this.quote(tableName)} drop foreign key ${this.quote(constraintName)}`;