Skip to content

Commit

Permalink
Issue #3133798 by Beakerboy, daffie: Semicolon removed from query eve…
Browse files Browse the repository at this point in the history
…n when it is allowed
  • Loading branch information
alexpott committed May 28, 2020
1 parent bef9a90 commit f75f77c
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/Drupal/Core/Database/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,11 @@ public function query($query, array $args = [], $options = []) {
// semicolons should only be needed for special cases like defining a
// function or stored procedure in SQL. Trim any trailing delimiter to
// minimize false positives.
$query = rtrim($query, "; \t\n\r\0\x0B");
$trim_chars = " \t\n\r\0\x0B";
if (empty($options['allow_delimiter_in_query'])) {
$trim_chars .= ';';
}
$query = rtrim($query, $trim_chars);
if (strpos($query, ';') !== FALSE && empty($options['allow_delimiter_in_query'])) {
throw new \InvalidArgumentException('; is not supported in SQL strings. Use only one statement at a time.');
}
Expand Down
55 changes: 55 additions & 0 deletions tests/Drupal/Tests/Core/Database/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Drupal\Tests\Core\Database;

use Drupal\Tests\Core\Database\Stub\StubConnection;
use Drupal\Tests\Core\Database\Stub\StubPDO;
use Drupal\Tests\UnitTestCase;

/**
Expand Down Expand Up @@ -297,4 +298,58 @@ public function testFilterComments($expected, $comment) {
);
}

/**
* Test rtrim() of query strings.
*
* @dataProvider provideQueriesToTrim
*/
public function testQueryTrim($expected, $query, $options) {
$mock_pdo = $this->getMockBuilder(StubPdo::class)
->setMethods(['execute', 'prepare', 'setAttribute'])
->getMock();

// Ensure that PDO::prepare() is called only once, and with the
// correctly trimmed query string.
$mock_pdo->expects($this->once())
->method('prepare')
->with($expected)
->willReturnSelf();
$connection = new StubConnection($mock_pdo, []);
$connection->query($query, [], $options);
}

/**
* Dataprovider for testQueryTrim().
*
* @return array
* Array of arrays with the following elements:
* - Expected trimmed query.
* - Padded query.
* - Query options.
*/
public function provideQueriesToTrim() {
return [
'remove_semicolon' => [
'SELECT * FROM test',
'SELECT * FROM test;',
[],
],
'keep_trailing_semicolon' => [
'SELECT * FROM test;',
'SELECT * FROM test;',
['allow_delimiter_in_query' => TRUE],
],
'remove_semicolon_with_whitespace' => [
'SELECT * FROM test',
'SELECT * FROM test; ',
[],
],
'keep_trailing_semicolon_with_whitespace' => [
'SELECT * FROM test;',
'SELECT * FROM test; ',
['allow_delimiter_in_query' => TRUE],
],
];
}

}

0 comments on commit f75f77c

Please sign in to comment.