summaryrefslogtreecommitdiff
path: root/rubocop/cop/usage_data/distinct_count_by_large_foreign_key.rb
diff options
context:
space:
mode:
authorGitLab Bot <gitlab-bot@gitlab.com>2020-08-20 18:42:06 +0000
committerGitLab Bot <gitlab-bot@gitlab.com>2020-08-20 18:42:06 +0000
commit6e4e1050d9dba2b7b2523fdd1768823ab85feef4 (patch)
tree78be5963ec075d80116a932011d695dd33910b4e /rubocop/cop/usage_data/distinct_count_by_large_foreign_key.rb
parent1ce776de4ae122aba3f349c02c17cebeaa8ecf07 (diff)
downloadgitlab-ce-6e4e1050d9dba2b7b2523fdd1768823ab85feef4.tar.gz
Add latest changes from gitlab-org/gitlab@13-3-stable-ee
Diffstat (limited to 'rubocop/cop/usage_data/distinct_count_by_large_foreign_key.rb')
-rw-r--r--rubocop/cop/usage_data/distinct_count_by_large_foreign_key.rb43
1 files changed, 43 insertions, 0 deletions
diff --git a/rubocop/cop/usage_data/distinct_count_by_large_foreign_key.rb b/rubocop/cop/usage_data/distinct_count_by_large_foreign_key.rb
new file mode 100644
index 00000000000..c10ecbcb4ba
--- /dev/null
+++ b/rubocop/cop/usage_data/distinct_count_by_large_foreign_key.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module RuboCop
+ module Cop
+ module UsageData
+ # Allows counts only for selected tables' foreign keys for `distinct_count` method.
+ #
+ # Because distinct_counts over large tables' foreign keys will take a long time
+ #
+ # @example
+ #
+ # # bad because pipeline_id points to a large table
+ # distinct_count(Ci::Build, :commit_id)
+ #
+ class DistinctCountByLargeForeignKey < RuboCop::Cop::Cop
+ MSG = 'Avoid doing `%s` on foreign keys for large tables having above 100 million rows.'.freeze
+
+ def_node_matcher :distinct_count?, <<-PATTERN
+ (send _ $:distinct_count $...)
+ PATTERN
+
+ def on_send(node)
+ distinct_count?(node) do |method_name, method_arguments|
+ next unless method_arguments && method_arguments.length >= 2
+ next if allowed_foreign_key?(method_arguments[1])
+
+ add_offense(node, location: :selector, message: format(MSG, method_name))
+ end
+ end
+
+ private
+
+ def allowed_foreign_key?(key)
+ key.type == :sym && allowed_foreign_keys.include?(key.value)
+ end
+
+ def allowed_foreign_keys
+ cop_config['AllowedForeignKeys'] || []
+ end
+ end
+ end
+ end
+end