Correspondence between database restrictions and validations

After some time from the beginning of the development of your project, you may notice that you have inconsistencies between the restrictions in the database and validations in the application. In this article, I explain how gem database_consistency will help you to tidy up your database.

We discuss two possible situations. Code examples are written for ActiveRecord .

First situation


Suppose you have a table that is represented as follows:

create_table :usersdo|t|
  t.string :nameend

and class declared as:

classUser < ApplicationRecord
  validates :name, presence:trueend

In this case, the validation can be ignored using methods like: save(validate: false)and in the end, the NULL value will be stored in the database. In most cases, you would not want this to happen (because you have established validation). Thus, it would be better to have a non-zero limit in the database.

create_table :usersdo|t|
  t.string :name, null:falseend

The second situation (reverse)


Suppose you have a table that is represented as follows:

create_table :usersdo|t|
  t.string :name, null:falseend

and class declared as:

classUser < ApplicationRecord
  validates :nameend

In this case, valid?will return a value truefor records that cannot be saved. Moreover, an attempt to save such a record to the database will execute from one to several SQL queries and ultimately will return an error, rolling back the entire transaction. All these manipulations are inefficient and can be easily solved by adding validation presence: true. In most cases, you should add this validation.

A question arose before me: how to find all such cases automatically?
I present to you my gem database_consistency . At the moment, it detects most cases. As a small bonus, it will also prompt a situation where it is possible to save a record with a NULL value in a column with a non-zero limit.

Some questions remain open:

  • What other opportunities to implement?
  • Is there a need to support other ORMs, for example sequel ?

Try it yourself and share your feedback. I would appreciate any input!

Also popular now: