Skip to content

Instantly share code, notes, and snippets.

@brad-decker
Last active August 10, 2016 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brad-decker/22da7166549d4345d4f5a1add9fd014d to your computer and use it in GitHub Desktop.
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.
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