@mikro-orm/sql 7.2.11-dev.9 → 7.2.12-dev.0

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. */
@@ -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
  }
@@ -953,7 +951,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
953
951
  if (transform) {
954
952
  sql = transform(sql);
955
953
  }
956
- 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));
957
955
  const pk = this.resolveInsertedPrimaryKeys(meta, data, res);
958
956
  for (let i = 0; i < collections.length; i++) {
959
957
  await this.processManyToMany(meta, pk[i], collections[i], false, options);
@@ -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() {
@@ -130,7 +130,7 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
130
130
  const quotedTableName = this.quoteIdentifier(schemaName ? `${schemaName}.${tableName}` : tableName);
131
131
  const quotedColumnNames = columns.map(c => this.quoteIdentifier(c.name));
132
132
  const quotedIndexName = this.quoteIdentifier(indexName);
133
- return `alter table ${quotedTableName} add fulltext index ${quotedIndexName}(${quotedColumnNames.join(',')})`;
133
+ return `alter table ${quotedTableName} add fulltext index ${quotedIndexName}(${quotedColumnNames.join(',')})`.replaceAll('\\?', '?');
134
134
  }
135
135
  getOrderByExpression(column, direction, collation) {
136
136
  const ret = [];
@@ -332,12 +332,12 @@ export class MySqlSchemaHelper extends SchemaHelper {
332
332
  if (routine.expression) {
333
333
  return routine.expression;
334
334
  }
335
- const name = this.platform.quoteIdentifier(routine.name);
335
+ const name = this.quote(routine.name);
336
336
  // MySQL functions reject direction prefixes (function params are always IN); procedures use them.
337
337
  const params = routine.params
338
338
  .map(p => {
339
339
  const dir = routine.type === 'procedure' ? `${p.direction.toUpperCase()} ` : '';
340
- return `${dir}${this.platform.quoteIdentifier(p.name)} ${p.type}`;
340
+ return `${dir}${this.quote(p.name)} ${p.type}`;
341
341
  })
342
342
  .join(', ');
343
343
  const determinism = routine.deterministic === true ? ' deterministic' : routine.deterministic === false ? ' not deterministic' : '';
@@ -357,7 +357,7 @@ export class MySqlSchemaHelper extends SchemaHelper {
357
357
  }
358
358
  dropRoutine(routine) {
359
359
  const kind = routine.type === 'procedure' ? 'procedure' : 'function';
360
- return `drop ${kind} if exists ${this.platform.quoteIdentifier(routine.name)}`;
360
+ return `drop ${kind} if exists ${this.quote(routine.name)}`;
361
361
  }
362
362
  async getAllRoutines(connection) {
363
363
  const sql = `
@@ -570,12 +570,13 @@ export class MySqlSchemaHelper extends SchemaHelper {
570
570
  async getAllEnumDefinitions(connection, tables, ctx) {
571
571
  const sql = `select column_name as column_name, column_type as column_type, table_name as table_name
572
572
  from information_schema.columns
573
- where data_type = 'enum' and table_name in (${tables.map(t => `'${t.table_name}'`).join(', ')}) and table_schema = database()`;
573
+ where data_type = 'enum' and table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(', ')}) and table_schema = database()`;
574
574
  const enums = await connection.execute(sql, [], 'all', ctx);
575
575
  return enums.reduce((o, item) => {
576
- o[item.table_name] ??= {};
576
+ const key = this.getTableKey(item);
577
+ o[key] ??= {};
577
578
  // items can hold commas, doubled quotes and backslash escapes
578
- o[item.table_name][item.column_name] = [...item.column_type.matchAll(/'((?:''|\\.|[^'\\])*)'/g)].map(([, value]) => this.unescapeDefault(value.replaceAll("''", "'")));
579
+ o[key][item.column_name] = [...item.column_type.matchAll(/'((?:''|\\.|[^'\\])*)'/g)].map(([, value]) => this.unescapeDefault(value.replaceAll("''", "'")));
579
580
  return o;
580
581
  }, {});
581
582
  }
@@ -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);
@@ -325,10 +325,11 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
325
325
  Object.keys(value).every(key => ARRAY_OPERATORS.includes(key) && Array.isArray(value[key]))) {
326
326
  lastOperator = '->';
327
327
  }
