@mikro-orm/sql 7.3.0-dev.23 → 7.3.0-dev.25

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() {
@@ -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);
@@ -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,18 +339,22 @@ 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);
352
- 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}`;
353
358
  }
354
359
  pad(number, digits) {
355
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`),
@@ -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.23",
3
+ "version": "7.3.0-dev.25",
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.3.0-dev.23"
56
+ "@mikro-orm/core": "7.3.0-dev.25"
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);
@@ -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)}`;