Skip to content
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
36 changes: 12 additions & 24 deletions analyzer-baseline.toml

Large diffs are not rendered by default.

14 changes: 1 addition & 13 deletions lint-baseline.toml
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ count = 2
file = "src/Pdo/Feature/SqliteRowCounter.php"
code = "no-fully-qualified-global-class-like"
message = "Fully-qualified class-like reference detected."
count = 2
count = 1

[[issues]]
file = "src/Pdo/Feature/SqliteRowCounter.php"
Expand Down Expand Up @@ -618,18 +618,6 @@ code = "prefer-test-attribute"
message = "Use `#[Test]` attribute instead of `test` prefix on method `testFormatParameterName`."
count = 1

[[issues]]
file = "test/unit/Pdo/Feature/SqliteRowCounterTest.php"
code = "assertion-style"
message = "Inconsistent assertions style."
count = 1

[[issues]]
file = "test/unit/Pdo/Feature/SqliteRowCounterTest.php"
code = "prefer-test-attribute"
message = "Use `#[Test]` attribute instead of `test` prefix on method `testRowCounterExists`."
count = 1

[[issues]]
file = "test/unit/Pdo/ResultTest.php"
code = "assert-description"
Expand Down
3 changes: 3 additions & 0 deletions mago.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ php-version = "8.3.0"
paths = ["src", "test"]
includes = ["vendor"]

[formatter]
parentheses-around-new-in-member-access = true

[linter]
baseline = "lint-baseline.toml"

Expand Down
8 changes: 4 additions & 4 deletions src/Metadata/Source.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ protected function loadColumnData(string $table, string $schema): void
$columns = [];

foreach ($results as $row) {
$columns[$row['name']] = [
$columns[(string) $row['name']] = [
// cid appears to be zero-based, ordinal position needs to be one-based
'ordinal_position' => $row['cid'] + 1,
'column_default' => $row['dflt_value'],
Expand Down Expand Up @@ -171,7 +171,7 @@ protected function loadConstraintData(string $table, string $schema): void
$constraint['constraint_type'] = 'PRIMARY KEY';
$primaryKey = null;
}
$constraints[$constraint['constraint_name']] = $constraint;
$constraints[(string) $constraint['constraint_name']] = $constraint;
}

if (null !== $primaryKey) {
Expand Down Expand Up @@ -268,7 +268,7 @@ protected function loadTableNameData(string $schema): void
$table = array_merge($table, $data);
}
}
$tables[$row['name']] = $table;
$tables[(string) $row['name']] = $table;
}
$this->data['table_names'][$schema] = $tables;
}
Expand Down Expand Up @@ -314,7 +314,7 @@ protected function loadTriggerData(string $schema): void
if (null !== ($data = $this->parseTrigger($row['sql']))) {
$trigger = array_merge($trigger, $data);
}
$triggers[$trigger['trigger_name']] = $trigger;
$triggers[(string) $trigger['trigger_name']] = $trigger;
}

$this->data['triggers'][$schema] = $triggers;
Expand Down
4 changes: 2 additions & 2 deletions src/Pdo/Driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ public function createResult($resource, Statement|string|null $context = null):
$sqliteRowCounter = $this->getFeature(Feature\SqliteRowCounter::class);
$rowCount = 0;

if ($sqliteRowCounter && $resource->columnCount() > 0) {
if ($sqliteRowCounter && $resource instanceof PDOStatement && $resource->columnCount() > 0) {
$rowCount = $sqliteRowCounter->getRowCountClosure($context);
}

$result->initialize($resource, $this->connection->getLastGeneratedValue(), $rowCount);
$result->initialize($resource, $this->getLastGeneratedValue(), $rowCount);

return $result;
}
Expand Down
53 changes: 41 additions & 12 deletions src/Pdo/Feature/SqliteRowCounter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
namespace PhpDb\Sqlite\Pdo\Feature;

use Closure;
use PDOException;
use PDOStatement;
use PhpDb\Adapter\Driver\Feature\AbstractFeature;
use PhpDb\Adapter\Driver\Pdo;
use PhpDb\Adapter\Driver\Pdo\Statement;
use PhpDb\Adapter\Exception\RuntimeException;

use function str_contains;
use function strtolower;
Expand All @@ -17,20 +20,26 @@
*/
class SqliteRowCounter extends AbstractFeature
{
/**
* @throws PDOException
* @throws RuntimeException
*/
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);
$pdo = $this->driver->getConnection()->getResource();

return (int) $countRow['count'];
return $this->fetchCount($pdo->query($countSql));
}

/**
* @throws PDOException
* @throws RuntimeException
*/
public function getCountForStatement(Pdo\Statement $statement): int
{
$countStmt = clone $statement;
Expand All @@ -40,19 +49,39 @@ public function getCountForStatement(Pdo\Statement $statement): int
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$countStmt->prepare($countSql);
$result = $countStmt->execute();
$countRow = $result->getResource()->fetch(\PDO::FETCH_ASSOC);
$result = $countStmt->execute();
$count = $this->fetchCount($result->getResource());
unset($statement, $result);

return (int) $countRow['count'];
return $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);
};
return (
/**
* @throws PDOException
* @throws RuntimeException
*/
function () use ($context): int {
return $context instanceof Pdo\Statement
? $this->getCountForStatement($context)
: $this->getCountForSql($context);
}
);
}

