From 7518a0aaf1aed40ba4344712c625b0dd62f56839 Mon Sep 17 00:00:00 2001 From: Sergei Morozov Date: Sat, 31 Oct 2020 17:01:14 -0700 Subject: [PATCH] Port SQL parser from PDO --- psalm.xml | 8 - .../Exception/MissingNamedParameter.php | 21 ++ .../Exception/MissingPositionalParameter.php | 23 ++ src/Connection.php | 54 ++- .../ConvertPositionalToNamedPlaceholders.php | 158 ++------ src/Driver/OCI8/Statement.php | 10 +- src/Exception/ParserException.php | 17 + src/ExpandArrayParameters.php | 150 ++++++++ src/Platforms/AbstractPlatform.php | 9 + src/Platforms/MySQL57Platform.php | 6 + src/SQL/Parser.php | 134 +++++++ src/SQL/Parser/Exception.php | 12 + src/SQL/Parser/Visitor.php | 32 ++ src/SQLParserUtils.php | 282 -------------- src/SQLParserUtilsException.php | 37 -- .../ExpandArrayParametersTest.php} | 308 +++------------- ...nvertPositionalToNamedPlaceholdersTest.php | 50 +-- tests/Functional/DataAccessTest.php | 20 +- tests/SQL/ParserTest.php | 343 ++++++++++++++++++ 19 files changed, 890 insertions(+), 784 deletions(-) create mode 100644 src/ArrayParameters/Exception/MissingNamedParameter.php create mode 100644 src/ArrayParameters/Exception/MissingPositionalParameter.php create mode 100644 src/Exception/ParserException.php create mode 100644 src/ExpandArrayParameters.php create mode 100644 src/SQL/Parser.php create mode 100644 src/SQL/Parser/Exception.php create mode 100644 src/SQL/Parser/Visitor.php delete mode 100644 src/SQLParserUtils.php delete mode 100644 src/SQLParserUtilsException.php rename tests/{SQLParserUtilsTest.php => Connection/ExpandArrayParametersTest.php} (58%) create mode 100644 tests/SQL/ParserTest.php diff --git a/psalm.xml b/psalm.xml index 2d8a65dc940..8ce2b9b9b11 100644 --- a/psalm.xml +++ b/psalm.xml @@ -75,14 +75,6 @@ - - - - - - diff --git a/src/ArrayParameters/Exception/MissingNamedParameter.php b/src/ArrayParameters/Exception/MissingNamedParameter.php new file mode 100644 index 00000000000..2ad60c6bc65 --- /dev/null +++ b/src/ArrayParameters/Exception/MissingNamedParameter.php @@ -0,0 +1,21 @@ +query($sql); } - [$sql, $params, $types] = SQLParserUtils::expandListParameters($sql, $params, $types); + if ($this->needsArrayParameterConversion($params, $types)) { + if ($this->parser === null) { + $this->parser = $this->getDatabasePlatform()->createSQLParser(); + } + + $visitor = new ExpandArrayParameters($params, $types); + + try { + $this->parser->parse($sql, $visitor); + } catch (Parser\Exception $e) { + throw ParserException::new($e); + } + + $sql = $visitor->getSQL(); + $params = $visitor->getParameters(); + $types = $visitor->getTypes(); + } $stmt = $connection->prepare($sql); @@ -1557,6 +1578,25 @@ private function execute(string $sql, array $params, array $types): Driver\Resul } } + /** + * @param array|array $params + * @param array|array $types + */ + private function needsArrayParameterConversion(array $params, array $types): bool + { + if (! is_int(key($params))) { + return true; + } + + foreach ($types as $type) { + if ($type === self::PARAM_INT_ARRAY || $type === self::PARAM_STR_ARRAY) { + return true; + } + } + + return false; + } + /** * Binds a set of parameters, some or all of which are typed with a PDO binding type * or DBAL mapping type, to a given statement. @@ -1571,13 +1611,11 @@ private function _bindTypedValues(DriverStatement $stmt, array $params, array $t { // Check whether parameters are positional or named. Mixing is not allowed. if (is_int(key($params))) { - // Positional parameters - $typeOffset = array_key_exists(0, $types) ? -1 : 0; - $bindIndex = 1; - foreach ($params as $value) { - $typeIndex = $bindIndex + $typeOffset; - if (isset($types[$typeIndex])) { - $type = $types[$typeIndex]; + $bindIndex = 1; + + foreach ($params as $key => $value) { + if (isset($types[$key])) { + $type = $types[$key]; [$value, $bindingType] = $this->getBindingInfo($value, $type); $stmt->bindValue($bindIndex, $value, $bindingType); } else { diff --git a/src/Driver/OCI8/ConvertPositionalToNamedPlaceholders.php b/src/Driver/OCI8/ConvertPositionalToNamedPlaceholders.php index ba09397f329..483879d4726 100644 --- a/src/Driver/OCI8/ConvertPositionalToNamedPlaceholders.php +++ b/src/Driver/OCI8/ConvertPositionalToNamedPlaceholders.php @@ -1,164 +1,58 @@ ). * * Oracle does not support positional parameters, hence this method converts all - * positional parameters into artificially named parameters. Note that this conversion - * is not perfect. All question marks (?) in the original statement are treated as - * placeholders and converted to a named parameter. + * positional parameters into artificially named parameters. * * @internal This class is not covered by the backward compatibility promise */ -final class ConvertPositionalToNamedPlaceholders +final class ConvertPositionalToNamedPlaceholders implements Visitor { - /** - * @param string $statement The SQL statement to convert. - * - * @return mixed[] [0] => the statement value (string), [1] => the paramMap value (array). - * - * @throws Exception - */ - public function __invoke(string $statement): array - { - $fragmentOffset = $tokenOffset = 0; - $fragments = $paramMap = []; - $currentLiteralDelimiter = null; - - do { - if ($currentLiteralDelimiter === null) { - $result = $this->findPlaceholderOrOpeningQuote( - $statement, - $tokenOffset, - $fragmentOffset, - $fragments, - $currentLiteralDelimiter, - $paramMap - ); - } else { - $result = $this->findClosingQuote($statement, $tokenOffset, $currentLiteralDelimiter); - } - } while ($result); + /** @var list */ + private $buffer = []; - if ($currentLiteralDelimiter !== null) { - throw NonTerminatedStringLiteral::new($tokenOffset - 1); - } + /** @var array */ + private $parameterMap = []; - $fragments[] = substr($statement, $fragmentOffset); - $statement = implode('', $fragments); - - return [$statement, $paramMap]; + public function acceptOther(string $sql): void + { + $this->buffer[] = $sql; } - /** - * Finds next placeholder or opening quote. - * - * @param string $statement The SQL statement to parse - * @param int $tokenOffset The offset to start searching from - * @param int $fragmentOffset The offset to build the next fragment from - * @param string[] $fragments Fragments of the original statement not containing placeholders - * @param string|null $currentLiteralDelimiter The delimiter of the current string literal - * or NULL if not currently in a literal - * @param string[] $paramMap Mapping of the original parameter positions - * to their named replacements - * - * @return bool Whether the token was found - */ - private function findPlaceholderOrOpeningQuote( - string $statement, - int &$tokenOffset, - int &$fragmentOffset, - array &$fragments, - ?string &$currentLiteralDelimiter, - array &$paramMap - ): bool { - $token = $this->findToken($statement, $tokenOffset, '/[?\'"]/'); - - if ($token === null) { - return false; - } - - if ($token === '?') { - $position = count($paramMap) + 1; - $param = ':param' . $position; - $fragments[] = substr($statement, $fragmentOffset, $tokenOffset - $fragmentOffset); - $fragments[] = $param; - $paramMap[$position] = $param; - $tokenOffset += 1; - $fragmentOffset = $tokenOffset; - - return true; - } + public function acceptPositionalParameter(string $sql): void + { + $position = count($this->parameterMap) + 1; + $param = ':param' . $position; - $currentLiteralDelimiter = $token; - ++$tokenOffset; + $this->parameterMap[$position] = $param; - return true; + $this->buffer[] = $param; } - /** - * Finds closing quote - * - * @param string $statement The SQL statement to parse - * @param int $tokenOffset The offset to start searching from - * @param string $currentLiteralDelimiter The delimiter of the current string literal - * - * @return bool Whether the token was found - */ - private function findClosingQuote( - string $statement, - int &$tokenOffset, - string &$currentLiteralDelimiter - ): bool { - $token = $this->findToken( - $statement, - $tokenOffset, - '/' . preg_quote($currentLiteralDelimiter, '/') . '/' - ); - - if ($token === null) { - return false; - } - - $currentLiteralDelimiter = null; - ++$tokenOffset; + public function acceptNamedParameter(string $sql): void + { + $this->buffer[] = $sql; + } - return true; + public function getSQL(): string + { + return implode('', $this->buffer); } /** - * Finds the token described by regex starting from the given offset. Updates the offset with the position - * where the token was found. - * - * @param string $statement The SQL statement to parse - * @param int $offset The offset to start searching from - * @param string $regex The regex containing token pattern - * - * @return string|null Token or NULL if not found + * @return array */ - private function findToken(string $statement, int &$offset, string $regex): ?string + public function getParameterMap(): array { - if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, $offset) === 1) { - $offset = $matches[0][1]; - - return $matches[0][0]; - } - - return null; + return $this->parameterMap; } } diff --git a/src/Driver/OCI8/Statement.php b/src/Driver/OCI8/Statement.php index 5257eb5453e..a1621c7ed1a 100644 --- a/src/Driver/OCI8/Statement.php +++ b/src/Driver/OCI8/Statement.php @@ -8,6 +8,7 @@ use Doctrine\DBAL\Driver\Result as ResultInterface; use Doctrine\DBAL\Driver\Statement as StatementInterface; use Doctrine\DBAL\ParameterType; +use Doctrine\DBAL\SQL\Parser; use function assert; use function is_int; @@ -60,14 +61,17 @@ final class Statement implements StatementInterface */ public function __construct($dbh, $query, ExecutionMode $executionMode) { - [$query, $paramMap] = (new ConvertPositionalToNamedPlaceholders())($query); + $parser = new Parser(false); + $visitor = new ConvertPositionalToNamedPlaceholders(); - $stmt = oci_parse($dbh, $query); + $parser->parse($query, $visitor); + + $stmt = oci_parse($dbh, $visitor->getSQL()); assert(is_resource($stmt)); $this->_sth = $stmt; $this->_dbh = $dbh; - $this->_paramMap = $paramMap; + $this->_paramMap = $visitor->getParameterMap(); $this->executionMode = $executionMode; } diff --git a/src/Exception/ParserException.php b/src/Exception/ParserException.php new file mode 100644 index 00000000000..dc6d54a712d --- /dev/null +++ b/src/Exception/ParserException.php @@ -0,0 +1,17 @@ +getMessage(), 0, $e); + } +} diff --git a/src/ExpandArrayParameters.php b/src/ExpandArrayParameters.php new file mode 100644 index 00000000000..33ff8b73690 --- /dev/null +++ b/src/ExpandArrayParameters.php @@ -0,0 +1,150 @@ +|array */ + private $originalValues; + + /** @var array|array */ + private $originalTypes; + + /** @var int */ + private $originalParameterIndex = 0; + + /** @var list */ + private $convertedSQL = []; + + /** @var list */ + private $convertedValues = []; + + /** @var array */ + private $convertedTypes = []; + + /** + * @param array|array $values + * @param array|array $types + */ + public function __construct(array $values, array $types) + { + $this->originalValues = $values; + $this->originalTypes = $types; + } + + public function acceptPositionalParameter(string $sql): void + { + $index = $this->originalParameterIndex; + + if (! array_key_exists($index, $this->originalValues)) { + throw MissingPositionalParameter::new($index); + } + + $this->acceptParameter($index, $this->originalValues[$index]); + + $this->originalParameterIndex++; + } + + public function acceptNamedParameter(string $sql): void + { + $name = substr($sql, 1); + + if (! array_key_exists($name, $this->originalValues)) { + throw MissingNamedParameter::new($name); + } + + $this->acceptParameter($name, $this->originalValues[$name]); + } + + public function acceptOther(string $sql): void + { + $this->convertedSQL[] = $sql; + } + + public function getSQL(): string + { + return implode('', $this->convertedSQL); + } + + /** + * @return list + */ + public function getParameters(): array + { + return $this->convertedValues; + } + + /** + * @param int|string $key + * @param mixed $value + */ + private function acceptParameter($key, $value): void + { + if (isset($this->originalTypes[$key])) { + $type = $this->originalTypes[$key]; + + if ($type === Connection::PARAM_INT_ARRAY || $type === Connection::PARAM_STR_ARRAY) { + if (count($value) === 0) { + $this->appendSQL('NULL'); + } else { + $this->appendTypedParameters($value, $type - Connection::ARRAY_PARAM_OFFSET); + } + } else { + $this->appendTypedParameters([$value], $type); + } + } else { + $this->appendUntypedParameter($value); + } + } + + /** + * @return array + */ + public function getTypes(): array + { + return $this->convertedTypes; + } + + private function appendSQL(string $sql): void + { + $this->convertedSQL[] = $sql; + } + + /** + * @param list $values + * @param Type|int|string|null $type + */ + private function appendTypedParameters(array $values, $type): void + { + $this->convertedSQL[] = implode(', ', array_fill(0, count($values), '?')); + + $index = count($this->convertedValues); + + foreach ($values as $value) { + $this->convertedValues[] = $value; + $this->convertedTypes[$index] = $type; + + $index++; + } + } + + /** + * @param mixed $value + */ + private function appendUntypedParameter($value): void + { + $this->convertedSQL[] = '?'; + $this->convertedValues[] = $value; + } +} diff --git a/src/Platforms/AbstractPlatform.php b/src/Platforms/AbstractPlatform.php index b0dcef25521..6ef2831958e 100644 --- a/src/Platforms/AbstractPlatform.php +++ b/src/Platforms/AbstractPlatform.php @@ -24,6 +24,7 @@ use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\TableDiff; use Doctrine\DBAL\Schema\UniqueConstraint; +use Doctrine\DBAL\SQL\Parser; use Doctrine\DBAL\TransactionIsolationLevel; use Doctrine\DBAL\Types; use Doctrine\DBAL\Types\Type; @@ -3543,6 +3544,14 @@ final public function escapeStringForLike(string $inputString, string $escapeCha ); } + /** + * @internal + */ + public function createSQLParser(): Parser + { + return new Parser(false); + } + protected function getLikeWildcardCharacters(): string { return '%_'; diff --git a/src/Platforms/MySQL57Platform.php b/src/Platforms/MySQL57Platform.php index 669cac6e718..a3ec50441e4 100644 --- a/src/Platforms/MySQL57Platform.php +++ b/src/Platforms/MySQL57Platform.php @@ -4,6 +4,7 @@ use Doctrine\DBAL\Schema\Index; use Doctrine\DBAL\Schema\TableDiff; +use Doctrine\DBAL\SQL\Parser; use Doctrine\DBAL\Types\Types; /** @@ -27,6 +28,11 @@ public function getJsonTypeDeclarationSQL(array $column) return 'JSON'; } + public function createSQLParser(): Parser + { + return new Parser(true); + } + /** * {@inheritdoc} */ diff --git a/src/SQL/Parser.php b/src/SQL/Parser.php new file mode 100644 index 00000000000..dd742b8c2c6 --- /dev/null +++ b/src/SQL/Parser.php @@ -0,0 +1,134 @@ +getMySQLStringLiteralPattern("'"), + $this->getMySQLStringLiteralPattern('"'), + ]; + } else { + $patterns = [ + $this->getAnsiSQLStringLiteralPattern("'"), + $this->getAnsiSQLStringLiteralPattern('"'), + ]; + } + + $patterns = array_merge($patterns, [ + self::BACKTICK_IDENTIFIER, + self::BRACKET_IDENTIFIER, + self::MULTICHAR, + self::ONE_LINE_COMMENT, + self::MULTI_LINE_COMMENT, + self::OTHER, + ]); + + $this->sqlPattern = sprintf('(%s)+', implode('|', $patterns)); + } + + /** + * Parses the given SQL statement + * + * @throws Exception + */ + public function parse(string $sql, Visitor $visitor): void + { + /** @var array $patterns */ + $patterns = [ + self::NAMED_PARAMETER => static function (string $sql) use ($visitor): void { + $visitor->acceptNamedParameter($sql); + }, + self::POSITIONAL_PARAMETER => static function (string $sql) use ($visitor): void { + $visitor->acceptPositionalParameter($sql); + }, + $this->sqlPattern => static function (string $sql) use ($visitor): void { + $visitor->acceptOther($sql); + }, + self::SPECIAL => static function (string $sql) use ($visitor): void { + $visitor->acceptOther($sql); + }, + ]; + + $offset = 0; + + while (($handler = current($patterns)) !== false) { + $match = $this->match($sql, $offset, key($patterns)); + + if ($match !== null) { + $handler($match); + reset($patterns); + + $offset += strlen($match); + } else { + next($patterns); + } + } + + assert($offset === strlen($sql)); + } + + private function getMySQLStringLiteralPattern(string $delimiter): string + { + return $delimiter . '((\\\\' . self::ANY . ')|(?![' . $delimiter . '\\\\])' . self::ANY . ')*' . $delimiter; + } + + private function getAnsiSQLStringLiteralPattern(string $delimiter): string + { + return $delimiter . '[^' . $delimiter . ']*' . $delimiter; + } + + /** + * If the part of the string from the given offset matches the given pattern, returns the matching substring + * and updates the offset with the position to resume parsing from. Otherwise, returns NULL. + * + * @param string $sql The SQL statement to parse + * @param int $offset The offset to match from + * @param string $pattern The pattern + */ + private function match(string $sql, int $offset, string $pattern): ?string + { + if (preg_match('~\G' . $pattern . '~', $sql, $matches, 0, $offset) === 1) { + return $matches[0]; + } + + return null; + } +} diff --git a/src/SQL/Parser/Exception.php b/src/SQL/Parser/Exception.php new file mode 100644 index 00000000000..442adbb3dd6 --- /dev/null +++ b/src/SQL/Parser/Exception.php @@ -0,0 +1,12 @@ + - */ - private static function getPositionalPlaceholderPositions(string $statement): array - { - return self::collectPlaceholders( - $statement, - '?', - self::POSITIONAL_TOKEN, - static function (string $_, int $placeholderPosition, int $fragmentPosition, array &$carry): void { - $carry[] = $placeholderPosition + $fragmentPosition; - } - ); - } - - /** - * Returns a map of placeholder positions to their parameter names. - * - * @return array - */ - private static function getNamedPlaceholderPositions(string $statement): array - { - return self::collectPlaceholders( - $statement, - ':', - self::NAMED_TOKEN, - static function ( - string $placeholder, - int $placeholderPosition, - int $fragmentPosition, - array &$carry - ): void { - $carry[$placeholderPosition + $fragmentPosition] = substr($placeholder, 1); - } - ); - } - - /** - * @return mixed[] - */ - private static function collectPlaceholders( - string $statement, - string $match, - string $token, - callable $collector - ): array { - if (strpos($statement, $match) === false) { - return []; - } - - $carry = []; - - foreach (self::getUnquotedStatementFragments($statement) as $fragment) { - preg_match_all('/' . $token . '/', $fragment[0], $matches, PREG_OFFSET_CAPTURE); - foreach ($matches[0] as $placeholder) { - $collector($placeholder[0], $placeholder[1], $fragment[1], $carry); - } - } - - return $carry; - } - - /** - * For a positional query this method can rewrite the sql statement with regard to array parameters. - * - * @param string $query SQL query - * @param mixed[] $params Query parameters - * @param array|array $types Parameter types - * - * @return mixed[] - * - * @throws SQLParserUtilsException - */ - public static function expandListParameters($query, $params, $types) - { - $isPositional = is_int(key($params)); - $arrayPositions = []; - $bindIndex = -1; - - if ($isPositional) { - // make sure that $types has the same keys as $params - // to allow omitting parameters with unspecified types - $types += array_fill_keys(array_keys($params), null); - - ksort($params); - ksort($types); - } - - foreach ($types as $name => $type) { - ++$bindIndex; - - if ($type !== Connection::PARAM_INT_ARRAY && $type !== Connection::PARAM_STR_ARRAY) { - continue; - } - - if ($isPositional) { - $name = $bindIndex; - } - - $arrayPositions[$name] = false; - } - - if ($isPositional && count($arrayPositions) === 0) { - return [$query, $params, $types]; - } - - if ($isPositional) { - $paramOffset = 0; - $queryOffset = 0; - $params = array_values($params); - $types = array_values($types); - - $paramPos = self::getPositionalPlaceholderPositions($query); - - foreach ($paramPos as $needle => $needlePos) { - if (! isset($arrayPositions[$needle])) { - continue; - } - - $needle += $paramOffset; - $needlePos += $queryOffset; - $count = count($params[$needle]); - - $params = array_merge( - array_slice($params, 0, $needle), - $params[$needle], - array_slice($params, $needle + 1) - ); - - $types = array_merge( - array_slice($types, 0, $needle), - $count > 0 ? - // array needles are at {@link \Doctrine\DBAL\ParameterType} constants - // + {@link \Doctrine\DBAL\Connection::ARRAY_PARAM_OFFSET} - array_fill(0, $count, $types[$needle] - Connection::ARRAY_PARAM_OFFSET) : - [], - array_slice($types, $needle + 1) - ); - - $expandStr = $count > 0 ? implode(', ', array_fill(0, $count, '?')) : 'NULL'; - $query = substr($query, 0, $needlePos) . $expandStr . substr($query, $needlePos + 1); - - $paramOffset += $count - 1; // Grows larger by number of parameters minus the replaced needle. - $queryOffset += strlen($expandStr) - 1; - } - - return [$query, $params, $types]; - } - - $queryOffset = 0; - $typesOrd = []; - $paramsOrd = []; - - $paramPos = self::getNamedPlaceholderPositions($query); - - foreach ($paramPos as $pos => $paramName) { - $paramLen = strlen($paramName) + 1; - $value = static::extractParam($paramName, $params, true); - - if (! isset($arrayPositions[$paramName]) && ! isset($arrayPositions[':' . $paramName])) { - $pos += $queryOffset; - $queryOffset -= $paramLen - 1; - $paramsOrd[] = $value; - $typesOrd[] = static::extractParam($paramName, $types, false, ParameterType::STRING); - $query = substr($query, 0, $pos) . '?' . substr($query, $pos + $paramLen); - - continue; - } - - $count = count($value); - $expandStr = $count > 0 ? implode(', ', array_fill(0, $count, '?')) : 'NULL'; - - foreach ($value as $val) { - $paramsOrd[] = $val; - $typesOrd[] = static::extractParam($paramName, $types, false) - Connection::ARRAY_PARAM_OFFSET; - } - - $pos += $queryOffset; - $queryOffset += strlen($expandStr) - $paramLen; - $query = substr($query, 0, $pos) . $expandStr . substr($query, $pos + $paramLen); - } - - return [$query, $paramsOrd, $typesOrd]; - } - - /** - * Slice the SQL statement around pairs of quotes and - * return string fragments of SQL outside of quoted literals. - * Each fragment is captured as a 2-element array: - * - * 0 => matched fragment string, - * 1 => offset of fragment in $statement - * - * @param string $statement - * - * @return mixed[][] - */ - private static function getUnquotedStatementFragments($statement) - { - $literal = self::ESCAPED_SINGLE_QUOTED_TEXT . '|' . - self::ESCAPED_DOUBLE_QUOTED_TEXT . '|' . - self::ESCAPED_BACKTICK_QUOTED_TEXT . '|' . - self::ESCAPED_BRACKET_QUOTED_TEXT; - $expression = sprintf('/((.+(?i:ARRAY)\\[.+\\])|([^\'"`\\[]+))(?:%s)?/s', $literal); - - preg_match_all($expression, $statement, $fragments, PREG_OFFSET_CAPTURE); - - return $fragments[1]; - } - - /** - * @param string $paramName The name of the parameter (without a colon in front) - * @param mixed $paramsOrTypes A hash of parameters or types - * @param bool $isParam - * @param mixed $defaultValue An optional default value. If omitted, an exception is thrown - * - * @return mixed - * - * @throws SQLParserUtilsException - */ - private static function extractParam($paramName, $paramsOrTypes, $isParam, $defaultValue = null) - { - if (array_key_exists($paramName, $paramsOrTypes)) { - return $paramsOrTypes[$paramName]; - } - - if ($defaultValue !== null) { - return $defaultValue; - } - - if ($isParam) { - throw SQLParserUtilsException::missingParam($paramName); - } - - throw SQLParserUtilsException::missingType($paramName); - } -} diff --git a/src/SQLParserUtilsException.php b/src/SQLParserUtilsException.php deleted file mode 100644 index 297b0761b8d..00000000000 --- a/src/SQLParserUtilsException.php +++ /dev/null @@ -1,37 +0,0 @@ - 42, 0 => 30]], // explicit keys - ]; - } - - /** - * @return mixed[][] - */ - public function dataGetPlaceholderNamedPositions(): iterable - { - return [ - // none - ['SELECT * FROM Foo', []], - - // named - ['SELECT :foo FROM :bar', [7 => 'foo', 17 => 'bar']], - ['SELECT * FROM Foo WHERE bar IN (:name1, :name2)', [32 => 'name1', 40 => 'name2']], - ['SELECT ":foo" FROM Foo WHERE bar IN (:name1, :name2)', [37 => 'name1', 45 => 'name2']], - ["SELECT ':foo' FROM Foo WHERE bar IN (:name1, :name2)", [37 => 'name1', 45 => 'name2']], - ['SELECT :foo_id', [7 => 'foo_id']], // Ticket DBAL-231 - ['SELECT @rank := 1', []], // Ticket DBAL-398 - ['SELECT @rank := 1 AS rank, :foo AS foo FROM :bar', [27 => 'foo', 44 => 'bar']], // Ticket DBAL-398 - // Ticket GH-113 - [ - 'SELECT * FROM Foo WHERE bar > :start_date AND baz > :start_date', - [ - 30 => 'start_date', - 52 => 'start_date', - ], - ], - - // Ticket GH-259 - [ - 'SELECT foo::date as date FROM Foo WHERE bar > :start_date AND baz > :start_date', - [ - 46 => 'start_date', - 68 => 'start_date', - ], - ], - - // Ticket DBAL-552 - [ - 'SELECT `d.ns:col_name` FROM my_table d WHERE `d.date` >= :param1', - [57 => 'param1'], - ], - - // Ticket DBAL-552 - ['SELECT [d.ns:col_name] FROM my_table d WHERE [d.date] >= :param1', [57 => 'param1']], - ['SELECT * FROM foo WHERE jsonb_exists_any(foo.bar, ARRAY[:foo])', [56 => 'foo']], // Ticket GH-2295 - ['SELECT * FROM foo WHERE jsonb_exists_any(foo.bar, array[:foo])', [56 => 'foo']],[ - 'SELECT table.column1, ARRAY[\'3\'] FROM schema.table table WHERE table.f1 = :foo AND ARRAY[\'3\']', - [74 => 'foo'], - ], - [ - 'SELECT table.column1, ARRAY[\'3\']::integer[] FROM schema.table table' - . ' WHERE table.f1 = :foo AND ARRAY[\'3\']::integer[]', - [85 => 'foo'], - ], - [ - 'SELECT table.column1, ARRAY[:foo] FROM schema.table table WHERE table.f1 = :bar AND ARRAY[\'3\']', - [ - 28 => 'foo', - 75 => 'bar', - ], - ], - [ - 'SELECT table.column1, ARRAY[:foo]::integer[] FROM schema.table table' - . ' WHERE table.f1 = :bar AND ARRAY[\'3\']::integer[]', - [ - 28 => 'foo', - 86 => 'bar', - ], - ], - [ - <<<'SQLDATA' -SELECT * FROM foo WHERE -bar = ':not_a_param1 ''":not_a_param2"''' -OR bar=:a_param1 -OR bar=:a_param2||':not_a_param3' -OR bar=':not_a_param4 '':not_a_param5'' :not_a_param6' -OR bar='' -OR bar=:a_param3 -SQLDATA -, - [ - 74 => 'a_param1', - 91 => 'a_param2', - 190 => 'a_param3', - ], - ], - [ - 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' - . " WHERE (data.description LIKE :condition_0 ESCAPE '\\\\')" - . " AND (data.description LIKE :condition_1 ESCAPE '\\\\') ORDER BY id ASC", - [ - 121 => 'condition_0', - 174 => 'condition_1', - ], - ], - [ - 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' - . ' WHERE (data.description LIKE :condition_0 ESCAPE "\\\\")' - . ' AND (data.description LIKE :condition_1 ESCAPE "\\\\") ORDER BY id ASC', - [ - 121 => 'condition_0', - 174 => 'condition_1', - ], - ], - [ - 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' - . ' WHERE (data.description LIKE :condition_0 ESCAPE "\\\\")' - . ' AND (data.description LIKE :condition_1 ESCAPE \'\\\\\') ORDER BY id ASC', - [ - 121 => 'condition_0', - 174 => 'condition_1', - ], - ], - [ - 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' - . ' WHERE (data.description LIKE :condition_0 ESCAPE `\\\\`)' - . ' AND (data.description LIKE :condition_1 ESCAPE `\\\\`) ORDER BY id ASC', - [ - 121 => 'condition_0', - 174 => 'condition_1', - ], - ], - [ - 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' - . ' WHERE (data.description LIKE :condition_0 ESCAPE \'\\\\\')' - . ' AND (data.description LIKE :condition_1 ESCAPE `\\\\`) ORDER BY id ASC', - [ - 121 => 'condition_0', - 174 => 'condition_1', - ], - ], - [ - "SELECT * FROM Foo WHERE (foo.bar LIKE :condition_0 ESCAPE '\')" - . " AND (foo.baz = :condition_1) AND (foo.bak LIKE :condition_2 ESCAPE '\')", - [ - 38 => 'condition_0', - 78 => 'condition_1', - 110 => 'condition_2', - ], - ], - ]; - } - - /** - * @param int[] $expectedParamPos - * - * @dataProvider dataGetPlaceholderPositionalPositions - */ - public function testGetPositionalPlaceholderPositions(string $query, array $expectedParamPos): void - { - $reflection = new ReflectionMethod(SQLParserUtils::class, 'getPositionalPlaceholderPositions'); - $reflection->setAccessible(true); - - self::assertEquals($expectedParamPos, $reflection->invoke(null, $query)); - } - - /** - * @param string[] $expectedParamPos - * - * @dataProvider dataGetPlaceholderNamedPositions - */ - public function testGetNamedPlaceholderPositions(string $query, array $expectedParamPos): void - { - $reflection = new ReflectionMethod(SQLParserUtils::class, 'getNamedPlaceholderPositions'); - $reflection->setAccessible(true); - - self::assertEquals($expectedParamPos, $reflection->invoke(null, $query)); - } - /** * @return mixed[][] */ @@ -301,7 +93,7 @@ public static function dataExpandListParameters(): iterable [2 => ParameterType::STRING, 1 => ParameterType::STRING], 'SELECT * FROM Foo WHERE foo = ? AND bar = ? AND baz = ?', [1 => 'bar', 0 => 1, 2 => 'baz'], - [1 => ParameterType::STRING, 2 => ParameterType::STRING, 0 => null], + [1 => ParameterType::STRING, 2 => ParameterType::STRING], ], 'Positional: explicit keys for array params and array types' => [ 'SELECT * FROM Foo WHERE foo IN (?) AND bar IN (?) AND baz = ?', @@ -318,27 +110,6 @@ public static function dataExpandListParameters(): iterable ParameterType::BOOLEAN, ], ], - 'Positional starts from 1: One non-list before and one after list-needle' => [ - 'SELECT * FROM Foo WHERE foo = ? AND bar IN (?) AND baz = ? AND foo IN (?)', - [1 => 1, 2 => [1, 2, 3], 3 => 4, 4 => [5, 6]], - [ - 1 => ParameterType::INTEGER, - 2 => Connection::PARAM_INT_ARRAY, - 3 => ParameterType::INTEGER, - 4 => Connection::PARAM_INT_ARRAY, - ], - 'SELECT * FROM Foo WHERE foo = ? AND bar IN (?, ?, ?) AND baz = ? AND foo IN (?, ?)', - [1, 1, 2, 3, 4, 5, 6], - [ - ParameterType::INTEGER, - ParameterType::INTEGER, - ParameterType::INTEGER, - ParameterType::INTEGER, - ParameterType::INTEGER, - ParameterType::INTEGER, - ParameterType::INTEGER, - ], - ], 'Named: Very simple with param int' => [ 'SELECT * FROM Foo WHERE foo = :foo', ['foo' => 1], @@ -464,7 +235,11 @@ public static function dataExpandListParameters(): iterable ['foo' => Connection::PARAM_INT_ARRAY, 'baz' => 'string'], 'SELECT * FROM Foo WHERE foo IN (?, ?) OR bar = ? OR baz = ?', [1, 2, 'bar', 'baz'], - [ParameterType::INTEGER, ParameterType::INTEGER, ParameterType::STRING, 'string'], + [ + 0 => ParameterType::INTEGER, + 1 => ParameterType::INTEGER, + 3 => 'string', + ], ], [ 'SELECT * FROM Foo WHERE foo IN (:foo) OR bar = :bar', @@ -472,7 +247,7 @@ public static function dataExpandListParameters(): iterable ['foo' => Connection::PARAM_INT_ARRAY], 'SELECT * FROM Foo WHERE foo IN (?, ?) OR bar = ?', [1, 2, 'bar'], - [ParameterType::INTEGER, ParameterType::INTEGER, ParameterType::STRING], + [ParameterType::INTEGER, ParameterType::INTEGER], ], 'Named parameters and partially implicit types' => [ 'SELECT * FROM Foo WHERE foo = :foo OR bar = :bar', @@ -480,7 +255,7 @@ public static function dataExpandListParameters(): iterable ['foo' => ParameterType::INTEGER], 'SELECT * FROM Foo WHERE foo = ? OR bar = ?', ['foo', 'bar'], - [ParameterType::INTEGER, ParameterType::STRING], + [ParameterType::INTEGER], ], 'Named parameters and explicit types' => [ 'SELECT * FROM Foo WHERE foo = :foo OR bar = :bar', @@ -520,16 +295,16 @@ public static function dataExpandListParameters(): iterable [1 => Connection::PARAM_STR_ARRAY], 'SELECT NULL FROM dummy WHERE ? IN (?, ?)', ['foo', 'bar', 'baz'], - [null, ParameterType::STRING, ParameterType::STRING], + [1 => ParameterType::STRING, ParameterType::STRING], ], ]; } /** - * @param mixed[] $params - * @param mixed[] $types - * @param mixed[] $expectedParams - * @param mixed[] $expectedTypes + * @param array|array $params + * @param array|array $types + * @param list $expectedParams + * @param array $expectedTypes * * @dataProvider dataExpandListParameters */ @@ -541,7 +316,7 @@ public function testExpandListParameters( array $expectedParams, array $expectedTypes ): void { - [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types); + [$query, $params, $types] = $this->expandArrayParameters($query, $params, $types); self::assertEquals($expectedQuery, $query, 'Query was not rewritten correctly.'); self::assertEquals($expectedParams, $params, 'Params dont match'); @@ -564,16 +339,6 @@ public static function dataQueryWithMissingParameters(): iterable [], [], ], - [ - 'SELECT * FROM foo WHERE bar = :param', - [], - ['param' => Connection::PARAM_INT_ARRAY], - ], - [ - 'SELECT * FROM foo WHERE bar = :param', - [], - [':param' => Connection::PARAM_INT_ARRAY], - ], [ 'SELECT * FROM foo WHERE bar = :param', [], @@ -588,16 +353,37 @@ public static function dataQueryWithMissingParameters(): iterable } /** - * @param mixed[] $params - * @param mixed[] $types + * @param array|array $params + * @param array|array $types * * @dataProvider dataQueryWithMissingParameters */ public function testExceptionIsThrownForMissingParam(string $query, array $params, array $types = []): void { - $this->expectException(SQLParserUtilsException::class); - $this->expectExceptionMessage('Value for :param not found in params array. Params array key should be "param"'); + $this->expectException(MissingNamedParameter::class); - SQLParserUtils::expandListParameters($query, $params, $types); + $this->expandArrayParameters($query, $params, $types); + } + + /** + * @param array|array $params + * @param array|array $types + * + * @return array{0: string, 1: list, 2: array} + * + * @throws Exception + */ + private function expandArrayParameters(string $sql, array $params, array $types): array + { + $parser = new Parser(true); + $visitor = new ExpandArrayParameters($params, $types); + + $parser->parse($sql, $visitor); + + return [ + $visitor->getSQL(), + $visitor->getParameters(), + $visitor->getTypes(), + ]; } } diff --git a/tests/Driver/OCI8/ConvertPositionalToNamedPlaceholdersTest.php b/tests/Driver/OCI8/ConvertPositionalToNamedPlaceholdersTest.php index 17046373a7e..d3779a6419a 100644 --- a/tests/Driver/OCI8/ConvertPositionalToNamedPlaceholdersTest.php +++ b/tests/Driver/OCI8/ConvertPositionalToNamedPlaceholdersTest.php @@ -5,19 +5,11 @@ namespace Doctrine\Tests\DBAL\Driver\OCI8; use Doctrine\DBAL\Driver\OCI8\ConvertPositionalToNamedPlaceholders; -use Doctrine\DBAL\Driver\OCI8\Exception\NonTerminatedStringLiteral; +use Doctrine\DBAL\SQL\Parser; use PHPUnit\Framework\TestCase; class ConvertPositionalToNamedPlaceholdersTest extends TestCase { - /** @var ConvertPositionalToNamedPlaceholders */ - private $convertPositionalToNamedPlaceholders; - - protected function setUp(): void - { - $this->convertPositionalToNamedPlaceholders = new ConvertPositionalToNamedPlaceholders(); - } - /** * @param mixed[] $expectedOutputParamsMap * @@ -28,10 +20,13 @@ public function testConvertPositionalToNamedParameters( string $expectedOutputSQL, array $expectedOutputParamsMap ): void { - [$statement, $params] = ($this->convertPositionalToNamedPlaceholders)($inputSQL); + $parser = new Parser(false); + $visitor = new ConvertPositionalToNamedPlaceholders(); + + $parser->parse($inputSQL, $visitor); - self::assertEquals($expectedOutputSQL, $statement); - self::assertEquals($expectedOutputParamsMap, $params); + self::assertEquals($expectedOutputSQL, $visitor->getSQL()); + self::assertEquals($expectedOutputParamsMap, $visitor->getParameterMap()); } /** @@ -92,35 +87,4 @@ public static function positionalToNamedPlaceholdersProvider(): iterable ], ]; } - - /** - * @dataProvider nonTerminatedLiteralProvider - */ - public function testConvertNonTerminatedLiteral(string $sql, string $expectedExceptionMessageRegExp): void - { - $this->expectException(NonTerminatedStringLiteral::class); - $this->expectExceptionMessageMatches($expectedExceptionMessageRegExp); - ($this->convertPositionalToNamedPlaceholders)($sql); - } - - /** - * @return array> - */ - public static function nonTerminatedLiteralProvider(): iterable - { - return [ - 'no-matching-quote' => [ - "SELECT 'literal FROM DUAL", - '/offset 7./', - ], - 'no-matching-double-quote' => [ - 'SELECT 1 "COL1 FROM DUAL', - '/offset 9./', - ], - 'incorrect-escaping-syntax' => [ - "SELECT 'quoted \\'string' FROM DUAL", - '/offset 23./', - ], - ]; - } } diff --git a/tests/Functional/DataAccessTest.php b/tests/Functional/DataAccessTest.php index db109d56513..4e942b792ce 100644 --- a/tests/Functional/DataAccessTest.php +++ b/tests/Functional/DataAccessTest.php @@ -271,8 +271,8 @@ public function testExecuteQueryBindDateTimeType(): void { $value = $this->connection->fetchOne( 'SELECT count(*) AS c FROM fetch_table WHERE test_datetime = ?', - [1 => new DateTime('2010-01-01 10:10:10')], - [1 => Types::DATETIME_MUTABLE] + [new DateTime('2010-01-01 10:10:10')], + [Types::DATETIME_MUTABLE] ); self::assertEquals(1, $value); @@ -284,20 +284,20 @@ public function testExecuteStatementBindDateTimeType(): void $sql = 'INSERT INTO fetch_table (test_int, test_string, test_datetime) VALUES (?, ?, ?)'; $affectedRows = $this->connection->executeStatement($sql, [ - 1 => 50, - 2 => 'foo', - 3 => $datetime, + 50, + 'foo', + $datetime, ], [ - 1 => ParameterType::INTEGER, - 2 => ParameterType::STRING, - 3 => Types::DATETIME_MUTABLE, + ParameterType::INTEGER, + ParameterType::STRING, + Types::DATETIME_MUTABLE, ]); self::assertEquals(1, $affectedRows); self::assertEquals(1, $this->connection->executeQuery( 'SELECT count(*) AS c FROM fetch_table WHERE test_datetime = ?', - [1 => $datetime], - [1 => Types::DATETIME_MUTABLE] + [$datetime], + [Types::DATETIME_MUTABLE] )->fetchOne()); } diff --git a/tests/SQL/ParserTest.php b/tests/SQL/ParserTest.php new file mode 100644 index 00000000000..74903794324 --- /dev/null +++ b/tests/SQL/ParserTest.php @@ -0,0 +1,343 @@ + */ + private $result = []; + + /** + * @dataProvider parametersProvider + */ + public function testParameters(string $sql, string $expected): void + { + $parser = new Parser(false); + $parser->parse($sql, $this); + + $this->assertParsed($expected); + } + + /** + * @return iterable> + */ + public static function parametersProvider(): iterable + { + yield [ + 'SELECT ?', + 'SELECT {?}', + ]; + + yield [ + 'SELECT * FROM Foo WHERE bar IN (?, ?, ?)', + 'SELECT * FROM Foo WHERE bar IN ({?}, {?}, {?})', + ]; + + yield [ + 'SELECT ? FROM ?', + 'SELECT {?} FROM {?}', + ]; + + yield [ + 'SELECT "?" FROM foo WHERE bar = ?', + 'SELECT "?" FROM foo WHERE bar = {?}', + ]; + + yield [ + "SELECT '?' FROM foo WHERE bar = ?", + "SELECT '?' FROM foo WHERE bar = {?}", + ]; + + yield [ + 'SELECT `?` FROM foo WHERE bar = ?', + 'SELECT `?` FROM foo WHERE bar = {?}', + ]; + + yield [ + 'SELECT [?] FROM foo WHERE bar = ?', + 'SELECT [?] FROM foo WHERE bar = {?}', + ]; + + yield [ + 'SELECT * FROM foo WHERE jsonb_exists_any(foo.bar, ARRAY[?])', + 'SELECT * FROM foo WHERE jsonb_exists_any(foo.bar, ARRAY[{?}])', + ]; + + yield [ + "SELECT 'Doctrine\DBAL?' FROM foo WHERE bar = ?", + "SELECT 'Doctrine\DBAL?' FROM foo WHERE bar = {?}", + ]; + + yield [ + 'SELECT "Doctrine\DBAL?" FROM foo WHERE bar = ?', + 'SELECT "Doctrine\DBAL?" FROM foo WHERE bar = {?}', + ]; + + yield [ + 'SELECT `Doctrine\DBAL?` FROM foo WHERE bar = ?', + 'SELECT `Doctrine\DBAL?` FROM foo WHERE bar = {?}', + ]; + + yield [ + 'SELECT [Doctrine\DBAL?] FROM foo WHERE bar = ?', + 'SELECT [Doctrine\DBAL?] FROM foo WHERE bar = {?}', + ]; + + yield [ + <<<'SQL' +SELECT * FROM FOO WHERE bar = 'it''s a trap? \' OR bar = ? +AND baz = """quote"" me on it? \" OR baz = ? +SQL +, + <<<'SQL' +SELECT * FROM FOO WHERE bar = 'it''s a trap? \' OR bar = {?} +AND baz = """quote"" me on it? \" OR baz = {?} +SQL +, + ]; + + yield [ + 'SELECT :foo FROM :bar', + 'SELECT {:foo} FROM {:bar}', + ]; + + yield [ + 'SELECT * FROM Foo WHERE bar IN (:name1, :name2)', + 'SELECT * FROM Foo WHERE bar IN ({:name1}, {:name2})', + ]; + + yield [ + 'SELECT ":foo" FROM Foo WHERE bar IN (:name1, :name2)', + 'SELECT ":foo" FROM Foo WHERE bar IN ({:name1}, {:name2})', + ]; + + yield [ + "SELECT ':foo' FROM Foo WHERE bar IN (:name1, :name2)", + "SELECT ':foo' FROM Foo WHERE bar IN ({:name1}, {:name2})", + ]; + + yield [ + 'SELECT :foo_id', + 'SELECT {:foo_id}', + ]; + + yield [ + 'SELECT @rank := 1 AS rank, :foo AS foo FROM :bar', + 'SELECT @rank := 1 AS rank, {:foo} AS foo FROM {:bar}', + ]; + + yield [ + 'SELECT * FROM Foo WHERE bar > :start_date AND baz > :start_date', + 'SELECT * FROM Foo WHERE bar > {:start_date} AND baz > {:start_date}', + ]; + + yield [ + 'SELECT foo::date as date FROM Foo WHERE bar > :start_date AND baz > :start_date', + 'SELECT foo::date as date FROM Foo WHERE bar > {:start_date} AND baz > {:start_date}', + ]; + + yield [ + 'SELECT `d.ns:col_name` FROM my_table d WHERE `d.date` >= :param1', + 'SELECT `d.ns:col_name` FROM my_table d WHERE `d.date` >= {:param1}', + ]; + + yield [ + 'SELECT [d.ns:col_name] FROM my_table d WHERE [d.date] >= :param1', + 'SELECT [d.ns:col_name] FROM my_table d WHERE [d.date] >= {:param1}', + ]; + + yield [ + 'SELECT * FROM foo WHERE jsonb_exists_any(foo.bar, ARRAY[:foo])', + 'SELECT * FROM foo WHERE jsonb_exists_any(foo.bar, ARRAY[{:foo}])', + ]; + + yield [ + 'SELECT * FROM foo WHERE jsonb_exists_any(foo.bar, array[:foo])', + 'SELECT * FROM foo WHERE jsonb_exists_any(foo.bar, array[{:foo}])', + ]; + + yield [ + "SELECT table.column1, ARRAY['3'] FROM schema.table table WHERE table.f1 = :foo AND ARRAY['3']", + "SELECT table.column1, ARRAY['3'] FROM schema.table table WHERE table.f1 = {:foo} AND ARRAY['3']", + ]; + + yield [ + "SELECT table.column1, ARRAY['3']::integer[] FROM schema.table table" + . " WHERE table.f1 = :foo AND ARRAY['3']::integer[]", + "SELECT table.column1, ARRAY['3']::integer[] FROM schema.table table" + . " WHERE table.f1 = {:foo} AND ARRAY['3']::integer[]", + ]; + + yield [ + "SELECT table.column1, ARRAY[:foo] FROM schema.table table WHERE table.f1 = :bar AND ARRAY['3']", + "SELECT table.column1, ARRAY[{:foo}] FROM schema.table table WHERE table.f1 = {:bar} AND ARRAY['3']", + ]; + + yield [ + 'SELECT table.column1, ARRAY[:foo]::integer[] FROM schema.table table' + . " WHERE table.f1 = :bar AND ARRAY['3']::integer[]", + 'SELECT table.column1, ARRAY[{:foo}]::integer[] FROM schema.table table' + . " WHERE table.f1 = {:bar} AND ARRAY['3']::integer[]", + ]; + + yield [ + <<<'SQL' +SELECT * FROM foo WHERE +bar = ':not_a_param1 ''":not_a_param2"''' +OR bar=:a_param1 +OR bar=:a_param2||':not_a_param3' +OR bar=':not_a_param4 '':not_a_param5'' :not_a_param6' +OR bar='' +OR bar=:a_param3 +SQL +, + <<<'SQL' +SELECT * FROM foo WHERE +bar = ':not_a_param1 ''":not_a_param2"''' +OR bar={:a_param1} +OR bar={:a_param2}||':not_a_param3' +OR bar=':not_a_param4 '':not_a_param5'' :not_a_param6' +OR bar='' +OR bar={:a_param3} +SQL +, + ]; + + yield [ + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . " WHERE (data.description LIKE :condition_0 ESCAPE '\\\\')" + . " AND (data.description LIKE :condition_1 ESCAPE '\\\\') ORDER BY id ASC", + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . " WHERE (data.description LIKE {:condition_0} ESCAPE '\\\\')" + . " AND (data.description LIKE {:condition_1} ESCAPE '\\\\') ORDER BY id ASC", + ]; + + yield [ + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . ' WHERE (data.description LIKE :condition_0 ESCAPE "\\\\")' + . ' AND (data.description LIKE :condition_1 ESCAPE "\\\\") ORDER BY id ASC', + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . ' WHERE (data.description LIKE {:condition_0} ESCAPE "\\\\")' + . ' AND (data.description LIKE {:condition_1} ESCAPE "\\\\") ORDER BY id ASC', + ]; + + yield [ + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . ' WHERE (data.description LIKE :condition_0 ESCAPE "\\\\")' + . ' AND (data.description LIKE :condition_1 ESCAPE \'\\\\\') ORDER BY id ASC', + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . ' WHERE (data.description LIKE {:condition_0} ESCAPE "\\\\")' + . ' AND (data.description LIKE {:condition_1} ESCAPE \'\\\\\') ORDER BY id ASC', + ]; + + yield [ + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . ' WHERE (data.description LIKE :condition_0 ESCAPE `\\\\`)' + . ' AND (data.description LIKE :condition_1 ESCAPE `\\\\`) ORDER BY id ASC', + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . ' WHERE (data.description LIKE {:condition_0} ESCAPE `\\\\`)' + . ' AND (data.description LIKE {:condition_1} ESCAPE `\\\\`) ORDER BY id ASC', + ]; + + yield [ + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . ' WHERE (data.description LIKE :condition_0 ESCAPE \'\\\\\')' + . ' AND (data.description LIKE :condition_1 ESCAPE `\\\\`) ORDER BY id ASC', + 'SELECT data.age AS age, data.id AS id, data.name AS name, data.id AS id FROM test_data data' + . ' WHERE (data.description LIKE {:condition_0} ESCAPE \'\\\\\')' + . ' AND (data.description LIKE {:condition_1} ESCAPE `\\\\`) ORDER BY id ASC', + ]; + + yield [ + "SELECT * FROM Foo WHERE (foo.bar LIKE :condition_0 ESCAPE '\')" + . " AND (foo.baz = :condition_1) AND (foo.bak LIKE :condition_2 ESCAPE '\')", + "SELECT * FROM Foo WHERE (foo.bar LIKE {:condition_0} ESCAPE '\')" + . " AND (foo.baz = {:condition_1}) AND (foo.bak LIKE {:condition_2} ESCAPE '\')", + ]; + } + + /** + * @dataProvider mySQLParametersProvider + */ + public function testMySQLEscaping(string $sql, string $expected): void + { + $parser = new Parser(true); + $parser->parse($sql, $this); + + $this->assertParsed($expected); + } + + /** + * @return iterable> + */ + public static function mySQLParametersProvider(): iterable + { + yield [ + <<<'SQL' +SELECT * FROM FOO WHERE bar = 'it\'s a trap? \\' OR bar = ? +AND baz = "\"quote\" me on it? \\" OR baz = ? +SQL +, + <<<'SQL' +SELECT * FROM FOO WHERE bar = 'it\'s a trap? \\' OR bar = {?} +AND baz = "\"quote\" me on it? \\" OR baz = {?} +SQL +, + ]; + } + + /** + * @dataProvider noParametersProvider + */ + public function testNoParameters(string $sql): void + { + $parser = new Parser(false); + $parser->parse($sql, $this); + + $this->assertParsed($sql); + } + + /** + * @return iterable> + */ + public static function noParametersProvider(): iterable + { + yield ['SELECT * FROM Foo']; + yield ["SELECT '?' FROM foo"]; + yield ['SELECT "?" FROM foo']; + yield ['SELECT `?` FROM foo']; + yield ['SELECT [?] FROM foo']; + yield ["SELECT 'Doctrine\DBAL?' FROM foo"]; + yield ['SELECT "Doctrine\DBAL?" FROM foo']; + yield ['SELECT `Doctrine\DBAL?` FROM foo']; + yield ['SELECT [Doctrine\DBAL?] FROM foo']; + yield ['SELECT @rank := 1']; + } + + public function acceptPositionalParameter(string $sql): void + { + $this->result[] = sprintf('{%s}', $sql); + } + + public function acceptNamedParameter(string $sql): void + { + $this->result[] = sprintf('{%s}', $sql); + } + + public function acceptOther(string $sql): void + { + $this->result[] = $sql; + } + + private function assertParsed(string $expected): void + { + self::assertSame($expected, implode('', $this->result)); + } +}