The question I'm asking has been answered before here: Sql Server - Constraint - Allow to set column A only if column B is null and vice-versa
However, I'm not sure how to implement this in sequelize.
I noticed sequelize has a validator option you can use on it's models, and while this works during entry using the ORM, it does not add a 'true' constraint to the database since I can still insert things manually into the database. This is a problem for my use case.
validate: {
customValidator(value) {
if (value !== null && this.cash_amount !== null) {
throw new Error("Percent of Equity and Cash Amount CAN NOT both have values!");
}
}
}
How do I add a 'true constraint' like in the answer I linked?
The SQL way of doing what I want is this:
ALTER TABLE foo WITH CHECK ADD
CONSTRAINT CK_Foo_reason CHECK (
ColA IS NOT NULL AND ColB IS NULL
OR
ColA IS NULL AND ColB IS NOT NULL
)
Just like the question I linked, this is my goal:
Example
- if A is NULL, B can have a value
- if B iS NULL, A can have a value
- A and B can't have value at the same time
- A and B can't BOTH be null at the same time
Extra Info:
Sequelize appears to recognize the difference between it's validations which are done at the model level and not with the SQL engine and true constraints as it says on this article. Does this mean there is no way to do this to automatically create the constraints in sequelize?