328
+ const quote = (key) => this.quoteValue(key).replaceAll('?', '\\?');
328
329
  if (path.length === 0) {
329
- return cast(`${root}${lastOperator}${this.quoteValue(last)}`);
330
+ return cast(`${root}${lastOperator}${quote(last)}`);
330
331
  }
331
- 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)}`);
332
333
  }
333
334
  getJsonIndexDefinition(index) {
334
335
  return index.columnNames.map(column => {
@@ -338,17 +339,21 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
338
339
  const path = column.split('.');
339
340
  const first = path.shift();
340
341
  const last = path.pop();
342
+ const root = this.quoteIdentifier(first).replaceAll('\\?', '?');
341
343
  if (path.length === 0) {
342
- return `(${this.quoteIdentifier(first)}->>${this.quoteValue(last)})`;
344
+ return `(${root}->>${this.quoteValue(last)})`;
343
345
  }
344
- 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)})`;
345
347
  });
346
348
  }
347
349
  quoteIdentifier(id, quote = '"') {
348
350
  if (RawQueryFragment.isKnownFragment(id)) {
349
351
  return super.quoteIdentifier(id);
350
352
  }
351
- const escaped = id.toString().replaceAll(quote, quote + quote);
353
+ const escaped = id
354
+ .toString()
355
+ .replaceAll(quote, quote + quote)
356
+ .replaceAll('?', '\\?');
352
357
  return `${quote}${escaped.replaceAll('.', `${quote}.${quote}`)}${quote}`;
353
358
  }
