Skip to content

Instantly share code, notes, and snippets.

@matthewrudy
Created February 26, 2017 23:40
Show Gist options
  • Select an option

  • Save matthewrudy/4400b3eee9f8dd7e15e4674359886c58 to your computer and use it in GitHub Desktop.

Select an option

Save matthewrudy/4400b3eee9f8dd7e15e4674359886c58 to your computer and use it in GitHub Desktop.

Revisions

  1. matthewrudy created this gist Feb 26, 2017.
    62 changes: 62 additions & 0 deletions db-structure-clean.rake
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    # frozen_string_literal: true
    namespace :db do
    namespace :structure do

    STRUCTURE_PATH = 'db/structure.sql'

    def clean_structure_file
    original = File.read(STRUCTURE_PATH)
    cleaned = original.dup

    # trailing whitespace
    cleaned.gsub!(/ +$/, '')

    # last line
    cleaned.gsub!(/\n+\Z/, "\n")

    # postgresql 9.5 dumps the row lock status
    cleaned.gsub!(/SET row_security = off;\n/, "")

    # postgresql 9.6 dumps the idle transaction timeout
    cleaned.gsub!(/SET idle_in_transaction_session_timeout = 0;\n/, "")

    # postgresql 9.5 dumps its details
    cleaned.gsub!(/\-\- Dumped from database version 9\.\d\.\d\n\-\- Dumped by pg_dump version 9.\d.\d\n\n/, "")

    # postgresql 9.5 doesn't show empty Tablespace
    cleaned.gsub!(/\-\- Name: ([A-Za-z0-9_ ]+); Type: (TABLE|CONSTRAINT|INDEX); Schema: public; Owner: \-$/) do |_|
    "-- Name: #{$1}; Type: #{$2}; Schema: public; Owner: -; Tablespace:"
    end

    # postgresql 9.6 shows the table and the name
    cleaned.gsub!(/\-\- Name: ([A-Za-z0-9_]+) ([A-Za-z0-9_]+);/) do |_|
    if $1 == "EXTENSION"
    "-- Name: #{$1} #{$2};"
    else
    "-- Name: #{$2};"
    end
    end

    # postgresql 9.5 puts a space here
    cleaned.gsub!(/SET search_path TO "\$user", public;/, "SET search_path TO \"$user\",public;")

    # postgresql 9.6 quotes the position field
    cleaned.gsub!(/"position" integer,/, "position integer,")

    return if original == cleaned

    File.open(STRUCTURE_PATH, 'w') do |f|
    f.write(cleaned)
    end
    end

    Rake::Task['dump'].enhance do
    clean_structure_file
    end

    desc "clean the structure.sql file"
    task :clean do
    clean_structure_file
    end
    end
    end