query-interface.js
2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'use strict';
/**
Returns an object that treats MySQL's inabilities to do certain queries.
@class QueryInterface
@static
@private
*/
const sequelizeErrors = require('../../errors');
/**
A wrapper that fixes MySQL's inability to cleanly remove columns from existing tables if they have a foreign key constraint.
@param {QueryInterface} qi
@param {string} tableName The name of the table.
@param {string} columnName The name of the attribute that we want to remove.
@param {object} options
@private
*/
async function removeColumn(qi, tableName, columnName, options) {
options = options || {};
const [results] = await qi.sequelize.query(
qi.QueryGenerator.getForeignKeyQuery(tableName.tableName ? tableName : {
tableName,
schema: qi.sequelize.config.database
}, columnName),
Object.assign({ raw: true }, options)
);
//Exclude primary key constraint
if (results.length && results[0].constraint_name !== 'PRIMARY') {
await Promise.all(results.map(constraint => qi.sequelize.query(
qi.QueryGenerator.dropForeignKeyQuery(tableName, constraint.constraint_name),
Object.assign({ raw: true }, options)
)));
}
return await qi.sequelize.query(
qi.QueryGenerator.removeColumnQuery(tableName, columnName),
Object.assign({ raw: true }, options)
);
}
/**
* @param {QueryInterface} qi
* @param {string} tableName
* @param {string} constraintName
* @param {object} options
*
* @private
*/
async function removeConstraint(qi, tableName, constraintName, options) {
const sql = qi.QueryGenerator.showConstraintsQuery(
tableName.tableName ? tableName : {
tableName,
schema: qi.sequelize.config.database
}, constraintName);
const constraints = await qi.sequelize.query(sql, Object.assign({}, options,
{ type: qi.sequelize.QueryTypes.SHOWCONSTRAINTS }));
const constraint = constraints[0];
let query;
if (!constraint || !constraint.constraintType) {
throw new sequelizeErrors.UnknownConstraintError(
{
message: `Constraint ${constraintName} on table ${tableName} does not exist`,
constraint: constraintName,
table: tableName
});
}
if (constraint.constraintType === 'FOREIGN KEY') {
query = qi.QueryGenerator.dropForeignKeyQuery(tableName, constraintName);
} else {
query = qi.QueryGenerator.removeIndexQuery(constraint.tableName, constraint.constraintName);
}
return await qi.sequelize.query(query, options);
}
exports.removeConstraint = removeConstraint;
exports.removeColumn = removeColumn;