354
359
  pad(number, digits) {
@@ -105,7 +105,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
105
105
  // breaking a plain `table_name not in (...)` predicate).
106
106
  return (`select table_name, table_schema as schema_name, ` +
107
107
  `(select pg_catalog.obj_description(c.oid) from pg_catalog.pg_class c
108
- where c.oid = (select ('"' || table_schema || '"."' || table_name || '"')::regclass::oid) and c.relname = table_name) as table_comment ` +
108
+ where c.oid = (select format('%I.%I', table_schema, table_name)::regclass::oid) and c.relname = table_name) as table_comment ` +
109
109
  `from information_schema.tables t ` +
110
110
  `where ${this.getIgnoredNamespacesConditionSQL('table_schema')} ` +
111
111
  `and table_name != 'geometry_columns' and table_name != 'spatial_ref_sys' and table_type != 'VIEW' ` +
@@ -598,14 +598,14 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
598
598
  const forEach = trigger.forEach === 'statement' ? 'STATEMENT' : 'ROW';
599
599
  const when = trigger.when ? `\n when (${trigger.when})` : '';
600
600
  const fnName = this.getSchemaQualifiedTriggerFnName(table, trigger);
601
- const triggerName = this.platform.quoteIdentifier(trigger.name);
601
+ const triggerName = this.quote(trigger.name);
602
602
  const fnSql = `create or replace function ${fnName}() returns trigger as $$ begin ${this.normalizeTriggerBody(trigger.body)} end; $$ language plpgsql`;
603
603
  const triggerSql = `create trigger ${triggerName} ${timing} ${events} on ${table.getQuotedName()} for each ${forEach}${when} execute function ${fnName}()`;
604
604
  return `${fnSql};\n${triggerSql}`;
605
605
  }
606
606
  /** Generates SQL to drop a PostgreSQL trigger and its associated function. */
607
607
  dropTrigger(table, trigger) {
608
- const triggerName = this.platform.quoteIdentifier(trigger.name);
608
+ const triggerName = this.quote(trigger.name);
609
609
  const fnName = this.getSchemaQualifiedTriggerFnName(table, trigger);
610
610
  return `drop trigger if exists ${triggerName} on ${table.getQuotedName()};\ndrop function if exists ${fnName}()`;
611
611
  }
@@ -782,7 +782,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
782
782
  .map(p => {
783
783
  const dir = p.direction === 'in' ? '' : `${p.direction.toUpperCase()} `;
784
784
  const def = p.defaultRaw ? ` default ${p.defaultRaw}` : '';
785
- const name = p.name ? `${this.platform.quoteIdentifier(p.name)} ` : '';
785
+ const name = p.name ? `${this.quote(p.name)} ` : '';
786
786
  return `${dir}${name}${p.type}${def}`;
787
787
  })
788
788
  .join(', ');
@@ -796,7 +796,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
796
796
  // INOUT before IN/OUT, with required trailing space so identifiers like `input` aren't
797
797
  // mis-parsed as a direction keyword. The name is optional — `pg_get_function_arguments`
798
798
  // omits it for unnamed parameters (e.g. `text`), leaving just the type.
799
- const match = /^(?:(INOUT|VARIADIC|IN|OUT)\s+)?(?:(?:"((?:[^"]|"")+)"|([\w$]+))\s+)?(.+?)(?:\s+default\s+.+)?$/i.exec(trimmed);
799
+ const match = /^(?:(INOUT|VARIADIC|IN|OUT)\s+)?(?:(?:"((?:[^"]|"")+)"|([\w$]+))\s+)?(.+?)(?:\s+default\s+.+)?$/is.exec(trimmed);
800
800
  /* v8 ignore next 3: defensive guard for unexpected `pg_get_function_arguments` output shapes */
801
801
  if (!match) {
802
802
  throw new Error(`Could not parse PostgreSQL routine parameter signature: ${JSON.stringify(trimmed)}`);
@@ -820,9 +820,9 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
820
820
  const rawName = `${table.name}_${trigger.name}_fn`;
821
821
  const defaultSchema = this.platform.getDefaultSchemaName();
822
822
  if (table.schema && table.schema !== defaultSchema) {
823
- return `${this.platform.quoteIdentifier(table.schema)}.${this.platform.quoteIdentifier(rawName)}`;
823
+ return `${this.quote(table.schema)}.${this.quote(rawName)}`;
824
824
  }
825
- return this.platform.quoteIdentifier(rawName);
825
+ return this.quote(rawName);
826
826
  }
827
827
  /**
828
828
  * Resolves the real name of the implicit 'default' collation (the DB's `datcollate`),
@@ -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
  }
@@ -245,8 +245,9 @@ export class SqliteSchemaHelper extends SchemaHelper {
245
245
  }
246
246
  for (let i = cols.length - 1; i >= 0; i--) {
247
247
  const col = cols[i];
248
+ const name = col.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
248
249
  // the first column is not preceded by a comma
249
- const re = ` *(?:^|,) *[\`"']?${col.name}[\`"']? (.*)`;
250
+ const re = ` *(?:^|,) *[\`"']?${name}[\`"']? (.*)`;
250
251
  const columnDef = new RegExp(re, 'i').exec(columnsDef);
251
252
  if (columnDef) {
252
253
  columns[col.name] = { name: col.name, definition: columnDef[1] };
@@ -264,7 +265,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
264
265
  if (!schemaName || schemaName === 'main') {
265
266
  return '';
266
267
  }
267
- return `${this.platform.quoteIdentifier(schemaName)}.`;
268
+ return `${this.quote(schemaName)}.`;
268
269
  }
269
270
  /**
270
271
  * Returns all database names excluding 'temp'.
@@ -283,7 +284,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
283
284
  }
284
285
  async getColumns(connection, tableName, schemaName, ctx) {
285
286
  const prefix = this.getSchemaPrefix(schemaName);
286
- const columns = await connection.execute(`pragma ${prefix}table_xinfo('${tableName}')`, [], 'all', ctx);
287
+ const columns = await connection.execute(`pragma ${prefix}table_xinfo(${this.platform.quoteValue(tableName)})`, [], 'all', ctx);
287
288
  const sql = `select sql from ${prefix}sqlite_master where type = ? and name = ?`;
288
289
  const tableDefinition = await connection.execute(sql, ['table', tableName], 'get', ctx);
289
290
  const composite = columns.reduce((count, col) => count + (col.pk ? 1 : 0), 0) > 1;
@@ -370,15 +371,15 @@ export class SqliteSchemaHelper extends SchemaHelper {
370
371
  }
371
372
  async getPrimaryKeys(connection, indexes, tableName, schemaName, ctx) {
372
373
  const prefix = this.getSchemaPrefix(schemaName);
373
- const sql = `pragma ${prefix}table_info(\`${tableName}\`)`;
374
+ const sql = `pragma ${prefix}table_info(${this.platform.quoteValue(tableName)})`;
374
375
  const cols = await connection.execute(sql, [], 'all', ctx);
375
376
  return cols.filter(col => !!col.pk).map(col => col.name);
376
377
  }
377
378
  async getIndexes(connection, tableName, schemaName, ctx) {
378
379
  const prefix = this.getSchemaPrefix(schemaName);
379
- const sql = `pragma ${prefix}table_info(\`${tableName}\`)`;
380
+ const sql = `pragma ${prefix}table_info(${this.platform.quoteValue(tableName)})`;
380
381
  const cols = await connection.execute(sql, [], 'all', ctx);
381
- const indexes = await connection.execute(`pragma ${prefix}index_list(\`${tableName}\`)`, [], 'all', ctx);
382
+ const indexes = await connection.execute(`pragma ${prefix}index_list(${this.platform.quoteValue(tableName)})`, [], 'all', ctx);
382
383
  // sqlite_master.sql holds the original CREATE INDEX statement — the only place a partial
383
384
  // index's WHERE predicate is preserved (PRAGMA index_* don't expose it).
384
385
  const indexSqls = await connection.execute(`select name, sql from ${prefix}sqlite_master where type = 'index' and tbl_name = ?`, [tableName], 'all', ctx);
@@ -400,7 +401,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
400
401
  });
401
402
  }
402
403
  for (const index of indexes.filter(index => !this.isImplicitIndex(index.name))) {
403
- const res = await connection.execute(`pragma ${prefix}index_info(\`${index.name}\`)`, [], 'all', ctx);
404
+ const res = await connection.execute(`pragma ${prefix}index_info(${this.platform.quoteValue(index.name)})`, [], 'all', ctx);
404
405
  const where = wherePredicates.get(index.name);
405
406
  ret.push(...res.map(row => ({
406
407
  columnNames: [row.name],
@@ -442,7 +443,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
442
443
  }
443
444
  async getColumnDefinitions(connection, tableName, schemaName, ctx) {
444
445
  const prefix = this.getSchemaPrefix(schemaName);
445
- const columns = await connection.execute(`pragma ${prefix}table_xinfo('${tableName}')`, [], 'all', ctx);
446
+ const columns = await connection.execute(`pragma ${prefix}table_xinfo(${this.platform.quoteValue(tableName)})`, [], 'all', ctx);
446
447
  const sql = `select sql from ${prefix}sqlite_master where type = ? and name = ?`;
447
448
  const tableDefinition = await connection.execute(sql, ['table', tableName], 'get', ctx);
448
449
  return this.parseTableDefinition(tableDefinition.sql, columns);
@@ -450,7 +451,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
450
451
  async getForeignKeys(connection, tableName, schemaName, ctx) {
451
452
  const { constraints } = await this.getColumnDefinitions(connection, tableName, schemaName, ctx);
452
453
  const prefix = this.getSchemaPrefix(schemaName);
453
- const fks = await connection.execute(`pragma ${prefix}foreign_key_list(\`${tableName}\`)`, [], 'all', ctx);
454
+ const fks = await connection.execute(`pragma ${prefix}foreign_key_list(${this.platform.quoteValue(tableName)})`, [], 'all', ctx);
454
455
  const qualifiedTableName = schemaName ? `${schemaName}.${tableName}` : tableName;
455
456
  return fks.reduce((ret, fk) => {
456
457
  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.2.11-dev.9",
3
+ "version": "7.2.12-dev.0",
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.10"
53
+ "@mikro-orm/core": "^7.2.11"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.2.11-dev.9"
56
+ "@mikro-orm/core": "7.2.12-dev.0"
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('.')));
@@ -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
  }
@@ -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);
@@ -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 };
@@ -2302,19 +2297,19 @@ export class QueryBuilder {
2302
2297
  });
2303
2298
  if (field instanceof NativeQueryBuilder) {
2304
2299
  const alias = field[VirtualFieldAlias];
2305
- const rendered = field.toString();
2300
+ const rendered = this.platform.quoteIdentifier(field.toRaw());
2306
2301
  // strip the known trailing alias via the platform quoting, so it works on every dialect (mssql uses `[...]`)
2307
2302
  const suffix = ` as ${this.platform.quoteIdentifier(alias)}`;
2308
2303
  return { alias, expr: rendered.endsWith(suffix) ? rendered.slice(0, -suffix.length) : rendered };
2309
2304
  }
2310
2305
  if (isRaw(field)) {
2311
- const compiled = this.platform.formatQuery(field.sql, field.params);
2306
+ const compiled = this.platform.quoteIdentifier(field);
2312
2307
  const close = compiled[compiled.length - 1];
2313
2308
  const open = close === ']' ? '[' : close === '"' ? '"' : close === '`' ? '`' : undefined;
2314
2309
  // scan back for the trailing `as <quoted alias>` (linear, avoids regex backtracking on user SQL)
2315
2310
  const start = open ? compiled.lastIndexOf(open, compiled.length - 2) : -1;
2316
2311
  if (start >= 4 && compiled.slice(start - 4, start) === ' as ') {
2317
- 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) };
2318
2313
  }
2319
2314
  return { alias: fieldName, expr: compiled };
2320
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
  }
@@ -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);
@@ -836,9 +836,10 @@ export class DatabaseTable {
836
836
  let field = baseName;
837
837
  if (fk) {
838
838
  const idx = fk.columnNames.indexOf(baseName);
839
- let replacedFieldName = field.replace(new RegExp(`_${fk.referencedColumnNames[idx]}$`), '');
839
+ const stripSuffix = (suffix) => (field.endsWith(suffix) ? field.slice(0, -suffix.length) : field);
840
+ let replacedFieldName = stripSuffix(`_${fk.referencedColumnNames[idx]}`);
840
841
  if (replacedFieldName === field) {
841
- replacedFieldName = field.replace(new RegExp(`_${namingStrategy.referenceColumnName()}$`), '');
842
+ replacedFieldName = stripSuffix(`_${namingStrategy.referenceColumnName()}`);
842
843
  }
843
844
  field = replacedFieldName;
844
845
  }
@@ -993,9 +993,9 @@ export class SchemaHelper {
993
993
  qualifiedRoutineName(routine) {
994
994
  const defaultSchema = this.platform.getDefaultSchemaName();
995
995
  if (routine.schema && routine.schema !== defaultSchema) {
996
- return `${this.platform.quoteIdentifier(routine.schema)}.${this.platform.quoteIdentifier(routine.name)}`;
996
+ return `${this.quote(routine.schema)}.${this.quote(routine.name)}`;
997
997
  }
998
- return this.platform.quoteIdentifier(routine.name);
998
+ return this.quote(routine.name);
999
999
  }
1000
1000
  /** @internal */
1001
1001
  getTableName(table, schema) {
@@ -1022,7 +1022,8 @@ export class SchemaHelper {
1022
1022
  return comment;
1023
1023
  }
1024
1024
  quote(...keys) {
1025
- return this.platform.quoteIdentifier(keys.filter(Boolean).join('.'));
1025
+ // DDL is not a query template, so question marks need no escaping there
1026
+ return this.platform.quoteIdentifier(keys.filter(Boolean).join('.')).replaceAll('\\?', '?');
1026
1027
  }
1027
1028
  dropForeignKey(tableName, constraintName) {
1028
1029
  return `alter table ${this.quote(tableName)} drop foreign key ${this.quote(constraintName)}`;