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
39 changes: 39 additions & 0 deletions src/QueryReflection/QueryReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,13 @@ private function replaceParameters(string $queryString, array $parameters): stri
foreach ($parameters as $placeholderKey => $parameter) {
$value = $parameter->simulatedValue;

// PostgreSQL parses a quoted literal with the input function of the type it is compared to,
// so no simulated string fits every column (e.g. uuid, jsonb, enum). An untyped NULL is
// resolved from context instead, like a bind parameter. see https://github.com/staabm/phpstan-dba/issues/600
if (null !== $value && $this->isNonConstantString($parameter->type) && $this->isPgsql()) {
$value = null;
}

if (\is_string($value)) {
// XXX escaping
$value = "'" . $value . "'";
Expand All @@ -596,6 +603,38 @@ private function replaceParameters(string $queryString, array $parameters): stri
return $queryString;
}

/**
* Whether the type is a string we know nothing about: not a constant and not numeric,
* possibly nullable or a list of such strings.
*/
private function isNonConstantString(Type $type): bool
{
if ($type->isIterable()->yes()) {
$type = $type->getIterableValueType();
}
$type = TypeCombinator::removeNull($type);

return $type->isString()->yes()
&& ! $type->isNumericString()->yes()
&& ! $type->isConstantScalarValue()->yes();
}

/**
* Checks the datasource rather than the reflector class,
* so wrapped reflectors (recording, lazy, ...) are detected as well.
*/
private function isPgsql(): bool
{
$reflector = self::reflector();
if (! $reflector instanceof RecordingReflector) {
return false;
}

$datasource = $reflector->getDatasource();

return $datasource instanceof \PDO && 'pgsql' === $datasource->getAttribute(\PDO::ATTR_DRIVER_NAME);
}

private static function reflector(): QueryReflector
{
if (null === self::$reflector) {
Expand Down
1 change: 1 addition & 0 deletions tests/default/DbaInferenceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public function dataFileAsserts(): iterable
if ('pdo-pgsql' === getenv('DBA_REFLECTOR')) {
yield from $this->gatherAssertTypes(__DIR__ . '/data/pdo-pgsql.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/typemix-pgsql.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-600.php');
} else {
yield from $this->gatherAssertTypes(__DIR__ . '/data/pdo-mysql.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/typemix-mysql.php');
Expand Down
61 changes: 61 additions & 0 deletions tests/default/data/bug-600.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace Bug600;

use Doctrine\DBAL\Connection;
use PDO;
use function PHPStan\Testing\assertType;

class Foo
{
public function uuidColumn(Connection $conn, string $id)
{
$row = $conn->fetchAssociative('SELECT name FROM uuid_entity WHERE id = :id', ['id' => $id]);
assertType('array{name: string}|false', $row);
}

/**
* @param non-empty-string $id
*/
public function uuidColumnNonEmptyString(Connection $conn, string $id)
{
$row = $conn->fetchAssociative('SELECT name FROM uuid_entity WHERE id = ?', [$id]);
assertType('array{name: string}|false', $row);
}

public function nullableUuidColumn(Connection $conn, ?string $parentId)
{
$rows = $conn->fetchAllAssociative('SELECT name FROM uuid_entity WHERE parent_id = :parentId', ['parentId' => $parentId]);
assertType('list<array{name: string}>', $rows);
}

/**
* @param list<string> $ids
*/
public function uuidColumnInList(Connection $conn, array $ids)
{
$names = $conn->fetchFirstColumn('SELECT name FROM uuid_entity WHERE id IN (:ids)', ['ids' => $ids]);
assertType('list<string>', $names);
}

public function uuidColumnPdo(PDO $pdo, string $id)
{
$stmt = $pdo->prepare('SELECT name FROM uuid_entity WHERE id = :id');
$stmt->execute(['id' => $id]);
foreach ($stmt as $row) {
assertType('array{name: string, 0: string}', $row);
}
}

public function jsonbColumn(Connection $conn, string $filter)
{
$row = $conn->fetchAssociative('SELECT pid FROM typemix WHERE c_jsonb @> :filter', ['filter' => $filter]);
assertType('array{pid: int<1, 2147483647>}|false', $row);
}

public function enumColumn(Connection $conn, string $size)
{
$row = $conn->fetchAssociative('SELECT pid FROM typemix WHERE c_enum = :size', ['size' => $size]);
assertType('array{pid: int<1, 2147483647>}|false', $row);
}
}
9 changes: 9 additions & 0 deletions tests/pgsql-schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,12 @@ ALTER TABLE cmsdomain

CREATE INDEX ON cmsdomain(cmsdomainid);
CREATE INDEX ON cmsdomain(url);

CREATE TABLE uuid_entity (
id uuid NOT NULL,
parent_id uuid DEFAULT NULL,
name varchar(255) NOT NULL
);

ALTER TABLE uuid_entity
ADD PRIMARY KEY (id);
17 changes: 13 additions & 4 deletions tests/rules/SyntaxErrorInPreparedStatementMethodRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public function testSyntaxErrorInQueryRule(): void
],
[
'Query error: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "package" does not exist
LINE 1: EXPLAIN UPDATE package SET indexedAt=\'1970-01-01\' WHERE id I...
LINE 1: EXPLAIN UPDATE package SET indexedAt=NULL WHERE id IN (NULL)...
^ (42P01).',
180,
],
Expand Down Expand Up @@ -343,19 +343,19 @@ public function testSyntaxErrorWithInferencePlaceholder()
$expectedErrors = [
[
"Query error: SQLSTATE[42703]: Undefined column: 7 ERROR: column \"does_not_exist\" does not exist
LINE 1: SELECT email, does_not_exist FROM ada WHERE email = '1970-01...
LINE 1: SELECT email, does_not_exist FROM ada WHERE email = NULL AND...
^ (42703).",
12,
],
[
"Query error: SQLSTATE[42703]: Undefined column: 7 ERROR: column \"does_not_exist\" does not exist
LINE 1: SELECT email, does_not_exist FROM ada WHERE email = '1970-01...
LINE 1: SELECT email, does_not_exist FROM ada WHERE email = NULL AND...
^ (42703).",
36,
],
[
"Query error: SQLSTATE[42703]: Undefined column: 7 ERROR: column \"does_not_exist\" does not exist
LINE 1: SELECT email, does_not_exist FROM ada WHERE email = '1970-01...
LINE 1: SELECT email, does_not_exist FROM ada WHERE email = NULL AND...
^ (42703).",
60,
],
Expand Down Expand Up @@ -386,6 +386,15 @@ public function testSyntaxErrorWithInferencePlaceholder()
$this->analyse([__DIR__ . '/data/syntax-error-with-inference-placeholder.php'], $expectedErrors);
}

public function testBug600(): void
{
if (PdoPgSqlQueryReflector::NAME !== getenv('DBA_REFLECTOR')) {
self::markTestSkipped('The uuid_entity table only exists in the PostgreSQL test schema.');
}

$this->analyse([__DIR__ . '/data/bug-600.php'], []);
}

public function testBug749(): void
{
if (MysqliQueryReflector::NAME !== getenv('DBA_REFLECTOR')) {
Expand Down
41 changes: 41 additions & 0 deletions tests/rules/data/bug-600.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Bug600;

use Doctrine\DBAL\Connection;

class UuidQueries
{
public function select(Connection $conn, string $id)
{
$conn->fetchAssociative('SELECT name FROM uuid_entity WHERE id = :id', ['id' => $id]);
}

/**
* @param list<string> $ids
*/
public function selectInList(Connection $conn, array $ids)
{
$conn->fetchFirstColumn('SELECT name FROM uuid_entity WHERE id IN (:ids)', ['ids' => $ids]);
}

public function updateNullable(Connection $conn, string $id, ?string $parentId)
{
$conn->executeStatement('UPDATE uuid_entity SET parent_id = :parentId WHERE id = :id', ['id' => $id, 'parentId' => $parentId]);
}

public function insertIntoNotNullColumns(Connection $conn, string $id, string $name)
{
$conn->executeStatement('INSERT INTO uuid_entity (id, name) VALUES (:id, :name)', ['id' => $id, 'name' => $name]);
}

public function jsonb(Connection $conn, string $filter)
{
$conn->fetchAssociative('SELECT pid FROM typemix WHERE c_jsonb @> :filter', ['filter' => $filter]);
}

public function enum(Connection $conn, string $size)
{
$conn->fetchAssociative('SELECT pid FROM typemix WHERE c_enum = :size', ['size' => $size]);
}
}
Loading