Merge pull request #731 from lolo3129/master

Adding named parameters support to sql requests
master
n0nag0n 1 day ago committed by GitHub
commit 82693315b3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -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,11 +105,62 @@ class SimplePdo extends PdoWrapper
*/ */
protected function processInStatementSql(string $sql, array $params = []): array protected function processInStatementSql(string $sql, array $params = []): array
{ {
// 1. throw an exception if mixed parameters are found in sql
$pattern = '/(:[a-zA-Z][a-zA-Z0-9]*)/i';
$named_params_nb = preg_match_all($pattern, $sql, $matches_named, PREG_OFFSET_CAPTURE);
$pattern = '/(\?)/i';
$unnamed_params_nb = preg_match_all($pattern, $sql, $matches_unnamed, PREG_OFFSET_CAPTURE);
if (($named_params_nb === false)
|| ($unnamed_params_nb === false)
|| (($named_params_nb != 0) && ($unnamed_params_nb != 0)))
{
throw new PDOException(
"processInStatementSql failed: mixed named and unamed parameters found."
);
}
// 2. handle named parameters
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])
|| !is_array($params[$param_key])) // Not defined param or single value, keep as-is
continue;
if (empty($params[$param_key])) // Empty array
$newSql = str_replace($inStatement, 'IN (NULL)', $newSql);
else { // replace IN parameters
$i = 0;
$keys = [];
foreach($params[$param_key] as $val) {
$keys[] = ":{$param_key}{$i}";
$newParams["{$param_key}{$i}"] = $val;
$i++;
}
$newSql = str_replace($inStatement, "IN (". implode(", ", $keys) . ")", $newSql);
}
unset($newParams[$param_key]);
}
}
return ['sql' => $newSql, 'params' => $newParams];
}
// 3. handle unnamed parameters
// First, find all placeholders (?) in the original SQL and their positions // 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 = $sql; $originalSql = $sql;
$newParams = []; $newParams = [];
$paramIndex = 0;
// Find all ? positions and whether they're part of IN(?) // Find all ? positions and whether they're part of IN(?)
$pattern = '/IN\s*\(\s*\?\s*\)/i'; $pattern = '/IN\s*\(\s*\?\s*\)/i';

@ -203,6 +203,12 @@ class SimplePdoTest extends TestCase
$this->assertCount(2, $rows); // John and Jane $this->assertCount(2, $rows); // John and Jane
} }
public function testFetchAllWithNamedParams(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE name LIKE :name', [ 'name' => 'J%']);
$this->assertCount(2, $rows); // John and Jane
}
// ========================================================================= // =========================================================================
// fetchColumn Tests // fetchColumn Tests
// ========================================================================= // =========================================================================
@ -258,24 +264,55 @@ class SimplePdoTest extends TestCase
$this->assertCount(2, $rows); $this->assertCount(2, $rows);
} }
public function testInStatementWithNamedArrayOfIntegers(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(:ids)', [ 'ids' => [1, 2]]);
$this->assertCount(2, $rows);
}
public function testInStatementWithArrayOfStrings(): void public function testInStatementWithArrayOfStrings(): void
{ {
$rows = $this->db->fetchAll('SELECT * FROM users WHERE name IN(?)', [['John', 'Jane']]); $rows = $this->db->fetchAll('SELECT * FROM users WHERE name IN(?)', [['John', 'Jane']]);
$this->assertCount(2, $rows); $this->assertCount(2, $rows);
} }
public function testInStatementWithNamedArrayOfStrings(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE name IN(:names)', ['names' => ['John', 'Jane']]);
$this->assertCount(2, $rows);
}
public function testInStatementWithEmptyArray(): void public function testInStatementWithEmptyArray(): void
{ {
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(?)', [[]]); $rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(?)', [[]]);
$this->assertCount(0, $rows); // IN(NULL) matches nothing $this->assertCount(0, $rows); // IN(NULL) matches nothing
} }
public function testInStatementWithNamedEmptyArray(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(:empty)', [ 'empty' => []]);
$this->assertCount(0, $rows); // IN(NULL) matches nothing
}
public function testInStatementWithSingleValue(): void public function testInStatementWithSingleValue(): void
{ {
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(?)', [1]); $rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(?)', [1]);
$this->assertCount(1, $rows); $this->assertCount(1, $rows);
} }
public function testInStatementWithSingleNamedValue(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(:ids)', ['ids' => 1]);
$this->assertCount(1, $rows);
}
public function testInStatementWithNamedSingleValue(): void
{
$rows = $this->db->fetchAll('SELECT * FROM users WHERE id IN(:val)', ['val' => 1]);
$this->assertCount(1, $rows);
}
public function testMultipleInStatements(): void public function testMultipleInStatements(): void
{ {
$rows = $this->db->fetchAll( $rows = $this->db->fetchAll(
@ -285,6 +322,24 @@ class SimplePdoTest extends TestCase
$this->assertCount(2, $rows); // John (id=1) and Bob (id=3) $this->assertCount(2, $rows); // John (id=1) and Bob (id=3)
} }
public function testMultipleInStatementsNamed(): void
{
$rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id IN(:ids) AND name IN(:names)',
['ids' => [1, 2, 3], 'names' => ['John', 'Bob']]
);
$this->assertCount(2, $rows); // John (id=1) and Bob (id=3)
}
public function testMultipleInStatementsMixed(): void
{
$this->expectException(PDOException::class);
$rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id IN(?) AND name IN(:names)',
[[1, 2, 3], 'names' => ['John', 'Bob']]
);
}
public function testInStatementWithOtherParams(): void public function testInStatementWithOtherParams(): void
{ {
$rows = $this->db->fetchAll( $rows = $this->db->fetchAll(
@ -294,6 +349,35 @@ class SimplePdoTest extends TestCase
$this->assertCount(2, $rows); $this->assertCount(2, $rows);
} }
public function testInStatementWithOtherNamedParams(): void
{
$rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id > :id AND name IN(:names)',
['id' => 0, 'names' => ['John', 'Jane']]
);
$this->assertCount(2, $rows);
}
public function testInStatementWithMixedParams1(): void
{
$this->expectException(PDOException::class);
$rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id > ? AND name IN(:names)',
[0, 'names' => ['John', 'Jane']]
);
}
public function testInStatementWithMixedParams2(): void
{
$this->expectException(PDOException::class);
$rows = $this->db->fetchAll(
'SELECT * FROM users WHERE id > :id AND name IN(?)',
['id' => 0, ['John', 'Jane']]
);
}
// ========================================================================= // =========================================================================
// insert() Tests // insert() Tests
// ========================================================================= // =========================================================================

Loading…
Cancel
Save