Change default referential action
See original GitHub issueProblem
Associations (foreign keys) in Sequelize define a rather opinionated default referential action for ON UPDATE
/ ON DELETE
clauses.
For ON UPDATE
, Sequelize defaults to CASCADE
.
For ON DELETE
, Sequelize defaults to SET NULL
if the source field allows null values; otherwise, CASCADE
is the default.
It would be convenient to set RESTRICT
or NO ACTION
as the default (database-wide) in some circumstances. In MySQL, for example, the default referential action is RESTRICT
when not explicitly specified; Sequelizes seems to override these defaults.
Describe the solution you’d like
It would be nice to override the “default” referential action for ON UPDATE
and ON DELETE
when associations are created. It can get annoying to override this behavior for every single association in the database if RESTRICT
is the general rule / policy. This could be done in the options
Object passed to the new Sequelize instance (see usage example below).
Why should this be in Sequelize This is a small change (probably ~10 lines of code), but it gives extra flexibility to the developer without requiring the developer to be verbose with association definitions.
Describe alternatives you’ve considered
Another possible solution is creating some sort of hook that allows one to change the default onDelete
and onUpdate
options of an association. I don’t know of any such hook at this time.
Usage example
const db = new Sequelize(config.database, config.username, config.password, {
host: config.host,
// New `associations` key
associations: {
onDelete: 'RESTRICT',
onUpdate: 'CASCADE',
}
})
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:8 (3 by maintainers)
We discussed whether to accept this feature request at today’s meeting. We did not feel it was necessary to implement this, as this is already achievable with hooks, and we felt the demand was too low for the extra complexity.
Example of how this can be handled with hooks:
It’s unfortunately a bit verbose, but you only need to write it once.
We can revisit this at a later date if there is enough demand for it.
Also, thanks to you, I just learned that
||=
is a thing in JavaScript.