3-state boolean columns emphasis on NOT NULL constraint#363
3-state boolean columns emphasis on NOT NULL constraint#363armandmgt wants to merge 2 commits intorubocop:masterfrom
Conversation
Co-authored-by: Phil Pirozhkov <pirj@users.noreply.github.com>
|
Hello @koic ! Would you have some time to review this so that we can follow up with the modification of the rubocop cop ? |
|
@rubocop/style-guide-editors WDYT? |
|
|
||
| With SQL databases, if a boolean column is not given a default value, it will have three possible values: `true`, `false` and `NULL`. | ||
| With SQL databases, if a boolean column is nullable, it will have three possible values: `true`, `false` and `NULL`. | ||
| Boolean operators https://en.wikipedia.org/wiki/Three-valued_logic[work in unexpected ways] with `NULL`. |
There was a problem hiding this comment.
This article is long and math heavy, is there perhaps a better reference?
There was a problem hiding this comment.
I found https://modern-sql.com/concept/three-valued-logic and the quite succinct PostgreSQL documentation https://www.postgresql.org/docs/current/functions-logical.html
I tend to favour the first one but I'm concerned about the link becoming broken
| To avoid such situations, boolean columns should always have a default value and a `NOT NULL` constraint. | ||
| To avoid such situations, boolean columns should always have a `NOT NULL` constraint. | ||
|
|
||
| Note that when adding a boolean column to an existing table, a default value should be put in place. Otherwise the `NOT NULL` constraint will break for existing rows. |
There was a problem hiding this comment.
Or it can be added without the constraint, backfilled, and have the constraint added afterwards.
There was a problem hiding this comment.
True ! Though adding the default is safer because between the backfill and adding the constraint, new rows might be inserted
Would you like to see a small phrase about the "no constraint, backfill, constraint" procedure ?
As discussed in #343, the problem of 3-state boolean columns comes from the nullability of the column.
This PR adds emphasis on this. Default values are only required when adding a column to an existing table so
create_table :users { |t| t.boolean :active, null: false }is completely valid.fixes #343