update query builder support expression

This commit is contained in:
Yuri Kuznetsov
2022-11-11 13:25:50 +02:00
parent 31bf387cbe
commit ef47d3d2bf
3 changed files with 63 additions and 11 deletions
+17 -2
View File
@@ -29,6 +29,7 @@
namespace Espo\ORM\Query;
use Espo\ORM\Query\Part\Expression;
use RuntimeException;
class UpdateBuilder implements Builder
@@ -78,11 +79,25 @@ class UpdateBuilder implements Builder
/**
* Values to set. Column => Value map.
*
* @param array<string,mixed> $set
* @param array<string, scalar|Expression|null> $set
*/
public function set(array $set): self
{
$this->params['set'] = $set;
$modified = [];
foreach ($set as $key => $value) {
if (!$value instanceof Expression) {
$modified[$key] = $value;
continue;
}
$newKey = rtrim($key, ':') . ':';
$modified[$newKey] = $value->getValue();
}
$this->params['set'] = $modified;
return $this;
}
@@ -339,6 +339,27 @@ class MysqlQueryComposerTest extends \PHPUnit\Framework\TestCase
$this->assertEquals($expectedSql, $sql);
}
public function testUpdateQueryWithSetExpression()
{
$query = $this->queryBuilder
->update()
->in('Comment')
->join('post')
->set([
'name' => Expression::column('post.name'),
])
->build();
$sql = $this->query->composeUpdate($query);
$expectedSql =
"UPDATE `comment` " .
"JOIN `post` AS `post` ON comment.post_id = post.id ".
"SET comment.name = post.name";
$this->assertEquals($expectedSql, $sql);
}
public function testInsertQuery1()
{
$sql = $this->query->compose(Insert::fromRaw([
+25 -9
View File
@@ -29,15 +29,14 @@
namespace tests\unit\Espo\ORM;
use Espo\ORM\{
QueryBuilder,
Query\Select,
Query\Insert,
Query\Update,
Query\Delete,
Query\Union,
Query\Part\Selection,
};
use Espo\ORM\Query\Delete;
use Espo\ORM\Query\Insert;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Select;
use Espo\ORM\Query\Union;
use Espo\ORM\Query\Update;
use Espo\ORM\QueryBuilder;
use RuntimeException;
@@ -218,6 +217,23 @@ class QueryBuilderTest extends \PHPUnit\Framework\TestCase
->build();
}
public function testUpdate2()
{
$update = $this->queryBuilder
->update()
->in('Test')
->set(['col' => Expression::add(1, 2)])
->build();
$this->assertInstanceOf(Update::class, $update);
$this->assertEquals(
['col:' => 'ADD:(1, 2)'],
$update->getRaw()['set']
);
}
public function testUnion1()
{
$q1 = $this->queryBuilder