Skip to content

Commit 58fb592

Browse files
committed
ruby: add tests
1 parent d7ffc3f commit 58fb592

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
| DatabaseQueryInLoop.rb:11:13:11:52 | call to first | This call to a database query operation happens inside $@, and could be hoisted to a single call outside the loop. | DatabaseQueryInLoop.rb:10:9:12:11 | call to map | this loop |
2+
| DatabaseQueryInLoop.rb:16:20:16:59 | call to first | This call to a database query operation happens inside $@, and could be hoisted to a single call outside the loop. | DatabaseQueryInLoop.rb:15:9:21:11 | call to map | this loop |
3+
| DatabaseQueryInLoop.rb:19:17:19:56 | call to first | This call to a database query operation happens inside $@, and could be hoisted to a single call outside the loop. | DatabaseQueryInLoop.rb:18:13:20:15 | call to map | this loop |
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
queries/performance/DatabaseQueryInLoop.ql
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
class User < ActiveRecord::Base
3+
end
4+
5+
class DatabaseQueryInLoopTest
6+
def test
7+
### These are bad
8+
9+
# simple query in loop
10+
names.map do |name|
11+
User.where(login: name).pluck(:id).first
12+
end
13+
14+
# nested loop
15+
names.map do |name|
16+
user = User.where(login: name).pluck(:id).first
17+
18+
ids.map do |user_id|
19+
User.where(id: user_id).pluck(:id).first
20+
end
21+
end
22+
23+
### These are OK
24+
25+
# Not in loop
26+
User.where(login: owner_slug).pluck(:id).first
27+
28+
# Loops over constant array
29+
%w(first-name second-name).map { |name| User.where(login: name).pluck(:id).first }
30+
31+
constant_names = [first-name, second-name]
32+
constant_names.each do |name|
33+
User.where(login: name).pluck(:id).first
34+
end
35+
36+
# Loop traversal is influenced by query result
37+
# raising an exception if the user is not found
38+
names.map do |name|
39+
user = User.where(login: name).pluck(:id).first
40+
unless user
41+
raise Error.new("User '#{name}' not found")
42+
end
43+
end
44+
45+
# skipping through the loop when users are not relevant
46+
names.map do |name|
47+
user = User.where(login: name).pluck(:id).first
48+
if not isRelevant(user)
49+
next
50+
end
51+
end
52+
end
53+
end

0 commit comments

Comments
 (0)