class ActiveRecord::ConnectionAdapters::PostgreSQLCheckConstraint

Creates CHECK constraints for PostgreSQL tables.

This class is meant to be used by PostgreSQL column and table definition and manipulation methods. There are several ways to create a CHECK constraint:

Column Definition

When creating a new table via PostgreSQLAdapter#create_table, you can specify CHECK constraints on individual columns during definition.

Example

create_table(:foo) do |t|
  t.integer :fancy_id, :check => "fancy_id != 10"
end

# Produces:
#
# CREATE TABLE "foo" (
#   "id" serial primary key,
#   "fancy_id" integer DEFAULT NULL NULL,
#   CHECK (fancy_id != 10)
# );

You can also provide an Array to :check with multiple CHECK constraints. Each CHECK constraint can be either a String containing the CHECK expression or a Hash containing :name and :expression values if you want to provide a specific name for the constraint. Otherwise, PostgreSQL will provide a name automatically. Thus, the following is equivalent to the example above:

create_table(:foo) do |t|
  t.integer :fancy_id, :check => [ { :expression => "fancy_id != 10" } ]
end

See below for additional options.

Table Definition

CHECK constraints can also be applied to the table directly rather than on a column definition.

Examples

create_table(:foo) do |t|
  t.integer :fancy_id
  t.integer :another_fancy_id
  t.check_constraint 'fancy_id != another_fancy_id'
end

# Produces:
#
# CREATE TABLE "foo" (
#   "id" serial primary key,
#   "fancy_id" integer DEFAULT NULL NULL,
#   "another_fancy_id" integer DEFAULT NULL NULL,
#   CHECK (fancy_id != another_fancy_id)
# );

create_table(:foo) do |t|
  t.integer :fancy_id
  t.integer :another_fancy_id
  t.check_constraint 'fancy_id != another_fancy_id', :name => 'my_constraint'
end

# Produces:
#
# CREATE TABLE "foo" (
#   "id" serial primary key,
#   "fancy_id" integer DEFAULT NULL NULL,
#   "another_fancy_id" integer DEFAULT NULL NULL,
#   CONSTRAINT "my_constraint" CHECK (fancy_id != another_fancy_id)
# );

See below for additional options.

Table Manipulation

You can also create new CHECK constraints outside of a table definition using PostgreSQLAdapter#add_check_constraint.

Example

add_check_constraint(:foo, 'fancy_id != 10')

# Produces:
#
# ALTER TABLE "foo" ADD CHECK (fancy_id != 10);

See below for additional options.

CHECK Constraint Options

Dropping CHECK Constraints

Like all PostgreSQL constraints, you can use PostgreSQLAdapter#drop_constraint to remove a constraint from a table.

Attributes

expression[RW]