Is it possible to set validations based on database constraints?
I'm a big fan of having my database be the source of truth which often means setting up DB constraints.
For example:
add_check_constraint :users, "char_length(display_name) <= 70", name: "display_name_length"
Then my model would typically have a validation like this:
validates :display_name, presence: true, length: { maximum: 70 }
You can have different types of constraints too such as:
add_check_constraint :packages, "amount >= 0 AND amount <= 2147483647", name: "amount_range"
With a validation of:
validates :amount, numericality: { only_integer: true, in: 0..2_147_483_647 }
You could also have:
add_check_constraint :packages, "char_length(discount_amount_label) <= 18", name: "discount_amount_label_length"
With a validation of:
validates :discount_amount_label, allow_nil: true, length: { maximum: 19 }
In the above example the column itself allows null values so this tool could extract that from the schema.
It would be tricky to pick out all of them with perfect accuracy since character lengths and things like ranges can have arbitrary expressions but maybe it's doable long term? I think capturing most of them with a reasonable amount of accuracy to get you going will be beneficial.
For example, check out this constraint:
add_check_constraint :packages,
"discount_amount >= 0 AND discount_amount <= 2147483647 AND discount_amount <= amount",
name: "discount_amount_range"
And then its column information:
t.integer :discount_amount, null: false, default: 0
If you wanted to programmatically create a validation from this you could factor:
- It is of type integer so it must have whole numbers
- It defaults to 0 and can't be null
- It can't be larger than the amount
You could produce a validation like this:
validates :discount_amount,
numericality: { only_integer: true },
comparison: { greater_than_or_equal_to: 0, less_than: :amount }
It may save some time of checking Rails' docs to put together that validation?
Great ideas here. Happy to accept a PR that introduces some of this.