[13.x] Fix union cursor pagination when ordering by an aliased expression
Merged
MR
8d ago+24+24+01234567890123456789-1-1-0123456789
Found this while playing with cursor pagination on union queries. If you order by an aliased expression, the first page is fine but the second one blows up:
$query = fn () => DB::table('test_posts')
->select('id')->selectRaw('UPPER(test_posts.title) as label')
->unionAll(
DB::table('test_users')->select('id')->selectRaw('UPPER(test_users.name) as label')
)
->orderBy('label')
->orderBy('id');
$page1 = $query()->cursorPaginate(2);
$page2 = $query()->cursorPaginate(2, cursor: $page1->nextCursor());
// SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UPPER(test_users.name)' in 'where clause'
The expression already gets wrapped in an Expression everywhere else in paginateUsingCursor() (#41003, #61837), but the > / < check on the union side was missed, so it ends up quoted as a column name. I just added the same check there.
The test goes both directions and puts a duplicate label right on the page boundary, so the id ordering decides what’s on page 2. It fails on SQLite, MySQL 8.4 and Postgres 16 without the fix.