Skip to content

Commit

Permalink
feat: SQL_CALC_FOUND_ROWS
Browse files Browse the repository at this point in the history
  • Loading branch information
mecha committed Feb 1, 2024
1 parent ca43dbf commit a12fb20
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Query/SelectQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class SelectQuery extends Query implements DataSource
protected ?string $alias = null;
/** @var array<string|Term> */
protected array $columns = [];
protected bool $calcFoundRows = false;

/**
* Constructor.
Expand Down Expand Up @@ -81,6 +82,20 @@ public function columns(array $columns): self
return $new;
}

/**
* Creates a copy with a different calcFoundRows setting.
*
* @param bool $calcFoundRows Whether to calculate the number of rows that
* would have been returned if there was no LIMIT clause.
* @return static The new instance.
*/
public function calcFoundRows(bool $calcFoundRows = true): self
{
$new = clone $this;
$new->calcFoundRows = $calcFoundRows;
return $new;
}

/**
* Creates a copy with a new selection offset, based on the current limit and the given page number.
*
Expand Down Expand Up @@ -121,8 +136,10 @@ public function toSql(): string
? 'FROM ' . $this->source->compileSource()
: '';

$calc = $this->calcFoundRows ? 'SQL_CALC_FOUND_ROWS ' : '';

$result = [
'SELECT ' . $this->compileColumnList(),
'SELECT ' . $calc . $this->compileColumnList(),
$from,
$this->compileJoins(),
$this->compileWhere(),
Expand Down
16 changes: 16 additions & 0 deletions tests/Query/SelectQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,22 @@ public function testFrom()
$this->assertSame($source, $this->expose($new)->source);
}

public function testCalcFoundRows()
{
$query = new SelectQuery();

$new1 = $query->calcFoundRows();

$this->assertNotSame($query, $new1);
$this->assertTrue($this->expose($new1)->calcFoundRows);

$new2 = $query->calcFoundRows(false);

$this->assertNotSame($query, $new2);
$this->assertNotSame($new1, $new2);
$this->assertFalse($this->expose($new2)->calcFoundRows);
}

public function testColumns()
{
$query = new SelectQuery();
Expand Down

0 comments on commit a12fb20

Please sign in to comment.