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 2e9a159
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/Sql/ValueFormatter.php
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~', $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
5 changes: 4 additions & 1 deletion tests/Sql/ValueFormatterTest.php
Expand Up @@ -37,7 +37,10 @@ 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 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 2e9a159

Please sign in to comment.