Skip to content

Add count select for total count queries #7

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
12 changes: 5 additions & 7 deletions src/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ protected function select() : Select
*/
protected function count() : Select
{
return $this->select()->columns([
self::COUNT_COLUMN => new Literal('COUNT(1)')
]);
return new Count($this->tableGateway->getTable());
}

/**
Expand Down Expand Up @@ -109,13 +107,13 @@ protected function fetchListEntities(Select $select) : ResultSetInterface
}

/**
* @param \Zend\Db\Sql\Select $select
* @param Count $select
* @return int
*/
protected function fetchCount(Select $select)
protected function fetchCount(Count $select)
{
$statement = $this->tableGateway->getSql()->prepareStatementForSqlObject($select);
$results = $statement->execute();
$statement = $this->tableGateway->getSql()->prepareStatementForSqlObject($select);
$results = $statement->execute();

return $results->current()[self::COUNT_COLUMN];
}
Expand Down
27 changes: 27 additions & 0 deletions src/Select/Count.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Matters\Select;

use Zend\Db\Sql\Literal;
use Zend\Db\Sql\Select;

class Count extends Select
{
const COUNT_COLUMN = 'count';

/**
* Count constructor.
*/
public function __construct($table = null)
{
parent::__construct($table);
parent::columns([
self::COUNT_COLUMN => new Literal('COUNT(1)')
]);
}

public function columns(array $columns, $prefixColumnsWithTable = true)
{
throw new \BadMethodCallException('The columns should not be changed');
}
}
28 changes: 28 additions & 0 deletions tests/Select/CountTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Matters\Select;

use PHPUnit\Framework\TestCase;
use Zend\Db\Adapter\Platform\Postgresql;

class CountTest extends TestCase
{
public function testInstance()
{
$select = (new Count())->from('carot');
$select->where("color = 'purple'");

$platform = new class extends Postgresql
{
public function quoteValue($value)
{
return '"'. $value .'"';
}
};

self::assertSame(
'SELECT COUNT(1) AS "count" FROM "carot" WHERE color = \'purple\'',
$select->getSqlString($platform)
);
}
}