adding exception for mixed named and unamed parameters

refacto with that exception
pull/731/head
Laurent (Blerot) 1 day ago
parent 4e471fcf2e
commit 6d05336efb

@ -90,10 +90,14 @@ class SimplePdo extends PdoWrapper
/** /**
* Don't worry about this guy. Converts stuff for IN statements * Don't worry about this guy. Converts stuff for IN statements
* either named or unamed parameters
* *
* Ex: $row = $db->fetchAll("SELECT * FROM table WHERE id = ? AND something IN(?), [ $id, [1,2,3] ]); * Ex: $row = $db->fetchAll("SELECT * FROM table WHERE id = ? AND something IN(?), [ $id, [1,2,3] ]);
* Converts this to "SELECT * FROM table WHERE id = ? AND something IN(?,?,?)" * Converts this to "SELECT * FROM table WHERE id = ? AND something IN(?,?,?)"
* *
* Ex: $row = $db->fetchAll("SELECT * FROM table WHERE id = :id AND something IN(:something), [ 'id' => $id, 'something' => [1,2,3] ]);
* Converts this to "SELECT * FROM table WHERE id = :id AND something IN(:something0 , :something1 , :something2)"
*
* @param string $sql the sql statement * @param string $sql the sql statement
* @param array<int|string,mixed> $params the params for the sql statement * @param array<int|string,mixed> $params the params for the sql statement
* *
@ -101,43 +105,61 @@ class SimplePdo extends PdoWrapper
*/ */
protected function processInStatementSql(string $sql, array $params = []): array protected function processInStatementSql(string $sql, array $params = []): array
{ {
$originalSql_ = $sql; // 1. throw an exception if mixed parameters are found in sql
$params_ = $params; $pattern = '/(:[a-zA-Z][a-zA-Z0-9]*)/i';
$newParams = []; $named_params_nb = preg_match_all($pattern, $sql, $matches_named, PREG_OFFSET_CAPTURE);
// First, find all placeholders with named parameter inside IN pattern $pattern = '/(\?)/i';
$pattern = '/IN\s*\(\s*(:[a-zA-Z][a-zA-Z0-9]*)\s*\)/i'; $unnamed_params_nb = preg_match_all($pattern, $sql, $matches_unnamed, PREG_OFFSET_CAPTURE);
$inPositions = [];
if (preg_match_all($pattern, $originalSql_, $matches, PREG_OFFSET_CAPTURE)) { if (($named_params_nb === false)
foreach ($matches[1] as $k => $match) || ($unnamed_params_nb === false)
$inPositions[$match[0]] = $matches[0][$k]; || (($named_params_nb != 0) && ($unnamed_params_nb != 0)))
{
throw new PDOException(
"processInStatementSql failed: mixed named and unamed parameters found."
);
} }
// and process each param
foreach($inPositions as $param => $match) { // 2. handle named parameters
$param_key = substr($param, 1); if ($named_params_nb > 0)
{
$newSql = $sql;
$newParams = $params;
// Find all placeholders with named parameter inside IN pattern
$pattern = '/IN\s*\(\s*(:[a-zA-Z][a-zA-Z0-9]*)\s*\)/i';
if (preg_match_all($pattern, $sql, $matches, PREG_OFFSET_CAPTURE)) {
// Then process each param
foreach ($matches[1] as $k => $match) {
$param_key = substr($match[0], 1);
$inStatement = $matches[0][$k];
if (!isset($params[$param_key]) if (!isset($params[$param_key])
|| !is_array($params[$param_key])) // Not defined param or single value, keep as-is || !is_array($params[$param_key])) // Not defined param or single value, keep as-is
continue; continue;
if (empty($params[$param_key])) if (empty($params[$param_key])) // Empty array
// Empty array $newSql = str_replace($inStatement, 'IN (NULL)', $newSql);
$originalSql_ = str_replace($match, 'IN (NULL)', $originalSql_); else { // replace IN parameters
else {
$i = 0; $i = 0;
$keys = []; $keys = [];
foreach($params[$param_key] as $val) { foreach($params[$param_key] as $val) {
$keys[] = "{$param}{$i}"; $keys[] = ":{$param_key}{$i}";
$newParams["{$param_key}{$i}"] = $val; $newParams["{$param_key}{$i}"] = $val;
$i++; $i++;
} }
$originalSql_ = str_replace($match, "IN (". implode(", ", $keys) . ")", $originalSql_); $newSql = str_replace($inStatement, "IN (". implode(", ", $keys) . ")", $newSql);
}
unset($newParams[$param_key]);
} }
unset($params_[$param_key]);
} }
$params_ = array_merge($params_, $newParams);
// Then, find all placeholders (?) in the original SQL and their positions return ['sql' => $newSql, 'params' => $newParams];
}
// 3. handle unnamed parameters
// First, find all placeholders (?) in the original SQL and their positions
// We need to track which are IN(?) patterns vs regular ? // We need to track which are IN(?) patterns vs regular ?
$originalSql = $originalSql_; $originalSql = $sql;
$newParams = []; $newParams = [];
// Find all ? positions and whether they're part of IN(?) // Find all ? positions and whether they're part of IN(?)
@ -177,10 +199,9 @@ class SimplePdo extends PdoWrapper
$offset = 0; $offset = 0;
// Process each param // Process each param
$i = 0; for ($i = 0; $i < count($params); $i++) {
foreach($params_ as $key => $val) {
if (isset($inParamIndices[$i])) { if (isset($inParamIndices[$i])) {
$value = $params_[$i]; $value = $params[$i];
// Find the next IN(?) in the remaining SQL // Find the next IN(?) in the remaining SQL
if (preg_match($pattern, $newSql, $match, PREG_OFFSET_CAPTURE, $offset)) { if (preg_match($pattern, $newSql, $match, PREG_OFFSET_CAPTURE, $offset)) {
@ -206,12 +227,8 @@ class SimplePdo extends PdoWrapper
} }
} }
} else { } else {
if (is_numeric($key)) $newParams[] = $params[$i];
$newParams[] = $params_[$i];
else
$newParams[$key] = $val;
} }
$i++;
} }
return ['sql' => $newSql, 'params' => $newParams]; return ['sql' => $newSql, 'params' => $newParams];

@ -333,11 +333,11 @@ class SimplePdoTest extends TestCase
public function testMultipleInStatementsMixed(): void public function testMultipleInStatementsMixed(): void
{ {
$this->expectException(PDOException::class);
$rows = $this->db->fetchAll( $rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id IN(?) AND name IN(:names)', 'SELECT * FROM users WHERE id IN(?) AND name IN(:names)',
[[1, 2, 3], 'names' => ['John', 'Bob']] [[1, 2, 3], 'names' => ['John', 'Bob']]
); );
$this->assertCount(2, $rows); // John (id=1) and Bob (id=3)
} }
public function testInStatementWithOtherParams(): void public function testInStatementWithOtherParams(): void
@ -361,20 +361,20 @@ class SimplePdoTest extends TestCase
public function testInStatementWithMixedParams1(): void public function testInStatementWithMixedParams1(): void
{ {
$this->expectException(PDOException::class);
$rows = $this->db->fetchAll( $rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id > ? AND name IN(:names)', 'SELECT * FROM users WHERE id > ? AND name IN(:names)',
['id' => 0, 'names' => ['John', 'Jane']] [0, 'names' => ['John', 'Jane']]
); );
$this->assertCount(2, $rows);
} }
public function testInStatementWithMixedParams2(): void public function testInStatementWithMixedParams2(): void
{ {
$this->expectException(PDOException::class);
$rows = $this->db->fetchAll( $rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id > :id AND name IN(?)', 'SELECT * FROM users WHERE id > :id AND name IN(?)',
['id' => 0, ['John', 'Jane']] ['id' => 0, ['John', 'Jane']]
); );
$this->assertCount(2, $rows);
} }

Loading…
Cancel
Save