/**
* @throws PDOException
* @throws RuntimeException
*/
private function fetchCount(mixed $statement): int
{
if (! $statement instanceof PDOStatement) {
throw new RuntimeException('Unable to fetch the row count: the count query did not produce a statement');
}
$countRow = $statement->fetch(\PDO::FETCH_ASSOC);

return (int) $countRow['count'];
}
}
8 changes: 5 additions & 3 deletions test/unit/AdapterPlatformTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use PDO;
use PhpDb\Adapter\Driver\PdoDriverInterface;
use PhpDb\Adapter\Exception\VunerablePlatformQuoteException;
use PhpDb\Adapter\Exception\RuntimeException;
use PhpDb\Sqlite\AdapterPlatform;
use PhpDb\Sqlite\Sql\Platform as SqlPlatformDecorator;
use PHPUnit\Framework\Attributes\CoversClass;
Expand Down Expand Up @@ -152,7 +152,8 @@ public function testQuoteValueList(): void
{
$expected = "'Foo O\\'Bar'";
$platform = new AdapterPlatform();
$this->expectException(VunerablePlatformQuoteException::class);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('without extension/driver support can introduce security vulnerabilities');
$actual = $platform->quoteValueList("Foo O'Bar");
self::assertEquals($expected, $actual);
}
Expand All @@ -161,7 +162,8 @@ public function testQuoteValueThrowsExeceptionWithoutDriverSupport(): void
{
$platform = new AdapterPlatform();
//$this->expectNotToPerformAssertions();
$this->expectException(VunerablePlatformQuoteException::class);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('without extension/driver support can introduce security vulnerabilities');
$platform->quoteValue('value');
}

Expand Down
58 changes: 58 additions & 0 deletions test/unit/Pdo/DriverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,26 @@
namespace PhpDbTest\Sqlite\Pdo;

use Override;
use PDO;
use PDOStatement;
use PhpDb\Adapter\Driver\Pdo\Result;
use PhpDb\Adapter\Driver\PdoDriverAwareInterface;
use PhpDb\Adapter\Driver\PdoDriverInterface;
use PhpDb\Adapter\Driver\ResultInterface;
use PhpDb\Adapter\Driver\StatementInterface;
use PhpDb\Exception\RuntimeException;
use PhpDb\Sqlite\Pdo\Connection;
use PhpDb\Sqlite\Pdo\Driver;
use PhpDb\Sqlite\Pdo\Feature\SqliteRowCounter;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;

#[CoversClass(Driver::class)]
#[Group('unit')]
final class DriverTest extends TestCase
{
protected Driver $pdo;
Expand Down Expand Up @@ -51,6 +58,42 @@ public static function getParamsAndType(): array
];
}

#[Test]
public function createResultCarriesTheConnectionsLastGeneratedValue(): void
{
$result = $this->createDriverWithRowCounter()->createResult($this->createStub(PDOStatement::class));

static::assertSame('42', $result->getGeneratedValue());
}

#[Test]
public function createResultCountsRowsWithTheRowCounterWhenTheStatementReturnsColumns(): void
{
$countStatement = $this->createStub(PDOStatement::class);
$countStatement->method('fetch')->willReturn(['count' => '5']);
$pdo = $this->createStub(PDO::class);
$pdo->method('query')->willReturn($countStatement);

$resource = $this->createStub(PDOStatement::class);
$resource->method('columnCount')->willReturn(1);

$result = $this->createDriverWithRowCounter($pdo)->createResult($resource, 'SELECT * FROM foo');

static::assertSame(5, $result->count());
}

#[Test]
public function createResultSkipsTheRowCounterWhenTheStatementReturnsNoColumns(): void
{
$resource = $this->createStub(PDOStatement::class);
$resource->method('columnCount')->willReturn(0);
$resource->method('rowCount')->willReturn(3);

$result = $this->createDriverWithRowCounter()->createResult($resource, 'DELETE FROM foo');

static::assertSame(0, $result->count());
}

#[DataProvider('getParamsAndType')]
public function testFormatParameterName(int|string $name, ?string $type, string $expected): void
{
Expand Down Expand Up @@ -86,4 +129,19 @@ protected function setUp(): void
$this->createMock(ResultInterface::class),
);
}

private function createDriverWithRowCounter(?PDO $pdo = null): Driver
{
$connection = $this->createStub(Connection::class);
$connection->method('getLastGeneratedValue')->willReturn('42');
$connection->method('getResource')->willReturn($pdo ?? $this->createStub(PDO::class));

/** @var StatementInterface&PdoDriverAwareInterface&MockObject $statementPrototype */
$statementPrototype = $this->createMockForIntersectionOfInterfaces([
StatementInterface::class,
PdoDriverAwareInterface::class,
]);

return new Driver($connection, $statementPrototype, new Result(), [new SqliteRowCounter()]);
}
}
Loading
Loading