Skip to content

[11.x] Support for multiple partition by columns in groupLimit() #52072

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2642,7 +2642,7 @@ public function limit($value)
* Add a "group limit" clause to the query.
*
* @param int $value
* @param string $column
* @param string|array $column
* @return $this
*/
public function groupLimit($value, $column)
Expand Down Expand Up @@ -3008,11 +3008,12 @@ protected function withoutGroupLimitKeys($items)
{
$keysToRemove = ['laravel_row'];

if (is_string($this->groupLimit['column'])) {
$column = last(explode('.', $this->groupLimit['column']));

$keysToRemove[] = '@laravel_group := '.$this->grammar->wrap($column);
$keysToRemove[] = '@laravel_group := '.$this->grammar->wrap('pivot_'.$column);
if (isset($this->groupLimit['column'])) {
foreach ((array) $this->groupLimit['column'] as $i => $column) {
$column = last(explode('.', $column));
$keysToRemove[] = '@laravel_group'.$i.' := '.$this->grammar->wrap($column);
$keysToRemove[] = '@laravel_group'.$i.' := '.$this->grammar->wrap('pivot_'.$column);
}
}

$items->each(function ($item) use ($keysToRemove) {
Expand Down
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Query/Grammars/Grammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -1027,13 +1027,13 @@ protected function compileGroupLimit(Builder $query)
/**
* Compile a row number clause.
*
* @param string $partition
* @param string|array $partition
* @param string $orders
* @return string
*/
protected function compileRowNumber($partition, $orders)
{
$over = trim('partition by '.$this->wrap($partition).' '.$orders);
$over = trim('partition by '.$this->columnize((array) $partition).' '.$orders);

return ', row_number() over ('.$over.') as '.$this->wrap('laravel_row');
}
Expand Down
34 changes: 25 additions & 9 deletions src/Illuminate/Database/Query/Grammars/MySqlGrammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,26 +141,42 @@ protected function compileLegacyGroupLimit(Builder $query)
$query->offset = null;
}

$column = last(explode('.', $query->groupLimit['column']));
$column = $this->wrap($column);
$groupColumns = (array) $query->groupLimit['column'];

$partition = ', @laravel_row := if(@laravel_group = '.$column.', @laravel_row + 1, 1) as `laravel_row`';
$partition .= ', @laravel_group := '.$column;
$groupPartitions = [];
$groupSelects = [];
$groupInitialValues = [];
$groupOrders = [];

foreach ($groupColumns as $i => $column) {
$groupInitialValues[] = '@laravel_group'.$i.' := 0';

$groupOrders[] = [
'column' => $column,
'direction' => 'asc',
];

$column = $this->wrap(last(explode('.', $column)));

$groupPartitions[] = '@laravel_group'.$i.' = '.$column;

$groupSelects[] = '@laravel_group'.$i.' := '.$column;
}

$partition = ', @laravel_row := if('.implode(' and ', $groupPartitions).', @laravel_row + 1, 1) as `laravel_row`';
$partition .= ', '.implode(', ', $groupSelects);

$orders = (array) $query->orders;

array_unshift($orders, [
'column' => $query->groupLimit['column'],
'direction' => 'asc',
]);
array_unshift($orders, ...$groupOrders);

$query->orders = $orders;

$components = $this->compileComponents($query);

$sql = $this->concatenate($components);

$from = '(select @laravel_row := 0, @laravel_group := 0) as `laravel_vars`, ('.$sql.') as `laravel_table`';
$from = '(select @laravel_row := 0, '.implode(', ', $groupInitialValues).') as `laravel_vars`, ('.$sql.') as `laravel_table`';

$sql = 'select `laravel_table`.*'.$partition.' from '.$from.' having `laravel_row` <= '.$limit;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ protected function compileLimit(Builder $query, $limit)
/**
* Compile a row number clause.
*
* @param string $partition
* @param string|array $partition
* @param string $orders
* @return string
*/
Expand Down
62 changes: 62 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6243,6 +6243,68 @@ public function testToRawSql()
$this->assertSame('select * from "users" where "email" = \'foo\'', $builder->toRawSql());
}

public function testGroupLimit()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->orderBy('foo')->groupLimit(1, 'bar');
$this->assertSame('select * from (select *, row_number() over (partition by "bar" order by "foo" asc) as "laravel_row" from "users") as "laravel_table" where "laravel_row" <= 1 order by "laravel_row"', $builder->toSql());

$builder = $this->getBuilder();
$builder->select('*')->from('users')->orderBy('foo')->groupLimit(1, ['bar', 'baz']);
$this->assertSame('select * from (select *, row_number() over (partition by "bar", "baz" order by "foo" asc) as "laravel_row" from "users") as "laravel_table" where "laravel_row" <= 1 order by "laravel_row"', $builder->toSql());
}

public function testGroupLimitMySql()
{
$connection = m::mock(ConnectionInterface::class);
$connection->shouldReceive('getServerVersion')->andReturn('8.0.11');
$connection->shouldReceive('isMaria')->andReturn(false);

$grammar = new MySqlGrammar;
$processor = m::mock(Processor::class);

$builder = new Builder($connection, $grammar, $processor);

$builder->select('*')->from('users')->orderBy('foo')->groupLimit(1, 'bar');
$this->assertSame('select * from (select *, row_number() over (partition by `bar` order by `foo` asc) as `laravel_row` from `users`) as `laravel_table` where `laravel_row` <= 1 order by `laravel_row`', $builder->toSql());

$builder = new Builder($connection, $grammar, $processor);

$builder->select('*')->from('users')->orderBy('foo')->groupLimit(1, ['bar', 'baz']);
$this->assertSame('select * from (select *, row_number() over (partition by `bar`, `baz` order by `foo` asc) as `laravel_row` from `users`) as `laravel_table` where `laravel_row` <= 1 order by `laravel_row`', $builder->toSql());
}

public function testGroupLimitMySqlLegacy()
{
$connection = m::mock(ConnectionInterface::class);
$connection->shouldReceive('getServerVersion')->andReturn('8.0.10');
$connection->shouldReceive('isMaria')->andReturn(false);

$grammar = new MySqlGrammar;
$processor = m::mock(Processor::class);

$builder = new Builder($connection, $grammar, $processor);

$builder->select('*')->from('users')->orderBy('foo')->groupLimit(1, 'bar');
$this->assertSame('select `laravel_table`.*, @laravel_row := if(@laravel_group0 = `bar`, @laravel_row + 1, 1) as `laravel_row`, @laravel_group0 := `bar` from (select @laravel_row := 0, @laravel_group0 := 0) as `laravel_vars`, (select * from `users` order by `bar` asc, `foo` asc) as `laravel_table` having `laravel_row` <= 1 order by `laravel_row`', $builder->toSql());

$builder = new Builder($connection, $grammar, $processor);

$builder->select('*')->from('users')->orderBy('foo')->groupLimit(1, ['bar', 'baz']);
$this->assertSame('select `laravel_table`.*, @laravel_row := if(@laravel_group0 = `bar` and @laravel_group1 = `baz`, @laravel_row + 1, 1) as `laravel_row`, @laravel_group0 := `bar`, @laravel_group1 := `baz` from (select @laravel_row := 0, @laravel_group0 := 0, @laravel_group1 := 0) as `laravel_vars`, (select * from `users` order by `bar` asc, `baz` asc, `foo` asc) as `laravel_table` having `laravel_row` <= 1 order by `laravel_row`', $builder->toSql());
}

public function testGroupLimitSqlServer()
{
$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->orderBy('foo')->groupLimit(1, 'bar');
$this->assertSame('select * from (select *, row_number() over (partition by [bar] order by [foo] asc) as [laravel_row] from [users]) as [laravel_table] where [laravel_row] <= 1 order by [laravel_row]', $builder->toSql());

$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->groupLimit(1, 'bar');
$this->assertSame('select * from (select *, row_number() over (partition by [bar] order by (select 0)) as [laravel_row] from [users]) as [laravel_table] where [laravel_row] <= 1 order by [laravel_row]', $builder->toSql());
}

protected function getConnection()
{
$connection = m::mock(ConnectionInterface::class);
Expand Down
6 changes: 3 additions & 3 deletions tests/Integration/Database/EloquentEagerLoadingLimitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function testBelongsToMany(): void
$this->assertEquals([3, 2], $users[0]->roles->pluck('id')->all());
$this->assertEquals([6, 5], $users[1]->roles->pluck('id')->all());
$this->assertArrayNotHasKey('laravel_row', $users[0]->roles[0]);
$this->assertArrayNotHasKey('@laravel_group := `user_id`', $users[0]->roles[0]);
$this->assertArrayNotHasKey('@laravel_group0 := `user_id`', $users[0]->roles[0]);
}

public function testBelongsToManyWithOffset(): void
Expand All @@ -107,7 +107,7 @@ public function testHasMany(): void
$this->assertEquals([3, 2], $users[0]->posts->pluck('id')->all());
$this->assertEquals([6, 5], $users[1]->posts->pluck('id')->all());
$this->assertArrayNotHasKey('laravel_row', $users[0]->posts[0]);
$this->assertArrayNotHasKey('@laravel_group := `user_id`', $users[0]->posts[0]);
$this->assertArrayNotHasKey('@laravel_group0 := `user_id`', $users[0]->posts[0]);
}

public function testHasManyWithOffset(): void
Expand All @@ -129,7 +129,7 @@ public function testHasManyThrough(): void
$this->assertEquals([3, 2], $users[0]->comments->pluck('id')->all());
$this->assertEquals([6, 5], $users[1]->comments->pluck('id')->all());
$this->assertArrayNotHasKey('laravel_row', $users[0]->comments[0]);
$this->assertArrayNotHasKey('@laravel_group := `user_id`', $users[0]->comments[0]);
$this->assertArrayNotHasKey('@laravel_group0 := `user_id`', $users[0]->comments[0]);
}

public function testHasManyThroughWithOffset(): void
Expand Down