Skip to content

Make it possible to create union main part for a CTE#7326

Merged
derrabus merged 1 commit intodoctrine:4.4.xfrom
sbuerk:4.4.x-cte-allow-union-as-main-query
Mar 3, 2026
Merged

Make it possible to create union main part for a CTE#7326
derrabus merged 1 commit intodoctrine:4.4.xfrom
sbuerk:4.4.x-cte-allow-union-as-main-query

Conversation

@sbuerk
Copy link
Contributor

@sbuerk sbuerk commented Mar 2, 2026

Q A
Type bug
Fixed issues #7318

Summary

Technically this change adopts the solution for adding
the CTE with parts to a SELECT query for UNION query
handling using the WithSQLBuilder in case with parts
has been set to allow creating queries like

WITH
-- CTE with parts
  cte_a AS (SELECT * FROM a_table)

-- CTEmain part
      (SELECT cte_a.*, 'lit1' from cte_a)
UNION (SELECT cte_a.*, 'lit2' from cte_a)

using the union and with api on the same level:

$qb = $connection->createQueryBuilder();

$cte = $qb->sub()
  ->select('*')
  ->from('a_table');

$union1 = $qb->sub()
  ->select('cte_a.*', $qb->expr()->literal('lit1'))
  ->from('cte_a');

$union1 = $qb->sub()
  ->select('cte_a.*', $qb->expr()->literal('lit2'))
  ->from('cte_a');

$qb->with('cte_a', $cte)
  ->union($union1)
  ->addUnion($union2);

This is a valid use-case and supported by databases supporting
common table expressions albeit I could not find that documented
in any documentation and real world use-cases exists and is the
reason why this change has been considered as bugfix.

This change modifies the internal handling of
`QueryBuilder` to prepand the CTE `with` parts
to allow creating valid union main parts like
following plain SQL:

```sql
WITH
-- CTE with parts
  cte_a AS (SELECT * FROM a_table)

-- CTEmain part
      (SELECT cte_a.*, 'lit1' from cte_a)
UNION (SELECT cte_a.*, 'lit2' from cte_a)
```

Resolves: doctrine#7318
@sbuerk sbuerk force-pushed the 4.4.x-cte-allow-union-as-main-query branch from 1f8e64d to 160c3b2 Compare March 2, 2026 10:48
@derrabus derrabus merged commit 3ccea71 into doctrine:4.4.x Mar 3, 2026
137 checks passed
@derrabus derrabus added this to the 4.4.3 milestone Mar 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants