diff options
author | Sean McGivern <sean@gitlab.com> | 2018-10-02 17:29:45 +0300 |
---|---|---|
committer | Sean McGivern <sean@gitlab.com> | 2018-10-04 16:28:15 +0300 |
commit | 28e6af88aa16a33717dbdbe870a8423300aef042 (patch) | |
tree | 1fd34b9d217e88b22d5c928d142cf8117f2fd5e6 /app | |
parent | 819ecd5fb01ab64cacc31253c51984a7564949d7 (diff) |
Fix N+1 for notification recipients on private projects
If we don't call #to_a, we're relying on the members already being loaded from
elsewhere. Otherwise we'll do a separate query for each user:
[1] pry(main)> Project.first.team.members.include?(User.first)
Project Load (0.7ms) SELECT "projects".* FROM "projects" ORDER BY "projects"."id" ASC LIMIT 1
↳ (pry):3
User Load (1.8ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
↳ (pry):3
User Exists (0.6ms) SELECT 1 AS one FROM "users" INNER JOIN "project_authorizations" ON "users"."id" = "project_authorizations"."user_id" WHERE "project_authorizations"."project_id" = $1 AND "users"."id" = $2 LIMIT 1 [["project_id", 1], ["id", 1]]
↳ (pry):3
=> true
[2] pry(main)> Project.first.team.members.to_a.include?(User.first)
Project Load (12.8ms) SELECT "projects".* FROM "projects" ORDER BY "projects"."id" ASC LIMIT 1
↳ (pry):1
User Load (9.6ms) SELECT "users".* FROM "users" INNER JOIN "project_authorizations" ON "users"."id" = "project_authorizations"."user_id" WHERE "project_authorizations"."project_id" = $1 [["project_id", 1]]
↳ (pry):1
User Load (0.6ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
↳ (pry):1
=> true
Diffstat (limited to 'app')
-rw-r--r-- | app/policies/project_policy.rb | 6 |
1 files changed, 5 insertions, 1 deletions
diff --git a/app/policies/project_policy.rb b/app/policies/project_policy.rb index d0e84b1aa38..f2c246cd969 100644 --- a/app/policies/project_policy.rb +++ b/app/policies/project_policy.rb @@ -390,7 +390,11 @@ class ProjectPolicy < BasePolicy greedy_load_subject ||= !@user.persisted? if greedy_load_subject - project.team.members.include?(user) + # We want to load all the members with one query. Calling #include? on + # project.team.members will perform a separate query for each user, unless + # project.team.members was loaded before somewhere else. Calling #to_a + # ensures it's always loaded before checking for membership. + project.team.members.to_a.include?(user) else # otherwise we just make a specific query for # this particular user. |