Skip to content

Commit

Permalink
Fix handling null in SELECT, WHERE and HAVING
Browse files Browse the repository at this point in the history
  • Loading branch information
simPod committed Dec 23, 2020
1 parent 4d4693c commit 3c6b90c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/Sql/ValueFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,14 @@ public function format($value, ?string $paramName = null, ?string $sql = null) :
}

if ($value === null) {
return 'IS NULL';
if (
$paramName !== null && $sql !== null
&& preg_match(sprintf('~(HAVING|WHERE)[\s\S]*?=\s*?:%s~', $paramName), $sql) === 1
) {
return 'IS NULL';
}

return 'NULL';
}

if ($value instanceof DateTimeImmutable) {
Expand All @@ -72,7 +79,7 @@ public function format($value, ?string $paramName = null, ?string $sql = null) :
if (is_array($value)) {
if (
$paramName !== null && $sql !== null
&& preg_match(sprintf('~\s+IN\s+\\(:%s\\)~', $paramName), $sql) === 1
&& preg_match(sprintf('~\s+?IN\s+?\\(:%s\\)~', $paramName), $sql) === 1
) {
return implode(
',',
Expand Down
15 changes: 14 additions & 1 deletion tests/Sql/ValueFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,20 @@ public function providerFormat() : iterable
yield 'float .5' => ['1.5', 1.5];
yield 'string' => ["'ping'", 'ping'];
yield 'string escaped' => ["'ping\\\\n'", 'ping\n'];
yield 'null' => ['IS NULL', null];
yield 'null' => ['NULL', null];
yield 'null with WHERE' => ['IS NULL', null, 'null', 'SELECT 1 FROM table WHERE x = :null'];
yield 'null with multiline WHERE' => [
'IS NULL',
null,
'null',
<<<SQL
SELECT 1 FROM table WHERE
1 = 1
AND x = :null
SQL,
];
yield 'null with HAVING' => ['IS NULL', null, 'null', 'SELECT 1 FROM table HAVING x = :null'];
yield 'null with SELECT' => ['NULL', null, 'SELECT :null'];
yield 'array' => ["['a','b','c']", ['a', 'b', 'c']];
yield 'array in array' => ["[['a']]", [['a']]];
yield 'array with null' => ['[NULL]', [null]];
Expand Down

0 comments on commit 3c6b90c

Please sign in to comment.