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