- # Can read object (evidently a group or user) whose UUID is listed
- # explicitly in user_uuids.
- sql_conds += ["#{sql_table}.uuid IN (:user_uuids)"]
- trashed_check = if include_trash then "EXISTS" else "0 IN " end
- perm_check = "perm_level >= 1"
-
- if self.column_names.include? "owner_uuid"
- # to be readable:
- # row(s) exists granting readable permission to uuid or owner, and none are trashed
- sql_conds += ["#{trashed_check}(SELECT MAX(trashed) FROM permission_view "+
- "WHERE user_uuid IN (:user_uuids) AND #{perm_check} AND "+
- "(#{sql_table}.uuid = target_uuid OR (#{sql_table}.owner_uuid = target_uuid AND target_owner_uuid is NOT NULL)))"]
- # reader is owner, and item is not trashed
- not_trashed_check = if include_trash then
- ""
- else
- "AND 1 NOT IN (SELECT MAX(trashed) FROM permission_view "+
- "WHERE #{sql_table}.uuid = target_uuid OR #{sql_table}.owner_uuid = target_uuid)"
- end
- sql_conds += ["(#{sql_table}.owner_uuid IN (:user_uuids) #{not_trashed_check})"]
- else
- # to be readable:
- # * a non-trash row exists with readable permission uuid
- sql_conds += ["#{trashed_check}(SELECT MAX(trashed) FROM permission_view "+
- "WHERE user_uuid IN (:user_uuids) AND #{perm_check} AND "+
- "#{sql_table}.uuid = target_uuid) "]
+ trashed_check = ""
+ if !include_trash then
+ trashed_check = "AND trashed = 0"
+ end
+
+ # Note: it is possible to combine the direct_check and
+ # owner_check into a single EXISTS() clause, however it turns
+ # out query optimizer doesn't like it and forces a sequential
+ # table scan. Constructing the query with separate EXISTS()
+ # clauses enables it to use the index.
+ #
+ # see issue 13208 for details.
+
+ # Match a direct read permission link from the user to the record uuid
+ direct_check = "EXISTS(SELECT 1 FROM #{PERMISSION_VIEW} "+
+ "WHERE user_uuid IN (:user_uuids) AND perm_level >= 1 #{trashed_check} AND target_uuid = #{sql_table}.uuid)"
+
+ # Match a read permission link from the user to the record's owner_uuid
+ owner_check = ""
+ if sql_table != "api_client_authorizations" and sql_table != "groups" then
+ owner_check = "OR EXISTS(SELECT 1 FROM #{PERMISSION_VIEW} "+
+ "WHERE user_uuid IN (:user_uuids) AND perm_level >= 1 #{trashed_check} AND target_uuid = #{sql_table}.owner_uuid AND target_owner_uuid IS NOT NULL) "