Skip to content

Commit b1a5e4e

Browse files
committed
feat: added InsertOnDuplicate sql generator
1 parent 26ef87e commit b1a5e4e

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

src/Sql/InsertOnDuplicate.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace EcomDev\MySQL2JSONL\Sql;
4+
5+
class InsertOnDuplicate
6+
{
7+
public function generate(string $tableName, array $columns, int $rowCount, $onUpdate = []): string
8+
{
9+
$sqlOnUpdate = '';
10+
11+
if ($onUpdate) {
12+
$sqlOnUpdate = sprintf(
13+
' ON DUPLICATE KEY UPDATE %s',
14+
implode(
15+
',',
16+
array_map(fn ($column) => "`$column` = VALUES(`$column`)", $onUpdate)
17+
)
18+
);
19+
}
20+
21+
$rowLine = rtrim(str_repeat('?,', count($columns)), ',');
22+
$rowLines = str_repeat(
23+
"($rowLine),",
24+
$rowCount
25+
);
26+
27+
$sql = sprintf(
28+
'INSERT INTO `%s` (%s) VALUES %s%s',
29+
$tableName,
30+
implode(',', array_map(fn ($column) => "`$column`", $columns)),
31+
rtrim(
32+
$rowLines,
33+
','
34+
),
35+
$sqlOnUpdate
36+
);
37+
38+
return $sql;
39+
}
40+
}

tests/Sql/InsertOnDuplicateTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
namespace EcomDev\MySQL2JSONL\Sql;
4+
5+
use PHPUnit\Framework\Attributes\Test;
6+
use PHPUnit\Framework\TestCase;
7+
8+
class InsertOnDuplicateTest extends TestCase
9+
{
10+
#[Test]
11+
public function generatesSingleRow()
12+
{
13+
$this->assertEquals(
14+
'INSERT INTO `table1` (`column_one`,`column_two`) VALUES (?,?)',
15+
(new InsertOnDuplicate())
16+
->generate('table1', ['column_one', 'column_two'], 1)
17+
);
18+
}
19+
20+
#[Test]
21+
public function generatesMultipleRows()
22+
{
23+
$this->assertEquals(
24+
'INSERT INTO `table1` (`column_one`,`column_two`) VALUES (?,?),(?,?),(?,?)',
25+
(new InsertOnDuplicate())
26+
->generate('table1', ['column_one', 'column_two'], 3)
27+
);
28+
}
29+
30+
#[Test]
31+
public function generatesSingleRowWithOnDuplicate()
32+
{
33+
$this->assertEquals(
34+
'INSERT INTO `table1` (`column_one`,`column_two`) VALUES (?,?) ON DUPLICATE KEY UPDATE `column_two` = VALUES(`column_two`)',
35+
(new InsertOnDuplicate())
36+
->generate(
37+
'table1',
38+
['column_one', 'column_two'],
39+
1,
40+
['column_two']
41+
)
42+
);
43+
}
44+
}

0 commit comments

Comments
 (0)