forked from php-db/phpdb-sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqliteRowCounter.php
More file actions
58 lines (49 loc) · 1.66 KB
/
SqliteRowCounter.php
File metadata and controls
58 lines (49 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
declare(strict_types=1);
namespace PhpDb\Sqlite\Pdo\Feature;
use Closure;
use PhpDb\Adapter\Driver\Feature\AbstractFeature;
use PhpDb\Adapter\Driver\Pdo;
use PhpDb\Adapter\Driver\Pdo\Statement;
use function str_contains;
use function strtolower;
/**
* SqliteRowCounter
*/
class SqliteRowCounter extends AbstractFeature
{
public function getCountForStatement(Pdo\Statement $statement): int
{
$countStmt = clone $statement;
$sql = $statement->getSql();
if (empty($sql) || ! str_contains(strtolower($sql), 'select')) {
return 0;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$countStmt->prepare($countSql);
$result = $countStmt->execute();
$countRow = $result->getResource()->fetch(\PDO::FETCH_ASSOC);
unset($statement, $result);
return (int) $countRow['count'];
}
public function getCountForSql(string $sql): int
{
if (empty($sql) || ! str_contains(strtolower($sql), 'select')) {
return 0;
}
$countSql = 'SELECT COUNT(*) as count FROM (' . $sql . ')';
/** @var \PDO $pdo */
$pdo = $this->driver->getConnection()->getResource();
$result = $pdo->query($countSql);
$countRow = $result->fetch(\PDO::FETCH_ASSOC);
return (int) $countRow['count'];
}
public function getRowCountClosure(Statement|string|null $context): Closure
{
return function () use ($context): int {
return $context instanceof Pdo\Statement
? $this->getCountForStatement($context)
: $this->getCountForSql($context);
};
}
}