Skip to content

Commit

Permalink
Suppress N+1 query on GET /history/:id and GET /message
Browse files Browse the repository at this point in the history
  • Loading branch information
rosylilly committed Oct 22, 2017
1 parent 3f79822 commit 0765cf6
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions isubata/webapp/ruby/app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,16 +122,17 @@ def user
last_message_id = params[:last_message_id].to_i
statement = db.prepare('SELECT * FROM message WHERE id > ? AND channel_id = ? ORDER BY id DESC LIMIT 100')
rows = statement.execute(last_message_id, channel_id).to_a
users = get_users(rows.map { |r| r['user_id'] }.uniq)
response = []
rows.each do |row|
r = {}
r['id'] = row['id']
statement = db.prepare('SELECT name, display_name, avatar_icon FROM user WHERE id = ?')
r['user'] = statement.execute(row['user_id']).first
# statement = db.prepare('SELECT name, display_name, avatar_icon FROM user WHERE id = ?')
r['user'] = users[row['user_id']] # statement.execute(row['user_id']).first
r['date'] = row['created_at'].strftime("%Y/%m/%d %H:%M:%S")
r['content'] = row['content']
response << r
statement.close
# statement.close
end
response.reverse!

Expand Down Expand Up @@ -200,16 +201,17 @@ def user
statement = db.prepare('SELECT * FROM message WHERE channel_id = ? ORDER BY id DESC LIMIT ? OFFSET ?')
rows = statement.execute(@channel_id, n, (@page - 1) * n).to_a
statement.close
users = get_users(rows.map { |r| r['user_id'] }.uniq)
@messages = []
rows.each do |row|
r = {}
r['id'] = row['id']
statement = db.prepare('SELECT name, display_name, avatar_icon FROM user WHERE id = ?')
r['user'] = statement.execute(row['user_id']).first
# statement = db.prepare('SELECT name, display_name, avatar_icon FROM user WHERE id = ?')
r['user'] = users[row['user_id']] # statement.execute(row['user_id']).first
r['date'] = row['created_at'].strftime("%Y/%m/%d %H:%M:%S")
r['content'] = row['content']
@messages << r
statement.close
# statement.close
end
@messages.reverse!

Expand Down Expand Up @@ -423,4 +425,15 @@ def ext2mime(ext)
end
''
end

def get_users(ids)
rows = db.query("SELECT id, name, display_name, avatar_icon FROM user WHERE id IN (#{ids.join(',')})")

dict = {}
rows.each do |row|
dict[row['id']] = row.select { |k, v| %w[name display_name avatar_icon].include?(k) }
end

dict
end
end

0 comments on commit 0765cf6

Please sign in to comment.