forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseQueryInLoop.rb
More file actions
61 lines (49 loc) · 1.63 KB
/
DatabaseQueryInLoop.rb
File metadata and controls
61 lines (49 loc) · 1.63 KB
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
class User < ActiveRecord::Base
end
class DatabaseQueryInLoopTest
def test
### These are bad
# simple query in loop
names.map do |name|
User.where(login: name).pluck(:id).first
end
# nested loop
names.map do |name|
user = User.where(login: name).pluck(:id).first
ids.map do |user_id|
User.where(id: user_id).pluck(:id).first
end
end
### These are OK
# Not in loop
User.where(login: owner_slug).pluck(:id).first
# Loops over constant array
%w(first-name second-name).map { |name| User.where(login: name).pluck(:id).first }
constant_names = [first-name, second-name]
constant_names.each do |name|
User.where(login: name).pluck(:id).first
end
# Loop traversal is influenced by query result
# raising an exception if the user is not found
names.map do |name|
user = User.where(login: name).pluck(:id).first
unless user
raise Error.new("User '#{name}' not found")
end
end
# more complicated condition
names.map do |name|
user = User.where(login: name).pluck(:id).first
unless cond && user
raise Error.new("User '#{name}' not found")
end
end
# skipping through the loop when users are not relevant
names.map do |name|
user = User.where(login: name).pluck(:id).first
if not isRelevant(user)
next
end
end
end
end