Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider constraints when sorting columns #20

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 20 additions & 38 deletions lib/activerecord-clean-db-structure/clean_dump.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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")

This comment was marked as outdated.


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!(/^(?<table>CREATE TABLE .+?\(\n)(?<columns>.+?)(?=\n\);$)/m) do
table = $~[:table]
columns =
$~[:columns]
.split(",\n")
.sort_by { |column| column.delete('"') }
.partition { |column| !column.match?(/\A *CONSTRAINT/) }
.flatten
.join(",\n")

[table, columns].join
end
end

private

# Cleanup of schema_migrations values to prevent merge conflicts:
# - sorts all values chronological
# - places the comma's in front of each value (except for the first)
Expand Down