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\Db\Query\QueryInterface; |
19
|
|
|
use Yiisoft\Json\Json; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* The class JsonExpressionBuilder builds {@see JsonExpression} for PostgreSQL DBMS. |
23
|
|
|
*/ |
24
|
|
|
final class JsonExpressionBuilder implements ExpressionBuilderInterface |
25
|
|
|
{ |
26
|
|
|
use ExpressionBuilderTrait; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Method builds the raw SQL from the $expression that will not be additionally escaped or quoted. |
30
|
|
|
* |
31
|
|
|
* @param ExpressionInterface $expression the expression to be built. |
32
|
|
|
* @param array $params the binding parameters. |
33
|
|
|
* |
34
|
|
|
* @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException |
35
|
|
|
* |
36
|
|
|
* @return string the raw SQL that will not be additionally escaped or quoted. |
37
|
|
|
*/ |
38
|
16 |
|
public function build(ExpressionInterface $expression, array &$params = []): string |
39
|
|
|
{ |
40
|
|
|
/** |
41
|
|
|
* @var JsonExpression $expression |
42
|
|
|
* @var array|mixed|QueryInterface $value |
43
|
|
|
*/ |
44
|
16 |
|
$value = $expression->getValue(); |
45
|
|
|
|
46
|
16 |
|
if ($value instanceof Query) { |
47
|
2 |
|
[$sql, $params] = $this->queryBuilder->build($value, $params); |
48
|
2 |
|
return "($sql)" . $this->getTypecast($expression); |
49
|
|
|
} |
50
|
|
|
|
51
|
14 |
|
if ($value instanceof ArrayExpression) { |
52
|
1 |
|
$placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')'; |
53
|
|
|
} else { |
54
|
14 |
|
$placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params); |
55
|
|
|
} |
56
|
|
|
|
57
|
14 |
|
return $placeholder . $this->getTypecast($expression); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param JsonExpression $expression |
62
|
|
|
* |
63
|
|
|
* @return string the typecast expression based on {@see type}. |
64
|
|
|
*/ |
65
|
16 |
|
protected function getTypecast(JsonExpression $expression): string |
66
|
|
|
{ |
67
|
16 |
|
if ($expression->getType() === null) { |
68
|
13 |
|
return ''; |
69
|
|
|
} |
70
|
|
|
|
71
|
4 |
|
return '::' . (string) $expression->getType(); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|