@@ -108,6 +108,9 @@ class QueryResultTypeWalker extends SqlWalker
108108 /** @var bool */
109109 private $ hasGroupByClause ;
110110
111+ /** @var bool */
112+ private $ hasCondition ;
113+
111114 /**
112115 * @param Query<mixed> $query
113116 */
@@ -136,6 +139,7 @@ public function __construct($query, $parserResult, array $queryComponents)
136139 $ this ->nullableQueryComponents = [];
137140 $ this ->hasAggregateFunction = false ;
138141 $ this ->hasGroupByClause = false ;
142+ $ this ->hasCondition = false ;
139143
140144 // The object is instantiated by Doctrine\ORM\Query\Parser, so receiving
141145 // dependencies through the constructor is not an option. Instead, we
@@ -592,6 +596,8 @@ public function walkOrderByItem($orderByItem): string
592596 */
593597 public function walkHavingClause ($ havingClause ): string
594598 {
599+ $ this ->hasCondition = true ;
600+
595601 return $ this ->marshalType (new MixedType ());
596602 }
597603
@@ -1016,6 +1022,8 @@ public function walkWhereClause($whereClause): string
10161022 */
10171023 public function walkConditionalExpression ($ condExpr ): string
10181024 {
1025+ $ this ->hasCondition = true ;
1026+
10191027 return $ this ->marshalType (new MixedType ());
10201028 }
10211029
@@ -1303,7 +1311,10 @@ public function walkResultVariable($resultVariable): string
13031311 */
13041312 private function addScalar ($ alias , Type $ type ): void
13051313 {
1306- if ($ type instanceof UnionType) {
1314+ // Since we don't check the condition inside the WHERE or HAVING
1315+ // conditions, we cannot be sure all the union types are correct.
1316+ // For exemple, a condition `WHERE foo.bar IS NOT NULL` could be added.
1317+ if ($ this ->hasCondition && $ type instanceof UnionType) {
13071318 $ type = TypeUtils::toBenevolentUnion ($ type );
13081319 }
13091320
0 commit comments