-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
add_check_constraint.rb
111 lines (101 loc) · 3.06 KB
/
add_check_constraint.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# frozen_string_literal: true
module RuboCop
module Cop
module Migration
# Activate a check constraint in a separate migration in PostgreSQL.
#
# Adding a check constraint without `NOT VALID` blocks reads and writes in Postgres and
# blocks writes in MySQL and MariaDB while every row is checked.
#
# @safety
# Only meaningful in PostgreSQL.
#
# @example
# # bad
# class AddCheckConstraintToOrdersPrice < ActiveRecord::Migration[7.0]
# def change
# add_check_constraint :orders, 'price > 0', name: 'orders_price_positive'
# end
# end
#
# # good
# class AddCheckConstraintToOrdersPriceWithoutValidation < ActiveRecord::Migration[7.0]
# def change
# add_check_constraint :orders, 'price > 0', name: 'orders_price_positive', validate: false
# end
# end
#
# class ActivateCheckConstraintOnOrdersPrice < ActiveRecord::Migration[7.0]
# def change
# validate_check_constraint :orders, name: 'orders_price_positive'
# end
# end
class AddCheckConstraint < RuboCop::Cop::Base
extend AutoCorrector
MSG = 'Activate a check constraint in a separate migration in PostgreSQL.'
RESTRICT_ON_SEND = %i[
add_check_constraint
].freeze
# @param node [RuboCop::AST::SendNode]
# @return [void]
def on_send(node)
return unless bad?(node)
add_offense(node) do |corrector|
autocorrect(corrector, node)
end
end
private
# @!method add_check_constraint?(node)
# @param node [RuboCop::AST::SendNode]
# @return [Boolean]
def_node_matcher :add_check_constraint?, <<~PATTERN
(send
nil?
:add_check_constraint
...
)
PATTERN
# @!method add_check_constraint_with_validate_false?(node)
# @param node [RuboCop::AST::SendNode]
# @return [Boolean]
def_node_matcher :add_check_constraint_with_validate_false?, <<~PATTERN
(send
nil?
:add_check_constraint
_
_
(hash
<
(pair
(sym :validate)
false
)
...
>
)
)
PATTERN
# @param corrector [RuboCop::Cop::Corrector]
# @param node [RuboCop::AST::SendNode]
# @return [void]
def autocorrect(
corrector,
node
)
target = node.last_argument
target = target.pairs.last if target.hash_type?
corrector.insert_after(
target,
', validate: false'
)
end
# @param node [RuboCop::AST::SendNode]
# @return [Boolean]
def bad?(node)
add_check_constraint?(node) &&
!add_check_constraint_with_validate_false?(node)
end
end
end
end
end