5
5
6
6
use Doctrine \DBAL \Platforms \MySqlPlatform ;
7
7
use Doctrine \DBAL \Schema \Schema ;
8
+ use PHPSQLParser \builders \OrderByBuilder ;
9
+ use PHPSQLParser \builders \SelectStatementBuilder ;
8
10
use TheCodingMachine \TDBM \TDBMException ;
9
11
use TheCodingMachine \TDBM \TDBMService ;
10
12
use PHPSQLParser \PHPSQLCreator ;
@@ -103,7 +105,7 @@ private function compute(string $sql, ?string $sqlCount): array
103
105
* @param mixed[] $parsedSql
104
106
* @param null|string $sqlCount
105
107
* @return mixed[] An array of 3 elements: [$processedSql, $processedSqlCount, $columnDescriptors]
106
- * @throws \PHPSQLParser\exceptions\UnsupportedFeatureException
108
+ * @throws \PHPSQLParser\exceptions\UnsupportedFeatureException|\PHPSQLParser\exceptions\UnableToCreateSQLException
107
109
*/
108
110
private function processParsedUnionQuery (array $ parsedSql , ?string $ sqlCount ): array
109
111
{
@@ -117,9 +119,9 @@ private function processParsedUnionQuery(array $parsedSql, ?string $sqlCount): a
117
119
118
120
// Let's reparse the returned SQL (not the most efficient way of doing things)
119
121
$ parser = new PHPSQLParser ();
120
- $ parsedSql = $ parser ->parse ($ selectProcessedSql );
122
+ $ parsedSelectSql = $ parser ->parse ($ selectProcessedSql );
121
123
122
- $ parsedSqlList [] = $ parsedSql ;
124
+ $ parsedSqlList [] = $ parsedSelectSql ;
123
125
}
124
126
125
127
// Let's rebuild the UNION query
@@ -130,12 +132,31 @@ private function processParsedUnionQuery(array $parsedSql, ?string $sqlCount): a
130
132
131
133
$ generator = new PHPSQLCreator ();
132
134
133
- $ processedSql = $ generator ->create ($ query );
135
+ // Replaced the default generator by our own to add parenthesis around each SELECT
136
+ $ processedSql = $ this ->buildUnion ($ query );
134
137
$ processedSqlCount = $ generator ->create ($ countQuery );
135
138
139
+ // Let's add the ORDER BY if any
140
+ if (isset ($ parsedSql ['0 ' ]['ORDER ' ])) {
141
+ $ orderByBuilder = new OrderByBuilder ();
142
+ $ processedSql .= " " . $ orderByBuilder ->build ($ parsedSql ['0 ' ]['ORDER ' ]);
143
+ }
144
+
136
145
return [$ processedSql , $ sqlCount ?? $ processedSqlCount , $ columnDescriptors ];
137
146
}
138
147
148
+ /**
149
+ * @param mixed[] $parsed
150
+ */
151
+ private function buildUnion (array $ parsed ): string
152
+ {
153
+ $ selectBuilder = new SelectStatementBuilder ();
154
+
155
+ return implode (' UNION ' , array_map (function ($ clause ) use ($ selectBuilder ) {
156
+ return '( ' . $ selectBuilder ->build ($ clause ) . ') ' ;
157
+ }, $ parsed ['UNION ' ]));
158
+ }
159
+
139
160
/**
140
161
* @param mixed[] $parsedSql
141
162
* @param null|string $sqlCount
0 commit comments