query-interface.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. /**
  3. Returns an object that treats MSSQL's inabilities to do certain queries.
  4. @class QueryInterface
  5. @static
  6. @private
  7. */
  8. /**
  9. A wrapper that fixes MSSQL's inability to cleanly remove columns from existing tables if they have a default constraint.
  10. @param {QueryInterface} qi
  11. @param {string} tableName The name of the table.
  12. @param {string} attributeName The name of the attribute that we want to remove.
  13. @param {Object} options
  14. @param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
  15. @private
  16. */
  17. const removeColumn = function(qi, tableName, attributeName, options) {
  18. options = Object.assign({ raw: true }, options || {});
  19. const findConstraintSql = qi.QueryGenerator.getDefaultConstraintQuery(tableName, attributeName);
  20. return qi.sequelize.query(findConstraintSql, options)
  21. .then(([results]) => {
  22. if (!results.length) {
  23. // No default constraint found -- we can cleanly remove the column
  24. return;
  25. }
  26. const dropConstraintSql = qi.QueryGenerator.dropConstraintQuery(tableName, results[0].name);
  27. return qi.sequelize.query(dropConstraintSql, options);
  28. })
  29. .then(() => {
  30. const findForeignKeySql = qi.QueryGenerator.getForeignKeyQuery(tableName, attributeName);
  31. return qi.sequelize.query(findForeignKeySql, options);
  32. })
  33. .then(([results]) => {
  34. if (!results.length) {
  35. // No foreign key constraints found, so we can remove the column
  36. return;
  37. }
  38. const dropForeignKeySql = qi.QueryGenerator.dropForeignKeyQuery(tableName, results[0].constraint_name);
  39. return qi.sequelize.query(dropForeignKeySql, options);
  40. })
  41. .then(() => {
  42. //Check if the current column is a primaryKey
  43. const primaryKeyConstraintSql = qi.QueryGenerator.getPrimaryKeyConstraintQuery(tableName, attributeName);
  44. return qi.sequelize.query(primaryKeyConstraintSql, options);
  45. })
  46. .then(([result]) => {
  47. if (!result.length) {
  48. return;
  49. }
  50. const dropConstraintSql = qi.QueryGenerator.dropConstraintQuery(tableName, result[0].constraintName);
  51. return qi.sequelize.query(dropConstraintSql, options);
  52. })
  53. .then(() => {
  54. const removeSql = qi.QueryGenerator.removeColumnQuery(tableName, attributeName);
  55. return qi.sequelize.query(removeSql, options);
  56. });
  57. };
  58. module.exports = {
  59. removeColumn
  60. };