不要怂,就是干,撸起袖子干!

query-interface.js 2.13 KB
'use strict';

const { QueryInterface } = require('../abstract/query-interface');

/**
 * The interface that Sequelize uses to talk with MSSQL database
 */
class MSSqlQueryInterface extends QueryInterface {
  /**
  * A wrapper that fixes MSSQL's inability to cleanly remove columns from existing tables if they have a default constraint.
  *
  * @override
  */
  async removeColumn(tableName, attributeName, options) {
    options = { raw: true, ...options || {} };

    const findConstraintSql = this.queryGenerator.getDefaultConstraintQuery(tableName, attributeName);
    const [results0] = await this.sequelize.query(findConstraintSql, options);
    if (results0.length) {
      // No default constraint found -- we can cleanly remove the column
      const dropConstraintSql = this.queryGenerator.dropConstraintQuery(tableName, results0[0].name);
      await this.sequelize.query(dropConstraintSql, options);
    }
    const findForeignKeySql = this.queryGenerator.getForeignKeyQuery(tableName, attributeName);
    const [results] = await this.sequelize.query(findForeignKeySql, options);
    if (results.length) {
      // No foreign key constraints found, so we can remove the column
      const dropForeignKeySql = this.queryGenerator.dropForeignKeyQuery(tableName, results[0].constraint_name);
      await this.sequelize.query(dropForeignKeySql, options);
    }
    //Check if the current column is a primaryKey
    const primaryKeyConstraintSql = this.queryGenerator.getPrimaryKeyConstraintQuery(tableName, attributeName);
    const [result] = await this.sequelize.query(primaryKeyConstraintSql, options);
    if (result.length) {
      const dropConstraintSql = this.queryGenerator.dropConstraintQuery(tableName, result[0].constraintName);
      await this.sequelize.query(dropConstraintSql, options);
    }
    const removeSql = this.queryGenerator.removeColumnQuery(tableName, attributeName);
    return this.sequelize.query(removeSql, options);
  }

  /**
   * @override
   */
  _convertUpsertResult(result, model) {
    return [
      result.$action === 'INSERT',
      result[model.primaryKeyField]
    ];
  }
}

exports.MSSqlQueryInterface = MSSqlQueryInterface;