Skip to content

Instantly share code, notes, and snippets.

@danini-the-panini
Created October 19, 2018 13:01
Show Gist options
  • Save danini-the-panini/625c2d3cecfde5f8450356ab10185d48 to your computer and use it in GitHub Desktop.
Save danini-the-panini/625c2d3cecfde5f8450356ab10185d48 to your computer and use it in GitHub Desktop.

Revisions

  1. Daniel Smith created this gist Oct 19, 2018.
    43 changes: 43 additions & 0 deletions rein_schema_dumper.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    module Rein::SchemaDumper
    def tables(stream)
    super
    check_constraints(stream)
    end

    def check_constraints(stream)
    constraints = @connection.execute <<-SQL
    select *
    from information_schema.check_constraints as c, information_schema.constraint_column_usage as u
    where c.constraint_name = u.constraint_name
    and c.constraint_schema = 'public'
    and u.constraint_schema = 'public'
    SQL

    if constraints.any?
    stream.puts
    end

    constraints.each do |constraint|
    table_name = constraint['table_name']
    column_name = constraint['column_name']
    check_clause = constraint['check_clause']

    case check_clause
    when /#{column_name}\s+(>=|>|=|!=|<|<=)\s+(\d+)/
    definition = case $1
    when '>=' then 'greater_than_or_equal_to'
    when '>' then 'greater_than'
    when '<=' then 'less_than_or_equal_to'
    when '<' then 'less_than'
    when '=' then 'equal_to'
    when '!=' then 'not_equal_to'
    end
    stream.puts <<-RUBY
    add_numericality_constraint "#{table_name}", "#{column_name}", #{definition}: #{$2}
    RUBY
    end
    end
    end
    end

    ActiveRecord::SchemaDumper.prepend Rein::SchemaDumper