Skip to content

Commit 4b7dbe2

Browse files
author
Митрофанов Николай
committed
fix process of inserting string with a question mark
1 parent 04ad18b commit 4b7dbe2

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

src/ClickHouseStatement.php

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -264,18 +264,31 @@ public function errorInfo()
264264
*/
265265
public function execute($params = null)
266266
{
267+
$hasZeroIndex = false;
267268
if (\is_array($params)) {
268269
$this->values = array_replace($this->values, $params);//TODO array keys must be all strings or all integers?
270+
$hasZeroIndex = array_key_exists(0, $params);
269271
}
270272

271273
$sql = $this->statement;
272-
foreach (array_keys($this->values) as $key) {
273-
$sql = preg_replace(
274-
'/(' . (\is_int($key) ? '\?' : ':' . $key) . ')/i',
275-
$this->getTypedParam($key),
276-
$sql,
277-
1
278-
);
274+
275+
if ($hasZeroIndex) {
276+
$statementParts = explode('?', $sql);
277+
array_walk($statementParts, function (&$part, $key) {
278+
if (array_key_exists($key, $this->values)) {
279+
$part .= $this->getTypedParam($key);
280+
}
281+
});
282+
$sql = implode('', $statementParts);
283+
} else {
284+
foreach (array_keys($this->values) as $key) {
285+
$sql = preg_replace(
286+
'/(' . (\is_int($key) ? '\?' : ':' . $key) . ')/i',
287+
$this->getTypedParam($key),
288+
$sql,
289+
1
290+
);
291+
}
279292
}
280293

281294
$this->processViaSMI2($sql);

tests/InsertTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,18 @@ public function testInsertViaQueryBuilder()
8080

8181
$this->assertEquals([['payload' => 'v5'], ['payload' => 'v6']], $this->connection->fetchAll("SELECT payload from test_insert_table WHERE id IN (5, 6) ORDER BY id"));
8282
}
83+
84+
public function testStatementInsertWithoutKeyName()
85+
{
86+
$statement = $this->connection->prepare('INSERT INTO test_insert_table(id, payload) VALUES (?, ?), (?, ?)');
87+
$statement->execute([7, 'v?7', 8, 'v8']);
88+
$this->assertEquals([['payload' => 'v?7'], ['payload' => 'v8']], $this->connection->fetchAll("SELECT payload from test_insert_table WHERE id IN (7, 8) ORDER BY id"));
89+
}
90+
91+
public function testStatementInsertWithKeyName()
92+
{
93+
$statement = $this->connection->prepare('INSERT INTO test_insert_table(id, payload) VALUES (:v0, :v1), (:v2, :v3)');
94+
$statement->execute(['v0' => 9, 'v1' => 'v?9', 'v2' => 10, 'v3' => 'v10']);
95+
$this->assertEquals([['payload' => 'v?9'], ['payload' => 'v10']], $this->connection->fetchAll("SELECT payload from test_insert_table WHERE id IN (9, 10) ORDER BY id"));
96+
}
8397
}

0 commit comments

Comments
 (0)