Skip to content
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

Use phpmyadmin/sql-parser #313

Closed
wants to merge 2 commits into from
Closed
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"ext-mysqli": "*",
"composer-runtime-api": "^2.0",
"composer/semver": "^3.2",
"phpmyadmin/sql-parser": "^5.5",
"phpstan/phpstan": "^1.2"
},
"require-dev": {
Expand Down
20 changes: 18 additions & 2 deletions src/QueryReflection/MysqliQueryReflector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use mysqli;
use mysqli_result;
use mysqli_sql_exception;
use PhpMyAdmin\SqlParser\Parser;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
use PHPStan\Type\Constant\ConstantIntegerType;
Expand Down Expand Up @@ -76,6 +77,11 @@ public function validateQueryString(string $queryString): ?Error
*/
public function getResultType(string $queryString, int $fetchType): ?Type
{
$parser = new Parser($queryString, false);

/** @var ?\PhpMyAdmin\SqlParser\Statements\SelectStatement $statement */
$statement = $parser->statements[0] ?? null;

$result = $this->simulateQuery($queryString);
if (!\is_array($result)) {
return null;
Expand All @@ -94,16 +100,26 @@ public function getResultType(string $queryString, int $fetchType): ?Type
throw new ShouldNotHappenException();
}

$function = null;

if (null !== $statement) {
$parsedExpression = $statement->expr[$i];

if (!empty($parsedExpression->function)) {
$function = strtoupper($parsedExpression->function);
}
}

if (self::FETCH_TYPE_ASSOC === $fetchType || self::FETCH_TYPE_BOTH === $fetchType) {
$arrayBuilder->setOffsetValueType(
new ConstantStringType($val->name),
$this->typeMapper->mapToPHPStanType($val->type, $val->flags, $val->length)
$this->typeMapper->mapToPHPStanType($val->type, $val->flags, $val->length, $function)
);
}
if (self::FETCH_TYPE_NUMERIC === $fetchType || self::FETCH_TYPE_BOTH === $fetchType) {
$arrayBuilder->setOffsetValueType(
new ConstantIntegerType($i),
$this->typeMapper->mapToPHPStanType($val->type, $val->flags, $val->length)
$this->typeMapper->mapToPHPStanType($val->type, $val->flags, $val->length, $function)
);
}
++$i;
Expand Down
22 changes: 19 additions & 3 deletions src/QueryReflection/QueryReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

namespace staabm\PHPStanDba\QueryReflection;

use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Statement;
use PhpMyAdmin\SqlParser\Utils\Query;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\Concat;
use PHPStan\Analyser\Scope;
Expand Down Expand Up @@ -193,12 +196,25 @@ private function resolveQueryStringExpr(Expr $queryExpr, Scope $scope): ?string
return QuerySimulation::simulateParamValueType($type, false);
}

public static function parseQuery(string $query): Statement
{
$parser = new Parser($query, false);

if (1 !== \count($parser->statements)) {
throw new ShouldNotHappenException('query contains zero or more than one statements');
}

return $parser->statements[0];
}

public static function getQueryType(string $query): ?string
{
$query = ltrim($query);
$statement = self::parseQuery($query);

$flags = Query::getFlags($statement);

if (preg_match('/^\s*\(?\s*(SELECT|SHOW|UPDATE|INSERT|DELETE|REPLACE|CREATE|CALL|OPTIMIZE)/i', $query, $matches)) {
return strtoupper($matches[1]);
if ($flags['querytype']) {
return $flags['querytype'];
}

return null;
Expand Down
37 changes: 11 additions & 26 deletions src/QueryReflection/QuerySimulation.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

namespace staabm\PHPStanDba\QueryReflection;

use PHPStan\ShouldNotHappenException;
use PhpMyAdmin\SqlParser\Components\Limit;
use PhpMyAdmin\SqlParser\Statements\SelectStatement;
use PHPStan\Type\Accessory\AccessoryType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\BooleanType;
Expand Down Expand Up @@ -119,38 +120,22 @@ public static function simulateParamValueType(Type $paramType, bool $preparedPar

public static function simulate(string $queryString): ?string
{
$queryString = self::stripTraillingLimit($queryString);
$statement = QueryReflection::parseQuery($queryString);

if (null === $queryString) {
if (!($statement instanceof SelectStatement)) {
return null;
}
$queryString .= ' LIMIT 0';

return $queryString;
}

private static function stripTraillingLimit(string $queryString): ?string
{
// XXX someday we will use a proper SQL parser
$queryString = rtrim($queryString);
/* @var SelectStatement $statement */

// strip trailling delimiting semicolon
$queryString = rtrim($queryString, ';');
// strip FOR UPDATE
$statement->end_options = null;

// strip trailling FOR UPDATE/FOR SHARE
$queryString = preg_replace('/(.*)FOR (UPDATE|SHARE)\s*$/i', '$1', $queryString);
// strip INTO
$statement->into = null;

if (null === $queryString) {
throw new ShouldNotHappenException('Could not strip trailling FOR UPDATE/SHARE from query');
}

// strip trailling OFFSET
$queryString = preg_replace('/(.*)OFFSET\s+["\']?\d+["\']?\s*$/i', '$1', $queryString);

if (null === $queryString) {
throw new ShouldNotHappenException('Could not strip trailing OFFSET from query');
}
$statement->limit = new Limit(0, 0);

return preg_replace('/\s*LIMIT\s+["\']?\d+["\']?\s*(,\s*["\']?\d*["\']?)?\s*$/i', '', $queryString);
return $statement->build();
}
}
6 changes: 5 additions & 1 deletion src/TypeMapping/MysqlTypeMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ final class MysqlTypeMapper
/**
* @param list<string> $mysqlFlags
*/
public function mapToPHPStanType(string $mysqlType, array $mysqlFlags, int $length): Type
public function mapToPHPStanType(string $mysqlType, array $mysqlFlags, int $length, ?string $function = null): Type
{
$numeric = false;
$notNull = false;
Expand Down Expand Up @@ -82,6 +82,10 @@ public function mapToPHPStanType(string $mysqlType, array $mysqlFlags, int $leng
default => null,
};
}

if ('COUNT' === $function) {
$phpstanType = $mysqlIntegerRanges->unsignedBigInt();
}
}

if ($autoIncrement) {
Expand Down
4 changes: 2 additions & 2 deletions src/TypeMapping/MysqliTypeMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ public function __construct()
$this->typeMapper = new MysqlTypeMapper();
}

public function mapToPHPStanType(int $mysqlType, int $mysqlFlags, int $length): Type
public function mapToPHPStanType(int $mysqlType, int $mysqlFlags, int $length, ?string $function = null): Type
{
return $this->typeMapper->mapToPHPStanType($this->type2txt($mysqlType), $this->flags2txt($mysqlFlags), $length);
return $this->typeMapper->mapToPHPStanType($this->type2txt($mysqlType), $this->flags2txt($mysqlFlags), $length, $function);
}

private function type2txt(int $typeId): string
Expand Down