Skip to content

Commit

Permalink
[9.x] Fix aliasing with cursor pagination (#45188)
Browse files Browse the repository at this point in the history
* Fix aliasing with cursor pagination

* add testCursorPaginateWithDynamicColumnWithCastInSelectRaw

* Update BuildsQueries.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
maximepvrt and taylorotwell committed Dec 7, 2022
1 parent f06af0c commit 38c2126
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/Illuminate/Database/Concerns/BuildsQueries.php
Expand Up @@ -427,10 +427,10 @@ protected function getOriginalColumnNameForCursorPagination($builder, string $pa

if (! is_null($columns)) {
foreach ($columns as $column) {
if (($position = stripos($column, ' as ')) !== false) {
$as = substr($column, $position, 4);
if (($position = strripos($column, ' as ')) !== false) {
$original = substr($column, 0, $position);

[$original, $alias] = explode($as, $column);
$alias = substr($column, $position + 4);

if ($parameter === $alias || $builder->getGrammar()->wrap($parameter) === $alias) {
return $original;
Expand Down
41 changes: 41 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Expand Up @@ -4632,6 +4632,47 @@ public function testCursorPaginateWithDynamicColumnInSelectRaw()
]), $result);
}

public function testCursorPaginateWithDynamicColumnWithCastInSelectRaw()
{
$perPage = 15;
$cursorName = 'cursor';
$cursor = new Cursor(['test' => 'bar']);
$builder = $this->getMockQueryBuilder();
$builder->from('foobar')->select('*')->selectRaw('(CAST(CONCAT(firstname, \' \', lastname) as VARCHAR)) as test')->orderBy('test');
$builder->shouldReceive('newQuery')->andReturnUsing(function () use ($builder) {
return new Builder($builder->connection, $builder->grammar, $builder->processor);
});

$path = 'http://foo.bar?cursor='.$cursor->encode();

$results = collect([['test' => 'foo'], ['test' => 'bar']]);

$builder->shouldReceive('get')->once()->andReturnUsing(function () use ($builder, $results) {
$this->assertEquals(
'select *, (CAST(CONCAT(firstname, \' \', lastname) as VARCHAR)) as test from "foobar" where ((CAST(CONCAT(firstname, \' \', lastname) as VARCHAR)) > ?) order by "test" asc limit 16',
$builder->toSql());
$this->assertEquals(['bar'], $builder->bindings['where']);

return $results;
});

CursorPaginator::currentCursorResolver(function () use ($cursor) {
return $cursor;
});

Paginator::currentPathResolver(function () use ($path) {
return $path;
});

$result = $builder->cursorPaginate();

$this->assertEquals(new CursorPaginator($results, $perPage, $cursor, [
'path' => $path,
'cursorName' => $cursorName,
'parameters' => ['test'],
]), $result);
}

public function testCursorPaginateWithDynamicColumnInSelectSub()
{
$perPage = 15;
Expand Down

0 comments on commit 38c2126

Please sign in to comment.