diff --git a/lib/activerecord-clean-db-structure/clean_dump.rb b/lib/activerecord-clean-db-structure/clean_dump.rb index 8abb6c5..be05125 100644 --- a/lib/activerecord-clean-db-structure/clean_dump.rb +++ b/lib/activerecord-clean-db-structure/clean_dump.rb @@ -127,52 +127,34 @@ def run # Reduce 2+ lines of whitespace to one line of whitespace dump.gsub!(/\n{2,}/m, "\n\n") + # End the file with a single end-of-line character + dump.sub!(/\n*\z/m, "\n") if options[:order_column_definitions] == true - dump.replace(order_column_definitions(dump)) + order_column_definitions end end - def order_column_definitions(source) - result = [] - - parse_column_name = ->(line) { line.match(/^ "?([^" ]+)/)[1] } - with_column_separator = ->(line) { line.sub(/,?\n$/, ",\n") } - without_column_separator = ->(line) { line.sub(/,\n$/, "\n") } - - inside_table = false - columns = [] - - source.each_line do |source_line| - if source_line.start_with?("CREATE TABLE") - inside_table = true - columns = [] - result << source_line - elsif source_line.start_with?(");") - if inside_table - inside_table = false - columns.sort_by!(&:first) - - columns[0..-2].each do |_, line| - result << with_column_separator[line] - end - - result << without_column_separator[columns.last[1]] - end - - result << source_line - elsif inside_table - columns << [parse_column_name[source_line], source_line] - else - result << source_line - end - end + private - result.join + # Orders the columns definitions alphabetically + # - ignores quotes which surround column names that are equal to reserved PostgreSQL names. + # - keeps the columns at the top and places the constraints at the bottom. + def order_column_definitions + dump.gsub!(/^(?