Skip to content

Commit 364fcc8

Browse files
authored
Merge pull request #99 from dimagi/union-cte
Fix UNION query with common table expression
2 parents 8011d62 + 0e7f074 commit 364fcc8

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

django_cte/query.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ class CTECompiler(object):
6868

6969
@classmethod
7070
def generate_sql(cls, connection, query, as_sql):
71-
if query.combinator:
71+
if not query._with_ctes:
7272
return as_sql()
7373

7474
ctes = []

tests/test_cte.py

+31
Original file line numberDiff line numberDiff line change
@@ -596,3 +596,34 @@ def test_left_outer_join_on_empty_result_set_cte(self):
596596
)
597597

598598
self.assertEqual(len(orders), 22)
599+
600+
def test_union_query_with_cte(self):
601+
orders = (
602+
Order.objects
603+
.filter(region__parent="sun")
604+
.only("region", "amount")
605+
)
606+
orders_cte = With(orders, name="orders_cte")
607+
orders_cte_queryset = orders_cte.queryset()
608+
609+
earth_orders = orders_cte_queryset.filter(region="earth")
610+
mars_orders = orders_cte_queryset.filter(region="mars")
611+
612+
earth_mars = earth_orders.union(mars_orders, all=True)
613+
earth_mars_cte = (
614+
earth_mars
615+
.with_cte(orders_cte)
616+
.order_by("region", "amount")
617+
.values_list("region", "amount")
618+
)
619+
print(earth_mars_cte.query)
620+
621+
self.assertEqual(list(earth_mars_cte), [
622+
('earth', 30),
623+
('earth', 31),
624+
('earth', 32),
625+
('earth', 33),
626+
('mars', 40),
627+
('mars', 41),
628+
('mars', 42),
629+
])

0 commit comments

Comments
 (0)