Last active
August 10, 2016 19:49
-
-
Save brad-decker/22da7166549d4345d4f5a1add9fd014d to your computer and use it in GitHub Desktop.
Sequelize Postgres Migration update constraint helper for changing the value of onUpdate and onDelete.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const constraintOpts = { | |
onDelete: 'NO ACTION', | |
onUpdate: 'NO ACTION' | |
}; | |
/** | |
* updateConstraint | |
* @param {QueryInterface} queryInterface - sequelize queryInterface proviced in up/down methods of migrations | |
* @param {SequelizeModel} model - base sequelize model where the foreign key exists | |
* @param {String} fkey - foreign key field name (ex: userId) | |
* @param {SequelizeModel} referenced - The sequelize model that the foreign key references | |
* @param {Object} options - The onDelete/onUpdate values. defaults: NO ACTION. Accepts: 'CASCADE', "SET NULL", etc | |
*/ | |
export function updateConstaint(queryInterface, model, fkey, referenced, options = constraintOpts) { | |
const constraint = `"${model.getTableName()}_${fkey}_fkey"`; | |
return queryInterface.sequelize.query(` | |
ALTER TABLE "${model.getTableName()}" | |
DROP CONSTRAINT ${constraint}, | |
ADD CONSTRAINT ${constraint} | |
FOREIGN KEY ("${fkey}") | |
REFERENCES "${referenced.getTableName()}"(id) | |
ON UPDATE ${options.onUpdate} ON DELETE ${options.onDelete}; | |
`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment