Skip to content

Commit 32a62ef

Browse files
committed
Fix #2 by adding getTotalCount() method.
1 parent 6d250f1 commit 32a62ef

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

src/PostgresEngine.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,22 @@ public function paginate(Builder $builder, $perPage, $page)
166166
return $this->performSearch($builder, $perPage, $page);
167167
}
168168

169+
/**
170+
* Get the total count from a raw result returned by the engine.
171+
*
172+
* @param mixed $results
173+
* @return int
174+
*/
175+
public function getTotalCount($results)
176+
{
177+
if (empty($results)) {
178+
return 0;
179+
}
180+
181+
return (int) array_first($results)
182+
->total_count;
183+
}
184+
169185
/**
170186
* Perform the given search on the engine.
171187
*
@@ -184,6 +200,7 @@ protected function performSearch(Builder $builder, $perPage = 0, $page = 1)
184200
->crossJoin($this->database->raw('plainto_tsquery(?) query'))
185201
->select($builder->model->getKeyName())
186202
->selectRaw("{$this->rankingExpression($builder->model, $indexColumn)} AS rank")
203+
->selectRaw('COUNT(*) OVER () AS total_count')
187204
->whereRaw("$indexColumn @@ query")
188205
->orderBy('rank', 'desc')
189206
->orderBy('id');

tests/PostgresEngineTest.php

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,8 @@ public function test_search()
9292

9393
$table->shouldReceive('crossJoin')->with('plainto_tsquery(?) query')->andReturnSelf()
9494
->shouldReceive('select')->with('id')->andReturnSelf()
95-
->shouldReceive('selectRaw')->andReturnSelf()
95+
->shouldReceive('selectRaw')->with('ts_rank(searchable,query) AS rank')->andReturnSelf()
96+
->shouldReceive('selectRaw')->with('COUNT(*) OVER () AS total_count')->andReturnSelf()
9697
->shouldReceive('whereRaw')->andReturnSelf()
9798
->shouldReceive('orderBy')->with('rank', 'desc')->andReturnSelf()
9899
->shouldReceive('orderBy')->with('id')->andReturnSelf()
@@ -119,11 +120,22 @@ public function test_map_correctly_maps_results_to_models()
119120
$model->shouldReceive('get')->once()->andReturn(Collection::make([new TestModel()]));
120121

121122
$results = $engine->map(
122-
json_decode('[{"id": 1, "rank": 0.33}]'), $model);
123+
json_decode('[{"id": 1, "rank": 0.33, "total_count": 1}]'), $model);
123124

124125
$this->assertCount(1, $results);
125126
}
126127

128+
public function test_it_returns_total_count()
129+
{
130+
list($engine) = $this->getEngine();
131+
132+
$count = $engine->getTotalCount(
133+
json_decode('[{"id": 1, "rank": 0.33, "total_count": 100}]')
134+
);
135+
136+
$this->assertEquals(100, $count);
137+
}
138+
127139
protected function getEngine($config = [])
128140
{
129141
$resolver = Mockery::mock(ConnectionResolverInterface::class);

0 commit comments

Comments
 (0)