|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Pfilsx\PostgreSQLDoctrine\ORM\Query\AST\Functions; |
| 6 | + |
| 7 | +use Doctrine\ORM\Query\AST\Node; |
| 8 | +use Doctrine\ORM\Query\Lexer; |
| 9 | +use Doctrine\ORM\Query\Parser; |
| 10 | +use Doctrine\ORM\Query\SqlWalker; |
| 11 | + |
| 12 | +/** |
| 13 | + * Implementation of PostgreSql STRING_AGG(). |
| 14 | + * |
| 15 | + * @see https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE |
| 16 | + * |
| 17 | + * @example STRING_AGG(entity.field, ', ') |
| 18 | + * @example STRING_AGG(entity.field, ', ') FILTER (WHERE entity.field IS NOT NULL) |
| 19 | + */ |
| 20 | +final class StringAgg extends AggregateWithFilterFunction |
| 21 | +{ |
| 22 | + private bool $distinct = false; |
| 23 | + private Node $expr; |
| 24 | + private Node $delimiter; |
| 25 | + |
| 26 | + public function parseFunction(Parser $parser): void |
| 27 | + { |
| 28 | + $parser->match(Lexer::T_IDENTIFIER); |
| 29 | + $parser->match(Lexer::T_OPEN_PARENTHESIS); |
| 30 | + |
| 31 | + $lexer = $parser->getLexer(); |
| 32 | + if ($lexer->isNextToken(Lexer::T_DISTINCT)) { |
| 33 | + $parser->match(Lexer::T_DISTINCT); |
| 34 | + $this->distinct = true; |
| 35 | + } |
| 36 | + |
| 37 | + $this->expr = $parser->StringPrimary(); |
| 38 | + $parser->match(Lexer::T_COMMA); |
| 39 | + $this->delimiter = $parser->StringPrimary(); |
| 40 | + |
| 41 | + $parser->match(Lexer::T_CLOSE_PARENTHESIS); |
| 42 | + } |
| 43 | + |
| 44 | + public function getFunctionSql(SqlWalker $sqlWalker): string |
| 45 | + { |
| 46 | + return sprintf('STRING_AGG(%s%s, %s)', |
| 47 | + $this->distinct ? 'DISTINCT' : '', |
| 48 | + $this->expr->dispatch($sqlWalker), |
| 49 | + $this->delimiter->dispatch($sqlWalker) |
| 50 | + ); |
| 51 | + } |
| 52 | +} |
0 commit comments