Skip to content

Commit

Permalink
fix process of inserting string with a question mark
Browse files Browse the repository at this point in the history
  • Loading branch information
Митрофанов Николай committed Jun 21, 2018
1 parent 04ad18b commit 4b7dbe2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
27 changes: 20 additions & 7 deletions src/ClickHouseStatement.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,18 +264,31 @@ public function errorInfo()
*/
public function execute($params = null)
{
$hasZeroIndex = false;
if (\is_array($params)) {
$this->values = array_replace($this->values, $params);//TODO array keys must be all strings or all integers?
$hasZeroIndex = array_key_exists(0, $params);
}

$sql = $this->statement;
foreach (array_keys($this->values) as $key) {
$sql = preg_replace(
'/(' . (\is_int($key) ? '\?' : ':' . $key) . ')/i',
$this->getTypedParam($key),
$sql,
1
);

if ($hasZeroIndex) {
$statementParts = explode('?', $sql);
array_walk($statementParts, function (&$part, $key) {
if (array_key_exists($key, $this->values)) {
$part .= $this->getTypedParam($key);
}
});
$sql = implode('', $statementParts);
} else {
foreach (array_keys($this->values) as $key) {
$sql = preg_replace(
'/(' . (\is_int($key) ? '\?' : ':' . $key) . ')/i',
$this->getTypedParam($key),
$sql,
1
);
}
}

$this->processViaSMI2($sql);
Expand Down
14 changes: 14 additions & 0 deletions tests/InsertTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,18 @@ public function testInsertViaQueryBuilder()

$this->assertEquals([['payload' => 'v5'], ['payload' => 'v6']], $this->connection->fetchAll("SELECT payload from test_insert_table WHERE id IN (5, 6) ORDER BY id"));
}

public function testStatementInsertWithoutKeyName()
{
$statement = $this->connection->prepare('INSERT INTO test_insert_table(id, payload) VALUES (?, ?), (?, ?)');
$statement->execute([7, 'v?7', 8, 'v8']);
$this->assertEquals([['payload' => 'v?7'], ['payload' => 'v8']], $this->connection->fetchAll("SELECT payload from test_insert_table WHERE id IN (7, 8) ORDER BY id"));
}

public function testStatementInsertWithKeyName()
{
$statement = $this->connection->prepare('INSERT INTO test_insert_table(id, payload) VALUES (:v0, :v1), (:v2, :v3)');
$statement->execute(['v0' => 9, 'v1' => 'v?9', 'v2' => 10, 'v3' => 'v10']);
$this->assertEquals([['payload' => 'v?9'], ['payload' => 'v10']], $this->connection->fetchAll("SELECT payload from test_insert_table WHERE id IN (9, 10) ORDER BY id"));
}
}

0 comments on commit 4b7dbe2

Please sign in to comment.