Sha256: c95ada2f20f8d924a3e3db6b9107ac3d2abb912c297ef17b8280167c8881ab89

Contents?: true

Size: 1021 Bytes

Versions: 5

Compression:

Stored size: 1021 Bytes

Contents

# frozen_string_literal: true

class AddUniqueNameIndexToCountySubdivisions < ActiveRecord::Migration[5.0]
  def up
    return if index_exists?(:us_geo_county_subdivisions, [:name, :county_geoid], name: "index_us_geo_county_subdivisions_on_unique_name")

    duplicates_sql = <<~SQL
      SELECT t2.geoid, t2.name
      FROM us_geo_county_subdivisions t1,
           us_geo_county_subdivisions t2
      WHERE t1.geoid < t2.geoid
        AND t1.county_geoid = t2.county_geoid
        AND t1.name = t2.name
    SQL

    update_sql = "UPDATE us_geo_county_subdivisions SET name = ? WHERE geoid = ?"

    select_all(duplicates_sql).each do |row|
      update ActiveRecord::Base.sanitize_sql([update_sql, "#{row["name"]} (duplicate)", row["geoid"]])
    end

    add_index :us_geo_county_subdivisions, [:name, :county_geoid], unique: true, name: "index_us_geo_county_subdivisions_on_unique_name"
  end

  def down
    remove_index :us_geo_county_subdivisions, name: "index_us_geo_county_subdivisions_on_unique_name"
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
us_geo-2.1.1 db/migrate/20230417000200_add_unique_name_index_to_county_subdivisions.rb
us_geo-2.1.0 db/migrate/20230417000200_add_unique_name_index_to_county_subdivisions.rb
us_geo-2.0.4 db/migrate/20230417000200_add_unique_name_index_to_county_subdivisions.rb
us_geo-2.0.3 db/migrate/20230417000200_add_unique_name_index_to_county_subdivisions.rb
us_geo-2.0.2 db/migrate/20230417000200_add_unique_name_index_to_county_subdivisions.rb