2021-03-11 19:13:27 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
require_relative '../../migration_helpers'
|
|
|
|
|
|
|
|
module RuboCop
|
|
|
|
module Cop
|
|
|
|
module Migration
|
|
|
|
# Cop that checks if `add_concurrent_foreign_key` is used instead of
|
|
|
|
# `add_foreign_key`.
|
2022-10-11 01:57:18 +05:30
|
|
|
class AddConcurrentForeignKey < RuboCop::Cop::Base
|
2017-08-17 22:00:37 +05:30
|
|
|
include MigrationHelpers
|
|
|
|
|
2021-04-29 21:17:54 +05:30
|
|
|
MSG = '`add_foreign_key` requires downtime, use `add_concurrent_foreign_key` instead'
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2020-05-24 23:13:21 +05:30
|
|
|
def_node_matcher :false_node?, <<~PATTERN
|
2021-01-03 14:25:43 +05:30
|
|
|
(false)
|
|
|
|
PATTERN
|
|
|
|
|
|
|
|
def_node_matcher :with_lock_retries?, <<~PATTERN
|
|
|
|
(:send nil? :with_lock_retries)
|
2020-05-24 23:13:21 +05:30
|
|
|
PATTERN
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
def on_send(node)
|
|
|
|
return unless in_migration?(node)
|
|
|
|
|
|
|
|
name = node.children[1]
|
|
|
|
|
2021-01-03 14:25:43 +05:30
|
|
|
return unless name == :add_foreign_key
|
|
|
|
return if in_with_lock_retries?(node)
|
|
|
|
return if not_valid_fk?(node)
|
|
|
|
|
2022-10-11 01:57:18 +05:30
|
|
|
add_offense(node.loc.selector)
|
2017-08-17 22:00:37 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def method_name(node)
|
|
|
|
node.children.first
|
|
|
|
end
|
2020-05-24 23:13:21 +05:30
|
|
|
|
|
|
|
def not_valid_fk?(node)
|
|
|
|
node.each_node(:pair).any? do |pair|
|
|
|
|
pair.children[0].children[0] == :validate && false_node?(pair.children[1])
|
|
|
|
end
|
|
|
|
end
|
2021-01-03 14:25:43 +05:30
|
|
|
|
|
|
|
def in_with_lock_retries?(node)
|
|
|
|
node.each_ancestor(:block).any? do |parent|
|
|
|
|
with_lock_retries?(parent.to_a.first)
|
|
|
|
end
|
|
|
|
end
|
2017-08-17 22:00:37 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|