text: Consider the ruby on rails function in the User model:
  ```
  def messages(result_limit: nil)
      hidden_subtypes = []
      Message::APP_HIDDEN_SUBTYPES.each { |subtype| hidden_subtypes << Message.sub_types[subtype] }
      messages_as_sender = Message.where(sender_id: self.id)
        .where('sub_type is NULL or sub_type NOT IN (?)', hidden_subtypes)
        .order(id: :DESC)
      messages_as_sender = messages_as_sender.limit(result_limit) if result_limit.present?
  
      messages_as_receiver = Message.where(receiver_id: self.id)
        .where('sub_type is NULL or sub_type NOT IN (?)', hidden_subtypes)
        .order(id: :DESC)
      messages_as_receiver = messages_as_receiver.limit(result_limit) if result_limit.present?
  
      return messages_as_sender.or(messages_as_receiver)
    end
  ```
  
  The problem with this function is that we have indexes (receiver_id,id) and (sender_id,id) on Message model but postgres still ends up performing sort after performing BitmapOr. We would need to perform two separate queries but still return a scope to the caller. This can be done through the use of UNION ALL. Rewrite the messages function to address this performance issue.