Skip to content

Commit

Permalink
fix: always escape identifiers in insertBatch()
Browse files Browse the repository at this point in the history
  • Loading branch information
ytetsuro committed Sep 26, 2021
1 parent 2b40f0e commit 5427050
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
4 changes: 2 additions & 2 deletions system/Database/BaseBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1604,7 +1604,7 @@ public function insertBatch(?array $set = null, ?bool $escape = null, int $batch
$affectedRows = 0;

for ($i = 0, $total = count($this->QBSet); $i < $total; $i += $batchSize) {
$sql = $this->_insertBatch($this->db->protectIdentifiers($table, true, $escape, false), $this->QBKeys, array_slice($this->QBSet, $i, $batchSize));
$sql = $this->_insertBatch($this->db->protectIdentifiers($table, true, null, false), $this->QBKeys, array_slice($this->QBSet, $i, $batchSize));

if ($this->testMode) {
$affectedRows++;
Expand Down Expand Up @@ -1672,7 +1672,7 @@ public function setInsertBatch($key, string $value = '', ?bool $escape = null)
}

foreach ($keys as $k) {
$this->QBKeys[] = $this->db->protectIdentifiers($k, false, $escape);
$this->QBKeys[] = $this->db->protectIdentifiers($k, false);
}

return $this;
Expand Down
30 changes: 30 additions & 0 deletions tests/system/Database/Builder/InsertTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,36 @@ public function testInsertBatch()
$this->assertSame($expected, str_replace("\n", ' ', $query->getQuery()));
}

public function testInsertBatchWithoutEscape()
{
$builder = $this->db->table('jobs');

$insertData = [
[
'id' => 2,
'name' => '1 + 1',
'description' => '1 + 2',
],
[
'id' => 3,
'name' => '2 + 1',
'description' => '2 + 2',
],
];

$this->db->shouldReturn('execute', 1)->shouldReturn('affectedRows', 1);
$builder->insertBatch($insertData, false);

$query = $this->db->getLastQuery();
$this->assertInstanceOf(Query::class, $query);

$raw = 'INSERT INTO "jobs" ("description", "id", "name") VALUES (:description:,:id:,:name:), (:description.1:,:id.1:,:name.1:)';
$this->assertSame($raw, str_replace("\n", ' ', $query->getOriginalQuery()));

$expected = "INSERT INTO \"jobs\" (\"description\", \"id\", \"name\") VALUES (1 + 2,2,1 + 1), (2 + 2,3,2 + 1)";
$this->assertSame($expected, str_replace("\n", ' ', $query->getQuery()));
}

/**
* @see https://github.com/codeigniter4/CodeIgniter4/issues/4345
*/
Expand Down

0 comments on commit 5427050

Please sign in to comment.