Created
October 19, 2018 13:01
-
-
Save danini-the-panini/625c2d3cecfde5f8450356ab10185d48 to your computer and use it in GitHub Desktop.
Partial schema dumber for nullobject/rein. Supports only numerical check constraints on PostgreSQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment