Skip to content

Support `#last` on relations with keyset order

What does this MR do and why?

When a relation has a complex order clause, ActiveRecord cannot reverse it automatically. But when the order clause is built using Gitlab::Pagination::Keyset::Order, we can determine the reverse order because we pass it in explicitly in these cases.

This patch allows ActiveRecord to use the specified reverse order when calling #last and other related methods that need a reverse order.

Before:

[1] pry(main)> Issue.order_by_relative_position.last
ActiveRecord::IrreversibleOrderError: Order "\"issues\".\"relative_position\" ASC NULLS LAST, \"issues\".\"id\" ASC" cannot be reversed automatically
from /Users/work/.asdf/installs/ruby/2.7.5/lib/ruby/gems/2.7.0/gems/activerecord-6.1.6.1/lib/active_record/relation/query_methods.rb:1348:in `block in reverse_sql_order'

After:

[1] pry(main)> Issue.order_by_relative_position.last
=> #<Issue id:526 gitlab-org/gitlab-test#34>

MR acceptance checklist

This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by Heinrich Lee Yu

Merge request reports

Loading