gitlab-org--gitlab-foss/rubocop/cop/migration/column_with_default.rb
Yorick Peterse c740445ad3
Added RuboCop cops for checking DB migrations
There are currently two cops for this:

* Migration/AddIndex: checks if indexes are added concurrently
* Migration/ColumnWithDefault: checks if columns with default values are
  added in a concurrent manner

Both cops are fairly simple and make no attempt at correcting the code
as this is quite hard to do (e.g. modifications may need to be applied
in various places in the same file). They however should provide enough
to catch people ignoring the comments in generated migrations telling
them to use add_concurrent_index or add_column_with_default.
2016-06-29 14:14:02 +02:00

50 lines
1.3 KiB
Ruby

module RuboCop
module Cop
module Migration
# Cop that checks if columns are added in a way that doesn't require
# downtime.
class ColumnWithDefault < RuboCop::Cop::Cop
include MigrationHelpers
WHITELISTED_TABLES = [:application_settings]
MSG = 'add_column with a default value requires downtime, ' \
'use add_column_with_default instead'
def on_send(node)
return unless in_migration?(node)
name = node.children[1]
return unless name == :add_column
# Ignore whitelisted tables.
return if table_whitelisted?(node.children[2])
opts = node.children.last
return unless opts && opts.type == :hash
opts.each_node(:pair) do |pair|
if hash_key_type(pair) == :sym && hash_key_name(pair) == :default
add_offense(node, :selector)
end
end
end
def table_whitelisted?(symbol)
symbol && symbol.type == :sym &&
WHITELISTED_TABLES.include?(symbol.children[0])
end
def hash_key_type(pair)
pair.children[0].type
end
def hash_key_name(pair)
pair.children[0].children[0]
end
end
end
end
end