debian-mirror-gitlab/rubocop/cop/migration/safer_boolean_column.rb

93 lines
2.9 KiB
Ruby
Raw Normal View History

2021-03-11 19:13:27 +05:30
# frozen_string_literal: true
2018-03-17 18:26:18 +05:30
require_relative '../../migration_helpers'
module RuboCop
module Cop
module Migration
# This cop requires a default value and disallows nulls for boolean
# columns on small tables.
#
# In general, this prevents 3-state-booleans.
# https://robots.thoughtbot.com/avoid-the-threestate-boolean-problem
#
# In particular, for the `application_settings` table, this ensures that
# upgraded installations get a proper default for the new boolean setting.
# A developer might otherwise mistakenly assume that a value in
# `ApplicationSetting.defaults` is sufficient.
#
2019-12-04 20:38:33 +05:30
# See https://gitlab.com/gitlab-org/gitlab/issues/2750 for more
2018-03-17 18:26:18 +05:30
# information.
2022-10-11 01:57:18 +05:30
class SaferBooleanColumn < RuboCop::Cop::Base
2018-03-17 18:26:18 +05:30
include MigrationHelpers
2021-04-29 21:17:54 +05:30
DEFAULT_OFFENSE = 'Boolean columns on the `%s` table should have a default. You may wish to use `add_column_with_default`.'
NULL_OFFENSE = 'Boolean columns on the `%s` table should disallow nulls.'
DEFAULT_AND_NULL_OFFENSE = 'Boolean columns on the `%s` table should have a default and should disallow nulls. You may wish to use `add_column_with_default`.'
2018-03-17 18:26:18 +05:30
def_node_matcher :add_column?, <<~PATTERN
(send nil? :add_column $...)
PATTERN
def on_send(node)
return unless in_migration?(node)
matched = add_column?(node)
return unless matched
table, _, type = matched.to_a.take(3).map(&:children).map(&:first)
opts = matched[3]
2020-11-24 15:15:51 +05:30
return unless SMALL_TABLES.include?(table) && type == :boolean
2018-03-17 18:26:18 +05:30
no_default = no_default?(opts)
nulls_allowed = nulls_allowed?(opts)
offense = if no_default && nulls_allowed
DEFAULT_AND_NULL_OFFENSE
elsif no_default
DEFAULT_OFFENSE
elsif nulls_allowed
NULL_OFFENSE
end
2022-10-11 01:57:18 +05:30
add_offense(node, message: format(offense, table)) if offense
2018-03-17 18:26:18 +05:30
end
def no_default?(opts)
return true unless opts
each_hash_node_pair(opts) do |key, value|
2018-10-15 14:42:47 +05:30
break value == 'nil' if key == :default
2018-03-17 18:26:18 +05:30
end
end
def nulls_allowed?(opts)
return true unless opts
each_hash_node_pair(opts) do |key, value|
2018-10-15 14:42:47 +05:30
break value != 'false' if key == :null
2018-03-17 18:26:18 +05:30
end
end
def each_hash_node_pair(hash_node, &block)
hash_node.each_node(:pair) do |pair|
key = hash_pair_key(pair)
value = hash_pair_value(pair)
yield(key, value)
end
end
def hash_pair_key(pair)
pair.children[0].children[0]
end
def hash_pair_value(pair)
pair.children[1].source
end
end
end
end
end