Module: DynamicMigrations::ActiveRecord::Migrators::Validation

Included in:
DynamicMigrations::ActiveRecord::Migrators
Defined in:
lib/dynamic_migrations/active_record/migrators/validation.rb

Instance Method Summary collapse

Instance Method Details

#add_validation(table_name, name:, initially_deferred: false, deferrable: false, comment: nil, &block) ⇒ Object

this exists because because the standard rails migration does not support deffered constraints



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/dynamic_migrations/active_record/migrators/validation.rb', line 6

def add_validation table_name, name:, initially_deferred: false, deferrable: false, comment: nil, &block
  unless block
    raise MissingFunctionBlockError, "create_function requires a block"
  end
  # todo - remove this once steep/rbs can better handle blocks
  unless block.is_a? NilClass
    sql = block.call.strip
  end

  if initially_deferred == true && deferrable == false
    raise DeferrableOptionsError, "A constraint can only be initially deferred if it is also deferrable"
  end

  # allow it to be deferred, and defer it by default
  deferrable_sql = if initially_deferred
    "DEFERRABLE INITIALLY DEFERRED"

  # allow it to be deferred, but do not deferr by default
  elsif deferrable
    "DEFERRABLE INITIALLY IMMEDIATE"

  # it can not be deferred (this is the default)
  else
    "NOT DEFERRABLE"
  end

  execute <<~SQL
    ALTER TABLE #{table_name}
      ADD CONSTRAINT #{name}
        CHECK (#{sql})
        #{deferrable_sql};
  SQL

  if comment.is_a? String
    set_validation_comment table_name, name, comment
  end
end

#remove_validation(table_name, name) ⇒ Object



44
45
46
47
48
49
# File 'lib/dynamic_migrations/active_record/migrators/validation.rb', line 44

def remove_validation table_name, name
  execute <<~SQL
    ALTER TABLE #{table_name}
      DROP CONSTRAINT #{name};
  SQL
end

#remove_validation_comment(table_name, validation_name) ⇒ Object

remove a validation comment



59
60
61
62
63
# File 'lib/dynamic_migrations/active_record/migrators/validation.rb', line 59

def remove_validation_comment table_name, validation_name
  execute <<~SQL
    COMMENT ON CONSTRAINT #{validation_name} ON #{schema_name}.#{table_name} IS NULL;
  SQL
end

#set_validation_comment(table_name, validation_name, comment) ⇒ Object

add a comment to the validation



52
53
54
55
56
# File 'lib/dynamic_migrations/active_record/migrators/validation.rb', line 52

def set_validation_comment table_name, validation_name, comment
  execute <<~SQL
    COMMENT ON CONSTRAINT #{validation_name} ON #{schema_name}.#{table_name} IS #{quote comment};
  SQL
end