Skip to content

Commit

Permalink
fix: remove add/removeTicks (#15973)
Browse files Browse the repository at this point in the history
  • Loading branch information
WikiRik committed Jun 18, 2023
1 parent c4eef63 commit ef00e92
Show file tree
Hide file tree
Showing 25 changed files with 27 additions and 117 deletions.
2 changes: 0 additions & 2 deletions packages/core/src/dialects/abstract/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,8 +366,6 @@ export abstract class AbstractDialect {

abstract readonly defaultVersion: string;
abstract readonly Query: typeof AbstractQuery;
/** @deprecated use {@link TICK_CHAR_RIGHT} & {@link TICK_CHAR_LEFT} */
abstract readonly TICK_CHAR: string;
abstract readonly TICK_CHAR_LEFT: string;
abstract readonly TICK_CHAR_RIGHT: string;
abstract readonly queryGenerator: AbstractQueryGenerator;
Expand Down
2 changes: 0 additions & 2 deletions packages/core/src/dialects/db2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ export class Db2Dialect extends AbstractDialect {
readonly queryInterface: Db2QueryInterface;
readonly Query = Db2Query;

/** @deprecated */
readonly TICK_CHAR = '"';
readonly TICK_CHAR_LEFT = '"';
readonly TICK_CHAR_RIGHT = '"';

Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/dialects/db2/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export class Db2QueryGenerator extends Db2QueryGeneratorTypeScript {
// DROP SCHEMA Can't drop schema if it is not empty.
// DROP SCHEMA Can't drop objects belonging to the schema
// So, call the admin procedure to drop schema.
const query = `CALL SYSPROC.ADMIN_DROP_SCHEMA(${wrapSingleQuote(schema.trim())}, NULL, $sequelize_errorSchema, $sequelize_errorTable)`;
const query = `CALL SYSPROC.ADMIN_DROP_SCHEMA(${this.escape(schema.trim())}, NULL, $sequelize_errorSchema, $sequelize_errorTable)`;

if (this._errorTableCount >= Number.MAX_SAFE_INTEGER) {
this._errorTableCount = 0;
Expand Down Expand Up @@ -209,7 +209,7 @@ export class Db2QueryGenerator extends Db2QueryGeneratorTypeScript {
const schemaName = table.schema || this.sequelize.config.username.toUpperCase();

// https://www.ibm.com/docs/en/db2-for-zos/11?topic=tables-systables
return `SELECT name FROM sysibm.systables WHERE NAME = ${wrapSingleQuote(tableName)} AND CREATOR = ${wrapSingleQuote(schemaName)}`;
return `SELECT name FROM sysibm.systables WHERE NAME = ${this.escape(tableName)} AND CREATOR = ${this.escape(schemaName)}`;
}

addColumnQuery(table, key, dataType, options) {
Expand Down Expand Up @@ -842,7 +842,6 @@ export class Db2QueryGenerator extends Db2QueryGeneratorTypeScript {
function wrapSingleQuote(identifier) {
if (identifier) {
return `'${identifier}'`;
// return addTicks("'"); // It removes quote from center too.
}

return '';
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/dialects/ibmi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export class IBMiDialect extends AbstractDialect {
readonly dataTypesDocumentationUrl = 'https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_73/db2/rbafzch2data.htm';
readonly defaultVersion = '7.3.0';
readonly Query = IBMiQuery;
readonly TICK_CHAR = '"';
readonly TICK_CHAR_LEFT = '"';
readonly TICK_CHAR_RIGHT = '"';

Expand Down
11 changes: 0 additions & 11 deletions packages/core/src/dialects/ibmi/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { BaseSqlExpression } from '../../expression-builders/base-sql-expression.js';
import { conformIndex } from '../../model-internals';
import { rejectInvalidOptions } from '../../utils/check';
import { addTicks } from '../../utils/dialect';
import { nameIndex, removeTrailingSemicolon } from '../../utils/string';
import { defaultValueSchemable } from '../../utils/query-builder-utils';
import { attributeTypeToSql, normalizeDataType } from '../abstract/data-types-utils';
Expand All @@ -19,8 +18,6 @@ const util = require('node:util');
const _ = require('lodash');
const { IBMiQueryGeneratorTypeScript } = require('./query-generator-typescript');
const DataTypes = require('../../data-types');
const { Model } = require('../../model');
const SqlString = require('../../sql-string');

const typeWithoutDefault = new Set(['BLOB']);

Expand Down Expand Up @@ -626,11 +623,3 @@ export class IBMiQueryGenerator extends IBMiQueryGeneratorTypeScript {
DROP FOREIGN KEY ${this.quoteIdentifier(foreignKey)}`;
}
}

/**
* @param {string} identifier
* @deprecated use "escape" or "escapeString" on QueryGenerator
*/
function wrapSingleQuote(identifier) {
return addTicks(identifier, '\'');
}
1 change: 0 additions & 1 deletion packages/core/src/dialects/mariadb/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ export class MariaDbDialect extends AbstractDialect {
},
);

readonly TICK_CHAR = '`';
readonly TICK_CHAR_LEFT = '`';
readonly TICK_CHAR_RIGHT = '`';
readonly defaultVersion = '10.1.44'; // minimum supported version
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/dialects/mssql/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export class MssqlDialect extends AbstractDialect {
// .github/workflows/ci.yml
// minimum supported version
readonly defaultVersion = '14.0.1000';
readonly TICK_CHAR = '"';
readonly TICK_CHAR_LEFT = '[';
readonly TICK_CHAR_RIGHT = ']';

Expand Down
24 changes: 7 additions & 17 deletions packages/core/src/dialects/mssql/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
import { Col } from '../../expression-builders/col.js';
import { Literal } from '../../expression-builders/literal.js';
import { rejectInvalidOptions } from '../../utils/check';
import { addTicks, removeTicks } from '../../utils/dialect';
import { joinSQLFragments } from '../../utils/join-sql-fragments';
import { defaultValueSchemable } from '../../utils/query-builder-utils';
import { generateIndexName, underscore } from '../../utils/string';
import { generateIndexName } from '../../utils/string';
import { attributeTypeToSql, normalizeDataType } from '../abstract/data-types-utils';
import {
ADD_COLUMN_QUERY_SUPPORTABLE_OPTIONS,
Expand All @@ -21,7 +20,6 @@ const DataTypes = require('../../data-types');
const { TableHints } = require('../../table-hints');
const { MsSqlQueryGeneratorTypeScript } = require('./query-generator-typescript');
const randomBytes = require('node:crypto').randomBytes;
const semver = require('semver');
const { Op } = require('../../operators');

/* istanbul ignore next */
Expand Down Expand Up @@ -50,7 +48,7 @@ export class MsSqlQueryGenerator extends MsSqlQueryGeneratorTypeScript {
const collation = options?.collate ? `COLLATE ${this.escape(options.collate)}` : '';

return [
'IF NOT EXISTS (SELECT * FROM sys.databases WHERE name =', wrapSingleQuote(databaseName), ')',
'IF NOT EXISTS (SELECT * FROM sys.databases WHERE name =', this.escape(databaseName), ')',
'BEGIN',
'CREATE DATABASE', this.quoteIdentifier(databaseName),
`${collation};`,
Expand All @@ -60,7 +58,7 @@ export class MsSqlQueryGenerator extends MsSqlQueryGeneratorTypeScript {

dropDatabaseQuery(databaseName) {
return [
'IF EXISTS (SELECT * FROM sys.databases WHERE name =', wrapSingleQuote(databaseName), ')',
'IF EXISTS (SELECT * FROM sys.databases WHERE name =', this.escape(databaseName), ')',
'BEGIN',
'DROP DATABASE', this.quoteIdentifier(databaseName), ';',
'END;',
Expand All @@ -85,7 +83,7 @@ export class MsSqlQueryGenerator extends MsSqlQueryGeneratorTypeScript {
return [
'IF NOT EXISTS (SELECT schema_name',
'FROM information_schema.schemata',
'WHERE schema_name =', wrapSingleQuote(schema), ')',
'WHERE schema_name =', this.escape(schema), ')',
'BEGIN',
'EXEC sp_executesql N\'CREATE SCHEMA',
this.quoteIdentifier(schema),
Expand All @@ -96,7 +94,7 @@ export class MsSqlQueryGenerator extends MsSqlQueryGeneratorTypeScript {

dropSchemaQuery(schema) {
// Mimics Postgres CASCADE, will drop objects belonging to the schema
const quotedSchema = wrapSingleQuote(schema);
const quotedSchema = this.escape(schema);

return [
'IF EXISTS (SELECT schema_name',
Expand Down Expand Up @@ -760,7 +758,7 @@ export class MsSqlQueryGenerator extends MsSqlQueryGeneratorTypeScript {
}

getPrimaryKeyConstraintQuery(table, attributeName) {
const tableName = wrapSingleQuote(table.tableName || table);
const tableName = this.escape(table.tableName || table);

return joinSQLFragments([
'SELECT K.TABLE_NAME AS tableName,',
Expand All @@ -773,7 +771,7 @@ export class MsSqlQueryGenerator extends MsSqlQueryGeneratorTypeScript {
'AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA',
'AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME',
'WHERE C.CONSTRAINT_TYPE = \'PRIMARY KEY\'',
`AND K.COLUMN_NAME = ${wrapSingleQuote(attributeName)}`,
`AND K.COLUMN_NAME = ${this.escape(attributeName)}`,
`AND K.TABLE_NAME = ${tableName}`,
';',
]);
Expand Down Expand Up @@ -923,11 +921,3 @@ export class MsSqlQueryGenerator extends MsSqlQueryGeneratorTypeScript {
return fragment;
}
}

/**
* @param {string} identifier
* @deprecated use "escape" or "escapeString" on QueryGenerator
*/
function wrapSingleQuote(identifier) {
return addTicks(removeTicks(identifier, '\''), '\'');
}
1 change: 0 additions & 1 deletion packages/core/src/dialects/mysql/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ export class MysqlDialect extends AbstractDialect {

// minimum supported version
readonly defaultVersion = '5.7.0';
readonly TICK_CHAR = '`';
readonly TICK_CHAR_LEFT = '`';
readonly TICK_CHAR_RIGHT = '`';

Expand Down
14 changes: 0 additions & 14 deletions packages/core/src/dialects/mysql/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import { inspect } from 'node:util';
import { rejectInvalidOptions } from '../../utils/check';
import { addTicks } from '../../utils/dialect';
import { joinSQLFragments } from '../../utils/join-sql-fragments';
import { EMPTY_OBJECT } from '../../utils/object.js';
import { defaultValueSchemable } from '../../utils/query-builder-utils';
Expand All @@ -11,11 +10,6 @@ import { ADD_COLUMN_QUERY_SUPPORTABLE_OPTIONS, REMOVE_COLUMN_QUERY_SUPPORTABLE_O

const _ = require('lodash');
const { MySqlQueryGeneratorTypeScript } = require('./query-generator-typescript');
const { Op } = require('../../operators');

const JSON_FUNCTION_REGEX = /^\s*((?:[a-z]+_){0,2}jsonb?(?:_[a-z]+){0,2})\([^)]*\)/i;
const JSON_OPERATOR_REGEX = /^\s*(->>?|@>|<@|\?[&|]?|\|{2}|#-)/i;
const TOKEN_CAPTURE_REGEX = /^\s*((?:(["'`])(?:(?!\2).|\2{2})*\2)|[\s\w]+|[()+,.;-])/i;

const typeWithoutDefault = new Set(['BLOB', 'TEXT', 'GEOMETRY', 'JSON']);
const ADD_COLUMN_QUERY_SUPPORTED_OPTIONS = new Set();
Expand Down Expand Up @@ -410,11 +404,3 @@ export class MySqlQueryGenerator extends MySqlQueryGeneratorTypeScript {
return fragment;
}
}

/**
* @param {string} identifier
* @deprecated use "escape" or "escapeString" on QueryGenerator
*/
function wrapSingleQuote(identifier) {
return addTicks(identifier, '\'');
}
1 change: 0 additions & 1 deletion packages/core/src/dialects/postgres/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ export class PostgresDialect extends AbstractDialect {

// minimum supported version
readonly defaultVersion = '11.0.0';
readonly TICK_CHAR = '"';
readonly TICK_CHAR_LEFT = '"';
readonly TICK_CHAR_RIGHT = '"';

Expand Down
6 changes: 1 addition & 5 deletions packages/core/src/dialects/postgres/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { EMPTY_OBJECT } from '../../utils/object.js';
import { defaultValueSchemable } from '../../utils/query-builder-utils';
import { generateIndexName } from '../../utils/string';
import { ENUM } from './data-types';
import { quoteIdentifier, removeTicks } from '../../utils/dialect';
import { quoteIdentifier } from '../../utils/dialect';
import { rejectInvalidOptions } from '../../utils/check';
import {
CREATE_DATABASE_QUERY_SUPPORTABLE_OPTIONS,
Expand Down Expand Up @@ -553,10 +553,6 @@ export class PostgresQueryGenerator extends PostgresQueryGeneratorTypeScript {
return `ALTER FUNCTION ${oldFunctionName}(${paramList}) RENAME TO ${newFunctionName};`;
}

pgEscapeAndQuote(val) {
return this.quoteIdentifier(removeTicks(this.escape(val), '\''));
}

_expandFunctionParamList(params) {
if (params === undefined || !Array.isArray(params)) {
throw new Error('_expandFunctionParamList: function parameters array required, including an empty one for no arguments');
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/dialects/postgres/query-interface.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ export class PostgresQueryInterface extends AbstractQueryInterface {
options = options || {};

return this.sequelize.queryRaw(
this.queryGenerator.pgEnumDrop(null, null, this.queryGenerator.pgEscapeAndQuote(enumName)),
this.queryGenerator.pgEnumDrop(null, null, this.queryGenerator.quoteIdentifier(enumName)),
{ ...options, raw: true },
);
}
Expand All @@ -204,7 +204,7 @@ export class PostgresQueryInterface extends AbstractQueryInterface {
const enums = await this.pgListEnums(null, options);

return await Promise.all(enums.map(result => this.sequelize.queryRaw(
this.queryGenerator.pgEnumDrop(null, null, this.queryGenerator.pgEscapeAndQuote(result.enum_name)),
this.queryGenerator.pgEnumDrop(null, null, this.queryGenerator.quoteIdentifier(result.enum_name)),
{ ...options, raw: true },
)));
}
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/dialects/snowflake/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ export class SnowflakeDialect extends AbstractDialect {
// TODO: fix the minimum supported version
readonly defaultVersion = '5.7.0';
readonly Query = SnowflakeQuery;
readonly TICK_CHAR = '"';
readonly TICK_CHAR_LEFT = '"';
readonly TICK_CHAR_RIGHT = '"';
readonly connectionManager: SnowflakeConnectionManager;
Expand Down
10 changes: 1 addition & 9 deletions packages/core/src/dialects/snowflake/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { joinSQLFragments } from '../../utils/join-sql-fragments';
import { EMPTY_OBJECT } from '../../utils/object.js';
import { defaultValueSchemable } from '../../utils/query-builder-utils';
import { addTicks, quoteIdentifier } from '../../utils/dialect.js';
import { quoteIdentifier } from '../../utils/dialect.js';
import { rejectInvalidOptions } from '../../utils/check';
import {
ADD_COLUMN_QUERY_SUPPORTABLE_OPTIONS,
Expand Down Expand Up @@ -559,11 +559,3 @@ export class SnowflakeQueryGenerator extends SnowflakeQueryGeneratorTypeScript {
return identifier;
}
}

/**
* @param {string} identifier
* @deprecated use "escape" or "escapeString" on QueryGenerator
*/
function wrapSingleQuote(identifier) {
return addTicks(identifier, '\'');
}
1 change: 0 additions & 1 deletion packages/core/src/dialects/sqlite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ export class SqliteDialect extends AbstractDialect {

readonly defaultVersion = '3.8.0';
readonly Query = SqliteQuery;
readonly TICK_CHAR = '`';
readonly TICK_CHAR_LEFT = '`';
readonly TICK_CHAR_RIGHT = '`';
readonly connectionManager: SqliteConnectionManager;
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/dialects/sqlite/query-generator.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict';

import { addTicks, removeTicks } from '../../utils/dialect';
import { removeNullishValuesFromHash } from '../../utils/format';
import { EMPTY_OBJECT } from '../../utils/object.js';
import { defaultValueSchemable } from '../../utils/query-builder-utils';
Expand Down Expand Up @@ -212,7 +211,7 @@ export class SqliteQueryGenerator extends SqliteQueryGeneratorTypeScript {
truncateTableQuery(tableName, options = {}) {
return [
`DELETE FROM ${this.quoteTable(tableName)}`,
options.restartIdentity ? `; DELETE FROM ${this.quoteTable('sqlite_sequence')} WHERE ${this.quoteIdentifier('name')} = ${addTicks(removeTicks(this.quoteTable(tableName), '`'), '\'')};` : '',
options.restartIdentity ? `; DELETE FROM ${this.quoteTable('sqlite_sequence')} WHERE ${this.quoteIdentifier('name')} = ${this.quoteTable(tableName)};` : '',
].join('');
}

Expand Down
7 changes: 4 additions & 3 deletions packages/core/src/dialects/sqlite/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ export class SqliteQuery extends AbstractQuery {
});
}

// TODO [>7]: remove usages of replace(/`/g, '') in favor of something that does not mishandle backticks
parseConstraintsFromSql(sql) {
let constraints = sql.split('CONSTRAINT ');
let referenceTableName; let referenceTableKeys; let updateAction; let deleteAction;
Expand All @@ -312,10 +313,10 @@ export class SqliteQuery extends AbstractQuery {

const referencesRegex = /REFERENCES.+\((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*\)/;
const referenceConditions = constraintSql.match(referencesRegex)[0].split(' ');
referenceTableName = removeTicks(referenceConditions[1]);
referenceTableName = referenceConditions[1].replace(/`/g, '');
let columnNames = referenceConditions[2];
columnNames = columnNames.replace(/\(|\)/g, '').split(', ');
referenceTableKeys = columnNames.map(column => removeTicks(column));
referenceTableKeys = columnNames.map(column => column.replace(/`/g, ''));
}

const constraintCondition = constraintSql.match(/\((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*\)/)[0];
Expand All @@ -327,7 +328,7 @@ export class SqliteQuery extends AbstractQuery {
}

return {
constraintName: removeTicks(constraint[0]),
constraintName: constraint[0].replace(/`/g, ''),
constraintType: constraint[1],
updateAction,
deleteAction,
Expand Down
31 changes: 0 additions & 31 deletions packages/core/src/utils/dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,37 +38,6 @@ export function toDefaultValue(value: unknown): unknown {
return value;
}

/**
* @deprecated use {@link AbstractDialect#TICK_CHAR_LEFT} and {@link AbstractDialect#TICK_CHAR_RIGHT},
* or {@link AbstractQueryGenerator#quoteIdentifier}
*/
export const TICK_CHAR = '`';

/**
* @deprecated this is a bad way to quote identifiers and it should not be used anymore.
* it mangles the input if the input contains identifier quotes, which should not happen.
* Use {@link quoteIdentifier} instead
*
* @param s
* @param tickChar
* @returns
*/
export function addTicks(s: string, tickChar: string = TICK_CHAR): string {
return tickChar + removeTicks(s, tickChar) + tickChar;
}

/**
* @deprecated this is a bad way to quote identifiers and it should not be used anymore.
* Use {@link quoteIdentifier} instead
*
* @param s
* @param tickChar
* @returns
*/
export function removeTicks(s: string, tickChar: string = TICK_CHAR): string {
return s.replace(new RegExp(tickChar, 'g'), '');
}

export function quoteIdentifier(identifier: string, leftTick: string, rightTick: string): string {
if (!isString(identifier)) {
throw new Error(`quoteIdentifier received a non-string identifier: ${NodeUtil.inspect(identifier)}`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ if (current.dialect.name === 'mssql') {

it('getPrimaryKeyConstraintQuery', function () {
expectsql(this.queryGenerator.getPrimaryKeyConstraintQuery('myTable', 'myColumnName'), {
mssql: 'SELECT K.TABLE_NAME AS tableName, K.COLUMN_NAME AS columnName, K.CONSTRAINT_NAME AS constraintName FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME WHERE C.CONSTRAINT_TYPE = \'PRIMARY KEY\' AND K.COLUMN_NAME = \'myColumnName\' AND K.TABLE_NAME = \'myTable\';',
mssql: 'SELECT K.TABLE_NAME AS tableName, K.COLUMN_NAME AS columnName, K.CONSTRAINT_NAME AS constraintName FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME WHERE C.CONSTRAINT_TYPE = \'PRIMARY KEY\' AND K.COLUMN_NAME = N\'myColumnName\' AND K.TABLE_NAME = N\'myTable\';',
});
});

Expand Down

0 comments on commit ef00e92

Please sign in to comment.