Skip to content

Commit

Permalink
Add InsertMultipleQuery.php
Browse files Browse the repository at this point in the history
  • Loading branch information
byjg committed Sep 4, 2024
1 parent a5b340b commit 962da52
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
3 changes: 1 addition & 2 deletions src/InsertMultipleQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use ByJG\AnyDataset\Db\DbFunctionsInterface;
use ByJG\MicroOrm\Exception\OrmInvalidFieldsException;
use ByJG\MicroOrm\Literal\LiteralInterface;

class InsertMultipleQuery extends Updatable
{
Expand Down Expand Up @@ -39,7 +38,7 @@ public function addRow($row)
$rowToAdd = [];
foreach ($this->fields as $field) {
if (!array_key_exists($field, $row)) {
throw new \InvalidArgumentException('The row must have the same fields');
throw new \InvalidArgumentException("The field '$field' must be in the row");
}
$rowToAdd[$field] = $row[$field];
}
Expand Down
42 changes: 40 additions & 2 deletions tests/InsertMultipleQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
namespace Tests;

use ByJG\MicroOrm\InsertMultipleQuery;
use ByJG\MicroOrm\SqlObject;
use ByJG\MicroOrm\SqlObjectEnum;
use PHPUnit\Framework\TestCase;

class InsertMultipleQueryTest extends TestCase
Expand Down Expand Up @@ -44,7 +42,47 @@ public function testInsert()
'fld22' => 'E',
'fld32' => 'F',
], $params);
}

public function testInsertStatic()
{
$query = InsertMultipleQuery::getInstance('test', ['fld1', 'fld2', 'fld3']);

$query->addRow(['fld1' => 'A', 'fld2' => 'B', 'fld3' => 'C']);
$query->addRow(['fld1' => 'D', 'fld2' => 'E', 'fld3' => 'F']);

$params = [];
$sql = $query->build($params);

$this->assertEquals('INSERT INTO test ( fld1, fld2, fld3 ) values ( :fld11, :fld21, :fld31 ), ( :fld12, :fld22, :fld32 )', $sql);
$this->assertEquals([
'fld11' => 'A',
'fld21' => 'B',
'fld31' => 'C',
'fld12' => 'D',
'fld22' => 'E',
'fld32' => 'F',
], $params);
}

public function testInsertError()
{
$query = InsertMultipleQuery::getInstance('test', ['fld1', 'fld2', 'fld3']);

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The row must have the same number of fields');

$query->addRow(['fld1' => 'A', 'fld2' => 'B']);
}

public function testInsertError2()
{
$query = InsertMultipleQuery::getInstance('test', ['fld1', 'fld2', 'fld3']);

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage("The field 'fld3' must be in the row");

$query->addRow(['fld1' => 'A', 'fld2' => 'B', 'nonexistent' => 'C']);
}

}

0 comments on commit 962da52

Please sign in to comment.