Database constraints made easy for ActiveRecord.
Data integrity is a good thing. Constraining the values allowed by your application at the database-level, rather than at the application-level, is a more robust way of ensuring your data stays sane.
Unfortunately, ActiveRecord doesn't encourage (or even allow) you to use database integrity without resorting to hand-crafted SQL. Rein (pronounced "rain") adds a handful of methods to your ActiveRecord migrations so that you can easily tame the data in your database.
All methods in the DSL are automatically reversible, so you can take advantage of reversible Rails migrations.
Install the gem:
> gem install reinAdd a constraint to your migrations:
class CreateAuthorsTable < ActiveRecord::Migration
def change
create_table :authors do |t|
t.string :name, null: false
end
# An author must have a name.
add_presence_constraint :authors, :name
end
endThe table below summarises the constraint operations provided by Rein and whether they support validation.
| Rein name | Rein method | SQL | Supports NOT VALID? |
|---|---|---|---|
| Foreign Key | add_foreign_key_constraint |
FOREIGN KEY |
yes |
| Unique | add_unique_constraint |
UNIQUE |
no |
| Exclusion | add_exclusion_constraint |
EXCLUDE |
no |
| Inclusion | add_inclusion_constraint |
CHECK |
yes |
| Length | add_length_constraint |
CHECK |
yes |
| Match | add_match_constraint |
CHECK |
yes |
| Numericality | add_numericality_constraint |
CHECK |
yes |
| Presence | add_presence_constraint |
CHECK |
yes |
| Null | add_null_constraint |
CHECK |
yes |
| Check | add_check_constraint |
CHECK |
yes |
A foreign key constraint specifies that the values in a column must match the values appearing in some row of another table.
For example, let's say that we want to constrain the author_id column in the
books table to one of the id values in the authors table:
add_foreign_key_constraint :books, :authorsAdding a foreign key doesn't automatically create an index on the referenced
column. Having an index will generally speed up any joins you perform on the
foreign key. To create an index you can specify the index option:
add_foreign_key_constraint :books, :authors, index: trueRein will automatically infer the column names for the tables, but if we need
to be explicit we can using the referenced and referencing options:
add_foreign_key_constraint :books, :authors, referencing: :author_id, referenced: :idWe can also specify the behaviour when one of the referenced rows is updated or deleted:
add_foreign_key_constraint :books, :authors, on_delete: :cascade, on_update: :cascadeHere's all the options for specifying the delete/update behaviour:
no_action: if any referencing rows still exist when the constraint is
checked, an error is raised; this is the default behavior if you do not
specify anything.cascade: when a referenced row is deleted, row(s) referencing it should be
automatically deleted as well.set_null: sets the referencing columns to be nulls when the referenced row
is deleted.set_default: sets the referencing columns to its default values when the
referenced row is deleted.restrict: prevents deletion of a referenced row.To remove a foreign key constraint:
remove_foreign_key_constraint :books, :authorsA unique constraint specifies that certain columns in a table must be unique.
For example, all the books should have unique ISBNs:
add_unique_constraint :books, :isbnBy default, the database checks unique constraints immediately (i.e. as soon as a record is created or updated). If a record with a duplicate value exists, then the database will raise an error.
Sometimes it is necessary to wait until the end of a transaction to do the checking (e.g. maybe you want to swap the ISBNs for two books). To do so, you need to tell the database to defer checking the constraint until the end of the current transaction:
BEGIN;
SET CONSTRAINTS books_isbn_unique DEFERRED;
UPDATE books SET isbn = 'foo' WHERE id = 1;
UPDATE books SET isbn = 'bar' WHERE id = 2;
COMMIT;This blog
post offers
a good explanation of how to do this in a Rails app when using the
acts_as_list plugin.
If you always want to defer checking a unique constraint, then you can set
the deferred option to true:
add_unique_constraint :books, :isbn, deferred: trueIf you really don't want the ability to optionally defer a unique constraint in
a transaction, then you can set the deferrable option to false:
add_unique_constraint :authors, :name, deferrable: falseAn exclusion constraint is a lot like a unique constraint, but more general.
Whereas a unique constraint forbids two rows from having all constrained
columns be equal, an exclusion constraint forbids two rows from having all
constrained columns be some relationship, where the relationship is up to you
(and can be different for each column). For instance you can prevent two
ranges from overlapping with the && operator. You can read more in the
Postgres
docs
or a slideshow by the author, Jeff
Davis.
For example, no two people should own copyright to a book at the same time:
add_exclusion_constraint :book_owners, [[:book_id, '='], [:owned_during, '&&']], using: :gistBy default, the database checks exclusion constraints immediately (i.e. as soon as a record is created or updated). If a record with an excluded value exists, then the database will raise an error.
Sometimes it is necessary to wait until the end of a transaction to do the checking (e.g. maybe you want to move the date a copyright changed hands). To do so, you need to tell the database to defer checking the constraint until the end of the current transaction:
BEGIN;
SET CONSTRAINTS book_owners_exclude DEFERRED;
UPDATE book_owners
SET owned_during = tsrange(lower(owned_during), '1943-12-22')
WHERE book_id = 1 AND owner_id = 1;
UPDATE book_owners
SET owned_during = tsrange('1943-12-22', upper(owned_during))
WHERE book_id = 1 AND owner_id = 2;
COMMIT;If you always want to defer checking a unique constraint, then you can set
the deferred option to true:
add_exclusion_constraint :book_owners, [[:book_id, '='], [:owned_during, '&&']], using: :gist, deferred: trueIf you really don't want the ability to optionally defer a unique constraint in
a transaction, then you can set the deferrable option to false:
add_exclusion_constraint :book_owners, [[:book_id, '='], [:owned_during, '&&']], using: :gist, deferrable: falseIf you want to specify something like a operator class for a attribute specific attribute, you can add it to the attribute specification between attribute name and the operator:
add_exclusion_constraint :book_owners, [[:book_id, :gist_int8_ops, '='], [:owned_during, '&&']], using: :gistIf you want to set the constraint to a subset of the table, you can use a where
option to set the filter condition:
add_exclusion_constraint :books, [[:isbn, '=']], using: :gist, where: "state='active'"An inclusion constraint specifies the possible values that a column value can take.
For example, we can ensure that state column values can only ever be
available or on_loan:
add_inclusion_constraint :books, :state, in: %w[available on_loan]To remove an inclusion constraint:
remove_inclusion_constraint :books, :stateYou may also include an if option to enforce the constraint only under
certain conditions, like so:
add_inclusion_constraint :books, :state,
in: %w[available on_loan],
if: "deleted_at IS NULL"You may optionally provide a name option to customize the name:
add_inclusion_constraint :books, :state,
in: %w[available on_loan],
name: "books_state_is_valid"A length constraint specifies the range of values that the length of a string column value can take.
For example, we can ensure that the call_number can only ever be a
value between 1 and 255:
add_length_constraint :books, :call_number,
greater_than_or_equal_to: 1,
less_than_or_equal_to: 255Here's all the options for constraining the values:
equal_tonot_equal_toless_thanless_than_or_equal_togreater_thangreater_than_or_equal_toYou may also include an if option to enforce the constraint only under
certain conditions, like so:
add_length_constraint :books, :call_number,
greater_than_or_equal_to: 1,
less_than_or_equal_to: 12,
if: "status = 'published'"You may optionally provide a name option to customize the name:
add_length_constraint :books, :call_number,
greater_than_or_equal_to: 1,
less_than_or_equal_to: 12,
name: "books_call_number_is_valid"To remove a length constraint:
remove_length_constraint :books, :call_numberA match constraint ensures that a string column value matches (or does not match) a POSIX-style regular expression.
For example, we can ensure that the title can only contain printable ASCII
characters, but not ampersands:
add_match_constraint :books, :title, accepts: '\A[ -~]*\Z', rejects: '&'Match constraints are case-sensitive. You make them case-insensitive by using
accepts_case_insensitive and rejects_case_insensitive instead of accepts
or rejects.
If you only want to enforce the constraint under certain conditions,
you can pass an optional if option:
add_match_constraint :books, :title, accepts: '\A[ -~]*\Z', if: "status = 'published'"You may optionally provide a name option to customize the name:
add_match_constraint :books, :title, name: "books_title_is_valid"To remove a match constraint:
remove_match_constraint :books, :titleA numericality constraint specifies the range of values that a numeric column value can take.
For example, we can ensure that the publication_month can only ever be a
value between 1 and 12:
add_numericality_constraint :books, :publication_month,
greater_than_or_equal_to: 1,
less_than_or_equal_to: 12Here's all the options for constraining the values:
equal_tonot_equal_toless_thanless_than_or_equal_togreater_thangreater_than_or_equal_toYou may also include an if option to enforce the constraint only under
certain conditions, like so:
addNo open issues yet, or sync has not completed.