From a12fb200cad3f1e277390bfe90a0bb5a7fb3144d Mon Sep 17 00:00:00 2001 From: Miguel Muscat Date: Thu, 1 Feb 2024 11:13:40 +0100 Subject: [PATCH] feat: SQL_CALC_FOUND_ROWS --- src/Query/SelectQuery.php | 19 ++++++++++++++++++- tests/Query/SelectQueryTest.php | 16 ++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/Query/SelectQuery.php b/src/Query/SelectQuery.php index d2cceef..300b4cf 100644 --- a/src/Query/SelectQuery.php +++ b/src/Query/SelectQuery.php @@ -26,6 +26,7 @@ class SelectQuery extends Query implements DataSource protected ?string $alias = null; /** @var array */ protected array $columns = []; + protected bool $calcFoundRows = false; /** * Constructor. @@ -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. * @@ -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(), diff --git a/tests/Query/SelectQueryTest.php b/tests/Query/SelectQueryTest.php index c0960cc..27be32b 100644 --- a/tests/Query/SelectQueryTest.php +++ b/tests/Query/SelectQueryTest.php @@ -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();