rubocop-dev_doc 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/config/default.yml +23 -0
- data/lib/rubocop/cop/dev_doc/rails/create_or_find_by.rb +66 -0
- data/lib/rubocop/cop/dev_doc/rails/find_or_create_by_justification.rb +106 -0
- data/lib/rubocop/cop/dev_doc/rails/rescue_record_not_unique_index.rb +212 -0
- data/lib/rubocop/cop/dev_doc/rails/unique_index_backing.rb +205 -0
- data/lib/rubocop/dev_doc/version.rb +1 -1
- metadata +5 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 34e773b91c19e7fcf99043ec8241ccfda6fedddd52bc17e11b3693852a226710
|
|
4
|
+
data.tar.gz: cd2f7c295e98c4963c0914ecf1131a192d69a905315e533f3f4e9571245c01af
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: f517e4d2f400bd915fd40eb9efde0e4cfd30c13f2e4fb289a2cf1bf489dc27a2888db2d0ab3482c3648f4e33397274fdae4262ba593bf31ed5c1720b073637b9
|
|
7
|
+
data.tar.gz: 62751bf6320874a8834de4bff344bf2fd2e905d71371c03aa7402812c7909528d25acaf3ccbb1f31490c0b8adf30b6a77376de399c83384efba2588639b21380
|
data/config/default.yml
CHANGED
|
@@ -132,6 +132,29 @@ DevDoc/Rails/AvoidBypassingValidation:
|
|
|
132
132
|
- "spec/**/*"
|
|
133
133
|
- "test/**/*"
|
|
134
134
|
|
|
135
|
+
DevDoc/Rails/CreateOrFindBy:
|
|
136
|
+
Description: "`create_or_find_by` / `create_or_find_by!` are banned — their preconditions are the exception, not the rule. Use the two rules of 03_model.md item 14 instead."
|
|
137
|
+
Enabled: true
|
|
138
|
+
Include:
|
|
139
|
+
- "app/**/*.rb"
|
|
140
|
+
- "lib/**/*.rb"
|
|
141
|
+
|
|
142
|
+
DevDoc/Rails/FindOrCreateByJustification:
|
|
143
|
+
Description: "`find_or_create_by` is the rule-1 exception of 03_model.md item 14 and needs an adjacent `unique-write:` comment; strict mode flags literal attributes a unique index already covers (that site is rule 2)."
|
|
144
|
+
Enabled: true
|
|
145
|
+
Include:
|
|
146
|
+
- "app/**/*.rb"
|
|
147
|
+
- "lib/**/*.rb"
|
|
148
|
+
JustificationMarker: "unique-write:"
|
|
149
|
+
Strict: true
|
|
150
|
+
|
|
151
|
+
DevDoc/Rails/RescueRecordNotUniqueIndex:
|
|
152
|
+
Description: "A `rescue ActiveRecord::RecordNotUnique` must guard a write inside `transaction(requires_new: true)` that a unique index backs (literal attributes against the schema, or a `# unique_index: <name>` tag) — 03_model.md item 14, rule 2."
|
|
153
|
+
Enabled: true
|
|
154
|
+
Include:
|
|
155
|
+
- "app/**/*.rb"
|
|
156
|
+
- "lib/**/*.rb"
|
|
157
|
+
|
|
135
158
|
DevDoc/Migration/DateColumnNaming:
|
|
136
159
|
Description: "Date columns should end with `_on`; datetime columns should end with `_at`."
|
|
137
160
|
Enabled: true
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
module RuboCop
|
|
2
|
+
module Cop
|
|
3
|
+
module DevDoc
|
|
4
|
+
module Rails
|
|
5
|
+
# `create_or_find_by` / `create_or_find_by!` are banned; uniqueness
|
|
6
|
+
# writes follow the two rules of 03_model.md item 14 instead.
|
|
7
|
+
#
|
|
8
|
+
# ## Rationale
|
|
9
|
+
# `create_or_find_by` looks like the safe default for a
|
|
10
|
+
# unique-constrained row, but it is only correct under preconditions
|
|
11
|
+
# that are the exception, not the rule: a FULL non-partial unique
|
|
12
|
+
# index over EXACTLY the passed attributes (a partial or wider index
|
|
13
|
+
# lets the INSERT succeed where the method assumed it would conflict),
|
|
14
|
+
# literal attributes, and no uniqueness validation sabotaging the
|
|
15
|
+
# INSERT (Rails tries the validation first, so a scope the index does
|
|
16
|
+
# not share turns the race into `RecordInvalid` instead of the
|
|
17
|
+
# re-fetch path). Soft-deletable models under a plain unique index
|
|
18
|
+
# break it further: the conflict re-fetch uses the default scope, so
|
|
19
|
+
# a soft-deleted winner turns the method into `nil`/`RecordNotFound`.
|
|
20
|
+
#
|
|
21
|
+
# The two rules that replace it (03_model.md item 14): rule 2, the
|
|
22
|
+
# default — the unique index is the arbiter (`transaction(requires_new:
|
|
23
|
+
# true)` around the write, `rescue ActiveRecord::RecordNotUnique`, the
|
|
24
|
+
# rescue body states what losing the race means; policed by
|
|
25
|
+
# `DevDoc/Rails/RescueRecordNotUniqueIndex`); rule 1, the exception —
|
|
26
|
+
# `find_or_create_by` only when no unique index is possible and a rare
|
|
27
|
+
# duplicate is tolerable, stated in an adjacent justification comment
|
|
28
|
+
# (policed by `DevDoc/Rails/FindOrCreateByJustification`). Total
|
|
29
|
+
# enforcement, zero judgment: the method name itself is the offense.
|
|
30
|
+
#
|
|
31
|
+
# @example
|
|
32
|
+
# # bad
|
|
33
|
+
# Membership.create_or_find_by!(member: m, group: g)
|
|
34
|
+
#
|
|
35
|
+
# # good — rule 2: the index arbitrates, the rescue states the loss
|
|
36
|
+
# def self.add_member!(member, group)
|
|
37
|
+
# transaction(requires_new: true) do
|
|
38
|
+
# create!(member: member, group: group)
|
|
39
|
+
# end
|
|
40
|
+
# rescue ActiveRecord::RecordNotUnique
|
|
41
|
+
# # Lost the (group, member) race: the winner's row is the same membership.
|
|
42
|
+
# find_by!(member: member, group: group)
|
|
43
|
+
# end
|
|
44
|
+
#
|
|
45
|
+
# # good — rule 1 (only where no index is possible; comment required)
|
|
46
|
+
# # unique-write: no index possible here because ...; a rare duplicate is tolerable because ...
|
|
47
|
+
# Widget.find_or_create_by!(token: token)
|
|
48
|
+
class CreateOrFindBy < Base
|
|
49
|
+
MSG = '`create_or_find_by%<bang>s` is banned: its preconditions (a full, non-partial unique ' \
|
|
50
|
+
'index over exactly the passed attributes, literal attributes, no uniqueness ' \
|
|
51
|
+
'validation on the INSERT path) are the exception, not the rule. Use the two rules ' \
|
|
52
|
+
'of 03_model.md item 14 instead: the index as arbiter (rule 2) or a justified ' \
|
|
53
|
+
'find_or_create_by (rule 1).'.freeze
|
|
54
|
+
|
|
55
|
+
RESTRICT_ON_SEND = %i[create_or_find_by create_or_find_by!].freeze
|
|
56
|
+
|
|
57
|
+
def on_send(node)
|
|
58
|
+
add_offense(node.loc.selector, message: format(MSG, bang: node.method_name.to_s.end_with?('!') ? '!' : ''))
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
alias on_csend on_send
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
require_relative 'unique_index_backing'
|
|
2
|
+
|
|
3
|
+
module RuboCop
|
|
4
|
+
module Cop
|
|
5
|
+
module DevDoc
|
|
6
|
+
module Rails
|
|
7
|
+
# Rule 1 of 03_model.md item 14: `find_or_create_by` is the rare
|
|
8
|
+
# exception for unique-constrained rows and must carry an adjacent
|
|
9
|
+
# justification comment; when a unique index already backs the
|
|
10
|
+
# written attributes, the site is rule 2 instead (the index is the
|
|
11
|
+
# arbiter — attempt, rescue, state the loss).
|
|
12
|
+
#
|
|
13
|
+
# ## Rationale
|
|
14
|
+
# `find_or_create_by` is SELECT-first, so under a race both callers
|
|
15
|
+
# see "not found" and both INSERT; without a rescue one of them
|
|
16
|
+
# 500s. The two-rules standard (03_model.md item 14) therefore makes
|
|
17
|
+
# the index-arbiter shape the default and keeps `find_or_create_by`
|
|
18
|
+
# only where NO unique index is possible and a rare duplicate (or a
|
|
19
|
+
# rescued conflict) is tolerable — a claim the author must state
|
|
20
|
+
# where a reviewer reads it, in an adjacent `unique-write:` comment.
|
|
21
|
+
#
|
|
22
|
+
# Strict mode (on by default) reads the schema: literal attribute
|
|
23
|
+
# keys on a CONSTANT receiver that resolve to a covering unique
|
|
24
|
+
# index produce a different offense — the justification, whatever it
|
|
25
|
+
# says, is factually wrong there, because an index exists and rule 2
|
|
26
|
+
# applies. Sites whose attributes do not resolve (dynamic hashes,
|
|
27
|
+
# association receivers) are silently skipped by strict mode and
|
|
28
|
+
# judged only on the comment.
|
|
29
|
+
#
|
|
30
|
+
# `DevDoc/Rails/CreateOrFindBy` bans the `create_or_find_by` family
|
|
31
|
+
# separately (total enforcement, no justification escapes it).
|
|
32
|
+
#
|
|
33
|
+
# ## Configuration
|
|
34
|
+
# `JustificationMarker` (default: `unique-write:`) — accepted
|
|
35
|
+
# trailing on the flagged line or in the contiguous comment block
|
|
36
|
+
# ending on the line directly above it (the shared
|
|
37
|
+
# adjacent-justification contract). `Strict` (default: true) —
|
|
38
|
+
# enable the schema-backed "this should be rule 2" pass.
|
|
39
|
+
#
|
|
40
|
+
# @example
|
|
41
|
+
# # bad — no stated reason for the rule-1 exception
|
|
42
|
+
# Widget.find_or_create_by!(token: token)
|
|
43
|
+
#
|
|
44
|
+
# # good — rule 1, justified
|
|
45
|
+
# # unique-write: tokens are recycled weekly with no stable key to index; a rare
|
|
46
|
+
# # duplicate pair is merged by the nightly sweep
|
|
47
|
+
# Widget.find_or_create_by!(token: token)
|
|
48
|
+
#
|
|
49
|
+
# # bad (strict) — an index covers these columns; this is rule 2
|
|
50
|
+
# Widget.find_or_create_by!(token: token) # index_widgets_on_token exists
|
|
51
|
+
class FindOrCreateByJustification < Base
|
|
52
|
+
include Auth::AdjacentJustification
|
|
53
|
+
include UniqueIndexBacking
|
|
54
|
+
|
|
55
|
+
MSG = '`find_or_create_by%<bang>s` is the rule-1 exception of 03_model.md item 14 and needs an ' \
|
|
56
|
+
'adjacent "%<marker>s <why>" comment stating why no unique index is possible here and why a ' \
|
|
57
|
+
'rare duplicate is tolerable.'.freeze
|
|
58
|
+
STRICT_MSG = 'A unique index (%<index>s) covers these attributes — this write is rule 2 of ' \
|
|
59
|
+
'03_model.md item 14: attempt the write inside `transaction(requires_new: true)`, rescue ' \
|
|
60
|
+
'`ActiveRecord::RecordNotUnique`, and state what losing the race means. (No comment ' \
|
|
61
|
+
'saves it: the justification would be factually wrong.)'.freeze
|
|
62
|
+
|
|
63
|
+
RESTRICT_ON_SEND = %i[find_or_create_by find_or_create_by!].freeze
|
|
64
|
+
|
|
65
|
+
def on_send(node)
|
|
66
|
+
if (index = strict_offending_index(node))
|
|
67
|
+
add_offense(node.loc.selector, message: format(STRICT_MSG, index: index.name))
|
|
68
|
+
elsif !adjacent_justification?(node)
|
|
69
|
+
add_offense(node.loc.selector, message: missing_justification_message(node))
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
alias on_csend on_send
|
|
74
|
+
|
|
75
|
+
private
|
|
76
|
+
|
|
77
|
+
# The covering unique index when strict mode is on, the write's
|
|
78
|
+
# attributes are a literal hash, and a CONSTANT receiver names the
|
|
79
|
+
# table — nil otherwise (silent skip, per the cop's doc).
|
|
80
|
+
def strict_offending_index(node)
|
|
81
|
+
return nil unless strict? && node.receiver&.const_type?
|
|
82
|
+
|
|
83
|
+
keys = write_attribute_keys(node)
|
|
84
|
+
return nil unless keys
|
|
85
|
+
|
|
86
|
+
table = receiver_table(node.receiver)
|
|
87
|
+
covering_unique_index(table: table, attribute_keys: keys)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def strict?
|
|
91
|
+
cop_config.fetch('Strict', true)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def missing_justification_message(node)
|
|
95
|
+
bang = node.method_name.to_s.end_with?('!') ? '!' : ''
|
|
96
|
+
format(MSG, bang: bang, marker: justification_marker)
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def justification_marker
|
|
100
|
+
cop_config.fetch('JustificationMarker', 'unique-write:')
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
end
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
require_relative 'unique_index_backing'
|
|
2
|
+
|
|
3
|
+
module RuboCop
|
|
4
|
+
module Cop
|
|
5
|
+
module DevDoc
|
|
6
|
+
module Rails
|
|
7
|
+
# Rule 2 of 03_model.md item 14, checked at the rescue site: a
|
|
8
|
+
# `rescue ActiveRecord::RecordNotUnique` must guard a write that
|
|
9
|
+
# (a) sits inside its own `transaction(requires_new: true)` and
|
|
10
|
+
# (b) is backed by a unique index in the schema.
|
|
11
|
+
#
|
|
12
|
+
# ## Rationale
|
|
13
|
+
# A rescued `RecordNotUnique` makes two promises, and both can be
|
|
14
|
+
# wrong silently:
|
|
15
|
+
#
|
|
16
|
+
# - **The savepoint promise.** In Postgres, one failed statement
|
|
17
|
+
# poisons the whole transaction; without a savepoint the rescue
|
|
18
|
+
# "succeeds" and the caller's NEXT statement raises
|
|
19
|
+
# `PG::InFailedSqlTransaction` — a 500 far from the race that
|
|
20
|
+
# caused it. Whether a site sits inside a caller's transaction is
|
|
21
|
+
# a property of its callers, and callers change, so the wrapper is
|
|
22
|
+
# required unconditionally: outside any transaction a savepoint
|
|
23
|
+
# costs one ordinary transaction; inside one it is the difference
|
|
24
|
+
# between a rescued race and a broken request.
|
|
25
|
+
# - **The index promise.** The rescue can only fire on a unique
|
|
26
|
+
# index; if none backs the write, the rescue is dead code and
|
|
27
|
+
# duplicates accumulate quietly. The cop proves the premise from
|
|
28
|
+
# the schema: the write's literal attribute keys (plus the
|
|
29
|
+
# association-implied foreign key and query-chain contributions —
|
|
30
|
+
# see `UniqueIndexBacking`) must cover a unique index, partial and
|
|
31
|
+
# expression indexes included.
|
|
32
|
+
#
|
|
33
|
+
# Writes whose attributes do not resolve (dynamic hashes,
|
|
34
|
+
# unresolvable receivers) carry a `# unique_index: <name>` tag
|
|
35
|
+
# adjacent to the write; the cop checks the named index exists.
|
|
36
|
+
# Name-only, by Decision: a column list adds review noise the
|
|
37
|
+
# per-site test already covers.
|
|
38
|
+
#
|
|
39
|
+
# There is deliberately NO prose requirement on rescue sites:
|
|
40
|
+
# `DevDoc/Style/RescueJustification` already exempts race verdicts,
|
|
41
|
+
# and the choice at a rule-2 site is stated by its rescue body —
|
|
42
|
+
# this cop checks facts (the savepoint wraps, the index exists),
|
|
43
|
+
# not sentences.
|
|
44
|
+
#
|
|
45
|
+
# Modifier rescues (`write rescue fallback`) are out of scope, as in
|
|
46
|
+
# RescueJustification: `Style/RescueModifier` flags every one on
|
|
47
|
+
# form alone. The rescued class is matched AS WRITTEN — spell it
|
|
48
|
+
# `ActiveRecord::RecordNotUnique` (a leading `::` is fine).
|
|
49
|
+
#
|
|
50
|
+
# @example
|
|
51
|
+
# # bad — no savepoint: a lost race poisons the caller's transaction
|
|
52
|
+
# def add(member)
|
|
53
|
+
# assignees.create!(member: member)
|
|
54
|
+
# rescue ActiveRecord::RecordNotUnique
|
|
55
|
+
# nil
|
|
56
|
+
# end
|
|
57
|
+
#
|
|
58
|
+
# # good — rule 2: savepoint, index-backed write, stated loss
|
|
59
|
+
# def add(member)
|
|
60
|
+
# transaction(requires_new: true) do
|
|
61
|
+
# assignees.create!(member: member)
|
|
62
|
+
# end
|
|
63
|
+
# rescue ActiveRecord::RecordNotUnique
|
|
64
|
+
# # Lost the (assignee_group, member) race: the member is already in the group.
|
|
65
|
+
# nil
|
|
66
|
+
# end
|
|
67
|
+
class RescueRecordNotUniqueIndex < Base
|
|
68
|
+
include RescueNode
|
|
69
|
+
include UniqueIndexBacking
|
|
70
|
+
|
|
71
|
+
SAVEPOINT_MSG = 'The write guarded by this `rescue ActiveRecord::RecordNotUnique` must sit inside its own ' \
|
|
72
|
+
'`transaction(requires_new: true)`: without a savepoint the rescued failed INSERT poisons ' \
|
|
73
|
+
'the caller\'s transaction and the NEXT statement raises PG::InFailedSqlTransaction ' \
|
|
74
|
+
'(03_model.md item 14, rule 2).'.freeze
|
|
75
|
+
INDEX_MSG = 'No unique index backs this write, so this `rescue ActiveRecord::RecordNotUnique` can never ' \
|
|
76
|
+
'fire and duplicates accumulate silently. Match the write\'s literal attributes against the ' \
|
|
77
|
+
'schema, or tag the write `# unique_index: <name>` (03_model.md item 14, rule 2).'.freeze
|
|
78
|
+
TAG_MSG = 'The `# unique_index:` tag names no index%<scope>s in db/schema.rb — a typo, or the index was ' \
|
|
79
|
+
'dropped. Fix the name or the write\'s attributes.'.freeze
|
|
80
|
+
|
|
81
|
+
RECORD_NOT_UNIQUE = 'ActiveRecord::RecordNotUnique'.freeze
|
|
82
|
+
private_constant :RECORD_NOT_UNIQUE
|
|
83
|
+
|
|
84
|
+
# The `# unique_index: <name>` tag adjacent to a write, read for
|
|
85
|
+
# its capture (name-only, by Decision).
|
|
86
|
+
UNIQUE_INDEX_TAG = /unique_index:\s*([A-Za-z0-9_]+)/
|
|
87
|
+
|
|
88
|
+
# Writes whose INSERT/UPDATE can raise RecordNotUnique. The
|
|
89
|
+
# upsert family is absent (ON CONFLICT absorbs the race); so are
|
|
90
|
+
# destroys (a DELETE cannot violate a unique index).
|
|
91
|
+
PERSISTENCE_WRITES = %i[
|
|
92
|
+
create create! insert insert! insert_all insert_all! create_or_find_by create_or_find_by!
|
|
93
|
+
find_or_create_by find_or_create_by! first_or_create first_or_create!
|
|
94
|
+
update update! update_all update_column update_columns update_attribute
|
|
95
|
+
save save! touch increment! decrement! toggle!
|
|
96
|
+
].freeze
|
|
97
|
+
|
|
98
|
+
def on_rescue(node)
|
|
99
|
+
check_writes(node.body) if guards_record_not_unique?(node)
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
private
|
|
103
|
+
|
|
104
|
+
# The rescued classes are matched as written (leading `::`
|
|
105
|
+
# ignored), the same fail-closed spelling contract as
|
|
106
|
+
# RescueJustification's class list; modifier rescues are out of
|
|
107
|
+
# scope.
|
|
108
|
+
def guards_record_not_unique?(rescue_node)
|
|
109
|
+
rescue_node.resbody_branches.reject { |resbody| rescue_modifier?(resbody) }.any? do |resbody|
|
|
110
|
+
resbody.exceptions.any? { |exception| exception.source.sub(/\A::/, '') == RECORD_NOT_UNIQUE }
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def check_writes(region)
|
|
115
|
+
return unless region
|
|
116
|
+
|
|
117
|
+
region.each_node(:send, :csend) do |candidate|
|
|
118
|
+
next unless PERSISTENCE_WRITES.include?(candidate.method_name)
|
|
119
|
+
next if inside_rescue_body?(candidate, region)
|
|
120
|
+
|
|
121
|
+
check_savepoint(candidate)
|
|
122
|
+
check_index(candidate)
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# A write lexically inside a nested rescue's body is not guarded
|
|
127
|
+
# by THIS rescue — its own clause owns it.
|
|
128
|
+
def inside_rescue_body?(candidate, region)
|
|
129
|
+
candidate.each_ancestor.take_while { |ancestor| !ancestor.equal?(region) }.any?(&:resbody_type?)
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def check_savepoint(write)
|
|
133
|
+
return if requires_new_ancestor?(write)
|
|
134
|
+
|
|
135
|
+
add_offense(write.loc.selector, message: SAVEPOINT_MSG)
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# Any lexically enclosing `transaction(requires_new: true)` counts:
|
|
139
|
+
# the failed INSERT rolls back to that savepoint however deeply the
|
|
140
|
+
# write nests inside the guarded region. A do-block's send node is
|
|
141
|
+
# the block's CHILD, so block ancestors are inspected through their
|
|
142
|
+
# send node.
|
|
143
|
+
def requires_new_ancestor?(write)
|
|
144
|
+
write.each_ancestor.any? do |ancestor|
|
|
145
|
+
transaction = enclosing_transaction(ancestor)
|
|
146
|
+
transaction && requires_new?(transaction)
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# The `transaction` send for a block ancestor (through its send
|
|
151
|
+
# node) or a send ancestor, else nil.
|
|
152
|
+
def enclosing_transaction(ancestor)
|
|
153
|
+
candidate = ancestor.block_type? ? ancestor.send_node : ancestor
|
|
154
|
+
return nil unless candidate.respond_to?(:method_name)
|
|
155
|
+
return nil unless candidate.send_type? || candidate.csend_type?
|
|
156
|
+
return nil unless candidate.method_name == :transaction
|
|
157
|
+
|
|
158
|
+
candidate
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def requires_new?(transaction_send)
|
|
162
|
+
transaction_send.arguments.any? do |argument|
|
|
163
|
+
next false unless argument.hash_type?
|
|
164
|
+
|
|
165
|
+
argument.pairs.any? do |pair|
|
|
166
|
+
pair.key.sym_type? && pair.key.value == :requires_new && pair.value.true_type?
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def check_index(write)
|
|
172
|
+
return unless schema
|
|
173
|
+
|
|
174
|
+
table, implied_fk = receiver_resolution(write.receiver, write)
|
|
175
|
+
keys = write_attribute_keys(write)
|
|
176
|
+
return if covering_unique_index(table: table, attribute_keys: keys || [], implied_fk: implied_fk)
|
|
177
|
+
|
|
178
|
+
offense = index_offense(adjacent_unique_index_tag_name(write), table)
|
|
179
|
+
add_offense(write.loc.selector, message: offense) if offense
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# The index gap's message: INDEX_MSG when no tag names the write,
|
|
183
|
+
# missing-tag wording when the tag names no index.
|
|
184
|
+
def index_offense(name, table)
|
|
185
|
+
return INDEX_MSG unless name
|
|
186
|
+
return nil if named_index(name, table: table)
|
|
187
|
+
|
|
188
|
+
format(TAG_MSG, scope: table ? " on #{table}" : '')
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# The `# unique_index:` tag on the write's own line or in the
|
|
192
|
+
# contiguous comment block above it — the shared
|
|
193
|
+
# adjacent-justification placement contract, read for its capture.
|
|
194
|
+
def adjacent_unique_index_tag_name(write)
|
|
195
|
+
comments = processed_source.comments.group_by { |comment| comment.location.line }
|
|
196
|
+
adjacent = comments[write.first_line].to_a + comments_above(write.first_line - 1, comments)
|
|
197
|
+
adjacent.filter_map { |comment| comment.text[UNIQUE_INDEX_TAG, 1] }.first
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
def comments_above(line, comments)
|
|
201
|
+
found = []
|
|
202
|
+
while (line_comments = comments[line])
|
|
203
|
+
found.concat(line_comments)
|
|
204
|
+
line -= 1
|
|
205
|
+
end
|
|
206
|
+
found
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
end
|
|
210
|
+
end
|
|
211
|
+
end
|
|
212
|
+
end
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
require 'active_support/inflector'
|
|
2
|
+
|
|
3
|
+
module RuboCop
|
|
4
|
+
module Cop
|
|
5
|
+
module DevDoc
|
|
6
|
+
module Rails
|
|
7
|
+
# Shared schema resolution for the uniqueness-write cops
|
|
8
|
+
# (`RescueRecordNotUniqueIndex`, `FindOrCreateByJustification`):
|
|
9
|
+
# given a write's receiver and literal attribute keys, decide whether
|
|
10
|
+
# a unique index backs the write. Conventions (all escape-hatched by
|
|
11
|
+
# the `# unique_index: <name>` tag, read by the host cop at the
|
|
12
|
+
# write):
|
|
13
|
+
#
|
|
14
|
+
# - A CONSTANT receiver names the model (`Activity.create!` ->
|
|
15
|
+
# `activities`); a NIL receiver is a class-level write on the
|
|
16
|
+
# enclosing class.
|
|
17
|
+
# - An association-style receiver resolves by Rails naming: the
|
|
18
|
+
# first PLURAL method in the chain is the association
|
|
19
|
+
# (`organization.organization_managers`,
|
|
20
|
+
# `folders.managed_by_platform`, bare `assignees`), its pluralized
|
|
21
|
+
# name is the table, and the segment before it (or the enclosing
|
|
22
|
+
# class, for a bare association) implies the foreign key —
|
|
23
|
+
# credited only when the table has that column, so a custom
|
|
24
|
+
# `foreign_key:` falls to the tag. A chain with no plural segment
|
|
25
|
+
# is class-level query methods on the enclosing class.
|
|
26
|
+
# - An attribute key `member` covers the columns `member` and
|
|
27
|
+
# `member_id`; an expression index covers the identifiers it names
|
|
28
|
+
# (`user_id, lower((name)::text)` covers `user_id` and `name`).
|
|
29
|
+
# Partial unique indexes count: the rescue fires on any unique
|
|
30
|
+
# violation regardless of the index predicate, and the schema
|
|
31
|
+
# loader exposes no `where` anyway.
|
|
32
|
+
#
|
|
33
|
+
# Everything unresolvable (dynamic hashes, unknown tables) reports
|
|
34
|
+
# `nil` — the host cops require the tag there.
|
|
35
|
+
module UniqueIndexBacking
|
|
36
|
+
include ActiveRecordHelper
|
|
37
|
+
|
|
38
|
+
# Chain calls whose literal hash keys contribute to a write's
|
|
39
|
+
# covered columns (`Model.where(a: 1).create!` writes `a`;
|
|
40
|
+
# `find_or_initialize_by(email:).update!(...)` inserts the
|
|
41
|
+
# initialized attributes).
|
|
42
|
+
ATTRIBUTE_CONTRIBUTORS = %i[
|
|
43
|
+
where find_or_initialize_by find_or_create_by find_or_create_by!
|
|
44
|
+
first_or_create first_or_create! create_or_find_by create_or_find_by!
|
|
45
|
+
].freeze
|
|
46
|
+
|
|
47
|
+
# Node types that can root a receiver chain and still name the
|
|
48
|
+
# association's owner (a local, an ivar, a gvar).
|
|
49
|
+
VARIABLE_ROOTS = %i[lvar ivar cvar gvar].freeze
|
|
50
|
+
|
|
51
|
+
private
|
|
52
|
+
|
|
53
|
+
# The unique index on `table` whose columns (or expression
|
|
54
|
+
# identifiers) are all covered by `attribute_keys` plus the
|
|
55
|
+
# receiver-implied foreign key, or nil.
|
|
56
|
+
def covering_unique_index(table:, attribute_keys:, implied_fk: nil)
|
|
57
|
+
tbl = table && schema&.table_by(name: table)
|
|
58
|
+
return nil unless tbl
|
|
59
|
+
|
|
60
|
+
candidates = covered_columns(attribute_keys, implied_fk, tbl)
|
|
61
|
+
return nil if candidates.empty?
|
|
62
|
+
|
|
63
|
+
tbl.indices.find { |index| unique_index_covers?(index, candidates) }
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# The schema's index by exact name — on `table` when it resolved,
|
|
67
|
+
# across the whole schema when it did not.
|
|
68
|
+
def named_index(name, table: nil)
|
|
69
|
+
return nil unless schema && name
|
|
70
|
+
|
|
71
|
+
indices = table ? schema.table_by(name: table)&.indices : schema.tables.flat_map(&:indices)
|
|
72
|
+
indices.to_a.find { |index| index.name == name }
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Column identifiers named by an expression index:
|
|
76
|
+
# `lower((name)::text)` -> name; `date(entered_at)` -> entered_at.
|
|
77
|
+
def expression_columns(index)
|
|
78
|
+
index.expression.to_s.split(',').flat_map do |segment|
|
|
79
|
+
stripped = segment.strip
|
|
80
|
+
stripped.match?(/\A[a-z_][a-z0-9_]*\z/) ? [stripped] : stripped.scan(/\(([a-z_][a-z0-9_]*)\)/).flatten
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# [table, implied_fk] for a write's receiver, per the module-doc
|
|
85
|
+
# conventions; [nil, nil] when unresolvable.
|
|
86
|
+
def receiver_resolution(receiver, node)
|
|
87
|
+
return [enclosing_table(node), nil] if receiver.nil?
|
|
88
|
+
return [receiver_table(receiver), nil] if receiver.const_type?
|
|
89
|
+
return association_resolution(receiver, node) if receiver.send_type? || receiver.csend_type?
|
|
90
|
+
|
|
91
|
+
[nil, nil]
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# Name segments of a receiver chain, root first: `folders.managed_by_platform`
|
|
95
|
+
# -> [:folders, :managed_by_platform]; `organization.organization_managers`
|
|
96
|
+
# inside `def self.x(organization:)` -> [:organization, :organization_managers]
|
|
97
|
+
# (a bound variable root contributes its name; the parser spells a
|
|
98
|
+
# kwarg as an lvar, a bare call as a send — both name the owner).
|
|
99
|
+
def receiver_chain_segments(receiver)
|
|
100
|
+
segments = []
|
|
101
|
+
root = each_receiver_link(receiver) { |link| segments.unshift(link.method_name) }
|
|
102
|
+
segments.unshift(root.children.first.to_s) if VARIABLE_ROOTS.include?(root&.type)
|
|
103
|
+
segments
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Yields each send/csend link of a receiver chain toward its root,
|
|
107
|
+
# returning the node that stopped the walk (nil, a variable, ...).
|
|
108
|
+
def each_receiver_link(receiver)
|
|
109
|
+
cursor = receiver
|
|
110
|
+
while cursor.is_a?(RuboCop::AST::Node) && (cursor.send_type? || cursor.csend_type?)
|
|
111
|
+
yield cursor
|
|
112
|
+
cursor = cursor.receiver
|
|
113
|
+
end
|
|
114
|
+
cursor
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# [table, implied_fk] for an association-style chain, per the
|
|
118
|
+
# module-doc conventions (no plural segment -> the enclosing
|
|
119
|
+
# class's table, no implied key).
|
|
120
|
+
def association_resolution(receiver, node)
|
|
121
|
+
segments = receiver_chain_segments(receiver)
|
|
122
|
+
association = segments.find { |seg| ActiveSupport::Inflector.pluralize(seg.to_s) == seg.to_s }
|
|
123
|
+
return [enclosing_table(node), nil] unless association
|
|
124
|
+
|
|
125
|
+
owner_index = segments.index(association)
|
|
126
|
+
owner = owner_index.zero? ? enclosing_class_name(node) : segments[owner_index - 1].to_s
|
|
127
|
+
[ActiveSupport::Inflector.pluralize(association.to_s), "#{ActiveSupport::Inflector.underscore(owner)}_id"]
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# The table a CONSTANT receiver names: `Activity` / `::Activity` ->
|
|
131
|
+
# `activities`; `Members::Filter` -> `members_filters` (Rails'
|
|
132
|
+
# own class-to-table arithmetic).
|
|
133
|
+
def receiver_table(const_node)
|
|
134
|
+
dotted_to_table(const_node.source)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def enclosing_class_name(node)
|
|
138
|
+
class_node = node.each_ancestor.find(&:class_type?)
|
|
139
|
+
return nil unless class_node
|
|
140
|
+
|
|
141
|
+
class_node.identifier.source
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def enclosing_table(node)
|
|
145
|
+
name = enclosing_class_name(node)
|
|
146
|
+
name && dotted_to_table(name)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def dotted_to_table(dotted)
|
|
150
|
+
ActiveSupport::Inflector.pluralize(ActiveSupport::Inflector.underscore(dotted.sub(/\A::/, '')).tr('/', '_'))
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# Literal keys of a write's own hash plus those contributed by
|
|
154
|
+
# query calls in its receiver chain. nil when the write's own
|
|
155
|
+
# attributes are dynamic.
|
|
156
|
+
def write_attribute_keys(write)
|
|
157
|
+
own = literal_hash_keys(write)
|
|
158
|
+
return nil unless own
|
|
159
|
+
|
|
160
|
+
own + chain_contributed_keys(write)
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# A send's literal symbol/string hash keys, [] when it takes no
|
|
164
|
+
# hash, nil when its attributes are dynamic.
|
|
165
|
+
def literal_hash_keys(send_node)
|
|
166
|
+
hash = send_node.first_argument
|
|
167
|
+
return nil unless hash.nil? || hash.hash_type?
|
|
168
|
+
|
|
169
|
+
return [] if hash.nil?
|
|
170
|
+
|
|
171
|
+
hash.each_child_node(:pair).filter_map do |pair|
|
|
172
|
+
pair.key.value if pair.key.sym_type? || pair.key.str_type?
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
def chain_contributed_keys(write)
|
|
177
|
+
keys = []
|
|
178
|
+
each_receiver_link(write.receiver) do |link|
|
|
179
|
+
keys.concat(literal_hash_keys(link).compact) if ATTRIBUTE_CONTRIBUTORS.include?(link.method_name)
|
|
180
|
+
end
|
|
181
|
+
keys
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# Both spellings an attribute key can satisfy: `member` writes the
|
|
185
|
+
# `member_id` column via association assignment, or `member` itself
|
|
186
|
+
# when it is a plain column.
|
|
187
|
+
def covered_columns(attribute_keys, implied_fk, tbl)
|
|
188
|
+
columns = attribute_keys.flat_map { |key| [key.to_s, "#{key}_id"] }
|
|
189
|
+
columns << implied_fk if implied_fk && tbl.columns.map(&:name).include?(implied_fk)
|
|
190
|
+
columns.to_set
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
# A unique index whose enforced columns (listed, or named inside
|
|
194
|
+
# its expression) are all covered.
|
|
195
|
+
def unique_index_covers?(index, candidates)
|
|
196
|
+
return false unless index.unique
|
|
197
|
+
|
|
198
|
+
enforced = index.columns.any? ? index.columns : expression_columns(index)
|
|
199
|
+
enforced.all? { |column| candidates.include?(column) }
|
|
200
|
+
end
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
end
|
|
205
|
+
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: rubocop-dev_doc
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.20.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- dev-doc contributors
|
|
@@ -149,8 +149,10 @@ files:
|
|
|
149
149
|
- lib/rubocop/cop/dev_doc/rails/avoid_rails_callbacks.rb
|
|
150
150
|
- lib/rubocop/cop/dev_doc/rails/avoid_raw_sql.rb
|
|
151
151
|
- lib/rubocop/cop/dev_doc/rails/bang_save_in_transaction.rb
|
|
152
|
+
- lib/rubocop/cop/dev_doc/rails/create_or_find_by.rb
|
|
152
153
|
- lib/rubocop/cop/dev_doc/rails/enum_column_not_null.rb
|
|
153
154
|
- lib/rubocop/cop/dev_doc/rails/enum_must_be_symbolized.rb
|
|
155
|
+
- lib/rubocop/cop/dev_doc/rails/find_or_create_by_justification.rb
|
|
154
156
|
- lib/rubocop/cop/dev_doc/rails/no_block_predicate_on_relation.rb
|
|
155
157
|
- lib/rubocop/cop/dev_doc/rails/no_collection_ids_writer_in_controller.rb
|
|
156
158
|
- lib/rubocop/cop/dev_doc/rails/no_deliver_later_in_transaction.rb
|
|
@@ -161,8 +163,10 @@ files:
|
|
|
161
163
|
- lib/rubocop/cop/dev_doc/rails/no_perform_later_in_model.rb
|
|
162
164
|
- lib/rubocop/cop/dev_doc/rails/no_persistence_in_service.rb
|
|
163
165
|
- lib/rubocop/cop/dev_doc/rails/no_transaction_in_controller.rb
|
|
166
|
+
- lib/rubocop/cop/dev_doc/rails/rescue_record_not_unique_index.rb
|
|
164
167
|
- lib/rubocop/cop/dev_doc/rails/soft_failure_in_bang_method.rb
|
|
165
168
|
- lib/rubocop/cop/dev_doc/rails/strong_parameters_expect.rb
|
|
169
|
+
- lib/rubocop/cop/dev_doc/rails/unique_index_backing.rb
|
|
166
170
|
- lib/rubocop/cop/dev_doc/route/no_custom_actions.rb
|
|
167
171
|
- lib/rubocop/cop/dev_doc/route/resource_name_number.rb
|
|
168
172
|
- lib/rubocop/cop/dev_doc/route/resources_require_only.rb
|