Skip to content

Commit

Permalink
Adding ORDER support for UNION queries
Browse files Browse the repository at this point in the history
  • Loading branch information
mhtghn authored and homersimpsons committed May 24, 2023
1 parent 5c091cd commit e4346d3
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/QueryFactory/FindObjectsFromRawSqlQueryFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Schema\Schema;
use PHPSQLParser\builders\OrderByBuilder;
use PHPSQLParser\builders\SelectStatementBuilder;
use TheCodingMachine\TDBM\TDBMException;
use TheCodingMachine\TDBM\TDBMService;
use PHPSQLParser\PHPSQLCreator;
Expand Down Expand Up @@ -103,7 +105,7 @@ private function compute(string $sql, ?string $sqlCount): array
* @param mixed[] $parsedSql
* @param null|string $sqlCount
* @return mixed[] An array of 3 elements: [$processedSql, $processedSqlCount, $columnDescriptors]
* @throws \PHPSQLParser\exceptions\UnsupportedFeatureException
* @throws \PHPSQLParser\exceptions\UnsupportedFeatureException|\PHPSQLParser\exceptions\UnableToCreateSQLException
*/
private function processParsedUnionQuery(array $parsedSql, ?string $sqlCount): array
{
Expand All @@ -117,9 +119,9 @@ private function processParsedUnionQuery(array $parsedSql, ?string $sqlCount): a

// Let's reparse the returned SQL (not the most efficient way of doing things)
$parser = new PHPSQLParser();
$parsedSql = $parser->parse($selectProcessedSql);
$parsedSelectSql = $parser->parse($selectProcessedSql);

$parsedSqlList[] = $parsedSql;
$parsedSqlList[] = $parsedSelectSql;
}

// Let's rebuild the UNION query
Expand All @@ -130,12 +132,31 @@ private function processParsedUnionQuery(array $parsedSql, ?string $sqlCount): a

$generator = new PHPSQLCreator();

$processedSql = $generator->create($query);
// Replaced the default generator by our own to add parenthesis around each SELECT
$processedSql = $this->buildUnion($query);
$processedSqlCount = $generator->create($countQuery);

// Let's add the ORDER BY if any
if (isset($parsedSql['0']['ORDER'])) {
$orderByBuilder = new OrderByBuilder();
$processedSql .= " " . $orderByBuilder->build($parsedSql['0']['ORDER']);
}

return [$processedSql, $sqlCount ?? $processedSqlCount, $columnDescriptors];
}

/**
* @param mixed[] $parsed
*/
private function buildUnion(array $parsed): string
{
$selectBuilder = new SelectStatementBuilder();

return implode(' UNION ', array_map(function ($clause) use ($selectBuilder) {
return '(' . $selectBuilder->build($clause) . ')';
}, $parsed['UNION']));
}

/**
* @param mixed[] $parsedSql
* @param null|string $sqlCount
Expand Down

0 comments on commit e4346d3

Please sign in to comment.