Created
May 13, 2015 14:44
-
-
Save scarfacedeb/bdf4e7b25c143cd87de7 to your computer and use it in GitHub Desktop.
Simple script to find missing unique constrains for uniqueness validations in rails
This file contains hidden or 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
# run from the root: ruby find_missing_indices.rb | |
require File.expand_path("../config/environment", __FILE__) | |
Rails.application.eager_load! | |
models = ActiveRecord::Base.descendants | |
conn = ActiveRecord::Base.connection | |
missing_index = [] | |
models.each do |model| | |
uniqueness_validators = model.validators.select {|v| v.class == ActiveRecord::Validations::UniquenessValidator } | |
uniqueness_validators.each do |validation| | |
attrs = validation.attributes.dup | |
attrs.concat Array(validation.options[:scope]) if validation.options.key? :scope | |
attrs = attrs.map(&:to_s).map { |attr| model.column_names.include?(attr) ? attr : "#{attr}_id" }.sort | |
unique_indices = conn.indexes(model.table_name).select { |idx| idx.unique } | |
unless unique_indices.any? { |idx| idx.columns.sort == attrs } | |
missing_index << [model, validation] | |
end | |
end | |
end | |
puts "=== Missing indices ===" | |
missing_index.each do |(model, validation)| | |
msg = "#{model}: validates #{validation.attributes}" | |
msg << " (scope: #{validation.options[:scope]})" if validation.options.key? :scope | |
puts msg | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment