|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\Pgsql\Expression; |
|
6
|
|
|
|
|
7
|
|
|
use Yiisoft\Db\Exception\InvalidArgumentException; |
|
8
|
|
|
use Yiisoft\Db\Expression\ArrayExpression; |
|
9
|
|
|
use Yiisoft\Db\Expression\ExpressionBuilderInterface; |
|
10
|
|
|
use Yiisoft\Db\Expression\ExpressionBuilderTrait; |
|
11
|
|
|
use Yiisoft\Db\Expression\ExpressionInterface; |
|
12
|
|
|
use Yiisoft\Db\Expression\JsonExpression; |
|
13
|
|
|
use Yiisoft\Db\Query\Query; |
|
14
|
|
|
use Yiisoft\Json\Json; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Class JsonExpressionBuilder builds {@see JsonExpression} for PostgreSQL DBMS. |
|
18
|
|
|
*/ |
|
19
|
|
|
class JsonExpressionBuilder implements ExpressionBuilderInterface |
|
20
|
|
|
{ |
|
21
|
|
|
use ExpressionBuilderTrait; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* {@inheritdoc} |
|
25
|
|
|
* |
|
26
|
|
|
* @param JsonExpression|ExpressionInterface $expression the expression to be built |
|
27
|
|
|
* @param array $params |
|
28
|
|
|
* |
|
29
|
|
|
* @return string |
|
30
|
|
|
*/ |
|
31
|
15 |
|
public function build(ExpressionInterface $expression, array &$params = []): string |
|
32
|
|
|
{ |
|
33
|
15 |
|
$value = $expression->getValue(); |
|
|
|
|
|
|
34
|
|
|
|
|
35
|
15 |
|
if ($value instanceof Query) { |
|
36
|
2 |
|
[$sql, $params] = $this->queryBuilder->build($value, $params); |
|
37
|
2 |
|
return "($sql)" . $this->getTypecast($expression); |
|
38
|
|
|
} |
|
39
|
13 |
|
if ($value instanceof ArrayExpression) { |
|
40
|
|
|
$placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')'; |
|
41
|
|
|
} else { |
|
42
|
13 |
|
$placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
13 |
|
return $placeholder . $this->getTypecast($expression); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param JsonExpression $expression |
|
50
|
|
|
* |
|
51
|
|
|
* @return string the typecast expression based on [[type]]. |
|
52
|
|
|
*/ |
|
53
|
15 |
|
protected function getTypecast(JsonExpression $expression): string |
|
54
|
|
|
{ |
|
55
|
15 |
|
if ($expression->getType() === null) { |
|
56
|
12 |
|
return ''; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
3 |
|
return '::' . $expression->getType(); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|